wizard-ql 2.1.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -186,7 +186,7 @@
186
186
  same "printed page" as the copyright notice for easier
187
187
  identification within third-party archives.
188
188
 
189
- Copyright 2025 Guidance Analytics
189
+ Copyright 2026 Arthur Neuman
190
190
 
191
191
  Licensed under the Apache License, Version 2.0 (the "License");
192
192
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -16,10 +16,15 @@
16
16
  𝗟<sub>anguage</sub>
17
17
  </h2>
18
18
 
19
- #### WizardQL is a natural-language-like query language for constructing data queries for resources that meet conditions.
19
+ #### WizardQL is a natural-language-like query language for constructing data queries for resources that meet conditions, fitted with extensive type completion.
20
+
21
+ [Demo](https://exoRift.github.io/wizard-ql)
22
+
23
+ ## Installation
24
+ `npm i wizard-ql`
20
25
 
21
26
  ## Examples
22
- `parse('(rank >= 10 & role = admin) | banned')`
27
+ `WizardParser.parse('(rank >= 10 & role = admin) | banned')`
23
28
 
24
29
  > ```js
25
30
  > {
@@ -35,27 +40,27 @@
35
40
  > field: "rank",
36
41
  > operation: "GEQ",
37
42
  > value: 10,
38
- > validated: false,
43
+ > validated: false
39
44
  > }, {
40
45
  > type: "condition",
41
46
  > field: "role",
42
47
  > operation: "EQUAL",
43
48
  > value: "admin",
44
- > validated: false,
49
+ > validated: false
45
50
  > }
46
- > ],
51
+ > ]
47
52
  > }, {
48
53
  > type: "condition",
49
54
  > field: "banned",
50
55
  > operation: "EQUAL",
51
56
  > value: true,
52
- > validated: false,
57
+ > validated: false
53
58
  > }
54
- > ],
59
+ > ]
55
60
  > }
56
61
  > ```
57
62
 
58
- `parse('flagged OR (name MATCHES "decorative_.*" AND !(price >= 20 AND price <= 30))')`
63
+ `WizardParser.parse('flagged OR (name MATCHES "decorative_.*" AND !(price >= 20 AND price <= 30))')`
59
64
 
60
65
  > ```js
61
66
  > {
@@ -67,7 +72,7 @@
67
72
  > field: "flagged",
68
73
  > operation: "EQUAL",
69
74
  > value: true,
70
- > validated: false,
75
+ > validated: false
71
76
  > }, {
72
77
  > type: "group",
73
78
  > operation: "AND",
@@ -77,7 +82,7 @@
77
82
  > field: "name",
78
83
  > operation: "MATCH",
79
84
  > value: "decorative_.*",
80
- > validated: false,
85
+ > validated: false
81
86
  > }, {
82
87
  > type: "group",
83
88
  > operation: "OR",
@@ -87,19 +92,19 @@
87
92
  > field: "price",
88
93
  > operation: "LESS",
89
94
  > value: 20,
90
- > validated: false,
95
+ > validated: false
91
96
  > }, {
92
97
  > type: "condition",
93
98
  > field: "price",
94
99
  > operation: "GREATER",
95
100
  > value: 30,
96
- > validated: false,
101
+ > validated: false
97
102
  > }
98
- > ],
103
+ > ]
99
104
  > }
100
- > ],
105
+ > ]
101
106
  > }
102
- > ],
107
+ > ]
103
108
  > }
104
109
  > ```
105
110
 
@@ -128,10 +133,13 @@ Simply denoting a field name (`field`) transforms it into `field = true`
128
133
 
129
134
  (`!field`) transforms it into `field = false`
130
135
 
136
+ > [!NOTE]
137
+ > This is true for the default operator set. If custom operators are defined, a custom [implicit condition](#implicit-condition) can be defined as well.
138
+
131
139
  ### Group
132
140
  *A group is multiple conditions joined by a junction operator such as AND or OR.*
133
141
  `({CONDITION} [...{J_OPERATOR} {CONDITION}])`
134
- Groups are implicit when junction operators are used (follows PEMDAS [ANDs grouped before ORs]). Parentheses can be used to denote them explicitly.
142
+ Groups are implicit when junction operators are used (follows PEMDAS \[ANDs grouped before ORs\]). Parentheses can be used to denote them explicitly.
135
143
 
136
144
  Groups can be nested.
137
145
  > Example: `user.activated & ((user.role = member & user.group : [abc, xyz]) | (user.role = admin & user.privileged))`
@@ -139,7 +147,7 @@ Groups can be nested.
139
147
  Groups can also be negated
140
148
  > `!(firstname = John & lastname = Doe)` &rarr; `firstname != John | lastname != Doe`
141
149
 
142
- ## Operators
150
+ ## Default Operators
143
151
  ### Junction Operators
144
152
  <details>
145
153
  <summary>AND</summary>
@@ -159,7 +167,7 @@ Groups can also be negated
159
167
  - `V`
160
168
  </details>
161
169
 
162
- ### Comparison Operators
170
+ ### Condition Operators
163
171
  <details>
164
172
  <summary>EQUAL</summary>
165
173
 
@@ -243,10 +251,61 @@ Groups can also be negated
243
251
  - `!~`
244
252
  </details>
245
253
 
254
+ ## Custom Operators
255
+ If the default operators don't fulfill your needs, a custom operator set can be defined.
256
+
257
+ ```js
258
+ new WizardParser({
259
+ operators: {
260
+ [OPERATOR_NAME]: {
261
+ negationName: NEGATION_OPERATOR_NAME,
262
+ aliases: ['ALIAS'],
263
+ type: 'numeric',
264
+ negationAliases: ['NEGALIAS']
265
+ },
266
+ ...
267
+ }
268
+ })
269
+ ```
270
+
271
+ An operator is inherently two operators: the base operator and its negation. When defining an operator, you must also define its `negationName`. You can also define aliases for operators and their negations.
272
+
273
+ Lastly, you must supply the data type the operator functions on. This type also determines the operator type (condition/junction \[a junction joins conditions together into a group\]).
274
+ - For **condition operators**, `type` can be `'primitive'`, `'boolean'`, `'string'`, `'number'`, `'date'`, `'numeric'`, or `'array'`. `primitive` allows all data types (singular). `array` allows all data types within an array. `numeric` allows `number` or `date`; however, `number` will be used unless the condition's field is only of type `date`.
275
+ - For **junction operators**, `type` can be `sumjunction` or `productjunction`. They're both group operators, but have different precedence for logical PEMDAS. For example, `A & B | C` becomes `(A & B) | C`. In logic, "and" is a product junction, and "or" is a sum junction. The negation of a sum junction is a product junction and vice-versa.
276
+
277
+ When defining custom operators, their names should be all uppercase. Two operators should not share names or aliases. This applies to the keys of the operator record, `negationName`, `aliases`, and `negationAliases`.
278
+
279
+ For condition operators, if, for whatever reason, you want to define the negation operators first, you can supply `exclusionary: true` which marks the operator you defined in the record as the negatory one.
280
+
281
+ ## Implicit Condition
282
+ You may have noted the existed of [implicit boolean](#implicit-boolean) for the default operator set. Once you start defining custom operators, there is no longer a default implicit condition. One can optionally be defined.
283
+
284
+ ```js
285
+ new WizardParser({
286
+ operators: {
287
+ [OPERATOR_NAME]: {
288
+ negationName: NEGATION_OPERATOR_NAME,
289
+ aliases: ['ALIAS'],
290
+ type: 'numeric',
291
+ negationAliases: ['NEGALIAS']
292
+ },
293
+ ...
294
+ },
295
+ implicitCondition: {
296
+ operator: OPERATOR_NAME, // The operator to use
297
+ value: '0', // The value, as a string
298
+ asType: 'number' // What datatype should the value be read as
299
+ }
300
+ })
301
+ ```
302
+
303
+ The implicit condition is applied when a field name is denoted without any operator. Example: (`field = value | otherfield`). In this case, `otherfield` would be parsed as `otherfield OPERATOR_NAME 0`. If a negator precedes the field (`!otherfield`), it uses the negated variant of the implicit operator.
304
+
246
305
  ## Constraints
247
- The `parse` function can be passed an object containing various constraints as its second parameter
306
+ When constructing a WizardParser instance (`new WizardParser()`), the constructor can be passed properties containing various constraints.
248
307
 
249
- ### `restricted`
308
+ ### Restricted Fields (`restricted`)
250
309
  A record mapping field names to restrictions. A value of `true` totally prohibits the usage of a field.
251
310
 
252
311
  Otherwise, a tuple can be passed
@@ -257,38 +316,38 @@ Values can be direct values (string, number, boolean) or regex expressions
257
316
  "allow" will allow the values/patterns and deny all others
258
317
  "deny" will deny the values/patterns and allow all others
259
318
 
260
- ### `types`
319
+ ### Field Types (`types`)
261
320
  A record mapping field names to (`boolean`, `string`, `number`, `date`). The value in the record can either be a single allowed type or an array of allowed types. Only operators that can function on that type can be used for that field. By default, fields will be treated as being able to be any of the three types.
262
321
 
263
322
  > Example:
264
323
  > ```js
265
- > parse('field1 = value', {
324
+ > new WizardParser({
266
325
  > types: {
267
326
  > field1: 'string',
268
327
  > field2: ['string', 'number']
269
328
  > }
270
- > })
329
+ > }).parse('field1 = value')
271
330
  > ```
272
331
 
273
332
  > [!NOTE]
274
- > A value will only be attempted to be parsed as a date if `'date'` is included in the field's type record.
275
- > If the value is a number, it will be parsed as number of milliseconds. Any non-number character will cause the value to be parsed as a string
333
+ > A value will only be attempted to be parsed as a date if `'date'` is included in the field's type record or if the operator is exclusively a date operator.
334
+ > According to the default date parser, if the value is a number, it will be parsed as number of milliseconds. Any non-number character will cause the value to be parsed as a string (See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)
276
335
 
277
336
  The type coercion priority chain is as follows:
278
337
  `boolean` -> `date` -> `number` -> `string`
279
338
  > [!WARNING]
280
- > This can cause issues for numbers with leading zeros. If this is a potential problem, make sure to exclude `number` from the types and include `string`
339
+ > This can cause issues for numbers with leading zeros. If this is a potential problem, make sure to exclude `number` from the field types and include `string`
281
340
 
282
341
  ### Regarding constraints: `validated` property
283
342
  When a field has matched either a key in `types` or a field in `restricted`, the `validated` property on the parsed condition will be true. This is due to a limitation with TypeScript's type checking.
284
343
 
285
344
  Therefore, type inference would look something like this:
286
345
  ```js
287
- const parsed = parse('field = value', {
346
+ const parsed = new WizardParser({
288
347
  types: {
289
348
  field: ['string', 'number']
290
349
  }
291
- })
350
+ }).parse('field = value')
292
351
 
293
352
  if (parsed.validated) {
294
353
  switch (parsed.type) {
@@ -304,6 +363,9 @@ if (parsed.validated) {
304
363
  }
305
364
  ```
306
365
 
366
+ ### `disallowUnvalidated`
367
+ Fields that are not present in the type or restriction record will considered invalid fields. This will make resulting parsed expression types far more usable without having to check if `validated === true`
368
+
307
369
  ### `caseInsensitive`
308
370
  Type/constraint checks will be case-insensitive on the field name
309
371
  > [!NOTE]
@@ -312,41 +374,78 @@ Type/constraint checks will be case-insensitive on the field name
312
374
  > [!WARNING]
313
375
  > Mismatching casing between the restricted record and the type record will prioritize the restricted record
314
376
 
315
- ### `disallowUnvalidated`
316
- Fields that are not present in the type or restriction record will considered invalid fields
317
-
318
377
  ### `dateInterpreter`
319
378
  A callback that determines how WizardQL interprets dates. Wizard will attempt to parse a value as a date if `'date'` is supplied in its type record
320
379
 
321
380
  By default, this is simply `(v) => new Date(v)`
322
381
 
323
382
  ## Stringification
324
- Parsed expressions can be converted back into strings using the `stringify` function. The stringify function comes with its own slew of options as its second parameter
383
+ Parsed expressions can be converted back into strings using the `stringify` method. The stringify method comes with its own options as its second parameter (or it can just be a string, selecting the dialect)
384
+
385
+ ```js
386
+ const parser = new WizardParser()
325
387
 
326
- ### `junctionNotation`
327
- The notation to use for junction operators
388
+ const parsed = parser.parse('...')
389
+ if (parsed) console.log(parser.stringify(parsed, DIALECT))
390
+ ```
391
+
392
+ ### `dialect`
393
+ The dialect determines how operators are stringified.
394
+
395
+ Custom dialects can be supplied in the WizardParser constructor. If using the default operators, the default dialects are:
328
396
  - Programmatic: `&`
329
397
  - Linguistic: `AND`
330
398
  - Formal: `^`
331
399
 
332
- ### `comparisonNotation`
333
- The notation to use for comparison operators
334
- - Programmatic: `=`
335
- - Linguistic: `EQUALS`
336
-
337
400
  ### `alwaysParenthesize`
338
401
  Always put parentheses around every group
339
402
 
340
403
  ### `compact`
341
- Don't include spaces in the output (except for surrounding lingustic operators)
404
+ Don't include spaces in the output. Operators that contain alpha characters will always be surrounded with spaces.
405
+
406
+ ### `condenseImplicit`
407
+ Conditions that are an instance of the [implicit condition](#implicit-condition) or its negation will be condensed into the implicit notation (`field`, `!field`).
408
+
409
+ For example, if the default condition is `some_field LESS 0` (assuming the LESS operator is defined), `field < 0` becomes `field` and `field >= 0` becomes `!field`. There is a special exception for booleans (also utilized for the default operator [implicit boolean](#implicit-boolean)) where `field = false`, which is technically not a negation of the implicit condition (`field != true`), is still condensed to `!field`
342
410
 
343
- ### `condenseBoolean`
344
- `EQUAL`/`NOTEQUAL` regarding booleans will be condensed into [implicit form](#implicit-boolean)
411
+ ### Date Serialization
412
+ A custom callback can be supplied to the parser constructor for how dates should be stringified. The default simply calls `Date.toISOString()`
413
+
414
+ ```js
415
+ new WizardParser({
416
+ dateSerializer: (d) => d.getTime().toString() // Serialize to time in milliseconds instead
417
+ })
418
+ ```
419
+
420
+ ### Custom Dialects
421
+ > See the default dialects [here](#dialect)
422
+
423
+ Whether using the default operator set or custom operators (must define custom dialects for custom operators if you're looking to stringify), custom dialects can be defined. This determines how `WizardParser.stringify()` prints operator names to the resulting string.
424
+
425
+ ```js
426
+ new WizardParser({
427
+ operators: {
428
+ [OPERATOR_NAME]: {
429
+ negationName: NEGATION_OPERATOR_NAME,
430
+ aliases: ['ALIAS'],
431
+ type: 'numeric',
432
+ negationAliases: ['NEGALIAS']
433
+ },
434
+ ...
435
+ },
436
+ dialects: {
437
+ [DIALECT_NAME]: {
438
+ [OPERATOR_NAME]: 'operator_denotation',
439
+ ...
440
+ }
441
+ }
442
+ })
443
+ ```
345
444
 
346
445
  ## Summarize
347
- You can use the `summarize` function to summarize a parsed expression, aggregated by field name across groups
446
+ You can use the `summarize` method to summarize a parsed expression, aggregated by field name across groups. This is useful for authorization checks
348
447
 
349
- `summarize(parse('(foo in [1, 2] and (bar = 2 or baz)) V (bar !: [1, 3] and foo = 3)'))`
448
+ `WizardParser.summarize(parse('(foo in [1, 2] and (bar = 2 or baz)) V (bar !: [1, 3] and foo = 3)'))`
350
449
  > ```js
351
450
  > [
352
451
  > ['foo', [
@@ -384,15 +483,15 @@ You can use the `summarize` function to summarize a parsed expression, aggregate
384
483
  > ```
385
484
 
386
485
  > [!NOTE]
387
- > `exclusionary` implies a negative operation (once that excludes the value)
486
+ > `exclusionary` implies a negatory operation (one that excludes the value)
388
487
 
389
488
  ## Execution Example
390
- Below is an example of how a Wizard query would be executed in the context of a [KnexJS Query](https://knexjs.org/)
489
+ Below is an example of how a Wizard query would be safely executed in the context of a [KnexJS Query](https://knexjs.org)
391
490
 
392
- https://github.com/guidance-analytics/wizard-ql/blob/bf8693e2cb5678ef855600d70bc495a614aa3d0b/src/execute.ts#L1-L35
491
+ https://github.com/exoRift/wizard-ql/blob/424c92e8fc205cf22a639887ebbafd822a7c8731/src/execute.ts#L1-L36
393
492
 
394
493
  ## DOM Input
395
- Wizard comes pre-packaged with a DOM input that applies classes for tokens, making for query input with syntax highlighting (up to discretion)
494
+ Wizard comes pre-packaged with a DOM input that applies classes for tokens, making for a query input with syntax highlighting (up to discretion)
396
495
 
397
496
  ```js
398
497
  // NOTE: The input element should be a regular div element, not an input element
@@ -408,14 +507,16 @@ Depending on a token's type, attributes will be applied to the contents of the i
408
507
  - `data-node` - An actual token
409
508
  - `data-quoted` - Quoted text
410
509
  - `data-number` - A number
411
- - `data-bracket` - A parenthesis or array bracket
412
- - `data-delimiter` - A comma
413
- - `data-negation` - A negatory exclamation mark
414
- - `data-operation` - A comparison or junction operator
510
+ - `data-bracket` - A parenthesis or array bracket (value is the bracket)
511
+ - `data-delimiter` - An array delimiter (comma)
512
+ - `data-negator` - A negation operator (exclamation mark)
513
+ - `data-operator` - A condition or junction operator (value will be 'junction' or 'condition')
415
514
 
416
515
  A token can also possess `data-error` if it is part of an error span
417
516
 
418
517
  The input itself can have the following attributes:
419
518
  - `data-error-message` - The error message
420
519
  - `data-error-start` - The starting token index for the error
421
- - `data-error-end` - The end token index for the error
520
+ - `data-error-end` - The end token index for the error
521
+
522
+ An example for styling this input can be found [here](./test/preview/index.css)
@@ -1,10 +1,10 @@
1
- import { type Token, type TypeRecord } from './spec';
2
- import { type ExpressionConstraints, parse } from './parse';
1
+ import { WizardParser, type WizardParserConfig } from './parser';
3
2
  import { ConstraintError, ParseError } from './errors';
4
- interface DOMInputOptions<T extends TypeRecord, V extends boolean> {
3
+ import type { ClassifiedToken, FieldTypeRecord, OperatorRecord } from './spec';
4
+ interface DOMInputOptions<F extends FieldTypeRecord, O extends OperatorRecord, V extends boolean, D extends string> {
5
5
  input: HTMLElement;
6
- constraints?: ExpressionConstraints<T, V>;
7
- onUpdate?: (expression: ReturnType<typeof parse<T, V>> | ParseError | ConstraintError, tokens: Token[], string: string) => void;
6
+ config?: WizardParserConfig<F, O, V, D>;
7
+ onUpdate?: (expression: ReturnType<WizardParser<F, O, V, D>['parse']> | ParseError | ConstraintError, tokens: ClassifiedToken[], string: string) => void;
8
8
  parseOnInitialize?: boolean;
9
9
  }
10
10
  /**
@@ -12,5 +12,5 @@ interface DOMInputOptions<T extends TypeRecord, V extends boolean> {
12
12
  * @warn This is a DOM function that is not meant for the backend
13
13
  * @returns A destroy function (destroys listening and functionality, not the element)
14
14
  */
15
- export declare function createDOMInput<const T extends TypeRecord, const V extends boolean>({ input, constraints, onUpdate, parseOnInitialize }: DOMInputOptions<T, V>): () => void;
15
+ export declare function createDOMInput<const F extends FieldTypeRecord, const O extends OperatorRecord, const V extends boolean, const D extends string>({ input, config, onUpdate, parseOnInitialize }: DOMInputOptions<F, O, V, D>): () => void;
16
16
  export {};
package/dist/errors.d.ts CHANGED
@@ -15,7 +15,7 @@ export declare class ParseError extends Error {
15
15
  /** The end token index */
16
16
  readonly endIndex: number | undefined;
17
17
  /** The tokens being parsed */
18
- readonly tokens: Token[] | undefined;
18
+ readonly tokens: readonly Token[] | undefined;
19
19
  /**
20
20
  * Construct a Parsing Error
21
21
  * @param message The error message
@@ -25,7 +25,7 @@ export declare class ParseError extends Error {
25
25
  * @param endToken The last token this error pertains to
26
26
  * @param endIndex The end token index
27
27
  */
28
- constructor(message: string, tokens: Token[] | undefined, startToken: Token | undefined, startIndex: number | undefined, endToken?: Token | undefined, endIndex?: number | undefined);
28
+ constructor(message: string, tokens: readonly Token[] | undefined, startToken: Token | undefined, startIndex: number | undefined, endToken?: Token | undefined, endIndex?: number | undefined);
29
29
  }
30
30
  /**
31
31
  * A WizardQL string expression parsing constraint error
@@ -43,7 +43,7 @@ export declare class ConstraintError extends Error {
43
43
  /** The end token index */
44
44
  readonly endIndex: number | undefined;
45
45
  /** The tokens being parsed */
46
- readonly tokens: Token[] | undefined;
46
+ readonly tokens: readonly Token[] | undefined;
47
47
  /**
48
48
  * Construct a Constraint Error
49
49
  * @param message The error message
@@ -53,5 +53,5 @@ export declare class ConstraintError extends Error {
53
53
  * @param endToken The last token this error pertains to
54
54
  * @param endIndex The end token index
55
55
  */
56
- constructor(message: string, tokens: Token[] | undefined, startToken: Token | undefined, startIndex: number | undefined, endToken?: Token | undefined, endIndex?: number | undefined);
56
+ constructor(message: string, tokens: readonly Token[] | undefined, startToken: Token | undefined, startIndex: number | undefined, endToken?: Token | undefined, endIndex?: number | undefined);
57
57
  }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,4 @@
1
- export { type Operation, type ComparisonOperation, type JunctionOperation, type Expression, type UncheckedExpression, type Condition, type UncheckedCondition, type Group, type Primitive, type TypeRecord, type Token, type ComparisonTypeToTSType, OPERATION_PURPOSE_DICTIONARY, COMPARISON_TYPE_DICTIONARY, OPERATION_ALIAS_DICTIONARY } from './spec';
2
- export { type ExpressionConstraints, QUOTE_EDGE_REGEX, parse, tokenize } from './parse';
3
- export { executeAsKnex } from './execute';
4
- export { type AggregationValue, summarize } from './summarize';
5
- export { type StringifyOptions, stringify } from './stringify';
1
+ export * from './spec';
2
+ export * from './parser';
6
3
  export { ParseError, ConstraintError } from './errors';
7
4
  export { createDOMInput } from './dominput';