@aglyn/plugins-commerce 1.29.1 → 1.29.3

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 (89) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/checkout-tax-blocked-notice.component.d.ts +18 -0
  3. package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
  4. package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
  5. package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
  6. package/src/lib/components/console/payments-settings-card.component.js +99 -5
  7. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  8. package/src/lib/components/console/product-editor-dialog.component.js +14 -3
  9. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/products-hub-card.component.js +51 -14
  11. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  12. package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
  13. package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
  14. package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
  15. package/src/lib/components/console/tax-settings-card.component.js +22 -8
  16. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  17. package/src/lib/constants/operator-alerts.d.ts +9 -0
  18. package/src/lib/constants/operator-alerts.js +22 -1
  19. package/src/lib/constants/operator-alerts.js.map +1 -1
  20. package/src/lib/declarations.server.js +11 -0
  21. package/src/lib/declarations.server.js.map +1 -1
  22. package/src/lib/model/commerce-record-routes.d.ts +13 -1
  23. package/src/lib/model/commerce-record-routes.js +22 -2
  24. package/src/lib/model/commerce-record-routes.js.map +1 -1
  25. package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
  26. package/src/lib/model/commerce-tax-readiness.js +99 -0
  27. package/src/lib/model/commerce-tax-readiness.js.map +1 -0
  28. package/src/lib/model/commerce.d.ts +7 -0
  29. package/src/lib/model/commerce.js +17 -4
  30. package/src/lib/model/commerce.js.map +1 -1
  31. package/src/lib/model/payments-setup-status.d.ts +68 -0
  32. package/src/lib/model/payments-setup-status.js +103 -0
  33. package/src/lib/model/payments-setup-status.js.map +1 -0
  34. package/src/lib/plan-entitlements.d.ts +2 -2
  35. package/src/lib/plan-entitlements.js +4 -12
  36. package/src/lib/plan-entitlements.js.map +1 -1
  37. package/src/lib/server/cart-checkout.js +3 -0
  38. package/src/lib/server/cart-checkout.js.map +1 -1
  39. package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
  40. package/src/lib/server/checkout-tax-refusal.js +133 -0
  41. package/src/lib/server/checkout-tax-refusal.js.map +1 -0
  42. package/src/lib/server/checkout.d.ts +2 -1
  43. package/src/lib/server/checkout.js +7 -2
  44. package/src/lib/server/checkout.js.map +1 -1
  45. package/src/lib/server/connect-prefill.d.ts +65 -0
  46. package/src/lib/server/connect-prefill.js +85 -0
  47. package/src/lib/server/connect-prefill.js.map +1 -0
  48. package/src/lib/server/connect.d.ts +4 -2
  49. package/src/lib/server/connect.js +117 -37
  50. package/src/lib/server/connect.js.map +1 -1
  51. package/src/lib/server/draft-order.js +4 -2
  52. package/src/lib/server/draft-order.js.map +1 -1
  53. package/src/lib/server/pos-order.js +1 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/product-writer.d.ts +27 -0
  56. package/src/lib/server/product-writer.js +174 -4
  57. package/src/lib/server/product-writer.js.map +1 -1
  58. package/src/lib/server/quote-pay.d.ts +6 -0
  59. package/src/lib/server/quote-pay.js +8 -2
  60. package/src/lib/server/quote-pay.js.map +1 -1
  61. package/src/lib/server/seller-stripe-account.d.ts +19 -0
  62. package/src/lib/server/seller-stripe-account.js +40 -4
  63. package/src/lib/server/seller-stripe-account.js.map +1 -1
  64. package/src/lib/server/site-page-resolver.d.ts +11 -5
  65. package/src/lib/server/site-page-resolver.js +102 -19
  66. package/src/lib/server/site-page-resolver.js.map +1 -1
  67. package/src/lib/server/site-search.d.ts +43 -0
  68. package/src/lib/server/site-search.js +124 -0
  69. package/src/lib/server/site-search.js.map +1 -0
  70. package/src/lib/server/tax-readiness.d.ts +56 -0
  71. package/src/lib/server/tax-readiness.js +169 -0
  72. package/src/lib/server/tax-readiness.js.map +1 -0
  73. package/src/lib/server.js +10 -2
  74. package/src/lib/server.js.map +1 -1
  75. package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
  76. package/src/lib/transfer/product-image-copy.server.js +307 -0
  77. package/src/lib/transfer/product-image-copy.server.js.map +1 -0
  78. package/src/lib/transfer/product-images.d.ts +62 -0
  79. package/src/lib/transfer/product-images.js +143 -0
  80. package/src/lib/transfer/product-images.js.map +1 -0
  81. package/src/lib/transfer/product-sources.d.ts +92 -0
  82. package/src/lib/transfer/product-sources.js +519 -0
  83. package/src/lib/transfer/product-sources.js.map +1 -0
  84. package/src/lib/transfer/product-transfer.d.ts +26 -1
  85. package/src/lib/transfer/product-transfer.js +283 -11
  86. package/src/lib/transfer/product-transfer.js.map +1 -1
  87. package/src/lib/transfer/products.server.d.ts +29 -3
  88. package/src/lib/transfer/products.server.js +289 -13
  89. package/src/lib/transfer/products.server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/products.server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferPicklistList,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { PRODUCT_LIST_QUERY } from '../constants/product-list-query'\nimport {\n commerceSlug,\n liftLegacyProduct,\n productCollectionIds,\n productSearchFields,\n productStockFields,\n variantMatrixProblem,\n type HostProduct,\n type SmartCollectionRules,\n} from '../model/commerce'\nimport {\n PRODUCT_CATEGORY_PICKLIST,\n PRODUCT_FIELD,\n PRODUCT_FIXED_PICKLISTS,\n PRODUCT_LEVEL_FIELDS,\n PRODUCT_VARIANT_ORDER,\n applyProductRow,\n createProductDocument,\n planProductTransfer,\n productExportRowCount,\n productExportRows,\n productPlanHandles,\n productRecord,\n productRowChanges,\n productVariantKey,\n type ProductPlannedRow,\n} from './product-transfer'\nimport {\n NOTHING,\n ROW_BUDGET_MS,\n eachSourceDoc,\n firestoreOf,\n hostRefOf,\n readSourcePage,\n readerSeesHost,\n revertEntries,\n withoutUndefined,\n type CommerceListSource,\n type Firestore,\n} from './server-common'\n\n/*\n * PRODUCTS: THE SERVER HALF (AGL-3531). The pure half — the fields, the\n * Shopify layout, the plan that folds rows into products — is\n * `product-transfer.ts`; this is where it meets the store.\n *\n * Writes keep the product write path's rules: a create is counted against\n * the plan's product allowance in the same transaction that creates it (the\n * `api/hosts/resources` rule, AGL-2231), is born live (`deletedAt: null`)\n * with its creator and stamps, and every write carries the search, stock\n * and smart-collection keys every writer derives (AGL-3321) and leaves an\n * entry in the site's activity. A stock count a file changes is logged as a\n * correction, the same log a manual adjustment writes.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\nconst ID_IN_MAX = 30\n\nfunction productsOf(firestore: Firestore, ctx: TransferResourceContext) {\n return hostRefOf(firestore, ctx).collection('products')\n}\n\nfunction productSource(firestore: Firestore, ctx: TransferResourceContext): CommerceListSource {\n return {\n collection: productsOf(firestore, ctx),\n declaration: PRODUCT_LIST_QUERY,\n base: [{ path: 'deletedAt', op: '==', value: null }],\n }\n}\n\nconst isLive = (data: FirebaseFirestore.DocumentData | undefined): boolean =>\n Boolean(data) && (data?.['deletedAt'] === null || data?.['deletedAt'] === undefined)\n\n/** The site's categories, id → name. */\nasync function readCategoryNames(firestore: Firestore, ctx: TransferResourceContext): Promise<Map<string, string>> {\n const snapshot = await hostRefOf(firestore, ctx).collection('productCategories').limit(2000).get()\n return new Map(snapshot.docs.map((doc) => [doc.id, String(doc.get('name') ?? doc.id)]))\n}\n\n/** Names → ids by the site's categories, in any case; a name it lacks is left out. */\nfunction categoryIdsBy(names: ReadonlyMap<string, string>) {\n const byName = new Map([...names].map(([id, name]) => [name.trim().toLowerCase(), id]))\n return (wanted: readonly string[]) => {\n const ids: string[] = []\n for (const name of wanted) {\n const id = byName.get(name.trim().toLowerCase()) ?? (names.has(name) ? name : undefined)\n if (id && !ids.includes(id)) ids.push(id)\n }\n return ids\n }\n}\n\n/** The smart collections a product's write answers (AGL-3321). */\nexport async function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]> {\n const snapshot = await hostRefOf(firestore, ctx)\n .collection('collections')\n .where('kind', '==', 'catalog')\n .where('mode', '==', 'smart')\n .get()\n return snapshot.docs.map((doc) => ({ id: doc.id, rules: doc.get('rules') ?? [], matchAll: doc.get('matchAll') }))\n}\n\n/** The keys every product write derives, from the product as it will stand. */\nexport function derivedKeys(product: HostProduct, smart: readonly SmartCollectionRules[]): Record<string, unknown> {\n return {\n ...productSearchFields(product),\n ...productStockFields(product),\n collectionIds: productCollectionIds(product, smart),\n priceUsd: product.variants[0]?.priceUsd ?? 0,\n imageUrl: product.mediaUrls?.[0] ?? null,\n }\n}\n\n/** The document fields a product write may set, the product resource's allow-list. */\nconst PRODUCT_DOC_KEYS = [\n 'name',\n 'description',\n 'type',\n 'status',\n 'tags',\n 'categoryIds',\n 'mediaUrls',\n 'options',\n 'variants',\n 'seo',\n 'taxExempt',\n 'oversellPolicy',\n 'lowStockThreshold',\n 'posQuickKey',\n 'checkIn',\n 'modifierGroups',\n] as const\n\n/** The record keys an undo entry keeps: the product's writable fields and its variants. */\nfunction undoKeys(record: Readonly<Record<string, unknown>>, only?: readonly string[]): Record<string, unknown> {\n const keys =\n only ??\n [\n ...PRODUCT_LEVEL_FIELDS.filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...((record[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map(productVariantKey),\n ]\n return Object.fromEntries(keys.map((key) => [key, record[key] ?? null]))\n}\n\n/*------------------------------------------\n * Export\n *-----------------------------------------*/\n\n/** The rows of one page of products. A product is as many rows as it has variants (or images). */\nexport async function readProductsPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n const pageSize = Math.max(1, Math.min(200, options?.pageSize ?? 200))\n const page = await readSourcePage(firestore, productSource(firestore, ctx), cursor, options, pageSize)\n const names = fieldIds.includes(PRODUCT_FIELD.categories) ? await readCategoryNames(firestore, ctx) : new Map()\n const rows = page.docs\n .filter((doc) => isLive(doc.data()))\n .flatMap((doc) => productExportRows(doc.id, liftLegacyProduct(doc.data() as ProductDoc), fieldIds, names))\n return { rows, next: page.next }\n}\n\n/** How many rows the export writes: every live product's variant (or image) rows. */\nexport async function countProductRows(\n ctx: TransferResourceContext,\n options: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<number> {\n if (!readerSeesHost(ctx, options)) return 0\n let rows = 0\n await eachSourceDoc(firestore, productSource(firestore, ctx), options, (doc) => {\n const data = doc.data() as ProductDoc | undefined\n if (isLive(data)) rows += productExportRowCount(liftLegacyProduct(data as ProductDoc))\n })\n return rows\n}\n\n/*------------------------------------------\n * Matching\n *-----------------------------------------*/\n\n/** The values a product is found by: its handle, every SKU it carries, its id. */\nfunction matchValues(id: string, data: ProductDoc): Record<string, unknown> {\n const product = liftLegacyProduct(data)\n return {\n [PRODUCT_FIELD.handle]: product.slug,\n [PRODUCT_FIELD.sku]: product.variants.map((variant) => variant.sku).filter(Boolean),\n id,\n }\n}\n\n/** The live products holding each requested handle, SKU or id, and each one's record. */\nexport async function lookupProducts(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n firestore: Firestore = firestoreOf(),\n): Promise<TransferLookupResult> {\n const products = productsOf(firestore, ctx)\n const found = new Map<string, ProductDoc>()\n const keys: MatchKeySpec[] = []\n for (const request of requests) {\n keys.push({ fieldId: request.fieldId, normalizer: request.normalizer })\n for (let at = 0; at < request.values.length; at += ID_IN_MAX) {\n const slice = request.values.slice(at, at + ID_IN_MAX)\n if (request.fieldId === 'id') {\n const snapshots = await firestore.getAll(...slice.map((id) => products.doc(id)))\n for (const doc of snapshots) if (doc.exists && isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n continue\n }\n const query =\n request.fieldId === PRODUCT_FIELD.handle\n ? products.where('slug', 'in', slice)\n : request.fieldId === PRODUCT_FIELD.sku\n ? products.where('skus', 'array-contains-any', slice)\n : null\n if (!query) continue\n for (const doc of (await query.get()).docs) if (isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n }\n }\n const names = found.size ? await readCategoryNames(firestore, ctx) : new Map<string, string>()\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n for (const [id, data] of found) records.set(id, productRecord(liftLegacyProduct(data), names))\n const lookup = buildMatchLookup(\n [...found].map(([id, data]) => ({ id, values: matchValues(id, data) })),\n keys,\n )\n return { lookup, records }\n}\n\n/*------------------------------------------\n * Lists\n *-----------------------------------------*/\n\n/** The fixed lists, and the site's categories as a list a file may add to. */\nexport async function productPicklists(\n ctx: TransferResourceContext,\n picklistIds: readonly string[],\n firestore: Firestore = firestoreOf(),\n): Promise<Record<string, TransferPicklistList>> {\n const out: Record<string, TransferPicklistList> = {}\n for (const picklistId of picklistIds) {\n const fixed = PRODUCT_FIXED_PICKLISTS[picklistId]\n if (fixed) {\n out[picklistId] = {\n spec: fixed,\n set: {\n values: fixed.standardValues.map((value) => ({ id: value.id, label: value.label, active: true })),\n defaultValueId: fixed.defaultValueId ?? null,\n },\n }\n } else if (picklistId === PRODUCT_CATEGORY_PICKLIST) {\n const names = await readCategoryNames(firestore, ctx)\n out[picklistId] = {\n spec: { restricted: false, standardValues: [] },\n set: {\n values: [...names].map(([id, label]) => ({ id, label, active: true })),\n defaultValueId: null,\n },\n }\n }\n }\n return out\n}\n\n/**\n * The categories the person chose to add, created before the first product\n * names them — each under the id the wizard minted, so a retry finds it.\n */\nexport async function addProductCategories(\n ctx: TransferResourceContext,\n picklistId: string,\n values: readonly PicklistValue[],\n firestore: Firestore = firestoreOf(),\n): Promise<void> {\n if (picklistId !== PRODUCT_CATEGORY_PICKLIST) return\n const categories = hostRefOf(firestore, ctx).collection('productCategories')\n const names = await readCategoryNames(firestore, ctx)\n const held = new Set([...names.values()].map((name) => name.trim().toLowerCase()))\n for (const value of values) {\n const name = value.label.trim()\n if (!name || held.has(name.toLowerCase())) continue\n held.add(name.toLowerCase())\n await categories.doc(value.id).set({ name, slug: commerceSlug(name) || value.id, parentId: null }, { merge: true })\n }\n}\n\n/*------------------------------------------\n * Plan\n *-----------------------------------------*/\n\nconst newId = () => Aglyn.createResourceUid()\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\n/**\n * The dry run: the slugs a new product would collide with (a deleted\n * product's included, which still holds its address) and the plan's room\n * for new products, then the fold of `planProductTransfer`.\n */\nexport async function planProducts(\n ctx: TransferResourceContext,\n input: BuildTransferPlanInput,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferPlan> {\n const products = productsOf(firestore, ctx)\n const taken = new Set<string>()\n const candidates = productPlanHandles(input.rows).flatMap((base) => [base, ...[2, 3, 4, 5].map((n) => `${base}-${n}`)])\n for (let at = 0; at < candidates.length; at += ID_IN_MAX) {\n const slice = candidates.slice(at, at + ID_IN_MAX)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n const owner = await getOrgForHost(ctx.hostId as string)\n const org = owner?.org ?? null\n const used = await countLiveDocuments(products)\n const maxCreates = Aglyn.checkEntitlement(org as never, 'commerce')\n ? Aglyn.checkQuota(org as never, 'productsPerHost', used).remaining\n : 0\n return planProductTransfer(input, {\n newProductId: newId,\n newVariantId,\n slugTaken: (slug) => taken.has(slug),\n maxCreates,\n })\n}\n\n/*------------------------------------------\n * Apply\n *-----------------------------------------*/\n\n/** A refusal the apply records for one row, rather than failing the chunk. */\nclass RowRefusal extends Error {\n constructor(\n readonly reason: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/** Writes one chunk of planned product rows through the product write path. */\nexport async function applyProducts(\n ctx: TransferResourceContext,\n chunk: TransferChunk<ProductPlannedRow>,\n writer: TransferApplyWriter,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferApplyResult> {\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const products = productsOf(firestore, ctx)\n const hostId = ctx.hostId as string\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const owner = await getOrgForHost(hostId)\n const org = owner?.org ?? null\n const actor = { uid: ctx.actorUid ?? 'import', email: null }\n const logged = new Set<string>()\n const adjustments: Array<{ productId: string; variantId: string; delta: number }> = []\n\n const done = async (result: TransferRowResult, entry?: TransferUndoEntry) => {\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n }\n\n for (const row of chunk.rows) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n const plan = row.commerce\n if (!plan) {\n await done({ row: row.index, outcome: 'failed', message: 'The dry run carried nothing to write for this row.' })\n continue\n }\n const ref = products.doc(plan.productId)\n try {\n if (plan.role === 'create') {\n const product = createProductDocument(plan.create as NonNullable<typeof plan.create>, categoryIdsOf)\n const now = Date.now()\n const doc = withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: ctx.actorUid,\n })\n const created = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(ref)\n // A retry after the write landed and before its row was recorded.\n if (existing.exists) return false\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) {\n throw new RowRefusal('planLimit', `Your plan includes ${quota.limit} products — upgrade in Billing for more.`)\n }\n tx.create(ref, doc)\n return true\n })\n if (created && !logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: plan.productId, name: product.name })\n }\n await done(\n { row: row.index, outcome: 'created', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'created',\n written: undoKeys(productRecord(product, names)),\n },\n )\n continue\n }\n\n if (plan.role === 'part') {\n // Written with its product by the product's first row.\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n await done({\n row: row.index,\n outcome: 'failed',\n reason: 'matchedRecordMissing',\n message: `The product on row ${plan.leader + 1} was not created, so this row's variant was not either.`,\n })\n } else {\n await done({ row: row.index, outcome: 'created', recordId: plan.productId })\n }\n continue\n }\n\n // An existing product: this row's changes, read and written in one transaction.\n const changes = productRowChanges(row)\n const outcome = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || !isLive(data)) {\n throw new RowRefusal('matchedRecordMissing', 'The product was deleted after the dry run.')\n }\n const current = liftLegacyProduct(data as ProductDoc)\n const next = applyProductRow(current, changes, categoryIdsOf)\n const invalid = validateProductForSave(next)\n if (invalid) throw new RowRefusal('refusedValue', invalid)\n // What the product editor's Save asks too, of the options as stored.\n if (next.modifierGroups?.length && PRODUCT_FIELD.modifierGroups in changes.product) {\n const matrix = variantMatrixProblem(next.options)\n if (matrix) throw new RowRefusal('refusedValue', matrix)\n }\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n const was = (current as unknown as Record<string, unknown>)[key]\n if (JSON.stringify(value) === JSON.stringify(was)) continue\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n Object.assign(patch, withoutUndefined(derivedKeys(next, smart)), {\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n tx.update(ref, patch)\n return { current, next }\n })\n const before = productRecord(outcome.current, names)\n const afterRecord = productRecord(outcome.next, names)\n const touched = [\n ...Object.keys(changes.product).filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...(changes.variant ? [productVariantKey(changes.variant.id)] : []),\n ]\n if (changes.variant) {\n const was = outcome.current.variants.find((variant) => variant.id === changes.variant?.id)\n const now = outcome.next.variants.find((variant) => variant.id === changes.variant?.id)\n if (typeof was?.inventory === 'number' && typeof now?.inventory === 'number' && was.inventory !== now.inventory) {\n adjustments.push({ productId: plan.productId, variantId: now.id, delta: now.inventory - was.inventory })\n }\n }\n if (!logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Updated product from an import', {\n type: 'content',\n id: plan.productId,\n name: outcome.next.name,\n })\n }\n await done(\n { row: row.index, outcome: 'updated', recordId: plan.productId },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'updated',\n previous: undoKeys(before, touched),\n written: undoKeys(afterRecord, touched),\n },\n )\n } catch (error) {\n if (!(error instanceof RowRefusal)) throw error\n await done({ row: row.index, outcome: 'failed', reason: error.reason, message: error.message })\n }\n }\n\n // The stock history: what the import moved, as a correction (AGL-281).\n const log = hostRefOf(firestore, ctx).collection('inventoryAdjustments')\n for (const adjustment of adjustments) {\n await log.doc(Aglyn.createResourceUid()).set({ ...adjustment, reason: 'correction', source: 'import', atMs: Date.now() })\n }\n return { results, undo }\n}\n\n/*------------------------------------------\n * Undo\n *-----------------------------------------*/\n\n/** Reverses one chunk: a created product deleted, an updated one's fields and variants put back. */\nexport async function revertProducts(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferRevertResult> {\n const products = productsOf(firestore, ctx)\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n return revertEntries(snapshot, decisions, {\n async current(entry) {\n const doc = await products.doc(entry.recordId).get()\n return doc.exists && isLive(doc.data()) ? productRecord(liftLegacyProduct(doc.data() as ProductDoc), names) : null\n },\n async remove(entry) {\n await products.doc(entry.recordId).delete()\n },\n async restore(entry, values) {\n const ref = products.doc(entry.recordId)\n await firestore.runTransaction(async (tx) => {\n const doc = await tx.get(ref)\n if (!doc.exists) return\n let next = liftLegacyProduct(doc.data() as ProductDoc)\n const productValues: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (!key.startsWith('$variant:')) {\n productValues[key] = value\n continue\n }\n const variantId = key.slice('$variant:'.length)\n if (value === null) next = { ...next, variants: next.variants.filter((variant) => variant.id !== variantId) }\n else {\n // A record holds a variant's own check-in only when it has one, so its absence here is a blank to put back.\n const restored = { [PRODUCT_FIELD.variantCheckIn]: null, ...(value as Record<string, unknown>) }\n next = applyProductRow(next, { variant: { id: variantId, isNew: false, values: restored } }, categoryIdsOf)\n }\n }\n next = applyProductRow(next, { product: productValues }, categoryIdsOf)\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n tx.update(ref, {\n ...patch,\n ...withoutUndefined(derivedKeys(next, smart)),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n })\n },\n })\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","buildMatchLookup","firebaseAdmin","getOrgForHost","logHostActivity","PRODUCT_LIST_QUERY","commerceSlug","liftLegacyProduct","productCollectionIds","productSearchFields","productStockFields","variantMatrixProblem","PRODUCT_CATEGORY_PICKLIST","PRODUCT_FIELD","PRODUCT_FIXED_PICKLISTS","PRODUCT_LEVEL_FIELDS","PRODUCT_VARIANT_ORDER","applyProductRow","createProductDocument","planProductTransfer","productExportRowCount","productExportRows","productPlanHandles","productRecord","productRowChanges","productVariantKey","NOTHING","ROW_BUDGET_MS","eachSourceDoc","firestoreOf","hostRefOf","readSourcePage","readerSeesHost","revertEntries","withoutUndefined","ID_IN_MAX","productsOf","firestore","ctx","collection","productSource","declaration","base","path","op","value","isLive","data","Boolean","undefined","readCategoryNames","snapshot","limit","get","Map","docs","map","doc","id","String","categoryIdsBy","names","byName","name","trim","toLowerCase","wanted","ids","has","includes","push","readSmartCollections","where","rules","matchAll","derivedKeys","product","smart","collectionIds","priceUsd","variants","imageUrl","mediaUrls","PRODUCT_DOC_KEYS","undoKeys","record","only","keys","filter","fieldId","published","Object","fromEntries","key","readProductsPage","cursor","fieldIds","options","pageSize","Math","max","min","page","categories","rows","flatMap","next","countProductRows","matchValues","handle","slug","sku","variant","lookupProducts","requests","products","found","request","normalizer","at","values","length","slice","snapshots","getAll","exists","set","query","size","records","lookup","productPicklists","picklistIds","out","picklistId","fixed","spec","standardValues","label","active","defaultValueId","restricted","addProductCategories","held","Set","add","parentId","merge","newId","createResourceUid","newVariantId","planProducts","input","taken","candidates","n","owner","hostId","org","used","maxCreates","checkEntitlement","checkQuota","remaining","newProductId","slugTaken","RowRefusal","Error","reason","message","applyProducts","chunk","writer","results","undo","Timestamp","FieldValue","categoryIdsOf","actor","uid","actorUid","email","logged","adjustments","done","result","entry","markApplied","row","earlier","alreadyApplied","index","timeLeftMs","plan","commerce","outcome","ref","productId","role","create","now","Date","createdAtMs","updatedAtMs","deletedAt","createdAt","updatedAt","createdBy","created","runTransaction","tx","existing","aggregate","quota","Number","allowed","type","recordId","action","written","leader","changes","current","invalid","modifierGroups","matrix","patch","was","JSON","stringify","delete","assign","update","before","afterRecord","touched","find","inventory","variantId","delta","previous","error","log","adjustment","source","atMs","revertProducts","decisions","remove","restore","productValues","entries","startsWith","restored","variantCheckIn","isNew"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,gBAAgB,QASX,6BAA4B;AAanC,SAASC,aAAa,EAAEC,aAAa,EAAEC,eAAe,QAAQ,2BAA0B;AACxF,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SACEC,YAAY,EACZC,iBAAiB,EACjBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,EAClBC,oBAAoB,QAGf,uBAAmB;AAC1B,SACEC,yBAAyB,EACzBC,aAAa,EACbC,uBAAuB,EACvBC,oBAAoB,EACpBC,qBAAqB,EACrBC,eAAe,EACfC,qBAAqB,EACrBC,mBAAmB,EACnBC,qBAAqB,EACrBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,wBAAoB;AAC3B,SACEC,OAAO,EACPC,aAAa,EACbC,aAAa,EACbC,WA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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 { validateProductForSave } from '../model/product-card-rules'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistValue } from '@aglyn/aglyn/app-utils/picklists'\nimport type {\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferPicklistList,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, logHostActivity } from '@aglyn/tenant-data-admin'\nimport { pluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { parseMediaRef } from '@aglyn/aglyn/app-utils/media-ref'\nimport { PRODUCT_LIST_QUERY } from '../constants/product-list-query'\nimport {\n commerceSlug,\n liftLegacyProduct,\n productCollectionIds,\n productSearchFields,\n productStockFields,\n variantMatrixProblem,\n type HostProduct,\n type SmartCollectionRules,\n} from '../model/commerce'\nimport {\n PRODUCT_CATEGORY_PICKLIST,\n PRODUCT_FIELD,\n PRODUCT_FIXED_PICKLISTS,\n PRODUCT_LEVEL_FIELDS,\n PRODUCT_VARIANT_ORDER,\n applyProductRow,\n createProductDocument,\n planProductTransfer,\n productExportRowCount,\n productExportRows,\n productPlanHandles,\n productRecord,\n productRowChanges,\n productVariantKey,\n type ProductPlannedRow,\n type ProductRowPlan,\n} from './product-transfer'\nimport { PRODUCT_IMPORT_FOLDER_NAME, PRODUCT_IMPORT_IMAGE_SLOT_MS, productImageCell } from './product-images'\nimport {\n productImageCopier,\n productImageKey,\n type CopiedProductImage,\n type ProductImageCopier,\n type ProductImageCopierDeps,\n} from './product-image-copy.server'\nimport { productFileSource } from './product-sources'\nimport {\n NOTHING,\n ROW_BUDGET_MS,\n eachSourceDoc,\n firestoreOf,\n hostRefOf,\n readSourcePage,\n readerSeesHost,\n revertEntries,\n withoutUndefined,\n type CommerceListSource,\n type Firestore,\n} from './server-common'\n\n/*\n * PRODUCTS: THE SERVER HALF (AGL-3531). The pure half — the fields, the\n * Shopify layout, the plan that folds rows into products — is\n * `product-transfer.ts`; this is where it meets the store.\n *\n * Writes keep the product write path's rules: a create is counted against\n * the plan's product allowance in the same transaction that creates it (the\n * `api/hosts/resources` rule, AGL-2231), is born live (`deletedAt: null`)\n * with its creator and stamps, and every write carries the search, stock\n * and smart-collection keys every writer derives (AGL-3321) and leaves an\n * entry in the site's activity. A stock count a file changes is logged as a\n * correction, the same log a manual adjustment writes.\n */\n\ntype ProductDoc = Partial<HostProduct> & Record<string, unknown>\n\nconst ID_IN_MAX = 30\n\nfunction productsOf(firestore: Firestore, ctx: TransferResourceContext) {\n return hostRefOf(firestore, ctx).collection('products')\n}\n\nfunction productSource(firestore: Firestore, ctx: TransferResourceContext): CommerceListSource {\n return {\n collection: productsOf(firestore, ctx),\n declaration: PRODUCT_LIST_QUERY,\n base: [{ path: 'deletedAt', op: '==', value: null }],\n }\n}\n\nconst isLive = (data: FirebaseFirestore.DocumentData | undefined): boolean =>\n Boolean(data) && (data?.['deletedAt'] === null || data?.['deletedAt'] === undefined)\n\n/** The site's categories, id → name. */\nasync function readCategoryNames(firestore: Firestore, ctx: TransferResourceContext): Promise<Map<string, string>> {\n const snapshot = await hostRefOf(firestore, ctx).collection('productCategories').limit(2000).get()\n return new Map(snapshot.docs.map((doc) => [doc.id, String(doc.get('name') ?? doc.id)]))\n}\n\n/** Names → ids by the site's categories, in any case; a name it lacks is left out. */\nfunction categoryIdsBy(names: ReadonlyMap<string, string>) {\n const byName = new Map([...names].map(([id, name]) => [name.trim().toLowerCase(), id]))\n return (wanted: readonly string[]) => {\n const ids: string[] = []\n for (const name of wanted) {\n const id = byName.get(name.trim().toLowerCase()) ?? (names.has(name) ? name : undefined)\n if (id && !ids.includes(id)) ids.push(id)\n }\n return ids\n }\n}\n\n/** The smart collections a product's write answers (AGL-3321). */\nexport async function readSmartCollections(firestore: Firestore, ctx: TransferResourceContext): Promise<SmartCollectionRules[]> {\n const snapshot = await hostRefOf(firestore, ctx)\n .collection('collections')\n .where('kind', '==', 'catalog')\n .where('mode', '==', 'smart')\n .get()\n return snapshot.docs.map((doc) => ({ id: doc.id, rules: doc.get('rules') ?? [], matchAll: doc.get('matchAll') }))\n}\n\n/** The keys every product write derives, from the product as it will stand. */\nexport function derivedKeys(product: HostProduct, smart: readonly SmartCollectionRules[]): Record<string, unknown> {\n return {\n ...productSearchFields(product),\n ...productStockFields(product),\n collectionIds: productCollectionIds(product, smart),\n priceUsd: product.variants[0]?.priceUsd ?? 0,\n imageUrl: product.mediaUrls?.[0] ?? null,\n }\n}\n\n/** The document fields a product write may set, the product resource's allow-list. */\nconst PRODUCT_DOC_KEYS = [\n 'name',\n 'description',\n 'type',\n 'status',\n 'tags',\n 'categoryIds',\n 'mediaUrls',\n 'options',\n 'variants',\n 'seo',\n 'taxExempt',\n 'oversellPolicy',\n 'lowStockThreshold',\n 'posQuickKey',\n 'checkIn',\n 'modifierGroups',\n] as const\n\n/** The record keys an undo entry keeps: the product's writable fields and its variants. */\nfunction undoKeys(record: Readonly<Record<string, unknown>>, only?: readonly string[]): Record<string, unknown> {\n const keys =\n only ??\n [\n ...PRODUCT_LEVEL_FIELDS.filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...((record[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map(productVariantKey),\n ]\n return Object.fromEntries(keys.map((key) => [key, record[key] ?? null]))\n}\n\n/*------------------------------------------\n * Export\n *-----------------------------------------*/\n\n/** The rows of one page of products. A product is as many rows as it has variants (or images). */\nexport async function readProductsPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n const pageSize = Math.max(1, Math.min(200, options?.pageSize ?? 200))\n const page = await readSourcePage(firestore, productSource(firestore, ctx), cursor, options, pageSize)\n const names = fieldIds.includes(PRODUCT_FIELD.categories) ? await readCategoryNames(firestore, ctx) : new Map()\n const rows = page.docs\n .filter((doc) => isLive(doc.data()))\n .flatMap((doc) => productExportRows(doc.id, liftLegacyProduct(doc.data() as ProductDoc), fieldIds, names))\n return { rows, next: page.next }\n}\n\n/** How many rows the export writes: every live product's variant (or image) rows. */\nexport async function countProductRows(\n ctx: TransferResourceContext,\n options: TransferReadOptions,\n firestore: Firestore = firestoreOf(),\n): Promise<number> {\n if (!readerSeesHost(ctx, options)) return 0\n let rows = 0\n await eachSourceDoc(firestore, productSource(firestore, ctx), options, (doc) => {\n const data = doc.data() as ProductDoc | undefined\n if (isLive(data)) rows += productExportRowCount(liftLegacyProduct(data as ProductDoc))\n })\n return rows\n}\n\n/*------------------------------------------\n * Matching\n *-----------------------------------------*/\n\n/** The values a product is found by: its handle, every SKU it carries, its id. */\nfunction matchValues(id: string, data: ProductDoc): Record<string, unknown> {\n const product = liftLegacyProduct(data)\n return {\n [PRODUCT_FIELD.handle]: product.slug,\n [PRODUCT_FIELD.sku]: product.variants.map((variant) => variant.sku).filter(Boolean),\n id,\n }\n}\n\n/** The live products holding each requested handle, SKU or id, and each one's record. */\nexport async function lookupProducts(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n firestore: Firestore = firestoreOf(),\n): Promise<TransferLookupResult> {\n const products = productsOf(firestore, ctx)\n const found = new Map<string, ProductDoc>()\n const keys: MatchKeySpec[] = []\n for (const request of requests) {\n keys.push({ fieldId: request.fieldId, normalizer: request.normalizer })\n for (let at = 0; at < request.values.length; at += ID_IN_MAX) {\n const slice = request.values.slice(at, at + ID_IN_MAX)\n if (request.fieldId === 'id') {\n const snapshots = await firestore.getAll(...slice.map((id) => products.doc(id)))\n for (const doc of snapshots) if (doc.exists && isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n continue\n }\n const query =\n request.fieldId === PRODUCT_FIELD.handle\n ? products.where('slug', 'in', slice)\n : request.fieldId === PRODUCT_FIELD.sku\n ? products.where('skus', 'array-contains-any', slice)\n : null\n if (!query) continue\n for (const doc of (await query.get()).docs) if (isLive(doc.data())) found.set(doc.id, doc.data() as ProductDoc)\n }\n }\n const names = found.size ? await readCategoryNames(firestore, ctx) : new Map<string, string>()\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n for (const [id, data] of found) records.set(id, productRecord(liftLegacyProduct(data), names))\n const lookup = buildMatchLookup(\n [...found].map(([id, data]) => ({ id, values: matchValues(id, data) })),\n keys,\n )\n return { lookup, records }\n}\n\n/*------------------------------------------\n * Lists\n *-----------------------------------------*/\n\n/** The fixed lists, and the site's categories as a list a file may add to. */\nexport async function productPicklists(\n ctx: TransferResourceContext,\n picklistIds: readonly string[],\n firestore: Firestore = firestoreOf(),\n): Promise<Record<string, TransferPicklistList>> {\n const out: Record<string, TransferPicklistList> = {}\n for (const picklistId of picklistIds) {\n const fixed = PRODUCT_FIXED_PICKLISTS[picklistId]\n if (fixed) {\n out[picklistId] = {\n spec: fixed,\n set: {\n values: fixed.standardValues.map((value) => ({ id: value.id, label: value.label, active: true })),\n defaultValueId: fixed.defaultValueId ?? null,\n },\n }\n } else if (picklistId === PRODUCT_CATEGORY_PICKLIST) {\n const names = await readCategoryNames(firestore, ctx)\n out[picklistId] = {\n spec: { restricted: false, standardValues: [] },\n set: {\n values: [...names].map(([id, label]) => ({ id, label, active: true })),\n defaultValueId: null,\n },\n }\n }\n }\n return out\n}\n\n/**\n * The categories the person chose to add, created before the first product\n * names them — each under the id the wizard minted, so a retry finds it.\n */\nexport async function addProductCategories(\n ctx: TransferResourceContext,\n picklistId: string,\n values: readonly PicklistValue[],\n firestore: Firestore = firestoreOf(),\n): Promise<void> {\n if (picklistId !== PRODUCT_CATEGORY_PICKLIST) return\n const categories = hostRefOf(firestore, ctx).collection('productCategories')\n const names = await readCategoryNames(firestore, ctx)\n const held = new Set([...names.values()].map((name) => name.trim().toLowerCase()))\n for (const value of values) {\n const name = value.label.trim()\n if (!name || held.has(name.toLowerCase())) continue\n held.add(name.toLowerCase())\n await categories.doc(value.id).set({ name, slug: commerceSlug(name) || value.id, parentId: null }, { merge: true })\n }\n}\n\n/*------------------------------------------\n * Plan\n *-----------------------------------------*/\n\nconst newId = () => Aglyn.createResourceUid()\nconst newVariantId = () => `v${Aglyn.createResourceUid().slice(0, 10)}`\n\n/**\n * The photos the matched products already show that an earlier import\n * copied (AGL-4245), by the photo's key: each library file a product names\n * is read once (a Firestore read, no file and no network), and one carrying\n * an `importedFrom` key answers for the address that key was made from. So\n * the same file imported again plans its photos as the files they already\n * are. A photo a product does not show, or whose file was deleted since,\n * is copied again.\n */\nasync function copiedPhotosOf(\n firestore: Firestore,\n ctx: TransferResourceContext,\n existing: BuildTransferPlanInput['existing'],\n): Promise<(url: string) => string | null> {\n const hostId = ctx.hostId as string\n const named = new Map<string, string>()\n for (const record of existing.values()) {\n const values: unknown[] = [...((record[PRODUCT_FIELD.image] as unknown[] | undefined) ?? [])]\n for (const variantId of (record[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []) {\n values.push((record[productVariantKey(variantId)] as Record<string, unknown> | undefined)?.[PRODUCT_FIELD.variantImage])\n }\n for (const value of values) {\n const ref = parseMediaRef(value)\n if (ref && ref.scope === hostId && !named.has(ref.mediaId)) named.set(ref.mediaId, String(value))\n }\n }\n const byKey = new Map<string, string>()\n const media = hostRefOf(firestore, ctx).collection('media')\n const ids = [...named.keys()]\n for (let at = 0; at < ids.length; at += ID_IN_MAX) {\n const docs = await firestore.getAll(...ids.slice(at, at + ID_IN_MAX).map((id) => media.doc(id)))\n for (const doc of docs) {\n const key = doc.exists ? doc.get('importedFrom.key') : null\n if (typeof key === 'string' && key && !doc.get('deletedAt')) byKey.set(key, named.get(doc.id) as string)\n }\n }\n return (url) => (byKey.size ? (byKey.get(productImageKey(url)) ?? null) : null)\n}\n\n/**\n * The dry run: the slugs a new product would collide with (a deleted\n * product's included, which still holds its address) and the plan's room\n * for new products, then the fold of `planProductTransfer`.\n */\nexport async function planProducts(\n ctx: TransferResourceContext,\n input: BuildTransferPlanInput,\n firestore: Firestore = firestoreOf(),\n): Promise<TransferPlan> {\n const products = productsOf(firestore, ctx)\n const taken = new Set<string>()\n const candidates = productPlanHandles(input.rows).flatMap((base) => [base, ...[2, 3, 4, 5].map((n) => `${base}-${n}`)])\n for (let at = 0; at < candidates.length; at += ID_IN_MAX) {\n const slice = candidates.slice(at, at + ID_IN_MAX)\n for (const doc of (await products.where('slug', 'in', slice).get()).docs) taken.add(String(doc.get('slug')))\n }\n const owner = await getOrgForHost(ctx.hostId as string)\n const org = owner?.org ?? null\n const used = await countLiveDocuments(products)\n const maxCreates = Aglyn.checkEntitlement(org as never, 'commerce')\n ? Aglyn.checkQuota(org as never, 'productsPerHost', used).remaining\n : 0\n return planProductTransfer(input, {\n newProductId: newId,\n newVariantId,\n slugTaken: (slug) => taken.has(slug),\n maxCreates,\n // A Wix or Squarespace file, by its headers (AGL-4245).\n source: productFileSource(ctx.headers, input.rows),\n copiedPhoto: await copiedPhotosOf(firestore, ctx, input.existing),\n })\n}\n\n/*------------------------------------------\n * Apply\n *-----------------------------------------*/\n\n/** A refusal the apply records for one row, rather than failing the chunk. */\nclass RowRefusal extends Error {\n constructor(\n readonly reason: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/*------------------------------------------\n * Photos (AGL-4245)\n *-----------------------------------------*/\n\n/** The photo addresses a planned row copies: a new product's, or the photos a row changes. */\nexport function rowPhotoUrls(row: ProductPlannedRow): string[] {\n const plan = row.commerce\n const values: unknown[] = []\n if (plan?.role === 'create' && plan.create) {\n values.push(...((plan.create.values[PRODUCT_FIELD.image] as unknown[] | undefined) ?? []))\n for (const variant of plan.create.variants) values.push(variant.values[PRODUCT_FIELD.variantImage])\n } else if (plan?.role === 'update') {\n for (const change of row.diff) {\n if (change.fieldId === PRODUCT_FIELD.image && Array.isArray(change.after)) values.push(...change.after)\n if (change.fieldId === PRODUCT_FIELD.variantImage) values.push(change.after)\n }\n }\n const urls: string[] = []\n for (const value of values) {\n const cell = productImageCell(value)\n if (cell?.kind === 'copy' && !urls.includes(cell.url)) urls.push(cell.url)\n }\n return urls\n}\n\n/**\n * A library file a row's write named for a copied photo, kept with its undo\n * entry. Undo asks the library to remove each, and the library removes only\n * the ones this job stored and nothing still uses.\n */\nexport interface ImportedProductMedia {\n mediaId: string\n src: string\n key: string\n /** The photo's address in the file. */\n url: string\n}\n\ninterface SettledPhotos {\n row: ProductPlannedRow\n failed: Array<{ url: string; reason: string }>\n created: ImportedProductMedia[]\n}\n\n/**\n * The row with each address it names swapped for the library file it was\n * copied to: a photo that was not copied is left out (a product whose every\n * new photo failed keeps the ones it has), and why is kept for its result.\n * Every library file it names is listed for its undo.\n */\nfunction settlePhotos(row: ProductPlannedRow, copier: ProductImageCopier): SettledPhotos {\n const failed: SettledPhotos['failed'] = []\n const created: ImportedProductMedia[] = []\n const swap = (value: unknown): string | null => {\n const cell = productImageCell(value)\n if (!cell) return null\n if (cell.kind === 'stored') return cell.value\n if (cell.kind === 'skip') return null\n const answer = copier.result(cell.url) as (CopiedProductImage & { src?: string; mediaId?: string; created?: boolean; key?: string; reason?: string }) | undefined\n if (!answer?.ok) {\n if (!failed.some((entry) => entry.url === cell.url)) failed.push({ url: cell.url, reason: answer?.reason ?? 'it could not be copied' })\n return null\n }\n if (!created.some((entry) => entry.mediaId === answer.mediaId)) {\n created.push({ mediaId: answer.mediaId as string, src: answer.src as string, key: answer.key as string, url: cell.url })\n }\n return answer.src as string\n }\n const swapList = (value: unknown): string[] => {\n const out: string[] = []\n for (const entry of Array.isArray(value) ? value : []) {\n const next = swap(entry)\n if (next && !out.includes(next)) out.push(next)\n }\n return out\n }\n const plan = row.commerce as ProductRowPlan\n if (plan.role === 'create' && plan.create) {\n const values = { ...plan.create.values }\n if (PRODUCT_FIELD.image in values) {\n const list = swapList(values[PRODUCT_FIELD.image])\n if (list.length) values[PRODUCT_FIELD.image] = list\n else delete values[PRODUCT_FIELD.image]\n }\n const variants = plan.create.variants.map((variant) => {\n if (!(PRODUCT_FIELD.variantImage in variant.values)) return variant\n const next = { ...variant.values }\n const image = swap(next[PRODUCT_FIELD.variantImage])\n if (image) next[PRODUCT_FIELD.variantImage] = image\n else delete next[PRODUCT_FIELD.variantImage]\n return { ...variant, values: next }\n })\n return { row: { ...row, commerce: { ...plan, create: { ...plan.create, values, variants } } }, failed, created }\n }\n if (plan.role !== 'update') return { row, failed, created }\n const diff = row.diff.flatMap((change) => {\n if (change.fieldId === PRODUCT_FIELD.image && Array.isArray(change.after)) {\n const list = swapList(change.after)\n return list.length ? [{ ...change, after: list }] : []\n }\n if (change.fieldId === PRODUCT_FIELD.variantImage && !isBlankCell(change.after)) {\n const image = swap(change.after)\n return image ? [{ ...change, after: image }] : []\n }\n return [change]\n })\n return { row: { ...row, diff }, failed, created }\n}\n\nconst isBlankCell = (value: unknown) => value === null || value === undefined || String(value).trim() === ''\n\n/** A row's result sentence for the photos that were not copied, naming the product. */\nexport function photoFailureMessage(name: string, failed: SettledPhotos['failed']): string | undefined {\n if (!failed.length) return undefined\n const count = failed.length\n const listed = failed\n .slice(0, 3)\n .map((entry) => `${entry.url} (${entry.reason})`)\n .join('; ')\n const more = count > 3 ? `; and ${count - 3} more` : ''\n return (\n `${count} photo${count === 1 ? '' : 's'} of \"${name || 'this product'}\" could not be copied: ${listed}${more}. ` +\n `The product was saved without ${count === 1 ? 'it' : 'them'}; add ${count === 1 ? 'it' : 'them'} on the product.`\n )\n}\n\n/** The library files an undo entry's write stored. */\nfunction importedMediaOf(entry: TransferUndoEntry): ImportedProductMedia[] {\n const list = (entry.extras?.['importedMedia'] as unknown[] | undefined) ?? []\n return list.filter(\n (item): item is ImportedProductMedia =>\n Boolean(item) && typeof (item as ImportedProductMedia).mediaId === 'string' && typeof (item as ImportedProductMedia).key === 'string',\n )\n}\n\n/** Writes one chunk of planned product rows through the product write path. */\nexport async function applyProducts(\n ctx: TransferResourceContext,\n chunk: TransferChunk<ProductPlannedRow>,\n writer: TransferApplyWriter,\n firestore: Firestore = firestoreOf(),\n images: ProductImageCopierDeps = { ingest: pluginMediaIngest() },\n): Promise<TransferApplyResult> {\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const products = productsOf(firestore, ctx)\n const hostId = ctx.hostId as string\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const owner = await getOrgForHost(hostId)\n const org = owner?.org ?? null\n const actor = { uid: ctx.actorUid ?? 'import', email: null }\n const logged = new Set<string>()\n const adjustments: Array<{ productId: string; variantId: string; delta: number }> = []\n // The chunk's photos (AGL-4245): copied before the row that names them is written.\n const copier = productImageCopier({ hostId, uid: ctx.actorUid, ...(ctx.jobId ? { jobId: ctx.jobId } : {}) }, images)\n\n const done = async (result: TransferRowResult, entry?: TransferUndoEntry) => {\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n }\n\n for (const row of chunk.rows) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n if (!row.commerce) {\n await done({ row: row.index, outcome: 'failed', message: 'The dry run carried nothing to write for this row.' })\n continue\n }\n // A row's photos are copied first, never starting one that could not\n // finish in this pass; a row whose photos run out of time is written on\n // the next pass, which finds every photo this one stored.\n const photoUrls = rowPhotoUrls(row)\n if (copier.pending(photoUrls).length) {\n if (writer.timeLeftMs() < ROW_BUDGET_MS + PRODUCT_IMPORT_IMAGE_SLOT_MS) break\n const finished = await copier.copy(photoUrls, Date.now() + writer.timeLeftMs() - ROW_BUDGET_MS)\n if (!finished) break\n }\n const settled = photoUrls.length ? settlePhotos(row, copier) : { row, failed: [], created: [] }\n const plan = settled.row.commerce as ProductRowPlan\n const extras = settled.created.length ? { extras: { importedMedia: settled.created } } : {}\n const ref = products.doc(plan.productId)\n try {\n if (plan.role === 'create') {\n const product = createProductDocument(plan.create as NonNullable<typeof plan.create>, categoryIdsOf)\n const now = Date.now()\n const doc = withoutUndefined({\n ...product,\n ...derivedKeys(product, smart),\n createdAtMs: now,\n updatedAtMs: now,\n deletedAt: null,\n createdAt: Timestamp.now(),\n updatedAt: Timestamp.now(),\n createdBy: ctx.actorUid,\n })\n const created = await firestore.runTransaction(async (tx) => {\n const existing = await tx.get(ref)\n // A retry after the write landed and before its row was recorded.\n if (existing.exists) return false\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const quota = Aglyn.checkQuota(org as never, 'productsPerHost', Number(used) || 0)\n if (!quota.allowed) {\n throw new RowRefusal('planLimit', `Your plan includes ${quota.limit} products — upgrade in Billing for more.`)\n }\n tx.create(ref, doc)\n return true\n })\n if (created && !logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Imported product', { type: 'content', id: plan.productId, name: product.name })\n }\n const message = photoFailureMessage(product.name, settled.failed)\n await done(\n { row: row.index, outcome: 'created', recordId: plan.productId, ...(message ? { message } : {}) },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'created',\n written: undoKeys(productRecord(product, names)),\n ...extras,\n },\n )\n continue\n }\n\n if (plan.role === 'part') {\n // Written with its product by the product's first row.\n const snapshot = await ref.get()\n if (!snapshot.exists) {\n await done({\n row: row.index,\n outcome: 'failed',\n reason: 'matchedRecordMissing',\n message: `The product on row ${plan.leader + 1} was not created, so this row's variant was not either.`,\n })\n } else {\n await done({ row: row.index, outcome: 'created', recordId: plan.productId })\n }\n continue\n }\n\n // An existing product: this row's changes, read and written in one transaction.\n const changes = productRowChanges(settled.row)\n const outcome = await firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n const data = snapshot.data() as ProductDoc | undefined\n if (!snapshot.exists || !isLive(data)) {\n throw new RowRefusal('matchedRecordMissing', 'The product was deleted after the dry run.')\n }\n const current = liftLegacyProduct(data as ProductDoc)\n const next = applyProductRow(current, changes, categoryIdsOf)\n const invalid = validateProductForSave(next)\n if (invalid) throw new RowRefusal('refusedValue', invalid)\n // What the product editor's Save asks too, of the options as stored.\n if (next.modifierGroups?.length && PRODUCT_FIELD.modifierGroups in changes.product) {\n const matrix = variantMatrixProblem(next.options)\n if (matrix) throw new RowRefusal('refusedValue', matrix)\n }\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n const was = (current as unknown as Record<string, unknown>)[key]\n if (JSON.stringify(value) === JSON.stringify(was)) continue\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n Object.assign(patch, withoutUndefined(derivedKeys(next, smart)), {\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n tx.update(ref, patch)\n return { current, next }\n })\n const before = productRecord(outcome.current, names)\n const afterRecord = productRecord(outcome.next, names)\n const touched = [\n ...Object.keys(changes.product).filter((fieldId) => fieldId !== PRODUCT_FIELD.published),\n ...(changes.variant ? [productVariantKey(changes.variant.id)] : []),\n ]\n if (changes.variant) {\n const was = outcome.current.variants.find((variant) => variant.id === changes.variant?.id)\n const now = outcome.next.variants.find((variant) => variant.id === changes.variant?.id)\n if (typeof was?.inventory === 'number' && typeof now?.inventory === 'number' && was.inventory !== now.inventory) {\n adjustments.push({ productId: plan.productId, variantId: now.id, delta: now.inventory - was.inventory })\n }\n }\n if (!logged.has(plan.productId)) {\n logged.add(plan.productId)\n await logHostActivity(hostId, actor, 'Updated product from an import', {\n type: 'content',\n id: plan.productId,\n name: outcome.next.name,\n })\n }\n const message = photoFailureMessage(outcome.next.name, settled.failed)\n await done(\n { row: row.index, outcome: 'updated', recordId: plan.productId, ...(message ? { message } : {}) },\n {\n row: row.index,\n recordId: plan.productId,\n action: 'updated',\n previous: undoKeys(before, touched),\n written: undoKeys(afterRecord, touched),\n ...extras,\n },\n )\n } catch (error) {\n if (!(error instanceof RowRefusal)) throw error\n await done({ row: row.index, outcome: 'failed', reason: error.reason, message: error.message })\n }\n }\n\n // The stock history: what the import moved, as a correction (AGL-281).\n const log = hostRefOf(firestore, ctx).collection('inventoryAdjustments')\n for (const adjustment of adjustments) {\n await log.doc(Aglyn.createResourceUid()).set({ ...adjustment, reason: 'correction', source: 'import', atMs: Date.now() })\n }\n return { results, undo }\n}\n\n/*------------------------------------------\n * Undo\n *-----------------------------------------*/\n\n/**\n * The library files an undone chunk's writes named (AGL-4245), handed to the\n * library to remove once this chunk's own products are put back: a record\n * kept on undo keeps its files, and the library removes only what this job\n * stored and its usage scan finds nowhere, a page or another product's\n * variant included. A file kept for being in use is a note on the undo,\n * cleared when a later chunk removes it.\n */\nasync function removeImportedProductMedia(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n kept: ReadonlySet<string>,\n ingest: ProductImageCopierDeps['ingest'],\n): Promise<Record<string, string | null>> {\n const notes: Record<string, string | null> = {}\n if (!ingest?.removeImportedPhotos || !ctx.hostId || !ctx.actorUid) return notes\n const media = new Map<string, ImportedProductMedia>()\n for (const entry of snapshot.entries) {\n if (kept.has(entry.recordId)) continue\n for (const item of importedMediaOf(entry)) media.set(item.mediaId, item)\n }\n if (!media.size) return notes\n try {\n const answer = await ingest.removeImportedPhotos({\n hostId: ctx.hostId,\n uid: ctx.actorUid,\n jobId: snapshot.jobId,\n photos: [...media.values()].map((item) => ({ mediaId: item.mediaId, sourceKey: item.key })),\n })\n for (const mediaId of answer.removed) notes[`photo:${mediaId}`] = null\n const where = answer.usedBy.slice(0, 3).join(', ') + (answer.usedBy.length > 3 ? ` and ${answer.usedBy.length - 3} more` : '')\n for (const mediaId of answer.kept) {\n const url = media.get(mediaId)?.url\n notes[`photo:${mediaId}`] =\n `A photo this import copied${url ? ` (${url})` : ''} stays in your media library, in the \"${PRODUCT_IMPORT_FOLDER_NAME}\" folder, because it is still in use${where ? `: ${where}` : ''}.`\n }\n } catch (error) {\n // A file left behind is a file the owner can delete; the undo of the products stands.\n console.warn('[commerce] imported photos could not be removed on undo', { hostId: ctx.hostId, error })\n }\n return notes\n}\n\n/** Reverses one chunk: a created product deleted, an updated one's fields and variants put back, and the photos it stored removed. */\nexport async function revertProducts(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n firestore: Firestore = firestoreOf(),\n images: Pick<ProductImageCopierDeps, 'ingest'> = { ingest: pluginMediaIngest() },\n): Promise<TransferRevertResult> {\n const products = productsOf(firestore, ctx)\n const names = await readCategoryNames(firestore, ctx)\n const categoryIdsOf = categoryIdsBy(names)\n const smart = await readSmartCollections(firestore, ctx)\n const { Timestamp, FieldValue } = firebaseAdmin.firestore\n const reverted = await revertEntries(snapshot, decisions, {\n async current(entry) {\n const doc = await products.doc(entry.recordId).get()\n return doc.exists && isLive(doc.data()) ? productRecord(liftLegacyProduct(doc.data() as ProductDoc), names) : null\n },\n async remove(entry) {\n await products.doc(entry.recordId).delete()\n },\n async restore(entry, values) {\n const ref = products.doc(entry.recordId)\n await firestore.runTransaction(async (tx) => {\n const doc = await tx.get(ref)\n if (!doc.exists) return\n let next = liftLegacyProduct(doc.data() as ProductDoc)\n const productValues: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(values)) {\n if (!key.startsWith('$variant:')) {\n productValues[key] = value\n continue\n }\n const variantId = key.slice('$variant:'.length)\n if (value === null) next = { ...next, variants: next.variants.filter((variant) => variant.id !== variantId) }\n else {\n // A record holds a variant's own check-in only when it has one, so its absence here is a blank to put back.\n const restored = { [PRODUCT_FIELD.variantCheckIn]: null, ...(value as Record<string, unknown>) }\n next = applyProductRow(next, { variant: { id: variantId, isNew: false, values: restored } }, categoryIdsOf)\n }\n }\n next = applyProductRow(next, { product: productValues }, categoryIdsOf)\n const patch: Record<string, unknown> = {}\n for (const key of PRODUCT_DOC_KEYS) {\n const value = (next as unknown as Record<string, unknown>)[key]\n patch[key] = value === undefined ? FieldValue.delete() : withoutUndefined(value)\n }\n tx.update(ref, {\n ...patch,\n ...withoutUndefined(derivedKeys(next, smart)),\n updatedAtMs: Date.now(),\n updatedAt: Timestamp.now(),\n })\n })\n },\n })\n const kept = new Set(reverted.conflicts.map((step) => step.recordId))\n const notes = await removeImportedProductMedia(ctx, snapshot, kept, images.ingest)\n return Object.keys(notes).length ? { ...reverted, notes } : reverted\n}\n"],"names":["validateProductForSave","Aglyn","countLiveDocuments","buildMatchLookup","firebaseAdmin","getOrgForHost","logHostActivity","pluginMediaIngest","parseMediaRef","PRODUCT_LIST_QUERY","commerceSlug","liftLegacyProduct","productCollectionIds","productSearchFields","productStockFields","variantMatrixProblem","PRODUCT_CATEGORY_PICKLIST","PRODUCT_FIELD","PRODUCT_FIXED_PICKLISTS","PRODUCT_LEVEL_FIELDS","PRODUCT_VARIANT_ORDER","applyProductRow","createProductDocument","planProductTransfer","productExportRowCount","productExportRows","productPlanHandles","productRecord","productRowChanges","productVariantKey","PRODUCT_IMPORT_FOLDER_NAME","PRODUCT_IMPORT_IMAGE_SLOT_MS","productImageCell","productImageCopier","productImageKey","productFileSource","NOTHING","ROW_BUDGET_MS","eachSourceDoc","firestoreOf","hostRefOf","readSourcePage","readerSeesHost","revertEntries","withoutUndefined","ID_IN_MAX","productsOf","firestore","ctx","collection","productSource","declaration","base","path","op","value","isLive","data","Boolean","undefined","readCategoryNames","snapshot","limit","get","Map","docs","map","doc","id","String","categoryIdsBy","names","byName","name","trim","toLowerCase","wanted","ids","has","includes","push","readSmartCollections","where","rules","matchAll","derivedKeys","product","smart","collectionIds","priceUsd","variants","imageUrl","mediaUrls","PRODUCT_DOC_KEYS","undoKeys","record","only","keys","filter","fieldId","published","Object","fromEntries","key","readProductsPage","cursor","fieldIds","options","pageSize","Math","max","min","page","categories","rows","flatMap","next","countProductRows","matchValues","handle","slug","sku","variant","lookupProducts","requests","products","found","request","normalizer","at","values","length","slice","snapshots","getAll","exists","set","query","size","records","lookup","productPicklists","picklistIds","out","picklistId","fixed","spec","standardValues","label","active","defaultValueId","restricted","addProductCategories","held","Set","add","parentId","merge","newId","createResourceUid","newVariantId","copiedPhotosOf","existing","hostId","named","image","variantId","variantImage","ref","scope","mediaId","byKey","media","url","planProducts","input","taken","candidates","n","owner","org","used","maxCreates","checkEntitlement","checkQuota","remaining","newProductId","slugTaken","source","headers","copiedPhoto","RowRefusal","Error","reason","message","rowPhotoUrls","row","plan","commerce","role","create","change","diff","Array","isArray","after","urls","cell","kind","settlePhotos","copier","failed","created","swap","answer","result","ok","some","entry","src","swapList","list","isBlankCell","photoFailureMessage","count","listed","join","more","importedMediaOf","extras","item","applyProducts","chunk","writer","images","ingest","results","undo","Timestamp","FieldValue","categoryIdsOf","actor","uid","actorUid","email","logged","adjustments","jobId","done","markApplied","earlier","alreadyApplied","index","timeLeftMs","outcome","photoUrls","pending","finished","copy","Date","now","settled","importedMedia","productId","createdAtMs","updatedAtMs","deletedAt","createdAt","updatedAt","createdBy","runTransaction","tx","aggregate","quota","Number","allowed","type","recordId","action","written","leader","changes","current","invalid","modifierGroups","matrix","patch","was","JSON","stringify","delete","assign","update","before","afterRecord","touched","find","inventory","delta","previous","error","log","adjustment","atMs","removeImportedProductMedia","kept","notes","removeImportedPhotos","entries","photos","sourceKey","removed","usedBy","console","warn","revertProducts","decisions","reverted","remove","restore","productValues","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