@aglyn/plugins-commerce 1.12.0 → 1.14.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.
- package/package.json +13 -13
- package/src/lib/components/console/catalog-organization-card.component.js +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/host-quotes-card.component.js +3 -2
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +5 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +104 -16
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
- package/src/lib/components/console/quote-pay-link.component.js +23 -12
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
- package/src/lib/components/console/quote-proofs.component.js +73 -5
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.js +9 -6
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +1 -1
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/quote-page-body.js +14 -8
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +1 -1
- package/src/lib/model/commerce-invoices.js +4 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-quote-email.d.ts +7 -6
- package/src/lib/model/commerce-quote-email.js +11 -6
- package/src/lib/model/commerce-quote-email.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +6 -1
- package/src/lib/model/commerce-quote-pay.js +18 -8
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
- package/src/lib/model/commerce-quote-proofs.js +58 -2
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +22 -1
- package/src/lib/model/commerce-quotes.js +25 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/plugin-permissions.d.ts +1 -1
- package/src/lib/model/plugin-permissions.js +10 -0
- package/src/lib/model/plugin-permissions.js.map +1 -1
- package/src/lib/server/commerce-pdf.d.ts +1 -1
- package/src/lib/server/commerce-pdf.js +1 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/paid-media-delivery.js +1 -1
- package/src/lib/server/paid-media-delivery.js.map +1 -1
- package/src/lib/server/quote-email.js +29 -25
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.js +6 -2
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proof-media.d.ts +63 -0
- package/src/lib/server/quote-proof-media.js +96 -0
- package/src/lib/server/quote-proof-media.js.map +1 -0
- package/src/lib/server/quote-proofs.js +9 -5
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote-uploads.d.ts +3 -1
- package/src/lib/server/quote-uploads.js +2 -1
- package/src/lib/server/quote-uploads.js.map +1 -1
- package/src/lib/server/quote.d.ts +3 -0
- package/src/lib/server/quote.js +127 -20
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/tenant-emails.js +16 -9
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/transfer/gift-cards.server.js +9 -11
- package/src/lib/transfer/gift-cards.server.js.map +1 -1
- package/src/lib/utils/commerce-document-pdf.js +12 -9
- package/src/lib/utils/commerce-document-pdf.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +2 -0
- package/src/lib/utils/quote-email-content.js +20 -10
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.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 type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","payLinkStoreOf","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,gBAAgB,QAAgC,oCAAmC;AAC5F,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,2BAA0B;AACrF,SAASC,QAAQ,QAA2B,wCAAuC;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,iDAAgD;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,EACrBC,cAAc,QAGT,oCAAgC;AACvC,SAASC,gBAAgB,QAAQ,4BAAwB;AACzD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,OAAO,QAA8B,oBAAgB;AAC9D,SAASC,eAAe,QAAQ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AKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK3H;YAAuB6I,UAAUtC;YAAgBqB;QAC3F,IAAI,SAASU,SAAS,OAAOxI,QAAQiJ,KAAKT,QAAQI,GAAG;QACrD,OAAOtI,qBAAqB2I,KAAKT;IACnC,EAAE,OAAO3D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB2I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEpD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.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 type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'proof' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, view.proofOnly ? 'proof' : 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","payLinkStoreOf","revision","Number","quote","payUrl","filename","proofOnly","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,gBAAgB,QAAgC,oCAAmC;AAC5F,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,2BAA0B;AACrF,SAASC,QAAQ,QAA2B,wCAAuC;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,iDAAgD;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,qBAAqB,EACrBC,cAAc,QAGT,oCAAgC;AACvC,SAASC,gBAAgB,QAAQ,4BAAwB;AACzD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,OAAO,QAA8B,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AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK5H;YAAuB8I,UAAUvC;YAAgBsB;QAC3F,IAAI,SAASU,SAAS,OAAOzI,QAAQkJ,KAAKT,QAAQI,GAAG;QACrD,OAAOvI,qBAAqB4I,KAAKT;IACnC,EAAE,OAAO5D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB4I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAErD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
@@ -119,7 +119,7 @@ import { mediaCdnScopeRefusal, parseMediaCdnScope, selectAutoRendition } from "@
|
|
|
119
119
|
}
|
|
120
120
|
// The CDN would 404 an org asset this site is not allowed to use, so a
|
|
121
121
|
// link to one is a link that cannot play.
|
|
122
|
-
if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'))) {
|
|
122
|
+
if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'), document.get('scopeMode'))) {
|
|
123
123
|
return refuse('not-found');
|
|
124
124
|
}
|
|
125
125
|
if (document.get('private') !== true) return refuse('not-private');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/paid-media-delivery.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 {\n hostQualifiedScope,\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n MEDIA_CDN_ROUTE,\n paidMediaAssetOfObject,\n parseMediaRenditions,\n parsePaidMediaSource,\n} from '@aglyn/aglyn/server'\nimport {\n type MediaDeliveryProvider,\n mediaDeliveryProvider,\n} from '@aglyn/aglyn/plugin-manager/media-delivery-provider'\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { mediaDeliveryRedirect } from '@aglyn/tenant-data-admin/server/media-delivery'\nimport {\n assertMediaSignatureTtl,\n mediaSignatureQuery,\n mintMediaSignature,\n} from '@aglyn/tenant-data-admin/server/media-signing'\nimport { isMediaStoragePathInScope } from '@aglyn/tenant-data-admin/server/media-storage-path'\nimport {\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n selectAutoRendition,\n} from '@aglyn/tenant-data-admin/server/serve-media-cdn'\n\n/**\n * Turning a URL stored on a product into a link a buyer may follow (AGL-2814).\n *\n * A product's paid media — its members videos — is stored as whatever the\n * author's picker wrote: a media reference, a CDN path, a raw Storage download\n * URL, or a hotlink somebody typed. `parsePaidMediaSource` says which of those\n * a value is. The commerce routes verify who is entitled and then redirect;\n * this module decides WHERE they may redirect, and its whole job is that the\n * answer is never a URL that outlives the purchase.\n *\n * ## The rules, in the order they are applied\n *\n * 1. **A library asset is delivered only when it is PRIVATE**, as a CDN URL\n * signed with {@link mintMediaSignature}. The CDN refuses a private asset on\n * every path without an unexpired signature, which is what makes the link\n * die. A public asset is refused here instead of redirected to: its URL\n * works for anyone forever, so handing it to a buyer is the leak itself.\n * 2. **A Storage download URL is never redirected to.** Its token lives as\n * long as the object. When the object belongs to a library asset, rule 1\n * applies to that asset. When no asset owns it (a legacy object, a derived\n * rendition file), it gets a V4 signed read URL with the same bounded\n * lifetime. When it is not in this platform's bucket, or not inside the\n * site's own library or its org's, it is refused.\n * 3. **Only the requesting site's own libraries are signed.** A product is\n * author data. Signing whatever scope it names would let one site's author\n * mint working links to another org's private files, so a host scope must\n * be this site and an org scope must be this site's org, and the signed\n * scope is always qualified with this site so the CDN's `visibleTo` check\n * runs against the site actually selling it.\n * 4. **A hotlink to somebody else's server passes through unchanged.** No code\n * of ours runs there and nothing here can make its URL expire. That is the\n * author's hosting decision, and the docs say so. EXCEPT a hotlink whose\n * host wears a brand it is not (`lookalikeBrandForHost`, the phishing\n * screen's rule): the redirect leaves from the merchant's own domain, so a\n * lure behind it is one no screen of the page or the receipt ever saw. It\n * is refused for every workspace, like a lookalike link in an email\n * (AGL-3363), and the caller files it.\n * 5. **A signed Storage read is a download when it is one.** A download, or\n * an object whose type a browser would run (HTML, SVG, XML), is signed\n * with `response-content-disposition: attachment`, so the file is saved\n * rather than rendered (AGL-3363). The CDN already does this for its own\n * deliveries; a V4 URL carried nothing.\n *\n * ## A video with a copy at the delivery provider (AGL-2824)\n *\n * A caller that asks for it with `delivery` gets, for a video that passes\n * rule 1, the delivery provider's own short-lived URL instead of the signed CDN\n * URL, whenever `mediaDeliveryRedirect` finds a current copy and the release\n * flag is on for the owning org. It is the URL the CDN would redirect the\n * signed request to anyway, minted one hop earlier and bounded by the same\n * lifetime. Anything else takes the signed CDN URL exactly as before.\n */\n\n/** Why a stored URL was not turned into a link. */\nexport type PaidMediaRefusal =\n /** A library asset the public can still fetch without a signature. */\n | 'not-private'\n /** No such asset, a deleted one, or one not shared with this site. */\n | 'not-found'\n /** Another site's library, another org's, or outside the media prefixes. */\n | 'out-of-scope'\n /** A Storage URL for a bucket this platform does not serve from. */\n | 'foreign-storage'\n /** Not a value any delivery can be built from. */\n | 'malformed'\n /** A hotlink to a host that wears another brand's name (AGL-3363). */\n | 'lookalike'\n\nexport type PaidMediaDelivery =\n | {\n ok: true\n via: 'signed-cdn'\n location: string\n expiresAtMs: number\n /** The scope segment the signature covers. */\n scope: string\n mediaId: string\n }\n | {\n ok: true\n via: 'signed-storage'\n location: string\n expiresAtMs: number\n objectPath: string\n /** Whose library the object is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The object's size, 0 when Storage did not say. */\n sizeBytes: number\n }\n | { ok: true; via: 'external'; location: string }\n | {\n ok: true\n via: 'delivery'\n location: string\n expiresAtMs: number\n /** The scope segment the delivery was minted for. */\n scope: string\n mediaId: string\n /** Whose library the asset is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The size of the copy the provider serves. */\n sizeBytes: number\n }\n | {\n ok: false\n refusal: PaidMediaRefusal\n /** For a `lookalike`: the host it wears a brand in, for the caller to file. */\n host?: string\n }\n\n/** A document read, reduced to what this module asks of one. */\nexport interface PaidMediaDocument {\n exists: boolean\n get(field: string): unknown\n}\n\n/** Every read and signature this module needs, injectable for tests. */\nexport interface PaidMediaDeliveryIo {\n /** The platform's media bucket; empty when unconfigured. */\n bucketName: string\n readMedia(\n collection: 'hosts' | 'orgs',\n scopeId: string,\n mediaId: string,\n ): Promise<PaidMediaDocument>\n /** The org a site belongs to, or null for an unindexed site. */\n orgIdForHost(hostId: string): Promise<string | null>\n /**\n * A V4 signed read URL for one object in {@link bucketName}. `attachment`\n * signs `response-content-disposition: attachment` into it (AGL-3363).\n */\n signStorageRead(\n objectPath: string,\n expiresAtMs: number,\n options?: { attachment?: boolean },\n ): Promise<string>\n /**\n * The object's size in bytes, for the bandwidth a signed read can send;\n * 0 when it cannot be read. Optional, so a double that never signs a\n * Storage read need not answer it.\n */\n storageObjectSize?(objectPath: string): Promise<number>\n}\n\n/** Object types a browser runs rather than shows: always saved, never rendered. */\nconst ACTIVE_OBJECT_EXTENSION = /\\.(html?|xhtml|xht|svgz?|xml|xsl|xslt|mht|mhtml|js|mjs)$/i\n\n/** Is this signed read a download, by the caller's ask or by what the object is? */\nexport function storageReadIsAttachment(\n objectPath: string,\n cdnParams: ReadonlyArray<readonly [string, string]> | undefined,\n): boolean {\n if ((cdnParams ?? []).some(([key, value]) => key === 'download' && value === '1')) {\n return true\n }\n return ACTIVE_OBJECT_EXTENSION.test(objectPath)\n}\n\n/**\n * Resolves a stored product media URL to a redirect target that expires, or\n * says why there is none. See the module comment for the rules.\n *\n * `cdnParams` ride on a signed CDN URL ahead of the signature, which covers\n * `(scope, mediaId, exp)` and never the parameters, so they select a\n * representation of the one asset the signature names and nothing else.\n */\nexport async function resolvePaidMediaDelivery(options: {\n stored: unknown\n /** The site selling the media; the only libraries it may sign from. */\n hostId: string\n /** The lifetime of the link; bounded by `assertMediaSignatureTtl`. */\n ttlMs: number\n cdnParams?: ReadonlyArray<readonly [string, string]>\n /**\n * Hand a video with a current copy at the delivery provider its URL there\n * (AGL-2824). `accept` is the request's `Accept`, which chooses the\n * rendition when `cdnParams` asks for `?r=auto`. The provider and the flag\n * verdict default to the registered provider and the release flag.\n */\n delivery?: {\n accept?: unknown\n provider?: MediaDeliveryProvider | null\n enabled?: (orgId: string | null) => Promise<boolean>\n }\n nowMs?: number\n io: PaidMediaDeliveryIo\n}): Promise<PaidMediaDelivery> {\n const { hostId, ttlMs, io } = options\n const nowMs = options.nowMs ?? Date.now()\n const refuse = (refusal: PaidMediaRefusal): PaidMediaDelivery => ({\n ok: false,\n refusal,\n })\n if (!hostId) return refuse('out-of-scope')\n\n // One lookup per call, and only for the forms that need to know the org.\n let orgId: Promise<string | null> | undefined\n const siteOrgId = () => (orgId ??= io.orgIdForHost(hostId))\n\n /**\n * The delivery provider's URL for a private library video, or null for\n * the signed CDN URL. The representation is the one the CDN would pick for\n * the same `?r=` and `Accept`, so the buyer gets the copy the signed URL\n * would have been redirected to.\n */\n const deliverFromProvider = async (\n delivery: NonNullable<typeof options.delivery>,\n asset: {\n collection: 'hosts' | 'orgs'\n scopeId: string\n orgScope: boolean\n deliveryScope: string\n mediaId: string\n document: PaidMediaDocument\n },\n ): Promise<PaidMediaDelivery | null> => {\n const provider =\n delivery.provider === undefined ? mediaDeliveryProvider('deliver') : delivery.provider\n if (!provider) return null\n const requested = (options.cdnParams ?? []).find(\n ([key]) => key === MEDIA_CDN_RENDITION_PARAM,\n )?.[1]\n const renditions = parseMediaRenditions(asset.document.get('videoRenditions'))\n const rendition = !requested\n ? undefined\n : requested === MEDIA_CDN_RENDITION_AUTO\n ? selectAutoRendition(renditions, delivery.accept)\n : renditions.find((entry) => entry.key === requested)\n const redirect = await mediaDeliveryRedirect({\n provider,\n asset: {\n collection: asset.collection,\n scopeId: asset.scopeId,\n mediaId: asset.mediaId,\n },\n document: asset.document,\n rendition,\n servedType: rendition ? rendition.contentType : asset.document.get('contentType'),\n claims: { scope: asset.deliveryScope, mediaId: asset.mediaId, hostId },\n orgId: async () => (asset.orgScope ? asset.scopeId : await siteOrgId()),\n ...(delivery.enabled ? { deliveryEnabled: delivery.enabled } : {}),\n ttlMs,\n nowMs,\n }).catch(() => null)\n if (!redirect) return null\n return {\n ok: true,\n via: 'delivery',\n location: redirect.location,\n expiresAtMs: redirect.expiresAtMs,\n scope: asset.deliveryScope,\n mediaId: asset.mediaId,\n collection: asset.collection,\n scopeId: asset.scopeId,\n sizeBytes: redirect.sizeBytes,\n }\n }\n\n const deliverAsset = async (\n scope: string,\n mediaId: string,\n ): Promise<PaidMediaDelivery> => {\n const parsed = parseMediaCdnScope(scope)\n if (!parsed) return refuse('malformed')\n let collection: 'hosts' | 'orgs'\n let deliveryScope: string\n if (parsed.isOrg) {\n const owner = await siteOrgId()\n if (!owner || parsed.scopeId !== owner) return refuse('out-of-scope')\n collection = 'orgs'\n deliveryScope = hostQualifiedScope(scope, hostId)\n } else {\n if (parsed.scopeId !== hostId) return refuse('out-of-scope')\n collection = 'hosts'\n deliveryScope = hostId\n }\n const deliveryParsed = parseMediaCdnScope(deliveryScope)\n if (!deliveryParsed) return refuse('malformed')\n const document = await io.readMedia(collection, parsed.scopeId, mediaId)\n if (!document?.exists || document.get('deletedAt')) {\n return refuse('not-found')\n }\n // The CDN would 404 an org asset this site is not allowed to use, so a\n // link to one is a link that cannot play.\n if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'))) {\n return refuse('not-found')\n }\n if (document.get('private') !== true) return refuse('not-private')\n assertMediaSignatureTtl(ttlMs)\n const delivered = options.delivery\n ? await deliverFromProvider(options.delivery, {\n collection,\n scopeId: parsed.scopeId,\n orgScope: parsed.isOrg,\n deliveryScope,\n mediaId,\n document,\n })\n : null\n if (delivered) return delivered\n const signature = mintMediaSignature(deliveryScope, mediaId, nowMs, ttlMs)\n const params = new URLSearchParams()\n for (const [key, value] of options.cdnParams ?? []) {\n if (key !== 'exp' && key !== 'sig') params.set(key, value)\n }\n const prefix = params.toString()\n return {\n ok: true,\n via: 'signed-cdn',\n location:\n `${MEDIA_CDN_ROUTE}/${deliveryScope}/${mediaId}?` +\n `${prefix ? `${prefix}&` : ''}${mediaSignatureQuery(signature)}`,\n expiresAtMs: signature.exp,\n scope: deliveryScope,\n mediaId,\n }\n }\n\n const source = parsePaidMediaSource(options.stored)\n switch (source.kind) {\n case 'malformed':\n return refuse('malformed')\n case 'external': {\n let externalHost: string\n try {\n externalHost = new URL(source.url).hostname\n } catch {\n return refuse('malformed')\n }\n if (lookalikeBrandForHost(externalHost)) {\n return { ok: false, refusal: 'lookalike', host: externalHost }\n }\n return { ok: true, via: 'external', location: source.url }\n }\n case 'asset':\n return deliverAsset(source.scope, source.mediaId)\n case 'storage-object': {\n if (!io.bucketName || source.bucket !== io.bucketName) {\n return refuse('foreign-storage')\n }\n const { objectPath } = source\n const segments = objectPath.split('/')\n let base: string | null = null\n if (segments[0] === 'hosts' && segments[1] === hostId) {\n base = `hosts/${hostId}`\n } else if (segments[0] === 'orgs' && segments[1]) {\n const owner = await siteOrgId()\n if (owner && segments[1] === owner) base = `orgs/${owner}`\n }\n // The same prefix test the CDN applies to a document's `storagePath`,\n // which also refuses traversal and empty segments.\n if (!base || !isMediaStoragePathInScope(objectPath, base)) {\n return refuse('out-of-scope')\n }\n // An object keyed like an asset IS that asset, and the asset's own rules\n // decide — including refusing it when the asset is still public.\n const asset = paidMediaAssetOfObject(objectPath)\n if (asset) return deliverAsset(asset.scope, asset.mediaId)\n assertMediaSignatureTtl(ttlMs)\n const expiresAtMs = nowMs + ttlMs\n const [location, sizeBytes] = await Promise.all([\n io.signStorageRead(objectPath, expiresAtMs, {\n attachment: storageReadIsAttachment(objectPath, options.cdnParams),\n }),\n io.storageObjectSize?.(objectPath).catch(() => 0) ?? Promise.resolve(0),\n ])\n return {\n ok: true,\n via: 'signed-storage',\n location,\n expiresAtMs,\n objectPath,\n collection: segments[0] === 'orgs' ? 'orgs' : 'hosts',\n scopeId: segments[1],\n sizeBytes,\n }\n }\n }\n}\n\n/**\n * The production reads behind {@link resolvePaidMediaDelivery}, built on the\n * caller's Firestore and bucket handles so a route's own mocks reach them.\n */\nexport function createPaidMediaDeliveryIo(options: {\n firestore: {\n collection(name: string): {\n doc(id: string): {\n get(): Promise<PaidMediaDocument>\n collection(name: string): {\n doc(id: string): { get(): Promise<PaidMediaDocument> }\n }\n }\n }\n }\n bucket: {\n name?: string\n file(path: string): {\n getSignedUrl(config: {\n version: 'v4'\n action: 'read'\n expires: number\n responseDisposition?: string\n }): Promise<[string] | string[]>\n getMetadata?(): Promise<[{ size?: unknown }, ...unknown[]] | Array<{ size?: unknown }>>\n }\n }\n}): PaidMediaDeliveryIo {\n const { firestore, bucket } = options\n return {\n bucketName: String(bucket?.name ?? ''),\n readMedia: (collection, scopeId, mediaId) =>\n firestore\n .collection(collection)\n .doc(scopeId)\n .collection('media')\n .doc(mediaId)\n .get(),\n orgIdForHost: async (hostId) => {\n const index = await firestore.collection('hostIndex').doc(hostId).get()\n const orgId = index.exists ? index.get('orgId') : undefined\n return typeof orgId === 'string' && orgId ? orgId : null\n },\n signStorageRead: async (objectPath, expiresAtMs, signOptions) => {\n const [url] = await bucket.file(objectPath).getSignedUrl({\n version: 'v4',\n action: 'read',\n expires: expiresAtMs,\n ...(signOptions?.attachment ? { responseDisposition: 'attachment' } : {}),\n })\n return String(url)\n },\n storageObjectSize: async (objectPath) => {\n const file = bucket.file(objectPath)\n if (!file.getMetadata) return 0\n const [metadata] = await file.getMetadata()\n const size = Number(metadata?.size)\n return Number.isSafeInteger(size) && size > 0 ? size : 0\n },\n }\n}\n"],"names":["hostQualifiedScope","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","MEDIA_CDN_ROUTE","paidMediaAssetOfObject","parseMediaRenditions","parsePaidMediaSource","mediaDeliveryProvider","lookalikeBrandForHost","mediaDeliveryRedirect","assertMediaSignatureTtl","mediaSignatureQuery","mintMediaSignature","isMediaStoragePathInScope","mediaCdnScopeRefusal","parseMediaCdnScope","selectAutoRendition","ACTIVE_OBJECT_EXTENSION","storageReadIsAttachment","objectPath","cdnParams","some","key","value","test","resolvePaidMediaDelivery","options","hostId","ttlMs","io","nowMs","Date","now","refuse","refusal","ok","orgId","siteOrgId","orgIdForHost","deliverFromProvider","delivery","asset","provider","undefined","requested","find","renditions","document","get","rendition","accept","entry","redirect","collection","scopeId","mediaId","servedType","contentType","claims","scope","deliveryScope","orgScope","enabled","deliveryEnabled","catch","via","location","expiresAtMs","sizeBytes","deliverAsset","parsed","isOrg","owner","deliveryParsed","readMedia","exists","delivered","signature","params","URLSearchParams","set","prefix","toString","exp","source","stored","kind","externalHost","URL","url","hostname","host","bucketName","bucket","segments","split","base","Promise","all","signStorageRead","attachment","storageObjectSize","resolve","createPaidMediaDeliveryIo","firestore","String","name","doc","index","signOptions","file","getSignedUrl","version","action","expires","responseDisposition","getMetadata","metadata","size","Number","isSafeInteger"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,QACf,sBAAqB;AAC5B,SAEEC,qBAAqB,QAChB,sDAAqD;AAC5D,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,qBAAqB,QAAQ,iDAAgD;AACtF,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,kBAAkB,QACb,gDAA+C;AACtD,SAASC,yBAAyB,QAAQ,qD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Q;QACtD;QACA+D,iBAAiB,OAAOhF,YAAYgD,aAAa0C;YAC/C,MAAM,CAACpB,IAAI,GAAG,MAAMI,OAAOiB,IAAI,CAAC3F,YAAY4F,YAAY,CAAC;gBACvDC,SAAS;gBACTC,QAAQ;gBACRC,SAAS/C;eACL0C,CAAAA,+BAAAA,YAAaT,UAAU,IAAG;gBAAEe,qBAAqB;YAAa,IAAI,CAAC;YAEzE,OAAOV,OAAOhB;QAChB;QACAY,mBAAmB,OAAOlF;YACxB,MAAM2F,OAAOjB,OAAOiB,IAAI,CAAC3F;YACzB,IAAI,CAAC2F,KAAKM,WAAW,EAAE,OAAO;YAC9B,MAAM,CAACC,SAAS,GAAG,MAAMP,KAAKM,WAAW;YACzC,MAAME,OAAOC,OAAOF,4BAAAA,SAAUC,IAAI;YAClC,OAAOC,OAAOC,aAAa,CAACF,SAASA,OAAO,IAAIA,OAAO;QACzD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/paid-media-delivery.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 {\n hostQualifiedScope,\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n MEDIA_CDN_ROUTE,\n paidMediaAssetOfObject,\n parseMediaRenditions,\n parsePaidMediaSource,\n} from '@aglyn/aglyn/server'\nimport {\n type MediaDeliveryProvider,\n mediaDeliveryProvider,\n} from '@aglyn/aglyn/plugin-manager/media-delivery-provider'\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { mediaDeliveryRedirect } from '@aglyn/tenant-data-admin/server/media-delivery'\nimport {\n assertMediaSignatureTtl,\n mediaSignatureQuery,\n mintMediaSignature,\n} from '@aglyn/tenant-data-admin/server/media-signing'\nimport { isMediaStoragePathInScope } from '@aglyn/tenant-data-admin/server/media-storage-path'\nimport {\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n selectAutoRendition,\n} from '@aglyn/tenant-data-admin/server/serve-media-cdn'\n\n/**\n * Turning a URL stored on a product into a link a buyer may follow (AGL-2814).\n *\n * A product's paid media — its members videos — is stored as whatever the\n * author's picker wrote: a media reference, a CDN path, a raw Storage download\n * URL, or a hotlink somebody typed. `parsePaidMediaSource` says which of those\n * a value is. The commerce routes verify who is entitled and then redirect;\n * this module decides WHERE they may redirect, and its whole job is that the\n * answer is never a URL that outlives the purchase.\n *\n * ## The rules, in the order they are applied\n *\n * 1. **A library asset is delivered only when it is PRIVATE**, as a CDN URL\n * signed with {@link mintMediaSignature}. The CDN refuses a private asset on\n * every path without an unexpired signature, which is what makes the link\n * die. A public asset is refused here instead of redirected to: its URL\n * works for anyone forever, so handing it to a buyer is the leak itself.\n * 2. **A Storage download URL is never redirected to.** Its token lives as\n * long as the object. When the object belongs to a library asset, rule 1\n * applies to that asset. When no asset owns it (a legacy object, a derived\n * rendition file), it gets a V4 signed read URL with the same bounded\n * lifetime. When it is not in this platform's bucket, or not inside the\n * site's own library or its org's, it is refused.\n * 3. **Only the requesting site's own libraries are signed.** A product is\n * author data. Signing whatever scope it names would let one site's author\n * mint working links to another org's private files, so a host scope must\n * be this site and an org scope must be this site's org, and the signed\n * scope is always qualified with this site so the CDN's `visibleTo` check\n * runs against the site actually selling it.\n * 4. **A hotlink to somebody else's server passes through unchanged.** No code\n * of ours runs there and nothing here can make its URL expire. That is the\n * author's hosting decision, and the docs say so. EXCEPT a hotlink whose\n * host wears a brand it is not (`lookalikeBrandForHost`, the phishing\n * screen's rule): the redirect leaves from the merchant's own domain, so a\n * lure behind it is one no screen of the page or the receipt ever saw. It\n * is refused for every workspace, like a lookalike link in an email\n * (AGL-3363), and the caller files it.\n * 5. **A signed Storage read is a download when it is one.** A download, or\n * an object whose type a browser would run (HTML, SVG, XML), is signed\n * with `response-content-disposition: attachment`, so the file is saved\n * rather than rendered (AGL-3363). The CDN already does this for its own\n * deliveries; a V4 URL carried nothing.\n *\n * ## A video with a copy at the delivery provider (AGL-2824)\n *\n * A caller that asks for it with `delivery` gets, for a video that passes\n * rule 1, the delivery provider's own short-lived URL instead of the signed CDN\n * URL, whenever `mediaDeliveryRedirect` finds a current copy and the release\n * flag is on for the owning org. It is the URL the CDN would redirect the\n * signed request to anyway, minted one hop earlier and bounded by the same\n * lifetime. Anything else takes the signed CDN URL exactly as before.\n */\n\n/** Why a stored URL was not turned into a link. */\nexport type PaidMediaRefusal =\n /** A library asset the public can still fetch without a signature. */\n | 'not-private'\n /** No such asset, a deleted one, or one not shared with this site. */\n | 'not-found'\n /** Another site's library, another org's, or outside the media prefixes. */\n | 'out-of-scope'\n /** A Storage URL for a bucket this platform does not serve from. */\n | 'foreign-storage'\n /** Not a value any delivery can be built from. */\n | 'malformed'\n /** A hotlink to a host that wears another brand's name (AGL-3363). */\n | 'lookalike'\n\nexport type PaidMediaDelivery =\n | {\n ok: true\n via: 'signed-cdn'\n location: string\n expiresAtMs: number\n /** The scope segment the signature covers. */\n scope: string\n mediaId: string\n }\n | {\n ok: true\n via: 'signed-storage'\n location: string\n expiresAtMs: number\n objectPath: string\n /** Whose library the object is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The object's size, 0 when Storage did not say. */\n sizeBytes: number\n }\n | { ok: true; via: 'external'; location: string }\n | {\n ok: true\n via: 'delivery'\n location: string\n expiresAtMs: number\n /** The scope segment the delivery was minted for. */\n scope: string\n mediaId: string\n /** Whose library the asset is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The size of the copy the provider serves. */\n sizeBytes: number\n }\n | {\n ok: false\n refusal: PaidMediaRefusal\n /** For a `lookalike`: the host it wears a brand in, for the caller to file. */\n host?: string\n }\n\n/** A document read, reduced to what this module asks of one. */\nexport interface PaidMediaDocument {\n exists: boolean\n get(field: string): unknown\n}\n\n/** Every read and signature this module needs, injectable for tests. */\nexport interface PaidMediaDeliveryIo {\n /** The platform's media bucket; empty when unconfigured. */\n bucketName: string\n readMedia(\n collection: 'hosts' | 'orgs',\n scopeId: string,\n mediaId: string,\n ): Promise<PaidMediaDocument>\n /** The org a site belongs to, or null for an unindexed site. */\n orgIdForHost(hostId: string): Promise<string | null>\n /**\n * A V4 signed read URL for one object in {@link bucketName}. `attachment`\n * signs `response-content-disposition: attachment` into it (AGL-3363).\n */\n signStorageRead(\n objectPath: string,\n expiresAtMs: number,\n options?: { attachment?: boolean },\n ): Promise<string>\n /**\n * The object's size in bytes, for the bandwidth a signed read can send;\n * 0 when it cannot be read. Optional, so a double that never signs a\n * Storage read need not answer it.\n */\n storageObjectSize?(objectPath: string): Promise<number>\n}\n\n/** Object types a browser runs rather than shows: always saved, never rendered. */\nconst ACTIVE_OBJECT_EXTENSION = /\\.(html?|xhtml|xht|svgz?|xml|xsl|xslt|mht|mhtml|js|mjs)$/i\n\n/** Is this signed read a download, by the caller's ask or by what the object is? */\nexport function storageReadIsAttachment(\n objectPath: string,\n cdnParams: ReadonlyArray<readonly [string, string]> | undefined,\n): boolean {\n if ((cdnParams ?? []).some(([key, value]) => key === 'download' && value === '1')) {\n return true\n }\n return ACTIVE_OBJECT_EXTENSION.test(objectPath)\n}\n\n/**\n * Resolves a stored product media URL to a redirect target that expires, or\n * says why there is none. See the module comment for the rules.\n *\n * `cdnParams` ride on a signed CDN URL ahead of the signature, which covers\n * `(scope, mediaId, exp)` and never the parameters, so they select a\n * representation of the one asset the signature names and nothing else.\n */\nexport async function resolvePaidMediaDelivery(options: {\n stored: unknown\n /** The site selling the media; the only libraries it may sign from. */\n hostId: string\n /** The lifetime of the link; bounded by `assertMediaSignatureTtl`. */\n ttlMs: number\n cdnParams?: ReadonlyArray<readonly [string, string]>\n /**\n * Hand a video with a current copy at the delivery provider its URL there\n * (AGL-2824). `accept` is the request's `Accept`, which chooses the\n * rendition when `cdnParams` asks for `?r=auto`. The provider and the flag\n * verdict default to the registered provider and the release flag.\n */\n delivery?: {\n accept?: unknown\n provider?: MediaDeliveryProvider | null\n enabled?: (orgId: string | null) => Promise<boolean>\n }\n nowMs?: number\n io: PaidMediaDeliveryIo\n}): Promise<PaidMediaDelivery> {\n const { hostId, ttlMs, io } = options\n const nowMs = options.nowMs ?? Date.now()\n const refuse = (refusal: PaidMediaRefusal): PaidMediaDelivery => ({\n ok: false,\n refusal,\n })\n if (!hostId) return refuse('out-of-scope')\n\n // One lookup per call, and only for the forms that need to know the org.\n let orgId: Promise<string | null> | undefined\n const siteOrgId = () => (orgId ??= io.orgIdForHost(hostId))\n\n /**\n * The delivery provider's URL for a private library video, or null for\n * the signed CDN URL. The representation is the one the CDN would pick for\n * the same `?r=` and `Accept`, so the buyer gets the copy the signed URL\n * would have been redirected to.\n */\n const deliverFromProvider = async (\n delivery: NonNullable<typeof options.delivery>,\n asset: {\n collection: 'hosts' | 'orgs'\n scopeId: string\n orgScope: boolean\n deliveryScope: string\n mediaId: string\n document: PaidMediaDocument\n },\n ): Promise<PaidMediaDelivery | null> => {\n const provider =\n delivery.provider === undefined ? mediaDeliveryProvider('deliver') : delivery.provider\n if (!provider) return null\n const requested = (options.cdnParams ?? []).find(\n ([key]) => key === MEDIA_CDN_RENDITION_PARAM,\n )?.[1]\n const renditions = parseMediaRenditions(asset.document.get('videoRenditions'))\n const rendition = !requested\n ? undefined\n : requested === MEDIA_CDN_RENDITION_AUTO\n ? selectAutoRendition(renditions, delivery.accept)\n : renditions.find((entry) => entry.key === requested)\n const redirect = await mediaDeliveryRedirect({\n provider,\n asset: {\n collection: asset.collection,\n scopeId: asset.scopeId,\n mediaId: asset.mediaId,\n },\n document: asset.document,\n rendition,\n servedType: rendition ? rendition.contentType : asset.document.get('contentType'),\n claims: { scope: asset.deliveryScope, mediaId: asset.mediaId, hostId },\n orgId: async () => (asset.orgScope ? asset.scopeId : await siteOrgId()),\n ...(delivery.enabled ? { deliveryEnabled: delivery.enabled } : {}),\n ttlMs,\n nowMs,\n }).catch(() => null)\n if (!redirect) return null\n return {\n ok: true,\n via: 'delivery',\n location: redirect.location,\n expiresAtMs: redirect.expiresAtMs,\n scope: asset.deliveryScope,\n mediaId: asset.mediaId,\n collection: asset.collection,\n scopeId: asset.scopeId,\n sizeBytes: redirect.sizeBytes,\n }\n }\n\n const deliverAsset = async (\n scope: string,\n mediaId: string,\n ): Promise<PaidMediaDelivery> => {\n const parsed = parseMediaCdnScope(scope)\n if (!parsed) return refuse('malformed')\n let collection: 'hosts' | 'orgs'\n let deliveryScope: string\n if (parsed.isOrg) {\n const owner = await siteOrgId()\n if (!owner || parsed.scopeId !== owner) return refuse('out-of-scope')\n collection = 'orgs'\n deliveryScope = hostQualifiedScope(scope, hostId)\n } else {\n if (parsed.scopeId !== hostId) return refuse('out-of-scope')\n collection = 'hosts'\n deliveryScope = hostId\n }\n const deliveryParsed = parseMediaCdnScope(deliveryScope)\n if (!deliveryParsed) return refuse('malformed')\n const document = await io.readMedia(collection, parsed.scopeId, mediaId)\n if (!document?.exists || document.get('deletedAt')) {\n return refuse('not-found')\n }\n // The CDN would 404 an org asset this site is not allowed to use, so a\n // link to one is a link that cannot play.\n if (\n mediaCdnScopeRefusal(\n deliveryParsed,\n document.get('visibleTo'),\n document.get('scopeMode'),\n )\n ) {\n return refuse('not-found')\n }\n if (document.get('private') !== true) return refuse('not-private')\n assertMediaSignatureTtl(ttlMs)\n const delivered = options.delivery\n ? await deliverFromProvider(options.delivery, {\n collection,\n scopeId: parsed.scopeId,\n orgScope: parsed.isOrg,\n deliveryScope,\n mediaId,\n document,\n })\n : null\n if (delivered) return delivered\n const signature = mintMediaSignature(deliveryScope, mediaId, nowMs, ttlMs)\n const params = new URLSearchParams()\n for (const [key, value] of options.cdnParams ?? []) {\n if (key !== 'exp' && key !== 'sig') params.set(key, value)\n }\n const prefix = params.toString()\n return {\n ok: true,\n via: 'signed-cdn',\n location:\n `${MEDIA_CDN_ROUTE}/${deliveryScope}/${mediaId}?` +\n `${prefix ? `${prefix}&` : ''}${mediaSignatureQuery(signature)}`,\n expiresAtMs: signature.exp,\n scope: deliveryScope,\n mediaId,\n }\n }\n\n const source = parsePaidMediaSource(options.stored)\n switch (source.kind) {\n case 'malformed':\n return refuse('malformed')\n case 'external': {\n let externalHost: string\n try {\n externalHost = new URL(source.url).hostname\n } catch {\n return refuse('malformed')\n }\n if (lookalikeBrandForHost(externalHost)) {\n return { ok: false, refusal: 'lookalike', host: externalHost }\n }\n return { ok: true, via: 'external', location: source.url }\n }\n case 'asset':\n return deliverAsset(source.scope, source.mediaId)\n case 'storage-object': {\n if (!io.bucketName || source.bucket !== io.bucketName) {\n return refuse('foreign-storage')\n }\n const { objectPath } = source\n const segments = objectPath.split('/')\n let base: string | null = null\n if (segments[0] === 'hosts' && segments[1] === hostId) {\n base = `hosts/${hostId}`\n } else if (segments[0] === 'orgs' && segments[1]) {\n const owner = await siteOrgId()\n if (owner && segments[1] === owner) base = `orgs/${owner}`\n }\n // The same prefix test the CDN applies to a document's `storagePath`,\n // which also refuses traversal and empty segments.\n if (!base || !isMediaStoragePathInScope(objectPath, base)) {\n return refuse('out-of-scope')\n }\n // An object keyed like an asset IS that asset, and the asset's own rules\n // decide — including refusing it when the asset is still public.\n const asset = paidMediaAssetOfObject(objectPath)\n if (asset) return deliverAsset(asset.scope, asset.mediaId)\n assertMediaSignatureTtl(ttlMs)\n const expiresAtMs = nowMs + ttlMs\n const [location, sizeBytes] = await Promise.all([\n io.signStorageRead(objectPath, expiresAtMs, {\n attachment: storageReadIsAttachment(objectPath, options.cdnParams),\n }),\n io.storageObjectSize?.(objectPath).catch(() => 0) ?? Promise.resolve(0),\n ])\n return {\n ok: true,\n via: 'signed-storage',\n location,\n expiresAtMs,\n objectPath,\n collection: segments[0] === 'orgs' ? 'orgs' : 'hosts',\n scopeId: segments[1],\n sizeBytes,\n }\n }\n }\n}\n\n/**\n * The production reads behind {@link resolvePaidMediaDelivery}, built on the\n * caller's Firestore and bucket handles so a route's own mocks reach them.\n */\nexport function createPaidMediaDeliveryIo(options: {\n firestore: {\n collection(name: string): {\n doc(id: string): {\n get(): Promise<PaidMediaDocument>\n collection(name: string): {\n doc(id: string): { get(): Promise<PaidMediaDocument> }\n }\n }\n }\n }\n bucket: {\n name?: string\n file(path: string): {\n getSignedUrl(config: {\n version: 'v4'\n action: 'read'\n expires: number\n responseDisposition?: string\n }): Promise<[string] | string[]>\n getMetadata?(): Promise<[{ size?: unknown }, ...unknown[]] | Array<{ size?: unknown }>>\n }\n }\n}): PaidMediaDeliveryIo {\n const { firestore, bucket } = options\n return {\n bucketName: String(bucket?.name ?? ''),\n readMedia: (collection, scopeId, mediaId) =>\n firestore\n .collection(collection)\n .doc(scopeId)\n .collection('media')\n .doc(mediaId)\n .get(),\n orgIdForHost: async (hostId) => {\n const index = await firestore.collection('hostIndex').doc(hostId).get()\n const orgId = index.exists ? index.get('orgId') : undefined\n return typeof orgId === 'string' && orgId ? orgId : null\n },\n signStorageRead: async (objectPath, expiresAtMs, signOptions) => {\n const [url] = await bucket.file(objectPath).getSignedUrl({\n version: 'v4',\n action: 'read',\n expires: expiresAtMs,\n ...(signOptions?.attachment ? { responseDisposition: 'attachment' } : {}),\n })\n return String(url)\n },\n storageObjectSize: async (objectPath) => {\n const file = bucket.file(objectPath)\n if (!file.getMetadata) return 0\n const [metadata] = await file.getMetadata()\n const size = Number(metadata?.size)\n return Number.isSafeInteger(size) && size > 0 ? size : 0\n },\n }\n}\n"],"names":["hostQualifiedScope","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","MEDIA_CDN_ROUTE","paidMediaAssetOfObject","parseMediaRenditions","parsePaidMediaSource","mediaDeliveryProvider","lookalikeBrandForHost","mediaDeliveryRedirect","assertMediaSignatureTtl","mediaSignatureQuery","mintMediaSignature","isMediaStoragePathInScope","mediaCdnScopeRefusal","parseMediaCdnScope","selectAutoRendition","ACTIVE_OBJECT_EXTENSION","storageReadIsAttachment","objectPath","cdnParams","some","key","value","test","resolvePaidMediaDelivery","options","hostId","ttlMs","io","nowMs","Date","now","refuse","refusal","ok","orgId","siteOrgId","orgIdForHost","deliverFromProvider","delivery","asset","provider","undefined","requested","find","renditions","document","get","rendition","accept","entry","redirect","collection","scopeId","mediaId","servedType","contentType","claims","scope","deliveryScope","orgScope","enabled","deliveryEnabled","catch","via","location","expiresAtMs","sizeBytes","deliverAsset","parsed","isOrg","owner","deliveryParsed","readMedia","exists","delivered","signature","params","URLSearchParams","set","prefix","toString","exp","source","stored","kind","externalHost","URL","url","hostname","host","bucketName","bucket","segments","split","base","Promise","all","signStorageRead","attachment","storageObjectSize","resolve","createPaidMediaDeliveryIo","firestore","String","name","doc","index","signOptions","file","getSignedUrl","version","action","expires","responseDisposition","getMetadata","metadata","size","Number","isSafeInteger"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,QACf,sBAAqB;AAC5B,SAEEC,qBAAqB,QAChB,sDAAqD;AAC5D,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,qBAAqB,QAAQ,iDAAgD;AACtF,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,kBAAkB,QACb,gDAA+C;AACtD,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SACEC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,QACd,kDAAiD;AAoJxD,iFAAiF,GACjF,MAAMC,0BAA0B;AAEhC,kFAAkF,GAClF,OAAO,SAASC,wBACdC,UAAkB,EAClBC,SAA+D;IAE/D,IAAI,CAACA,oBA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eACL0C,CAAAA,+BAAAA,YAAaT,UAAU,IAAG;gBAAEe,qBAAqB;YAAa,IAAI,CAAC;YAEzE,OAAOV,OAAOhB;QAChB;QACAY,mBAAmB,OAAOlF;YACxB,MAAM2F,OAAOjB,OAAOiB,IAAI,CAAC3F;YACzB,IAAI,CAAC2F,KAAKM,WAAW,EAAE,OAAO;YAC9B,MAAM,CAACC,SAAS,GAAG,MAAMP,KAAKM,WAAW;YACzC,MAAME,OAAOC,OAAOF,4BAAAA,SAAUC,IAAI;YAClC,OAAOC,OAAOC,aAAa,CAACF,SAASA,OAAO,IAAIA,OAAO;QACzD;IACF;AACF"}
|
|
@@ -128,29 +128,32 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
128
128
|
radius: theme == null ? void 0 : theme.buttonRadius,
|
|
129
129
|
store: CommerceModel.payLinkStoreOf(input.store)
|
|
130
130
|
});
|
|
131
|
-
// The PDF is what the email says is attached; without it nothing goes.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
131
|
+
// The PDF is what the email says is attached; without it nothing goes. A
|
|
132
|
+
// proof with no price yet says no such thing: its proof is the whole of it.
|
|
133
|
+
let pdf = null;
|
|
134
|
+
if (!content.proofOnly) {
|
|
135
|
+
try {
|
|
136
|
+
pdf = await deps.quotePdf({
|
|
137
|
+
hostId,
|
|
138
|
+
quoteId,
|
|
139
|
+
order,
|
|
140
|
+
host,
|
|
141
|
+
store: input.store,
|
|
142
|
+
owner: input.owner,
|
|
143
|
+
payUrl: input.payUrl
|
|
144
|
+
});
|
|
145
|
+
} catch (error) {
|
|
146
|
+
console.error('[commerce/quote-email] the PDF could not be made', {
|
|
147
|
+
hostId,
|
|
148
|
+
quoteId,
|
|
149
|
+
error
|
|
150
|
+
});
|
|
151
|
+
return {
|
|
152
|
+
sent: false,
|
|
153
|
+
status: 500,
|
|
154
|
+
error: 'The quote’s PDF could not be made, so nothing was sent. Try again.'
|
|
155
|
+
};
|
|
156
|
+
}
|
|
154
157
|
}
|
|
155
158
|
const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens);
|
|
156
159
|
const thread = readEmailThread((_order_quote = order.quote) == null ? void 0 : _order_quote.emailThread);
|
|
@@ -180,7 +183,8 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
180
183
|
fromName: resolveBrandingProfile((_input_owner = input.owner) == null ? void 0 : _input_owner.org).fromName,
|
|
181
184
|
sendingIdentity: identity,
|
|
182
185
|
audience: 'tenant',
|
|
183
|
-
context: 'quote'
|
|
186
|
+
context: 'quote'
|
|
187
|
+
}, pdf ? {
|
|
184
188
|
attachments: [
|
|
185
189
|
{
|
|
186
190
|
filename: pdf.filename,
|
|
@@ -188,7 +192,7 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
188
192
|
content: Buffer.from(pdf.bytes).toString('base64')
|
|
189
193
|
}
|
|
190
194
|
]
|
|
191
|
-
}));
|
|
195
|
+
} : {}));
|
|
192
196
|
if (!result.sent) return _extends({
|
|
193
197
|
sent: false
|
|
194
198
|
}, refusalOf(result));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the quote wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the quote wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the quote wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The quote email could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n\n // The PDF is what the email says is attached; without it nothing goes.\n let pdf: CommercePdfFile\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","linkReplaced","colors","radius","buttonRadius","payLinkStoreOf","pdf","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,QAMJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,cAAc,EACdC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,eAAe,EAAEC,iBAAiB,QAA+B,kCAA8B;AAgFxG,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMV,cAAcW,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,YAAY,IAAMnB;QAClBoB,iBAAiB,CAACC,SAAWb,oBAAoBa;QACjDC,QAAQ,CAACD,QAAQE,KAAKC,SAAWd,0BAA0BO,aAAaI,QAAQE,KAAKC;QACrFC,OAAO,OAAOJ,SAAW,AAAC,CAAA,MAAMV,eAAeM,aAAaI,QAAQP,gBAAe,EAAGW,KAAK;QAC3FC,UAAU,OAAOC,QAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,YAAY,CAACD;QACzEE,MAAM,CAACC,UAAYxB,UAAUwB;QAC7BC,OAAO,OAAOV;YACZ,MAAMZ,eAAeY;QACvB;QACAW,aAAa,CAACC,QAAUrB,gCAAgCqB;IAC1D;AACF;AASA,MAAMC,QAAQ;AAEd,mDAAmD,GACnD,OAAO,SAASC,kBAAkBC,IAA6B;QAEjBA;IAD5C,MAAMC,QAAQxC,iBAAiB,gBAAgBuC;IAC/C,OAAOE,OAAOD,gBAAAA,QAAS,IAAIE,IAAI,MAAMD,QAAOF,aAAAA,IAAI,CAAC,OAA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A,MAAM;eAAUhC,UAAUC;YACrD,4DAA4D;YAC5D,MAAMM,KAAK3B,KAAK,CAACV,QAAQ+C,KAAK,CAAC,CAACb,QAAU2B,QAAQ3B,KAAK,CAAC,sCAAsCA;YAC9F,OAAO;gBACL4B,MAAM;gBACNM;gBACAoB,UAAU,GAAE,aAAA,AAACzD,OAAoD0D,EAAE,YAAvD,aAA2D;gBACvE/C;gBACA+B;gBACAT,QAAQtF,qBAAqBsF,QAAQ;oBAAEI;oBAAW1B;gBAAQ;YAC5D;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the quote wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the quote wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the quote wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The quote email could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n\n // The PDF is what the email says is attached; without it nothing goes. A\n // proof with no price yet says no such thing: its proof is the whole of it.\n let pdf: CommercePdfFile | null = null\n if (!content.proofOnly) {\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n ...(pdf\n ? {\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n }\n : {}),\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","linkReplaced","colors","radius","buttonRadius","payLinkStoreOf","pdf","proofOnly","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,QAMJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,cAAc,EACdC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,eAAe,EAAEC,iBAAiB,QAA+B,kCAA8B;AAgFxG,OAAO,SAASC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|
|
196
196
|
if (version < current && !options.history) {
|
|
197
|
+
// What the customer was sent, in their words: a proof with no price says proof (AGL-4184).
|
|
198
|
+
const noun = kind === 'quote' && CommerceModel.quoteIsProofOnly(order) ? 'proof' : nounOf(kind);
|
|
197
199
|
return {
|
|
198
200
|
outcome: {
|
|
199
201
|
status: 410,
|
|
200
202
|
body: {
|
|
201
203
|
state: 'replaced',
|
|
202
204
|
kind,
|
|
205
|
+
noun,
|
|
203
206
|
storeName,
|
|
204
207
|
replaced: true,
|
|
205
|
-
error: `This ${
|
|
208
|
+
error: `This ${noun} was updated, and ${storeName || 'the business'} sent you a newer link.`
|
|
206
209
|
}
|
|
207
210
|
}
|
|
208
211
|
};
|
|
@@ -313,12 +316,13 @@ function headerOf(req, name) {
|
|
|
313
316
|
if ('outcome' in linked) {
|
|
314
317
|
// The replaced page is a page, not a failure: answered as data.
|
|
315
318
|
if (linked.outcome.status === 410) {
|
|
316
|
-
const { storeName, kind } = linked.outcome.body;
|
|
319
|
+
const { storeName, kind, noun } = linked.outcome.body;
|
|
317
320
|
return {
|
|
318
321
|
status: 200,
|
|
319
322
|
body: {
|
|
320
323
|
state: 'replaced',
|
|
321
324
|
kind,
|
|
325
|
+
noun,
|
|
322
326
|
storeName
|
|
323
327
|
}
|
|
324
328
|
};
|