@ecomweb/storefront-kit 0.6.0 → 0.10.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.
Files changed (79) hide show
  1. package/README.md +28 -1
  2. package/dist/api/proxy.js +5 -1
  3. package/dist/api/proxy.js.map +1 -1
  4. package/dist/api/server-client.js +7 -4
  5. package/dist/api/server-client.js.map +1 -1
  6. package/dist/auth/cookies.js +51 -33
  7. package/dist/auth/cookies.js.map +1 -1
  8. package/dist/auth/error-copy.js +5 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/route-handlers.js +2 -2
  11. package/dist/auth/route-handlers.js.map +1 -1
  12. package/dist/auth/session-refresh.js +11 -5
  13. package/dist/auth/session-refresh.js.map +1 -1
  14. package/dist/auth/session.js +8 -4
  15. package/dist/auth/session.js.map +1 -1
  16. package/dist/checkout/get-payment-state.js.map +1 -1
  17. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  18. package/dist/checkout/order-handoff.js +10 -1
  19. package/dist/checkout/order-handoff.js.map +1 -1
  20. package/dist/checkout/quote-changed.js +16 -0
  21. package/dist/checkout/quote-changed.js.map +1 -0
  22. package/dist/checkout/use-checkout.js +44 -7
  23. package/dist/checkout/use-checkout.js.map +1 -1
  24. package/dist/config/schema.js +12 -1
  25. package/dist/config/schema.js.map +1 -1
  26. package/dist/config/server.js +9 -2
  27. package/dist/config/server.js.map +1 -1
  28. package/dist/config.d.ts +3 -3
  29. package/dist/index.d.ts +167 -26
  30. package/dist/index.js +37 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/middleware/create-storefront-middleware.js +62 -26
  33. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  34. package/dist/middleware.d.ts +2 -2
  35. package/dist/{mode-YNx2aOtQ.d.ts → mode-Lm9t4qzX.d.ts} +1 -1
  36. package/dist/orders/index.js +17 -1
  37. package/dist/orders/index.js.map +1 -1
  38. package/dist/orders/shipment-tracking.js +80 -0
  39. package/dist/orders/shipment-tracking.js.map +1 -0
  40. package/dist/promotions/use-promotion-validation.js +19 -16
  41. package/dist/promotions/use-promotion-validation.js.map +1 -1
  42. package/dist/{schema-Tc0qRs-Q.d.ts → schema-Dg0ZflMW.d.ts} +1 -0
  43. package/dist/server.d.ts +8 -2
  44. package/dist/server.js +2 -0
  45. package/dist/server.js.map +1 -1
  46. package/dist/shipping/format-shipping-option.js +28 -0
  47. package/dist/shipping/format-shipping-option.js.map +1 -1
  48. package/dist/shipping/messages.js +2 -0
  49. package/dist/shipping/messages.js.map +1 -1
  50. package/dist/shipping/option-id.js +7 -0
  51. package/dist/shipping/option-id.js.map +1 -0
  52. package/dist/shipping/shipping-calculation-reducer.js +61 -10
  53. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  54. package/dist/shipping/use-shipping-calculation.js +38 -5
  55. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  56. package/dist/stores/get-store-by-host.js +41 -6
  57. package/dist/stores/get-store-by-host.js.map +1 -1
  58. package/dist/stores/store-subdomain.js +25 -0
  59. package/dist/stores/store-subdomain.js.map +1 -0
  60. package/dist/stores/store-traffic.js +50 -0
  61. package/dist/stores/store-traffic.js.map +1 -0
  62. package/dist/stores/ttl-cache.js +34 -0
  63. package/dist/stores/ttl-cache.js.map +1 -0
  64. package/dist/theme/define.js.map +1 -1
  65. package/dist/theme/index.js.map +1 -1
  66. package/dist/theme/preview-bridge.js +33 -0
  67. package/dist/theme/preview-bridge.js.map +1 -0
  68. package/dist/theme/preview-cookie.js +13 -6
  69. package/dist/theme/preview-cookie.js.map +1 -1
  70. package/dist/theme/preview-host.js +7 -0
  71. package/dist/theme/preview-host.js.map +1 -0
  72. package/dist/theme/read-preview-host.js +10 -0
  73. package/dist/theme/read-preview-host.js.map +1 -0
  74. package/dist/theme/read-preview-token.js +5 -3
  75. package/dist/theme/read-preview-token.js.map +1 -1
  76. package/dist/theme/settings-context.js +14 -1
  77. package/dist/theme/settings-context.js.map +1 -1
  78. package/dist/theme.d.ts +65 -5
  79. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef))?.value;\n const refresh = req.cookies.get(refreshCookieName(storeRef))?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n jar.set(accessCookieName(storeRef), rotated.access_token);\n jar.set(refreshCookieName(storeRef), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAQ7B,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1B,SAAS,cAAc,OAAe,SAA0B;AACrE,MAAI;AACF,UAAM,UAAU,KAAK;AAAA,MACnB,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,IAC5D;AACA,QAAI,OAAO,QAAQ,QAAQ,SAAU,QAAO;AAC5C,WAAO,QAAQ,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaA,eAAsB,oBACpB,KACA,UAC+B;AAC/B,QAAM,SAAS,IAAI,QAAQ,IAAI,iBAAiB,QAAQ,CAAC,GAAG;AAC5D,QAAM,UAAU,IAAI,QAAQ,IAAI,kBAAkB,QAAQ,CAAC,GAAG;AAE9D,MAAI,CAAC,UAAU,CAAC,QAAS,QAAO;AAChC,MAAI,CAAC,cAAc,QAAQ,sBAAsB,EAAG,QAAO;AAE3D,MAAI;AACF,UAAM,MAAM,MAAM;AAAA,MAChB,GAAG,aAAa,EAAE,MAAM,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,MACtE;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,wBAAwB,aAAa,EAAE;AAAA;AAAA;AAAA;AAAA,UAIvC,GAAG,mBAAmB,IAAI,OAAO;AAAA,QACnC;AAAA,QACA,MAAM,KAAK,UAAU,EAAE,eAAe,QAAQ,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAO/C,QAAQ,YAAY,QAAQ,wBAAwB;AAAA,MACtD;AAAA,IACF;AAEA,QAAI,CAAC,IAAI,GAAI,QAAO;AAEpB,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,QAAI,MAAM,gBAAgB,MAAM,eAAe;AAC7C,aAAO;AAAA,QACL,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAkBO,SAAS,yBACd,KACA,YACA,UACA,SACS;AACT,QAAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,QAAI,IAAI,iBAAiB,QAAQ,GAAG,QAAQ,YAAY;AACxD,QAAI,IAAI,kBAAkB,QAAQ,GAAG,QAAQ,aAAa;AAC1D,YAAQ;AAAA,MACN;AAAA,MACA,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;A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K;AAC5B,QAAI,MAAM,gBAAgB,MAAM,eAAe;AAC7C,aAAO;AAAA,QACL,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,MACtB;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAkBO,SAAS,yBACd,KACA,YACA,UACA,SACS;AACT,QAAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,UAAQ,OAAO,yBAAyB;AAExC,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,UAAM,OAAO,eAAe,UAAU,UAAU;AAChD,QAAI,IAAI,iBAAiB,UAAU,IAAI,GAAG,QAAQ,YAAY;AAC9D,QAAI,IAAI,kBAAkB,UAAU,IAAI,GAAG,QAAQ,aAAa;AAChE,YAAQ;AAAA,MACN;AAAA,MACA,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,15 +1,19 @@
1
1
  import "server-only";
2
2
  import { cache } from "react";
3
3
  import { cookies, headers } from "next/headers";
4
- import { readAuthCookies } from "./cookies.js";
4
+ import { authCookiePathFor, readAuthCookies } from "./cookies.js";
5
5
  import { clientIpFrom } from "./client-ip.js";
6
6
  import { createAuthApi } from "./sdk.js";
7
7
  const getServerIdentity = cache(
8
8
  async (storeRef) => {
9
- const jar = await cookies();
10
- const tokens = readAuthCookies(jar, storeRef);
9
+ const requestHeaders = await headers();
10
+ const tokens = readAuthCookies(
11
+ await cookies(),
12
+ storeRef,
13
+ authCookiePathFor({ headers: requestHeaders }, storeRef)
14
+ );
11
15
  if (!tokens) return null;
12
- const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(
16
+ const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(
13
17
  tokens.access_token
14
18
  );
15
19
  return me.success ? me.data ?? null : null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n const jar = await cookies();\n const tokens = readAuthCookies(jar, storeRef);\n if (!tokens) return null;\n\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable — and the backend rate-limits this\n // call per `storeId:clientIp`, so it has to carry the shopper's address\n // like every other server-side auth call does.\n const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAC3D,UAAM,MAAM,MAAM,QAAQ;AAC1B,UAAM,SAAS,gBAAgB,KAAK,QAAQ;AAC5C,QAAI,CAAC,OAAQ,QAAO;AAMpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,MAAM,QAAQ,CAAC,CAAC,EAAE;AAAA,MACtE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,cAAc,CAAC,EAAE;AAAA,MACrE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
@@ -1,5 +1,12 @@
1
1
  const HANDOFF_KEY = "ecw:order-handoff";
2
2
  const MAX_AGE_MS = 24 * 60 * 60 * 1e3;
3
+ function isSummary(value) {
4
+ if (!value || typeof value !== "object") return false;
5
+ const s = value;
6
+ return typeof s.customer_name === "string" && typeof s.address === "string" && typeof s.payment_label === "string" && typeof s.subtotal === "number" && Array.isArray(s.items) && s.items.every(
7
+ (item) => !!item && typeof item === "object" && typeof item.name === "string" && typeof item.quantity === "number" && typeof item.price === "number"
8
+ );
9
+ }
3
10
  function writeOrderHandoff(handoff) {
4
11
  try {
5
12
  window.localStorage.setItem(
@@ -29,7 +36,8 @@ function readOrderHandoff(order_code) {
29
36
  function matchHandoff(parsed, order_code, now) {
30
37
  if (!parsed || typeof parsed !== "object") return null;
31
38
  const h = parsed;
32
- if (typeof h.order_code !== "string" || h.order_code !== order_code) return null;
39
+ if (typeof h.order_code !== "string" || h.order_code !== order_code)
40
+ return null;
33
41
  if (typeof h.payment_method !== "string" || h.payment_method.length === 0) {
34
42
  return null;
35
43
  }
@@ -43,6 +51,7 @@ function matchHandoff(parsed, order_code, now) {
43
51
  provider_code: typeof h.provider_code === "string" && h.provider_code.length > 0 ? h.provider_code : null,
44
52
  total: h.total,
45
53
  currency_code: typeof h.currency_code === "string" && h.currency_code.length > 0 ? h.currency_code : "VND",
54
+ summary: isSummary(h.summary) ? h.summary : null,
46
55
  written_at: h.written_at
47
56
  };
48
57
  }
@@ -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 /public/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\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 written_at: number;\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(order_code: string | null): 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) 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 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;AAa3B,SAAS,kBACd,SACM;AACN,MAAI;AACF,WA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AW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
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 /public/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":[]}
@@ -0,0 +1,16 @@
1
+ import { SHIPPING_ERROR_CODES } from "@ecomweb/sdk";
2
+ function quoteChangedOptionsFrom(error) {
3
+ if (!error || typeof error !== "object") return null;
4
+ const { code, details } = error;
5
+ if (code !== SHIPPING_ERROR_CODES.QUOTE_CHANGED) return null;
6
+ const raw = details?.options;
7
+ if (!Array.isArray(raw) || raw.length === 0) return null;
8
+ const valid = raw.every(
9
+ (o) => !!o && typeof o === "object" && typeof o.rate_id === "number" && typeof o.amount === "number"
10
+ );
11
+ return valid ? raw : null;
12
+ }
13
+ export {
14
+ quoteChangedOptionsFrom
15
+ };
16
+ //# sourceMappingURL=quote-changed.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/quote-changed.ts"],"sourcesContent":["import { SHIPPING_ERROR_CODES, type ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * The options the API now offers, read off a 409 SHIPPING_QUOTE_CHANGED.\n * Null for any other error, or when `details.options` is missing, empty or\n * has an entry without a numeric `rate_id` and `amount`; the caller then\n * treats it as a plain error. Duck-typed like `insufficientItemsFrom`.\n */\nexport function quoteChangedOptionsFrom(\n error: unknown\n): ShippingOption[] | null {\n if (!error || typeof error !== \"object\") return null;\n const { code, details } = error as { code?: unknown; details?: unknown };\n if (code !== SHIPPING_ERROR_CODES.QUOTE_CHANGED) return null;\n\n const raw = (details as { options?: unknown } | null | undefined)?.options;\n if (!Array.isArray(raw) || raw.length === 0) return null;\n\n const valid = raw.every(\n o =>\n !!o &&\n typeof o === \"object\" &&\n typeof (o as ShippingOption).rate_id === \"number\" &&\n typeof (o as ShippingOption).amount === \"number\"\n );\n return valid ? (raw as ShippingOption[]) : null;\n}\n"],"mappings":"AAAA,SAAS,4BAAiD;AAQnD,SAAS,wBACd,OACyB;AACzB,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,SAAS,qBAAqB,cAAe,QAAO;AAExD,QAAM,MAAO,SAAsD;AACnE,MAAI,CAAC,MAAM,QAAQ,GAAG,KAAK,IAAI,WAAW,EAAG,QAAO;AAEpD,QAAM,QAAQ,IAAI;AAAA,IAChB,OACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,OAAQ,EAAqB,YAAY,YACzC,OAAQ,EAAqB,WAAW;AAAA,EAC5C;AACA,SAAO,QAAS,MAA2B;AAC7C;","names":[]}
@@ -1,5 +1,8 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useRef, useState } from "react";
3
+ import {
4
+ SHIPPING_ERROR_CODES
5
+ } from "@ecomweb/sdk";
3
6
  import { useAuth } from "../auth/context.js";
4
7
  import { useCart } from "../cart/server-context.js";
5
8
  import { useNotify } from "../notices.js";
@@ -14,6 +17,7 @@ import {
14
17
  getPaymentRedirectIntent
15
18
  } from "./payment-redirect.js";
16
19
  import { startGatewayRedirect } from "./start-gateway-redirect.js";
20
+ import { quoteChangedOptionsFrom } from "./quote-changed.js";
17
21
  import { insufficientItemsFrom, stockIssuesByLine } from "./stock-issues.js";
18
22
  import { getPaymentMethod } from "./utils.js";
19
23
  const defaultNavigateToGateway = (url) => {
@@ -22,6 +26,7 @@ const defaultNavigateToGateway = (url) => {
22
26
  function useCheckout({
23
27
  province,
24
28
  ward,
29
+ includeCarrierOptions = false,
25
30
  navigateToGateway = defaultNavigateToGateway
26
31
  }) {
27
32
  const store = useStoreData();
@@ -59,7 +64,8 @@ function useCheckout({
59
64
  ward,
60
65
  subtotal,
61
66
  totalWeight,
62
- itemsCount: items.length
67
+ itemsCount: items.length,
68
+ includeCarrierOptions
63
69
  });
64
70
  const promotionState = usePromotionValidation({
65
71
  storeRef: store.ref,
@@ -109,7 +115,9 @@ function useCheckout({
109
115
  inFlight.current = true;
110
116
  setIsSubmitting(true);
111
117
  setStockIssues({});
118
+ const quoteRequestId = shippingQuote.currentRequestId();
112
119
  try {
120
+ const shippingOption = shippingQuote.selectedOption;
113
121
  const orderData = {
114
122
  cart_id: cartId || void 0,
115
123
  customer_name: input.fullName,
@@ -125,10 +133,17 @@ function useCheckout({
125
133
  // The shopper's choice of rate is real input; the API prices it and
126
134
  // rejects a rate_id that isn't one it just quoted for this address
127
135
  // and cart. useShippingCalculation clears the selection the moment an
128
- // input it was quoted against changes, so this is either null
129
- // (omitted, the API picks) or a rate from the matching quote.
130
- ...shippingQuote.selectedShippingRate && {
131
- shipping_rate_id: shippingQuote.selectedShippingRate
136
+ // input it was quoted against changes, so this is either nothing
137
+ // (omitted, the API picks) or an option from the matching quote.
138
+ // A carrier option also names its service and the amount the shopper
139
+ // saw; after a quote_changed that is the replaced amount, so the
140
+ // retry confirms the new price.
141
+ ...shippingOption && {
142
+ shipping_rate_id: shippingOption.rate_id,
143
+ ...shippingOption.carrier_service_id && {
144
+ shipping_service_id: shippingOption.carrier_service_id,
145
+ shipping_quoted_amount: shippingOption.amount
146
+ }
132
147
  },
133
148
  notes: input.notes || void 0,
134
149
  promotion_id: promotionState.appliedPromotion?.id || void 0,
@@ -167,7 +182,8 @@ function useCheckout({
167
182
  payment_method: input.paymentMethod,
168
183
  provider_code: method?.provider_code ?? null,
169
184
  total: Number(order.total ?? 0),
170
- currency_code: order.currency_code ?? "VND"
185
+ currency_code: order.currency_code ?? "VND",
186
+ summary: input.summary ?? null
171
187
  });
172
188
  clearCart(false);
173
189
  return {
@@ -181,9 +197,26 @@ function useCheckout({
181
197
  setStockIssues(issues);
182
198
  return { kind: "stock_issues", issues };
183
199
  }
200
+ const changed = quoteChangedOptionsFrom(error);
201
+ if (changed) {
202
+ shippingQuote.replaceOptions(
203
+ changed,
204
+ shippingQuote.selectedOptionId,
205
+ quoteRequestId
206
+ );
207
+ return { kind: "quote_changed" };
208
+ }
209
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
210
+ if (code === "ORDER_PROMOTION_NOT_APPLICABLE") {
211
+ promotionState.removePromoCode();
212
+ }
213
+ if (code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE || code === SHIPPING_ERROR_CODES.QUOTE_CHANGED) {
214
+ shippingQuote.retryCalculation();
215
+ }
184
216
  return {
185
217
  kind: "error",
186
- message: error instanceof Error ? error.message : String(error)
218
+ message: error instanceof Error ? error.message : String(error),
219
+ ...typeof code === "string" && { code }
187
220
  };
188
221
  } finally {
189
222
  inFlight.current = false;
@@ -215,7 +248,11 @@ function useCheckout({
215
248
  isCalculating: shippingQuote.isCalculatingShipping,
216
249
  hasCalculated: shippingQuote.hasCalculatedShipping,
217
250
  calculationFailed: shippingQuote.calculationFailed,
251
+ /** @deprecated Use selectOption. */
218
252
  selectRate: shippingQuote.handleShippingRateSelect,
253
+ selectedOptionId: shippingQuote.selectedOptionId,
254
+ selectedOption: shippingQuote.selectedOption,
255
+ selectOption: shippingQuote.handleShippingOptionSelect,
219
256
  retry: shippingQuote.retryCalculation
220
257
  },
221
258
  promotion: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PaymentMethod, StorePaymentMethod } from \"@ecomweb/sdk\";\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 { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\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\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.\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 }\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 /** 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 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 });\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 inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n\n try {\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 null\n // (omitted, the API picks) or a rate from the matching quote.\n ...(shippingQuote.selectedShippingRate && {\n shipping_rate_id: shippingQuote.selectedShippingRate,\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || 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 });\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 return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\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 selectRate: shippingQuote.handleShippingRateSelect,\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 plac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,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA,MACjC,YAAY,cAAc;AAAA,MAC1B,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 { 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 { 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 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 ...(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. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\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,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,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,QAA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mB,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":[]}
@@ -34,7 +34,13 @@ const serverConfigSchema = z.object({
34
34
  * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it
35
35
  * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.
36
36
  */
37
- clientIpHeader: z.enum(["x-forwarded-for", "cf-connecting-ip"])
37
+ clientIpHeader: z.enum(["x-forwarded-for", "cf-connecting-ip"]),
38
+ /**
39
+ * Requests a minute to one store, on one server, above which the
40
+ * multi-tenant middleware logs that store (log only, nothing is refused).
41
+ * 0 turns it off.
42
+ */
43
+ storeTrafficLogPerMinute: z.number().int().min(0)
38
44
  });
39
45
  class ConfigError extends Error {
40
46
  constructor(message) {
@@ -54,12 +60,17 @@ function parseOrThrow(schema, candidate, envNameOf) {
54
60
  ${lines.join("\n")}`
55
61
  );
56
62
  }
63
+ function countOf(v, fallback) {
64
+ const n = Number(v);
65
+ return v !== void 0 && Number.isInteger(n) && n >= 0 ? n : fallback;
66
+ }
57
67
  function sampleRateOf(v, fallback) {
58
68
  const n = Number(v);
59
69
  return v !== void 0 && Number.isFinite(n) && n >= 0 && n <= 1 ? n : fallback;
60
70
  }
61
71
  export {
62
72
  ConfigError,
73
+ countOf,
63
74
  envValue,
64
75
  logLevelOf,
65
76
  parseOrThrow,
@@ -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 platformApiKey: z.string().min(1),\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});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\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): 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 return ` - ${envNameOf[field] ?? field}: ${issue.message}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\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,KAAi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AAC;AAChE,CAAC;AAGM,MAAM,oBAAoB,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,aACd,QACA,WACA,WACG;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,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO;AAAA,EAC3D,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;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":[]}
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 platformApiKey: z.string().min(1),\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\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): 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 return ` - ${envNameOf[field] ?? field}: ${issue.message}`;\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;AAGA,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,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACrC,QAAQ;AAAA,EACR,cAAc,EAAE,OAAO;AAAA,EACvB,QAAQ;AAAA,EACR,kBAAkB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAClC,sBAAsB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACjD,gBAAgB,EAAE,OAAO,EAAE,SAAS;AAAA,EACpC,0BAA0B,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9C,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,UAAU,EAAE,KAAK,UAAU,EAAE,SAAS;AAAA,EACtC,qBAAqB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC;AAC9C,CAAC;AAGM,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,yBAAyB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAA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
5
  envValue,
5
6
  logLevelOf,
6
7
  parseOrThrow,
@@ -16,7 +17,11 @@ function parseMulti(env) {
16
17
  appEnv: envValue(env, "APP_ENV") ?? "unknown",
17
18
  googleVerification: envValue(env, "GOOGLE_VERIFICATION"),
18
19
  logLevel: logLevelOf(envValue(env, "LOG_LEVEL")),
19
- clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for"
20
+ clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for",
21
+ storeTrafficLogPerMinute: countOf(
22
+ envValue(env, "STORE_TRAFFIC_LOG_PER_MINUTE"),
23
+ 600
24
+ )
20
25
  },
21
26
  {
22
27
  platformApiKey: "PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY",
@@ -37,7 +42,9 @@ function parseSingle(env) {
37
42
  appEnv: envValue(env, "APP_ENV") ?? "production",
38
43
  googleVerification: envValue(env, "GOOGLE_VERIFICATION"),
39
44
  logLevel: logLevelOf(envValue(env, "LOG_LEVEL")),
40
- clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for"
45
+ clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for",
46
+ // One store per site: there are no neighbours to watch.
47
+ storeTrafficLogPerMinute: 0
41
48
  },
42
49
  {
43
50
  platformApiKey: "ECOMWEB_PUBLISHABLE_KEY",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\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 platformApiKey:\n envValue(env, \"PLATFORM_API_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_PLATFORM_API_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 },\n {\n platformApiKey: \"PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n // The key is publishable, and next.config inlines it at build time as\n // NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg\n // still runs when the runtime env does not repeat it.\n platformApiKey:\n envValue(env, \"ECOMWEB_PUBLISHABLE_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_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 },\n {\n platformApiKey: \"ECOMWEB_PUBLISHABLE_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 return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,gBACE,SAAS,KAAK,kBAAkB,KAChC,SAAS,KAAK,8BAA8B;AAAA,MAC9C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,cAAc,KAAK;AAAA,MAC7C,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA,IACvD;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAA8B;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,MAIE,gBACE,SAAS,KAAK,yBAAyB,KACvC,SAAS,KAAK,qCAAqC;AAAA,MACrD,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,UAAU,KAAK;AAAA,MACzC,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA,IACvD;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAEG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAEO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,GAAG,QAAQ;AAAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
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 platformApiKey:\n envValue(env, \"PLATFORM_API_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_PLATFORM_API_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 platformApiKey: \"PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n // The key is publishable, and next.config inlines it at build time as\n // NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg\n // still runs when the runtime env does not repeat it.\n platformApiKey:\n envValue(env, \"ECOMWEB_PUBLISHABLE_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_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 platformApiKey: \"ECOMWEB_PUBLISHABLE_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 return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,g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AAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
package/dist/config.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { E as EnvSource, P as PublicConfig } from './schema-Tc0qRs-Q.js';
2
- export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Tc0qRs-Q.js';
3
- export { S as StorefrontMode, r as resolveMode } from './mode-YNx2aOtQ.js';
1
+ import { E as EnvSource, P as PublicConfig } from './schema-Dg0ZflMW.js';
2
+ export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Dg0ZflMW.js';
3
+ export { S as StorefrontMode, r as resolveMode } from './mode-Lm9t4qzX.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Parses the variables of the mode `env` selects (see resolveMode). */