@aglyn/plugins-commerce 1.0.0-beta.230 → 1.0.0-beta.232

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 (609) hide show
  1. package/package.json +13 -13
  2. package/src/index.d.ts +0 -1
  3. package/src/index.js +0 -1
  4. package/src/index.js.map +1 -1
  5. package/src/lib/barcode/barcode-decode.d.ts +71 -0
  6. package/src/lib/barcode/barcode-decode.js +498 -0
  7. package/src/lib/barcode/barcode-decode.js.map +1 -0
  8. package/src/lib/barcode/barcode-encode.d.ts +44 -0
  9. package/src/lib/barcode/barcode-encode.js +138 -0
  10. package/src/lib/barcode/barcode-encode.js.map +1 -0
  11. package/src/lib/barcode/barcode-scanner.component.d.ts +23 -0
  12. package/src/lib/barcode/barcode-scanner.component.js +260 -0
  13. package/src/lib/barcode/barcode-scanner.component.js.map +1 -0
  14. package/src/lib/barcode/scan-button.component.d.ts +10 -0
  15. package/src/lib/barcode/scan-button.component.js +62 -0
  16. package/src/lib/barcode/scan-button.component.js.map +1 -0
  17. package/src/lib/barcode/scanner-wedge.d.ts +35 -0
  18. package/src/lib/barcode/scanner-wedge.js +108 -0
  19. package/src/lib/barcode/scanner-wedge.js.map +1 -0
  20. package/src/lib/components/account.js +10 -1
  21. package/src/lib/components/account.js.map +1 -1
  22. package/src/lib/components/cart-extras.d.ts +45 -0
  23. package/src/lib/components/cart-extras.js +127 -0
  24. package/src/lib/components/cart-extras.js.map +1 -0
  25. package/src/lib/components/cart.js +82 -15
  26. package/src/lib/components/cart.js.map +1 -1
  27. package/src/lib/components/checkout-return-notice.d.ts +26 -0
  28. package/src/lib/components/checkout-return-notice.js +48 -0
  29. package/src/lib/components/checkout-return-notice.js.map +1 -0
  30. package/src/lib/components/commerce-console-page.js +124 -0
  31. package/src/lib/components/commerce-console-page.js.map +1 -1
  32. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  33. package/src/lib/components/commerce-console-sections.js +4 -0
  34. package/src/lib/components/commerce-console-sections.js.map +1 -1
  35. package/src/lib/components/console/bulk-fulfill.d.ts +44 -0
  36. package/src/lib/components/console/bulk-fulfill.js +84 -0
  37. package/src/lib/components/console/bulk-fulfill.js.map +1 -0
  38. package/src/lib/components/console/catalog-organization-card.component.js +1 -0
  39. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  40. package/src/lib/components/console/customer-notifications-card.component.d.ts +19 -0
  41. package/src/lib/components/console/customer-notifications-card.component.js +149 -0
  42. package/src/lib/components/console/customer-notifications-card.component.js.map +1 -0
  43. package/src/lib/components/console/host-orders-card.component.js +88 -6
  44. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  45. package/src/lib/components/console/locations-card.component.js +164 -57
  46. package/src/lib/components/console/locations-card.component.js.map +1 -1
  47. package/src/lib/components/console/order-detail-dialog.component.js +209 -61
  48. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  49. package/src/lib/components/console/order-fulfillment-panel.component.d.ts +48 -0
  50. package/src/lib/components/console/order-fulfillment-panel.component.js +542 -0
  51. package/src/lib/components/console/order-fulfillment-panel.component.js.map +1 -0
  52. package/src/lib/components/console/order-invoice.component.d.ts +33 -0
  53. package/src/lib/components/console/order-invoice.component.js +81 -0
  54. package/src/lib/components/console/order-invoice.component.js.map +1 -0
  55. package/src/lib/components/console/order-receipt-resend.component.d.ts +21 -0
  56. package/src/lib/components/console/order-receipt-resend.component.js +203 -0
  57. package/src/lib/components/console/order-receipt-resend.component.js.map +1 -0
  58. package/src/lib/components/console/order-returns.component.d.ts +36 -0
  59. package/src/lib/components/console/order-returns.component.js +142 -0
  60. package/src/lib/components/console/order-returns.component.js.map +1 -0
  61. package/src/lib/components/console/order-shipping-actions.component.d.ts +54 -0
  62. package/src/lib/components/console/order-shipping-actions.component.js +149 -0
  63. package/src/lib/components/console/order-shipping-actions.component.js.map +1 -0
  64. package/src/lib/components/console/order-webhooks-card.component.d.ts +50 -0
  65. package/src/lib/components/console/order-webhooks-card.component.js +623 -0
  66. package/src/lib/components/console/order-webhooks-card.component.js.map +1 -0
  67. package/src/lib/components/console/order-zones.d.ts +155 -0
  68. package/src/lib/components/console/order-zones.js +40 -0
  69. package/src/lib/components/console/order-zones.js.map +1 -0
  70. package/src/lib/components/console/payment-methods-card.component.d.ts +67 -0
  71. package/src/lib/components/console/payment-methods-card.component.js +395 -0
  72. package/src/lib/components/console/payment-methods-card.component.js.map +1 -0
  73. package/src/lib/components/console/pos/pos-api.d.ts +124 -0
  74. package/src/lib/components/console/pos/pos-api.js +101 -0
  75. package/src/lib/components/console/pos/pos-api.js.map +1 -0
  76. package/src/lib/components/console/pos/pos-cart-panel.component.d.ts +36 -0
  77. package/src/lib/components/console/pos/pos-cart-panel.component.js +160 -0
  78. package/src/lib/components/console/pos/pos-cart-panel.component.js.map +1 -0
  79. package/src/lib/components/console/pos/pos-item-dialog.component.d.ts +39 -0
  80. package/src/lib/components/console/pos/pos-item-dialog.component.js +352 -0
  81. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -0
  82. package/src/lib/components/console/pos/pos-product-grid.component.d.ts +47 -0
  83. package/src/lib/components/console/pos/pos-product-grid.component.js +272 -0
  84. package/src/lib/components/console/pos/pos-product-grid.component.js.map +1 -0
  85. package/src/lib/components/console/pos/pos-receipt-panel.component.d.ts +27 -0
  86. package/src/lib/components/console/pos/pos-receipt-panel.component.js +282 -0
  87. package/src/lib/components/console/pos/pos-receipt-panel.component.js.map +1 -0
  88. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +53 -0
  89. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +445 -0
  90. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -0
  91. package/src/lib/components/console/pos/pos-tender-panel.component.d.ts +31 -0
  92. package/src/lib/components/console/pos/pos-tender-panel.component.js +640 -0
  93. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -0
  94. package/src/lib/components/console/pos/use-pos-display.d.ts +43 -0
  95. package/src/lib/components/console/pos/use-pos-display.js +161 -0
  96. package/src/lib/components/console/pos/use-pos-display.js.map +1 -0
  97. package/src/lib/components/console/pos-devices-card.component.d.ts +14 -0
  98. package/src/lib/components/console/pos-devices-card.component.js +546 -0
  99. package/src/lib/components/console/pos-devices-card.component.js.map +1 -0
  100. package/src/lib/components/console/pos-display/brand-screen.d.ts +33 -0
  101. package/src/lib/components/console/pos-display/brand-screen.js +85 -0
  102. package/src/lib/components/console/pos-display/brand-screen.js.map +1 -0
  103. package/src/lib/components/console/pos-display/cart-screen.d.ts +29 -0
  104. package/src/lib/components/console/pos-display/cart-screen.js +166 -0
  105. package/src/lib/components/console/pos-display/cart-screen.js.map +1 -0
  106. package/src/lib/components/console/pos-display/pairing-screen.d.ts +24 -0
  107. package/src/lib/components/console/pos-display/pairing-screen.js +127 -0
  108. package/src/lib/components/console/pos-display/pairing-screen.js.map +1 -0
  109. package/src/lib/components/console/pos-display/pos-display-api.d.ts +90 -0
  110. package/src/lib/components/console/pos-display/pos-display-api.js +140 -0
  111. package/src/lib/components/console/pos-display/pos-display-api.js.map +1 -0
  112. package/src/lib/components/console/pos-display/receipt-screen.d.ts +35 -0
  113. package/src/lib/components/console/pos-display/receipt-screen.js +200 -0
  114. package/src/lib/components/console/pos-display/receipt-screen.js.map +1 -0
  115. package/src/lib/components/console/pos-display/tip-screen.d.ts +36 -0
  116. package/src/lib/components/console/pos-display/tip-screen.js +211 -0
  117. package/src/lib/components/console/pos-display/tip-screen.js.map +1 -0
  118. package/src/lib/components/console/pos-display-page.component.d.ts +16 -0
  119. package/src/lib/components/console/pos-display-page.component.js +407 -0
  120. package/src/lib/components/console/pos-display-page.component.js.map +1 -0
  121. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.d.ts +40 -0
  122. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js +289 -0
  123. package/src/lib/components/console/pos-ops/pos-customer-lookup.component.js.map +1 -0
  124. package/src/lib/components/console/pos-ops/pos-last-receipt.component.d.ts +34 -0
  125. package/src/lib/components/console/pos-ops/pos-last-receipt.component.js +61 -0
  126. package/src/lib/components/console/pos-ops/pos-last-receipt.component.js.map +1 -0
  127. package/src/lib/components/console/pos-ops/pos-operations-bar.component.d.ts +38 -0
  128. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js +129 -0
  129. package/src/lib/components/console/pos-ops/pos-operations-bar.component.js.map +1 -0
  130. package/src/lib/components/console/pos-ops/pos-ops-api.d.ts +37 -0
  131. package/src/lib/components/console/pos-ops/pos-ops-api.js +60 -0
  132. package/src/lib/components/console/pos-ops/pos-ops-api.js.map +1 -0
  133. package/src/lib/components/console/pos-ops/pos-pin-pad.component.d.ts +48 -0
  134. package/src/lib/components/console/pos-ops/pos-pin-pad.component.js +220 -0
  135. package/src/lib/components/console/pos-ops/pos-pin-pad.component.js.map +1 -0
  136. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.d.ts +63 -0
  137. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.js +186 -0
  138. package/src/lib/components/console/pos-ops/pos-receipt-actions.component.js.map +1 -0
  139. package/src/lib/components/console/pos-ops/pos-receipt.d.ts +39 -0
  140. package/src/lib/components/console/pos-ops/pos-receipt.js +182 -0
  141. package/src/lib/components/console/pos-ops/pos-receipt.js.map +1 -0
  142. package/src/lib/components/console/pos-ops/pos-return-dialog.component.d.ts +40 -0
  143. package/src/lib/components/console/pos-ops/pos-return-dialog.component.js +465 -0
  144. package/src/lib/components/console/pos-ops/pos-return-dialog.component.js.map +1 -0
  145. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.d.ts +29 -0
  146. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js +253 -0
  147. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js.map +1 -0
  148. package/src/lib/components/console/pos-ops/pos-shift-panel.component.d.ts +34 -0
  149. package/src/lib/components/console/pos-ops/pos-shift-panel.component.js +494 -0
  150. package/src/lib/components/console/pos-ops/pos-shift-panel.component.js.map +1 -0
  151. package/src/lib/components/console/pos-ops/pos-shift-report.component.d.ts +37 -0
  152. package/src/lib/components/console/pos-ops/pos-shift-report.component.js +102 -0
  153. package/src/lib/components/console/pos-ops/pos-shift-report.component.js.map +1 -0
  154. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.d.ts +30 -0
  155. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.js +277 -0
  156. package/src/lib/components/console/pos-ops/pos-staff-pins-card.component.js.map +1 -0
  157. package/src/lib/components/console/pos-ops/register-ops.d.ts +28 -0
  158. package/src/lib/components/console/pos-ops/register-ops.js +28 -0
  159. package/src/lib/components/console/pos-ops/register-ops.js.map +1 -0
  160. package/src/lib/components/console/pos-ops/use-pos-cashier.d.ts +46 -0
  161. package/src/lib/components/console/pos-ops/use-pos-cashier.js +128 -0
  162. package/src/lib/components/console/pos-ops/use-pos-cashier.js.map +1 -0
  163. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.d.ts +36 -0
  164. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.js +64 -0
  165. package/src/lib/components/console/pos-ops/use-pos-sale-receipt.js.map +1 -0
  166. package/src/lib/components/console/pos-page.component.d.ts +13 -5
  167. package/src/lib/components/console/pos-page.component.js +756 -654
  168. package/src/lib/components/console/pos-page.component.js.map +1 -1
  169. package/src/lib/components/console/pos-zones.d.ts +23 -0
  170. package/src/lib/components/console/pos-zones.js +31 -0
  171. package/src/lib/components/console/pos-zones.js.map +1 -0
  172. package/src/lib/components/console/product-editor-dialog.component.js +61 -71
  173. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  174. package/src/lib/components/console/product-labels-dialog.component.d.ts +13 -0
  175. package/src/lib/components/console/product-labels-dialog.component.js +197 -0
  176. package/src/lib/components/console/product-labels-dialog.component.js.map +1 -0
  177. package/src/lib/components/console/product-register-fields.component.d.ts +19 -0
  178. package/src/lib/components/console/product-register-fields.component.js +241 -0
  179. package/src/lib/components/console/product-register-fields.component.js.map +1 -0
  180. package/src/lib/components/console/product-zones.d.ts +44 -0
  181. package/src/lib/components/console/product-zones.js.map +1 -1
  182. package/src/lib/components/console/products-hub-card.component.js +23 -20
  183. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  184. package/src/lib/components/console/register-hardware-card.component.d.ts +33 -0
  185. package/src/lib/components/console/register-hardware-card.component.js +826 -0
  186. package/src/lib/components/console/register-hardware-card.component.js.map +1 -0
  187. package/src/lib/components/console/registers-card.component.js +24 -5
  188. package/src/lib/components/console/registers-card.component.js.map +1 -1
  189. package/src/lib/components/console/return-actions.d.ts +38 -0
  190. package/src/lib/components/console/return-actions.js +76 -0
  191. package/src/lib/components/console/return-actions.js.map +1 -0
  192. package/src/lib/components/console/return-detail-dialog.component.d.ts +34 -0
  193. package/src/lib/components/console/return-detail-dialog.component.js +718 -0
  194. package/src/lib/components/console/return-detail-dialog.component.js.map +1 -0
  195. package/src/lib/components/console/return-settings-card.component.d.ts +34 -0
  196. package/src/lib/components/console/return-settings-card.component.js +195 -0
  197. package/src/lib/components/console/return-settings-card.component.js.map +1 -0
  198. package/src/lib/components/console/return-zones.d.ts +87 -0
  199. package/src/lib/components/console/return-zones.js +31 -0
  200. package/src/lib/components/console/return-zones.js.map +1 -0
  201. package/src/lib/components/console/returns-card.component.d.ts +45 -0
  202. package/src/lib/components/console/returns-card.component.js +159 -0
  203. package/src/lib/components/console/returns-card.component.js.map +1 -0
  204. package/src/lib/components/console/shipping-settings-card.component.js +161 -5
  205. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  206. package/src/lib/components/console/shippingeasy-card.component.d.ts +59 -0
  207. package/src/lib/components/console/shippingeasy-card.component.js +378 -0
  208. package/src/lib/components/console/shippingeasy-card.component.js.map +1 -0
  209. package/src/lib/components/console/shipstation-card.component.d.ts +35 -0
  210. package/src/lib/components/console/shipstation-card.component.js +345 -0
  211. package/src/lib/components/console/shipstation-card.component.js.map +1 -0
  212. package/src/lib/components/console/start-return-dialog.component.d.ts +40 -0
  213. package/src/lib/components/console/start-return-dialog.component.js +243 -0
  214. package/src/lib/components/console/start-return-dialog.component.js.map +1 -0
  215. package/src/lib/components/console/stock-movements-card.component.js +2 -1
  216. package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
  217. package/src/lib/components/console/store-settings-card.component.js +2 -66
  218. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  219. package/src/lib/components/console/store-zones.d.ts +42 -0
  220. package/src/lib/components/console/store-zones.js +39 -0
  221. package/src/lib/components/console/store-zones.js.map +1 -0
  222. package/src/lib/components/console/storefront-tax-summary-card.component.js +1 -0
  223. package/src/lib/components/console/storefront-tax-summary-card.component.js.map +1 -1
  224. package/src/lib/components/order-status.d.ts +36 -0
  225. package/src/lib/components/order-status.js +502 -0
  226. package/src/lib/components/order-status.js.map +1 -0
  227. package/src/lib/components/product-detail.js +41 -2
  228. package/src/lib/components/product-detail.js.map +1 -1
  229. package/src/lib/components/return-request.d.ts +32 -0
  230. package/src/lib/components/return-request.js +576 -0
  231. package/src/lib/components/return-request.js.map +1 -0
  232. package/src/lib/components/storefront-payment-appearance.d.ts +32 -0
  233. package/src/lib/components/storefront-payment-appearance.js +114 -0
  234. package/src/lib/components/storefront-payment-appearance.js.map +1 -0
  235. package/src/lib/components/storefront-payment-element.d.ts +57 -1
  236. package/src/lib/components/storefront-payment-element.js +332 -33
  237. package/src/lib/components/storefront-payment-element.js.map +1 -1
  238. package/src/lib/constants/order-status.d.ts +22 -0
  239. package/src/lib/constants/order-status.js +22 -0
  240. package/src/lib/constants/order-status.js.map +1 -0
  241. package/src/lib/constants/return-request.d.ts +27 -0
  242. package/src/lib/constants/return-request.js +32 -0
  243. package/src/lib/constants/return-request.js.map +1 -0
  244. package/src/lib/constants/stock-movement-query.js +2 -1
  245. package/src/lib/constants/stock-movement-query.js.map +1 -1
  246. package/src/lib/declarations.console-server.js +9 -0
  247. package/src/lib/declarations.console-server.js.map +1 -1
  248. package/src/lib/declarations.server.d.ts +2 -1
  249. package/src/lib/declarations.server.js +68 -1
  250. package/src/lib/declarations.server.js.map +1 -1
  251. package/src/lib/model/buyer-notifications.d.ts +59 -0
  252. package/src/lib/model/buyer-notifications.js +97 -0
  253. package/src/lib/model/buyer-notifications.js.map +1 -0
  254. package/src/lib/model/commerce-orders.d.ts +171 -2
  255. package/src/lib/model/commerce-orders.js +26 -16
  256. package/src/lib/model/commerce-orders.js.map +1 -1
  257. package/src/lib/model/commerce-payment-methods.d.ts +146 -0
  258. package/src/lib/model/commerce-payment-methods.js +247 -0
  259. package/src/lib/model/commerce-payment-methods.js.map +1 -0
  260. package/src/lib/model/commerce-pos-ops.d.ts +437 -0
  261. package/src/lib/model/commerce-pos-ops.js +721 -0
  262. package/src/lib/model/commerce-pos-ops.js.map +1 -0
  263. package/src/lib/model/commerce-pos.d.ts +263 -0
  264. package/src/lib/model/commerce-pos.js +375 -0
  265. package/src/lib/model/commerce-pos.js.map +1 -0
  266. package/src/lib/model/commerce-printers.d.ts +211 -0
  267. package/src/lib/model/commerce-printers.js +181 -0
  268. package/src/lib/model/commerce-printers.js.map +1 -0
  269. package/src/lib/model/commerce-receipt.d.ts +97 -0
  270. package/src/lib/model/commerce-receipt.js +180 -0
  271. package/src/lib/model/commerce-receipt.js.map +1 -0
  272. package/src/lib/model/commerce-returns.d.ts +207 -0
  273. package/src/lib/model/commerce-returns.js +300 -0
  274. package/src/lib/model/commerce-returns.js.map +1 -0
  275. package/src/lib/model/commerce-shipping.d.ts +44 -1
  276. package/src/lib/model/commerce-shipping.js +53 -9
  277. package/src/lib/model/commerce-shipping.js.map +1 -1
  278. package/src/lib/model/commerce-tax-engine.d.ts +90 -0
  279. package/src/lib/model/commerce-tax-engine.js +129 -0
  280. package/src/lib/model/commerce-tax-engine.js.map +1 -0
  281. package/src/lib/model/commerce.d.ts +91 -2
  282. package/src/lib/model/commerce.js +89 -1
  283. package/src/lib/model/commerce.js.map +1 -1
  284. package/src/lib/model/index.d.ts +16 -0
  285. package/src/lib/model/index.js +16 -0
  286. package/src/lib/model/index.js.map +1 -1
  287. package/src/lib/model/order-events.d.ts +154 -0
  288. package/src/lib/model/order-events.js +153 -0
  289. package/src/lib/model/order-events.js.map +1 -0
  290. package/src/lib/model/order-fulfillment.d.ts +117 -0
  291. package/src/lib/model/order-fulfillment.js +217 -0
  292. package/src/lib/model/order-fulfillment.js.map +1 -0
  293. package/src/lib/model/order-history.d.ts +58 -0
  294. package/src/lib/model/order-history.js +22 -0
  295. package/src/lib/model/order-history.js.map +1 -0
  296. package/src/lib/model/order-list-fields.d.ts +9 -1
  297. package/src/lib/model/order-list-fields.js +7 -1
  298. package/src/lib/model/order-list-fields.js.map +1 -1
  299. package/src/lib/model/order-shipping-export.d.ts +91 -0
  300. package/src/lib/model/order-shipping-export.js +192 -0
  301. package/src/lib/model/order-shipping-export.js.map +1 -0
  302. package/src/lib/model/order-status-view.d.ts +103 -0
  303. package/src/lib/model/order-status-view.js +156 -0
  304. package/src/lib/model/order-status-view.js.map +1 -0
  305. package/src/lib/model/order-webhooks.d.ts +142 -0
  306. package/src/lib/model/order-webhooks.js +91 -0
  307. package/src/lib/model/order-webhooks.js.map +1 -0
  308. package/src/lib/model/product-channel.d.ts +56 -0
  309. package/src/lib/model/product-channel.js +86 -0
  310. package/src/lib/model/product-channel.js.map +1 -0
  311. package/src/lib/model/product-modifiers.d.ts +80 -0
  312. package/src/lib/model/product-modifiers.js +140 -0
  313. package/src/lib/model/product-modifiers.js.map +1 -0
  314. package/src/lib/model/product-write.d.ts +186 -0
  315. package/src/lib/model/product-write.js +116 -0
  316. package/src/lib/model/product-write.js.map +1 -0
  317. package/src/lib/model/shippingeasy.d.ts +94 -0
  318. package/src/lib/model/shippingeasy.js +267 -0
  319. package/src/lib/model/shippingeasy.js.map +1 -0
  320. package/src/lib/model/shipstation.d.ts +125 -0
  321. package/src/lib/model/shipstation.js +399 -0
  322. package/src/lib/model/shipstation.js.map +1 -0
  323. package/src/lib/model/smart-collection-reads.d.ts +32 -0
  324. package/src/lib/model/smart-collection-reads.js +63 -0
  325. package/src/lib/model/smart-collection-reads.js.map +1 -0
  326. package/src/lib/model/tracking-url.d.ts +74 -0
  327. package/src/lib/model/tracking-url.js +159 -0
  328. package/src/lib/model/tracking-url.js.map +1 -0
  329. package/src/lib/plugin-config.d.ts +13 -0
  330. package/src/lib/plugin-config.js +77 -5
  331. package/src/lib/plugin-config.js.map +1 -1
  332. package/src/lib/plugin.js +26 -0
  333. package/src/lib/plugin.js.map +1 -1
  334. package/src/lib/pos-ops-config.d.ts +39 -0
  335. package/src/lib/pos-ops-config.js +88 -0
  336. package/src/lib/pos-ops-config.js.map +1 -0
  337. package/src/lib/printing/print-document.d.ts +106 -0
  338. package/src/lib/printing/print-document.js +464 -0
  339. package/src/lib/printing/print-document.js.map +1 -0
  340. package/src/lib/printing/product-labels.d.ts +58 -0
  341. package/src/lib/printing/product-labels.js +116 -0
  342. package/src/lib/printing/product-labels.js.map +1 -0
  343. package/src/lib/printing/render-epson.d.ts +57 -0
  344. package/src/lib/printing/render-epson.js +135 -0
  345. package/src/lib/printing/render-epson.js.map +1 -0
  346. package/src/lib/printing/render-star.d.ts +45 -0
  347. package/src/lib/printing/render-star.js +100 -0
  348. package/src/lib/printing/render-star.js.map +1 -0
  349. package/src/lib/printing/render-text.d.ts +25 -0
  350. package/src/lib/printing/render-text.js +53 -0
  351. package/src/lib/printing/render-text.js.map +1 -0
  352. package/src/lib/server/api-v1/openapi.js +27 -4
  353. package/src/lib/server/api-v1/openapi.js.map +1 -1
  354. package/src/lib/server/api-v1/order-view.d.ts +67 -0
  355. package/src/lib/server/api-v1/order-view.js +120 -0
  356. package/src/lib/server/api-v1/order-view.js.map +1 -0
  357. package/src/lib/server/api-v1/orders-and-products.js +58 -65
  358. package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
  359. package/src/lib/server/billing-webhook.js +135 -28
  360. package/src/lib/server/billing-webhook.js.map +1 -1
  361. package/src/lib/server/cancel-order.js +29 -0
  362. package/src/lib/server/cancel-order.js.map +1 -1
  363. package/src/lib/server/carrier-rates-availability.d.ts +26 -0
  364. package/src/lib/server/carrier-rates-availability.js +76 -0
  365. package/src/lib/server/carrier-rates-availability.js.map +1 -0
  366. package/src/lib/server/carrier-shipping.d.ts +84 -0
  367. package/src/lib/server/carrier-shipping.js +135 -0
  368. package/src/lib/server/carrier-shipping.js.map +1 -0
  369. package/src/lib/server/cart-checkout.d.ts +2 -0
  370. package/src/lib/server/cart-checkout.js +226 -22
  371. package/src/lib/server/cart-checkout.js.map +1 -1
  372. package/src/lib/server/channel-order-updates.d.ts +50 -0
  373. package/src/lib/server/channel-order-updates.js +290 -0
  374. package/src/lib/server/channel-order-updates.js.map +1 -0
  375. package/src/lib/server/channel-orders.d.ts +85 -0
  376. package/src/lib/server/channel-orders.js +543 -0
  377. package/src/lib/server/channel-orders.js.map +1 -0
  378. package/src/lib/server/checkout-extras.d.ts +64 -0
  379. package/src/lib/server/checkout-extras.js +157 -0
  380. package/src/lib/server/checkout-extras.js.map +1 -0
  381. package/src/lib/server/{feed.d.ts → checkout-status.d.ts} +2 -7
  382. package/src/lib/server/checkout-status.js +111 -0
  383. package/src/lib/server/checkout-status.js.map +1 -0
  384. package/src/lib/server/checkout.js +86 -9
  385. package/src/lib/server/checkout.js.map +1 -1
  386. package/src/lib/server/draft-order.js +34 -5
  387. package/src/lib/server/draft-order.js.map +1 -1
  388. package/src/lib/server/fulfill-order.d.ts +127 -10
  389. package/src/lib/server/fulfill-order.js +451 -49
  390. package/src/lib/server/fulfill-order.js.map +1 -1
  391. package/src/lib/server/legacy-feed.d.ts +28 -0
  392. package/src/lib/server/legacy-feed.js +52 -0
  393. package/src/lib/server/legacy-feed.js.map +1 -0
  394. package/src/lib/server/native-checkout.d.ts +34 -15
  395. package/src/lib/server/native-checkout.js +32 -17
  396. package/src/lib/server/native-checkout.js.map +1 -1
  397. package/src/lib/server/order-event-host-emit.d.ts +23 -0
  398. package/src/lib/server/order-event-host-emit.js +30 -0
  399. package/src/lib/server/order-event-host-emit.js.map +1 -0
  400. package/src/lib/server/order-event-triggers.d.ts +37 -0
  401. package/src/lib/server/order-event-triggers.js +119 -0
  402. package/src/lib/server/order-event-triggers.js.map +1 -0
  403. package/src/lib/server/order-events.d.ts +62 -0
  404. package/src/lib/server/order-events.js +109 -0
  405. package/src/lib/server/order-events.js.map +1 -0
  406. package/src/lib/server/order-history.d.ts +23 -0
  407. package/src/lib/server/order-history.js +65 -0
  408. package/src/lib/server/order-history.js.map +1 -0
  409. package/src/lib/server/order-notifications.d.ts +185 -0
  410. package/src/lib/server/order-notifications.js +567 -0
  411. package/src/lib/server/order-notifications.js.map +1 -0
  412. package/src/lib/server/order-receipt-send.d.ts +39 -0
  413. package/src/lib/server/order-receipt-send.js +151 -0
  414. package/src/lib/server/order-receipt-send.js.map +1 -0
  415. package/src/lib/server/order-status-token.d.ts +31 -0
  416. package/src/lib/server/order-status-token.js +75 -0
  417. package/src/lib/server/order-status-token.js.map +1 -0
  418. package/src/lib/server/order-status.d.ts +58 -0
  419. package/src/lib/server/order-status.js +141 -0
  420. package/src/lib/server/order-status.js.map +1 -0
  421. package/src/lib/server/order-webhooks.d.ts +108 -0
  422. package/src/lib/server/order-webhooks.js +622 -0
  423. package/src/lib/server/order-webhooks.js.map +1 -0
  424. package/src/lib/server/orders-shipping-prepare.d.ts +26 -0
  425. package/src/lib/server/orders-shipping-prepare.js +121 -0
  426. package/src/lib/server/orders-shipping-prepare.js.map +1 -0
  427. package/src/lib/server/payment-method-domains.d.ts +209 -0
  428. package/src/lib/server/payment-method-domains.js +444 -0
  429. package/src/lib/server/payment-method-domains.js.map +1 -0
  430. package/src/lib/server/payment-methods.d.ts +77 -0
  431. package/src/lib/server/payment-methods.js +284 -0
  432. package/src/lib/server/payment-methods.js.map +1 -0
  433. package/src/lib/server/pos-auth.d.ts +50 -0
  434. package/src/lib/server/pos-auth.js +121 -0
  435. package/src/lib/server/pos-auth.js.map +1 -0
  436. package/src/lib/server/pos-customer.d.ts +49 -0
  437. package/src/lib/server/pos-customer.js +257 -0
  438. package/src/lib/server/pos-customer.js.map +1 -0
  439. package/src/lib/server/pos-display.d.ts +57 -0
  440. package/src/lib/server/pos-display.js +419 -0
  441. package/src/lib/server/pos-display.js.map +1 -0
  442. package/src/lib/server/pos-fee-month.d.ts +34 -0
  443. package/src/lib/server/pos-fee-month.js +36 -0
  444. package/src/lib/server/pos-fee-month.js.map +1 -0
  445. package/src/lib/server/pos-ops-gate.d.ts +161 -0
  446. package/src/lib/server/pos-ops-gate.js +295 -0
  447. package/src/lib/server/pos-ops-gate.js.map +1 -0
  448. package/src/lib/server/pos-ops-routes.d.ts +22 -0
  449. package/src/lib/server/pos-ops-routes.js +36 -0
  450. package/src/lib/server/pos-ops-routes.js.map +1 -0
  451. package/src/lib/server/pos-order.d.ts +1 -18
  452. package/src/lib/server/pos-order.js +222 -42
  453. package/src/lib/server/pos-order.js.map +1 -1
  454. package/src/lib/server/pos-payment.d.ts +39 -0
  455. package/src/lib/server/pos-payment.js +922 -0
  456. package/src/lib/server/pos-payment.js.map +1 -0
  457. package/src/lib/server/pos-print.d.ts +82 -0
  458. package/src/lib/server/pos-print.js +193 -0
  459. package/src/lib/server/pos-print.js.map +1 -0
  460. package/src/lib/server/pos-readers.d.ts +27 -0
  461. package/src/lib/server/pos-readers.js +276 -0
  462. package/src/lib/server/pos-readers.js.map +1 -0
  463. package/src/lib/server/pos-refund-authority.d.ts +60 -0
  464. package/src/lib/server/pos-refund-authority.js +72 -0
  465. package/src/lib/server/pos-refund-authority.js.map +1 -0
  466. package/src/lib/server/pos-return.d.ts +58 -0
  467. package/src/lib/server/pos-return.js +891 -0
  468. package/src/lib/server/pos-return.js.map +1 -0
  469. package/src/lib/server/pos-sale-stamp.d.ts +66 -0
  470. package/src/lib/server/pos-sale-stamp.js +84 -0
  471. package/src/lib/server/pos-sale-stamp.js.map +1 -0
  472. package/src/lib/server/pos-sale.d.ts +170 -0
  473. package/src/lib/server/pos-sale.js +461 -0
  474. package/src/lib/server/pos-sale.js.map +1 -0
  475. package/src/lib/server/pos-shift.d.ts +45 -0
  476. package/src/lib/server/pos-shift.js +484 -0
  477. package/src/lib/server/pos-shift.js.map +1 -0
  478. package/src/lib/server/pos-staff-pin.d.ts +26 -0
  479. package/src/lib/server/pos-staff-pin.js +339 -0
  480. package/src/lib/server/pos-staff-pin.js.map +1 -0
  481. package/src/lib/server/pos-stripe.d.ts +91 -0
  482. package/src/lib/server/pos-stripe.js +129 -0
  483. package/src/lib/server/pos-stripe.js.map +1 -0
  484. package/src/lib/server/pos-terminal-connection-token.d.ts +48 -0
  485. package/src/lib/server/pos-terminal-connection-token.js +166 -0
  486. package/src/lib/server/pos-terminal-connection-token.js.map +1 -0
  487. package/src/lib/server/pos-terminal.d.ts +218 -0
  488. package/src/lib/server/pos-terminal.js +1014 -0
  489. package/src/lib/server/pos-terminal.js.map +1 -0
  490. package/src/lib/server/print-queue.d.ts +124 -0
  491. package/src/lib/server/print-queue.js +301 -0
  492. package/src/lib/server/print-queue.js.map +1 -0
  493. package/src/lib/server/printer-poll.d.ts +75 -0
  494. package/src/lib/server/printer-poll.js +325 -0
  495. package/src/lib/server/printer-poll.js.map +1 -0
  496. package/src/lib/server/printer-secret.d.ts +39 -0
  497. package/src/lib/server/printer-secret.js +56 -0
  498. package/src/lib/server/printer-secret.js.map +1 -0
  499. package/src/lib/server/printers.d.ts +114 -0
  500. package/src/lib/server/printers.js +546 -0
  501. package/src/lib/server/printers.js.map +1 -0
  502. package/src/lib/server/product-catalog.d.ts +42 -0
  503. package/src/lib/server/product-catalog.js +309 -0
  504. package/src/lib/server/product-catalog.js.map +1 -0
  505. package/src/lib/server/product-drafts.d.ts +5 -1
  506. package/src/lib/server/product-drafts.js +3 -3
  507. package/src/lib/server/product-drafts.js.map +1 -1
  508. package/src/lib/server/product-writer.d.ts +19 -0
  509. package/src/lib/server/product-writer.js +261 -0
  510. package/src/lib/server/product-writer.js.map +1 -0
  511. package/src/lib/server/products-write.d.ts +61 -0
  512. package/src/lib/server/products-write.js +375 -0
  513. package/src/lib/server/products-write.js.map +1 -0
  514. package/src/lib/server/refund.js +110 -45
  515. package/src/lib/server/refund.js.map +1 -1
  516. package/src/lib/server/reserve.js +2 -0
  517. package/src/lib/server/reserve.js.map +1 -1
  518. package/src/lib/server/return-status-action.d.ts +37 -0
  519. package/src/lib/server/return-status-action.js +57 -0
  520. package/src/lib/server/return-status-action.js.map +1 -0
  521. package/src/lib/server/returns.d.ts +119 -0
  522. package/src/lib/server/returns.js +938 -0
  523. package/src/lib/server/returns.js.map +1 -0
  524. package/src/lib/server/shipment-records.d.ts +36 -0
  525. package/src/lib/server/shipment-records.js +289 -0
  526. package/src/lib/server/shipment-records.js.map +1 -0
  527. package/src/lib/server/shipping-connector-gates.d.ts +40 -0
  528. package/src/lib/server/shipping-connector-gates.js +97 -0
  529. package/src/lib/server/shipping-connector-gates.js.map +1 -0
  530. package/src/lib/server/shipping-connectors.d.ts +29 -0
  531. package/src/lib/server/shipping-connectors.js +236 -0
  532. package/src/lib/server/shipping-connectors.js.map +1 -0
  533. package/src/lib/server/shippingeasy.d.ts +238 -0
  534. package/src/lib/server/shippingeasy.js +787 -0
  535. package/src/lib/server/shippingeasy.js.map +1 -0
  536. package/src/lib/server/shipstation.d.ts +129 -0
  537. package/src/lib/server/shipstation.js +483 -0
  538. package/src/lib/server/shipstation.js.map +1 -0
  539. package/src/lib/server/site-page-resolver.d.ts +5 -0
  540. package/src/lib/server/site-page-resolver.js +156 -1
  541. package/src/lib/server/site-page-resolver.js.map +1 -1
  542. package/src/lib/server/stock-levels.d.ts +21 -0
  543. package/src/lib/server/stock-levels.js +263 -0
  544. package/src/lib/server/stock-levels.js.map +1 -0
  545. package/src/lib/server/stripe-refund.d.ts +47 -0
  546. package/src/lib/server/stripe-refund.js +87 -0
  547. package/src/lib/server/stripe-refund.js.map +1 -0
  548. package/src/lib/server/supplier-update.js +46 -5
  549. package/src/lib/server/supplier-update.js.map +1 -1
  550. package/src/lib/server/tax-engine-quote.d.ts +47 -0
  551. package/src/lib/server/tax-engine-quote.js +105 -0
  552. package/src/lib/server/tax-engine-quote.js.map +1 -0
  553. package/src/lib/server.js +143 -2
  554. package/src/lib/server.js.map +1 -1
  555. package/src/lib/site.js +12 -0
  556. package/src/lib/site.js.map +1 -1
  557. package/src/lib/subprocessors.d.ts +26 -0
  558. package/src/lib/subprocessors.js +50 -0
  559. package/src/lib/subprocessors.js.map +1 -0
  560. package/src/lib/tenant-emails.js +461 -3
  561. package/src/lib/tenant-emails.js.map +1 -1
  562. package/src/lib/testing/fake-firestore.d.ts +45 -0
  563. package/src/lib/testing/fake-firestore.js +189 -0
  564. package/src/lib/testing/fake-firestore.js.map +1 -0
  565. package/src/lib/testing/memory-firestore.d.ts +136 -0
  566. package/src/lib/testing/memory-firestore.js +282 -0
  567. package/src/lib/testing/memory-firestore.js.map +1 -0
  568. package/src/lib/testing/pos-ops-harness.d.ts +50 -0
  569. package/src/lib/testing/pos-ops-harness.js +184 -0
  570. package/src/lib/testing/pos-ops-harness.js.map +1 -0
  571. package/src/lib/testing/pos-ops-memory-firestore.d.ts +55 -0
  572. package/src/lib/testing/pos-ops-memory-firestore.js +376 -0
  573. package/src/lib/testing/pos-ops-memory-firestore.js.map +1 -0
  574. package/src/lib/transfer/products.server.d.ts +5 -0
  575. package/src/lib/transfer/products.server.js +2 -2
  576. package/src/lib/transfer/products.server.js.map +1 -1
  577. package/src/lib/transfer/records-transfer.d.ts +11 -1
  578. package/src/lib/transfer/records-transfer.js +127 -5
  579. package/src/lib/transfer/records-transfer.js.map +1 -1
  580. package/src/lib/transfer/records.server.d.ts +9 -2
  581. package/src/lib/transfer/records.server.js +58 -7
  582. package/src/lib/transfer/records.server.js.map +1 -1
  583. package/src/lib/transfer/register-transfer-resources.js +40 -1
  584. package/src/lib/transfer/register-transfer-resources.js.map +1 -1
  585. package/src/lib/transfer/register-transfer-ui.js +4 -1
  586. package/src/lib/transfer/register-transfer-ui.js.map +1 -1
  587. package/src/lib/transfer/shipping-presets.d.ts +23 -0
  588. package/src/lib/transfer/shipping-presets.js +156 -0
  589. package/src/lib/transfer/shipping-presets.js.map +1 -0
  590. package/src/lib/transfer/tracking-transfer.d.ts +101 -0
  591. package/src/lib/transfer/tracking-transfer.js +546 -0
  592. package/src/lib/transfer/tracking-transfer.js.map +1 -0
  593. package/src/lib/transfer/tracking.server.d.ts +37 -0
  594. package/src/lib/transfer/tracking.server.js +393 -0
  595. package/src/lib/transfer/tracking.server.js.map +1 -0
  596. package/src/lib/transfer/transfer-keys.d.ts +2 -1
  597. package/src/lib/transfer/transfer-keys.js +6 -2
  598. package/src/lib/transfer/transfer-keys.js.map +1 -1
  599. package/src/lib/utils/code128.d.ts +37 -0
  600. package/src/lib/utils/code128.js +199 -0
  601. package/src/lib/utils/code128.js.map +1 -0
  602. package/src/lib/utils/order-invoice.d.ts +55 -0
  603. package/src/lib/utils/order-invoice.js +127 -0
  604. package/src/lib/utils/order-invoice.js.map +1 -0
  605. package/src/lib/utils/use-checkout-return-notice.d.ts +34 -0
  606. package/src/lib/utils/use-checkout-return-notice.js +78 -0
  607. package/src/lib/utils/use-checkout-return-notice.js.map +1 -0
  608. package/src/lib/server/feed.js +0 -69
  609. package/src/lib/server/feed.js.map +0 -1
@@ -14,7 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { nameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
17
+ */ import { modifierGroupsProblem } from "./product-modifiers.js";
18
+ import { nameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
19
+ import { draftProductChannelFacts } from "./product-channel.js";
18
20
  /**
19
21
  * Commerce catalog v1 (AGL-276): products with options/variants,
20
22
  * hierarchical categories, tags, and manual/smart collections. Pure
@@ -41,6 +43,78 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
41
43
  * subscription is still alive. A constant cannot express any of that.
42
44
  * `commerce-fee-single-source.spec.ts` fails the build if one comes back.
43
45
  */ /** Product price ceiling (whole USD). */ export const COMMERCE_MAX_PRICE_USD = 10000;
46
+ /** A product's packed size for one unit, when all three sides are known. */ export function productParcelDimensions(product) {
47
+ const facts = product == null ? void 0 : product.shipping;
48
+ const side = (value)=>{
49
+ const number = Number(value);
50
+ return Number.isFinite(number) && number > 0 ? Math.min(number, 300) : 0;
51
+ };
52
+ const lengthCm = side(facts == null ? void 0 : facts.lengthCm);
53
+ const widthCm = side(facts == null ? void 0 : facts.widthCm);
54
+ const heightCm = side(facts == null ? void 0 : facts.heightCm);
55
+ return lengthCm && widthCm && heightCm ? {
56
+ lengthCm,
57
+ widthCm,
58
+ heightCm
59
+ } : undefined;
60
+ }
61
+ /**
62
+ * Shipping facts as the product editor stages them, keystroke by keystroke
63
+ * (AGL-3647): {@link normalizeProductShippingFacts}, except that a country
64
+ * of origin being typed keeps its first letter. The editor runs this on
65
+ * every keystroke, and the strict form drops anything short of two letters,
66
+ * so the field could never be typed into. Readers normalize what is stored.
67
+ */ export function draftProductShippingFacts(value) {
68
+ var _ref;
69
+ const facts = normalizeProductShippingFacts(value);
70
+ const typed = String((_ref = value == null ? void 0 : value['originCountry']) != null ? _ref : '').trim().toUpperCase();
71
+ if (/^[A-Z]$/.test(typed)) return _extends({}, facts, {
72
+ originCountry: typed
73
+ });
74
+ return facts;
75
+ }
76
+ /** A stored product's shipping facts made safe (AGL-3612); never throws. */ export function normalizeProductShippingFacts(value) {
77
+ var _raw_hsCode, _raw_originCountry;
78
+ if (!value || typeof value !== 'object') return undefined;
79
+ const raw = value;
80
+ const facts = {};
81
+ for (const side of [
82
+ 'lengthCm',
83
+ 'widthCm',
84
+ 'heightCm'
85
+ ]){
86
+ const number = Number(raw[side]);
87
+ if (raw[side] !== null && raw[side] !== undefined && Number.isFinite(number) && number > 0) {
88
+ facts[side] = Math.min(Math.round(number * 10) / 10, 300);
89
+ }
90
+ }
91
+ const hsCode = String((_raw_hsCode = raw['hsCode']) != null ? _raw_hsCode : '').replace(/[^0-9.]/g, '').slice(0, 14);
92
+ if (hsCode) facts.hsCode = hsCode;
93
+ const originCountry = String((_raw_originCountry = raw['originCountry']) != null ? _raw_originCountry : '').trim().toUpperCase();
94
+ if (/^[A-Z]{2}$/.test(originCountry)) facts.originCountry = originCountry;
95
+ return Object.keys(facts).length ? facts : undefined;
96
+ }
97
+ /** A stored location's postal address made safe (AGL-3612); never throws. */ export function normalizePostalAddress(value) {
98
+ var _raw_country;
99
+ if (!value || typeof value !== 'object') return undefined;
100
+ const raw = value;
101
+ const address = {};
102
+ for (const field of [
103
+ 'line1',
104
+ 'line2',
105
+ 'city',
106
+ 'state',
107
+ 'postalCode',
108
+ 'phone'
109
+ ]){
110
+ var _raw_field;
111
+ const text = String((_raw_field = raw[field]) != null ? _raw_field : '').trim().slice(0, 120);
112
+ if (text) address[field] = text;
113
+ }
114
+ const country = String((_raw_country = raw['country']) != null ? _raw_country : '').trim().toUpperCase();
115
+ if (/^[A-Z]{2}$/.test(country)) address.country = country;
116
+ return Object.keys(address).length ? address : undefined;
117
+ }
44
118
  /**
45
119
  * The register ids within the plan's `posRegisters` cap (AGL-482), ranked
46
120
  * by creation order — the same ordering `pos-order.ts` enforces at sale
@@ -298,6 +372,18 @@ export const COMMERCE_SLUG_MAX_LENGTH = 80;
298
372
  var _product_options;
299
373
  var _values_optionNames;
300
374
  const patch = {};
375
+ if (values.shipping && typeof values.shipping === 'object') {
376
+ var _draftProductShippingFacts;
377
+ // Stored whole, never `undefined`: the editor's save is a full `setDoc`,
378
+ // which refuses an undefined field. Nothing known is an empty map.
379
+ patch.shipping = (_draftProductShippingFacts = draftProductShippingFacts(_extends({}, product.shipping, values.shipping))) != null ? _draftProductShippingFacts : {};
380
+ }
381
+ if (values.channel && typeof values.channel === 'object') {
382
+ var _draftProductChannelFacts;
383
+ // Stored whole, never `undefined`, for the same reason. Nothing entered
384
+ // is an empty map. Kept as typed: this runs on every keystroke.
385
+ patch.channel = (_draftProductChannelFacts = draftProductChannelFacts(_extends({}, product.channel, values.channel))) != null ? _draftProductChannelFacts : {};
386
+ }
301
387
  if (typeof values.description === 'string') patch.description = values.description;
302
388
  if (Array.isArray(values.tags)) {
303
389
  patch.tags = [
@@ -726,6 +812,8 @@ export function productCollectionIds(product, smartCollections) {
726
812
  if (new Set(options.map((option)=>option.name.trim())).size !== options.length) {
727
813
  return 'Each option needs its own name';
728
814
  }
815
+ const modifierProblem = modifierGroupsProblem(product.modifierGroups);
816
+ if (modifierProblem) return modifierProblem;
729
817
  const variants = (_product_variants = product.variants) != null ? _product_variants : [];
730
818
  if (variants.length === 0) return 'Products need at least one variant';
731
819
  if (variants.length > COMMERCE_MAX_VARIANTS) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce.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\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\n\n/**\n * Commerce catalog v1 (AGL-276): products with options/variants,\n * hierarchical categories, tags, and manual/smart collections. Pure\n * model + helpers — no I/O; the products hub and storefront APIs operate\n * over these shapes. Documents live under `hosts/{hostId}/products`,\n * `.../productCategories`, and `.../collections`; the legacy Commerce\n * Starter product doc (AGL-90: name/priceUsd/inventory) lifts into this\n * shape via `liftLegacyProduct`, so existing docs keep working.\n */\n\n/*\n * THERE IS NO STOREFRONT FEE CONSTANT, and that absence is load-bearing\n * (AGL-2295).\n *\n * `COMMERCE_PLATFORM_FEE_PERCENT = 2` lived here with ZERO call sites. It\n * asserted a flat 2% that agrees with the plan table for exactly one cell\n * (Starter, physical) and disagrees with the other fifteen — Starter digital\n * is 5%, Pro digital 3%, Business 2%, Scale 1%, and every physical rate above\n * Starter is 0%. Nothing was wrong while nothing read it; the cost was that\n * the next reader wiring it up would silently re-price every plan, and a\n * constant sitting in the model beside the types reads like the answer.\n *\n * The single source is `resolveTransactionFeePct(org, productType)` in\n * `plan-entitlements.ts`, resolved PER REQUEST from the org — because it\n * depends on the plan, on per-org staff overrides, and on whether the\n * subscription is still alive. A constant cannot express any of that.\n * `commerce-fee-single-source.spec.ts` fails the build if one comes back.\n */\n/** Product price ceiling (whole USD). */\nexport const COMMERCE_MAX_PRICE_USD = 10000\n\nexport type ProductType = 'physical' | 'digital' | 'service'\nexport type ProductStatus = 'draft' | 'active' | 'archived'\n\n/** One axis of variation, e.g. { name: 'Size', values: ['S','M','L'] }. */\nexport interface ProductOption {\n name: string\n values: string[]\n}\n\n/** A sellable configuration of a product (every product has ≥ 1). */\nexport interface ProductVariant {\n /** Stable id unique within the product (never reused after delete). */\n id: string\n /** Option selections keyed by option name; {} for the default variant. */\n options?: Record<string, string>\n sku?: string\n barcode?: string\n priceUsd: number\n /** Strike-through price; a sale badge shows when > priceUsd. */\n compareAtPriceUsd?: number\n weightGrams?: number\n /** null/undefined = untracked; 0 = sold out (matches AGL-96). */\n inventory?: number | null\n /**\n * Per-location stock (AGL-286); `inventory` stays the summed\n * denormalization. Absent = single default location.\n */\n inventoryByLocation?: Record<string, number>\n /** Media-library image URL shown when this variant is selected. */\n imageUrl?: string\n}\n\n/** `hosts/{hostId}/locations/{id}` doc (AGL-286). */\nexport interface InventoryLocation {\n name: string\n isDefault?: boolean\n address?: string\n}\n\n/**\n * `hosts/{hostId}/registers/{id}` doc (AGL-472): a named point-of-sale\n * register. Creation is capped by the plan's `posRegisters` quota (Pro 1,\n * Business 2, Advanced 5; raised by a per-org entitlement override for the\n * $89/mo add-on), enforced server-side by the resources route. Each POS\n * sale stamps its `registerId` so takings are attributable per register.\n */\nexport interface PosRegister {\n name: string\n /** Optional default inventory location this register sells from. */\n locationId?: string\n}\n\n/**\n * The register ids within the plan's `posRegisters` cap (AGL-482), ranked\n * by creation order — the same ordering `pos-order.ts` enforces at sale\n * time. Registers beyond the cap (e.g. after a Business→Pro downgrade) are\n * excluded so the console/POS can dim or hide them instead of surfacing a\n * checkout 403. `cap` of `Infinity` returns all.\n */\nexport function registersWithinCap(\n registers: Array<{ $id: string; createdAt?: any }>,\n cap: number,\n): Set<string> {\n const createdMs = (r: { createdAt?: any }) =>\n r.createdAt?.toMillis?.() ?? r.createdAt?.seconds ?? 0\n const ranked = [...registers].sort(\n (a, b) => createdMs(a) - createdMs(b) || a.$id.localeCompare(b.$id),\n )\n return new Set(ranked.slice(0, Math.max(0, cap)).map((r) => r.$id))\n}\n\n/**\n * `hosts/{hostId}/suppliers/{id}` doc (AGL-289): where dropshipped\n * order lines route on payment. Email and webhook are both optional but\n * one must be set for routing to do anything; webhook payloads are\n * HMAC-SHA256-signed with `webhookSecret`.\n */\nexport interface HostSupplier {\n name: string\n email?: string\n webhookUrl?: string\n webhookSecret?: string\n}\n\n/** `hosts/{hostId}/products/{id}` doc. */\nexport interface HostProduct {\n name: string\n /** Host-unique URL segment for /products/{slug}. */\n slug: string\n description?: string\n type: ProductType\n status: ProductStatus\n /** Ordered media-library image URLs (first = primary). */\n mediaUrls?: string[]\n categoryIds?: string[]\n /**\n * The SMART collections this product's rules answer (AGL-3321), written by\n * every writer — see `productCollectionIds`.\n */\n collectionIds?: string[]\n tags?: string[]\n options?: ProductOption[]\n variants: ProductVariant[]\n /** Per-product overrides for PDP meta tags (AGL-299 consumes). */\n seo?: { title?: string; description?: string; imageUrl?: string }\n /** Supplier for dropship routing (AGL-289). */\n supplierId?: string\n /** Out-of-stock behavior (AGL-281): deny (default) or allow backorder. */\n oversellPolicy?: 'deny' | 'backorder'\n /** Never taxed regardless of tax settings (AGL-285). */\n taxExempt?: boolean\n /**\n * Digital delivery (AGL-302): downloadable files for `digital`\n * products. Buyers always download the CURRENT list, so uploading a\n * new version re-delivers to everyone.\n */\n digitalFiles?: Array<{ url: string; fileName: string; version?: string }>\n /** Max download attempts per order line; absent = unlimited. */\n downloadLimit?: number\n /**\n * Recurring billing (AGL-303): buyers subscribe instead of buying\n * once; an active subscription is the entitlement content gating\n * checks (AGL-309).\n */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /**\n * Buyer-chosen billing (AGL-545): with `subscription` set, true lets\n * the buyer pick one-time OR subscribe on the PDP (default one-time);\n * absent/false keeps the product subscription-only.\n */\n subscriptionOptional?: boolean\n /** Members-only videos (AGL-315), streamed via short-TTL links. */\n gatedVideos?: Array<{ url: string; title?: string }>\n /** Manual related products for the upsell block (AGL-325). */\n relatedProductIds?: string[]\n /** Buying this issues a gift-card code for its price (AGL-322). */\n giftCard?: boolean\n /** Tracked-total at/below this alerts host managers (AGL-281). */\n lowStockThreshold?: number\n createdAtMs?: number\n updatedAtMs?: number\n deletedAt?: number | null\n /** Legacy Commerce Starter fields kept so old docs read back (AGL-90). */\n priceUsd?: number\n inventory?: number | null\n imageUrl?: string\n}\n\n/** `hosts/{hostId}/productCategories/{id}` doc (tree via parentId). */\nexport interface ProductCategory {\n name: string\n slug: string\n parentId?: string | null\n order?: number\n}\n\nexport type CollectionRuleField =\n | 'tag'\n | 'categoryId'\n | 'priceUsd'\n | 'name'\n | 'type'\nexport type CollectionRuleOp = 'eq' | 'neq' | 'lt' | 'gt' | 'contains'\n\nexport interface CollectionRule {\n field: CollectionRuleField\n op: CollectionRuleOp\n value: string | number\n}\n\n/** `hosts/{hostId}/collections/{id}` doc. */\nexport interface HostCollection {\n name: string\n slug: string\n description?: string\n mode: 'manual' | 'smart'\n /** Manual mode: explicit ordered membership. */\n productIds?: string[]\n /** Smart mode: rules evaluated over active products. */\n rules?: CollectionRule[]\n /** Smart mode: true = every rule must match (default), false = any. */\n matchAll?: boolean\n /** Media-library image URL for the collection card/landing hero. */\n imageUrl?: string\n order?: number\n}\n\n/**\n * Payment-provider seam (AGL-284): checkout/session creation goes\n * through a provider id so PayPal (etc.) can slot in without reworking\n * callers. Stripe is the only implementation today; store settings\n * (AGL-295) will carry the selection when a second provider exists.\n */\nexport type PaymentProviderId = 'stripe'\n\nexport interface PaymentCheckoutRequest {\n provider: PaymentProviderId\n hostId: string\n amountCents: number\n feeCents: number\n productName: string\n successUrl: string\n cancelUrl: string\n metadata?: Record<string, string>\n}\n\n/** Variant ceiling per product (Shopify parity). */\nexport const COMMERCE_MAX_VARIANTS = 100\nexport const COMMERCE_MAX_OPTIONS = 3\nexport const COMMERCE_MAX_OPTION_VALUES = 25\nexport const COMMERCE_SLUG_MAX_LENGTH = 80\n\n/** Lowercase-kebab slug from a product/category/collection name. */\nexport function commerceSlug(name: string): string {\n return String(name ?? '')\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, COMMERCE_SLUG_MAX_LENGTH)\n}\n\n/**\n * The search keys a product write carries, so the catalog can be searched by\n * the QUERY rather than by the rows a listener happened to fetch (AGL-2501).\n *\n * The hub lists `limit(500)`, and the search compared what that returned — so\n * a product past the window answered \"no products match\", which reads as the\n * product not existing rather than as the search not reaching it. Filtering\n * server-side needs fields Firestore can index, and neither of the two things\n * a merchant searches by is one:\n *\n * - A NAME needs case-insensitive contains, which Firestore has no operator\n * for. `nameSearchFields` denormalizes it into the three shapes that are\n * indexable — an exact key, word-prefix tokens for `array-contains`, and\n * the key reversed so \"ends with\" becomes a prefix range.\n * - A SKU lives inside `variants`, an array of OBJECTS, and Firestore cannot\n * query a field inside one. Flattened here into a top-level array so a SKU\n * is one `array-contains`.\n *\n * ⛔ A SKU therefore matches WHOLE, not as a substring: \"abc-123\" finds it and\n * \"123\" does not. That is the right way round for a SKU, which is a value\n * somebody copies rather than half-remembers — unlike a name, where the tokens\n * above buy word-prefix matching precisely because names are half-remembered.\n *\n * `barcodes` is the same flattening for the same reason, and it is the one the\n * register depends on: a keyboard-wedge scanner types the code and presses\n * Enter, so the lookup has to be exact and has to reach the whole catalog. A\n * scan is never a half-remembered value.\n *\n * Lower-cased because the translator lower-cases the typed query before it\n * builds the `array-contains`; stored and typed have to be normalized the same\n * way or the two silently disagree.\n *\n * ⚠️ Each array is OMITTED when a product has none, rather than written as\n * `[]`. `isNotEmpty` is served as `!= null`, and an empty array is not null —\n * so a product with no SKUs at all would answer \"has a SKU\" for every row.\n *\n * `priceFromCents` is the storefront's price key (AGL-3321): the price a\n * product grid card shows — \"From $X\", the lowest variant price — in whole\n * cents, so the catalog's price slider and its price sorts are a range and an\n * `orderBy` on one stored number rather than a comparison over variants no\n * query can reach. Written only when the variants are, because it is derived\n * from them: a write that carries no variants must not stamp a price.\n *\n * ⚠️ Spread this at EVERY write that sets a product's name or variants. A\n * write that sets the name without it leaves the keys describing the previous\n * name, and the product becomes findable only by what it used to be called.\n */\nexport function productSearchFields(product: {\n name: string\n variants?: ProductVariant[]\n}): {\n name: string\n nameLower: string\n nameTokens: string[]\n nameReversed: string\n skus?: string[]\n barcodes?: string[]\n priceFromCents?: number\n} {\n const flatten = (read: (variant: ProductVariant) => string | undefined) => [\n ...new Set(\n (product.variants ?? [])\n .map((variant) => (read(variant) ?? '').trim().toLowerCase())\n .filter(Boolean),\n ),\n ]\n const skus = flatten((variant) => variant.sku)\n const barcodes = flatten((variant) => variant.barcode)\n return {\n ...nameSearchFields(product.name),\n ...(skus.length ? { skus } : {}),\n ...(barcodes.length ? { barcodes } : {}),\n ...(product.variants\n ? { priceFromCents: productPriceFromCents({ variants: product.variants }) }\n : {}),\n }\n}\n\n/**\n * The price a storefront card shows, in whole cents (AGL-3321): the low end\n * of the variant range, which is what \"From $X\" prints and what the catalog's\n * price filter and price sorts compare. Stored as `priceFromCents` by\n * {@link productSearchFields}; `0` for a product with no priced variant yet.\n */\nexport function productPriceFromCents(\n product: Pick<HostProduct, 'variants'>,\n): number {\n return Math.round(productPriceRange(product)[0] * 100)\n}\n\n/**\n * The stock keys a product write carries (AGL-3321): the flat `inventory`\n * total, and `soldOut` — whether a storefront card reads \"Sold out\", which is\n * what the product grid's In stock chip asks the catalog query for\n * (`soldOut == false`). A grid cannot ask a query about stock inside\n * `variants`, so the verdict is stored beside them.\n *\n * ⚠️ Spread this at EVERY write that changes `variants` or `oversellPolicy`:\n * a sale, a cancellation, a stock adjustment and the editor alike. A write\n * that moves stock without it leaves a sold-out product under In stock, or an\n * in-stock one missing from it. Stored by `backfill-products-list-fields.mjs`\n * on the products written before it.\n */\nexport function productStockFields(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n): { inventory: number | null; soldOut: boolean } {\n const inventory = productInventory(product)\n return {\n inventory,\n soldOut: inventory != null && inventory <= 0 && product.oversellPolicy !== 'backorder',\n }\n}\n\n/**\n * Cartesian product of option values → the variant option combinations\n * the products hub materializes into a variants matrix. Empty/absent\n * options yield a single default combination ({}).\n */\nexport function expandVariantMatrix(\n options: ProductOption[] | undefined,\n): Array<Record<string, string>> {\n const usable = (options ?? []).filter(\n (option) => option.name && (option.values?.length ?? 0) > 0,\n )\n if (usable.length === 0) return [{}]\n let combos: Array<Record<string, string>> = [{}]\n for (const option of usable) {\n const next: Array<Record<string, string>> = []\n for (const combo of combos) {\n for (const value of option.values) {\n next.push({ ...combo, [option.name]: value })\n }\n }\n combos = next\n if (combos.length > COMMERCE_MAX_VARIANTS) {\n return combos.slice(0, COMMERCE_MAX_VARIANTS)\n }\n }\n return combos\n}\n\n/**\n * The option axes renamed, with every variant's selection carried to the new\n * name in place (AGL-3066).\n *\n * A variant keeps its selections keyed by option NAME, so a rename has to move\n * each key rather than rebuild the matrix: a rebuild matches variants by name\n * and value, finds none under the new name, and replaces every variant with a\n * new id holding the first variant's price and stock and no SKU, barcode,\n * compare-at price or weight. Moving the key keeps the id every order line\n * and stock movement refers to, and every field a person set.\n *\n * `names` holds one entry per option, in order; an entry that is not a string\n * keeps that option's name. Each selection keeps its position among a\n * variant's selections, because a variant is labeled by them in order.\n *\n * Two options may share a name for a moment while a person types. A variant\n * cannot hold two selections under one name, so while the new names are not\n * all different nothing is moved, and `validateProduct` refuses the product.\n * The selection left under the old name is found again by its value once the\n * names differ, so typing through a duplicate loses nothing.\n */\nexport function renameProductOptions(\n product: Pick<HostProduct, 'options' | 'variants'>,\n names: ReadonlyArray<string | null | undefined>,\n): Pick<HostProduct, 'options' | 'variants'> {\n const current = product.options ?? []\n const options = current.map((option, index) => {\n const name = names[index]\n return typeof name === 'string' ? { ...option, name } : option\n })\n const next = options.map((option) => option.name)\n if (new Set(next).size !== next.length) return { options, variants: product.variants }\n const variants = (product.variants ?? []).map((variant) => {\n const selections = variant.options\n if (!selections) return variant\n const axisOf = optionAxesOf(current, selections)\n const moved: Record<string, string> = {}\n let changed = false\n for (const [key, value] of Object.entries(selections)) {\n const axis = axisOf.get(key)\n const name = axis === undefined ? key : next[axis]\n if (name !== key) changed = true\n moved[name] = value\n }\n return changed ? { ...variant, options: moved } : variant\n })\n return { options, variants }\n}\n\n/**\n * Which option each of a variant's selections belongs to: the option of the\n * same name first, and then, for a selection under a name no option has any\n * longer, the one remaining option whose values hold its value. A selection\n * that fits neither belongs to no option and is left as it is.\n */\nfunction optionAxesOf(\n options: readonly ProductOption[],\n selections: Readonly<Record<string, string>>,\n): Map<string, number> {\n const axisOf = new Map<string, number>()\n const taken = new Set<number>()\n options.forEach((option, index) => {\n if (Object.prototype.hasOwnProperty.call(selections, option.name) && !axisOf.has(option.name)) {\n axisOf.set(option.name, index)\n taken.add(index)\n }\n })\n for (const [key, value] of Object.entries(selections)) {\n if (axisOf.has(key)) continue\n const axis = options.findIndex(\n (option, index) => !taken.has(index) && (option.values ?? []).includes(value),\n )\n if (axis === -1) continue\n axisOf.set(key, axis)\n taken.add(axis)\n }\n return axisOf\n}\n\n/**\n * Whether a variant has a price a sale can charge (AGL-2916).\n *\n * A product proposed by AI is created with every price left empty for the\n * merchant to set, so a stored variant can lack one. `Number(undefined)` is\n * no price, and neither is `null`, which `Number` reads as zero: a sale door\n * that priced either would charge nothing, or fail at the processor.\n */\nexport function variantHasPrice(variant: object | null | undefined): boolean {\n const price = (variant as { priceUsd?: unknown } | null | undefined)?.priceUsd\n return typeof price === 'number' && Number.isFinite(price) && price >= 0\n}\n\n/** Whether any variant of a product still needs its price set (AGL-2916). */\nexport function productPriceMissing(product: { variants?: readonly object[] }): boolean {\n return (product.variants ?? []).some((variant) => !variantHasPrice(variant))\n}\n\n/** Copy proposed for a product, by field (AGL-2916). A field left out is left alone. */\nexport interface ProductCopyValues {\n description?: string\n tags?: string[]\n categoryIds?: string[]\n /** One name per option the product has, in order. */\n optionNames?: string[]\n seoTitle?: string\n seoDescription?: string\n}\n\n/**\n * The fields proposed copy changes on a product (AGL-2916), in the shape the\n * editor stores them: only the fields `values` names. Tags and categories are\n * each kept once; the search listing keeps its share image; and option names\n * rename the product's options through `renameProductOptions`, keeping every\n * variant, only when they name each option once with a name of its own.\n */\nexport function productCopyPatch(\n product: Pick<HostProduct, 'options' | 'variants' | 'seo'>,\n values: ProductCopyValues,\n): Partial<Pick<HostProduct, 'description' | 'tags' | 'categoryIds' | 'seo' | 'options' | 'variants'>> {\n const patch: Partial<\n Pick<HostProduct, 'description' | 'tags' | 'categoryIds' | 'seo' | 'options' | 'variants'>\n > = {}\n if (typeof values.description === 'string') patch.description = values.description\n if (Array.isArray(values.tags)) {\n patch.tags = [...new Set(values.tags.map((tag) => tag.trim()).filter(Boolean))]\n }\n if (Array.isArray(values.categoryIds)) {\n patch.categoryIds = [...new Set(values.categoryIds.filter(Boolean))]\n }\n if (typeof values.seoTitle === 'string' || typeof values.seoDescription === 'string') {\n patch.seo = {\n ...product.seo,\n ...(typeof values.seoTitle === 'string' ? { title: values.seoTitle } : {}),\n ...(typeof values.seoDescription === 'string' ? { description: values.seoDescription } : {}),\n }\n }\n const options = product.options ?? []\n const names = values.optionNames?.map((name) => name.trim())\n if (\n names &&\n options.length > 0 &&\n names.length === options.length &&\n names.every(Boolean) &&\n new Set(names).size === names.length &&\n names.some((name, index) => name !== options[index].name)\n ) {\n Object.assign(patch, renameProductOptions(product, names))\n }\n return patch\n}\n\n/** A product proposed for a store, before anyone has priced it (AGL-2916). */\nexport interface ProposedProduct {\n name: string\n type: ProductType\n description: string\n tags: string[]\n options: ProductOption[]\n seoTitle: string\n seoDescription: string\n}\n\n/** A new product whose variants carry no price yet. */\nexport type UnpricedProductDraft = Omit<HostProduct, 'variants'> & {\n variants: Array<Omit<ProductVariant, 'priceUsd'>>\n}\n\n/**\n * The document a proposed product is created as (AGL-2916): a `draft`, under\n * a slug no product in `takenSlugs` has, with one variant for each\n * combination of its options and NO price on any of them. Prices are the\n * merchant's to set: the editor refuses to save the product until every\n * variant has one, and no sale door sells a variant without one\n * (`variantHasPrice`). The search keys travel with the name, as on every\n * create path.\n */\nexport function unpricedProductDraft(\n proposal: ProposedProduct,\n takenSlugs: ReadonlySet<string>,\n nowMs: number,\n): UnpricedProductDraft {\n const name = proposal.name.trim().slice(0, 120)\n const base = commerceSlug(name) || 'product'\n let slug = base\n for (let suffix = 2; takenSlugs.has(slug); suffix += 1) slug = `${base}-${suffix}`\n const seen = new Set<string>()\n const options = proposal.options\n .map((option) => ({\n name: option.name.trim(),\n values: [...new Set(option.values.map((value) => value.trim()).filter(Boolean))].slice(\n 0,\n COMMERCE_MAX_OPTION_VALUES,\n ),\n }))\n .filter((option) => {\n if (!option.name || !option.values.length || seen.has(option.name)) return false\n seen.add(option.name)\n return true\n })\n .slice(0, COMMERCE_MAX_OPTIONS)\n const variants = options.length\n ? expandVariantMatrix(options).map((combo, index) => ({\n id: `v${nowMs.toString(36)}${index}`,\n options: combo,\n }))\n : [{ id: 'default' }]\n const seoTitle = proposal.seoTitle.trim()\n const seoDescription = proposal.seoDescription.trim()\n return {\n // The keys for the variants as created: no price is `priceFromCents: 0`\n // and no tracked stock is never sold out, so the draft is ordered and\n // filtered like every other product once it is priced and activated.\n ...productSearchFields({ name, variants: variants as ProductVariant[] }),\n ...productStockFields({ variants: variants as ProductVariant[] }),\n slug,\n type: proposal.type,\n status: 'draft',\n description: proposal.description,\n tags: [...new Set(proposal.tags.map((tag) => tag.trim()).filter(Boolean))],\n ...(options.length ? { options } : {}),\n variants,\n ...(seoTitle || seoDescription\n ? { seo: { ...(seoTitle ? { title: seoTitle } : {}), ...(seoDescription ? { description: seoDescription } : {}) } }\n : {}),\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** Variant whose option selections match exactly; undefined if none. */\nexport function findVariant(\n product: Pick<HostProduct, 'variants'>,\n selections: Record<string, string>,\n): ProductVariant | undefined {\n return product.variants?.find((variant) => {\n const options = variant.options ?? {}\n const keys = new Set([...Object.keys(options), ...Object.keys(selections)])\n for (const key of keys) {\n if (options[key] !== selections[key]) return false\n }\n return true\n })\n}\n\n/** [min, max] price across variants; [0, 0] when there are none. */\nexport function productPriceRange(\n product: Pick<HostProduct, 'variants'>,\n): [number, number] {\n const prices = (product.variants ?? [])\n .map((variant) => Number(variant.priceUsd))\n .filter((price) => Number.isFinite(price) && price >= 0)\n if (prices.length === 0) return [0, 0]\n return [Math.min(...prices), Math.max(...prices)]\n}\n\n/** Sum of tracked inventory; null when every variant is untracked. */\nexport function productInventory(\n product: Pick<HostProduct, 'variants'>,\n): number | null {\n let total: number | null = null\n for (const variant of product.variants ?? []) {\n if (variant.inventory == null) continue\n total = (total ?? 0) + Number(variant.inventory)\n }\n return total\n}\n\n/**\n * Reasons an inventory adjustment doc may carry (AGL-281).\n *\n * `cancellation` is the only one written automatically in the PLUS direction\n * (AGL-1808): cancelling an order the transition rules prove was never\n * fulfilled puts back exactly what the sale took. It is deliberately not\n * `refund` — no money moved — and not `correction`, which is what a merchant\n * picks when the count disagreed with the shelf for a reason nobody recorded.\n * Kept out of the \"Adjust stock\" dialog's menu on purpose: a merchant reaching\n * for it by hand means something else happened.\n */\nexport type InventoryAdjustmentReason =\n 'sale' | 'refund' | 'restock' | 'correction' | 'damage' | 'cancellation'\n\n/** `hosts/{hostId}/inventoryAdjustments/{id}` doc. */\nexport interface InventoryAdjustment {\n productId: string\n variantId: string\n /** Positive = stock added, negative = removed. */\n delta: number\n /**\n * What the count ACTUALLY moved by, when the floor in\n * `adjustVariantInventory` absorbed part of `delta` (AGL-2149). Written only\n * when the two differ, which for a sale means a backorder product that sold\n * past zero: `delta` stays the units sold — that is the merchant's stock\n * history and it must keep saying \"3 went out the door\" — while this says how\n * many of them the count could give up.\n *\n * A REVERSAL MUST READ THIS, NOT `delta`. Restoring `delta` on a backorder\n * sale that the floor swallowed invents inventory that never existed: 0 sells\n * 3, the count stays 0, and a `+3` on cancellation leaves 3 units nobody has.\n * Absent on every row written before AGL-2149 and on every row where nothing\n * was clamped, so `appliedDelta ?? delta` is the reader.\n */\n appliedDelta?: number\n reason: InventoryAdjustmentReason\n /** Order id for sale/refund adjustments. */\n orderId?: string\n /** Location for multi-location stock (AGL-286); absent = default. */\n locationId?: string\n atMs: number\n}\n\n/**\n * Whether `quantity` of a variant is purchasable (AGL-281): untracked\n * stock always is; tracked stock honors the product's oversell policy.\n */\nexport function canPurchase(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n variantId: string | undefined,\n quantity = 1,\n): boolean {\n const variant = variantId\n ? product.variants?.find((item) => item.id === variantId)\n : product.variants?.[0]\n if (!variant) return false\n if (variant.inventory == null) return true\n if (product.oversellPolicy === 'backorder') return true\n return Number(variant.inventory) >= quantity\n}\n\n/**\n * What the register has to SAY about a line it is about to sell (AGL-2357).\n *\n * ## The defect\n *\n * `pos-order.ts` contains no `canPurchase` call. Every storefront door gates on\n * it; the register does not, so a merchant who set `oversellPolicy: 'deny'` in\n * the product editor silently got `backorder` at the counter — the count floors\n * at zero underneath and nothing anywhere says so.\n *\n * ## The decision, and why it is a shortfall and not a refusal\n *\n * Warn, never block. A till is the wrong place for a stale number to stop a\n * real sale: the cashier is holding the goods, the physical shelf is the truth,\n * and refusing loses a sale over data that is behind. But \"deny\" must at least\n * SAY something. So this reports the shortfall and the caller sells anyway.\n * Honouring the policy with a manager-level override is the post-launch shape\n * (AGL-2372) and wants an audit trail this deliberately does not build.\n *\n * ## Why the test is `canPurchase`\n *\n * Exactly the gate the register was missing, and no wider. An untracked variant\n * has no number to be short against, and a `backorder` product's merchant chose\n * to sell past zero — warning them would be noise about a setting they set on\n * purpose. So a shortfall is reported only where a purchase would have been\n * refused anywhere else in the product.\n */\nexport interface StockShortfall {\n productId: string\n variantId?: string\n /** Product name at the time of sale, for a message the cashier can read. */\n name: string\n variantLabel?: string\n /** Units the cashier is ringing up. */\n requested: number\n /** Units the count says are on the shelf; never negative. */\n available: number\n}\n\nexport function stockShortfall(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n variantId: string | undefined,\n quantity = 1,\n): { available: number } | null {\n if (canPurchase(product, variantId, quantity)) return null\n const variant = variantId\n ? product.variants?.find((item) => item.id === variantId)\n : product.variants?.[0]\n // `canPurchase` answers false for a variant that does not exist at all. That\n // is not a stock shortfall and must not be reported as \"0 in stock\" — the\n // register's own line builder falls back to `variants[0]`, so the case is\n // unreachable from the counter, and inventing a count for it would be the\n // one failure mode this feature must not have.\n if (!variant || variant.inventory == null) return null\n return { available: Math.max(0, Math.round(Number(variant.inventory) || 0)) }\n}\n\n/**\n * Whether stock tracking MEANS anything on a product (AGL-1744).\n *\n * `canPurchase` above gates every checkout on stock, subscription sessions\n * included, but nothing ever decrements for a subscription — not on the\n * initial charge (the `commerce-subscription` webhook branch deliberately\n * writes no order and touches no inventory, AGL-1732) and not on renewal\n * (`invoice.payment_succeeded` is unhandled repo-wide, AGL-1743). So on a\n * subscription-only product that gate is permanently satisfied: one unit of\n * stock sells an unlimited number of subscriptions, and the count never\n * moves however many boxes ship. The merchant set a number, the system\n * checks it on every sale, and the number is never true.\n *\n * AGL-1750 resolved the half AGL-1744 had to leave open: every paid invoice\n * of a PHYSICAL subscription now mints an order and decrements its variant's\n * stock (the `invoice.paid` branch of the commerce webhook), opening cycle\n * included. So the honest split is now three-way:\n *\n * - `subscriptionOptional` (\"Both\") products have a real one-time path —\n * the cart only ever builds `mode: 'payment'` sessions, and buy-now with\n * `billing: 'once'` records a plain order — and that path decrements\n * honestly. Withdrawing stock tracking there would delete a working\n * control and re-open the AGL-1711 oversell on the half that works.\n * - a PHYSICAL subscription box consumes a unit every cycle, and since\n * AGL-1750 the cycle's own order decrements it — the count moves as the\n * boxes ship, so the number the merchant sets is kept true again.\n * - a DIGITAL or SERVICE subscription-only product still has no\n * decrementing path anywhere, so the field stays withdrawn there: one\n * unit would still sell unlimited subscriptions.\n *\n * This says nothing about what `canPurchase` returns — that is the gate for\n * every other purchase path and is deliberately untouched. This is a console\n * predicate: it stops the editor inviting a merchant to set a number the\n * system will never keep true.\n */\nexport function stockTrackingApplies(\n product: Pick<HostProduct, 'subscription' | 'subscriptionOptional' | 'type'>,\n): boolean {\n return (\n !product.subscription ||\n product.subscriptionOptional === true ||\n product.type === 'physical'\n )\n}\n\n/** Buyer's requested billing mode on a checkout POST (AGL-545). */\nexport type CheckoutBillingChoice = 'once' | 'subscribe'\n\n/**\n * Resolves the Stripe Checkout mode for a product + the buyer's\n * requested billing choice (AGL-545). The product doc is authoritative:\n * - no `subscription` → always one-time (the request field is ignored)\n * - `subscription` without `subscriptionOptional` → always subscription\n * (a forged `billing: 'once'` cannot buy a subscription product once)\n * - `subscriptionOptional` → the buyer chooses; absent/invalid choices\n * default to one-time, matching the PDP default.\n */\nexport function resolveCheckoutBillingMode(\n product: Pick<HostProduct, 'subscription' | 'subscriptionOptional'>,\n requested?: string | null,\n): 'payment' | 'subscription' {\n if (!product.subscription) return 'payment'\n if (!product.subscriptionOptional) return 'subscription'\n return requested === 'subscribe' ? 'subscription' : 'payment'\n}\n\n/**\n * Applies a stock delta to one variant, flooring at zero (race-window\n * sales can't drive the display negative), and returns the new variants\n * array — callers persist it plus the `productInventory` denormalization.\n * With `locationId`, the delta lands in that location's bucket and the\n * flat `inventory` re-sums across locations (AGL-286).\n */\nexport function adjustVariantInventory(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n delta: number,\n locationId?: string,\n): ProductVariant[] {\n return (product.variants ?? []).map((variant) => {\n if (variant.id !== variantId || variant.inventory == null) return variant\n if (locationId && variant.inventoryByLocation) {\n const buckets = {\n ...variant.inventoryByLocation,\n [locationId]: Math.max(\n 0,\n Number(variant.inventoryByLocation[locationId] ?? 0) + delta,\n ),\n }\n return {\n ...variant,\n inventoryByLocation: buckets,\n inventory: Object.values(buckets).reduce(\n (sum, count) => sum + Number(count),\n 0,\n ),\n }\n }\n return {\n ...variant,\n inventory: Math.max(0, Number(variant.inventory) + delta),\n }\n })\n}\n\n/**\n * What `adjustVariantInventory` will ACTUALLY move the count by (AGL-2149).\n *\n * The floor in that helper is not a rounding detail, it is a silent absorber. A\n * backorder product (`oversellPolicy: 'backorder'`, which `canPurchase` admits\n * at any stock level) sitting at 0 sells 3: `Math.max(0, 0 + -3)` is 0, so the\n * count does not move — correctly, since inventory is a shelf count and shelves\n * do not go negative — but the ledger row said `-3` and every reversal read it\n * as three units to put back. Cancelling that order handed the merchant 3 units\n * that never existed and a stock badge that offers them for sale.\n *\n * Removing the floor is not the alternative: every reader of `inventory` — the\n * badges, `canPurchase`, `productInventory`, `isLowStock` — assumes it cannot\n * go negative, and a negative count would be a far wider change than the bug.\n * So the clamp stays and the amount it absorbed is recorded instead.\n *\n * Deliberately mirrors `adjustVariantInventory`'s own arithmetic, including\n * which field the clamp applies to in the location-tracked case, so the two\n * cannot disagree about what happened.\n */\nexport function appliedVariantInventoryDelta(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n delta: number,\n locationId?: string,\n): number {\n const variant = (product.variants ?? []).find(\n (item) => item.id === variantId,\n )\n if (!variant || variant.inventory == null) return 0\n if (locationId && variant.inventoryByLocation) {\n const before = Number(variant.inventoryByLocation[locationId] ?? 0)\n return Math.max(0, before + delta) - before\n }\n const before = Number(variant.inventory)\n return Math.max(0, before + delta) - before\n}\n\n/**\n * Moves stock between two locations of a tracked variant (AGL-286).\n * Quantity clamps to what the source location holds; the flat total is\n * unchanged by construction.\n */\nexport function transferVariantInventory(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n fromLocationId: string,\n toLocationId: string,\n quantity: number,\n): ProductVariant[] {\n return (product.variants ?? []).map((variant) => {\n if (variant.id !== variantId || variant.inventory == null) return variant\n const buckets = { ...(variant.inventoryByLocation ?? {}) }\n const available = Math.max(0, Number(buckets[fromLocationId] ?? 0))\n const moved = Math.min(available, Math.max(0, Math.round(quantity)))\n if (moved === 0) return variant\n buckets[fromLocationId] = available - moved\n buckets[toLocationId] = Math.max(0, Number(buckets[toLocationId] ?? 0)) + moved\n return { ...variant, inventoryByLocation: buckets }\n })\n}\n\n/** True when tracked stock is at/below the product's alert threshold. */\nexport function isLowStock(\n product: Pick<HostProduct, 'variants' | 'lowStockThreshold'>,\n): boolean {\n const threshold = product.lowStockThreshold\n if (threshold == null || !(threshold >= 0)) return false\n const total = productInventory(product)\n return total != null && total <= threshold\n}\n\nfunction ruleMatches(product: HostProduct, rule: CollectionRule): boolean {\n const value = rule.value\n switch (rule.field) {\n case 'tag': {\n const tags = product.tags ?? []\n const has = tags.includes(String(value))\n return rule.op === 'neq' ? !has : has\n }\n case 'categoryId': {\n const ids = product.categoryIds ?? []\n const has = ids.includes(String(value))\n return rule.op === 'neq' ? !has : has\n }\n case 'priceUsd': {\n const [min, max] = productPriceRange(product)\n const numeric = Number(value)\n if (!Number.isFinite(numeric)) return false\n if (rule.op === 'lt') return min < numeric\n if (rule.op === 'gt') return max > numeric\n if (rule.op === 'neq') return min !== numeric || max !== numeric\n return min <= numeric && numeric <= max\n }\n case 'name': {\n const name = (product.name ?? '').toLowerCase()\n const needle = String(value).toLowerCase()\n if (rule.op === 'contains') return name.includes(needle)\n if (rule.op === 'neq') return name !== needle\n return name === needle\n }\n case 'type': {\n const matches = product.type === value\n return rule.op === 'neq' ? !matches : matches\n }\n default:\n return false\n }\n}\n\n/**\n * Whether a product's own fields answer a SMART collection's rules — its\n * tags, categories, prices, name and type, and nothing about whether it is\n * on sale. That is the storefront query's scope (`deletedAt == null`,\n * `status == 'active'`), so membership stored on the product never goes stale\n * when a product is archived or brought back.\n *\n * A collection with no rules holds nothing.\n */\n/** What smart-collection membership reads of a product — a draft's too. */\nexport interface MembershipProduct {\n name?: string\n type?: ProductType\n tags?: string[]\n categoryIds?: string[]\n variants?: ReadonlyArray<{ id?: string; priceUsd?: number | null }>\n}\n\nexport function smartCollectionMatches(\n product: MembershipProduct,\n collection: Pick<HostCollection, 'rules' | 'matchAll'>,\n): boolean {\n const rules = collection.rules ?? []\n if (rules.length === 0) return false\n const matcher = (rule: CollectionRule) => ruleMatches(product as HostProduct, rule)\n return collection.matchAll === false\n ? rules.some(matcher)\n : rules.every(matcher)\n}\n\n/**\n * Smart-collection membership: draft/archived/deleted products never\n * match; manual collections answer from productIds.\n */\nexport function matchesCollection(\n product: HostProduct,\n collection: HostCollection,\n productId?: string,\n): boolean {\n if (product.deletedAt || product.status !== 'active') return false\n if (collection.mode === 'manual') {\n return productId != null &&\n (collection.productIds ?? []).includes(productId)\n }\n return smartCollectionMatches(product, collection)\n}\n\n/**\n * The stored membership of a product in the host's SMART collections\n * (AGL-3321): the ids of those whose rules it answers\n * ({@link smartCollectionMatches}), sorted.\n *\n * The storefront reads a smart collection whose rules no query can hold (a\n * NOT, an OR, a name rule, a price over) as `collectionIds array-contains\n * <id>` — so the membership is WRITTEN, by every product writer from the\n * host's smart collections as they stand, and by the collection-membership\n * route for every product whenever a smart collection's rules change or it\n * is deleted. `tools/scripts/backfill-product-collection-ids.mjs` stamps the\n * products written before; the two answer\n * `tools/scripts/lib/product-collection-ids.fixtures.json`.\n */\nexport const PRODUCT_COLLECTION_IDS = 'collectionIds'\n\n/** A smart collection as membership is computed from it. */\nexport interface SmartCollectionRules {\n id: string\n rules?: CollectionRule[]\n matchAll?: boolean\n}\n\nexport function productCollectionIds(\n product: MembershipProduct,\n smartCollections: readonly SmartCollectionRules[],\n): string[] {\n return smartCollections\n .filter((collection) => smartCollectionMatches(product, collection))\n .map((collection) => collection.id)\n .sort()\n}\n\n/**\n * Lifts a legacy Commerce Starter doc (AGL-90: flat name/priceUsd/\n * inventory/imageUrl) into the catalog shape with a single default\n * variant. Already-lifted docs pass through unchanged.\n */\nexport function liftLegacyProduct(\n raw: Partial<HostProduct> & { name?: string },\n): HostProduct {\n if (Array.isArray(raw.variants) && raw.variants.length > 0) {\n return raw as HostProduct\n }\n const priceUsd = Number(raw.priceUsd ?? 0)\n return {\n ...raw,\n name: raw.name ?? 'Product',\n slug: raw.slug || commerceSlug(raw.name ?? 'product'),\n type: raw.type ?? 'physical',\n status: raw.status ?? 'active',\n variants: [\n {\n id: 'default',\n priceUsd: Number.isFinite(priceUsd) ? priceUsd : 0,\n inventory: raw.inventory ?? null,\n },\n ],\n }\n}\n\n/** Actionable error, or null when the product is storable. */\nexport function validateProduct(product: HostProduct): string | null {\n if (!product.name?.trim()) return 'Product name is required'\n if (!product.slug || product.slug !== commerceSlug(product.slug)) {\n return 'Slug must be lowercase letters, numbers, and dashes'\n }\n if (!['physical', 'digital', 'service'].includes(product.type)) {\n return 'Unknown product type'\n }\n if (!['draft', 'active', 'archived'].includes(product.status)) {\n return 'Unknown product status'\n }\n const options = product.options ?? []\n if (options.length > COMMERCE_MAX_OPTIONS) {\n return `At most ${COMMERCE_MAX_OPTIONS} options per product`\n }\n for (const option of options) {\n if (!option.name?.trim()) return 'Option names are required'\n if ((option.values?.length ?? 0) === 0) {\n return `Option \"${option.name}\" needs at least one value`\n }\n if (option.values.length > COMMERCE_MAX_OPTION_VALUES) {\n return `Option \"${option.name}\" has too many values`\n }\n if (new Set(option.values).size !== option.values.length) {\n return `Option \"${option.name}\" has duplicate values`\n }\n }\n // A variant keys its selections by option name, so two options with one\n // name cannot both be selected (AGL-3066).\n if (new Set(options.map((option) => option.name.trim())).size !== options.length) {\n return 'Each option needs its own name'\n }\n const variants = product.variants ?? []\n if (variants.length === 0) return 'Products need at least one variant'\n if (variants.length > COMMERCE_MAX_VARIANTS) {\n return `At most ${COMMERCE_MAX_VARIANTS} variants per product`\n }\n const ids = new Set<string>()\n const skus = new Set<string>()\n for (const variant of variants) {\n if (!variant.id) return 'Variants need stable ids'\n if (ids.has(variant.id)) return 'Variant ids must be unique'\n ids.add(variant.id)\n if (variant.priceUsd === undefined || variant.priceUsd === null) {\n return 'Set a price for every variant'\n }\n const price = Number(variant.priceUsd)\n if (!Number.isFinite(price) || price < 0) {\n return 'Variant prices must be zero or more'\n }\n if (price > COMMERCE_MAX_PRICE_USD) {\n return `Prices are capped at $${COMMERCE_MAX_PRICE_USD}`\n }\n if (variant.sku) {\n if (skus.has(variant.sku)) return 'Variant SKUs must be unique'\n skus.add(variant.sku)\n }\n if (\n variant.compareAtPriceUsd != null &&\n Number(variant.compareAtPriceUsd) <= price\n ) {\n return 'Compare-at price must exceed the price'\n }\n }\n return null\n}\n\n/** Actionable error, or null when the collection is storable. */\nexport function validateCollection(collection: HostCollection): string | null {\n if (!collection.name?.trim()) return 'Collection name is required'\n if (\n !collection.slug ||\n collection.slug !== commerceSlug(collection.slug)\n ) {\n return 'Slug must be lowercase letters, numbers, and dashes'\n }\n if (collection.mode !== 'manual' && collection.mode !== 'smart') {\n return 'Unknown collection mode'\n }\n if (collection.mode === 'smart') {\n const rules = collection.rules ?? []\n if (rules.length === 0) return 'Smart collections need at least one rule'\n for (const rule of rules) {\n if (\n !['tag', 'categoryId', 'priceUsd', 'name', 'type'].includes(rule.field)\n ) {\n return 'Unknown rule field'\n }\n if (!['eq', 'neq', 'lt', 'gt', 'contains'].includes(rule.op)) {\n return 'Unknown rule operator'\n }\n if (rule.value === '' || rule.value == null) {\n return 'Rule values are required'\n }\n }\n }\n return null\n}\n"],"names":["nameSearchFields","COMMERCE_MAX_PRICE_USD","registersWithinCap","registers","cap","createdMs","r","createdAt","toMillis","seconds","ranked","sort","a","b","$id","localeCompare","Set","slice","Math","max","map","COMMERCE_MAX_VARIANTS","COMMERCE_MAX_OPTIONS","COMMERCE_MAX_OPTION_VALUES","COMMERCE_SLUG_MAX_LENGTH","commerceSlug","name","String","normalize","replace","toLowerCase","productSearchFields","product","flatten","read","variants","variant","trim","filter","Boolean","skus","sku","barcodes","barcode","length","priceFromCents","productPriceFromCents","round","productPriceRange","productStockFields","inventory","productInventory","soldOut","oversellPolicy","expandVariantMatrix","options","usable","option","values","combos","next","combo","value","push","renameProductOptions","names","current","index","size","selections","axisOf","optionAxesOf","moved","changed","key","Object","entries","axis","get","undefined","Map","taken","forEach","prototype","hasOwnProperty","call","has","set","add","findIndex","includes","variantHasPrice","price","priceUsd","Number","isFinite","productPriceMissing","some","productCopyPatch","patch","description","Array","isArray","tags","tag","categoryIds","seoTitle","seoDescription","seo","title","optionNames","every","assign","unpricedProductDraft","proposal","takenSlugs","nowMs","base","slug","suffix","seen","id","toString","type","status","createdAtMs","updatedAtMs","findVariant","find","keys","prices","min","total","canPurchase","variantId","quantity","item","stockShortfall","available","stockTrackingApplies","subscription","subscriptionOptional","resolveCheckoutBillingMode","requested","adjustVariantInventory","delta","locationId","inventoryByLocation","buckets","reduce","sum","count","appliedVariantInventoryDelta","before","transferVariantInventory","fromLocationId","toLocationId","isLowStock","threshold","lowStockThreshold","ruleMatches","rule","field","op","ids","numeric","needle","matches","smartCollectionMatches","collection","rules","matcher","matchAll","matchesCollection","productId","deletedAt","mode","productIds","PRODUCT_COLLECTION_IDS","productCollectionIds","smartCollections","liftLegacyProduct","raw","validateProduct","compareAtPriceUsd","validateCollection"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,qCAAoC;AAErE;;;;;;;;CAQC,GAED;;;;;;;;;;;;;;;;;CAiBC,GACD,uCAAuC,GACvC,OAAO,MAAMC,yBAAyB,MAAK;AAsD3C;;;;;;CAMC,GAC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;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,+DAA+D,GAC/D,OAAO,SAAS6F,mBAAmBhB,UAA0B;QACtDA;IAAL,IAAI,GAACA,mBAAAA,WAAW/I,IAAI,qBAAf+I,iBAAiBpI,IAAI,KAAI,OAAO;IACrC,IACE,CAACoI,WAAWnD,IAAI,IAChBmD,WAAWnD,IAAI,KAAK7F,aAAagJ,WAAWnD,IAAI,GAChD;QACA,OAAO;IACT;IACA,IAAImD,WAAWO,IAAI,KAAK,YAAYP,WAAWO,IAAI,KAAK,SAAS;QAC/D,OAAO;IACT;IACA,IAAIP,WAAWO,IAAI,KAAK,SAAS;YACjBP;QAAd,MAAMC,SAAQD,oBAAAA,WAAWC,KAAK,YAAhBD,oBAAoB,EAAE;QACpC,IAAIC,MAAM9H,MAAM,KAAK,GAAG,OAAO;QAC/B,KAAK,MAAMqH,QAAQS,MAAO;YACxB,IACE,CAAC;gBAAC;gBAAO;gBAAc;gBAAY;gBAAQ;aAAO,CAAChF,QAAQ,CAACuE,KAAKC,KAAK,GACtE;gBACA,OAAO;YACT;YACA,IAAI,CAAC;gBAAC;gBAAM;gBAAO;gBAAM;gBAAM;aAAW,CAACxE,QAAQ,CAACuE,KAAKE,EAAE,GAAG;gBAC5D,OAAO;YACT;YACA,IAAIF,KAAKnG,KAAK,KAAK,MAAMmG,KAAKnG,KAAK,IAAI,MAAM;gBAC3C,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce.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\nimport { modifierGroupsProblem, type ProductModifierGroup } from './product-modifiers'\nimport { nameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport { draftProductChannelFacts, type ProductChannelFacts } from './product-channel'\n\n/**\n * Commerce catalog v1 (AGL-276): products with options/variants,\n * hierarchical categories, tags, and manual/smart collections. Pure\n * model + helpers — no I/O; the products hub and storefront APIs operate\n * over these shapes. Documents live under `hosts/{hostId}/products`,\n * `.../productCategories`, and `.../collections`; the legacy Commerce\n * Starter product doc (AGL-90: name/priceUsd/inventory) lifts into this\n * shape via `liftLegacyProduct`, so existing docs keep working.\n */\n\n/*\n * THERE IS NO STOREFRONT FEE CONSTANT, and that absence is load-bearing\n * (AGL-2295).\n *\n * `COMMERCE_PLATFORM_FEE_PERCENT = 2` lived here with ZERO call sites. It\n * asserted a flat 2% that agrees with the plan table for exactly one cell\n * (Starter, physical) and disagrees with the other fifteen — Starter digital\n * is 5%, Pro digital 3%, Business 2%, Scale 1%, and every physical rate above\n * Starter is 0%. Nothing was wrong while nothing read it; the cost was that\n * the next reader wiring it up would silently re-price every plan, and a\n * constant sitting in the model beside the types reads like the answer.\n *\n * The single source is `resolveTransactionFeePct(org, productType)` in\n * `plan-entitlements.ts`, resolved PER REQUEST from the org — because it\n * depends on the plan, on per-org staff overrides, and on whether the\n * subscription is still alive. A constant cannot express any of that.\n * `commerce-fee-single-source.spec.ts` fails the build if one comes back.\n */\n/** Product price ceiling (whole USD). */\nexport const COMMERCE_MAX_PRICE_USD = 10000\n\nexport type ProductType = 'physical' | 'digital' | 'service'\nexport type ProductStatus = 'draft' | 'active' | 'archived'\n\n/** One axis of variation, e.g. { name: 'Size', values: ['S','M','L'] }. */\nexport interface ProductOption {\n name: string\n values: string[]\n}\n\n/** A sellable configuration of a product (every product has ≥ 1). */\nexport interface ProductVariant {\n /** Stable id unique within the product (never reused after delete). */\n id: string\n /** Option selections keyed by option name; {} for the default variant. */\n options?: Record<string, string>\n sku?: string\n barcode?: string\n priceUsd: number\n /** Strike-through price; a sale badge shows when > priceUsd. */\n compareAtPriceUsd?: number\n weightGrams?: number\n /** null/undefined = untracked; 0 = sold out (matches AGL-96). */\n inventory?: number | null\n /**\n * Per-location stock (AGL-286); `inventory` stays the summed\n * denormalization. Absent = single default location.\n */\n inventoryByLocation?: Record<string, number>\n /** Media-library image URL shown when this variant is selected. */\n imageUrl?: string\n}\n\n/** A product's packed size and customs facts (AGL-3612). */\nexport interface ProductShippingFacts {\n lengthCm?: number | null\n widthCm?: number | null\n heightCm?: number | null\n /** Harmonized System tariff code. */\n hsCode?: string\n /** ISO-3166 alpha-2 country the product was made in. */\n originCountry?: string\n}\n\n/** A place's postal address, in parts (AGL-3612). Country is ISO-3166 alpha-2. */\nexport interface PostalAddress {\n line1?: string\n line2?: string\n city?: string\n state?: string\n postalCode?: string\n country?: string\n phone?: string\n}\n\n/** `hosts/{hostId}/locations/{id}` doc (AGL-286). */\nexport interface InventoryLocation {\n name: string\n isDefault?: boolean\n /** Free text, as the location was first described. */\n address?: string\n /**\n * The same place as a postal address (AGL-3612), so parcels can ship from\n * it. Optional: a location written before this has only `address`.\n */\n postalAddress?: PostalAddress\n}\n\n/** A product's packed size for one unit, when all three sides are known. */\nexport function productParcelDimensions(\n product: Pick<HostProduct, 'shipping'> | null | undefined,\n): { lengthCm: number; widthCm: number; heightCm: number } | undefined {\n const facts = product?.shipping\n const side = (value: unknown) => {\n const number = Number(value)\n return Number.isFinite(number) && number > 0 ? Math.min(number, 300) : 0\n }\n const lengthCm = side(facts?.lengthCm)\n const widthCm = side(facts?.widthCm)\n const heightCm = side(facts?.heightCm)\n return lengthCm && widthCm && heightCm ? { lengthCm, widthCm, heightCm } : undefined\n}\n\n/**\n * Shipping facts as the product editor stages them, keystroke by keystroke\n * (AGL-3647): {@link normalizeProductShippingFacts}, except that a country\n * of origin being typed keeps its first letter. The editor runs this on\n * every keystroke, and the strict form drops anything short of two letters,\n * so the field could never be typed into. Readers normalize what is stored.\n */\nexport function draftProductShippingFacts(value: unknown): ProductShippingFacts | undefined {\n const facts = normalizeProductShippingFacts(value)\n const typed = String((value as Record<string, unknown> | null)?.['originCountry'] ?? '')\n .trim()\n .toUpperCase()\n if (/^[A-Z]$/.test(typed)) return { ...facts, originCountry: typed }\n return facts\n}\n\n/** A stored product's shipping facts made safe (AGL-3612); never throws. */\nexport function normalizeProductShippingFacts(value: unknown): ProductShippingFacts | undefined {\n if (!value || typeof value !== 'object') return undefined\n const raw = value as Record<string, unknown>\n const facts: ProductShippingFacts = {}\n for (const side of ['lengthCm', 'widthCm', 'heightCm'] as const) {\n const number = Number(raw[side])\n if (raw[side] !== null && raw[side] !== undefined && Number.isFinite(number) && number > 0) {\n facts[side] = Math.min(Math.round(number * 10) / 10, 300)\n }\n }\n const hsCode = String(raw['hsCode'] ?? '').replace(/[^0-9.]/g, '').slice(0, 14)\n if (hsCode) facts.hsCode = hsCode\n const originCountry = String(raw['originCountry'] ?? '').trim().toUpperCase()\n if (/^[A-Z]{2}$/.test(originCountry)) facts.originCountry = originCountry\n return Object.keys(facts).length ? facts : undefined\n}\n\n/** A stored location's postal address made safe (AGL-3612); never throws. */\nexport function normalizePostalAddress(value: unknown): PostalAddress | undefined {\n if (!value || typeof value !== 'object') return undefined\n const raw = value as Record<string, unknown>\n const address: PostalAddress = {}\n for (const field of ['line1', 'line2', 'city', 'state', 'postalCode', 'phone'] as const) {\n const text = String(raw[field] ?? '').trim().slice(0, 120)\n if (text) address[field] = text\n }\n const country = String(raw['country'] ?? '').trim().toUpperCase()\n if (/^[A-Z]{2}$/.test(country)) address.country = country\n return Object.keys(address).length ? address : undefined\n}\n\n/**\n * `hosts/{hostId}/registers/{id}` doc (AGL-472): a named point-of-sale\n * register. Creation is capped by the plan's `posRegisters` quota (Pro 1,\n * Business 2, Advanced 5; raised by a per-org entitlement override for the\n * $89/mo add-on), enforced server-side by the resources route. Each POS\n * sale stamps its `registerId` so takings are attributable per register.\n */\nexport interface PosRegister {\n name: string\n /** Optional default inventory location this register sells from. */\n locationId?: string\n}\n\n/**\n * The register ids within the plan's `posRegisters` cap (AGL-482), ranked\n * by creation order — the same ordering `pos-order.ts` enforces at sale\n * time. Registers beyond the cap (e.g. after a Business→Pro downgrade) are\n * excluded so the console/POS can dim or hide them instead of surfacing a\n * checkout 403. `cap` of `Infinity` returns all.\n */\nexport function registersWithinCap(\n registers: Array<{ $id: string; createdAt?: any }>,\n cap: number,\n): Set<string> {\n const createdMs = (r: { createdAt?: any }) =>\n r.createdAt?.toMillis?.() ?? r.createdAt?.seconds ?? 0\n const ranked = [...registers].sort(\n (a, b) => createdMs(a) - createdMs(b) || a.$id.localeCompare(b.$id),\n )\n return new Set(ranked.slice(0, Math.max(0, cap)).map((r) => r.$id))\n}\n\n/**\n * `hosts/{hostId}/suppliers/{id}` doc (AGL-289): where dropshipped\n * order lines route on payment. Email and webhook are both optional but\n * one must be set for routing to do anything; webhook payloads are\n * HMAC-SHA256-signed with `webhookSecret`.\n */\nexport interface HostSupplier {\n name: string\n email?: string\n webhookUrl?: string\n webhookSecret?: string\n}\n\n/** `hosts/{hostId}/products/{id}` doc. */\nexport interface HostProduct {\n name: string\n /** Host-unique URL segment for /products/{slug}. */\n slug: string\n description?: string\n type: ProductType\n status: ProductStatus\n /** Ordered media-library image URLs (first = primary). */\n mediaUrls?: string[]\n categoryIds?: string[]\n /**\n * The SMART collections this product's rules answer (AGL-3321), written by\n * every writer — see `productCollectionIds`.\n */\n collectionIds?: string[]\n tags?: string[]\n options?: ProductOption[]\n variants: ProductVariant[]\n /** Per-product overrides for PDP meta tags (AGL-299 consumes). */\n seo?: { title?: string; description?: string; imageUrl?: string }\n /**\n * What shopping channels ask of the product (AGL-3637): brand, GTIN, MPN,\n * condition and Google category. Absent means nothing was entered; the\n * channel feeds fall back to the store's defaults.\n */\n channel?: ProductChannelFacts\n /** Supplier for dropship routing (AGL-289). */\n supplierId?: string\n /** Out-of-stock behavior (AGL-281): deny (default) or allow backorder. */\n oversellPolicy?: 'deny' | 'backorder'\n /** Never taxed regardless of tax settings (AGL-285). */\n taxExempt?: boolean\n /**\n * Digital delivery (AGL-302): downloadable files for `digital`\n * products. Buyers always download the CURRENT list, so uploading a\n * new version re-delivers to everyone.\n */\n digitalFiles?: Array<{ url: string; fileName: string; version?: string }>\n /** Max download attempts per order line; absent = unlimited. */\n downloadLimit?: number\n /**\n * Recurring billing (AGL-303): buyers subscribe instead of buying\n * once; an active subscription is the entitlement content gating\n * checks (AGL-309).\n */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /**\n * Buyer-chosen billing (AGL-545): with `subscription` set, true lets\n * the buyer pick one-time OR subscribe on the PDP (default one-time);\n * absent/false keeps the product subscription-only.\n */\n subscriptionOptional?: boolean\n /** Members-only videos (AGL-315), streamed via short-TTL links. */\n gatedVideos?: Array<{ url: string; title?: string }>\n /** Manual related products for the upsell block (AGL-325). */\n relatedProductIds?: string[]\n /**\n * What one unit ships as (AGL-3612): its packed size, for a carrier to\n * price, and its customs facts, for a parcel that crosses a border. Weight\n * stays per variant. Absent means unknown, and a label is priced in the\n * merchant's default box.\n */\n shipping?: ProductShippingFacts\n /** Buying this issues a gift-card code for its price (AGL-322). */\n giftCard?: boolean\n /** Tracked-total at/below this alerts host managers (AGL-281). */\n lowStockThreshold?: number\n /**\n * Choices added to the item at the register (AGL-3607) — \"Oat milk\",\n * \"Extra shot\" — priced by the server from this list. See\n * `product-modifiers.ts`.\n */\n modifierGroups?: ProductModifierGroup[]\n /** Shown under Quick keys on the register's first screen (AGL-3607). */\n posQuickKey?: boolean\n createdAtMs?: number\n updatedAtMs?: number\n deletedAt?: number | null\n /** Legacy Commerce Starter fields kept so old docs read back (AGL-90). */\n priceUsd?: number\n inventory?: number | null\n imageUrl?: string\n}\n\n/** `hosts/{hostId}/productCategories/{id}` doc (tree via parentId). */\nexport interface ProductCategory {\n name: string\n slug: string\n parentId?: string | null\n order?: number\n}\n\nexport type CollectionRuleField =\n | 'tag'\n | 'categoryId'\n | 'priceUsd'\n | 'name'\n | 'type'\nexport type CollectionRuleOp = 'eq' | 'neq' | 'lt' | 'gt' | 'contains'\n\nexport interface CollectionRule {\n field: CollectionRuleField\n op: CollectionRuleOp\n value: string | number\n}\n\n/** `hosts/{hostId}/collections/{id}` doc. */\nexport interface HostCollection {\n name: string\n slug: string\n description?: string\n mode: 'manual' | 'smart'\n /** Manual mode: explicit ordered membership. */\n productIds?: string[]\n /** Smart mode: rules evaluated over active products. */\n rules?: CollectionRule[]\n /** Smart mode: true = every rule must match (default), false = any. */\n matchAll?: boolean\n /** Media-library image URL for the collection card/landing hero. */\n imageUrl?: string\n order?: number\n}\n\n/**\n * Payment-provider seam (AGL-284): checkout/session creation goes\n * through a provider id so PayPal (etc.) can slot in without reworking\n * callers. Stripe is the only implementation today; store settings\n * (AGL-295) will carry the selection when a second provider exists.\n */\nexport type PaymentProviderId = 'stripe'\n\nexport interface PaymentCheckoutRequest {\n provider: PaymentProviderId\n hostId: string\n amountCents: number\n feeCents: number\n productName: string\n successUrl: string\n cancelUrl: string\n metadata?: Record<string, string>\n}\n\n/** Variant ceiling per product (Shopify parity). */\nexport const COMMERCE_MAX_VARIANTS = 100\nexport const COMMERCE_MAX_OPTIONS = 3\nexport const COMMERCE_MAX_OPTION_VALUES = 25\nexport const COMMERCE_SLUG_MAX_LENGTH = 80\n\n/** Lowercase-kebab slug from a product/category/collection name. */\nexport function commerceSlug(name: string): string {\n return String(name ?? '')\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, COMMERCE_SLUG_MAX_LENGTH)\n}\n\n/**\n * The search keys a product write carries, so the catalog can be searched by\n * the QUERY rather than by the rows a listener happened to fetch (AGL-2501).\n *\n * The hub lists `limit(500)`, and the search compared what that returned — so\n * a product past the window answered \"no products match\", which reads as the\n * product not existing rather than as the search not reaching it. Filtering\n * server-side needs fields Firestore can index, and neither of the two things\n * a merchant searches by is one:\n *\n * - A NAME needs case-insensitive contains, which Firestore has no operator\n * for. `nameSearchFields` denormalizes it into the three shapes that are\n * indexable — an exact key, word-prefix tokens for `array-contains`, and\n * the key reversed so \"ends with\" becomes a prefix range.\n * - A SKU lives inside `variants`, an array of OBJECTS, and Firestore cannot\n * query a field inside one. Flattened here into a top-level array so a SKU\n * is one `array-contains`.\n *\n * ⛔ A SKU therefore matches WHOLE, not as a substring: \"abc-123\" finds it and\n * \"123\" does not. That is the right way round for a SKU, which is a value\n * somebody copies rather than half-remembers — unlike a name, where the tokens\n * above buy word-prefix matching precisely because names are half-remembered.\n *\n * `barcodes` is the same flattening for the same reason, and it is the one the\n * register depends on: a keyboard-wedge scanner types the code and presses\n * Enter, so the lookup has to be exact and has to reach the whole catalog. A\n * scan is never a half-remembered value.\n *\n * Lower-cased because the translator lower-cases the typed query before it\n * builds the `array-contains`; stored and typed have to be normalized the same\n * way or the two silently disagree.\n *\n * ⚠️ Each array is OMITTED when a product has none, rather than written as\n * `[]`. `isNotEmpty` is served as `!= null`, and an empty array is not null —\n * so a product with no SKUs at all would answer \"has a SKU\" for every row.\n *\n * `priceFromCents` is the storefront's price key (AGL-3321): the price a\n * product grid card shows — \"From $X\", the lowest variant price — in whole\n * cents, so the catalog's price slider and its price sorts are a range and an\n * `orderBy` on one stored number rather than a comparison over variants no\n * query can reach. Written only when the variants are, because it is derived\n * from them: a write that carries no variants must not stamp a price.\n *\n * ⚠️ Spread this at EVERY write that sets a product's name or variants. A\n * write that sets the name without it leaves the keys describing the previous\n * name, and the product becomes findable only by what it used to be called.\n */\nexport function productSearchFields(product: {\n name: string\n variants?: ProductVariant[]\n}): {\n name: string\n nameLower: string\n nameTokens: string[]\n nameReversed: string\n skus?: string[]\n barcodes?: string[]\n priceFromCents?: number\n} {\n const flatten = (read: (variant: ProductVariant) => string | undefined) => [\n ...new Set(\n (product.variants ?? [])\n .map((variant) => (read(variant) ?? '').trim().toLowerCase())\n .filter(Boolean),\n ),\n ]\n const skus = flatten((variant) => variant.sku)\n const barcodes = flatten((variant) => variant.barcode)\n return {\n ...nameSearchFields(product.name),\n ...(skus.length ? { skus } : {}),\n ...(barcodes.length ? { barcodes } : {}),\n ...(product.variants\n ? { priceFromCents: productPriceFromCents({ variants: product.variants }) }\n : {}),\n }\n}\n\n/**\n * The price a storefront card shows, in whole cents (AGL-3321): the low end\n * of the variant range, which is what \"From $X\" prints and what the catalog's\n * price filter and price sorts compare. Stored as `priceFromCents` by\n * {@link productSearchFields}; `0` for a product with no priced variant yet.\n */\nexport function productPriceFromCents(\n product: Pick<HostProduct, 'variants'>,\n): number {\n return Math.round(productPriceRange(product)[0] * 100)\n}\n\n/**\n * The stock keys a product write carries (AGL-3321): the flat `inventory`\n * total, and `soldOut` — whether a storefront card reads \"Sold out\", which is\n * what the product grid's In stock chip asks the catalog query for\n * (`soldOut == false`). A grid cannot ask a query about stock inside\n * `variants`, so the verdict is stored beside them.\n *\n * ⚠️ Spread this at EVERY write that changes `variants` or `oversellPolicy`:\n * a sale, a cancellation, a stock adjustment and the editor alike. A write\n * that moves stock without it leaves a sold-out product under In stock, or an\n * in-stock one missing from it. Stored by `backfill-products-list-fields.mjs`\n * on the products written before it.\n */\nexport function productStockFields(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n): { inventory: number | null; soldOut: boolean } {\n const inventory = productInventory(product)\n return {\n inventory,\n soldOut: inventory != null && inventory <= 0 && product.oversellPolicy !== 'backorder',\n }\n}\n\n/**\n * Cartesian product of option values → the variant option combinations\n * the products hub materializes into a variants matrix. Empty/absent\n * options yield a single default combination ({}).\n */\nexport function expandVariantMatrix(\n options: ProductOption[] | undefined,\n): Array<Record<string, string>> {\n const usable = (options ?? []).filter(\n (option) => option.name && (option.values?.length ?? 0) > 0,\n )\n if (usable.length === 0) return [{}]\n let combos: Array<Record<string, string>> = [{}]\n for (const option of usable) {\n const next: Array<Record<string, string>> = []\n for (const combo of combos) {\n for (const value of option.values) {\n next.push({ ...combo, [option.name]: value })\n }\n }\n combos = next\n if (combos.length > COMMERCE_MAX_VARIANTS) {\n return combos.slice(0, COMMERCE_MAX_VARIANTS)\n }\n }\n return combos\n}\n\n/**\n * The option axes renamed, with every variant's selection carried to the new\n * name in place (AGL-3066).\n *\n * A variant keeps its selections keyed by option NAME, so a rename has to move\n * each key rather than rebuild the matrix: a rebuild matches variants by name\n * and value, finds none under the new name, and replaces every variant with a\n * new id holding the first variant's price and stock and no SKU, barcode,\n * compare-at price or weight. Moving the key keeps the id every order line\n * and stock movement refers to, and every field a person set.\n *\n * `names` holds one entry per option, in order; an entry that is not a string\n * keeps that option's name. Each selection keeps its position among a\n * variant's selections, because a variant is labeled by them in order.\n *\n * Two options may share a name for a moment while a person types. A variant\n * cannot hold two selections under one name, so while the new names are not\n * all different nothing is moved, and `validateProduct` refuses the product.\n * The selection left under the old name is found again by its value once the\n * names differ, so typing through a duplicate loses nothing.\n */\nexport function renameProductOptions(\n product: Pick<HostProduct, 'options' | 'variants'>,\n names: ReadonlyArray<string | null | undefined>,\n): Pick<HostProduct, 'options' | 'variants'> {\n const current = product.options ?? []\n const options = current.map((option, index) => {\n const name = names[index]\n return typeof name === 'string' ? { ...option, name } : option\n })\n const next = options.map((option) => option.name)\n if (new Set(next).size !== next.length) return { options, variants: product.variants }\n const variants = (product.variants ?? []).map((variant) => {\n const selections = variant.options\n if (!selections) return variant\n const axisOf = optionAxesOf(current, selections)\n const moved: Record<string, string> = {}\n let changed = false\n for (const [key, value] of Object.entries(selections)) {\n const axis = axisOf.get(key)\n const name = axis === undefined ? key : next[axis]\n if (name !== key) changed = true\n moved[name] = value\n }\n return changed ? { ...variant, options: moved } : variant\n })\n return { options, variants }\n}\n\n/**\n * Which option each of a variant's selections belongs to: the option of the\n * same name first, and then, for a selection under a name no option has any\n * longer, the one remaining option whose values hold its value. A selection\n * that fits neither belongs to no option and is left as it is.\n */\nfunction optionAxesOf(\n options: readonly ProductOption[],\n selections: Readonly<Record<string, string>>,\n): Map<string, number> {\n const axisOf = new Map<string, number>()\n const taken = new Set<number>()\n options.forEach((option, index) => {\n if (Object.prototype.hasOwnProperty.call(selections, option.name) && !axisOf.has(option.name)) {\n axisOf.set(option.name, index)\n taken.add(index)\n }\n })\n for (const [key, value] of Object.entries(selections)) {\n if (axisOf.has(key)) continue\n const axis = options.findIndex(\n (option, index) => !taken.has(index) && (option.values ?? []).includes(value),\n )\n if (axis === -1) continue\n axisOf.set(key, axis)\n taken.add(axis)\n }\n return axisOf\n}\n\n/**\n * Whether a variant has a price a sale can charge (AGL-2916).\n *\n * A product proposed by AI is created with every price left empty for the\n * merchant to set, so a stored variant can lack one. `Number(undefined)` is\n * no price, and neither is `null`, which `Number` reads as zero: a sale door\n * that priced either would charge nothing, or fail at the processor.\n */\nexport function variantHasPrice(variant: object | null | undefined): boolean {\n const price = (variant as { priceUsd?: unknown } | null | undefined)?.priceUsd\n return typeof price === 'number' && Number.isFinite(price) && price >= 0\n}\n\n/** Whether any variant of a product still needs its price set (AGL-2916). */\nexport function productPriceMissing(product: { variants?: readonly object[] }): boolean {\n return (product.variants ?? []).some((variant) => !variantHasPrice(variant))\n}\n\n/** Copy proposed for a product, by field (AGL-2916). A field left out is left alone. */\nexport interface ProductCopyValues {\n description?: string\n tags?: string[]\n categoryIds?: string[]\n /** One name per option the product has, in order. */\n optionNames?: string[]\n seoTitle?: string\n seoDescription?: string\n /**\n * Packed size and customs facts (AGL-3612), merged over what the product\n * has; a side set to `null` is cleared.\n */\n shipping?: Partial<ProductShippingFacts>\n /**\n * Shopping-channel facts (AGL-3637), merged over what the product has; a\n * field set to `''` is cleared.\n */\n channel?: { [Field in keyof ProductChannelFacts]?: string }\n}\n\n/**\n * The fields proposed copy changes on a product (AGL-2916), in the shape the\n * editor stores them: only the fields `values` names. Tags and categories are\n * each kept once; the search listing keeps its share image; and option names\n * rename the product's options through `renameProductOptions`, keeping every\n * variant, only when they name each option once with a name of its own.\n */\nexport function productCopyPatch(\n product: Pick<HostProduct, 'options' | 'variants' | 'seo' | 'shipping'> &\n Pick<Partial<HostProduct>, 'channel'>,\n values: ProductCopyValues,\n): Partial<\n Pick<HostProduct, 'description' | 'tags' | 'categoryIds' | 'seo' | 'options' | 'variants' | 'shipping' | 'channel'>\n> {\n const patch: Partial<\n Pick<HostProduct, 'description' | 'tags' | 'categoryIds' | 'seo' | 'options' | 'variants' | 'shipping' | 'channel'>\n > = {}\n if (values.shipping && typeof values.shipping === 'object') {\n // Stored whole, never `undefined`: the editor's save is a full `setDoc`,\n // which refuses an undefined field. Nothing known is an empty map.\n patch.shipping = draftProductShippingFacts({ ...product.shipping, ...values.shipping }) ?? {}\n }\n if (values.channel && typeof values.channel === 'object') {\n // Stored whole, never `undefined`, for the same reason. Nothing entered\n // is an empty map. Kept as typed: this runs on every keystroke.\n patch.channel = draftProductChannelFacts({ ...product.channel, ...values.channel }) ?? {}\n }\n if (typeof values.description === 'string') patch.description = values.description\n if (Array.isArray(values.tags)) {\n patch.tags = [...new Set(values.tags.map((tag) => tag.trim()).filter(Boolean))]\n }\n if (Array.isArray(values.categoryIds)) {\n patch.categoryIds = [...new Set(values.categoryIds.filter(Boolean))]\n }\n if (typeof values.seoTitle === 'string' || typeof values.seoDescription === 'string') {\n patch.seo = {\n ...product.seo,\n ...(typeof values.seoTitle === 'string' ? { title: values.seoTitle } : {}),\n ...(typeof values.seoDescription === 'string' ? { description: values.seoDescription } : {}),\n }\n }\n const options = product.options ?? []\n const names = values.optionNames?.map((name) => name.trim())\n if (\n names &&\n options.length > 0 &&\n names.length === options.length &&\n names.every(Boolean) &&\n new Set(names).size === names.length &&\n names.some((name, index) => name !== options[index].name)\n ) {\n Object.assign(patch, renameProductOptions(product, names))\n }\n return patch\n}\n\n/** A product proposed for a store, before anyone has priced it (AGL-2916). */\nexport interface ProposedProduct {\n name: string\n type: ProductType\n description: string\n tags: string[]\n options: ProductOption[]\n seoTitle: string\n seoDescription: string\n}\n\n/** A new product whose variants carry no price yet. */\nexport type UnpricedProductDraft = Omit<HostProduct, 'variants'> & {\n variants: Array<Omit<ProductVariant, 'priceUsd'>>\n}\n\n/**\n * The document a proposed product is created as (AGL-2916): a `draft`, under\n * a slug no product in `takenSlugs` has, with one variant for each\n * combination of its options and NO price on any of them. Prices are the\n * merchant's to set: the editor refuses to save the product until every\n * variant has one, and no sale door sells a variant without one\n * (`variantHasPrice`). The search keys travel with the name, as on every\n * create path.\n */\nexport function unpricedProductDraft(\n proposal: ProposedProduct,\n takenSlugs: ReadonlySet<string>,\n nowMs: number,\n): UnpricedProductDraft {\n const name = proposal.name.trim().slice(0, 120)\n const base = commerceSlug(name) || 'product'\n let slug = base\n for (let suffix = 2; takenSlugs.has(slug); suffix += 1) slug = `${base}-${suffix}`\n const seen = new Set<string>()\n const options = proposal.options\n .map((option) => ({\n name: option.name.trim(),\n values: [...new Set(option.values.map((value) => value.trim()).filter(Boolean))].slice(\n 0,\n COMMERCE_MAX_OPTION_VALUES,\n ),\n }))\n .filter((option) => {\n if (!option.name || !option.values.length || seen.has(option.name)) return false\n seen.add(option.name)\n return true\n })\n .slice(0, COMMERCE_MAX_OPTIONS)\n const variants = options.length\n ? expandVariantMatrix(options).map((combo, index) => ({\n id: `v${nowMs.toString(36)}${index}`,\n options: combo,\n }))\n : [{ id: 'default' }]\n const seoTitle = proposal.seoTitle.trim()\n const seoDescription = proposal.seoDescription.trim()\n return {\n // The keys for the variants as created: no price is `priceFromCents: 0`\n // and no tracked stock is never sold out, so the draft is ordered and\n // filtered like every other product once it is priced and activated.\n ...productSearchFields({ name, variants: variants as ProductVariant[] }),\n ...productStockFields({ variants: variants as ProductVariant[] }),\n slug,\n type: proposal.type,\n status: 'draft',\n description: proposal.description,\n tags: [...new Set(proposal.tags.map((tag) => tag.trim()).filter(Boolean))],\n ...(options.length ? { options } : {}),\n variants,\n ...(seoTitle || seoDescription\n ? { seo: { ...(seoTitle ? { title: seoTitle } : {}), ...(seoDescription ? { description: seoDescription } : {}) } }\n : {}),\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** Variant whose option selections match exactly; undefined if none. */\nexport function findVariant(\n product: Pick<HostProduct, 'variants'>,\n selections: Record<string, string>,\n): ProductVariant | undefined {\n return product.variants?.find((variant) => {\n const options = variant.options ?? {}\n const keys = new Set([...Object.keys(options), ...Object.keys(selections)])\n for (const key of keys) {\n if (options[key] !== selections[key]) return false\n }\n return true\n })\n}\n\n/** [min, max] price across variants; [0, 0] when there are none. */\nexport function productPriceRange(\n product: Pick<HostProduct, 'variants'>,\n): [number, number] {\n const prices = (product.variants ?? [])\n .map((variant) => Number(variant.priceUsd))\n .filter((price) => Number.isFinite(price) && price >= 0)\n if (prices.length === 0) return [0, 0]\n return [Math.min(...prices), Math.max(...prices)]\n}\n\n/** Sum of tracked inventory; null when every variant is untracked. */\nexport function productInventory(\n product: Pick<HostProduct, 'variants'>,\n): number | null {\n let total: number | null = null\n for (const variant of product.variants ?? []) {\n if (variant.inventory == null) continue\n total = (total ?? 0) + Number(variant.inventory)\n }\n return total\n}\n\n/**\n * Reasons an inventory adjustment doc may carry (AGL-281).\n *\n * `cancellation` is the only one written automatically in the PLUS direction\n * (AGL-1808): cancelling an order the transition rules prove was never\n * fulfilled puts back exactly what the sale took. It is deliberately not\n * `refund` — no money moved — and not `correction`, which is what a merchant\n * picks when the count disagreed with the shelf for a reason nobody recorded.\n * Kept out of the \"Adjust stock\" dialog's menu on purpose: a merchant reaching\n * for it by hand means something else happened.\n *\n * `sync` is a count another warehouse reported (AGL-3634): a fulfillment\n * network holding the goods said how many it can ship, and the count was set\n * to that. Written only through core's `core.stock-levels`, with `source`\n * naming who counted, and kept out of the dialog's menu for the same reason.\n */\nexport type InventoryAdjustmentReason =\n 'sale' | 'refund' | 'restock' | 'correction' | 'damage' | 'cancellation' | 'sync'\n\n/** `hosts/{hostId}/inventoryAdjustments/{id}` doc. */\nexport interface InventoryAdjustment {\n productId: string\n variantId: string\n /** Positive = stock added, negative = removed. */\n delta: number\n /**\n * What the count ACTUALLY moved by, when the floor in\n * `adjustVariantInventory` absorbed part of `delta` (AGL-2149). Written only\n * when the two differ, which for a sale means a backorder product that sold\n * past zero: `delta` stays the units sold — that is the merchant's stock\n * history and it must keep saying \"3 went out the door\" — while this says how\n * many of them the count could give up.\n *\n * A REVERSAL MUST READ THIS, NOT `delta`. Restoring `delta` on a backorder\n * sale that the floor swallowed invents inventory that never existed: 0 sells\n * 3, the count stays 0, and a `+3` on cancellation leaves 3 units nobody has.\n * Absent on every row written before AGL-2149 and on every row where nothing\n * was clamped, so `appliedDelta ?? delta` is the reader.\n */\n appliedDelta?: number\n reason: InventoryAdjustmentReason\n /** Order id for sale/refund adjustments. */\n orderId?: string\n /** Location for multi-location stock (AGL-286); absent = default. */\n locationId?: string\n /**\n * Who counted, for a `sync` row: the warehouse that reported it (AGL-3634);\n * for a `sale` another channel made, that channel (AGL-3638).\n */\n source?: string\n atMs: number\n}\n\n/**\n * Whether `quantity` of a variant is purchasable (AGL-281): untracked\n * stock always is; tracked stock honors the product's oversell policy.\n */\nexport function canPurchase(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n variantId: string | undefined,\n quantity = 1,\n): boolean {\n const variant = variantId\n ? product.variants?.find((item) => item.id === variantId)\n : product.variants?.[0]\n if (!variant) return false\n if (variant.inventory == null) return true\n if (product.oversellPolicy === 'backorder') return true\n return Number(variant.inventory) >= quantity\n}\n\n/**\n * What the register has to SAY about a line it is about to sell (AGL-2357).\n *\n * ## The defect\n *\n * `pos-order.ts` contains no `canPurchase` call. Every storefront door gates on\n * it; the register does not, so a merchant who set `oversellPolicy: 'deny'` in\n * the product editor silently got `backorder` at the counter — the count floors\n * at zero underneath and nothing anywhere says so.\n *\n * ## The decision, and why it is a shortfall and not a refusal\n *\n * Warn, never block. A till is the wrong place for a stale number to stop a\n * real sale: the cashier is holding the goods, the physical shelf is the truth,\n * and refusing loses a sale over data that is behind. But \"deny\" must at least\n * SAY something. So this reports the shortfall and the caller sells anyway.\n * Honouring the policy with a manager-level override is the post-launch shape\n * (AGL-2372) and wants an audit trail this deliberately does not build.\n *\n * ## Why the test is `canPurchase`\n *\n * Exactly the gate the register was missing, and no wider. An untracked variant\n * has no number to be short against, and a `backorder` product's merchant chose\n * to sell past zero — warning them would be noise about a setting they set on\n * purpose. So a shortfall is reported only where a purchase would have been\n * refused anywhere else in the product.\n */\nexport interface StockShortfall {\n productId: string\n variantId?: string\n /** Product name at the time of sale, for a message the cashier can read. */\n name: string\n variantLabel?: string\n /** Units the cashier is ringing up. */\n requested: number\n /** Units the count says are on the shelf; never negative. */\n available: number\n}\n\nexport function stockShortfall(\n product: Pick<HostProduct, 'variants' | 'oversellPolicy'>,\n variantId: string | undefined,\n quantity = 1,\n): { available: number } | null {\n if (canPurchase(product, variantId, quantity)) return null\n const variant = variantId\n ? product.variants?.find((item) => item.id === variantId)\n : product.variants?.[0]\n // `canPurchase` answers false for a variant that does not exist at all. That\n // is not a stock shortfall and must not be reported as \"0 in stock\" — the\n // register's own line builder falls back to `variants[0]`, so the case is\n // unreachable from the counter, and inventing a count for it would be the\n // one failure mode this feature must not have.\n if (!variant || variant.inventory == null) return null\n return { available: Math.max(0, Math.round(Number(variant.inventory) || 0)) }\n}\n\n/**\n * Whether stock tracking MEANS anything on a product (AGL-1744).\n *\n * `canPurchase` above gates every checkout on stock, subscription sessions\n * included, but nothing ever decrements for a subscription — not on the\n * initial charge (the `commerce-subscription` webhook branch deliberately\n * writes no order and touches no inventory, AGL-1732) and not on renewal\n * (`invoice.payment_succeeded` is unhandled repo-wide, AGL-1743). So on a\n * subscription-only product that gate is permanently satisfied: one unit of\n * stock sells an unlimited number of subscriptions, and the count never\n * moves however many boxes ship. The merchant set a number, the system\n * checks it on every sale, and the number is never true.\n *\n * AGL-1750 resolved the half AGL-1744 had to leave open: every paid invoice\n * of a PHYSICAL subscription now mints an order and decrements its variant's\n * stock (the `invoice.paid` branch of the commerce webhook), opening cycle\n * included. So the honest split is now three-way:\n *\n * - `subscriptionOptional` (\"Both\") products have a real one-time path —\n * the cart only ever builds `mode: 'payment'` sessions, and buy-now with\n * `billing: 'once'` records a plain order — and that path decrements\n * honestly. Withdrawing stock tracking there would delete a working\n * control and re-open the AGL-1711 oversell on the half that works.\n * - a PHYSICAL subscription box consumes a unit every cycle, and since\n * AGL-1750 the cycle's own order decrements it — the count moves as the\n * boxes ship, so the number the merchant sets is kept true again.\n * - a DIGITAL or SERVICE subscription-only product still has no\n * decrementing path anywhere, so the field stays withdrawn there: one\n * unit would still sell unlimited subscriptions.\n *\n * This says nothing about what `canPurchase` returns — that is the gate for\n * every other purchase path and is deliberately untouched. This is a console\n * predicate: it stops the editor inviting a merchant to set a number the\n * system will never keep true.\n */\nexport function stockTrackingApplies(\n product: Pick<HostProduct, 'subscription' | 'subscriptionOptional' | 'type'>,\n): boolean {\n return (\n !product.subscription ||\n product.subscriptionOptional === true ||\n product.type === 'physical'\n )\n}\n\n/** Buyer's requested billing mode on a checkout POST (AGL-545). */\nexport type CheckoutBillingChoice = 'once' | 'subscribe'\n\n/**\n * Resolves the Stripe Checkout mode for a product + the buyer's\n * requested billing choice (AGL-545). The product doc is authoritative:\n * - no `subscription` → always one-time (the request field is ignored)\n * - `subscription` without `subscriptionOptional` → always subscription\n * (a forged `billing: 'once'` cannot buy a subscription product once)\n * - `subscriptionOptional` → the buyer chooses; absent/invalid choices\n * default to one-time, matching the PDP default.\n */\nexport function resolveCheckoutBillingMode(\n product: Pick<HostProduct, 'subscription' | 'subscriptionOptional'>,\n requested?: string | null,\n): 'payment' | 'subscription' {\n if (!product.subscription) return 'payment'\n if (!product.subscriptionOptional) return 'subscription'\n return requested === 'subscribe' ? 'subscription' : 'payment'\n}\n\n/**\n * Applies a stock delta to one variant, flooring at zero (race-window\n * sales can't drive the display negative), and returns the new variants\n * array — callers persist it plus the `productInventory` denormalization.\n * With `locationId`, the delta lands in that location's bucket and the\n * flat `inventory` re-sums across locations (AGL-286).\n */\nexport function adjustVariantInventory(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n delta: number,\n locationId?: string,\n): ProductVariant[] {\n return (product.variants ?? []).map((variant) => {\n if (variant.id !== variantId || variant.inventory == null) return variant\n if (locationId && variant.inventoryByLocation) {\n const buckets = {\n ...variant.inventoryByLocation,\n [locationId]: Math.max(\n 0,\n Number(variant.inventoryByLocation[locationId] ?? 0) + delta,\n ),\n }\n return {\n ...variant,\n inventoryByLocation: buckets,\n inventory: Object.values(buckets).reduce(\n (sum, count) => sum + Number(count),\n 0,\n ),\n }\n }\n return {\n ...variant,\n inventory: Math.max(0, Number(variant.inventory) + delta),\n }\n })\n}\n\n/**\n * What `adjustVariantInventory` will ACTUALLY move the count by (AGL-2149).\n *\n * The floor in that helper is not a rounding detail, it is a silent absorber. A\n * backorder product (`oversellPolicy: 'backorder'`, which `canPurchase` admits\n * at any stock level) sitting at 0 sells 3: `Math.max(0, 0 + -3)` is 0, so the\n * count does not move — correctly, since inventory is a shelf count and shelves\n * do not go negative — but the ledger row said `-3` and every reversal read it\n * as three units to put back. Cancelling that order handed the merchant 3 units\n * that never existed and a stock badge that offers them for sale.\n *\n * Removing the floor is not the alternative: every reader of `inventory` — the\n * badges, `canPurchase`, `productInventory`, `isLowStock` — assumes it cannot\n * go negative, and a negative count would be a far wider change than the bug.\n * So the clamp stays and the amount it absorbed is recorded instead.\n *\n * Deliberately mirrors `adjustVariantInventory`'s own arithmetic, including\n * which field the clamp applies to in the location-tracked case, so the two\n * cannot disagree about what happened.\n */\nexport function appliedVariantInventoryDelta(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n delta: number,\n locationId?: string,\n): number {\n const variant = (product.variants ?? []).find(\n (item) => item.id === variantId,\n )\n if (!variant || variant.inventory == null) return 0\n if (locationId && variant.inventoryByLocation) {\n const before = Number(variant.inventoryByLocation[locationId] ?? 0)\n return Math.max(0, before + delta) - before\n }\n const before = Number(variant.inventory)\n return Math.max(0, before + delta) - before\n}\n\n/**\n * Moves stock between two locations of a tracked variant (AGL-286).\n * Quantity clamps to what the source location holds; the flat total is\n * unchanged by construction.\n */\nexport function transferVariantInventory(\n product: Pick<HostProduct, 'variants'>,\n variantId: string,\n fromLocationId: string,\n toLocationId: string,\n quantity: number,\n): ProductVariant[] {\n return (product.variants ?? []).map((variant) => {\n if (variant.id !== variantId || variant.inventory == null) return variant\n const buckets = { ...(variant.inventoryByLocation ?? {}) }\n const available = Math.max(0, Number(buckets[fromLocationId] ?? 0))\n const moved = Math.min(available, Math.max(0, Math.round(quantity)))\n if (moved === 0) return variant\n buckets[fromLocationId] = available - moved\n buckets[toLocationId] = Math.max(0, Number(buckets[toLocationId] ?? 0)) + moved\n return { ...variant, inventoryByLocation: buckets }\n })\n}\n\n/** True when tracked stock is at/below the product's alert threshold. */\nexport function isLowStock(\n product: Pick<HostProduct, 'variants' | 'lowStockThreshold'>,\n): boolean {\n const threshold = product.lowStockThreshold\n if (threshold == null || !(threshold >= 0)) return false\n const total = productInventory(product)\n return total != null && total <= threshold\n}\n\nfunction ruleMatches(product: HostProduct, rule: CollectionRule): boolean {\n const value = rule.value\n switch (rule.field) {\n case 'tag': {\n const tags = product.tags ?? []\n const has = tags.includes(String(value))\n return rule.op === 'neq' ? !has : has\n }\n case 'categoryId': {\n const ids = product.categoryIds ?? []\n const has = ids.includes(String(value))\n return rule.op === 'neq' ? !has : has\n }\n case 'priceUsd': {\n const [min, max] = productPriceRange(product)\n const numeric = Number(value)\n if (!Number.isFinite(numeric)) return false\n if (rule.op === 'lt') return min < numeric\n if (rule.op === 'gt') return max > numeric\n if (rule.op === 'neq') return min !== numeric || max !== numeric\n return min <= numeric && numeric <= max\n }\n case 'name': {\n const name = (product.name ?? '').toLowerCase()\n const needle = String(value).toLowerCase()\n if (rule.op === 'contains') return name.includes(needle)\n if (rule.op === 'neq') return name !== needle\n return name === needle\n }\n case 'type': {\n const matches = product.type === value\n return rule.op === 'neq' ? !matches : matches\n }\n default:\n return false\n }\n}\n\n/**\n * Whether a product's own fields answer a SMART collection's rules — its\n * tags, categories, prices, name and type, and nothing about whether it is\n * on sale. That is the storefront query's scope (`deletedAt == null`,\n * `status == 'active'`), so membership stored on the product never goes stale\n * when a product is archived or brought back.\n *\n * A collection with no rules holds nothing.\n */\n/** What smart-collection membership reads of a product — a draft's too. */\nexport interface MembershipProduct {\n name?: string\n type?: ProductType\n tags?: string[]\n categoryIds?: string[]\n variants?: ReadonlyArray<{ id?: string; priceUsd?: number | null }>\n}\n\nexport function smartCollectionMatches(\n product: MembershipProduct,\n collection: Pick<HostCollection, 'rules' | 'matchAll'>,\n): boolean {\n const rules = collection.rules ?? []\n if (rules.length === 0) return false\n const matcher = (rule: CollectionRule) => ruleMatches(product as HostProduct, rule)\n return collection.matchAll === false\n ? rules.some(matcher)\n : rules.every(matcher)\n}\n\n/**\n * Smart-collection membership: draft/archived/deleted products never\n * match; manual collections answer from productIds.\n */\nexport function matchesCollection(\n product: HostProduct,\n collection: HostCollection,\n productId?: string,\n): boolean {\n if (product.deletedAt || product.status !== 'active') return false\n if (collection.mode === 'manual') {\n return productId != null &&\n (collection.productIds ?? []).includes(productId)\n }\n return smartCollectionMatches(product, collection)\n}\n\n/**\n * The stored membership of a product in the host's SMART collections\n * (AGL-3321): the ids of those whose rules it answers\n * ({@link smartCollectionMatches}), sorted.\n *\n * The storefront reads a smart collection whose rules no query can hold (a\n * NOT, an OR, a name rule, a price over) as `collectionIds array-contains\n * <id>` — so the membership is WRITTEN, by every product writer from the\n * host's smart collections as they stand, and by the collection-membership\n * route for every product whenever a smart collection's rules change or it\n * is deleted. `tools/scripts/backfill-product-collection-ids.mjs` stamps the\n * products written before; the two answer\n * `tools/scripts/lib/product-collection-ids.fixtures.json`.\n */\nexport const PRODUCT_COLLECTION_IDS = 'collectionIds'\n\n/** A smart collection as membership is computed from it. */\nexport interface SmartCollectionRules {\n id: string\n rules?: CollectionRule[]\n matchAll?: boolean\n}\n\nexport function productCollectionIds(\n product: MembershipProduct,\n smartCollections: readonly SmartCollectionRules[],\n): string[] {\n return smartCollections\n .filter((collection) => smartCollectionMatches(product, collection))\n .map((collection) => collection.id)\n .sort()\n}\n\n/**\n * Lifts a legacy Commerce Starter doc (AGL-90: flat name/priceUsd/\n * inventory/imageUrl) into the catalog shape with a single default\n * variant. Already-lifted docs pass through unchanged.\n */\nexport function liftLegacyProduct(\n raw: Partial<HostProduct> & { name?: string },\n): HostProduct {\n if (Array.isArray(raw.variants) && raw.variants.length > 0) {\n return raw as HostProduct\n }\n const priceUsd = Number(raw.priceUsd ?? 0)\n return {\n ...raw,\n name: raw.name ?? 'Product',\n slug: raw.slug || commerceSlug(raw.name ?? 'product'),\n type: raw.type ?? 'physical',\n status: raw.status ?? 'active',\n variants: [\n {\n id: 'default',\n priceUsd: Number.isFinite(priceUsd) ? priceUsd : 0,\n inventory: raw.inventory ?? null,\n },\n ],\n }\n}\n\n/** Actionable error, or null when the product is storable. */\nexport function validateProduct(product: HostProduct): string | null {\n if (!product.name?.trim()) return 'Product name is required'\n if (!product.slug || product.slug !== commerceSlug(product.slug)) {\n return 'Slug must be lowercase letters, numbers, and dashes'\n }\n if (!['physical', 'digital', 'service'].includes(product.type)) {\n return 'Unknown product type'\n }\n if (!['draft', 'active', 'archived'].includes(product.status)) {\n return 'Unknown product status'\n }\n const options = product.options ?? []\n if (options.length > COMMERCE_MAX_OPTIONS) {\n return `At most ${COMMERCE_MAX_OPTIONS} options per product`\n }\n for (const option of options) {\n if (!option.name?.trim()) return 'Option names are required'\n if ((option.values?.length ?? 0) === 0) {\n return `Option \"${option.name}\" needs at least one value`\n }\n if (option.values.length > COMMERCE_MAX_OPTION_VALUES) {\n return `Option \"${option.name}\" has too many values`\n }\n if (new Set(option.values).size !== option.values.length) {\n return `Option \"${option.name}\" has duplicate values`\n }\n }\n // A variant keys its selections by option name, so two options with one\n // name cannot both be selected (AGL-3066).\n if (new Set(options.map((option) => option.name.trim())).size !== options.length) {\n return 'Each option needs its own name'\n }\n const modifierProblem = modifierGroupsProblem(product.modifierGroups)\n if (modifierProblem) return modifierProblem\n const variants = product.variants ?? []\n if (variants.length === 0) return 'Products need at least one variant'\n if (variants.length > COMMERCE_MAX_VARIANTS) {\n return `At most ${COMMERCE_MAX_VARIANTS} variants per product`\n }\n const ids = new Set<string>()\n const skus = new Set<string>()\n for (const variant of variants) {\n if (!variant.id) return 'Variants need stable ids'\n if (ids.has(variant.id)) return 'Variant ids must be unique'\n ids.add(variant.id)\n if (variant.priceUsd === undefined || variant.priceUsd === null) {\n return 'Set a price for every variant'\n }\n const price = Number(variant.priceUsd)\n if (!Number.isFinite(price) || price < 0) {\n return 'Variant prices must be zero or more'\n }\n if (price > COMMERCE_MAX_PRICE_USD) {\n return `Prices are capped at $${COMMERCE_MAX_PRICE_USD}`\n }\n if (variant.sku) {\n if (skus.has(variant.sku)) return 'Variant SKUs must be unique'\n skus.add(variant.sku)\n }\n if (\n variant.compareAtPriceUsd != null &&\n Number(variant.compareAtPriceUsd) <= price\n ) {\n return 'Compare-at price must exceed the price'\n }\n }\n return null\n}\n\n/** Actionable error, or null when the collection is storable. */\nexport function validateCollection(collection: HostCollection): string | null {\n if (!collection.name?.trim()) return 'Collection name is required'\n if (\n !collection.slug ||\n collection.slug !== commerceSlug(collection.slug)\n ) {\n return 'Slug must be lowercase letters, numbers, and dashes'\n }\n if (collection.mode !== 'manual' && collection.mode !== 'smart') {\n return 'Unknown collection mode'\n }\n if (collection.mode === 'smart') {\n const rules = collection.rules ?? []\n if (rules.length === 0) return 'Smart collections need at least one rule'\n for (const rule of rules) {\n if (\n !['tag', 'categoryId', 'priceUsd', 'name', 'type'].includes(rule.field)\n ) {\n return 'Unknown rule field'\n }\n if (!['eq', 'neq', 'lt', 'gt', 'contains'].includes(rule.op)) {\n return 'Unknown rule operator'\n }\n if (rule.value === '' || rule.value == null) {\n return 'Rule values are required'\n }\n }\n }\n return null\n}\n"],"names":["modifierGroupsProblem","nameSearchFields","draftProductChannelFacts","COMMERCE_MAX_PRICE_USD","productParcelDimensions","product","facts","shipping","side","value","number","Number","isFinite","Math","min","lengthCm","widthCm","heightCm","undefined","draftProductShippingFacts","normalizeProductShippingFacts","typed","String","trim","toUpperCase","test","originCountry","raw","round","hsCode","replace","slice","Object","keys","length","normalizePostalAddress","address","field","text","country","registersWithinCap","registers","cap","createdMs","r","createdAt","toMillis","seconds","ranked","sort","a","b","$id","localeCompare","Set","max","map","COMMERCE_MAX_VARIANTS","COMMERCE_MAX_OPTIONS","COMMERCE_MAX_OPTION_VALUES","COMMERCE_SLUG_MAX_LENGTH","commerceSlug","name","normalize","toLowerCase","productSearchFields","flatten","read","variants","variant","filter","Boolean","skus","sku","barcodes","barcode","priceFromCents","productPriceFromCents","productPriceRange","productStockFields","inventory","productInventory","soldOut","oversellPolicy","expandVariantMatrix","options","usable","option","values","combos","next","combo","push","renameProductOptions","names","current","index","size","selections","axisOf","optionAxesOf","moved","changed","key","entries","axis","get","Map","taken","forEach","prototype","hasOwnProperty","call","has","set","add","findIndex","includes","variantHasPrice","price","priceUsd","productPriceMissing","some","productCopyPatch","patch","channel","description","Array","isArray","tags","tag","categoryIds","seoTitle","seoDescription","seo","title","optionNames","every","assign","unpricedProductDraft","proposal","takenSlugs","nowMs","base","slug","suffix","seen","id","toString","type","status","createdAtMs","updatedAtMs","findVariant","find","prices","total","canPurchase","variantId","quantity","item","stockShortfall","available","stockTrackingApplies","subscription","subscriptionOptional","resolveCheckoutBillingMode","requested","adjustVariantInventory","delta","locationId","inventoryByLocation","buckets","reduce","sum","count","appliedVariantInventoryDelta","before","transferVariantInventory","fromLocationId","toLocationId","isLowStock","threshold","lowStockThreshold","ruleMatches","rule","op","ids","numeric","needle","matches","smartCollectionMatches","collection","rules","matcher","matchAll","matchesCollection","productId","deletedAt","mode","productIds","PRODUCT_COLLECTION_IDS","productCollectionIds","smartCollections","liftLegacyProduct","validateProduct","modifierProblem","modifierGroups","compareAtPriceUsd","validateCollection"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,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;QAC/B,KAAK,MAAMuJ,QAAQQ,MAAO;YACxB,IACE,CAAC;gBAAC;gBAAO;gBAAc;gBAAY;gBAAQ;aAAO,CAAC5E,QAAQ,CAACoE,KAAKpJ,KAAK,GACtE;gBACA,OAAO;YACT;YACA,IAAI,CAAC;gBAAC;gBAAM;gBAAO;gBAAM;gBAAM;aAAW,CAACgF,QAAQ,CAACoE,KAAKC,EAAE,GAAG;gBAC5D,OAAO;YACT;YACA,IAAID,KAAKhL,KAAK,KAAK,MAAMgL,KAAKhL,KAAK,IAAI,MAAM;gBAC3C,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT"}
@@ -29,7 +29,11 @@ export * from './commerce-dispute';
29
29
  export * from './commerce-topics';
30
30
  export * from './commerce-gift-cards';
31
31
  export * from './commerce-orders';
32
+ export * from './commerce-printers';
33
+ export * from './commerce-pos';
34
+ export * from './product-modifiers';
32
35
  export * from './commerce-promotions';
36
+ export * from './commerce-receipt';
33
37
  export * from './commerce-reservations';
34
38
  export * from './commerce-shipping';
35
39
  export * from './commerce-stock-holds';
@@ -39,3 +43,15 @@ export * from './commerce-tax-decision';
39
43
  export * from './order-figures';
40
44
  export * from './order-list-fields';
41
45
  export * from './purchase-analytics';
46
+ export * from './tracking-url';
47
+ export * from './buyer-notifications';
48
+ export * from './order-fulfillment';
49
+ export * from './order-events';
50
+ export * from './commerce-returns';
51
+ export * from './order-shipping-export';
52
+ export * from './order-status-view';
53
+ export * from './order-webhooks';
54
+ export * from './shipstation';
55
+ export * from './commerce-payment-methods';
56
+ export * from './product-channel';
57
+ export * from './product-write';
@@ -27,7 +27,11 @@ export * from "./commerce-dispute.js";
27
27
  export * from "./commerce-topics.js";
28
28
  export * from "./commerce-gift-cards.js";
29
29
  export * from "./commerce-orders.js";
30
+ export * from "./commerce-printers.js";
31
+ export * from "./commerce-pos.js";
32
+ export * from "./product-modifiers.js";
30
33
  export * from "./commerce-promotions.js";
34
+ export * from "./commerce-receipt.js";
31
35
  export * from "./commerce-reservations.js";
32
36
  export * from "./commerce-shipping.js";
33
37
  export * from "./commerce-stock-holds.js";
@@ -37,5 +41,17 @@ export * from "./commerce-tax-decision.js";
37
41
  export * from "./order-figures.js";
38
42
  export * from "./order-list-fields.js";
39
43
  export * from "./purchase-analytics.js";
44
+ export * from "./tracking-url.js";
45
+ export * from "./buyer-notifications.js";
46
+ export * from "./order-fulfillment.js";
47
+ export * from "./order-events.js";
48
+ export * from "./commerce-returns.js";
49
+ export * from "./order-shipping-export.js";
50
+ export * from "./order-status-view.js";
51
+ export * from "./order-webhooks.js";
52
+ export * from "./shipstation.js";
53
+ export * from "./commerce-payment-methods.js";
54
+ export * from "./product-channel.js";
55
+ export * from "./product-write.js";
40
56
 
41
57
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/index.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 * Commerce domain model (AGL-411): pure types + logic relocated from the\n * core `@aglyn/aglyn` app-utils — the commerce plugin owns its domain.\n * Context-free and framework-free, so both the plugin's client components\n * and its `/server` handlers (and other plugins/apps via\n * `@aglyn/plugins-commerce/model`) can import it.\n */\nexport * from './commerce'\nexport * from './commerce-cart'\nexport * from './commerce-connect-transfer'\nexport * from './commerce-discounts'\nexport * from './commerce-dispute'\nexport * from './commerce-topics'\nexport * from './commerce-gift-cards'\nexport * from './commerce-orders'\nexport * from './commerce-promotions'\nexport * from './commerce-reservations'\nexport * from './commerce-shipping'\nexport * from './commerce-stock-holds'\nexport * from './commerce-subscription-status'\nexport * from './commerce-tax'\nexport * from './commerce-tax-decision'\nexport * from './order-figures'\nexport * from './order-list-fields'\nexport * from './purchase-analytics'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GACD,cAAc,gBAAY;AAC1B,cAAc,qBAAiB;AAC/B,cAAc,iCAA6B;AAC3C,cAAc,0BAAsB;AACpC,cAAc,wBAAoB;AAClC,cAAc,uBAAmB;AACjC,cAAc,2BAAuB;AACrC,cAAc,uBAAmB;AACjC,cAAc,2BAAuB;AACrC,cAAc,6BAAyB;AACvC,cAAc,yBAAqB;AACnC,cAAc,4BAAwB;AACtC,cAAc,oCAAgC;AAC9C,cAAc,oBAAgB;AAC9B,cAAc,6BAAyB;AACvC,cAAc,qBAAiB;AAC/B,cAAc,yBAAqB;AACnC,cAAc,0BAAsB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/index.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 * Commerce domain model (AGL-411): pure types + logic relocated from the\n * core `@aglyn/aglyn` app-utils — the commerce plugin owns its domain.\n * Context-free and framework-free, so both the plugin's client components\n * and its `/server` handlers (and other plugins/apps via\n * `@aglyn/plugins-commerce/model`) can import it.\n */\nexport * from './commerce'\nexport * from './commerce-cart'\nexport * from './commerce-connect-transfer'\nexport * from './commerce-discounts'\nexport * from './commerce-dispute'\nexport * from './commerce-topics'\nexport * from './commerce-gift-cards'\nexport * from './commerce-orders'\nexport * from './commerce-printers'\nexport * from './commerce-pos'\nexport * from './product-modifiers'\nexport * from './commerce-promotions'\nexport * from './commerce-receipt'\nexport * from './commerce-reservations'\nexport * from './commerce-shipping'\nexport * from './commerce-stock-holds'\nexport * from './commerce-subscription-status'\nexport * from './commerce-tax'\nexport * from './commerce-tax-decision'\nexport * from './order-figures'\nexport * from './order-list-fields'\nexport * from './purchase-analytics'\nexport * from './tracking-url'\nexport * from './buyer-notifications'\nexport * from './order-fulfillment'\nexport * from './order-events'\nexport * from './commerce-returns'\nexport * from './order-shipping-export'\nexport * from './order-status-view'\nexport * from './order-webhooks'\nexport * from './shipstation'\nexport * from './commerce-payment-methods'\nexport * from './product-channel'\nexport * from './product-write'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GACD,cAAc,gBAAY;AAC1B,cAAc,qBAAiB;AAC/B,cAAc,iCAA6B;AAC3C,cAAc,0BAAsB;AACpC,cAAc,wBAAoB;AAClC,cAAc,uBAAmB;AACjC,cAAc,2BAAuB;AACrC,cAAc,uBAAmB;AACjC,cAAc,yBAAqB;AACnC,cAAc,oBAAgB;AAC9B,cAAc,yBAAqB;AACnC,cAAc,2BAAuB;AACrC,cAAc,wBAAoB;AAClC,cAAc,6BAAyB;AACvC,cAAc,yBAAqB;AACnC,cAAc,4BAAwB;AACtC,cAAc,oCAAgC;AAC9C,cAAc,oBAAgB;AAC9B,cAAc,6BAAyB;AACvC,cAAc,qBAAiB;AAC/B,cAAc,yBAAqB;AACnC,cAAc,0BAAsB;AACpC,cAAc,oBAAgB;AAC9B,cAAc,2BAAuB;AACrC,cAAc,yBAAqB;AACnC,cAAc,oBAAgB;AAC9B,cAAc,wBAAoB;AAClC,cAAc,6BAAyB;AACvC,cAAc,yBAAqB;AACnC,cAAc,sBAAkB;AAChC,cAAc,mBAAe;AAC7B,cAAc,gCAA4B;AAC1C,cAAc,uBAAmB;AACjC,cAAc,qBAAiB"}