@thorprovider/storefront 0.7.0 → 0.10.0

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 (164) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +677 -80
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +477 -38
  11. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/fulfillment-evidence-port.ts +31 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +21 -4
  15. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +6 -2
  16. package/assets/templates/app/lib/__STOREFRONT__/order-detail-mapper.ts +642 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +25 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +28 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  21. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  22. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +21 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +4 -1
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  37. package/assets/templates/features/checkout/handlers.ts +24 -4
  38. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  39. package/assets/templates/features/customer-addresses/state.ts +33 -0
  40. package/assets/templates/features/customer-auth/state.ts +10 -0
  41. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  42. package/assets/templates/features/customer-profile/state.ts +18 -0
  43. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  44. package/assets/templates/views/account/assembly/assembly.json +36 -0
  45. package/assets/templates/views/account/assembly/index.skeleton.tsx +277 -0
  46. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1057 -0
  47. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  50. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  51. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  52. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  53. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  54. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  55. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  56. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  57. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  58. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  59. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  60. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  63. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  64. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  65. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  66. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  67. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  68. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  69. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  70. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  71. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  72. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  73. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  74. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  75. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  76. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  77. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  78. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  79. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  80. package/assets/templates/views/account/content.ts +326 -0
  81. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  82. package/assets/templates/views/account/fulfillment-evidence.client.tsx +34 -0
  83. package/assets/templates/views/account/fulfillment-evidence.defaults.ts +145 -0
  84. package/assets/templates/views/account/fulfillment-evidence.schema.ts +15 -0
  85. package/assets/templates/views/account/index.tsx +259 -38
  86. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  87. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  88. package/assets/templates/views/account/orders-advanced.client.tsx +77 -0
  89. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  90. package/assets/templates/views/account/registry.tsx +935 -420
  91. package/assets/templates/views/account/schema.ts +50 -0
  92. package/assets/templates/views/account/sections-data.ts +2 -0
  93. package/assets/templates/views/cart/content.ts +1 -0
  94. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  95. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  96. package/assets/templates/views/category/content.ts +2 -0
  97. package/assets/templates/views/category/index.tsx +2 -0
  98. package/assets/templates/views/category/sections-data.ts +2 -0
  99. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  100. package/assets/templates/views/checkout/content.ts +51 -0
  101. package/assets/templates/views/checkout/index.tsx +1 -1
  102. package/assets/templates/views/checkout/props.ts +10 -2
  103. package/assets/templates/views/checkout/registry.tsx +104 -42
  104. package/assets/templates/views/checkout/schema.ts +76 -1
  105. package/assets/templates/views/home/assembly/assembly.json +23 -2
  106. package/assets/templates/views/home/assembly/index.skeleton.tsx +4 -1
  107. package/assets/templates/views/home/assembly/registry.skeleton.tsx +1 -0
  108. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/binding.json +5 -0
  109. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/catalog.part +4 -0
  110. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/element.part +4 -0
  111. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +10 -0
  112. package/assets/templates/views/home/content.ts +247 -1
  113. package/assets/templates/views/home/data.ts +10 -1
  114. package/assets/templates/views/home/index.tsx +8 -6
  115. package/assets/templates/views/home/props.ts +7 -1
  116. package/assets/templates/views/home/registry.tsx +11 -28
  117. package/assets/templates/views/home/schema.ts +163 -0
  118. package/assets/templates/views/home/sections-data.ts +2 -0
  119. package/assets/templates/views/product/content.ts +1 -0
  120. package/assets/templates/views/static/content.ts +1 -0
  121. package/bin/storefront.js +356 -27
  122. package/package.json +2 -1
  123. package/recipes/adapter-surface.json +159 -0
  124. package/recipes/archetypes.json +43 -4
  125. package/recipes/catalog.json +147 -2
  126. package/recipes/feature.schema.json +9 -0
  127. package/recipes/features.json +72 -1
  128. package/recipes/manifest.schema.json +5 -0
  129. package/recipes/recipe.schema.json +13 -1
  130. package/recipes/recipes.json +37 -7
  131. package/recipes/section.schema.json +112 -0
  132. package/recipes/sections.json +281 -4
  133. package/recipes/validate.mjs +83 -1
  134. package/scripts/adapter-surface.mjs +41 -0
  135. package/scripts/agent-blocks.mjs +700 -0
  136. package/scripts/block-validator.mjs +45 -0
  137. package/scripts/candidate.mjs +56 -14
  138. package/scripts/composers.mjs +7 -2
  139. package/scripts/default-sections.mjs +78 -0
  140. package/scripts/file-classes.mjs +18 -0
  141. package/scripts/generate-adapter-surface.mjs +148 -0
  142. package/scripts/operations.mjs +100 -0
  143. package/scripts/reconcile.mjs +67 -39
  144. package/scripts/section-configure.mjs +316 -0
  145. package/scripts/sync-assets.mjs +1 -0
  146. package/scripts/view-assembly.mjs +101 -14
  147. package/skills/sf-feature/SKILL.md +19 -0
  148. package/skills/sf-view-gen/SKILL.md +73 -7
  149. package/skills/sf-view-gen/assets/recipes/archetypes.json +43 -4
  150. package/skills/sf-view-gen/assets/recipes/catalog.json +147 -2
  151. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  152. package/skills/sf-view-gen/assets/recipes/recipes.json +37 -7
  153. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  154. package/skills/sf-view-gen/assets/recipes/sections.json +281 -4
  155. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  156. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  157. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  158. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  159. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  160. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  161. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  162. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  163. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  164. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
@@ -0,0 +1,45 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { join } from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+
6
+ const UNAVAILABLE_CODE = 'E_BLOCK_VALIDATOR_UNAVAILABLE'
7
+
8
+ function unavailable(reason, message) {
9
+ return { ok: false, error: { code: UNAVAILABLE_CODE, reason, message } }
10
+ }
11
+
12
+ export async function resolveBlockValidator(projectDir, exportName) {
13
+ const name = typeof exportName === 'string' && exportName.length > 0 ? exportName : String(exportName)
14
+ let projectRequire
15
+ let resolvedPath
16
+
17
+ try {
18
+ projectRequire = createRequire(join(projectDir, 'package.json'))
19
+ resolvedPath = projectRequire.resolve('@thorprovider/blocks/contracts')
20
+ } catch (error) {
21
+ const packageInstalled = projectRequire?.resolve.paths('@thorprovider/blocks')
22
+ ?.some((nodeModulesPath) => existsSync(join(nodeModulesPath, '@thorprovider', 'blocks')))
23
+ const reason = error?.code === 'ERR_PACKAGE_PATH_NOT_EXPORTED' || packageInstalled
24
+ ? 'subpath-missing'
25
+ : 'package-missing'
26
+ return unavailable(reason, `Could not resolve @thorprovider/blocks/contracts for validator export "${name}": the installed package or contracts subpath is missing.`)
27
+ }
28
+
29
+ let contracts
30
+ try {
31
+ contracts = await import(pathToFileURL(resolvedPath).href)
32
+ } catch {
33
+ return unavailable('import-failed', `Could not load @thorprovider/blocks/contracts for validator export "${name}".`)
34
+ }
35
+
36
+ if (!Object.prototype.hasOwnProperty.call(contracts, name)) {
37
+ return unavailable('export-missing', `The installed @thorprovider/blocks/contracts module is missing validator export "${name}".`)
38
+ }
39
+
40
+ if (typeof contracts[name] !== 'function') {
41
+ return unavailable('export-not-function', `The installed validator export "${name}" is not a function.`)
42
+ }
43
+
44
+ return { ok: true, validate: contracts[name] }
45
+ }
@@ -43,10 +43,10 @@ export const CANDIDATE_TOOLSET = Object.freeze({
43
43
  '@json-render/next': '0.21.0',
44
44
  }),
45
45
  local: Object.freeze({
46
- '@thorprovider/blocks': '3.0.2',
47
- '@thorprovider/adapters': '5.2.2',
48
- '@thorprovider/runtime': '0.4.2',
49
- '@thorprovider/types': '7.1.0',
46
+ '@thorprovider/blocks': '4.3.1',
47
+ '@thorprovider/adapters': '5.5.0',
48
+ '@thorprovider/runtime': '0.7.0',
49
+ '@thorprovider/types': '7.6.0',
50
50
  }),
51
51
  })
52
52
 
@@ -64,14 +64,15 @@ export function packSlug(name) {
64
64
  }
65
65
 
66
66
  /**
67
- * Find the local tarball for a package in a packs directory. Accepts the
68
- * documented `yarn pack --filename <slug>-<version>.tgz` name, a plain
69
- * `<slug>.tgz`, or any `.tgz` containing the slug.
67
+ * Find the local tarball for a package in a packs directory. Prefers the
68
+ * deterministic plain `<slug>.tgz` name (what `consumer:create --pack-path`
69
+ * writes), then falls back to the documented `yarn pack --filename
70
+ * <slug>-<version>.tgz` name, or any `.tgz` containing the slug.
70
71
  */
71
72
  export function findPack(packsDir, name, version) {
72
73
  if (!existsSync(packsDir)) return null
73
74
  const slug = packSlug(name)
74
- const named = [`${slug}-${version}.tgz`, `${slug}.tgz`]
75
+ const named = version ? [`${slug}.tgz`, `${slug}-${version}.tgz`] : [`${slug}.tgz`]
75
76
  for (const file of named) {
76
77
  const abs = join(packsDir, file)
77
78
  if (existsSync(abs)) return abs
@@ -89,6 +90,13 @@ export function findPack(packsDir, name, version) {
89
90
  * - `resolutions`: when `packsDir` is given, name -> `file:<abs>` mapping each
90
91
  * local `@thorprovider/*` package (and the CLI) to its packed tarball.
91
92
  * - `missingPacks`: local packages requested but absent from the packs dir.
93
+ * - `invalidPacks`: local packages whose tarball was found but rejected —
94
+ * unreadable, wrong manifest name, no version, or (for the CLI pack) a
95
+ * version other than the running CLI.
96
+ *
97
+ * Without a packs dir, versions are the pinned registry candidates. With one,
98
+ * each dependency version is adopted from the verified tarball manifest, so a
99
+ * local pack may carry unreleased versions that differ from the pins.
92
100
  */
93
101
  export function buildInstallPlan({ cliVersion, packsDir, toolset = CANDIDATE_TOOLSET } = {}) {
94
102
  const dependencies = {
@@ -98,15 +106,46 @@ export function buildInstallPlan({ cliVersion, packsDir, toolset = CANDIDATE_TOO
98
106
  }
99
107
  const resolutions = {}
100
108
  const missingPacks = []
109
+ const invalidPacks = []
101
110
  if (packsDir) {
102
111
  const local = { ...toolset.local, '@thorprovider/storefront': cliVersion }
103
- for (const [name, version] of Object.entries(local)) {
104
- const pack = findPack(packsDir, name, version)
105
- if (!pack) missingPacks.push(name)
106
- else resolutions[name] = `file:${pack}`
112
+ for (const [name, pinnedVersion] of Object.entries(local)) {
113
+ const pack = findPack(packsDir, name, pinnedVersion)
114
+ if (!pack) {
115
+ missingPacks.push(name)
116
+ continue
117
+ }
118
+ const manifest = readPackManifest(pack)
119
+ if (!manifest) {
120
+ invalidPacks.push({ name, code: 'E_PACK_UNREADABLE', message: `${pack}: cannot read as a package tarball` })
121
+ continue
122
+ }
123
+ if (manifest.name !== name) {
124
+ invalidPacks.push({
125
+ name,
126
+ code: 'E_PACK_NAME_MISMATCH',
127
+ message: `${pack} declares ${manifest.name}, expected ${name}`,
128
+ })
129
+ continue
130
+ }
131
+ const version = typeof manifest.version === 'string' && manifest.version ? manifest.version : null
132
+ if (!version) {
133
+ invalidPacks.push({ name, code: 'E_PACK_VERSION_MISSING', message: `${pack} declares no version` })
134
+ continue
135
+ }
136
+ if (name === '@thorprovider/storefront' && version !== cliVersion) {
137
+ invalidPacks.push({
138
+ name,
139
+ code: 'E_PACK_CLI_MISMATCH',
140
+ message: `${pack} declares ${manifest.name}@${version}, expected the running CLI ${cliVersion} — repack the candidate`,
141
+ })
142
+ continue
143
+ }
144
+ dependencies[name] = version
145
+ resolutions[name] = `file:${pack}`
107
146
  }
108
147
  }
109
- return { dependencies, resolutions, missingPacks, scaffolder: toolset.scaffolder, packageManager: toolset.packageManager }
148
+ return { dependencies, resolutions, missingPacks, invalidPacks, scaffolder: toolset.scaffolder, packageManager: toolset.packageManager }
110
149
  }
111
150
 
112
151
  /** Read the actual version of a sibling monorepo package (drift guard). */
@@ -280,7 +319,11 @@ export function declaredExportTargets(exportsMap) {
280
319
  export function blockSpecifierPath(specifier) {
281
320
  if (specifier === '@thorprovider/blocks') return 'package/dist/index.mjs'
282
321
  if (specifier === '@thorprovider/blocks/contracts') return 'package/dist/lib/contracts.mjs'
322
+ if (specifier === '@thorprovider/blocks/ports') return 'package/dist/ports/index.mjs'
283
323
  if (specifier === '@thorprovider/blocks/styles.css') return 'package/styles.css'
324
+ if (specifier === '@thorprovider/blocks/order-history-engine') {
325
+ return 'package/dist/blocks/designs/order-history/engine.mjs'
326
+ }
284
327
  if (!specifier.startsWith('@thorprovider/blocks/')) return null
285
328
  return `package/dist/${specifier.slice('@thorprovider/blocks/'.length)}.mjs`
286
329
  }
@@ -521,4 +564,3 @@ export async function verifyRegistryToolset({
521
564
  for (const result of Object.values(resolved)) result.cleanup?.()
522
565
  return { ok: errors.length === 0, errors }
523
566
  }
524
-
@@ -88,7 +88,7 @@ function isPlainObject(value) {
88
88
  * availability flags below so the generated host can suppress links to routes
89
89
  * that are not installed (e.g. the cart review page or checkout).
90
90
  */
91
- export function buildCompositionComposer(features, views = []) {
91
+ export function buildCompositionComposer(features, views = [], capabilities = []) {
92
92
  const entries = (Array.isArray(features) ? features : []).map((feature) =>
93
93
  typeof feature === 'string' ? { name: feature, config: {} } : feature,
94
94
  )
@@ -131,7 +131,12 @@ export function buildCompositionComposer(features, views = []) {
131
131
  `// generated host uses these to hide links to routes that are not installed,\n` +
132
132
  `// so a removed view never leaves an active dead-end navigation target.\n` +
133
133
  `export const cartViewAvailable = ${cartViewAvailable}\n\n` +
134
- `export const checkoutAvailable = ${checkoutAvailable}\n`
134
+ `export const checkoutAvailable = ${checkoutAvailable}\n\n` +
135
+ `// Backend capability flags recorded by \`storefront setup\` (empty when the\n` +
136
+ `// backend advertises none). A control whose capability is absent is omitted\n` +
137
+ `// at render time, never rendered disabled or inert.\n` +
138
+ `export const backendCapabilities: readonly string[] = ${JSON.stringify([...capabilities])}\n\n` +
139
+ `export const accountEmailEditable = backendCapabilities.includes('updateEmail')\n`
135
140
  )
136
141
  }
137
142
 
@@ -0,0 +1,78 @@
1
+ import { loadRecipes } from '../recipes/validate.mjs'
2
+ import { normalizeViewSections } from './section-compat.mjs'
3
+ import { reduceSectionAdd, SECTION_DIAGNOSTIC_CODES } from './section-operations.mjs'
4
+
5
+ export class DefaultSectionSeedError extends Error {
6
+ constructor(code, message) {
7
+ super(message)
8
+ this.name = 'DefaultSectionSeedError'
9
+ this.code = code
10
+ }
11
+ }
12
+
13
+ function errorCodeForDiagnostics(diagnostics) {
14
+ if (diagnostics.some((entry) => entry.code === SECTION_DIAGNOSTIC_CODES.E_SECTION_LIMIT)) {
15
+ return 'E_DEFAULT_LIMIT'
16
+ }
17
+ return 'E_DEFAULT_DISALLOWED'
18
+ }
19
+
20
+ export function seedDefaultSections(manifest, { recipes = loadRecipes() } = {}) {
21
+ let next = manifest
22
+
23
+ for (const recipe of recipes.views ?? []) {
24
+ const insertionsAfterSlot = new Map()
25
+ for (const seed of recipe.defaultSections ?? []) {
26
+ const view = next.views.find((entry) => entry.name === recipe.name)
27
+ if (!view) continue
28
+
29
+ const normalized = normalizeViewSections(
30
+ recipe.name,
31
+ view.sections ?? [],
32
+ recipe.registeredSlots ?? [],
33
+ {
34
+ allowedSections: recipe.allowedSections ?? [],
35
+ maxSections: recipe.maxSections,
36
+ },
37
+ )
38
+ if (!normalized.ok) {
39
+ throw new DefaultSectionSeedError(
40
+ errorCodeForDiagnostics(normalized.diagnostics),
41
+ `Cannot seed "${seed.type}" into "${recipe.name}": ${normalized.diagnostics.map((entry) => entry.message).join(' ')}`,
42
+ )
43
+ }
44
+
45
+ let at
46
+ let afterSlot
47
+ if (seed.after !== undefined) {
48
+ afterSlot = `slot:${seed.after}`
49
+ const anchorIndex = normalized.sections.findIndex((entry) => entry.id === afterSlot)
50
+ if (anchorIndex < 0) {
51
+ throw new DefaultSectionSeedError(
52
+ 'E_DEFAULT_AFTER_MISSING',
53
+ `Default section "${seed.type}" for "${recipe.name}" names missing slot "${seed.after}".`,
54
+ )
55
+ }
56
+ at = anchorIndex + 1 + (insertionsAfterSlot.get(afterSlot) ?? 0)
57
+ }
58
+
59
+ const result = reduceSectionAdd(next, {
60
+ view: recipe.name,
61
+ type: seed.type,
62
+ ...(at === undefined ? {} : { at }),
63
+ })
64
+ if (!result.ok) {
65
+ throw new DefaultSectionSeedError(
66
+ errorCodeForDiagnostics(result.diagnostics),
67
+ result.diagnostics.map((entry) => entry.message).join(' '),
68
+ )
69
+ }
70
+ next = result.manifest
71
+ if (afterSlot !== undefined) {
72
+ insertionsAfterSlot.set(afterSlot, (insertionsAfterSlot.get(afterSlot) ?? 0) + 1)
73
+ }
74
+ }
75
+ }
76
+
77
+ return next
78
+ }
@@ -33,6 +33,7 @@ const RULES = [
33
33
  'views/*/content.ts',
34
34
  'views/*/props.ts',
35
35
  'views/*/data.ts',
36
+ 'views/*/sections/**',
36
37
  'app/lib/*/mappers.ts',
37
38
  'app/lib/*/icon-map.ts',
38
39
  // The shell brand/newsletter seam is user-owned so its edits survive sync.
@@ -65,8 +66,18 @@ const RULES = [
65
66
  'app/lib/*/projection-ownership.client.tsx',
66
67
  'app/lib/*/store-context.ts',
67
68
  'app/lib/*/commerce.ts',
69
+ 'app/lib/*/ports.ts',
70
+ 'app/lib/*/orders-port.ts',
71
+ 'app/lib/*/order-detail-port.ts',
72
+ 'app/lib/*/order-detail-mapper.ts',
73
+ 'app/lib/*/fulfillment-evidence-port.ts',
74
+ 'app/lib/*/addresses-port.ts',
75
+ 'app/lib/*/customer-profile-port.ts',
76
+ 'app/lib/*/account-address.ts',
77
+ 'app/lib/*/account-profile.ts',
68
78
  'app/lib/*/cart-state.ts',
69
79
  'app/lib/*/checkout-shipping.core.ts',
80
+ 'app/lib/*/confirmation.core.ts',
70
81
  'app/lib/*/actions.ts',
71
82
  'app/lib/*/catalog.ts',
72
83
  'app/lib/*/section-sources.ts',
@@ -79,6 +90,12 @@ const RULES = [
79
90
  'features/**',
80
91
  'views/*/index.tsx',
81
92
  'views/*/registry.tsx',
93
+ 'views/*/orders-advanced.client.tsx',
94
+ 'views/*/order-detail.client.tsx',
95
+ 'views/*/fulfillment-evidence.client.tsx',
96
+ 'views/*/fulfillment-evidence.schema.ts',
97
+ 'views/*/*.defaults.ts',
98
+ 'views/checkout/checkout-commerce-hosted.tsx',
82
99
  // The views-root barrels are generated by reconcile (buildBarrel /
83
100
  // buildClientRegistryBarrel), not copied from a view template. Their
84
101
  // canonical template paths are app/lib/*/views/{index,registry}.ts, but
@@ -90,6 +107,7 @@ const RULES = [
90
107
  // Per-slot/per-variant assembly sources compose the derived index/registry;
91
108
  // they are authoring input and are never copied into a project.
92
109
  'views/*/assembly/**',
110
+ 'views/*/sections-data.ts',
93
111
  ],
94
112
  },
95
113
  ].map((rule) => ({ class: rule.class, regexes: rule.patterns.map(globToRegExp) }))
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // Generate `recipes/adapter-surface.json`: the callables a generated storefront
3
+ // may import from the adapter/commerce contract, derived from the real sources
4
+ // in this monorepo. Used by `feature add` to refuse a declared need that does
5
+ // not exist (the `getRelatedProducts` class of drift).
6
+ //
7
+ // The published package ships the JSON, not this script: a consumer install has
8
+ // no `packages/types` or `packages/runtime` beside it. A test regenerates the
9
+ // manifest from source and fails on any byte difference, so the committed file
10
+ // cannot drift from the contract it documents.
11
+ //
12
+ // Usage: node scripts/generate-adapter-surface.mjs [--check]
13
+
14
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
15
+ import { dirname, join, resolve } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url))
19
+ const PKG_ROOT = resolve(here, '..')
20
+ const REPO_ROOT = resolve(PKG_ROOT, '..', '..')
21
+ const OUTPUT = join(PKG_ROOT, 'recipes', 'adapter-surface.json')
22
+
23
+ const SOURCES = {
24
+ commerce: ['packages/types/src/commerce-provider.ts', 'CommerceProvider'],
25
+ auth: ['packages/types/src/auth.ts', 'AuthProvider'],
26
+ }
27
+
28
+ /**
29
+ * Return the text between the opening brace at `openIndex` and its match,
30
+ * ignoring braces inside strings, template literals, and comments.
31
+ */
32
+ function balancedBlock(text, openIndex) {
33
+ const open = text[openIndex]
34
+ const close = open === '{' ? '}' : open === '(' ? ')' : open === '[' ? ']' : null
35
+ if (!close) throw new Error(`Unsupported block opener "${open}".`)
36
+ let depth = 0
37
+ let quote = null
38
+ for (let i = openIndex; i < text.length; i += 1) {
39
+ const ch = text[i]
40
+ const next = text[i + 1]
41
+ if (quote) {
42
+ if (ch === '\\') {
43
+ i += 1
44
+ } else if (ch === quote) {
45
+ quote = null
46
+ }
47
+ continue
48
+ }
49
+ if (ch === '/' && next === '/') {
50
+ const end = text.indexOf('\n', i)
51
+ i = end === -1 ? text.length : end
52
+ continue
53
+ }
54
+ if (ch === '/' && next === '*') {
55
+ const end = text.indexOf('*/', i + 2)
56
+ i = end === -1 ? text.length : end + 1
57
+ continue
58
+ }
59
+ if (ch === '"' || ch === "'" || ch === '`') {
60
+ quote = ch
61
+ continue
62
+ }
63
+ if (ch === open) depth += 1
64
+ else if (ch === close) {
65
+ depth -= 1
66
+ if (depth === 0) return text.slice(openIndex + 1, i)
67
+ }
68
+ }
69
+ throw new Error('Unbalanced block.')
70
+ }
71
+
72
+ /** Extract two-space-indented method names from an interface body. */
73
+ function interfaceMethods(source, interfaceName) {
74
+ const marker = `export interface ${interfaceName} {`
75
+ const start = source.indexOf(marker)
76
+ if (start === -1) throw new Error(`Interface ${interfaceName} not found.`)
77
+ const body = balancedBlock(source, start + marker.length - 1)
78
+ const names = new Set()
79
+ for (const line of body.split('\n')) {
80
+ const match = /^ {2}(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\(/.exec(line)
81
+ if (match && match[1] !== 'constructor') names.add(match[1])
82
+ }
83
+ return [...names].sort()
84
+ }
85
+
86
+ /** Extract every exported function name from a directory of TS sources. */
87
+ function runtimeFunctions(dir) {
88
+ const names = new Set()
89
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
90
+ if (!entry.isFile() || !entry.name.endsWith('.ts') || entry.name.endsWith('.test.ts')) continue
91
+ const source = readFileSync(join(dir, entry.name), 'utf8')
92
+ for (const match of source.matchAll(/^export (?:async )?function ([A-Za-z_$][\w$]*)/gm)) {
93
+ names.add(match[1])
94
+ }
95
+ }
96
+ return [...names].sort()
97
+ }
98
+
99
+ export function buildSurface() {
100
+ const surface = { version: '1.0.0' }
101
+ for (const [key, [relPath, interfaceName]] of Object.entries(SOURCES)) {
102
+ const file = join(REPO_ROOT, relPath)
103
+ if (!existsSync(file)) throw new Error(`Contract source not found: ${relPath}`)
104
+ surface[key] = interfaceMethods(readFileSync(file, 'utf8'), interfaceName)
105
+ }
106
+ const runtimeDir = join(REPO_ROOT, 'packages', 'runtime', 'src', 'commerce')
107
+ if (!existsSync(runtimeDir)) throw new Error('runtime/commerce source not found.')
108
+ surface.runtime = runtimeFunctions(runtimeDir)
109
+ surface.generatedFrom = [
110
+ 'packages/types/src/commerce-provider.ts',
111
+ 'packages/types/src/auth.ts',
112
+ 'packages/runtime/src/commerce',
113
+ ]
114
+ return surface
115
+ }
116
+
117
+ export function surfaceJson(surface = buildSurface()) {
118
+ return `${JSON.stringify(surface, null, 2)}\n`
119
+ }
120
+
121
+ export function surfaceNames(surface = buildSurface()) {
122
+ return new Set([...(surface.commerce ?? []), ...(surface.auth ?? []), ...(surface.runtime ?? [])])
123
+ }
124
+
125
+ function main() {
126
+ const check = process.argv.includes('--check')
127
+ const next = surfaceJson()
128
+ const prev = existsSync(OUTPUT) ? readFileSync(OUTPUT, 'utf8') : null
129
+ if (check) {
130
+ if (prev !== next) {
131
+ console.error('recipes/adapter-surface.json is out of date. Run: node scripts/generate-adapter-surface.mjs')
132
+ process.exitCode = 1
133
+ return
134
+ }
135
+ console.log('adapter-surface.json is up to date.')
136
+ return
137
+ }
138
+ if (prev === next) {
139
+ console.log('adapter-surface.json already up to date.')
140
+ return
141
+ }
142
+ writeFileSync(OUTPUT, next, 'utf8')
143
+ console.log(`Wrote ${OUTPUT}`)
144
+ }
145
+
146
+ if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
147
+ main()
148
+ }
@@ -34,6 +34,7 @@ import {
34
34
  allowedFeatureNames,
35
35
  allowedViewNames,
36
36
  featureConfigRejectionFor,
37
+ featureStatus,
37
38
  getCatalogVariant,
38
39
  getFeature,
39
40
  isAllowedVariant,
@@ -42,6 +43,7 @@ import {
42
43
  resolveIntent,
43
44
  resolveMountClaims,
44
45
  } from '../recipes/validate.mjs'
46
+ import { unknownNeeds } from './adapter-surface.mjs'
45
47
  import { MANIFEST_FILE, normalizeFeature, normalizeView } from './manifest.mjs'
46
48
  import {
47
49
  createOperationRegistry,
@@ -123,6 +125,12 @@ export const DIAGNOSTIC_CODES = Object.freeze({
123
125
  E_UNPROVEN_CHECKOUT_OPTION: 'E_UNPROVEN_CHECKOUT_OPTION',
124
126
  E_SLOT_OWNED_BY_INSTANCE: 'E_SLOT_OWNED_BY_INSTANCE',
125
127
  E_OWNERSHIP_CONFLICT: 'E_OWNERSHIP_CONFLICT',
128
+ E_HELD_FEATURE: 'E_HELD_FEATURE',
129
+ E_UNKNOWN_ADAPTER_NEED: 'E_UNKNOWN_ADAPTER_NEED',
130
+ E_FEATURE_DEPENDENCY_MISSING: 'E_FEATURE_DEPENDENCY_MISSING',
131
+ E_FEATURE_IN_USE: 'E_FEATURE_IN_USE',
132
+ E_CAPABILITY_UNMET: 'E_CAPABILITY_UNMET',
133
+ E_CAPABILITY_UNKNOWN: 'E_CAPABILITY_UNKNOWN',
126
134
  })
127
135
 
128
136
  // The six closed operation field schemas: the required and optional fields of
@@ -564,6 +572,90 @@ function reduceViewConfigure(manifest, op, ctx) {
564
572
  return { ok: true, manifest: { ...manifest, views } }
565
573
  }
566
574
 
575
+ /**
576
+ * The install gate for one feature spec, as a pure function of the resulting
577
+ * manifest and the registry entry. Returns diagnostics in a stable order:
578
+ * held, static need, feature dependency, backend capability. Injected
579
+ * `options.unknownNeeds` and `options.status` let a test exercise the gate
580
+ * without mutating the loaded registry.
581
+ */
582
+ export function installGateDiagnostics(manifest, spec, options = {}) {
583
+ if (!spec) return []
584
+ const diagnostics = []
585
+ const status =
586
+ options.status ?? spec.status ?? (spec.mvp === true ? 'executable' : 'held')
587
+ if (status === 'held') {
588
+ diagnostics.push(
589
+ diagnostic(
590
+ DIAGNOSTIC_CODES.E_HELD_FEATURE,
591
+ `Feature "${spec.name}" is held and cannot be installed: ${spec.reason ?? 'no reason declared'} (owner: ${spec.owner ?? 'unassigned'}).`,
592
+ ),
593
+ )
594
+ return diagnostics
595
+ }
596
+ const needsUnknown = options.unknownNeeds ?? unknownNeeds
597
+ const unknown = needsUnknown(spec.adapter?.needs)
598
+ if (unknown.length > 0) {
599
+ diagnostics.push(
600
+ diagnostic(
601
+ DIAGNOSTIC_CODES.E_UNKNOWN_ADAPTER_NEED,
602
+ `Feature "${spec.name}" declares needs that do not exist on the adapter contract: ${unknown.join(', ')}.`,
603
+ ),
604
+ )
605
+ }
606
+ const missingRequires = (Array.isArray(spec.requires) ? spec.requires : []).filter(
607
+ (dependency) => !manifest.features.some((feature) => feature.name === dependency),
608
+ )
609
+ if (missingRequires.length > 0) {
610
+ diagnostics.push(
611
+ diagnostic(
612
+ DIAGNOSTIC_CODES.E_FEATURE_DEPENDENCY_MISSING,
613
+ `Feature "${spec.name}" requires ${missingRequires.join(', ')}, which ${missingRequires.length === 1 ? 'is' : 'are'} not installed.`,
614
+ ),
615
+ )
616
+ }
617
+ const declaredCapabilities = Array.isArray(spec.backendCapabilities)
618
+ ? spec.backendCapabilities
619
+ : []
620
+ if (declaredCapabilities.length > 0) {
621
+ const advertised = Array.isArray(manifest.capabilities) ? manifest.capabilities : null
622
+ if (!advertised) {
623
+ diagnostics.push(
624
+ diagnostic(
625
+ DIAGNOSTIC_CODES.E_CAPABILITY_UNKNOWN,
626
+ `Feature "${spec.name}" needs backend capabilities (${declaredCapabilities.join(', ')}) but the configured backend has no recorded capabilities. Run \`storefront setup\` to probe it.`,
627
+ ),
628
+ )
629
+ } else {
630
+ const unmet = declaredCapabilities.filter((capability) => !advertised.includes(capability))
631
+ if (unmet.length > 0) {
632
+ diagnostics.push(
633
+ diagnostic(
634
+ DIAGNOSTIC_CODES.E_CAPABILITY_UNMET,
635
+ `Feature "${spec.name}" needs backend capabilities the configured backend does not advertise: ${unmet.join(', ')}.`,
636
+ ),
637
+ )
638
+ }
639
+ }
640
+ }
641
+ return diagnostics
642
+ }
643
+
644
+ /** The removal gate: an installed feature another feature requires stays. */
645
+ export function removeGateDiagnostics(manifest, name, options = {}) {
646
+ const getSpec = options.getFeatureSpec ?? getFeature
647
+ const dependents = manifest.features
648
+ .filter((feature) => (getSpec(feature.name)?.requires ?? []).includes(name))
649
+ .map((feature) => feature.name)
650
+ if (dependents.length === 0) return []
651
+ return [
652
+ diagnostic(
653
+ DIAGNOSTIC_CODES.E_FEATURE_IN_USE,
654
+ `Feature "${name}" cannot be removed: ${dependents.join(', ')} require${dependents.length === 1 ? 's' : ''} it. Remove the dependent feature first.`,
655
+ ),
656
+ ]
657
+ }
658
+
567
659
  function reduceFeatureAdd(manifest, op, ctx) {
568
660
  const name = op.feature
569
661
  if (!requireString(op, 'feature')) {
@@ -578,6 +670,10 @@ function reduceFeatureAdd(manifest, op, ctx) {
578
670
  `Unknown feature "${name}". Allowed features: ${allowedFeatureNames().join(', ')}.`,
579
671
  )
580
672
  }
673
+ const installDiagnostics = installGateDiagnostics(manifest, getFeature(name))
674
+ if (installDiagnostics.length > 0) {
675
+ return { ok: false, diagnostics: installDiagnostics }
676
+ }
581
677
  const present = manifest.features.some((feature) => feature.name === name)
582
678
  if (present && !ctx.force) {
583
679
  return fail(
@@ -624,6 +720,10 @@ function reduceFeatureRemove(manifest, op) {
624
720
  if (!manifest.features.some((feature) => feature.name === name)) {
625
721
  return fail(DIAGNOSTIC_CODES.E_FEATURE_NOT_INSTALLED, `Feature "${name}" is not installed.`)
626
722
  }
723
+ const removalDiagnostics = removeGateDiagnostics(manifest, name)
724
+ if (removalDiagnostics.length > 0) {
725
+ return { ok: false, diagnostics: removalDiagnostics }
726
+ }
627
727
  const features = manifest.features.filter((feature) => feature.name !== name)
628
728
  const stillOwned = new Set(features.flatMap((feature) => getFeature(feature.name)?.views ?? []))
629
729
  const removedViews = (getFeature(name)?.views ?? []).filter((view) => !stillOwned.has(view))