@ecomweb/storefront-kit 0.13.1 → 0.14.1

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 (42) hide show
  1. package/README.md +26 -0
  2. package/dist/api/response.js.map +1 -1
  3. package/dist/auth/context.js.map +1 -1
  4. package/dist/auth/sdk.js +6 -2
  5. package/dist/auth/sdk.js.map +1 -1
  6. package/dist/cart/server-context.js.map +1 -1
  7. package/dist/checkout/use-checkout.js.map +1 -1
  8. package/dist/client-info.js +7 -0
  9. package/dist/client-info.js.map +1 -0
  10. package/dist/config/schema.js.map +1 -1
  11. package/dist/config/server.js.map +1 -1
  12. package/dist/config/version-check.js +94 -0
  13. package/dist/config/version-check.js.map +1 -0
  14. package/dist/config.d.ts +73 -4
  15. package/dist/config.js +9 -0
  16. package/dist/config.js.map +1 -1
  17. package/dist/currency.js.map +1 -1
  18. package/dist/index.d.ts +306 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/logging.js.map +1 -1
  21. package/dist/middleware.d.ts +2 -2
  22. package/dist/middleware.js.map +1 -1
  23. package/dist/{mode-Lm9t4qzX.d.ts → mode-DXo-EhTJ.d.ts} +1 -1
  24. package/dist/orders/shipment-tracking.js.map +1 -1
  25. package/dist/provider.js.map +1 -1
  26. package/dist/{schema-Dg0ZflMW.d.ts → schema-DIF0CZNV.d.ts} +4 -0
  27. package/dist/sdk.js +5 -2
  28. package/dist/sdk.js.map +1 -1
  29. package/dist/server.d.ts +9 -1
  30. package/dist/server.js.map +1 -1
  31. package/dist/shipping/location-areas.js.map +1 -1
  32. package/dist/storage.js.map +1 -1
  33. package/dist/store/store-context.js.map +1 -1
  34. package/dist/store-scope/index.js.map +1 -1
  35. package/dist/stores/basic-settings.js.map +1 -1
  36. package/dist/stores/cached.js.map +1 -1
  37. package/dist/theme/define.js.map +1 -1
  38. package/dist/theme/index.js.map +1 -1
  39. package/dist/theme/settings-context.js.map +1 -1
  40. package/dist/theme/style.js.map +1 -1
  41. package/dist/theme.d.ts +33 -0
  42. package/package.json +5 -3
package/README.md CHANGED
@@ -166,3 +166,29 @@ component.
166
166
  Semver. Within 1.x no export is removed and no required prop or parameter
167
167
  is added. Before 1.0, a minor (0.x) release may break; your caret range
168
168
  (`^0.y.z`) only takes the patches of your minor.
169
+
170
+ ## Version reporting and update warnings
171
+
172
+ Every SDK request the kit makes sends
173
+ `X-Ecomweb-Client: @ecomweb/storefront-kit/<version> @ecomweb/sdk/<version>`
174
+ (versions baked in at build), so the dashboard can tell a store owner when the
175
+ storefront runs an old or insecure kit.
176
+
177
+ `checkClientVersions` (`@ecomweb/storefront-kit/config`) warns at build time.
178
+ Call it from `next.config.mjs` with Next's `phase`; it does nothing outside
179
+ `next build`, gives up after 2 s and never fails the build. Set
180
+ `ECOMWEB_SKIP_VERSION_CHECK=1` to turn it off.
181
+
182
+ ```js
183
+ import { checkClientVersions } from "@ecomweb/storefront-kit/config";
184
+
185
+ export default async function config(phase) {
186
+ await checkClientVersions({ phase, apiUrl: process.env.ECOMWEB_API_URL });
187
+ return nextConfig;
188
+ }
189
+ ```
190
+
191
+ To update: `ecomweb storefront upgrade`
192
+ ([guide](https://help.ecomweb.app/guides/storefront/upgrade-kit)); release
193
+ notes are the releases of
194
+ [ecomwebai/ecomweb-storefront-sdk](https://github.com/ecomwebai/ecomweb-storefront-sdk).
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/response.ts"],"sourcesContent":["import { ApiResponse } from \"../interfaces\";\n\nexport class ApiClientError extends Error {\n statusCode: number;\n code?: string;\n /**\n * A business error's structured payload, for example the per-line items of\n * an INSUFFICIENT_INVENTORY rejection. Carried here as well as on the SDK's\n * own error class because this repo has two: checkout's order creation\n * throws the SDK's, while the payment helpers throw this one. Dropping the\n * payload on one of them would lose it silently on whichever path a caller\n * happens to be using.\n */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n// Unwraps a successful response, throws if not successful\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Unwraps a response but returns null for specific status codes (default 404)\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Ensures the response is successful (useful for void endpoints)\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n"],"mappings":"AAEO,MAAM,uBAAuB,MAAM;AAAA,EACxC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA;AAAA,EACA,YAAY,SAAiB,aAAa,GAAG,MAAe,SAAmB;AAC7E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAGO,SAAS,OAAU,UAA6B;AACrD,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,aACd,UACA,kBAA4B,CAAC,GAAG,GACtB;AACV,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,MACE,CAAC,SAAS,WACV,SAAS,SACT,gBAAgB,SAAS,SAAS,MAAM,UAAU,GAClD;AACA,WAAO;AAAA,EACT;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,cAAc,UAAkC;AAC9D,MAAI,SAAS,QAAS;AACtB,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;","names":[]}
1
+ {"version":3,"sources":["../../src/api/response.ts"],"sourcesContent":["import { ApiResponse } from \"../interfaces\";\n\nexport class ApiClientError extends Error {\n statusCode: number;\n code?: string;\n /**\n * A business error's structured payload, for example the per-line items of\n * an INSUFFICIENT_INVENTORY rejection. Carried here as well as on the SDK's\n * own error class because this repo has two: checkout's order creation\n * throws the SDK's, while the payment helpers throw this one. Dropping the\n * payload on one of them would lose it silently on whichever path a caller\n * happens to be using.\n */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n// Unwraps a successful response, throws if not successful\n/**\n * Returns the data of a successful API response.\n *\n * @param response - A response from an SDK call.\n * @returns The response data.\n * @throws ApiClientError when the response failed, with the API's message, status code and error code.\n */\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Unwraps a response but returns null for specific status codes (default 404)\n/**\n * Returns the data of a successful API response, or `null` when the API\n * answered with one of the given status codes.\n *\n * @param response - A response from an SDK call.\n * @param nullStatusCodes - Statuses that mean \"nothing there\"; defaults to `[404]`.\n * @returns The response data, or `null` when not found.\n * @throws ApiClientError on any other API error.\n */\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Ensures the response is successful (useful for void endpoints)\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n"],"mappings":"AAEO,MAAM,uBAAuB,MAAM;AAAA,EACxC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA;AAAA,EACA,YAAY,SAAiB,aAAa,GAAG,MAAe,SAAmB;AAC7E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAUO,SAAS,OAAU,UAA6B;AACrD,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAYO,SAAS,aACd,UACA,kBAA4B,CAAC,GAAG,GACtB;AACV,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,MACE,CAAC,SAAS,WACV,SAAS,SACT,gBAAgB,SAAS,SAAS,MAAM,UAAU,GAClD;AACA,WAAO;AAAA,EACT;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,cAAc,UAAkC;AAC9D,MAAI,SAAS,QAAS;AACtB,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/context.tsx"],"sourcesContent":["\"use client\";\n\nimport type React from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { useStoreData } from \"../store/store-context\";\nimport { storeApiPath } from \"../store-scope\";\n\ninterface AuthError {\n message: string;\n code?: string;\n}\n\ninterface AuthContextType {\n user: CurrentIdentity | null;\n loading: boolean;\n isAnonymous: boolean;\n signIn: (\n email: string,\n password: string\n ) => Promise<{ error: AuthError | null }>;\n signUp: (\n email: string,\n password: string,\n name?: string\n ) => Promise<{ error: AuthError | null }>;\n sendLoginCode: (email: string) => Promise<{ error: AuthError | null }>;\n verifyOtp: (\n email: string,\n code: string\n ) => Promise<{ error: AuthError | null }>;\n signInWithGoogle: (nextPath?: string) => Promise<{ error: AuthError | null }>;\n signInAnonymously: () => Promise<{ error: AuthError | null }>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n const store = useStoreData();\n const storeRef = store.ref;\n const [user, setUser] = useState<CurrentIdentity | null>(null);\n const [loading, setLoading] = useState(true);\n\n const base = storeApiPath(storeRef, \"auth\");\n\n /** Tokens live in httpOnly cookies, so identity comes from the server. */\n const loadUser = useCallback(async () => {\n try {\n const res = await fetch(storeApiPath(storeRef, \"auth/session\"), {\n cache: \"no-store\",\n });\n setUser(res.ok ? ((await res.json()).identity ?? null) : null);\n } catch {\n setUser(null);\n } finally {\n setLoading(false);\n }\n }, [storeRef]);\n\n useEffect(() => {\n void loadUser();\n }, [loadUser]);\n\n const post = useCallback(\n async (\n action: string,\n body?: unknown\n ): Promise<{ error: AuthError | null }> => {\n const res = await fetch(`${base}/${action}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n\n if (!res.ok) {\n const payload = await res.json().catch(() => null);\n return { error: payload?.error ?? { message: \"Request failed\" } };\n }\n\n return { error: null };\n },\n [base]\n );\n\n const signIn = useCallback(\n async (email: string, password: string) => {\n const result = await post(\"login\", { email, password });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signUp = useCallback(\n async (email: string, password: string, name?: string) =>\n // Registration deliberately does not log the caller in. An anonymous\n // identity being upgraded is identified server-side from the session\n // cookie (lib/auth/route-handlers.ts), never from anything sent here.\n post(\"register\", { email, password, name }),\n [post]\n );\n\n const sendLoginCode = useCallback(\n async (email: string) => post(\"otp/request\", { email }),\n [post]\n );\n\n const verifyOtp = useCallback(\n async (email: string, code: string) => {\n const result = await post(\"otp/verify\", { email, code });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signInWithGoogle = useCallback(\n async (nextPath?: string) => {\n const res = await fetch(\n `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || \"/\")}`\n );\n\n if (!res.ok) return { error: { message: \"Google sign-in unavailable\" } };\n\n const { url } = await res.json();\n window.location.href = url;\n return { error: null };\n },\n [base]\n );\n\n const signInAnonymously = useCallback(async () => {\n const result = await post(\"anonymous\");\n if (!result.error) await loadUser();\n return result;\n }, [post, loadUser]);\n\n const signOut = useCallback(async () => {\n await post(\"logout\");\n setUser(null);\n }, [post]);\n\n const value: AuthContextType = {\n user,\n loading,\n isAnonymous: user?.is_anonymous ?? false,\n signIn,\n signUp,\n sendLoginCode,\n verifyOtp,\n signInWithGoogle,\n signInAnonymously,\n signOut,\n refresh: loadUser,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuth() {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error(\"useAuth must be used within an AuthProvider\");\n }\n return context;\n}\n"],"mappings":";AAoKS;AAjKT;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AA+B7B,MAAM,cAAc,cAA2C,MAAS;AAEjE,SAAS,aAAa,EAAE,SAAS,GAAkC;AACxE,QAAM,QAAQ,aAAa;AAC3B,QAAM,WAAW,MAAM;AACvB,QAAM,CAAC,MAAM,OAAO,IAAI,SAAiC,IAAI;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAE3C,QAAM,OAAO,aAAa,UAAU,MAAM;AAG1C,QAAM,WAAW,YAAY,YAAY;AACvC,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,aAAa,UAAU,cAAc,GAAG;AAAA,QAC9D,OAAO;AAAA,MACT,CAAC;AACD,cAAQ,IAAI,MAAO,MAAM,IAAI,KAAK,GAAG,YAAY,OAAQ,IAAI;AAAA,IAC/D,QAAQ;AACN,cAAQ,IAAI;AAAA,IACd,UAAE;AACA,iBAAW,KAAK;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,QAAQ,C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M,QAAQ;AAAA,EACjB;AAEA,QAAM,mBAAmB;AAAA,IACvB,OAAO,aAAsB;AAC3B,YAAM,MAAM,MAAM;AAAA,QAChB,GAAG,IAAI,2BAA2B,mBAAmB,YAAY,GAAG,CAAC;AAAA,MACvE;AAEA,UAAI,CAAC,IAAI,GAAI,QAAO,EAAE,OAAO,EAAE,SAAS,6BAA6B,EAAE;AAEvE,YAAM,EAAE,IAAI,IAAI,MAAM,IAAI,KAAK;AAC/B,aAAO,SAAS,OAAO;AACvB,aAAO,EAAE,OAAO,KAAK;AAAA,IACvB;AAAA,IACA,CAAC,IAAI;AAAA,EACP;AAEA,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,SAAS,MAAM,KAAK,WAAW;AACrC,QAAI,CAAC,OAAO,MAAO,OAAM,SAAS;AAClC,WAAO;AAAA,EACT,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,QAAM,UAAU,YAAY,YAAY;AACtC,UAAM,KAAK,QAAQ;AACnB,YAAQ,IAAI;AAAA,EACd,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,aAAa,MAAM,gBAAgB;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AAEA,SAAO,oBAAC,YAAY,UAAZ,EAAqB,OAAe,UAAS;AACvD;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/context.tsx"],"sourcesContent":["\"use client\";\n\nimport type React from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { useStoreData } from \"../store/store-context\";\nimport { storeApiPath } from \"../store-scope\";\n\ninterface AuthError {\n message: string;\n code?: string;\n}\n\ninterface AuthContextType {\n user: CurrentIdentity | null;\n loading: boolean;\n isAnonymous: boolean;\n signIn: (\n email: string,\n password: string\n ) => Promise<{ error: AuthError | null }>;\n signUp: (\n email: string,\n password: string,\n name?: string\n ) => Promise<{ error: AuthError | null }>;\n sendLoginCode: (email: string) => Promise<{ error: AuthError | null }>;\n verifyOtp: (\n email: string,\n code: string\n ) => Promise<{ error: AuthError | null }>;\n signInWithGoogle: (nextPath?: string) => Promise<{ error: AuthError | null }>;\n signInAnonymously: () => Promise<{ error: AuthError | null }>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n const store = useStoreData();\n const storeRef = store.ref;\n const [user, setUser] = useState<CurrentIdentity | null>(null);\n const [loading, setLoading] = useState(true);\n\n const base = storeApiPath(storeRef, \"auth\");\n\n /** Tokens live in httpOnly cookies, so identity comes from the server. */\n const loadUser = useCallback(async () => {\n try {\n const res = await fetch(storeApiPath(storeRef, \"auth/session\"), {\n cache: \"no-store\",\n });\n setUser(res.ok ? ((await res.json()).identity ?? null) : null);\n } catch {\n setUser(null);\n } finally {\n setLoading(false);\n }\n }, [storeRef]);\n\n useEffect(() => {\n void loadUser();\n }, [loadUser]);\n\n const post = useCallback(\n async (\n action: string,\n body?: unknown\n ): Promise<{ error: AuthError | null }> => {\n const res = await fetch(`${base}/${action}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n\n if (!res.ok) {\n const payload = await res.json().catch(() => null);\n return { error: payload?.error ?? { message: \"Request failed\" } };\n }\n\n return { error: null };\n },\n [base]\n );\n\n const signIn = useCallback(\n async (email: string, password: string) => {\n const result = await post(\"login\", { email, password });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signUp = useCallback(\n async (email: string, password: string, name?: string) =>\n // Registration deliberately does not log the caller in. An anonymous\n // identity being upgraded is identified server-side from the session\n // cookie (lib/auth/route-handlers.ts), never from anything sent here.\n post(\"register\", { email, password, name }),\n [post]\n );\n\n const sendLoginCode = useCallback(\n async (email: string) => post(\"otp/request\", { email }),\n [post]\n );\n\n const verifyOtp = useCallback(\n async (email: string, code: string) => {\n const result = await post(\"otp/verify\", { email, code });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signInWithGoogle = useCallback(\n async (nextPath?: string) => {\n const res = await fetch(\n `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || \"/\")}`\n );\n\n if (!res.ok) return { error: { message: \"Google sign-in unavailable\" } };\n\n const { url } = await res.json();\n window.location.href = url;\n return { error: null };\n },\n [base]\n );\n\n const signInAnonymously = useCallback(async () => {\n const result = await post(\"anonymous\");\n if (!result.error) await loadUser();\n return result;\n }, [post, loadUser]);\n\n const signOut = useCallback(async () => {\n await post(\"logout\");\n setUser(null);\n }, [post]);\n\n const value: AuthContextType = {\n user,\n loading,\n isAnonymous: user?.is_anonymous ?? false,\n signIn,\n signUp,\n sendLoginCode,\n verifyOtp,\n signInWithGoogle,\n signInAnonymously,\n signOut,\n refresh: loadUser,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n\n/**\n * The shopper's sign-in state and actions: `user`, `loading`, `isAnonymous`,\n * `signIn`, `signUp`, `sendLoginCode`, `verifyOtp`, `signInWithGoogle`,\n * `signInAnonymously`, `signOut` and `refresh`. The sign-in actions resolve to\n * `{ error }` and do not throw.\n *\n * Must run under {@link StorefrontKitProvider}, which includes the auth provider.\n *\n * @returns The auth context.\n * @throws When used outside the provider.\n */\nexport function useAuth() {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error(\"useAuth must be used within an AuthProvider\");\n }\n return context;\n}\n"],"mappings":";AAoKS;AAjKT;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA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tC,UAAM,KAAK,QAAQ;AACnB,YAAQ,IAAI;AAAA,EACd,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,aAAa,MAAM,gBAAgB;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AAEA,SAAO,oBAAC,YAAY,UAAZ,EAAqB,OAAe,UAAS;AACvD;AAaO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
package/dist/auth/sdk.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import "server-only";
2
- import { AuthApi } from "@ecomweb/sdk";
2
+ import { AuthApi, withClientHeader } from "@ecomweb/sdk";
3
3
  import { forwardingHeaders } from "./client-ip.js";
4
+ import { KIT_CLIENT_TOKEN } from "../client-info.js";
4
5
  import { publicConfig } from "../config.js";
5
6
  import { serverConfig } from "../config/server.js";
6
7
  import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
@@ -69,7 +70,10 @@ function authHttpClient(clientIp, previewToken) {
69
70
  };
70
71
  }
71
72
  function createAuthApi(storeRef, clientIp, previewToken) {
72
- return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);
73
+ return new AuthApi(
74
+ withClientHeader(authHttpClient(clientIp, previewToken), KIT_CLIENT_TOKEN),
75
+ storeRef
76
+ );
73
77
  }
74
78
  export {
75
79
  authHttpClient,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\n return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,eAAe;AAExB,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAQ9B,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAWO,SAAS,mBAA2B;AACzC,SAAO,aAAa,EAAE;AACxB;AAEA,eAAe,KACb,QACA,KACA,MACA,SACA,UACA,cACyB;AACzB,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,GAAG,IAAI;AAAA,MACxD;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,w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Q,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI,QAAQ,eAAe,UAAU,YAAY,GAAG,QAAQ;AACrE;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\n return new AuthApi(\n withClientHeader(authHttpClient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MACT,OAAO;AAAA,QACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI;AAAA,IACT,iBAAiB,eAAe,UAAU,YAAY,GAAG,gBAAgB;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n useRef,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n // The API returns lines in no fixed order, and an updated line moves.\n // Without this, the row under the shopper's finger swaps mid-tap.\n const inAddedOrder = [...cart.items].sort(\n (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)\n );\n const items: CartItem[] = inAddedOrder.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n // No cart for this identity. Keeping the state would show the\n // previous identity's items (guest before sign-in, account after\n // sign-out) as if they could be bought.\n dispatch({ type: \"CLEAR_CART\" });\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Shared while running: the provider's effect can fire twice for one sign-in.\n const movingGuestCart = useRef<Promise<void> | null>(null);\n\n /**\n * Signing in switches to the account's cart, so without this whatever the\n * shopper added as a guest disappears, even on checkout's own \"sign in and\n * come back\" link. Each line is added before it is removed, and a line that\n * cannot be added stays in the guest cart, so nothing is lost on a failure.\n */\n const moveGuestCartToAccount = useCallback(() => {\n if (!movingGuestCart.current) {\n movingGuestCart.current = (async () => {\n try {\n const guestCart = await cartApiService.getCart(storeRef, false);\n for (const item of guestCart?.items ?? []) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id ?? undefined,\n quantity: item.quantity,\n },\n true\n );\n await cartApiService.removeFromCart(storeRef, item.id, false);\n } catch (error) {\n console.error(\"Could not move a guest cart line:\", error);\n }\n }\n } catch (error) {\n console.error(\"Could not read the guest cart:\", error);\n } finally {\n movingGuestCart.current = null;\n }\n })();\n }\n return movingGuestCart.current;\n }, [storeRef]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n if (!storeRef || !isAuth || isBrowserStorePreview()) {\n loadCart();\n return;\n }\n dispatch({ type: \"SET_LOADING\", payload: true });\n moveGuestCartToAccount().then(loadCart);\n }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAkbI;AAhbJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAE/C,SAAS,sBAAoD;AA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,SAAS;AAAA,EACjB;AAEA,QAAM,aAAa,OAAO,YAAoB;AAC5C,QAAI,sBAAsB,GAAG;AAC3B,aAAO,8BAA8B;AACrC;AAAA,IACF;AACA,QAAI,CAAC,YAAY,CAAC,MAAM,UAAW;AAEnC,QAAI;AACF,YAAM,eAAe,WAAW,QAAQ;AAGxC,YAAM,SAAS;AAEf,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,KAAK;AAC7C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SACE;AAAA,IAAC,YAAY;AAAA,IAAZ;AAAA,MACC,OAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
1
+ {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n useRef,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n // The API returns lines in no fixed order, and an updated line moves.\n // Without this, the row under the shopper's finger swaps mid-tap.\n const inAddedOrder = [...cart.items].sort(\n (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)\n );\n const items: CartItem[] = inAddedOrder.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n // No cart for this identity. Keeping the state would show the\n // previous identity's items (guest before sign-in, account after\n // sign-out) as if they could be bought.\n dispatch({ type: \"CLEAR_CART\" });\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Shared while running: the provider's effect can fire twice for one sign-in.\n const movingGuestCart = useRef<Promise<void> | null>(null);\n\n /**\n * Signing in switches to the account's cart, so without this whatever the\n * shopper added as a guest disappears, even on checkout's own \"sign in and\n * come back\" link. Each line is added before it is removed, and a line that\n * cannot be added stays in the guest cart, so nothing is lost on a failure.\n */\n const moveGuestCartToAccount = useCallback(() => {\n if (!movingGuestCart.current) {\n movingGuestCart.current = (async () => {\n try {\n const guestCart = await cartApiService.getCart(storeRef, false);\n for (const item of guestCart?.items ?? []) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id ?? undefined,\n quantity: item.quantity,\n },\n true\n );\n await cartApiService.removeFromCart(storeRef, item.id, false);\n } catch (error) {\n console.error(\"Could not move a guest cart line:\", error);\n }\n }\n } catch (error) {\n console.error(\"Could not read the guest cart:\", error);\n } finally {\n movingGuestCart.current = null;\n }\n })();\n }\n return movingGuestCart.current;\n }, [storeRef]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n if (!storeRef || !isAuth || isBrowserStorePreview()) {\n loadCart();\n return;\n }\n dispatch({ type: \"SET_LOADING\", payload: true });\n moveGuestCartToAccount().then(loadCart);\n }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\n/**\n * The shopper's cart and the actions to change it: `items`, `itemCount`,\n * `subtotal`, `total`, `discountAmount`, `isLoading`, `addItem`, `removeItem`,\n * `updateQuantity`, `clearCart`, `refreshCart`, `mergeCarts` and\n * `reorderItems`. Amounts are in the store's currency.\n *\n * Must run under {@link StorefrontKitProvider}, which includes the cart provider.\n *\n * @returns The cart context.\n * @throws When used outside the provider.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useCart } from \"@ecomweb/storefront-kit\";\n *\n * export function CartBadge() {\n * const { itemCount, isLoading } = useCart();\n * return <span>{isLoading ? \"…\" : itemCount}</span>;\n * }\n * ```\n */\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAkbI;AAhbJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAE/C,SAAS,sBAAoD;AAqB7D,MAAM,cAAc,CAAC,OAAkB,WAAkC;AACvE,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,OAAO;AAAA,MACpB;AAAA,IAEF,KAAK,aAAa;AAChB,YAAM,OAAO,OAAO;AAGpB,YAAM,eAAe,CAAC,GAAG,KAAK,KAAK,EAAE;AAAA,QACnC,CAAC,GAAG,MAAM,KAAK,MAAM,EAAE,UAAU,IAAI,KAAK,MAAM,EAAE,UAAU;AAAA,MAC9D;AACA,YAAM,QAAoB,aAAa,IAAI,CAAC,UAAuB;AAAA,QACjE,IAAI,KAAK;AAAA,QACT,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,cAAc;AAAA,QAC9B,MAAM,KAAK;AAAA,QACX,OAAO,KAAK;AAAA,QACZ,eAAe,KAAK;AAAA,QACpB,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,YAAY,KAAK;AAAA,QACjB,eAAe,KAAK;AAAA,MACtB,EAAE;AAEF,aAAO;AAAA,QACL,GAAG;A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,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n // The API applies a discount-code promotion only when the code itself\n // comes with its id; older APIs ignore the field.\n promotion_code: promotionState.appliedPromotion?.code || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way. PROMOTION_IDENTITY_REQUIRED keeps the code: the\n // shopper only has to add an email and place again.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;AAiEjC,MAAM,2BAA2B,CAAC,QAAgB;AAChD,SAAO,SAAS,OAAO;AACzB;AAOO,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA,wBAAwB;AAAA,EACxB,oBAAoB;AACtB,GAAuB;AACrB,Q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C,UAAU;AACrE,aAAO,EAAE,MAAM,mBAAmB,WAAW,cAAc,WAAW;AAAA,IACxE,UAAE;AACA,4BAAsB,KAAK;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,eAAe,UAAU,CAAC;AAEhC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,MACR,KAAK,cAAc;AAAA,MACnB,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA;AAAA,MAEjC,YAAY,cAAc;AAAA,MAC1B,kBAAkB,cAAc;AAAA,MAChC,gBAAgB,cAAc;AAAA,MAC9B,cAAc,cAAc;AAAA,MAC5B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n SHIPPING_ERROR_CODES,\n type PaymentMethod,\n type StorePaymentMethod,\n} from \"@ecomweb/sdk\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"../stores/store-preview-guard\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff, type OrderHandoffSummary } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { quoteChangedOptionsFrom } from \"./quote-changed\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n /**\n * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\n * - quote_changed: nothing was placed; the shipping options were replaced with\n * the API's new prices and the selection kept where possible; show\n * `SHIPPING_MESSAGES.quoteChanged` and let the shopper place again.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string; code?: string }\n | { kind: \"quote_changed\" }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /**\n * Ask the API for carrier-quoted shipping options too. Off by default;\n * passed to `useShippingCalculation`.\n */\n includeCarrierOptions?: boolean;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n *\n * Must run under {@link StorefrontKitProvider}, which supplies the store, auth\n * and cart it reads.\n *\n * @param options - The address codes shipping is quoted for, and optional\n * carrier quotes and gateway navigation ({@link UseCheckoutOptions}).\n * @returns The cart `items`, `paymentMethods`, `shipping`, `promotion` and\n * `totals` state, `stockIssues`, and `placeOrder` with the payment redirect\n * helpers.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useCheckout } from \"@ecomweb/storefront-kit\";\n *\n * export function PlaceOrderButton({ province, ward, form }) {\n * const checkout = useCheckout({ province, ward });\n * return (\n * <button\n * disabled={checkout.isSubmitting}\n * onClick={() => checkout.placeOrder(form)}\n * >\n * Pay {checkout.totals.total}\n * </button>\n * );\n * }\n * ```\n */\nexport function useCheckout({\n province,\n ward,\n includeCarrierOptions = false,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n includeCarrierOptions,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n // A preview is read-only: the API would refuse the order anyway.\n if (isBrowserStorePreview()) {\n return {\n kind: \"error\",\n message: STORE_PREVIEW_READ_ONLY_MESSAGE,\n code: \"STORE_COMING_SOON\",\n };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n // The quote this attempt is made against. A reply that lands after the\n // shopper changed the address must not overwrite the newer options.\n const quoteRequestId = shippingQuote.currentRequestId();\n\n try {\n const shippingOption = shippingQuote.selectedOption;\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either nothing\n // (omitted, the API picks) or an option from the matching quote.\n // A carrier option also names its service and the amount the shopper\n // saw; after a quote_changed that is the replaced amount, so the\n // retry confirms the new price.\n ...(shippingOption && {\n shipping_rate_id: shippingOption.rate_id,\n ...(shippingOption.carrier_service_id && {\n shipping_service_id: shippingOption.carrier_service_id,\n shipping_quoted_amount: shippingOption.amount,\n }),\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n // The API applies a discount-code promotion only when the code itself\n // comes with its id; older APIs ignore the field.\n promotion_code: promotionState.appliedPromotion?.code || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n summary: input.summary ?? null,\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n // The carrier's price moved since the shopper saw it. Show the new\n // options (selection kept where possible) and let them place again.\n const changed = quoteChangedOptionsFrom(error);\n if (changed) {\n shippingQuote.replaceOptions(\n changed,\n shippingQuote.selectedOptionId,\n quoteRequestId\n );\n return { kind: \"quote_changed\" };\n }\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown (or the code is used up). Keeping the code would fail every\n // retry the same way. PROMOTION_IDENTITY_REQUIRED keeps the code: the\n // shopper only has to add an email and place again.\n if (\n code === \"ORDER_PROMOTION_NOT_APPLICABLE\" ||\n code === \"PROMOTION_USAGE_LIMIT_REACHED\"\n ) {\n promotionState.removePromoCode();\n }\n // The carrier could not price the chosen option, or reported a changed\n // quote we cannot use: refresh the options so the shopper can pick\n // again instead of being stuck on a stale list.\n if (\n code === SHIPPING_ERROR_CODES.RATE_UNAVAILABLE ||\n code === SHIPPING_ERROR_CODES.QUOTE_CHANGED\n ) {\n shippingQuote.retryCalculation();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n /** @deprecated Use selectOption. */\n selectRate: shippingQuote.handleShippingRateSelect,\n selectedOptionId: shippingQuote.selectedOptionId,\n selectedOption: shippingQuote.selectedOption,\n selectOption: shippingQuote.handleShippingOptionSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AACzD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,yBAAmD;AAC5D;AAAA,EACE;AAAA,OAEK;AACP,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,yBAAyB;AACzD,SAAS,wBAAwB;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A,EACF;AACF;","names":[]}
@@ -0,0 +1,7 @@
1
+ const KIT_VERSION = true ? "0.14.1" : "dev";
2
+ const KIT_CLIENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;
3
+ export {
4
+ KIT_CLIENT_TOKEN,
5
+ KIT_VERSION
6
+ };
7
+ //# sourceMappingURL=client-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client-info.ts"],"sourcesContent":["// Replaced at build time (tsup `define`, and the workspace's Next and vitest\n// configs) with this package's version from package.json.\ndeclare const __ECOMWEB_KIT_VERSION__: string | undefined;\n\n/**\n * This package's version, baked in at build time. `dev` when the source runs\n * without the define (the API ignores a version that isn't semver).\n */\nexport const KIT_VERSION: string =\n typeof __ECOMWEB_KIT_VERSION__ === \"string\" ? __ECOMWEB_KIT_VERSION__ : \"dev\";\n\n/** The kit's token in `X-Ecomweb-Client`, put before the SDK's own. */\nexport const KIT_CLIENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;\n"],"mappings":"AAQO,MAAM,cACX,OAA8C,WAA0B;AAGnE,MAAM,mBAAmB,2BAA2B,WAAW;","names":[]}
@@ -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 /**\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,EAA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
+ {"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\n/**\n * Thrown when the storefront's environment variables are missing or invalid.\n * The message names the variable behind every bad field.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>\n): 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,UAA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AO;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;AAGO,SAAS,QAAQ,GAAuB,UAA0B;AACvE,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,UAAU,CAAC,KAAK,KAAK,IAAI,IAAI;AAChE;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n 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_PU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AAkB,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\n/**\n * The server's parsed configuration, read from the environment on the first\n * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`\n * in server code, never in a client component.\n *\n * @returns The validated server config.\n * @throws ConfigError when a required variable is missing or invalid.\n */\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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AS;AACX;AAUO,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":[]}
@@ -0,0 +1,94 @@
1
+ import { SDK_VERSION } from "@ecomweb/sdk";
2
+ import { KIT_VERSION } from "../client-info.js";
3
+ const PRODUCTION_BUILD_PHASE = "phase-production-build";
4
+ const DEFAULT_API_URL = "https://apibase.ecomweb.app/api/v1";
5
+ const DEFAULT_TIMEOUT_MS = 2e3;
6
+ const CHECKED_FLAG = "__ECOMWEB_VERSION_CHECKED";
7
+ const KIT_PACKAGE = "@ecomweb/storefront-kit";
8
+ const SDK_PACKAGE = "@ecomweb/sdk";
9
+ function parseSemver(v) {
10
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v?.trim() ?? "");
11
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
12
+ }
13
+ function isBelow(a, b) {
14
+ const x = parseSemver(a);
15
+ const y = parseSemver(b);
16
+ if (!x || !y) return false;
17
+ for (let i = 0; i < 3; i++) {
18
+ if (x[i] !== y[i]) return x[i] < y[i];
19
+ }
20
+ return false;
21
+ }
22
+ function judge(pkg, installed, body) {
23
+ if (!parseSemver(installed)) return null;
24
+ const policy = body.packages?.[pkg];
25
+ if (!policy) return null;
26
+ const advisories = (body.advisories ?? []).filter(
27
+ (a) => a.package === pkg && isBelow(installed, a.fixed_in)
28
+ );
29
+ const status = isBelow(installed, policy.security_minimum) ? "security_update" : isBelow(installed, policy.minimum_supported) ? "unsupported" : isBelow(installed, policy.latest) ? "update_available" : "up_to_date";
30
+ return {
31
+ status,
32
+ package: pkg,
33
+ installed,
34
+ latest: policy.latest,
35
+ advisories,
36
+ upgradeGuideUrl: body.upgrade_guide_url
37
+ };
38
+ }
39
+ const SEVERITY = {
40
+ up_to_date: 0,
41
+ update_available: 1,
42
+ unsupported: 2,
43
+ security_update: 3
44
+ };
45
+ function formatClientVersionWarning(report) {
46
+ const behind = `${report.package} ${report.installed}`;
47
+ const latest = report.latest ? ` (latest ${report.latest})` : "";
48
+ const headline = report.status === "security_update" ? `ecomweb: security update available: ${behind} has known security issues${latest}.` : report.status === "unsupported" ? `ecomweb: ${behind} is no longer supported${latest}.` : `ecomweb: update available: ${behind}${latest}.`;
49
+ const lines = [headline];
50
+ for (const a of report.advisories) {
51
+ const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : "";
52
+ lines.push(` - ${a.summary ?? a.id ?? "advisory"}${fixed}`);
53
+ }
54
+ lines.push(" Update with: ecomweb storefront upgrade");
55
+ if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);
56
+ lines.push(" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)");
57
+ return lines.join("\n");
58
+ }
59
+ async function checkClientVersions(options = {}) {
60
+ const env = options.env ?? process.env;
61
+ if (options.phase !== PRODUCTION_BUILD_PHASE) return null;
62
+ if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === "1") return null;
63
+ if (env[CHECKED_FLAG] === "1") return null;
64
+ env[CHECKED_FLAG] = "1";
65
+ try {
66
+ const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\/+$/, "");
67
+ const doFetch = options.fetch ?? fetch;
68
+ const response = await doFetch(`${base}/public/storefront-clients/versions`, {
69
+ headers: { accept: "application/json" },
70
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
71
+ });
72
+ if (!response.ok) return null;
73
+ const body = await response.json();
74
+ const reports = [
75
+ judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),
76
+ judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body)
77
+ ].filter((r) => r !== null);
78
+ if (reports.length === 0) return null;
79
+ const worst = reports.reduce(
80
+ (a, b) => SEVERITY[b.status] > SEVERITY[a.status] ? b : a
81
+ );
82
+ if (worst.status !== "up_to_date") {
83
+ (options.warn ?? console.warn)(formatClientVersionWarning(worst));
84
+ }
85
+ return worst;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ export {
91
+ checkClientVersions,
92
+ formatClientVersionWarning
93
+ };
94
+ //# sourceMappingURL=version-check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/version-check.ts"],"sourcesContent":["import { SDK_VERSION } from \"@ecomweb/sdk\";\nimport { KIT_VERSION } from \"../client-info\";\nimport type { EnvSource } from \"./schema\";\n\n/** Next's `phase` for `next build` (next/constants PHASE_PRODUCTION_BUILD). */\nconst PRODUCTION_BUILD_PHASE = \"phase-production-build\";\nconst DEFAULT_API_URL = \"https://apibase.ecomweb.app/api/v1\";\nconst DEFAULT_TIMEOUT_MS = 2000;\n// Set once a build has checked, so Next's build workers (which load the\n// config again and inherit the env) stay quiet.\nconst CHECKED_FLAG = \"__ECOMWEB_VERSION_CHECKED\";\n\nconst KIT_PACKAGE = \"@ecomweb/storefront-kit\";\nconst SDK_PACKAGE = \"@ecomweb/sdk\";\n\ninterface PackagePolicy {\n latest?: string;\n minimum_supported?: string;\n security_minimum?: string;\n}\n\ninterface Advisory {\n id?: string;\n package?: string;\n fixed_in?: string;\n severity?: string;\n summary?: string;\n url?: string;\n}\n\ninterface VersionsResponse {\n packages?: Record<string, PackagePolicy | undefined>;\n advisories?: Advisory[];\n upgrade_guide_url?: string;\n}\n\nexport type ClientVersionStatus =\n | \"up_to_date\"\n | \"update_available\"\n | \"unsupported\"\n | \"security_update\";\n\nexport interface ClientVersionReport {\n status: ClientVersionStatus;\n /** The package judged: the kit, or the SDK when the kit is current. */\n package: string;\n installed: string;\n latest?: string;\n advisories: Advisory[];\n upgradeGuideUrl?: string;\n}\n\nexport interface CheckClientVersionsOptions {\n /** Next's config `phase`; the check runs only for `next build`. */\n phase?: string;\n /** The API base, `/api/v1` included. Defaults to production. */\n apiUrl?: string;\n env?: EnvSource;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Where the warning goes; `console.warn` by default. */\n warn?: (message: string) => void;\n /** Overrides the baked-in versions (tests). */\n installed?: { kit?: string; sdk?: string };\n}\n\ntype Semver = [number, number, number];\n\nfunction parseSemver(v: string | undefined): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v?.trim() ?? \"\");\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/** True when `a` is a lower version than `b`; false if either isn't semver. */\nfunction isBelow(a: string, b: string | undefined): boolean {\n const x = parseSemver(a);\n const y = parseSemver(b);\n if (!x || !y) return false;\n for (let i = 0; i < 3; i++) {\n if (x[i] !== y[i]) return x[i] < y[i];\n }\n return false;\n}\n\nfunction judge(\n pkg: string,\n installed: string,\n body: VersionsResponse\n): ClientVersionReport | null {\n if (!parseSemver(installed)) return null;\n const policy = body.packages?.[pkg];\n if (!policy) return null;\n const advisories = (body.advisories ?? []).filter(\n a => a.package === pkg && isBelow(installed, a.fixed_in)\n );\n const status: ClientVersionStatus = isBelow(installed, policy.security_minimum)\n ? \"security_update\"\n : isBelow(installed, policy.minimum_supported)\n ? \"unsupported\"\n : isBelow(installed, policy.latest)\n ? \"update_available\"\n : \"up_to_date\";\n return {\n status,\n package: pkg,\n installed,\n latest: policy.latest,\n advisories,\n upgradeGuideUrl: body.upgrade_guide_url,\n };\n}\n\nconst SEVERITY: Record<ClientVersionStatus, number> = {\n up_to_date: 0,\n update_available: 1,\n unsupported: 2,\n security_update: 3,\n};\n\n/**\n * Turns a version report into the multi-line warning that\n * {@link checkClientVersions} prints: the headline, one line per advisory and\n * how to update.\n *\n * @param report - The report to describe.\n * @returns The warning text, ready for `console.warn`.\n */\nexport function formatClientVersionWarning(report: ClientVersionReport): string {\n const behind = `${report.package} ${report.installed}`;\n const latest = report.latest ? ` (latest ${report.latest})` : \"\";\n const headline =\n report.status === \"security_update\"\n ? `ecomweb: security update available: ${behind} has known security issues${latest}.`\n : report.status === \"unsupported\"\n ? `ecomweb: ${behind} is no longer supported${latest}.`\n : `ecomweb: update available: ${behind}${latest}.`;\n const lines = [headline];\n for (const a of report.advisories) {\n const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : \"\";\n lines.push(` - ${a.summary ?? a.id ?? \"advisory\"}${fixed}`);\n }\n lines.push(\" Update with: ecomweb storefront upgrade\");\n if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);\n lines.push(\" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Checks the installed kit and SDK against the platform's supported versions\n * and prints a warning when they are behind. For `next.config.mjs`:\n *\n * ```js\n * export default async function config(phase) {\n * await checkClientVersions({ phase, apiUrl: API_URL });\n * return nextConfig;\n * }\n * ```\n *\n * Runs during `next build` only, once per build, and never fails or slows it\n * beyond the timeout (2 s): any error is ignored. Off with\n * `ECOMWEB_SKIP_VERSION_CHECK=1`. Returns the report, or null when it did not\n * check.\n */\nexport async function checkClientVersions(\n options: CheckClientVersionsOptions = {}\n): Promise<ClientVersionReport | null> {\n const env = options.env ?? process.env;\n if (options.phase !== PRODUCTION_BUILD_PHASE) return null;\n if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === \"1\") return null;\n if (env[CHECKED_FLAG] === \"1\") return null;\n env[CHECKED_FLAG] = \"1\";\n\n try {\n const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const response = await doFetch(`${base}/public/storefront-clients/versions`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n if (!response.ok) return null;\n const body = (await response.json()) as VersionsResponse;\n\n const reports = [\n judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),\n judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body),\n ].filter((r): r is ClientVersionReport => r !== null);\n if (reports.length === 0) return null;\n\n const worst = reports.reduce((a, b) =>\n SEVERITY[b.status] > SEVERITY[a.status] ? b : a\n );\n if (worst.status !== \"up_to_date\") {\n // A build-time notice for the developer, not runtime logging.\n // eslint-disable-next-line no-console\n (options.warn ?? console.warn)(formatClientVersionWarning(worst));\n }\n return worst;\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAI5B,MAAM,yBAAyB;AAC/B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAG3B,MAAM,eAAe;AAErB,MAAM,cAAc;AACpB,MAAM,cAAc;AAuDpB,SAAS,YAAY,GAAsC;AACzD,QAAM,IAAI,yBAAyB,KAAK,GAAG,KAAK,KAAK,EAAE;AACvD,SAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI;AAC1D;AAGA,SAAS,QAAQ,GAAW,GAAgC;AAC1D,QAAM,IAAI,YAAY,CAAC;AACvB,QAAM,IAAI,YAAY,CAAC;AACvB,MAAI,CAAC,KAAK,CAAC,EAAG,QAAO;AACrB,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,QAAI,EAAE,CAAC,MAAM,EAAE,CAAC,EAAG,QAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AAAA,EACtC;AACA,SAAO;AACT;AAEA,SAAS,MACP,KACA,WACA,MAC4B;AAC5B,MAAI,CAAC,YAAY,SAAS,EAAG,QAAO;AACpC,QAAM,SAAS,KAAK,WAAW,GAAG;AAClC,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,cAAc,KAAK,cAAc,CAAC,GAAG;AAAA,IACzC,OAAK,EAAE,YAAY,OAAO,QAAQ,WAAW,EAAE,QAAQ;AAAA,EACzD;AACA,QAAM,SAA8B,QAAQ,WAAW,OAAO,gBAAgB,IAC1E,oBACA,QAAQ,W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