@elytracms/studio 0.0.42 → 0.0.44
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/dist/components/app-views/studio-config.d.ts +12 -0
- package/dist/components/app-views/studio-config.js.map +1 -1
- package/dist/components/assets/asset-detail.js +1 -1
- package/dist/components/assets/asset-detail.js.map +1 -1
- package/dist/components/assets/assets-collection-view-source.d.ts +13 -1
- package/dist/components/assets/assets-collection-view-source.js +42 -51
- package/dist/components/assets/assets-collection-view-source.js.map +1 -1
- package/dist/components/assets/assets-module.js +19 -6
- package/dist/components/assets/assets-module.js.map +1 -1
- package/dist/components/assets/assets-store.d.ts +2 -1
- package/dist/components/assets/assets-store.js +4 -8
- package/dist/components/assets/assets-store.js.map +1 -1
- package/dist/components/assets/assets-view-preference.d.ts +0 -8
- package/dist/components/assets/assets-view-preference.js +12 -13
- package/dist/components/assets/assets-view-preference.js.map +1 -1
- package/dist/components/auth-context.d.ts +2 -1
- package/dist/components/auth-context.js +6 -8
- package/dist/components/auth-context.js.map +1 -1
- package/dist/components/builder/builder-store.d.ts +2 -2
- package/dist/components/builder/builder-store.js +4 -8
- package/dist/components/builder/builder-store.js.map +1 -1
- package/dist/components/cms/bulk-actions.js +2 -1
- package/dist/components/cms/bulk-actions.js.map +1 -1
- package/dist/components/cms/cell-edit.js +2 -1
- package/dist/components/cms/cell-edit.js.map +1 -1
- package/dist/components/cms/cms-composition-validators.d.ts +25 -0
- package/dist/components/cms/cms-composition-validators.js +75 -0
- package/dist/components/cms/cms-composition-validators.js.map +1 -0
- package/dist/components/cms/cms-labels.d.ts +15 -0
- package/dist/components/cms/cms-labels.js +27 -0
- package/dist/components/cms/cms-labels.js.map +1 -0
- package/dist/components/cms/cms-store.d.ts +23 -10
- package/dist/components/cms/cms-store.js +87 -165
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/collection-table.js +1 -1
- package/dist/components/cms/collection-table.js.map +1 -1
- package/dist/components/cms/detail-editor.js +111 -348
- package/dist/components/cms/detail-editor.js.map +1 -1
- package/dist/components/cms/discard-draft.d.ts +18 -0
- package/dist/components/cms/discard-draft.js +18 -0
- package/dist/components/cms/discard-draft.js.map +1 -1
- package/dist/components/cms/document-editor-context.d.ts +2 -1
- package/dist/components/cms/document-editor-context.js +4 -9
- package/dist/components/cms/document-editor-context.js.map +1 -1
- package/dist/components/cms/document-ref-utils.d.ts +33 -0
- package/dist/components/cms/document-ref-utils.js +47 -0
- package/dist/components/cms/document-ref-utils.js.map +1 -0
- package/dist/components/cms/document-staging.d.ts +8 -3
- package/dist/components/cms/document-staging.js +81 -21
- package/dist/components/cms/document-staging.js.map +1 -1
- package/dist/components/cms/field-control.js +1 -1
- package/dist/components/cms/field-control.js.map +1 -1
- package/dist/components/cms/issues-pane.js +1 -1
- package/dist/components/cms/issues-pane.js.map +1 -1
- package/dist/components/cms/rich-text/block-commands.d.ts +36 -0
- package/dist/components/cms/rich-text/block-commands.js +47 -0
- package/dist/components/cms/rich-text/block-commands.js.map +1 -0
- package/dist/components/cms/rich-text/slash-command.js +25 -8
- package/dist/components/cms/rich-text/slash-command.js.map +1 -1
- package/dist/components/cms/rich-text/toolbar.js +3 -2
- package/dist/components/cms/rich-text/toolbar.js.map +1 -1
- package/dist/components/cms/use-compare-selection.d.ts +27 -0
- package/dist/components/cms/use-compare-selection.js +29 -0
- package/dist/components/cms/use-compare-selection.js.map +1 -0
- package/dist/components/cms/use-discard-controller.d.ts +44 -0
- package/dist/components/cms/use-discard-controller.js +51 -0
- package/dist/components/cms/use-discard-controller.js.map +1 -0
- package/dist/components/cms/use-embed-inspector-host.d.ts +12 -0
- package/dist/components/cms/use-embed-inspector-host.js +17 -0
- package/dist/components/cms/use-embed-inspector-host.js.map +1 -0
- package/dist/components/cms/use-field-focus.d.ts +38 -0
- package/dist/components/cms/use-field-focus.js +70 -0
- package/dist/components/cms/use-field-focus.js.map +1 -0
- package/dist/components/cms/use-live-url.d.ts +41 -0
- package/dist/components/cms/use-live-url.js +55 -0
- package/dist/components/cms/use-live-url.js.map +1 -0
- package/dist/components/cms/use-publish-controller.d.ts +49 -0
- package/dist/components/cms/use-publish-controller.js +102 -0
- package/dist/components/cms/use-publish-controller.js.map +1 -0
- package/dist/components/cms/use-published-perspective.d.ts +67 -0
- package/dist/components/cms/use-published-perspective.js +67 -0
- package/dist/components/cms/use-published-perspective.js.map +1 -0
- package/dist/components/cms/use-restore-version.d.ts +57 -0
- package/dist/components/cms/use-restore-version.js +66 -0
- package/dist/components/cms/use-restore-version.js.map +1 -0
- package/dist/components/cms/use-save-mode.d.ts +35 -0
- package/dist/components/cms/use-save-mode.js +54 -0
- package/dist/components/cms/use-save-mode.js.map +1 -0
- package/dist/components/cms/version-compare.js +14 -17
- package/dist/components/cms/version-compare.js.map +1 -1
- package/dist/components/cms/versions-model.d.ts +31 -0
- package/dist/components/cms/versions-model.js +30 -0
- package/dist/components/cms/versions-model.js.map +1 -1
- package/dist/components/cms/versions-pane.js +21 -19
- package/dist/components/cms/versions-pane.js.map +1 -1
- package/dist/components/cms/view-bar.js +9 -6
- package/dist/components/cms/view-bar.js.map +1 -1
- package/dist/components/collab/collab-context.d.ts +2 -1
- package/dist/components/collab/collab-context.js +4 -8
- package/dist/components/collab/collab-context.js.map +1 -1
- package/dist/components/collection-view/collection-view-context.d.ts +9 -1
- package/dist/components/collection-view/collection-view-context.js +4 -9
- package/dist/components/collection-view/collection-view-context.js.map +1 -1
- package/dist/components/components/component-detail.js +2 -5
- package/dist/components/components/component-detail.js.map +1 -1
- package/dist/components/components/component-preview.js +8 -4
- package/dist/components/components/component-preview.js.map +1 -1
- package/dist/components/components/registry-browser.js +24 -5
- package/dist/components/components/registry-browser.js.map +1 -1
- package/dist/components/components/transfer-dialog.d.ts +21 -6
- package/dist/components/components/transfer-dialog.js +120 -31
- package/dist/components/components/transfer-dialog.js.map +1 -1
- package/dist/components/components/transfer.d.ts +74 -8
- package/dist/components/components/transfer.js +87 -2
- package/dist/components/components/transfer.js.map +1 -1
- package/dist/components/delivery-health-banner.d.ts +12 -6
- package/dist/components/delivery-health-banner.js +27 -29
- package/dist/components/delivery-health-banner.js.map +1 -1
- package/dist/components/dev-login-badge.d.ts +0 -2
- package/dist/components/dev-login-badge.js +1 -3
- package/dist/components/dev-login-badge.js.map +1 -1
- package/dist/components/playground-badge.d.ts +0 -2
- package/dist/components/playground-badge.js +0 -2
- package/dist/components/playground-badge.js.map +1 -1
- package/dist/components/project-list.js +2 -6
- package/dist/components/project-list.js.map +1 -1
- package/dist/components/project-session.d.ts +6 -2
- package/dist/components/project-session.js +32 -83
- package/dist/components/project-session.js.map +1 -1
- package/dist/components/project-switcher.js +2 -6
- package/dist/components/project-switcher.js.map +1 -1
- package/dist/components/rail-store-status.d.ts +7 -5
- package/dist/components/rail-store-status.js +12 -9
- package/dist/components/rail-store-status.js.map +1 -1
- package/dist/components/rail-view-source.d.ts +111 -0
- package/dist/components/rail-view-source.js +139 -0
- package/dist/components/rail-view-source.js.map +1 -0
- package/dist/components/redirects/redirects-collection-view-source.d.ts +13 -1
- package/dist/components/redirects/redirects-collection-view-source.js +42 -70
- package/dist/components/redirects/redirects-collection-view-source.js.map +1 -1
- package/dist/components/redirects/redirects-store.d.ts +2 -1
- package/dist/components/redirects/redirects-store.js +4 -8
- package/dist/components/redirects/redirects-store.js.map +1 -1
- package/dist/components/section-state.d.ts +12 -3
- package/dist/components/section-state.js +8 -4
- package/dist/components/section-state.js.map +1 -1
- package/dist/components/studio-context.d.ts +2 -1
- package/dist/components/studio-context.js +4 -8
- package/dist/components/studio-context.js.map +1 -1
- package/dist/components/studio-shell.js +1 -1
- package/dist/components/studio-shell.js.map +1 -1
- package/dist/components/theme-context.d.ts +2 -1
- package/dist/components/theme-context.js +4 -8
- package/dist/components/theme-context.js.map +1 -1
- package/dist/components/use-hydration-phase.d.ts +65 -0
- package/dist/components/use-hydration-phase.js +64 -0
- package/dist/components/use-hydration-phase.js.map +1 -0
- package/dist/components/users/users-collection-view-source.d.ts +13 -1
- package/dist/components/users/users-collection-view-source.js +60 -79
- package/dist/components/users/users-collection-view-source.js.map +1 -1
- package/dist/components/users/users-store.d.ts +2 -1
- package/dist/components/users/users-store.js +4 -8
- package/dist/components/users/users-store.js.map +1 -1
- package/dist/components/workspace-projects.d.ts +14 -0
- package/dist/components/workspace-projects.js +21 -0
- package/dist/components/workspace-projects.js.map +1 -1
- package/dist/lib/ai/anthropic-provider.d.ts +29 -0
- package/dist/lib/ai/anthropic-provider.js +59 -0
- package/dist/lib/ai/anthropic-provider.js.map +1 -0
- package/dist/lib/ai/apply-content.d.ts +9 -0
- package/dist/lib/ai/apply-content.js +170 -0
- package/dist/lib/ai/apply-content.js.map +1 -0
- package/dist/lib/ai/config.d.ts +58 -0
- package/dist/lib/ai/config.js +134 -0
- package/dist/lib/ai/config.js.map +1 -0
- package/dist/lib/ai/fake-provider.d.ts +34 -0
- package/dist/lib/ai/fake-provider.js +31 -0
- package/dist/lib/ai/fake-provider.js.map +1 -0
- package/dist/lib/ai/index.d.ts +22 -0
- package/dist/lib/ai/index.js +23 -0
- package/dist/lib/ai/index.js.map +1 -0
- package/dist/lib/ai/knowledge.d.ts +39 -0
- package/dist/lib/ai/knowledge.js +60 -0
- package/dist/lib/ai/knowledge.js.map +1 -0
- package/dist/lib/ai/provenance.d.ts +20 -0
- package/dist/lib/ai/provenance.js +15 -0
- package/dist/lib/ai/provenance.js.map +1 -0
- package/dist/lib/ai/route.d.ts +24 -0
- package/dist/lib/ai/route.js +90 -0
- package/dist/lib/ai/route.js.map +1 -0
- package/dist/lib/ai/shape.d.ts +35 -0
- package/dist/lib/ai/shape.js +113 -0
- package/dist/lib/ai/shape.js.map +1 -0
- package/dist/lib/ai/types.d.ts +227 -0
- package/dist/lib/ai/types.js +2 -0
- package/dist/lib/ai/types.js.map +1 -0
- package/dist/lib/data/data-store.d.ts +2 -1
- package/dist/lib/data/data-store.js +4 -8
- package/dist/lib/data/data-store.js.map +1 -1
- package/dist/lib/delivery/instant-publish.d.ts +9 -13
- package/dist/lib/delivery/instant-publish.js +0 -7
- package/dist/lib/delivery/instant-publish.js.map +1 -1
- package/dist/lib/diff-view-preference.js +4 -4
- package/dist/lib/diff-view-preference.js.map +1 -1
- package/dist/lib/i18n/messages.en.js +5 -2
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/local-preference.d.ts +37 -0
- package/dist/lib/local-preference.js +36 -0
- package/dist/lib/local-preference.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.d.ts +3 -1
- package/dist/lib/persistence/convex-adapter.js +20 -0
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/rail.js +7 -6
- package/dist/lib/rail.js.map +1 -1
- package/dist/lib/required-context.d.ts +24 -0
- package/dist/lib/required-context.js +28 -0
- package/dist/lib/required-context.js.map +1 -0
- package/dist/lib/theme.js +11 -4
- package/dist/lib/theme.js.map +1 -1
- package/dist/lib/workspace/index.d.ts +9 -0
- package/dist/lib/workspace/index.js +11 -0
- package/dist/lib/workspace/index.js.map +1 -1
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -1
- package/dist/ui/segmented-control.d.ts +46 -0
- package/dist/ui/segmented-control.js +13 -0
- package/dist/ui/segmented-control.js.map +1 -0
- package/package.json +8 -2
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Target-shape derivation for `applyContentWithShape` (EC-331).
|
|
3
|
+
*
|
|
4
|
+
* Reuses the existing collection→JSON-Schema derivation (`collectionJsonSchema`,
|
|
5
|
+
* cms-core) rather than writing a new one, then applies the three leashes the AI
|
|
6
|
+
* engine adds on top:
|
|
7
|
+
*
|
|
8
|
+
* - `ai.exclude` fields are removed entirely (the model never sees them → cannot
|
|
9
|
+
* write them).
|
|
10
|
+
* - relation fields become an ENUM over the provided candidate ids (or are omitted
|
|
11
|
+
* when no candidates exist) — so a hallucinated relation id is not representable
|
|
12
|
+
* as valid structured output.
|
|
13
|
+
* - rich-text fields are emitted in the `{ version, doc }` ProseMirror storage shape
|
|
14
|
+
* (the `allow` leash on embeds is enforced later by `validateRichTextEmbeds`).
|
|
15
|
+
*
|
|
16
|
+
* Localized fields stay flat in the shape (the model authors one locale at a time);
|
|
17
|
+
* the engine routes their values under `localized[locale]`.
|
|
18
|
+
*/
|
|
19
|
+
import { collectionJsonSchema, resolveLabel } from '@elytracms/core/cms-core';
|
|
20
|
+
/** The rich-text `{ version, doc }` storage envelope, as a JSON Schema. */
|
|
21
|
+
function richTextEnvelopeSchema() {
|
|
22
|
+
return {
|
|
23
|
+
type: 'object',
|
|
24
|
+
description: 'Rich text in the ProseMirror storage shape: { version, doc: { type: "doc", content: [...] } }.',
|
|
25
|
+
properties: {
|
|
26
|
+
version: { type: 'number' },
|
|
27
|
+
doc: {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
type: { type: 'string', const: 'doc' },
|
|
31
|
+
content: { type: 'array', items: { type: 'object' } },
|
|
32
|
+
},
|
|
33
|
+
required: ['type', 'content'],
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
required: ['version', 'doc'],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** A field's model-facing description: resolved label + optional `ai.hint`. */
|
|
40
|
+
function describe(field, locale) {
|
|
41
|
+
const label = resolveLabel(field.form?.label, locale) ?? field.name;
|
|
42
|
+
const hint = field.ai?.hint;
|
|
43
|
+
const parts = [label, hint].filter((p) => typeof p === 'string' && p.length > 0);
|
|
44
|
+
return parts.length > 0 ? parts.join(' — ') : undefined;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Build the leash-aware target shape from a collection + candidates. Deterministic;
|
|
48
|
+
* never throws. Reuses `collectionJsonSchema` as the base, then rewrites relations /
|
|
49
|
+
* rich text and strips excluded fields.
|
|
50
|
+
*/
|
|
51
|
+
export function buildTargetShape(input) {
|
|
52
|
+
const base = collectionJsonSchema(input.collection);
|
|
53
|
+
const properties = {
|
|
54
|
+
...(base.properties ?? {}),
|
|
55
|
+
};
|
|
56
|
+
const excluded = [];
|
|
57
|
+
const localizedFields = [];
|
|
58
|
+
const relationFields = [];
|
|
59
|
+
for (const field of input.collection.fields) {
|
|
60
|
+
if (field.localized)
|
|
61
|
+
localizedFields.push(field.name);
|
|
62
|
+
if (field.ai?.exclude) {
|
|
63
|
+
excluded.push(field.name);
|
|
64
|
+
delete properties[field.name];
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (field.type === 'relation') {
|
|
68
|
+
const candidates = input.candidates?.[field.name] ?? [];
|
|
69
|
+
if (candidates.length === 0) {
|
|
70
|
+
// No candidate ids ⇒ omit the field: the model cannot emit a relation value
|
|
71
|
+
// at all, so a hallucinated id is structurally impossible.
|
|
72
|
+
delete properties[field.name];
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const ids = candidates.map((c) => c.id);
|
|
76
|
+
const label = candidates
|
|
77
|
+
.map((c) => (c.label ? `${c.id} (${c.label})` : c.id))
|
|
78
|
+
.join(', ');
|
|
79
|
+
const idSchema = {
|
|
80
|
+
type: 'string',
|
|
81
|
+
enum: ids,
|
|
82
|
+
description: `Choose one of: ${label}`,
|
|
83
|
+
};
|
|
84
|
+
properties[field.name] = field.multiple ? { type: 'array', items: idSchema } : idSchema;
|
|
85
|
+
relationFields.push({
|
|
86
|
+
fieldName: field.name,
|
|
87
|
+
target: field.target,
|
|
88
|
+
multiple: field.multiple,
|
|
89
|
+
candidateIds: ids,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
else if (field.type === 'richText') {
|
|
93
|
+
properties[field.name] = richTextEnvelopeSchema();
|
|
94
|
+
}
|
|
95
|
+
const prop = properties[field.name];
|
|
96
|
+
if (prop) {
|
|
97
|
+
const desc = describe(field, input.locale);
|
|
98
|
+
// Preserve an existing description (e.g. relation enum / rich-text note).
|
|
99
|
+
if (desc && typeof prop.description !== 'string')
|
|
100
|
+
prop.description = desc;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const requiredIn = Array.isArray(base.required) ? base.required : [];
|
|
104
|
+
const required = requiredIn.filter((n) => !excluded.includes(n) && properties[n] !== undefined);
|
|
105
|
+
const schema = {
|
|
106
|
+
type: 'object',
|
|
107
|
+
properties,
|
|
108
|
+
additionalProperties: false,
|
|
109
|
+
...(required.length > 0 ? { required } : {}),
|
|
110
|
+
};
|
|
111
|
+
return { schema, excluded, localizedFields, relationFields };
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=shape.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shape.js","sourceRoot":"","sources":["../../../src/lib/ai/shape.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAkC7E,2EAA2E;AAC3E,SAAS,sBAAsB;IAC7B,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,WAAW,EACT,gGAAgG;QAClG,UAAU,EAAE;YACV,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YAC3B,GAAG,EAAE;gBACH,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACV,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE;oBACtC,OAAO,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE;iBACtD;gBACD,QAAQ,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC;aAC9B;SACF;QACD,QAAQ,EAAE,CAAC,SAAS,EAAE,KAAK,CAAC;KAC7B,CAAA;AACH,CAAC;AAED,+EAA+E;AAC/E,SAAS,QAAQ,CAAC,KAAe,EAAE,MAAe;IAChD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK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CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QACnC,IAAI,IAAI,EAAE,CAAC;YACT,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;YAC1C,0EAA0E;YAC1E,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,WAAW,KAAK,QAAQ;gBAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAA;QAC3E,CAAC;IACH,CAAC;IAED,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,IAAI,CAAC,QAAqB,CAAC,CAAC,CAAC,EAAE,CAAA;IAClF,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAA;IAE/F,MAAM,MAAM,GAAe;QACzB,IAAI,EAAE,QAAQ;QACd,UAAU;QACV,oBAAoB,EAAE,KAAK;QAC3B,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7C,CAAA;IACD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,EAAE,cAAc,EAAE,CAAA;AAC9D,CAAC","sourcesContent":["/**\n * Target-shape derivation for `applyContentWithShape` (EC-331).\n *\n * Reuses the existing collection→JSON-Schema derivation (`collectionJsonSchema`,\n * cms-core) rather than writing a new one, then applies the three leashes the AI\n * engine adds on top:\n *\n * - `ai.exclude` fields are removed entirely (the model never sees them → cannot\n * write them).\n * - relation fields become an ENUM over the provided candidate ids (or are omitted\n * when no candidates exist) — so a hallucinated relation id is not representable\n * as valid structured output.\n * - rich-text fields are emitted in the `{ version, doc }` ProseMirror storage shape\n * (the `allow` leash on embeds is enforced later by `validateRichTextEmbeds`).\n *\n * Localized fields stay flat in the shape (the model authors one locale at a time);\n * the engine routes their values under `localized[locale]`.\n */\nimport { collectionJsonSchema, resolveLabel } from '@elytracms/core/cms-core'\nimport type { CollectionDef, FieldDef, JsonSchema } from '@elytracms/core/cms-core'\nimport type { RelationCandidates } from './types'\n\n/** A relation field's resolved candidate set — how the engine maps ids → reference envelopes. */\nexport interface TargetRelationField {\n fieldName: string\n /** The relation's target collection id. */\n target: string\n multiple: boolean\n /** The allowed candidate ids (the enum the model chose from). */\n candidateIds: string[]\n}\n\n/** The derived target shape + the metadata the engine needs to post-process the output. */\nexport interface TargetShape {\n /** The JSON Schema the structured output must satisfy. */\n schema: JsonSchema\n /** Field names removed by `ai.exclude` (untouchable). */\n excluded: string[]\n /** Field names whose values route under `localized[locale]`. */\n localizedFields: string[]\n /** Relation fields with their candidate enums. */\n relationFields: TargetRelationField[]\n}\n\nexport interface BuildTargetShapeInput {\n collection: CollectionDef\n /** Relation candidate ids by field — a relation field with none is omitted from the shape. */\n candidates?: RelationCandidates\n /** UI locale for resolving field labels into descriptions. */\n locale?: string\n}\n\n/** The rich-text `{ version, doc }` storage envelope, as a JSON Schema. */\nfunction richTextEnvelopeSchema(): JsonSchema {\n return {\n type: 'object',\n description:\n 'Rich text in the ProseMirror storage shape: { version, doc: { type: \"doc\", content: [...] } }.',\n properties: {\n version: { type: 'number' },\n doc: {\n type: 'object',\n properties: {\n type: { type: 'string', const: 'doc' },\n content: { type: 'array', items: { type: 'object' } },\n },\n required: ['type', 'content'],\n },\n },\n required: ['version', 'doc'],\n }\n}\n\n/** A field's model-facing description: resolved label + optional `ai.hint`. */\nfunction describe(field: FieldDef, locale?: string): string | undefined {\n const label = resolveLabel(field.form?.label, locale) ?? field.name\n const hint = field.ai?.hint\n const parts = [label, hint].filter((p): p is string => typeof p === 'string' && p.length > 0)\n return parts.length > 0 ? parts.join(' — ') : undefined\n}\n\n/**\n * Build the leash-aware target shape from a collection + candidates. Deterministic;\n * never throws. Reuses `collectionJsonSchema` as the base, then rewrites relations /\n * rich text and strips excluded fields.\n */\nexport function buildTargetShape(input: BuildTargetShapeInput): TargetShape {\n const base = collectionJsonSchema(input.collection)\n const properties: Record<string, JsonSchema> = {\n ...((base.properties as Record<string, JsonSchema>) ?? {}),\n }\n const excluded: string[] = []\n const localizedFields: string[] = []\n const relationFields: TargetRelationField[] = []\n\n for (const field of input.collection.fields) {\n if (field.localized) localizedFields.push(field.name)\n\n if (field.ai?.exclude) {\n excluded.push(field.name)\n delete properties[field.name]\n continue\n }\n\n if (field.type === 'relation') {\n const candidates = input.candidates?.[field.name] ?? []\n if (candidates.length === 0) {\n // No candidate ids ⇒ omit the field: the model cannot emit a relation value\n // at all, so a hallucinated id is structurally impossible.\n delete properties[field.name]\n continue\n }\n const ids = candidates.map((c) => c.id)\n const label = candidates\n .map((c) => (c.label ? `${c.id} (${c.label})` : c.id))\n .join(', ')\n const idSchema: JsonSchema = {\n type: 'string',\n enum: ids,\n description: `Choose one of: ${label}`,\n }\n properties[field.name] = field.multiple ? { type: 'array', items: idSchema } : idSchema\n relationFields.push({\n fieldName: field.name,\n target: field.target,\n multiple: field.multiple,\n candidateIds: ids,\n })\n } else if (field.type === 'richText') {\n properties[field.name] = richTextEnvelopeSchema()\n }\n\n const prop = properties[field.name]\n if (prop) {\n const desc = describe(field, input.locale)\n // Preserve an existing description (e.g. relation enum / rich-text note).\n if (desc && typeof prop.description !== 'string') prop.description = desc\n }\n }\n\n const requiredIn = Array.isArray(base.required) ? (base.required as string[]) : []\n const required = requiredIn.filter((n) => !excluded.includes(n) && properties[n] !== undefined)\n\n const schema: JsonSchema = {\n type: 'object',\n properties,\n additionalProperties: false,\n ...(required.length > 0 ? { required } : {}),\n }\n return { schema, excluded, localizedFields, relationFields }\n}\n"]}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).
|
|
3
|
+
*
|
|
4
|
+
* Pure types only: this module imports nothing at runtime (every import is
|
|
5
|
+
* `import type`), so referencing `StudioAiConfig` from the studio-config type does
|
|
6
|
+
* NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives
|
|
7
|
+
* in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,
|
|
8
|
+
* `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when
|
|
9
|
+
* the `ai` block is configured and the AI subsystem actually boots. The Anthropic
|
|
10
|
+
* provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so
|
|
11
|
+
* even importing this barrel never eagerly loads the SDK.
|
|
12
|
+
*/
|
|
13
|
+
import type { CollectionDef, CollectionRegistry, CmsValidationIssue, FieldValues, JsonSchema, ValidateDocumentOptions } from '@elytracms/core/cms-core';
|
|
14
|
+
import type { ComponentManifest } from '@elytracms/core/component-registry';
|
|
15
|
+
/**
|
|
16
|
+
* The capabilities the engine requires of a provider. Both must be `true` — the
|
|
17
|
+
* capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +
|
|
18
|
+
* structured output are the non-negotiable floor for schema-guaranteed authoring).
|
|
19
|
+
*/
|
|
20
|
+
export interface AiProviderCapabilities {
|
|
21
|
+
/** The provider can call tools (function/tool calling). */
|
|
22
|
+
toolCalling: boolean;
|
|
23
|
+
/** The provider can return schema-constrained structured output. */
|
|
24
|
+
structuredOutput: boolean;
|
|
25
|
+
}
|
|
26
|
+
/** A request for one schema-constrained structured object — the engine's core primitive. */
|
|
27
|
+
export interface GenerateStructuredRequest {
|
|
28
|
+
/** System prompt: rules, injection stance, closed-world constraints. */
|
|
29
|
+
system?: string;
|
|
30
|
+
/** The task prompt plus assembled context (knowledge, existing values, prior issues). */
|
|
31
|
+
prompt: string;
|
|
32
|
+
/** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */
|
|
33
|
+
schema: JsonSchema;
|
|
34
|
+
/** A short name for the schema (some providers surface it as the tool/output name). */
|
|
35
|
+
schemaName?: string;
|
|
36
|
+
/** A one-line description of what the schema represents. */
|
|
37
|
+
schemaDescription?: string;
|
|
38
|
+
}
|
|
39
|
+
/** Token usage a provider may report (best-effort; recorded for soft spend counters). */
|
|
40
|
+
export interface AiUsage {
|
|
41
|
+
inputTokens?: number;
|
|
42
|
+
outputTokens?: number;
|
|
43
|
+
}
|
|
44
|
+
export interface GenerateStructuredResult {
|
|
45
|
+
/** The structured object the provider produced (best-effort match to the request schema). */
|
|
46
|
+
object: unknown;
|
|
47
|
+
usage?: AiUsage;
|
|
48
|
+
}
|
|
49
|
+
/** One chat message the streaming route relays to the provider. */
|
|
50
|
+
export interface AiChatMessage {
|
|
51
|
+
role: 'system' | 'user' | 'assistant';
|
|
52
|
+
content: string;
|
|
53
|
+
}
|
|
54
|
+
/** A streaming chat/completion request the server-route factory forwards to the provider. */
|
|
55
|
+
export interface StreamChatRequest {
|
|
56
|
+
system?: string;
|
|
57
|
+
messages: AiChatMessage[];
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A provider adapter over a tool-calling, structured-output model. Anthropic in
|
|
61
|
+
* production, {@link FakeProvider} (deterministic, keyless) in tests/playground —
|
|
62
|
+
* both implement this identical surface so the whole loop runs without a key.
|
|
63
|
+
*/
|
|
64
|
+
export interface AiProvider {
|
|
65
|
+
/** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */
|
|
66
|
+
readonly id: string;
|
|
67
|
+
/** The model id the provider targets, when fixed; recorded in provenance. */
|
|
68
|
+
readonly model?: string;
|
|
69
|
+
/** The provider's capabilities — validated by the capability gate at config load. */
|
|
70
|
+
capabilities(): AiProviderCapabilities;
|
|
71
|
+
/** Produce a single schema-constrained structured object. */
|
|
72
|
+
generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>;
|
|
73
|
+
/**
|
|
74
|
+
* Stream a chat/completion response as a Web `Response` — the server-route body.
|
|
75
|
+
* Optional: headless callers may only use {@link generateStructured}.
|
|
76
|
+
*/
|
|
77
|
+
streamChat?(request: StreamChatRequest): Promise<Response>;
|
|
78
|
+
}
|
|
79
|
+
/** Soft, advisory limits for the route counter and the engine repair loop. */
|
|
80
|
+
export interface AiLimits {
|
|
81
|
+
/** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */
|
|
82
|
+
maxRequestsPerMinute?: number;
|
|
83
|
+
/** Cap on repair attempts after the first generation (engine default when omitted). */
|
|
84
|
+
maxRepairAttempts?: number;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like
|
|
88
|
+
* `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's
|
|
89
|
+
* ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical
|
|
90
|
+
* path); `enabled: false` is a temporary kill-switch that keeps the config.
|
|
91
|
+
*/
|
|
92
|
+
export interface StudioAiConfig {
|
|
93
|
+
/**
|
|
94
|
+
* Temporary kill-switch. Presence of the whole `ai` block enables the feature;
|
|
95
|
+
* `enabled: false` disables it without removing the config. Omitted ⇒ enabled.
|
|
96
|
+
*/
|
|
97
|
+
enabled?: boolean;
|
|
98
|
+
/** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */
|
|
99
|
+
provider: AiProvider;
|
|
100
|
+
/** Project knowledge sources assembled into the model's context. */
|
|
101
|
+
knowledge?: KnowledgeSource[];
|
|
102
|
+
/** Soft rate / repair limits. */
|
|
103
|
+
limits?: AiLimits;
|
|
104
|
+
}
|
|
105
|
+
/** An inline knowledge literal (markdown prose versioned with the repo). */
|
|
106
|
+
export interface KnowledgeItem {
|
|
107
|
+
title?: string;
|
|
108
|
+
content: string;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is
|
|
112
|
+
* prose held in the DB (data), while the mechanism stays code. Resolved by a
|
|
113
|
+
* caller-supplied collection reader (starter-kit / studio wires it to operations).
|
|
114
|
+
*/
|
|
115
|
+
export interface KnowledgeCollectionSource {
|
|
116
|
+
readonly kind: 'collection';
|
|
117
|
+
/** Collection id whose documents supply editable knowledge prose. */
|
|
118
|
+
readonly collectionId: string;
|
|
119
|
+
/** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */
|
|
120
|
+
readonly field?: string;
|
|
121
|
+
}
|
|
122
|
+
/** An async (or sync) function producing knowledge items at resolve time. */
|
|
123
|
+
export type KnowledgeFn = () => KnowledgeItem | KnowledgeItem[] | Promise<KnowledgeItem | KnowledgeItem[]>;
|
|
124
|
+
/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */
|
|
125
|
+
export type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource;
|
|
126
|
+
/** The assembled knowledge context — a flat, deterministic list of resolved items. */
|
|
127
|
+
export interface ResolvedKnowledge {
|
|
128
|
+
items: KnowledgeItem[];
|
|
129
|
+
}
|
|
130
|
+
/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */
|
|
131
|
+
export type KnowledgeCollectionReader = (source: KnowledgeCollectionSource) => KnowledgeItem[] | Promise<KnowledgeItem[]>;
|
|
132
|
+
/**
|
|
133
|
+
* A relation candidate id (from a `searchDocuments`/tool result). Relation fields may
|
|
134
|
+
* ONLY use ids present here — the target shape emits them as an enum, so a
|
|
135
|
+
* hallucinated id is not even representable as valid structured output.
|
|
136
|
+
*/
|
|
137
|
+
export interface RelationCandidate {
|
|
138
|
+
id: string;
|
|
139
|
+
/** Human label (title) for the model to choose against. */
|
|
140
|
+
label?: string;
|
|
141
|
+
}
|
|
142
|
+
/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */
|
|
143
|
+
export type RelationCandidates = Record<string, RelationCandidate[]>;
|
|
144
|
+
/** The typed draft-values patch the engine emits — applied by the draft-write path. */
|
|
145
|
+
export interface ContentPatch {
|
|
146
|
+
collection: string;
|
|
147
|
+
id: string;
|
|
148
|
+
/** Non-localized field values. */
|
|
149
|
+
values: FieldValues;
|
|
150
|
+
/** Per-locale field values (localized fields, under the target locale). */
|
|
151
|
+
localized?: Record<string, FieldValues>;
|
|
152
|
+
}
|
|
153
|
+
/** Origin marker the draft-write path records so an AI-authored draft is attributable. */
|
|
154
|
+
export interface AiProvenance {
|
|
155
|
+
origin: 'assistant';
|
|
156
|
+
/** Provider id (e.g. `anthropic`, `fake`). */
|
|
157
|
+
provider: string;
|
|
158
|
+
/** Model id, when the provider fixes one. */
|
|
159
|
+
model?: string;
|
|
160
|
+
/** ISO timestamp when the content was generated. */
|
|
161
|
+
at: string;
|
|
162
|
+
}
|
|
163
|
+
export interface ApplyContentInput {
|
|
164
|
+
provider: AiProvider;
|
|
165
|
+
registry: CollectionRegistry;
|
|
166
|
+
collection: CollectionDef;
|
|
167
|
+
/** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */
|
|
168
|
+
documentId: string;
|
|
169
|
+
/** The author's instruction / prompt. */
|
|
170
|
+
instruction: string;
|
|
171
|
+
/** Assembled knowledge context (from `resolveKnowledge`). */
|
|
172
|
+
knowledge?: ResolvedKnowledge;
|
|
173
|
+
/** Component manifests — context for `allow`-leashed richText/blocks fields. */
|
|
174
|
+
components?: readonly ComponentManifest[];
|
|
175
|
+
/** Relation candidate ids by field — the ONLY ids a relation field may use. */
|
|
176
|
+
candidates?: RelationCandidates;
|
|
177
|
+
/** Existing draft values (updates): the model output merges over these before validation. */
|
|
178
|
+
existing?: FieldValues;
|
|
179
|
+
/** Target locale for localized fields (their values land under `localized[locale]`). */
|
|
180
|
+
locale?: string;
|
|
181
|
+
/** Injected rich-text embed leash (studio-wired); enforced when present. */
|
|
182
|
+
validateRichTextEmbeds?: ValidateDocumentOptions['validateRichTextEmbeds'];
|
|
183
|
+
/** Injected blocks composition leash (studio-wired); enforced when present. */
|
|
184
|
+
validateComposition?: ValidateDocumentOptions['validateComposition'];
|
|
185
|
+
/** Document store for relation/asset existence checks (optional). */
|
|
186
|
+
store?: ValidateDocumentOptions['store'];
|
|
187
|
+
/** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */
|
|
188
|
+
maxRepairAttempts?: number;
|
|
189
|
+
}
|
|
190
|
+
/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */
|
|
191
|
+
export type ApplyContentResult = {
|
|
192
|
+
ok: true;
|
|
193
|
+
patch: ContentPatch;
|
|
194
|
+
provenance: AiProvenance;
|
|
195
|
+
/** Total generation attempts made (1 = happy path, >1 = repaired). */
|
|
196
|
+
attempts: number;
|
|
197
|
+
/** Non-error issues surfaced by the accepted document (e.g. warnings). */
|
|
198
|
+
issues: CmsValidationIssue[];
|
|
199
|
+
} | {
|
|
200
|
+
ok: false;
|
|
201
|
+
/** The error-severity issues from the final failed attempt. */
|
|
202
|
+
issues: CmsValidationIssue[];
|
|
203
|
+
attempts: number;
|
|
204
|
+
provenance: AiProvenance;
|
|
205
|
+
};
|
|
206
|
+
/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */
|
|
207
|
+
export interface AiSession {
|
|
208
|
+
/** Authenticated principal id. */
|
|
209
|
+
userId: string;
|
|
210
|
+
[key: string]: unknown;
|
|
211
|
+
}
|
|
212
|
+
export interface AiRouteHandlerOptions {
|
|
213
|
+
/** The provider (holds the host-env key). The route is a thin proxy over it. */
|
|
214
|
+
provider: AiProvider;
|
|
215
|
+
/**
|
|
216
|
+
* Server-side session check (reject anonymous callers). Returns a session for an
|
|
217
|
+
* authenticated caller, `null` otherwise. Wired by the host to its own auth — the
|
|
218
|
+
* route consumes it, never re-implements it.
|
|
219
|
+
*/
|
|
220
|
+
getSession: (request: Request) => AiSession | null | Promise<AiSession | null>;
|
|
221
|
+
/** Soft per-project rate limit (advisory spend guard). */
|
|
222
|
+
limits?: AiLimits;
|
|
223
|
+
/** Derive the per-project rate-bucket key from a request (default: one global bucket). */
|
|
224
|
+
projectKey?: (request: Request) => string;
|
|
225
|
+
}
|
|
226
|
+
/** The mounted route handler: a framework-agnostic Web `Request → Response`. */
|
|
227
|
+
export type AiRouteHandler = (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/ai/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).\n *\n * Pure types only: this module imports nothing at runtime (every import is\n * `import type`), so referencing `StudioAiConfig` from the studio-config type does\n * NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives\n * in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,\n * `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when\n * the `ai` block is configured and the AI subsystem actually boots. The Anthropic\n * provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so\n * even importing this barrel never eagerly loads the SDK.\n */\nimport type {\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n FieldValues,\n JsonSchema,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\n\n// --- Provider seam ----------------------------------------------------------------\n\n/**\n * The capabilities the engine requires of a provider. Both must be `true` — the\n * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +\n * structured output are the non-negotiable floor for schema-guaranteed authoring).\n */\nexport interface AiProviderCapabilities {\n /** The provider can call tools (function/tool calling). */\n toolCalling: boolean\n /** The provider can return schema-constrained structured output. */\n structuredOutput: boolean\n}\n\n/** A request for one schema-constrained structured object — the engine's core primitive. */\nexport interface GenerateStructuredRequest {\n /** System prompt: rules, injection stance, closed-world constraints. */\n system?: string\n /** The task prompt plus assembled context (knowledge, existing values, prior issues). */\n prompt: string\n /** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */\n schema: JsonSchema\n /** A short name for the schema (some providers surface it as the tool/output name). */\n schemaName?: string\n /** A one-line description of what the schema represents. */\n schemaDescription?: string\n}\n\n/** Token usage a provider may report (best-effort; recorded for soft spend counters). */\nexport interface AiUsage {\n inputTokens?: number\n outputTokens?: number\n}\n\nexport interface GenerateStructuredResult {\n /** The structured object the provider produced (best-effort match to the request schema). */\n object: unknown\n usage?: AiUsage\n}\n\n/** One chat message the streaming route relays to the provider. */\nexport interface AiChatMessage {\n role: 'system' | 'user' | 'assistant'\n content: string\n}\n\n/** A streaming chat/completion request the server-route factory forwards to the provider. */\nexport interface StreamChatRequest {\n system?: string\n messages: AiChatMessage[]\n}\n\n/**\n * A provider adapter over a tool-calling, structured-output model. Anthropic in\n * production, {@link FakeProvider} (deterministic, keyless) in tests/playground —\n * both implement this identical surface so the whole loop runs without a key.\n */\nexport interface AiProvider {\n /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */\n readonly id: string\n /** The model id the provider targets, when fixed; recorded in provenance. */\n readonly model?: string\n /** The provider's capabilities — validated by the capability gate at config load. */\n capabilities(): AiProviderCapabilities\n /** Produce a single schema-constrained structured object. */\n generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>\n /**\n * Stream a chat/completion response as a Web `Response` — the server-route body.\n * Optional: headless callers may only use {@link generateStructured}.\n */\n streamChat?(request: StreamChatRequest): Promise<Response>\n}\n\n// --- Config seam ------------------------------------------------------------------\n\n/** Soft, advisory limits for the route counter and the engine repair loop. */\nexport interface AiLimits {\n /** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */\n maxRequestsPerMinute?: number\n /** Cap on repair attempts after the first generation (engine default when omitted). */\n maxRepairAttempts?: number\n}\n\n/**\n * The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like\n * `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's\n * ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical\n * path); `enabled: false` is a temporary kill-switch that keeps the config.\n */\nexport interface StudioAiConfig {\n /**\n * Temporary kill-switch. Presence of the whole `ai` block enables the feature;\n * `enabled: false` disables it without removing the config. Omitted ⇒ enabled.\n */\n enabled?: boolean\n /** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */\n provider: AiProvider\n /** Project knowledge sources assembled into the model's context. */\n knowledge?: KnowledgeSource[]\n /** Soft rate / repair limits. */\n limits?: AiLimits\n}\n\n// --- Knowledge seam ---------------------------------------------------------------\n\n/** An inline knowledge literal (markdown prose versioned with the repo). */\nexport interface KnowledgeItem {\n title?: string\n content: string\n}\n\n/**\n * A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is\n * prose held in the DB (data), while the mechanism stays code. Resolved by a\n * caller-supplied collection reader (starter-kit / studio wires it to operations).\n */\nexport interface KnowledgeCollectionSource {\n readonly kind: 'collection'\n /** Collection id whose documents supply editable knowledge prose. */\n readonly collectionId: string\n /** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */\n readonly field?: string\n}\n\n/** An async (or sync) function producing knowledge items at resolve time. */\nexport type KnowledgeFn = () =>\n | KnowledgeItem\n | KnowledgeItem[]\n | Promise<KnowledgeItem | KnowledgeItem[]>\n\n/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */\nexport type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource\n\n/** The assembled knowledge context — a flat, deterministic list of resolved items. */\nexport interface ResolvedKnowledge {\n items: KnowledgeItem[]\n}\n\n/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */\nexport type KnowledgeCollectionReader = (\n source: KnowledgeCollectionSource,\n) => KnowledgeItem[] | Promise<KnowledgeItem[]>\n\n// --- Engine seam ------------------------------------------------------------------\n\n/**\n * A relation candidate id (from a `searchDocuments`/tool result). Relation fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated id is not even representable as valid structured output.\n */\nexport interface RelationCandidate {\n id: string\n /** Human label (title) for the model to choose against. */\n label?: string\n}\n\n/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type RelationCandidates = Record<string, RelationCandidate[]>\n\n/** The typed draft-values patch the engine emits — applied by the draft-write path. */\nexport interface ContentPatch {\n collection: string\n id: string\n /** Non-localized field values. */\n values: FieldValues\n /** Per-locale field values (localized fields, under the target locale). */\n localized?: Record<string, FieldValues>\n}\n\n/** Origin marker the draft-write path records so an AI-authored draft is attributable. */\nexport interface AiProvenance {\n origin: 'assistant'\n /** Provider id (e.g. `anthropic`, `fake`). */\n provider: string\n /** Model id, when the provider fixes one. */\n model?: string\n /** ISO timestamp when the content was generated. */\n at: string\n}\n\nexport interface ApplyContentInput {\n provider: AiProvider\n registry: CollectionRegistry\n collection: CollectionDef\n /** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */\n documentId: string\n /** The author's instruction / prompt. */\n instruction: string\n /** Assembled knowledge context (from `resolveKnowledge`). */\n knowledge?: ResolvedKnowledge\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Relation candidate ids by field — the ONLY ids a relation field may use. */\n candidates?: RelationCandidates\n /** Existing draft values (updates): the model output merges over these before validation. */\n existing?: FieldValues\n /** Target locale for localized fields (their values land under `localized[locale]`). */\n locale?: string\n /** Injected rich-text embed leash (studio-wired); enforced when present. */\n validateRichTextEmbeds?: ValidateDocumentOptions['validateRichTextEmbeds']\n /** Injected blocks composition leash (studio-wired); enforced when present. */\n validateComposition?: ValidateDocumentOptions['validateComposition']\n /** Document store for relation/asset existence checks (optional). */\n store?: ValidateDocumentOptions['store']\n /** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */\n maxRepairAttempts?: number\n}\n\n/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */\nexport type ApplyContentResult =\n | {\n ok: true\n patch: ContentPatch\n provenance: AiProvenance\n /** Total generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues surfaced by the accepted document (e.g. warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n ok: false\n /** The error-severity issues from the final failed attempt. */\n issues: CmsValidationIssue[]\n attempts: number\n provenance: AiProvenance\n }\n\n// --- Route seam -------------------------------------------------------------------\n\n/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */\nexport interface AiSession {\n /** Authenticated principal id. */\n userId: string\n [key: string]: unknown\n}\n\nexport interface AiRouteHandlerOptions {\n /** The provider (holds the host-env key). The route is a thin proxy over it. */\n provider: AiProvider\n /**\n * Server-side session check (reject anonymous callers). Returns a session for an\n * authenticated caller, `null` otherwise. Wired by the host to its own auth — the\n * route consumes it, never re-implements it.\n */\n getSession: (request: Request) => AiSession | null | Promise<AiSession | null>\n /** Soft per-project rate limit (advisory spend guard). */\n limits?: AiLimits\n /** Derive the per-project rate-bucket key from a request (default: one global bucket). */\n projectKey?: (request: Request) => string\n}\n\n/** The mounted route handler: a framework-agnostic Web `Request → Response`. */\nexport type AiRouteHandler = (request: Request) => Promise<Response>\n"]}
|
|
@@ -78,6 +78,7 @@ export type DataAction = {
|
|
|
78
78
|
* live here and the app's test harness has no DOM to drive effects through.
|
|
79
79
|
*/
|
|
80
80
|
export declare function dataStateReducer(state: DataState, action: DataAction): DataState;
|
|
81
|
+
declare const useData: () => DataStore;
|
|
81
82
|
/**
|
|
82
83
|
* The session's starting state: EMPTY. The studio seeds no sample sources (Oli,
|
|
83
84
|
* 2026-06-19) — real sources arrive from the project's config collections (the
|
|
@@ -94,4 +95,4 @@ export interface DataProviderProps {
|
|
|
94
95
|
projectId?: string;
|
|
95
96
|
}
|
|
96
97
|
export declare function DataProvider({ children, projectId }: DataProviderProps): import("react").JSX.Element;
|
|
97
|
-
export
|
|
98
|
+
export { useData };
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
2
|
+
import { useCallback, useEffect, useMemo, useReducer, useState } from 'react';
|
|
3
3
|
import { SourceRegistry, captureSample, inferSchema, resolveBinding, resolveCondition, tokensForSchema, } from '@elytracms/core/data-binding';
|
|
4
4
|
import { getStudioOperations } from '../operations';
|
|
5
5
|
import { useOperationCache, useOperationQuery } from '@elytracms/studio/lib/query';
|
|
6
|
+
import { createRequiredContext } from '@elytracms/studio/lib/required-context';
|
|
6
7
|
import { STUDIO_SYSTEM_COLLECTION_IDS } from '../operations/session-hydration';
|
|
7
8
|
import { resolveDeploymentCollections } from '../workspace';
|
|
8
9
|
import { hasContentSession } from './collection-content';
|
|
@@ -67,7 +68,7 @@ export function dataStateReducer(state, action) {
|
|
|
67
68
|
return state;
|
|
68
69
|
}
|
|
69
70
|
}
|
|
70
|
-
const DataContext =
|
|
71
|
+
const { Context: DataContext, useRequired: useData } = createRequiredContext('Data');
|
|
71
72
|
/**
|
|
72
73
|
* The session's starting state: EMPTY. The studio seeds no sample sources (Oli,
|
|
73
74
|
* 2026-06-19) — real sources arrive from the project's config collections (the
|
|
@@ -206,10 +207,5 @@ export function DataProvider({ children, projectId }) {
|
|
|
206
207
|
}, [state, persist, persistError]);
|
|
207
208
|
return _jsx(DataContext.Provider, { value: store, children: children });
|
|
208
209
|
}
|
|
209
|
-
export
|
|
210
|
-
const store = useContext(DataContext);
|
|
211
|
-
if (!store)
|
|
212
|
-
throw new Error('useData must be used within a <DataProvider>.');
|
|
213
|
-
return store;
|
|
214
|
-
}
|
|
210
|
+
export { useData };
|
|
215
211
|
//# sourceMappingURL=data-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-store.js","sourceRoot":"","sources":["../../../src/lib/data/data-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAExG,OAAO,EACL,cAAc,EACd,aAAa,EACb,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,eAAe,GAChB,MAAM,8BAA8B,CAAA;AAUrC,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AAEnD,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAClF,OA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IACrB,MAAM,KAAK,GAAG,UAAU,CAAC,WAAW,CAAC,CAAA;IACrC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAA;IAC5E,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n SourceRegistry,\n captureSample,\n inferSchema,\n resolveBinding,\n resolveCondition,\n tokensForSchema,\n} from '@elytracms/core/data-binding'\nimport type {\n BindingResolution,\n ConditionResolution,\n DataSource,\n InferredSchema,\n PayloadStore,\n RepeaterItemContext,\n} from '@elytracms/core/data-binding'\nimport type { BindingReference, Condition, JsonValue } from '@elytracms/core/project-graph'\nimport { getStudioOperations } from '../operations'\nimport type { OperationResult, OperationsClient } from '../operations'\nimport { useOperationCache, useOperationQuery } from '@elytracms/studio/lib/query'\nimport { STUDIO_SYSTEM_COLLECTION_IDS } from '../operations/session-hydration'\nimport { resolveDeploymentCollections } from '../workspace'\nimport { hasContentSession } from './collection-content'\nimport { captureSourceSample, cmsSourceForCollection } from './sample-capture'\nimport { deleteDataSource, loadDataSources, saveDataSource } from './sources-store'\n\n/**\n * The project's live data layer (brief §4.6, §7.5, EC-167). Holds the source\n * registry the Builder's Content tab binds through, plus the captured payloads\n * that drive binding resolution. One uniform model across CMS queries, data\n * providers, and the built-in REST/Convex kinds — resolution, sampling,\n * inference and tokenization treat them all identically.\n *\n * There is no source-authoring UI (EC-167): sources exist because code declared\n * them (registered data providers), the schema implied them (per-collection CMS\n * queries), or an editor flow provisioned them (repeating sections, template\n * pages).\n *\n * Persistence: when mounted with a `projectId`, the store hydrates the\n * project's persisted source records (the `cms-data-sources` system collection,\n * see `sources-store.ts`) over the deterministic playground seeds — persisted\n * wins by id, but never over a source provisioned/removed in THIS session —\n * and every provision/remove writes through `@elytracms/core/operations`. Without a\n * `projectId` (tests, fixtures) the store is pure session state, exactly as\n * before.\n */\nexport interface DataStore {\n sources: DataSource[]\n registry: SourceRegistry\n payloads: PayloadStore\n knownSourceIds: ReadonlySet<string>\n\n getSource: (id: string) => DataSource | undefined\n removeSource: (id: string) => void\n /**\n * Create or replace a source with a known id + config and capture its sample\n * immediately (EC-166/EC-167): repeating sections and template pages\n * provision their per-scope CMS query / provider sources through this.\n */\n provisionSource: (source: DataSource) => void\n\n /**\n * The latest persistence failure in plain language, or `null`. Persistence\n * is best-effort on top of the live session (the canvas keeps working on\n * session state), but a failure is recorded here — visible, never silent.\n */\n persistError: string | null\n\n /** The stable path tokens a source exposes from its inferred schema (EC-085). */\n tokensOf: (id: string) => string[]\n schemaOf: (id: string) => InferredSchema | undefined\n sampleOf: (id: string) => JsonValue | undefined\n\n /** Resolve a binding to a renderer-ready resolution (value/props/condition/issue). */\n resolve: (ref: BindingReference, item?: RepeaterItemContext) => BindingResolution\n /** Resolve a binding to the concrete value the renderer injects (EC-086–089). */\n resolveValue: (ref: BindingReference, item?: RepeaterItemContext) => JsonValue | undefined\n /** Evaluate a condition against the captured payloads (EC-088). */\n resolveCondition: (condition: Condition, item?: RepeaterItemContext) => ConditionResolution\n}\n\nexport interface DataState {\n sources: DataSource[]\n /**\n * Ids provisioned or removed in THIS session. Hydration (which resolves\n * asynchronously) never overrides them — the editor's latest action wins\n * over whatever was persisted before it.\n */\n sessionIds: ReadonlySet<string>\n}\n\nexport type DataAction =\n | { type: 'remove'; id: string }\n | { type: 'provision'; source: DataSource }\n /** Merge the project's persisted source records in (persisted wins over seeds). */\n | { type: 'hydrate'; sources: DataSource[] }\n\nfunction upsert(sources: DataSource[], source: DataSource): DataSource[] {\n const exists = sources.some((s) => s.id === source.id)\n return exists ? sources.map((s) => (s.id === source.id ? source : s)) : [...sources, source]\n}\n\n/**\n * A persisted record hydrates as-is when it carries its captured sample;\n * otherwise recapture. Exception (EC-177 gap 1): with a hydrated content\n * session configured (Convex mode), CMS sources ALWAYS recapture by replaying\n * their stored query over the live documents — a sample captured by an earlier\n * session may carry stale (or fixture-derived) entries.\n */\nfunction withSample(source: DataSource): DataSource {\n if (source.kind === 'cms' && hasContentSession()) {\n const sample = captureSourceSample(source)\n return sample !== undefined ? captureSample(source, sample) : source\n }\n if (source.sample !== undefined) return source\n // No persisted sample: try an honest capture (a provider runs; anything the\n // studio can't fetch returns undefined) — never fabricate.\n const sample = captureSourceSample(source)\n return sample !== undefined ? captureSample(source, sample) : source\n}\n\n/**\n * The store's reducer, exported because hydration/session-precedence semantics\n * live here and the app's test harness has no DOM to drive effects through.\n */\nexport function dataStateReducer(state: DataState, action: DataAction): DataState {\n switch (action.type) {\n case 'remove':\n return {\n ...state,\n sources: state.sources.filter((s) => s.id !== action.id),\n sessionIds: new Set([...state.sessionIds, action.id]),\n }\n case 'provision': {\n // Upsert by id; attach a sample only if one can be captured honestly (a\n // provider run, or live CMS content) — otherwise the source carries none.\n const sample = captureSourceSample(action.source)\n const provisioned = sample !== undefined ? captureSample(action.source, sample) : action.source\n return {\n ...state,\n sources: upsert(state.sources, provisioned),\n sessionIds: new Set([...state.sessionIds, provisioned.id]),\n }\n }\n case 'hydrate': {\n let sources = state.sources\n for (const source of action.sources) {\n if (state.sessionIds.has(source.id)) continue // this session already decided\n sources = upsert(sources, withSample(source))\n }\n return sources === state.sources ? state : { ...state, sources }\n }\n default:\n return state\n }\n}\n\nconst DataContext = createContext<DataStore | null>(null)\n\n/**\n * The session's starting state: EMPTY. The studio seeds no sample sources (Oli,\n * 2026-06-19) — real sources arrive from the project's config collections (the\n * hydrate effect, Convex mode) or are added by the author. Nothing is faked.\n */\nexport function initialDataState(): DataState {\n return { sources: [], sessionIds: new Set() }\n}\n\nexport interface DataProviderProps {\n children: ReactNode\n /**\n * When set, the store hydrates from and persists to this project's\n * `cms-data-sources` system collection (through `@elytracms/core/operations`).\n * Without it the store is pure session state (tests, fixtures).\n */\n projectId?: string\n}\n\nexport function DataProvider({ children, projectId }: DataProviderProps) {\n const [state, dispatch] = useReducer(dataStateReducer, undefined, initialDataState)\n const [persistError, setPersistError] = useState<string | null>(null)\n\n // EC-192: surface every config-driven content collection as a pickable CMS\n // source, so the binding/condition pickers list what actually exists — the\n // same collection set the CMS uses (`resolveDeploymentCollections`) — rather\n // than only the demo fixture sources. Merged additively (the `hydrate` upsert\n // skips session-decided ids and recaptures live samples in Convex mode); studio\n // SYSTEM collections (routes/redirects/saved views/data sources) are excluded.\n useEffect(() => {\n if (projectId === undefined) return\n const collections = resolveDeploymentCollections().filter(\n (collection) => !STUDIO_SYSTEM_COLLECTION_IDS.has(collection.id),\n )\n if (collections.length === 0) return\n dispatch({ type: 'hydrate', sources: collections.map(cmsSourceForCollection) })\n }, [projectId])\n\n // Hydrate the project's persisted sources through the one operations-backed\n // query cache (EC-308/AD-17). Sources provisioned by other sessions on the\n // same project show up here; the playground seeds stay for everything not\n // persisted. The reducer's `hydrate` keeps session precedence — a source\n // provisioned/removed in THIS session always wins over the hydrated list.\n const cache = useOperationCache()\n const sourcesQuery = useOperationQuery<DataSource[]>({\n queryKey: ['dataSources', projectId ?? '∅'],\n loader: async (operations) => {\n const result = await loadDataSources(operations, projectId as string)\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n },\n enabled: projectId !== undefined,\n })\n const hydratedSources = sourcesQuery.data\n useEffect(() => {\n if (hydratedSources) dispatch({ type: 'hydrate', sources: hydratedSources })\n }, [hydratedSources])\n const sourcesError = sourcesQuery.isError ? sourcesQuery.error : null\n useEffect(() => {\n if (sourcesError)\n setPersistError(sourcesError instanceof Error ? sourcesError.message : 'Loading data sources failed.')\n }, [sourcesError])\n\n // Best-effort persistence on top of the live session: the canvas keeps\n // working on session state; a failed write surfaces via `persistError`. On a\n // confirmed write, invalidate the hydration query so a later remount\n // re-hydrates the provisioned/removed source rather than a stale list.\n const persist = useCallback(\n (write: (operations: OperationsClient, projectId: string) => Promise<OperationResult<void>>) => {\n if (projectId === undefined) return\n void getStudioOperations()\n .then(({ operations }) => write(operations, projectId))\n .then((result) => {\n if (!result.ok) {\n setPersistError(result.error.message)\n return\n }\n void cache.invalidate(['dataSources', projectId])\n })\n .catch((error: unknown) => {\n setPersistError(error instanceof Error ? error.message : 'Saving the data source failed.')\n })\n },\n [projectId, cache],\n )\n\n const store = useMemo<DataStore>(() => {\n const registry = SourceRegistry.from(state.sources)\n const payloads: Record<string, JsonValue> = {}\n for (const source of state.sources) {\n if (source.sample !== undefined) payloads[source.id] = source.sample\n }\n const knownSourceIds = registry.knownSourceIds()\n const ctx = { payloads, registry }\n\n const getSource = (id: string) => registry.get(id)\n const resolve = (ref: BindingReference, item?: RepeaterItemContext) =>\n resolveBinding(ref, ctx, item)\n\n return {\n sources: state.sources,\n registry,\n payloads,\n knownSourceIds,\n getSource,\n removeSource: (id) => {\n dispatch({ type: 'remove', id })\n persist((operations, pid) => deleteDataSource(operations, pid, id))\n },\n provisionSource: (source) => {\n dispatch({ type: 'provision', source })\n // Persist exactly what the session resolves: the source plus any sample\n // that can be captured honestly (a provider run / live CMS content) —\n // never a fabricated one. Matches the `provision` reducer.\n const sample = captureSourceSample(source)\n const provisioned = sample !== undefined ? captureSample(source, sample) : source\n persist((operations, pid) => saveDataSource(operations, pid, provisioned))\n },\n persistError,\n tokensOf: (id) => {\n const schema = getSource(id)?.schema\n return schema ? tokensForSchema(schema) : []\n },\n schemaOf: (id) => {\n const source = getSource(id)\n if (source?.schema) return source.schema\n if (source?.sample !== undefined) return inferSchema(source.sample)\n return undefined\n },\n sampleOf: (id) => getSource(id)?.sample,\n resolve,\n resolveValue: (ref, item) => {\n const r = resolve(ref, item)\n switch (r.kind) {\n case 'value':\n return r.value\n case 'props':\n return r.props\n case 'condition':\n return r.pass\n case 'issue':\n return undefined\n default: {\n const never: never = r\n return never\n }\n }\n },\n resolveCondition: (condition, item) => resolveCondition(condition, ctx, item),\n }\n }, [state, persist, persistError])\n\n return <DataContext.Provider value={store}>{children}</DataContext.Provider>\n}\n\nexport function useData(): DataStore {\n const store = useContext(DataContext)\n if (!store) throw new Error('useData must be used within a <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;oBAChB,KAAK,WAAW;wBACd,OAAO,CAAC,CAAC,IAAI,CAAA;oBACf,KAAK,OAAO;wBACV,OAAO,SAAS,CAAA;oBAClB,OAAO,CAAC,CAAC,CAAC;wBACR,MAAM,KAAK,GAAU,CAAC,CAAA;wBACtB,OAAO,KAAK,CAAA;oBACd,CAAC;gBACH,CAAC;YACH,CAAC;YACD,gBAAgB,EAAE,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC;SAC9E,CAAA;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAA;IAElC,OAAO,KAAC,WAAW,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAAwB,CAAA;AAC9E,CAAC;AAED,OAAO,EAAE,OAAO,EAAE,CAAA","sourcesContent":["import { useCallback, useEffect, useMemo, useReducer, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n SourceRegistry,\n captureSample,\n inferSchema,\n resolveBinding,\n resolveCondition,\n tokensForSchema,\n} from '@elytracms/core/data-binding'\nimport type {\n BindingResolution,\n ConditionResolution,\n DataSource,\n InferredSchema,\n PayloadStore,\n RepeaterItemContext,\n} from '@elytracms/core/data-binding'\nimport type { BindingReference, Condition, JsonValue } from '@elytracms/core/project-graph'\nimport { getStudioOperations } from '../operations'\nimport type { OperationResult, OperationsClient } from '../operations'\nimport { useOperationCache, useOperationQuery } from '@elytracms/studio/lib/query'\nimport { createRequiredContext } from '@elytracms/studio/lib/required-context'\nimport { STUDIO_SYSTEM_COLLECTION_IDS } from '../operations/session-hydration'\nimport { resolveDeploymentCollections } from '../workspace'\nimport { hasContentSession } from './collection-content'\nimport { captureSourceSample, cmsSourceForCollection } from './sample-capture'\nimport { deleteDataSource, loadDataSources, saveDataSource } from './sources-store'\n\n/**\n * The project's live data layer (brief §4.6, §7.5, EC-167). Holds the source\n * registry the Builder's Content tab binds through, plus the captured payloads\n * that drive binding resolution. One uniform model across CMS queries, data\n * providers, and the built-in REST/Convex kinds — resolution, sampling,\n * inference and tokenization treat them all identically.\n *\n * There is no source-authoring UI (EC-167): sources exist because code declared\n * them (registered data providers), the schema implied them (per-collection CMS\n * queries), or an editor flow provisioned them (repeating sections, template\n * pages).\n *\n * Persistence: when mounted with a `projectId`, the store hydrates the\n * project's persisted source records (the `cms-data-sources` system collection,\n * see `sources-store.ts`) over the deterministic playground seeds — persisted\n * wins by id, but never over a source provisioned/removed in THIS session —\n * and every provision/remove writes through `@elytracms/core/operations`. Without a\n * `projectId` (tests, fixtures) the store is pure session state, exactly as\n * before.\n */\nexport interface DataStore {\n sources: DataSource[]\n registry: SourceRegistry\n payloads: PayloadStore\n knownSourceIds: ReadonlySet<string>\n\n getSource: (id: string) => DataSource | undefined\n removeSource: (id: string) => void\n /**\n * Create or replace a source with a known id + config and capture its sample\n * immediately (EC-166/EC-167): repeating sections and template pages\n * provision their per-scope CMS query / provider sources through this.\n */\n provisionSource: (source: DataSource) => void\n\n /**\n * The latest persistence failure in plain language, or `null`. Persistence\n * is best-effort on top of the live session (the canvas keeps working on\n * session state), but a failure is recorded here — visible, never silent.\n */\n persistError: string | null\n\n /** The stable path tokens a source exposes from its inferred schema (EC-085). */\n tokensOf: (id: string) => string[]\n schemaOf: (id: string) => InferredSchema | undefined\n sampleOf: (id: string) => JsonValue | undefined\n\n /** Resolve a binding to a renderer-ready resolution (value/props/condition/issue). */\n resolve: (ref: BindingReference, item?: RepeaterItemContext) => BindingResolution\n /** Resolve a binding to the concrete value the renderer injects (EC-086–089). */\n resolveValue: (ref: BindingReference, item?: RepeaterItemContext) => JsonValue | undefined\n /** Evaluate a condition against the captured payloads (EC-088). */\n resolveCondition: (condition: Condition, item?: RepeaterItemContext) => ConditionResolution\n}\n\nexport interface DataState {\n sources: DataSource[]\n /**\n * Ids provisioned or removed in THIS session. Hydration (which resolves\n * asynchronously) never overrides them — the editor's latest action wins\n * over whatever was persisted before it.\n */\n sessionIds: ReadonlySet<string>\n}\n\nexport type DataAction =\n | { type: 'remove'; id: string }\n | { type: 'provision'; source: DataSource }\n /** Merge the project's persisted source records in (persisted wins over seeds). */\n | { type: 'hydrate'; sources: DataSource[] }\n\nfunction upsert(sources: DataSource[], source: DataSource): DataSource[] {\n const exists = sources.some((s) => s.id === source.id)\n return exists ? sources.map((s) => (s.id === source.id ? source : s)) : [...sources, source]\n}\n\n/**\n * A persisted record hydrates as-is when it carries its captured sample;\n * otherwise recapture. Exception (EC-177 gap 1): with a hydrated content\n * session configured (Convex mode), CMS sources ALWAYS recapture by replaying\n * their stored query over the live documents — a sample captured by an earlier\n * session may carry stale (or fixture-derived) entries.\n */\nfunction withSample(source: DataSource): DataSource {\n if (source.kind === 'cms' && hasContentSession()) {\n const sample = captureSourceSample(source)\n return sample !== undefined ? captureSample(source, sample) : source\n }\n if (source.sample !== undefined) return source\n // No persisted sample: try an honest capture (a provider runs; anything the\n // studio can't fetch returns undefined) — never fabricate.\n const sample = captureSourceSample(source)\n return sample !== undefined ? captureSample(source, sample) : source\n}\n\n/**\n * The store's reducer, exported because hydration/session-precedence semantics\n * live here and the app's test harness has no DOM to drive effects through.\n */\nexport function dataStateReducer(state: DataState, action: DataAction): DataState {\n switch (action.type) {\n case 'remove':\n return {\n ...state,\n sources: state.sources.filter((s) => s.id !== action.id),\n sessionIds: new Set([...state.sessionIds, action.id]),\n }\n case 'provision': {\n // Upsert by id; attach a sample only if one can be captured honestly (a\n // provider run, or live CMS content) — otherwise the source carries none.\n const sample = captureSourceSample(action.source)\n const provisioned = sample !== undefined ? captureSample(action.source, sample) : action.source\n return {\n ...state,\n sources: upsert(state.sources, provisioned),\n sessionIds: new Set([...state.sessionIds, provisioned.id]),\n }\n }\n case 'hydrate': {\n let sources = state.sources\n for (const source of action.sources) {\n if (state.sessionIds.has(source.id)) continue // this session already decided\n sources = upsert(sources, withSample(source))\n }\n return sources === state.sources ? state : { ...state, sources }\n }\n default:\n return state\n }\n}\n\nconst { Context: DataContext, useRequired: useData } = createRequiredContext<DataStore>('Data')\n\n/**\n * The session's starting state: EMPTY. The studio seeds no sample sources (Oli,\n * 2026-06-19) — real sources arrive from the project's config collections (the\n * hydrate effect, Convex mode) or are added by the author. Nothing is faked.\n */\nexport function initialDataState(): DataState {\n return { sources: [], sessionIds: new Set() }\n}\n\nexport interface DataProviderProps {\n children: ReactNode\n /**\n * When set, the store hydrates from and persists to this project's\n * `cms-data-sources` system collection (through `@elytracms/core/operations`).\n * Without it the store is pure session state (tests, fixtures).\n */\n projectId?: string\n}\n\nexport function DataProvider({ children, projectId }: DataProviderProps) {\n const [state, dispatch] = useReducer(dataStateReducer, undefined, initialDataState)\n const [persistError, setPersistError] = useState<string | null>(null)\n\n // EC-192: surface every config-driven content collection as a pickable CMS\n // source, so the binding/condition pickers list what actually exists — the\n // same collection set the CMS uses (`resolveDeploymentCollections`) — rather\n // than only the demo fixture sources. Merged additively (the `hydrate` upsert\n // skips session-decided ids and recaptures live samples in Convex mode); studio\n // SYSTEM collections (routes/redirects/saved views/data sources) are excluded.\n useEffect(() => {\n if (projectId === undefined) return\n const collections = resolveDeploymentCollections().filter(\n (collection) => !STUDIO_SYSTEM_COLLECTION_IDS.has(collection.id),\n )\n if (collections.length === 0) return\n dispatch({ type: 'hydrate', sources: collections.map(cmsSourceForCollection) })\n }, [projectId])\n\n // Hydrate the project's persisted sources through the one operations-backed\n // query cache (EC-308/AD-17). Sources provisioned by other sessions on the\n // same project show up here; the playground seeds stay for everything not\n // persisted. The reducer's `hydrate` keeps session precedence — a source\n // provisioned/removed in THIS session always wins over the hydrated list.\n const cache = useOperationCache()\n const sourcesQuery = useOperationQuery<DataSource[]>({\n queryKey: ['dataSources', projectId ?? '∅'],\n loader: async (operations) => {\n const result = await loadDataSources(operations, projectId as string)\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n },\n enabled: projectId !== undefined,\n })\n const hydratedSources = sourcesQuery.data\n useEffect(() => {\n if (hydratedSources) dispatch({ type: 'hydrate', sources: hydratedSources })\n }, [hydratedSources])\n const sourcesError = sourcesQuery.isError ? sourcesQuery.error : null\n useEffect(() => {\n if (sourcesError)\n setPersistError(sourcesError instanceof Error ? sourcesError.message : 'Loading data sources failed.')\n }, [sourcesError])\n\n // Best-effort persistence on top of the live session: the canvas keeps\n // working on session state; a failed write surfaces via `persistError`. On a\n // confirmed write, invalidate the hydration query so a later remount\n // re-hydrates the provisioned/removed source rather than a stale list.\n const persist = useCallback(\n (write: (operations: OperationsClient, projectId: string) => Promise<OperationResult<void>>) => {\n if (projectId === undefined) return\n void getStudioOperations()\n .then(({ operations }) => write(operations, projectId))\n .then((result) => {\n if (!result.ok) {\n setPersistError(result.error.message)\n return\n }\n void cache.invalidate(['dataSources', projectId])\n })\n .catch((error: unknown) => {\n setPersistError(error instanceof Error ? error.message : 'Saving the data source failed.')\n })\n },\n [projectId, cache],\n )\n\n const store = useMemo<DataStore>(() => {\n const registry = SourceRegistry.from(state.sources)\n const payloads: Record<string, JsonValue> = {}\n for (const source of state.sources) {\n if (source.sample !== undefined) payloads[source.id] = source.sample\n }\n const knownSourceIds = registry.knownSourceIds()\n const ctx = { payloads, registry }\n\n const getSource = (id: string) => registry.get(id)\n const resolve = (ref: BindingReference, item?: RepeaterItemContext) =>\n resolveBinding(ref, ctx, item)\n\n return {\n sources: state.sources,\n registry,\n payloads,\n knownSourceIds,\n getSource,\n removeSource: (id) => {\n dispatch({ type: 'remove', id })\n persist((operations, pid) => deleteDataSource(operations, pid, id))\n },\n provisionSource: (source) => {\n dispatch({ type: 'provision', source })\n // Persist exactly what the session resolves: the source plus any sample\n // that can be captured honestly (a provider run / live CMS content) —\n // never a fabricated one. Matches the `provision` reducer.\n const sample = captureSourceSample(source)\n const provisioned = sample !== undefined ? captureSample(source, sample) : source\n persist((operations, pid) => saveDataSource(operations, pid, provisioned))\n },\n persistError,\n tokensOf: (id) => {\n const schema = getSource(id)?.schema\n return schema ? tokensForSchema(schema) : []\n },\n schemaOf: (id) => {\n const source = getSource(id)\n if (source?.schema) return source.schema\n if (source?.sample !== undefined) return inferSchema(source.sample)\n return undefined\n },\n sampleOf: (id) => getSource(id)?.sample,\n resolve,\n resolveValue: (ref, item) => {\n const r = resolve(ref, item)\n switch (r.kind) {\n case 'value':\n return r.value\n case 'props':\n return r.props\n case 'condition':\n return r.pass\n case 'issue':\n return undefined\n default: {\n const never: never = r\n return never\n }\n }\n },\n resolveCondition: (condition, item) => resolveCondition(condition, ctx, item),\n }\n }, [state, persist, persistError])\n\n return <DataContext.Provider value={store}>{children}</DataContext.Provider>\n}\n\nexport { useData }\n"]}
|
|
@@ -1,18 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* EC-268: instant-publish (EC-146) configuration health, studio-side.
|
|
3
|
-
* `delivery
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
2
|
+
* EC-268: instant-publish (EC-146) configuration health, studio-side. Reads
|
|
3
|
+
* through `operations.delivery.config` (EC-329 — the operations seam, not a
|
|
4
|
+
* raw Convex client) to `PersistenceAdapter.delivery`, reporting whether each
|
|
5
|
+
* delivery env var is set (booleans only — never the values); these helpers
|
|
6
|
+
* turn that into the list the health banner shows. Kept pure + React-free so
|
|
7
|
+
* it is unit-testable and reusable (a future `elytra doctor`, EC-259, can
|
|
8
|
+
* format the same status).
|
|
7
9
|
*/
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
projectScope: boolean;
|
|
11
|
-
/** `CANVAS_REVALIDATE_ENDPOINT` — the host route the webhook POSTs to. */
|
|
12
|
-
revalidateEndpoint: boolean;
|
|
13
|
-
/** `CANVAS_REVALIDATE_SECRET` — shared HMAC secret (= host `REVALIDATE_SECRET`). */
|
|
14
|
-
revalidateSecret: boolean;
|
|
15
|
-
}
|
|
10
|
+
import type { DeliveryConfigStatus } from '@elytracms/core/persistence';
|
|
11
|
+
export type { DeliveryConfigStatus };
|
|
16
12
|
/** The pipeline env vars, in setup order, paired with the status key each maps to. */
|
|
17
13
|
export declare const INSTANT_PUBLISH_VARS: readonly [{
|
|
18
14
|
readonly key: "projectScope";
|
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* EC-268: instant-publish (EC-146) configuration health, studio-side. The Convex
|
|
3
|
-
* `delivery:deliveryConfig` query reports whether each delivery env var is set
|
|
4
|
-
* (booleans only — never the values); these helpers turn that into the list the
|
|
5
|
-
* health banner shows. Kept pure + React-free so it is unit-testable and reusable
|
|
6
|
-
* (a future `elytra doctor`, EC-259, can format the same status).
|
|
7
|
-
*/
|
|
8
1
|
/** The pipeline env vars, in setup order, paired with the status key each maps to. */
|
|
9
2
|
export const INSTANT_PUBLISH_VARS = [
|
|
10
3
|
{ key: 'projectScope', env: 'CANVAS_PROJECT_SCOPE' },
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instant-publish.js","sourceRoot":"","sources":["../../../src/lib/delivery/instant-publish.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"instant-publish.js","sourceRoot":"","sources":["../../../src/lib/delivery/instant-publish.ts"],"names":[],"mappings":"AAYA,sFAAsF;AACtF,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,sBAAsB,EAAE;IACpD,EAAE,GAAG,EAAE,oBAAoB,EAAE,GAAG,EAAE,4BAA4B,EAAE;IAChE,EAAE,GAAG,EAAE,kBAAkB,EAAE,GAAG,EAAE,0BAA0B,EAAE;CACsB,CAAA;AAEpF,qFAAqF;AACrF,MAAM,UAAU,yBAAyB,CAAC,MAA4B;IACpE,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;AAC7F,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,0BAA0B,CAAC,MAA4B;IACrE,OAAO,yBAAyB,CAAC,MAAM,CAAC,CAAC,MAAM,KAAK,CAAC,CAAA;AACvD,CAAC","sourcesContent":["/**\n * EC-268: instant-publish (EC-146) configuration health, studio-side. Reads\n * through `operations.delivery.config` (EC-329 — the operations seam, not a\n * raw Convex client) to `PersistenceAdapter.delivery`, reporting whether each\n * delivery env var is set (booleans only — never the values); these helpers\n * turn that into the list the health banner shows. Kept pure + React-free so\n * it is unit-testable and reusable (a future `elytra doctor`, EC-259, can\n * format the same status).\n */\nimport type { DeliveryConfigStatus } from '@elytracms/core/persistence'\nexport type { DeliveryConfigStatus }\n\n/** The pipeline env vars, in setup order, paired with the status key each maps to. */\nexport const INSTANT_PUBLISH_VARS = [\n { key: 'projectScope', env: 'CANVAS_PROJECT_SCOPE' },\n { key: 'revalidateEndpoint', env: 'CANVAS_REVALIDATE_ENDPOINT' },\n { key: 'revalidateSecret', env: 'CANVAS_REVALIDATE_SECRET' },\n] as const satisfies ReadonlyArray<{ key: keyof DeliveryConfigStatus; env: string }>\n\n/** The env var names that are NOT set, in setup order (empty = fully configured). */\nexport function missingInstantPublishVars(status: DeliveryConfigStatus): string[] {\n return INSTANT_PUBLISH_VARS.filter((entry) => !status[entry.key]).map((entry) => entry.env)\n}\n\n/** True when every instant-publish env var is set. */\nexport function isInstantPublishConfigured(status: DeliveryConfigStatus): boolean {\n return missingInstantPublishVars(status).length === 0\n}\n"]}
|
|
@@ -6,16 +6,16 @@
|
|
|
6
6
|
* best-effort instead of a new persistence mechanism. Unavailable storage (SSR,
|
|
7
7
|
* privacy mode) degrades to the default every session — never a crash.
|
|
8
8
|
*/
|
|
9
|
-
import {
|
|
9
|
+
import { createEnumPreference } from './local-preference';
|
|
10
10
|
export const DIFF_VIEW_STORAGE_KEY = 'elytra-version-diff-view';
|
|
11
11
|
export const DEFAULT_DIFF_VIEW_MODE = 'sideBySide';
|
|
12
|
+
const preference = createEnumPreference(DIFF_VIEW_STORAGE_KEY, ['sideBySide', 'unified'], DEFAULT_DIFF_VIEW_MODE);
|
|
12
13
|
/** Read the persisted preference, or the default when unset/unavailable/invalid. */
|
|
13
14
|
export function readDiffViewMode() {
|
|
14
|
-
|
|
15
|
-
return value === 'sideBySide' || value === 'unified' ? value : DEFAULT_DIFF_VIEW_MODE;
|
|
15
|
+
return preference.read();
|
|
16
16
|
}
|
|
17
17
|
/** Persist the preference (best-effort; storage may be unavailable). */
|
|
18
18
|
export function storeDiffViewMode(mode) {
|
|
19
|
-
|
|
19
|
+
preference.store(mode);
|
|
20
20
|
}
|
|
21
21
|
//# sourceMappingURL=diff-view-preference.js.map
|