-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeSpec.js
More file actions
276 lines (235 loc) · 8.02 KB
/
TypeSpec.js
File metadata and controls
276 lines (235 loc) · 8.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* @file Type specification and validation utilities.
* Provides TypeSpec class for parsing and validating complex type specifications
* including arrays, unions, and options.
*/
import Collection from "./Collection.js"
import Data from "./Data.js"
import Sass from "./Sass.js"
import Util from "./Util.js"
/**
* Options for creating a new TypeSpec.
*
* @typedef {object} TypeSpecOptions
* @property {string} [delimiter="|"] - The delimiter for union types
*/
/**
* Options for type validation methods.
*
* @typedef {object} TypeValidationOptions
* @property {boolean} [allowEmpty=true] - Whether empty values are allowed
*/
/**
* Type specification class for parsing and validating complex type definitions.
* Supports union types, array types, and validation options.
*/
export default class TypeSpec {
#specs
/**
* Creates a new TypeSpec instance.
*
* @param {string} string - The type specification string (e.g., "string|number", "object[]")
* @param {TypeSpecOptions} [options] - Additional parsing options
*/
constructor(string, options) {
this.#specs = []
this.#parse(string, options)
Object.freeze(this.#specs)
this.specs = this.#specs
this.length = this.#specs.length
this.stringRepresentation = this.toString()
Object.freeze(this)
}
/**
* Returns a string representation of the type specification.
*
* @returns {string} The type specification as a string (e.g., "string|number[]")
*/
toString() {
return this.#specs
.map(spec => {
return `${spec.typeName}${spec.array ? "[]" : ""}`
})
.join("|")
}
/**
* Returns a JSON representation of the TypeSpec.
*
* @returns {unknown} Object containing specs, length, and string representation
*/
toJSON() {
// Serialize as a string representation or as raw data
return {
specs: this.#specs,
length: this.length,
stringRepresentation: this.toString(),
}
}
/**
* Executes a provided function once for each type specification.
*
* @param {function(unknown): void} callback - Function to execute for each spec
*/
forEach(callback) {
this.#specs.forEach(callback)
}
/**
* Tests whether all type specifications pass the provided test function.
*
* @param {function(unknown): boolean} callback - Function to test each spec
* @returns {boolean} True if all specs pass the test
*/
every(callback) {
return this.#specs.every(callback)
}
/**
* Tests whether at least one type specification passes the provided test function.
*
* @param {function(unknown): boolean} callback - Function to test each spec
* @returns {boolean} True if at least one spec passes the test
*/
some(callback) {
return this.#specs.some(callback)
}
/**
* Creates a new array with all type specifications that pass the provided test function.
*
* @param {function(unknown): boolean} callback - Function to test each spec
* @returns {Array<unknown>} New array with filtered specs
*/
filter(callback) {
return this.#specs.filter(callback)
}
/**
* Creates a new array populated with the results of calling the provided function on every spec.
*
* @param {function(unknown): unknown} callback - Function to call on each spec
* @returns {Array<unknown>} New array with mapped values
*/
map(callback) {
return this.#specs.map(callback)
}
/**
* Executes a reducer function on each spec, resulting in a single output value.
*
* @param {function(unknown, unknown): unknown} callback - Function to execute on each spec
* @param {unknown} initialValue - Initial value for the accumulator
* @returns {unknown} The final accumulated value
*/
reduce(callback, initialValue) {
return this.#specs.reduce(callback, initialValue)
}
/**
* Returns the first type specification that satisfies the provided testing function.
*
* @param {function(unknown): boolean} callback - Function to test each spec
* @returns {object|undefined} The first spec that matches, or undefined
*/
find(callback) {
return this.#specs.find(callback)
}
/**
* Tests whether a value matches any of the type specifications.
* Handles array types, union types, and empty value validation.
*
* @param {unknown} value - The value to test against the type specifications
* @param {TypeValidationOptions} [options] - Validation options
* @returns {boolean} True if the value matches any type specification
*/
matches(value, options) {
return this.match(value, options).length > 0
}
/**
* Returns matching type specifications for a value.
*
* @param {unknown} value - The value to test against the type specifications
* @param {TypeValidationOptions} [options] - Validation options
* @returns {Array<object>} Array of matching type specifications
*/
match(value, options) {
const allowEmpty = options?.allowEmpty ?? true
// If we have a list of types, because the string was validly parsed, we
// need to ensure that all of the types that were parsed are valid types in
// JavaScript.
if(this.length && !this.every(t => Data.isValidType(t.typeName)))
return []
// Now, let's do some checking with the types, respecting the array flag
// with the value
const valueType = Data.typeOf(value)
const isArray = valueType === "Array"
// We need to ensure that we match the type and the consistency of the
// types in an array, if it is an array and an array is allowed.
const matchingTypeSpec = this.filter(spec => {
const {typeName: allowedType, array: allowedArray} = spec
const empty =
Data.emptyableTypes.includes(allowedType) &&
Data.isEmpty(value)
// Handle non-array values
if(!isArray && !allowedArray) {
if(valueType === allowedType)
return allowEmpty || !empty
if(valueType === "Null" || valueType === "Undefined")
return false
if(allowedType === "Object" && Data.isPlainObject(value))
return true
// We already don't match directly, let's check their breeding.
const lineage = this.#getTypeLineage(value)
return lineage.includes(allowedType)
}
// Handle array values
if(isArray) {
// Special case for generic "Array" type
if(allowedType === "Array" && !allowedArray)
return allowEmpty || !empty
// Must be an array type specification
if(!allowedArray)
return false
// Handle empty arrays
if(empty)
return allowEmpty
// Check if array elements match the required type
return Collection.isArrayUniform(value, allowedType)
}
return false
})
return matchingTypeSpec
}
/**
* Parses a type specification string into individual type specs.
* Handles union types separated by delimiters and array notation.
*
* @private
* @param {string} string - The type specification string to parse
* @param {TypeSpecOptions} [options] - Parsing options
* @throws {Sass} If the type specification is invalid
*/
#parse(string, options={delimiter: "|"}) {
const delimiter = options?.delimiter ?? "|"
const parts = string.split(delimiter)
this.#specs = parts.map(part => {
const typeMatches = /^(\w+)(\[\])?$/.exec(part)
if(!typeMatches || typeMatches.length !== 3)
throw Sass.new(`Invalid type: ${part}`)
const typeName = Util.capitalize(typeMatches[1])
if(!Data.isValidType(typeName))
throw Sass.new(`Invalid type: ${typeMatches[1]}`)
return {
typeName,
array: typeMatches[2] === "[]",
}
})
}
#getTypeLineage(value) {
const lineage = [Object.getPrototypeOf(value)]
const names = [lineage.at(-1).constructor.name]
for(;;) {
const prototype = Object.getPrototypeOf(lineage.at(-1))
const name = prototype?.constructor.name
if(!prototype || !name || name === "Object")
break
lineage.push(prototype)
names.push(prototype.constructor.name)
}
return names
}
}