@aglyn/plugins-commerce 1.26.5 → 1.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,10 +16,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { checkEntitlement, isHostPluginEnabled } from "@aglyn/aglyn/server";
18
18
  import { ApiErrors, apiJson, listResponse } from "@aglyn/tenant-data-admin";
19
- import { paginate, readJsonBody, requireScope, serialize } from "@aglyn/tenant-data-admin/server/api-v1-kit";
19
+ import { paginate, readJsonBody, requireScope, requireSitePermission } from "@aglyn/tenant-data-admin/server/api-v1-kit";
20
20
  import { BUNDLE_ID } from "../../constants/bundle-common.js";
21
21
  import { recordOrderShipment } from "../fulfill-order.js";
22
22
  import { orderViewFromData } from "./order-view.js";
23
+ import { productView } from "./product-view.js";
23
24
  import { isUnpaidQuote } from "../../model/commerce-quotes.js";
24
25
  /**
25
26
  * A site's orders and products on the customer REST API,
@@ -322,71 +323,57 @@ export async function handleOrders(request, ctx, segments, url) {
322
323
  });
323
324
  }
324
325
  /**
325
- * Price and stock live on VARIANTS, never on the product — a product-level
326
- * `inventory` exists only as a denormalized sum the console rewrites on every
327
- * decrement, and a product-level `priceUsd` is the legacy single-variant
328
- * shape. Publishing either as the product's price would be wrong the moment a
329
- * product has two variants, so the variant array is the contract and the
330
- * product carries only the roll-up, clearly named.
331
- *
332
- * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.
333
- * Collapsing them (the `?? 0` an integrator writes on the first day) turns
334
- * every untracked product into an out-of-stock one, so the distinction is
335
- * carried through verbatim rather than defaulted.
336
- */ function variantView(variant) {
337
- var _variant_id, _variant_sku, _variant_barcode, _variant_options;
338
- const inventory = variant.inventory;
339
- return {
340
- id: (_variant_id = variant.id) != null ? _variant_id : null,
341
- sku: (_variant_sku = variant.sku) != null ? _variant_sku : null,
342
- barcode: (_variant_barcode = variant.barcode) != null ? _variant_barcode : null,
343
- options: (_variant_options = variant.options) != null ? _variant_options : {},
344
- priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,
345
- compareAtPriceUsd: typeof variant.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null,
346
- weightGrams: typeof variant.weightGrams === 'number' ? variant.weightGrams : null,
347
- inventory: typeof inventory === 'number' ? inventory : null,
348
- inventoryTracked: typeof inventory === 'number'
349
- };
350
- }
351
- function productView(doc) {
352
- var _doc_data, _data_name, _data_slug, _data_description, _data_type, _data_status, _data_tags, _data_categoryIds, _data_mediaUrls, _data_options, _serialize;
353
- const data = (_doc_data = doc.data()) != null ? _doc_data : {};
354
- const variants = Array.isArray(data.variants) ? data.variants : [];
355
- const tracked = variants.filter((v)=>typeof v.inventory === 'number');
356
- return {
357
- id: doc.id,
358
- object: 'product',
359
- name: (_data_name = data.name) != null ? _data_name : null,
360
- slug: (_data_slug = data.slug) != null ? _data_slug : null,
361
- description: (_data_description = data.description) != null ? _data_description : null,
362
- type: (_data_type = data.type) != null ? _data_type : null,
363
- status: (_data_status = data.status) != null ? _data_status : null,
364
- tags: (_data_tags = data.tags) != null ? _data_tags : [],
365
- categoryIds: (_data_categoryIds = data.categoryIds) != null ? _data_categoryIds : [],
366
- mediaUrls: (_data_mediaUrls = data.mediaUrls) != null ? _data_mediaUrls : [],
367
- options: (_data_options = data.options) != null ? _data_options : [],
368
- variants: variants.map(variantView),
369
- // The sum across TRACKED variants only, and `null` when none of them is
370
- // tracked — so an untracked catalogue reads as "we don't count this"
371
- // rather than as a store with nothing left to sell.
372
- inventory: tracked.length ? tracked.reduce((sum, v)=>{
373
- var _v_inventory;
374
- return sum + Number((_v_inventory = v.inventory) != null ? _v_inventory : 0);
375
- }, 0) : null,
376
- subscription: (_serialize = serialize(data.subscription)) != null ? _serialize : null,
377
- created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,
378
- updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null
379
- };
326
+ * The product writes' gates (AGL-4235), each load-bearing, in `updateOrder`'s
327
+ * order: `products:write` on the credential, the `commerce` PLAN entitlement,
328
+ * this plugin switched on for this site, and — for an app a person connected
329
+ * — that person's "Edit site content" on the site, the permission the
330
+ * console's product editor and the native apps' save route ask. The router
331
+ * has already applied the site's lock and the person's membership.
332
+ */ function productWriteRefusal(ctx, hostId, hostDoc) {
333
+ const denied = requireScope(ctx, 'products:write');
334
+ if (denied) return denied;
335
+ const unentitled = requireCommerce(ctx);
336
+ if (unentitled) return unentitled;
337
+ if (!isHostPluginEnabled(ctx.org, hostDoc.data(), BUNDLE_ID)) {
338
+ return ApiErrors.notFound({
339
+ message: 'No such site',
340
+ headers: ctx.headers
341
+ });
342
+ }
343
+ return requireSitePermission(ctx, hostDoc, 'site.edit');
380
344
  }
381
345
  export async function handleProducts(request, ctx, segments, url) {
382
- const [, hostId, , productId] = segments;
346
+ const [, hostId, , productId, sub, variantId] = segments;
347
+ if (sub !== undefined && (sub !== 'variants' || !variantId || segments.length > 6)) {
348
+ return ApiErrors.notFound({
349
+ message: 'Unknown endpoint',
350
+ headers: ctx.headers
351
+ });
352
+ }
353
+ const writing = request.method === 'POST' && !productId || (request.method === 'PATCH' || request.method === 'DELETE') && productId && !variantId || request.method === 'PATCH' && variantId;
354
+ // `products:write` is asked BEFORE `products:read`, as the order writes ask
355
+ // theirs (AGL-900): a key that only writes the catalog holds no read scope.
356
+ if (writing) {
357
+ var _ref;
358
+ var _ctx_site;
359
+ const hostDoc = (_ref = (_ctx_site = ctx.site) == null ? void 0 : _ctx_site.snapshot) != null ? _ref : await hostRef(ctx, hostId).get();
360
+ const refused = productWriteRefusal(ctx, hostId, hostDoc);
361
+ if (refused) return refused;
362
+ const writes = await import("./product-writes.js");
363
+ if (variantId) return writes.updateProductVariant(request, ctx, hostId, productId, variantId);
364
+ if (!productId) return writes.createProduct(request, ctx, hostId);
365
+ if (request.method === 'PATCH') return writes.updateProduct(request, ctx, hostId, productId);
366
+ return writes.deleteProductOverApi(ctx, hostId, productId);
367
+ }
383
368
  const denied = requireScope(ctx, 'products:read');
384
369
  if (denied) return denied;
385
370
  const unentitled = requireCommerce(ctx);
386
371
  if (unentitled) return unentitled;
387
- if (request.method !== 'GET') {
372
+ if (request.method !== 'GET' || variantId) {
388
373
  return ApiErrors.methodNotAllowed({
389
- headers: ctx.headers
374
+ headers: _extends({}, ctx.headers, {
375
+ Allow: variantId ? 'PATCH' : productId ? 'GET, PATCH, DELETE' : 'GET, POST'
376
+ })
390
377
  });
391
378
  }
392
379
  const collection = hostRef(ctx, hostId).collection('products');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/orders-and-products.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 { checkEntitlement, isHostPluginEnabled } from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { BUNDLE_ID } from '../../constants/bundle-common'\nimport { type OrderFulfilmentTarget, recordOrderShipment } from '../fulfill-order'\nimport { orderViewFromData } from './order-view'\nimport { isUnpaidQuote } from '../../model/commerce-quotes'\n\n/**\n * A site's orders and products on the customer REST API,\n * `/v1/sites/{siteId}/orders/…` and `/v1/sites/{siteId}/products/…`\n * (AGL-1928, AGL-2461, AGL-3080). Registered from this plugin's console\n * server declarations; the console's `/v1` router owns the pipeline in\n * front — the key, the plan's API access, the request quota, the rate limit —\n * and refuses a site the key's organization does not own before it hands a\n * request here.\n */\n\n/**\n * Commerce resources need the `commerce` entitlement as well as the scope\n * (AGL-1928). `apiAccess` alone is the wrong gate here: it says the org may\n * call the API at all, not that it may still use the store. AGL-1873 closed\n * exactly this class on the write side — two money doors that asked the\n * plugin switch (`org.enabledPlugins`) instead of the plan, so a lapsed org\n * kept selling — and the same reasoning applies to a read. `enabledPlugins`\n * is the customer's own on/off switch and survives a downgrade; the plan does\n * not, and the published rule is that paid features stop at the door when the\n * plan no longer includes them.\n *\n * Answered as `plan_required` rather than `not_found`, deliberately. Hiding a\n * store that plainly exists behind a 404 sends an integrator hunting a wrong\n * site id; the honest answer names the plan.\n */\nfunction requireCommerce(ctx: ApiV1Context): Response | null {\n return checkEntitlement(ctx.org, 'commerce')\n ? null\n : ApiErrors.planRequired({\n message: 'Commerce is not included in this organization’s plan',\n code: 'commerce',\n headers: ctx.headers,\n })\n}\n\nfunction hostRef(ctx: ApiV1Context, hostId: string) {\n return ctx.firestore.collection('hosts').doc(hostId)\n}\n\n/**\n * Orders carry a legacy Commerce Starter shape (AGL-90) alongside the modern\n * one: `amountCents`/`feeCents` at the top level rather than a `totals` map.\n * The console lifts them through `CommerceModel.liftLegacyOrder` and reads\n * `lifted.totals?.totalCents ?? order.amountCents`. The API cannot publish two\n * shapes for one object, so the legacy fields are folded into `totals` here\n * and a client only ever sees the modern one. `channel` defaults to `online`\n * for the same reason the console's list does — an absent channel is a\n * pre-channel order, not an unknown one.\n */\nfunction orderView(doc: FirebaseFirestore.DocumentSnapshot) {\n return orderViewFromData(doc.id, doc.data() ?? {})\n}\n\nexport async function handleOrders(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , orderId] = segments\n // `orders:write` is checked BEFORE `orders:read`, matching `handleSites`\n // and `handleScopedMedia` (AGL-900): a fulfilment key that only records\n // shipments must not be told it lacks a read scope it was never meant to\n // hold.\n if (request.method === 'PATCH' && orderId) {\n const deniedWrite = requireScope(ctx, 'orders:write')\n if (deniedWrite) return deniedWrite\n const unentitledWrite = requireCommerce(ctx)\n if (unentitledWrite) return unentitledWrite\n return updateOrder(request, ctx, hostId, orderId)\n }\n const denied = requireScope(ctx, 'orders:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: orderId ? 'GET, PATCH' : 'GET' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('orders')\n\n if (orderId) {\n const snap = await collection.doc(orderId).get()\n // An unpaid quote is not an order yet (AGL-4093).\n if (!snap.exists || isUnpaidQuote(snap.data())) {\n return ApiErrors.notFound({ message: 'No such order', headers: ctx.headers })\n }\n return apiJson(orderView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const channel = url.searchParams.get('channel')\n // `online` is the DEFAULT, not a stored value on older orders, so filtering\n // for it in Firestore would silently drop every pre-channel order. Those are\n // exactly the oldest orders an accounting backfill is reaching for, so this\n // one value is filtered after the read instead. The page can therefore come\n // back shorter than `limit` while `has_more` is still true — which the\n // published pagination contract already tells clients to expect (check\n // `has_more`, never a page's length).\n if (channel && channel !== 'online') query = query.where('channel', '==', channel)\n const { docs, nextCursor } = await paginate(query, url)\n // Unpaid quotes share the collection and are not orders yet (AGL-4093);\n // left out after the read, like `online` above, so a page can be short.\n const data = docs\n .filter((doc) => !isUnpaidQuote(doc.data()))\n .map(orderView)\n .filter((order) => (channel === 'online' ? order.channel === 'online' : true))\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n/**\n * Statuses this endpoint will move an order TO, and the two it names as\n * refused. Kept as data so the 400 can list them and the docs can be checked\n * against the same source the handler branches on.\n */\nconst ORDER_WRITE_TARGETS: OrderFulfilmentTarget[] = ['fulfilled', 'delivered']\n\n/** The keys a PATCH may carry (AGL-3611 added the last three). */\nconst ORDER_WRITABLE_KEYS = ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify']\n\n/**\n * Transitions that exist in the commerce model and are DELIBERATELY not\n * reachable here — refused by name with a 400 that says why, never silently\n * ignored. `cancelled` releases held stock under its own transaction and\n * `refunded` moves money under another; admitting either here would hand a\n * caller a door around exactly the specifics those two routes exist to\n * enforce, and an API key is the credential least able to answer the\n * questions they ask.\n */\nconst ORDER_WRITE_REFUSED: Record<string, string> = {\n cancelled:\n 'Canceling an order releases held stock, so it is not part of this endpoint. Cancel it in the console.',\n refunded:\n 'Refunding an order moves money, so it is not part of this endpoint. Refund it in the console.',\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/orders/{orderId}` — record a shipment (AGL-2461).\n *\n * ## The write is the console's, shared\n *\n * The transition rule, the transaction that re-asks it under the write, the\n * fulfillment append and the timeline entry are `recordOrderShipment`'s,\n * the one implementation the console's `commerce/fulfill-order` route calls\n * too. A second copy of `ORDER_TRANSITIONS` here would be the bug rather\n * than the fix: two tables drift, and drift here means the API writing an\n * order status the console forbids — `paid → delivered` skipping\n * fulfilment, or a write onto a `refunded` order. That is the class\n * AGL-1818/AGL-1819 exist to close, and it is money-adjacent.\n *\n * ## What THIS function is responsible for: all of the authorization\n *\n * `recordOrderShipment` is pre-authorized by contract — it takes `hostId`\n * on trust — so every gate is here, and all four are load-bearing:\n *\n * 1. `orders:write` on the key (checked by the caller, above).\n * 2. The `commerce` PLAN entitlement (checked by the caller, above) — the\n * plan, never the plugin switch, which is the AGL-1873 distinction.\n * 3. **Org owns the site** — the console's `handleSites` refuses an unowned\n * `hostId` with a 404 before it hands any site resource to its plugin,\n * which is what keeps this from being a cross-tenant write primitive\n * addressable by anyone who can guess a host id. Deliberately NOT\n * re-checked here: a second copy would be a gate no test can redden\n * (removing either one alone leaves the other answering), and an unproven\n * guard on a cross-tenant write is worse than the one guard a test\n * actually holds. `api-v1-order-fulfilment.spec.ts`'s \"CANNOT move\n * another org's order\" case is that test, and it fails when\n * `handleSites`' `orgOwnsHost` is removed.\n * 4. **This plugin is switched on for this site.** The resource is\n * registered for every organization the console serves, so its being here\n * says nothing about one org's configuration; without this an org that\n * switched commerce off for a site would still accept writes into it,\n * which is the per-site enablement rule (AGL-1014) the plugin API\n * dispatcher applies to every other commerce door.\n *\n * ## No `Idempotency-Key`\n *\n * None is needed and none is accepted: the write returns without writing when\n * the order is already in the target status, so a retry lands the same state\n * AND returns the same `200` with the same order body — the contract\n * `updateRecord`, `updateContact` and `updateFormSubmission` are held to.\n */\nasync function updateOrder(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n orderId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((key) => !ORDER_WRITABLE_KEYS.includes(key))\n if (unknown.length > 0) {\n // Named, not dropped — the `updateFormSubmission` / `updateContact` rule.\n // A silently ignored `trackingUrl` here reads as \"we recorded your\n // shipment as you described it\" when half of it went nowhere, and the\n // caller is a warehouse system that will never look again.\n return ApiErrors.badRequest({\n message:\n 'Only `status`, `carrier`, `trackingNumber`, `trackingUrl`, `lineItems` and `notify` can be set on an order',\n code: 'validation_failed',\n fields: Object.fromEntries(\n unknown.map((key) => [key, 'Not writable on an order']),\n ),\n headers: ctx.headers,\n })\n }\n\n const status = String(body.status ?? '')\n const refusal = ORDER_WRITE_REFUSED[status]\n if (refusal) {\n return ApiErrors.badRequest({\n message: refusal,\n code: 'validation_failed',\n fields: { status: refusal },\n headers: ctx.headers,\n })\n }\n if (!(ORDER_WRITE_TARGETS as string[]).includes(status)) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n status: `Must be one of: ${ORDER_WRITE_TARGETS.join(', ')}`,\n },\n headers: ctx.headers,\n })\n }\n // Bounded exactly as the console route bounds them, so one field cannot be\n // used to stuff an order document through a door the console keeps narrow.\n const carrier = String(body.carrier ?? '').slice(0, 40)\n const trackingNumber = String(body.trackingNumber ?? '').slice(0, 60)\n // Partial shipments (AGL-3611): `lineItems: [{ lineItemId, quantity }]`.\n // Absent keeps the old meaning, everything still to ship.\n let lineItems: Array<{ lineItemId: number; quantity: number }> | undefined\n if (body.lineItems !== undefined) {\n if (status !== 'fulfilled' || !Array.isArray(body.lineItems) || body.lineItems.length === 0) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n lineItems:\n status !== 'fulfilled'\n ? 'Only a `fulfilled` update names line items'\n : 'Must be a non-empty array of { lineItemId, quantity }',\n },\n headers: ctx.headers,\n })\n }\n lineItems = (body.lineItems as unknown[]).slice(0, 500).map((entry) => ({\n lineItemId: Number((entry as Record<string, unknown>)?.lineItemId),\n quantity: Number((entry as Record<string, unknown>)?.quantity),\n }))\n }\n const idempotencyKey = request.headers.get('idempotency-key') ?? undefined\n\n // Gate 4: this plugin, on for this site.\n const hostSnap = await hostRef(ctx, hostId).get()\n if (!isHostPluginEnabled(ctx.org, hostSnap.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({\n message: 'No such site',\n headers: ctx.headers,\n })\n }\n\n const outcome = await recordOrderShipment({\n hostId,\n orderId,\n to: status as OrderFulfilmentTarget,\n carrier,\n trackingNumber,\n ...(lineItems ? { lineItems } : {}),\n ...(typeof body.trackingUrl === 'string' ? { trackingUrl: body.trackingUrl } : {}),\n ...(body.notify === false ? { notify: false } : {}),\n ...(idempotencyKey ? { idempotencyKey } : {}),\n })\n if (outcome.outcome === 'invalid_lines') {\n return outcome.problem.problem === 'over_fulfilled'\n ? ApiErrors.conflict({\n message: outcome.message,\n code: 'over_fulfilled',\n headers: ctx.headers,\n })\n : ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: { lineItems: outcome.message },\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'no_such_order') {\n return ApiErrors.notFound({\n message: 'No such order',\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'blocked') {\n // A NEW 409 code (`order_transition`), because an integrator has to be\n // able to tell \"the order moved on without me\" apart from every other\n // conflict this API can raise — it is the one a fulfilment poller will\n // actually hit, and the one it must not retry forever.\n return ApiErrors.conflict({\n message: `Orders in \"${outcome.from}\" cannot be marked ${status}`,\n code: 'order_transition',\n headers: ctx.headers,\n })\n }\n // The order object, on both `recorded` and `already` — a retry lands the\n // same state and reads the same 200. Re-read after the write so the body\n // shows the shipment that was just recorded rather than the one before it.\n return apiJson(orderView(await hostRef(ctx, hostId).collection('orders').doc(orderId).get()), {\n headers: ctx.headers,\n })\n}\n\n/**\n * Price and stock live on VARIANTS, never on the product — a product-level\n * `inventory` exists only as a denormalized sum the console rewrites on every\n * decrement, and a product-level `priceUsd` is the legacy single-variant\n * shape. Publishing either as the product's price would be wrong the moment a\n * product has two variants, so the variant array is the contract and the\n * product carries only the roll-up, clearly named.\n *\n * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.\n * Collapsing them (the `?? 0` an integrator writes on the first day) turns\n * every untracked product into an out-of-stock one, so the distinction is\n * carried through verbatim rather than defaulted.\n */\nfunction variantView(variant: Record<string, unknown>) {\n const inventory = variant.inventory\n return {\n id: variant.id ?? null,\n sku: variant.sku ?? null,\n barcode: variant.barcode ?? null,\n options: variant.options ?? {},\n priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,\n compareAtPriceUsd:\n typeof variant.compareAtPriceUsd === 'number'\n ? variant.compareAtPriceUsd\n : null,\n weightGrams:\n typeof variant.weightGrams === 'number' ? variant.weightGrams : null,\n inventory: typeof inventory === 'number' ? inventory : null,\n inventoryTracked: typeof inventory === 'number',\n }\n}\n\nfunction productView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n const variants = Array.isArray(data.variants)\n ? (data.variants as Array<Record<string, unknown>>)\n : []\n const tracked = variants.filter((v) => typeof v.inventory === 'number')\n return {\n id: doc.id,\n object: 'product',\n name: data.name ?? null,\n slug: data.slug ?? null,\n description: data.description ?? null,\n type: data.type ?? null,\n status: data.status ?? null,\n tags: data.tags ?? [],\n categoryIds: data.categoryIds ?? [],\n mediaUrls: data.mediaUrls ?? [],\n options: data.options ?? [],\n variants: variants.map(variantView),\n // The sum across TRACKED variants only, and `null` when none of them is\n // tracked — so an untracked catalogue reads as \"we don't count this\"\n // rather than as a store with nothing left to sell.\n inventory: tracked.length\n ? tracked.reduce((sum, v) => sum + Number(v.inventory ?? 0), 0)\n : null,\n subscription: serialize(data.subscription) ?? null,\n created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,\n updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null,\n }\n}\n\nexport async function handleProducts(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , productId] = segments\n const denied = requireScope(ctx, 'products:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n const collection = hostRef(ctx, hostId).collection('products')\n\n if (productId) {\n const snap = await collection.doc(productId).get()\n // A soft-deleted product is gone as far as a customer is concerned. The\n // console filters `deletedAt` client-side; the API must not hand back a\n // product the merchant deleted just because the document survives.\n if (!snap.exists || snap.get('deletedAt')) {\n return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n }\n return apiJson(productView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const { docs, nextCursor } = await paginate(query, url)\n const data = docs.filter((doc) => !doc.get('deletedAt')).map(productView)\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n"],"names":["checkEntitlement","isHostPluginEnabled","ApiErrors","apiJson","listResponse","paginate","readJsonBody","requireScope","serialize","BUNDLE_ID","recordOrderShipment","orderViewFromData","isUnpaidQuote","requireCommerce","ctx","org","planRequired","message","code","headers","hostRef","hostId","firestore","collection","doc","orderView","id","data","handleOrders","request","segments","url","orderId","method","deniedWrite","unentitledWrite","updateOrder","denied","unentitled","methodNotAllowed","Allow","snap","get","exists","notFound","query","status","searchParams","where","channel","docs","nextCursor","filter","map","order","ORDER_WRITE_TARGETS","ORDER_WRITABLE_KEYS","ORDER_WRITE_REFUSED","cancelled","refunded","body","unknown","Object","keys","key","includes","length","badRequest","fields","fromEntries","String","refusal","join","carrier","slice","trackingNumber","lineItems","undefined","Array","isArray","entry","lineItemId","Number","quantity","idempotencyKey","hostSnap","outcome","to","trackingUrl","notify","problem","conflict","from","variantView","variant","inventory","sku","barcode","options","priceUsd","compareAtPriceUsd","weightGrams","inventoryTracked","productView","variants","tracked","v","object","name","slug","description","type","tags","categoryIds","mediaUrls","reduce","sum","subscription","created","createdAtMs","Date","toISOString","updated","updatedAtMs","handleProducts","productId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,mBAAmB,QAAQ,sBAAqB;AAC3E,SACEC,SAAS,EACTC,OAAO,EACPC,YAAY,QACP,2BAA0B;AACjC,SAEEC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,SAAS,QAAQ,mCAA+B;AACzD,SAAqCC,mBAAmB,QAAQ,sBAAkB;AAClF,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,aAAa,QAAQ,iCAA6B;AAE3D;;;;;;;;CAQC,GAED;;;;;;;;;;;;;;CAcC,GACD,SAASC,gBAAgBC,GAAiB;IACxC,OAAOd,iBAAiBc,IAAIC,GAAG,EAAE,cAC7B,OACAb,UAAUc,YAAY,CAAC;QACrBC,SAAS;QACTC,MAAM;QACNC,SAASL,IAAIK,OAAO;IACtB;AACN;AAEA,SAASC,QAAQN,GAAiB,EAAEO,MAAc;IAChD,OAAOP,IAAIQ,SAAS,CAACC,UAAU,CAAC,SAASC,GAAG,CAACH;AAC/C;AAEA;;;;;;;;;CASC,GACD,SA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OAAOd;IACnD,MAAMJ,OAAOuB,KAAKE,MAAM,CAAC,CAAC5B,MAAQ,CAACA,IAAIkB,GAAG,CAAC,cAAcW,GAAG,CAACkD;IAC7D,OAAOnG,aAAauB,MAAMwB,YAAYrC,IAAIK,OAAO;AACnD"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/orders-and-products.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 { checkEntitlement, isHostPluginEnabled } from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n paginate,\n readJsonBody,\n requireScope,\n requireSitePermission,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { BUNDLE_ID } from '../../constants/bundle-common'\nimport { type OrderFulfilmentTarget, recordOrderShipment } from '../fulfill-order'\nimport { orderViewFromData } from './order-view'\nimport { productView } from './product-view'\nimport { isUnpaidQuote } from '../../model/commerce-quotes'\n\n/**\n * A site's orders and products on the customer REST API,\n * `/v1/sites/{siteId}/orders/…` and `/v1/sites/{siteId}/products/…`\n * (AGL-1928, AGL-2461, AGL-3080). Registered from this plugin's console\n * server declarations; the console's `/v1` router owns the pipeline in\n * front — the key, the plan's API access, the request quota, the rate limit —\n * and refuses a site the key's organization does not own before it hands a\n * request here.\n */\n\n/**\n * Commerce resources need the `commerce` entitlement as well as the scope\n * (AGL-1928). `apiAccess` alone is the wrong gate here: it says the org may\n * call the API at all, not that it may still use the store. AGL-1873 closed\n * exactly this class on the write side — two money doors that asked the\n * plugin switch (`org.enabledPlugins`) instead of the plan, so a lapsed org\n * kept selling — and the same reasoning applies to a read. `enabledPlugins`\n * is the customer's own on/off switch and survives a downgrade; the plan does\n * not, and the published rule is that paid features stop at the door when the\n * plan no longer includes them.\n *\n * Answered as `plan_required` rather than `not_found`, deliberately. Hiding a\n * store that plainly exists behind a 404 sends an integrator hunting a wrong\n * site id; the honest answer names the plan.\n */\nfunction requireCommerce(ctx: ApiV1Context): Response | null {\n return checkEntitlement(ctx.org, 'commerce')\n ? null\n : ApiErrors.planRequired({\n message: 'Commerce is not included in this organization’s plan',\n code: 'commerce',\n headers: ctx.headers,\n })\n}\n\nfunction hostRef(ctx: ApiV1Context, hostId: string) {\n return ctx.firestore.collection('hosts').doc(hostId)\n}\n\n/**\n * Orders carry a legacy Commerce Starter shape (AGL-90) alongside the modern\n * one: `amountCents`/`feeCents` at the top level rather than a `totals` map.\n * The console lifts them through `CommerceModel.liftLegacyOrder` and reads\n * `lifted.totals?.totalCents ?? order.amountCents`. The API cannot publish two\n * shapes for one object, so the legacy fields are folded into `totals` here\n * and a client only ever sees the modern one. `channel` defaults to `online`\n * for the same reason the console's list does — an absent channel is a\n * pre-channel order, not an unknown one.\n */\nfunction orderView(doc: FirebaseFirestore.DocumentSnapshot) {\n return orderViewFromData(doc.id, doc.data() ?? {})\n}\n\nexport async function handleOrders(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , orderId] = segments\n // `orders:write` is checked BEFORE `orders:read`, matching `handleSites`\n // and `handleScopedMedia` (AGL-900): a fulfilment key that only records\n // shipments must not be told it lacks a read scope it was never meant to\n // hold.\n if (request.method === 'PATCH' && orderId) {\n const deniedWrite = requireScope(ctx, 'orders:write')\n if (deniedWrite) return deniedWrite\n const unentitledWrite = requireCommerce(ctx)\n if (unentitledWrite) return unentitledWrite\n return updateOrder(request, ctx, hostId, orderId)\n }\n const denied = requireScope(ctx, 'orders:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: orderId ? 'GET, PATCH' : 'GET' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('orders')\n\n if (orderId) {\n const snap = await collection.doc(orderId).get()\n // An unpaid quote is not an order yet (AGL-4093).\n if (!snap.exists || isUnpaidQuote(snap.data())) {\n return ApiErrors.notFound({ message: 'No such order', headers: ctx.headers })\n }\n return apiJson(orderView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const channel = url.searchParams.get('channel')\n // `online` is the DEFAULT, not a stored value on older orders, so filtering\n // for it in Firestore would silently drop every pre-channel order. Those are\n // exactly the oldest orders an accounting backfill is reaching for, so this\n // one value is filtered after the read instead. The page can therefore come\n // back shorter than `limit` while `has_more` is still true — which the\n // published pagination contract already tells clients to expect (check\n // `has_more`, never a page's length).\n if (channel && channel !== 'online') query = query.where('channel', '==', channel)\n const { docs, nextCursor } = await paginate(query, url)\n // Unpaid quotes share the collection and are not orders yet (AGL-4093);\n // left out after the read, like `online` above, so a page can be short.\n const data = docs\n .filter((doc) => !isUnpaidQuote(doc.data()))\n .map(orderView)\n .filter((order) => (channel === 'online' ? order.channel === 'online' : true))\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n/**\n * Statuses this endpoint will move an order TO, and the two it names as\n * refused. Kept as data so the 400 can list them and the docs can be checked\n * against the same source the handler branches on.\n */\nconst ORDER_WRITE_TARGETS: OrderFulfilmentTarget[] = ['fulfilled', 'delivered']\n\n/** The keys a PATCH may carry (AGL-3611 added the last three). */\nconst ORDER_WRITABLE_KEYS = ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify']\n\n/**\n * Transitions that exist in the commerce model and are DELIBERATELY not\n * reachable here — refused by name with a 400 that says why, never silently\n * ignored. `cancelled` releases held stock under its own transaction and\n * `refunded` moves money under another; admitting either here would hand a\n * caller a door around exactly the specifics those two routes exist to\n * enforce, and an API key is the credential least able to answer the\n * questions they ask.\n */\nconst ORDER_WRITE_REFUSED: Record<string, string> = {\n cancelled:\n 'Canceling an order releases held stock, so it is not part of this endpoint. Cancel it in the console.',\n refunded:\n 'Refunding an order moves money, so it is not part of this endpoint. Refund it in the console.',\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/orders/{orderId}` — record a shipment (AGL-2461).\n *\n * ## The write is the console's, shared\n *\n * The transition rule, the transaction that re-asks it under the write, the\n * fulfillment append and the timeline entry are `recordOrderShipment`'s,\n * the one implementation the console's `commerce/fulfill-order` route calls\n * too. A second copy of `ORDER_TRANSITIONS` here would be the bug rather\n * than the fix: two tables drift, and drift here means the API writing an\n * order status the console forbids — `paid → delivered` skipping\n * fulfilment, or a write onto a `refunded` order. That is the class\n * AGL-1818/AGL-1819 exist to close, and it is money-adjacent.\n *\n * ## What THIS function is responsible for: all of the authorization\n *\n * `recordOrderShipment` is pre-authorized by contract — it takes `hostId`\n * on trust — so every gate is here, and all four are load-bearing:\n *\n * 1. `orders:write` on the key (checked by the caller, above).\n * 2. The `commerce` PLAN entitlement (checked by the caller, above) — the\n * plan, never the plugin switch, which is the AGL-1873 distinction.\n * 3. **Org owns the site** — the console's `handleSites` refuses an unowned\n * `hostId` with a 404 before it hands any site resource to its plugin,\n * which is what keeps this from being a cross-tenant write primitive\n * addressable by anyone who can guess a host id. Deliberately NOT\n * re-checked here: a second copy would be a gate no test can redden\n * (removing either one alone leaves the other answering), and an unproven\n * guard on a cross-tenant write is worse than the one guard a test\n * actually holds. `api-v1-order-fulfilment.spec.ts`'s \"CANNOT move\n * another org's order\" case is that test, and it fails when\n * `handleSites`' `orgOwnsHost` is removed.\n * 4. **This plugin is switched on for this site.** The resource is\n * registered for every organization the console serves, so its being here\n * says nothing about one org's configuration; without this an org that\n * switched commerce off for a site would still accept writes into it,\n * which is the per-site enablement rule (AGL-1014) the plugin API\n * dispatcher applies to every other commerce door.\n *\n * ## No `Idempotency-Key`\n *\n * None is needed and none is accepted: the write returns without writing when\n * the order is already in the target status, so a retry lands the same state\n * AND returns the same `200` with the same order body — the contract\n * `updateRecord`, `updateContact` and `updateFormSubmission` are held to.\n */\nasync function updateOrder(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n orderId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((key) => !ORDER_WRITABLE_KEYS.includes(key))\n if (unknown.length > 0) {\n // Named, not dropped — the `updateFormSubmission` / `updateContact` rule.\n // A silently ignored `trackingUrl` here reads as \"we recorded your\n // shipment as you described it\" when half of it went nowhere, and the\n // caller is a warehouse system that will never look again.\n return ApiErrors.badRequest({\n message:\n 'Only `status`, `carrier`, `trackingNumber`, `trackingUrl`, `lineItems` and `notify` can be set on an order',\n code: 'validation_failed',\n fields: Object.fromEntries(\n unknown.map((key) => [key, 'Not writable on an order']),\n ),\n headers: ctx.headers,\n })\n }\n\n const status = String(body.status ?? '')\n const refusal = ORDER_WRITE_REFUSED[status]\n if (refusal) {\n return ApiErrors.badRequest({\n message: refusal,\n code: 'validation_failed',\n fields: { status: refusal },\n headers: ctx.headers,\n })\n }\n if (!(ORDER_WRITE_TARGETS as string[]).includes(status)) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n status: `Must be one of: ${ORDER_WRITE_TARGETS.join(', ')}`,\n },\n headers: ctx.headers,\n })\n }\n // Bounded exactly as the console route bounds them, so one field cannot be\n // used to stuff an order document through a door the console keeps narrow.\n const carrier = String(body.carrier ?? '').slice(0, 40)\n const trackingNumber = String(body.trackingNumber ?? '').slice(0, 60)\n // Partial shipments (AGL-3611): `lineItems: [{ lineItemId, quantity }]`.\n // Absent keeps the old meaning, everything still to ship.\n let lineItems: Array<{ lineItemId: number; quantity: number }> | undefined\n if (body.lineItems !== undefined) {\n if (status !== 'fulfilled' || !Array.isArray(body.lineItems) || body.lineItems.length === 0) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n lineItems:\n status !== 'fulfilled'\n ? 'Only a `fulfilled` update names line items'\n : 'Must be a non-empty array of { lineItemId, quantity }',\n },\n headers: ctx.headers,\n })\n }\n lineItems = (body.lineItems as unknown[]).slice(0, 500).map((entry) => ({\n lineItemId: Number((entry as Record<string, unknown>)?.lineItemId),\n quantity: Number((entry as Record<string, unknown>)?.quantity),\n }))\n }\n const idempotencyKey = request.headers.get('idempotency-key') ?? undefined\n\n // Gate 4: this plugin, on for this site.\n const hostSnap = await hostRef(ctx, hostId).get()\n if (!isHostPluginEnabled(ctx.org, hostSnap.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({\n message: 'No such site',\n headers: ctx.headers,\n })\n }\n\n const outcome = await recordOrderShipment({\n hostId,\n orderId,\n to: status as OrderFulfilmentTarget,\n carrier,\n trackingNumber,\n ...(lineItems ? { lineItems } : {}),\n ...(typeof body.trackingUrl === 'string' ? { trackingUrl: body.trackingUrl } : {}),\n ...(body.notify === false ? { notify: false } : {}),\n ...(idempotencyKey ? { idempotencyKey } : {}),\n })\n if (outcome.outcome === 'invalid_lines') {\n return outcome.problem.problem === 'over_fulfilled'\n ? ApiErrors.conflict({\n message: outcome.message,\n code: 'over_fulfilled',\n headers: ctx.headers,\n })\n : ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: { lineItems: outcome.message },\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'no_such_order') {\n return ApiErrors.notFound({\n message: 'No such order',\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'blocked') {\n // A NEW 409 code (`order_transition`), because an integrator has to be\n // able to tell \"the order moved on without me\" apart from every other\n // conflict this API can raise — it is the one a fulfilment poller will\n // actually hit, and the one it must not retry forever.\n return ApiErrors.conflict({\n message: `Orders in \"${outcome.from}\" cannot be marked ${status}`,\n code: 'order_transition',\n headers: ctx.headers,\n })\n }\n // The order object, on both `recorded` and `already` — a retry lands the\n // same state and reads the same 200. Re-read after the write so the body\n // shows the shipment that was just recorded rather than the one before it.\n return apiJson(orderView(await hostRef(ctx, hostId).collection('orders').doc(orderId).get()), {\n headers: ctx.headers,\n })\n}\n\n/**\n * The product writes' gates (AGL-4235), each load-bearing, in `updateOrder`'s\n * order: `products:write` on the credential, the `commerce` PLAN entitlement,\n * this plugin switched on for this site, and — for an app a person connected\n * — that person's \"Edit site content\" on the site, the permission the\n * console's product editor and the native apps' save route ask. The router\n * has already applied the site's lock and the person's membership.\n */\nfunction productWriteRefusal(ctx: ApiV1Context, hostId: string, hostDoc: FirebaseFirestore.DocumentSnapshot): Response | null {\n const denied = requireScope(ctx, 'products:write')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (!isHostPluginEnabled(ctx.org, hostDoc.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({ message: 'No such site', headers: ctx.headers })\n }\n return requireSitePermission(ctx, hostDoc, 'site.edit')\n}\n\nexport async function handleProducts(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , productId, sub, variantId] = segments\n if (sub !== undefined && (sub !== 'variants' || !variantId || segments.length > 6)) {\n return ApiErrors.notFound({ message: 'Unknown endpoint', headers: ctx.headers })\n }\n const writing =\n (request.method === 'POST' && !productId) ||\n ((request.method === 'PATCH' || request.method === 'DELETE') && productId && !variantId) ||\n (request.method === 'PATCH' && variantId)\n // `products:write` is asked BEFORE `products:read`, as the order writes ask\n // theirs (AGL-900): a key that only writes the catalog holds no read scope.\n if (writing) {\n const hostDoc = ctx.site?.snapshot ?? (await hostRef(ctx, hostId).get())\n const refused = productWriteRefusal(ctx, hostId, hostDoc)\n if (refused) return refused\n const writes = await import('./product-writes')\n if (variantId) return writes.updateProductVariant(request, ctx, hostId, productId, variantId)\n if (!productId) return writes.createProduct(request, ctx, hostId)\n if (request.method === 'PATCH') return writes.updateProduct(request, ctx, hostId, productId)\n return writes.deleteProductOverApi(ctx, hostId, productId)\n }\n const denied = requireScope(ctx, 'products:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET' || variantId) {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: variantId ? 'PATCH' : productId ? 'GET, PATCH, DELETE' : 'GET, POST' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('products')\n\n if (productId) {\n const snap = await collection.doc(productId).get()\n // A soft-deleted product is gone as far as a customer is concerned. The\n // console filters `deletedAt` client-side; the API must not hand back a\n // product the merchant deleted just because the document survives.\n if (!snap.exists || snap.get('deletedAt')) {\n return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n }\n return apiJson(productView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const { docs, nextCursor } = await paginate(query, url)\n const data = docs.filter((doc) => !doc.get('deletedAt')).map(productView)\n return listResponse(data, nextCursor, ctx.headers)\n}\n"],"names":["checkEntitlement","isHostPluginEnabled","ApiErrors","apiJson","listResponse","paginate","readJsonBody","requireScope","requireSitePermission","BUNDLE_ID","recordOrderShipment","orderViewFromData","productView","isUnpaidQuote","requireCommerce","ctx","org","planRequired","message","code","headers","hostRef","hostId","firestore","collection","doc","orderView","id","data","handleOrders","request","segments","url","orderId","method","deniedWrite","unentitledWrite","updateOrder","denied","unentitled","methodNotAllowed","Allow","snap","get","exists","notFound","query","status","searchParams","where","channel","docs","nextCursor","filter","map","order","ORDER_WRITE_TARGETS","ORDER_WRITABLE_KEYS","ORDER_WRITE_REFUSED","cancelled","refunded","body","unknown","Object","keys","key","includes","length","badRequest","fields","fromEntries","String","refusal","join","carrier","slice","trackingNumber","lineItems","undefined","Array","isArray","entry","lineItemId","Number","quantity","idempotencyKey","hostSnap","outcome","to","trackingUrl","notify","problem","conflict","from","productWriteRefusal","hostDoc","handleProducts","productId","sub","variantId","writing","site","snapshot","refused","writes","updateProductVariant","createProduct","updateProduct","deleteProductOverApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,mBAAmB,QAAQ,sBAAqB;AAC3E,SACEC,SAAS,EACTC,OAAO,EACPC,YAAY,QACP,2BAA0B;AACjC,SAEEC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,qBAAqB,QAChB,6CAA4C;AACnD,SAASC,SAAS,QAAQ,mCAA+B;AACzD,SAAqCC,mBAAmB,QAAQ,sBAAkB;AAClF,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,WAAW,QAAQ,oBAAgB;AAC5C,SAASC,aAAa,QAAQ,iCAA6B;AAE3D;;;;;;;;CAQC,GAED;;;;;;;;;;;;;;CAcC,GACD,SAASC,gBAAgBC,GAAiB;IACxC,OAAOf,iBAAiBe,IAAIC,GAAG,EAAE,cAC7B,OACAd,UAAUe,YAAY,CAAC;QACrBC,SAAS;QACTC,MAAM;QACNC,SAASL,IAAIK,OAAO;IACtB;AACN;AAEA,SAASC,QAAQN,GAAiB,EAAEO,MAAc;IAChD,OAAOP,IAAIQ,SAAS,CAACC,UAAU,CAAC,SAASC,GAAG,CAACH;AAC/C;AAEA;;;;;;;;;CASC,GACD,SAASI,UAAUD,GAAuC;QACvBA;IAAjC,OAAOd,kBAAkBc,IAAIE,EAAE,GAAEF,YAAAA,IAAIG,IAAI,cAARH,YAAc,CAAC;AAClD;AAEA,OAAO,eAAeI,aACpBC,OAAgB,EAChBf,GAAiB,EACjBgB,QAAkB,EAClBC,GAAQ;IAER,MAAM,GAAGV,UAAUW,QAAQ,GAAGF;IAC9B,yEAAyE;IACzE,wEAAwE;IACxE,yEAAyE;IACzE,QAAQ;IACR,IAAID,QAAQI,MAAM,KAAK,WAAWD,SAAS;QACzC,MAAME,cAAc5B,aAAaQ,KAAK;QACtC,IAAIoB,aAAa,OAAOA;QACxB,M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AAiCtB;IACrC,MAAMuB,SAASf,IAAIgB,YAAY,CAACL,GAAG,CAAC;IACpC,IAAII,QAAQD,QAAQA,MAAMG,KAAK,CAAC,UAAU,MAAMF;IAChD,MAAM,EAAEI,IAAI,EAAEC,UAAU,EAAE,GAAG,MAAM/C,SAASyC,OAAOd;IACnD,MAAMJ,OAAOuB,KAAKE,MAAM,CAAC,CAAC5B,MAAQ,CAACA,IAAIkB,GAAG,CAAC,cAAcW,GAAG,CAAC1C;IAC7D,OAAOR,aAAawB,MAAMwB,YAAYrC,IAAIK,OAAO;AACnD"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * A product as the customer API publishes it (AGL-1928): the reads and, since
19
+ * AGL-4235, the writes answer this one shape.
20
+ */
21
+ /**
22
+ * Price and stock live on VARIANTS, never on the product — a product-level
23
+ * `inventory` exists only as a denormalized sum the console rewrites on every
24
+ * decrement, and a product-level `priceUsd` is the legacy single-variant
25
+ * shape. Publishing either as the product's price would be wrong the moment a
26
+ * product has two variants, so the variant array is the contract and the
27
+ * product carries only the roll-up, clearly named.
28
+ *
29
+ * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.
30
+ * Collapsing them (the `?? 0` an integrator writes on the first day) turns
31
+ * every untracked product into an out-of-stock one, so the distinction is
32
+ * carried through verbatim rather than defaulted.
33
+ */
34
+ export declare function variantView(variant: Record<string, unknown>): {
35
+ id: unknown;
36
+ sku: unknown;
37
+ barcode: unknown;
38
+ options: unknown;
39
+ priceUsd: number;
40
+ compareAtPriceUsd: number;
41
+ weightGrams: number;
42
+ inventory: number;
43
+ inventoryTracked: boolean;
44
+ };
45
+ export declare function productView(doc: FirebaseFirestore.DocumentSnapshot): {
46
+ id: string;
47
+ object: string;
48
+ name: any;
49
+ slug: any;
50
+ description: any;
51
+ type: any;
52
+ status: any;
53
+ tags: any;
54
+ categoryIds: any;
55
+ mediaUrls: any;
56
+ options: any;
57
+ variants: {
58
+ id: unknown;
59
+ sku: unknown;
60
+ barcode: unknown;
61
+ options: unknown;
62
+ priceUsd: number;
63
+ compareAtPriceUsd: number;
64
+ weightGrams: number;
65
+ inventory: number;
66
+ inventoryTracked: boolean;
67
+ }[];
68
+ seo: {
69
+ title: any;
70
+ description: any;
71
+ };
72
+ inventory: number;
73
+ subscription: unknown;
74
+ created: string;
75
+ updated: string;
76
+ };
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { serialize } from "@aglyn/tenant-data-admin/server/api-v1-kit";
17
+ /**
18
+ * A product as the customer API publishes it (AGL-1928): the reads and, since
19
+ * AGL-4235, the writes answer this one shape.
20
+ */ /**
21
+ * Price and stock live on VARIANTS, never on the product — a product-level
22
+ * `inventory` exists only as a denormalized sum the console rewrites on every
23
+ * decrement, and a product-level `priceUsd` is the legacy single-variant
24
+ * shape. Publishing either as the product's price would be wrong the moment a
25
+ * product has two variants, so the variant array is the contract and the
26
+ * product carries only the roll-up, clearly named.
27
+ *
28
+ * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.
29
+ * Collapsing them (the `?? 0` an integrator writes on the first day) turns
30
+ * every untracked product into an out-of-stock one, so the distinction is
31
+ * carried through verbatim rather than defaulted.
32
+ */ export function variantView(variant) {
33
+ var _variant_id, _variant_sku, _variant_barcode, _variant_options;
34
+ const inventory = variant.inventory;
35
+ return {
36
+ id: (_variant_id = variant.id) != null ? _variant_id : null,
37
+ sku: (_variant_sku = variant.sku) != null ? _variant_sku : null,
38
+ barcode: (_variant_barcode = variant.barcode) != null ? _variant_barcode : null,
39
+ options: (_variant_options = variant.options) != null ? _variant_options : {},
40
+ priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,
41
+ compareAtPriceUsd: typeof variant.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null,
42
+ weightGrams: typeof variant.weightGrams === 'number' ? variant.weightGrams : null,
43
+ inventory: typeof inventory === 'number' ? inventory : null,
44
+ inventoryTracked: typeof inventory === 'number'
45
+ };
46
+ }
47
+ export function productView(doc) {
48
+ var _doc_data, _data_name, _data_slug, _data_description, _data_type, _data_status, _data_tags, _data_categoryIds, _data_mediaUrls, _data_options, _serialize;
49
+ var _data_seo, _data_seo1;
50
+ const data = (_doc_data = doc.data()) != null ? _doc_data : {};
51
+ const variants = Array.isArray(data.variants) ? data.variants : [];
52
+ const tracked = variants.filter((v)=>typeof v.inventory === 'number');
53
+ return {
54
+ id: doc.id,
55
+ object: 'product',
56
+ name: (_data_name = data.name) != null ? _data_name : null,
57
+ slug: (_data_slug = data.slug) != null ? _data_slug : null,
58
+ description: (_data_description = data.description) != null ? _data_description : null,
59
+ type: (_data_type = data.type) != null ? _data_type : null,
60
+ status: (_data_status = data.status) != null ? _data_status : null,
61
+ tags: (_data_tags = data.tags) != null ? _data_tags : [],
62
+ categoryIds: (_data_categoryIds = data.categoryIds) != null ? _data_categoryIds : [],
63
+ mediaUrls: (_data_mediaUrls = data.mediaUrls) != null ? _data_mediaUrls : [],
64
+ options: (_data_options = data.options) != null ? _data_options : [],
65
+ variants: variants.map(variantView),
66
+ // The product's own search listing (AGL-4235): what its page's title and
67
+ // description say to a search engine, `null` where the page falls back
68
+ // to the product's name and description.
69
+ seo: {
70
+ title: typeof ((_data_seo = data.seo) == null ? void 0 : _data_seo.title) === 'string' && data.seo.title ? data.seo.title : null,
71
+ description: typeof ((_data_seo1 = data.seo) == null ? void 0 : _data_seo1.description) === 'string' && data.seo.description ? data.seo.description : null
72
+ },
73
+ // The sum across TRACKED variants only, and `null` when none of them is
74
+ // tracked — so an untracked catalogue reads as "we don't count this"
75
+ // rather than as a store with nothing left to sell.
76
+ inventory: tracked.length ? tracked.reduce((sum, v)=>{
77
+ var _v_inventory;
78
+ return sum + Number((_v_inventory = v.inventory) != null ? _v_inventory : 0);
79
+ }, 0) : null,
80
+ subscription: (_serialize = serialize(data.subscription)) != null ? _serialize : null,
81
+ created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,
82
+ updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null
83
+ };
84
+ }
85
+
86
+ //# sourceMappingURL=product-view.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/product-view.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 { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n/**\n * A product as the customer API publishes it (AGL-1928): the reads and, since\n * AGL-4235, the writes answer this one shape.\n */\n\n/**\n * Price and stock live on VARIANTS, never on the product — a product-level\n * `inventory` exists only as a denormalized sum the console rewrites on every\n * decrement, and a product-level `priceUsd` is the legacy single-variant\n * shape. Publishing either as the product's price would be wrong the moment a\n * product has two variants, so the variant array is the contract and the\n * product carries only the roll-up, clearly named.\n *\n * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.\n * Collapsing them (the `?? 0` an integrator writes on the first day) turns\n * every untracked product into an out-of-stock one, so the distinction is\n * carried through verbatim rather than defaulted.\n */\nexport function variantView(variant: Record<string, unknown>) {\n const inventory = variant.inventory\n return {\n id: variant.id ?? null,\n sku: variant.sku ?? null,\n barcode: variant.barcode ?? null,\n options: variant.options ?? {},\n priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,\n compareAtPriceUsd:\n typeof variant.compareAtPriceUsd === 'number'\n ? variant.compareAtPriceUsd\n : null,\n weightGrams:\n typeof variant.weightGrams === 'number' ? variant.weightGrams : null,\n inventory: typeof inventory === 'number' ? inventory : null,\n inventoryTracked: typeof inventory === 'number',\n }\n}\n\nexport function productView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n const variants = Array.isArray(data.variants)\n ? (data.variants as Array<Record<string, unknown>>)\n : []\n const tracked = variants.filter((v) => typeof v.inventory === 'number')\n return {\n id: doc.id,\n object: 'product',\n name: data.name ?? null,\n slug: data.slug ?? null,\n description: data.description ?? null,\n type: data.type ?? null,\n status: data.status ?? null,\n tags: data.tags ?? [],\n categoryIds: data.categoryIds ?? [],\n mediaUrls: data.mediaUrls ?? [],\n options: data.options ?? [],\n variants: variants.map(variantView),\n // The product's own search listing (AGL-4235): what its page's title and\n // description say to a search engine, `null` where the page falls back\n // to the product's name and description.\n seo: {\n title: typeof data.seo?.title === 'string' && data.seo.title ? data.seo.title : null,\n description:\n typeof data.seo?.description === 'string' && data.seo.description ? data.seo.description : null,\n },\n // The sum across TRACKED variants only, and `null` when none of them is\n // tracked — so an untracked catalogue reads as \"we don't count this\"\n // rather than as a store with nothing left to sell.\n inventory: tracked.length\n ? tracked.reduce((sum, v) => sum + Number(v.inventory ?? 0), 0)\n : null,\n subscription: serialize(data.subscription) ?? null,\n created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,\n updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null,\n }\n}\n\n"],"names":["serialize","variantView","variant","inventory","id","sku","barcode","options","priceUsd","compareAtPriceUsd","weightGrams","inventoryTracked","productView","doc","data","variants","Array","isArray","tracked","filter","v","object","name","slug","description","type","status","tags","categoryIds","mediaUrls","map","seo","title","length","reduce","sum","Number","subscription","created","createdAtMs","Date","toISOString","updated","updatedAtMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AAEtE;;;CAGC,GAED;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,YAAYC,OAAgC;QAGpDA,aACCA,cACIA,kBACAA;IALX,MAAMC,YAAYD,QAAQC,SAAS;IACnC,OAAO;QACLC,EAAE,GAAEF,cAAAA,QAAQE,EAAE,YAAVF,cAAc;QAClBG,GAAG,GAAEH,eAAAA,QAAQG,GAAG,YAAXH,eAAe;QACpBI,OAAO,GAAEJ,mBAAAA,QAAQI,OAAO,YAAfJ,mBAAmB;QAC5BK,OAAO,GAAEL,mBAAAA,QAAQK,OAAO,YAAfL,mBAAmB,CAAC;QAC7BM,UAAU,OAAON,QAAQM,QAAQ,KAAK,WAAWN,QAAQM,QAAQ,GAAG;QACpEC,mBACE,OAAOP,QAAQO,iBAAiB,KAAK,WACjCP,QAAQO,iBAAiB,GACzB;QACNC,aACE,OAAOR,QAAQQ,WAAW,KAAK,WAAWR,QAAQQ,WAAW,GAAG;QAClEP,WAAW,OAAOA,cAAc,WAAWA,YAAY;QACvDQ,kBAAkB,OAAOR,cAAc;IACzC;AACF;AAEA,OAAO,SAASS,YAAYC,GAAuC;QACpDA,WAQLC,YACAA,YACOA,mBACPA,YACEA,cACF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/F;QACA,wEAAwE;QACxE,qEAAqE;QACrE,oDAAoD;QACpDrB,WAAWe,QAAQe,MAAM,GACrBf,QAAQgB,MAAM,CAAC,CAACC,KAAKf;gBAAmBA;mBAAbe,MAAMC,QAAOhB,eAAAA,EAAEjB,SAAS,YAAXiB,eAAe;WAAI,KAC3D;QACJiB,YAAY,GAAErC,aAAAA,UAAUc,KAAKuB,YAAY,aAA3BrC,aAAgC;QAC9CsC,SAASxB,KAAKyB,WAAW,GAAG,IAAIC,KAAKJ,OAAOtB,KAAKyB,WAAW,GAAGE,WAAW,KAAK;QAC/EC,SAAS5B,KAAK6B,WAAW,GAAG,IAAIH,KAAKJ,OAAOtB,KAAK6B,WAAW,GAAGF,WAAW,KAAK;IACjF;AACF"}
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type ApiV1Context } from '@aglyn/tenant-data-admin/server/api-v1-kit';
18
+ import { type ProductOption, type ProductStatus, type ProductType, type ProductVariant } from '../../model/commerce';
19
+ import { type EditedProduct } from '../../model/product-write';
20
+ import { type ProductBuildRefusal, type ProductSaveInput } from '../products-write';
21
+ /** The members a product write may carry, in the order the description lists them. */
22
+ export declare const PRODUCT_WRITABLE_KEYS: readonly ["name", "description", "status", "type", "slug", "tags", "categoryIds", "mediaUrls", "options", "variants", "seo"];
23
+ /** The members a variant write may carry. */
24
+ export declare const VARIANT_WRITABLE_KEYS: readonly ["priceUsd", "compareAtPriceUsd", "sku", "barcode", "weightGrams", "inventory"];
25
+ /**
26
+ * The kinds of product a caller may make. A digital product delivers files a
27
+ * person uploads in the editor, so it is made there.
28
+ */
29
+ export declare const PRODUCT_API_TYPES: readonly ProductType[];
30
+ export declare const PRODUCT_DIGITAL_REFUSAL = "A digital product delivers files uploaded in the console, so it is created and changed to digital there.";
31
+ export declare const PRODUCT_STATUSES: readonly ProductStatus[];
32
+ /** The stock a digital or service subscription cannot keep (AGL-1744), as the editor says it. */
33
+ export declare const PRODUCT_STOCK_NOT_TRACKED = "Stock is not tracked on a digital or service subscription. Send `null` to clear it.";
34
+ /** One variant's writable fields, as parsed. `null` clears a field; absent leaves it. */
35
+ export interface VariantWrite {
36
+ priceUsd?: number | null;
37
+ compareAtPriceUsd?: number | null;
38
+ sku?: string | null;
39
+ barcode?: string | null;
40
+ weightGrams?: number | null;
41
+ inventory?: number | null;
42
+ }
43
+ /** One entry of a product write's `variants`: the variant it names, and what changes on it. */
44
+ export interface VariantTargetWrite extends VariantWrite {
45
+ id?: string;
46
+ options?: Record<string, string>;
47
+ }
48
+ export interface ProductWriteValues {
49
+ name?: string;
50
+ description?: string;
51
+ status?: ProductStatus;
52
+ type?: ProductType;
53
+ slug?: string;
54
+ tags?: string[];
55
+ categoryIds?: string[];
56
+ mediaUrls?: string[];
57
+ options?: ProductOption[];
58
+ variants?: VariantTargetWrite[];
59
+ seo?: {
60
+ title?: string | null;
61
+ description?: string | null;
62
+ };
63
+ }
64
+ type Parsed<T> = {
65
+ values: T;
66
+ } | {
67
+ errors: Record<string, string>;
68
+ };
69
+ /**
70
+ * One variant's writable fields from a body (`VariantWrite`). With `target`,
71
+ * also the `id` or `options` that name which variant it is — an entry of a
72
+ * product write's `variants`.
73
+ */
74
+ export declare function readVariantWrite(body: unknown, options?: {
75
+ target?: boolean;
76
+ prefix?: string;
77
+ }): Parsed<VariantTargetWrite>;
78
+ /**
79
+ * A product write's body (`ProductWrite`): the members the editor lets a
80
+ * person set without a further plan feature. Every member it does not name
81
+ * is a 400 that names it. `create` requires `name`.
82
+ */
83
+ export declare function readProductWrite(body: Record<string, unknown>, options: {
84
+ create: boolean;
85
+ }): Parsed<ProductWriteValues>;
86
+ /** A variant with a variant write applied, as the editor's grid applies a typed cell. */
87
+ export declare function applyVariantWrite(variant: ProductVariant, write: VariantWrite): ProductVariant;
88
+ /**
89
+ * The product a write makes of `base`: only the members it carries change,
90
+ * so every field it does not name — the ones this API does not expose
91
+ * included — stays as stored.
92
+ */
93
+ export declare function mergeProductWrite(base: EditedProduct, values: ProductWriteValues, nowMs: number): EditedProduct | ProductBuildRefusal;
94
+ /** Seams for the specs; production passes none. */
95
+ export interface ProductApiDeps {
96
+ now?: () => number;
97
+ dropCache?: ProductSaveInput['dropCache'];
98
+ }
99
+ /**
100
+ * The product a create starts from: the editor's blank draft, unpriced.
101
+ *
102
+ * The editor opens a new product at its default price for the person looking
103
+ * at it to change or clear. A caller sees no such field: one that sent no
104
+ * price asked for none, so its variant is saved unpriced — "Price coming
105
+ * soon", not for sale (`variantHasPrice`) — rather than at a price nobody
106
+ * chose. A grid rebuilt from options takes the first variant's values, as the
107
+ * editor's does, so its new combinations are unpriced too until a variant
108
+ * write prices them.
109
+ */
110
+ export declare function unpricedProductDraft(): EditedProduct;
111
+ /**
112
+ * `POST /v1/sites/{siteId}/products` — the editor's Add product.
113
+ *
114
+ * A draft unless `status` says otherwise, as the editor starts one, so a new
115
+ * product is not on sale until someone means it to be. The id is minted
116
+ * here. The slug is claimed from the name when none is sent, as Duplicate
117
+ * claims one (`claimProductSlug`), and a sent slug another product holds —
118
+ * a deleted one's included, because a deleted product still answers its
119
+ * slug on the storefront — is a 409.
120
+ *
121
+ * Replay-safe on an `Idempotency-Key`, as `createContact` is and for its
122
+ * reasons: validation above the claim, every refusal after it releasing the
123
+ * key, the plan and the allowance counted inside the save's transaction.
124
+ */
125
+ export declare function createProduct(request: Request, ctx: ApiV1Context, hostId: string, deps?: ProductApiDeps): Promise<Response>;
126
+ /**
127
+ * `PATCH /v1/sites/{siteId}/products/{productId}` — the editor's save, for
128
+ * the fields sent. The editor's save is a full replace, so the stored product
129
+ * is read in the save's transaction and only the members sent change on it:
130
+ * subscription terms, add-ons, stock holds, stored timestamps and every other
131
+ * field this API does not expose stay as stored. A slug another product
132
+ * holds is a 409. An empty body changes nothing and answers the product.
133
+ */
134
+ export declare function updateProduct(request: Request, ctx: ApiV1Context, hostId: string, productId: string, deps?: ProductApiDeps): Promise<Response>;
135
+ /**
136
+ * `PATCH /v1/sites/{siteId}/products/{productId}/variants/{variantId}` —
137
+ * one row of the editor's variant grid: its price, compare-at price, SKU,
138
+ * barcode, weight and stock, through the same save, so every check runs.
139
+ * Answers the whole product.
140
+ */
141
+ export declare function updateProductVariant(request: Request, ctx: ApiV1Context, hostId: string, productId: string, variantId: string, deps?: ProductApiDeps): Promise<Response>;
142
+ /**
143
+ * `DELETE /v1/sites/{siteId}/products/{productId}` — the products list's
144
+ * Delete: `deletedAt` on the product, which takes it off sale, and the
145
+ * site's cache drop. Asked again, it answers the same receipt; a product
146
+ * that never existed is a 404.
147
+ */
148
+ export declare function deleteProductOverApi(ctx: ApiV1Context, hostId: string, productId: string, deps?: ProductApiDeps): Promise<Response>;
149
+ export {};