@tokenoftrust/storefront-runner 7.3.2 → 7.5.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 (415) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +32 -8
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +16 -2
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  17. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  18. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  19. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  20. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  21. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  22. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  23. package/apps/storefront/src/lib/activity/store.ts +9 -3
  24. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  25. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  26. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  27. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  28. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  29. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  30. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  31. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  32. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  33. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  34. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  35. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  36. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  37. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  38. package/apps/storefront/src/middleware/index.ts +7 -3
  39. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  40. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  41. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  42. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  43. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  44. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  45. package/apps/storefront/tsconfig.astro.json +11 -0
  46. package/package.json +1 -1
  47. package/packages/public-runtime/src/activity/README.md +12 -0
  48. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  49. package/packages/public-runtime/src/activity/event.ts +19 -0
  50. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  51. package/packages/public-runtime/src/catalog-files.ts +3 -2
  52. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  53. package/packages/public-runtime/src/checkout.ts +70 -0
  54. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  55. package/packages/public-runtime/src/compliance/index.ts +1 -1
  56. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  57. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  58. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  59. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  60. package/packages/public-runtime/src/product.ts +9 -1
  61. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  62. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  63. package/pnpm-lock.runner.yaml +0 -15
  64. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  65. package/scripts/tenant/validate.mjs +128 -0
  66. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  67. package/apps/storefront/drizzle.config.apps.ts +0 -13
  68. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  69. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  70. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  71. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  72. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  73. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  74. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  75. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  76. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  77. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  78. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  79. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  80. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  81. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  82. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  83. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  84. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  85. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  86. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  87. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  88. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  89. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  90. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  91. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  92. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  93. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  94. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  95. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  96. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  97. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  98. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  99. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  100. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  101. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  102. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  103. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  104. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  105. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  106. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  107. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  108. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  109. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  110. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  111. package/apps/storefront/perf/README.md +0 -64
  112. package/apps/storefront/perf/assert-budgets.ts +0 -159
  113. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  114. package/apps/storefront/playwright.config.ts +0 -23
  115. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  116. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  117. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  118. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  119. package/apps/storefront/public/js/dashboard-team.js +0 -356
  120. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  121. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  122. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  123. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  124. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  125. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  126. package/apps/storefront/src/config/storeName.ts +0 -34
  127. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  128. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  129. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  130. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  131. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  132. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  133. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  134. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  135. package/apps/storefront/src/lib/access/dashboard/agentStoreEntry.ts +0 -253
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -153
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -474
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/agentGrantAttestation.ts +0 -74
  209. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  210. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  211. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  221. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  222. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  223. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  224. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  225. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  226. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  227. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  228. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  229. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  230. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  231. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  232. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  233. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  234. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  235. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  236. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  237. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  238. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  239. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  240. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  242. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  243. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  244. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  245. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  246. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  247. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  248. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  249. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  250. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  251. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  252. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  253. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  254. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  255. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  256. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  257. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  258. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  259. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  260. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  261. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  262. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  263. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  264. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  267. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  268. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  269. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  270. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  271. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  272. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  274. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  275. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  276. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  277. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  278. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  279. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  280. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  281. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  282. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  284. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  285. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  286. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  287. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  288. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  289. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  290. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  291. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  292. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  293. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  294. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  295. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  296. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  297. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  298. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  299. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  300. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  301. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  302. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  303. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  304. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  305. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  306. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  307. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  308. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  310. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  311. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  312. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  313. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  314. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  315. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  316. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  317. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  318. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  319. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  320. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  321. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  322. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  323. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  324. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  325. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  326. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  327. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  328. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  329. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  330. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  331. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  335. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  336. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  337. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  338. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  339. package/apps/storefront/src/pages/api/contact.ts +0 -144
  340. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  341. package/apps/storefront/src/styles/admin.css +0 -1161
  342. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  343. package/apps/storefront/test/pipeline/harness.ts +0 -209
  344. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  345. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  346. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  347. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  348. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  349. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  350. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  351. package/apps/storefront/vitest.config.cts +0 -44
  352. package/apps/storefront/vitest.faults.config.cts +0 -13
  353. package/apps/storefront/vitest.workers.config.cts +0 -7
  354. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  359. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  363. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  367. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  370. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  375. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  379. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  380. package/packages/feedback/package.json +0 -35
  381. package/packages/feedback/scripts/build-player.mjs +0 -28
  382. package/packages/feedback/src/index.ts +0 -1
  383. package/packages/feedback/src/primitives/composer.ts +0 -639
  384. package/packages/feedback/src/primitives/dialog.ts +0 -263
  385. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  386. package/packages/feedback/src/primitives/index.ts +0 -10
  387. package/packages/feedback/src/primitives/launcher.ts +0 -200
  388. package/packages/feedback/src/primitives/picker.ts +0 -663
  389. package/packages/feedback/src/primitives/redaction.ts +0 -204
  390. package/packages/feedback/src/primitives/selection.ts +0 -49
  391. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  392. package/packages/feedback/src/primitives/styles.ts +0 -77
  393. package/packages/feedback/src/primitives/surface.ts +0 -124
  394. package/packages/feedback/src/primitives/target.ts +0 -293
  395. package/packages/feedback/src/tour/canonical.ts +0 -27
  396. package/packages/feedback/src/tour/index.ts +0 -3
  397. package/packages/feedback/src/tour/player/browser.ts +0 -5
  398. package/packages/feedback/src/tour/player/host.ts +0 -12
  399. package/packages/feedback/src/tour/player/index.ts +0 -205
  400. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  401. package/packages/feedback/src/tour/player/player.css +0 -130
  402. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  403. package/packages/feedback/src/tour/player/surface.ts +0 -295
  404. package/packages/feedback/src/tour/player/types.ts +0 -8
  405. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  406. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  407. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  408. package/packages/feedback/src/tour/sanitize.ts +0 -76
  409. package/packages/feedback/src/tour/schema.ts +0 -362
  410. package/packages/feedback/src/v1/guards.ts +0 -335
  411. package/packages/feedback/src/v1/index.ts +0 -3
  412. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  413. package/packages/feedback/src/v1/types.ts +0 -177
  414. package/packages/feedback/tsconfig.json +0 -9
  415. package/packages/feedback/vitest.config.cts +0 -21
@@ -1,186 +0,0 @@
1
- import type { AdminTenantEnvelope } from "../../access/admin/envelope";
2
- import { MOCK_ANCHOR_ISO, offsetIso, pick, randomBool, randomInt, seededRandom } from "../../developer-experience/admin/seed";
3
- import type {
4
- OrderDetail,
5
- OrderEvidenceEvent,
6
- OrderLineItem,
7
- OrderQueueSummary,
8
- OrderRow,
9
- OrdersViewModel,
10
- } from "../admin/viewmodels/orders";
11
- import { tenantProfile } from "../../access/fixtures/tenants";
12
- import { memoizeByEnvelope } from "../../developer-experience/admin/memoizeByEnvelope";
13
-
14
- // Must stay index-aligned with customers.ts's NAMES: an order's customerId is
15
- // derived from the picked name's position here, and customers.ts assigns each
16
- // customer the id `cust-<tenant>-<position>`. The evidence graph joins order→
17
- // customer by that shared id, so these two arrays must remain identical.
18
- const CUSTOMER_NAMES = [
19
- "Riley Harper",
20
- "Jordan Lee",
21
- "Casey Nguyen",
22
- "Morgan Blake",
23
- "Sam Ortiz",
24
- "Avery Chen",
25
- "Quinn Sullivan",
26
- "Reese Patel",
27
- ];
28
-
29
- // Must stay index-aligned with products.ts's PRODUCT_NAMES: an order's productId
30
- // is derived from the picked item's position here, and products.ts assigns each
31
- // product the id `prod-<tenant>-<position>`. The evidence graph joins order→
32
- // product by that shared id, so these pools must remain identical per vertical.
33
- const ITEM_POOLS: Record<string, string[]> = {
34
- vape: ["Vape Pen Starter Kit", "Disposable Vape 5000", "Nicotine Pouches 6mg", "Replacement Coil 3-Pack"],
35
- tobacco: ["Pipe Tobacco 1oz", "Cigar Sampler Pack", "Rolling Papers 32ct", "Loose Leaf Blend"],
36
- };
37
-
38
- function buildRow(rng: () => number, index: number, targetTenant: string, vertical: string): OrderRow {
39
- const items = ITEM_POOLS[vertical] ?? ITEM_POOLS.vape!;
40
- const total = randomInt(rng, 45, 420);
41
- const isHold = randomBool(rng, index === 0 ? 1 : 0.28);
42
- const isCompleted = !isHold && randomBool(rng, 0.35);
43
- const payment = isHold ? "authorized" : "captured";
44
- const shipState = isHold ? "hold_review_required" : isCompleted ? "completed" : "ready_to_ship";
45
- const blocker = isHold ? pick(rng, ["Payment capture", "Manual review", "Age verification hold"]) : null;
46
-
47
- const customerIndex = randomInt(rng, 0, CUSTOMER_NAMES.length - 1);
48
- const itemIndex = randomInt(rng, 0, items.length - 1);
49
-
50
- return {
51
- id: `#${2_200_000_000 + Math.floor(rng() * 90_000_000)}`,
52
- placedAt: offsetIso(MOCK_ANCHOR_ISO, -randomInt(rng, 5, 600)),
53
- customerId: `cust-${targetTenant}-${customerIndex}`,
54
- customerName: CUSTOMER_NAMES[customerIndex]!,
55
- customerNote: index === 0 ? "First-time customer" : `Returning customer, ${randomInt(rng, 2, 6)} orders`,
56
- itemsSummary: items[itemIndex]!,
57
- productId: `prod-${targetTenant}-${itemIndex}`,
58
- total,
59
- payment,
60
- shipState,
61
- blocker,
62
- nextStep: isHold ? (blocker === "Payment capture" ? "Capture payment" : "Review risk") : isCompleted ? "View record" : "Create label",
63
- riskLevel: isHold ? "high" : randomBool(rng, 0.15) ? "medium" : "low",
64
- };
65
- }
66
-
67
- function buildDetail(row: OrderRow, rng: () => number): OrderDetail {
68
- const lineItems: OrderLineItem[] = [
69
- { sku: `sku-${row.id.slice(1, 6)}`, name: row.itemsSummary, quantity: 1, unitPrice: Math.round(row.total * 0.82) },
70
- ];
71
- const shipping = 5;
72
- const estimatedTax = 0;
73
- const taxesAndFees = row.total - lineItems[0]!.unitPrice - shipping;
74
-
75
- const evidenceTimeline: OrderEvidenceEvent[] = [
76
- { title: "Order imported", detail: "Storefront order became available in the admin queue.", at: row.placedAt },
77
- { title: "Payment authorized", detail: "The customer completed checkout and payment was authorized.", at: offsetIso(row.placedAt, 0) },
78
- ];
79
- if (row.blocker) {
80
- evidenceTimeline.push({ title: "Hold added", detail: `${row.blocker} must be resolved before shipment.`, at: offsetIso(row.placedAt, 1) });
81
- }
82
-
83
- return {
84
- ...row,
85
- lineItems,
86
- shipping,
87
- estimatedTax,
88
- taxesAndFees,
89
- readinessChecks: [
90
- {
91
- key: "payment_capture",
92
- label: "Payment capture",
93
- value: row.payment === "captured" ? "Captured" : "Authorized",
94
- detail: "Capture the authorization before creating the shipping label.",
95
- tone: row.payment === "captured" ? "green" : "amber",
96
- action: "Capture payment",
97
- blocking: row.payment !== "captured",
98
- },
99
- {
100
- key: "tax_and_fees",
101
- label: "Tax and fees",
102
- value: "Collected",
103
- detail: "Required amounts are included in the order total.",
104
- tone: "blue",
105
- action: "View total",
106
- blocking: false,
107
- },
108
- {
109
- key: "identity_and_age",
110
- label: "Identity and age",
111
- value: row.blocker === "Age verification hold" ? "Needs review" : "Passed",
112
- detail: "Checkout assurance completed before order placement.",
113
- tone: row.blocker === "Age verification hold" ? "amber" : "green",
114
- action: "View evidence",
115
- blocking: row.blocker === "Age verification hold",
116
- },
117
- {
118
- key: "address",
119
- label: "Address",
120
- value: "Serviceable",
121
- detail: "Destination is deliverable after any hold is resolved.",
122
- tone: "green",
123
- action: "View address",
124
- blocking: false,
125
- },
126
- ],
127
- evidenceTimeline,
128
- };
129
- }
130
-
131
- function computeOrdersViewModel(envelope: AdminTenantEnvelope): OrdersViewModel {
132
- const { targetTenant } = envelope;
133
- const profile = tenantProfile(targetTenant);
134
- const rng = seededRandom(`orders:${targetTenant}`);
135
-
136
- const rowCount = randomInt(rng, 5, 8);
137
- const rows = Array.from({ length: rowCount }, (_, index) => buildRow(rng, index, targetTenant, profile.vertical));
138
-
139
- // Newest-first, so the "All orders — Newest first" queue copy and the
140
- // "Oldest open order first" unfulfilled copy actually hold, and so
141
- // today.oldestOpenAt below can be read off the chronological tail.
142
- rows.sort((a, b) => new Date(b.placedAt).getTime() - new Date(a.placedAt).getTime());
143
-
144
- const detailsById: Record<string, OrderDetail> = {};
145
- for (const row of rows) {
146
- detailsById[row.id] = buildDetail(row, rng);
147
- }
148
-
149
- const needsAttention = rows.filter((r) => r.shipState === "hold_review_required").length;
150
- const readyToShip = rows.filter((r) => r.shipState === "ready_to_ship").length;
151
- const completed = rows.filter((r) => r.shipState === "completed").length;
152
-
153
- const queues: OrderQueueSummary[] = [
154
- { key: "needs_attention", label: "Needs attention", count: needsAttention, detail: "Hold before shipment" },
155
- { key: "ready_to_ship", label: "Ready to ship", count: readyToShip, detail: "Labels available" },
156
- { key: "unfulfilled", label: "Unfulfilled", count: readyToShip + needsAttention, detail: "Oldest open order first" },
157
- { key: "all", label: "All orders", count: rows.length, detail: "Newest first" },
158
- { key: "completed", label: "Completed", count: completed, detail: "Delivered" },
159
- ];
160
-
161
- const paidOrders = rows.filter((r) => r.payment === "captured");
162
- const grossSales = paidOrders.reduce((sum, r) => sum + r.total, 0);
163
-
164
- const openPlacedAt = rows.filter((r) => r.shipState !== "completed").map((r) => r.placedAt);
165
- const oldestOpenAt = openPlacedAt.length
166
- ? openPlacedAt.reduce((oldest, at) => (at < oldest ? at : oldest))
167
- : null;
168
-
169
- return {
170
- targetTenant,
171
- queues,
172
- rows,
173
- detailsById,
174
- today: {
175
- grossSales,
176
- paidOrders: paidOrders.length,
177
- averageOrder: paidOrders.length ? Math.round((grossSales / paidOrders.length) * 100) / 100 : 0,
178
- refunds: 0,
179
- oldestOpenAt,
180
- day: null,
181
- timeZone: "UTC",
182
- },
183
- };
184
- }
185
-
186
- export const getOrdersViewModel = memoizeByEnvelope(computeOrdersViewModel);
@@ -1,207 +0,0 @@
1
- /**
2
- * FoxyOrderClient — the boundary to tot-foxycart's order-read surface.
3
- * `ordersStore.ts` and the read routes / event receiver never call `fetch`
4
- * directly; they go through this seam so a fake can stand in for tot-foxycart
5
- * in tests.
6
- *
7
- * The service is `tot-foxycart/routes/foxyOrderApi.js` +
8
- * `modules/integrations/foxyOrderMapper.node.js`:
9
- * a `GET {baseUrl}/commerce/orders?appDomain=&limit=&offset=&since=&until=&status=`
10
- * list endpoint returning `{ orders, limit, offset, total, hasMore }` (limit/offset,
11
- * NOT page/pageSize), and a
12
- * `GET {baseUrl}/commerce/orders/{externalOrderId}?appDomain=` detail endpoint
13
- * returning `{ order }` (an envelope, not the bare order),
14
- * both Bearer-authenticated with the tenant's Foxy partner API key. `FoxyOrder`
15
- * below mirrors `buildOrderPayload()`'s actual normalized DTO — NOT the
16
- * contract's minimized `Order` shape (`contract/openapi.yaml`); mapping one to
17
- * the other is `orderMapper.ts`'s job.
18
- *
19
- * Modeled on `../../messaging/messagesClient.ts`'s interface + Http impl +
20
- * factory shape and `../../webhooks/deliveryEngine.ts`'s bounded-timeout
21
- * `fetch` (AbortController, injectable `fetchImpl`) — but adds a settable
22
- * test seam (`setFoxyOrderClientForTesting`) since this client, unlike
23
- * `messagesClient.ts`, is a shared singleton that multiple callers (read
24
- * routes, event receiver) each independently resolve.
25
- */
26
- import { readEnv } from "@/lib/publication/shared/env";
27
-
28
- /** One order line item, as tot-foxycart's `buildOrderPayload()` returns it. */
29
- export interface FoxyOrderLineItem {
30
- sku: string;
31
- name?: string;
32
- quantity: number;
33
- unitPrice?: number;
34
- totalPrice?: number;
35
- /** Collapsed `fx:item_options` ({ name: value }); `flavor` below mirrors the common one. */
36
- options?: Record<string, string>;
37
- flavor?: string;
38
- }
39
-
40
- /**
41
- * One order, as tot-foxycart's `buildOrderPayload()` actually returns it
42
- * (`foxyOrderMapper.node.js`). Deliberately does NOT model every upstream
43
- * field — `shippingAddress`/`billingAddress`/`paymentRef`/`paymentMetadata`/
44
- * `exciseTax` are compliance-floor/PII-adjacent internals the contract's
45
- * minimized `Order` never surfaces, so they're left off here rather than
46
- * risk a caller reaching for them.
47
- *
48
- * There is no raw customer id field — only `customerEmail`/`customerName`.
49
- * `orderMapper.ts` hashes `customerEmail` (never persisted or forwarded raw)
50
- * as the input to `customerHash.ts`.
51
- *
52
- * `status` is free text passed straight through from Foxy (only `"completed"`
53
- * is observed in tot-foxycart's own fixtures; its own fallback is
54
- * `"confirmed"`) — NOT the contract's closed `created|fulfilled|cancelled`
55
- * enum. `orderMapper.ts` normalizes it.
56
- */
57
- export interface FoxyOrder {
58
- /** tot-foxycart's transaction id — this becomes `orders.externalOrderId`. */
59
- externalId: string;
60
- /** Human-facing order number (Foxy's `display_id`). */
61
- externalNumber?: string;
62
- /** ISO 8601-*like* — Foxy's offset omits the colon (`-0500` not `-05:00`). */
63
- orderedAt: string;
64
- /** Optional last-modified timestamp when upstream order state changed after placement. */
65
- updatedAt?: string;
66
- currency: string;
67
- status: string;
68
- customerEmail?: string;
69
- customerName?: string;
70
- subtotal?: number;
71
- shipping?: number;
72
- tax?: number;
73
- total: number;
74
- lineItems: FoxyOrderLineItem[];
75
- }
76
-
77
- export interface FoxyOrderPage {
78
- orders: FoxyOrder[];
79
- limit: number;
80
- offset: number;
81
- total: number;
82
- hasMore: boolean;
83
- }
84
-
85
- export interface FoxyOrderListOptions {
86
- limit?: number;
87
- offset?: number;
88
- since?: string;
89
- until?: string;
90
- status?: string;
91
- }
92
-
93
- export interface FoxyOrderClient {
94
- /** List orders for one tenant (identified by its Foxy-facing `appDomain`). */
95
- listOrders(tenantAppDomain: string, options?: FoxyOrderListOptions): Promise<FoxyOrderPage>;
96
- /** Fetch one order by tot-foxycart's id, or `null` if it doesn't exist. */
97
- getOrder(tenantAppDomain: string, externalOrderId: string): Promise<FoxyOrder | null>;
98
- }
99
-
100
- export class FoxyOrderClientError extends Error {}
101
-
102
- /** Bounded per-request timeout — mirrors `deliveryEngine.ts`'s `DEFAULT_TIMEOUT_MS`. */
103
- const DEFAULT_TIMEOUT_MS = 10_000;
104
-
105
- const FOXY_ORDER_API_URL_ENV = "FOXY_ORDER_API_URL";
106
- const FOXY_ORDER_API_KEY_ENV = "FOXY_ORDER_API_KEY";
107
-
108
- export interface HttpFoxyOrderClientConfig {
109
- /** tot-foxycart base URL (e.g. `https://commerce.tokenoftrust.com`). No trailing slash required. */
110
- baseUrl: string;
111
- /** Per-store Foxy partner API key, sent as a Bearer token. */
112
- apiKey: string;
113
- /** Defaults to the global `fetch`. Override in tests with a fake. */
114
- fetchImpl?: typeof fetch;
115
- timeoutMs?: number;
116
- }
117
-
118
- export class HttpFoxyOrderClient implements FoxyOrderClient {
119
- private readonly baseUrl: string;
120
- private readonly apiKey: string;
121
- private readonly fetchImpl: typeof fetch;
122
- private readonly timeoutMs: number;
123
-
124
- constructor(config: HttpFoxyOrderClientConfig) {
125
- if (!config.baseUrl) throw new FoxyOrderClientError("foxyOrderClient: FOXY_ORDER_API_URL is not configured");
126
- if (!config.apiKey) throw new FoxyOrderClientError("foxyOrderClient: FOXY_ORDER_API_KEY is not configured");
127
- this.baseUrl = config.baseUrl.replace(/\/+$/, "");
128
- this.apiKey = config.apiKey;
129
- // Called unbound: the Workers runtime refuses fetch invoked with any `this` but the global.
130
- const doFetch = config.fetchImpl ?? fetch;
131
- this.fetchImpl = (input, init) => doFetch(input, init);
132
- this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
133
- }
134
-
135
- async listOrders(tenantAppDomain: string, options: FoxyOrderListOptions = {}): Promise<FoxyOrderPage> {
136
- const params = new URLSearchParams({ appDomain: tenantAppDomain });
137
- if (options.limit != null) params.set("limit", String(options.limit));
138
- if (options.offset != null) params.set("offset", String(options.offset));
139
- if (options.since != null) params.set("since", options.since);
140
- if (options.until != null) params.set("until", options.until);
141
- if (options.status != null) params.set("status", options.status);
142
- return this.request<FoxyOrderPage>(`/commerce/orders?${params}`);
143
- }
144
-
145
- async getOrder(tenantAppDomain: string, externalOrderId: string): Promise<FoxyOrder | null> {
146
- const params = new URLSearchParams({ appDomain: tenantAppDomain });
147
- const result = await this.request<{ order: FoxyOrder } | null>(
148
- `/commerce/orders/${encodeURIComponent(externalOrderId)}?${params}`,
149
- { allowNotFound: true },
150
- );
151
- return result ? result.order : null;
152
- }
153
-
154
- private async request<T>(path: string, opts: { allowNotFound?: boolean } = {}): Promise<T> {
155
- const controller = new AbortController();
156
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
157
- let res: Response;
158
- try {
159
- res = await this.fetchImpl(`${this.baseUrl}${path}`, {
160
- method: "GET",
161
- headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json" },
162
- signal: controller.signal,
163
- });
164
- } catch (cause) {
165
- const isTimeout = cause instanceof Error && cause.name === "AbortError";
166
- throw new FoxyOrderClientError(
167
- `foxyOrderClient: request to ${path} failed (${isTimeout ? "timeout" : "network error"})`,
168
- );
169
- } finally {
170
- clearTimeout(timer);
171
- }
172
- if (opts.allowNotFound && res.status === 404) return null as T;
173
- if (!res.ok) {
174
- throw new FoxyOrderClientError(`foxyOrderClient: ${path} returned ${res.status}`);
175
- }
176
- return (await res.json()) as T;
177
- }
178
- }
179
-
180
- // --- Test seam ---------------------------------------------------------------
181
- // Callers (read routes, event receiver) each resolve their own client
182
- // instance via `getFoxyOrderClient()`; a module-level override lets a single
183
- // `setFoxyOrderClientForTesting` call stand in for tot-foxycart across all of
184
- // them in one test, without threading a fake through every call site.
185
- let testOverride: FoxyOrderClient | null = null;
186
-
187
- export function setFoxyOrderClientForTesting(client: FoxyOrderClient): void {
188
- testOverride = client;
189
- }
190
-
191
- export function resetFoxyOrderClientForTesting(): void {
192
- testOverride = null;
193
- }
194
-
195
- /**
196
- * Resolve the active `FoxyOrderClient`: the test override if one is set,
197
- * otherwise a real `HttpFoxyOrderClient` built from env (fails closed —
198
- * throws {@link FoxyOrderClientError} — when unconfigured).
199
- */
200
- export async function getFoxyOrderClient(
201
- overrides: Partial<HttpFoxyOrderClientConfig> = {},
202
- ): Promise<FoxyOrderClient> {
203
- if (testOverride) return testOverride;
204
- const baseUrl = overrides.baseUrl ?? (await readEnv(FOXY_ORDER_API_URL_ENV)) ?? "";
205
- const apiKey = overrides.apiKey ?? (await readEnv(FOXY_ORDER_API_KEY_ENV)) ?? "";
206
- return new HttpFoxyOrderClient({ ...overrides, baseUrl, apiKey });
207
- }
@@ -1,222 +0,0 @@
1
- /**
2
- * A Private App's read of one order's ship-to recipient (`getFulfillmentRecipient`). The caller has
3
- * already verified the token and scope, refused query overrides, and resolved one stage that equals
4
- * both the routed stage and the order's stage.
5
- *
6
- * Order of work:
7
- * 1. The install must be active on the tenant (else the generic 401 `invalid_token`) and still hold
8
- * the recipient scope (else 403 `scope_denied`). Has any assignment of this order named the
9
- * install? If not, `not-assigned`, and no contact table is touched.
10
- * 2. The order's current assignment must be this install's `active` assignment and the order
11
- * releasable at its current event version, else `assignment-held` / `assignment-ended`.
12
- * 3. The app-access audit insert (`appAuditStatement`) re-checks install, scope, assignment, order
13
- * version, consent and quota in one statement and is the only write. Nothing is decrypted, and
14
- * the ship group's state is not read, unless it committed its row.
15
- * 4. Zero rows are classified from current state: install, scope, assignment, consent, then quota.
16
- *
17
- * Every failure is a code. A storage read that throws, before or after admission, answers 503
18
- * `unavailable`; the audit insert's own error 503 `audit-unavailable`; the data key 503
19
- * `vault-key-unavailable`. Responses carry codes and opaque ids only; the recipient is returned only
20
- * on success.
21
- */
22
- import type { Queryable } from "@/lib/catalog/d1/catalog.js";
23
- import type { KmsClient } from "@/lib/customers/contactVault/kms.js";
24
- import {
25
- APP_CONTACT_PURPOSE,
26
- APP_CONTACT_READS_PER_HOUR,
27
- appAuditStatement,
28
- HOUR_MS,
29
- type VaultStage,
30
- } from "@/lib/customers/contactVault/contactAudit.js";
31
- import { isOpaqueId, type FulfillmentService } from "@/lib/fulfillment/fulfillmentService";
32
- import { readOrderShipRecipient } from "./orderContactVault.js";
33
- import type { ContactAddress } from "./orderContact.js";
34
-
35
- export const RECIPIENT_SCOPE = "orders:read:recipient";
36
-
37
- export interface AppRecipient {
38
- orderId: string;
39
- name?: string;
40
- company?: string;
41
- line1: string;
42
- line2?: string;
43
- city: string;
44
- region?: string;
45
- postalCode?: string;
46
- country: string;
47
- }
48
-
49
- export type AppRecipientCode =
50
- | "invalid_token"
51
- | "scope_denied"
52
- | "not-assigned"
53
- | "assignment-held"
54
- | "assignment-ended"
55
- | "consent-missing"
56
- | "consent-revoked"
57
- | "consent-expired"
58
- | "quota"
59
- | "contact-erased"
60
- | "contact-expired"
61
- | "contact-absent"
62
- | "contact-unreadable"
63
- | "audit-unavailable"
64
- | "vault-key-unavailable"
65
- | "unavailable";
66
-
67
- export type AppRecipientOutcome =
68
- | { ok: true; recipient: AppRecipient }
69
- | { ok: false; status: number; code: AppRecipientCode; retryAfterSeconds?: number };
70
-
71
- export interface AppRecipientInput {
72
- tenantId: string;
73
- stage: VaultStage;
74
- installId: string;
75
- orderId: string;
76
- now: Date;
77
- }
78
-
79
- export interface AppRecipientDeps {
80
- /** The apps database: audit insert, vault and authority reads. */
81
- db: Queryable;
82
- /** Reads the order's fulfillment view (assignment, holds, version); never decrypts. */
83
- service: Pick<FulfillmentService, "get">;
84
- kms: KmsClient;
85
- auditId?: () => string;
86
- }
87
-
88
- type Eligibility =
89
- | { kind: "eligible"; assignmentId: string; eventVersion: number }
90
- | { kind: "refused"; status: number; code: AppRecipientCode };
91
-
92
- const refused = (status: number, code: AppRecipientCode) => ({ kind: "refused", status, code }) as const;
93
-
94
- async function installRefusal(db: Queryable, input: AppRecipientInput): Promise<Eligibility | null> {
95
- const install = await db.first<{ tenant_id: string; status: string; scopes: string }>(
96
- "SELECT tenant_id, status, scopes FROM app_installs WHERE install_id = ?",
97
- input.installId,
98
- );
99
- if (!install || install.tenant_id !== input.tenantId || install.status !== "active") return refused(401, "invalid_token");
100
- let scopes: unknown;
101
- try {
102
- scopes = JSON.parse(install.scopes);
103
- } catch {
104
- scopes = [];
105
- }
106
- if (!Array.isArray(scopes) || !scopes.includes(RECIPIENT_SCOPE)) return refused(403, "scope_denied");
107
- return null;
108
- }
109
-
110
- async function eligibility(deps: AppRecipientDeps, input: AppRecipientInput): Promise<Eligibility> {
111
- const { tenantId, stage, installId, orderId } = input;
112
- const installRefused = await installRefusal(deps.db, input);
113
- if (installRefused) return installRefused;
114
- const named = await deps.db.first(
115
- `SELECT 1 AS named FROM fulfillment_assignments
116
- WHERE tenant_id = ? AND stage = ? AND order_id = ? AND install_id = ? LIMIT 1`,
117
- tenantId, stage, orderId, installId,
118
- );
119
- if (!named) return refused(404, "not-assigned");
120
- const view = await deps.service.get({ role: "caller", actorId: installId, tenantId, stage }, orderId);
121
- const assignment = view.ok ? view.value.assignment : null;
122
- if (!view.ok || !assignment || assignment.installId !== installId) return refused(409, "assignment-ended");
123
- if (assignment.state !== "active") return refused(409, "assignment-held");
124
- const releasable = view.value.fulfillment === "ready" && view.value.holds.length === 0 && view.value.lines.length > 0;
125
- if (!releasable) return refused(409, "assignment-held");
126
- return { kind: "eligible", assignmentId: assignment.assignmentId, eventVersion: view.value.eventVersion };
127
- }
128
-
129
- /** Why the audit insert admitted nothing, read from current state; null when nothing explains it. */
130
- async function classifyRefusal(
131
- deps: AppRecipientDeps,
132
- input: AppRecipientInput,
133
- admitted: { eventVersion: number },
134
- ): Promise<{ status: number; code: AppRecipientCode; retryAfterSeconds?: number } | null> {
135
- const { db } = deps;
136
- const { tenantId, stage, installId, now } = input;
137
- const current = await eligibility(deps, input);
138
- if (current.kind === "refused") return { status: current.status, code: current.code };
139
- if (current.eventVersion !== admitted.eventVersion) return null;
140
- const at = now.toISOString();
141
- const live = await db.first(
142
- `SELECT 1 AS live FROM app_contact_consents
143
- WHERE install_id = ? AND tenant_id = ? AND stage = ? AND purpose = ? AND revoked_at IS NULL AND expires_at > ?`,
144
- installId, tenantId, stage, APP_CONTACT_PURPOSE, at,
145
- );
146
- if (!live) {
147
- const latest = await db.first<{ revoked_at: string | null }>(
148
- `SELECT revoked_at FROM app_contact_consents
149
- WHERE install_id = ? AND tenant_id = ? AND stage = ? AND purpose = ?
150
- ORDER BY granted_at DESC, rowid DESC LIMIT 1`,
151
- installId, tenantId, stage, APP_CONTACT_PURPOSE,
152
- );
153
- if (!latest) return { status: 403, code: "consent-missing" };
154
- return { status: 403, code: latest.revoked_at !== null ? "consent-revoked" : "consent-expired" };
155
- }
156
- const hourAgo = new Date(now.getTime() - HOUR_MS).toISOString();
157
- const used = await db.first<{ n: number; oldest: string | null }>(
158
- "SELECT COUNT(*) AS n, MIN(at) AS oldest FROM app_contact_access_audit WHERE install_id = ? AND tenant_id = ? AND at > ?",
159
- installId, tenantId, hourAgo,
160
- );
161
- if (Number(used?.n ?? 0) >= APP_CONTACT_READS_PER_HOUR) {
162
- // The oldest counted read leaves the window an hour after it was admitted.
163
- const oldest = used?.oldest ? Date.parse(used.oldest) : Number.NaN;
164
- const wait = Number.isFinite(oldest) ? Math.ceil((oldest + HOUR_MS - now.getTime()) / 1000) : 1;
165
- return { status: 429, code: "quota", retryAfterSeconds: Math.max(1, wait) };
166
- }
167
- return null;
168
- }
169
-
170
- function exported(orderId: string, shipTo: ContactAddress): AppRecipient {
171
- const recipient: AppRecipient = { orderId, line1: shipTo.line1, city: shipTo.city, country: shipTo.country };
172
- for (const field of ["name", "company", "line2", "region", "postalCode"] as const) {
173
- const value = shipTo[field];
174
- if (typeof value === "string" && value.length > 0) recipient[field] = value;
175
- }
176
- return recipient;
177
- }
178
-
179
- const ATTEMPTS = 2;
180
- const UNAVAILABLE = { ok: false, status: 503, code: "unavailable" } as const;
181
-
182
- export async function readAppRecipient(deps: AppRecipientDeps, input: AppRecipientInput): Promise<AppRecipientOutcome> {
183
- if (!isOpaqueId(input.orderId)) return { ok: false, status: 404, code: "not-assigned" };
184
- for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
185
- let eligible: Eligibility;
186
- try {
187
- eligible = await eligibility(deps, input);
188
- } catch {
189
- return UNAVAILABLE;
190
- }
191
- if (eligible.kind === "refused") return { ok: false, status: eligible.status, code: eligible.code };
192
- const admission = appAuditStatement({
193
- auditId: deps.auditId?.() ?? crypto.randomUUID(),
194
- installId: input.installId,
195
- tenantId: input.tenantId,
196
- stage: input.stage,
197
- orderId: input.orderId,
198
- assignmentId: eligible.assignmentId,
199
- eventVersion: eligible.eventVersion,
200
- scope: RECIPIENT_SCOPE,
201
- now: input.now,
202
- });
203
- let read: Awaited<ReturnType<typeof readOrderShipRecipient>>;
204
- try {
205
- read = await readOrderShipRecipient(deps.db, deps.kms, {
206
- tenantId: input.tenantId, stage: input.stage, orderId: input.orderId, admission, now: input.now,
207
- });
208
- } catch {
209
- return UNAVAILABLE;
210
- }
211
- if (read.ok) return { ok: true, recipient: exported(input.orderId, read.shipTo) };
212
- if (read.reason !== "not-admitted") return { ok: false, status: read.status, code: read.reason };
213
- let why: { status: number; code: AppRecipientCode; retryAfterSeconds?: number } | null;
214
- try {
215
- why = await classifyRefusal(deps, input, eligible);
216
- } catch {
217
- return UNAVAILABLE;
218
- }
219
- if (why) return { ok: false, ...why };
220
- }
221
- return { ok: false, status: 409, code: "assignment-held" };
222
- }
@@ -1,63 +0,0 @@
1
- /**
2
- * The signed order-contact command (decision gv-contact-vault-command-contract-v1b): the only
3
- * inbound path for a customer's contact. Body `{tenantId, stage, contact}` exactly; the caller token
4
- * must carry `use: "order-contact"` and a digest of the canonical body. The commerce intake refuses
5
- * these tokens and keeps refusing every private key in its own events.
6
- */
7
- import { canonicalJson, sha256Hex } from "@tot/public-runtime";
8
- import type { Queryable } from "../../catalog/d1/catalog.js";
9
- import { verifySignedCommerceToken, type CommerceCallerConfig } from "../data/orderForwardReceiver.js";
10
- import type { KmsClient } from "@/lib/customers/contactVault/kms.js";
11
- import { readOrderContactCommand } from "./orderContact.js";
12
- import { sealOrderContact, type SealOutcome } from "./orderContactVault.js";
13
- import { type VaultStage } from "@/lib/customers/contactVault/contactAudit.js";
14
-
15
- export type ContactIntakeResult =
16
- | { ok: true; duplicate: boolean; tenantId: string; stage: VaultStage }
17
- | { ok: false; status: number; reason: string };
18
-
19
- function isRecord(value: unknown): value is Record<string, unknown> {
20
- return value !== null && typeof value === "object" && !Array.isArray(value);
21
- }
22
-
23
- function isStage(value: unknown): value is VaultStage {
24
- return value === "preview" || value === "publication";
25
- }
26
-
27
- export async function receiveOrderContact(
28
- db: Queryable,
29
- kms: KmsClient,
30
- body: unknown,
31
- token: string,
32
- config: CommerceCallerConfig,
33
- tenantClass: { regulated: boolean },
34
- ): Promise<ContactIntakeResult> {
35
- if (!isStage(config.expectedStage)) return { ok: false, status: 503, reason: "vault-unavailable" };
36
- if (!isRecord(body)) return { ok: false, status: 400, reason: "malformed" };
37
- const { tenantId, stage, contact } = body;
38
- if (typeof tenantId !== "string" || tenantId.trim() === "") return { ok: false, status: 401, reason: "tenant" };
39
- if (!isStage(stage)) return { ok: false, status: 401, reason: "stage" };
40
- const verified = await verifySignedCommerceToken(token, config, { tenantId, stage, use: "order-contact" });
41
- if (!verified.ok) return { ok: false, status: 401, reason: verified.reason };
42
- const keys = Object.keys(body);
43
- if (keys.length !== 3 || !["tenantId", "stage", "contact"].every((key) => keys.includes(key))) {
44
- return { ok: false, status: 400, reason: "malformed" };
45
- }
46
- if ((await sha256Hex(canonicalJson({ tenantId, stage, contact }))) !== verified.digest) {
47
- return { ok: false, status: 401, reason: "signature" };
48
- }
49
- const command = readOrderContactCommand(contact);
50
- if (!command) return { ok: false, status: 400, reason: "malformed" };
51
- const sealed: SealOutcome = await sealOrderContact(db, kms, {
52
- tenantId,
53
- stage,
54
- command,
55
- regulated: tenantClass.regulated,
56
- issuer: verified.issuer,
57
- jti: verified.jti,
58
- now: new Date(config.now),
59
- });
60
- return sealed.ok
61
- ? { ok: true, duplicate: sealed.duplicate, tenantId, stage }
62
- : { ok: false, status: sealed.status, reason: sealed.reason };
63
- }