@aglyn/plugins-commerce 1.0.0-beta.277 → 1.0.0-beta.282

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 (212) hide show
  1. package/package.json +17 -14
  2. package/src/lib/components/commerce-console-page.js +33 -1
  3. package/src/lib/components/commerce-console-page.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/pos/pos-hardware-api.d.ts +122 -0
  7. package/src/lib/components/console/pos/pos-hardware-api.js +90 -0
  8. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -0
  9. package/src/lib/components/console/pos/pos-reader-splash-api.d.ts +58 -0
  10. package/src/lib/components/console/pos/pos-reader-splash-api.js +101 -0
  11. package/src/lib/components/console/pos/pos-reader-splash-api.js.map +1 -0
  12. package/src/lib/components/console/pos-devices-card.component.js +5 -0
  13. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  14. package/src/lib/components/console/pos-hardware-card.component.d.ts +26 -0
  15. package/src/lib/components/console/pos-hardware-card.component.js +456 -0
  16. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -0
  17. package/src/lib/components/console/pos-hardware-orders-staff-page.component.d.ts +14 -0
  18. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +519 -0
  19. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -0
  20. package/src/lib/components/console/pos-ops/pos-check-in-dialog.component.d.ts +27 -0
  21. package/src/lib/components/console/pos-ops/pos-check-in-dialog.component.js +444 -0
  22. package/src/lib/components/console/pos-ops/pos-check-in-dialog.component.js.map +1 -0
  23. package/src/lib/components/console/pos-ops/pos-check-in-zone.component.d.ts +9 -0
  24. package/src/lib/components/console/pos-ops/pos-check-in-zone.component.js +37 -0
  25. package/src/lib/components/console/pos-ops/pos-check-in-zone.component.js.map +1 -0
  26. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.d.ts +24 -0
  27. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +346 -0
  28. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -0
  29. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.d.ts +5 -1
  30. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js +83 -4
  31. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js.map +1 -1
  32. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.d.ts +35 -0
  33. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +546 -0
  34. package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -0
  35. package/src/lib/components/console/pos-ops/pos-operations-bar.component.d.ts +2 -1
  36. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js +20 -1
  37. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js.map +1 -1
  38. package/src/lib/components/console/pos-ops/pos-ops-api.d.ts +1 -1
  39. package/src/lib/components/console/pos-ops/pos-ops-api.js.map +1 -1
  40. package/src/lib/components/console/pos-page.component.js +6 -3
  41. package/src/lib/components/console/pos-page.component.js.map +1 -1
  42. package/src/lib/components/console/pos-reader-splash-setting.component.d.ts +22 -0
  43. package/src/lib/components/console/pos-reader-splash-setting.component.js +275 -0
  44. package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -0
  45. package/src/lib/components/console/pos-reader-splash-staff-page.component.d.ts +14 -0
  46. package/src/lib/components/console/pos-reader-splash-staff-page.component.js +301 -0
  47. package/src/lib/components/console/pos-reader-splash-staff-page.component.js.map +1 -0
  48. package/src/lib/components/console/pos-zones.d.ts +37 -3
  49. package/src/lib/components/console/pos-zones.js +11 -1
  50. package/src/lib/components/console/pos-zones.js.map +1 -1
  51. package/src/lib/components/console/product-check-in-fields.component.d.ts +20 -0
  52. package/src/lib/components/console/product-check-in-fields.component.js +172 -0
  53. package/src/lib/components/console/product-check-in-fields.component.js.map +1 -0
  54. package/src/lib/components/console/product-editor-dialog.component.js +48 -9
  55. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  56. package/src/lib/components/console/product-register-fields.component.d.ts +12 -0
  57. package/src/lib/components/console/product-register-fields.component.js +39 -1
  58. package/src/lib/components/console/product-register-fields.component.js.map +1 -1
  59. package/src/lib/components/console/products-hub-card.component.js +21 -6
  60. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  61. package/src/lib/components/console/reservations-card.component.js +239 -70
  62. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  63. package/src/lib/components/reservation-widget.js +16 -0
  64. package/src/lib/components/reservation-widget.js.map +1 -1
  65. package/src/lib/constants/operator-alerts.d.ts +6 -0
  66. package/src/lib/constants/operator-alerts.js +20 -1
  67. package/src/lib/constants/operator-alerts.js.map +1 -1
  68. package/src/lib/declarations.console-server.js +7 -0
  69. package/src/lib/declarations.console-server.js.map +1 -1
  70. package/src/lib/declarations.d.ts +26 -0
  71. package/src/lib/declarations.js +34 -0
  72. package/src/lib/declarations.js.map +1 -0
  73. package/src/lib/model/commerce-check-in-product.d.ts +37 -0
  74. package/src/lib/model/commerce-check-in-product.js +49 -0
  75. package/src/lib/model/commerce-check-in-product.js.map +1 -0
  76. package/src/lib/model/commerce-check-in.d.ts +187 -0
  77. package/src/lib/model/commerce-check-in.js +468 -0
  78. package/src/lib/model/commerce-check-in.js.map +1 -0
  79. package/src/lib/model/commerce-pos-day-report.d.ts +209 -0
  80. package/src/lib/model/commerce-pos-day-report.js +572 -0
  81. package/src/lib/model/commerce-pos-day-report.js.map +1 -0
  82. package/src/lib/model/commerce-pos-offline.d.ts +65 -3
  83. package/src/lib/model/commerce-pos-offline.js +104 -7
  84. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +1 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +43 -3
  89. package/src/lib/model/commerce-pos.js +73 -5
  90. package/src/lib/model/commerce-pos.js.map +1 -1
  91. package/src/lib/model/commerce-reservations.d.ts +73 -7
  92. package/src/lib/model/commerce-reservations.js +90 -10
  93. package/src/lib/model/commerce-reservations.js.map +1 -1
  94. package/src/lib/model/commerce.d.ts +40 -0
  95. package/src/lib/model/commerce.js +22 -4
  96. package/src/lib/model/commerce.js.map +1 -1
  97. package/src/lib/model/index.d.ts +1 -0
  98. package/src/lib/model/index.js +1 -0
  99. package/src/lib/model/index.js.map +1 -1
  100. package/src/lib/model/plugin-permissions.d.ts +1 -1
  101. package/src/lib/model/plugin-permissions.js +2 -1
  102. package/src/lib/model/plugin-permissions.js.map +1 -1
  103. package/src/lib/model/pos-hardware.d.ts +288 -0
  104. package/src/lib/model/pos-hardware.js +499 -0
  105. package/src/lib/model/pos-hardware.js.map +1 -0
  106. package/src/lib/model/pos-offline-card-limits.d.ts +20 -0
  107. package/src/lib/model/pos-offline-card-limits.js +28 -0
  108. package/src/lib/model/pos-offline-card-limits.js.map +1 -0
  109. package/src/lib/model/pos-reader-splash.d.ts +114 -0
  110. package/src/lib/model/pos-reader-splash.js +141 -0
  111. package/src/lib/model/pos-reader-splash.js.map +1 -0
  112. package/src/lib/model/product-write.d.ts +6 -0
  113. package/src/lib/plugin-config.d.ts +10 -0
  114. package/src/lib/plugin-config.js +40 -0
  115. package/src/lib/plugin-config.js.map +1 -1
  116. package/src/lib/plugin.js +28 -0
  117. package/src/lib/plugin.js.map +1 -1
  118. package/src/lib/server/cart-checkout.js +3 -1
  119. package/src/lib/server/cart-checkout.js.map +1 -1
  120. package/src/lib/server/cart.js +12 -1
  121. package/src/lib/server/cart.js.map +1 -1
  122. package/src/lib/server/catalog.js +49 -12
  123. package/src/lib/server/catalog.js.map +1 -1
  124. package/src/lib/server/checkout-extras.js +1 -1
  125. package/src/lib/server/checkout-extras.js.map +1 -1
  126. package/src/lib/server/checkout.js +7 -0
  127. package/src/lib/server/checkout.js.map +1 -1
  128. package/src/lib/server/person-eraser.d.ts +8 -1
  129. package/src/lib/server/person-eraser.js +23 -1
  130. package/src/lib/server/person-eraser.js.map +1 -1
  131. package/src/lib/server/pos-check-in.d.ts +49 -0
  132. package/src/lib/server/pos-check-in.js +652 -0
  133. package/src/lib/server/pos-check-in.js.map +1 -0
  134. package/src/lib/server/pos-day-report.d.ts +46 -0
  135. package/src/lib/server/pos-day-report.js +299 -0
  136. package/src/lib/server/pos-day-report.js.map +1 -0
  137. package/src/lib/server/pos-hardware-admin.d.ts +50 -0
  138. package/src/lib/server/pos-hardware-admin.js +366 -0
  139. package/src/lib/server/pos-hardware-admin.js.map +1 -0
  140. package/src/lib/server/pos-hardware-notify.d.ts +27 -0
  141. package/src/lib/server/pos-hardware-notify.js +142 -0
  142. package/src/lib/server/pos-hardware-notify.js.map +1 -0
  143. package/src/lib/server/pos-hardware-user-eraser.d.ts +26 -0
  144. package/src/lib/server/pos-hardware-user-eraser.js +67 -0
  145. package/src/lib/server/pos-hardware-user-eraser.js.map +1 -0
  146. package/src/lib/server/pos-hardware-webhook.d.ts +31 -0
  147. package/src/lib/server/pos-hardware-webhook.js +176 -0
  148. package/src/lib/server/pos-hardware-webhook.js.map +1 -0
  149. package/src/lib/server/pos-hardware.d.ts +58 -0
  150. package/src/lib/server/pos-hardware.js +234 -0
  151. package/src/lib/server/pos-hardware.js.map +1 -0
  152. package/src/lib/server/pos-offline-card-reconcile.d.ts +38 -0
  153. package/src/lib/server/pos-offline-card-reconcile.js +58 -0
  154. package/src/lib/server/pos-offline-card-reconcile.js.map +1 -0
  155. package/src/lib/server/pos-offline-sync.d.ts +32 -0
  156. package/src/lib/server/pos-offline-sync.js +191 -15
  157. package/src/lib/server/pos-offline-sync.js.map +1 -1
  158. package/src/lib/server/pos-ops-routes.d.ts +4 -2
  159. package/src/lib/server/pos-ops-routes.js +14 -2
  160. package/src/lib/server/pos-ops-routes.js.map +1 -1
  161. package/src/lib/server/pos-order.js +39 -51
  162. package/src/lib/server/pos-order.js.map +1 -1
  163. package/src/lib/server/pos-payment.js +8 -4
  164. package/src/lib/server/pos-payment.js.map +1 -1
  165. package/src/lib/server/pos-reader-splash-admin.d.ts +36 -0
  166. package/src/lib/server/pos-reader-splash-admin.js +295 -0
  167. package/src/lib/server/pos-reader-splash-admin.js.map +1 -0
  168. package/src/lib/server/pos-reader-splash-render.d.ts +40 -0
  169. package/src/lib/server/pos-reader-splash-render.js +138 -0
  170. package/src/lib/server/pos-reader-splash-render.js.map +1 -0
  171. package/src/lib/server/pos-reader-splash-server.d.ts +32 -0
  172. package/src/lib/server/pos-reader-splash-server.js +32 -0
  173. package/src/lib/server/pos-reader-splash-server.js.map +1 -0
  174. package/src/lib/server/pos-reader-splash.d.ts +105 -0
  175. package/src/lib/server/pos-reader-splash.js +548 -0
  176. package/src/lib/server/pos-reader-splash.js.map +1 -0
  177. package/src/lib/server/pos-sale.d.ts +2 -1
  178. package/src/lib/server/pos-sale.js +3 -1
  179. package/src/lib/server/pos-sale.js.map +1 -1
  180. package/src/lib/server/pos-terminal.d.ts +67 -4
  181. package/src/lib/server/pos-terminal.js +239 -32
  182. package/src/lib/server/pos-terminal.js.map +1 -1
  183. package/src/lib/server/process-restock.js +4 -0
  184. package/src/lib/server/process-restock.js.map +1 -1
  185. package/src/lib/server/product-card.js +2 -2
  186. package/src/lib/server/product-card.js.map +1 -1
  187. package/src/lib/server/product-catalog.d.ts +2 -0
  188. package/src/lib/server/product-catalog.js +11 -4
  189. package/src/lib/server/product-catalog.js.map +1 -1
  190. package/src/lib/server/product.js +3 -1
  191. package/src/lib/server/product.js.map +1 -1
  192. package/src/lib/server/related.js +8 -1
  193. package/src/lib/server/related.js.map +1 -1
  194. package/src/lib/server/reservation-availability-query.d.ts +35 -0
  195. package/src/lib/server/reservation-availability-query.js +34 -0
  196. package/src/lib/server/reservation-availability-query.js.map +1 -0
  197. package/src/lib/server/reservation-availability.d.ts +21 -0
  198. package/src/lib/server/reservation-availability.js +64 -10
  199. package/src/lib/server/reservation-availability.js.map +1 -1
  200. package/src/lib/server/reservation-walk-in.d.ts +28 -0
  201. package/src/lib/server/reservation-walk-in.js +166 -0
  202. package/src/lib/server/reservation-walk-in.js.map +1 -0
  203. package/src/lib/server/reserve.js +13 -10
  204. package/src/lib/server/reserve.js.map +1 -1
  205. package/src/lib/server/reviews.js +3 -1
  206. package/src/lib/server/reviews.js.map +1 -1
  207. package/src/lib/server/site-page-resolver.js +5 -2
  208. package/src/lib/server/site-page-resolver.js.map +1 -1
  209. package/src/lib/server.js +26 -0
  210. package/src/lib/server.js.map +1 -1
  211. package/src/lib/testing/fake-firestore.js +72 -0
  212. package/src/lib/testing/fake-firestore.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet. Loaded on first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","req","res","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","localFulfillmentHandler","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,gCAAgC,QAAQ,wCAAoC;AACrF,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,0BAAsB;AACjE,SAASC,uBAAuB,QAAQ,wDAAuD;AAC/F,SAASC,uBAAu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;IACzE,uDAAuD;IACvDhG,2BAA2B,IAAMhB,cAAcyI,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // A paid card-reader order from the POS hardware shop (AGL-4038), on the\n // same platform webhook: its own handler, self-selecting on the session's\n // `metadata.type`, so the storefront sections above never see it.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-hardware-webhook')).posHardwareBillingWebhookHandler(event),\n )\n // A card the Aglyn POS app took offline (AGL-4039): its PaymentIntent can\n // reach Stripe before the sale reaches the server, so every event on one is\n // kept by the sale's key. Self-selecting on `metadata.kind`.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-offline-card-reconcile')).posOfflineCardBillingWebhookHandler(event),\n )\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // A staff walk-in from the Reservations card and the native apps\n // (AGL-4046): availability re-asked inside the transaction that writes, so\n // two staff cannot hand out the last unit at once. Loaded on first call.\n registerPluginApiRoute('commerce/reservations/walk-in', async (req, res) =>\n (await import('./server/reservation-walk-in')).reservationWalkInHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet. Loaded on first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The POS hardware shop (AGL-4038): the Hardware card's catalog, Checkout\n // and order list, gated like a sale and hidden until the deployment prices\n // it; and the staff page's orders, which name no site. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware', async (req, res) =>\n (await import('./server/pos-hardware')).posHardwareHandler(req, res),\n )\n // A store's card reader start-up screen (AGL-4048): the POS devices card's\n // setting, gated like a sale, and the staff page's platform default. Both\n // draw images, so each loads with its first call.\n registerPluginApiRoute('commerce/pos-reader-splash', async (req, res) =>\n (await import('./server/pos-reader-splash')).posReaderSplashHandler(req, res),\n )\n registerPluginApiRoute('commerce/admin/reader-splash', {\n web: async (request) =>\n (await import('./server/pos-reader-splash-admin')).posReaderSplashAdmin(request),\n })\n registerPluginApiRoute('commerce/admin/hardware-orders', {\n web: async (request) =>\n (await import('./server/pos-hardware-admin')).posHardwareAdminOrders(request),\n })\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","req","res","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","event","posHardwareBillingWebhookHandler","posOfflineCardBillingWebhookHandler","localFulfillmentHandler","productSaveHandler","productStockHandler","reservationWalkInHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posHardwareHandler","posReaderSplashHandler","posReaderSplashAdmin","posHardwareAdminOrders","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA4B;AAC7E,SAASC,yBAAyB,QAAQ,2BAAuB;AACjE,SAASC,2BAA2B,QAAQ,oCAAgC;AAC5E,SAASC,gCAAgC,QAAQ,wCAAoC;AACrF,SAASC,0BAA0B,QAAQ,4CAAwC;AACnF,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,0BAAsB;AACjE,SAASC,uBAAuB,QAAQ,wDAAuD;AAC/F,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,qBAAqB,QAAQ,qDAAoD;AAC1F,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,0BAA0B,QAAQ,4BAAwB;AACnE,SAASC,oBAAoB,QAAQ,gCAA4B;AACjE,SAASC,sBAAsB,QAAQ,qBAAiB;AACxD,SAASC,wBAAwB,QAAQ,iCAA6B;AAC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B,oCAAoC,OAAOsH,KAAKC,MACrE,AAAC,CAAA,MAAM,MAAM,CAAC,sCAAkC,EAAG6B,4BAA4B,CAAC9B,KAAKC;IAEvF,wEAAwE;IACxE,wEAAwE;IACxE,wEAAwE;IACxE,yEAAyE;IACzE,sEAAsE;IACtEvH,uBACE,gCACA;QACEyH,KAAK,OAAOC,SAASiB,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,0BAAsB,EAAGU,gBAAgB,CAAC3B,SAASiB;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpE7I,uBACE,iCACA;QACEyH,KAAK,OAAOC,SAASiB,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGW,iBAAiB,CAAC5B,SAASiB;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnC7I,uBAAuB,gCAAgC,OAAOsH,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGgC,yBAAyB,CAACjC,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDhG,2BAA2B,IAAMhB,cAAciJ,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
@@ -154,8 +154,72 @@ function collectionRef(path, filters = []) {
154
154
  }
155
155
  });
156
156
  }
157
+ function collectionGroupRef(name, shape = {
158
+ filters: []
159
+ }) {
160
+ const next = (patch)=>collectionGroupRef(name, _extends({}, shape, patch));
161
+ return {
162
+ where: (field, _op, value)=>next({
163
+ filters: [
164
+ ...shape.filters,
165
+ [
166
+ field,
167
+ value
168
+ ]
169
+ ]
170
+ }),
171
+ orderBy: (field, direction)=>next({
172
+ order: {
173
+ field,
174
+ desc: direction === 'desc'
175
+ }
176
+ }),
177
+ startAfter: (snapshot)=>next({
178
+ after: snapshot.ref.path
179
+ }),
180
+ limit: (cap)=>next({
181
+ cap
182
+ }),
183
+ get: async ()=>{
184
+ let keys = [
185
+ ...fakeDocs.keys()
186
+ ].filter((key)=>{
187
+ const parts = key.split('/');
188
+ return parts.length >= 2 && parts.length % 2 === 0 && parts[parts.length - 2] === name;
189
+ }).filter((key)=>shape.filters.every(([field, value])=>{
190
+ var _fakeDocs_get;
191
+ return ((_fakeDocs_get = fakeDocs.get(key)) == null ? void 0 : _fakeDocs_get[field]) === value;
192
+ }));
193
+ if (shape.order) {
194
+ const { field, desc } = shape.order;
195
+ const sign = desc ? -1 : 1;
196
+ keys.sort((a, b)=>{
197
+ var _ref, _ref1;
198
+ var _fakeDocs_get, _fakeDocs_get1;
199
+ const left = (_ref = (_fakeDocs_get = fakeDocs.get(a)) == null ? void 0 : _fakeDocs_get[field]) != null ? _ref : 0;
200
+ const right = (_ref1 = (_fakeDocs_get1 = fakeDocs.get(b)) == null ? void 0 : _fakeDocs_get1[field]) != null ? _ref1 : 0;
201
+ if (left !== right) return left < right ? -sign : sign;
202
+ return a < b ? -sign : a > b ? sign : 0;
203
+ });
204
+ }
205
+ if (shape.after) {
206
+ const at = keys.indexOf(shape.after);
207
+ keys = at >= 0 ? keys.slice(at + 1) : keys;
208
+ }
209
+ if (shape.cap !== undefined) keys = keys.slice(0, shape.cap);
210
+ const docs = keys.map(snapshotOf);
211
+ return {
212
+ docs,
213
+ empty: docs.length === 0,
214
+ size: docs.length
215
+ };
216
+ }
217
+ };
218
+ }
157
219
  export const fakeFirestore = {
158
220
  collection: (name)=>collectionRef(name),
221
+ collectionGroup: (name)=>collectionGroupRef(name),
222
+ doc: (path)=>docRef(path),
159
223
  runTransaction: async (fn)=>{
160
224
  const writes = [];
161
225
  const outcome = await fn({
@@ -166,6 +230,14 @@ export const fakeFirestore = {
166
230
  update: (ref, value)=>{
167
231
  writes.push(()=>applyWrite(ref.path, value, 'update'));
168
232
  },
233
+ create: (ref, value)=>{
234
+ if (fakeDocs.has(ref.path)) {
235
+ const error = new Error(`ALREADY_EXISTS: ${ref.path}`);
236
+ error.code = 6;
237
+ throw error;
238
+ }
239
+ writes.push(()=>applyWrite(ref.path, value, 'set'));
240
+ },
169
241
  delete: (ref)=>{
170
242
  writes.push(()=>fakeDocs.delete(ref.path));
171
243
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/fake-firestore.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An in-memory stand-in for the Admin SDK's Firestore, for the register's\n * money-path specs (AGL-3607). Faithful where the code under test leans on\n * it: `create()` refuses an existing document, `update()` refuses a missing\n * one, merge-sets merge one level, and the `increment`, `delete` and\n * `arrayUnion` sentinels resolve against the stored value. A transaction\n * buffers its writes and applies them at commit, so a throw inside it writes\n * nothing.\n */\n\nconst INCREMENT = Symbol('increment')\nconst DELETE = Symbol('delete')\nconst UNION = Symbol('arrayUnion')\n\nexport const fakeFieldValue = {\n increment: (value: number) => ({ [INCREMENT]: value }),\n delete: () => ({ [DELETE]: true }),\n arrayUnion: (...values: unknown[]) => ({ [UNION]: values }),\n serverTimestamp: () => '<server-timestamp>',\n}\n\nexport const fakeDocs = new Map<string, Record<string, any>>()\n\nlet autoId = 0\n\nfunction resolveValue(existing: any, value: any): any {\n if (value && typeof value === 'object') {\n if (INCREMENT in value) return (Number(existing) || 0) + value[INCREMENT]\n if (UNION in value) {\n const base = Array.isArray(existing) ? [...existing] : []\n for (const item of value[UNION]) {\n if (!base.some((entry) => JSON.stringify(entry) === JSON.stringify(item))) base.push(item)\n }\n return base\n }\n }\n return value\n}\n\nfunction applyWrite(\n path: string,\n value: Record<string, any>,\n mode: 'set' | 'merge' | 'update',\n) {\n const existing = fakeDocs.get(path)\n if (mode === 'update' && !existing) {\n const error: any = new Error(`NOT_FOUND: ${path}`)\n error.code = 5\n throw error\n }\n const next: Record<string, any> = mode === 'set' ? {} : { ...(existing ?? {}) }\n for (const [key, raw] of Object.entries(value)) {\n if (raw && typeof raw === 'object' && DELETE in raw) {\n delete next[key]\n continue\n }\n if (\n mode === 'merge' &&\n raw &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n !(INCREMENT in raw) &&\n !(UNION in raw) &&\n next[key] &&\n typeof next[key] === 'object' &&\n !Array.isArray(next[key])\n ) {\n const nested = { ...next[key] }\n for (const [inner, innerValue] of Object.entries(raw)) {\n if (innerValue && typeof innerValue === 'object' && DELETE in (innerValue as any)) {\n delete nested[inner]\n } else {\n nested[inner] = resolveValue(nested[inner], innerValue)\n }\n }\n next[key] = nested\n continue\n }\n next[key] = resolveValue(existing?.[key], raw)\n }\n fakeDocs.set(path, next)\n}\n\nfunction snapshotOf(path: string) {\n const data = fakeDocs.get(path)\n return {\n id: path.split('/').pop() as string,\n exists: data !== undefined,\n ref: docRef(path),\n data: () => (data ? JSON.parse(JSON.stringify(data)) : undefined),\n get: (field: string) => data?.[field],\n }\n}\n\nexport function docRef(path: string): any {\n return {\n id: path.split('/').pop() as string,\n path,\n get: async () => snapshotOf(path),\n set: async (value: Record<string, any>, options?: { merge?: boolean }) =>\n applyWrite(path, value, options?.merge ? 'merge' : 'set'),\n update: async (value: Record<string, any>) => applyWrite(path, value, 'update'),\n create: async (value: Record<string, any>) => {\n if (fakeDocs.has(path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${path}`)\n error.code = 6\n throw error\n }\n applyWrite(path, value, 'set')\n },\n delete: async () => {\n fakeDocs.delete(path)\n },\n collection: (name: string) => collectionRef(`${path}/${name}`),\n }\n}\n\nfunction collectionRef(path: string, filters: Array<[string, string, any]> = []): any {\n const children = () =>\n [...fakeDocs.keys()].filter(\n (key) => key.startsWith(`${path}/`) && !key.slice(path.length + 1).includes('/'),\n )\n const query = {\n where: (field: string, op: string, value: any) =>\n collectionRef(path, [...filters, [field, op, value]]),\n limit: () => query,\n orderBy: () => query,\n get: async () => {\n const docs = children()\n .filter((key) =>\n filters.every(([field, op, value]) => {\n const stored = fakeDocs.get(key)?.[field]\n if (op === '==') return stored === value\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n return false\n }),\n )\n .map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n }\n return {\n ...query,\n path,\n doc: (id?: string) => docRef(`${path}/${id ?? `auto-${++autoId}`}`),\n add: async (value: Record<string, any>) => {\n const ref = docRef(`${path}/auto-${++autoId}`)\n applyWrite(ref.path, value, 'set')\n return ref\n },\n }\n}\n\nexport const fakeFirestore: any = {\n collection: (name: string) => collectionRef(name),\n runTransaction: async (fn: (transaction: any) => Promise<any>) => {\n const writes: Array<() => void> = []\n const outcome = await fn({\n get: (ref: any) => ref.get(),\n set: (ref: any, value: any, options?: { merge?: boolean }) => {\n writes.push(() => applyWrite(ref.path, value, options?.merge ? 'merge' : 'set'))\n },\n update: (ref: any, value: any) => {\n writes.push(() => applyWrite(ref.path, value, 'update'))\n },\n delete: (ref: any) => {\n writes.push(() => fakeDocs.delete(ref.path))\n },\n })\n for (const write of writes) write()\n return outcome\n },\n recursiveDelete: async (ref: any) => {\n for (const key of [...fakeDocs.keys()]) {\n if (key === ref.path || key.startsWith(`${ref.path}/`)) fakeDocs.delete(key)\n }\n },\n}\n\nexport function resetFakeFirestore(): void {\n fakeDocs.clear()\n autoId = 0\n}\n"],"names":["INCREMENT","Symbol","DELETE","UNION","fakeFieldValue","increment","value","delete","arrayUnion","values","serverTimestamp","fakeDocs","Map","autoId","resolveValue","existing","Number","base","Array","isArray","item","some","entry","JSON","stringify","push","applyWrite","path","mode","get","error","Error","code","next","key","raw","Object","entries","nested","inner","innerValue","set","snapshotOf","data","id","split","pop","exists","undefined","ref","docRef","parse","field","options","merge","update","create","has","collection","name","collectionRef","filters","children","keys","filter","startsWith","slice","length","includes","query","where","op","limit","orderBy","docs","every","stored","map","empty","size","doc","add","fakeFirestore","runTransaction","fn","writes","outcome","write","recursiveDelete","resetFakeFirestore","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,MAAMA,YAAYC,OAAO;AACzB,MAAMC,SAASD,OAAO;AACtB,MAAME,QAAQF,OAAO;AAErB,OAAO,MAAMG,iBAAiB;IAC5BC,WAAW,CAACC,QAAmB,CAAA;YAAE,CAACN,UAAU,EAAEM;QAAM,CAAA;IACpDC,QAAQ,IAAO,CAAA;YAAE,CAACL,OAAO,EAAE;QAAK,CAAA;IAChCM,YAAY,CAAC,GAAGC,SAAuB,CAAA;YAAE,CAACN,MAAM,EAAEM;QAAO,CAAA;IACzDC,iBAAiB,IAAM;AACzB,EAAC;AAED,OAAO,MAAMC,WAAW,IAAIC,MAAkC;AAE9D,IAAIC,SAAS;AAEb,SAASC,aAAaC,QAAa,EAAET,KAAU;IAC7C,IAAIA,SAAS,OAAOA,UAAU,UAAU;QACtC,IAAIN,aAAaM,OAAO,OAAO,AAACU,CAAAA,OAAOD,aAAa,CAAA,IAAKT,KAAK,CAACN,UAAU;QACzE,IAAIG,SAASG,OAAO;YAClB,MAAMW,OAAOC,MAAMC,OAAO,CAACJ,YAAY;mBAAIA;aAAS,GAAG,EAAE;YACzD,KAAK,MAAMK,QAAQd,KAAK,CAACH,MAAM,CAAE;gBAC/B,IAAI,CAACc,KAAKI,IAAI,CAAC,CAACC,QAAUC,KAAKC,SAAS,CAACF,WAAWC,KAAKC,SAAS,CAACJ,QAAQH,KAAKQ,IAAI,CAACL;YACvF;YACA,OAAOH;QACT;IACF;IACA,OAAOX;AACT;AAEA,SAASoB,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,KAAK,IAAG,UAAU;YAC3E;YACAC,QAAQ,CAACN,KAAU3C;gBACjB+E,OAAO5D,IAAI,CAAC,IAAMC,WAAWuB,IAAItB,IAAI,EAAErB,OAAO;YAChD;YACAC,QAAQ,CAAC0C;gBACPoC,OAAO5D,IAAI,CAAC,IAAMd,SAASJ,MAAM,CAAC0C,IAAItB,IAAI;YAC5C;QACF;QACA,KAAK,MAAM4D,SAASF,OAAQE;QAC5B,OAAOD;IACT;IACAE,iBAAiB,OAAOvC;QACtB,KAAK,MAAMf,OAAO;eAAIvB,SAASoD,IAAI;SAAG,CAAE;YACtC,IAAI7B,QAAQe,IAAItB,IAAI,IAAIO,IAAI+B,UAAU,CAAC,GAAGhB,IAAItB,IAAI,CAAC,CAAC,CAAC,GAAGhB,SAASJ,MAAM,CAAC2B;QAC1E;IACF;AACF,EAAC;AAED,OAAO,SAASuD;IACd9E,SAAS+E,KAAK;IACd7E,SAAS;AACX"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/testing/fake-firestore.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An in-memory stand-in for the Admin SDK's Firestore, for the register's\n * money-path specs (AGL-3607). Faithful where the code under test leans on\n * it: `create()` refuses an existing document, `update()` refuses a missing\n * one, merge-sets merge one level, and the `increment`, `delete` and\n * `arrayUnion` sentinels resolve against the stored value. A transaction\n * buffers its writes and applies them at commit, so a throw inside it writes\n * nothing.\n */\n\nconst INCREMENT = Symbol('increment')\nconst DELETE = Symbol('delete')\nconst UNION = Symbol('arrayUnion')\n\nexport const fakeFieldValue = {\n increment: (value: number) => ({ [INCREMENT]: value }),\n delete: () => ({ [DELETE]: true }),\n arrayUnion: (...values: unknown[]) => ({ [UNION]: values }),\n serverTimestamp: () => '<server-timestamp>',\n}\n\nexport const fakeDocs = new Map<string, Record<string, any>>()\n\nlet autoId = 0\n\nfunction resolveValue(existing: any, value: any): any {\n if (value && typeof value === 'object') {\n if (INCREMENT in value) return (Number(existing) || 0) + value[INCREMENT]\n if (UNION in value) {\n const base = Array.isArray(existing) ? [...existing] : []\n for (const item of value[UNION]) {\n if (!base.some((entry) => JSON.stringify(entry) === JSON.stringify(item))) base.push(item)\n }\n return base\n }\n }\n return value\n}\n\nfunction applyWrite(\n path: string,\n value: Record<string, any>,\n mode: 'set' | 'merge' | 'update',\n) {\n const existing = fakeDocs.get(path)\n if (mode === 'update' && !existing) {\n const error: any = new Error(`NOT_FOUND: ${path}`)\n error.code = 5\n throw error\n }\n const next: Record<string, any> = mode === 'set' ? {} : { ...(existing ?? {}) }\n for (const [key, raw] of Object.entries(value)) {\n if (raw && typeof raw === 'object' && DELETE in raw) {\n delete next[key]\n continue\n }\n if (\n mode === 'merge' &&\n raw &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n !(INCREMENT in raw) &&\n !(UNION in raw) &&\n next[key] &&\n typeof next[key] === 'object' &&\n !Array.isArray(next[key])\n ) {\n const nested = { ...next[key] }\n for (const [inner, innerValue] of Object.entries(raw)) {\n if (innerValue && typeof innerValue === 'object' && DELETE in (innerValue as any)) {\n delete nested[inner]\n } else {\n nested[inner] = resolveValue(nested[inner], innerValue)\n }\n }\n next[key] = nested\n continue\n }\n next[key] = resolveValue(existing?.[key], raw)\n }\n fakeDocs.set(path, next)\n}\n\nfunction snapshotOf(path: string) {\n const data = fakeDocs.get(path)\n return {\n id: path.split('/').pop() as string,\n exists: data !== undefined,\n ref: docRef(path),\n data: () => (data ? JSON.parse(JSON.stringify(data)) : undefined),\n get: (field: string) => data?.[field],\n }\n}\n\nexport function docRef(path: string): any {\n return {\n id: path.split('/').pop() as string,\n path,\n get: async () => snapshotOf(path),\n set: async (value: Record<string, any>, options?: { merge?: boolean }) =>\n applyWrite(path, value, options?.merge ? 'merge' : 'set'),\n update: async (value: Record<string, any>) => applyWrite(path, value, 'update'),\n create: async (value: Record<string, any>) => {\n if (fakeDocs.has(path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${path}`)\n error.code = 6\n throw error\n }\n applyWrite(path, value, 'set')\n },\n delete: async () => {\n fakeDocs.delete(path)\n },\n collection: (name: string) => collectionRef(`${path}/${name}`),\n }\n}\n\nfunction collectionRef(path: string, filters: Array<[string, string, any]> = []): any {\n const children = () =>\n [...fakeDocs.keys()].filter(\n (key) => key.startsWith(`${path}/`) && !key.slice(path.length + 1).includes('/'),\n )\n const query = {\n where: (field: string, op: string, value: any) =>\n collectionRef(path, [...filters, [field, op, value]]),\n limit: () => query,\n orderBy: () => query,\n get: async () => {\n const docs = children()\n .filter((key) =>\n filters.every(([field, op, value]) => {\n const stored = fakeDocs.get(key)?.[field]\n if (op === '==') return stored === value\n if (op === 'array-contains') return Array.isArray(stored) && stored.includes(value)\n return false\n }),\n )\n .map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n }\n return {\n ...query,\n path,\n doc: (id?: string) => docRef(`${path}/${id ?? `auto-${++autoId}`}`),\n add: async (value: Record<string, any>) => {\n const ref = docRef(`${path}/auto-${++autoId}`)\n applyWrite(ref.path, value, 'set')\n return ref\n },\n }\n}\n\n/**\n * Every document in a collection named `name` at any depth, filtered by\n * equality (AGL-4038). `orderBy` sorts on one field, ties broken by path as\n * Firestore does, `startAfter` takes a document snapshot, and `limit` caps\n * the answer, so a cursor-paged staff list can be specced.\n */\ninterface GroupShape {\n filters: Array<[string, any]>\n order?: { field: string; desc: boolean }\n after?: string\n cap?: number\n}\nfunction collectionGroupRef(name: string, shape: GroupShape = { filters: [] }): any {\n const next = (patch: Partial<GroupShape>) => collectionGroupRef(name, { ...shape, ...patch })\n return {\n where: (field: string, _op: string, value: any) => next({ filters: [...shape.filters, [field, value]] }),\n orderBy: (field: string, direction?: string) => next({ order: { field, desc: direction === 'desc' } }),\n startAfter: (snapshot: { ref: { path: string } }) => next({ after: snapshot.ref.path }),\n limit: (cap: number) => next({ cap }),\n get: async () => {\n let keys = [...fakeDocs.keys()]\n .filter((key) => {\n const parts = key.split('/')\n return parts.length >= 2 && parts.length % 2 === 0 && parts[parts.length - 2] === name\n })\n .filter((key) => shape.filters.every(([field, value]) => fakeDocs.get(key)?.[field] === value))\n if (shape.order) {\n const { field, desc } = shape.order\n const sign = desc ? -1 : 1\n keys.sort((a, b) => {\n const left = fakeDocs.get(a)?.[field] ?? 0\n const right = fakeDocs.get(b)?.[field] ?? 0\n if (left !== right) return left < right ? -sign : sign\n return a < b ? -sign : a > b ? sign : 0\n })\n }\n if (shape.after) {\n const at = keys.indexOf(shape.after)\n keys = at >= 0 ? keys.slice(at + 1) : keys\n }\n if (shape.cap !== undefined) keys = keys.slice(0, shape.cap)\n const docs = keys.map(snapshotOf)\n return { docs, empty: docs.length === 0, size: docs.length }\n },\n }\n}\n\nexport const fakeFirestore: any = {\n collection: (name: string) => collectionRef(name),\n collectionGroup: (name: string) => collectionGroupRef(name),\n doc: (path: string) => docRef(path),\n runTransaction: async (fn: (transaction: any) => Promise<any>) => {\n const writes: Array<() => void> = []\n const outcome = await fn({\n get: (ref: any) => ref.get(),\n set: (ref: any, value: any, options?: { merge?: boolean }) => {\n writes.push(() => applyWrite(ref.path, value, options?.merge ? 'merge' : 'set'))\n },\n update: (ref: any, value: any) => {\n writes.push(() => applyWrite(ref.path, value, 'update'))\n },\n create: (ref: any, value: any) => {\n if (fakeDocs.has(ref.path)) {\n const error: any = new Error(`ALREADY_EXISTS: ${ref.path}`)\n error.code = 6\n throw error\n }\n writes.push(() => applyWrite(ref.path, value, 'set'))\n },\n delete: (ref: any) => {\n writes.push(() => fakeDocs.delete(ref.path))\n },\n })\n for (const write of writes) write()\n return outcome\n },\n recursiveDelete: async (ref: any) => {\n for (const key of [...fakeDocs.keys()]) {\n if (key === ref.path || key.startsWith(`${ref.path}/`)) fakeDocs.delete(key)\n }\n },\n}\n\nexport function resetFakeFirestore(): void {\n fakeDocs.clear()\n autoId = 0\n}\n"],"names":["INCREMENT","Symbol","DELETE","UNION","fakeFieldValue","increment","value","delete","arrayUnion","values","serverTimestamp","fakeDocs","Map","autoId","resolveValue","existing","Number","base","Array","isArray","item","some","entry","JSON","stringify","push","applyWrite","path","mode","get","error","Error","code","next","key","raw","Object","entries","nested","inner","innerValue","set","snapshotOf","data","id","split","pop","exists","undefined","ref","docRef","parse","field","options","merge","update","create","has","collection","name","collectionRef","filters","children","keys","filter","startsWith","slice","length","includes","query","where","op","limit","orderBy","docs","every","stored","map","empty","size","doc","add","collectionGroupRef","shape","patch","_op","direction","order","desc","startAfter","snapshot","after","cap","parts","sign","sort","a","b","left","right","at","indexOf","fakeFirestore","collectionGroup","runTransaction","fn","writes","outcome","write","recursiveDelete","resetFakeFirestore","clear"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,MAAMA,YAAYC,OAAO;AACzB,MAAMC,SAASD,OAAO;AACtB,MAAME,QAAQF,OAAO;AAErB,OAAO,MAAMG,iBAAiB;IAC5BC,WAAW,CAACC,QAAmB,CAAA;YAAE,CAACN,UAAU,EAAEM;QAAM,CAAA;IACpDC,QAAQ,IAAO,CAAA;YAAE,CAACL,OAAO,EAAE;QAAK,CAAA;IAChCM,YAAY,CAAC,GAAGC,SAAuB,CAAA;YAAE,CAACN,MAAM,EAAEM;QAAO,CAAA;IACzDC,iBAAiB,IAAM;AACzB,EAAC;AAED,OAAO,MAAMC,WAAW,IAAIC,MAAkC;AAE9D,IAAIC,SAAS;AAEb,SAASC,aAAaC,QAAa,EAAET,KAAU;IAC7C,IAAIA,SAAS,OAAOA,UAAU,UAAU;QACtC,IAAIN,aAAaM,OAAO,OAAO,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