@schema-engine/forms 0.5.1 → 0.5.3
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 +6 -5
- package/dist/agent-tool/index.js +13 -6
- package/dist/agent-tool/index.js.map +2 -2
- package/dist/builder/types.utils.d.ts +1 -0
- package/dist/chunk-2MKT7OIS.js +40 -0
- package/dist/chunk-2MKT7OIS.js.map +7 -0
- package/dist/{chunk-HPPFSWIV.js → chunk-2U4WRMPB.js} +26 -22
- package/dist/chunk-2U4WRMPB.js.map +7 -0
- package/dist/{chunk-YUUDXRBW.js → chunk-3ABPK4QP.js} +62 -2
- package/dist/chunk-3ABPK4QP.js.map +7 -0
- package/dist/chunk-3BMTC224.js +21 -0
- package/dist/chunk-3BMTC224.js.map +7 -0
- package/dist/chunk-3GZKJSXI.js +49 -0
- package/dist/chunk-3GZKJSXI.js.map +7 -0
- package/dist/{chunk-NJXKMF67.js → chunk-4HSGF4WX.js} +33 -52
- package/dist/chunk-4HSGF4WX.js.map +7 -0
- package/dist/chunk-4SWCTY7K.js +8 -0
- package/dist/chunk-4SWCTY7K.js.map +7 -0
- package/dist/{chunk-KLATKWUA.js → chunk-4YANBG3M.js} +1 -1
- package/dist/chunk-53SXH32V.js +43 -0
- package/dist/chunk-53SXH32V.js.map +7 -0
- package/dist/{chunk-DP7SYLLI.js → chunk-6OJ46PR2.js} +15 -20
- package/dist/chunk-6OJ46PR2.js.map +7 -0
- package/dist/chunk-AAOFZ27F.js +39 -0
- package/dist/chunk-AAOFZ27F.js.map +7 -0
- package/dist/{chunk-NJTLBSTR.js → chunk-AROD3D4R.js} +1 -1
- package/dist/{chunk-Q5LEK7CI.js → chunk-AT2NHSY3.js} +1 -1
- package/dist/chunk-B2PMISHZ.js +43 -0
- package/dist/chunk-B2PMISHZ.js.map +7 -0
- package/dist/chunk-BHCSZ4VO.js +27 -0
- package/dist/chunk-BHCSZ4VO.js.map +7 -0
- package/dist/chunk-BXGE5IXF.js +38 -0
- package/dist/chunk-BXGE5IXF.js.map +7 -0
- package/dist/chunk-CW7UMF3K.js +48 -0
- package/dist/chunk-CW7UMF3K.js.map +7 -0
- package/dist/{chunk-BLFLCSG3.js → chunk-DEWI6E3O.js} +2 -2
- package/dist/chunk-DSPTVDHL.js +45 -0
- package/dist/chunk-DSPTVDHL.js.map +7 -0
- package/dist/chunk-DU26WGQA.js +27 -0
- package/dist/chunk-DU26WGQA.js.map +7 -0
- package/dist/{chunk-GH34XFCC.js → chunk-EO5CW7XD.js} +2 -2
- package/dist/{chunk-A5VLMQAK.js → chunk-ERSCXYVE.js} +2 -2
- package/dist/chunk-EWNYEO6T.js.map +7 -0
- package/dist/{chunk-CRVXBWSY.js → chunk-FGL773EA.js} +1 -1
- package/dist/chunk-FVW5Z2CC.js +36 -0
- package/dist/chunk-FVW5Z2CC.js.map +7 -0
- package/dist/chunk-GDUF2SWI.js +32 -0
- package/dist/chunk-GDUF2SWI.js.map +7 -0
- package/dist/{chunk-GQHMU3AR.js → chunk-HEWLTCU4.js} +4 -4
- package/dist/{chunk-6R2MBQPL.js → chunk-HKLDRUFN.js} +4 -1
- package/dist/{chunk-6R2MBQPL.js.map → chunk-HKLDRUFN.js.map} +2 -2
- package/dist/{chunk-J2FC5K4B.js → chunk-IHXXPIFD.js} +1 -2
- package/dist/chunk-IHXXPIFD.js.map +7 -0
- package/dist/{chunk-GRZU6F7Q.js → chunk-KANWAQNI.js} +33 -38
- package/dist/chunk-KANWAQNI.js.map +7 -0
- package/dist/chunk-KWQJFQII.js +52 -0
- package/dist/chunk-KWQJFQII.js.map +7 -0
- package/dist/{chunk-PH3LWLYN.js → chunk-MFZYG6DN.js} +3 -2
- package/dist/chunk-MFZYG6DN.js.map +7 -0
- package/dist/{chunk-WUTGZYP4.js → chunk-MG7VFU6V.js} +2 -2
- package/dist/chunk-OG3OLZ5R.js +184 -0
- package/dist/chunk-OG3OLZ5R.js.map +7 -0
- package/dist/{chunk-WLDCYUN6.js → chunk-OKJLJ3GI.js} +1 -1
- package/dist/chunk-QDU55RCZ.js.map +7 -0
- package/dist/chunk-QFQB5EBY.js +38 -0
- package/dist/chunk-QFQB5EBY.js.map +7 -0
- package/dist/{chunk-6IZYNHZ3.js → chunk-RDQFBY6S.js} +45 -31
- package/dist/chunk-RDQFBY6S.js.map +7 -0
- package/dist/chunk-RMX7C43O.js.map +7 -0
- package/dist/chunk-T5JAAPFB.js +40 -0
- package/dist/chunk-T5JAAPFB.js.map +7 -0
- package/dist/chunk-TDXFT6Q5.js +57 -0
- package/dist/chunk-TDXFT6Q5.js.map +7 -0
- package/dist/{chunk-JA5ET6MC.js → chunk-TWQU2IGF.js} +6 -6
- package/dist/chunk-V3GYAG33.js +12 -0
- package/dist/chunk-V3GYAG33.js.map +7 -0
- package/dist/{chunk-V5H7L5PJ.js → chunk-WHLID5BN.js} +59 -23
- package/dist/{chunk-V5H7L5PJ.js.map → chunk-WHLID5BN.js.map} +2 -2
- package/dist/chunk-XKINCUXT.js +51 -0
- package/dist/chunk-XKINCUXT.js.map +7 -0
- package/dist/chunk-XLEOTW6H.js +50 -0
- package/dist/chunk-XLEOTW6H.js.map +7 -0
- package/dist/chunk-YHSOS3IH.js +53 -0
- package/dist/chunk-YHSOS3IH.js.map +7 -0
- package/dist/chunk-YKXOBPSU.js +19 -0
- package/dist/chunk-YKXOBPSU.js.map +7 -0
- package/dist/{chunk-ZYP3MIH3.js → chunk-YW2KZUAM.js} +5 -3
- package/dist/chunk-YW2KZUAM.js.map +7 -0
- package/dist/{chunk-E4VONSLO.js.map → chunk-YZFL6JPZ.js.map} +2 -2
- package/dist/{chunk-6EYX257T.js → chunk-Z5KZDT7V.js} +1 -1
- package/dist/chunk-ZZ4KB6GE.js +47 -0
- package/dist/chunk-ZZ4KB6GE.js.map +7 -0
- package/dist/default-elements/array-elements.d.ts +793 -0
- package/dist/default-elements/array-elements.js +34 -0
- package/dist/default-elements/array-elements.js.map +7 -0
- package/dist/default-elements/checkbox-group.d.ts +812 -0
- package/dist/default-elements/checkbox-group.js +40 -0
- package/dist/default-elements/checkbox-group.js.map +7 -0
- package/dist/default-elements/checkbox.d.ts +788 -0
- package/dist/default-elements/checkbox.js +38 -0
- package/dist/default-elements/checkbox.js.map +7 -0
- package/dist/default-elements/combobox.d.ts +806 -0
- package/dist/default-elements/combobox.js +40 -0
- package/dist/default-elements/combobox.js.map +7 -0
- package/dist/default-elements/define-contract.d.ts +25 -0
- package/dist/default-elements/define-contract.js +8 -0
- package/dist/default-elements/define-contract.js.map +7 -0
- package/dist/default-elements/drop-zone.d.ts +789 -0
- package/dist/default-elements/drop-zone.js +40 -0
- package/dist/default-elements/drop-zone.js.map +7 -0
- package/dist/default-elements/fieldset.d.ts +783 -0
- package/dist/default-elements/fieldset.js +34 -0
- package/dist/default-elements/fieldset.js.map +7 -0
- package/dist/default-elements/index.d.ts +75 -0
- package/dist/default-elements/index.js +240 -0
- package/dist/default-elements/index.js.map +7 -0
- package/dist/default-elements/input-otp.d.ts +1298 -0
- package/dist/default-elements/input-otp.js +38 -0
- package/dist/default-elements/input-otp.js.map +7 -0
- package/dist/default-elements/input.d.ts +843 -0
- package/dist/default-elements/input.js +40 -0
- package/dist/default-elements/input.js.map +7 -0
- package/dist/default-elements/masked-input.d.ts +835 -0
- package/dist/default-elements/masked-input.js +40 -0
- package/dist/default-elements/masked-input.js.map +7 -0
- package/dist/default-elements/number.d.ts +821 -0
- package/dist/default-elements/number.js +38 -0
- package/dist/default-elements/number.js.map +7 -0
- package/dist/default-elements/phone-input.d.ts +785 -0
- package/dist/default-elements/phone-input.js +40 -0
- package/dist/default-elements/phone-input.js.map +7 -0
- package/dist/default-elements/radio.d.ts +812 -0
- package/dist/default-elements/radio.js +40 -0
- package/dist/default-elements/radio.js.map +7 -0
- package/dist/default-elements/select.d.ts +809 -0
- package/dist/default-elements/select.js +40 -0
- package/dist/default-elements/select.js.map +7 -0
- package/dist/default-elements/slider.d.ts +800 -0
- package/dist/default-elements/slider.js +38 -0
- package/dist/default-elements/slider.js.map +7 -0
- package/dist/default-elements/submission-alert.d.ts +804 -0
- package/dist/default-elements/submission-alert.js +36 -0
- package/dist/default-elements/submission-alert.js.map +7 -0
- package/dist/default-elements/submit-button.d.ts +771 -0
- package/dist/default-elements/submit-button.js +34 -0
- package/dist/default-elements/submit-button.js.map +7 -0
- package/dist/default-elements/switch.d.ts +794 -0
- package/dist/default-elements/switch.js +38 -0
- package/dist/default-elements/switch.js.map +7 -0
- package/dist/default-elements/textarea.d.ts +815 -0
- package/dist/default-elements/textarea.js +40 -0
- package/dist/default-elements/textarea.js.map +7 -0
- package/dist/engine/build-form-engine.js +22 -18
- package/dist/engine/create-form-engine.js +23 -19
- package/dist/engine/form-engine.js +22 -18
- package/dist/engine/index.js +25 -21
- package/dist/engine/schema-artifacts.js +6 -2
- package/dist/engine/step-machine.d.ts +10 -0
- package/dist/engine/step-machine.js +5 -5
- package/dist/engine/submission-schema.js +8 -6
- package/dist/engine/value-validation.js +4 -4
- package/dist/index.d.ts +4 -2
- package/dist/index.js +40 -31
- package/dist/index.js.map +3 -3
- package/dist/lib/export-schema.d.ts +128 -0
- package/dist/lib/export-schema.js +15 -0
- package/dist/lib/export-schema.js.map +7 -0
- package/dist/lib/exported-recipe-view.d.ts +17 -0
- package/dist/lib/exported-recipe-view.js +10 -0
- package/dist/lib/exported-recipe-view.js.map +7 -0
- package/dist/lib/field-scope.js +2 -2
- package/dist/lib/grid-track-items.d.ts +26 -0
- package/dist/lib/grid-track-items.js +10 -0
- package/dist/lib/grid-track-items.js.map +7 -0
- package/dist/lib/is-zod-type.d.ts +5 -0
- package/dist/lib/is-zod-type.js +6 -0
- package/dist/lib/is-zod-type.js.map +7 -0
- package/dist/lib/submission-shape.js +3 -3
- package/dist/lib/validate-form/grid-checks.d.ts +24 -0
- package/dist/lib/validate-form/grid-checks.js +6 -1
- package/dist/lib/validate-form/parse-elements.d.ts +9 -7
- package/dist/lib/validate-form/parse-elements.js +5 -6
- package/dist/lib/validate-form/parse-owner-actions.js +1 -1
- package/dist/lib/validate-form/parse-view.js +1 -1
- package/dist/lib/validate-form/step-checks.js +3 -3
- package/dist/lib/validate-form/validation-error.d.ts +1 -10
- package/dist/lib/validate-form/validation-error.js +3 -5
- package/dist/lib/validate-form.d.ts +1 -1
- package/dist/lib/validate-form.js +14 -15
- package/dist/lib/zod-json-schema.d.ts +0 -4
- package/dist/lib/zod-json-schema.js +7 -5
- package/dist/recipes/built-in-specs.js +2 -2
- package/dist/recipes/built-in.js +2 -2
- package/dist/recipes/define-form-recipe.d.ts +2 -2
- package/dist/recipes/define-form-recipe.js +1 -1
- package/dist/recipes/define-recipe-spec.d.ts +3 -2
- package/dist/recipes/define-recipe-spec.js +1 -1
- package/dist/recipes/index.js +8 -8
- package/dist/recipes/types.d.ts +2 -2
- package/dist/recipes/view-model.d.ts +2 -2
- package/dist/recipes/view-model.js +6 -6
- package/dist/runtime/create-form-runtime.js +14 -13
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +14 -13
- package/dist/runtime/types.d.ts +11 -0
- package/dist/runtime/types.js +1 -1
- package/dist/schemas/base-field.d.ts +14 -6
- package/dist/schemas/base-field.js +5 -5
- package/dist/schemas/form-config-shape.d.ts +33 -21
- package/dist/schemas/form-config-shape.js +5 -5
- package/dist/schemas/form-config.d.ts +55 -35
- package/dist/schemas/form-config.js +5 -5
- package/dist/schemas/index.js +5 -5
- package/dist/schemas/validation/dependencies.js +4 -4
- package/dist/schemas/validation/index.js +5 -5
- package/dist/schemas/validation/utils.js +3 -3
- package/dist/schemas/validation/validation-registry.d.ts +1 -1
- package/dist/schemas/validation/validation-registry.js +4 -4
- package/dist/state-container/create-form-state-container.js +8 -8
- package/dist/state-container/index.js +9 -9
- package/dist/state-container/selectors.js +5 -5
- package/dist/state-container/submission.js +6 -6
- package/dist/testing/form-state-container-conformance.js +7 -7
- package/dist/testing/index.js +7 -7
- package/dist/types/define-element.d.ts +2 -2
- package/dist/types/define-element.js +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/registration.d.ts +7 -0
- package/package.json +8 -4
- package/skill/SKILL.md +26 -25
- package/skill/reference/forms.md +7 -7
- package/dist/chunk-25PLQDKN.js +0 -45
- package/dist/chunk-25PLQDKN.js.map +0 -7
- package/dist/chunk-2XWISGGM.js.map +0 -7
- package/dist/chunk-6IZYNHZ3.js.map +0 -7
- package/dist/chunk-DP7SYLLI.js.map +0 -7
- package/dist/chunk-GRZU6F7Q.js.map +0 -7
- package/dist/chunk-HPPFSWIV.js.map +0 -7
- package/dist/chunk-J2FC5K4B.js.map +0 -7
- package/dist/chunk-K22S7IZR.js.map +0 -7
- package/dist/chunk-NJXKMF67.js.map +0 -7
- package/dist/chunk-PH3LWLYN.js.map +0 -7
- package/dist/chunk-PHNMDWSK.js.map +0 -7
- package/dist/chunk-PN5EH6DM.js +0 -36
- package/dist/chunk-PN5EH6DM.js.map +0 -7
- package/dist/chunk-YUUDXRBW.js.map +0 -7
- package/dist/chunk-ZYP3MIH3.js.map +0 -7
- package/dist/{chunk-KLATKWUA.js.map → chunk-4YANBG3M.js.map} +0 -0
- package/dist/{chunk-S7I76ISM.js → chunk-7QLR5WM3.js} +3 -3
- /package/dist/{chunk-S7I76ISM.js.map → chunk-7QLR5WM3.js.map} +0 -0
- /package/dist/{chunk-NJTLBSTR.js.map → chunk-AROD3D4R.js.map} +0 -0
- /package/dist/{chunk-Q5LEK7CI.js.map → chunk-AT2NHSY3.js.map} +0 -0
- /package/dist/{chunk-BLFLCSG3.js.map → chunk-DEWI6E3O.js.map} +0 -0
- /package/dist/{chunk-GH34XFCC.js.map → chunk-EO5CW7XD.js.map} +0 -0
- /package/dist/{chunk-A5VLMQAK.js.map → chunk-ERSCXYVE.js.map} +0 -0
- /package/dist/{chunk-K22S7IZR.js → chunk-EWNYEO6T.js} +0 -0
- /package/dist/{chunk-CRVXBWSY.js.map → chunk-FGL773EA.js.map} +0 -0
- /package/dist/{chunk-GQHMU3AR.js.map → chunk-HEWLTCU4.js.map} +0 -0
- /package/dist/{chunk-WUTGZYP4.js.map → chunk-MG7VFU6V.js.map} +0 -0
- /package/dist/{chunk-WLDCYUN6.js.map → chunk-OKJLJ3GI.js.map} +0 -0
- /package/dist/{chunk-2XWISGGM.js → chunk-QDU55RCZ.js} +0 -0
- /package/dist/{chunk-PHNMDWSK.js → chunk-RMX7C43O.js} +0 -0
- /package/dist/{chunk-JA5ET6MC.js.map → chunk-TWQU2IGF.js.map} +0 -0
- /package/dist/{chunk-E4VONSLO.js → chunk-YZFL6JPZ.js} +0 -0
- /package/dist/{chunk-6EYX257T.js.map → chunk-Z5KZDT7V.js.map} +0 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @schema-engine/forms
|
|
2
2
|
|
|
3
|
-
The forms domain of Schema Engine: elements, validation rules, constraints, steps, the form state and the submit lifecycle, with no renderer. A form is a JSON document that names registered elements by `$type`. [`@schema-engine/forms-react`](https://www.npmjs.com/package/@schema-engine/forms-react) and [`@schema-engine/forms-radiant`](https://www.npmjs.com/package/@schema-engine/forms-radiant) draw it.
|
|
3
|
+
The forms domain of Schema Engine: elements, validation rules, constraints, steps, the form state and the submit lifecycle, which run with no renderer. A form is a JSON document that names registered elements by `$type`. [`@schema-engine/forms-react`](https://www.npmjs.com/package/@schema-engine/forms-react) and [`@schema-engine/forms-radiant`](https://www.npmjs.com/package/@schema-engine/forms-radiant) draw it.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -8,7 +8,7 @@ The forms domain of Schema Engine: elements, validation rules, constraints, step
|
|
|
8
8
|
pnpm add @schema-engine/forms zod
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
First-party schemas use the `zod/mini` entry point. Registrations may use any [Standard Schema](https://standardschema.dev/) validator.
|
|
11
|
+
First-party schemas use the `zod/mini` entry point. Registrations may use any [Standard Schema](https://standardschema.dev/) validator, and so may the slot schemas of a recipe spec. The JSON Schema export reads each schema the same way for an element, an action, a rule and a recipe slot: a Zod schema through the Zod converter, any other schema that sets `~standard.jsonSchema` (ArkType, or a schema you write) as what it returns, and any other schema by its shape (a registration by its `$type`, a recipe slot as an open object with its appearance axes).
|
|
12
12
|
|
|
13
13
|
## Example
|
|
14
14
|
|
|
@@ -38,7 +38,7 @@ const result = engine.safeValidateForm({
|
|
|
38
38
|
});
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
`result` is `{ success: true, data }` with the frozen, normalized config, or `{ success: false, issues }` with the `path` of every key to fix.
|
|
41
|
+
`result` is `{ success: true, data }` with the frozen, normalized config, or `{ success: false, issues }` with the `path` of every key to fix. To draw the form, give the engine and the config to a renderer: `FormRenderer` of Forms React or Forms Radiant. A renderer creates a `createFormRuntime` for each form it draws, which owns the submission, the wizard steps and every action; only a renderer author calls it.
|
|
42
42
|
|
|
43
43
|
## Entry points
|
|
44
44
|
|
|
@@ -46,6 +46,7 @@ const result = engine.safeValidateForm({
|
|
|
46
46
|
| --------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
47
47
|
| `@schema-engine/forms` | The engine, `defineInput` and `defineStatic`, the runtime, the actions and the types |
|
|
48
48
|
| `@schema-engine/forms/state-container` | The form state container, its selectors and the issue formatter type |
|
|
49
|
+
| `@schema-engine/forms/default-elements` | The contract of each default element, for a renderer to bind its `render` to |
|
|
49
50
|
| `@schema-engine/forms/csrf` | CSRF policies for the engine's requests and native posts |
|
|
50
51
|
| `@schema-engine/forms/server-errors` | `fromProblemDetails` and `fromJsonApiErrors`, to show a server's answer on its fields |
|
|
51
52
|
| `@schema-engine/forms/recipes` | The forms recipe protocol, to write a view recipe |
|
|
@@ -57,10 +58,10 @@ const result = engine.safeValidateForm({
|
|
|
57
58
|
## Documentation
|
|
58
59
|
|
|
59
60
|
- [Forms](https://schema-engine.com/docs/forms/overview): what a form can do.
|
|
60
|
-
- [Installation and quick start](https://schema-engine.com/docs/forms/getting-started):
|
|
61
|
+
- [Installation and quick start](https://schema-engine.com/docs/forms/getting-started): create the engine, check JSON and render it.
|
|
61
62
|
- [Engine and registrations](https://schema-engine.com/docs/forms/engine): the engine, custom fields and configuration errors.
|
|
62
63
|
- [Validation](https://schema-engine.com/docs/forms/validation) and [custom and async rules](https://schema-engine.com/docs/forms/validation-custom).
|
|
63
|
-
- [Form state](https://schema-engine.com/docs/forms/form-state), [Wizard
|
|
64
|
+
- [Form state](https://schema-engine.com/docs/forms/form-state), [Wizard](https://schema-engine.com/docs/forms/wizard) and [Actions in forms](https://schema-engine.com/docs/forms/actions).
|
|
64
65
|
- [Issue text](https://schema-engine.com/docs/forms/issue-text), [Server errors](https://schema-engine.com/docs/forms/server-errors) and [CSRF](https://schema-engine.com/docs/forms/csrf).
|
|
65
66
|
- [Agent tools](https://schema-engine.com/docs/forms/agent-tool) and [API reference](https://schema-engine.com/docs/forms/api-reference).
|
|
66
67
|
- [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
|
package/dist/agent-tool/index.js
CHANGED
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
import {
|
|
2
2
|
issueText
|
|
3
3
|
} from "../chunk-HIS4MGIR.js";
|
|
4
|
+
import {
|
|
5
|
+
issuePath
|
|
6
|
+
} from "../chunk-2U4WRMPB.js";
|
|
7
|
+
import "../chunk-OG3OLZ5R.js";
|
|
8
|
+
import "../chunk-4SWCTY7K.js";
|
|
4
9
|
import {
|
|
5
10
|
buildSubmissionShape
|
|
6
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-AROD3D4R.js";
|
|
7
12
|
import {
|
|
8
13
|
logger
|
|
9
14
|
} from "../chunk-VGGERKV2.js";
|
|
10
|
-
import "../chunk-
|
|
11
|
-
import "../chunk-
|
|
15
|
+
import "../chunk-3B7CJOF6.js";
|
|
16
|
+
import "../chunk-4YANBG3M.js";
|
|
17
|
+
import "../chunk-YDGH7DTL.js";
|
|
18
|
+
import "../chunk-7QLR5WM3.js";
|
|
12
19
|
import "../chunk-QLGM2AZW.js";
|
|
20
|
+
import "../chunk-CRQWKC67.js";
|
|
13
21
|
import "../chunk-ZUYSGCEH.js";
|
|
22
|
+
import "../chunk-OR2L7EKO.js";
|
|
14
23
|
import {
|
|
15
24
|
FORM_ROOT
|
|
16
25
|
} from "../chunk-PCL2KNHC.js";
|
|
@@ -85,9 +94,7 @@ function registerFormAgentTool(runtime, options) {
|
|
|
85
94
|
if (signal.aborted) return text("The call was cancelled before the form was changed.");
|
|
86
95
|
const checked = submission.partial["~standard"].validate(input);
|
|
87
96
|
if (checked.issues) {
|
|
88
|
-
const lines = checked.issues.map(
|
|
89
|
-
(issue) => `- ${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || "input"}: ${issue.message}`
|
|
90
|
-
);
|
|
97
|
+
const lines = checked.issues.map((issue) => `- ${issuePath(issue) || "input"}: ${issue.message}`);
|
|
91
98
|
return text(`The input does not match the form, so nothing was filled in:
|
|
92
99
|
${lines.join("\n")}`);
|
|
93
100
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/agent-tool/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { logger } from '@/lib/logger';\nimport { isPlainObject } from '@/lib/is-plain-object';\nimport { buildSubmissionShape, type SubmissionShape } from '@/lib/submission-shape';\nimport type { JSONSchemaObject } from '@/lib/standard-json-schema';\nimport type { FormRuntime, SubmitOutcome } from '@/runtime';\nimport { issueText } from '@/state-container/issue-text';\nimport { FORM_ROOT } from '@/state-container/types';\nimport type { FormStateIssue, FormSubmissionIssue } from '@/state-container/types';\n\n/** What the page hands `execute` besides the input. */\ninterface AgentToolExecuteOptions {\n\t/** Aborted when the agent cancels the call. */\n\treadonly signal: AbortSignal;\n}\n\n/** The MCP shape of a tool result: what the agent reads. */\nexport interface FormAgentToolResult {\n\treadonly content: readonly [{ readonly type: 'text'; readonly text: string }];\n}\n\ninterface ModelContext {\n\tregisterTool(\n\t\ttool: {\n\t\t\tname: string;\n\t\t\tdescription: string;\n\t\t\tinputSchema: JSONSchemaObject;\n\t\t\texecute(input: unknown, options: AgentToolExecuteOptions): Promise<FormAgentToolResult>;\n\t\t},\n\t\toptions: { signal: AbortSignal },\n\t): unknown;\n}\n\n/** The text of an issue for the form at `field.path`; `undefined` or an empty text says nothing worth showing. */\nexport type FormAgentIssueFormatter = (\n\tissue: FormStateIssue | FormSubmissionIssue,\n\tfield: { readonly path: string },\n) => string | undefined;\n\n/** What {@link registerFormAgentTool} registers a form with. */\nexport interface FormAgentToolOptions {\n\t/** Unique among the page's tools; the browser rejects a duplicate. */\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Submits the form after filling it, for a form that only reads or changes something low risk and reversible.\n\t *\n\t * @remarks Without it the tool fills the form and reports that it waits for the user to submit, so a person confirms. Default: `false`.\n\t */\n\tautoSubmit?: boolean;\n\t/**\n\t * The form's own issue formatter, such as the one `useFormContext()` or `FormController` gives.\n\t *\n\t * @remarks Default: the engine's. An issue with no text from either is reported by its own `message`, then its `type` and its `params`.\n\t */\n\tformatIssue?: FormAgentIssueFormatter;\n}\n\nconst text = (value: string): FormAgentToolResult => ({ content: [{ type: 'text', text: value }] });\n\ninterface Write {\n\treadonly path: string;\n\treadonly kind: 'value' | 'rows';\n\treadonly value: unknown;\n}\n\n/** The writes that put `value` into the container: a leaf field takes its whole value, a list its whole rows. */\nfunction collectWrites(shape: SubmissionShape, value: unknown, path: string, writes: Write[]): void {\n\tif (shape.kind === 'object') {\n\t\tif (!isPlainObject(value)) return;\n\t\tfor (const [key, child] of Object.entries(shape.fields)) {\n\t\t\tif (Object.hasOwn(value, key) && value[key] !== undefined) {\n\t\t\t\tcollectWrites(child, value[key], path === '' ? key : `${path}.${key}`, writes);\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\twrites.push({ path, kind: shape.kind === 'array' ? 'rows' : 'value', value });\n}\n\n/** Puts `value` at the path: a list writes its rows, and a value that is no list, as `undefined` for a list the form never had, is written as it is. */\nfunction writeTo(container: FormRuntime['container'], { path, kind, value }: Write): void {\n\tif (kind === 'rows' && Array.isArray(value)) container.fieldArray(path).replace([...value]);\n\telse container.setValue(path, value);\n}\n\n/** The text of one issue: what {@link issueText} gives, else the issue's type and params, which an agent can still act on. */\nfunction agentIssueText(\n\tissue: FormStateIssue | FormSubmissionIssue,\n\tpath: string,\n\tformatIssue: FormAgentIssueFormatter | undefined,\n): string {\n\tconst text = issueText(issue, path, formatIssue);\n\tif (text) return text;\n\treturn issue.params && Object.keys(issue.params).length > 0\n\t\t? `${issue.type} ${JSON.stringify(issue.params)}`\n\t\t: issue.type;\n}\n\nfunction describeErrors(runtime: FormRuntime, formatIssue: FormAgentIssueFormatter | undefined): string[] {\n\tconst lines = Object.entries(runtime.container.getSnapshot().errors).map(([path, error]) => {\n\t\tconst reasons = [...new Set(error.all.map((issue) => agentIssueText(issue, path, formatIssue)))];\n\t\treturn `- ${path === FORM_ROOT ? 'form' : path}: ${reasons.join('; ')}`;\n\t});\n\tfor (const failure of runtime.getSnapshot().submission.failures) {\n\t\tlines.push(`- form: ${agentIssueText(failure, FORM_ROOT, formatIssue)}`);\n\t}\n\treturn lines;\n}\n\nfunction reportOutcome(\n\toutcome: SubmitOutcome,\n\truntime: FormRuntime,\n\tformatIssue: FormAgentIssueFormatter | undefined,\n): string {\n\tswitch (outcome) {\n\t\tcase 'submitted':\n\t\t\treturn 'The form was submitted.';\n\t\tcase 'invalid':\n\t\tcase 'failed': {\n\t\t\tconst lines = describeErrors(runtime, formatIssue);\n\t\t\treturn `The form was not submitted. Fix these and call the tool again:\\n${lines.join('\\n')}`;\n\t\t}\n\t\tcase 'overtaken':\n\t\t\treturn 'The form changed while it was checked, so it was not submitted. Call the tool again.';\n\t\tcase 'busy':\n\t\t\treturn 'The form is busy with another submission. Call the tool again in a moment.';\n\t\tdefault:\n\t\t\treturn `The form could not be submitted (${outcome}). The values were filled in.`;\n\t}\n}\n\n/**\n * Registers a rendered form as a WebMCP tool, so a browser agent can fill it and, when the page allows, submit it.\n *\n * @param runtime - The form's runtime, which the renderer binding hands over (`useFormRuntime()` in React, `FormController` in Radiant).\n * @returns The function that unregisters the tool, by aborting the signal it registered with. Calling it again does nothing.\n * @experimental\n *\n * @remarks\n * WebMCP is an Origin Trial and its API may change. Nothing else in the package imports this entry.\n * It does nothing on the server and where the browser has no `document.modelContext`.\n *\n * The input schema is the JSON Schema of the runtime's `submissionSchema`, which describes each field by its label and\n * help text, and it throws when a value schema has no JSON Schema. `execute` first checks the input\n * against the same schema without requiring any key, so a value of the wrong type is refused before it reaches the form. It then writes the values into\n * the form's container, the way a person's edits arrive, and, when `autoSubmit` is set, runs `runtime.submit()`: the same\n * validation, constraints, value check, actions and `onSubmit` as a human submit. In a wizard it submits again after each\n * step it moves past, so the answers fill the steps they make active and a skipped step's values are not submitted.\n * A refused submission returns its issues as text, worded by the form's formatter, so the agent can retry.\n *\n * A call whose signal is aborted before it writes changes nothing. One aborted while it submits puts back the values and the\n * step the user had, unless the form was already submitted; errors the submission recorded stay.\n */\nexport function registerFormAgentTool(runtime: FormRuntime, options: FormAgentToolOptions): () => void {\n\tif (typeof document === 'undefined') return () => {};\n\tconst modelContext = (document as Document & { modelContext?: ModelContext }).modelContext;\n\tif (!modelContext) return () => {};\n\n\tconst { name, description, autoSubmit = false } = options;\n\tconst formatIssue = options.formatIssue ?? runtime.formatIssue;\n\tconst submission = runtime.submissionSchema;\n\tconst shape = buildSubmissionShape(runtime.config.steps);\n\tconst inputSchema = { ...submission['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) };\n\n\tconst execute = async (input: unknown, { signal }: AgentToolExecuteOptions): Promise<FormAgentToolResult> => {\n\t\tif (signal.aborted) return text('The call was cancelled before the form was changed.');\n\n\t\tconst checked = submission.partial['~standard'].validate(input);\n\t\tif (checked.issues) {\n\t\t\tconst lines = checked.issues.map(
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { issuePath } from '@/engine/submission-schema';\nimport { logger } from '@/lib/logger';\nimport { isPlainObject } from '@/lib/is-plain-object';\nimport { buildSubmissionShape, type SubmissionShape } from '@/lib/submission-shape';\nimport type { JSONSchemaObject } from '@/lib/standard-json-schema';\nimport type { FormRuntime, SubmitOutcome } from '@/runtime';\nimport { issueText } from '@/state-container/issue-text';\nimport { FORM_ROOT } from '@/state-container/types';\nimport type { FormStateIssue, FormSubmissionIssue } from '@/state-container/types';\n\n/** What the page hands `execute` besides the input. */\ninterface AgentToolExecuteOptions {\n\t/** Aborted when the agent cancels the call. */\n\treadonly signal: AbortSignal;\n}\n\n/** The MCP shape of a tool result: what the agent reads. */\nexport interface FormAgentToolResult {\n\treadonly content: readonly [{ readonly type: 'text'; readonly text: string }];\n}\n\ninterface ModelContext {\n\tregisterTool(\n\t\ttool: {\n\t\t\tname: string;\n\t\t\tdescription: string;\n\t\t\tinputSchema: JSONSchemaObject;\n\t\t\texecute(input: unknown, options: AgentToolExecuteOptions): Promise<FormAgentToolResult>;\n\t\t},\n\t\toptions: { signal: AbortSignal },\n\t): unknown;\n}\n\n/** The text of an issue for the form at `field.path`; `undefined` or an empty text says nothing worth showing. */\nexport type FormAgentIssueFormatter = (\n\tissue: FormStateIssue | FormSubmissionIssue,\n\tfield: { readonly path: string },\n) => string | undefined;\n\n/** What {@link registerFormAgentTool} registers a form with. */\nexport interface FormAgentToolOptions {\n\t/** Unique among the page's tools; the browser rejects a duplicate. */\n\tname: string;\n\tdescription: string;\n\t/**\n\t * Submits the form after filling it, for a form that only reads or changes something low risk and reversible.\n\t *\n\t * @remarks Without it the tool fills the form and reports that it waits for the user to submit, so a person confirms. Default: `false`.\n\t */\n\tautoSubmit?: boolean;\n\t/**\n\t * The form's own issue formatter, such as the one `useFormContext()` or `FormController` gives.\n\t *\n\t * @remarks Default: the engine's. An issue with no text from either is reported by its own `message`, then its `type` and its `params`.\n\t */\n\tformatIssue?: FormAgentIssueFormatter;\n}\n\nconst text = (value: string): FormAgentToolResult => ({ content: [{ type: 'text', text: value }] });\n\ninterface Write {\n\treadonly path: string;\n\treadonly kind: 'value' | 'rows';\n\treadonly value: unknown;\n}\n\n/** The writes that put `value` into the container: a leaf field takes its whole value, a list its whole rows. */\nfunction collectWrites(shape: SubmissionShape, value: unknown, path: string, writes: Write[]): void {\n\tif (shape.kind === 'object') {\n\t\tif (!isPlainObject(value)) return;\n\t\tfor (const [key, child] of Object.entries(shape.fields)) {\n\t\t\tif (Object.hasOwn(value, key) && value[key] !== undefined) {\n\t\t\t\tcollectWrites(child, value[key], path === '' ? key : `${path}.${key}`, writes);\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\twrites.push({ path, kind: shape.kind === 'array' ? 'rows' : 'value', value });\n}\n\n/** Puts `value` at the path: a list writes its rows, and a value that is no list, as `undefined` for a list the form never had, is written as it is. */\nfunction writeTo(container: FormRuntime['container'], { path, kind, value }: Write): void {\n\tif (kind === 'rows' && Array.isArray(value)) container.fieldArray(path).replace([...value]);\n\telse container.setValue(path, value);\n}\n\n/** The text of one issue: what {@link issueText} gives, else the issue's type and params, which an agent can still act on. */\nfunction agentIssueText(\n\tissue: FormStateIssue | FormSubmissionIssue,\n\tpath: string,\n\tformatIssue: FormAgentIssueFormatter | undefined,\n): string {\n\tconst text = issueText(issue, path, formatIssue);\n\tif (text) return text;\n\treturn issue.params && Object.keys(issue.params).length > 0\n\t\t? `${issue.type} ${JSON.stringify(issue.params)}`\n\t\t: issue.type;\n}\n\nfunction describeErrors(runtime: FormRuntime, formatIssue: FormAgentIssueFormatter | undefined): string[] {\n\tconst lines = Object.entries(runtime.container.getSnapshot().errors).map(([path, error]) => {\n\t\tconst reasons = [...new Set(error.all.map((issue) => agentIssueText(issue, path, formatIssue)))];\n\t\treturn `- ${path === FORM_ROOT ? 'form' : path}: ${reasons.join('; ')}`;\n\t});\n\tfor (const failure of runtime.getSnapshot().submission.failures) {\n\t\tlines.push(`- form: ${agentIssueText(failure, FORM_ROOT, formatIssue)}`);\n\t}\n\treturn lines;\n}\n\nfunction reportOutcome(\n\toutcome: SubmitOutcome,\n\truntime: FormRuntime,\n\tformatIssue: FormAgentIssueFormatter | undefined,\n): string {\n\tswitch (outcome) {\n\t\tcase 'submitted':\n\t\t\treturn 'The form was submitted.';\n\t\tcase 'invalid':\n\t\tcase 'failed': {\n\t\t\tconst lines = describeErrors(runtime, formatIssue);\n\t\t\treturn `The form was not submitted. Fix these and call the tool again:\\n${lines.join('\\n')}`;\n\t\t}\n\t\tcase 'overtaken':\n\t\t\treturn 'The form changed while it was checked, so it was not submitted. Call the tool again.';\n\t\tcase 'busy':\n\t\t\treturn 'The form is busy with another submission. Call the tool again in a moment.';\n\t\tdefault:\n\t\t\treturn `The form could not be submitted (${outcome}). The values were filled in.`;\n\t}\n}\n\n/**\n * Registers a rendered form as a WebMCP tool, so a browser agent can fill it and, when the page allows, submit it.\n *\n * @param runtime - The form's runtime, which the renderer binding hands over (`useFormRuntime()` in React, `FormController` in Radiant).\n * @returns The function that unregisters the tool, by aborting the signal it registered with. Calling it again does nothing.\n * @experimental\n *\n * @remarks\n * WebMCP is an Origin Trial and its API may change. Nothing else in the package imports this entry.\n * It does nothing on the server and where the browser has no `document.modelContext`.\n *\n * The input schema is the JSON Schema of the runtime's `submissionSchema`, which describes each field by its label and\n * help text, and it throws when a value schema has no JSON Schema. `execute` first checks the input\n * against the same schema without requiring any key, so a value of the wrong type is refused before it reaches the form. It then writes the values into\n * the form's container, the way a person's edits arrive, and, when `autoSubmit` is set, runs `runtime.submit()`: the same\n * validation, constraints, value check, actions and `onSubmit` as a human submit. In a wizard it submits again after each\n * step it moves past, so the answers fill the steps they make active and a skipped step's values are not submitted.\n * A refused submission returns its issues as text, worded by the form's formatter, so the agent can retry.\n *\n * A call whose signal is aborted before it writes changes nothing. One aborted while it submits puts back the values and the\n * step the user had, unless the form was already submitted; errors the submission recorded stay.\n */\nexport function registerFormAgentTool(runtime: FormRuntime, options: FormAgentToolOptions): () => void {\n\tif (typeof document === 'undefined') return () => {};\n\tconst modelContext = (document as Document & { modelContext?: ModelContext }).modelContext;\n\tif (!modelContext) return () => {};\n\n\tconst { name, description, autoSubmit = false } = options;\n\tconst formatIssue = options.formatIssue ?? runtime.formatIssue;\n\tconst submission = runtime.submissionSchema;\n\tconst shape = buildSubmissionShape(runtime.config.steps);\n\tconst inputSchema = { ...submission['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) };\n\n\tconst execute = async (input: unknown, { signal }: AgentToolExecuteOptions): Promise<FormAgentToolResult> => {\n\t\tif (signal.aborted) return text('The call was cancelled before the form was changed.');\n\n\t\tconst checked = submission.partial['~standard'].validate(input);\n\t\tif (checked.issues) {\n\t\t\tconst lines = checked.issues.map((issue) => `- ${issuePath(issue) || 'input'}: ${issue.message}`);\n\t\t\treturn text(`The input does not match the form, so nothing was filled in:\\n${lines.join('\\n')}`);\n\t\t}\n\n\t\tconst { container } = runtime;\n\t\tconst startStep = runtime.getSnapshot().current;\n\t\tconst writes: Write[] = [];\n\t\tcollectWrites(shape, checked.value, '', writes);\n\t\tconst before = writes.map((write) => ({ ...write, value: container.getValue(write.path) }));\n\t\tfor (const write of writes) writeTo(container, write);\n\n\t\tif (!autoSubmit) {\n\t\t\treturn text('The form is filled in and waits for the user to review and submit it.');\n\t\t}\n\n\t\tlet outcome: SubmitOutcome = 'refused';\n\t\tfor (let step = 0; step <= runtime.getSnapshot().steps.length; step += 1) {\n\t\t\toutcome = await runtime.submit();\n\t\t\tif (outcome !== 'moved') break;\n\t\t\tif (signal.aborted) break;\n\t\t}\n\t\tif (signal.aborted && outcome !== 'submitted') {\n\t\t\tfor (const write of before.toReversed()) writeTo(container, write);\n\t\t\tawait runtime.goTo(startStep);\n\t\t\treturn text('The call was cancelled, so the form was put back as the user had it.');\n\t\t}\n\t\treturn text(reportOutcome(outcome, runtime, formatIssue));\n\t};\n\n\tconst controller = new AbortController();\n\tvoid (async () => {\n\t\ttry {\n\t\t\tawait modelContext.registerTool({ name, description, inputSchema, execute }, { signal: controller.signal });\n\t\t} catch (error) {\n\t\t\tif (!controller.signal.aborted) logger.error(`Could not register the agent tool \"${name}\".`, { error });\n\t\t}\n\t})();\n\treturn () => controller.abort();\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAM,OAAO,CAAC,WAAwC,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,MAAM,CAAC,EAAE;AASjG,SAAS,cAAc,OAAwB,OAAgB,MAAc,QAAuB;AACnG,MAAI,MAAM,SAAS,UAAU;AAC5B,QAAI,CAAC,cAAc,KAAK,EAAG;AAC3B,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,MAAM,GAAG;AACxD,UAAI,OAAO,OAAO,OAAO,GAAG,KAAK,MAAM,GAAG,MAAM,QAAW;AAC1D,sBAAc,OAAO,MAAM,GAAG,GAAG,SAAS,KAAK,MAAM,GAAG,IAAI,IAAI,GAAG,IAAI,MAAM;AAAA,MAC9E;AAAA,IACD;AACA;AAAA,EACD;AACA,SAAO,KAAK,EAAE,MAAM,MAAM,MAAM,SAAS,UAAU,SAAS,SAAS,MAAM,CAAC;AAC7E;AAGA,SAAS,QAAQ,WAAqC,EAAE,MAAM,MAAM,MAAM,GAAgB;AACzF,MAAI,SAAS,UAAU,MAAM,QAAQ,KAAK,EAAG,WAAU,WAAW,IAAI,EAAE,QAAQ,CAAC,GAAG,KAAK,CAAC;AAAA,MACrF,WAAU,SAAS,MAAM,KAAK;AACpC;AAGA,SAAS,eACR,OACA,MACA,aACS;AACT,QAAMA,QAAO,UAAU,OAAO,MAAM,WAAW;AAC/C,MAAIA,MAAM,QAAOA;AACjB,SAAO,MAAM,UAAU,OAAO,KAAK,MAAM,MAAM,EAAE,SAAS,IACvD,GAAG,MAAM,IAAI,IAAI,KAAK,UAAU,MAAM,MAAM,CAAC,KAC7C,MAAM;AACV;AAEA,SAAS,eAAe,SAAsB,aAA4D;AACzG,QAAM,QAAQ,OAAO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,SAAS,OAAO;AACf,UAAI,CAAC,WAAW,OAAO,QAAS,QAAO,MAAM,sCAAsC,IAAI,MAAM,EAAE,MAAM,CAAC;AAAA,IACvG;AAAA,EACD,GAAG;AACH,SAAO,MAAM,WAAW,MAAM;AAC/B;",
|
|
6
6
|
"names": ["text"]
|
|
7
7
|
}
|
|
@@ -110,6 +110,7 @@ export type RecipeRegistrationConstraint = {
|
|
|
110
110
|
readonly kind: 'single-step' | 'wizard';
|
|
111
111
|
readonly slots: readonly string[];
|
|
112
112
|
readonly appearanceAxes?: SlotAppearanceAxes;
|
|
113
|
+
readonly slotSchemas?: Readonly<Partial<Record<string, StandardSchemaConstraint>>>;
|
|
113
114
|
readonly metadata: {
|
|
114
115
|
readonly name: string;
|
|
115
116
|
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defineStaticContract
|
|
3
|
+
} from "./chunk-V3GYAG33.js";
|
|
4
|
+
import {
|
|
5
|
+
BaseFieldSchema
|
|
6
|
+
} from "./chunk-237BHPDH.js";
|
|
7
|
+
|
|
8
|
+
// src/default-elements/submission-alert.ts
|
|
9
|
+
import * as z from "zod/mini";
|
|
10
|
+
var SubmissionAlertExtensionSchema = z.object({
|
|
11
|
+
/** Which submission states to show the alert for */
|
|
12
|
+
showOn: z.optional(z.array(z.enum(["idle", "submitting", "success", "error"]))),
|
|
13
|
+
/** Auto-dismiss after ms (0 = never) */
|
|
14
|
+
autoDismiss: z.optional(z.number()),
|
|
15
|
+
/** Custom success message */
|
|
16
|
+
successMessage: z.optional(z.string()),
|
|
17
|
+
/** Custom error message */
|
|
18
|
+
errorMessage: z.optional(z.string()),
|
|
19
|
+
/** Custom message while submitting */
|
|
20
|
+
submittingMessage: z.optional(z.string())
|
|
21
|
+
});
|
|
22
|
+
var SubmissionAlertConfigSchema = z.extend(BaseFieldSchema, {
|
|
23
|
+
$type: z.literal("submission-alert"),
|
|
24
|
+
...SubmissionAlertExtensionSchema.shape
|
|
25
|
+
});
|
|
26
|
+
var SubmissionAlertElementContract = defineStaticContract({
|
|
27
|
+
$type: "submission-alert",
|
|
28
|
+
schema: SubmissionAlertConfigSchema,
|
|
29
|
+
metadata: {
|
|
30
|
+
name: "Submission Alert",
|
|
31
|
+
description: "Displays form submission status (submitting, success, error)",
|
|
32
|
+
category: "content"
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export {
|
|
37
|
+
SubmissionAlertExtensionSchema,
|
|
38
|
+
SubmissionAlertConfigSchema,
|
|
39
|
+
SubmissionAlertElementContract
|
|
40
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/default-elements/submission-alert.ts"],
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod/mini';\nimport { BaseFieldSchema } from '@/schemas/base-field';\nimport { defineStaticContract } from './define-contract';\n\nexport const SubmissionAlertExtensionSchema = z.object({\n\t/** Which submission states to show the alert for */\n\tshowOn: z.optional(z.array(z.enum(['idle', 'submitting', 'success', 'error']))),\n\t/** Auto-dismiss after ms (0 = never) */\n\tautoDismiss: z.optional(z.number()),\n\t/** Custom success message */\n\tsuccessMessage: z.optional(z.string()),\n\t/** Custom error message */\n\terrorMessage: z.optional(z.string()),\n\t/** Custom message while submitting */\n\tsubmittingMessage: z.optional(z.string()),\n});\n\nexport const SubmissionAlertConfigSchema = z.extend(BaseFieldSchema, {\n\t$type: z.literal('submission-alert'),\n\t...SubmissionAlertExtensionSchema.shape,\n});\n\nexport type SubmissionAlertExtension = z.infer<typeof SubmissionAlertExtensionSchema>;\nexport type SubmissionAlertConfig = z.infer<typeof SubmissionAlertConfigSchema>;\n\n/** The contract of the `submission-alert` element: what every renderer of it agrees on. */\nexport const SubmissionAlertElementContract = defineStaticContract({\n\t$type: 'submission-alert',\n\tschema: SubmissionAlertConfigSchema,\n\tmetadata: {\n\t\tname: 'Submission Alert',\n\t\tdescription: 'Displays form submission status (submitting, success, error)',\n\t\tcategory: 'content',\n\t},\n});\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAAA,YAAY,OAAO;AAIZ,IAAM,iCAAmC,SAAO;AAAA;AAAA,EAEtD,QAAU,WAAW,QAAQ,OAAK,CAAC,QAAQ,cAAc,WAAW,OAAO,CAAC,CAAC,CAAC;AAAA;AAAA,EAE9E,aAAe,WAAW,SAAO,CAAC;AAAA;AAAA,EAElC,gBAAkB,WAAW,SAAO,CAAC;AAAA;AAAA,EAErC,cAAgB,WAAW,SAAO,CAAC;AAAA;AAAA,EAEnC,mBAAqB,WAAW,SAAO,CAAC;AACzC,CAAC;AAEM,IAAM,8BAAgC,SAAO,iBAAiB;AAAA,EACpE,OAAS,UAAQ,kBAAkB;AAAA,EACnC,GAAG,+BAA+B;AACnC,CAAC;AAMM,IAAM,iCAAiC,qBAAqB;AAAA,EAClE,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AAAA,IACT,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,EACX;AACD,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,16 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createJSONSchemaEmbedder,
|
|
3
|
+
readStandardJSONSchema
|
|
4
|
+
} from "./chunk-OG3OLZ5R.js";
|
|
1
5
|
import {
|
|
2
6
|
isZodType
|
|
3
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-4SWCTY7K.js";
|
|
4
8
|
import {
|
|
5
9
|
buildSubmissionShape
|
|
6
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-AROD3D4R.js";
|
|
7
11
|
import {
|
|
8
12
|
frozenCopy
|
|
9
13
|
} from "./chunk-3B7CJOF6.js";
|
|
10
14
|
import {
|
|
11
15
|
getValidationRulesForElement,
|
|
12
16
|
isFieldRequired
|
|
13
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-4YANBG3M.js";
|
|
14
18
|
import {
|
|
15
19
|
isPlainObject
|
|
16
20
|
} from "./chunk-CMPOBBRV.js";
|
|
@@ -140,46 +144,46 @@ function standardOptions(options) {
|
|
|
140
144
|
throw new Error(`The JSON Schema target '${options.target}' is not supported for a submission.`);
|
|
141
145
|
}
|
|
142
146
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
if (hasJsonSchema(schema)) return schema["~standard"].jsonSchema[io](options);
|
|
147
|
+
function leafJsonSchema(name, schema, context) {
|
|
148
|
+
const { io, options, embedder } = context;
|
|
146
149
|
if (isZodType(schema)) {
|
|
147
|
-
|
|
148
|
-
...standardOptions(options),
|
|
149
|
-
|
|
150
|
-
unrepresentable: "any"
|
|
151
|
-
});
|
|
152
|
-
return rest;
|
|
150
|
+
return embedder.embed(
|
|
151
|
+
z.toJSONSchema(schema, { ...standardOptions(options), io, unrepresentable: "any" })
|
|
152
|
+
);
|
|
153
153
|
}
|
|
154
|
+
const converter = readStandardJSONSchema(schema);
|
|
155
|
+
if (converter) return embedder.embed(converter[io](options));
|
|
154
156
|
throw new Error(`The value schema of '${name}' has no JSON Schema.`);
|
|
155
157
|
}
|
|
156
|
-
function toJsonSchema(node,
|
|
157
|
-
const schema = nodeJsonSchema(node,
|
|
158
|
+
function toJsonSchema(node, context) {
|
|
159
|
+
const schema = nodeJsonSchema(node, context);
|
|
158
160
|
return node.kind !== "any" && node.description ? { ...schema, description: node.description } : schema;
|
|
159
161
|
}
|
|
160
|
-
function nodeJsonSchema(node,
|
|
162
|
+
function nodeJsonSchema(node, context) {
|
|
161
163
|
switch (node.kind) {
|
|
162
164
|
case "any":
|
|
163
165
|
return {};
|
|
164
166
|
case "leaf": {
|
|
165
|
-
const schema = leafJsonSchema(node.name, node.schema,
|
|
167
|
+
const schema = leafJsonSchema(node.name, node.schema, context);
|
|
166
168
|
return node.required ? schema : { anyOf: [schema, ...EMPTY.map((empty) => ({ const: empty }))] };
|
|
167
169
|
}
|
|
168
170
|
case "array":
|
|
169
|
-
return { type: "array", items: toJsonSchema(node.row,
|
|
171
|
+
return { type: "array", items: toJsonSchema(node.row, context) };
|
|
170
172
|
case "object": {
|
|
171
173
|
const required = node.fields.flatMap(([key, child]) => isRequired(child) ? [key] : []);
|
|
172
174
|
return {
|
|
173
175
|
type: "object",
|
|
174
|
-
properties: Object.fromEntries(
|
|
175
|
-
node.fields.map(([key, child]) => [key, toJsonSchema(child, io, options)])
|
|
176
|
-
),
|
|
176
|
+
properties: Object.fromEntries(node.fields.map(([key, child]) => [key, toJsonSchema(child, context)])),
|
|
177
177
|
...required.length ? { required } : {},
|
|
178
178
|
additionalProperties: false
|
|
179
179
|
};
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
182
|
}
|
|
183
|
+
function treeJsonSchema(tree, io, options) {
|
|
184
|
+
const embedder = createJSONSchemaEmbedder(options.target, { kind: "document" });
|
|
185
|
+
return embedder.finish({ ...toJsonSchema(tree, { io, options, embedder }) });
|
|
186
|
+
}
|
|
183
187
|
function createSubmissionSchema(config, source) {
|
|
184
188
|
const shape = buildSubmissionShape(config.steps);
|
|
185
189
|
const root = nodeOf(shape, source);
|
|
@@ -197,8 +201,8 @@ function createSubmissionSchema(config, source) {
|
|
|
197
201
|
validate: validator(partial)
|
|
198
202
|
});
|
|
199
203
|
const jsonSchema = {
|
|
200
|
-
input: (options) => (
|
|
201
|
-
output: (options) => (
|
|
204
|
+
input: (options) => treeJsonSchema(tree, "input", options),
|
|
205
|
+
output: (options) => treeJsonSchema(tree, "output", options)
|
|
202
206
|
};
|
|
203
207
|
return {
|
|
204
208
|
"~standard": { ...props(false), jsonSchema },
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/engine/submission-schema.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';\nimport * as z from 'zod/mini';\nimport { frozenCopy } from '@/lib/frozen-copy';\nimport { isPlainObject } from '@/lib/is-plain-object';\nimport { buildSubmissionShape, type ShapeElement, type ShapeStep, type SubmissionShape } from '@/lib/submission-shape';\nimport { isZodType } from '@/lib/is-zod-type';\nimport { createJSONSchemaEmbedder, readStandardJSONSchema, type JSONSchemaEmbedder } from '@/lib/export-schema';\nimport type { JSONSchemaObject } from '@/lib/standard-json-schema';\nimport type { ValidationRegistry } from '@/schemas/validation/validation-registry';\nimport { getValidationRulesForElement, isFieldRequired } from '@/schemas/validation/utils';\nimport type { BaseValidationRule } from '@/schemas/validation/types';\nimport type { AnyElementRegistration } from '@/types/registration';\n\n/**\n * The submitted values of a form, as a Standard Schema, and as a Standard JSON Schema where its value schemas can say so.\n *\n * @remarks\n * `~standard.validate` checks a submission: the values the container submits, whose keys are the fields' names\n * (dotted names nested), and returns them without any key a field does not declare. A mismatch is a broken\n * element contract, not a user error. `partial` is the same schema with every key optional at every depth and\n * every leaf allowed to be empty, for the `defaultValues` of a form that has not been filled. A value schema that cannot\n * check a default (it throws, or is asynchronous) is reported there as an issue at its field, so one default that cannot\n * be checked never stops the others from being.\n *\n * @remarks\n * An issue of `partial` is at the field, because a default is kept or dropped as a whole: a leaf is a field, a group is\n * not (its fields are), and a list is one field, so an issue inside a row is at the list (`tags`, not `tags.0` or\n * `tags.0.name`). `createFormRuntime` drops the default of each field `partial` reports.\n */\nexport interface SubmissionSchema<TValues = Readonly<Record<string, unknown>>>\n\textends StandardSchemaV1<unknown, TValues>, StandardJSONSchemaV1<unknown, TValues> {\n\treadonly '~standard': StandardSchemaV1.Props<unknown, TValues> & StandardJSONSchemaV1.Props<unknown, TValues>;\n\treadonly partial: {\n\t\treadonly '~standard': Omit<StandardSchemaV1.Props<unknown, unknown>, 'validate'> & {\n\t\t\treadonly validate: (value: unknown) => StandardSchemaV1.Result<unknown>;\n\t\t};\n\t};\n}\n\n/** What the composer needs of an engine: the element registrations and the validation rules. */\nexport interface SubmissionSchemaSource {\n\tgetElement(id: string): AnyElementRegistration | undefined;\n\treadonly validationRegistry: ValidationRegistry;\n}\n\n/** What it reads of the form config: its steps and its payload. */\nexport interface SubmissionSchemaConfig {\n\treadonly steps: readonly ShapeStep[];\n\treadonly payload?: Readonly<Record<string, unknown>>;\n}\n\n/** The empty values of an optional leaf field, which a submission keeps so a PATCH can tell cleared from untouched. */\nconst EMPTY = ['', null] as const;\n\ntype Issues = StandardSchemaV1.Issue[];\ntype Key = PropertyKey;\n\n/** A node of the schema: what the shape's field, object or array checks, with the value schema of each leaf resolved. */\ntype Node =\n\t| {\n\t\t\treadonly kind: 'leaf';\n\t\t\treadonly name: string;\n\t\t\treadonly schema: StandardSchemaV1;\n\t\t\treadonly required: boolean;\n\t\t\treadonly description?: string;\n\t }\n\t| {\n\t\t\treadonly kind: 'object';\n\t\t\treadonly fields: ReadonlyArray<readonly [string, Node]>;\n\t\t\treadonly required: boolean;\n\t\t\treadonly description?: string;\n\t }\n\t| { readonly kind: 'array'; readonly row: Node; readonly required: boolean; readonly description?: string }\n\t| { readonly kind: 'any' };\n\nconst isEmpty = (value: unknown): boolean => value === undefined || value === '' || value === null;\n\nconst isRequired = (node: Node): boolean => node.kind !== 'any' && node.required;\n\n/**\n * Whether a key is required: its field has a `required` rule and nothing can leave it out, or something inside it is required.\n */\nfunction requiredOf(shape: SubmissionShape, source: SubmissionSchemaSource, inside = false): boolean {\n\tconst { element } = shape;\n\tconst ruled =\n\t\telement !== undefined &&\n\t\t!shape.conditional &&\n\t\tisFieldRequired(\n\t\t\tgetValidationRulesForElement(\n\t\t\t\telement as { $type?: string; rules?: readonly BaseValidationRule[] },\n\t\t\t\tsource.validationRegistry,\n\t\t\t),\n\t\t);\n\treturn ruled || inside;\n}\n\n/** What the JSON Schema says about a field: its label, then its help text. */\nfunction describeElement(element: ShapeElement | undefined): { description?: string } {\n\tconst { label, description } = (element ?? {}) as { label?: unknown; description?: unknown };\n\tconst parts = [label, description].filter((part): part is string => typeof part === 'string' && part !== '');\n\treturn parts.length > 0 ? { description: parts.join(': ') } : {};\n}\n\nfunction leafOf(shape: Extract<SubmissionShape, { kind: 'field' }>, source: SubmissionSchemaSource): Node {\n\tconst { element } = shape;\n\tconst registration = element.$type ? source.getElement(element.$type) : undefined;\n\tconst schema = registration && 'value' in registration ? registration.value?.(element as never) : undefined;\n\tif (schema === undefined) return { kind: 'any' };\n\treturn {\n\t\tkind: 'leaf',\n\t\tname: element.name ?? '',\n\t\tschema,\n\t\trequired: requiredOf(shape, source),\n\t\t...describeElement(element),\n\t};\n}\n\nfunction nodeOf(shape: SubmissionShape, source: SubmissionSchemaSource): Node {\n\tif (shape.kind === 'field') return leafOf(shape, source);\n\tif (shape.kind === 'array') {\n\t\treturn {\n\t\t\tkind: 'array',\n\t\t\trow: nodeOf(shape.row, source),\n\t\t\trequired: requiredOf(shape, source),\n\t\t\t...describeElement(shape.element),\n\t\t};\n\t}\n\tconst fields = Object.entries(shape.fields).map(([key, child]) => [key, nodeOf(child, source)] as const);\n\tconst inside = fields.some(([, child]) => isRequired(child));\n\treturn { kind: 'object', fields, required: requiredOf(shape, source, inside), ...describeElement(shape.element) };\n}\n\nfunction validateLeaf(schema: StandardSchemaV1, value: unknown): StandardSchemaV1.Result<unknown> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result instanceof Promise) throw new Error('A value schema must validate synchronously.');\n\treturn result;\n}\n\nconst joined = (path: readonly Key[], key: Key): readonly Key[] => [...path, key];\n\n/** What an issue of a partial parse says when a default could not be checked at all, which the runtime reads to tell it from a mismatch. */\nexport const DEFAULT_NOT_CHECKED = 'The default could not be checked: ';\n\n/** An issue of a partial parse, moved to the field it is about: a list is one field, so a path inside a row is its list's. */\nfunction atField(issue: StandardSchemaV1.Issue): StandardSchemaV1.Issue {\n\tconst path = issue.path ?? [];\n\tconst row = path.findIndex((segment) => typeof segment === 'number');\n\treturn row === -1 ? issue : { ...issue, path: path.slice(0, row) };\n}\n\n/** What parsing a node found: the value it keeps (`undefined` leaves the key out) and every issue, under `path`. */\nfunction parse(node: Node, value: unknown, path: readonly Key[], partial: boolean, issues: Issues): unknown {\n\tswitch (node.kind) {\n\t\tcase 'any':\n\t\t\treturn value;\n\t\tcase 'leaf': {\n\t\t\tif ((partial || !node.required) && isEmpty(value)) return value;\n\t\t\tlet result: StandardSchemaV1.Result<unknown>;\n\t\t\ttry {\n\t\t\t\tresult = validateLeaf(node.schema, value);\n\t\t\t} catch (error) {\n\t\t\t\tif (!partial) throw error;\n\t\t\t\tconst cause = error instanceof Error ? error.message : String(error);\n\t\t\t\tissues.push({ message: `${DEFAULT_NOT_CHECKED}${cause}`, path });\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tif (result.issues === undefined) return result.value;\n\t\t\tfor (const issue of result.issues) {\n\t\t\t\tconst inside = partial\n\t\t\t\t\t? []\n\t\t\t\t\t: (issue.path ?? []).map((segment) => (typeof segment === 'object' ? segment.key : segment));\n\t\t\t\tissues.push({ ...issue, path: [...path, ...inside] });\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\tcase 'array': {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (!Array.isArray(value)) {\n\t\t\t\tissues.push({ message: 'Expected a list', path });\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\treturn value.map((row, index) => parse(node.row, row, joined(path, index), partial, issues));\n\t\t}\n\t\tcase 'object': {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (!isPlainObject(value)) {\n\t\t\t\tissues.push({ message: 'Expected an object', path });\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tconst kept: Record<string, unknown> = {};\n\t\t\tfor (const [key, child] of node.fields) {\n\t\t\t\tconst present = Object.hasOwn(value, key) && value[key] !== undefined;\n\t\t\t\tif (!present) {\n\t\t\t\t\tif (isRequired(child) && !partial) {\n\t\t\t\t\t\tissues.push({ message: 'Required', path: joined(path, key) });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tkept[key] = parse(child, value[key], joined(path, key), partial, issues);\n\t\t\t}\n\t\t\treturn kept;\n\t\t}\n\t}\n}\n\n/** The path of an issue as the dotted string a field is known by (`contacts.0.email`). */\nexport function issuePath(issue: StandardSchemaV1.Issue): string {\n\treturn (issue.path ?? []).map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.');\n}\n\nfunction standardOptions(options: StandardJSONSchemaV1.Options): {\n\ttarget: 'draft-2020-12' | 'draft-7' | 'openapi-3.0';\n} {\n\tswitch (options.target) {\n\t\tcase 'draft-2020-12':\n\t\t\treturn { target: 'draft-2020-12' };\n\t\tcase 'draft-07':\n\t\t\treturn { target: 'draft-7' };\n\t\tcase 'openapi-3.0':\n\t\t\treturn { target: 'openapi-3.0' };\n\t\tdefault:\n\t\t\tthrow new Error(`The JSON Schema target '${options.target}' is not supported for a submission.`);\n\t}\n}\n\n/** What writing the JSON Schema of a submission reads at every node. */\ninterface JsonContext {\n\treadonly io: 'input' | 'output';\n\treadonly options: StandardJSONSchemaV1.Options;\n\treadonly embedder: JSONSchemaEmbedder;\n}\n\n/**\n * The JSON Schema of a leaf's value schema, by the export's rule: Zod (classic or Mini) through the Zod converter,\n * any other schema by its own `~standard.jsonSchema`.\n *\n * @remarks\n * Zod comes first so a classic and a Mini value schema write the same JSON Schema, with an unrepresentable type (a\n * date) as `{}` rather than an error. Each result is embedded by the export's {@link JSONSchemaEmbedder}.\n */\nfunction leafJsonSchema(name: string, schema: StandardSchemaV1, context: JsonContext): JSONSchemaObject {\n\tconst { io, options, embedder } = context;\n\tif (isZodType(schema)) {\n\t\treturn embedder.embed(\n\t\t\tz.toJSONSchema(schema, { ...standardOptions(options), io, unrepresentable: 'any' }) as JSONSchemaObject,\n\t\t);\n\t}\n\tconst converter = readStandardJSONSchema(schema);\n\tif (converter) return embedder.embed(converter[io](options));\n\tthrow new Error(`The value schema of '${name}' has no JSON Schema.`);\n}\n\nfunction toJsonSchema(node: Node, context: JsonContext): JSONSchemaObject {\n\tconst schema = nodeJsonSchema(node, context);\n\treturn node.kind !== 'any' && node.description ? { ...schema, description: node.description } : schema;\n}\n\nfunction nodeJsonSchema(node: Node, context: JsonContext): JSONSchemaObject {\n\tswitch (node.kind) {\n\t\tcase 'any':\n\t\t\treturn {};\n\t\tcase 'leaf': {\n\t\t\tconst schema = leafJsonSchema(node.name, node.schema, context);\n\t\t\treturn node.required ? schema : { anyOf: [schema, ...EMPTY.map((empty) => ({ const: empty }))] };\n\t\t}\n\t\tcase 'array':\n\t\t\treturn { type: 'array', items: toJsonSchema(node.row, context) };\n\t\tcase 'object': {\n\t\t\tconst required = node.fields.flatMap(([key, child]) => (isRequired(child) ? [key] : []));\n\t\t\treturn {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: Object.fromEntries(node.fields.map(([key, child]) => [key, toJsonSchema(child, context)])),\n\t\t\t\t...(required.length ? { required } : {}),\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/** The JSON Schema of a submission tree, with the definitions its leaves hoisted at its root. */\nfunction treeJsonSchema(tree: Node, io: 'input' | 'output', options: StandardJSONSchemaV1.Options): JSONSchemaObject {\n\tconst embedder = createJSONSchemaEmbedder(options.target, { kind: 'document' });\n\treturn embedder.finish({ ...toJsonSchema(tree, { io, options, embedder }) });\n}\n\n/**\n * Composes the submission schema of a form from its elements' value declarations.\n *\n * @remarks\n * The rules are the container's, read from one {@link buildSubmissionShape}: dotted names nest, named containers\n * become objects, `containerKind: 'array'` becomes an array, a one-child row is a list of values (unless its child is a container of its own, which makes the rows objects) and the `payload`\n * keys are added as they are. A named element that declares no value (a static one) is carried as it is, so the keys of the schema are exactly the shape's. An optional\n * leaf field accepts its empty value (`''` or `null`) as well as its declared one, because a submission keeps what the\n * user cleared; a required field is held to its declaration. Its JSON Schema describes each field by its label, then its help text. A value schema is read once, when this is called.\n */\nexport function createSubmissionSchema(\n\tconfig: SubmissionSchemaConfig,\n\tsource: SubmissionSchemaSource,\n): SubmissionSchema {\n\tconst shape = buildSubmissionShape(config.steps);\n\tconst root = nodeOf(shape, source);\n\tconst payload = Object.entries(config.payload ?? {}).map(([key]) => [key, { kind: 'any' } as Node] as const);\n\tconst tree: Node = root.kind === 'object' ? { ...root, fields: [...root.fields, ...payload] } : root;\n\n\tconst validator =\n\t\t(partial: boolean) =>\n\t\t(value: unknown): StandardSchemaV1.Result<Readonly<Record<string, unknown>>> => {\n\t\t\tconst issues: Issues = [];\n\t\t\tconst parsed = parse(tree, value, [], partial, issues);\n\t\t\tif (issues.length) return { issues: partial ? issues.map(atField) : issues };\n\t\t\treturn isPlainObject(parsed)\n\t\t\t\t? { value: frozenCopy(parsed) }\n\t\t\t\t: { issues: [{ message: 'Expected an object' }] };\n\t\t};\n\tconst props = (partial: boolean) => ({\n\t\tversion: 1 as const,\n\t\tvendor: 'schema-engine',\n\t\tvalidate: validator(partial),\n\t});\n\tconst jsonSchema: StandardJSONSchemaV1.Converter = {\n\t\tinput: (options) => treeJsonSchema(tree, 'input', options),\n\t\toutput: (options) => treeJsonSchema(tree, 'output', options),\n\t};\n\treturn {\n\t\t'~standard': { ...props(false), jsonSchema },\n\t\tpartial: { '~standard': props(true) },\n\t};\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;AACA,YAAY,OAAO;AAmDnB,IAAM,QAAQ,CAAC,IAAI,IAAI;AAuBvB,IAAM,UAAU,CAAC,UAA4B,UAAU,UAAa,UAAU,MAAM,UAAU;AAE9F,IAAM,aAAa,CAAC,SAAwB,KAAK,SAAS,SAAS,KAAK;AAKxE,SAAS,WAAW,OAAwB,QAAgC,SAAS,OAAgB;AACpG,QAAM,EAAE,QAAQ,IAAI;AACpB,QAAM,QACL,YAAY,UACZ,CAAC,MAAM,eACP;AAAA,IACC;AAAA,MACC;AAAA,MACA,OAAO;AAAA,IACR;AAAA,EACD;AACD,SAAO,SAAS;AACjB;AAGA,SAAS,gBAAgB,SAA6D;AACrF,QAAM,EAAE,OAAO,YAAY,IAAK,WAAW,CAAC;AAC5C,QAAM,QAAQ,CAAC,OAAO,WAAW,EAA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,CAAC,YAAY,eAAe,MAAM,UAAU,OAAO;AAAA,EAC5D;AACA,SAAO;AAAA,IACN,aAAa,EAAE,GAAG,MAAM,KAAK,GAAG,WAAW;AAAA,IAC3C,SAAS,EAAE,aAAa,MAAM,IAAI,EAAE;AAAA,EACrC;AACD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,7 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
placedTrackItems
|
|
3
|
+
} from "./chunk-DU26WGQA.js";
|
|
1
4
|
import {
|
|
2
5
|
isRecord,
|
|
6
|
+
isTaggedConfig,
|
|
3
7
|
issueAt
|
|
4
8
|
} from "./chunk-LMWJAD3B.js";
|
|
9
|
+
import {
|
|
10
|
+
getElementChildren
|
|
11
|
+
} from "./chunk-ZUYSGCEH.js";
|
|
5
12
|
|
|
6
13
|
// src/lib/validate-form/grid-checks.ts
|
|
7
14
|
import {
|
|
@@ -11,11 +18,15 @@ import {
|
|
|
11
18
|
elementAreaSlots,
|
|
12
19
|
elementHiddenSlots,
|
|
13
20
|
elementGridKeys,
|
|
21
|
+
elementIsSubgrid,
|
|
14
22
|
elementUsesGridWidths,
|
|
15
23
|
GRID_TEMPLATE_KEYS,
|
|
16
24
|
gridAreaTemplates,
|
|
25
|
+
gridSpanIssues,
|
|
17
26
|
gridUsesAreas,
|
|
18
27
|
namedPlacementOverflow,
|
|
28
|
+
spanPlacementIssue,
|
|
29
|
+
subgridPlacementIssue,
|
|
19
30
|
WIDTH_TRACKS
|
|
20
31
|
} from "@schema-engine/layout";
|
|
21
32
|
function gridKeyPath(grid, keys, slot) {
|
|
@@ -90,6 +101,29 @@ function areaPlacementIssue(item, nested) {
|
|
|
90
101
|
`${label} sets grid ${quotedKeys(["area", ...others])}; use an area or a width, offset or raw line, not both.`
|
|
91
102
|
);
|
|
92
103
|
}
|
|
104
|
+
function spanIssue(item) {
|
|
105
|
+
const issue = spanPlacementIssue(item);
|
|
106
|
+
return issue ? issueAt(issue.path, `${elementLabel(item)} ${issue.message}`) : void 0;
|
|
107
|
+
}
|
|
108
|
+
function subgridIssue(item, kind) {
|
|
109
|
+
if (!elementIsSubgrid(item)) return void 0;
|
|
110
|
+
const label = elementLabel(item);
|
|
111
|
+
const path = elementGridKeyPath(item, ["subgrid"]);
|
|
112
|
+
if (kind === "array") {
|
|
113
|
+
return issueAt(
|
|
114
|
+
path,
|
|
115
|
+
`${label} sets grid 'subgrid' but is an array; subgrid rows are not supported yet, so only a container that lays its children out as one group can use 'subgrid'.`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
if (!getElementChildren(item)) {
|
|
119
|
+
return issueAt(
|
|
120
|
+
path,
|
|
121
|
+
`${label} sets grid 'subgrid' but has no elements; only a container can lay its children on its parent's tracks.`
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
const placement = subgridPlacementIssue(item);
|
|
125
|
+
return placement ? issueAt(placement.path, `${label} ${placement.message}`) : void 0;
|
|
126
|
+
}
|
|
93
127
|
function templateTrackKeys(grid) {
|
|
94
128
|
const entries = [grid, ...Object.values(grid?.responsive ?? {})];
|
|
95
129
|
return GRID_TEMPLATE_KEYS.filter((key) => entries.some((entry) => entry?.[key] !== void 0));
|
|
@@ -124,17 +158,41 @@ function templateIssues(label, grid, gridPath) {
|
|
|
124
158
|
function fieldPlacementIssues(label, grid, scope, templatesValid, sharedBySteps) {
|
|
125
159
|
const usesAreas = gridUsesAreas(grid);
|
|
126
160
|
const issues = [];
|
|
127
|
-
const widths = scope.elements.find(({ element }) => elementUsesGridWidths(element));
|
|
161
|
+
const widths = placedTrackItems(scope.elements).filter((item) => isTaggedConfig(item.element)).find(({ element }) => elementUsesGridWidths(element));
|
|
128
162
|
const exclusive = usesAreas ? ["areas"] : templateTrackKeys(grid);
|
|
129
163
|
if (widths && exclusive.length > 0) {
|
|
130
164
|
const tracksPath = gridKeyPath(grid, GRID_TEMPLATE_KEYS) ?? [];
|
|
165
|
+
const inSubgrid = !scope.elements.some(({ element }) => element === widths.element);
|
|
166
|
+
const path = inSubgrid ? [...widths.path, ...elementGridKeyPath(widths.element, ["width", "offset"])] : [...scope.gridPath, ...usesAreas ? ["areas"] : tracksPath];
|
|
131
167
|
issues.push(
|
|
132
168
|
issueAt(
|
|
133
|
-
|
|
169
|
+
path,
|
|
134
170
|
`${label} sets ${quotedKeys(exclusive)} but ${elementLabel(widths.element)} uses 'width' or 'offset'; a grid uses areas, widths or columns.`
|
|
135
171
|
)
|
|
136
172
|
);
|
|
137
173
|
}
|
|
174
|
+
const tracked = placedTrackItems(scope.elements);
|
|
175
|
+
for (const { path: relative, message } of gridSpanIssues(
|
|
176
|
+
grid,
|
|
177
|
+
tracked.map(({ element }) => element)
|
|
178
|
+
)) {
|
|
179
|
+
const [index, ...rest] = relative;
|
|
180
|
+
const target = typeof index === "number" ? tracked[index] : void 0;
|
|
181
|
+
if (!target) continue;
|
|
182
|
+
issues.push(
|
|
183
|
+
issueAt([...target.path, ...rest], `${elementLabel(target.element)} ${message}`)
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (usesAreas) {
|
|
187
|
+
for (const { element, path } of scope.elements.filter(({ element: element2 }) => elementIsSubgrid(element2))) {
|
|
188
|
+
issues.push(
|
|
189
|
+
issueAt(
|
|
190
|
+
[...path, ...elementGridKeyPath(element, ["subgrid"])],
|
|
191
|
+
`${elementLabel(element)} sets grid 'subgrid' but the ${label.toLowerCase()} draws 'areas'; a subgrid spans its parent's full row and cannot claim an area.`
|
|
192
|
+
)
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
138
196
|
const claimants = scope.elements.filter(({ element }) => Object.keys(elementAreaSlots(element)).length > 0);
|
|
139
197
|
if (!usesAreas) {
|
|
140
198
|
for (const { element, path } of claimants) {
|
|
@@ -207,6 +265,8 @@ export {
|
|
|
207
265
|
elementGridKeyPath,
|
|
208
266
|
namedPlacementIssue,
|
|
209
267
|
areaPlacementIssue,
|
|
268
|
+
spanIssue,
|
|
269
|
+
subgridIssue,
|
|
210
270
|
templateIssues,
|
|
211
271
|
fieldPlacementIssues
|
|
212
272
|
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/validate-form/grid-checks.ts"],
|
|
4
|
+
"sourcesContent": ["import type { FormTaggedConfig } from '@/schemas/form-config';\nimport type { ContainerKind } from '@/types/registration';\nimport { getElementChildren } from '@/lib/element-children';\nimport { placedTrackItems } from '@/lib/grid-track-items';\nimport {\n\tareaNames,\n\tareaTemplateIssues,\n\tcascadeValues,\n\telementAreaSlots,\n\telementHiddenSlots,\n\telementGridKeys,\n\telementIsSubgrid,\n\telementUsesGridWidths,\n\tGRID_TEMPLATE_KEYS,\n\tgridAreaTemplates,\n\tgridSpanIssues,\n\tgridUsesAreas,\n\tnamedPlacementOverflow,\n\tspanPlacementIssue,\n\tsubgridPlacementIssue,\n\tWIDTH_TRACKS,\n\ttype CascadeSlot,\n\ttype GridLayoutConfig,\n} from '@schema-engine/layout';\nimport { isTaggedConfig, issueAt, isRecord, type FormValidationIssue, type Path } from './issues';\n\n/**\n * Where a grid sets the first of `keys`, relative to the grid: `['columns']` or\n * `['responsive', 'md', 'columns']`. With `slot`, only that slot's entry is read.\n *\n * @remarks\n * A path always names a key the author wrote, never a viewport the cascade resolved to, so an editor\n * or a YAML file lands on real text.\n */\nfunction gridKeyPath(grid: unknown, keys: readonly string[], slot?: CascadeSlot): Path | undefined {\n\tif (!isRecord(grid)) return undefined;\n\tconst entries: Array<{ slot: string; prefix: Path; entry: unknown }> = [\n\t\t{ slot: 'default', prefix: [], entry: grid },\n\t];\n\tif (isRecord(grid.responsive)) {\n\t\tfor (const [name, entry] of Object.entries(grid.responsive)) {\n\t\t\tentries.push({ slot: name, prefix: ['responsive', name], entry });\n\t\t}\n\t}\n\tfor (const { slot: entrySlot, prefix, entry } of entries) {\n\t\tif ((slot !== undefined && entrySlot !== slot) || !isRecord(entry)) continue;\n\t\tconst key = keys.find((name) => entry[name] !== undefined);\n\t\tif (key !== undefined) return [...prefix, key];\n\t}\n\treturn undefined;\n}\n\n/** Where an element sets the first of `keys` in its `grid`, relative to the element; `['grid']` when none is set. */\nexport function elementGridKeyPath(item: FormTaggedConfig, keys: readonly string[], slot?: CascadeSlot): Path {\n\tconst path = gridKeyPath(item.grid, keys, slot);\n\treturn path ? ['grid', ...path] : ['grid'];\n}\n\n/** Where a grid's `areas` template for a slot sits, below the grid. An array is the `default` template itself. */\nfunction areasPath(grid: GridLayoutConfig | undefined, slot: CascadeSlot): Path {\n\treturn Array.isArray(grid?.areas) ? ['areas'] : ['areas', slot];\n}\n\nfunction elementLabel(item: Record<string, unknown>): string {\n\tif (typeof item.name === 'string') return `Field '${item.name}'`;\n\treturn typeof item.id === 'string' ? `Element '${item.id}'` : 'Element';\n}\n\n/** Placement keys that cannot sit beside a field's `area`, which is a placement of its own. */\nconst AREA_EXCLUSIVE_KEYS = ['width', 'offset', 'column', 'row'] as const;\n\nfunction quotedKeys(keys: readonly string[]): string {\n\treturn keys.map((key) => `'${key}'`).join(' and ');\n}\n\n/**\n * Why a field's named placement is invalid, or `undefined` when it is fine.\n *\n * @remarks\n * Applies at every depth: a container lays its children out in a grid of its\n * own, so a nested field's tracks add up the same way a top-level field's do.\n * The path is relative to the element and names the key that conflicts, or the one that overflows.\n */\nexport function namedPlacementIssue(item: FormTaggedConfig): FormValidationIssue | undefined {\n\tconst keys = elementGridKeys(item);\n\tconst named = ['width', 'offset'].filter((key) => keys.has(key));\n\tif (named.length === 0) return undefined;\n\tconst label = elementLabel(item);\n\tif (keys.has('column')) {\n\t\treturn issueAt(\n\t\t\telementGridKeyPath(item, ['column']),\n\t\t\t`${label} sets grid ${quotedKeys(named)} and 'column'; use named widths or a raw column, not both.`,\n\t\t);\n\t}\n\tconst overflow = namedPlacementOverflow(item);\n\tif (overflow) {\n\t\treturn issueAt(\n\t\t\telementGridKeyPath(item, ['width', 'offset'], overflow.slot),\n\t\t\t`${label} sets grid 'width' and 'offset' that span ${overflow.tracks} of ${WIDTH_TRACKS} tracks at ${overflow.slot === 'default' ? 'default' : `'${overflow.slot}'`}; together they must fit in ${WIDTH_TRACKS} tracks.`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\n/** The slot as it reads in a message: nothing for the default width, else ` at 'md'`. */\nfunction atSlot(slot: string): string {\n\treturn slot === 'default' ? '' : ` at '${slot}'`;\n}\n\n/**\n * Why a field's `area` cannot sit beside its other placement, or inside a container.\n *\n * @remarks\n * An area is a placement of its own: it resolves to the field's column and row,\n * so a width, offset or raw line set next to it would fight it. A container lays\n * its children out in a grid that takes no `areas`, so a child has no template\n * to name. The path is relative to the element.\n */\nexport function areaPlacementIssue(item: FormTaggedConfig, nested: boolean): FormValidationIssue | undefined {\n\tconst keys = elementGridKeys(item);\n\tif (!keys.has('area')) return undefined;\n\tconst label = elementLabel(item);\n\tif (nested) {\n\t\treturn issueAt(\n\t\t\telementGridKeyPath(item, ['area']),\n\t\t\t`${label} sets grid 'area' inside a container; a container lays its children out without areas.`,\n\t\t);\n\t}\n\tconst others = AREA_EXCLUSIVE_KEYS.filter((key) => keys.has(key));\n\tif (others.length === 0) return undefined;\n\treturn issueAt(\n\t\telementGridKeyPath(item, others),\n\t\t`${label} sets grid ${quotedKeys(['area', ...others])}; use an area or a width, offset or raw line, not both.`,\n\t);\n}\n\n/**\n * Why a field's `span` cannot sit beside its other placement, or `undefined` when it is fine.\n *\n * @remarks\n * A span is a placement of its own, so a `width`, `offset`, raw `column` or `area` in the same slot would give\n * the field two answers; different slots may differ. Applies at every depth. The path is relative to the element.\n */\nexport function spanIssue(item: FormTaggedConfig): FormValidationIssue | undefined {\n\tconst issue = spanPlacementIssue(item);\n\treturn issue ? issueAt(issue.path, `${elementLabel(item)} ${issue.message}`) : undefined;\n}\n\n/**\n * Why an element cannot be a subgrid, or `undefined` when it can or is not one.\n *\n * @param kind The container semantics the element's registration declares.\n *\n * @remarks\n * A subgrid lays its children on its parent's tracks, so it needs children, and its own placement must\n * leave it spanning the parent's full row (see `subgridPlacementIssue`). An array is rejected for now:\n * its rows are each a box of their own and do not pass the tracks on. The path is relative to the element.\n */\nexport function subgridIssue(item: FormTaggedConfig, kind: ContainerKind | undefined): FormValidationIssue | undefined {\n\tif (!elementIsSubgrid(item)) return undefined;\n\tconst label = elementLabel(item);\n\tconst path = elementGridKeyPath(item, ['subgrid']);\n\tif (kind === 'array') {\n\t\treturn issueAt(\n\t\t\tpath,\n\t\t\t`${label} sets grid 'subgrid' but is an array; subgrid rows are not supported yet, so only a container that lays its children out as one group can use 'subgrid'.`,\n\t\t);\n\t}\n\tif (!getElementChildren(item)) {\n\t\treturn issueAt(\n\t\t\tpath,\n\t\t\t`${label} sets grid 'subgrid' but has no elements; only a container can lay its children on its parent's tracks.`,\n\t\t);\n\t}\n\tconst placement = subgridPlacementIssue(item);\n\treturn placement ? issueAt(placement.path, `${label} ${placement.message}`) : undefined;\n}\n\n/** An element of a step that validated, with where it sits in the form. */\nexport interface PlacedElement {\n\telement: FormTaggedConfig;\n\tpath: Path;\n}\n\ninterface GridScope {\n\t/** Where the grid that lays the step out sits: the step's own, else the form's. */\n\tgridPath: Path;\n\telements: readonly PlacedElement[];\n}\n\n/** The grid keys that set its own tracks (`columns`, `minColumnWidth`), at any breakpoint. */\nfunction templateTrackKeys(grid: GridLayoutConfig | undefined): string[] {\n\tconst entries = [grid, ...Object.values(grid?.responsive ?? {})];\n\treturn GRID_TEMPLATE_KEYS.filter((key) => entries.some((entry) => entry?.[key] !== undefined));\n}\n\n/**\n * Why a grid's `areas` cannot be a template: it sets `columns` or\n * `minColumnWidth` beside them, a responsive record has no `default`, or a\n * template has rows of unequal length or a non-rectangular area.\n *\n * @param gridPath Where the grid sits in the form, prefixed to each issue.\n *\n * @remarks\n * Nothing here depends on the fields, so a grid shared by several steps is\n * checked once rather than once per step.\n */\nexport function templateIssues(\n\tlabel: string,\n\tgrid: GridLayoutConfig | undefined,\n\tgridPath: Path,\n): FormValidationIssue[] {\n\tif (!gridUsesAreas(grid)) return [];\n\tconst templates = gridAreaTemplates(grid);\n\tconst issues: FormValidationIssue[] = [];\n\tconst tracks = templateTrackKeys(grid);\n\tif (tracks.length > 0) {\n\t\tissues.push(\n\t\t\tissueAt(\n\t\t\t\t[...gridPath, 'areas'],\n\t\t\t\t`${label} sets ${quotedKeys(['areas', ...tracks])}; a grid uses areas, widths or columns.`,\n\t\t\t),\n\t\t);\n\t}\n\tif (templates.default === undefined) {\n\t\tissues.push(\n\t\t\tissueAt(\n\t\t\t\t[...gridPath, 'areas'],\n\t\t\t\t`${label} 'areas' per breakpoint must include 'default', the layout below the narrowest breakpoint.`,\n\t\t\t),\n\t\t);\n\t}\n\tfor (const { path, message } of areaTemplateIssues(grid)) {\n\t\tconst slot = String(path[1] ?? 'default');\n\t\tissues.push(issueAt([...gridPath, ...path], `${label} areas${atSlot(slot)}: ${message}`));\n\t}\n\treturn issues;\n}\n\n/**\n * Why a step's fields do not fit the grid that lays them out.\n *\n * @remarks\n * Fields are checked against the cascade the stylesheet applies: a field's area\n * at a breakpoint is the last one set at or below it, and so is the template.\n * That is what a viewport gets, and it catches a template that changes at `md`\n * under a field that kept its `default` area.\n *\n * The widths check reads the grid's track items, which include the children of a subgrid, since they sit\n * on this grid's tracks. When the offender is such a child the issue is at its own `width` or `offset`,\n * the key to remove; for a direct child it stays at the grid's tracks, as it always was.\n */\nexport function fieldPlacementIssues(\n\tlabel: string,\n\tgrid: GridLayoutConfig | undefined,\n\tscope: GridScope,\n\ttemplatesValid: boolean,\n\tsharedBySteps: boolean,\n): FormValidationIssue[] {\n\tconst usesAreas = gridUsesAreas(grid);\n\tconst issues: FormValidationIssue[] = [];\n\n\tconst widths = placedTrackItems(scope.elements)\n\t\t.filter((item): item is PlacedElement => isTaggedConfig(item.element))\n\t\t.find(({ element }) => elementUsesGridWidths(element));\n\tconst exclusive = usesAreas ? ['areas'] : templateTrackKeys(grid);\n\tif (widths && exclusive.length > 0) {\n\t\tconst tracksPath = gridKeyPath(grid, GRID_TEMPLATE_KEYS) ?? [];\n\t\tconst inSubgrid = !scope.elements.some(({ element }) => element === widths.element);\n\t\tconst path = inSubgrid\n\t\t\t? [...widths.path, ...elementGridKeyPath(widths.element, ['width', 'offset'])]\n\t\t\t: [...scope.gridPath, ...(usesAreas ? ['areas'] : tracksPath)];\n\t\tissues.push(\n\t\t\tissueAt(\n\t\t\t\tpath,\n\t\t\t\t`${label} sets ${quotedKeys(exclusive)} but ${elementLabel(widths.element)} uses 'width' or 'offset'; a grid uses areas, widths or columns.`,\n\t\t\t),\n\t\t);\n\t}\n\n\tconst tracked = placedTrackItems(scope.elements);\n\tfor (const { path: relative, message } of gridSpanIssues(\n\t\tgrid,\n\t\ttracked.map(({ element }) => element),\n\t)) {\n\t\tconst [index, ...rest] = relative;\n\t\tconst target = typeof index === 'number' ? tracked[index] : undefined;\n\t\tif (!target) continue;\n\t\tissues.push(\n\t\t\tissueAt([...target.path, ...rest], `${elementLabel(target.element as Record<string, unknown>)} ${message}`),\n\t\t);\n\t}\n\n\tif (usesAreas) {\n\t\tfor (const { element, path } of scope.elements.filter(({ element }) => elementIsSubgrid(element))) {\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, ...elementGridKeyPath(element, ['subgrid'])],\n\t\t\t\t\t`${elementLabel(element)} sets grid 'subgrid' but the ${label.toLowerCase()} draws 'areas'; a subgrid spans its parent's full row and cannot claim an area.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst claimants = scope.elements.filter(({ element }) => Object.keys(elementAreaSlots(element)).length > 0);\n\tif (!usesAreas) {\n\t\tfor (const { element, path } of claimants) {\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, ...elementGridKeyPath(element, ['area'])],\n\t\t\t\t\t`${elementLabel(element)} sets grid 'area' but the ${label.toLowerCase()} has no 'areas'.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t} else if (templatesValid) {\n\t\tissues.push(...areaClaimIssues(label, grid, scope.gridPath, claimants, sharedBySteps));\n\t}\n\treturn issues;\n}\n\nfunction areaClaimIssues(\n\tlabel: string,\n\tgrid: GridLayoutConfig | undefined,\n\tgridPath: Path,\n\tclaimants: readonly PlacedElement[],\n\tsharedBySteps: boolean,\n): FormValidationIssue[] {\n\tconst issues: FormValidationIssue[] = [];\n\tconst templates = gridAreaTemplates(grid);\n\tconst templateBySlot = cascadeValues(templates);\n\tconst claims = claimants.map(({ element, path }) => ({\n\t\telement,\n\t\tpath,\n\t\tauthored: elementAreaSlots(element),\n\t\tbySlot: cascadeValues(elementAreaSlots(element)),\n\t\thiddenBySlot: cascadeValues(elementHiddenSlots(element)),\n\t}));\n\n\tfor (const { element, path, authored, bySlot, hiddenBySlot } of claims) {\n\t\tfor (const [index, { slot, value: area }] of bySlot.entries()) {\n\t\t\tconst rows = templateBySlot[index]?.value;\n\t\t\tif (area === undefined || rows === undefined || hiddenBySlot[index]?.value) continue;\n\t\t\tconst names = areaNames(rows);\n\t\t\tif (names.includes(area)) continue;\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, ...elementGridKeyPath(element, ['area'], authoredSlot(authored, slot))],\n\t\t\t\t\t`${elementLabel(element)} claims area '${area}'${atSlot(slot)}, which is not in the grid areas (${names.join(', ')}).`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst hint = sharedBySteps ? '; a form template applies to every step without a grid of its own' : '';\n\tconst reported = new Set<string>();\n\tfor (const [index, { slot, value: rows }] of templateBySlot.entries()) {\n\t\tif (rows === undefined) continue;\n\t\tfor (const name of areaNames(rows)) {\n\t\t\tconst claimed = claims.some(({ bySlot }) => bySlot[index]?.value === name);\n\t\t\tif (claimed || reported.has(name)) continue;\n\t\t\treported.add(name);\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...gridPath, ...areasPath(grid, authoredSlot(templates, slot))],\n\t\t\t\t\t`${label} area '${name}'${atSlot(slot)} is not claimed by any field${hint}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * The slot whose authored entry a cascaded slot resolves to: itself when it sets one, else the last\n * narrower slot that did. A message says where a viewport lands; a path says what the author wrote.\n */\nfunction authoredSlot<T>(authored: Partial<Record<CascadeSlot, T>>, slot: CascadeSlot): CascadeSlot {\n\tlet found: CascadeSlot = 'default';\n\tfor (const { slot: candidate } of cascadeValues(authored)) {\n\t\tif (authored[candidate] !== undefined) found = candidate;\n\t\tif (candidate === slot) break;\n\t}\n\treturn found;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;AAIA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGM;AAWP,SAAS,YAAY,MAAe,MAAyB,MAAsC;AAClG,MAAI,CAAC,SAAS,IAAI,EAAG,QAAO;AAC5B,QAAM,UAAiE;AAAA,IACtE,EAAE,MAAM,WAAW,QAAQ,CAAC,GAAG,OAAO,KAAK;AAAA,EAC5C;AACA,MAAI,SAAS,KAAK,UAAU,GAAG;AAC9B,eAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,GAAG;AAC5D,cAAQ,KAAK,EAAE,MAAM,MAAM,QAAQ,CAAC,cAAc,IAAI,GAAG,MAAM,CAAC;AAAA,IACjE;AAAA,EACD;AACA,aAAW,EAAE,MAAM,WAAW,QAAQ,MAAM,KAAK,SAAS;AACzD,QAAK,SAAS,UAAa,cAAc,QAAS,CAAC,SAAS,KAAK,EAAG;AACpE,UAAM,MAAM,KAAK,KAAK,CAAC,SAAS,MAAM,IAAI,MAAM,MAAS;AACzD,QAAI,QAAQ,OAAW,QAAO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@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveExportSchema
|
|
3
|
+
} from "./chunk-OG3OLZ5R.js";
|
|
4
|
+
|
|
5
|
+
// src/lib/exported-recipe-view.ts
|
|
6
|
+
import * as z from "zod/mini";
|
|
7
|
+
function createExportedRecipeView($type, slotSchemas, openSlot) {
|
|
8
|
+
const shape = { $type: z.literal($type) };
|
|
9
|
+
for (const [slot, schema] of Object.entries(slotSchemas)) {
|
|
10
|
+
if (schema !== void 0) {
|
|
11
|
+
const open = () => openSlot(slot);
|
|
12
|
+
const source = resolveExportSchema(schema, open);
|
|
13
|
+
shape[slot] = z.prefault(source.kind === "open" ? open() : source.schema, {});
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return z.strictObject(shape);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
createExportedRecipeView
|
|
21
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/exported-recipe-view.ts"],
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod/mini';\nimport { resolveExportSchema } from '@/lib/export-schema';\n\n/**\n * The view schema the JSON Schema export lists a recipe by, built from the schema of each declared slot.\n *\n * @param $type - The recipe's `$type`\n * @param slotSchemas - The slot schemas its spec declared\n * @param openSlot - The open object a slot is listed by when the export cannot read its schema\n *\n * @remarks\n * The recipe's own validation schema is a Standard Schema of no one library, which the export cannot read. Each slot is\n * read by {@link resolveExportSchema}, and every slot is optional on input and parsed from `{}` when omitted, as the\n * view schema validates it. A Zod slot is exported in full, as its own schema. A slot that exports itself as Standard\n * JSON Schema is exported as what it returns. Any other slot is listed by `openSlot`, so an editor knows the slot\n * exists, can pick its appearance, and does not reject keys it cannot see. The caller closes `appearance` to the\n * slot's declared axes on the Zod and open slots.\n */\nexport function createExportedRecipeView(\n\t$type: string,\n\tslotSchemas: Readonly<Partial<Record<string, unknown>>>,\n\topenSlot: (slot: string) => z.ZodMiniType,\n): z.ZodMiniType {\n\tconst shape: Record<string, z.ZodMiniType> = { $type: z.literal($type) };\n\tfor (const [slot, schema] of Object.entries(slotSchemas)) {\n\t\tif (schema !== undefined) {\n\t\t\tconst open = () => openSlot(slot);\n\t\t\tconst source = resolveExportSchema(schema, open);\n\t\t\tshape[slot] = z.prefault(source.kind === 'open' ? open() : source.schema, {});\n\t\t}\n\t}\n\treturn z.strictObject(shape);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;AAAA,YAAY,OAAO;AAkBZ,SAAS,yBACf,OACA,aACA,UACgB;AAChB,QAAM,QAAuC,EAAE,OAAS,UAAQ,KAAK,EAAE;AACvE,aAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,WAAW,GAAG;AACzD,QAAI,WAAW,QAAW;AACzB,YAAM,OAAO,MAAM,SAAS,IAAI;AAChC,YAAM,SAAS,oBAAoB,QAAQ,IAAI;AAC/C,YAAM,IAAI,IAAM,WAAS,OAAO,SAAS,SAAS,KAAK,IAAI,OAAO,QAAQ,CAAC,CAAC;AAAA,IAC7E;AAAA,EACD;AACA,SAAS,eAAa,KAAK;AAC5B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|