@ecomweb/storefront-kit 0.14.0 → 0.15.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/README.md +25 -1
- package/bin/check-client-bundle-lib.d.mts +16 -0
- package/bin/check-client-bundle-lib.mjs +58 -0
- package/bin/check-client-bundle.d.mts +11 -0
- package/bin/check-client-bundle.mjs +8 -0
- package/dist/api/client.js +39 -0
- package/dist/api/client.js.map +1 -1
- package/dist/api/index.js.map +1 -1
- package/dist/api/proxy-guard.js +29 -0
- package/dist/api/proxy-guard.js.map +1 -0
- package/dist/api/proxy-routes.js +126 -0
- package/dist/api/proxy-routes.js.map +1 -0
- package/dist/api/proxy.js +17 -4
- package/dist/api/proxy.js.map +1 -1
- package/dist/api/response.js.map +1 -1
- package/dist/api/server-sdk.js +41 -0
- package/dist/api/server-sdk.js.map +1 -0
- package/dist/api/store-preview-header.js.map +1 -1
- package/dist/auth/context.js.map +1 -1
- package/dist/auth/sdk.js +15 -5
- package/dist/auth/sdk.js.map +1 -1
- package/dist/auth/session-refresh.js +7 -4
- package/dist/auth/session-refresh.js.map +1 -1
- package/dist/cart/api.js.map +1 -1
- package/dist/cart/server-context.js.map +1 -1
- package/dist/checkout/get-payment-state.js +4 -8
- package/dist/checkout/get-payment-state.js.map +1 -1
- package/dist/checkout/initiate-gateway-payment.js +5 -7
- package/dist/checkout/initiate-gateway-payment.js.map +1 -1
- package/dist/checkout/order-handoff.js.map +1 -1
- package/dist/checkout/payment-redirect.js.map +1 -1
- package/dist/checkout/use-checkout.js.map +1 -1
- package/dist/client-info.js +1 -1
- package/dist/config/public.js +2 -0
- package/dist/config/public.js.map +1 -1
- package/dist/config/schema.js +16 -4
- package/dist/config/schema.js.map +1 -1
- package/dist/config/secret-guard.js +20 -0
- package/dist/config/secret-guard.js.map +1 -0
- package/dist/config/server.js +15 -8
- package/dist/config/server.js.map +1 -1
- package/dist/config/version-check.js.map +1 -1
- package/dist/config.d.ts +22 -4
- package/dist/config.js +2 -0
- package/dist/config.js.map +1 -1
- package/dist/currency.js.map +1 -1
- package/dist/index.d.ts +331 -69
- package/dist/index.js.map +1 -1
- package/dist/logging.js.map +1 -1
- package/dist/middleware/create-storefront-middleware.js +14 -3
- package/dist/middleware/create-storefront-middleware.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/middleware.js.map +1 -1
- package/dist/{mode-Lm9t4qzX.d.ts → mode-oVZCQxrc.d.ts} +1 -1
- package/dist/orders/api-client.js +3 -3
- package/dist/orders/api-client.js.map +1 -1
- package/dist/orders/bank-transfer.js +1 -1
- package/dist/orders/bank-transfer.js.map +1 -1
- package/dist/orders/shipment-tracking.js.map +1 -1
- package/dist/orders/use-order-status.js +2 -2
- package/dist/orders/use-order-status.js.map +1 -1
- package/dist/promotions/use-promotion-validation.js +2 -2
- package/dist/promotions/use-promotion-validation.js.map +1 -1
- package/dist/provider.js.map +1 -1
- package/dist/request/served-store.js +5 -0
- package/dist/request/served-store.js.map +1 -0
- package/dist/{schema-Dg0ZflMW.d.ts → schema-B3nAYiwT.d.ts} +5 -1
- package/dist/sdk.js +3 -3
- package/dist/sdk.js.map +1 -1
- package/dist/server/routes.js +16 -9
- package/dist/server/routes.js.map +1 -1
- package/dist/server.d.ts +46 -5
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/shipping/location-areas.js.map +1 -1
- package/dist/shipping/use-shipping-calculation.js +2 -2
- package/dist/shipping/use-shipping-calculation.js.map +1 -1
- package/dist/storage.js.map +1 -1
- package/dist/store/store-context.js.map +1 -1
- package/dist/store-scope/index.js.map +1 -1
- package/dist/stores/basic-settings.js.map +1 -1
- package/dist/stores/cached.js.map +1 -1
- package/dist/theme/define.js.map +1 -1
- package/dist/theme/index.js.map +1 -1
- package/dist/theme/settings-context.js.map +1 -1
- package/dist/theme/style.js.map +1 -1
- package/dist/theme.d.ts +33 -0
- package/package.json +6 -2
- package/dist/api/server-client.js +0 -162
- package/dist/api/server-client.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /storefront/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * What the thank-you page shows of the order (contact, address, methods,\n * lines, money), built by the storefront when it places the order. Like the\n * rest of the handoff it stays in the shopper's own browser.\n */\nexport interface OrderHandoffSummary {\n customer_name: string;\n phone: string;\n email: string | null;\n /** The delivery address as one display line. */\n address: string;\n shipping_method: string | null;\n shipping_fee: number | null;\n payment_label: string;\n items: {\n name: string;\n variant: string | null;\n quantity: number;\n /** Unit price. */\n price: number;\n image: string | null;\n }[];\n subtotal: number;\n discount: number;\n}\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n /** Absent for gateway returns and older handoffs. */\n summary?: OrderHandoffSummary | null;\n written_at: number;\n}\n\nfunction isSummary(value: unknown): value is OrderHandoffSummary {\n if (!value || typeof value !== \"object\") return false;\n const s = value as Record<string, unknown>;\n return (\n typeof s.customer_name === \"string\" &&\n typeof s.address === \"string\" &&\n typeof s.payment_label === \"string\" &&\n typeof s.subtotal === \"number\" &&\n Array.isArray(s.items) &&\n s.items.every(\n item =>\n !!item &&\n typeof item === \"object\" &&\n typeof (item as Record<string, unknown>).name === \"string\" &&\n typeof (item as Record<string, unknown>).quantity === \"number\" &&\n typeof (item as Record<string, unknown>).price === \"number\"\n )\n );\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(\n order_code: string | null\n): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code)\n return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n summary: isSummary(h.summary) ? h.summary : null,\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {\n // Nothing to do; a stale entry expires on its own.\n }\n}\n"],"mappings":"AAoBA,MAAM,cAAc;AAGpB,MAAM,aAAa,KAAK,KAAK,KAAK;AAyClC,SAAS,UAAU,OAA8C;AAC/D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SACE,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,YAAY,YACrB,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,aAAa,YACtB,MAAM,QAAQ,EAAE,KAAK,KACrB,EAAE,MAAM;AAAA,IACN,UACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,OAAQ,KAAiC,SAAS,YAClD,OAAQ,KAAiC,aAAa,YACtD,OAAQ,KAAiC,UAAU;AAAA,EACvD;AAEJ;AAEO,SAAS,kBACd,SACM;AACN,MAAI;AACF,WAAO,aAAa;AAAA,MAClB;AAAA,MACA,KAAK,UAAU,EAAE,GAAG,SAAS,YAAY,KAAK,IAAI,EAAE,CAAC;AAAA,IACvD;AAAA,EACF,QAAQ;AAAA,EAIR;AACF;AAOO,SAAS,iBACd,YACqB;AACrB,MAAI,CAAC,WAAY,QAAO;AACxB,MAAI,MAAqB;AACzB,MAAI;AACF,UAAM,OAAO,aAAa,QAAQ,WAAW;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,IAAK,QAAO;AAEjB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,aAAa,QAAQ,YAAY,KAAK,IAAI,CAAC;AACpD;AAMO,SAAS,aACd,QACA,YACA,KACqB;AACrB,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,IAAI;AAEV,MAAI,OAAO,EAAE,eAAe,YAAY,EAAE,eAAe;AACvD,WAAO;AACT,MAAI,OAAO,EAAE,mBAAmB,YAAY,EAAE,eAAe,WAAW,GAAG;AACzE,WAAO;AAAA,EACT;AACA,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,SAAS,EAAE,KAAK,EAAG,QAAO;AACrE,MAAI,OAAO,EAAE,eAAe,YAAY,MAAM,EAAE,aAAa,YAAY;AACvE,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,YAAY,EAAE;AAAA,IACd,gBAAgB,EAAE;AAAA,IAClB,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,OAAO,EAAE;AAAA,IACT,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,SAAS,UAAU,EAAE,OAAO,IAAI,EAAE,UAAU;AAAA,IAC5C,YAAY,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,oBAA0B;AACxC,MAAI;AACF,WAAO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/checkout/payment-redirect.ts"],"sourcesContent":["/**\n * Decides whether a just-placed checkout should send the shopper to a\n * payment gateway, or leave today's inline \"order placed\" success flow\n * untouched.\n *\n * Deliberately pure: no network call, no `window` access. The page\n * component (`checkout-page-client.tsx`) performs the actual redirect once\n * this function tells it to.\n */\n\n/**\n * The pinned `@ecomweb/sdk` version's `StorePaymentMethod` type does not yet\n * declare `provider_code` (see `lib/checkout/initiate-gateway-payment.ts` for\n * the full story — the SDK PR that adds it is not merged, and this repo's\n * lockfile pins an older commit). The backend already returns the field on\n * `GET /
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/payment-redirect.ts"],"sourcesContent":["/**\n * Decides whether a just-placed checkout should send the shopper to a\n * payment gateway, or leave today's inline \"order placed\" success flow\n * untouched.\n *\n * Deliberately pure: no network call, no `window` access. The page\n * component (`checkout-page-client.tsx`) performs the actual redirect once\n * this function tells it to.\n */\n\n/**\n * The pinned `@ecomweb/sdk` version's `StorePaymentMethod` type does not yet\n * declare `provider_code` (see `lib/checkout/initiate-gateway-payment.ts` for\n * the full story — the SDK PR that adds it is not merged, and this repo's\n * lockfile pins an older commit). The backend already returns the field on\n * `GET /storefront/stores/:storeRef/payment-methods` today, so this function is\n * typed against only the one field it actually needs rather than the SDK's\n * (currently stale) full type, and the call site casts to this shape.\n */\nexport interface PaymentMethodWithProviderCode {\n provider_code?: string | null;\n}\n\nexport interface PaymentRedirectIntent {\n readonly provider_code: string;\n readonly order_code: string;\n}\n\n/**\n * A payment method with a non-null `provider_code` is gateway-backed\n * (OnePay, MoMo, ...) and the shopper must be sent to the provider to pay.\n * A method without one (`cod`, `bank_transfer`) is settled offline — the\n * existing inline success screen is correct for it and this returns `null`.\n *\n * The returned intent carries `order_code`, never an order id: the\n * `payments/initiate` endpoint is keyed on it deliberately, because the\n * storefront API key authenticates the store rather than the shopper and a\n * raw sequential id would let a caller enumerate a store's orders.\n */\nexport function getPaymentRedirectIntent(\n method: PaymentMethodWithProviderCode | null | undefined,\n order_code: string\n): PaymentRedirectIntent | null {\n const provider_code = method?.provider_code;\n if (!provider_code) {\n return null;\n }\n\n return { provider_code, order_code };\n}\n"],"mappings":"AAuCO,SAAS,yBACd,QACA,YAC8B;AAC9B,QAAM,gBAAgB,QAAQ;AAC9B,MAAI,CAAC,eAAe;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,eAAe,WAAW;AACrC;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n // The API applies a discount-code promotion only when the code itself\n // comes with its id; older APIs ignore the field.\n promotion_code: promotionState.appliedPromotion?.code || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way. PROMOTION_IDENTITY_REQUIRED keeps the code: the\n // shopper only has to add an email and place again.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,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S,YAAY;AAEnB,cAAQ,MAAM,6CAA6C,UAAU;AACrE,aAAO,EAAE,MAAM,mBAAmB,WAAW,cAAc,WAAW;AAAA,IACxE,UAAE;AACA,4BAAsB,KAAK;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,eAAe,UAAU,CAAC;AAEhC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,MACR,KAAK,cAAc;AAAA,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA;AAAA,MAEjC,YAAY,cAAc;AAAA,MAC1B,kBAAkB,cAAc;AAAA,MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n *\n * Must run under {@link StorefrontKitProvider}, which supplies the store, auth\n * and cart it reads.\n *\n * @param options - The address codes shipping is quoted for, and optional\n * carrier quotes and gateway navigation ({@link UseCheckoutOptions}).\n * @returns The cart `items`, `paymentMethods`, `shipping`, `promotion` and\n * `totals` state, `stockIssues`, and `placeOrder` with the payment redirect\n * helpers.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useCheckout } from \"@ecomweb/storefront-kit\";\n *\n * export function PlaceOrderButton({ province, ward, form }) {\n * const checkout = useCheckout({ province, ward });\n * return (\n * <button\n * disabled={checkout.isSubmitting}\n * onClick={() => checkout.placeOrder(form)}\n * >\n * Pay {checkout.totals.total}\n * </button>\n * );\n * }\n * ```\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n // The API applies a discount-code promotion only when the code itself\n // comes with its id; older APIs ignore the field.\n promotion_code: promotionState.appliedPromotion?.code || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way. PROMOTION_IDENTITY_REQUIRED keeps the code: the\n // shopper only has to add an email and place again.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,S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,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
package/dist/client-info.js
CHANGED
package/dist/config/public.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolveMode } from "./mode.js";
|
|
2
|
+
import { assertNoSecretInPublicEnv } from "./secret-guard.js";
|
|
2
3
|
import {
|
|
3
4
|
envValue,
|
|
4
5
|
logLevelOf,
|
|
@@ -84,6 +85,7 @@ function parseSingle(env) {
|
|
|
84
85
|
);
|
|
85
86
|
}
|
|
86
87
|
function parsePublicConfig(env) {
|
|
88
|
+
assertNoSecretInPublicEnv(env);
|
|
87
89
|
return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
|
|
88
90
|
}
|
|
89
91
|
let cached;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\n// Production serves the API under /api/v1 (Kong strips the prefix) and stored\n// assets at the origin's /storage/v1.\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app/api/v1\";\n\n/** Stored assets live at the API host's /storage/v1, whatever path the API has. */\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url; // the schema reports the invalid API URL\n }\n}\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? originOf(apiUrl)\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,\n // both\n NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS:\n process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS,\n NEXT_PUBLIC_LOG_LEVEL: process.env.NEXT_PUBLIC_LOG_LEVEL,\n NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE:\n process.env.NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE,\n }));\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,MAAM,oBAA4C;AAAA,EAChD,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,sBAAsB;AAAA,EACtB,gBAAgB;AAClB;AAGA,MAAM,qBAA6C;AAAA,EACjD,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,QAAQ;AAAA,EACR,QAAQ;AACV;AAIA,MAAM,yBAAyB;AAG/B,SAAS,SAAS,KAAqB;AACrC,MAAI;AACF,WAAO,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,gBAAgB;AAAA,MAChB,UAAU,WAAW,SAAS,KAAK,uBAAuB,CAAC;AAAA,MAC3D,qBAAqB;AAAA,QACnB,SAAS,KAAK,oCAAoC;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAGG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAMO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,0BAA0B,QAAQ,IAAI;AAAA,IACtC,cACE,OAAO,WAAW,cAAc,QAAQ,IAAI,eAAe;AAAA;AAAA,IAE7D,qBAAqB,QAAQ,IAAI;AAAA,IACjC,4BAA4B,QAAQ,IAAI;AAAA,IACxC,qBAAqB,QAAQ,IAAI;AAAA,IACjC,8BAA8B,QAAQ,IAAI;AAAA,IAC1C,oCACE,QAAQ,IAAI;AAAA,IACd,0BAA0B,QAAQ,IAAI;AAAA,IACtC,8BAA8B,QAAQ,IAAI;AAAA;AAAA,IAE1C,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,qCACE,QAAQ,IAAI;AAAA,IACd,6BAA6B,QAAQ,IAAI;AAAA,IACzC,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,sBAAsB,QAAQ,IAAI;AAAA;AAAA,IAElC,0CACE,QAAQ,IAAI;AAAA,IACd,uBAAuB,QAAQ,IAAI;AAAA,IACnC,oCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/config/public.ts"],"sourcesContent":["import { resolveMode } from \"./mode\";\nimport { assertNoSecretInPublicEnv } from \"./secret-guard\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n publicConfigSchema,\n sampleRateOf,\n type EnvSource,\n type PublicConfig,\n} from \"./schema\";\n\nconst MULTI_ENV_NAME_OF: Record<string, string> = {\n apiUrl: \"NEXT_PUBLIC_API_URL\",\n storefrontApiKey: \"NEXT_PUBLIC_PLATFORM_API_KEY\",\n appUrl: \"NEXT_PUBLIC_APP_URL\",\n platformDomainSuffix: \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\",\n primaryMenuRef: \"NEXT_PUBLIC_PRIMARY_MENU_REF\",\n};\n\n/** next.config.mjs derives these NEXT_PUBLIC_ names from ECOMWEB_* / SITE_URL. */\nconst SINGLE_ENV_NAME_OF: Record<string, string> = {\n storeRef: \"ECOMWEB_STORE_REF\",\n storefrontApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n apiUrl: \"ECOMWEB_API_URL\",\n appUrl: \"SITE_URL\",\n};\n\n// Production serves the API under /api/v1 (Kong strips the prefix) and stored\n// assets at the origin's /storage/v1.\nconst DEFAULT_SINGLE_API_URL = \"https://apibase.ecomweb.app/api/v1\";\n\n/** Stored assets live at the API host's /storage/v1, whatever path the API has. */\nfunction originOf(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return url; // the schema reports the invalid API URL\n }\n}\n\nfunction parseMulti(env: EnvSource): PublicConfig {\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"multi\",\n storeRef: null,\n apiUrl: envValue(env, \"NEXT_PUBLIC_API_URL\")?.replace(/\\/$/, \"\"),\n assetBaseUrl: (envValue(env, \"NEXT_PUBLIC_ASSET_BASE_URL\") ?? \"\").replace(\n /\\/$/,\n \"\"\n ),\n appUrl: envValue(env, \"NEXT_PUBLIC_APP_URL\") ?? \"https://ecomweb.app\",\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n platformDomainSuffix:\n envValue(env, \"NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX\") ?? \"ecomsite.app\",\n appBaseUrlFlag: envValue(env, \"NEXT_PUBLIC_APP_BASE_URL\"),\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef:\n envValue(env, \"NEXT_PUBLIC_PRIMARY_MENU_REF\") ?? \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n MULTI_ENV_NAME_OF\n );\n}\n\nfunction parseSingle(env: EnvSource): PublicConfig {\n const apiUrl = (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_API_URL\") ?? DEFAULT_SINGLE_API_URL\n ).replace(/\\/$/, \"\");\n return parseOrThrow(\n publicConfigSchema,\n {\n mode: \"single\",\n storeRef: envValue(env, \"NEXT_PUBLIC_ECOMWEB_STORE_REF\"),\n apiUrl,\n assetBaseUrl: (\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_ASSET_URL\") ?? originOf(apiUrl)\n ).replace(/\\/$/, \"\"),\n appUrl: envValue(env, \"NEXT_PUBLIC_SITE_URL\")?.replace(/\\/$/, \"\"),\n storefrontApiKey: envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n platformDomainSuffix: null,\n appBaseUrlFlag: undefined,\n imageTransformationsFlag: envValue(\n env,\n \"NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS\"\n ),\n primaryMenuRef: \"main-menu\",\n logLevel: logLevelOf(envValue(env, \"NEXT_PUBLIC_LOG_LEVEL\")),\n webVitalsSampleRate: sampleRateOf(\n envValue(env, \"NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE\"),\n 0.1\n ),\n },\n SINGLE_ENV_NAME_OF\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parsePublicConfig(env: EnvSource): PublicConfig {\n assertNoSecretInPublicEnv(env);\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: PublicConfig | undefined;\n\n/** Specs that stub env per test call this in beforeEach. */\nexport function resetPublicConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * Every NEXT_PUBLIC_ var is spelled out literally: Next inlines only literal\n * `process.env.NEXT_PUBLIC_X` reads into client bundles.\n */\nexport function publicConfig(): PublicConfig {\n return (cached ??= parsePublicConfig({\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n ECOMWEB_MODE:\n typeof window === \"undefined\" ? process.env.ECOMWEB_MODE : undefined,\n // multi\n NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,\n NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,\n NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,\n NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,\n NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX:\n process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,\n NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,\n NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,\n // single\n NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,\n NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,\n NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,\n // both\n NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS:\n process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRAN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AAQ,IAAI;AAAA,IACd,0BAA0B,QAAQ,IAAI;AAAA,IACtC,8BAA8B,QAAQ,IAAI;AAAA;AAAA,IAE1C,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,qCACE,QAAQ,IAAI;AAAA,IACd,6BAA6B,QAAQ,IAAI;AAAA,IACzC,+BAA+B,QAAQ,IAAI;AAAA,IAC3C,sBAAsB,QAAQ,IAAI;AAAA;AAAA,IAElC,0CACE,QAAQ,IAAI;AAAA,IACd,uBAAuB,QAAQ,IAAI;AAAA,IACnC,oCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
|
package/dist/config/schema.js
CHANGED
|
@@ -7,6 +7,7 @@ function envValue(env, key) {
|
|
|
7
7
|
function logLevelOf(v) {
|
|
8
8
|
return LOG_LEVELS.includes(v ?? "") ? v : void 0;
|
|
9
9
|
}
|
|
10
|
+
const SECRET_IN_PUBLIC_MESSAGE = "holds a secret key; secret keys go in server-only variables (ECOMWEB_SECRET_KEY, PLATFORM_SECRET_KEY)";
|
|
10
11
|
const httpUrl = z.url({ protocol: /^https?$/ });
|
|
11
12
|
const publicConfigSchema = z.object({
|
|
12
13
|
mode: z.enum(["multi", "single"]),
|
|
@@ -14,7 +15,9 @@ const publicConfigSchema = z.object({
|
|
|
14
15
|
apiUrl: httpUrl,
|
|
15
16
|
assetBaseUrl: z.string(),
|
|
16
17
|
appUrl: httpUrl,
|
|
17
|
-
storefrontApiKey: z.string().min(1),
|
|
18
|
+
storefrontApiKey: z.string().min(1).refine((v) => !v.trim().startsWith("sk_"), {
|
|
19
|
+
message: SECRET_IN_PUBLIC_MESSAGE
|
|
20
|
+
}),
|
|
18
21
|
platformDomainSuffix: z.string().min(1).nullable(),
|
|
19
22
|
appBaseUrlFlag: z.string().optional(),
|
|
20
23
|
imageTransformationsFlag: z.string().optional(),
|
|
@@ -23,7 +26,14 @@ const publicConfigSchema = z.object({
|
|
|
23
26
|
webVitalsSampleRate: z.number().min(0).max(1)
|
|
24
27
|
});
|
|
25
28
|
const serverConfigSchema = z.object({
|
|
26
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Signs every server-side call. Empty only while `next build` runs (builds
|
|
31
|
+
* get no secret); read it through `storefrontSecretKey()`, which throws on
|
|
32
|
+
* an empty one.
|
|
33
|
+
*/
|
|
34
|
+
secretKey: z.string({ error: "is required" }).refine((v) => !v.trim().startsWith("pk_"), {
|
|
35
|
+
message: "is a publishable key; this variable takes the secret key (sk_...)"
|
|
36
|
+
}),
|
|
27
37
|
clientIpForwarderSecret: z.string().min(1).optional(),
|
|
28
38
|
appBaseUrl: z.string().min(1),
|
|
29
39
|
appEnv: z.string().min(1),
|
|
@@ -48,12 +58,13 @@ class ConfigError extends Error {
|
|
|
48
58
|
this.name = "ConfigError";
|
|
49
59
|
}
|
|
50
60
|
}
|
|
51
|
-
function parseOrThrow(schema, candidate, envNameOf) {
|
|
61
|
+
function parseOrThrow(schema, candidate, envNameOf, notes = {}) {
|
|
52
62
|
const result = schema.safeParse(candidate);
|
|
53
63
|
if (result.success) return result.data;
|
|
54
64
|
const lines = result.error.issues.map((issue) => {
|
|
55
65
|
const field = String(issue.path[0] ?? "");
|
|
56
|
-
|
|
66
|
+
const note = notes[field] ? ` ${notes[field]}` : "";
|
|
67
|
+
return ` - ${envNameOf[field] ?? field}: ${issue.message}${note}`;
|
|
57
68
|
});
|
|
58
69
|
throw new ConfigError(
|
|
59
70
|
`Invalid storefront configuration:
|
|
@@ -70,6 +81,7 @@ function sampleRateOf(v, fallback) {
|
|
|
70
81
|
}
|
|
71
82
|
export {
|
|
72
83
|
ConfigError,
|
|
84
|
+
SECRET_IN_PUBLIC_MESSAGE,
|
|
73
85
|
countOf,
|
|
74
86
|
envValue,
|
|
75
87
|
logLevelOf,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z.string().min(1),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n
|
|
1
|
+
{"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** The message for a secret key found where the browser could read it. */\nexport const SECRET_IN_PUBLIC_MESSAGE =\n \"holds a secret key; secret keys go in server-only variables (ECOMWEB_SECRET_KEY, PLATFORM_SECRET_KEY)\";\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z\n .string()\n .min(1)\n .refine(v => !v.trim().startsWith(\"sk_\"), {\n message: SECRET_IN_PUBLIC_MESSAGE,\n }),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n /**\n * Signs every server-side call. Empty only while `next build` runs (builds\n * get no secret); read it through `storefrontSecretKey()`, which throws on\n * an empty one.\n */\n secretKey: z\n .string({ error: \"is required\" })\n .refine(v => !v.trim().startsWith(\"pk_\"), {\n message:\n \"is a publishable key; this variable takes the secret key (sk_...)\",\n }),\n clientIpForwarderSecret: z.string().min(1).optional(),\n appBaseUrl: z.string().min(1),\n appEnv: z.string().min(1),\n googleVerification: z.string().optional(),\n logLevel: z.enum(LOG_LEVELS).optional(),\n /**\n * The header carrying the shopper's IP that this server's edge sets and a\n * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it\n * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.\n */\n clientIpHeader: z.enum([\"x-forwarded-for\", \"cf-connecting-ip\"]),\n /**\n * Requests a minute to one store, on one server, above which the\n * multi-tenant middleware logs that store (log only, nothing is refused).\n * 0 turns it off.\n */\n storeTrafficLogPerMinute: z.number().int().min(0),\n});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\n\n/**\n * Thrown when the storefront's environment variables are missing or invalid.\n * The message names the variable behind every bad field.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>,\n notes: Record<string, string> = {}\n): T {\n const result = schema.safeParse(candidate);\n if (result.success) return result.data;\n const lines = result.error.issues.map(issue => {\n const field = String(issue.path[0] ?? \"\");\n const note = notes[field] ? ` ${notes[field]}` : \"\";\n return ` - ${envNameOf[field] ?? field}: ${issue.message}${note}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\n}\n\n/** A non-negative integer from `v`, else `fallback`. */\nexport function countOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\nexport function sampleRateOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1\n ? n\n : fallback;\n}\n"],"mappings":"AAAA,SAAS,SAAS;AAKlB,MAAM,aAAa,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAGvD,SAAS,SAAS,KAAgB,KAAiC;AACxE,QAAM,IAAI,IAAI,GAAG,GAAG,KAAK;AACzB,SAAO,IAAI,IAAI;AACjB;AAEO,SAAS,WAAW,GAA6C;AACtE,SAAQ,WAAiC,SAAS,KAAK,EAAE,IACpD,IACD;AACN;AAGO,MAAM,2BACX;AAGF,MAAM,UAAU,EAAE,IAAI,EAAE,UAAU,WAAW,CAAC;AAEvC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,MAAM,EAAE,KAAK,CAAC,SAAS,QAAQ,CAAC;AAAA,EAChC,UAAU,EAA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AClD,CAAC;AAOM,MAAM,oBAAoB,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,aACd,QACA,WACA,WACA,QAAgC,CAAC,GAC9B;AACH,QAAM,SAAS,OAAO,UAAU,SAAS;AACzC,MAAI,OAAO,QAAS,QAAO,OAAO;AAClC,QAAM,QAAQ,OAAO,MAAM,OAAO,IAAI,WAAS;AAC7C,UAAM,QAAQ,OAAO,MAAM,KAAK,CAAC,KAAK,EAAE;AACxC,UAAM,OAAO,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,CAAC,KAAK;AACjD,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO,GAAG,IAAI;AAAA,EAClE,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;AAGO,SAAS,QAAQ,GAAuB,UAA0B;AACvE,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,UAAU,CAAC,KAAK,KAAK,IAAI,IAAI;AAChE;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfigError,
|
|
3
|
+
SECRET_IN_PUBLIC_MESSAGE
|
|
4
|
+
} from "./schema.js";
|
|
5
|
+
function isSecretKeyValue(value) {
|
|
6
|
+
return value?.trim().startsWith("sk_") ?? false;
|
|
7
|
+
}
|
|
8
|
+
function assertNoSecretInPublicEnv(env) {
|
|
9
|
+
const leaked = Object.keys(env).filter((key) => key.startsWith("NEXT_PUBLIC_") && isSecretKeyValue(env[key])).sort();
|
|
10
|
+
if (leaked.length === 0) return;
|
|
11
|
+
throw new ConfigError(
|
|
12
|
+
`Invalid storefront configuration:
|
|
13
|
+
${leaked.map((key) => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`).join("\n")}`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
export {
|
|
17
|
+
assertNoSecretInPublicEnv,
|
|
18
|
+
isSecretKeyValue
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=secret-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/config/secret-guard.ts"],"sourcesContent":["import {\n ConfigError,\n SECRET_IN_PUBLIC_MESSAGE,\n type EnvSource,\n} from \"./schema\";\n\n/** True when `value` is a secret key (`sk_` prefix, ignoring whitespace). */\nexport function isSecretKeyValue(value: string | undefined): boolean {\n return value?.trim().startsWith(\"sk_\") ?? false;\n}\n\n/**\n * Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those\n * into the browser bundle. The error names every offending variable and never\n * prints a value.\n *\n * @param env The environment to check.\n * @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.\n */\nexport function assertNoSecretInPublicEnv(env: EnvSource): void {\n const leaked = Object.keys(env)\n .filter(key => key.startsWith(\"NEXT_PUBLIC_\") && isSecretKeyValue(env[key]))\n .sort();\n if (leaked.length === 0) return;\n throw new ConfigError(\n `Invalid storefront configuration:\\n${leaked\n .map(key => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`)\n .join(\"\\n\")}`\n );\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAGA,SAAS,iBAAiB,OAAoC;AACnE,SAAO,OAAO,KAAK,EAAE,WAAW,KAAK,KAAK;AAC5C;AAUO,SAAS,0BAA0B,KAAsB;AAC9D,QAAM,SAAS,OAAO,KAAK,GAAG,EAC3B,OAAO,SAAO,IAAI,WAAW,cAAc,KAAK,iBAAiB,IAAI,GAAG,CAAC,CAAC,EAC1E,KAAK;AACR,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,OACnC,IAAI,SAAO,OAAO,GAAG,KAAK,wBAAwB,EAAE,EACpD,KAAK,IAAI,CAAC;AAAA,EACf;AACF;","names":[]}
|
package/dist/config/server.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "server-only";
|
|
2
2
|
import { resolveMode } from "./mode.js";
|
|
3
|
+
import { assertNoSecretInPublicEnv } from "./secret-guard.js";
|
|
3
4
|
import {
|
|
4
5
|
countOf,
|
|
5
6
|
envValue,
|
|
@@ -7,11 +8,18 @@ import {
|
|
|
7
8
|
parseOrThrow,
|
|
8
9
|
serverConfigSchema
|
|
9
10
|
} from "./schema.js";
|
|
11
|
+
function secretOf(env, name) {
|
|
12
|
+
const value = envValue(env, name);
|
|
13
|
+
if (value === void 0 && env.NEXT_PHASE === "phase-production-build") {
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
10
18
|
function parseMulti(env) {
|
|
11
19
|
return parseOrThrow(
|
|
12
20
|
serverConfigSchema,
|
|
13
21
|
{
|
|
14
|
-
|
|
22
|
+
secretKey: secretOf(env, "PLATFORM_SECRET_KEY"),
|
|
15
23
|
clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
|
|
16
24
|
appBaseUrl: envValue(env, "APP_BASE_URL") ?? "http://localhost:3002",
|
|
17
25
|
appEnv: envValue(env, "APP_ENV") ?? "unknown",
|
|
@@ -24,19 +32,17 @@ function parseMulti(env) {
|
|
|
24
32
|
)
|
|
25
33
|
},
|
|
26
34
|
{
|
|
27
|
-
|
|
35
|
+
secretKey: "PLATFORM_SECRET_KEY",
|
|
28
36
|
clientIpHeader: "CLIENT_IP_HEADER"
|
|
29
|
-
}
|
|
37
|
+
},
|
|
38
|
+
envValue(env, "PLATFORM_API_KEY") ? { secretKey: "(PLATFORM_API_KEY is retired)" } : {}
|
|
30
39
|
);
|
|
31
40
|
}
|
|
32
41
|
function parseSingle(env) {
|
|
33
42
|
return parseOrThrow(
|
|
34
43
|
serverConfigSchema,
|
|
35
44
|
{
|
|
36
|
-
|
|
37
|
-
// NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg
|
|
38
|
-
// still runs when the runtime env does not repeat it.
|
|
39
|
-
platformApiKey: envValue(env, "ECOMWEB_PUBLISHABLE_KEY") ?? envValue(env, "NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY"),
|
|
45
|
+
secretKey: secretOf(env, "ECOMWEB_SECRET_KEY"),
|
|
40
46
|
clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
|
|
41
47
|
appBaseUrl: envValue(env, "SITE_URL") ?? "http://localhost:3000",
|
|
42
48
|
appEnv: envValue(env, "APP_ENV") ?? "production",
|
|
@@ -47,12 +53,13 @@ function parseSingle(env) {
|
|
|
47
53
|
storeTrafficLogPerMinute: 0
|
|
48
54
|
},
|
|
49
55
|
{
|
|
50
|
-
|
|
56
|
+
secretKey: "ECOMWEB_SECRET_KEY",
|
|
51
57
|
clientIpHeader: "CLIENT_IP_HEADER"
|
|
52
58
|
}
|
|
53
59
|
);
|
|
54
60
|
}
|
|
55
61
|
function parseServerConfig(env) {
|
|
62
|
+
assertNoSecretInPublicEnv(env);
|
|
56
63
|
return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
|
|
57
64
|
}
|
|
58
65
|
let cached;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n
|
|
1
|
+
{"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport { assertNoSecretInPublicEnv } from \"./secret-guard\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\n/**\n * The secret key, from the runtime env only (never a NEXT_PUBLIC_ fallback).\n * `next build` gets none (hosted builds hold no secret), so while it runs a\n * missing key reads as empty; `storefrontSecretKey()` throws on an empty one.\n */\nfunction secretOf(env: EnvSource, name: string): string | undefined {\n const value = envValue(env, name);\n if (value === undefined && env.NEXT_PHASE === \"phase-production-build\") {\n return \"\";\n }\n return value;\n}\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"PLATFORM_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"APP_BASE_URL\") ?? \"http://localhost:3002\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"unknown\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n storeTrafficLogPerMinute: countOf(\n envValue(env, \"STORE_TRAFFIC_LOG_PER_MINUTE\"),\n 600\n ),\n },\n {\n secretKey: \"PLATFORM_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n },\n envValue(env, \"PLATFORM_API_KEY\")\n ? { secretKey: \"(PLATFORM_API_KEY is retired)\" }\n : {}\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"ECOMWEB_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"SITE_URL\") ?? \"http://localhost:3000\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"production\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n // One store per site: there are no neighbours to watch.\n storeTrafficLogPerMinute: 0,\n },\n {\n secretKey: \"ECOMWEB_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parseServerConfig(env: EnvSource): ServerConfig {\n assertNoSecretInPublicEnv(env);\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * The server's parsed configuration, read from the environment on the first\n * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`\n * in server code, never in a client component.\n *\n * @returns The validated server config.\n * @throws ConfigError when a required variable is missing or invalid.\n */\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAOP,SAAS,SAAS,KAAgB,MAAkC;AAClE,QAAM,QAAQ,SAAS,KAAK,IAAI;AAChC,MAAI,UAAU,UAAa,IAAI,eAAe,0BAA0B;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;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AW,kBAAkB;AAAA,IACnC,GAAG,QAAQ;AAAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/version-check.ts"],"sourcesContent":["import { SDK_VERSION } from \"@ecomweb/sdk\";\nimport { KIT_VERSION } from \"../client-info\";\nimport type { EnvSource } from \"./schema\";\n\n/** Next's `phase` for `next build` (next/constants PHASE_PRODUCTION_BUILD). */\nconst PRODUCTION_BUILD_PHASE = \"phase-production-build\";\nconst DEFAULT_API_URL = \"https://apibase.ecomweb.app/api/v1\";\nconst DEFAULT_TIMEOUT_MS = 2000;\n// Set once a build has checked, so Next's build workers (which load the\n// config again and inherit the env) stay quiet.\nconst CHECKED_FLAG = \"__ECOMWEB_VERSION_CHECKED\";\n\nconst KIT_PACKAGE = \"@ecomweb/storefront-kit\";\nconst SDK_PACKAGE = \"@ecomweb/sdk\";\n\ninterface PackagePolicy {\n latest?: string;\n minimum_supported?: string;\n security_minimum?: string;\n}\n\ninterface Advisory {\n id?: string;\n package?: string;\n fixed_in?: string;\n severity?: string;\n summary?: string;\n url?: string;\n}\n\ninterface VersionsResponse {\n packages?: Record<string, PackagePolicy | undefined>;\n advisories?: Advisory[];\n upgrade_guide_url?: string;\n}\n\nexport type ClientVersionStatus =\n | \"up_to_date\"\n | \"update_available\"\n | \"unsupported\"\n | \"security_update\";\n\nexport interface ClientVersionReport {\n status: ClientVersionStatus;\n /** The package judged: the kit, or the SDK when the kit is current. */\n package: string;\n installed: string;\n latest?: string;\n advisories: Advisory[];\n upgradeGuideUrl?: string;\n}\n\nexport interface CheckClientVersionsOptions {\n /** Next's config `phase`; the check runs only for `next build`. */\n phase?: string;\n /** The API base, `/api/v1` included. Defaults to production. */\n apiUrl?: string;\n env?: EnvSource;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Where the warning goes; `console.warn` by default. */\n warn?: (message: string) => void;\n /** Overrides the baked-in versions (tests). */\n installed?: { kit?: string; sdk?: string };\n}\n\ntype Semver = [number, number, number];\n\nfunction parseSemver(v: string | undefined): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v?.trim() ?? \"\");\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/** True when `a` is a lower version than `b`; false if either isn't semver. */\nfunction isBelow(a: string, b: string | undefined): boolean {\n const x = parseSemver(a);\n const y = parseSemver(b);\n if (!x || !y) return false;\n for (let i = 0; i < 3; i++) {\n if (x[i] !== y[i]) return x[i] < y[i];\n }\n return false;\n}\n\nfunction judge(\n pkg: string,\n installed: string,\n body: VersionsResponse\n): ClientVersionReport | null {\n if (!parseSemver(installed)) return null;\n const policy = body.packages?.[pkg];\n if (!policy) return null;\n const advisories = (body.advisories ?? []).filter(\n a => a.package === pkg && isBelow(installed, a.fixed_in)\n );\n const status: ClientVersionStatus = isBelow(installed, policy.security_minimum)\n ? \"security_update\"\n : isBelow(installed, policy.minimum_supported)\n ? \"unsupported\"\n : isBelow(installed, policy.latest)\n ? \"update_available\"\n : \"up_to_date\";\n return {\n status,\n package: pkg,\n installed,\n latest: policy.latest,\n advisories,\n upgradeGuideUrl: body.upgrade_guide_url,\n };\n}\n\nconst SEVERITY: Record<ClientVersionStatus, number> = {\n up_to_date: 0,\n update_available: 1,\n unsupported: 2,\n security_update: 3,\n};\n\nexport function formatClientVersionWarning(report: ClientVersionReport): string {\n const behind = `${report.package} ${report.installed}`;\n const latest = report.latest ? ` (latest ${report.latest})` : \"\";\n const headline =\n report.status === \"security_update\"\n ? `ecomweb: security update available: ${behind} has known security issues${latest}.`\n : report.status === \"unsupported\"\n ? `ecomweb: ${behind} is no longer supported${latest}.`\n : `ecomweb: update available: ${behind}${latest}.`;\n const lines = [headline];\n for (const a of report.advisories) {\n const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : \"\";\n lines.push(` - ${a.summary ?? a.id ?? \"advisory\"}${fixed}`);\n }\n lines.push(\" Update with: ecomweb storefront upgrade\");\n if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);\n lines.push(\" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Checks the installed kit and SDK against the platform's supported versions\n * and prints a warning when they are behind. For `next.config.mjs`:\n *\n * ```js\n * export default async function config(phase) {\n * await checkClientVersions({ phase, apiUrl: API_URL });\n * return nextConfig;\n * }\n * ```\n *\n * Runs during `next build` only, once per build, and never fails or slows it\n * beyond the timeout (2 s): any error is ignored. Off with\n * `ECOMWEB_SKIP_VERSION_CHECK=1`. Returns the report, or null when it did not\n * check.\n */\nexport async function checkClientVersions(\n options: CheckClientVersionsOptions = {}\n): Promise<ClientVersionReport | null> {\n const env = options.env ?? process.env;\n if (options.phase !== PRODUCTION_BUILD_PHASE) return null;\n if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === \"1\") return null;\n if (env[CHECKED_FLAG] === \"1\") return null;\n env[CHECKED_FLAG] = \"1\";\n\n try {\n const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const response = await doFetch(`${base}/public/storefront-clients/versions`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n if (!response.ok) return null;\n const body = (await response.json()) as VersionsResponse;\n\n const reports = [\n judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),\n judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body),\n ].filter((r): r is ClientVersionReport => r !== null);\n if (reports.length === 0) return null;\n\n const worst = reports.reduce((a, b) =>\n SEVERITY[b.status] > SEVERITY[a.status] ? b : a\n );\n if (worst.status !== \"up_to_date\") {\n // A build-time notice for the developer, not runtime logging.\n // eslint-disable-next-line no-console\n (options.warn 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iB,KAAK;AAAA,EACxB;AACF;AAEA,MAAM,WAAgD;AAAA,EACpD,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,iBAAiB;AACnB;
|
|
1
|
+
{"version":3,"sources":["../../src/config/version-check.ts"],"sourcesContent":["import { SDK_VERSION } from \"@ecomweb/sdk\";\nimport { KIT_VERSION } from \"../client-info\";\nimport type { EnvSource } from \"./schema\";\n\n/** Next's `phase` for `next build` (next/constants PHASE_PRODUCTION_BUILD). */\nconst PRODUCTION_BUILD_PHASE = \"phase-production-build\";\nconst DEFAULT_API_URL = \"https://apibase.ecomweb.app/api/v1\";\nconst DEFAULT_TIMEOUT_MS = 2000;\n// Set once a build has checked, so Next's build workers (which load the\n// config again and inherit the env) stay quiet.\nconst CHECKED_FLAG = \"__ECOMWEB_VERSION_CHECKED\";\n\nconst KIT_PACKAGE = \"@ecomweb/storefront-kit\";\nconst SDK_PACKAGE = \"@ecomweb/sdk\";\n\ninterface PackagePolicy {\n latest?: string;\n minimum_supported?: string;\n security_minimum?: string;\n}\n\ninterface Advisory {\n id?: string;\n package?: string;\n fixed_in?: string;\n severity?: string;\n summary?: string;\n url?: string;\n}\n\ninterface VersionsResponse {\n packages?: Record<string, PackagePolicy | undefined>;\n advisories?: Advisory[];\n upgrade_guide_url?: string;\n}\n\nexport type ClientVersionStatus =\n | \"up_to_date\"\n | \"update_available\"\n | \"unsupported\"\n | \"security_update\";\n\nexport interface ClientVersionReport {\n status: ClientVersionStatus;\n /** The package judged: the kit, or the SDK when the kit is current. */\n package: string;\n installed: string;\n latest?: string;\n advisories: Advisory[];\n upgradeGuideUrl?: string;\n}\n\nexport interface CheckClientVersionsOptions {\n /** Next's config `phase`; the check runs only for `next build`. */\n phase?: string;\n /** The API base, `/api/v1` included. Defaults to production. */\n apiUrl?: string;\n env?: EnvSource;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Where the warning goes; `console.warn` by default. */\n warn?: (message: string) => void;\n /** Overrides the baked-in versions (tests). */\n installed?: { kit?: string; sdk?: string };\n}\n\ntype Semver = [number, number, number];\n\nfunction parseSemver(v: string | undefined): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v?.trim() ?? \"\");\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/** True when `a` is a lower version than `b`; false if either isn't semver. */\nfunction isBelow(a: string, b: string | undefined): boolean {\n const x = parseSemver(a);\n const y = parseSemver(b);\n if (!x || !y) return false;\n for (let i = 0; i < 3; i++) {\n if (x[i] !== y[i]) return x[i] < y[i];\n }\n return false;\n}\n\nfunction judge(\n pkg: string,\n installed: string,\n body: VersionsResponse\n): ClientVersionReport | null {\n if (!parseSemver(installed)) return null;\n const policy = body.packages?.[pkg];\n if (!policy) return null;\n const advisories = (body.advisories ?? []).filter(\n a => a.package === pkg && isBelow(installed, a.fixed_in)\n );\n const status: ClientVersionStatus = isBelow(installed, policy.security_minimum)\n ? \"security_update\"\n : isBelow(installed, policy.minimum_supported)\n ? \"unsupported\"\n : isBelow(installed, policy.latest)\n ? \"update_available\"\n : \"up_to_date\";\n return {\n status,\n package: pkg,\n installed,\n latest: policy.latest,\n advisories,\n upgradeGuideUrl: body.upgrade_guide_url,\n };\n}\n\nconst SEVERITY: Record<ClientVersionStatus, number> = {\n up_to_date: 0,\n update_available: 1,\n unsupported: 2,\n security_update: 3,\n};\n\n/**\n * Turns a version report into the multi-line warning that\n * {@link checkClientVersions} prints: the headline, one line per advisory and\n * how to update.\n *\n * @param report - The report to describe.\n * @returns The warning text, ready for `console.warn`.\n */\nexport function formatClientVersionWarning(report: ClientVersionReport): string {\n const behind = `${report.package} ${report.installed}`;\n const latest = report.latest ? ` (latest ${report.latest})` : \"\";\n const headline =\n report.status === \"security_update\"\n ? `ecomweb: security update available: ${behind} has known security issues${latest}.`\n : report.status === \"unsupported\"\n ? `ecomweb: ${behind} is no longer supported${latest}.`\n : `ecomweb: update available: ${behind}${latest}.`;\n const lines = [headline];\n for (const a of report.advisories) {\n const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : \"\";\n lines.push(` - ${a.summary ?? a.id ?? \"advisory\"}${fixed}`);\n }\n lines.push(\" Update with: ecomweb storefront upgrade\");\n if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);\n lines.push(\" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Checks the installed kit and SDK against the platform's supported versions\n * and prints a warning when they are behind. For `next.config.mjs`:\n *\n * ```js\n * export default async function config(phase) {\n * await checkClientVersions({ phase, apiUrl: API_URL });\n * return nextConfig;\n * }\n * ```\n *\n * Runs during `next build` only, once per build, and never fails or slows it\n * beyond the timeout (2 s): any error is ignored. Off with\n * `ECOMWEB_SKIP_VERSION_CHECK=1`. Returns the report, or null when it did not\n * check.\n */\nexport async function checkClientVersions(\n options: CheckClientVersionsOptions = {}\n): Promise<ClientVersionReport | null> {\n const env = options.env ?? process.env;\n if (options.phase !== PRODUCTION_BUILD_PHASE) return null;\n if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === \"1\") return null;\n if (env[CHECKED_FLAG] === \"1\") return null;\n env[CHECKED_FLAG] = \"1\";\n\n try {\n const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const response = await doFetch(`${base}/public/storefront-clients/versions`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n if (!response.ok) return null;\n const body = (await response.json()) as VersionsResponse;\n\n const reports = [\n judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),\n judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body),\n ].filter((r): r is ClientVersionReport => r !== null);\n if (reports.length === 0) return null;\n\n const worst = reports.reduce((a, b) =>\n SEVERITY[b.status] > SEVERITY[a.status] ? b : a\n );\n if (worst.status !== \"up_to_date\") {\n // A build-time notice for the developer, not runtime logging.\n // eslint-disable-next-line no-console\n (options.warn ?? console.warn)(formatClientVersionWarning(worst));\n }\n return worst;\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAI5B,MAAM,yBAAyB;AAC/B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAG3B,MAAM,eAAe;AAErB,MAAM,cAAc;AACpB,MAAM,cAAc;AAuDpB,SAAS,YAAY,GAAsC;AACzD,QAAM,IAAI,yBAAyB,KAAK,GAAG,KAAK,KAAK,EAAE;AACvD,SAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI;AAC1D;AAGA,SAAS,QAAQ,GAAW,GAAgC;AAC1D,QAAM,IAAI,YAAY,CAAC;AACvB,QAAM,IAAI,YAAY,CAAC;AACvB,MAAI,CAAC,KAAK,CAAC,EAAG,QAAO;AACrB,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,EAAE,CAAC,MAAM,EAAE,CAAC,EAAG,QAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AAAA,EACtC;AACA,SAAO;AACT;AAEA,SAAS,MACP,KACA,WACA,MAC4B;AAC5B,MAAI,CAAC,YAAY,SAAS,EAAG,QAAO;AACpC,QAAM,SAAS,KAAK,WAAW,GAAG;AAClC,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,cAAc,KAAK,cAAc,CAAC,GAAG;AAAA,IACzC,OAAK,EAAE,YAAY,OAAO,QAAQ,WAAW,EAAE,QAAQ;AAAA,EACzD;AACA,QAAM,SAA8B,QAAQ,WAAW,OAAO,gBAAgB,IAC1E,oBACA,QAAQ,WAAW,OAAO,iBAAiB,IACzC,gBACA,QAAQ,WAAW,OAAO,MAAM,IAC9B,qBACA;AACR,SAAO;AAAA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M,QAAQ,GAAG,IAAI,uCAAuC;AAAA,MAC3E,SAAS,EAAE,QAAQ,mBAAmB;AAAA,MACtC,QAAQ,YAAY,QAAQ,QAAQ,aAAa,kBAAkB;AAAA,IACrE,CAAC;AACD,QAAI,CAAC,SAAS,GAAI,QAAO;AACzB,UAAM,OAAQ,MAAM,SAAS,KAAK;AAElC,UAAM,UAAU;AAAA,MACd,MAAM,aAAa,QAAQ,WAAW,OAAO,aAAa,IAAI;AAAA,MAC9D,MAAM,aAAa,QAAQ,WAAW,OAAO,aAAa,IAAI;AAAA,IAChE,EAAE,OAAO,CAAC,MAAgC,MAAM,IAAI;AACpD,QAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,UAAM,QAAQ,QAAQ;AAAA,MAAO,CAAC,GAAG,MAC/B,SAAS,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,IAAI,IAAI;AAAA,IAChD;AACA,QAAI,MAAM,WAAW,cAAc;AAGjC,OAAC,QAAQ,QAAQ,QAAQ,MAAM,2BAA2B,KAAK,CAAC;AAAA,IAClE;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
package/dist/config.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { E as EnvSource, P as PublicConfig } from './schema-
|
|
2
|
-
export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-
|
|
3
|
-
export { S as StorefrontMode, r as resolveMode } from './mode-
|
|
1
|
+
import { E as EnvSource, P as PublicConfig } from './schema-B3nAYiwT.js';
|
|
2
|
+
export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-B3nAYiwT.js';
|
|
3
|
+
export { S as StorefrontMode, r as resolveMode } from './mode-oVZCQxrc.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
/** Parses the variables of the mode `env` selects (see resolveMode). */
|
|
@@ -13,6 +13,16 @@ declare function resetPublicConfigForTests(): void;
|
|
|
13
13
|
*/
|
|
14
14
|
declare function publicConfig(): PublicConfig;
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those
|
|
18
|
+
* into the browser bundle. The error names every offending variable and never
|
|
19
|
+
* prints a value.
|
|
20
|
+
*
|
|
21
|
+
* @param env The environment to check.
|
|
22
|
+
* @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.
|
|
23
|
+
*/
|
|
24
|
+
declare function assertNoSecretInPublicEnv(env: EnvSource): void;
|
|
25
|
+
|
|
16
26
|
/**
|
|
17
27
|
* This package's version, baked in at build time. `dev` when the source runs
|
|
18
28
|
* without the define (the API ignores a version that isn't semver).
|
|
@@ -55,6 +65,14 @@ interface CheckClientVersionsOptions {
|
|
|
55
65
|
sdk?: string;
|
|
56
66
|
};
|
|
57
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* Turns a version report into the multi-line warning that
|
|
70
|
+
* {@link checkClientVersions} prints: the headline, one line per advisory and
|
|
71
|
+
* how to update.
|
|
72
|
+
*
|
|
73
|
+
* @param report - The report to describe.
|
|
74
|
+
* @returns The warning text, ready for `console.warn`.
|
|
75
|
+
*/
|
|
58
76
|
declare function formatClientVersionWarning(report: ClientVersionReport): string;
|
|
59
77
|
/**
|
|
60
78
|
* Checks the installed kit and SDK against the platform's supported versions
|
|
@@ -74,4 +92,4 @@ declare function formatClientVersionWarning(report: ClientVersionReport): string
|
|
|
74
92
|
*/
|
|
75
93
|
declare function checkClientVersions(options?: CheckClientVersionsOptions): Promise<ClientVersionReport | null>;
|
|
76
94
|
|
|
77
|
-
export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
|
|
95
|
+
export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, assertNoSecretInPublicEnv, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
|
package/dist/config.js
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
} from "./config/public.js";
|
|
6
6
|
import { resolveMode } from "./config/mode.js";
|
|
7
7
|
import { ConfigError } from "./config/schema.js";
|
|
8
|
+
import { assertNoSecretInPublicEnv } from "./config/secret-guard.js";
|
|
8
9
|
import { KIT_CLIENT_TOKEN, KIT_VERSION } from "./client-info.js";
|
|
9
10
|
import {
|
|
10
11
|
checkClientVersions,
|
|
@@ -14,6 +15,7 @@ export {
|
|
|
14
15
|
ConfigError,
|
|
15
16
|
KIT_CLIENT_TOKEN,
|
|
16
17
|
KIT_VERSION,
|
|
18
|
+
assertNoSecretInPublicEnv,
|
|
17
19
|
checkClientVersions,
|
|
18
20
|
formatClientVersionWarning,
|
|
19
21
|
parsePublicConfig,
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Parsing and types for the storefront's configuration: public (client-safe)\n * settings, the deployment mode, the build-time version check and\n * `ConfigError`.\n *\n * Import from `@ecomweb/storefront-kit/config` in `next.config` and config\n * code. It has no React or server-only dependency.\n *\n * @packageDocumentation\n */\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport { assertNoSecretInPublicEnv } from \"./config/secret-guard\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAO1C,SAAS,kBAAkB,mBAAmB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
|
package/dist/currency.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/currency.ts"],"sourcesContent":["import currencyJs from \"currency.js\";\n\nexport type SupportedCurrency = \"VND\" | \"USD\" | \"EUR\" | \"SGD\";\n\nexport function getDefaultLocale(currency: SupportedCurrency): string {\n switch (currency) {\n case \"USD\":\n case \"EUR\":\n case \"SGD\":\n return \"en-US\";\n case \"VND\":\n return \"vi-VN\";\n default:\n return \"vi-VN\";\n }\n}\n\n/**\n * House formatting convention, one table for every currency we price in.\n *\n * A locale bundles four decisions — group separator, decimal separator,\n * symbol, and symbol placement — behind one string, and we want them from\n * different places. `vi-VN` renders 10.234.000 ₫ with a space and the dong\n * sign; the house style is 10.234.000đ, tight and with the Latin d-stroke.\n * So the table is explicit.\n *\n * Numerals are uniform across currencies: dot groups, comma decimals. Only\n * the symbol, its placement, and the precision vary.\n *\n * VND 10.234.000đ USD $1.234,50\n * EUR €1.234,50 SGD S$1.234,50\n *\n * Keep this in sync with the same table in ecomweb-dashboard/lib/currency.ts\n * and the API's src/common/utils/currency.utils.ts. The pinned tests in each\n * repo exist to catch drift between the three.\n */\nconst CURRENCY_FORMATS = {\n VND: { symbol: \"đ\", precision: 0, suffix: true },\n USD: { symbol: \"$\", precision: 2, suffix: false },\n EUR: { symbol: \"€\", precision: 2, suffix: false },\n SGD: { symbol: \"S$\", precision: 2, suffix: false },\n} as const;\n\n/** Narrows an arbitrary stored code to a currency we can price in. */\nexport function isSupportedCurrency(\n code: unknown\n): code is SupportedCurrency {\n return (\n typeof code === \"string\" &&\n Object.prototype.hasOwnProperty.call(CURRENCY_FORMATS, code)\n );\n}\n\nfunction getCurrencyOptions(_locale: string, code: SupportedCurrency | string) {\n const format =\n CURRENCY_FORMATS[code as SupportedCurrency] ?? CURRENCY_FORMATS.VND;\n\n return {\n symbol: format.symbol,\n precision: format.precision,\n // Uniform numerals: 1.234.567,89 regardless of currency.\n separator: \".\",\n decimal: \",\",\n // The sign stays outermost: -10.234.000đ and -$19,99.\n pattern: format.suffix ? \"#!\" : \"!#\",\n negativePattern: format.suffix ? \"-#!\" : \"-!#\",\n } as const;\n}\n\n/**\n * Format an amount as money in the given currency.\n *\n * `locale` is retained for call-site compatibility but no longer affects the\n * output — the house convention in CURRENCY_FORMATS is uniform across\n * locales. It still matters to formatNumber, which is not currency.\n */\nexport function formatPrice(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency | string = \"VND\"\n): string {\n const opts = getCurrencyOptions(locale, code);\n return currencyJs(amount, opts).format();\n}\n\nexport function formatNumber(amount: number, locale = \"vi-VN\"): string {\n // General number formatting (non-currency)\n return new Intl.NumberFormat(locale).format(amount);\n}\n\nexport function formatPriceRange(\n min?: number,\n max?: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n if (min == null && max == null) return \"\";\n if (max == null || min === max) return formatPrice(min || 0, locale, code);\n return `${formatPrice(min || 0, locale, code)} - ${formatPrice(max, locale, code)}`;\n}\n\n
|
|
1
|
+
{"version":3,"sources":["../src/currency.ts"],"sourcesContent":["import currencyJs from \"currency.js\";\n\nexport type SupportedCurrency = \"VND\" | \"USD\" | \"EUR\" | \"SGD\";\n\n/**\n * Picks the locale used to format prices in a currency: `en-US` for USD, EUR\n * and SGD, `vi-VN` for VND.\n *\n * @param currency - The store's currency code.\n * @returns A BCP 47 locale tag.\n */\nexport function getDefaultLocale(currency: SupportedCurrency): string {\n switch (currency) {\n case \"USD\":\n case \"EUR\":\n case \"SGD\":\n return \"en-US\";\n case \"VND\":\n return \"vi-VN\";\n default:\n return \"vi-VN\";\n }\n}\n\n/**\n * House formatting convention, one table for every currency we price in.\n *\n * A locale bundles four decisions — group separator, decimal separator,\n * symbol, and symbol placement — behind one string, and we want them from\n * different places. `vi-VN` renders 10.234.000 ₫ with a space and the dong\n * sign; the house style is 10.234.000đ, tight and with the Latin d-stroke.\n * So the table is explicit.\n *\n * Numerals are uniform across currencies: dot groups, comma decimals. Only\n * the symbol, its placement, and the precision vary.\n *\n * VND 10.234.000đ USD $1.234,50\n * EUR €1.234,50 SGD S$1.234,50\n *\n * Keep this in sync with the same table in ecomweb-dashboard/lib/currency.ts\n * and the API's src/common/utils/currency.utils.ts. The pinned tests in each\n * repo exist to catch drift between the three.\n */\nconst CURRENCY_FORMATS = {\n VND: { symbol: \"đ\", precision: 0, suffix: true },\n USD: { symbol: \"$\", precision: 2, suffix: false },\n EUR: { symbol: \"€\", precision: 2, suffix: false },\n SGD: { symbol: \"S$\", precision: 2, suffix: false },\n} as const;\n\n/** Narrows an arbitrary stored code to a currency we can price in. */\nexport function isSupportedCurrency(\n code: unknown\n): code is SupportedCurrency {\n return (\n typeof code === \"string\" &&\n Object.prototype.hasOwnProperty.call(CURRENCY_FORMATS, code)\n );\n}\n\nfunction getCurrencyOptions(_locale: string, code: SupportedCurrency | string) {\n const format =\n CURRENCY_FORMATS[code as SupportedCurrency] ?? CURRENCY_FORMATS.VND;\n\n return {\n symbol: format.symbol,\n precision: format.precision,\n // Uniform numerals: 1.234.567,89 regardless of currency.\n separator: \".\",\n decimal: \",\",\n // The sign stays outermost: -10.234.000đ and -$19,99.\n pattern: format.suffix ? \"#!\" : \"!#\",\n negativePattern: format.suffix ? \"-#!\" : \"-!#\",\n } as const;\n}\n\n/**\n * Format an amount as money in the given currency.\n *\n * `locale` is retained for call-site compatibility but no longer affects the\n * output — the house convention in CURRENCY_FORMATS is uniform across\n * locales. It still matters to formatNumber, which is not currency.\n */\nexport function formatPrice(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency | string = \"VND\"\n): string {\n const opts = getCurrencyOptions(locale, code);\n return currencyJs(amount, opts).format();\n}\n\n/**\n * Formats a plain number with the locale's digit grouping, without a currency\n * symbol.\n *\n * @param amount - The number to format.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @returns The formatted number.\n */\nexport function formatNumber(amount: number, locale = \"vi-VN\"): string {\n // General number formatting (non-currency)\n return new Intl.NumberFormat(locale).format(amount);\n}\n\n/**\n * Formats a price range such as a product's lowest and highest variant price.\n *\n * @param min - The lowest price.\n * @param max - The highest price.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns One formatted price when the two match or `max` is missing, `min - max` otherwise, and an empty string when both are missing.\n */\nexport function formatPriceRange(\n min?: number,\n max?: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n if (min == null && max == null) return \"\";\n if (max == null || min === max) return formatPrice(min || 0, locale, code);\n return `${formatPrice(min || 0, locale, code)} - ${formatPrice(max, locale, code)}`;\n}\n\n/**\n * Wraps a value in a currency.js object for safe money arithmetic (add,\n * subtract, multiply, format) without floating-point drift.\n *\n * @param value - The amount, as a number or numeric string.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns A currency.js value configured for that locale and currency.\n */\nexport const money = (\n value: number | string,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n) => currencyJs(value as any, getCurrencyOptions(locale, code));\n\n// Format for inputs (no symbol), keeps separators consistent with currency options\n/**\n * Formats an amount with the currency's separators but no symbol, for price\n * inputs.\n *\n * @param amount - The amount to format.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns The formatted amount.\n */\nexport function formatPriceWithoutSymbol(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n const base = getCurrencyOptions(locale, code);\n const opts = {\n ...base,\n symbol: \"\",\n pattern: \"#\",\n negativePattern: \"-#\",\n } as const;\n return currencyJs(amount, opts).format();\n}\n"],"mappings":"AAAA,OAAO,gBAAgB;AAWhB,SAAS,iBAAiB,UAAqC;AACpE,UAAQ,UAAU;AAAA,IAChB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAqBA,MAAM,mBAAmB;AAAA,EACvB,KAAK,EAAE,QAAQ,UAAK,WAAW,GAAG,QAAQ,KAAK;AAAA,EAC/C,KAAK,EAAE,QAAQ,KAAK,WAAW,GAAG,QAAQ,MAAM;AAAA,EAChD,KAAK,EAAE,QAAQ,UAAK,WAAW,GAAG,QAAQ,MAAM;AAAA,EAChD,KAAK,EAAE,QAAQ,MAAM,WAAW,GAAG,QAAQ,MAAM;AACnD;AAGO,SAAS,oBACd,MAC2B;AAC3B,SACE,OAAO,SAAS,YAChB,OAAO,UAAU,eAAe,KAAK,kBAAkB,IAAI;AAE/D;AAEA,SAAS,mBAAmB,SAAiB,MAAkC;AAC7E,QAAM,SACJ,iBAAiB,IAAyB,KAAK,iBAAiB;AAElE,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,WAAW,OAAO;AAAA;AAAA,IAElB,WAAW;AAAA,IACX,SAAS;AAAA;AAAA,IAET,SAAS,OAAO,SAAS,OAAO;AAAA,IAChC,iBAAiB,OAAO,SAAS,QAAQ;AAAA,EAC3C;AACF;AASO,SAAS,YACd,QACA,SAAiB,SACjB,OAAmC,OAC3B;AACR,QAAM,OAAO,mBAAmB,QAAQ,IAAI;AAC5C,SAAO,WAAW,QAAQ,IAAI,EAAE,OAAO;AACzC;AAUO,SAAS,aAAa,QAAgB,SAAS,SAAiB;AAErE,SAAO,IAAI,KAAK,aAAa,MAAM,EAAE,OAAO,MAAM;AACpD;AAWO,SAAS,iBAC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