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

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 (233) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -10
  3. package/dist/abi/canvas-live.d.ts +72 -0
  4. package/dist/abi/canvas-live.js +159 -0
  5. package/dist/abi/cart.d.ts +60 -0
  6. package/dist/abi/cart.js +396 -0
  7. package/dist/abi/convert.d.ts +360 -0
  8. package/dist/abi/convert.js +1330 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +213 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +264 -0
  16. package/dist/abi/page-data.js +746 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +46 -0
  30. package/dist/abi/wire.js +114 -0
  31. package/dist/build.d.ts +121 -0
  32. package/dist/build.js +401 -0
  33. package/dist/chunks.d.ts +23 -0
  34. package/dist/chunks.js +41 -0
  35. package/dist/client.d.ts +26 -0
  36. package/dist/client.js +101 -0
  37. package/dist/contract.d.ts +6 -0
  38. package/dist/contract.js +6 -0
  39. package/dist/headless/ai.d.ts +132 -0
  40. package/dist/headless/ai.js +99 -0
  41. package/dist/headless/hooks.d.ts +276 -0
  42. package/dist/headless/hooks.js +544 -0
  43. package/dist/headless/i18n.d.ts +13 -0
  44. package/dist/headless/i18n.js +45 -0
  45. package/dist/headless/index.d.ts +44 -0
  46. package/dist/headless/index.js +48 -0
  47. package/dist/headless/lazy-component.d.ts +72 -0
  48. package/dist/headless/lazy-component.js +225 -0
  49. package/dist/headless/lazy-section.d.ts +38 -0
  50. package/dist/headless/lazy-section.js +97 -0
  51. package/dist/headless/model.d.ts +73 -0
  52. package/dist/headless/model.js +115 -0
  53. package/dist/headless/money.d.ts +17 -0
  54. package/dist/headless/money.js +63 -0
  55. package/dist/headless/page.d.ts +45 -0
  56. package/dist/headless/page.js +53 -0
  57. package/dist/headless/platform.d.ts +55 -0
  58. package/dist/headless/platform.js +77 -0
  59. package/dist/headless/primitives/cart.d.ts +90 -0
  60. package/dist/headless/primitives/cart.js +153 -0
  61. package/dist/headless/primitives/collection.d.ts +68 -0
  62. package/dist/headless/primitives/collection.js +80 -0
  63. package/dist/headless/primitives/product.d.ts +101 -0
  64. package/dist/headless/primitives/product.js +117 -0
  65. package/dist/headless/primitives/storefront.d.ts +106 -0
  66. package/dist/headless/primitives/storefront.js +187 -0
  67. package/dist/headless/primitives/util.d.ts +19 -0
  68. package/dist/headless/primitives/util.js +42 -0
  69. package/dist/headless/strings.d.ts +9 -0
  70. package/dist/headless/strings.js +198 -0
  71. package/dist/headless/structured-data.d.ts +31 -0
  72. package/dist/headless/structured-data.js +57 -0
  73. package/dist/headless/tanqory-money.generated.d.ts +493 -0
  74. package/dist/headless/tanqory-money.generated.js +507 -0
  75. package/dist/headless/theme.d.ts +109 -0
  76. package/dist/headless/theme.js +62 -0
  77. package/dist/index.d.ts +21 -0
  78. package/dist/index.js +21 -553
  79. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  80. package/dist/runtime/data/StoreProvider.js +380 -0
  81. package/dist/runtime/data/handle.d.ts +14 -0
  82. package/dist/runtime/data/handle.js +16 -0
  83. package/dist/runtime/data/routes.d.ts +87 -0
  84. package/dist/runtime/data/routes.js +158 -0
  85. package/dist/runtime/data/to-ui.d.ts +286 -0
  86. package/dist/runtime/data/to-ui.js +1009 -0
  87. package/dist/runtime/entries/register.d.ts +9 -0
  88. package/dist/runtime/entries/register.js +9 -0
  89. package/dist/runtime/entries/sections.d.ts +16 -0
  90. package/dist/runtime/entries/sections.js +19 -0
  91. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  92. package/dist/runtime/kit/SectionTree.js +100 -0
  93. package/dist/runtime/kit/analytics.d.ts +63 -0
  94. package/dist/runtime/kit/analytics.js +250 -0
  95. package/dist/runtime/kit/cart.d.ts +222 -0
  96. package/dist/runtime/kit/cart.js +545 -0
  97. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  98. package/dist/runtime/kit/composition.js +3 -0
  99. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  100. package/dist/runtime/kit/config.js +6 -0
  101. package/dist/runtime/kit/consent.d.ts +29 -0
  102. package/dist/runtime/kit/consent.js +159 -0
  103. package/dist/runtime/kit/contract/content.d.ts +213 -0
  104. package/dist/runtime/kit/contract/content.js +119 -0
  105. package/dist/runtime/kit/contract/field-types.d.ts +360 -0
  106. package/dist/runtime/kit/contract/field-types.js +216 -0
  107. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  108. package/dist/runtime/kit/contract/groups.js +402 -0
  109. package/dist/runtime/kit/contract/index.d.ts +33 -0
  110. package/dist/runtime/kit/contract/index.js +33 -0
  111. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  112. package/dist/runtime/kit/contract/transform.js +133 -0
  113. package/dist/runtime/kit/contract/validate.d.ts +77 -0
  114. package/dist/runtime/kit/contract/validate.js +520 -0
  115. package/dist/runtime/kit/data.d.ts +732 -0
  116. package/dist/runtime/kit/data.js +1131 -0
  117. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  118. package/dist/runtime/kit/defineSection.js +10 -0
  119. package/dist/runtime/kit/dynamic-source.d.ts +118 -0
  120. package/dist/runtime/kit/dynamic-source.js +311 -0
  121. package/dist/runtime/kit/index.d.ts +24 -0
  122. package/dist/runtime/kit/index.js +24 -0
  123. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  124. package/dist/runtime/kit/jsx-to-json.js +28 -0
  125. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  126. package/dist/runtime/kit/mount.js +124 -0
  127. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  128. package/dist/runtime/kit/registry.js +12 -0
  129. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  130. package/dist/runtime/kit/ssg.js +56 -0
  131. package/dist/runtime/kit/storefront.d.ts +652 -0
  132. package/dist/runtime/kit/storefront.js +723 -0
  133. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  134. package/dist/runtime/kit/theme-context.js +25 -0
  135. package/dist/runtime/kit/types.d.ts +155 -0
  136. package/dist/runtime/kit/types.js +1 -0
  137. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  138. package/dist/runtime/platform/TrackingPixels.js +63 -0
  139. package/dist/runtime/platform/environment.d.ts +68 -0
  140. package/dist/runtime/platform/environment.js +85 -0
  141. package/dist/runtime/platform/locale.d.ts +27 -0
  142. package/dist/runtime/platform/locale.js +42 -0
  143. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  144. package/dist/runtime/platform/route-analytics.js +72 -0
  145. package/dist/runtime/platform/safe-href.d.ts +25 -0
  146. package/dist/runtime/platform/safe-href.js +69 -0
  147. package/dist/runtime/platform/safe-values.d.ts +37 -0
  148. package/dist/runtime/platform/safe-values.js +140 -0
  149. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  150. package/dist/runtime/render/SectionRenderer.js +199 -0
  151. package/dist/runtime/render/listing-query.d.ts +52 -0
  152. package/dist/runtime/render/listing-query.js +122 -0
  153. package/dist/runtime/render/localized-copy.d.ts +86 -0
  154. package/dist/runtime/render/localized-copy.js +129 -0
  155. package/dist/runtime/render/product-listing.d.ts +11 -0
  156. package/dist/runtime/render/product-listing.js +243 -0
  157. package/dist/runtime/render/resolved.d.ts +47 -0
  158. package/dist/runtime/render/resolved.js +80 -0
  159. package/dist/runtime/render/section-actions.d.ts +67 -0
  160. package/dist/runtime/render/section-actions.js +205 -0
  161. package/dist/runtime/render/starter.d.ts +11 -0
  162. package/dist/runtime/render/starter.js +96 -0
  163. package/dist/runtime/seo/head.d.ts +115 -0
  164. package/dist/runtime/seo/head.js +281 -0
  165. package/dist/runtime/seo/structured-data.d.ts +83 -0
  166. package/dist/runtime/seo/structured-data.js +252 -0
  167. package/dist/runtime/shell/PageShell.d.ts +18 -0
  168. package/dist/runtime/shell/PageShell.js +118 -0
  169. package/dist/runtime/shell/RuntimeBridge.d.ts +18 -0
  170. package/dist/runtime/shell/RuntimeBridge.js +124 -0
  171. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  172. package/dist/runtime/shell/overlay-state.js +59 -0
  173. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  174. package/dist/runtime/shell/preview-mode.js +11 -0
  175. package/dist/runtime/shell/spa-router.d.ts +14 -0
  176. package/dist/runtime/shell/spa-router.js +76 -0
  177. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  178. package/dist/runtime/shell/url-redirects.js +37 -0
  179. package/dist/runtime/slots.d.ts +74 -0
  180. package/dist/runtime/slots.js +16 -0
  181. package/dist/runtime.d.ts +34 -0
  182. package/dist/runtime.js +40 -0
  183. package/dist/sdk/app-block.d.ts +29 -0
  184. package/dist/sdk/app-block.js +22 -0
  185. package/dist/sdk/font-hooks.d.ts +7 -0
  186. package/dist/sdk/font-hooks.js +21 -0
  187. package/dist/sdk/fonts.d.ts +144 -0
  188. package/dist/sdk/fonts.js +241 -0
  189. package/dist/sdk/index.d.ts +32 -0
  190. package/dist/sdk/index.js +36 -0
  191. package/dist/sdk/motion-hooks.d.ts +23 -0
  192. package/dist/sdk/motion-hooks.js +46 -0
  193. package/dist/sdk/motion.d.ts +78 -0
  194. package/dist/sdk/motion.js +292 -0
  195. package/dist/sdk/referrals.d.ts +62 -0
  196. package/dist/sdk/referrals.js +20 -0
  197. package/dist/sdk/rewards.d.ts +85 -0
  198. package/dist/sdk/rewards.js +29 -0
  199. package/dist/sdk/runtime-context.d.ts +230 -0
  200. package/dist/sdk/runtime-context.js +73 -0
  201. package/dist/sdk/schema.d.ts +249 -0
  202. package/dist/sdk/schema.js +168 -0
  203. package/dist/sdk/server-render.d.ts +8 -0
  204. package/dist/sdk/server-render.js +12 -0
  205. package/dist/sdk/store-lookup.d.ts +32 -0
  206. package/dist/sdk/store-lookup.js +48 -0
  207. package/dist/sdk/store.d.ts +164 -0
  208. package/dist/sdk/store.js +5 -0
  209. package/dist/sdk/sx.d.ts +45 -0
  210. package/dist/sdk/sx.js +117 -0
  211. package/dist/sdk/theme.d.ts +212 -0
  212. package/dist/sdk/theme.js +27 -0
  213. package/dist/sdk/types.d.ts +789 -0
  214. package/dist/sdk/types.js +7 -0
  215. package/dist/server.d.ts +112 -0
  216. package/dist/server.js +589 -0
  217. package/dist/vite-chunks.d.ts +10 -0
  218. package/dist/vite-chunks.js +44 -0
  219. package/docs/headless-api.md +250 -0
  220. package/package.json +72 -26
  221. package/dist/index.js.map +0 -1
  222. package/dist/ssg-BZ5FYTw7.js +0 -1802
  223. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  224. package/dist/ssg.js +0 -8
  225. package/dist/ssg.js.map +0 -1
  226. package/dist/types/cart.d.ts +0 -86
  227. package/dist/types/data.d.ts +0 -357
  228. package/dist/types/dynamic-source.d.ts +0 -84
  229. package/dist/types/editor.d.ts +0 -5
  230. package/dist/types/index.d.ts +0 -20
  231. package/dist/types/preview-bridge.d.ts +0 -9
  232. package/dist/types/storefront.d.ts +0 -333
  233. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,520 @@
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, paletteValueProblems, fieldType, FIELD_TYPE_ALIASES, EDITOR_ONLY_TYPES, UNIVERSAL_CONSTRAINTS, isBoundSourceValue, isBoundTemplateValue, TEMPLATE_BINDABLE_TYPES, BOUND_TEMPLATE_MAX_TOKENS, LIST_RESOURCE_ITEMS, } from './field-types.js';
17
+ import { NODE_ID_PATTERN, NODE_NAME_MAX_LENGTH, TEMPLATE_AREAS, acceptsAppBlocks, isAppBlockType, isValidNodeName, roleOf, routeKindOfTemplate, } 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
+ // A section of any role may accept app blocks, a header or footer included (theme-abi §7.2 AppBlocks-1).
41
+ for (const [i, preset] of (def.presets ?? []).entries()) {
42
+ for (const [j, block] of (preset.blocks ?? []).entries()) {
43
+ const p = `${base}.presets[${i}].blocks[${j}]`;
44
+ if (isAppBlockType(block.type)) {
45
+ issues.push(err('invalid_app_block', p, `A preset cannot hold the app block "${block.type}": a merchant adds app blocks.`, def.name));
46
+ continue;
47
+ }
48
+ if (!def.allowedBlocks?.includes(block.type)) {
49
+ issues.push(err('disallowed_nesting', p, `Preset nests "${block.type}", which is not in allowedBlocks (${(def.allowedBlocks ?? []).join(', ') || 'none'}).`, def.name));
50
+ }
51
+ }
52
+ }
53
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
54
+ }
55
+ /**
56
+ * Editor-only types that already have a declarable form, and what to write instead (MCP limits item 7): the message
57
+ * names the replacement rather than only refusing the type.
58
+ */
59
+ const EDITOR_ONLY_REPLACEMENTS = {
60
+ font_picker: "A font setting is a select the editor draws as its font picker: field.font('Prompt', { label }) in a section, or fontSetting({ label }) in src/settings.ts (@tanqory/theme-kit), offering the platform catalogue first, then the theme's own fonts; render it with useFont().",
61
+ };
62
+ /** What to write instead of an editor-only type that has a declarable form, or undefined (MCP limits item 7). */
63
+ export function editorOnlyReplacement(type) {
64
+ return typeof type === 'string' && own(EDITOR_ONLY_REPLACEMENTS, type) ? EDITOR_ONLY_REPLACEMENTS[type] : undefined;
65
+ }
66
+ /** Validate one attribute declaration. */
67
+ function validateAttr(spec, path, nodeId) {
68
+ const issues = [];
69
+ const declared = spec?.type;
70
+ const canonical = canonicalFieldType(declared);
71
+ if (!canonical) {
72
+ if (typeof declared === 'string' && EDITOR_ONLY_TYPES.includes(declared)) {
73
+ const instead = editorOnlyReplacement(declared);
74
+ issues.push(err('editor_only_field_type', `${path}.type`, instead
75
+ ? `"${declared}" is rendered by the editor but cannot be declared by a theme. ${instead}`
76
+ : `"${declared}" is rendered by the editor but cannot be declared by a theme. Use a core type; promoting it requires a contract change.`, nodeId));
77
+ }
78
+ else {
79
+ issues.push(err('unknown_field_type', `${path}.type`, `Unknown field type "${String(declared)}". It will be silently downgraded to a plain text box.`, nodeId));
80
+ }
81
+ return issues;
82
+ }
83
+ const aliasTarget = FIELD_TYPE_ALIASES[String(declared)];
84
+ if (aliasTarget) {
85
+ issues.push(warn('alias_field_type', `${path}.type`, `"${declared}" is a legacy alias — use "${aliasTarget}".`, nodeId, aliasTarget));
86
+ }
87
+ const def = fieldType(canonical);
88
+ // Required constraints: a select with no options is an empty dropdown.
89
+ if (def.constraints.includes('options') && !Array.isArray(spec.options)) {
90
+ issues.push(err('missing_required_constraint', `${path}.options`, `Field type "${canonical}" requires \`options: [{ value, label }]\`.`, nodeId));
91
+ }
92
+ // A list says what its entries are (theme-abi registry `list` requires `items`).
93
+ if (canonical === 'list' && !(spec.items && typeof spec.items === 'object' && typeof spec.items.type === 'string' && spec.items.type)) {
94
+ issues.push(err('missing_required_constraint', `${path}.items`, 'Field type "list" requires `items: { type }`, e.g. `{ type: "product", resolve: true }` for a hand-picked list of products.', nodeId));
95
+ }
96
+ // Constraints that do nothing on this type are a sign the author expected
97
+ // different behaviour — the `columns`-on-a-section class of mistake.
98
+ for (const key of Object.keys(spec ?? {})) {
99
+ if (key === 'type')
100
+ continue;
101
+ if (UNIVERSAL_CONSTRAINTS.includes(key))
102
+ continue;
103
+ if (def.constraints.includes(key))
104
+ continue;
105
+ issues.push(warn('invalid_value', `${path}.${key}`, `"${key}" has no meaning for field type "${canonical}" and is ignored.`, nodeId));
106
+ }
107
+ if (spec.dynamic === true && !def.dynamicBindable) {
108
+ issues.push(err('invalid_binding', `${path}.dynamic`, `Field type "${canonical}" cannot be bound to a dynamic source.`, nodeId));
109
+ }
110
+ if (spec.default !== undefined) {
111
+ const t = typeof spec.default;
112
+ const want = def.value;
113
+ const okType = (want === 'string' && t === 'string') ||
114
+ (want === 'number' && t === 'number') ||
115
+ (want === 'boolean' && t === 'boolean') ||
116
+ ((want === 'string[]' || want === 'palette') && Array.isArray(spec.default));
117
+ if (!okType) {
118
+ issues.push(err('invalid_value', `${path}.default`, `Default for "${canonical}" should be ${want}, got ${Array.isArray(spec.default) ? 'array' : t}.`, nodeId));
119
+ }
120
+ else if (want === 'palette') {
121
+ for (const message of paletteValueProblems(spec.default, typeof spec.max === 'number' ? spec.max : undefined)) {
122
+ issues.push(err('invalid_value', `${path}.default`, message, nodeId));
123
+ }
124
+ }
125
+ }
126
+ return issues;
127
+ }
128
+ // ── Content tree ─────────────────────────────────────────────────────────
129
+ /**
130
+ * Validate a template document against a section catalogue.
131
+ *
132
+ * This is the check that makes the FAQ round trip provable: unknown component,
133
+ * unknown setting, disallowed nesting, duplicate id and missing id are each a
134
+ * distinct, addressable failure instead of a silent drop at render time.
135
+ */
136
+ export function validateDocument(doc, catalog, opts = {}) {
137
+ const issues = [];
138
+ const sections = Array.isArray(doc?.sections) ? doc.sections : [];
139
+ if (!Array.isArray(doc?.sections)) {
140
+ 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.'));
141
+ return { ok: false, issues };
142
+ }
143
+ walkLevel(sections, 'sections', null, catalog, issues, opts);
144
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
145
+ }
146
+ function walkLevel(nodes, basePath, parent, catalog, issues, opts) {
147
+ const seen = new Map();
148
+ nodes.forEach((node, i) => {
149
+ const path = `${basePath}[${i}]`;
150
+ const id = node?.id;
151
+ // ── identity ──
152
+ if (typeof id !== 'string' || id === '') {
153
+ 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>`));
154
+ }
155
+ else if (!NODE_ID_PATTERN.test(id)) {
156
+ issues.push(err('invalid_node_id', `${path}.id`, `Node id "${id}" must match ${NODE_ID_PATTERN.source}.`, id));
157
+ }
158
+ else if (seen.has(id)) {
159
+ 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));
160
+ }
161
+ else {
162
+ seen.set(id, i);
163
+ }
164
+ // ── name (the editor outline's own label for the node; never rendered) ──
165
+ if (node?.name !== undefined && !isValidNodeName(node.name)) {
166
+ issues.push(err('invalid_node_name', `${path}.name`, `Node name must be text of 1 to ${NODE_NAME_MAX_LENGTH} characters with no space at either end; leave it out to show the type's name.`, typeof id === 'string' && id ? id : undefined));
167
+ }
168
+ // ── app block (theme-abi §7.2) ──
169
+ if (isAppBlockType(node?.type)) {
170
+ walkAppBlock(node, path, parent, issues, opts);
171
+ return;
172
+ }
173
+ // ── component ──
174
+ const def = catalog[node?.type];
175
+ if (!def) {
176
+ issues.push(err('unknown_component', `${path}.type`, `Unknown component "${String(node?.type)}". It renders nothing and the editor offers no controls for it.`, id));
177
+ return;
178
+ }
179
+ // ── nesting ──
180
+ if (parent) {
181
+ const allowed = parent.allowedBlocks ?? [];
182
+ if (allowed.length === 0) {
183
+ issues.push(err('leaf_cannot_nest', path, `"${parent.name}" declares no allowedBlocks, so it cannot contain "${node.type}".`, id));
184
+ }
185
+ else if (!allowed.includes(node.type)) {
186
+ issues.push(err('disallowed_nesting', path, `"${parent.name}" does not allow "${node.type}". Allowed: ${allowed.join(', ')}.`, id));
187
+ }
188
+ }
189
+ // ── area ──
190
+ if (node.area !== undefined && !TEMPLATE_AREAS.includes(node.area)) {
191
+ issues.push(err('invalid_area', `${path}.area`, `Invalid area "${node.area}". Expected one of: ${TEMPLATE_AREAS.join(', ')}.`, id));
192
+ }
193
+ // ── role / placement ──
194
+ // A block at the top level, or a section nested inside another, is placed
195
+ // where it cannot render meaningfully; `category` used to be the only
196
+ // signal and it is a display grouping, not a rule.
197
+ const role = roleOf(def);
198
+ if (!parent && role === 'block') {
199
+ 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));
200
+ }
201
+ // Nesting itself is governed by the parent's `allowedBlocks` (checked
202
+ // above): a parent may legitimately host a section-role unit as a block —
203
+ // Nova's footer lists `newsletter`. Only chrome can never be nested.
204
+ if (parent && role === 'layout') {
205
+ issues.push(err('invalid_placement', path, `"${def.name}" is a layout section and cannot be nested inside "${parent.name}".`, id));
206
+ }
207
+ if (!parent) {
208
+ const slot = node.area ??
209
+ (def.area ?? (def.name === 'header' ? 'header' : def.name === 'footer' ? 'footer' : 'template'));
210
+ const allowedAreas = def.placement?.areas ?? (def.area ? [def.area] : undefined);
211
+ if (allowedAreas && !allowedAreas.includes(slot)) {
212
+ issues.push(err('invalid_placement', `${path}.area`, `"${def.name}" may only be placed in: ${allowedAreas.join(', ')} — not "${slot}".`, id, allowedAreas[0]));
213
+ }
214
+ if (def.placement?.templates?.length && opts.template) {
215
+ const base = opts.template.split('.')[0] ?? opts.template;
216
+ if (!def.placement.templates.includes(base)) {
217
+ issues.push(err('invalid_placement', path, `"${def.name}" may only be placed on: ${def.placement.templates.join(', ')} — not "${base}".`, id));
218
+ }
219
+ }
220
+ }
221
+ if (parent && def.placement?.parents?.length && !def.placement.parents.includes(parent.name)) {
222
+ issues.push(err('invalid_placement', path, `"${def.name}" may only be placed inside: ${def.placement.parents.join(', ')} — not "${parent.name}".`, id));
223
+ }
224
+ // ── settings ──
225
+ for (const [key, value] of Object.entries(node.settings ?? {})) {
226
+ const spec = def.attributes?.[key];
227
+ const sPath = `${path}.settings.${key}`;
228
+ if (!spec) {
229
+ const near = nearest(key, Object.keys(def.attributes ?? {}));
230
+ issues.push({
231
+ severity: opts.lenientSettings ? 'warning' : 'error',
232
+ code: 'unknown_setting',
233
+ ...(id ? { nodeId: id } : {}),
234
+ path: sPath,
235
+ message: `"${node.type}" does not declare a setting "${key}"; it is dropped at render and has no editor control.${near ? ` Did you mean "${near}"?` : ''}`,
236
+ ...(near ? { suggestion: near } : {}),
237
+ });
238
+ continue;
239
+ }
240
+ issues.push(...validateSettingValue(spec, value, sPath, id));
241
+ }
242
+ // ── required context ──
243
+ // Known context → an error: the caller has said where this renders, and a
244
+ // product block on the cart page shows a not-found state on every visit.
245
+ // Unknown context → a warning, so a bare document check still says so.
246
+ if (def.requiresContext?.length) {
247
+ const ctx = opts.context;
248
+ for (const need of def.requiresContext) {
249
+ if (ctx === undefined) {
250
+ issues.push(warn('missing_context', path, `"${def.name}" needs ${need} context; check the template that will host it provides one.`, id));
251
+ }
252
+ else if (!ctx.includes(need)) {
253
+ issues.push(err('missing_context', path, `"${def.name}" needs ${need} context, which this template does not provide.`, id));
254
+ }
255
+ }
256
+ }
257
+ // ── children ──
258
+ if (node.blocks?.length) {
259
+ walkLevel(node.blocks, `${path}.blocks`, def, catalog, issues, opts);
260
+ }
261
+ });
262
+ }
263
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
264
+ /**
265
+ * An `app:` node (theme-abi §7.2): placed only in a parent that lists `@app`, never at the top level, never with
266
+ * children of its own; its settings follow the app block's own definition when the store's app blocks are known.
267
+ */
268
+ function walkAppBlock(node, path, parent, issues, opts) {
269
+ const id = typeof node.id === 'string' && node.id ? node.id : undefined;
270
+ if (!parent) {
271
+ issues.push(err('invalid_placement', path, `The app block "${node.type}" can only be placed inside a section or block that accepts app blocks.`, id));
272
+ }
273
+ else if (!acceptsAppBlocks(parent.allowedBlocks)) {
274
+ issues.push(err('disallowed_nesting', path, `"${parent.name}" does not accept app blocks, so it cannot contain "${node.type}".`, id));
275
+ }
276
+ if (Array.isArray(node.blocks) && node.blocks.length) {
277
+ issues.push(err('leaf_cannot_nest', `${path}.blocks`, `The app block "${node.type}" cannot contain blocks.`, id));
278
+ }
279
+ if (!opts.appBlocks)
280
+ return;
281
+ const def = own(opts.appBlocks, node.type) ? opts.appBlocks[node.type] : undefined;
282
+ if (!def) {
283
+ issues.push(warn('app_block_unavailable', `${path}.type`, `The app block "${node.type}" is not available: its app is not installed, or its newest version no longer has this block. It is kept in the page and left out of the storefront until the app is installed again.`, id));
284
+ return;
285
+ }
286
+ // The app's own placement rules (its version's `targets` and `requires`): the editor's picker offers the block only
287
+ // where they allow, and a save from any other writer (the AI tools, the API) is held to the same rules here.
288
+ const name = def.name ?? node.type;
289
+ if (parent && def.targets?.length) {
290
+ const where = roleOf(parent) === 'block' ? 'block' : 'section';
291
+ if (!def.targets.includes(where)) {
292
+ issues.push(err('invalid_placement', path, where === 'block'
293
+ ? `The app block "${name}" can only be placed directly in a section, not inside the block "${parent.name}".`
294
+ : `The app block "${name}" can only be placed inside a block, not directly in the section "${parent.name}".`, id));
295
+ }
296
+ }
297
+ if (def.requires?.length && opts.template) {
298
+ const kind = routeKindOfTemplate(opts.template);
299
+ if (!kind || !def.requires.includes(kind)) {
300
+ issues.push(err('invalid_placement', path, `The app block "${name}" is for ${def.requires.join(', ')} pages, so it cannot be placed on the template "${opts.template}".`, id));
301
+ }
302
+ }
303
+ for (const [key, value] of Object.entries(node.settings ?? {})) {
304
+ const spec = own(def.settings ?? {}, key) ? def.settings[key] : undefined;
305
+ const sPath = `${path}.settings.${key}`;
306
+ if (!spec) {
307
+ issues.push({
308
+ severity: opts.lenientSettings ? 'warning' : 'error',
309
+ code: 'unknown_setting',
310
+ ...(id ? { nodeId: id } : {}),
311
+ path: sPath,
312
+ message: `The app block "${def.name ?? node.type}" does not declare a setting "${key}"; it has no editor control and the app never reads it.`,
313
+ });
314
+ continue;
315
+ }
316
+ issues.push(...validateSettingValue(spec, value, sPath, id));
317
+ }
318
+ }
319
+ /** Check one authored VALUE against its declared field type. */
320
+ function validateSettingValue(spec, value, path, nodeId) {
321
+ const canonical = canonicalFieldType(spec.type);
322
+ if (!canonical)
323
+ return []; // the definition itself is already reported
324
+ const def = fieldType(canonical);
325
+ const issues = [];
326
+ if (value === null || value === undefined)
327
+ return issues;
328
+ // O4: a value connected to a dynamic source. Allowed on every field type the contract marks bindable (the editor
329
+ // offers "Connect dynamic source" there); any other object, or a bound value on a type that cannot show one, is
330
+ // still an invalid value.
331
+ // Several sources in one text setting (`{ '@template' }`): text types only.
332
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && '@template' in value) {
333
+ if (!TEMPLATE_BINDABLE_TYPES.includes(canonical)) {
334
+ issues.push(err('invalid_binding', path, `Field type "${canonical}" cannot hold text with dynamic sources.`, nodeId));
335
+ }
336
+ else if (!isBoundTemplateValue(value)) {
337
+ issues.push(err('invalid_value', path, `Text with dynamic sources must be exactly { "@template": "… {{ <source> }} …" }, with 1 to ${BOUND_TEMPLATE_MAX_TOKENS} sources.`, nodeId));
338
+ }
339
+ return issues;
340
+ }
341
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && '@source' in value) {
342
+ if (!def.dynamicBindable) {
343
+ issues.push(err('invalid_binding', path, `Field type "${canonical}" cannot be bound to a dynamic source.`, nodeId));
344
+ }
345
+ else if (!isBoundSourceValue(value)) {
346
+ issues.push(err('invalid_value', path, 'A dynamic source must be exactly { "@source": "<product|collection|page|article|shop>.metafields.<namespace>.<key>" }.', nodeId));
347
+ }
348
+ return issues;
349
+ }
350
+ const t = typeof value;
351
+ const okType = (def.value === 'string' && t === 'string') ||
352
+ (def.value === 'number' && t === 'number') ||
353
+ (def.value === 'boolean' && t === 'boolean') ||
354
+ ((def.value === 'string[]' || def.value === 'palette') && Array.isArray(value));
355
+ if (!okType) {
356
+ issues.push(err('invalid_value', path, `Expected ${def.value} for field type "${canonical}", got ${Array.isArray(value) ? 'array' : t}.`, nodeId));
357
+ return issues;
358
+ }
359
+ // A hand-picked list holds handles: each entry a non-empty handle (the count is studio-api's page check, too_many_items).
360
+ if (canonical === 'list' && typeof spec.items?.type === 'string' && LIST_RESOURCE_ITEMS.includes(spec.items.type)) {
361
+ ;
362
+ value.forEach((entry, i) => {
363
+ if (typeof entry !== 'string' || !/^\S+$/.test(entry)) {
364
+ issues.push(err('invalid_value', `${path}[${i}]`, `Entry ${i + 1} must be a ${spec.items.type} handle.`, nodeId));
365
+ }
366
+ });
367
+ return issues;
368
+ }
369
+ // A palette's colours: named, unique, #rrggbb, at most 20 (theme-abi B.3).
370
+ if (def.value === 'palette') {
371
+ for (const message of paletteValueProblems(value, typeof spec.max === 'number' ? spec.max : undefined)) {
372
+ issues.push(err('invalid_value', path, message, nodeId));
373
+ }
374
+ return issues;
375
+ }
376
+ if (Array.isArray(spec.options) && typeof value === 'string') {
377
+ // Options are `{ value, label }` by contract; a bare string is the editor's
378
+ // accepted shorthand (normOptions) and must not crash the validator, which
379
+ // would turn a merchant's save into a 500 instead of an issue.
380
+ const allowed = spec.options
381
+ .map((o) => (typeof o === 'string' ? o : o?.value))
382
+ .filter((v) => typeof v === 'string');
383
+ if (!allowed.includes(value)) {
384
+ issues.push(err('invalid_value', path, `"${value}" is not one of the declared options: ${allowed.join(', ')}.`, nodeId, nearest(value, allowed) ?? undefined));
385
+ }
386
+ }
387
+ if (typeof value === 'number') {
388
+ if (typeof spec.min === 'number' && value < spec.min) {
389
+ issues.push(err('invalid_value', path, `${value} is below the minimum ${spec.min}.`, nodeId));
390
+ }
391
+ if (typeof spec.max === 'number' && value > spec.max) {
392
+ issues.push(err('invalid_value', path, `${value} is above the maximum ${spec.max}.`, nodeId));
393
+ }
394
+ }
395
+ return issues;
396
+ }
397
+ /** Closest candidate by edit distance, for "did you mean" — only when close. */
398
+ function nearest(input, candidates) {
399
+ let best = null;
400
+ let bestScore = Infinity;
401
+ for (const c of candidates) {
402
+ const d = distance(input.toLowerCase(), c.toLowerCase());
403
+ if (d < bestScore) {
404
+ bestScore = d;
405
+ best = c;
406
+ }
407
+ }
408
+ const limit = Math.max(2, Math.floor(input.length / 3));
409
+ return best !== null && bestScore <= limit ? best : null;
410
+ }
411
+ function distance(a, b) {
412
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
413
+ const cur = new Array(b.length + 1).fill(0);
414
+ for (let i = 1; i <= a.length; i++) {
415
+ cur[0] = i;
416
+ for (let j = 1; j <= b.length; j++) {
417
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
418
+ }
419
+ for (let j = 0; j <= b.length; j++)
420
+ prev[j] = cur[j];
421
+ }
422
+ return prev[b.length];
423
+ }
424
+ // ── Groups ───────────────────────────────────────────────────────────────
425
+ /** Validate one `groups/<name>.json` document against the catalogue. */
426
+ export function validateGroup(name, group, catalog, opts = {}) {
427
+ const issues = [];
428
+ if (!GROUP_NAME_PATTERN.test(name)) {
429
+ issues.push(err('invalid_group', `groups.${name}`, `Group name "${name}" must match ${GROUP_NAME_PATTERN.source}.`));
430
+ }
431
+ if (!isSectionGroupDoc(group)) {
432
+ issues.push(err('invalid_group', `groups.${name}`, `A group must be { type: ${GROUP_SLOTS.join(' | ')}, sections: [] }.`));
433
+ return { ok: false, issues };
434
+ }
435
+ // A group's nodes are validated as top-level nodes of their slot: a block
436
+ // cannot sit directly in a header, and a section limited to the template
437
+ // area cannot be shared as a footer.
438
+ const nodes = group.sections.map((n) => (n.area === undefined ? { ...n, area: group.type } : n));
439
+ walkLevel(nodes, `groups.${name}.sections`, null, catalog, issues, { ...opts, context: opts.context ?? [] });
440
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
441
+ }
442
+ /**
443
+ * Validate a template TOGETHER with the groups it binds — the check the editor,
444
+ * studio-api and the AI tools run before a save.
445
+ *
446
+ * - the template's own body validates as before;
447
+ * - each `ref` must name a supplied group (`unknown_group` otherwise);
448
+ * - each `override` validates as that slot's nodes;
449
+ * - the RESOLVED page is checked for duplicate ids across slots, so a group
450
+ * node and a body node cannot share an id.
451
+ */
452
+ export function validatePage(template, groups, catalog, opts = {}) {
453
+ const issues = [];
454
+ const base = validateDocument(template, catalog, opts);
455
+ issues.push(...base.issues);
456
+ const bindings = template?.groups ?? {};
457
+ for (const slot of GROUP_SLOTS) {
458
+ const b = bindings[slot];
459
+ if (b === undefined)
460
+ continue;
461
+ const path = `groups.${slot}`;
462
+ if (typeof b === 'string' || (b && typeof b === 'object' && 'ref' in b)) {
463
+ const ref = typeof b === 'string' ? b : b.ref;
464
+ if (typeof ref !== 'string' || !ref) {
465
+ issues.push(err('invalid_group', path, `Slot "${slot}" binding must be a group name or { override: [] }.`));
466
+ }
467
+ else if (!groups[ref]) {
468
+ 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)));
469
+ }
470
+ else if (groups[ref].type !== slot) {
471
+ issues.push(err('invalid_group', path, `Group "${ref}" is a ${groups[ref].type} group and cannot fill the ${slot} slot.`));
472
+ }
473
+ }
474
+ else if (b && typeof b === 'object' && 'override' in b) {
475
+ const nodes = b.override;
476
+ if (!Array.isArray(nodes)) {
477
+ issues.push(err('invalid_group', path, `Slot "${slot}" override must be an array of sections.`));
478
+ }
479
+ else {
480
+ walkLevel(nodes.map((n) => (n.area === undefined ? { ...n, area: slot } : n)), `${path}.override`, null, catalog, issues, opts);
481
+ }
482
+ }
483
+ else {
484
+ issues.push(err('invalid_group', path, `Slot "${slot}" binding must be a group name or { override: [] }.`));
485
+ }
486
+ }
487
+ // Duplicate ids across slots: the editor and every targeted edit key by id.
488
+ // Labels come from the slot each node was resolved INTO, not from the
489
+ // provenance map — a duplicate id has already overwritten its own entry there.
490
+ const resolved = resolvePage(template, groups);
491
+ const labelled = [];
492
+ for (const slot of GROUP_SLOTS) {
493
+ const r = resolved.slots[slot];
494
+ const label = r.mode === 'ref' ? `group ${r.group}` : `${slot} ${r.mode}`;
495
+ for (const n of r.sections)
496
+ if (n.id)
497
+ labelled.push({ id: n.id, label });
498
+ }
499
+ const headerCount = resolved.slots.header.sections.length;
500
+ const footerCount = resolved.slots.footer.sections.length;
501
+ const body = resolved.sections.slice(headerCount, resolved.sections.length - footerCount);
502
+ const bodyLabelled = body.filter((n) => n.id).map((n) => ({ id: n.id, label: 'template' }));
503
+ const ordered = [...labelled.slice(0, headerCount), ...bodyLabelled, ...labelled.slice(headerCount)];
504
+ const seen = new Map();
505
+ ordered.forEach(({ id, label }, i) => {
506
+ if (seen.has(id)) {
507
+ 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));
508
+ }
509
+ else {
510
+ seen.set(id, label);
511
+ }
512
+ });
513
+ return { ok: !issues.some((i) => i.severity === 'error'), issues };
514
+ }
515
+ /** Render issues as human lines — shared by the CLI and error responses. */
516
+ export function formatIssues(issues) {
517
+ return issues
518
+ .map((i) => `${i.severity === 'error' ? '✗' : '!'} [${i.code}] ${i.path}: ${i.message}`)
519
+ .join('\n');
520
+ }