@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -10
  3. package/dist/abi/canvas-live.d.ts +49 -0
  4. package/dist/abi/canvas-live.js +88 -0
  5. package/dist/abi/cart.d.ts +48 -0
  6. package/dist/abi/cart.js +321 -0
  7. package/dist/abi/convert.d.ts +192 -0
  8. package/dist/abi/convert.js +670 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +198 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/page-data.d.ts +209 -0
  14. package/dist/abi/page-data.js +583 -0
  15. package/dist/abi/page.d.ts +23 -0
  16. package/dist/abi/page.js +46 -0
  17. package/dist/abi/referrals.d.ts +23 -0
  18. package/dist/abi/referrals.js +89 -0
  19. package/dist/abi/rewards.d.ts +27 -0
  20. package/dist/abi/rewards.js +82 -0
  21. package/dist/abi/seo.d.ts +47 -0
  22. package/dist/abi/seo.js +68 -0
  23. package/dist/abi/shell.d.ts +22 -0
  24. package/dist/abi/shell.js +10 -0
  25. package/dist/abi/wire.d.ts +38 -0
  26. package/dist/abi/wire.js +84 -0
  27. package/dist/build.d.ts +113 -0
  28. package/dist/build.js +294 -0
  29. package/dist/client.d.ts +19 -0
  30. package/dist/client.js +76 -0
  31. package/dist/contract.d.ts +6 -0
  32. package/dist/contract.js +6 -0
  33. package/dist/headless/ai.d.ts +132 -0
  34. package/dist/headless/ai.js +99 -0
  35. package/dist/headless/hooks.d.ts +273 -0
  36. package/dist/headless/hooks.js +533 -0
  37. package/dist/headless/i18n.d.ts +13 -0
  38. package/dist/headless/i18n.js +45 -0
  39. package/dist/headless/index.d.ts +36 -0
  40. package/dist/headless/index.js +38 -0
  41. package/dist/headless/money.d.ts +25 -0
  42. package/dist/headless/money.js +61 -0
  43. package/dist/headless/page.d.ts +43 -0
  44. package/dist/headless/page.js +53 -0
  45. package/dist/headless/platform.d.ts +55 -0
  46. package/dist/headless/platform.js +77 -0
  47. package/dist/headless/primitives/cart.d.ts +90 -0
  48. package/dist/headless/primitives/cart.js +153 -0
  49. package/dist/headless/primitives/collection.d.ts +68 -0
  50. package/dist/headless/primitives/collection.js +80 -0
  51. package/dist/headless/primitives/product.d.ts +101 -0
  52. package/dist/headless/primitives/product.js +117 -0
  53. package/dist/headless/primitives/storefront.d.ts +106 -0
  54. package/dist/headless/primitives/storefront.js +186 -0
  55. package/dist/headless/primitives/util.d.ts +19 -0
  56. package/dist/headless/primitives/util.js +42 -0
  57. package/dist/headless/strings.d.ts +9 -0
  58. package/dist/headless/strings.js +186 -0
  59. package/dist/headless/structured-data.d.ts +31 -0
  60. package/dist/headless/structured-data.js +57 -0
  61. package/dist/headless/theme.d.ts +99 -0
  62. package/dist/headless/theme.js +54 -0
  63. package/dist/index.d.ts +20 -0
  64. package/dist/index.js +18 -553
  65. package/dist/runtime/data/StoreProvider.d.ts +56 -0
  66. package/dist/runtime/data/StoreProvider.js +308 -0
  67. package/dist/runtime/data/handle.d.ts +14 -0
  68. package/dist/runtime/data/handle.js +16 -0
  69. package/dist/runtime/data/routes.d.ts +87 -0
  70. package/dist/runtime/data/routes.js +154 -0
  71. package/dist/runtime/data/to-ui.d.ts +258 -0
  72. package/dist/runtime/data/to-ui.js +820 -0
  73. package/dist/runtime/entries/register.d.ts +9 -0
  74. package/dist/runtime/entries/register.js +9 -0
  75. package/dist/runtime/entries/sections.d.ts +16 -0
  76. package/dist/runtime/entries/sections.js +19 -0
  77. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  78. package/dist/runtime/kit/SectionTree.js +100 -0
  79. package/dist/runtime/kit/analytics.d.ts +63 -0
  80. package/dist/runtime/kit/analytics.js +233 -0
  81. package/dist/runtime/kit/cart.d.ts +186 -0
  82. package/dist/runtime/kit/cart.js +545 -0
  83. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  84. package/dist/runtime/kit/composition.js +3 -0
  85. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  86. package/dist/runtime/kit/config.js +6 -0
  87. package/dist/runtime/kit/consent.d.ts +29 -0
  88. package/dist/runtime/kit/consent.js +159 -0
  89. package/dist/runtime/kit/contract/content.d.ts +164 -0
  90. package/dist/runtime/kit/contract/content.js +83 -0
  91. package/dist/runtime/kit/contract/field-types.d.ts +290 -0
  92. package/dist/runtime/kit/contract/field-types.js +129 -0
  93. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  94. package/dist/runtime/kit/contract/groups.js +402 -0
  95. package/dist/runtime/kit/contract/index.d.ts +33 -0
  96. package/dist/runtime/kit/contract/index.js +33 -0
  97. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  98. package/dist/runtime/kit/contract/transform.js +133 -0
  99. package/dist/runtime/kit/contract/validate.d.ts +67 -0
  100. package/dist/runtime/kit/contract/validate.js +388 -0
  101. package/dist/runtime/kit/data.d.ts +636 -0
  102. package/dist/runtime/kit/data.js +1117 -0
  103. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  104. package/dist/runtime/kit/defineSection.js +10 -0
  105. package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
  106. package/dist/runtime/kit/dynamic-source.js +143 -0
  107. package/dist/runtime/kit/index.d.ts +24 -0
  108. package/dist/runtime/kit/index.js +24 -0
  109. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  110. package/dist/runtime/kit/jsx-to-json.js +28 -0
  111. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  112. package/dist/runtime/kit/mount.js +124 -0
  113. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  114. package/dist/runtime/kit/registry.js +12 -0
  115. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  116. package/dist/runtime/kit/ssg.js +56 -0
  117. package/dist/runtime/kit/storefront.d.ts +566 -0
  118. package/dist/runtime/kit/storefront.js +723 -0
  119. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  120. package/dist/runtime/kit/theme-context.js +25 -0
  121. package/dist/runtime/kit/types.d.ts +142 -0
  122. package/dist/runtime/kit/types.js +1 -0
  123. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  124. package/dist/runtime/platform/TrackingPixels.js +63 -0
  125. package/dist/runtime/platform/environment.d.ts +68 -0
  126. package/dist/runtime/platform/environment.js +85 -0
  127. package/dist/runtime/platform/locale.d.ts +27 -0
  128. package/dist/runtime/platform/locale.js +42 -0
  129. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  130. package/dist/runtime/platform/route-analytics.js +72 -0
  131. package/dist/runtime/platform/safe-href.d.ts +25 -0
  132. package/dist/runtime/platform/safe-href.js +69 -0
  133. package/dist/runtime/platform/safe-values.d.ts +37 -0
  134. package/dist/runtime/platform/safe-values.js +140 -0
  135. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  136. package/dist/runtime/render/SectionRenderer.js +111 -0
  137. package/dist/runtime/render/listing-query.d.ts +47 -0
  138. package/dist/runtime/render/listing-query.js +114 -0
  139. package/dist/runtime/render/localized-copy.d.ts +86 -0
  140. package/dist/runtime/render/localized-copy.js +129 -0
  141. package/dist/runtime/render/product-listing.d.ts +11 -0
  142. package/dist/runtime/render/product-listing.js +240 -0
  143. package/dist/runtime/render/section-actions.d.ts +48 -0
  144. package/dist/runtime/render/section-actions.js +170 -0
  145. package/dist/runtime/render/starter.d.ts +11 -0
  146. package/dist/runtime/render/starter.js +81 -0
  147. package/dist/runtime/seo/head.d.ts +87 -0
  148. package/dist/runtime/seo/head.js +224 -0
  149. package/dist/runtime/seo/structured-data.d.ts +22 -0
  150. package/dist/runtime/seo/structured-data.js +115 -0
  151. package/dist/runtime/shell/PageShell.d.ts +18 -0
  152. package/dist/runtime/shell/PageShell.js +113 -0
  153. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  154. package/dist/runtime/shell/RuntimeBridge.js +85 -0
  155. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  156. package/dist/runtime/shell/overlay-state.js +59 -0
  157. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  158. package/dist/runtime/shell/preview-mode.js +11 -0
  159. package/dist/runtime/shell/spa-router.d.ts +14 -0
  160. package/dist/runtime/shell/spa-router.js +76 -0
  161. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  162. package/dist/runtime/shell/url-redirects.js +37 -0
  163. package/dist/runtime/slots.d.ts +74 -0
  164. package/dist/runtime/slots.js +16 -0
  165. package/dist/runtime.d.ts +34 -0
  166. package/dist/runtime.js +40 -0
  167. package/dist/sdk/index.d.ts +24 -0
  168. package/dist/sdk/index.js +24 -0
  169. package/dist/sdk/referrals.d.ts +62 -0
  170. package/dist/sdk/referrals.js +20 -0
  171. package/dist/sdk/rewards.d.ts +85 -0
  172. package/dist/sdk/rewards.js +29 -0
  173. package/dist/sdk/runtime-context.d.ts +135 -0
  174. package/dist/sdk/runtime-context.js +73 -0
  175. package/dist/sdk/schema.d.ts +197 -0
  176. package/dist/sdk/schema.js +121 -0
  177. package/dist/sdk/server-render.d.ts +8 -0
  178. package/dist/sdk/server-render.js +12 -0
  179. package/dist/sdk/store-lookup.d.ts +27 -0
  180. package/dist/sdk/store-lookup.js +29 -0
  181. package/dist/sdk/store.d.ts +115 -0
  182. package/dist/sdk/store.js +1 -0
  183. package/dist/sdk/sx.d.ts +40 -0
  184. package/dist/sdk/sx.js +112 -0
  185. package/dist/sdk/theme.d.ts +152 -0
  186. package/dist/sdk/theme.js +10 -0
  187. package/dist/sdk/types.d.ts +470 -0
  188. package/dist/sdk/types.js +7 -0
  189. package/dist/server.d.ts +65 -0
  190. package/dist/server.js +370 -0
  191. package/docs/headless-api.md +220 -0
  192. package/package.json +77 -23
  193. package/dist/index.js.map +0 -1
  194. package/dist/ssg-BZ5FYTw7.js +0 -1802
  195. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  196. package/dist/ssg.js +0 -8
  197. package/dist/ssg.js.map +0 -1
  198. package/dist/types/cart.d.ts +0 -86
  199. package/dist/types/data.d.ts +0 -357
  200. package/dist/types/editor.d.ts +0 -5
  201. package/dist/types/index.d.ts +0 -20
  202. package/dist/types/preview-bridge.d.ts +0 -9
  203. package/dist/types/storefront.d.ts +0 -333
  204. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,67 @@
1
+ import { type ContractPageDoc, type SectionContract } from './content.js';
2
+ import { type GroupMap, type GroupedPageDoc } from './groups.js';
3
+ export type Severity = 'error' | 'warning';
4
+ export interface ValidationIssue {
5
+ severity: Severity;
6
+ /** Stable machine identifier. Callers branch on this, never on `message`. */
7
+ code: ValidationCode;
8
+ /** The node this is about, when there is one. */
9
+ nodeId?: string;
10
+ /** JSON path into the document, e.g. `sections[2].blocks[0].settings.answer`. */
11
+ path: string;
12
+ message: string;
13
+ /** The corrected value, when the validator knows it (aliases, casing). */
14
+ suggestion?: string;
15
+ }
16
+ export type ValidationCode = 'unknown_component' | 'unknown_setting' | 'unknown_field_type' | 'alias_field_type' | 'editor_only_field_type' | 'missing_node_id' | 'invalid_node_id' | 'duplicate_node_id' | 'disallowed_nesting' | 'leaf_cannot_nest' | 'invalid_area' | 'invalid_value' | 'missing_required_constraint' | 'invalid_binding' | 'missing_context' | 'invalid_placement' | 'unknown_group' | 'invalid_group';
17
+ export interface ValidationResult {
18
+ ok: boolean;
19
+ issues: ValidationIssue[];
20
+ }
21
+ /** The section catalogue a document is validated against. */
22
+ export type SectionCatalog = Record<string, SectionContract>;
23
+ export interface ValidateOptions {
24
+ /**
25
+ * Route context available where this document renders, for `requiresContext`.
26
+ * When supplied, a section placed outside its required context is an ERROR —
27
+ * the caller has said where this renders, and it would show a not-found
28
+ * state on every visit. Omitted → the same finding is a warning.
29
+ */
30
+ context?: readonly string[];
31
+ /**
32
+ * Treat unknown settings as warnings rather than errors. Off by default: an
33
+ * unknown setting is silently dropped at render, so the template claims to
34
+ * configure something it does not.
35
+ */
36
+ lenientSettings?: boolean;
37
+ /** Base template slug this document is, for `placement.templates`. */
38
+ template?: string;
39
+ }
40
+ /**
41
+ * Validate a section's own declaration — the shape a theme author or an AI
42
+ * writes in `defineSection({...})`.
43
+ */
44
+ export declare function validateSectionContract(def: SectionContract): ValidationResult;
45
+ /**
46
+ * Validate a template document against a section catalogue.
47
+ *
48
+ * This is the check that makes the FAQ round trip provable: unknown component,
49
+ * unknown setting, disallowed nesting, duplicate id and missing id are each a
50
+ * distinct, addressable failure instead of a silent drop at render time.
51
+ */
52
+ export declare function validateDocument(doc: ContractPageDoc, catalog: SectionCatalog, opts?: ValidateOptions): ValidationResult;
53
+ /** Validate one `groups/<name>.json` document against the catalogue. */
54
+ export declare function validateGroup(name: string, group: unknown, catalog: SectionCatalog, opts?: ValidateOptions): ValidationResult;
55
+ /**
56
+ * Validate a template TOGETHER with the groups it binds — the check the editor,
57
+ * studio-api and the AI tools run before a save.
58
+ *
59
+ * - the template's own body validates as before;
60
+ * - each `ref` must name a supplied group (`unknown_group` otherwise);
61
+ * - each `override` validates as that slot's nodes;
62
+ * - the RESOLVED page is checked for duplicate ids across slots, so a group
63
+ * node and a body node cannot share an id.
64
+ */
65
+ export declare function validatePage(template: GroupedPageDoc, groups: GroupMap, catalog: SectionCatalog, opts?: ValidateOptions): ValidationResult;
66
+ /** Render issues as human lines — shared by the CLI and error responses. */
67
+ export declare function formatIssues(issues: ValidationIssue[]): string;
@@ -0,0 +1,388 @@
1
+ /**
2
+ * THE validator. One implementation, called by the Editor API, the CLI, the AI
3
+ * tools and the theme's own test suite — so "valid" means the same thing in all
4
+ * four, and a fix in one is a fix in all.
5
+ *
6
+ * Dependency-free on purpose: studio-api ships a zero-npm-dependency image
7
+ * (`studio/CLAUDE.md` → Conventions), so it consumes the built single-file
8
+ * artifact rather than an npm install.
9
+ *
10
+ * Every finding carries `nodeId` + `path` + `code` + `message`. The codes are
11
+ * stable identifiers a caller can branch on; the messages are written to be
12
+ * actionable by whoever reads them — including a model feeding them into a
13
+ * repair loop, which is why they name the correct value rather than only
14
+ * rejecting the wrong one.
15
+ */
16
+ import { canonicalFieldType, fieldType, FIELD_TYPE_ALIASES, EDITOR_ONLY_TYPES, UNIVERSAL_CONSTRAINTS, } from './field-types.js';
17
+ import { NODE_ID_PATTERN, TEMPLATE_AREAS, roleOf, } from './content.js';
18
+ import { GROUP_SLOTS, GROUP_NAME_PATTERN, isSectionGroupDoc, resolvePage, } from './groups.js';
19
+ const err = (code, path, message, nodeId, suggestion) => ({
20
+ severity: 'error', code, path, message,
21
+ ...(nodeId ? { nodeId } : {}),
22
+ ...(suggestion ? { suggestion } : {}),
23
+ });
24
+ const warn = (code, path, message, nodeId, suggestion) => ({
25
+ severity: 'warning', code, path, message,
26
+ ...(nodeId ? { nodeId } : {}),
27
+ ...(suggestion ? { suggestion } : {}),
28
+ });
29
+ // ── Section definitions ──────────────────────────────────────────────────
30
+ /**
31
+ * Validate a section's own declaration — the shape a theme author or an AI
32
+ * writes in `defineSection({...})`.
33
+ */
34
+ export function validateSectionContract(def) {
35
+ const issues = [];
36
+ const base = `sections.${def.name}`;
37
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
38
+ issues.push(...validateAttr(spec, `${base}.attributes.${key}`, def.name));
39
+ }
40
+ for (const [i, preset] of (def.presets ?? []).entries()) {
41
+ for (const [j, block] of (preset.blocks ?? []).entries()) {
42
+ const p = `${base}.presets[${i}].blocks[${j}]`;
43
+ if (!def.allowedBlocks?.includes(block.type)) {
44
+ issues.push(err('disallowed_nesting', p, `Preset nests "${block.type}", which is not in allowedBlocks (${(def.allowedBlocks ?? []).join(', ') || 'none'}).`, def.name));
45
+ }
46
+ }
47
+ }
48
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
49
+ }
50
+ /** Validate one attribute declaration. */
51
+ function validateAttr(spec, path, nodeId) {
52
+ const issues = [];
53
+ const declared = spec?.type;
54
+ const canonical = canonicalFieldType(declared);
55
+ if (!canonical) {
56
+ if (typeof declared === 'string' && EDITOR_ONLY_TYPES.includes(declared)) {
57
+ issues.push(err('editor_only_field_type', `${path}.type`, `"${declared}" is rendered by the editor but cannot be declared by a theme. Use a core type; promoting it requires a contract change.`, nodeId));
58
+ }
59
+ else {
60
+ issues.push(err('unknown_field_type', `${path}.type`, `Unknown field type "${String(declared)}". It will be silently downgraded to a plain text box.`, nodeId));
61
+ }
62
+ return issues;
63
+ }
64
+ const aliasTarget = FIELD_TYPE_ALIASES[String(declared)];
65
+ if (aliasTarget) {
66
+ issues.push(warn('alias_field_type', `${path}.type`, `"${declared}" is a legacy alias — use "${aliasTarget}".`, nodeId, aliasTarget));
67
+ }
68
+ const def = fieldType(canonical);
69
+ // Required constraints: a select with no options is an empty dropdown.
70
+ if (def.constraints.includes('options') && !Array.isArray(spec.options)) {
71
+ issues.push(err('missing_required_constraint', `${path}.options`, `Field type "${canonical}" requires \`options: [{ value, label }]\`.`, nodeId));
72
+ }
73
+ // Constraints that do nothing on this type are a sign the author expected
74
+ // different behaviour — the `columns`-on-a-section class of mistake.
75
+ for (const key of Object.keys(spec ?? {})) {
76
+ if (key === 'type')
77
+ continue;
78
+ if (UNIVERSAL_CONSTRAINTS.includes(key))
79
+ continue;
80
+ if (def.constraints.includes(key))
81
+ continue;
82
+ issues.push(warn('invalid_value', `${path}.${key}`, `"${key}" has no meaning for field type "${canonical}" and is ignored.`, nodeId));
83
+ }
84
+ if (spec.dynamic === true && !def.dynamicBindable) {
85
+ issues.push(err('invalid_binding', `${path}.dynamic`, `Field type "${canonical}" cannot be bound to a dynamic source.`, nodeId));
86
+ }
87
+ if (spec.default !== undefined) {
88
+ const t = typeof spec.default;
89
+ const want = def.value;
90
+ const okType = (want === 'string' && t === 'string') ||
91
+ (want === 'number' && t === 'number') ||
92
+ (want === 'boolean' && t === 'boolean') ||
93
+ (want === 'string[]' && Array.isArray(spec.default));
94
+ if (!okType) {
95
+ issues.push(err('invalid_value', `${path}.default`, `Default for "${canonical}" should be ${want}, got ${Array.isArray(spec.default) ? 'array' : t}.`, nodeId));
96
+ }
97
+ }
98
+ return issues;
99
+ }
100
+ // ── Content tree ─────────────────────────────────────────────────────────
101
+ /**
102
+ * Validate a template document against a section catalogue.
103
+ *
104
+ * This is the check that makes the FAQ round trip provable: unknown component,
105
+ * unknown setting, disallowed nesting, duplicate id and missing id are each a
106
+ * distinct, addressable failure instead of a silent drop at render time.
107
+ */
108
+ export function validateDocument(doc, catalog, opts = {}) {
109
+ const issues = [];
110
+ const sections = Array.isArray(doc?.sections) ? doc.sections : [];
111
+ if (!Array.isArray(doc?.sections)) {
112
+ issues.push(err('invalid_value', 'sections', 'Document must have a `sections` array. The editor\'s object-map shape must be converted before it reaches disk.'));
113
+ return { ok: false, issues };
114
+ }
115
+ walkLevel(sections, 'sections', null, catalog, issues, opts);
116
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
117
+ }
118
+ function walkLevel(nodes, basePath, parent, catalog, issues, opts) {
119
+ const seen = new Map();
120
+ nodes.forEach((node, i) => {
121
+ const path = `${basePath}[${i}]`;
122
+ const id = node?.id;
123
+ // ── identity ──
124
+ if (typeof id !== 'string' || id === '') {
125
+ issues.push(err('missing_node_id', `${path}.id`, `Node of type "${node?.type}" has no id. Ids must be explicit — a missing id is filled in from the node's POSITION, so reordering silently reassigns it to different content.`, undefined, `${String(node?.type ?? 'node')}_<8 hex>`));
126
+ }
127
+ else if (!NODE_ID_PATTERN.test(id)) {
128
+ issues.push(err('invalid_node_id', `${path}.id`, `Node id "${id}" must match ${NODE_ID_PATTERN.source}.`, id));
129
+ }
130
+ else if (seen.has(id)) {
131
+ issues.push(err('duplicate_node_id', `${path}.id`, `Duplicate node id "${id}" (also at index ${seen.get(id)}). The editor keys nodes by id, so the later one overwrites the earlier.`, id));
132
+ }
133
+ else {
134
+ seen.set(id, i);
135
+ }
136
+ // ── component ──
137
+ const def = catalog[node?.type];
138
+ if (!def) {
139
+ issues.push(err('unknown_component', `${path}.type`, `Unknown component "${String(node?.type)}". It renders nothing and the editor offers no controls for it.`, id));
140
+ return;
141
+ }
142
+ // ── nesting ──
143
+ if (parent) {
144
+ const allowed = parent.allowedBlocks ?? [];
145
+ if (allowed.length === 0) {
146
+ issues.push(err('leaf_cannot_nest', path, `"${parent.name}" declares no allowedBlocks, so it cannot contain "${node.type}".`, id));
147
+ }
148
+ else if (!allowed.includes(node.type)) {
149
+ issues.push(err('disallowed_nesting', path, `"${parent.name}" does not allow "${node.type}". Allowed: ${allowed.join(', ')}.`, id));
150
+ }
151
+ }
152
+ // ── area ──
153
+ if (node.area !== undefined && !TEMPLATE_AREAS.includes(node.area)) {
154
+ issues.push(err('invalid_area', `${path}.area`, `Invalid area "${node.area}". Expected one of: ${TEMPLATE_AREAS.join(', ')}.`, id));
155
+ }
156
+ // ── role / placement ──
157
+ // A block at the top level, or a section nested inside another, is placed
158
+ // where it cannot render meaningfully; `category` used to be the only
159
+ // signal and it is a display grouping, not a rule.
160
+ const role = roleOf(def);
161
+ if (!parent && role === 'block') {
162
+ issues.push(err('invalid_placement', path, `"${def.name}" is a block and can only be placed inside a section that allows it${def.placement?.parents?.length ? ` (${def.placement.parents.join(', ')})` : ''}.`, id));
163
+ }
164
+ // Nesting itself is governed by the parent's `allowedBlocks` (checked
165
+ // above): a parent may legitimately host a section-role unit as a block —
166
+ // Nova's footer lists `newsletter`. Only chrome can never be nested.
167
+ if (parent && role === 'layout') {
168
+ issues.push(err('invalid_placement', path, `"${def.name}" is a layout section and cannot be nested inside "${parent.name}".`, id));
169
+ }
170
+ if (!parent) {
171
+ const slot = node.area ??
172
+ (def.area ?? (def.name === 'header' ? 'header' : def.name === 'footer' ? 'footer' : 'template'));
173
+ const allowedAreas = def.placement?.areas ?? (def.area ? [def.area] : undefined);
174
+ if (allowedAreas && !allowedAreas.includes(slot)) {
175
+ issues.push(err('invalid_placement', `${path}.area`, `"${def.name}" may only be placed in: ${allowedAreas.join(', ')} — not "${slot}".`, id, allowedAreas[0]));
176
+ }
177
+ if (def.placement?.templates?.length && opts.template) {
178
+ const base = opts.template.split('.')[0] ?? opts.template;
179
+ if (!def.placement.templates.includes(base)) {
180
+ issues.push(err('invalid_placement', path, `"${def.name}" may only be placed on: ${def.placement.templates.join(', ')} — not "${base}".`, id));
181
+ }
182
+ }
183
+ }
184
+ if (parent && def.placement?.parents?.length && !def.placement.parents.includes(parent.name)) {
185
+ issues.push(err('invalid_placement', path, `"${def.name}" may only be placed inside: ${def.placement.parents.join(', ')} — not "${parent.name}".`, id));
186
+ }
187
+ // ── settings ──
188
+ for (const [key, value] of Object.entries(node.settings ?? {})) {
189
+ const spec = def.attributes?.[key];
190
+ const sPath = `${path}.settings.${key}`;
191
+ if (!spec) {
192
+ const near = nearest(key, Object.keys(def.attributes ?? {}));
193
+ issues.push({
194
+ severity: opts.lenientSettings ? 'warning' : 'error',
195
+ code: 'unknown_setting',
196
+ ...(id ? { nodeId: id } : {}),
197
+ path: sPath,
198
+ message: `"${node.type}" does not declare a setting "${key}"; it is dropped at render and has no editor control.${near ? ` Did you mean "${near}"?` : ''}`,
199
+ ...(near ? { suggestion: near } : {}),
200
+ });
201
+ continue;
202
+ }
203
+ issues.push(...validateSettingValue(spec, value, sPath, id));
204
+ }
205
+ // ── required context ──
206
+ // Known context → an error: the caller has said where this renders, and a
207
+ // product block on the cart page shows a not-found state on every visit.
208
+ // Unknown context → a warning, so a bare document check still says so.
209
+ if (def.requiresContext?.length) {
210
+ const ctx = opts.context;
211
+ for (const need of def.requiresContext) {
212
+ if (ctx === undefined) {
213
+ issues.push(warn('missing_context', path, `"${def.name}" needs ${need} context; check the template that will host it provides one.`, id));
214
+ }
215
+ else if (!ctx.includes(need)) {
216
+ issues.push(err('missing_context', path, `"${def.name}" needs ${need} context, which this template does not provide.`, id));
217
+ }
218
+ }
219
+ }
220
+ // ── children ──
221
+ if (node.blocks?.length) {
222
+ walkLevel(node.blocks, `${path}.blocks`, def, catalog, issues, opts);
223
+ }
224
+ });
225
+ }
226
+ /** Check one authored VALUE against its declared field type. */
227
+ function validateSettingValue(spec, value, path, nodeId) {
228
+ const canonical = canonicalFieldType(spec.type);
229
+ if (!canonical)
230
+ return []; // the definition itself is already reported
231
+ const def = fieldType(canonical);
232
+ const issues = [];
233
+ if (value === null || value === undefined)
234
+ return issues;
235
+ const t = typeof value;
236
+ const okType = (def.value === 'string' && t === 'string') ||
237
+ (def.value === 'number' && t === 'number') ||
238
+ (def.value === 'boolean' && t === 'boolean') ||
239
+ (def.value === 'string[]' && Array.isArray(value));
240
+ if (!okType) {
241
+ issues.push(err('invalid_value', path, `Expected ${def.value} for field type "${canonical}", got ${Array.isArray(value) ? 'array' : t}.`, nodeId));
242
+ return issues;
243
+ }
244
+ if (Array.isArray(spec.options) && typeof value === 'string') {
245
+ // Options are `{ value, label }` by contract; a bare string is the editor's
246
+ // accepted shorthand (normOptions) and must not crash the validator, which
247
+ // would turn a merchant's save into a 500 instead of an issue.
248
+ const allowed = spec.options
249
+ .map((o) => (typeof o === 'string' ? o : o?.value))
250
+ .filter((v) => typeof v === 'string');
251
+ if (!allowed.includes(value)) {
252
+ issues.push(err('invalid_value', path, `"${value}" is not one of the declared options: ${allowed.join(', ')}.`, nodeId, nearest(value, allowed) ?? undefined));
253
+ }
254
+ }
255
+ if (typeof value === 'number') {
256
+ if (typeof spec.min === 'number' && value < spec.min) {
257
+ issues.push(err('invalid_value', path, `${value} is below the minimum ${spec.min}.`, nodeId));
258
+ }
259
+ if (typeof spec.max === 'number' && value > spec.max) {
260
+ issues.push(err('invalid_value', path, `${value} is above the maximum ${spec.max}.`, nodeId));
261
+ }
262
+ }
263
+ return issues;
264
+ }
265
+ /** Closest candidate by edit distance, for "did you mean" — only when close. */
266
+ function nearest(input, candidates) {
267
+ let best = null;
268
+ let bestScore = Infinity;
269
+ for (const c of candidates) {
270
+ const d = distance(input.toLowerCase(), c.toLowerCase());
271
+ if (d < bestScore) {
272
+ bestScore = d;
273
+ best = c;
274
+ }
275
+ }
276
+ const limit = Math.max(2, Math.floor(input.length / 3));
277
+ return best !== null && bestScore <= limit ? best : null;
278
+ }
279
+ function distance(a, b) {
280
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
281
+ const cur = new Array(b.length + 1).fill(0);
282
+ for (let i = 1; i <= a.length; i++) {
283
+ cur[0] = i;
284
+ for (let j = 1; j <= b.length; j++) {
285
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
286
+ }
287
+ for (let j = 0; j <= b.length; j++)
288
+ prev[j] = cur[j];
289
+ }
290
+ return prev[b.length];
291
+ }
292
+ // ── Groups ───────────────────────────────────────────────────────────────
293
+ /** Validate one `groups/<name>.json` document against the catalogue. */
294
+ export function validateGroup(name, group, catalog, opts = {}) {
295
+ const issues = [];
296
+ if (!GROUP_NAME_PATTERN.test(name)) {
297
+ issues.push(err('invalid_group', `groups.${name}`, `Group name "${name}" must match ${GROUP_NAME_PATTERN.source}.`));
298
+ }
299
+ if (!isSectionGroupDoc(group)) {
300
+ issues.push(err('invalid_group', `groups.${name}`, `A group must be { type: ${GROUP_SLOTS.join(' | ')}, sections: [] }.`));
301
+ return { ok: false, issues };
302
+ }
303
+ // A group's nodes are validated as top-level nodes of their slot: a block
304
+ // cannot sit directly in a header, and a section limited to the template
305
+ // area cannot be shared as a footer.
306
+ const nodes = group.sections.map((n) => (n.area === undefined ? { ...n, area: group.type } : n));
307
+ walkLevel(nodes, `groups.${name}.sections`, null, catalog, issues, { ...opts, context: opts.context ?? [] });
308
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
309
+ }
310
+ /**
311
+ * Validate a template TOGETHER with the groups it binds — the check the editor,
312
+ * studio-api and the AI tools run before a save.
313
+ *
314
+ * - the template's own body validates as before;
315
+ * - each `ref` must name a supplied group (`unknown_group` otherwise);
316
+ * - each `override` validates as that slot's nodes;
317
+ * - the RESOLVED page is checked for duplicate ids across slots, so a group
318
+ * node and a body node cannot share an id.
319
+ */
320
+ export function validatePage(template, groups, catalog, opts = {}) {
321
+ const issues = [];
322
+ const base = validateDocument(template, catalog, opts);
323
+ issues.push(...base.issues);
324
+ const bindings = template?.groups ?? {};
325
+ for (const slot of GROUP_SLOTS) {
326
+ const b = bindings[slot];
327
+ if (b === undefined)
328
+ continue;
329
+ const path = `groups.${slot}`;
330
+ if (typeof b === 'string' || (b && typeof b === 'object' && 'ref' in b)) {
331
+ const ref = typeof b === 'string' ? b : b.ref;
332
+ if (typeof ref !== 'string' || !ref) {
333
+ issues.push(err('invalid_group', path, `Slot "${slot}" binding must be a group name or { override: [] }.`));
334
+ }
335
+ else if (!groups[ref]) {
336
+ issues.push(err('unknown_group', path, `Slot "${slot}" references group "${ref}", which does not exist (groups/${ref}.json).`, undefined, Object.keys(groups).find((g) => groups[g].type === slot)));
337
+ }
338
+ else if (groups[ref].type !== slot) {
339
+ issues.push(err('invalid_group', path, `Group "${ref}" is a ${groups[ref].type} group and cannot fill the ${slot} slot.`));
340
+ }
341
+ }
342
+ else if (b && typeof b === 'object' && 'override' in b) {
343
+ const nodes = b.override;
344
+ if (!Array.isArray(nodes)) {
345
+ issues.push(err('invalid_group', path, `Slot "${slot}" override must be an array of sections.`));
346
+ }
347
+ else {
348
+ walkLevel(nodes.map((n) => (n.area === undefined ? { ...n, area: slot } : n)), `${path}.override`, null, catalog, issues, opts);
349
+ }
350
+ }
351
+ else {
352
+ issues.push(err('invalid_group', path, `Slot "${slot}" binding must be a group name or { override: [] }.`));
353
+ }
354
+ }
355
+ // Duplicate ids across slots: the editor and every targeted edit key by id.
356
+ // Labels come from the slot each node was resolved INTO, not from the
357
+ // provenance map — a duplicate id has already overwritten its own entry there.
358
+ const resolved = resolvePage(template, groups);
359
+ const labelled = [];
360
+ for (const slot of GROUP_SLOTS) {
361
+ const r = resolved.slots[slot];
362
+ const label = r.mode === 'ref' ? `group ${r.group}` : `${slot} ${r.mode}`;
363
+ for (const n of r.sections)
364
+ if (n.id)
365
+ labelled.push({ id: n.id, label });
366
+ }
367
+ const headerCount = resolved.slots.header.sections.length;
368
+ const footerCount = resolved.slots.footer.sections.length;
369
+ const body = resolved.sections.slice(headerCount, resolved.sections.length - footerCount);
370
+ const bodyLabelled = body.filter((n) => n.id).map((n) => ({ id: n.id, label: 'template' }));
371
+ const ordered = [...labelled.slice(0, headerCount), ...bodyLabelled, ...labelled.slice(headerCount)];
372
+ const seen = new Map();
373
+ ordered.forEach(({ id, label }, i) => {
374
+ if (seen.has(id)) {
375
+ issues.push(err('duplicate_node_id', `resolved[${i}].id`, `Node id "${id}" appears in both ${seen.get(id)} and ${label}. Ids must be unique across the page including its shared groups.`, id));
376
+ }
377
+ else {
378
+ seen.set(id, label);
379
+ }
380
+ });
381
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
382
+ }
383
+ /** Render issues as human lines — shared by the CLI and error responses. */
384
+ export function formatIssues(issues) {
385
+ return issues
386
+ .map((i) => `${i.severity === 'error' ? '✗' : '⚠'} [${i.code}] ${i.path}: ${i.message}`)
387
+ .join('\n');
388
+ }