@20baht/engine 0.0.0-stage → 0.1.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -2
  3. package/dist/approval.d.ts +15 -0
  4. package/dist/approval.js +18 -0
  5. package/dist/dates.d.ts +34 -0
  6. package/dist/dates.js +91 -0
  7. package/dist/defaults.d.ts +6 -0
  8. package/dist/defaults.js +37 -0
  9. package/dist/display.d.ts +33 -0
  10. package/dist/display.js +110 -0
  11. package/dist/engine/conditions.d.ts +27 -0
  12. package/dist/engine/conditions.js +123 -0
  13. package/dist/engine/evaluate.d.ts +8 -0
  14. package/dist/engine/evaluate.js +368 -0
  15. package/dist/engine/expressions.d.ts +3 -0
  16. package/dist/engine/expressions.js +70 -0
  17. package/dist/engine/form-session.d.ts +129 -0
  18. package/dist/engine/form-session.js +310 -0
  19. package/dist/engine/graph.d.ts +40 -0
  20. package/dist/engine/graph.js +59 -0
  21. package/dist/engine/runtime.d.ts +173 -0
  22. package/dist/engine/runtime.js +237 -0
  23. package/dist/engine/scripts.d.ts +34 -0
  24. package/dist/engine/scripts.js +98 -0
  25. package/dist/flags.d.ts +19 -0
  26. package/dist/flags.js +49 -0
  27. package/dist/form-values.d.ts +78 -0
  28. package/dist/form-values.js +6 -0
  29. package/dist/i18n.d.ts +171 -0
  30. package/dist/i18n.js +298 -0
  31. package/dist/index.d.ts +25 -0
  32. package/dist/index.js +23 -0
  33. package/dist/keys.d.ts +14 -0
  34. package/dist/keys.js +4 -0
  35. package/dist/legacy.d.ts +14 -0
  36. package/dist/legacy.js +47 -0
  37. package/dist/pattern-safety.d.ts +34 -0
  38. package/dist/pattern-safety.js +267 -0
  39. package/dist/same-data.d.ts +5 -0
  40. package/dist/same-data.js +23 -0
  41. package/dist/shortcut.d.ts +44 -0
  42. package/dist/shortcut.js +176 -0
  43. package/dist/types.d.ts +541 -0
  44. package/dist/types.js +1 -0
  45. package/dist/urls.d.ts +8 -0
  46. package/dist/urls.js +30 -0
  47. package/dist/validators.d.ts +39 -0
  48. package/dist/validators.js +372 -0
  49. package/dist/views.d.ts +12 -0
  50. package/dist/views.js +11 -0
  51. package/package.json +49 -4
@@ -0,0 +1,541 @@
1
+ /** Control types supported by v1 (spec 01 §2). */
2
+ export type FieldType = 'text' | 'textarea' | 'markdown' | 'number' | 'currency' | 'email' | 'password' | 'dropdown' | 'multiselect' | 'checkbox' | 'radio' | 'toggle' | 'date' | 'time' | 'file' | 'label' | 'section' | 'repeater' | 'tags' | 'rating' | 'range' | 'reference';
3
+ export type FieldWidth = '1/4' | '1/2' | '3/4' | 'full';
4
+ /** `date` field selection mode (spec 01 §2). */
5
+ export type DateMode = 'single' | 'range' | 'multiple';
6
+ export interface FieldOption {
7
+ key: string;
8
+ label: string;
9
+ /** Muted helper line: under the label on a radio card (variant: 'card'),
10
+ * and in a dropdown (`<baht-select>`) both under the label in each list
11
+ * option and after the label on the closed trigger while selected. */
12
+ description?: string;
13
+ /** radio (variant: 'card' only): icon name from the curated set (see icons.ts). */
14
+ icon?: string;
15
+ /** radio (variant: 'card' only): this option's own share of the row (same
16
+ * fractions as `FieldDescriptor.width`), instead of the default
17
+ * auto-wrapping ~200px card. Unset options keep the default. */
18
+ width?: FieldWidth;
19
+ }
20
+ /** Ordering/equality ops available to the `compare` validator. */
21
+ export type CompareOp = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';
22
+ /**
23
+ * Declarative validator (spec 01 §4). `custom` resolves `fn` from the
24
+ * registry; `compare` checks this value against a sibling field's value
25
+ * (same form — or same row inside a repeater) and skips while the sibling
26
+ * is empty or unknown.
27
+ */
28
+ export interface ValidatorSpec {
29
+ type: 'required' | 'minLength' | 'maxLength' | 'min' | 'max' | 'pattern' | 'email' | 'compare' | 'custom' | 'url';
30
+ value?: unknown;
31
+ fn?: string;
32
+ op?: CompareOp;
33
+ field?: string;
34
+ /** url: allowed schemes, without the colon (case-insensitive). Default `['http', 'https']`. */
35
+ schemes?: string[];
36
+ message?: string;
37
+ }
38
+ /** One item of `fields[]` (spec 01 §1). */
39
+ export interface FieldDescriptor {
40
+ order: number;
41
+ type: FieldType;
42
+ key: string;
43
+ label?: string;
44
+ placeholder?: string;
45
+ /**
46
+ * dropdown: the name of the empty choice, when no value means something ("The preset's own
47
+ * image"). Shown on the trigger and as the list's first row in plain text, not as a muted
48
+ * placeholder, and in read-only views. The value stays `null`.
49
+ */
50
+ empty_label?: string;
51
+ /**
52
+ * Leading icon inside the control (text/email/password/currency/textarea)
53
+ * or before the value (dropdown) — icon name from the curated set (see
54
+ * icons.ts). Unrecognized names render no icon (no layout shift).
55
+ */
56
+ icon?: string;
57
+ help?: string;
58
+ autocomplete?: string;
59
+ width?: FieldWidth;
60
+ value?: unknown;
61
+ disabled?: boolean;
62
+ readonly?: boolean;
63
+ required?: boolean;
64
+ options?: FieldOption[];
65
+ /** Registry name resolving this field's options from current form data. */
66
+ options_from?: string;
67
+ /**
68
+ * Same-form field keys this field's options depend on. When one changes
69
+ * (user edit), the options refetch and this field's value clears —
70
+ * cascading through chained dependents (province -> district -> …).
71
+ */
72
+ options_deps?: string[];
73
+ /**
74
+ * text/textarea/… max character length; **tags**: max characters per tag
75
+ * (default 32) — enforced per chip, not on the array as a whole.
76
+ */
77
+ max_length?: number;
78
+ min_length?: number;
79
+ min?: number | string;
80
+ /** number/currency/date/time upper bound; **rating**: star count (1–10, default 5); **range**: default 100. */
81
+ max?: number | string;
82
+ /**
83
+ * date: selection mode. 'single' (default) -> value is one ISO string;
84
+ * 'range' -> value is `[start, end]` (both ISO, inclusive); 'multiple' ->
85
+ * value is an ISO string[] in pick order.
86
+ */
87
+ date_mode?: DateMode;
88
+ /**
89
+ * date: DISPLAY format of the typed/rendered text (flatpickr tokens, e.g.
90
+ * 'd/m/Y', 'j M Y'). The VALUE stays ISO yyyy-mm-dd (or yyyy-mm-ddThh:mm
91
+ * with `enable_time`) regardless.
92
+ */
93
+ date_format?: string;
94
+ /**
95
+ * date: adds a time-of-day picker under the calendar. The VALUE switches
96
+ * from an ISO day ('2026-04-13') to an ISO local datetime with no seconds
97
+ * or offset ('2026-04-13T14:30'), for every `date_mode` (a range's two
98
+ * ends each carry their own time). `min` / `max` stay calendar days —
99
+ * they bound which DAY is pickable, not the time within it.
100
+ */
101
+ enable_time?: boolean;
102
+ /** date (`enable_time` only): 24-hour clock instead of AM/PM. Default false. */
103
+ time_24hr?: boolean;
104
+ /**
105
+ * date: days that cannot be picked — each entry an ISO date ('2026-04-13')
106
+ * or an inclusive ISO interval ('2026-04-13/2026-04-15'). Enforced by the
107
+ * engine too, so a hand-crafted submission cannot bypass the calendar.
108
+ */
109
+ disabled_dates?: string[];
110
+ /** date: weekdays that cannot be picked, 0 = Sunday … 6 = Saturday. */
111
+ disabled_weekdays?: number[];
112
+ step?: number;
113
+ /** number: reject fractions (validated on client and server). */
114
+ integer?: boolean;
115
+ rows?: number;
116
+ accept?: string;
117
+ multiple?: boolean;
118
+ max_size?: number;
119
+ /**
120
+ * Registry uploader name (spec 01 §13). With it, picking a file uploads
121
+ * immediately and the VALUE becomes a serializable UploadedFile ref
122
+ * (arrays when `multiple`) — without it, capture-only File handles (v1).
123
+ */
124
+ uploader?: string;
125
+ /**
126
+ * reference: name of the record lookup in `registry.references` (spec 01 §2.1). The value
127
+ * is the picked record's id; the lookup searches records and resolves an id to its label.
128
+ */
129
+ reference?: string;
130
+ text?: string;
131
+ /**
132
+ * section: this section starts a tab of `<baht-form>`, with `text` as its label. Fields before
133
+ * the first tab stay above the strip; each tab holds the fields up to the next tab section.
134
+ */
135
+ tab?: boolean;
136
+ /** section: a heading the user can fold, hiding the fields up to the next section. */
137
+ collapsible?: boolean;
138
+ /** section with `collapsible`: starts folded. An error inside unfolds it. */
139
+ collapsed?: boolean;
140
+ /**
141
+ * Never shown, and still sent: a value only scripts or the host set, such as what a workflow
142
+ * routes on. It takes no place in the layout and the form does not validate it, so do not mark it
143
+ * `required`. A rule that hides a field is different: the validator drops that field's value.
144
+ */
145
+ hidden?: boolean;
146
+ /** With `layout.columns: 2`: the column this field keeps to. Unset spans both. */
147
+ column?: 1 | 2;
148
+ /** repeater: `dialog` lists the rows as a table and edits one at a time in a modal. */
149
+ row_editor?: 'inline' | 'dialog';
150
+ variant?: string;
151
+ /**
152
+ * Feature flag gating this field (spec 01 §12): shown only while the flag
153
+ * is on ('name') or off ('!name'). Flag-off = as if the field were never in
154
+ * the schema — not rendered, not validated, absent from the payload.
155
+ */
156
+ flag?: string;
157
+ fields?: FieldDescriptor[];
158
+ min_rows?: number;
159
+ max_rows?: number;
160
+ add_label?: string;
161
+ /** tags: cap on the number of chips. Unset = unlimited. */
162
+ max_items?: number;
163
+ /**
164
+ * tags: false restricts chips to the suggestion list (matched
165
+ * case-insensitively) — typed text that isn't a suggestion cannot become a
166
+ * chip. Default true. The component enforces it against whatever options
167
+ * are resolved (static or `options_from`); @20baht/validator re-checks
168
+ * only static `options` — it cannot resolve `options_from` and trusts the
169
+ * client there, as it does for dropdown/multiselect.
170
+ */
171
+ allow_new?: boolean;
172
+ validators?: ValidatorSpec[];
173
+ formatter?: string;
174
+ }
175
+ /**
176
+ * A named, client-side-only projection of a form: which fields to show, in
177
+ * what order (e.g. per user role). Display sugar only — the submit payload is
178
+ * always the full form and the server always validates the complete schema.
179
+ */
180
+ export interface FormViewSpec {
181
+ name: string;
182
+ /** field keys included, in display order; keys absent from fields are ignored */
183
+ fields: string[];
184
+ }
185
+ /** A Form definition — consumed standalone by <baht-form> (spec 00 §4.1). */
186
+ /** `<baht-form>` layout, part of the schema so that hosts need no CSS of their own for it. */
187
+ export interface FormLayout {
188
+ /** `left` puts each label beside its control, on one line for the whole form. */
189
+ label?: 'top' | 'left';
190
+ /** Width of the label column with `label: 'left'`, e.g. `200px`. */
191
+ label_width?: string;
192
+ /** `2`: two independent columns, chosen per field with `column`. */
193
+ columns?: 1 | 2;
194
+ }
195
+ export interface FormDefinition {
196
+ form_id: string;
197
+ form_name: string;
198
+ fields: FieldDescriptor[];
199
+ /** Optional named display subsets; select one via <baht-form view="...">. */
200
+ views?: FormViewSpec[];
201
+ /** How the fields are laid out. Unset: labels on top, fields flowing by `width`. */
202
+ layout?: FormLayout;
203
+ /** Client scripts (spec 01 §14) — handlers referenced by name, resolved from `registry.scripts`. */
204
+ scripts?: ScriptSpec[];
205
+ }
206
+ /** When a client script runs: form load, one field's change, or submit/validate. */
207
+ export type ScriptEvent = 'load' | 'change' | 'submit';
208
+ /**
209
+ * One item of `scripts[]`. `field` is required for `change` (the field key the
210
+ * hook listens to) and ignored otherwise. `handler` names a function in
211
+ * `registry.scripts` — functions never travel in JSON.
212
+ */
213
+ export interface ScriptSpec {
214
+ id?: string;
215
+ on: ScriptEvent;
216
+ field?: string;
217
+ handler: string;
218
+ }
219
+ export type ScriptMessageType = 'info' | 'warning' | 'error';
220
+ export interface ScriptMessage {
221
+ message: string;
222
+ type: ScriptMessageType;
223
+ }
224
+ /** What a script handler receives as its second argument. */
225
+ export interface ScriptEventDetail {
226
+ on: ScriptEvent;
227
+ form_name: string;
228
+ /** `change` only: the field that changed. */
229
+ key?: string;
230
+ /** `change` only. */
231
+ oldValue?: unknown;
232
+ newValue?: unknown;
233
+ /** True while the form is loading (initial `change` pass + `load`), like ServiceNow's isLoading. */
234
+ isLoading: boolean;
235
+ /** Snapshot of the form's flat data when the script was invoked. */
236
+ data: Record<string, unknown>;
237
+ }
238
+ /**
239
+ * The `g` object handed to every script — the ServiceNow `g_form` equivalent,
240
+ * scoped to one form. State setters are OVERRIDES layered on top of the
241
+ * workflow's rule-derived states (script wins) until `resetState(key)`.
242
+ */
243
+ export interface ScriptContext {
244
+ readonly formName: string;
245
+ getValue(key: string): unknown;
246
+ getData(): Record<string, unknown>;
247
+ getField(key: string): FieldDescriptor | undefined;
248
+ /** Write a value — runs that field's `change` scripts (cascade, depth-guarded). */
249
+ setValue(key: string, value: unknown): void;
250
+ /** Reset a field to its descriptor default. */
251
+ clearValue(key: string): void;
252
+ setVisible(key: string, visible: boolean): void;
253
+ setReadOnly(key: string, readonly: boolean): void;
254
+ setRequired(key: string, required: boolean): void;
255
+ setDisabled(key: string, disabled: boolean): void;
256
+ /** Drop every script override on `key` (or on all fields when omitted). */
257
+ resetState(key?: string): void;
258
+ /** Inline message under a field's control (one per field; replaces the previous). */
259
+ showFieldMsg(key: string, message: string, type?: ScriptMessageType): void;
260
+ hideFieldMsg(key: string): void;
261
+ /** Form-level messages; `error` ones become `{ key: '$' }` validation errors on submit. */
262
+ addErrorMessage(message: string): void;
263
+ addInfoMessage(message: string): void;
264
+ clearMessages(): void;
265
+ }
266
+ /**
267
+ * A client script. `submit` handlers may return `false` to block the
268
+ * submission; other return values are ignored. Handlers are synchronous.
269
+ */
270
+ export type ScriptHandler = (g: ScriptContext, event: ScriptEventDetail) => void | boolean;
271
+ export type ApprovalDecision = 'approved' | 'rejected';
272
+ /** Comment box policy on an approval step. */
273
+ export type ApprovalCommentMode = 'hidden' | 'optional' | 'requireOnReject' | 'required';
274
+ export interface ApprovalConfig {
275
+ /** formNames whose data the summary shows; default = every earlier visible form. */
276
+ summary_forms?: string[];
277
+ approve_label?: string;
278
+ reject_label?: string;
279
+ comment?: ApprovalCommentMode;
280
+ /** Reject behavior: end the workflow (default) or send the user back to a form. */
281
+ on_reject?: {
282
+ action: 'end';
283
+ } | {
284
+ action: 'goto';
285
+ form: string;
286
+ };
287
+ }
288
+ /** A form inside a workflow: adds its position in the linear order. */
289
+ export interface WorkflowForm extends FormDefinition {
290
+ order: number;
291
+ /**
292
+ * 'approval' renders a decision step (summary + Approve/Reject) instead of
293
+ * fields; its `decision`/`comment` values live in data like any field.
294
+ * Default 'form'.
295
+ */
296
+ kind?: 'form' | 'approval';
297
+ approval?: ApprovalConfig;
298
+ /** Name of one of this form's `views` to render for this step (display only). */
299
+ view?: string;
300
+ /** Feature flag gating this whole step (spec 01 §12). */
301
+ flag?: string;
302
+ }
303
+ export type ConditionOp = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'notIn' | 'contains' | 'notContains' | 'startsWith' | 'endsWith' | 'isEmpty' | 'isNotEmpty';
304
+ /** Leaf: compare `form_name.fieldKey` against a constant or another field. */
305
+ export interface FieldCondition {
306
+ field: string;
307
+ op: ConditionOp;
308
+ value?: unknown;
309
+ value_field?: string;
310
+ }
311
+ export type Condition = FieldCondition | {
312
+ and: Condition[];
313
+ } | {
314
+ or: Condition[];
315
+ } | {
316
+ not: Condition;
317
+ };
318
+ export type ValueExpr = {
319
+ ref: string;
320
+ } | {
321
+ const: unknown;
322
+ } | {
323
+ op: 'add' | 'sub' | 'mul' | 'div' | 'concat' | 'coalesce';
324
+ args: ValueExpr[];
325
+ } | {
326
+ if: [Condition, ValueExpr, ValueExpr];
327
+ };
328
+ export interface FieldTarget {
329
+ form: string;
330
+ field: string;
331
+ }
332
+ export interface FormTarget {
333
+ form: string;
334
+ }
335
+ export type FieldActionType = 'show' | 'hide' | 'enable' | 'disable' | 'readonly' | 'required' | 'optional';
336
+ export type Action = {
337
+ action: FieldActionType;
338
+ target: FieldTarget;
339
+ } | {
340
+ action: 'setValue';
341
+ target: FieldTarget;
342
+ value: ValueExpr;
343
+ lock?: boolean;
344
+ } | {
345
+ action: 'showForm' | 'hideForm' | 'skipForm';
346
+ target: FormTarget;
347
+ };
348
+ export interface Rule {
349
+ id?: string;
350
+ priority?: number;
351
+ when?: Condition;
352
+ then?: Action[];
353
+ else?: Action[];
354
+ /** Feature flag gating this rule (spec 01 §12). */
355
+ flag?: string;
356
+ }
357
+ /** Flag values — typically fetched from one static JSON file (spec 01 §12). */
358
+ export type FeatureFlags = Record<string, boolean>;
359
+ /**
360
+ * A conditional edge between steps (spec 03 §6). With `transitions` present
361
+ * the wizard routes as a graph: from a form, the first edge whose `when`
362
+ * matches wins; `to: 'end'` submits. Forms with no outgoing edges (and
363
+ * non-matching edge sets) fall back to the next visible form in `order`, so
364
+ * linear authoring keeps working and branches are added only where needed.
365
+ */
366
+ export interface Transition {
367
+ from: string;
368
+ to: string;
369
+ when?: Condition;
370
+ flag?: string;
371
+ }
372
+ /** A Workflow definition — consumed by <baht-workflow> (spec 00 §4.2). */
373
+ export interface WorkflowDefinition {
374
+ workflow_id: string;
375
+ forms: WorkflowForm[];
376
+ rules: Rule[];
377
+ /** Optional graph routing (spec 03 §6); absent = linear by `order`. */
378
+ transitions?: Transition[];
379
+ }
380
+ /** One record a reference lookup returns (spec 01 §2.1). */
381
+ export interface ReferenceOption {
382
+ /** Record id — what the field's value holds. */
383
+ key: string;
384
+ label: string;
385
+ /** Secondary text shown right-aligned (e.g. the record's department or table). */
386
+ sub?: string;
387
+ }
388
+ /**
389
+ * A record lookup for `reference` fields, registered as `registry.references[name]`.
390
+ * `search` gets the typed term and the form's current flat data (for dependent lookups);
391
+ * `resolve` turns a stored id back into its label — used to display an existing value, and by
392
+ * `verifyReferences` in @20baht/validator to reject ids that do not exist. Without
393
+ * `resolve`, the raw id is shown and the server cannot verify it.
394
+ */
395
+ export interface ReferenceLookup {
396
+ search: (term: string, data: Record<string, unknown>) => ReferenceOption[] | Promise<ReferenceOption[]>;
397
+ resolve?: (id: string) => ReferenceOption | null | Promise<ReferenceOption | null>;
398
+ /** With `list`: what the table of records shows. */
399
+ columns?: FilterField[];
400
+ /** With `list`: every column on offer, dot-walked ones included. Their keys reach `list`. */
401
+ walk?: ReferenceColumns;
402
+ /** The columns this person chose for this table last time, if any. */
403
+ savedColumns?: () => string[] | null;
404
+ /** The person chose columns: keep them for `savedColumns`. */
405
+ saveColumns?: (keys: string[]) => void;
406
+ /** The filters this person saved for this table, if any. */
407
+ savedFilters?: () => SavedFilter[];
408
+ /** The person saved or deleted a filter: keep the list for `savedFilters`. */
409
+ saveFilters?: (filters: SavedFilter[]) => void;
410
+ /**
411
+ * One page of records. Set it and the field becomes a box to type in plus a search button that
412
+ * opens the records as a table. `pageOfRows` answers it from rows already in memory.
413
+ */
414
+ list?: (query: ReferenceQuery, data: Record<string, unknown>) => ReferencePage | Promise<ReferencePage>;
415
+ }
416
+ /** Columns a person can add to a table: a label, or fields to dot-walk into. */
417
+ export type ReferenceColumns = Record<string, string | {
418
+ label: string;
419
+ fields?: ReferenceColumns;
420
+ type?: FilterField['type'];
421
+ options?: FilterField['options'];
422
+ filterable?: boolean;
423
+ }>;
424
+ export type FilterOp = 'contains' | 'eq' | 'ne' | 'gt' | 'lt' | 'empty' | 'not_empty';
425
+ /** A column that can be filtered on. */
426
+ export interface FilterField {
427
+ key: string;
428
+ label: string;
429
+ type?: 'text' | 'number' | 'date' | 'choice';
430
+ /** With \`type: 'choice'\`. */
431
+ options?: {
432
+ key: string;
433
+ label: string;
434
+ }[];
435
+ }
436
+ export interface FilterCondition {
437
+ field: string;
438
+ op: FilterOp;
439
+ value: string;
440
+ }
441
+ /** What \`<baht-filter-builder>\` edits. Send it to your API, or test rows with \`matchesFilter\`. */
442
+ export interface FilterValue {
443
+ match: 'all' | 'any';
444
+ conditions: FilterCondition[];
445
+ }
446
+ /** A filter a person named to use again. The host keeps the list. */
447
+ export interface SavedFilter {
448
+ name: string;
449
+ value: FilterValue;
450
+ }
451
+ /** What the table of a reference's records asks for. */
452
+ export interface ReferenceQuery {
453
+ /** The box above the table: a term in one column. */
454
+ search?: {
455
+ field: string;
456
+ term: string;
457
+ };
458
+ /** The search row under the headers: column key -> term. */
459
+ columns: Record<string, string>;
460
+ filter: FilterValue;
461
+ sort?: {
462
+ key: string;
463
+ dir: 'asc' | 'desc';
464
+ };
465
+ /** 1-based. */
466
+ page: number;
467
+ pageSize: number;
468
+ }
469
+ /** One record of the table: its id, the label the field shows, and its cells by column key. */
470
+ export interface ReferenceRow {
471
+ key: string;
472
+ label: string;
473
+ values: Record<string, unknown>;
474
+ }
475
+ export interface ReferencePage {
476
+ rows: ReferenceRow[];
477
+ /** Records matching the query, on every page. */
478
+ total: number;
479
+ }
480
+ /** Serializable result of a registry uploader (spec 01 §13). */
481
+ export interface UploadedFile {
482
+ name: string;
483
+ size: number;
484
+ type?: string;
485
+ url: string;
486
+ }
487
+ /**
488
+ * A `custom` validator (`registry.validators[fn]`): null when valid, else the message.
489
+ * `data` is the surrounding flat data, the same object `compare` reads: the whole form,
490
+ * or the row for a repeater column (`{}` when the caller has none). `field` is the
491
+ * descriptor being validated. A one-argument `(value) => …` still fits.
492
+ */
493
+ export type CustomValidator = (value: unknown, data: Record<string, unknown>, field: FieldDescriptor) => string | null;
494
+ export interface Registry {
495
+ formatters?: Record<string, (value: unknown) => unknown>;
496
+ /** `custom` validators by name: see `CustomValidator`. */
497
+ validators?: Record<string, CustomValidator>;
498
+ /** Option fetchers for `options_from` — receive the form's current flat data. */
499
+ options?: Record<string, (data: Record<string, unknown>) => FieldOption[] | Promise<FieldOption[]>>;
500
+ /** File uploaders for `uploader` — take the picked File, return its ref. */
501
+ uploaders?: Record<string, (file: File) => Promise<UploadedFile>>;
502
+ /** `markdown` fields: which image URLs may embed. Unset: same origin. Others render as links. */
503
+ markdownImage?: (href: string) => boolean;
504
+ /** Client scripts for `scripts[].handler` (spec 01 §14). */
505
+ scripts?: Record<string, ScriptHandler>;
506
+ /** Record lookups for `reference` fields, by `field.reference` name. */
507
+ references?: Record<string, ReferenceLookup>;
508
+ }
509
+ export interface DerivedFieldState {
510
+ visible: boolean;
511
+ enabled: boolean;
512
+ readonly: boolean;
513
+ required: boolean;
514
+ /** True while a setValue rule with lock (default) is active on this field. */
515
+ computed: boolean;
516
+ }
517
+ export type NestedData = Record<string, Record<string, unknown>>;
518
+ export interface Derived {
519
+ /** Nested {form_name: {key: value}} — possibly mutated by setValue/clears. */
520
+ data: NestedData;
521
+ /** Keyed "formName.key". */
522
+ fields: Record<string, DerivedFieldState>;
523
+ /** skipForm/hideForm result per form_name. */
524
+ forms: Record<string, {
525
+ visible: boolean;
526
+ }>;
527
+ /**
528
+ * 'schema' = authoring defect (unknown rule target) — belongs at store
529
+ * time, not on a submission; 'data' = depends on the submitted values
530
+ * (non-convergence). Absent kind = 'schema' (pre-0.0.12 engines).
531
+ */
532
+ errors: {
533
+ ref: string;
534
+ message: string;
535
+ kind?: 'schema' | 'data';
536
+ }[];
537
+ }
538
+ export interface ValidationError {
539
+ key: string;
540
+ message: string;
541
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/urls.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * True for an absolute URL with one of `schemes` (lower-case, no colon): no whitespace or
3
+ * control characters anywhere, parseable by `URL`, and for host schemes (http, https, ftp,
4
+ * ws, wss) written as `scheme://host`. One anchored, linear regex for the scheme and the
5
+ * `URL` parser for the rest, so hostile input cannot backtrack.
6
+ */
7
+ export declare function isAllowedUrl(url: string, schemes: readonly string[]): boolean;
8
+ export declare function isSafeUrl(url: string): boolean;
package/dist/urls.js ADDED
@@ -0,0 +1,30 @@
1
+ const HOST_SCHEMES = new Set(['http', 'https', 'ftp', 'ws', 'wss']);
2
+ const SCHEME_RE = /^([a-z][a-z\d+.-]*):/i;
3
+ export function isAllowedUrl(url, schemes) {
4
+ for (let i = 0; i < url.length; i++) {
5
+ const c = url.charCodeAt(i);
6
+ if (c <= 0x20 || c === 0x7f || c === 0xa0 || c === 0x2028 || c === 0x2029)
7
+ return false;
8
+ }
9
+ const scheme = SCHEME_RE.exec(url)?.[1]?.toLowerCase();
10
+ if (scheme === undefined || !schemes.includes(scheme))
11
+ return false;
12
+ let parsed;
13
+ try {
14
+ parsed = new URL(url);
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ if (!HOST_SCHEMES.has(scheme))
20
+ return true;
21
+ return url.slice(scheme.length + 1, scheme.length + 3) === '//' && parsed.host !== '';
22
+ }
23
+ export function isSafeUrl(url) {
24
+ let start = 0;
25
+ while (start < url.length && url.charCodeAt(start) <= 0x20)
26
+ start++;
27
+ const normalized = url.slice(start).replace(/[\t\n\r]/g, '');
28
+ const scheme = /^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1];
29
+ return scheme === undefined || /^https?$/i.test(scheme);
30
+ }
@@ -0,0 +1,39 @@
1
+ import type { DerivedFieldState, FieldDescriptor, FieldOption, Registry, UploadedFile, ValidationError } from './types.js';
2
+ /** Text with nothing visible in it: what `required` treats as empty. */
3
+ export declare function isBlank(text: string): boolean;
4
+ /** Star count of a rating field: `max` when it is a whole number 1–10, else 5. */
5
+ export declare function ratingMax(field: FieldDescriptor): number;
6
+ /** A range field's slider bounds: numeric `min`/`max`/`step` or 0 / 100 / 1. */
7
+ export declare function rangeBounds(field: FieldDescriptor): {
8
+ min: number;
9
+ max: number;
10
+ step: number;
11
+ };
12
+ /**
13
+ * Canonical tags value (spec 01 §4 — tags): trimmed, non-empty strings,
14
+ * de-duplicated case-insensitively (first spelling wins), in entry order.
15
+ * With `options`, a tag matching an option key case-insensitively takes the
16
+ * option's key spelling, so case-sensitive rules (`contains "urgent"`) match.
17
+ * Non-array input (or non-string entries) never reaches canonical data —
18
+ * they're dropped rather than thrown, same as a stray non-string slipping
19
+ * into a `multiselect` array would be filtered by option-key matching.
20
+ * Exported: @20baht/validator applies the identical normalisation to the
21
+ * canonical `data` it persists, so client and server agree byte-for-byte.
22
+ */
23
+ export declare function normalizeTagsValue(value: unknown, options?: readonly Pick<FieldOption, 'key'>[]): string[];
24
+ /** lower-cased option key -> the option's own key (first one wins). */
25
+ export declare function optionKeyLookup(options: readonly Pick<FieldOption, 'key'>[] | undefined): Map<string, string>;
26
+ /**
27
+ * `rowStates` (repeaters only) are the rule-derived states of the row sub-fields,
28
+ * keyed `key[i].sub` (spec 02 §2a): a hidden one is skipped, a `required`
29
+ * override replaces the descriptor's.
30
+ */
31
+ export declare function validateField(field: FieldDescriptor, value: unknown, registry?: Registry, data?: Record<string, unknown>, rowStates?: Record<string, DerivedFieldState>): ValidationError[];
32
+ /** A time of day, 24-hour, minutes and no seconds: `00:00` … `23:59`. */
33
+ export declare const isTimeOfDay: (value: unknown) => value is string;
34
+ /**
35
+ * The serializable ref an uploader returns (spec 01 §13): a name, a finite non-negative size, a
36
+ * link-safe url and an optional type. The one check core's `file` validation and the
37
+ * server-side validator share.
38
+ */
39
+ export declare function isUploadedFile(v: unknown): v is UploadedFile;