@elytracms/studio 0.0.13 → 0.0.15
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/convex/cms.ts +8 -22
- package/convex/content.ts +3 -44
- package/convex/delivery.ts +8 -42
- package/convex/functions.ts +17 -2
- package/convex/members.ts +2 -2
- package/convex/referenceMaintenance.ts +4 -73
- package/convex/references.ts +4 -2
- package/convex/revalidate.ts +42 -0
- package/convex/schema.ts +17 -37
- package/convex/sync.ts +10 -42
- package/convex/triggers.ts +57 -0
- package/convex/webhooks.ts +3 -2
- package/dist/components/builder/builder-store.d.ts +85 -39
- package/dist/components/builder/builder-store.js +29 -125
- package/dist/components/builder/builder-store.js.map +1 -1
- package/dist/components/builder/canvas.js +23 -55
- package/dist/components/builder/canvas.js.map +1 -1
- package/dist/components/builder/clipboard-actions.js +3 -3
- package/dist/components/builder/clipboard-actions.js.map +1 -1
- package/dist/components/builder/composition-field-editor.js +13 -23
- package/dist/components/builder/composition-field-editor.js.map +1 -1
- package/dist/components/builder/insert-context.js +1 -1
- package/dist/components/builder/insert-context.js.map +1 -1
- package/dist/components/builder/page-tree.js +3 -4
- package/dist/components/builder/page-tree.js.map +1 -1
- package/dist/components/builder/property-inspector.js +4 -64
- package/dist/components/builder/property-inspector.js.map +1 -1
- package/dist/components/cms/cell.d.ts +0 -4
- package/dist/components/cms/cell.js +1 -5
- package/dist/components/cms/cell.js.map +1 -1
- package/dist/components/cms/cms-store.d.ts +1 -1
- package/dist/components/cms/cms-store.js +4 -9
- 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 +2 -2
- package/dist/components/cms/detail-editor.js.map +1 -1
- package/dist/components/cms/doc-state.d.ts +0 -5
- package/dist/components/cms/doc-state.js +1 -7
- package/dist/components/cms/doc-state.js.map +1 -1
- package/dist/components/cms/editable-cell.js +1 -1
- package/dist/components/cms/editable-cell.js.map +1 -1
- package/dist/components/collab/collab-context.d.ts +6 -14
- package/dist/components/collab/collab-context.js +3 -12
- package/dist/components/collab/collab-context.js.map +1 -1
- package/dist/components/collab/collab-seed.d.ts +7 -19
- package/dist/components/collab/collab-seed.js +9 -31
- package/dist/components/collab/collab-seed.js.map +1 -1
- package/dist/components/components/registry-browser.js +6 -12
- package/dist/components/components/registry-browser.js.map +1 -1
- package/dist/components/guards.d.ts +0 -9
- package/dist/components/guards.js +0 -12
- package/dist/components/guards.js.map +1 -1
- package/dist/components/section-state.d.ts +0 -2
- package/dist/components/section-state.js +0 -9
- package/dist/components/section-state.js.map +1 -1
- package/dist/components/section-surface.d.ts +3 -7
- package/dist/components/section-surface.js +5 -12
- package/dist/components/section-surface.js.map +1 -1
- package/dist/components/sections.d.ts +0 -1
- package/dist/components/sections.js +0 -10
- package/dist/components/sections.js.map +1 -1
- package/dist/components/studio-project-screen.js +13 -14
- package/dist/components/studio-project-screen.js.map +1 -1
- package/dist/components/studio-shell.d.ts +0 -4
- package/dist/components/studio-shell.js +1 -5
- package/dist/components/studio-shell.js.map +1 -1
- package/dist/lib/operations/graph-commands.d.ts +2 -6
- package/dist/lib/operations/graph-commands.js +1 -2
- package/dist/lib/operations/graph-commands.js.map +1 -1
- package/dist/lib/operations/index.d.ts +0 -2
- package/dist/lib/operations/index.js +0 -2
- package/dist/lib/operations/index.js.map +1 -1
- package/dist/lib/operations/session-hydration.d.ts +14 -24
- package/dist/lib/operations/session-hydration.js +15 -34
- package/dist/lib/operations/session-hydration.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.d.ts +1 -3
- package/dist/lib/persistence/convex-adapter.js +1 -154
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/persona/labels.js +0 -2
- package/dist/lib/persona/labels.js.map +1 -1
- package/dist/lib/references/reference-model.d.ts +0 -16
- package/dist/lib/references/reference-model.js +2 -54
- package/dist/lib/references/reference-model.js.map +1 -1
- package/dist/lib/references/references-store.js +3 -4
- package/dist/lib/references/references-store.js.map +1 -1
- package/dist/lib/registry/index.d.ts +0 -16
- package/dist/lib/registry/index.js +0 -15
- package/dist/lib/registry/index.js.map +1 -1
- package/dist/lib/webhooks/tags.js +2 -16
- package/dist/lib/webhooks/tags.js.map +1 -1
- package/package.json +3 -2
- package/convex/graphs.ts +0 -55
- package/convex/publishing.ts +0 -108
|
@@ -31,31 +31,6 @@ export function parseDocumentFieldPath(path) {
|
|
|
31
31
|
}
|
|
32
32
|
return null;
|
|
33
33
|
}
|
|
34
|
-
/**
|
|
35
|
-
* Resolve a graph index path (`root`, then repeated `slots/<slot>/<index>`
|
|
36
|
-
* hops, then a structure suffix) to the node it identifies. Walks the
|
|
37
|
-
* slot/index prefix structurally; a prefix that no longer exists (the graph
|
|
38
|
-
* drifted since indexing) resolves to `null`.
|
|
39
|
-
*/
|
|
40
|
-
export function resolveGraphNodePath(root, path) {
|
|
41
|
-
const tokens = path.split('/');
|
|
42
|
-
if (tokens[0] !== 'root')
|
|
43
|
-
return { node: null, remainder: tokens };
|
|
44
|
-
let node = root;
|
|
45
|
-
let index = 1;
|
|
46
|
-
while (index < tokens.length && tokens[index] === 'slots') {
|
|
47
|
-
const slot = tokens[index + 1];
|
|
48
|
-
const childIndex = Number(tokens[index + 2]);
|
|
49
|
-
const child = slot !== undefined && Number.isInteger(childIndex)
|
|
50
|
-
? node.slots?.[slot]?.[childIndex]
|
|
51
|
-
: undefined;
|
|
52
|
-
if (!child)
|
|
53
|
-
return { node: null, remainder: tokens.slice(index) };
|
|
54
|
-
node = child;
|
|
55
|
-
index += 3;
|
|
56
|
-
}
|
|
57
|
-
return { node, remainder: tokens.slice(index) };
|
|
58
|
-
}
|
|
59
34
|
/**
|
|
60
35
|
* Merge per-variant index records onto one row per logical entry. A
|
|
61
36
|
* draft-only row (`draft && !published`) is the Sanity hidden-draft-reference
|
|
@@ -94,8 +69,6 @@ export const REFERENCE_KIND_LABELS = {
|
|
|
94
69
|
'rich-text-link': 'rich-text link',
|
|
95
70
|
'rich-text-node': 'rich-text node',
|
|
96
71
|
'component-usage': 'component usage',
|
|
97
|
-
'prop-binding': 'prop binding',
|
|
98
|
-
'condition-binding': 'condition binding',
|
|
99
72
|
};
|
|
100
73
|
function fieldLabelOf(collection, fieldName) {
|
|
101
74
|
const field = collection?.fields.find((f) => f.name === fieldName);
|
|
@@ -170,30 +143,6 @@ function describeDocumentSource(context, entry) {
|
|
|
170
143
|
},
|
|
171
144
|
};
|
|
172
145
|
}
|
|
173
|
-
function describeGraphSource(context, entry) {
|
|
174
|
-
const isPage = entry.source.type === 'page';
|
|
175
|
-
// The canonical graph is layouts-only now (EC-187): a `page` source is no
|
|
176
|
-
// longer addressable in the graph (page bodies are CMS documents), so only a
|
|
177
|
-
// layout owner resolves a node; a page source labels by its id.
|
|
178
|
-
const owner = isPage
|
|
179
|
-
? undefined
|
|
180
|
-
: context.graph?.layouts.find((l) => l.id === entry.source.id);
|
|
181
|
-
const ownerLabel = `${isPage ? 'Page' : 'Layout'} · ${owner?.name ?? entry.source.id}`;
|
|
182
|
-
const resolved = owner ? resolveGraphNodePath(owner.root, entry.path) : null;
|
|
183
|
-
const node = resolved?.node ?? null;
|
|
184
|
-
const nodeLabel = node ? `${shortComponentId(node.componentId)} (${node.id})` : entry.path;
|
|
185
|
-
const remainder = resolved && node ? resolved.remainder.join('/') : null;
|
|
186
|
-
const locationLabel = remainder && remainder !== 'componentId' ? `${nodeLabel} · ${remainder}` : nodeLabel;
|
|
187
|
-
return {
|
|
188
|
-
sourceLabel: ownerLabel,
|
|
189
|
-
locationLabel,
|
|
190
|
-
// Layout nodes are not addressable in the page-scoped builder; link to the
|
|
191
|
-
// builder without a node selection in that case.
|
|
192
|
-
sourceLink: isPage
|
|
193
|
-
? { kind: 'builder-node', pageId: entry.source.id, ...(node ? { nodeId: node.id } : {}) }
|
|
194
|
-
: { kind: 'builder-node' },
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
146
|
function describeTarget(context, target) {
|
|
198
147
|
switch (target.type) {
|
|
199
148
|
case 'document': {
|
|
@@ -225,9 +174,8 @@ function describeTarget(context, target) {
|
|
|
225
174
|
}
|
|
226
175
|
/** Label + link one merged entry (see {@link buildReferenceEntryViews}). */
|
|
227
176
|
export function buildReferenceEntryView(entry, context) {
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
: describeGraphSource(context, entry);
|
|
177
|
+
// EC-287: a reference source is only ever a CMS document (structure is code).
|
|
178
|
+
const sourceParts = describeDocumentSource(context, entry);
|
|
231
179
|
return {
|
|
232
180
|
...entry,
|
|
233
181
|
kindLabel: REFERENCE_KIND_LABELS[entry.kind],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reference-model.js","sourceRoot":"","sources":["../../../src/lib/references/reference-model.ts"],"names":[],"mappings":"AASA;;;;;;;;;;GAUG;AAEH,iFAAiF;AAEjF,oFAAoF;AACpF,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAClC,IAAI,SAAS,IAAI,CAAC,IAAI,SAAS,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IAC/D,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAA;AAC9E,CAAC;AAUD;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAY;IACjD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC9B,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACxC,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM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AAA;AACH,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,wBAAwB,CACtC,OAAwC,EACxC,OAA8B;IAE9B,OAAO,sBAAsB,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,uBAAuB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;AAChG,CAAC","sourcesContent":["import type { CmsDocument, CollectionDef } from '@elytracms/core/cms-core'\nimport type { ComponentNode, ProjectGraph } from '@elytracms/core/project-graph'\nimport type {\n ReferenceEntryRecord,\n ReferenceKind,\n ReferenceSource,\n ReferenceTarget,\n} from '@elytracms/core/persistence'\n\n/**\n * Pure presentation model for the EC-172 references panels.\n *\n * The EC-155 index stores entries as `(source, path, target, kind)` per\n * variant; this module turns those records into renderable rows: variants\n * merged onto one row (draft/published badges), human-readable source/\n * location/target labels, and deep-link descriptors that pinpoint the exact\n * field (CMS) or graph node (builder) a path identifies. No data fetching, no\n * React — everything here is a deterministic function of its inputs, so it is\n * fully testable in the node environment.\n */\n\n// --- Path parsing -------------------------------------------------------------\n\n/** Split a `collection:id` document key (the index's document source/target id). */\nexport function parseDocumentKey(key: string): { collection: string; id: string } | null {\n const separator = key.indexOf(':')\n if (separator <= 0 || separator === key.length - 1) return null\n return { collection: key.slice(0, separator), id: key.slice(separator + 1) }\n}\n\nexport interface DocumentFieldPath {\n /** Present for `localized/<locale>/<field>` paths. */\n locale?: string\n field: string\n /** Tokens below the field value (array indices, rich-text node paths). */\n rest: readonly string[]\n}\n\n/**\n * Parse a document index path (`values/<field>/…` or\n * `localized/<locale>/<field>/…`) onto the owning field.\n */\nexport function parseDocumentFieldPath(path: string): DocumentFieldPath | null {\n const tokens = path.split('/')\n if (tokens[0] === 'values' && tokens[1]) {\n return { field: tokens[1], rest: tokens.slice(2) }\n }\n if (tokens[0] === 'localized' && tokens[1] && tokens[2]) {\n return { locale: tokens[1], field: tokens[2], rest: tokens.slice(3) }\n }\n return null\n}\n\nexport interface ResolvedGraphPath {\n /** The deepest node the structural prefix resolves to; `null` when the path no longer matches the graph. */\n node: ComponentNode | null\n /** Tokens below the node (`componentId`, `props/<name>/binding`, `condition/source`). */\n remainder: readonly string[]\n}\n\n/**\n * Resolve a graph index path (`root`, then repeated `slots/<slot>/<index>`\n * hops, then a structure suffix) to the node it identifies. Walks the\n * slot/index prefix structurally; a prefix that no longer exists (the graph\n * drifted since indexing) resolves to `null`.\n */\nexport function resolveGraphNodePath(root: ComponentNode, path: string): ResolvedGraphPath {\n const tokens = path.split('/')\n if (tokens[0] !== 'root') return { node: null, remainder: tokens }\n let node: ComponentNode = root\n let index = 1\n while (index < tokens.length && tokens[index] === 'slots') {\n const slot = tokens[index + 1]\n const childIndex = Number(tokens[index + 2])\n const child =\n slot !== undefined && Number.isInteger(childIndex)\n ? node.slots?.[slot]?.[childIndex]\n : undefined\n if (!child) return { node: null, remainder: tokens.slice(index) }\n node = child\n index += 3\n }\n return { node, remainder: tokens.slice(index) }\n}\n\n// --- Variant merging ----------------------------------------------------------\n\n/** One panel row: the same logical entry across both variants, with flags. */\nexport interface MergedReferenceEntry {\n /** Stable row key (source + path + target + kind). */\n key: string\n source: ReferenceSource\n path: string\n target: ReferenceTarget\n kind: ReferenceKind\n /** Present in the draft variant of the index. */\n draft: boolean\n /** Present in the published variant (a live reference). */\n published: boolean\n}\n\n/**\n * Merge per-variant index records onto one row per logical entry. A\n * draft-only row (`draft && !published`) is the Sanity hidden-draft-reference\n * case the panel must make visible. Order is deterministic:\n * source type → source id → path → target type → target id → kind.\n */\nexport function mergeReferenceVariants(\n records: readonly ReferenceEntryRecord[],\n): MergedReferenceEntry[] {\n const byKey = new Map<string, MergedReferenceEntry>()\n for (const record of records) {\n const key = `${record.source.type} ${record.source.id} ${record.path} ${record.target.type} ${record.target.id} ${record.kind}`\n const existing = byKey.get(key)\n if (existing) {\n if (record.variant === 'draft') existing.draft = true\n else existing.published = true\n continue\n }\n byKey.set(key, {\n key,\n source: record.source,\n path: record.path,\n target: record.target,\n kind: record.kind,\n draft: record.variant === 'draft',\n published: record.variant === 'published',\n })\n }\n return [...byKey.values()].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n}\n\n// --- Labels & deep links --------------------------------------------------------\n\n/** Human label per reference kind (entry-row badge). */\nexport const REFERENCE_KIND_LABELS: Record<ReferenceKind, string> = {\n 'relation-field': 'relation',\n 'asset-field': 'asset field',\n 'rich-text-link': 'rich-text link',\n 'rich-text-node': 'rich-text node',\n 'component-usage': 'component usage',\n 'prop-binding': 'prop binding',\n 'condition-binding': 'condition binding',\n}\n\n/**\n * A deep-link descriptor the panel renders as a router link. `cms-field`\n * carries the full index path so the document editor can highlight the exact\n * field control; `builder-node` carries the resolved node id so the builder\n * can select + scroll to the node.\n */\nexport type ReferenceDeepLink =\n | { kind: 'cms-field'; collectionId: string; documentId: string; fieldPath?: string }\n | { kind: 'builder-node'; pageId?: string; nodeId?: string }\n | { kind: 'component'; componentId: string }\n | { kind: 'asset'; assetId: string }\n\n/** Everything the model needs to label entries (loaded once per panel). */\nexport interface ReferenceLabelContext {\n collections: readonly CollectionDef[]\n /** Live documents keyed by `collection:id`. */\n documents: ReadonlyMap<string, CmsDocument>\n /** Latest draft graph (page/layout names + node resolution); `null` when absent. */\n graph: ProjectGraph | null\n /** Asset metadata keyed by asset id. */\n assets: ReadonlyMap<string, { filename: string; title?: string | undefined }>\n /** Resolves a component id to its manifest title (live registry lookup). */\n componentTitle: (componentId: string) => string | undefined\n}\n\n/** One fully-labelled panel row. */\nexport interface ReferenceEntryView extends MergedReferenceEntry {\n kindLabel: string\n /** The holding entity, e.g. `Post · Hello World` or `Page · Home`. */\n sourceLabel: string\n /** The exact location inside the source, e.g. `Author` or `Text (n-post-title)`. */\n locationLabel: string\n /** The referenced entity, e.g. `Ada Lovelace` or `cover.jpg`. */\n targetLabel: string\n /** Deep link to the exact source location (field control / graph node). */\n sourceLink: ReferenceDeepLink | null\n /** Link to the referenced entity's surface. */\n targetLink: ReferenceDeepLink | null\n}\n\nfunction fieldLabelOf(collection: CollectionDef | undefined, fieldName: string): string {\n const field = collection?.fields.find((f) => f.name === fieldName)\n return field?.form?.label ?? fieldName\n}\n\nfunction collectionLabelOf(collection: CollectionDef | undefined, collectionId: string): string {\n return collection?.form?.labelSingular ?? collection?.form?.label ?? collectionId\n}\n\n/** Resolve a document's display title (titleField value, default locale first). */\nexport function documentTitleOf(\n collection: CollectionDef | undefined,\n document: CmsDocument | undefined,\n fallback: string,\n): string {\n if (!collection || !document) return fallback\n const field = collection.titleField ?? 'title'\n const direct = document.values[field]\n if (typeof direct === 'string' && direct.length > 0) return direct\n const locales = Object.keys(document.localized ?? {}).sort()\n const preferred = document.defaultLocale\n for (const locale of [preferred, ...locales]) {\n if (!locale) continue\n const value = document.localized?.[locale]?.[field]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return fallback\n}\n\n/** Strip the namespace off a component id for compact labels. */\nexport function shortComponentId(componentId: string): string {\n return componentId.replace('base.primitives.', '').replace('project.', '')\n}\n\ninterface DocumentParts {\n collection: CollectionDef | undefined\n collectionId: string\n documentId: string\n title: string\n}\n\nfunction documentParts(context: ReferenceLabelContext, key: string): DocumentParts | null {\n const ref = parseDocumentKey(key)\n if (!ref) return null\n const collection = context.collections.find((c) => c.id === ref.collection)\n return {\n collection,\n collectionId: ref.collection,\n documentId: ref.id,\n title: documentTitleOf(collection, context.documents.get(key), ref.id),\n }\n}\n\nfunction describeDocumentSource(\n context: ReferenceLabelContext,\n entry: MergedReferenceEntry,\n): { sourceLabel: string; locationLabel: string; sourceLink: ReferenceDeepLink | null } {\n const parts = documentParts(context, entry.source.id)\n if (!parts) {\n return { sourceLabel: entry.source.id, locationLabel: entry.path, sourceLink: null }\n }\n const parsed = parseDocumentFieldPath(entry.path)\n const fieldLabel = parsed ? fieldLabelOf(parts.collection, parsed.field) : entry.path\n const qualifiers: string[] = []\n if (parsed?.locale) qualifiers.push(parsed.locale)\n if (entry.kind === 'rich-text-link') qualifiers.push('link')\n if (entry.kind === 'rich-text-node') qualifiers.push('embedded node')\n if (\n entry.kind === 'relation-field' &&\n parsed &&\n parsed.rest.length === 1 &&\n /^\\d+$/.test(parsed.rest[0]!)\n ) {\n qualifiers.push(`item ${parsed.rest[0]}`)\n }\n return {\n sourceLabel: `${collectionLabelOf(parts.collection, parts.collectionId)} · ${parts.title}`,\n locationLabel: qualifiers.length > 0 ? `${fieldLabel} (${qualifiers.join(', ')})` : fieldLabel,\n sourceLink: {\n kind: 'cms-field',\n collectionId: parts.collectionId,\n documentId: parts.documentId,\n fieldPath: entry.path,\n },\n }\n}\n\nfunction describeGraphSource(\n context: ReferenceLabelContext,\n entry: MergedReferenceEntry,\n): { sourceLabel: string; locationLabel: string; sourceLink: ReferenceDeepLink | null } {\n const isPage = entry.source.type === 'page'\n // The canonical graph is layouts-only now (EC-187): a `page` source is no\n // longer addressable in the graph (page bodies are CMS documents), so only a\n // layout owner resolves a node; a page source labels by its id.\n const owner = isPage\n ? undefined\n : context.graph?.layouts.find((l) => l.id === entry.source.id)\n const ownerLabel = `${isPage ? 'Page' : 'Layout'} · ${owner?.name ?? entry.source.id}`\n const resolved = owner ? resolveGraphNodePath(owner.root, entry.path) : null\n const node = resolved?.node ?? null\n const nodeLabel = node ? `${shortComponentId(node.componentId)} (${node.id})` : entry.path\n const remainder = resolved && node ? resolved.remainder.join('/') : null\n const locationLabel =\n remainder && remainder !== 'componentId' ? `${nodeLabel} · ${remainder}` : nodeLabel\n return {\n sourceLabel: ownerLabel,\n locationLabel,\n // Layout nodes are not addressable in the page-scoped builder; link to the\n // builder without a node selection in that case.\n sourceLink: isPage\n ? { kind: 'builder-node', pageId: entry.source.id, ...(node ? { nodeId: node.id } : {}) }\n : { kind: 'builder-node' },\n }\n}\n\nfunction describeTarget(\n context: ReferenceLabelContext,\n target: ReferenceTarget,\n): { targetLabel: string; targetLink: ReferenceDeepLink | null } {\n switch (target.type) {\n case 'document': {\n const parts = documentParts(context, target.id)\n if (!parts) return { targetLabel: target.id, targetLink: null }\n return {\n targetLabel: `${collectionLabelOf(parts.collection, parts.collectionId)} · ${parts.title}`,\n targetLink: {\n kind: 'cms-field',\n collectionId: parts.collectionId,\n documentId: parts.documentId,\n },\n }\n }\n case 'component':\n return {\n targetLabel: context.componentTitle(target.id) ?? shortComponentId(target.id),\n targetLink: { kind: 'component', componentId: target.id },\n }\n case 'asset': {\n const asset = context.assets.get(target.id)\n return {\n targetLabel: asset ? (asset.title ?? asset.filename) : target.id,\n targetLink: { kind: 'asset', assetId: target.id },\n }\n }\n }\n}\n\n/** Label + link one merged entry (see {@link buildReferenceEntryViews}). */\nexport function buildReferenceEntryView(\n entry: MergedReferenceEntry,\n context: ReferenceLabelContext,\n): ReferenceEntryView {\n const sourceParts =\n entry.source.type === 'document'\n ? describeDocumentSource(context, entry)\n : describeGraphSource(context, entry)\n return {\n ...entry,\n kindLabel: REFERENCE_KIND_LABELS[entry.kind],\n ...sourceParts,\n ...describeTarget(context, entry.target),\n }\n}\n\n/** Merge variants and label every record — the panel's full render model. */\nexport function buildReferenceEntryViews(\n records: readonly ReferenceEntryRecord[],\n context: ReferenceLabelContext,\n): ReferenceEntryView[] {\n return mergeReferenceVariants(records).map((entry) => buildReferenceEntryView(entry, context))\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reference-model.js","sourceRoot":"","sources":["../../../src/lib/references/reference-model.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;GAUG;AAEH,iFAAiF;AAEjF,oFAAoF;AACpF,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,MAAM,SAAS,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAClC,IAAI,SAAS,IAAI,CAAC,IAAI,SAAS,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,IAAI,CAAA;IAC/D,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,EAAE,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EAAE,KAAK,CAAC,MAAM,CAAC;KACzC,CAAA;AACH,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,wBAAwB,CACtC,OAAwC,EACxC,OAA8B;IAE9B,OAAO,sBAAsB,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,uBAAuB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;AAChG,CAAC","sourcesContent":["import type { CmsDocument, CollectionDef } from '@elytracms/core/cms-core'\nimport type {\n ReferenceEntryRecord,\n ReferenceKind,\n ReferenceSource,\n ReferenceTarget,\n} from '@elytracms/core/persistence'\n\n/**\n * Pure presentation model for the EC-172 references panels.\n *\n * The EC-155 index stores entries as `(source, path, target, kind)` per\n * variant; this module turns those records into renderable rows: variants\n * merged onto one row (draft/published badges), human-readable source/\n * location/target labels, and deep-link descriptors that pinpoint the exact\n * field (CMS) or graph node (builder) a path identifies. No data fetching, no\n * React — everything here is a deterministic function of its inputs, so it is\n * fully testable in the node environment.\n */\n\n// --- Path parsing -------------------------------------------------------------\n\n/** Split a `collection:id` document key (the index's document source/target id). */\nexport function parseDocumentKey(key: string): { collection: string; id: string } | null {\n const separator = key.indexOf(':')\n if (separator <= 0 || separator === key.length - 1) return null\n return { collection: key.slice(0, separator), id: key.slice(separator + 1) }\n}\n\nexport interface DocumentFieldPath {\n /** Present for `localized/<locale>/<field>` paths. */\n locale?: string\n field: string\n /** Tokens below the field value (array indices, rich-text node paths). */\n rest: readonly string[]\n}\n\n/**\n * Parse a document index path (`values/<field>/…` or\n * `localized/<locale>/<field>/…`) onto the owning field.\n */\nexport function parseDocumentFieldPath(path: string): DocumentFieldPath | null {\n const tokens = path.split('/')\n if (tokens[0] === 'values' && tokens[1]) {\n return { field: tokens[1], rest: tokens.slice(2) }\n }\n if (tokens[0] === 'localized' && tokens[1] && tokens[2]) {\n return { locale: tokens[1], field: tokens[2], rest: tokens.slice(3) }\n }\n return null\n}\n\n// --- Variant merging ----------------------------------------------------------\n\n/** One panel row: the same logical entry across both variants, with flags. */\nexport interface MergedReferenceEntry {\n /** Stable row key (source + path + target + kind). */\n key: string\n source: ReferenceSource\n path: string\n target: ReferenceTarget\n kind: ReferenceKind\n /** Present in the draft variant of the index. */\n draft: boolean\n /** Present in the published variant (a live reference). */\n published: boolean\n}\n\n/**\n * Merge per-variant index records onto one row per logical entry. A\n * draft-only row (`draft && !published`) is the Sanity hidden-draft-reference\n * case the panel must make visible. Order is deterministic:\n * source type → source id → path → target type → target id → kind.\n */\nexport function mergeReferenceVariants(\n records: readonly ReferenceEntryRecord[],\n): MergedReferenceEntry[] {\n const byKey = new Map<string, MergedReferenceEntry>()\n for (const record of records) {\n const key = `${record.source.type} ${record.source.id} ${record.path} ${record.target.type} ${record.target.id} ${record.kind}`\n const existing = byKey.get(key)\n if (existing) {\n if (record.variant === 'draft') existing.draft = true\n else existing.published = true\n continue\n }\n byKey.set(key, {\n key,\n source: record.source,\n path: record.path,\n target: record.target,\n kind: record.kind,\n draft: record.variant === 'draft',\n published: record.variant === 'published',\n })\n }\n return [...byKey.values()].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n}\n\n// --- Labels & deep links --------------------------------------------------------\n\n/** Human label per reference kind (entry-row badge). */\nexport const REFERENCE_KIND_LABELS: Record<ReferenceKind, string> = {\n 'relation-field': 'relation',\n 'asset-field': 'asset field',\n 'rich-text-link': 'rich-text link',\n 'rich-text-node': 'rich-text node',\n 'component-usage': 'component usage',\n}\n\n/**\n * A deep-link descriptor the panel renders as a router link. `cms-field`\n * carries the full index path so the document editor can highlight the exact\n * field control; `builder-node` carries the resolved node id so the builder\n * can select + scroll to the node.\n */\nexport type ReferenceDeepLink =\n | { kind: 'cms-field'; collectionId: string; documentId: string; fieldPath?: string }\n | { kind: 'builder-node'; pageId?: string; nodeId?: string }\n | { kind: 'component'; componentId: string }\n | { kind: 'asset'; assetId: string }\n\n/** Everything the model needs to label entries (loaded once per panel). */\nexport interface ReferenceLabelContext {\n collections: readonly CollectionDef[]\n /** Live documents keyed by `collection:id`. */\n documents: ReadonlyMap<string, CmsDocument>\n /** Asset metadata keyed by asset id. */\n assets: ReadonlyMap<string, { filename: string; title?: string | undefined }>\n /** Resolves a component id to its manifest title (live registry lookup). */\n componentTitle: (componentId: string) => string | undefined\n}\n\n/** One fully-labelled panel row. */\nexport interface ReferenceEntryView extends MergedReferenceEntry {\n kindLabel: string\n /** The holding entity, e.g. `Post · Hello World` or `Page · Home`. */\n sourceLabel: string\n /** The exact location inside the source, e.g. `Author` or `Text (n-post-title)`. */\n locationLabel: string\n /** The referenced entity, e.g. `Ada Lovelace` or `cover.jpg`. */\n targetLabel: string\n /** Deep link to the exact source location (field control / graph node). */\n sourceLink: ReferenceDeepLink | null\n /** Link to the referenced entity's surface. */\n targetLink: ReferenceDeepLink | null\n}\n\nfunction fieldLabelOf(collection: CollectionDef | undefined, fieldName: string): string {\n const field = collection?.fields.find((f) => f.name === fieldName)\n return field?.form?.label ?? fieldName\n}\n\nfunction collectionLabelOf(collection: CollectionDef | undefined, collectionId: string): string {\n return collection?.form?.labelSingular ?? collection?.form?.label ?? collectionId\n}\n\n/** Resolve a document's display title (titleField value, default locale first). */\nexport function documentTitleOf(\n collection: CollectionDef | undefined,\n document: CmsDocument | undefined,\n fallback: string,\n): string {\n if (!collection || !document) return fallback\n const field = collection.titleField ?? 'title'\n const direct = document.values[field]\n if (typeof direct === 'string' && direct.length > 0) return direct\n const locales = Object.keys(document.localized ?? {}).sort()\n const preferred = document.defaultLocale\n for (const locale of [preferred, ...locales]) {\n if (!locale) continue\n const value = document.localized?.[locale]?.[field]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return fallback\n}\n\n/** Strip the namespace off a component id for compact labels. */\nexport function shortComponentId(componentId: string): string {\n return componentId.replace('base.primitives.', '').replace('project.', '')\n}\n\ninterface DocumentParts {\n collection: CollectionDef | undefined\n collectionId: string\n documentId: string\n title: string\n}\n\nfunction documentParts(context: ReferenceLabelContext, key: string): DocumentParts | null {\n const ref = parseDocumentKey(key)\n if (!ref) return null\n const collection = context.collections.find((c) => c.id === ref.collection)\n return {\n collection,\n collectionId: ref.collection,\n documentId: ref.id,\n title: documentTitleOf(collection, context.documents.get(key), ref.id),\n }\n}\n\nfunction describeDocumentSource(\n context: ReferenceLabelContext,\n entry: MergedReferenceEntry,\n): { sourceLabel: string; locationLabel: string; sourceLink: ReferenceDeepLink | null } {\n const parts = documentParts(context, entry.source.id)\n if (!parts) {\n return { sourceLabel: entry.source.id, locationLabel: entry.path, sourceLink: null }\n }\n const parsed = parseDocumentFieldPath(entry.path)\n const fieldLabel = parsed ? fieldLabelOf(parts.collection, parsed.field) : entry.path\n const qualifiers: string[] = []\n if (parsed?.locale) qualifiers.push(parsed.locale)\n if (entry.kind === 'rich-text-link') qualifiers.push('link')\n if (entry.kind === 'rich-text-node') qualifiers.push('embedded node')\n if (\n entry.kind === 'relation-field' &&\n parsed &&\n parsed.rest.length === 1 &&\n /^\\d+$/.test(parsed.rest[0]!)\n ) {\n qualifiers.push(`item ${parsed.rest[0]}`)\n }\n return {\n sourceLabel: `${collectionLabelOf(parts.collection, parts.collectionId)} · ${parts.title}`,\n locationLabel: qualifiers.length > 0 ? `${fieldLabel} (${qualifiers.join(', ')})` : fieldLabel,\n sourceLink: {\n kind: 'cms-field',\n collectionId: parts.collectionId,\n documentId: parts.documentId,\n fieldPath: entry.path,\n },\n }\n}\n\n\nfunction describeTarget(\n context: ReferenceLabelContext,\n target: ReferenceTarget,\n): { targetLabel: string; targetLink: ReferenceDeepLink | null } {\n switch (target.type) {\n case 'document': {\n const parts = documentParts(context, target.id)\n if (!parts) return { targetLabel: target.id, targetLink: null }\n return {\n targetLabel: `${collectionLabelOf(parts.collection, parts.collectionId)} · ${parts.title}`,\n targetLink: {\n kind: 'cms-field',\n collectionId: parts.collectionId,\n documentId: parts.documentId,\n },\n }\n }\n case 'component':\n return {\n targetLabel: context.componentTitle(target.id) ?? shortComponentId(target.id),\n targetLink: { kind: 'component', componentId: target.id },\n }\n case 'asset': {\n const asset = context.assets.get(target.id)\n return {\n targetLabel: asset ? (asset.title ?? asset.filename) : target.id,\n targetLink: { kind: 'asset', assetId: target.id },\n }\n }\n }\n}\n\n/** Label + link one merged entry (see {@link buildReferenceEntryViews}). */\nexport function buildReferenceEntryView(\n entry: MergedReferenceEntry,\n context: ReferenceLabelContext,\n): ReferenceEntryView {\n // EC-287: a reference source is only ever a CMS document (structure is code).\n const sourceParts = describeDocumentSource(context, entry)\n return {\n ...entry,\n kindLabel: REFERENCE_KIND_LABELS[entry.kind],\n ...sourceParts,\n ...describeTarget(context, entry.target),\n }\n}\n\n/** Merge variants and label every record — the panel's full render model. */\nexport function buildReferenceEntryViews(\n records: readonly ReferenceEntryRecord[],\n context: ReferenceLabelContext,\n): ReferenceEntryView[] {\n return mergeReferenceVariants(records).map((entry) => buildReferenceEntryView(entry, context))\n}\n"]}
|
|
@@ -48,10 +48,9 @@ export function ensureReferenceIndex(studio, projectId) {
|
|
|
48
48
|
}
|
|
49
49
|
// --- Label context loading -------------------------------------------------------
|
|
50
50
|
async function loadLabelContext(operations, projectId) {
|
|
51
|
-
const [schemaResult, documentsResult,
|
|
51
|
+
const [schemaResult, documentsResult, assetsResult] = await Promise.all([
|
|
52
52
|
operations.schema.get({ projectId }),
|
|
53
53
|
operations.documents.list({ projectId }),
|
|
54
|
-
operations.graph.getLatest({ projectId }),
|
|
55
54
|
operations.assets.list({ projectId }),
|
|
56
55
|
]);
|
|
57
56
|
const collections = schemaResult.ok ? schemaResult.value.collections : [];
|
|
@@ -61,7 +60,8 @@ async function loadLabelContext(operations, projectId) {
|
|
|
61
60
|
documents.set(documentKey({ collection: record.document.collection, id: record.document.id }), record.document);
|
|
62
61
|
}
|
|
63
62
|
}
|
|
64
|
-
|
|
63
|
+
// EC-287: the project graph is retired; reference source labels resolve from
|
|
64
|
+
// CMS documents only. `page`/`layout` graph sources no longer exist.
|
|
65
65
|
const assets = new Map();
|
|
66
66
|
if (assetsResult.ok) {
|
|
67
67
|
for (const asset of assetsResult.value) {
|
|
@@ -72,7 +72,6 @@ async function loadLabelContext(operations, projectId) {
|
|
|
72
72
|
return {
|
|
73
73
|
collections,
|
|
74
74
|
documents,
|
|
75
|
-
graph,
|
|
76
75
|
assets,
|
|
77
76
|
componentTitle: (componentId) => registry.getManifest(componentId)?.title,
|
|
78
77
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"references-store.js","sourceRoot":"","sources":["../../../src/lib/references/references-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAQtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAA;AAiC5D,kFAAkF;AAElF;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,IAAI,OAAO,EAAgD,CAAA;AAErF;;;;;;;;;;GAUG;AACH,KAAK,UAAU,kBAAkB,CAAC,MAAwB,EAAE,SAAiB;IAC3E,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,SAAS,EAAE,CAAC,CAAA;QAC5E,IAAI,MAAM,CAAC,EAAE,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;YAAE,OAAM;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,0EAA0E;IAC5E,CAAC;IACD,MAAM,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,IAAI,CAC7D,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CA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M,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;gBACzD,IAAI,uBAAuB,CAAC,KAAK,CAAC;oBAAE,cAAc,EAAE,CAAA;YACtD,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;QACF,OAAO,GAAG,EAAE;YACV,QAAQ,GAAG,IAAI,CAAA;YACf,QAAQ,CAAC,OAAO,IAAI,CAAC,CAAA;YACrB,IAAI,WAAW;gBAAE,YAAY,CAAC,WAAW,CAAC,CAAA;YAC1C,WAAW,EAAE,EAAE,CAAA;QACjB,CAAC,CAAA;IACH,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAA;IAEV,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE;QAC/B,QAAQ,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CAAA;QAC5D,KAAK,IAAI,EAAE,CAAA;IACb,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAA;IAEV,OAAO,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,CAAA;AAC9B,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { documentKey } from '@elytracms/core/cms-core'\nimport type { CmsDocument, DocumentRef } from '@elytracms/core/cms-core'\nimport type { ProjectGraph } from '@elytracms/core/project-graph'\nimport type {\n ReferenceEntryRecord,\n ReferenceSource,\n ReferenceTarget,\n} from '@elytracms/core/persistence'\nimport { getStudioOperations } from '../operations'\nimport type { OperationEvent, OperationsClient, StudioOperations } from '../operations'\nimport { getStudioRegistry } from '../registry'\nimport { buildReferenceEntryViews } from './reference-model'\nimport type { ReferenceEntryView, ReferenceLabelContext } from './reference-model'\n\n/**\n * Data layer for the EC-172 references panels. All reads go through\n * `@elytracms/core/operations` queries (`references.outbound` / `references.inbound`\n * plus the labeling queries) — UI code never touches persistence repositories\n * or index tables. The hook keeps panels live: any succeeded command in a\n * content-bearing domain re-queries after the EC-155 maintained-on-write\n * attachment has flushed.\n */\n\nexport interface ReferencePanelQuery {\n projectId: string\n /** Enables the outbound (\"references\") section. */\n source?: ReferenceSource | undefined\n /** Enables the inbound (\"used by\") section. */\n target?: ReferenceTarget | undefined\n}\n\nexport interface ReferencePanelData {\n outbound: ReferenceEntryView[]\n inbound: ReferenceEntryView[]\n /**\n * Per-direction read error (EC-205): a direction whose query returns a\n * structured non-ok degrades to an empty list plus this message, surfaced as a\n * visible per-section error — instead of collapsing the whole panel into its\n * hard-error state. `null` when the direction loaded (or was not requested).\n */\n outboundError: string | null\n inboundError: string | null\n}\n\n// --- Index bootstrap -----------------------------------------------------------\n\n/**\n * The EC-155 index is maintained on write, but seeded/imported projects start\n * with an empty index. {@link ensureReferenceIndex} seeds it once per project per\n * operations client; failures (e.g. a viewer's command denial) degrade to\n * whatever the maintained-on-write index already holds.\n */\nconst backfillsByClient = new WeakMap<StudioOperations, Map<string, Promise<void>>>()\n\n/**\n * Seed the index once if it has never been backfilled, then never again — the\n * EC-269 mutation-free read path. The index is maintained on write, so the\n * (clear + rebuild) `backfill` is only needed to seed a never-built index. A\n * persisted marker (`references.buildMarker`, a read) records completion; when\n * present this returns after a single query with ZERO mutations — so opening the\n * References panel no longer rewrites the whole index every session (the normal\n * Convex case: the EC-233 import already backfilled). Only a genuinely empty/\n * never-built project still pays the one-time backfill (and a viewer who cannot\n * run it degrades to the maintained-on-write index, as before).\n */\nasync function seedReferenceIndex(studio: StudioOperations, projectId: string): Promise<void> {\n try {\n const marker = await studio.operations.references.buildMarker({ projectId })\n if (marker.ok && marker.value !== null) return\n } catch {\n // A marker-read failure falls through to the backfill (best-effort seed).\n }\n await studio.operations.references.backfill({ projectId }).then(\n () => undefined,\n () => undefined,\n )\n}\n\nexport function ensureReferenceIndex(studio: StudioOperations, projectId: string): Promise<void> {\n let byProject = backfillsByClient.get(studio)\n if (!byProject) {\n byProject = new Map()\n backfillsByClient.set(studio, byProject)\n }\n let pending = byProject.get(projectId)\n if (!pending) {\n pending = seedReferenceIndex(studio, projectId)\n byProject.set(projectId, pending)\n }\n return pending\n}\n\n// --- Label context loading -------------------------------------------------------\n\nasync function loadLabelContext(\n operations: OperationsClient,\n projectId: string,\n): Promise<ReferenceLabelContext> {\n const [schemaResult, documentsResult, graphResult, assetsResult] = await Promise.all([\n operations.schema.get({ projectId }),\n operations.documents.list({ projectId }),\n operations.graph.getLatest({ projectId }),\n operations.assets.list({ projectId }),\n ])\n\n const collections = schemaResult.ok ? schemaResult.value.collections : []\n const documents = new Map<string, CmsDocument>()\n if (documentsResult.ok) {\n for (const record of documentsResult.value) {\n documents.set(\n documentKey({ collection: record.document.collection, id: record.document.id }),\n record.document,\n )\n }\n }\n const graph: ProjectGraph | null = graphResult.ok ? graphResult.value.graph : null\n const assets = new Map<string, { filename: string; title?: string | undefined }>()\n if (assetsResult.ok) {\n for (const asset of assetsResult.value) {\n assets.set(asset.id, { filename: asset.filename, title: asset.title })\n }\n }\n const registry = getStudioRegistry().registry\n return {\n collections,\n documents,\n graph,\n assets,\n componentTitle: (componentId) => registry.getManifest(componentId)?.title,\n }\n}\n\n// --- Panel data loading -----------------------------------------------------------\n\n/** Load both directions + labels for one panel (operations queries only). */\nexport async function loadReferencePanelData(\n query: ReferencePanelQuery,\n): Promise<ReferencePanelData> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, query.projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n\n // EC-205: load each direction INDEPENDENTLY. A structured non-ok from one\n // direction is a degradable operation result (it carries an OperationError —\n // the documented contract), not an exception: degrade that direction to empty\n // and surface its error per-section (references-panel) while the other still\n // renders, instead of throwing the whole panel into its hard-error state. A\n // genuinely broken backend still throws from getStudioOperations/flush above.\n const [outbound, inbound] = await Promise.all([\n query.source\n ? operations.references.outbound({ projectId: query.projectId, source: query.source })\n : null,\n query.target\n ? operations.references.inbound({ projectId: query.projectId, target: query.target })\n : null,\n ])\n\n type DirectionResult = Awaited<ReturnType<typeof operations.references.outbound>>\n const settle = (\n result: DirectionResult | null,\n ): { records: ReferenceEntryRecord[]; error: string | null } =>\n result === null\n ? { records: [], error: null }\n : result.ok\n ? { records: result.value, error: null }\n : { records: [], error: result.error.message }\n const out = settle(outbound)\n const inb = settle(inbound)\n\n const context = await loadLabelContext(operations, query.projectId)\n return {\n outbound: buildReferenceEntryViews(out.records, context),\n inbound: buildReferenceEntryViews(inb.records, context),\n outboundError: out.error,\n inboundError: inb.error,\n }\n}\n\n// --- Impact loading (EC-173 safe unpublish/delete) -------------------------------\n\n/**\n * Load the labelled inbound entry views for a set of target documents in ONE\n * pass (one index flush, one label-context load) — the pre-flight data of the\n * EC-173 confirmation dialogs, including the bulk flows. Returns entries in\n * `targets` order; pair with `buildReferenceImpact` for break/block semantics.\n */\nexport async function loadInboundReferenceViews(\n projectId: string,\n targets: readonly DocumentRef[],\n): Promise<{ ref: DocumentRef; inbound: ReferenceEntryView[] }[]> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n\n const recordsPerTarget = await Promise.all(\n targets.map((ref) =>\n operations.references\n .inbound({ projectId, target: { type: 'document', id: documentKey(ref) } })\n .then((result) => {\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n }),\n ),\n )\n const context = await loadLabelContext(operations, projectId)\n return targets.map((ref, index) => ({\n ref,\n inbound: buildReferenceEntryViews(recordsPerTarget[index] ?? [], context),\n }))\n}\n\n/**\n * Inbound reference views for ONE asset (EC-202): the \"what uses this asset\"\n * pre-flight of the asset-delete dialog, index-accurate (the EC-155 reference\n * index, not the retired `find-asset-usages` string scan). Mirrors\n * {@link loadInboundReferenceViews} for a single `{ type: 'asset' }` target —\n * the source labels resolve the referencing documents/graph-nodes identically.\n */\nexport async function loadInboundAssetReferenceViews(\n projectId: string,\n assetId: string,\n): Promise<ReferenceEntryView[]> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n const result = await operations.references.inbound({\n projectId,\n target: { type: 'asset', id: assetId },\n })\n if (!result.ok) throw new Error(result.error.message)\n const context = await loadLabelContext(operations, projectId)\n return buildReferenceEntryViews(result.value, context)\n}\n\n// --- React hook ----------------------------------------------------------------\n\n/**\n * Domains whose successful commands can change the reference index or labels and\n * should refresh an open panel. `references` is deliberately ABSENT (EC-269):\n * reacting to reference-index command events (the `backfill`) would make the\n * panel re-trigger on its OWN index maintenance — a self-cascade that, compounded\n * with the per-keystroke `documents` events, produced hundreds of redundant\n * reloads per document. The index is maintained on write; the panel reacts to the\n * CONTENT domains that feed it, never to its own index writes.\n */\nconst REFRESH_DOMAINS: ReadonlySet<string> = new Set([\n 'documents',\n 'graph',\n 'publishing',\n 'assets',\n 'schema',\n])\n\n/**\n * Whether one operation event should refresh an open reference panel. Exported\n * for tests — pins the EC-269 contract that reference-index commands (and any\n * non-succeeded / non-command event) never trigger a reload.\n */\nexport function isReferenceRefreshEvent(event: OperationEvent): boolean {\n return (\n event.kind === 'command' && event.status === 'succeeded' && REFRESH_DOMAINS.has(event.domain)\n )\n}\n\n/**\n * Trailing-debounce window (ms) for event-driven panel reloads (EC-269): a burst\n * of content commands — e.g. one `documents.upsert` per keystroke from autosave —\n * coalesces into a SINGLE reload once the writes settle, instead of one full\n * (multi-query) reload per event. The initial mount load stays immediate.\n */\nexport const REFERENCE_RELOAD_DEBOUNCE_MS = 300\n\nexport type ReferencePanelStatus = 'loading' | 'ready' | 'error'\n\nexport interface ReferencePanelState {\n status: ReferencePanelStatus\n data: ReferencePanelData | null\n errorMessage: string | null\n refresh: () => void\n}\n\n/**\n * Live panel state for one entity: loads on mount, exposes explicit\n * loading/error states, and re-queries whenever a content-bearing command\n * succeeds anywhere in the studio (the index is maintained on write).\n */\nexport function useReferencePanel(query: ReferencePanelQuery): ReferencePanelState {\n const { projectId } = query\n const sourceType = query.source?.type\n const sourceId = query.source?.id\n const targetType = query.target?.type\n const targetId = query.target?.id\n\n const stableQuery = useMemo<ReferencePanelQuery>(\n () => ({\n projectId,\n ...(sourceType && sourceId ? { source: { type: sourceType, id: sourceId } } : {}),\n ...(targetType && targetId ? { target: { type: targetType, id: targetId } } : {}),\n }),\n [projectId, sourceType, sourceId, targetType, targetId],\n )\n\n const [state, setState] = useState<Omit<ReferencePanelState, 'refresh'>>({\n status: 'loading',\n data: null,\n errorMessage: null,\n })\n const epochRef = useRef(0)\n\n const load = useCallback(async () => {\n const epoch = ++epochRef.current\n try {\n const data = await loadReferencePanelData(stableQuery)\n if (epochRef.current === epoch) {\n setState({ status: 'ready', data, errorMessage: null })\n }\n } catch (cause) {\n if (epochRef.current === epoch) {\n setState({\n status: 'error',\n data: null,\n errorMessage: cause instanceof Error ? cause.message : String(cause),\n })\n }\n }\n }, [stableQuery])\n\n useEffect(() => {\n // Initial load is immediate; event-driven reloads are trailing-debounced so a\n // burst of content commands (per-keystroke autosave) coalesces into one reload\n // (EC-269).\n setState({ status: 'loading', data: null, errorMessage: null })\n void load()\n let disposed = false\n let unsubscribe: (() => void) | undefined\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n const scheduleReload = () => {\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n reloadTimer = undefined\n void load()\n }, REFERENCE_RELOAD_DEBOUNCE_MS)\n }\n void getStudioOperations().then((studio) => {\n if (disposed) return\n unsubscribe = studio.operations.events.subscribe((event) => {\n if (isReferenceRefreshEvent(event)) scheduleReload()\n })\n })\n return () => {\n disposed = true\n epochRef.current += 1\n if (reloadTimer) clearTimeout(reloadTimer)\n unsubscribe?.()\n }\n }, [load])\n\n const refresh = useCallback(() => {\n setState((previous) => ({ ...previous, status: 'loading' }))\n void load()\n }, [load])\n\n return { ...state, refresh }\n}\n"]}
|
|
1
|
+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G,EAAE;QAC/B,QAAQ,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CAAA;QAC5D,KAAK,IAAI,EAAE,CAAA;IACb,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAA;IAEV,OAAO,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,CAAA;AAC9B,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { documentKey } from '@elytracms/core/cms-core'\nimport type { CmsDocument, DocumentRef } from '@elytracms/core/cms-core'\nimport type {\n ReferenceEntryRecord,\n ReferenceSource,\n ReferenceTarget,\n} from '@elytracms/core/persistence'\nimport { getStudioOperations } from '../operations'\nimport type { OperationEvent, OperationsClient, StudioOperations } from '../operations'\nimport { getStudioRegistry } from '../registry'\nimport { buildReferenceEntryViews } from './reference-model'\nimport type { ReferenceEntryView, ReferenceLabelContext } from './reference-model'\n\n/**\n * Data layer for the EC-172 references panels. All reads go through\n * `@elytracms/core/operations` queries (`references.outbound` / `references.inbound`\n * plus the labeling queries) — UI code never touches persistence repositories\n * or index tables. The hook keeps panels live: any succeeded command in a\n * content-bearing domain re-queries after the EC-155 maintained-on-write\n * attachment has flushed.\n */\n\nexport interface ReferencePanelQuery {\n projectId: string\n /** Enables the outbound (\"references\") section. */\n source?: ReferenceSource | undefined\n /** Enables the inbound (\"used by\") section. */\n target?: ReferenceTarget | undefined\n}\n\nexport interface ReferencePanelData {\n outbound: ReferenceEntryView[]\n inbound: ReferenceEntryView[]\n /**\n * Per-direction read error (EC-205): a direction whose query returns a\n * structured non-ok degrades to an empty list plus this message, surfaced as a\n * visible per-section error — instead of collapsing the whole panel into its\n * hard-error state. `null` when the direction loaded (or was not requested).\n */\n outboundError: string | null\n inboundError: string | null\n}\n\n// --- Index bootstrap -----------------------------------------------------------\n\n/**\n * The EC-155 index is maintained on write, but seeded/imported projects start\n * with an empty index. {@link ensureReferenceIndex} seeds it once per project per\n * operations client; failures (e.g. a viewer's command denial) degrade to\n * whatever the maintained-on-write index already holds.\n */\nconst backfillsByClient = new WeakMap<StudioOperations, Map<string, Promise<void>>>()\n\n/**\n * Seed the index once if it has never been backfilled, then never again — the\n * EC-269 mutation-free read path. The index is maintained on write, so the\n * (clear + rebuild) `backfill` is only needed to seed a never-built index. A\n * persisted marker (`references.buildMarker`, a read) records completion; when\n * present this returns after a single query with ZERO mutations — so opening the\n * References panel no longer rewrites the whole index every session (the normal\n * Convex case: the EC-233 import already backfilled). Only a genuinely empty/\n * never-built project still pays the one-time backfill (and a viewer who cannot\n * run it degrades to the maintained-on-write index, as before).\n */\nasync function seedReferenceIndex(studio: StudioOperations, projectId: string): Promise<void> {\n try {\n const marker = await studio.operations.references.buildMarker({ projectId })\n if (marker.ok && marker.value !== null) return\n } catch {\n // A marker-read failure falls through to the backfill (best-effort seed).\n }\n await studio.operations.references.backfill({ projectId }).then(\n () => undefined,\n () => undefined,\n )\n}\n\nexport function ensureReferenceIndex(studio: StudioOperations, projectId: string): Promise<void> {\n let byProject = backfillsByClient.get(studio)\n if (!byProject) {\n byProject = new Map()\n backfillsByClient.set(studio, byProject)\n }\n let pending = byProject.get(projectId)\n if (!pending) {\n pending = seedReferenceIndex(studio, projectId)\n byProject.set(projectId, pending)\n }\n return pending\n}\n\n// --- Label context loading -------------------------------------------------------\n\nasync function loadLabelContext(\n operations: OperationsClient,\n projectId: string,\n): Promise<ReferenceLabelContext> {\n const [schemaResult, documentsResult, assetsResult] = await Promise.all([\n operations.schema.get({ projectId }),\n operations.documents.list({ projectId }),\n operations.assets.list({ projectId }),\n ])\n\n const collections = schemaResult.ok ? schemaResult.value.collections : []\n const documents = new Map<string, CmsDocument>()\n if (documentsResult.ok) {\n for (const record of documentsResult.value) {\n documents.set(\n documentKey({ collection: record.document.collection, id: record.document.id }),\n record.document,\n )\n }\n }\n // EC-287: the project graph is retired; reference source labels resolve from\n // CMS documents only. `page`/`layout` graph sources no longer exist.\n const assets = new Map<string, { filename: string; title?: string | undefined }>()\n if (assetsResult.ok) {\n for (const asset of assetsResult.value) {\n assets.set(asset.id, { filename: asset.filename, title: asset.title })\n }\n }\n const registry = getStudioRegistry().registry\n return {\n collections,\n documents,\n assets,\n componentTitle: (componentId) => registry.getManifest(componentId)?.title,\n }\n}\n\n// --- Panel data loading -----------------------------------------------------------\n\n/** Load both directions + labels for one panel (operations queries only). */\nexport async function loadReferencePanelData(\n query: ReferencePanelQuery,\n): Promise<ReferencePanelData> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, query.projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n\n // EC-205: load each direction INDEPENDENTLY. A structured non-ok from one\n // direction is a degradable operation result (it carries an OperationError —\n // the documented contract), not an exception: degrade that direction to empty\n // and surface its error per-section (references-panel) while the other still\n // renders, instead of throwing the whole panel into its hard-error state. A\n // genuinely broken backend still throws from getStudioOperations/flush above.\n const [outbound, inbound] = await Promise.all([\n query.source\n ? operations.references.outbound({ projectId: query.projectId, source: query.source })\n : null,\n query.target\n ? operations.references.inbound({ projectId: query.projectId, target: query.target })\n : null,\n ])\n\n type DirectionResult = Awaited<ReturnType<typeof operations.references.outbound>>\n const settle = (\n result: DirectionResult | null,\n ): { records: ReferenceEntryRecord[]; error: string | null } =>\n result === null\n ? { records: [], error: null }\n : result.ok\n ? { records: result.value, error: null }\n : { records: [], error: result.error.message }\n const out = settle(outbound)\n const inb = settle(inbound)\n\n const context = await loadLabelContext(operations, query.projectId)\n return {\n outbound: buildReferenceEntryViews(out.records, context),\n inbound: buildReferenceEntryViews(inb.records, context),\n outboundError: out.error,\n inboundError: inb.error,\n }\n}\n\n// --- Impact loading (EC-173 safe unpublish/delete) -------------------------------\n\n/**\n * Load the labelled inbound entry views for a set of target documents in ONE\n * pass (one index flush, one label-context load) — the pre-flight data of the\n * EC-173 confirmation dialogs, including the bulk flows. Returns entries in\n * `targets` order; pair with `buildReferenceImpact` for break/block semantics.\n */\nexport async function loadInboundReferenceViews(\n projectId: string,\n targets: readonly DocumentRef[],\n): Promise<{ ref: DocumentRef; inbound: ReferenceEntryView[] }[]> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n\n const recordsPerTarget = await Promise.all(\n targets.map((ref) =>\n operations.references\n .inbound({ projectId, target: { type: 'document', id: documentKey(ref) } })\n .then((result) => {\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n }),\n ),\n )\n const context = await loadLabelContext(operations, projectId)\n return targets.map((ref, index) => ({\n ref,\n inbound: buildReferenceEntryViews(recordsPerTarget[index] ?? [], context),\n }))\n}\n\n/**\n * Inbound reference views for ONE asset (EC-202): the \"what uses this asset\"\n * pre-flight of the asset-delete dialog, index-accurate (the EC-155 reference\n * index, not the retired `find-asset-usages` string scan). Mirrors\n * {@link loadInboundReferenceViews} for a single `{ type: 'asset' }` target —\n * the source labels resolve the referencing documents/graph-nodes identically.\n */\nexport async function loadInboundAssetReferenceViews(\n projectId: string,\n assetId: string,\n): Promise<ReferenceEntryView[]> {\n const studio = await getStudioOperations()\n await ensureReferenceIndex(studio, projectId)\n // Observe a settled index: maintained-on-write updates run async after events.\n await studio.references.flush()\n const operations = studio.operations\n const result = await operations.references.inbound({\n projectId,\n target: { type: 'asset', id: assetId },\n })\n if (!result.ok) throw new Error(result.error.message)\n const context = await loadLabelContext(operations, projectId)\n return buildReferenceEntryViews(result.value, context)\n}\n\n// --- React hook ----------------------------------------------------------------\n\n/**\n * Domains whose successful commands can change the reference index or labels and\n * should refresh an open panel. `references` is deliberately ABSENT (EC-269):\n * reacting to reference-index command events (the `backfill`) would make the\n * panel re-trigger on its OWN index maintenance — a self-cascade that, compounded\n * with the per-keystroke `documents` events, produced hundreds of redundant\n * reloads per document. The index is maintained on write; the panel reacts to the\n * CONTENT domains that feed it, never to its own index writes.\n */\nconst REFRESH_DOMAINS: ReadonlySet<string> = new Set([\n 'documents',\n 'graph',\n 'publishing',\n 'assets',\n 'schema',\n])\n\n/**\n * Whether one operation event should refresh an open reference panel. Exported\n * for tests — pins the EC-269 contract that reference-index commands (and any\n * non-succeeded / non-command event) never trigger a reload.\n */\nexport function isReferenceRefreshEvent(event: OperationEvent): boolean {\n return (\n event.kind === 'command' && event.status === 'succeeded' && REFRESH_DOMAINS.has(event.domain)\n )\n}\n\n/**\n * Trailing-debounce window (ms) for event-driven panel reloads (EC-269): a burst\n * of content commands — e.g. one `documents.upsert` per keystroke from autosave —\n * coalesces into a SINGLE reload once the writes settle, instead of one full\n * (multi-query) reload per event. The initial mount load stays immediate.\n */\nexport const REFERENCE_RELOAD_DEBOUNCE_MS = 300\n\nexport type ReferencePanelStatus = 'loading' | 'ready' | 'error'\n\nexport interface ReferencePanelState {\n status: ReferencePanelStatus\n data: ReferencePanelData | null\n errorMessage: string | null\n refresh: () => void\n}\n\n/**\n * Live panel state for one entity: loads on mount, exposes explicit\n * loading/error states, and re-queries whenever a content-bearing command\n * succeeds anywhere in the studio (the index is maintained on write).\n */\nexport function useReferencePanel(query: ReferencePanelQuery): ReferencePanelState {\n const { projectId } = query\n const sourceType = query.source?.type\n const sourceId = query.source?.id\n const targetType = query.target?.type\n const targetId = query.target?.id\n\n const stableQuery = useMemo<ReferencePanelQuery>(\n () => ({\n projectId,\n ...(sourceType && sourceId ? { source: { type: sourceType, id: sourceId } } : {}),\n ...(targetType && targetId ? { target: { type: targetType, id: targetId } } : {}),\n }),\n [projectId, sourceType, sourceId, targetType, targetId],\n )\n\n const [state, setState] = useState<Omit<ReferencePanelState, 'refresh'>>({\n status: 'loading',\n data: null,\n errorMessage: null,\n })\n const epochRef = useRef(0)\n\n const load = useCallback(async () => {\n const epoch = ++epochRef.current\n try {\n const data = await loadReferencePanelData(stableQuery)\n if (epochRef.current === epoch) {\n setState({ status: 'ready', data, errorMessage: null })\n }\n } catch (cause) {\n if (epochRef.current === epoch) {\n setState({\n status: 'error',\n data: null,\n errorMessage: cause instanceof Error ? cause.message : String(cause),\n })\n }\n }\n }, [stableQuery])\n\n useEffect(() => {\n // Initial load is immediate; event-driven reloads are trailing-debounced so a\n // burst of content commands (per-keystroke autosave) coalesces into one reload\n // (EC-269).\n setState({ status: 'loading', data: null, errorMessage: null })\n void load()\n let disposed = false\n let unsubscribe: (() => void) | undefined\n let reloadTimer: ReturnType<typeof setTimeout> | undefined\n const scheduleReload = () => {\n if (reloadTimer) clearTimeout(reloadTimer)\n reloadTimer = setTimeout(() => {\n reloadTimer = undefined\n void load()\n }, REFERENCE_RELOAD_DEBOUNCE_MS)\n }\n void getStudioOperations().then((studio) => {\n if (disposed) return\n unsubscribe = studio.operations.events.subscribe((event) => {\n if (isReferenceRefreshEvent(event)) scheduleReload()\n })\n })\n return () => {\n disposed = true\n epochRef.current += 1\n if (reloadTimer) clearTimeout(reloadTimer)\n unsubscribe?.()\n }\n }, [load])\n\n const refresh = useCallback(() => {\n setState((previous) => ({ ...previous, status: 'loading' }))\n void load()\n }, [load])\n\n return { ...state, refresh }\n}\n"]}
|
|
@@ -48,19 +48,3 @@ export interface RegistryHealth {
|
|
|
48
48
|
invalid: number;
|
|
49
49
|
}
|
|
50
50
|
export declare function registryHealth(studio: StudioRegistry): RegistryHealth;
|
|
51
|
-
export interface ComponentDraft {
|
|
52
|
-
id: string;
|
|
53
|
-
status: 'draft';
|
|
54
|
-
source: 'ai';
|
|
55
|
-
title: string;
|
|
56
|
-
/** The natural-language intent that would drive Phase 8 generation. */
|
|
57
|
-
prompt: string;
|
|
58
|
-
/** A preview of the manifest the generator would produce. */
|
|
59
|
-
manifestPreview: {
|
|
60
|
-
id: string;
|
|
61
|
-
namespace: 'project';
|
|
62
|
-
props: string[];
|
|
63
|
-
slots: string[];
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
export declare const componentDrafts: readonly ComponentDraft[];
|
|
@@ -96,19 +96,4 @@ export function registryHealth(studio) {
|
|
|
96
96
|
health[componentStatus(studio, m)] += 1;
|
|
97
97
|
return health;
|
|
98
98
|
}
|
|
99
|
-
export const componentDrafts = [
|
|
100
|
-
{
|
|
101
|
-
id: 'draft_testimonial',
|
|
102
|
-
status: 'draft',
|
|
103
|
-
source: 'ai',
|
|
104
|
-
title: 'Testimonial',
|
|
105
|
-
prompt: 'A customer testimonial card with a quote, author name, and avatar.',
|
|
106
|
-
manifestPreview: {
|
|
107
|
-
id: 'project.Testimonial',
|
|
108
|
-
namespace: 'project',
|
|
109
|
-
props: ['quote', 'authorName', 'avatar'],
|
|
110
|
-
slots: [],
|
|
111
|
-
},
|
|
112
|
-
},
|
|
113
|
-
];
|
|
114
99
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/lib/registry/index.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAA;AAG1F,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kCAAkC,CAAA;AAEpF,OAAO,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAA;AAChF,OAAO,EAAE,+BAA+B,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AAcjG;;;;;;;;;GASG;AACH,SAAS,iBAAiB;IAIxB,MAAM,UAAU,GAAG,2BAA2B,EAAE,CAAA;IAChD,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxC,OAAO;YACL,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC5C,eAAe,EAAE,MAAM,CAAC,WAAW,CACjC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,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MAAM,eAAe,GAA8B;IACxD;QACE,EAAE,EAAE,mBAAmB;QACvB,MAAM,EAAE,OAAO;QACf,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,aAAa;QACpB,MAAM,EAAE,oEAAoE;QAC5E,eAAe,EAAE;YACf,EAAE,EAAE,qBAAqB;YACzB,SAAS,EAAE,SAAS;YACpB,KAAK,EAAE,CAAC,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC;YACxC,KAAK,EAAE,EAAE;SACV;KACF;CACF,CAAA","sourcesContent":["import { ComponentRegistry, manifestPropFields } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport type { PropFieldLookup } from '@elytracms/core/cms-core'\nimport { basePrimitives, getImplementation } from '@elytracms/core/runtime-renderer'\nimport type { ComponentImplementations, RenderContext } from '@elytracms/core/runtime-renderer'\nimport { getActiveProjectSlug, resolveDeploymentComponents } from '../workspace'\nimport { projectComponentImplementations, projectComponentManifests } from './project-components'\n\n/**\n * The Studio's view of a project's component registry (brief §7.2, §8.3): the\n * platform primitives plus the project's own components, with their\n * implementations for live previews. Deterministic singleton, built in-process\n * from code-owned manifests — component manifests live in TS next to the\n * components, so local/CI/browser runs need no backend.\n */\nexport interface StudioRegistry {\n registry: ComponentRegistry\n implementations: ComponentImplementations\n}\n\n/**\n * EC-194/EC-208/EC-223: the consuming repo's OWN real components, INJECTED through\n * config-as-code (the mount contract). The active project's `components` field holds\n * the live (manifest + implementation) pairs the consumer's `elytra.config.ts` handed\n * in by dependency injection — for Aurora these live in\n * `apps/example-site/components/marketing` (Next-free, so they render identically in\n * the studio canvas and the host). No `@site` alias and no static codegen seam: the\n * registry reads the live set off the resolved config. Absent any, the studio falls\n * back to the built-in demo fixtures (golden path).\n */\nfunction projectComponents(): {\n manifests: ComponentManifest[]\n implementations: ComponentImplementations\n} {\n const components = resolveDeploymentComponents()\n if (components && components.length > 0) {\n return {\n manifests: components.map((c) => c.manifest),\n implementations: Object.fromEntries(\n components.map((c) => [c.manifest.id, c.implementation]),\n ) as ComponentImplementations,\n }\n }\n return { manifests: projectComponentManifests, implementations: projectComponentImplementations }\n}\n\n/** Compose a StudioRegistry from the base primitives plus a project component set. */\nfunction buildStudioRegistry(project: {\n manifests: ComponentManifest[]\n implementations: ComponentImplementations\n}): StudioRegistry {\n const base = basePrimitives()\n // Inline-editable opt-ins (EC-158) live directly on the base-primitive\n // manifests (`Heading.text`, `Text.value`) in `@elytracms/core/runtime-renderer`.\n return {\n registry: new ComponentRegistry([...base.manifests, ...project.manifests]),\n implementations: { ...base.implementations, ...project.implementations },\n }\n}\n\nlet cached: StudioRegistry | null = null\nlet cachedSlug: string | null = null\n\nexport function getStudioRegistry(): StudioRegistry {\n // Re-derive when the active project changes — different projects may register\n // different component libraries (per-project registry, AD-8).\n const slug = getActiveProjectSlug()\n if (cached && cachedSlug === slug) return cached\n cached = buildStudioRegistry(projectComponents())\n cachedSlug = slug\n return cached\n}\n\n/**\n * The built-in demo fixtures as a StudioRegistry, independent of the active\n * project's `components` config ref. This is the golden-path component set\n * (`project.MarketingHero`, `FeatureCard`, `PricingCallout`, `LegacyBanner`) used\n * when a project declares no ref — and the deterministic registry that blocks /\n * clipboard / thumbnail tests pin to, so they assert against a known component set\n * regardless of which library `elytra.config.ts` happens to select (EC-194).\n */\nexport function fixtureStudioRegistry(): StudioRegistry {\n return buildStudioRegistry({\n manifests: projectComponentManifests,\n implementations: projectComponentImplementations,\n })\n}\n\n/**\n * Adapt the live registry to the cms-core {@link PropFieldLookup} contract (EC-277):\n * a component id → its prop field-defs, name-injected. Threaded into the studio's\n * write-time self-typing lens so relation/asset props inside compositions are\n * self-typed on write (\"schema leads, component adopts\"). Manifests are code (AD-11);\n * persistence/cms-core never depend on the registry — the studio supplies this shape.\n */\nexport function studioManifestLookup(): PropFieldLookup {\n const { registry } = getStudioRegistry()\n return (componentId) => {\n const manifest = registry.getManifest(componentId)\n if (!manifest) return undefined\n return Object.fromEntries(manifestPropFields(manifest).map((field) => [field.name, field]))\n }\n}\n\n/** A RenderContext for fixture previews (bindings resolve to undefined). */\nexport function previewContext(studio: StudioRegistry): RenderContext {\n return {\n registry: studio.registry,\n implementations: studio.implementations,\n resolveBinding: () => undefined,\n }\n}\n\n/**\n * Per-component status (brief §4.11, §8.3, EC-055):\n * - `invalid`: the registry reported a structured issue for this id.\n * - `incompatible`: a manifest exists but no implementation is wired up.\n * - `valid`: healthy.\n */\nexport type ComponentStatus = 'valid' | 'incompatible' | 'invalid'\n\nexport function componentStatus(\n studio: StudioRegistry,\n manifest: ComponentManifest,\n): ComponentStatus {\n if (studio.registry.issues.some((i) => i.componentId === manifest.id)) return 'invalid'\n if (!getImplementation(studio.implementations, manifest.id)) return 'incompatible'\n return 'valid'\n}\n\nexport interface RegistryHealth {\n total: number\n valid: number\n incompatible: number\n invalid: number\n}\n\nexport function registryHealth(studio: StudioRegistry): RegistryHealth {\n const all = studio.registry.list()\n const health: RegistryHealth = { total: all.length, valid: 0, incompatible: 0, invalid: 0 }\n for (const m of all) health[componentStatus(studio, m)] += 1\n return health\n}\n\n// --- AI-generated component drafts (EC-058, brief §4.8) --------------------\n//\n// Placeholder hook points for Phase 8 AI generation. A drafted component is\n// represented as inspectable data (not an opaque blob): the prompt that produced\n// it plus a manifest preview. The Components surface renders these as read-only\n// draft cards so the extension point is visible and diffable today.\n\nexport interface ComponentDraft {\n id: string\n status: 'draft'\n source: 'ai'\n title: string\n /** The natural-language intent that would drive Phase 8 generation. */\n prompt: string\n /** A preview of the manifest the generator would produce. */\n manifestPreview: {\n id: string\n namespace: 'project'\n props: string[]\n slots: string[]\n }\n}\n\nexport const componentDrafts: readonly ComponentDraft[] = [\n {\n id: 'draft_testimonial',\n status: 'draft',\n source: 'ai',\n title: 'Testimonial',\n prompt: 'A customer testimonial card with a quote, author name, and avatar.',\n manifestPreview: {\n id: 'project.Testimonial',\n namespace: 'project',\n props: ['quote', 'authorName', 'avatar'],\n slots: [],\n },\n },\n]\n"]}
|
|
1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,QAA2B;IAE3B,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,KAAK,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,SAAS,CAAA;IACvF,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC,eAAe,EAAE,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,cAAc,CAAA;IAClF,OAAO,OAAO,CAAA;AAChB,CAAC;AASD,MAAM,UAAU,cAAc,CAAC,MAAsB;IACnD,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAA;IAClC,MAAM,MAAM,GAAmB,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAA;IAC3F,KAAK,MAAM,CAAC,IAAI,GAAG;QAAE,MAAM,CAAC,eAAe,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IAC5D,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { ComponentRegistry, manifestPropFields } from '@elytracms/core/component-registry'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport type { PropFieldLookup } from '@elytracms/core/cms-core'\nimport { basePrimitives, getImplementation } from '@elytracms/core/runtime-renderer'\nimport type { ComponentImplementations, RenderContext } from '@elytracms/core/runtime-renderer'\nimport { getActiveProjectSlug, resolveDeploymentComponents } from '../workspace'\nimport { projectComponentImplementations, projectComponentManifests } from './project-components'\n\n/**\n * The Studio's view of a project's component registry (brief §7.2, §8.3): the\n * platform primitives plus the project's own components, with their\n * implementations for live previews. Deterministic singleton, built in-process\n * from code-owned manifests — component manifests live in TS next to the\n * components, so local/CI/browser runs need no backend.\n */\nexport interface StudioRegistry {\n registry: ComponentRegistry\n implementations: ComponentImplementations\n}\n\n/**\n * EC-194/EC-208/EC-223: the consuming repo's OWN real components, INJECTED through\n * config-as-code (the mount contract). The active project's `components` field holds\n * the live (manifest + implementation) pairs the consumer's `elytra.config.ts` handed\n * in by dependency injection — for Aurora these live in\n * `apps/example-site/components/marketing` (Next-free, so they render identically in\n * the studio canvas and the host). No `@site` alias and no static codegen seam: the\n * registry reads the live set off the resolved config. Absent any, the studio falls\n * back to the built-in demo fixtures (golden path).\n */\nfunction projectComponents(): {\n manifests: ComponentManifest[]\n implementations: ComponentImplementations\n} {\n const components = resolveDeploymentComponents()\n if (components && components.length > 0) {\n return {\n manifests: components.map((c) => c.manifest),\n implementations: Object.fromEntries(\n components.map((c) => [c.manifest.id, c.implementation]),\n ) as ComponentImplementations,\n }\n }\n return { manifests: projectComponentManifests, implementations: projectComponentImplementations }\n}\n\n/** Compose a StudioRegistry from the base primitives plus a project component set. */\nfunction buildStudioRegistry(project: {\n manifests: ComponentManifest[]\n implementations: ComponentImplementations\n}): StudioRegistry {\n const base = basePrimitives()\n // Inline-editable opt-ins (EC-158) live directly on the base-primitive\n // manifests (`Heading.text`, `Text.value`) in `@elytracms/core/runtime-renderer`.\n return {\n registry: new ComponentRegistry([...base.manifests, ...project.manifests]),\n implementations: { ...base.implementations, ...project.implementations },\n }\n}\n\nlet cached: StudioRegistry | null = null\nlet cachedSlug: string | null = null\n\nexport function getStudioRegistry(): StudioRegistry {\n // Re-derive when the active project changes — different projects may register\n // different component libraries (per-project registry, AD-8).\n const slug = getActiveProjectSlug()\n if (cached && cachedSlug === slug) return cached\n cached = buildStudioRegistry(projectComponents())\n cachedSlug = slug\n return cached\n}\n\n/**\n * The built-in demo fixtures as a StudioRegistry, independent of the active\n * project's `components` config ref. This is the golden-path component set\n * (`project.MarketingHero`, `FeatureCard`, `PricingCallout`, `LegacyBanner`) used\n * when a project declares no ref — and the deterministic registry that blocks /\n * clipboard / thumbnail tests pin to, so they assert against a known component set\n * regardless of which library `elytra.config.ts` happens to select (EC-194).\n */\nexport function fixtureStudioRegistry(): StudioRegistry {\n return buildStudioRegistry({\n manifests: projectComponentManifests,\n implementations: projectComponentImplementations,\n })\n}\n\n/**\n * Adapt the live registry to the cms-core {@link PropFieldLookup} contract (EC-277):\n * a component id → its prop field-defs, name-injected. Threaded into the studio's\n * write-time self-typing lens so relation/asset props inside compositions are\n * self-typed on write (\"schema leads, component adopts\"). Manifests are code (AD-11);\n * persistence/cms-core never depend on the registry — the studio supplies this shape.\n */\nexport function studioManifestLookup(): PropFieldLookup {\n const { registry } = getStudioRegistry()\n return (componentId) => {\n const manifest = registry.getManifest(componentId)\n if (!manifest) return undefined\n return Object.fromEntries(manifestPropFields(manifest).map((field) => [field.name, field]))\n }\n}\n\n/** A RenderContext for fixture previews (bindings resolve to undefined). */\nexport function previewContext(studio: StudioRegistry): RenderContext {\n return {\n registry: studio.registry,\n implementations: studio.implementations,\n resolveBinding: () => undefined,\n }\n}\n\n/**\n * Per-component status (brief §4.11, §8.3, EC-055):\n * - `invalid`: the registry reported a structured issue for this id.\n * - `incompatible`: a manifest exists but no implementation is wired up.\n * - `valid`: healthy.\n */\nexport type ComponentStatus = 'valid' | 'incompatible' | 'invalid'\n\nexport function componentStatus(\n studio: StudioRegistry,\n manifest: ComponentManifest,\n): ComponentStatus {\n if (studio.registry.issues.some((i) => i.componentId === manifest.id)) return 'invalid'\n if (!getImplementation(studio.implementations, manifest.id)) return 'incompatible'\n return 'valid'\n}\n\nexport interface RegistryHealth {\n total: number\n valid: number\n incompatible: number\n invalid: number\n}\n\nexport function registryHealth(studio: StudioRegistry): RegistryHealth {\n const all = studio.registry.list()\n const health: RegistryHealth = { total: all.length, valid: 0, incompatible: 0, invalid: 0 }\n for (const m of all) health[componentStatus(studio, m)] += 1\n return health\n}\n"]}
|
|
@@ -24,11 +24,6 @@
|
|
|
24
24
|
* `collection:<name>:<locale>` membership tag for **all** configured
|
|
25
25
|
* locales, sweeping cached lists whose membership may have changed
|
|
26
26
|
* (new/removed/newly-matching documents).
|
|
27
|
-
* - **Graph publish/unpublish** (`publishing.*`): the whole-project sweep tag
|
|
28
|
-
* `project` — a layout, route, or binding change can affect any page, so
|
|
29
|
-
* the honest v1 fallback (a superset of the per-route + per-collection
|
|
30
|
-
* sweep) is to drop every cached entry of the project. Unrelated projects
|
|
31
|
-
* stay cached.
|
|
32
27
|
* - **Asset edit** (`assets.upsert` of an existing asset, `assets.remove`,
|
|
33
28
|
* EC-227): the `asset:<id>` tag, dropping exactly the pages that *baked* that
|
|
34
29
|
* asset's delivery shape (alt/dimensions/url). An `assets.upsert` CREATE (no
|
|
@@ -69,7 +64,6 @@ const DOCUMENT_OPERATIONS = new Set([
|
|
|
69
64
|
'documents.unpublish',
|
|
70
65
|
'documents.pinVersion',
|
|
71
66
|
]);
|
|
72
|
-
const PUBLISHING_OPERATIONS = new Set(['publishing.publish', 'publishing.unpublish']);
|
|
73
67
|
/**
|
|
74
68
|
* Asset-record mutations (EC-227): editing an asset (alt/dimensions/re-upload)
|
|
75
69
|
* must drop the published pages that *baked* its delivery shape, which carry the
|
|
@@ -114,20 +108,12 @@ export function webhookTagsForEvent(event, options) {
|
|
|
114
108
|
if (event.status !== 'succeeded' || event.kind !== 'command')
|
|
115
109
|
return null;
|
|
116
110
|
const isDocument = DOCUMENT_OPERATIONS.has(event.operation);
|
|
117
|
-
const isPublishing = PUBLISHING_OPERATIONS.has(event.operation);
|
|
118
111
|
const isAsset = ASSET_OPERATIONS.has(event.operation);
|
|
119
|
-
if (!isDocument && !
|
|
112
|
+
if (!isDocument && !isAsset)
|
|
120
113
|
return null;
|
|
121
114
|
const projectId = projectIdOfSummary(event.inputSummary);
|
|
122
115
|
if (projectId === undefined)
|
|
123
116
|
return null;
|
|
124
|
-
if (isPublishing) {
|
|
125
|
-
return {
|
|
126
|
-
projectId,
|
|
127
|
-
event: event.operation,
|
|
128
|
-
tags: [projectSweepWebhookTag(projectId)],
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
117
|
if (isAsset)
|
|
132
118
|
return assetTagsForEvent(projectId, event);
|
|
133
119
|
const parsed = parseSummary(event.inputSummary);
|
|
@@ -142,7 +128,7 @@ export function webhookTagsForEvent(event, options) {
|
|
|
142
128
|
}
|
|
143
129
|
// EC-207: routes/redirects are config-owned (a code deploy, which rebuilds the
|
|
144
130
|
// host) — they are no longer DB documents, so there is no route-document event
|
|
145
|
-
// to sweep the project for.
|
|
131
|
+
// to sweep the project for.
|
|
146
132
|
return { projectId, event: event.operation, tags: [...tags].sort() };
|
|
147
133
|
}
|
|
148
134
|
/** A non-empty string, else `undefined` (the asset id out of a summary). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tags.js","sourceRoot":"","sources":["../../../src/lib/webhooks/tags.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH,SAAS,MAAM,CAAC,SAAiB,EAAE,GAAW;IAC5C,OAAO,KAAK,SAAS,IAAI,GAAG,EAAE,CAAA;AAChC,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,aAAa,CAAC,SAAiB,EAAE,UAAkB,EAAE,EAAU;IAC7E,OAAO,MAAM,CAAC,SAAS,EAAE,OAAO,UAAU,IAAI,EAAE,EAAE,CAAC,CAAA;AACrD,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,oBAAoB,CAClC,SAAiB,EACjB,UAAkB,EAClB,MAAc;IAEd,OAAO,MAAM,CAAC,SAAS,EAAE,cAAc,UAAU,IAAI,MAAM,EAAE,CAAC,CAAA;AAChE,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,eAAe,CAAC,SAAiB,EAAE,OAAe;IAChE,OAAO,MAAM,CAAC,SAAS,EAAE,SAAS,OAAO,EAAE,CAAC,CAAA;AAC9C,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,sBAAsB,CAAC,SAAiB;IACtD,OAAO,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;AACrC,CAAC;AAED,8EAA8E;AAC9E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K,EAAE,KAAK,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,eAAe,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,EAAE,CAAA;IAC3F,CAAC;IACD,OAAO,KAAK,CAAC,SAAS,KAAK,eAAe;QACxC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,sBAAsB,CAAC,SAAS,CAAC,CAAC,EAAE;QAClF,CAAC,CAAC,IAAI,CAAA;AACV,CAAC","sourcesContent":["import type { OperationEvent } from '@elytracms/core/operations'\n\n/**\n * Pure tag computation for the EC-146 revalidation webhooks: map a succeeded\n * publish-shaped operation event onto the Next cache tags it invalidates.\n *\n * ## Tag format (mirror of `packages/next/src/cache.ts`)\n *\n * The canonical tag format lives in `@elytracms/next` (`src/cache.ts`). The\n * builder cannot depend on that package — it would drag the `next` peer\n * dependency into the studio bundle — so the three formatters are mirrored\n * here. Both sides pin the exact literal strings in their tests\n * (`tags.test.ts` here, `cache.test.ts` there) to keep them in lock-step.\n *\n * Every emitted tag is scoped `p:<projectId>:…` — the dispatcher always knows\n * the project id, and the scope keeps multi-project hosts from\n * cross-invalidating. Hosts must configure the same id as `cache.scope`.\n *\n * ## Which events produce which tags\n *\n * - **Document publish/unpublish/delete/save** (`documents.publish`,\n * `documents.unpublish`, `documents.pinVersion`, `documents.upsert`,\n * `documents.delete`): the document's own\n * `doc:<collection>:<id>` tag — dropping its detail page *and every cached\n * list that actually contained it* (fetch-time tagging) — plus the coarse\n * `collection:<name>:<locale>` membership tag for **all** configured\n * locales, sweeping cached lists whose membership may have changed\n * (new/removed/newly-matching documents).\n * - **Graph publish/unpublish** (`publishing.*`): the whole-project sweep tag\n * `project` — a layout, route, or binding change can affect any page, so\n * the honest v1 fallback (a superset of the per-route + per-collection\n * sweep) is to drop every cached entry of the project. Unrelated projects\n * stay cached.\n * - **Asset edit** (`assets.upsert` of an existing asset, `assets.remove`,\n * EC-227): the `asset:<id>` tag, dropping exactly the pages that *baked* that\n * asset's delivery shape (alt/dimensions/url). An `assets.upsert` CREATE (no\n * id in the summary — minted server-side) fires nothing: a brand-new asset is\n * in no cached page yet.\n * - **Fallback**: when a `documents` (or `assets.remove`) event's input summary\n * was truncated past the identity (EC-139 caps summaries at 160 chars; only\n * very large upserts hit this), the project sweep tag is emitted — coarse,\n * always correct, mirroring the EC-155 reference-index fallback.\n */\n\nfunction scoped(projectId: string, tag: string): string {\n return `p:${projectId}:${tag}`\n}\n\n/** `p:<projectId>:doc:<collection>:<id>` — mirror of `docCacheTag`. */\nexport function docWebhookTag(projectId: string, collection: string, id: string): string {\n return scoped(projectId, `doc:${collection}:${id}`)\n}\n\n/** `p:<projectId>:collection:<name>:<locale>` — mirror of `collectionCacheTag`. */\nexport function collectionWebhookTag(\n projectId: string,\n collection: string,\n locale: string,\n): string {\n return scoped(projectId, `collection:${collection}:${locale}`)\n}\n\n/** `p:<projectId>:asset:<id>` — mirror of `assetCacheTag` (EC-227). */\nexport function assetWebhookTag(projectId: string, assetId: string): string {\n return scoped(projectId, `asset:${assetId}`)\n}\n\n/** `p:<projectId>:project` — mirror of `projectSweepTag`. */\nexport function projectSweepWebhookTag(projectId: string): string {\n return scoped(projectId, 'project')\n}\n\n/** The operations whose success must reach the host's revalidate endpoint. */\nconst DOCUMENT_OPERATIONS = new Set([\n 'documents.upsert',\n 'documents.delete',\n // EC-224: publish/unpublish/pinVersion move the version pointer; their\n // `{ projectId, ref }` input drives the same doc + per-locale collection tag\n // set (the flat `documents.setState` op is gone).\n 'documents.publish',\n 'documents.unpublish',\n 'documents.pinVersion',\n])\nconst PUBLISHING_OPERATIONS = new Set(['publishing.publish', 'publishing.unpublish'])\n/**\n * Asset-record mutations (EC-227): editing an asset (alt/dimensions/re-upload)\n * must drop the published pages that *baked* its delivery shape, which carry the\n * `asset:<id>` tag. `assets.remove` always carries `assetId`; `assets.upsert`\n * carries `asset.id` only on an EDIT (a CREATE mints the id server-side).\n */\nconst ASSET_OPERATIONS = new Set(['assets.upsert', 'assets.remove'])\n\n/** One computed webhook emission: which project, why, and which tags. */\nexport interface WebhookTagSet {\n projectId: string\n /** The operation name, carried verbatim as the webhook `event`. */\n event: string\n /** Sorted, deduplicated, fully scoped Next tag strings. */\n tags: string[]\n}\n\n/** Tolerant parse of an EC-139 input summary (may be truncated past 160 chars). */\nfunction parseSummary(summary: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(summary)\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Extract the projectId even from a truncated summary (it serializes first). */\nfunction projectIdOfSummary(summary: string): string | undefined {\n const match = /\"projectId\":\"([^\"]+)\"/.exec(summary)\n return match?.[1]\n}\n\nfunction documentRefOf(value: unknown): { collection: string; id: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const candidate = value as { collection?: unknown; id?: unknown }\n return typeof candidate.collection === 'string' &&\n candidate.collection.length > 0 &&\n typeof candidate.id === 'string' &&\n candidate.id.length > 0\n ? { collection: candidate.collection, id: candidate.id }\n : undefined\n}\n\n/**\n * Compute the webhook tag set for one lifecycle event, or `null` when the\n * event is not a successful publish-shaped command (queries, failures, and\n * unrelated domains never fire webhooks).\n */\nexport function webhookTagsForEvent(\n event: Pick<OperationEvent, 'operation' | 'kind' | 'status' | 'inputSummary'>,\n options: { locales: readonly string[] },\n): WebhookTagSet | null {\n if (event.status !== 'succeeded' || event.kind !== 'command') return null\n\n const isDocument = DOCUMENT_OPERATIONS.has(event.operation)\n const isPublishing = PUBLISHING_OPERATIONS.has(event.operation)\n const isAsset = ASSET_OPERATIONS.has(event.operation)\n if (!isDocument && !isPublishing && !isAsset) return null\n\n const projectId = projectIdOfSummary(event.inputSummary)\n if (projectId === undefined) return null\n\n if (isPublishing) {\n return {\n projectId,\n event: event.operation,\n tags: [projectSweepWebhookTag(projectId)],\n }\n }\n\n if (isAsset) return assetTagsForEvent(projectId, event)\n\n const parsed = parseSummary(event.inputSummary)\n const ref = documentRefOf(parsed?.['ref']) ?? documentRefOf(parsed?.['document'])\n if (!ref) {\n // Truncated summary (large upsert payload): honest coarse fallback.\n return { projectId, event: event.operation, tags: [projectSweepWebhookTag(projectId)] }\n }\n\n const tags = new Set<string>([docWebhookTag(projectId, ref.collection, ref.id)])\n for (const locale of options.locales) {\n tags.add(collectionWebhookTag(projectId, ref.collection, locale))\n }\n // EC-207: routes/redirects are config-owned (a code deploy, which rebuilds the\n // host) — they are no longer DB documents, so there is no route-document event\n // to sweep the project for. Graph publishes still emit the project sweep above.\n return { projectId, event: event.operation, tags: [...tags].sort() }\n}\n\n/** A non-empty string, else `undefined` (the asset id out of a summary). */\nfunction stringOf(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Tags for an asset mutation (EC-227). The edit cases — `assets.remove` (carries\n * `assetId`) and `assets.upsert` of an existing asset (carries `asset.id`) —\n * emit exactly `asset:<id>`, dropping the pages that baked that asset. An\n * `assets.upsert` with **no** id is a CREATE: the id is minted server-side and a\n * brand-new asset cannot be baked into any existing page, so it invalidates\n * nothing (`null`, no webhook). A `remove` missing its id means a truncated\n * summary — sweep the project (coarse, always correct — the document fallback).\n */\nfunction assetTagsForEvent(\n projectId: string,\n event: Pick<OperationEvent, 'operation' | 'inputSummary'>,\n): WebhookTagSet | null {\n const parsed = parseSummary(event.inputSummary)\n const assetId =\n event.operation === 'assets.remove'\n ? stringOf(parsed?.['assetId'])\n : stringOf((parsed?.['asset'] as { id?: unknown } | undefined)?.id)\n if (assetId) {\n return { projectId, event: event.operation, tags: [assetWebhookTag(projectId, assetId)] }\n }\n return event.operation === 'assets.remove'\n ? { projectId, event: event.operation, tags: [projectSweepWebhookTag(projectId)] }\n : null\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tags.js","sourceRoot":"","sources":["../../../src/lib/webhooks/tags.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;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;;GAQG;AACH,SAAS,iBAAiB,CACxB,SAAiB,EACjB,KAAyD;IAEzD,MAAM,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC,YAAY,CAAC,CAAA;IAC/C,MAAM,OAAO,GACX,KAAK,CAAC,SAAS,KAAK,eAAe;QACjC,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC,CAAC,QAAQ,CAAE,MAAM,EAAE,CAAC,OAAO,CAAkC,EAAE,EAAE,CAAC,CAAA;IACvE,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,eAAe,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,EAAE,CAAA;IAC3F,CAAC;IACD,OAAO,KAAK,CAAC,SAAS,KAAK,eAAe;QACxC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,CAAC,SAAS,EAAE,IAAI,EAAE,CAAC,sBAAsB,CAAC,SAAS,CAAC,CAAC,EAAE;QAClF,CAAC,CAAC,IAAI,CAAA;AACV,CAAC","sourcesContent":["import type { OperationEvent } from '@elytracms/core/operations'\n\n/**\n * Pure tag computation for the EC-146 revalidation webhooks: map a succeeded\n * publish-shaped operation event onto the Next cache tags it invalidates.\n *\n * ## Tag format (mirror of `packages/next/src/cache.ts`)\n *\n * The canonical tag format lives in `@elytracms/next` (`src/cache.ts`). The\n * builder cannot depend on that package — it would drag the `next` peer\n * dependency into the studio bundle — so the three formatters are mirrored\n * here. Both sides pin the exact literal strings in their tests\n * (`tags.test.ts` here, `cache.test.ts` there) to keep them in lock-step.\n *\n * Every emitted tag is scoped `p:<projectId>:…` — the dispatcher always knows\n * the project id, and the scope keeps multi-project hosts from\n * cross-invalidating. Hosts must configure the same id as `cache.scope`.\n *\n * ## Which events produce which tags\n *\n * - **Document publish/unpublish/delete/save** (`documents.publish`,\n * `documents.unpublish`, `documents.pinVersion`, `documents.upsert`,\n * `documents.delete`): the document's own\n * `doc:<collection>:<id>` tag — dropping its detail page *and every cached\n * list that actually contained it* (fetch-time tagging) — plus the coarse\n * `collection:<name>:<locale>` membership tag for **all** configured\n * locales, sweeping cached lists whose membership may have changed\n * (new/removed/newly-matching documents).\n * - **Asset edit** (`assets.upsert` of an existing asset, `assets.remove`,\n * EC-227): the `asset:<id>` tag, dropping exactly the pages that *baked* that\n * asset's delivery shape (alt/dimensions/url). An `assets.upsert` CREATE (no\n * id in the summary — minted server-side) fires nothing: a brand-new asset is\n * in no cached page yet.\n * - **Fallback**: when a `documents` (or `assets.remove`) event's input summary\n * was truncated past the identity (EC-139 caps summaries at 160 chars; only\n * very large upserts hit this), the project sweep tag is emitted — coarse,\n * always correct, mirroring the EC-155 reference-index fallback.\n */\n\nfunction scoped(projectId: string, tag: string): string {\n return `p:${projectId}:${tag}`\n}\n\n/** `p:<projectId>:doc:<collection>:<id>` — mirror of `docCacheTag`. */\nexport function docWebhookTag(projectId: string, collection: string, id: string): string {\n return scoped(projectId, `doc:${collection}:${id}`)\n}\n\n/** `p:<projectId>:collection:<name>:<locale>` — mirror of `collectionCacheTag`. */\nexport function collectionWebhookTag(\n projectId: string,\n collection: string,\n locale: string,\n): string {\n return scoped(projectId, `collection:${collection}:${locale}`)\n}\n\n/** `p:<projectId>:asset:<id>` — mirror of `assetCacheTag` (EC-227). */\nexport function assetWebhookTag(projectId: string, assetId: string): string {\n return scoped(projectId, `asset:${assetId}`)\n}\n\n/** `p:<projectId>:project` — mirror of `projectSweepTag`. */\nexport function projectSweepWebhookTag(projectId: string): string {\n return scoped(projectId, 'project')\n}\n\n/** The operations whose success must reach the host's revalidate endpoint. */\nconst DOCUMENT_OPERATIONS = new Set([\n 'documents.upsert',\n 'documents.delete',\n // EC-224: publish/unpublish/pinVersion move the version pointer; their\n // `{ projectId, ref }` input drives the same doc + per-locale collection tag\n // set (the flat `documents.setState` op is gone).\n 'documents.publish',\n 'documents.unpublish',\n 'documents.pinVersion',\n])\n/**\n * Asset-record mutations (EC-227): editing an asset (alt/dimensions/re-upload)\n * must drop the published pages that *baked* its delivery shape, which carry the\n * `asset:<id>` tag. `assets.remove` always carries `assetId`; `assets.upsert`\n * carries `asset.id` only on an EDIT (a CREATE mints the id server-side).\n */\nconst ASSET_OPERATIONS = new Set(['assets.upsert', 'assets.remove'])\n\n/** One computed webhook emission: which project, why, and which tags. */\nexport interface WebhookTagSet {\n projectId: string\n /** The operation name, carried verbatim as the webhook `event`. */\n event: string\n /** Sorted, deduplicated, fully scoped Next tag strings. */\n tags: string[]\n}\n\n/** Tolerant parse of an EC-139 input summary (may be truncated past 160 chars). */\nfunction parseSummary(summary: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(summary)\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Extract the projectId even from a truncated summary (it serializes first). */\nfunction projectIdOfSummary(summary: string): string | undefined {\n const match = /\"projectId\":\"([^\"]+)\"/.exec(summary)\n return match?.[1]\n}\n\nfunction documentRefOf(value: unknown): { collection: string; id: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const candidate = value as { collection?: unknown; id?: unknown }\n return typeof candidate.collection === 'string' &&\n candidate.collection.length > 0 &&\n typeof candidate.id === 'string' &&\n candidate.id.length > 0\n ? { collection: candidate.collection, id: candidate.id }\n : undefined\n}\n\n/**\n * Compute the webhook tag set for one lifecycle event, or `null` when the\n * event is not a successful publish-shaped command (queries, failures, and\n * unrelated domains never fire webhooks).\n */\nexport function webhookTagsForEvent(\n event: Pick<OperationEvent, 'operation' | 'kind' | 'status' | 'inputSummary'>,\n options: { locales: readonly string[] },\n): WebhookTagSet | null {\n if (event.status !== 'succeeded' || event.kind !== 'command') return null\n\n const isDocument = DOCUMENT_OPERATIONS.has(event.operation)\n const isAsset = ASSET_OPERATIONS.has(event.operation)\n if (!isDocument && !isAsset) return null\n\n const projectId = projectIdOfSummary(event.inputSummary)\n if (projectId === undefined) return null\n\n if (isAsset) return assetTagsForEvent(projectId, event)\n\n const parsed = parseSummary(event.inputSummary)\n const ref = documentRefOf(parsed?.['ref']) ?? documentRefOf(parsed?.['document'])\n if (!ref) {\n // Truncated summary (large upsert payload): honest coarse fallback.\n return { projectId, event: event.operation, tags: [projectSweepWebhookTag(projectId)] }\n }\n\n const tags = new Set<string>([docWebhookTag(projectId, ref.collection, ref.id)])\n for (const locale of options.locales) {\n tags.add(collectionWebhookTag(projectId, ref.collection, locale))\n }\n // EC-207: routes/redirects are config-owned (a code deploy, which rebuilds the\n // host) — they are no longer DB documents, so there is no route-document event\n // to sweep the project for.\n return { projectId, event: event.operation, tags: [...tags].sort() }\n}\n\n/** A non-empty string, else `undefined` (the asset id out of a summary). */\nfunction stringOf(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * Tags for an asset mutation (EC-227). The edit cases — `assets.remove` (carries\n * `assetId`) and `assets.upsert` of an existing asset (carries `asset.id`) —\n * emit exactly `asset:<id>`, dropping the pages that baked that asset. An\n * `assets.upsert` with **no** id is a CREATE: the id is minted server-side and a\n * brand-new asset cannot be baked into any existing page, so it invalidates\n * nothing (`null`, no webhook). A `remove` missing its id means a truncated\n * summary — sweep the project (coarse, always correct — the document fallback).\n */\nfunction assetTagsForEvent(\n projectId: string,\n event: Pick<OperationEvent, 'operation' | 'inputSummary'>,\n): WebhookTagSet | null {\n const parsed = parseSummary(event.inputSummary)\n const assetId =\n event.operation === 'assets.remove'\n ? stringOf(parsed?.['assetId'])\n : stringOf((parsed?.['asset'] as { id?: unknown } | undefined)?.id)\n if (assetId) {\n return { projectId, event: event.operation, tags: [assetWebhookTag(projectId, assetId)] }\n }\n return event.operation === 'assets.remove'\n ? { projectId, event: event.operation, tags: [projectSweepWebhookTag(projectId)] }\n : null\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elytracms/studio",
|
|
3
3
|
"author": "finaldream <hi@finaldream.de>",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.15",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "The Elytra studio engine (UI + lib + routes + data-only Convex schema) as an importable package. Extraction staged in EXTRACTION.md (EC-223); Stages 1-2 = UI primitives + router-free lib leaves.",
|
|
7
7
|
"license": "MIT",
|
|
@@ -109,10 +109,11 @@
|
|
|
109
109
|
"class-variance-authority": "^0.7.1",
|
|
110
110
|
"clsx": "^2.1.1",
|
|
111
111
|
"convex": "^1.40.0",
|
|
112
|
+
"convex-helpers": "0.1.120",
|
|
112
113
|
"lucide-react": "^1.17.0",
|
|
113
114
|
"tailwind-merge": "^3.6.0",
|
|
114
115
|
"zod": "^4.0.0",
|
|
115
|
-
"@elytracms/core": "^0.0.
|
|
116
|
+
"@elytracms/core": "^0.0.15"
|
|
116
117
|
},
|
|
117
118
|
"peerDependencies": {
|
|
118
119
|
"@tanstack/react-router": "^1.170.0",
|
package/convex/graphs.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { v } from 'convex/values'
|
|
2
|
-
import { mutation, query } from './functions'
|
|
3
|
-
import { requireRole } from './guard'
|
|
4
|
-
import { maintainGraphDraftReferences } from './referenceMaintenance'
|
|
5
|
-
|
|
6
|
-
/** Project graph + revision persistence (EC-041). Revisions are append-only. */
|
|
7
|
-
|
|
8
|
-
export const saveRevision = mutation({
|
|
9
|
-
args: {
|
|
10
|
-
serializedGraph: v.string(),
|
|
11
|
-
schemaVersion: v.number(),
|
|
12
|
-
createdAt: v.string(),
|
|
13
|
-
label: v.optional(v.string()),
|
|
14
|
-
message: v.optional(v.string()),
|
|
15
|
-
},
|
|
16
|
-
handler: async (ctx, args) => {
|
|
17
|
-
await requireRole(ctx, 'editor') // EC-150
|
|
18
|
-
// Compute the next revision atomically inside the mutation.
|
|
19
|
-
const last = await ctx.db.query('graphRevisions').withIndex('by_revision').order('desc').first()
|
|
20
|
-
const revision = (last?.revision ?? 0) + 1
|
|
21
|
-
const id = await ctx.db.insert('graphRevisions', { ...args, revision })
|
|
22
|
-
const record = await ctx.db.get(id)
|
|
23
|
-
// EC-277: the latest revision IS the draft graph — reindex its component-usage
|
|
24
|
-
// and self-typed static-prop references in-transaction (AD-6 "at the source").
|
|
25
|
-
await maintainGraphDraftReferences(ctx, args.serializedGraph)
|
|
26
|
-
return record
|
|
27
|
-
},
|
|
28
|
-
})
|
|
29
|
-
|
|
30
|
-
export const latest = query({
|
|
31
|
-
args: {},
|
|
32
|
-
handler: async (ctx) => {
|
|
33
|
-
await requireRole(ctx, 'viewer') // EC-150
|
|
34
|
-
return ctx.db.query('graphRevisions').withIndex('by_revision').order('desc').first()
|
|
35
|
-
},
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
export const revision = query({
|
|
39
|
-
args: { revision: v.number() },
|
|
40
|
-
handler: async (ctx, args) => {
|
|
41
|
-
await requireRole(ctx, 'viewer') // EC-150
|
|
42
|
-
return ctx.db
|
|
43
|
-
.query('graphRevisions')
|
|
44
|
-
.withIndex('by_revision', (q) => q.eq('revision', args.revision))
|
|
45
|
-
.first()
|
|
46
|
-
},
|
|
47
|
-
})
|
|
48
|
-
|
|
49
|
-
export const listRevisions = query({
|
|
50
|
-
args: {},
|
|
51
|
-
handler: async (ctx) => {
|
|
52
|
-
await requireRole(ctx, 'viewer') // EC-150
|
|
53
|
-
return ctx.db.query('graphRevisions').withIndex('by_revision').order('desc').collect()
|
|
54
|
-
},
|
|
55
|
-
})
|