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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) 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 +256 -0
  7. package/dist/abi/convert.d.ts +126 -0
  8. package/dist/abi/convert.js +493 -0
  9. package/dist/abi/data-api.d.ts +11 -0
  10. package/dist/abi/data-api.js +178 -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 +198 -0
  14. package/dist/abi/page-data.js +577 -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 +237 -0
  72. package/dist/runtime/data/to-ui.js +759 -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 +167 -0
  82. package/dist/runtime/kit/cart.js +544 -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/{types → runtime/kit}/data.d.ts +276 -7
  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/{types → runtime/kit}/storefront.d.ts +206 -7
  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 +44 -0
  144. package/dist/runtime/render/section-actions.js +169 -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 +82 -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 +120 -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 +395 -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/editor.d.ts +0 -5
  200. package/dist/types/index.d.ts +0 -20
  201. package/dist/types/preview-bridge.d.ts +0 -9
  202. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,402 @@
1
+ /**
2
+ * Section groups — the shared header/footer contract.
3
+ *
4
+ * The problem this solves: every template carried its own copy of the header
5
+ * and footer (17 of Nova's 18 templates, and all 12 marketplace forks). Editing
6
+ * the header on the home page changed the home page only; the other sixteen
7
+ * copies drifted silently, and there was no way to say "this page is different
8
+ * on purpose" versus "nobody updated this copy".
9
+ *
10
+ * The model, in Tanqory's JSON-tree vocabulary:
11
+ *
12
+ * groups/<name>.json ONE source of truth per shared slot:
13
+ * { "type": "header", "sections": [ …ContractNode ] }
14
+ *
15
+ * templates/<slug>.json references the group instead of copying it:
16
+ * { "groups": { "header": "header", "footer": "footer" },
17
+ * "sections": [ …template-area sections only ] }
18
+ *
19
+ * or overrides it for THIS page, explicitly:
20
+ * { "groups": { "header": { "override": [ …nodes ] } } }
21
+ *
22
+ * `resolvePage` is the ONLY function that turns a template + its groups into
23
+ * the flat section list the runtime renders. The storefront, the SSG, the
24
+ * editor preview bridge, studio-api and the AI tools all call it, so "what
25
+ * does this page render" cannot be answered two different ways.
26
+ *
27
+ * Backward compatibility is total: a template with no `groups` key and inline
28
+ * header/footer sections (every template that exists today) resolves exactly
29
+ * as it did — those inline sections are treated as an implicit per-page
30
+ * override. Nothing has to migrate to keep working; migrating is what makes the
31
+ * header SHARED.
32
+ */
33
+ import { NODE_ID_PATTERN } from './content.js';
34
+ export const GROUP_SLOTS = ['header', 'footer'];
35
+ const bindingOf = (b) => {
36
+ if (b === undefined || b === null)
37
+ return null;
38
+ if (typeof b === 'string')
39
+ return { ref: b };
40
+ if (typeof b === 'object') {
41
+ if ('override' in b && Array.isArray(b.override))
42
+ return { override: b.override };
43
+ if ('ref' in b && typeof b.ref === 'string')
44
+ return { ref: b.ref };
45
+ }
46
+ return null;
47
+ };
48
+ /** The slot a legacy inline node belongs to, from `area` first, then its type. */
49
+ export function inlineSlotOf(node) {
50
+ const area = node?.area;
51
+ if (area === 'header' || area === 'footer')
52
+ return area;
53
+ if (area === 'template')
54
+ return 'template';
55
+ if (node?.type === 'header')
56
+ return 'header';
57
+ if (node?.type === 'footer')
58
+ return 'footer';
59
+ return 'template';
60
+ }
61
+ const withArea = (node, area) => node.area === area ? node : { ...node, area };
62
+ /**
63
+ * Resolve a template into the section list the runtime renders.
64
+ *
65
+ * Pure and deterministic: the same template + groups always produce the same
66
+ * list, so the storefront, the SSG, the preview and the editor agree by
67
+ * construction rather than by discipline.
68
+ */
69
+ export function resolvePage(template, groups = {}) {
70
+ const provenance = {};
71
+ const missingGroups = [];
72
+ const all = Array.isArray(template?.sections) ? template.sections : [];
73
+ // Legacy inline nodes are bucketed by slot once; a template that binds a slot
74
+ // explicitly ignores any inline node for that slot (the binding wins).
75
+ const inline = { header: [], template: [], footer: [] };
76
+ for (const node of all)
77
+ inline[inlineSlotOf(node)].push(node);
78
+ const slots = {};
79
+ for (const slot of GROUP_SLOTS) {
80
+ const b = bindingOf(template?.groups?.[slot]);
81
+ if (b?.ref !== undefined) {
82
+ const g = groups[b.ref];
83
+ if (!g) {
84
+ missingGroups.push(b.ref);
85
+ slots[slot] = { mode: 'ref', group: b.ref, sections: [] };
86
+ continue;
87
+ }
88
+ const sections = (Array.isArray(g.sections) ? g.sections : []).map((n) => withArea(n, slot));
89
+ for (const n of sections)
90
+ if (n.id)
91
+ provenance[n.id] = { kind: 'group', slot, group: b.ref };
92
+ slots[slot] = { mode: 'ref', group: b.ref, sections };
93
+ }
94
+ else if (b?.override !== undefined) {
95
+ const sections = b.override.map((n) => withArea(n, slot));
96
+ for (const n of sections)
97
+ if (n.id)
98
+ provenance[n.id] = { kind: 'override', slot };
99
+ slots[slot] = { mode: 'override', sections };
100
+ }
101
+ else if (inline[slot].length) {
102
+ const sections = inline[slot].map((n) => withArea(n, slot));
103
+ for (const n of sections)
104
+ if (n.id)
105
+ provenance[n.id] = { kind: 'inline', slot };
106
+ slots[slot] = { mode: 'inline', sections };
107
+ }
108
+ else {
109
+ slots[slot] = { mode: 'none', sections: [] };
110
+ }
111
+ }
112
+ const body = inline.template;
113
+ for (const n of body)
114
+ if (n.id)
115
+ provenance[n.id] = { kind: 'template' };
116
+ return {
117
+ sections: [...slots.header.sections, ...body, ...slots.footer.sections],
118
+ provenance,
119
+ slots,
120
+ missingGroups,
121
+ };
122
+ }
123
+ /**
124
+ * The inverse of `resolvePage`: take an edited flat list plus the provenance
125
+ * it was resolved with, and produce what to write to the template and to each
126
+ * group file.
127
+ *
128
+ * Rules that make this safe for a shared group:
129
+ * - A node whose provenance says `group` goes back to that group — and ONLY
130
+ * if the slot is still bound to that group. Nothing about a template save
131
+ * can silently rewrite a group the page no longer references.
132
+ * - A node with no provenance (newly inserted) lands where its `area` says.
133
+ * Inserted into a `ref`-bound slot, it becomes part of the shared group —
134
+ * that is the merchant editing "the header", which is shared by design and
135
+ * is reported as such by `groupImpact`.
136
+ * - Body nodes carry no `area` on disk unless they already had one, so a
137
+ * template that never used `area` on body nodes stays byte-identical.
138
+ */
139
+ export function splitPage(sections, previous, opts = {}) {
140
+ const buckets = { header: [], template: [], footer: [] };
141
+ for (const node of sections) {
142
+ const prov = node.id ? previous.provenance[node.id] : undefined;
143
+ const slot = prov
144
+ ? prov.kind === 'template'
145
+ ? 'template'
146
+ : prov.slot
147
+ : inlineSlotOf(node);
148
+ buckets[slot].push(node);
149
+ }
150
+ const source = previousTemplateShape(previous);
151
+ const groupsOut = {};
152
+ const groupsBinding = {};
153
+ // Legacy inline nodes stay inline, in slot order, so an unmigrated template
154
+ // saves back exactly as it was read.
155
+ const inline = { header: [], footer: [] };
156
+ for (const slot of GROUP_SLOTS) {
157
+ const prev = previous.slots[slot];
158
+ const want = opts.slots?.[slot];
159
+ const mode = want?.mode ?? (prev.mode === 'none' ? (buckets[slot].length ? 'inline' : 'none') : prev.mode);
160
+ const nodes = buckets[slot].map((n) => withArea(n, slot));
161
+ if (mode === 'ref') {
162
+ const name = want && want.mode === 'ref' ? want.group : prev.group;
163
+ if (!name)
164
+ throw new Error(`splitPage: slot "${slot}" is bound to a group but no group name is known`);
165
+ groupsBinding[slot] = name;
166
+ // Group nodes are stored without `area` — the slot is the group's `type`.
167
+ groupsOut[slot] = {
168
+ name,
169
+ doc: { type: slot, sections: nodes.map(stripArea) },
170
+ };
171
+ }
172
+ else if (mode === 'override') {
173
+ groupsBinding[slot] = { override: nodes };
174
+ }
175
+ else if (mode === 'inline') {
176
+ // Raw nodes, not `withArea` — a legacy template must save back byte-identical.
177
+ inline[slot] = buckets[slot];
178
+ }
179
+ // 'none' → nothing written for this slot.
180
+ }
181
+ // Rebuild in the SOURCE template's key order, so a save that changes nothing
182
+ // is byte-identical to what was read — that is what makes the revision check
183
+ // and the "nothing to write" short-circuit honest.
184
+ const next = {};
185
+ const merged = [...inline.header, ...buckets.template, ...inline.footer];
186
+ const hasGroups = Object.keys(groupsBinding).length > 0;
187
+ for (const [k, v] of Object.entries(source)) {
188
+ if (k === 'sections')
189
+ next.sections = merged;
190
+ else if (k === 'groups') {
191
+ if (hasGroups)
192
+ next.groups = groupsBinding;
193
+ }
194
+ else
195
+ next[k] = v;
196
+ }
197
+ if (!('sections' in next))
198
+ next.sections = merged;
199
+ if (hasGroups && !('groups' in next))
200
+ next.groups = groupsBinding;
201
+ const template = next;
202
+ return { template, groups: groupsOut };
203
+ }
204
+ /** `resolvePage` does not keep the template; carry the keys a split must preserve. */
205
+ function previousTemplateShape(previous) {
206
+ const extra = previous.template;
207
+ return extra ? { ...extra } : { sections: [] };
208
+ }
209
+ function stripArea(node) {
210
+ if (node.area === undefined)
211
+ return node;
212
+ const { area: _a, ...rest } = node;
213
+ return rest;
214
+ }
215
+ /**
216
+ * Attach the source template to a resolution so `splitPage` can preserve any
217
+ * top-level keys it does not model (`contentVersion`, future additions).
218
+ */
219
+ export function resolvePageFrom(template, groups = {}) {
220
+ return { ...resolvePage(template, groups), template };
221
+ }
222
+ /** Which templates render a given group — the blast radius of editing it. */
223
+ export function groupImpact(groupName, templates) {
224
+ const out = [];
225
+ for (const [slug, doc] of Object.entries(templates)) {
226
+ for (const slot of GROUP_SLOTS) {
227
+ const b = bindingOf(doc?.groups?.[slot]);
228
+ if (b?.ref === groupName) {
229
+ out.push(slug);
230
+ break;
231
+ }
232
+ }
233
+ }
234
+ return out.sort();
235
+ }
236
+ /**
237
+ * Canonical comparison form for a slot's nodes: type + settings-with-defaults
238
+ * + blocks, with ids REMOVED. Ids are identity, not content; two pages whose
239
+ * headers differ only in id are the same header.
240
+ */
241
+ export function slotSignature(nodes, defaults = {}) {
242
+ const norm = (n) => ({
243
+ type: n.type,
244
+ settings: sortKeys({ ...(defaults[n.type] ?? {}), ...(n.settings ?? {}) }),
245
+ blocks: (n.blocks ?? []).map(norm),
246
+ });
247
+ return JSON.stringify(nodes.map(norm));
248
+ }
249
+ function sortKeys(o) {
250
+ return Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
251
+ }
252
+ /** Human-readable diff between two signatures, for the migration report. */
253
+ function describeDifference(a, b, defaults = {}) {
254
+ const out = [];
255
+ const ta = a.map((n) => n.type).join(' + ') || '(empty)';
256
+ const tb = b.map((n) => n.type).join(' + ') || '(empty)';
257
+ if (ta !== tb)
258
+ out.push(`sections: ${tb} vs canonical ${ta}`);
259
+ const len = Math.min(a.length, b.length);
260
+ for (let i = 0; i < len; i++) {
261
+ if (a[i].type !== b[i].type)
262
+ continue;
263
+ const sa = { ...(defaults[a[i].type] ?? {}), ...(a[i].settings ?? {}) };
264
+ const sb = { ...(defaults[b[i].type] ?? {}), ...(b[i].settings ?? {}) };
265
+ for (const k of new Set([...Object.keys(sa), ...Object.keys(sb)])) {
266
+ if (JSON.stringify(sa[k]) !== JSON.stringify(sb[k])) {
267
+ out.push(`${a[i].type}.${k}: ${JSON.stringify(sb[k])} vs canonical ${JSON.stringify(sa[k])}`);
268
+ }
269
+ }
270
+ const ba = (a[i].blocks ?? []).map((x) => x.type).join(',');
271
+ const bb = (b[i].blocks ?? []).map((x) => x.type).join(',');
272
+ if (ba !== bb)
273
+ out.push(`${a[i].type}.blocks: [${bb}] vs canonical [${ba}]`);
274
+ else {
275
+ const blocksA = a[i].blocks ?? [];
276
+ const blocksB = b[i].blocks ?? [];
277
+ for (let j = 0; j < blocksA.length; j++) {
278
+ const x = { ...(defaults[blocksA[j].type] ?? {}), ...(blocksA[j].settings ?? {}) };
279
+ const y = { ...(defaults[blocksB[j].type] ?? {}), ...(blocksB[j].settings ?? {}) };
280
+ for (const k of new Set([...Object.keys(x), ...Object.keys(y)])) {
281
+ if (JSON.stringify(x[k]) !== JSON.stringify(y[k])) {
282
+ out.push(`${a[i].type}.blocks[${j}] (${blocksA[j].type}).${k}: ${JSON.stringify(y[k])} vs canonical ${JSON.stringify(x[k])}`);
283
+ }
284
+ }
285
+ }
286
+ }
287
+ }
288
+ return out;
289
+ }
290
+ /**
291
+ * Turn per-template inline header/footer copies into shared groups.
292
+ *
293
+ * Deterministic and idempotent:
294
+ * - The canonical composition for a slot is the one the MOST templates carry
295
+ * (ties broken by the alphabetically-first template that carries it).
296
+ * - A template whose copy matches canonical (after defaults) binds the group.
297
+ * - A template whose copy differs keeps its own nodes as an explicit
298
+ * `override` — the difference is REPORTED, never merged away.
299
+ * - A template with nothing in the slot binds nothing for it.
300
+ * - A template that already binds the slot is left alone, so running the
301
+ * migration twice changes nothing (`noop: true`).
302
+ *
303
+ * Ids, settings, blocks and order are carried verbatim into the group and into
304
+ * every override; nothing is re-minted.
305
+ */
306
+ export function extractGroups(templates, opts = {}) {
307
+ const defaults = opts.defaults ?? {};
308
+ const out = {};
309
+ for (const [slug, doc] of Object.entries(templates))
310
+ out[slug] = doc;
311
+ const groups = {};
312
+ const report = [];
313
+ let changed = false;
314
+ for (const slot of GROUP_SLOTS) {
315
+ const name = opts.names?.[slot] ?? slot;
316
+ const bySig = new Map();
317
+ const nodesBySlug = new Map();
318
+ const alreadyBound = [];
319
+ const empty = [];
320
+ for (const slug of Object.keys(templates).sort()) {
321
+ const doc = templates[slug];
322
+ if (bindingOf(doc.groups?.[slot])) {
323
+ alreadyBound.push(slug);
324
+ continue;
325
+ }
326
+ const nodes = (Array.isArray(doc.sections) ? doc.sections : []).filter((n) => inlineSlotOf(n) === slot);
327
+ if (!nodes.length) {
328
+ empty.push(slug);
329
+ continue;
330
+ }
331
+ nodesBySlug.set(slug, nodes);
332
+ const sig = slotSignature(nodes, defaults);
333
+ bySig.set(sig, [...(bySig.get(sig) ?? []), slug]);
334
+ }
335
+ if (!nodesBySlug.size) {
336
+ // Nothing inline anywhere: either already migrated (noop) or no such slot.
337
+ if (alreadyBound.length) {
338
+ report.push({
339
+ slot, group: name,
340
+ canonical: { signature: '', templates: [] },
341
+ overrides: [], empty, alreadyBound, idRemaps: [],
342
+ });
343
+ }
344
+ continue;
345
+ }
346
+ // Majority wins; ties → the signature whose first template sorts first.
347
+ const ranked = [...bySig.entries()].sort((a, b) => b[1].length - a[1].length || a[1][0].localeCompare(b[1][0]));
348
+ const [canonicalSig, canonicalSlugs] = ranked[0];
349
+ const canonicalNodes = nodesBySlug.get(canonicalSlugs[0]);
350
+ groups[slot] = {
351
+ name,
352
+ doc: { type: slot, sections: canonicalNodes.map(stripArea) },
353
+ };
354
+ const overrides = [];
355
+ const idRemaps = [];
356
+ for (const [slug, nodes] of nodesBySlug) {
357
+ const sig = slotSignature(nodes, defaults);
358
+ const doc = out[slug];
359
+ const rest = (doc.sections ?? []).filter((n) => inlineSlotOf(n) !== slot);
360
+ const binding = sig === canonicalSig ? name : { override: nodes.map((n) => withArea(n, slot)) };
361
+ if (sig !== canonicalSig) {
362
+ overrides.push({ template: slug, signature: sig, differences: describeDifference(canonicalNodes, nodes, defaults) });
363
+ }
364
+ else {
365
+ // Same content, possibly different ids: the group keeps the canonical
366
+ // template's ids. Say which ids this template loses.
367
+ const pairs = (a, b) => {
368
+ a.forEach((x, i) => {
369
+ const y = b[i];
370
+ if (!y)
371
+ return;
372
+ if (x.id && y.id && x.id !== y.id)
373
+ idRemaps.push({ template: slug, from: y.id, to: x.id });
374
+ pairs(x.blocks ?? [], y.blocks ?? []);
375
+ });
376
+ };
377
+ pairs(canonicalNodes, nodes);
378
+ }
379
+ out[slug] = {
380
+ ...doc,
381
+ groups: { ...(doc.groups ?? {}), [slot]: binding },
382
+ sections: rest,
383
+ };
384
+ changed = true;
385
+ }
386
+ report.push({
387
+ slot, group: name,
388
+ canonical: { signature: canonicalSig, templates: canonicalSlugs },
389
+ overrides, empty, alreadyBound, idRemaps,
390
+ });
391
+ }
392
+ return { groups, templates: out, report, noop: !changed };
393
+ }
394
+ /** Validate a group document's own shape (the content validator checks its nodes). */
395
+ export function isSectionGroupDoc(v) {
396
+ if (!v || typeof v !== 'object')
397
+ return false;
398
+ const g = v;
399
+ return GROUP_SLOTS.includes(g.type) && Array.isArray(g.sections);
400
+ }
401
+ /** Group file names must be safe path segments. */
402
+ export const GROUP_NAME_PATTERN = NODE_ID_PATTERN;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tanqory Theme Contract v1 — the shared agreement between the theme (kit),
3
+ * the CMS (studio-api + code-store), the Editor (studio-app), the storefront
4
+ * runtime, and any AI authoring against them.
5
+ *
6
+ * Owner: `@tanqory/theme-kit`. It already owns `AttrSpec` / `SectionDef` /
7
+ * `ContentNode` / `PageDoc`, so the contract derives from the code rather than
8
+ * restating it — and `tsc` proves the derivation.
9
+ *
10
+ * This entry is dependency-free (no React), so it builds to a single portable
11
+ * `dist/contract.js` that studio-api can vendor without breaking its
12
+ * zero-npm-dependency image.
13
+ */
14
+ export declare const CONTRACT_VERSION = "1.0.0";
15
+ /**
16
+ * Which theme-kit releases this contract describes.
17
+ *
18
+ * Nothing on the platform declared runtime compatibility before, so a theme
19
+ * built against one kit and rendered by another failed at runtime with no
20
+ * signal. A consumer compares its installed kit version against this range and
21
+ * says so up front.
22
+ */
23
+ export declare const KIT_COMPATIBILITY: {
24
+ /** Lowest kit release whose runtime honours everything in this contract. */
25
+ readonly min: "0.1.3";
26
+ /** Highest kit release verified against it. */
27
+ readonly maxVerified: "0.2.0";
28
+ };
29
+ export * from './field-types.js';
30
+ export * from './content.js';
31
+ export * from './groups.js';
32
+ export * from './transform.js';
33
+ export * from './validate.js';
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tanqory Theme Contract v1 — the shared agreement between the theme (kit),
3
+ * the CMS (studio-api + code-store), the Editor (studio-app), the storefront
4
+ * runtime, and any AI authoring against them.
5
+ *
6
+ * Owner: `@tanqory/theme-kit`. It already owns `AttrSpec` / `SectionDef` /
7
+ * `ContentNode` / `PageDoc`, so the contract derives from the code rather than
8
+ * restating it — and `tsc` proves the derivation.
9
+ *
10
+ * This entry is dependency-free (no React), so it builds to a single portable
11
+ * `dist/contract.js` that studio-api can vendor without breaking its
12
+ * zero-npm-dependency image.
13
+ */
14
+ export const CONTRACT_VERSION = '1.0.0';
15
+ /**
16
+ * Which theme-kit releases this contract describes.
17
+ *
18
+ * Nothing on the platform declared runtime compatibility before, so a theme
19
+ * built against one kit and rendered by another failed at runtime with no
20
+ * signal. A consumer compares its installed kit version against this range and
21
+ * says so up front.
22
+ */
23
+ export const KIT_COMPATIBILITY = {
24
+ /** Lowest kit release whose runtime honours everything in this contract. */
25
+ min: '0.1.3',
26
+ /** Highest kit release verified against it. */
27
+ maxVerified: '0.2.0',
28
+ };
29
+ export * from './field-types.js';
30
+ export * from './content.js';
31
+ export * from './groups.js';
32
+ export * from './transform.js';
33
+ export * from './validate.js';
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The canonical Editor ↔ runtime transform.
3
+ *
4
+ * Two shapes exist and both are load-bearing:
5
+ * runtime / disk : `{ sections: [ { type, id, settings, blocks? } ] }` — an
6
+ * ARRAY, because `SectionTree` does `node.blocks?.map`.
7
+ * editor UI : `{ order: [id], sections: { id: {...} } }` — an object map
8
+ * keyed by id, because the panel addresses nodes by id.
9
+ *
10
+ * studio-api converts between them today (`editor-routes.mjs:77-108`). That
11
+ * implementation is lossy in three ways this one is not:
12
+ *
13
+ * 1. **It rebuilds a fixed shape**, so any key it does not enumerate is
14
+ * destroyed on the first autosave. `area` — used 43× in Nova's templates,
15
+ * and written by the AI theme assembler — is dropped on read and never
16
+ * restored on write. Anything this contract adds later would go the same
17
+ * way. Here, unknown keys are carried through.
18
+ * 2. **A block with no id gets `` `${type}-${index}` ``** — a POSITIONAL
19
+ * identity. Reorder and `faq-item-0` silently means a different question,
20
+ * which breaks "edit one answer without touching the others".
21
+ * 3. **A section with no id falls back to its `type`**, so two sections of the
22
+ * same type collide in the map and the second overwrites the first.
23
+ *
24
+ * Ids are minted once, here, when genuinely absent — and reported, so the
25
+ * caller can persist them instead of re-minting on every read.
26
+ */
27
+ import { type ContractPageDoc } from './content.js';
28
+ /** The editor's object-map shape for one node. */
29
+ export interface EditorNode {
30
+ type: string;
31
+ settings: Record<string, unknown>;
32
+ blocks?: Record<string, EditorNode>;
33
+ order?: string[];
34
+ /** Keys the contract does not model, preserved verbatim across the round trip. */
35
+ [extra: string]: unknown;
36
+ }
37
+ export interface EditorDoc {
38
+ order: string[];
39
+ sections: Record<string, EditorNode>;
40
+ contentVersion?: number;
41
+ /**
42
+ * Top-level keys the transform does not model — `groups` (the shared
43
+ * header/footer bindings) above all — preserved verbatim, so a document that
44
+ * binds a group still binds it after an Editor round trip.
45
+ */
46
+ [extra: string]: unknown;
47
+ }
48
+ export interface TransformReport {
49
+ /** Ids minted because a node had none. Persist these or they change next read. */
50
+ mintedIds: Array<{
51
+ path: string;
52
+ type: string;
53
+ id: string;
54
+ }>;
55
+ /** Ids that collided and had to be disambiguated. */
56
+ renamedIds: Array<{
57
+ path: string;
58
+ from: string;
59
+ to: string;
60
+ }>;
61
+ }
62
+ /**
63
+ * runtime/disk → editor. Non-destructive: unmodelled keys survive in the node
64
+ * and are restored by `toRuntimeShape`.
65
+ */
66
+ export declare function toEditorShape(doc: ContractPageDoc, mint?: (type: string) => string): {
67
+ doc: EditorDoc;
68
+ report: TransformReport;
69
+ };
70
+ /** editor → runtime/disk. The exact inverse, including unmodelled keys. */
71
+ export declare function toRuntimeShape(doc: EditorDoc): ContractPageDoc;
72
+ /**
73
+ * Give every node an explicit id, in place of the positional fallback.
74
+ *
75
+ * Run once over a template authored before this contract (or by a producer that
76
+ * omitted ids) and persist the result: after that, ids are stable and a
77
+ * targeted edit addresses the node the author meant.
78
+ */
79
+ export declare function ensureNodeIds(doc: ContractPageDoc, mint?: (type: string) => string): {
80
+ doc: ContractPageDoc;
81
+ report: TransformReport;
82
+ };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The canonical Editor ↔ runtime transform.
3
+ *
4
+ * Two shapes exist and both are load-bearing:
5
+ * runtime / disk : `{ sections: [ { type, id, settings, blocks? } ] }` — an
6
+ * ARRAY, because `SectionTree` does `node.blocks?.map`.
7
+ * editor UI : `{ order: [id], sections: { id: {...} } }` — an object map
8
+ * keyed by id, because the panel addresses nodes by id.
9
+ *
10
+ * studio-api converts between them today (`editor-routes.mjs:77-108`). That
11
+ * implementation is lossy in three ways this one is not:
12
+ *
13
+ * 1. **It rebuilds a fixed shape**, so any key it does not enumerate is
14
+ * destroyed on the first autosave. `area` — used 43× in Nova's templates,
15
+ * and written by the AI theme assembler — is dropped on read and never
16
+ * restored on write. Anything this contract adds later would go the same
17
+ * way. Here, unknown keys are carried through.
18
+ * 2. **A block with no id gets `` `${type}-${index}` ``** — a POSITIONAL
19
+ * identity. Reorder and `faq-item-0` silently means a different question,
20
+ * which breaks "edit one answer without touching the others".
21
+ * 3. **A section with no id falls back to its `type`**, so two sections of the
22
+ * same type collide in the map and the second overwrites the first.
23
+ *
24
+ * Ids are minted once, here, when genuinely absent — and reported, so the
25
+ * caller can persist them instead of re-minting on every read.
26
+ */
27
+ import { mintNodeId } from './content.js';
28
+ /** Top-level keys the transform manages; everything else rides through. */
29
+ const MANAGED_DOC_KEYS = new Set(['sections', 'order', 'contentVersion']);
30
+ /** Keys the transform manages explicitly; everything else rides in `extra`. */
31
+ const MANAGED = new Set(['type', 'id', 'settings', 'blocks']);
32
+ /**
33
+ * runtime/disk → editor. Non-destructive: unmodelled keys survive in the node
34
+ * and are restored by `toRuntimeShape`.
35
+ */
36
+ export function toEditorShape(doc, mint = mintNodeId) {
37
+ const report = { mintedIds: [], renamedIds: [] };
38
+ const sections = Array.isArray(doc?.sections) ? doc.sections : [];
39
+ const { map, order } = levelToEditor(sections, 'sections', report, mint);
40
+ const extra = {};
41
+ for (const [k, v] of Object.entries(doc ?? {}))
42
+ if (!MANAGED_DOC_KEYS.has(k))
43
+ extra[k] = v;
44
+ return {
45
+ doc: {
46
+ order,
47
+ sections: map,
48
+ contentVersion: doc?.contentVersion ?? undefined,
49
+ ...extra,
50
+ },
51
+ report,
52
+ };
53
+ }
54
+ function levelToEditor(nodes, basePath, report, mint) {
55
+ const map = {};
56
+ const order = [];
57
+ nodes.forEach((node, i) => {
58
+ const path = `${basePath}[${i}]`;
59
+ let id = typeof node?.id === 'string' && node.id !== '' ? node.id : '';
60
+ if (!id) {
61
+ id = mint(node?.type ?? 'node');
62
+ report.mintedIds.push({ path, type: node?.type ?? 'node', id });
63
+ }
64
+ if (map[id]) {
65
+ const to = mint(node?.type ?? 'node');
66
+ report.renamedIds.push({ path, from: id, to });
67
+ id = to;
68
+ }
69
+ const extra = {};
70
+ for (const [k, v] of Object.entries(node ?? {})) {
71
+ if (!MANAGED.has(k))
72
+ extra[k] = v;
73
+ }
74
+ const child = Array.isArray(node?.blocks)
75
+ ? levelToEditor(node.blocks, `${path}.blocks`, report, mint)
76
+ : null;
77
+ map[id] = {
78
+ type: node?.type,
79
+ settings: node?.settings ?? {},
80
+ ...extra,
81
+ ...(child ? { blocks: child.map, order: child.order } : {}),
82
+ };
83
+ order.push(id);
84
+ });
85
+ return { map, order };
86
+ }
87
+ /** editor → runtime/disk. The exact inverse, including unmodelled keys. */
88
+ export function toRuntimeShape(doc) {
89
+ const order = Array.isArray(doc?.order) ? doc.order : Object.keys(doc?.sections ?? {});
90
+ const extra = {};
91
+ for (const [k, v] of Object.entries(doc ?? {}))
92
+ if (!MANAGED_DOC_KEYS.has(k))
93
+ extra[k] = v;
94
+ return {
95
+ ...(doc?.contentVersion !== undefined ? { contentVersion: doc.contentVersion } : {}),
96
+ sections: levelToRuntime(doc?.sections ?? {}, order),
97
+ ...extra,
98
+ };
99
+ }
100
+ function levelToRuntime(map, order) {
101
+ return order
102
+ .filter((id) => map[id])
103
+ .map((id) => {
104
+ const node = map[id];
105
+ const extra = {};
106
+ for (const [k, v] of Object.entries(node)) {
107
+ if (k === 'type' || k === 'settings' || k === 'blocks' || k === 'order')
108
+ continue;
109
+ extra[k] = v;
110
+ }
111
+ const blocks = node.blocks && typeof node.blocks === 'object'
112
+ ? levelToRuntime(node.blocks, Array.isArray(node.order) ? node.order : Object.keys(node.blocks))
113
+ : null;
114
+ return {
115
+ type: node.type,
116
+ id,
117
+ settings: node.settings ?? {},
118
+ ...extra,
119
+ ...(blocks && blocks.length ? { blocks } : {}),
120
+ };
121
+ });
122
+ }
123
+ /**
124
+ * Give every node an explicit id, in place of the positional fallback.
125
+ *
126
+ * Run once over a template authored before this contract (or by a producer that
127
+ * omitted ids) and persist the result: after that, ids are stable and a
128
+ * targeted edit addresses the node the author meant.
129
+ */
130
+ export function ensureNodeIds(doc, mint = mintNodeId) {
131
+ const { doc: editor, report } = toEditorShape(doc, mint);
132
+ return { doc: toRuntimeShape(editor), report };
133
+ }