astwerk 0.1.0 → 0.2.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/README.md CHANGED
@@ -70,7 +70,7 @@ is:open label:bug,ui -assignee:ahmet amount:10..40 (priority:high OR no:assignee
70
70
  | `amount:<10,>100` | either range |
71
71
  | `sprint:"Sprint 1".."Sprint 4"`, `sprint:<"Sprint 5"` | bounds with spaces, in quotes |
72
72
 
73
- - Field names are written exactly as the schema names them, and a field written any other way is reported as unknown. Values match without regard to case, so `is:OPEN` finds what `is:open` finds.
73
+ - Field names are written exactly as the schema names them, and a field written any other way is reported as unknown. Values match without regard to case, so `is:OPEN` finds what `is:open` finds. Case is compared without a locale, the same on every host, so the Turkish `İ` and `ı` do not match `i` and `I`.
74
74
  - `has` and `no` take a field name as their value, so no field can be named `has` or `no`.
75
75
  - `OR`, `AND` and `NOT` are operators only in capitals, so a lower-case `or` is free text.
76
76
  - `-` and `NOT` negate one term or word. A `-` negates only at the start of a word, so `amount:-5..5` runs from -5 to 5.
@@ -135,7 +135,7 @@ const issueSchema = defineSchema({
135
135
  })
136
136
  ```
137
137
 
138
- `get` may return one value, a list of values or nothing. A list matches when any of its values does, and an empty list or a missing value is what `no:field` finds. `text` gives the text that free words search, and without it free words filter nothing in `toPredicate`.
138
+ `get` may return one value, a list of values or nothing. A list matches when any of its values does, and an empty list or a missing value is what `no:field` finds. An empty string is a value, as it is in a database, so a `get` that means no value returns `undefined`. `text` gives the text that free words search, and without it free words filter nothing in `toPredicate`.
139
139
 
140
140
  ### Field Types
141
141
 
@@ -147,7 +147,9 @@ const issueSchema = defineSchema({
147
147
  | `boolean()` | `true` or `false`, in any case | no | no |
148
148
  | `date()` | a day or an instant, with `@today`. An item's value may be a `Date` | yes | no |
149
149
 
150
- `string()`, `number()` and `date()` take `suggest`, a function from the typed prefix to suggested values that may return a promise, and `tokens`. `enumOf` takes `tokens`.
150
+ `string()`, `number()` and `date()` take `suggest`, a function from the typed prefix to suggested values, and `tokens`. `enumOf` takes `tokens`.
151
+
152
+ `enumOf` is a list the schema closes, so `is:merged` on `enumOf(['open', 'closed'])` is an invalid value, reported and filtering nothing. No type checks a value against data, so a label that exists nowhere is a valid `string()` value that matches nothing. A field whose values come from data, such as labels or people, is therefore a `string()`, and the app passes the values it loads to `getSuggestions`, as [Values Loaded at Runtime](#values-loaded-at-runtime) shows.
151
153
 
152
154
  ### Dynamic Values
153
155
 
@@ -246,19 +248,37 @@ An `error` marks a part that filters nothing, and a `warning` text that filters
246
248
 
247
249
  `highlight` gives the spans to color, in order, with a kind for each: `key`, `value`, `dynamic` for a token, `text`, `keyword` for `OR`, `AND` and `NOT`, `negation`, `comparison`, `range`, `separator` and `paren`.
248
250
 
249
- `getCompletionContext` tells what the cursor is on. On a word that may become a field name it gives a `key` context, and on a value a `value` context with the field's key, the values already in the term and any comparison written before the value. Pass the context to `getSuggestions` for the suggestions, whose `insertText` replaces the text from `from` to `to`, quoted where the value needs it.
251
+ `getCompletionContext` tells what the cursor is on. On a word that may become a field name it gives a `key` context, and on a value a `value` context with the field's key, the values already in the term and any comparison written before the value. Pass the context to `getSuggestions` for the suggestions, whose `insertText` replaces the text from `from` to `to`, quoted where the value needs it. Field names and tokens are suggested when they start with the prefix, and a type's values as its `suggest` chooses. An editor that ranks candidates with its own matching passes the context with an empty `prefix` and gets them all.
250
252
 
251
253
  ```ts
252
254
  const context = getCompletionContext('is:open,c', 9)
253
255
  // { kind: 'value', key: 'is', prefix: 'c', from: 8, to: 9, taken: ['open'], atEnd: true }
254
256
 
255
257
  if (context != undefined) {
256
- const suggestions = await getSuggestions(context, issueSchema)
258
+ const suggestions = getSuggestions(context, issueSchema)
257
259
  // [{ label: 'closed', insertText: 'closed' }]
258
260
  }
259
261
  ```
260
262
 
261
- `getSuggestions` returns a promise only when the field type's `suggest` does, so an editor that offers the latest answer should drop the answers to older prefixes. Inside quoted free text there is no context to complete.
263
+ Inside quoted free text there is no context to complete.
264
+
265
+ ### Values Loaded at Runtime
266
+
267
+ Values that only the app can load, such as the labels of a repository, stay out of the schema, so the schema remains a definition and the canonical text never depends on what has loaded. Such a field is a `string()`, which takes any value, so a label that does not exist is written without a diagnostic and simply matches nothing; only the syntax around it is checked. The editor loads them for the field that `fieldNameOf` names, which follows aliases, and passes them to `getSuggestions` as `values`. They come after the field type's own values and tokens, so the editor shows the list at once and it grows below when they arrive. They are suggested as given, without filtering by the prefix, and the ones already in the term or in the list are left out.
268
+
269
+ ```ts
270
+ const context = getCompletionContext('labels:d', 8)
271
+
272
+ if (context?.kind == 'value' && fieldNameOf(issueSchema, context.key) == 'label') {
273
+ const shown = getSuggestions(context, issueSchema)
274
+ const labels = await searchLabels(context.prefix)
275
+ const complete = getSuggestions(context, issueSchema, {
276
+ values: labels.map(label => ({ value: label.name, description: label.description })),
277
+ })
278
+ }
279
+ ```
280
+
281
+ `getSuggestions` is synchronous, and astwerk uses no timers or browser APIs, so waiting until typing stops, cancelling a request for a prefix that is gone and showing that values are loading are the editor's.
262
282
 
263
283
  ## Queries
264
284
 
@@ -344,6 +364,10 @@ const cleared = stringify(withoutField(query, 'label'), issueSchema)
344
364
 
345
365
  TypeScript 5.4 or later. The package is published as ES modules.
346
366
 
367
+ ## The Name
368
+
369
+ In German, an _Ast_ is a branch, and _Astwerk_ is the branches of a tree taken together, as well as the late Gothic ornament of intertwined branches carved in stone. The name also begins with AST, the abstract syntax tree that every filter is read into, so it says what the package does: it turns a line of text into a tree of branches and writes the tree back as text.
370
+
347
371
  ## License
348
372
 
349
373
  MIT
package/dist/index.d.ts CHANGED
@@ -81,6 +81,56 @@ type CompletionContext = KeyCompletion | ValueCompletion;
81
81
  * What the cursor is on, for autocompletion. Returns `undefined` inside quoted free text, where nothing is suggested.
82
82
  */
83
83
  export declare function getCompletionContext(text: string, cursor: number): CompletionContext | undefined;
84
+ /**
85
+ * What tokens are resolved with. Apps add members for their own tokens, such as the signed-in user, by declaration
86
+ * merging.
87
+ */
88
+ interface ResolveContext {
89
+ /** @defaultValue the current time */
90
+ now?: Date;
91
+ }
92
+ interface TokenOffset {
93
+ amount: number;
94
+ unit?: string;
95
+ }
96
+ /** A dynamic value such as `@today-7d`. The query keeps it unresolved, so the text keeps its meaning. */
97
+ interface TokenValue {
98
+ kind: 'token';
99
+ name: string;
100
+ offset?: TokenOffset;
101
+ raw: string;
102
+ }
103
+ export declare function isTokenValue(value: unknown): value is TokenValue;
104
+ interface FieldSuggestion<V> {
105
+ value: V;
106
+ label?: string;
107
+ description?: string;
108
+ }
109
+ interface TokenDefinition<V> {
110
+ description?: string;
111
+ /** Allows an offset such as `+3` or `-7d`. A unit, when written, is one of these. */
112
+ offsetUnits?: ReadonlyArray<string>;
113
+ resolve(offset: TokenOffset | undefined, context: ResolveContext & {
114
+ now: Date;
115
+ }): V;
116
+ }
117
+ /** How a field reads, writes and compares its values. Built-in types and app types implement the same interface. */
118
+ interface FieldType<V> {
119
+ /** Returns `undefined` for text that is not a value of the type, which reports an invalid value. */
120
+ parse(raw: string): V | undefined;
121
+ format(value: V): string;
122
+ /** Decides `field:value`. Without it, `compare` decides, and without both, `==`. */
123
+ equals?(a: V, b: V): boolean;
124
+ /** Orders values. Only a type with `compare` takes comparisons and ranges. */
125
+ compare?(a: V, b: V): number;
126
+ /** Lets an unquoted `*` stand for any text, as in `label:*bug*`. */
127
+ wildcards?: boolean;
128
+ /** Values the type suggests for the typed prefix. Values an app loads at runtime go to `getSuggestions` instead. */
129
+ suggest?(prefix: string): Array<FieldSuggestion<V>>;
130
+ /** Dynamic values the type accepts, by name without the `@`. */
131
+ tokens?: Readonly<Record<string, TokenDefinition<V>>>;
132
+ }
133
+ type FieldTypeOptions<V> = Pick<FieldType<V>, 'suggest' | 'tokens'>;
84
134
  interface QueryGroup {
85
135
  type: 'and' | 'or';
86
136
  children: Array<Query>;
@@ -132,55 +182,6 @@ type Condition = InCondition | RangeCondition | TextCondition | EmptyCondition |
132
182
  type FieldCondition = Exclude<Condition, TextCondition>;
133
183
  type Query = QueryGroup | QueryNot | Condition | InvalidQuery;
134
184
  type QueryOf<Type extends Query['type']> = OfType<Query, Type>;
135
- /**
136
- * What tokens are resolved with. Apps add members for their own tokens, such as the signed-in user, by declaration
137
- * merging.
138
- */
139
- interface ResolveContext {
140
- /** @defaultValue the current time */
141
- now?: Date;
142
- }
143
- interface TokenOffset {
144
- amount: number;
145
- unit?: string;
146
- }
147
- /** A dynamic value such as `@today-7d`. The query keeps it unresolved, so the text keeps its meaning. */
148
- interface TokenValue {
149
- kind: 'token';
150
- name: string;
151
- offset?: TokenOffset;
152
- raw: string;
153
- }
154
- export declare function isTokenValue(value: unknown): value is TokenValue;
155
- interface FieldSuggestion<V> {
156
- value: V;
157
- label?: string;
158
- description?: string;
159
- }
160
- interface TokenDefinition<V> {
161
- description?: string;
162
- /** Allows an offset such as `+3` or `-7d`. A unit, when written, is one of these. */
163
- offsetUnits?: ReadonlyArray<string>;
164
- resolve(offset: TokenOffset | undefined, context: ResolveContext & {
165
- now: Date;
166
- }): V;
167
- }
168
- /** How a field reads, writes and compares its values. Built-in types and app types implement the same interface. */
169
- interface FieldType<V> {
170
- /** Returns `undefined` for text that is not a value of the type, which reports an invalid value. */
171
- parse(raw: string): V | undefined;
172
- format(value: V): string;
173
- /** Decides `field:value`. Without it, `compare` decides, and without both, `==`. */
174
- equals?(a: V, b: V): boolean;
175
- /** Orders values. Only a type with `compare` takes comparisons and ranges. */
176
- compare?(a: V, b: V): number;
177
- /** Lets an unquoted `*` stand for any text, as in `label:*bug*`. */
178
- wildcards?: boolean;
179
- suggest?(prefix: string): Array<FieldSuggestion<V>> | Promise<Array<FieldSuggestion<V>>>;
180
- /** Dynamic values the type accepts, by name without the `@`. */
181
- tokens?: Readonly<Record<string, TokenDefinition<V>>>;
182
- }
183
- type FieldTypeOptions<V> = Pick<FieldType<V>, 'suggest' | 'tokens'>;
184
185
  interface FieldDefinition<Item, V> {
185
186
  type: FieldType<V>;
186
187
  label?: string;
@@ -217,18 +218,23 @@ interface Schema<Item = unknown> {
217
218
  }
218
219
  /** Field names are matched exactly, so `Label:bug` is an unknown field when the field is `label`. */
219
220
  export declare function defineSchema<Item = unknown, Values extends Record<string, unknown> & ReservedFieldNames = {}>(definition: SchemaDefinition<Item, Values>): Schema<Item>;
221
+ /** The field a key stands for, following aliases. `undefined` for a key the schema does not know. */
222
+ export declare function fieldNameOf(schema: Schema, key: string): string | undefined;
220
223
  /** `insertText` is ready to replace the context's `from` to `to`, quoted where the value needs it. */
221
224
  interface Suggestion {
222
225
  label: string;
223
226
  insertText: string;
224
227
  description?: string;
225
228
  }
226
- type Suggestions = Array<Suggestion> | Promise<Array<Suggestion>>;
227
- /**
228
- * Suggests field names for a key, and for a value the field type's suggestions followed by its tokens. A field type
229
- * whose `suggest` is asynchronous makes the result a promise.
230
- */
231
- export declare function getSuggestions(context: CompletionContext, schema: Schema): Suggestions;
229
+ interface SuggestionOptions {
230
+ /**
231
+ * Values the app loaded for the field of a value context, such as the labels of a repository. They follow the
232
+ * field type's values and tokens, unfiltered by the prefix, without the ones the term or the list already has.
233
+ */
234
+ values?: ReadonlyArray<FieldSuggestion<unknown>>;
235
+ }
236
+ /** Suggests field names for a key, and for a value the field type's values, its tokens and then the loaded values. */
237
+ export declare function getSuggestions(context: CompletionContext, schema: Schema, options?: SuggestionOptions): Array<Suggestion>;
232
238
  export declare const DIAGNOSTIC_CODE: {
233
239
  readonly unknownField: 'unknownField';
234
240
  readonly invalidValue: 'invalidValue';
@@ -341,7 +347,10 @@ type DateValue = string | Date;
341
347
  * `created:>2026-01-31` starts the day after. `@today` is the current day in UTC.
342
348
  */
343
349
  export declare function date(options?: FieldTypeOptions<DateValue>): FieldType<DateValue>;
344
- /** One of a fixed list. A value written in another case reads as the listed one, so `is:OPEN` is `is:open`. */
350
+ /**
351
+ * One of a fixed list. A value written in another case reads as the listed one, so `is:OPEN` is `is:open`, and a value
352
+ * outside the list is an invalid value. Values that come from data, such as labels, belong in a `string()` field.
353
+ */
345
354
  export declare function enumOf<const Value extends string>(values: ReadonlyArray<Value>, options?: Pick<FieldTypeOptions<Value>, 'tokens'>): FieldType<Value>;
346
355
  /** A number with a dot for decimals. It takes comparisons and ranges. */
347
356
  export declare function number(options?: FieldTypeOptions<number>): FieldType<number>;
@@ -371,4 +380,4 @@ interface ParseResult {
371
380
  }
372
381
  /** Reads any text into a tree. Broken text gives diagnostics, never an exception. */
373
382
  export declare function parse(text: string): ParseResult;
374
- export type { BindResult, Bound, CompareOperator, CompareValue, CompletionContext, Condition, DateValue, Diagnostic, DiagnosticCode, DiagnosticSeverity, EmptyCondition, EqualValue, FieldCondition, FieldDefinition, FieldSuggestion, FieldType, FieldTypeOptions, Flat, FlatEmpty, FlatField, FlatRange, FlatSet, HighlightKind, HighlightSpan, InCondition, InvalidQuery, KeyCompletion, MatchCondition, ParseResult, Query, QueryGroup, QueryNot, QueryVisitor, RangeBound, RangeCondition, RangeValue, RawValue, ReservedFieldNames, ResolveContext, Schema, SchemaDefinition, Span, Suggestion, SyntaxGroup, SyntaxNode, SyntaxNot, SyntaxTerm, SyntaxText, TextCondition, TokenDefinition, TokenOffset, TokenValue, ValueCompletion };
383
+ export type { BindResult, Bound, CompareOperator, CompareValue, CompletionContext, Condition, DateValue, Diagnostic, DiagnosticCode, DiagnosticSeverity, EmptyCondition, EqualValue, FieldCondition, FieldDefinition, FieldSuggestion, FieldType, FieldTypeOptions, Flat, FlatEmpty, FlatField, FlatRange, FlatSet, HighlightKind, HighlightSpan, InCondition, InvalidQuery, KeyCompletion, MatchCondition, ParseResult, Query, QueryGroup, QueryNot, QueryVisitor, RangeBound, RangeCondition, RangeValue, RawValue, ReservedFieldNames, ResolveContext, Schema, SchemaDefinition, Span, Suggestion, SuggestionOptions, SyntaxGroup, SyntaxNode, SyntaxNot, SyntaxTerm, SyntaxText, TextCondition, TokenDefinition, TokenOffset, TokenValue, ValueCompletion };
package/dist/index.js CHANGED
@@ -519,6 +519,10 @@ function defineSchema(definition) {
519
519
  "~names": names
520
520
  };
521
521
  }
522
+ /** The field a key stands for, following aliases. `undefined` for a key the schema does not know. */
523
+ function fieldNameOf(schema, key) {
524
+ return schema["~names"].get(key);
525
+ }
522
526
  function findField(schema, name) {
523
527
  return Object.hasOwn(schema.fields, name) ? schema.fields[name] : void 0;
524
528
  }
@@ -616,12 +620,9 @@ function quote(raw) {
616
620
  return `"${raw.replace(/[\\"]/g, (match) => `\\${match}`)}"`;
617
621
  }
618
622
  // src/completion/suggestions.ts
619
- /**
620
- * Suggests field names for a key, and for a value the field type's suggestions followed by its tokens. A field type
621
- * whose `suggest` is asynchronous makes the result a promise.
622
- */
623
- function getSuggestions(context, schema) {
624
- return context.kind == "key" ? suggestKeys(context, schema) : suggestValues(context, schema);
623
+ /** Suggests field names for a key, and for a value the field type's values, its tokens and then the loaded values. */
624
+ function getSuggestions(context, schema, options = {}) {
625
+ return context.kind == "key" ? suggestKeys(context, schema) : suggestValues(context, schema, options.values ?? []);
625
626
  }
626
627
  function suggestKeys(context, schema) {
627
628
  const fields = Object.entries(schema.fields).filter(([name, field]) => startsWithIgnoringCase(name, context.prefix) || startsWithIgnoringCase(field.label ?? "", context.prefix)).map(([name, field]) => ({
@@ -635,14 +636,13 @@ function suggestKeys(context, schema) {
635
636
  }));
636
637
  return [...fields, ...presence];
637
638
  }
638
- function suggestValues(context, schema) {
639
+ function suggestValues(context, schema, loaded) {
639
640
  if (isPresenceKey(context.key)) return suggestFieldNames(context, schema);
640
- const field = findField(schema, schema["~names"].get(context.key) ?? "");
641
+ const field = findField(schema, fieldNameOf(schema, context.key) ?? "");
641
642
  if (field == void 0) return [];
642
- const tokens = suggestTokens(context, field.type);
643
- const values = field.type.suggest?.(context.prefix) ?? [];
644
- if (values instanceof Promise) return values.then((resolved) => [...toSuggestions(resolved, context, field.type), ...tokens]);
645
- return [...toSuggestions(values, context, field.type), ...tokens];
643
+ const own = [...toSuggestions(field.type.suggest?.(context.prefix) ?? [], context, field.type), ...suggestTokens(context, field.type)];
644
+ const added = toSuggestions(loaded, context, field.type).filter((suggestion) => !own.some((shown) => equalsIgnoringCase(shown.insertText, suggestion.insertText)));
645
+ return [...own, ...added];
646
646
  }
647
647
  function suggestFieldNames(context, schema) {
648
648
  return Object.entries(schema.fields).filter(([name]) => startsWithIgnoringCase(name, context.prefix) && !isTaken(name, context)).map(([name, field]) => ({
@@ -1365,7 +1365,7 @@ function toPredicate(query, schema, context = {}) {
1365
1365
  in: (condition) => matchesIn(condition, schema),
1366
1366
  range: (condition) => matchesRange(condition, schema),
1367
1367
  text: (condition) => matchesText(condition, schema),
1368
- empty: (condition) => (item) => fieldValues(item, condition.field, schema).every((value) => value === ""),
1368
+ empty: (condition) => (item) => fieldValues(item, condition.field, schema).length == 0,
1369
1369
  match: (condition) => matchesPattern(condition, schema)
1370
1370
  });
1371
1371
  }
@@ -1420,7 +1420,7 @@ function startsAWord(text, word) {
1420
1420
  }
1421
1421
  function fieldValues(item, field, schema) {
1422
1422
  const definition = findField(schema, field);
1423
- const value = definition != void 0 && "get" in definition ? definition.get?.(item) : ownProperty(item, field);
1423
+ const value = definition?.get == void 0 ? ownProperty(item, field) : definition.get(item);
1424
1424
  if (value == void 0) return [];
1425
1425
  return Array.isArray(value) ? value.filter((element) => element != void 0) : [value];
1426
1426
  }
@@ -1718,7 +1718,10 @@ function formatInstant(time) {
1718
1718
  return Number.isFinite(time) ? new Date(time).toISOString().replace(".000Z", "Z") : String(time);
1719
1719
  }
1720
1720
  // src/schema/types/enum-type.ts
1721
- /** One of a fixed list. A value written in another case reads as the listed one, so `is:OPEN` is `is:open`. */
1721
+ /**
1722
+ * One of a fixed list. A value written in another case reads as the listed one, so `is:OPEN` is `is:open`, and a value
1723
+ * outside the list is an invalid value. Values that come from data, such as labels, belong in a `string()` field.
1724
+ */
1722
1725
  function enumOf(values, options = {}) {
1723
1726
  return {
1724
1727
  parse: (raw) => values.find((value) => equalsIgnoringCase(value, raw)),
@@ -1761,4 +1764,4 @@ function string(options = {}) {
1761
1764
  function highlight(text) {
1762
1765
  return scan(text).highlights;
1763
1766
  }
1764
- export { DIAGNOSTIC_CODE, DIAGNOSTIC_SEVERITY, FLAT_EMPTY, HIGHLIGHT_KIND, bind, boolean, canonical, date, defineSchema, enumOf, fold, fromFlat, getCompletionContext, getSuggestions, highlight, isTokenValue, number, parse, resolveTokens, string, stringify, toFlat, toPredicate, valuesOf, withoutField };
1767
+ export { DIAGNOSTIC_CODE, DIAGNOSTIC_SEVERITY, FLAT_EMPTY, HIGHLIGHT_KIND, bind, boolean, canonical, date, defineSchema, enumOf, fieldNameOf, fold, fromFlat, getCompletionContext, getSuggestions, highlight, isTokenValue, number, parse, resolveTokens, string, stringify, toFlat, toPredicate, valuesOf, withoutField };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astwerk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A filter query language that parses key:value queries into a syntax tree, binds them to a schema and writes them back in one canonical form.",
5
5
  "keywords": [
6
6
  "ast",