@aglyn/plugins-commerce 1.36.0 → 1.37.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/storefront-payment-element.js +6 -25
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/server/woo/woo-images.d.ts +56 -0
- package/src/lib/server/woo/woo-images.js +166 -0
- package/src/lib/server/woo/woo-images.js.map +1 -0
- package/src/lib/server/woo/woo-products.js +22 -3
- package/src/lib/server/woo/woo-products.js.map +1 -1
- package/src/lib/server/woo/woo-shapes.js +20 -7
- package/src/lib/server/woo/woo-shapes.js.map +1 -1
- package/src/lib/transfer/product-images.d.ts +1 -1
- package/src/lib/transfer/product-images.js +1 -1
- package/src/lib/transfer/product-images.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-commerce",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.37.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,18 +25,18 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
31
|
-
"@aglyn/shared-ui-next": "1.
|
|
32
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
33
|
-
"@aglyn/shared-util-email": "1.
|
|
34
|
-
"@aglyn/shared-util-http": "1.
|
|
35
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
36
|
-
"@aglyn/shared-util-tools": "1.
|
|
37
|
-
"@aglyn/tenant-data-admin": "1.
|
|
38
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
39
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.37.0",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.37.0",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.37.0",
|
|
31
|
+
"@aglyn/shared-ui-next": "1.37.0",
|
|
32
|
+
"@aglyn/shared-ui-snackstack": "1.37.0",
|
|
33
|
+
"@aglyn/shared-util-email": "1.37.0",
|
|
34
|
+
"@aglyn/shared-util-http": "1.37.0",
|
|
35
|
+
"@aglyn/shared-util-timestamp": "1.37.0",
|
|
36
|
+
"@aglyn/shared-util-tools": "1.37.0",
|
|
37
|
+
"@aglyn/tenant-data-admin": "1.37.0",
|
|
38
|
+
"@aglyn/tenant-feature-instance": "1.37.0",
|
|
39
|
+
"@aglyn/tenant-runtime": "1.37.0",
|
|
40
40
|
"@stripe/react-stripe-js": "^7.0.1",
|
|
41
41
|
"@stripe/stripe-js": "^10.2.1",
|
|
42
42
|
"@swc/helpers": "0.5.24",
|
|
@@ -62,7 +62,6 @@ function getStripe(publishableKey, stripeAccount) {
|
|
|
62
62
|
stripePromises.clear();
|
|
63
63
|
}
|
|
64
64
|
const GENERIC_FAILURE = 'That payment could not be completed. Try another card.';
|
|
65
|
-
/** How long the address must sit still before the session re-prices on it. */ const ADDRESS_SETTLE_MS = 400;
|
|
66
65
|
function SummaryRow({ label, value, strong }) {
|
|
67
66
|
return /*#__PURE__*/ _jsxs(Box, {
|
|
68
67
|
sx: {
|
|
@@ -179,27 +178,11 @@ function PaymentForm({ payLabel, defaultEmail, onCancel, onRestart, wallets }) {
|
|
|
179
178
|
checkout,
|
|
180
179
|
selectedShippingId
|
|
181
180
|
]);
|
|
182
|
-
//
|
|
183
|
-
// the
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
|
|
187
|
-
useEffect(()=>()=>{
|
|
188
|
-
if (addressTimer.current) clearTimeout(addressTimer.current);
|
|
189
|
-
}, []);
|
|
190
|
-
const onShippingAddressChange = useCallback((event)=>{
|
|
191
|
-
if (!checkout || !event.complete) return;
|
|
192
|
-
if (addressTimer.current) clearTimeout(addressTimer.current);
|
|
193
|
-
const { name, address } = event.value;
|
|
194
|
-
addressTimer.current = setTimeout(()=>{
|
|
195
|
-
void checkout.updateShippingAddress({
|
|
196
|
-
name,
|
|
197
|
-
address
|
|
198
|
-
}).catch(()=>undefined);
|
|
199
|
-
}, ADDRESS_SETTLE_MS);
|
|
200
|
-
}, [
|
|
201
|
-
checkout
|
|
202
|
-
]);
|
|
181
|
+
// The shipping address is the Shipping Address Element's alone. Stripe
|
|
182
|
+
// reads the mounted element at confirm and keeps the session in step with
|
|
183
|
+
// it, and it REFUSES a confirm (an IntegrationError, which the shopper sees
|
|
184
|
+
// as a failed card) once updateShippingAddress() has also been called while
|
|
185
|
+
// the element is mounted. So nothing here pushes the address itself.
|
|
203
186
|
const commitEmail = useCallback(async ()=>{
|
|
204
187
|
if (!checkout || emailLocked) return true;
|
|
205
188
|
const trimmed = email.trim();
|
|
@@ -345,9 +328,7 @@ function PaymentForm({ payLabel, defaultEmail, onCancel, onRestart, wallets }) {
|
|
|
345
328
|
variant: "subtitle2",
|
|
346
329
|
children: 'Shipping address'
|
|
347
330
|
}),
|
|
348
|
-
/*#__PURE__*/ _jsx(ShippingAddressElement, {
|
|
349
|
-
onChange: onShippingAddressChange
|
|
350
|
-
}),
|
|
331
|
+
/*#__PURE__*/ _jsx(ShippingAddressElement, {}),
|
|
351
332
|
/*#__PURE__*/ _jsx(Typography, {
|
|
352
333
|
variant: "subtitle2",
|
|
353
334
|
children: 'Shipping method'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/storefront-payment-element.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n// The `/checkout` entry, not the main one: react-stripe-js v6 moved the\n// Checkout Sessions provider, its hook and its own `PaymentElement` there, and\n// the main entry's `PaymentElement` is the Elements one, which does not mount\n// under a Checkout provider.\nimport {\n CheckoutElementsProvider,\n PaymentElement,\n ShippingAddressElement,\n useCheckoutElements,\n} from '@stripe/react-stripe-js/checkout'\n// `/pure` deliberately, not the bare entry (AGL-2486). The bare entry ends\n// with a module-scope `Promise.resolve().then(() => getStripePromise())`,\n// so merely EVALUATING it injects the js.stripe.com/v3 script tag —\n// 249 KB gzipped — on any page that reaches this module, whether or not\n// `loadStripe` is ever called. `/pure` is the same API without that\n// statement, so the script is fetched when we ask for it and not before.\nimport { loadStripe } from '@stripe/stripe-js/pure'\n// The TYPE only, and from the bare entry because `/pure` does not re-export\n// it. `import type` is erased entirely at compile time, so this adds no\n// runtime import and cannot re-introduce the script injection above.\nimport type {\n Stripe,\n StripeAddressElementChangeEvent,\n StripeCheckoutContact,\n StripeCheckoutElementsSdkOptions,\n} from '@stripe/stripe-js'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport Radio from '@mui/material/Radio'\nimport RadioGroup from '@mui/material/RadioGroup'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { useTheme } from '@mui/material/styles'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n storefrontPaymentAppearance,\n storefrontPaymentFonts,\n} from './storefront-payment-appearance'\nimport type { StorefrontCheckoutWallets } from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944) — the shopper pays on the\n * merchant's own domain instead of being sent to `checkout.stripe.com`.\n *\n * ## THIS COMPONENT DOES NOT FULFIL ANYTHING\n *\n * It has no success callback, and that absence is the design rather than an\n * omission. `libs/plugins/commerce/src/lib/server/billing-webhook.ts` creates\n * the order on `checkout.session.completed` and is the only thing that ever\n * does. An in-page flow makes trusting the browser far more tempting than a\n * redirect does — the form is right there, `confirm()` resolves in hand, and\n * posting \"done, please fulfil\" is one line away — and the browser is the one\n * participant in a payment that can lie about having paid.\n *\n * It is also the participant that can VANISH. A shopper who confirms and\n * closes the tab never runs a callback, so a flow that fulfils here loses the\n * order outright while keeping the money; a shopper who refreshes the return\n * page runs it twice. Neither is reachable from a design with no callback in\n * it. What happens after a successful confirm is a redirect to `return_url`,\n * carrying the `session_id` the server put there — so the page can SHOW the\n * shopper a result by looking the order up, without being TOLD the outcome by\n * this code.\n *\n * ## Declines and 3DS\n *\n * Both were handled for us by the redirect and now have to be handled here.\n *\n * A decline resolves as `{ type: 'error' }` and is rendered inline WITHOUT\n * unmounting the form: the shopper's basket, address and chosen method are all\n * still on screen and they can try another card. That is the whole difference\n * between a recoverable decline and a dead end, and it is why the error state\n * below sits beside the element rather than replacing it.\n *\n * A 3DS challenge is Stripe's own: `confirm()` presents the challenge and, for\n * redirect-based methods, sends the browser to `return_url` and back. Nothing\n * here has to model it — but the button must stay disabled across the whole\n * await, because a second `confirm()` during a challenge is exactly the\n * double-submit the server's idempotency claim exists to survive and there is\n * no reason to make it lean on that.\n *\n * ## Everything the hosted page collected, collected here (AGL-3606)\n *\n * The hosted page asked for an email, a shipping address and a shipping\n * method, and showed a running total. A `ui_mode: 'elements'` session asks\n * for none of that on its own — the Payment Element is only the payment\n * method — so each is mounted here, read off the SESSION rather than off\n * anything the storefront believes:\n *\n * - **Email.** A session created with `customer_email` (the cart's email\n * field) already has one and Stripe refuses `updateEmail` on it, so it is\n * shown read-only. Otherwise a required field, sent with `updateEmail`\n * before `confirm()` — the receipt and the order's customer both come from\n * it, and a sale without one is an order nobody can be told about.\n * - **Shipping.** Only when the session carries shipping options, which the\n * server attaches only when the store ships to the destination. The\n * Shipping Address Element collects the address (and, under Stripe Tax,\n * is where the tax is computed from); the picker lists the session's own\n * options and selects through `updateShippingOption`.\n * - **Tax address without shipping.** Left to the Payment Element, which\n * collects the country and postal code Stripe Tax needs when the session\n * has `automatic_tax` and no shipping address. A Billing Address Element\n * there would make `updateBillingAddress` conflict with it.\n * - **The total.** Rendered from `session.total`, which Stripe recomputes on\n * every address and option change — tax and shipping included — so the\n * number on the button is the number charged.\n * - **The look.** `elementsOptions.appearance` and `fonts` come from the site\n * theme (`storefront-payment-appearance.ts`), so Stripe's frames wear the\n * merchant's palette, radius and typeface.\n *\n * ## Expired and redirect-returned sessions\n *\n * A session that expired, or that cannot be loaded, offers a fresh one through\n * `onRestart` (a NEW attempt key, so the server does not replay the dead\n * session). A redirect-based method that fails comes back to `return_url`\n * with the session still open; `use-checkout-return-notice.ts` reads that on\n * the return page and says nothing was charged.\n */\n\nexport interface StorefrontPaymentElementProps {\n /** Stripe's instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /**\n * The seller's connected account when the session is a DIRECT charge: the\n * session lives on that account, so Stripe.js has to be opened for it or the\n * client secret will not resolve.\n */\n stripeAccount?: string\n /** Shown on the pay button, so the merchant's own total reads through. */\n payLabel?: string\n /**\n * An email the storefront already knows but did not put on the session\n * (it prefills the field; the shopper can still change it). A session the\n * server created WITH an email shows that one read-only instead.\n */\n defaultEmail?: string\n /** Abandon the in-page form and return to the store. */\n onCancel?: () => void\n /**\n * Open a fresh session after this one expired or could not be loaded. The\n * caller must mint a NEW attempt key first, or the server replays the dead\n * session for the old one.\n */\n onRestart?: () => void\n /**\n * The wallets the merchant hid (AGL-3629). Stripe cannot exclude Apple Pay,\n * Google Pay or Link on the session, so the Payment Element is told instead.\n * Absent means every wallet the device supports shows.\n */\n wallets?: StorefrontCheckoutWallets\n /**\n * An address the shipping fields start with, where the session asks for\n * one: a quote's ship-to (AGL-4094). The shopper can still change it.\n */\n defaultShippingAddress?: StripeCheckoutContact\n}\n\n/**\n * `loadStripe` injects a script tag, so it is memoized per key rather than\n * called per render. Keyed because a page could in principle mount this for\n * two different merchants; in practice it is one, and the map costs nothing.\n */\nconst stripePromises = new Map<string, Promise<Stripe | null>>()\nfunction getStripe(\n publishableKey: string,\n stripeAccount?: string,\n): Promise<Stripe | null> | null {\n if (!publishableKey) return null\n const key = stripeAccount ? `${publishableKey}:${stripeAccount}` : publishableKey\n let promise = stripePromises.get(key)\n if (!promise) {\n promise = stripeAccount\n ? loadStripe(publishableKey, { stripeAccount })\n : loadStripe(publishableKey)\n stripePromises.set(key, promise)\n }\n return promise\n}\n\n/** Test seam: `loadStripe` caches per key across a file's tests otherwise. */\nexport function __resetStripePromises(): void {\n stripePromises.clear()\n}\n\nconst GENERIC_FAILURE = 'That payment could not be completed. Try another card.'\n\n/** How long the address must sit still before the session re-prices on it. */\nconst ADDRESS_SETTLE_MS = 400\n\nfunction SummaryRow({\n label,\n value,\n strong,\n}: {\n label: string\n value: string\n strong?: boolean\n}) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: 2 }}>\n <Typography\n variant={strong ? 'subtitle1' : 'body2'}\n color={strong ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Box>\n )\n}\n\nfunction SessionNotice({\n message,\n onCancel,\n onRestart,\n}: {\n message: string\n onCancel?: () => void\n onRestart?: () => void\n}) {\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n <Box sx={{ display: 'flex', gap: 1 }}>\n {onRestart ? (\n <Button variant=\"contained\" onClick={onRestart}>\n {'Start checkout again'}\n </Button>\n ) : null}\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel}>\n {'Back to the store'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nfunction PaymentForm({\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n}: Pick<\n StorefrontPaymentElementProps,\n 'payLabel' | 'defaultEmail' | 'onCancel' | 'onRestart' | 'wallets'\n>) {\n // A `{ type: 'loading' | 'success' | 'error' }` union since react-stripe-js\n // v6: the session is not usable until Stripe.js has booted against it.\n const checkoutState = useCheckoutElements()\n const checkout =\n checkoutState.type === 'success' ? checkoutState.checkout : null\n const [status, setStatus] = useState<'idle' | 'confirming' | 'error'>('idle')\n const [message, setMessage] = useState('')\n const [email, setEmail] = useState(defaultEmail ?? '')\n const [emailError, setEmailError] = useState('')\n const [shippingBusy, setShippingBusy] = useState(false)\n\n /**\n * The email the SERVER put on the session, latched at first load. Stripe\n * refuses `updateEmail` on such a session, so it is shown, not edited. Read\n * once rather than live because the session's email also becomes set the\n * moment THIS form calls `updateEmail` — which must not turn the field the\n * shopper is typing in into read-only text.\n */\n const serverEmail = useRef<string | null | undefined>(undefined)\n if (checkout && serverEmail.current === undefined) {\n serverEmail.current = checkout.email ? String(checkout.email) : null\n }\n const emailLocked = Boolean(serverEmail.current)\n\n const sessionShippingOptions = checkout?.shippingOptions\n const shippingOptions = useMemo(\n () => sessionShippingOptions ?? [],\n [sessionShippingOptions],\n )\n const collectsShipping = shippingOptions.length > 0\n const selectedShippingId = checkout?.shipping?.shippingOption?.id ?? ''\n\n // The hosted page pre-selects the first rate, so the in-page one does too:\n // a session with options and no selection cannot be confirmed, and making\n // the shopper discover that at the pay button is a decline they did not\n // cause. Once per session — a later deselect is not something Stripe does.\n const autoSelected = useRef(false)\n useEffect(() => {\n if (!checkout || !collectsShipping || selectedShippingId) return\n if (autoSelected.current) return\n autoSelected.current = true\n void checkout.updateShippingOption(shippingOptions[0].id)\n }, [checkout, collectsShipping, selectedShippingId, shippingOptions])\n\n const chooseShipping = useCallback(\n async (id: string) => {\n if (!checkout || id === selectedShippingId) return\n setShippingBusy(true)\n try {\n const result = await checkout.updateShippingOption(id)\n if (result?.type === 'error') {\n setMessage(\n String(result.error?.message ?? '') ||\n 'That shipping option could not be selected.',\n )\n }\n } finally {\n setShippingBusy(false)\n }\n },\n [checkout, selectedShippingId],\n )\n\n // Re-price on the address once it is complete and has stopped changing:\n // the Address Element fires per keystroke, and under Stripe Tax every\n // update is a tax calculation. Confirm sends the element's value anyway, so\n // this exists for the TOTAL — the shopper sees tax before they pay.\n const addressTimer = useRef<ReturnType<typeof setTimeout> | null>(null)\n useEffect(\n () => () => {\n if (addressTimer.current) clearTimeout(addressTimer.current)\n },\n [],\n )\n const onShippingAddressChange = useCallback(\n (event: StripeAddressElementChangeEvent) => {\n if (!checkout || !event.complete) return\n if (addressTimer.current) clearTimeout(addressTimer.current)\n const { name, address } = event.value\n addressTimer.current = setTimeout(() => {\n void checkout\n .updateShippingAddress({ name, address })\n .catch(() => undefined)\n }, ADDRESS_SETTLE_MS)\n },\n [checkout],\n )\n\n const commitEmail = useCallback(async (): Promise<boolean> => {\n if (!checkout || emailLocked) return true\n const trimmed = email.trim()\n if (!trimmed) {\n setEmailError('Enter your email for the receipt.')\n return false\n }\n if (checkout.email === trimmed) return true\n const result = await checkout.updateEmail(trimmed)\n if (result?.type === 'error') {\n setEmailError(\n String(result.error?.message ?? '') || 'Enter a valid email address.',\n )\n return false\n }\n setEmailError('')\n return true\n }, [checkout, email, emailLocked])\n\n const handlePay = useCallback(async () => {\n // Guarded rather than merely disabled: a disabled button is a rendering\n // fact, and a keyboard or a slow re-render can still land a second call\n // during a 3DS challenge.\n if (status === 'confirming' || !checkout) return\n setStatus('confirming')\n setMessage('')\n try {\n if (!(await commitEmail())) {\n setStatus('idle')\n return\n }\n const result = await checkout.confirm()\n if (result?.type === 'error') {\n // A decline, an expired card, an incomplete field, a failed 3DS\n // challenge. Recoverable: the form stays mounted with everything the\n // shopper typed still in it.\n setMessage(String(result.error?.message ?? '') || GENERIC_FAILURE)\n setStatus('error')\n return\n }\n // Success does NOT mean fulfilled, and nothing is reported to our server\n // here. Stripe redirects to the `return_url` the session carries; if it\n // has not by the time this resolves, the confirm is still in flight and\n // the button stays disabled rather than inviting a second attempt.\n } catch {\n // A throw is an integration error on Stripe's side of the contract, not\n // something the shopper did; its text is not written for them.\n setMessage(GENERIC_FAILURE)\n setStatus('error')\n }\n }, [checkout, commitEmail, status])\n\n if (checkoutState.type === 'error') {\n // The session could not be loaded — expired, or already completed in\n // another tab. Nothing typed here could be charged, so say so and offer a\n // fresh session or the way back rather than a form that cannot submit.\n return (\n <SessionNotice\n message=\"This checkout could not be loaded. Start again, or return to the store.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (!checkout) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>\n <CircularProgress size={28} aria-label=\"Loading checkout\" />\n </Box>\n )\n }\n\n if (checkout.status?.type === 'expired') {\n return (\n <SessionNotice\n message=\"This checkout expired before it was paid. Nothing was charged.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (checkout.status?.type === 'complete') {\n // Paid in another tab, or the return redirect is already under way.\n // Offering a restart here would be offering to charge twice.\n return (\n <Alert severity=\"success\" role=\"status\">\n {'This order is already paid.'}\n </Alert>\n )\n }\n\n const total = checkout.total\n const busy = status === 'confirming'\n const discount = total?.discount?.minorUnitsAmount ?? 0\n const tax = total?.taxExclusive?.minorUnitsAmount ?? 0\n const taxPending = checkout.tax?.status && checkout.tax.status !== 'ready'\n\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {emailLocked ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Receipt to ${serverEmail.current}`}\n </Typography>\n ) : (\n <TextField\n type=\"email\"\n label=\"Email\"\n required\n fullWidth\n autoComplete=\"email\"\n value={email}\n onChange={(event) => {\n setEmail(event.target.value)\n if (emailError) setEmailError('')\n }}\n onBlur={() => {\n if (email.trim()) void commitEmail()\n }}\n error={Boolean(emailError)}\n helperText={emailError || 'Your receipt is sent here.'}\n disabled={busy}\n />\n )}\n {collectsShipping ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}\n data-testid=\"storefront-shipping\"\n >\n <Typography variant=\"subtitle2\">{'Shipping address'}</Typography>\n <ShippingAddressElement onChange={onShippingAddressChange} />\n <Typography variant=\"subtitle2\">{'Shipping method'}</Typography>\n <RadioGroup\n aria-label=\"Shipping method\"\n value={selectedShippingId}\n onChange={(event) => void chooseShipping(event.target.value)}\n >\n {shippingOptions.map((option) => (\n <FormControlLabel\n key={option.id}\n value={option.id}\n disabled={busy || shippingBusy}\n control={<Radio />}\n label={`${option.displayName || 'Shipping'} — ${option.amount}`}\n />\n ))}\n </RadioGroup>\n </Box>\n ) : null}\n <PaymentElement options={wallets ? { wallets } : undefined} />\n {total ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}\n data-testid=\"storefront-checkout-total\"\n >\n <SummaryRow label=\"Subtotal\" value={total.subtotal.amount} />\n {discount ? (\n <SummaryRow label=\"Discount\" value={`−${total.discount.amount}`} />\n ) : null}\n {collectsShipping ? (\n <SummaryRow\n label=\"Shipping\"\n value={selectedShippingId ? total.shippingRate.amount : '—'}\n />\n ) : null}\n {tax || taxPending ? (\n <SummaryRow\n label=\"Tax\"\n value={taxPending ? 'Calculated from your address' : total.taxExclusive.amount}\n />\n ) : null}\n <Divider />\n <SummaryRow label=\"Total\" value={total.total.amount} strong />\n </Box>\n ) : null}\n {message ? (\n // `error` severity is right here and wrong for a lockdown pause — this\n // really is \"your payment did not go through\", which is the one thing\n // a shopper must be told plainly.\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1 }}>\n <Button\n variant=\"contained\"\n onClick={handlePay}\n disabled={busy || shippingBusy}\n fullWidth\n >\n {busy ? 'Paying…' : payLabel || 'Pay now'}\n </Button>\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel} disabled={busy}>\n {'Cancel'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nexport function StorefrontPaymentElement({\n clientSecret,\n publishableKey,\n stripeAccount,\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n defaultShippingAddress,\n}: StorefrontPaymentElementProps) {\n const stripe = useMemo(\n () => getStripe(publishableKey, stripeAccount),\n [publishableKey, stripeAccount],\n )\n const theme = useTheme()\n // Built once per session: the provider reads its options at mount and\n // ignores later changes, so a memo keyed on the theme as well would only\n // suggest a re-theme that never happens.\n const options = useMemo<StripeCheckoutElementsSdkOptions>(\n () => ({\n clientSecret,\n elementsOptions: {\n appearance: storefrontPaymentAppearance(theme),\n fonts: storefrontPaymentFonts(\n typeof theme.typography?.fontFamily === 'string'\n ? theme.typography.fontFamily\n : undefined,\n ),\n },\n ...(defaultShippingAddress ? { defaultValues: { shippingAddress: defaultShippingAddress } } : {}),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [clientSecret],\n )\n // Belt and braces with the server's own gate, which already refuses native\n // mode without a publishable key: rendering nothing beats rendering an empty\n // white box that looks like a broken payment form.\n if (!clientSecret || !stripe) return null\n return (\n <CheckoutElementsProvider stripe={stripe} options={options}>\n <Box sx={{ py: 2 }} data-testid=\"storefront-payment-element\">\n <PaymentForm\n payLabel={payLabel}\n defaultEmail={defaultEmail}\n onCancel={onCancel}\n onRestart={onRestart}\n wallets={wallets}\n />\n </Box>\n </CheckoutElementsProvider>\n )\n}\n\n/**\n * Re-exported so the old import path still resolves, but the definition now\n * lives in its own module (AGL-2486): a fallback imported FROM the lazily\n * loaded module drags that module into the eager bundle and cancels the\n * `lazy()`. Callers must import it from `./storefront-payment-element-fallback`\n * — importing it from here is exactly the bug, and re-exporting it does not\n * make that safe.\n */\nexport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\nexport default StorefrontPaymentElement\n"],"names":["CheckoutElementsProvider","PaymentElement","ShippingAddressElement","useCheckoutElements","loadStripe","Alert","Box","Button","CircularProgress","Divider","FormControlLabel","Radio","RadioGroup","TextField","Typography","useTheme","useCallback","useEffect","useMemo","useRef","useState","storefrontPaymentAppearance","storefrontPaymentFonts","stripePromises","Map","getStripe","publishableKey","stripeAccount","key","promise","get","set","__resetStripePromises","clear","GENERIC_FAILURE","ADDRESS_SETTLE_MS","SummaryRow","label","value","strong","sx","display","justifyContent","gap","variant","color","SessionNotice","message","onCancel","onRestart","flexDirection","severity","role","onClick","PaymentForm","payLabel","defaultEmail","wallets","checkout","total","checkoutState","type","status","setStatus","setMessage","email","setEmail","emailError","setEmailError","shippingBusy","setShippingBusy","serverEmail","undefined","current","String","emailLocked","Boolean","sessionShippingOptions","shippingOptions","collectsShipping","length","selectedShippingId","shipping","shippingOption","id","autoSelected","updateShippingOption","chooseShipping","result","error","addressTimer","clearTimeout","onShippingAddressChange","event","complete","name","address","setTimeout","updateShippingAddress","catch","commitEmail","trimmed","trim","updateEmail","handlePay","confirm","py","size","aria-label","busy","discount","minorUnitsAmount","tax","taxExclusive","taxPending","required","fullWidth","autoComplete","onChange","target","onBlur","helperText","disabled","data-testid","map","option","control","displayName","amount","options","subtotal","shippingRate","StorefrontPaymentElement","clientSecret","defaultShippingAddress","stripe","theme","elementsOptions","appearance","fonts","typography","fontFamily","defaultValues","shippingAddress","StorefrontPaymentElementFallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,wEAAwE;AACxE,+EAA+E;AAC/E,8EAA8E;AAC9E,6BAA6B;AAC7B,SACEA,wBAAwB,EACxBC,cAAc,EACdC,sBAAsB,EACtBC,mBAAmB,QACd,mCAAkC;AACzC,2EAA2E;AAC3E,0EAA0E;AAC1E,oEAAoE;AACpE,wEAAwE;AACxE,oEAAoE;AACpE,yEAAyE;AACzE,SAASC,UAAU,QAAQ,yBAAwB;AAUnD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,sBAAsB,iCAAgC;AAC7D,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AU,qBAAhBJ,kBAAkBK,UAAU,MAAK,WACpCL,MAAMI,UAAU,CAACC,UAAU,GAC3BrE;YAER;WACI8D,yBAAyB;YAAEQ,eAAe;gBAAEC,iBAAiBT;YAAuB;QAAE,IAAI,CAAC;OAEjG,uDAAuD;IACvD;QAACD;KAAa;IAEhB,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,IAAI,CAACA,gBAAgB,CAACE,QAAQ,OAAO;IACrC,qBACE,KAACvI;QAAyBuI,QAAQA;QAAQN,SAASA;kBACjD,cAAA,KAAC3H;YAAIkC,IAAI;gBAAEkE,IAAI;YAAE;YAAGiB,eAAY;sBAC9B,cAAA,KAACrE;gBACCC,UAAUA;gBACVC,cAAcA;gBACdR,UAAUA;gBACVC,WAAWA;gBACXQ,SAASA;;;;AAKnB;AAEA;;;;;;;CAOC,GACD,SAASuF,gCAAgC,QAAQ,2CAAuC;AAExF,eAAeZ,yBAAwB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/storefront-payment-element.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n// The `/checkout` entry, not the main one: react-stripe-js v6 moved the\n// Checkout Sessions provider, its hook and its own `PaymentElement` there, and\n// the main entry's `PaymentElement` is the Elements one, which does not mount\n// under a Checkout provider.\nimport {\n CheckoutElementsProvider,\n PaymentElement,\n ShippingAddressElement,\n useCheckoutElements,\n} from '@stripe/react-stripe-js/checkout'\n// `/pure` deliberately, not the bare entry (AGL-2486). The bare entry ends\n// with a module-scope `Promise.resolve().then(() => getStripePromise())`,\n// so merely EVALUATING it injects the js.stripe.com/v3 script tag —\n// 249 KB gzipped — on any page that reaches this module, whether or not\n// `loadStripe` is ever called. `/pure` is the same API without that\n// statement, so the script is fetched when we ask for it and not before.\nimport { loadStripe } from '@stripe/stripe-js/pure'\n// The TYPE only, and from the bare entry because `/pure` does not re-export\n// it. `import type` is erased entirely at compile time, so this adds no\n// runtime import and cannot re-introduce the script injection above.\nimport type {\n Stripe,\n StripeCheckoutContact,\n StripeCheckoutElementsSdkOptions,\n} from '@stripe/stripe-js'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport FormControlLabel from '@mui/material/FormControlLabel'\nimport Radio from '@mui/material/Radio'\nimport RadioGroup from '@mui/material/RadioGroup'\nimport TextField from '@mui/material/TextField'\nimport Typography from '@mui/material/Typography'\nimport { useTheme } from '@mui/material/styles'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n storefrontPaymentAppearance,\n storefrontPaymentFonts,\n} from './storefront-payment-appearance'\nimport type { StorefrontCheckoutWallets } from '../model/commerce-payment-methods'\n\n/**\n * The storefront Payment Element (AGL-1944) — the shopper pays on the\n * merchant's own domain instead of being sent to `checkout.stripe.com`.\n *\n * ## THIS COMPONENT DOES NOT FULFIL ANYTHING\n *\n * It has no success callback, and that absence is the design rather than an\n * omission. `libs/plugins/commerce/src/lib/server/billing-webhook.ts` creates\n * the order on `checkout.session.completed` and is the only thing that ever\n * does. An in-page flow makes trusting the browser far more tempting than a\n * redirect does — the form is right there, `confirm()` resolves in hand, and\n * posting \"done, please fulfil\" is one line away — and the browser is the one\n * participant in a payment that can lie about having paid.\n *\n * It is also the participant that can VANISH. A shopper who confirms and\n * closes the tab never runs a callback, so a flow that fulfils here loses the\n * order outright while keeping the money; a shopper who refreshes the return\n * page runs it twice. Neither is reachable from a design with no callback in\n * it. What happens after a successful confirm is a redirect to `return_url`,\n * carrying the `session_id` the server put there — so the page can SHOW the\n * shopper a result by looking the order up, without being TOLD the outcome by\n * this code.\n *\n * ## Declines and 3DS\n *\n * Both were handled for us by the redirect and now have to be handled here.\n *\n * A decline resolves as `{ type: 'error' }` and is rendered inline WITHOUT\n * unmounting the form: the shopper's basket, address and chosen method are all\n * still on screen and they can try another card. That is the whole difference\n * between a recoverable decline and a dead end, and it is why the error state\n * below sits beside the element rather than replacing it.\n *\n * A 3DS challenge is Stripe's own: `confirm()` presents the challenge and, for\n * redirect-based methods, sends the browser to `return_url` and back. Nothing\n * here has to model it — but the button must stay disabled across the whole\n * await, because a second `confirm()` during a challenge is exactly the\n * double-submit the server's idempotency claim exists to survive and there is\n * no reason to make it lean on that.\n *\n * ## Everything the hosted page collected, collected here (AGL-3606)\n *\n * The hosted page asked for an email, a shipping address and a shipping\n * method, and showed a running total. A `ui_mode: 'elements'` session asks\n * for none of that on its own — the Payment Element is only the payment\n * method — so each is mounted here, read off the SESSION rather than off\n * anything the storefront believes:\n *\n * - **Email.** A session created with `customer_email` (the cart's email\n * field) already has one and Stripe refuses `updateEmail` on it, so it is\n * shown read-only. Otherwise a required field, sent with `updateEmail`\n * before `confirm()` — the receipt and the order's customer both come from\n * it, and a sale without one is an order nobody can be told about.\n * - **Shipping.** Only when the session carries shipping options, which the\n * server attaches only when the store ships to the destination. The\n * Shipping Address Element collects the address (and, under Stripe Tax,\n * is where the tax is computed from); the picker lists the session's own\n * options and selects through `updateShippingOption`.\n * - **Tax address without shipping.** Left to the Payment Element, which\n * collects the country and postal code Stripe Tax needs when the session\n * has `automatic_tax` and no shipping address. A Billing Address Element\n * there would make `updateBillingAddress` conflict with it.\n * - **The total.** Rendered from `session.total`, which Stripe recomputes on\n * every address and option change — tax and shipping included — so the\n * number on the button is the number charged.\n * - **The look.** `elementsOptions.appearance` and `fonts` come from the site\n * theme (`storefront-payment-appearance.ts`), so Stripe's frames wear the\n * merchant's palette, radius and typeface.\n *\n * ## Expired and redirect-returned sessions\n *\n * A session that expired, or that cannot be loaded, offers a fresh one through\n * `onRestart` (a NEW attempt key, so the server does not replay the dead\n * session). A redirect-based method that fails comes back to `return_url`\n * with the session still open; `use-checkout-return-notice.ts` reads that on\n * the return page and says nothing was charged.\n */\n\nexport interface StorefrontPaymentElementProps {\n /** Stripe's instruction to the browser. Not a claim that money moved. */\n clientSecret: string\n publishableKey: string\n /**\n * The seller's connected account when the session is a DIRECT charge: the\n * session lives on that account, so Stripe.js has to be opened for it or the\n * client secret will not resolve.\n */\n stripeAccount?: string\n /** Shown on the pay button, so the merchant's own total reads through. */\n payLabel?: string\n /**\n * An email the storefront already knows but did not put on the session\n * (it prefills the field; the shopper can still change it). A session the\n * server created WITH an email shows that one read-only instead.\n */\n defaultEmail?: string\n /** Abandon the in-page form and return to the store. */\n onCancel?: () => void\n /**\n * Open a fresh session after this one expired or could not be loaded. The\n * caller must mint a NEW attempt key first, or the server replays the dead\n * session for the old one.\n */\n onRestart?: () => void\n /**\n * The wallets the merchant hid (AGL-3629). Stripe cannot exclude Apple Pay,\n * Google Pay or Link on the session, so the Payment Element is told instead.\n * Absent means every wallet the device supports shows.\n */\n wallets?: StorefrontCheckoutWallets\n /**\n * An address the shipping fields start with, where the session asks for\n * one: a quote's ship-to (AGL-4094). The shopper can still change it.\n */\n defaultShippingAddress?: StripeCheckoutContact\n}\n\n/**\n * `loadStripe` injects a script tag, so it is memoized per key rather than\n * called per render. Keyed because a page could in principle mount this for\n * two different merchants; in practice it is one, and the map costs nothing.\n */\nconst stripePromises = new Map<string, Promise<Stripe | null>>()\nfunction getStripe(\n publishableKey: string,\n stripeAccount?: string,\n): Promise<Stripe | null> | null {\n if (!publishableKey) return null\n const key = stripeAccount ? `${publishableKey}:${stripeAccount}` : publishableKey\n let promise = stripePromises.get(key)\n if (!promise) {\n promise = stripeAccount\n ? loadStripe(publishableKey, { stripeAccount })\n : loadStripe(publishableKey)\n stripePromises.set(key, promise)\n }\n return promise\n}\n\n/** Test seam: `loadStripe` caches per key across a file's tests otherwise. */\nexport function __resetStripePromises(): void {\n stripePromises.clear()\n}\n\nconst GENERIC_FAILURE = 'That payment could not be completed. Try another card.'\n\nfunction SummaryRow({\n label,\n value,\n strong,\n}: {\n label: string\n value: string\n strong?: boolean\n}) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'space-between', gap: 2 }}>\n <Typography\n variant={strong ? 'subtitle1' : 'body2'}\n color={strong ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Box>\n )\n}\n\nfunction SessionNotice({\n message,\n onCancel,\n onRestart,\n}: {\n message: string\n onCancel?: () => void\n onRestart?: () => void\n}) {\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n <Box sx={{ display: 'flex', gap: 1 }}>\n {onRestart ? (\n <Button variant=\"contained\" onClick={onRestart}>\n {'Start checkout again'}\n </Button>\n ) : null}\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel}>\n {'Back to the store'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nfunction PaymentForm({\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n}: Pick<\n StorefrontPaymentElementProps,\n 'payLabel' | 'defaultEmail' | 'onCancel' | 'onRestart' | 'wallets'\n>) {\n // A `{ type: 'loading' | 'success' | 'error' }` union since react-stripe-js\n // v6: the session is not usable until Stripe.js has booted against it.\n const checkoutState = useCheckoutElements()\n const checkout =\n checkoutState.type === 'success' ? checkoutState.checkout : null\n const [status, setStatus] = useState<'idle' | 'confirming' | 'error'>('idle')\n const [message, setMessage] = useState('')\n const [email, setEmail] = useState(defaultEmail ?? '')\n const [emailError, setEmailError] = useState('')\n const [shippingBusy, setShippingBusy] = useState(false)\n\n /**\n * The email the SERVER put on the session, latched at first load. Stripe\n * refuses `updateEmail` on such a session, so it is shown, not edited. Read\n * once rather than live because the session's email also becomes set the\n * moment THIS form calls `updateEmail` — which must not turn the field the\n * shopper is typing in into read-only text.\n */\n const serverEmail = useRef<string | null | undefined>(undefined)\n if (checkout && serverEmail.current === undefined) {\n serverEmail.current = checkout.email ? String(checkout.email) : null\n }\n const emailLocked = Boolean(serverEmail.current)\n\n const sessionShippingOptions = checkout?.shippingOptions\n const shippingOptions = useMemo(\n () => sessionShippingOptions ?? [],\n [sessionShippingOptions],\n )\n const collectsShipping = shippingOptions.length > 0\n const selectedShippingId = checkout?.shipping?.shippingOption?.id ?? ''\n\n // The hosted page pre-selects the first rate, so the in-page one does too:\n // a session with options and no selection cannot be confirmed, and making\n // the shopper discover that at the pay button is a decline they did not\n // cause. Once per session — a later deselect is not something Stripe does.\n const autoSelected = useRef(false)\n useEffect(() => {\n if (!checkout || !collectsShipping || selectedShippingId) return\n if (autoSelected.current) return\n autoSelected.current = true\n void checkout.updateShippingOption(shippingOptions[0].id)\n }, [checkout, collectsShipping, selectedShippingId, shippingOptions])\n\n const chooseShipping = useCallback(\n async (id: string) => {\n if (!checkout || id === selectedShippingId) return\n setShippingBusy(true)\n try {\n const result = await checkout.updateShippingOption(id)\n if (result?.type === 'error') {\n setMessage(\n String(result.error?.message ?? '') ||\n 'That shipping option could not be selected.',\n )\n }\n } finally {\n setShippingBusy(false)\n }\n },\n [checkout, selectedShippingId],\n )\n\n // The shipping address is the Shipping Address Element's alone. Stripe\n // reads the mounted element at confirm and keeps the session in step with\n // it, and it REFUSES a confirm (an IntegrationError, which the shopper sees\n // as a failed card) once updateShippingAddress() has also been called while\n // the element is mounted. So nothing here pushes the address itself.\n\n const commitEmail = useCallback(async (): Promise<boolean> => {\n if (!checkout || emailLocked) return true\n const trimmed = email.trim()\n if (!trimmed) {\n setEmailError('Enter your email for the receipt.')\n return false\n }\n if (checkout.email === trimmed) return true\n const result = await checkout.updateEmail(trimmed)\n if (result?.type === 'error') {\n setEmailError(\n String(result.error?.message ?? '') || 'Enter a valid email address.',\n )\n return false\n }\n setEmailError('')\n return true\n }, [checkout, email, emailLocked])\n\n const handlePay = useCallback(async () => {\n // Guarded rather than merely disabled: a disabled button is a rendering\n // fact, and a keyboard or a slow re-render can still land a second call\n // during a 3DS challenge.\n if (status === 'confirming' || !checkout) return\n setStatus('confirming')\n setMessage('')\n try {\n if (!(await commitEmail())) {\n setStatus('idle')\n return\n }\n const result = await checkout.confirm()\n if (result?.type === 'error') {\n // A decline, an expired card, an incomplete field, a failed 3DS\n // challenge. Recoverable: the form stays mounted with everything the\n // shopper typed still in it.\n setMessage(String(result.error?.message ?? '') || GENERIC_FAILURE)\n setStatus('error')\n return\n }\n // Success does NOT mean fulfilled, and nothing is reported to our server\n // here. Stripe redirects to the `return_url` the session carries; if it\n // has not by the time this resolves, the confirm is still in flight and\n // the button stays disabled rather than inviting a second attempt.\n } catch {\n // A throw is an integration error on Stripe's side of the contract, not\n // something the shopper did; its text is not written for them.\n setMessage(GENERIC_FAILURE)\n setStatus('error')\n }\n }, [checkout, commitEmail, status])\n\n if (checkoutState.type === 'error') {\n // The session could not be loaded — expired, or already completed in\n // another tab. Nothing typed here could be charged, so say so and offer a\n // fresh session or the way back rather than a form that cannot submit.\n return (\n <SessionNotice\n message=\"This checkout could not be loaded. Start again, or return to the store.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (!checkout) {\n return (\n <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>\n <CircularProgress size={28} aria-label=\"Loading checkout\" />\n </Box>\n )\n }\n\n if (checkout.status?.type === 'expired') {\n return (\n <SessionNotice\n message=\"This checkout expired before it was paid. Nothing was charged.\"\n onCancel={onCancel}\n onRestart={onRestart}\n />\n )\n }\n\n if (checkout.status?.type === 'complete') {\n // Paid in another tab, or the return redirect is already under way.\n // Offering a restart here would be offering to charge twice.\n return (\n <Alert severity=\"success\" role=\"status\">\n {'This order is already paid.'}\n </Alert>\n )\n }\n\n const total = checkout.total\n const busy = status === 'confirming'\n const discount = total?.discount?.minorUnitsAmount ?? 0\n const tax = total?.taxExclusive?.minorUnitsAmount ?? 0\n const taxPending = checkout.tax?.status && checkout.tax.status !== 'ready'\n\n return (\n <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n {emailLocked ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Receipt to ${serverEmail.current}`}\n </Typography>\n ) : (\n <TextField\n type=\"email\"\n label=\"Email\"\n required\n fullWidth\n autoComplete=\"email\"\n value={email}\n onChange={(event) => {\n setEmail(event.target.value)\n if (emailError) setEmailError('')\n }}\n onBlur={() => {\n if (email.trim()) void commitEmail()\n }}\n error={Boolean(emailError)}\n helperText={emailError || 'Your receipt is sent here.'}\n disabled={busy}\n />\n )}\n {collectsShipping ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}\n data-testid=\"storefront-shipping\"\n >\n <Typography variant=\"subtitle2\">{'Shipping address'}</Typography>\n <ShippingAddressElement />\n <Typography variant=\"subtitle2\">{'Shipping method'}</Typography>\n <RadioGroup\n aria-label=\"Shipping method\"\n value={selectedShippingId}\n onChange={(event) => void chooseShipping(event.target.value)}\n >\n {shippingOptions.map((option) => (\n <FormControlLabel\n key={option.id}\n value={option.id}\n disabled={busy || shippingBusy}\n control={<Radio />}\n label={`${option.displayName || 'Shipping'} — ${option.amount}`}\n />\n ))}\n </RadioGroup>\n </Box>\n ) : null}\n <PaymentElement options={wallets ? { wallets } : undefined} />\n {total ? (\n <Box\n sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}\n data-testid=\"storefront-checkout-total\"\n >\n <SummaryRow label=\"Subtotal\" value={total.subtotal.amount} />\n {discount ? (\n <SummaryRow label=\"Discount\" value={`−${total.discount.amount}`} />\n ) : null}\n {collectsShipping ? (\n <SummaryRow\n label=\"Shipping\"\n value={selectedShippingId ? total.shippingRate.amount : '—'}\n />\n ) : null}\n {tax || taxPending ? (\n <SummaryRow\n label=\"Tax\"\n value={taxPending ? 'Calculated from your address' : total.taxExclusive.amount}\n />\n ) : null}\n <Divider />\n <SummaryRow label=\"Total\" value={total.total.amount} strong />\n </Box>\n ) : null}\n {message ? (\n // `error` severity is right here and wrong for a lockdown pause — this\n // really is \"your payment did not go through\", which is the one thing\n // a shopper must be told plainly.\n <Alert severity=\"error\" role=\"alert\">\n {message}\n </Alert>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1 }}>\n <Button\n variant=\"contained\"\n onClick={handlePay}\n disabled={busy || shippingBusy}\n fullWidth\n >\n {busy ? 'Paying…' : payLabel || 'Pay now'}\n </Button>\n {onCancel ? (\n <Button variant=\"text\" onClick={onCancel} disabled={busy}>\n {'Cancel'}\n </Button>\n ) : null}\n </Box>\n </Box>\n )\n}\n\nexport function StorefrontPaymentElement({\n clientSecret,\n publishableKey,\n stripeAccount,\n payLabel,\n defaultEmail,\n onCancel,\n onRestart,\n wallets,\n defaultShippingAddress,\n}: StorefrontPaymentElementProps) {\n const stripe = useMemo(\n () => getStripe(publishableKey, stripeAccount),\n [publishableKey, stripeAccount],\n )\n const theme = useTheme()\n // Built once per session: the provider reads its options at mount and\n // ignores later changes, so a memo keyed on the theme as well would only\n // suggest a re-theme that never happens.\n const options = useMemo<StripeCheckoutElementsSdkOptions>(\n () => ({\n clientSecret,\n elementsOptions: {\n appearance: storefrontPaymentAppearance(theme),\n fonts: storefrontPaymentFonts(\n typeof theme.typography?.fontFamily === 'string'\n ? theme.typography.fontFamily\n : undefined,\n ),\n },\n ...(defaultShippingAddress ? { defaultValues: { shippingAddress: defaultShippingAddress } } : {}),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [clientSecret],\n )\n // Belt and braces with the server's own gate, which already refuses native\n // mode without a publishable key: rendering nothing beats rendering an empty\n // white box that looks like a broken payment form.\n if (!clientSecret || !stripe) return null\n return (\n <CheckoutElementsProvider stripe={stripe} options={options}>\n <Box sx={{ py: 2 }} data-testid=\"storefront-payment-element\">\n <PaymentForm\n payLabel={payLabel}\n defaultEmail={defaultEmail}\n onCancel={onCancel}\n onRestart={onRestart}\n wallets={wallets}\n />\n </Box>\n </CheckoutElementsProvider>\n )\n}\n\n/**\n * Re-exported so the old import path still resolves, but the definition now\n * lives in its own module (AGL-2486): a fallback imported FROM the lazily\n * loaded module drags that module into the eager bundle and cancels the\n * `lazy()`. Callers must import it from `./storefront-payment-element-fallback`\n * — importing it from here is exactly the bug, and re-exporting it does not\n * make that safe.\n */\nexport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\nexport default StorefrontPaymentElement\n"],"names":["CheckoutElementsProvider","PaymentElement","ShippingAddressElement","useCheckoutElements","loadStripe","Alert","Box","Button","CircularProgress","Divider","FormControlLabel","Radio","RadioGroup","TextField","Typography","useTheme","useCallback","useEffect","useMemo","useRef","useState","storefrontPaymentAppearance","storefrontPaymentFonts","stripePromises","Map","getStripe","publishableKey","stripeAccount","key","promise","get","set","__resetStripePromises","clear","GENERIC_FAILURE","SummaryRow","label","value","strong","sx","display","justifyContent","gap","variant","color","SessionNotice","message","onCancel","onRestart","flexDirection","severity","role","onClick","PaymentForm","payLabel","defaultEmail","wallets","checkout","total","checkoutState","type","status","setStatus","setMessage","email","setEmail","emailError","setEmailError","shippingBusy","setShippingBusy","serverEmail","undefined","current","String","emailLocked","Boolean","sessionShippingOptions","shippingOptions","collectsShipping","length","selectedShippingId","shipping","shippingOption","id","autoSelected","updateShippingOption","chooseShipping","result","error","commitEmail","trimmed","trim","updateEmail","handlePay","confirm","py","size","aria-label","busy","discount","minorUnitsAmount","tax","taxExclusive","taxPending","required","fullWidth","autoComplete","onChange","event","target","onBlur","helperText","disabled","data-testid","map","option","control","displayName","amount","options","subtotal","shippingRate","StorefrontPaymentElement","clientSecret","defaultShippingAddress","stripe","theme","elementsOptions","appearance","fonts","typography","fontFamily","defaultValues","shippingAddress","StorefrontPaymentElementFallback"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,wEAA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D;QAACD;KAAa;IAEhB,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,IAAI,CAACA,gBAAgB,CAACE,QAAQ,OAAO;IACrC,qBACE,KAAC7H;QAAyB6H,QAAQA;QAAQN,SAASA;kBACjD,cAAA,KAACjH;YAAIiC,IAAI;gBAAEwD,IAAI;YAAE;YAAGkB,eAAY;sBAC9B,cAAA,KAAC5D;gBACCC,UAAUA;gBACVC,cAAcA;gBACdR,UAAUA;gBACVC,WAAWA;gBACXQ,SAASA;;;;AAKnB;AAEA;;;;;;;CAOC,GACD,SAAS8E,gCAAgC,QAAQ,2CAAuC;AAExF,eAAeZ,yBAAwB"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { readConfiguredPublicBytes } from '@aglyn/tenant-data-admin';
|
|
18
|
+
import { addMediaToLibrary } from '@aglyn/tenant-data-admin/server/media-ingest';
|
|
19
|
+
import type { WooRequestContext } from './woo-context';
|
|
20
|
+
/** The largest picture fetched; a larger one is left out. */
|
|
21
|
+
export declare const WOO_IMAGE_MAX_BYTES: number;
|
|
22
|
+
/** How long one picture's host has to answer. */
|
|
23
|
+
export declare const WOO_IMAGE_TIMEOUT_MS = 15000;
|
|
24
|
+
/** Pictures copied for one write; WooCommerce sets no limit, a request must. */
|
|
25
|
+
export declare const WOO_IMAGES_PER_WRITE = 20;
|
|
26
|
+
/** The key a source address is remembered under. */
|
|
27
|
+
export declare function wooImageKey(src: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* The store's own address for `src` when it is already one: a page-relative
|
|
30
|
+
* library address, or an absolute one on the store's own origin (an app
|
|
31
|
+
* sends back the `src` it was given). `null` for anyone else's address.
|
|
32
|
+
*/
|
|
33
|
+
export declare function storeOwnImage(src: string, origin: string): string | null;
|
|
34
|
+
/** A file name for the copy, from the product's name and the source's type. */
|
|
35
|
+
export declare function wooImageFileName(productName: string, index: number, contentType: string): string;
|
|
36
|
+
export interface WooImageDeps {
|
|
37
|
+
fetchBytes?: typeof readConfiguredPublicBytes;
|
|
38
|
+
addMedia?: typeof addMediaToLibrary;
|
|
39
|
+
readCopies?: () => Promise<Record<string, {
|
|
40
|
+
src: string;
|
|
41
|
+
address: string;
|
|
42
|
+
atMs: number;
|
|
43
|
+
}>>;
|
|
44
|
+
writeCopies?: (copies: Record<string, {
|
|
45
|
+
src: string;
|
|
46
|
+
address: string;
|
|
47
|
+
atMs: number;
|
|
48
|
+
}>) => Promise<void>;
|
|
49
|
+
now?: () => number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Each source address the write names, as the store's own address: a copy
|
|
53
|
+
* in the site's library, or `null` when it could not be made. Answers in the
|
|
54
|
+
* order given.
|
|
55
|
+
*/
|
|
56
|
+
export declare function copyWooImages(ctx: Pick<WooRequestContext, 'hostId' | 'origin' | 'api' | 'grantId'>, productName: string, sources: readonly string[], deps?: WooImageDeps): Promise<Map<string, string | null>>;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ /*==========================================
|
|
17
|
+
* AN APP'S PRODUCT IMAGES, COPIED INTO THE SITE'S LIBRARY.
|
|
18
|
+
*
|
|
19
|
+
* WooCommerce downloads every image a product write names by `src` into the
|
|
20
|
+
* store's own media library, and so does this. A picture left on the app's
|
|
21
|
+
* host would not show: such hosts refuse other sites' pages (Tapstitch's
|
|
22
|
+
* answers 403 to any page that is not its own), and a published page loads
|
|
23
|
+
* pictures from the site's own addresses anyway.
|
|
24
|
+
*
|
|
25
|
+
* Each address is fetched once, under the outbound rules every configured
|
|
26
|
+
* address follows (https, a public server, no redirect, a size cap), and
|
|
27
|
+
* added to the site's own library by `addMediaToLibrary`, with every check an
|
|
28
|
+
* upload has. The copy is remembered by its source address, so an app that
|
|
29
|
+
* sends the same pictures on every update adds no second copy. An address
|
|
30
|
+
* already the store's own is kept as it is. A picture that cannot be fetched
|
|
31
|
+
* or is not one is left out, as WooCommerce leaves out an image it cannot
|
|
32
|
+
* sideload; the product is written without it.
|
|
33
|
+
*=========================================*/ import { firebaseAdmin, readConfiguredPublicBytes } from "@aglyn/tenant-data-admin";
|
|
34
|
+
import { addMediaToLibrary, isMediaIngestRefusal } from "@aglyn/tenant-data-admin/server/media-ingest";
|
|
35
|
+
import { createHash } from "node:crypto";
|
|
36
|
+
/** The largest picture fetched; a larger one is left out. */ export const WOO_IMAGE_MAX_BYTES = 20 * 1024 * 1024;
|
|
37
|
+
/** How long one picture's host has to answer. */ export const WOO_IMAGE_TIMEOUT_MS = 15000;
|
|
38
|
+
/** Pictures copied for one write; WooCommerce sets no limit, a request must. */ export const WOO_IMAGES_PER_WRITE = 20;
|
|
39
|
+
/** Remembered copies per store; the oldest go first. */ const REMEMBERED_MAX = 2000;
|
|
40
|
+
const IMAGE_TYPES = new Set([
|
|
41
|
+
'image/png',
|
|
42
|
+
'image/jpeg',
|
|
43
|
+
'image/webp',
|
|
44
|
+
'image/gif'
|
|
45
|
+
]);
|
|
46
|
+
/** Where the store keeps the copies it made, by source address. */ const copiesDoc = (ctx)=>firebaseAdmin.app().firestore().collection('hosts').doc(ctx.hostId).collection('wooMeta').doc('images');
|
|
47
|
+
/** The key a source address is remembered under. */ export function wooImageKey(src) {
|
|
48
|
+
return createHash('sha256').update(src).digest('hex').slice(0, 32);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The store's own address for `src` when it is already one: a page-relative
|
|
52
|
+
* library address, or an absolute one on the store's own origin (an app
|
|
53
|
+
* sends back the `src` it was given). `null` for anyone else's address.
|
|
54
|
+
*/ export function storeOwnImage(src, origin) {
|
|
55
|
+
if (src.startsWith('/') && !src.startsWith('//')) return src;
|
|
56
|
+
try {
|
|
57
|
+
const url = new URL(src);
|
|
58
|
+
if (url.origin === new URL(origin).origin) return `${url.pathname}${url.search}`;
|
|
59
|
+
if (url.hostname === 'firebasestorage.googleapis.com') return src;
|
|
60
|
+
} catch (unused) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
/** A file name for the copy, from the product's name and the source's type. */ export function wooImageFileName(productName, index, contentType) {
|
|
66
|
+
const base = productName.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'product';
|
|
67
|
+
const extension = contentType === 'image/jpeg' ? 'jpg' : contentType.split('/')[1] || 'img';
|
|
68
|
+
return `${base}-${index + 1}.${extension}`;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Each source address the write names, as the store's own address: a copy
|
|
72
|
+
* in the site's library, or `null` when it could not be made. Answers in the
|
|
73
|
+
* order given.
|
|
74
|
+
*/ export async function copyWooImages(ctx, productName, sources, deps = {}) {
|
|
75
|
+
var _deps_fetchBytes, _deps_addMedia, _deps_now, _deps_readCopies, _deps_writeCopies;
|
|
76
|
+
const fetchBytes = (_deps_fetchBytes = deps.fetchBytes) != null ? _deps_fetchBytes : readConfiguredPublicBytes;
|
|
77
|
+
const addMedia = (_deps_addMedia = deps.addMedia) != null ? _deps_addMedia : addMediaToLibrary;
|
|
78
|
+
const now = (_deps_now = deps.now) != null ? _deps_now : Date.now;
|
|
79
|
+
const readCopies = (_deps_readCopies = deps.readCopies) != null ? _deps_readCopies : async ()=>{
|
|
80
|
+
var _ref;
|
|
81
|
+
var _data;
|
|
82
|
+
return (_ref = (_data = (await copiesDoc(ctx).get()).data()) == null ? void 0 : _data['copies']) != null ? _ref : {};
|
|
83
|
+
};
|
|
84
|
+
const writeCopies = (_deps_writeCopies = deps.writeCopies) != null ? _deps_writeCopies : async (copies)=>void await copiesDoc(ctx).set({
|
|
85
|
+
copies
|
|
86
|
+
});
|
|
87
|
+
const answers = new Map();
|
|
88
|
+
const wanted = [
|
|
89
|
+
...new Set(sources)
|
|
90
|
+
];
|
|
91
|
+
const outside = wanted.filter((src)=>{
|
|
92
|
+
const own = storeOwnImage(src, ctx.origin);
|
|
93
|
+
if (own) answers.set(src, own);
|
|
94
|
+
return !own;
|
|
95
|
+
});
|
|
96
|
+
if (!outside.length) return answers;
|
|
97
|
+
const copies = await readCopies().catch(()=>({}));
|
|
98
|
+
let added = false;
|
|
99
|
+
let copied = 0;
|
|
100
|
+
for (const [index, src] of outside.entries()){
|
|
101
|
+
const key = wooImageKey(src);
|
|
102
|
+
const known = copies[key];
|
|
103
|
+
if ((known == null ? void 0 : known.src) === src && known.address) {
|
|
104
|
+
answers.set(src, known.address);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (copied >= WOO_IMAGES_PER_WRITE) {
|
|
108
|
+
answers.set(src, null);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
copied += 1;
|
|
112
|
+
const address = await copyOne(ctx, productName, index, src, fetchBytes, addMedia);
|
|
113
|
+
answers.set(src, address);
|
|
114
|
+
if (address) {
|
|
115
|
+
copies[key] = {
|
|
116
|
+
src,
|
|
117
|
+
address,
|
|
118
|
+
atMs: now()
|
|
119
|
+
};
|
|
120
|
+
added = true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (added) {
|
|
124
|
+
const kept = Object.entries(copies).sort(([, a], [, b])=>b.atMs - a.atMs).slice(0, REMEMBERED_MAX);
|
|
125
|
+
await writeCopies(Object.fromEntries(kept)).catch(()=>undefined);
|
|
126
|
+
}
|
|
127
|
+
return answers;
|
|
128
|
+
}
|
|
129
|
+
async function copyOne(ctx, productName, index, src, fetchBytes, addMedia) {
|
|
130
|
+
var _read_bytes;
|
|
131
|
+
let read;
|
|
132
|
+
try {
|
|
133
|
+
read = await fetchBytes(src, {
|
|
134
|
+
method: 'GET',
|
|
135
|
+
signal: AbortSignal.timeout(WOO_IMAGE_TIMEOUT_MS)
|
|
136
|
+
}, {
|
|
137
|
+
maxBytes: WOO_IMAGE_MAX_BYTES
|
|
138
|
+
});
|
|
139
|
+
} catch (unused) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
if (!('status' in read) || read.status < 200 || read.status >= 300 || !((_read_bytes = read.bytes) == null ? void 0 : _read_bytes.length)) return null;
|
|
143
|
+
if (!IMAGE_TYPES.has(read.contentType)) return null;
|
|
144
|
+
const scopeRef = ctx.api.firestore.collection('hosts').doc(ctx.hostId);
|
|
145
|
+
const result = await addMedia({
|
|
146
|
+
firestore: ctx.api.firestore,
|
|
147
|
+
org: ctx.api.org,
|
|
148
|
+
orgId: ctx.api.orgId,
|
|
149
|
+
scope: {
|
|
150
|
+
collection: 'hosts',
|
|
151
|
+
base: `hosts/${ctx.hostId}`,
|
|
152
|
+
hostId: ctx.hostId,
|
|
153
|
+
cdnScope: ctx.hostId
|
|
154
|
+
},
|
|
155
|
+
scopeRef,
|
|
156
|
+
bytes: read.bytes,
|
|
157
|
+
contentType: read.contentType,
|
|
158
|
+
fileName: wooImageFileName(productName, index, read.contentType),
|
|
159
|
+
alt: productName.slice(0, 500) || null,
|
|
160
|
+
uploadedBy: `woo:${ctx.grantId}`
|
|
161
|
+
}).catch(()=>null);
|
|
162
|
+
if (!result || isMediaIngestRefusal(result)) return null;
|
|
163
|
+
return result.cdnPath || result.url || null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
//# sourceMappingURL=woo-images.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-images.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * AN APP'S PRODUCT IMAGES, COPIED INTO THE SITE'S LIBRARY.\n *\n * WooCommerce downloads every image a product write names by `src` into the\n * store's own media library, and so does this. A picture left on the app's\n * host would not show: such hosts refuse other sites' pages (Tapstitch's\n * answers 403 to any page that is not its own), and a published page loads\n * pictures from the site's own addresses anyway.\n *\n * Each address is fetched once, under the outbound rules every configured\n * address follows (https, a public server, no redirect, a size cap), and\n * added to the site's own library by `addMediaToLibrary`, with every check an\n * upload has. The copy is remembered by its source address, so an app that\n * sends the same pictures on every update adds no second copy. An address\n * already the store's own is kept as it is. A picture that cannot be fetched\n * or is not one is left out, as WooCommerce leaves out an image it cannot\n * sideload; the product is written without it.\n *=========================================*/\n\nimport { firebaseAdmin, readConfiguredPublicBytes } from '@aglyn/tenant-data-admin'\nimport { addMediaToLibrary, isMediaIngestRefusal } from '@aglyn/tenant-data-admin/server/media-ingest'\nimport { createHash } from 'node:crypto'\nimport type { WooRequestContext } from './woo-context'\n\n/** The largest picture fetched; a larger one is left out. */\nexport const WOO_IMAGE_MAX_BYTES = 20 * 1024 * 1024\n\n/** How long one picture's host has to answer. */\nexport const WOO_IMAGE_TIMEOUT_MS = 15_000\n\n/** Pictures copied for one write; WooCommerce sets no limit, a request must. */\nexport const WOO_IMAGES_PER_WRITE = 20\n\n/** Remembered copies per store; the oldest go first. */\nconst REMEMBERED_MAX = 2_000\n\nconst IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])\n\n/** Where the store keeps the copies it made, by source address. */\nconst copiesDoc = (ctx: Pick<WooRequestContext, 'hostId'>) =>\n firebaseAdmin.app().firestore().collection('hosts').doc(ctx.hostId).collection('wooMeta').doc('images')\n\n/** The key a source address is remembered under. */\nexport function wooImageKey(src: string): string {\n return createHash('sha256').update(src).digest('hex').slice(0, 32)\n}\n\n/**\n * The store's own address for `src` when it is already one: a page-relative\n * library address, or an absolute one on the store's own origin (an app\n * sends back the `src` it was given). `null` for anyone else's address.\n */\nexport function storeOwnImage(src: string, origin: string): string | null {\n if (src.startsWith('/') && !src.startsWith('//')) return src\n try {\n const url = new URL(src)\n if (url.origin === new URL(origin).origin) return `${url.pathname}${url.search}`\n if (url.hostname === 'firebasestorage.googleapis.com') return src\n } catch {\n return null\n }\n return null\n}\n\n/** A file name for the copy, from the product's name and the source's type. */\nexport function wooImageFileName(productName: string, index: number, contentType: string): string {\n const base = productName.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'product'\n const extension = contentType === 'image/jpeg' ? 'jpg' : contentType.split('/')[1] || 'img'\n return `${base}-${index + 1}.${extension}`\n}\n\nexport interface WooImageDeps {\n fetchBytes?: typeof readConfiguredPublicBytes\n addMedia?: typeof addMediaToLibrary\n readCopies?: () => Promise<Record<string, { src: string; address: string; atMs: number }>>\n writeCopies?: (copies: Record<string, { src: string; address: string; atMs: number }>) => Promise<void>\n now?: () => number\n}\n\n/**\n * Each source address the write names, as the store's own address: a copy\n * in the site's library, or `null` when it could not be made. Answers in the\n * order given.\n */\nexport async function copyWooImages(\n ctx: Pick<WooRequestContext, 'hostId' | 'origin' | 'api' | 'grantId'>,\n productName: string,\n sources: readonly string[],\n deps: WooImageDeps = {},\n): Promise<Map<string, string | null>> {\n const fetchBytes = deps.fetchBytes ?? readConfiguredPublicBytes\n const addMedia = deps.addMedia ?? addMediaToLibrary\n const now = deps.now ?? Date.now\n const readCopies =\n deps.readCopies ?? (async () => ((await copiesDoc(ctx).get()).data()?.['copies'] ?? {}) as Record<string, { src: string; address: string; atMs: number }>)\n const writeCopies = deps.writeCopies ?? (async (copies) => void (await copiesDoc(ctx).set({ copies })))\n const answers = new Map<string, string | null>()\n const wanted = [...new Set(sources)]\n const outside = wanted.filter((src) => {\n const own = storeOwnImage(src, ctx.origin)\n if (own) answers.set(src, own)\n return !own\n })\n if (!outside.length) return answers\n const copies = await readCopies().catch(() => ({}) as Record<string, { src: string; address: string; atMs: number }>)\n let added = false\n let copied = 0\n for (const [index, src] of outside.entries()) {\n const key = wooImageKey(src)\n const known = copies[key]\n if (known?.src === src && known.address) {\n answers.set(src, known.address)\n continue\n }\n if (copied >= WOO_IMAGES_PER_WRITE) {\n answers.set(src, null)\n continue\n }\n copied += 1\n const address = await copyOne(ctx, productName, index, src, fetchBytes, addMedia)\n answers.set(src, address)\n if (address) {\n copies[key] = { src, address, atMs: now() }\n added = true\n }\n }\n if (added) {\n const kept = Object.entries(copies)\n .sort(([, a], [, b]) => b.atMs - a.atMs)\n .slice(0, REMEMBERED_MAX)\n await writeCopies(Object.fromEntries(kept)).catch(() => undefined)\n }\n return answers\n}\n\nasync function copyOne(\n ctx: Pick<WooRequestContext, 'hostId' | 'api' | 'grantId'>,\n productName: string,\n index: number,\n src: string,\n fetchBytes: typeof readConfiguredPublicBytes,\n addMedia: typeof addMediaToLibrary,\n): Promise<string | null> {\n let read: Awaited<ReturnType<typeof readConfiguredPublicBytes>>\n try {\n read = await fetchBytes(src, { method: 'GET', signal: AbortSignal.timeout(WOO_IMAGE_TIMEOUT_MS) }, { maxBytes: WOO_IMAGE_MAX_BYTES })\n } catch {\n return null\n }\n if (!('status' in read) || read.status < 200 || read.status >= 300 || !read.bytes?.length) return null\n if (!IMAGE_TYPES.has(read.contentType)) return null\n const scopeRef = ctx.api.firestore.collection('hosts').doc(ctx.hostId)\n const result = await addMedia({\n firestore: ctx.api.firestore,\n org: ctx.api.org,\n orgId: ctx.api.orgId,\n scope: { collection: 'hosts', base: `hosts/${ctx.hostId}`, hostId: ctx.hostId, cdnScope: ctx.hostId },\n scopeRef,\n bytes: read.bytes,\n contentType: read.contentType,\n fileName: wooImageFileName(productName, index, read.contentType),\n alt: productName.slice(0, 500) || null,\n uploadedBy: `woo:${ctx.grantId}`,\n }).catch(() => null)\n if (!result || isMediaIngestRefusal(result)) return null\n return result.cdnPath || result.url || null\n}\n"],"names":["firebaseAdmin","readConfiguredPublicBytes","addMediaToLibrary","isMediaIngestRefusal","createHash","WOO_IMAGE_MAX_BYTES","WOO_IMAGE_TIMEOUT_MS","WOO_IMAGES_PER_WRITE","REMEMBERED_MAX","IMAGE_TYPES","Set","copiesDoc","ctx","app","firestore","collection","doc","hostId","wooImageKey","src","update","digest","slice","storeOwnImage","origin","startsWith","url","URL","pathname","search","hostname","wooImageFileName","productName","index","contentType","base","replace","extension","split","copyWooImages","sources","deps","fetchBytes","addMedia","now","Date","readCopies","get","data","writeCopies","copies","set","answers","Map","wanted","outside","filter","own","length","catch","added","copied","entries","key","known","address","copyOne","atMs","kept","Object","sort","a","b","fromEntries","undefined","read","method","signal","AbortSignal","timeout","maxBytes","status","bytes","has","scopeRef","api","result","org","orgId","scope","cdnScope","fileName","alt","uploadedBy","grantId","cdnPath"],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E,eAAM;QACN,OAAO;IACT;IACA,IAAI,CAAE,CAAA,YAAYsE,IAAG,KAAMA,KAAKM,MAAM,GAAG,OAAON,KAAKM,MAAM,IAAI,OAAO,GAACN,cAAAA,KAAKO,KAAK,qBAAVP,YAAYjB,MAAM,GAAE,OAAO;IAClG,IAAI,CAACjD,YAAY0E,GAAG,CAACR,KAAKzC,WAAW,GAAG,OAAO;IAC/C,MAAMkD,WAAWxE,IAAIyE,GAAG,CAACvE,SAAS,CAACC,UAAU,CAAC,SAASC,GAAG,CAACJ,IAAIK,MAAM;IACrE,MAAMqE,SAAS,MAAM3C,SAAS;QAC5B7B,WAAWF,IAAIyE,GAAG,CAACvE,SAAS;QAC5ByE,KAAK3E,IAAIyE,GAAG,CAACE,GAAG;QAChBC,OAAO5E,IAAIyE,GAAG,CAACG,KAAK;QACpBC,OAAO;YAAE1E,YAAY;YAASoB,MAAM,CAAC,MAAM,EAAEvB,IAAIK,MAAM,EAAE;YAAEA,QAAQL,IAAIK,MAAM;YAAEyE,UAAU9E,IAAIK,MAAM;QAAC;QACpGmE;QACAF,OAAOP,KAAKO,KAAK;QACjBhD,aAAayC,KAAKzC,WAAW;QAC7ByD,UAAU5D,iBAAiBC,aAAaC,OAAO0C,KAAKzC,WAAW;QAC/D0D,KAAK5D,YAAYV,KAAK,CAAC,GAAG,QAAQ;QAClCuE,YAAY,CAAC,IAAI,EAAEjF,IAAIkF,OAAO,EAAE;IAClC,GAAGnC,KAAK,CAAC,IAAM;IACf,IAAI,CAAC2B,UAAUnF,qBAAqBmF,SAAS,OAAO;IACpD,OAAOA,OAAOS,OAAO,IAAIT,OAAO5D,GAAG,IAAI;AACzC"}
|
|
@@ -32,6 +32,7 @@ import { variantComboKey } from "../../model/product-write.js";
|
|
|
32
32
|
import { createProduct, deleteProductOverApi, updateProduct, updateProductVariant } from "../api-v1/product-writes.js";
|
|
33
33
|
import { jsonRequest, readAnswer } from "./woo-context.js";
|
|
34
34
|
import { wooIdsFor, wooIdTarget } from "./woo-ids.js";
|
|
35
|
+
import { copyWooImages } from "./woo-images.js";
|
|
35
36
|
import { mergeMeta, metaList, readProductMeta, readProductMetas, writeProductMeta } from "./woo-meta.js";
|
|
36
37
|
import { imagesFromWoo, optionsWithVariation, productWriteFromWoo, readWooPage, variantWriteFromWoo, variationOptionsFromWoo, wooError, wooImageId, wooInvalidId, wooNotFound, wooPaged, wooProduct, wooRefusalFrom, wooVariation } from "./woo-shapes.js";
|
|
37
38
|
const productsOf = (ctx)=>ctx.api.firestore.collection('hosts').doc(ctx.hostId).collection('products');
|
|
@@ -215,8 +216,19 @@ async function hostDoc(ctx) {
|
|
|
215
216
|
var _ctx_api_site;
|
|
216
217
|
return (_ref = (_ctx_api_site = ctx.api.site) == null ? void 0 : _ctx_api_site.snapshot) != null ? _ref : await ctx.api.firestore.collection('hosts').doc(ctx.hostId).get();
|
|
217
218
|
}
|
|
219
|
+
/**
|
|
220
|
+
* A write's `mediaUrls` as the store's own addresses: each picture an app
|
|
221
|
+
* named by its address, copied into the site's library (`woo-images.ts`).
|
|
222
|
+
*/ async function withLibraryImages(ctx, values, productName) {
|
|
223
|
+
if (!Array.isArray(values['mediaUrls'])) return;
|
|
224
|
+
const sources = values['mediaUrls'].map(String);
|
|
225
|
+
const copies = await copyWooImages(ctx, productName, sources);
|
|
226
|
+
values['mediaUrls'] = [
|
|
227
|
+
...new Set(sources.map((src)=>copies.get(src)).filter((src)=>Boolean(src)))
|
|
228
|
+
];
|
|
229
|
+
}
|
|
218
230
|
/** Create one product from a WooCommerce body; answers its id or a refusal. */ async function createOne(ctx, body) {
|
|
219
|
-
var _ref;
|
|
231
|
+
var _values_name, _ref;
|
|
220
232
|
var _answer_body;
|
|
221
233
|
const parsed = productWriteFromWoo(body, true);
|
|
222
234
|
if ('error' in parsed) return {
|
|
@@ -230,6 +242,7 @@ async function hostDoc(ctx) {
|
|
|
230
242
|
options: {}
|
|
231
243
|
}, parsed.simpleVariant)
|
|
232
244
|
];
|
|
245
|
+
await withLibraryImages(ctx, values, String((_values_name = values['name']) != null ? _values_name : ''));
|
|
233
246
|
const answer = await run(createProduct(jsonRequest('POST', values), ctx.api, ctx.hostId));
|
|
234
247
|
if (answer.status >= 400) return {
|
|
235
248
|
refusal: wooRefusalFrom(answer)
|
|
@@ -259,6 +272,11 @@ async function hostDoc(ctx) {
|
|
|
259
272
|
}, parsed.simpleVariant)
|
|
260
273
|
];
|
|
261
274
|
}
|
|
275
|
+
if (Array.isArray(values['mediaUrls'])) {
|
|
276
|
+
var _ref, _values_name;
|
|
277
|
+
const stored = await reread(ctx, productId);
|
|
278
|
+
await withLibraryImages(ctx, values, String((_ref = (_values_name = values['name']) != null ? _values_name : stored == null ? void 0 : stored['name']) != null ? _ref : ''));
|
|
279
|
+
}
|
|
262
280
|
if (Object.keys(values).length) {
|
|
263
281
|
const answer = await run(updateProduct(jsonRequest('PATCH', values), ctx.api, ctx.hostId, productId));
|
|
264
282
|
if (answer.status >= 400) return wooRefusalFrom(answer);
|
|
@@ -363,7 +381,7 @@ async function batchProducts(ctx) {
|
|
|
363
381
|
* missing option value, one for every variant's fields. Answers, per write,
|
|
364
382
|
* the variant id it landed on, or a refusal.
|
|
365
383
|
*/ async function applyVariations(ctx, productId, writes) {
|
|
366
|
-
var _ref;
|
|
384
|
+
var _ref, _current_name;
|
|
367
385
|
const stored = await reread(ctx, productId);
|
|
368
386
|
if (!stored) return {
|
|
369
387
|
refusal: wooInvalidId('product')
|
|
@@ -421,8 +439,9 @@ async function batchProducts(ctx) {
|
|
|
421
439
|
});
|
|
422
440
|
});
|
|
423
441
|
const media = Array.isArray(current['mediaUrls']) ? current['mediaUrls'] : [];
|
|
442
|
+
const copies = images.length ? await copyWooImages(ctx, String((_current_name = current['name']) != null ? _current_name : ''), images) : new Map();
|
|
424
443
|
const newImages = [
|
|
425
|
-
...new Set(images)
|
|
444
|
+
...new Set(images.map((src)=>copies.get(src)).filter((src)=>Boolean(src)))
|
|
426
445
|
].filter((src)=>!media.includes(src));
|
|
427
446
|
if (variantWrites.length || newImages.length) {
|
|
428
447
|
const body = {};
|