@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
@@ -1,4 +1,4 @@
1
- import type { SectionDef } from './types';
1
+ import type { SectionDef } from './types.js';
2
2
  /**
3
3
  * Declare a section (a top-level, editor-placeable unit). Attaches `blockName`
4
4
  * to the component so a JSX composition (`<Hero/>`) can be walked back into the
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Declare a section (a top-level, editor-placeable unit). Attaches `blockName`
3
+ * to the component so a JSX composition (`<Hero/>`) can be walked back into the
4
+ * content tree (see jsx-to-json.ts).
5
+ */
6
+ export function defineSection(def) {
7
+ ;
8
+ def.component.blockName = def.name;
9
+ return def;
10
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Dynamic sources — bind a section/block setting to a live metafield, resource
3
- * property, or metaobject field (Shopify "Insert dynamic source", the ⛁ icon).
3
+ * property, or metaobject field (the commerce standard "Insert dynamic source", the ⛁ icon).
4
4
  *
5
5
  * A setting value is normally a primitive. When the merchant connects a dynamic
6
6
  * source the editor stores a `{ '@source': '<path>' }` object instead, and the
@@ -12,13 +12,13 @@
12
12
  * product.title / shop.name → a plain resource property
13
13
  * metaobject:size:medium.label → a metaobject field (type:handle.key)
14
14
  *
15
- * The path grammar mirrors Shopify so themes/docs are portable. Resolution is
15
+ * The path grammar follows the standard commerce object model.
16
16
  * synchronous against already-loaded resources — the provider is responsible
17
17
  * for loading the bound metafields (see `collectBoundIdentifiers`).
18
18
  */
19
19
  import { type ReactNode } from 'react';
20
- import type { Product, Collection } from './data';
21
- import type { Shop, Metaobject } from './storefront';
20
+ import type { Product, Collection } from './data.js';
21
+ import type { Shop, Metaobject } from './storefront.js';
22
22
  /** A setting bound to a dynamic source instead of a literal value. */
23
23
  export interface BoundSource {
24
24
  '@source': string;
@@ -0,0 +1,143 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * Dynamic sources — bind a section/block setting to a live metafield, resource
4
+ * property, or metaobject field (the commerce standard "Insert dynamic source", the ⛁ icon).
5
+ *
6
+ * A setting value is normally a primitive. When the merchant connects a dynamic
7
+ * source the editor stores a `{ '@source': '<path>' }` object instead, and the
8
+ * theme resolves it at render against the CURRENT page resource:
9
+ *
10
+ * product.metafields.custom.subtitle → the page product's metafield
11
+ * collection.metafields.custom.tagline → the page collection's metafield
12
+ * shop.metafields.custom.announcement → the store's metafield (any page)
13
+ * product.title / shop.name → a plain resource property
14
+ * metaobject:size:medium.label → a metaobject field (type:handle.key)
15
+ *
16
+ * The path grammar follows the standard commerce object model.
17
+ * synchronous against already-loaded resources — the provider is responsible
18
+ * for loading the bound metafields (see `collectBoundIdentifiers`).
19
+ */
20
+ import { createContext, useContext } from 'react';
21
+ import { useData } from './data.js';
22
+ export function isBoundSource(v) {
23
+ return (typeof v === 'object' &&
24
+ v !== null &&
25
+ typeof v['@source'] === 'string');
26
+ }
27
+ const ResourceContext = createContext({});
28
+ /**
29
+ * Provide the current page's resources to dynamic sources. Wrap the page once
30
+ * (the layout does this). `shop` falls back to the data source so shop-level
31
+ * bindings work on every page without extra wiring.
32
+ */
33
+ export function DynamicSourceProvider({ value, children, }) {
34
+ return _jsx(ResourceContext.Provider, { value: value, children: children });
35
+ }
36
+ export function useResourceContext() {
37
+ const data = useData();
38
+ const ctx = useContext(ResourceContext);
39
+ // Shop is always available from the data source; an explicit provider value
40
+ // (carrying loaded shop metafields) takes precedence.
41
+ return { shop: data.shop, ...ctx };
42
+ }
43
+ const METAOBJECT_RE = /^metaobject:([^:]+):([^.]+)\.(.+)$/;
44
+ /** Resolve a `@source` path against a resource context. Returns null if unbound. */
45
+ export function resolveBoundSource(source, ctx) {
46
+ const mo = source.match(METAOBJECT_RE);
47
+ if (mo) {
48
+ const [, type, handle, field] = mo;
49
+ const obj = ctx.metaobject?.(type, handle);
50
+ return obj?.values?.[field] ?? null;
51
+ }
52
+ const parts = source.split('.');
53
+ const root = parts[0];
54
+ const resource = root === 'product'
55
+ ? ctx.product
56
+ : root === 'collection'
57
+ ? ctx.collection
58
+ : root === 'shop'
59
+ ? ctx.shop
60
+ : null;
61
+ if (!resource)
62
+ return null;
63
+ if (parts[1] === 'metafields') {
64
+ const ns = parts[2];
65
+ const key = parts.slice(3).join('.');
66
+ if (!ns || !key)
67
+ return null;
68
+ return resource.metafields?.[`${ns}.${key}`] ?? null;
69
+ }
70
+ // Plain resource property: product.title, shop.name, collection.title…
71
+ const direct = resource[parts[1]];
72
+ return direct == null ? null : String(direct);
73
+ }
74
+ /**
75
+ * Resolve a possibly-bound setting value for the current page.
76
+ * const heading = useBound(attributes.heading) // string | the literal | null
77
+ * A plain value passes through unchanged; a `{ '@source' }` object resolves to
78
+ * the live value (or null when the source has no value on this resource).
79
+ */
80
+ export function useBound(value) {
81
+ const ctx = useResourceContext();
82
+ if (!isBoundSource(value))
83
+ return value;
84
+ return resolveBoundSource(value['@source'], ctx);
85
+ }
86
+ /** Convenience: resolve to a string (empty when null/unbound-empty). */
87
+ export function useBoundText(value, fallback = '') {
88
+ const resolved = useBound(value);
89
+ if (resolved == null)
90
+ return fallback;
91
+ return typeof resolved === 'string' ? resolved : String(resolved);
92
+ }
93
+ /**
94
+ * Walk a content tree's section/block settings and collect every bound metafield
95
+ * identifier, grouped by resource. The provider uses this to request exactly the
96
+ * metafields the page binds (the live product/collection query takes identifiers).
97
+ */
98
+ export function collectBoundIdentifiers(nodes) {
99
+ const out = {
100
+ product: [],
101
+ collection: [],
102
+ shop: [],
103
+ };
104
+ const seen = new Set();
105
+ const visitSettings = (settings) => {
106
+ if (!settings)
107
+ return;
108
+ for (const v of Object.values(settings)) {
109
+ if (!isBoundSource(v))
110
+ continue;
111
+ const parts = v['@source'].split('.');
112
+ const root = parts[0];
113
+ if (parts[1] !== 'metafields')
114
+ continue;
115
+ const namespace = parts[2];
116
+ const key = parts.slice(3).join('.');
117
+ if (!namespace || !key || !(root in out))
118
+ continue;
119
+ const dedupe = `${root}:${namespace}.${key}`;
120
+ if (seen.has(dedupe))
121
+ continue;
122
+ seen.add(dedupe);
123
+ out[root].push({ namespace, key });
124
+ }
125
+ };
126
+ // Sections + blocks may store children as an array OR an object map (the
127
+ // editor's `{ id: node }` shape) — normalize both before iterating.
128
+ const toNodes = (v) => {
129
+ if (Array.isArray(v))
130
+ return v;
131
+ if (v && typeof v === 'object')
132
+ return Object.values(v);
133
+ return [];
134
+ };
135
+ const walk = (list) => {
136
+ for (const node of toNodes(list)) {
137
+ visitSettings(node.settings);
138
+ walk(node.blocks);
139
+ }
140
+ };
141
+ walk(nodes);
142
+ return out;
143
+ }
@@ -0,0 +1,24 @@
1
+ export { defineSection } from './defineSection.js';
2
+ export { createAnalytics, getAnalytics, subscribe, type Analytics, type AnalyticsOptions, type StorefrontEventType, type StorefrontEvent, } from './analytics.js';
3
+ export { getConsent, setConsent, hasConsent, hasDecided, setBannerRequired, isBannerRequired, setConsentMode, holdConsentClosed, isConsentArmed, onConsentModeChange, getConsentMode, consentModeFromShop, onConsentChange, type Consent, type ConsentMode, } from './consent.js';
4
+ export { defineTheme, defineSettings, type ThemeConfig, type SettingsSchema } from './config.js';
5
+ export { ThemeProvider, useSettings, useT } from './theme-context.js';
6
+ export { mount, groupsFromGlob, resolvePageSections, type MountOptions } from './mount.js';
7
+ export { renderStorefrontHTML, renderSectionPreviewHTML } from './ssg.js';
8
+ export { SectionTree, usePageTree } from './SectionTree.js';
9
+ export { registerSections, getSection, allSections } from './registry.js';
10
+ export { DataProvider, useData, createMockData, createLiveData, createLiveDataFromSnapshot, formatMoney, formatMoneyWithCurrency, formatMoneyWithoutCurrency, formatMoneyWithoutTrailingZeros, imageUrl, formatDate, formatWeight, } from './data.js';
11
+ export { CartProvider, useCart } from './cart.js';
12
+ export { DynamicSourceProvider, useResourceContext, useBound, useBoundText, isBoundSource, resolveBoundSource, collectBoundIdentifiers, } from './dynamic-source.js';
13
+ export type { Bound, BoundSource, ResourceContextValue } from './dynamic-source.js';
14
+ export type { CartApi, CartLine, CartState, AddToCartInput, AppliedDiscountCode, AppliedGiftCard, } from './cart.js';
15
+ export type { LiveDataOptions, Localization, LocalizedCountry, LocalizedMarket, LocalizedCurrency, ProductOption, ProductVariant, ImageRef, QuantityRule, UnitPriceMeasurement, StoreAvailability, SellingPlan, SellingPlanOption, SellingPlanGroup, Measurement, Rating, FocalPoint, ImagePresentation, ModelSource, VideoSource, GenericFile, Recommendations, } from './data.js';
16
+ export { toRecommendations } from './data.js';
17
+ export { jsxToJSON } from './jsx-to-json.js';
18
+ export { tag, type Tag } from './composition.js';
19
+ export type { Money, Product, Collection, DataApi } from './data.js';
20
+ export type { SectionDef, SectionProps, ContentNode, PageDoc, AttrSpec, SectionPreset, SectionGroupDoc } from './types.js';
21
+ export { customerTokenStore } from './storefront.js';
22
+ export type { StorefrontExtensions, Menu, MenuItem, MenuItemType, Blog, Article, SearchResults, CollectionProductsPage, PredictiveSearchResults, PageInfo, Filter, Metaobject, MetaobjectField, Shop, ShopPolicy, Image as StorefrontImage, Seo, CustomerApi, Customer, CustomerAddress, CustomerAddressInput, CustomerPaymentMethod, Order, OrderTransaction, OrderGiftCard, StoreCreditAccount, OrderLineItem, AuthResult, MutationResult, } from './storefront.js';
23
+ export { CONTRACT_VERSION, KIT_COMPATIBILITY, FIELD_TYPES, FIELD_TYPE_ALIASES, EDITOR_ONLY_TYPES, UNIVERSAL_CONSTRAINTS, canonicalFieldType, fieldType, TEMPLATE_AREAS, CONTEXT_KINDS, CURRENT_CONTENT_VERSION, NODE_ID_PATTERN, mintNodeId, roleOf, templateContext, SECTION_ROLES, GROUP_SLOTS, GROUP_NAME_PATTERN, resolvePage, resolvePageFrom, splitPage, groupImpact, extractGroups, slotSignature, inlineSlotOf, isSectionGroupDoc, validatePage, validateGroup, toEditorShape, toRuntimeShape, ensureNodeIds, validateDocument, validateSectionContract, formatIssues, } from './contract/index.js';
24
+ export type { FieldTypeDef, FieldTypeId, FieldTypeAlias, AnyFieldType, ControlKind, ValueKind, ContractNode, ContractPageDoc, SectionContract, SectionPresetContract, AttrContract, TemplateArea, ContextKind, SectionRole, PlacementContract, GroupSlot, GroupBinding, GroupedPageDoc, GroupMap, NodeSource, SlotResolution, ResolvedPage, SplitResult, SplitOptions, ExtractOptions, ExtractReport, ExtractResult, ValidationIssue, ValidationResult, ValidationCode, SectionCatalog, ValidateOptions, Severity, EditorNode, EditorDoc, TransformReport, } from './contract/index.js';
@@ -0,0 +1,24 @@
1
+ // @tanqory/theme-kit — public API. Themes import only from here.
2
+ export { defineSection } from './defineSection.js';
3
+ export { createAnalytics, getAnalytics, subscribe, } from './analytics.js';
4
+ export { getConsent, setConsent, hasConsent, hasDecided, setBannerRequired, isBannerRequired, setConsentMode, holdConsentClosed, isConsentArmed, onConsentModeChange, getConsentMode, consentModeFromShop, onConsentChange, } from './consent.js';
5
+ export { defineTheme, defineSettings } from './config.js';
6
+ export { ThemeProvider, useSettings, useT } from './theme-context.js';
7
+ export { mount, groupsFromGlob, resolvePageSections } from './mount.js';
8
+ export { renderStorefrontHTML, renderSectionPreviewHTML } from './ssg.js';
9
+ export { SectionTree, usePageTree } from './SectionTree.js';
10
+ export { registerSections, getSection, allSections } from './registry.js';
11
+ export { DataProvider, useData, createMockData, createLiveData, createLiveDataFromSnapshot, formatMoney, formatMoneyWithCurrency, formatMoneyWithoutCurrency, formatMoneyWithoutTrailingZeros, imageUrl, formatDate, formatWeight, } from './data.js';
12
+ export { CartProvider, useCart } from './cart.js';
13
+ export { DynamicSourceProvider, useResourceContext, useBound, useBoundText, isBoundSource, resolveBoundSource, collectBoundIdentifiers, } from './dynamic-source.js';
14
+ export { toRecommendations } from './data.js';
15
+ export { jsxToJSON } from './jsx-to-json.js';
16
+ export { tag } from './composition.js';
17
+ // commerce-standard storefront extensions (live data layer): navigation menus,
18
+ // blog/articles, search, recommendations, metaobjects, shop/policies, and the
19
+ // full customer account flow. See storefront.ts.
20
+ export { customerTokenStore } from './storefront.js';
21
+ // Tanqory Theme Contract v1 — the shared agreement between theme, CMS, Editor
22
+ // and AI. Also built as its own dependency-free entry (`@tanqory/theme-kit/contract`)
23
+ // so studio-api can vendor it without an npm install.
24
+ export { CONTRACT_VERSION, KIT_COMPATIBILITY, FIELD_TYPES, FIELD_TYPE_ALIASES, EDITOR_ONLY_TYPES, UNIVERSAL_CONSTRAINTS, canonicalFieldType, fieldType, TEMPLATE_AREAS, CONTEXT_KINDS, CURRENT_CONTENT_VERSION, NODE_ID_PATTERN, mintNodeId, roleOf, templateContext, SECTION_ROLES, GROUP_SLOTS, GROUP_NAME_PATTERN, resolvePage, resolvePageFrom, splitPage, groupImpact, extractGroups, slotSignature, inlineSlotOf, isSectionGroupDoc, validatePage, validateGroup, toEditorShape, toRuntimeShape, ensureNodeIds, validateDocument, validateSectionContract, formatIssues, } from './contract/index.js';
@@ -1,5 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
- import type { ContentNode } from './types';
2
+ import type { ContentNode } from './types.js';
3
3
  /**
4
4
  * Compile a *static* JSX composition into the canonical JSON block tree.
5
5
  *
@@ -0,0 +1,28 @@
1
+ import { Children, isValidElement } from 'react';
2
+ /**
3
+ * Compile a *static* JSX composition into the canonical JSON block tree.
4
+ *
5
+ * <Hero settings={{…}}><Button settings={{…}} /></Hero>
6
+ * → [{ type:'hero', settings:{…}, blocks:[{ type:'button', settings:{…} }] }]
7
+ *
8
+ * Only nesting + literal `settings` are read — there is no place for logic, which
9
+ * is exactly what keeps a page round-trippable by the editor. (Logic lives in
10
+ * the block components, never in a page composition.)
11
+ */
12
+ export function jsxToJSON(node) {
13
+ return Children.toArray(node).flatMap((el) => {
14
+ if (!isValidElement(el))
15
+ return [];
16
+ const name = el.type?.blockName;
17
+ if (!name)
18
+ return [];
19
+ const props = el.props;
20
+ const out = { type: name };
21
+ if (props.settings)
22
+ out.settings = props.settings;
23
+ const blocks = jsxToJSON(props.children);
24
+ if (blocks.length)
25
+ out.blocks = blocks;
26
+ return [out];
27
+ });
28
+ }
@@ -1,12 +1,20 @@
1
- import { type DataApi } from './data';
1
+ import { type DataApi } from './data.js';
2
+ import type { PageDoc, ContentNode } from './types.js';
3
+ import { type GroupMap } from './contract/groups.js';
2
4
  type GlobMap = Record<string, unknown>;
3
5
  export interface MountOptions {
4
- /** import.meta.glob('./sections/*.tsx', { eager: true }) — run in the THEME. */
6
+ /** import.meta.glob('../../../../themes/nova/app/platform/tanqory/sections/*.tsx', { eager: true }) — run in the THEME. */
5
7
  sections: GlobMap;
6
- /** import.meta.glob('./templates/*.json', { eager: true }). */
8
+ /** import.meta.glob('../../../../themes/nova/app/platform/tanqory/templates/*.json', { eager: true }). */
7
9
  pages: GlobMap;
8
- /** import.meta.glob('./layouts/*.tsx', { eager: true }) — optional. */
10
+ /** import.meta.glob('../../../../themes/nova/app/platform/tanqory/layouts/*.tsx', { eager: true }) — optional. */
9
11
  shell?: GlobMap;
12
+ /**
13
+ * import.meta.glob('../../../../themes/nova/app/platform/tanqory/groups/*.json', { eager: true }) — the shared
14
+ * header/footer groups a template may bind. Optional: a theme with no
15
+ * `groups/` renders its templates' inline header/footer exactly as before.
16
+ */
17
+ groups?: GlobMap;
10
18
  /** Data source the theme provides (createMockData(...) or a live client). */
11
19
  data: DataApi;
12
20
  /** Global settings values (config/settings.json). */
@@ -32,7 +40,20 @@ export interface MountOptions {
32
40
  * hydrating against mismatched markup throws React #418/#425.
33
41
  */
34
42
  forceClientRender?: boolean;
43
+ /**
44
+ * Exact studio origins allowed to drive the preview bridge (and the only
45
+ * targets it posts to). Defaults to the platform's studio hosts; a loopback
46
+ * page also accepts any loopback origin so the laptop loop works on any port.
47
+ */
48
+ previewOrigins?: readonly string[];
35
49
  }
50
+ /** `groups/<name>.json` glob → name-keyed map for `resolvePage`. */
51
+ export declare function groupsFromGlob(map?: GlobMap): GroupMap;
52
+ /**
53
+ * The section list a template renders — header group, body, footer group —
54
+ * through the ONE resolver the editor and the AI tools also use.
55
+ */
56
+ export declare function resolvePageSections(doc: PageDoc | undefined, groups: GroupMap): ContentNode[];
36
57
  /**
37
58
  * Boot a theme. The theme's entry passes its globbed sections/templates/layouts
38
59
  * (so Vite resolves them relative to the theme) plus a data source. Everything
@@ -0,0 +1,124 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import React from 'react';
3
+ import { createRoot, hydrateRoot } from 'react-dom/client';
4
+ import { registerSections } from './registry.js';
5
+ import { SectionTree } from './SectionTree.js';
6
+ import { DataProvider } from './data.js';
7
+ import { CartProvider } from './cart.js';
8
+ import { ThemeProvider } from './theme-context.js';
9
+ import { resolvePage } from './contract/groups.js';
10
+ import { getEditorRuntime } from '../slots.js';
11
+ /** `?key`, `?key=1`, `?key=true` are on; `?key=0` / `?key=false` are off. */
12
+ const flagOn = (search, key) => {
13
+ const v = new URLSearchParams(search).get(key);
14
+ return v !== null && v !== '0' && v !== 'false';
15
+ };
16
+ function defaultsOf(map) {
17
+ return Object.values(map).map((m) => m.default);
18
+ }
19
+ function pickByName(map, name) {
20
+ const hit = Object.entries(map).find(([key]) => key.endsWith(`/${name}.json`) || key.endsWith(`/${name}.tsx`));
21
+ return hit ? hit[1].default : undefined;
22
+ }
23
+ /** `groups/<name>.json` glob → name-keyed map for `resolvePage`. */
24
+ export function groupsFromGlob(map) {
25
+ const out = {};
26
+ for (const [key, mod] of Object.entries(map ?? {})) {
27
+ const name = key.replace(/^.*\//, '').replace(/\.json$/, '');
28
+ const doc = mod.default;
29
+ if (doc)
30
+ out[name] = doc;
31
+ }
32
+ return out;
33
+ }
34
+ /**
35
+ * The section list a template renders — header group, body, footer group —
36
+ * through the ONE resolver the editor and the AI tools also use.
37
+ */
38
+ export function resolvePageSections(doc, groups) {
39
+ if (!doc)
40
+ return [];
41
+ return resolvePage(doc, groups).sections;
42
+ }
43
+ /**
44
+ * Boot a theme. The theme's entry passes its globbed sections/templates/layouts
45
+ * (so Vite resolves them relative to the theme) plus a data source. Everything
46
+ * else — registry, tree rendering, providers — is the framework.
47
+ */
48
+ export function mount(opts) {
49
+ registerSections(defaultsOf(opts.sections));
50
+ const shells = opts.shell ? defaultsOf(opts.shell) : [];
51
+ const Shell = shells[0] ?? (({ children }) => _jsx(_Fragment, { children: children }));
52
+ const groups = groupsFromGlob(opts.groups);
53
+ const pageDoc = pickByName(opts.pages, opts.page ?? 'index') ?? { sections: [] };
54
+ const pageSections = resolvePageSections(pageDoc, groups);
55
+ const rootEl = document.getElementById(opts.rootId ?? 'root');
56
+ if (!rootEl)
57
+ throw new Error('[tanqory] mount target not found');
58
+ // `?edit=true` → visual editor (EDIT plane); otherwise the storefront (SERVE).
59
+ // Bare `?edit` counts as on; an explicit falsey value (`?edit=false` / `?edit=0`)
60
+ // stays on the storefront, so the flag can be toggled off from the URL without
61
+ // dropping the param. Editing only persists on the EDIT-plane sandbox (vite dev,
62
+ // `preview-<slug>`); the published `<slug>` is static and has no save endpoint.
63
+ const loc = typeof location !== 'undefined' ? location : { hostname: '', search: '' };
64
+ const on = (k) => flagOn(loc.search, k);
65
+ // PREVIEW plane = the dedicated `preview-<themeId>.<domain>` host (the editor
66
+ // canvas), or a loopback host with `?preview` (the laptop loop) — render the
67
+ // postMessage bridge. A published `<slug>` host stays on the SERVE plane no
68
+ // matter what its query string says: the bridge takes content from
69
+ // postMessage, so it must never mount on a page shoppers can be sent to.
70
+ const editor = getEditorRuntime();
71
+ const previewMode = Boolean(editor?.isPreviewPlane(loc));
72
+ const editMode = Boolean(editor?.Editor) && on('edit');
73
+ // All pages (name → sections) so the editor can switch between templates.
74
+ const pagesByName = {};
75
+ for (const [key, mod] of Object.entries(opts.pages)) {
76
+ const name = key.replace(/^.*\//, '').replace(/\.json$/, '');
77
+ pagesByName[name] = resolvePageSections(mod.default, groups);
78
+ }
79
+ const PreviewBridge = editor?.PreviewBridge;
80
+ const Editor = editor?.Editor;
81
+ const content = previewMode && PreviewBridge ? (_jsx(PreviewBridge, { pages: pagesByName, initialPage: opts.page ?? 'index', Shell: Shell, allowedOrigins: opts.previewOrigins })) : editMode && Editor ? (_jsx(Editor, { pages: pagesByName, initialPage: opts.page ?? 'index' })) : (_jsx(Shell, { children: _jsx(SectionTree, { tree: pageSections }) }));
82
+ // Holds the DataApi in state so `revalidate` can swap fresh data in AFTER
83
+ // hydration: first render = the SSG snapshot (markup matches the server
84
+ // byte-for-byte), then the fresh fetch reconciles in place (SWR).
85
+ const Root = () => {
86
+ const [data, setData] = React.useState(opts.data);
87
+ React.useEffect(() => {
88
+ if (!opts.revalidate)
89
+ return;
90
+ let live = true;
91
+ opts
92
+ .revalidate()
93
+ .then((fresh) => {
94
+ if (live && fresh)
95
+ setData(fresh);
96
+ })
97
+ .catch(() => {
98
+ /* keep the snapshot data — a failed refresh must not blank the page */
99
+ });
100
+ return () => {
101
+ live = false;
102
+ };
103
+ // mount() runs once per page load; opts never changes afterwards.
104
+ // eslint-disable-next-line react-hooks/exhaustive-deps
105
+ }, []);
106
+ return (_jsx(DataProvider, { value: data, children: _jsx(ThemeProvider, { settings: opts.settings, locale: opts.locale, children: _jsx(CartProvider, { children: content }) }) }));
107
+ };
108
+ const app = (_jsx(React.StrictMode, { children: _jsx(Root, {}) }));
109
+ // Storefront (SERVE plane) is prerendered to static HTML at build time (SSG,
110
+ // see ssg.tsx) — hydrate it so the markup is reused (no flash, SEO-ready).
111
+ // Preview/edit planes are always client-rendered (not prerendered).
112
+ // forceClientRender = the SSG markup is known not to match (different page /
113
+ // no snapshot): wipe it and client-render — hydrating would mismatch (#418).
114
+ const isStorefront = !previewMode && !editMode;
115
+ const hasSSG = rootEl.firstChild != null;
116
+ if (isStorefront && hasSSG && !opts.forceClientRender) {
117
+ hydrateRoot(rootEl, app);
118
+ }
119
+ else {
120
+ if (hasSSG)
121
+ rootEl.replaceChildren();
122
+ createRoot(rootEl).render(app);
123
+ }
124
+ }
@@ -1,4 +1,4 @@
1
- import type { SectionDef } from './types';
1
+ import type { SectionDef } from './types.js';
2
2
  export declare function registerSections(defs: SectionDef[]): void;
3
3
  export declare function getSection(name: string): SectionDef | undefined;
4
4
  /** All registered sections — the editor uses this to build its inserter. */
@@ -0,0 +1,12 @@
1
+ const registry = new Map();
2
+ export function registerSections(defs) {
3
+ for (const def of defs)
4
+ registry.set(def.name, def);
5
+ }
6
+ export function getSection(name) {
7
+ return registry.get(name);
8
+ }
9
+ /** All registered sections — the editor uses this to build its inserter. */
10
+ export function allSections() {
11
+ return [...registry.values()];
12
+ }
@@ -1,11 +1,17 @@
1
- import type { MountOptions } from './mount';
1
+ import { type FC, type ReactNode } from 'react';
2
+ import type { MountOptions } from './mount.js';
2
3
  /** Render a theme page to an HTML string (same tree mount() renders client-side). */
3
4
  export declare function renderStorefrontHTML(opts: MountOptions): string;
4
5
  /**
5
6
  * Render ONE section to an HTML string for the editor's "Add section" preview —
6
7
  * no Shell/layout, no page routing, no client SPA boot. This is the fast path
7
- * (Shopify-style): the runtime server-renders just the requested section with
8
+ * (commerce-standard): the runtime server-renders just the requested section with
8
9
  * the theme's providers + data and returns instant HTML. Block-composed sections
9
10
  * are seeded with their preset blocks so they aren't empty.
10
11
  */
11
- export declare function renderSectionPreviewHTML(opts: Pick<MountOptions, 'sections' | 'data' | 'settings' | 'locale'>, type: string, settingsOverride?: Record<string, unknown>): string;
12
+ export declare function renderSectionPreviewHTML(opts: Pick<MountOptions, 'sections' | 'data' | 'settings' | 'locale'> & {
13
+ /** What the section renders inside when there is no page shell (the theme's providers). */
14
+ wrap?: FC<{
15
+ children: ReactNode;
16
+ }>;
17
+ }, type: string, settingsOverride?: Record<string, unknown>): string;
@@ -0,0 +1,56 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { ShowStarterContext } from '../render/starter.js';
3
+ import { renderToString } from 'react-dom/server';
4
+ import { registerSections } from './registry.js';
5
+ import { SectionTree } from './SectionTree.js';
6
+ import { DataProvider } from './data.js';
7
+ import { CartProvider } from './cart.js';
8
+ import { ThemeProvider } from './theme-context.js';
9
+ import { groupsFromGlob, resolvePageSections } from './mount.js';
10
+ // Server-side render entry (SSG). Produces the storefront HTML string at BUILD
11
+ // time so the published page ships real content in <div id="root">…</div>
12
+ // (SEO + fast first paint) instead of an empty CSR shell. The client then
13
+ // hydrates the same tree (see mount.tsx). Storefront only — preview/edit planes
14
+ // stay client-only.
15
+ function defaultsOf(map) {
16
+ return Object.values(map).map((m) => m.default);
17
+ }
18
+ function pickByName(map, name) {
19
+ const hit = Object.entries(map).find(([key]) => key.endsWith(`/${name}.json`) || key.endsWith(`/${name}.tsx`));
20
+ return hit ? hit[1].default : undefined;
21
+ }
22
+ /** Render a theme page to an HTML string (same tree mount() renders client-side). */
23
+ export function renderStorefrontHTML(opts) {
24
+ registerSections(defaultsOf(opts.sections));
25
+ const shells = opts.shell ? defaultsOf(opts.shell) : [];
26
+ const Shell = shells[0] ?? (({ children }) => _jsx(_Fragment, { children: children }));
27
+ const pageDoc = pickByName(opts.pages, opts.page ?? 'index') ?? { sections: [] };
28
+ // Same resolver as mount(): the prerendered markup and the hydrated tree
29
+ // come from one function, so SSG and client cannot disagree about a group.
30
+ const sections = resolvePageSections(pageDoc, groupsFromGlob(opts.groups));
31
+ return renderToString(_jsx(DataProvider, { value: opts.data, children: _jsx(ThemeProvider, { settings: opts.settings, locale: opts.locale, children: _jsx(CartProvider, { children: _jsx(Shell, { children: _jsx(SectionTree, { tree: sections }) }) }) }) }));
32
+ }
33
+ /**
34
+ * Render ONE section to an HTML string for the editor's "Add section" preview —
35
+ * no Shell/layout, no page routing, no client SPA boot. This is the fast path
36
+ * (commerce-standard): the runtime server-renders just the requested section with
37
+ * the theme's providers + data and returns instant HTML. Block-composed sections
38
+ * are seeded with their preset blocks so they aren't empty.
39
+ */
40
+ export function renderSectionPreviewHTML(opts, type, settingsOverride) {
41
+ const defs = defaultsOf(opts.sections);
42
+ registerSections(defs);
43
+ const def = defs.find((d) => d.name === type);
44
+ const presetBlocks = def?.presets?.[0]?.blocks ?? [];
45
+ const node = {
46
+ type,
47
+ id: 'preview',
48
+ settings: settingsOverride ?? {},
49
+ blocks: presetBlocks.map((b, i) => ({
50
+ type: b.type,
51
+ id: `preview-${i}`,
52
+ settings: b.settings ?? {},
53
+ })),
54
+ };
55
+ return renderToString(_jsx(DataProvider, { value: opts.data, children: _jsx(ThemeProvider, { settings: opts.settings, locale: opts.locale, children: _jsx(CartProvider, { children: _jsx(ShowStarterContext.Provider, { value: true, children: opts.wrap ? (_jsx(opts.wrap, { children: _jsx(SectionTree, { tree: [node] }) })) : (_jsx(SectionTree, { tree: [node] })) }) }) }) }));
56
+ }