@ecomweb/storefront-kit 0.14.0 → 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.
@@ -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,GAAk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M,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,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,CAAC;AAEb,YAAU,MAAM;AACd,SAAK,SAAS;AAAA,EAChB,GAAG,CAAC,QAAQ,CAAC;AAEb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AAM,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;AAaO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;","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;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;AAAA,QACH;AAAA,QACA,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,kBAAkB,KAAK;AAAA,QACvB,gBAAgB,KAAK;AAAA,QACrB,aAAa,KAAK;AAAA,QAClB,WAAW,KAAK;AAAA,QAChB,QAAQ,KAAK;AAAA,QACb,WAAW;AAAA,MACb;AAAA,IACF;AAAA,IAEA,KAAK;AACH,aAAO;A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;AAAA,UACP,aAAa;AAAA,QACf,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,cAAc,YAAY;AAC9B,UAAM,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,QAC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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;AAwBO,SAAS,UAAU;AACxB,QAAM,UAAU,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;A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AA,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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AA,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,4 +1,4 @@
1
- const KIT_VERSION = true ? "0.14.0" : "dev";
1
+ const KIT_VERSION = true ? "0.14.1" : "dev";
2
2
  const KIT_CLIENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;
3
3
  export {
4
4
  KIT_CLIENT_TOKEN,
@@ -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":"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,UAAU,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMtC,gBAAgB,EAAE,KAAK,CAAC,mBAAmB,kBAAkB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9D,0BAA0B,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAClD,CAAC;AAGM,MAAM,oBAAoB,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,aACd,QACA,WACA,WACG;AACH,QAAM,SAAS,OAAO,UAAU,SAAS;AACzC,MAAI,OAAO,QAAS,QAAO,OAAO;AAClC,QAAM,QAAQ,OAAO,MAAM,OAAO,IAAI,WAAS;AAC7C,UAAM,QAAQ,OAAO,MAAM,KAAK,CAAC,KAAK,EAAE;AACxC,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO;AAAA,EAC3D,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;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
+ {"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,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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AAC;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_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,gBACE,SAAS,KAAK,kBAAkB,KAChC,SAAS,K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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;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,gBACE,SAAS,KAAK,kBAAkB,KAChC,SAAS,KAAK,8BAA8B;AAAA,MAC9C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,cAAc,KAAK;AAAA,MAC7C,QAAQ,SAAS,KAA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_VERSION } from \"@ecomweb/sdk\";\nimport { KIT_VERSION } from \"../client-info\";\nimport type { EnvSource } from \"./schema\";\n\n/** Next's `phase` for `next build` (next/constants PHASE_PRODUCTION_BUILD). */\nconst PRODUCTION_BUILD_PHASE = \"phase-production-build\";\nconst DEFAULT_API_URL = \"https://apibase.ecomweb.app/api/v1\";\nconst DEFAULT_TIMEOUT_MS = 2000;\n// Set once a build has checked, so Next's build workers (which load the\n// config again and inherit the env) stay quiet.\nconst CHECKED_FLAG = \"__ECOMWEB_VERSION_CHECKED\";\n\nconst KIT_PACKAGE = \"@ecomweb/storefront-kit\";\nconst SDK_PACKAGE = \"@ecomweb/sdk\";\n\ninterface PackagePolicy {\n latest?: string;\n minimum_supported?: string;\n security_minimum?: string;\n}\n\ninterface Advisory {\n id?: string;\n package?: string;\n fixed_in?: string;\n severity?: string;\n summary?: string;\n url?: string;\n}\n\ninterface VersionsResponse {\n packages?: Record<string, PackagePolicy | undefined>;\n advisories?: Advisory[];\n upgrade_guide_url?: string;\n}\n\nexport type ClientVersionStatus =\n | \"up_to_date\"\n | \"update_available\"\n | \"unsupported\"\n | \"security_update\";\n\nexport interface ClientVersionReport {\n status: ClientVersionStatus;\n /** The package judged: the kit, or the SDK when the kit is current. */\n package: string;\n installed: string;\n latest?: string;\n advisories: Advisory[];\n upgradeGuideUrl?: string;\n}\n\nexport interface CheckClientVersionsOptions {\n /** Next's config `phase`; the check runs only for `next build`. */\n phase?: string;\n /** The API base, `/api/v1` included. Defaults to production. */\n apiUrl?: string;\n env?: EnvSource;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Where the warning goes; `console.warn` by default. */\n warn?: (message: string) => void;\n /** Overrides the baked-in versions (tests). */\n installed?: { kit?: string; sdk?: string };\n}\n\ntype Semver = [number, number, number];\n\nfunction parseSemver(v: string | undefined): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v?.trim() ?? \"\");\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/** True when `a` is a lower version than `b`; false if either isn't semver. */\nfunction isBelow(a: string, b: string | undefined): boolean {\n const x = parseSemver(a);\n const y = parseSemver(b);\n if (!x || !y) return false;\n for (let i = 0; i < 3; i++) {\n if (x[i] !== y[i]) return x[i] < y[i];\n }\n return false;\n}\n\nfunction judge(\n pkg: string,\n installed: string,\n body: VersionsResponse\n): ClientVersionReport | null {\n if (!parseSemver(installed)) return null;\n const policy = body.packages?.[pkg];\n if (!policy) return null;\n const advisories = (body.advisories ?? []).filter(\n a => a.package === pkg && isBelow(installed, a.fixed_in)\n );\n const status: ClientVersionStatus = isBelow(installed, policy.security_minimum)\n ? \"security_update\"\n : isBelow(installed, policy.minimum_supported)\n ? \"unsupported\"\n : isBelow(installed, policy.latest)\n ? \"update_available\"\n : \"up_to_date\";\n return {\n status,\n package: pkg,\n installed,\n latest: policy.latest,\n advisories,\n upgradeGuideUrl: body.upgrade_guide_url,\n };\n}\n\nconst SEVERITY: Record<ClientVersionStatus, number> = {\n up_to_date: 0,\n update_available: 1,\n unsupported: 2,\n security_update: 3,\n};\n\nexport function formatClientVersionWarning(report: ClientVersionReport): string {\n const behind = `${report.package} ${report.installed}`;\n const latest = report.latest ? ` (latest ${report.latest})` : \"\";\n const headline =\n report.status === \"security_update\"\n ? `ecomweb: security update available: ${behind} has known security issues${latest}.`\n : report.status === \"unsupported\"\n ? `ecomweb: ${behind} is no longer supported${latest}.`\n : `ecomweb: update available: ${behind}${latest}.`;\n const lines = [headline];\n for (const a of report.advisories) {\n const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : \"\";\n lines.push(` - ${a.summary ?? a.id ?? \"advisory\"}${fixed}`);\n }\n lines.push(\" Update with: ecomweb storefront upgrade\");\n if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);\n lines.push(\" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)\");\n return lines.join(\"\\n\");\n}\n\n/**\n * Checks the installed kit and SDK against the platform's supported versions\n * and prints a warning when they are behind. For `next.config.mjs`:\n *\n * ```js\n * export default async function config(phase) {\n * await checkClientVersions({ phase, apiUrl: API_URL });\n * return nextConfig;\n * }\n * ```\n *\n * Runs during `next build` only, once per build, and never fails or slows it\n * beyond the timeout (2 s): any error is ignored. Off with\n * `ECOMWEB_SKIP_VERSION_CHECK=1`. Returns the report, or null when it did not\n * check.\n */\nexport async function checkClientVersions(\n options: CheckClientVersionsOptions = {}\n): Promise<ClientVersionReport | null> {\n const env = options.env ?? process.env;\n if (options.phase !== PRODUCTION_BUILD_PHASE) return null;\n if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === \"1\") return null;\n if (env[CHECKED_FLAG] === \"1\") return null;\n env[CHECKED_FLAG] = \"1\";\n\n try {\n const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const response = await doFetch(`${base}/public/storefront-clients/versions`, {\n headers: { accept: \"application/json\" },\n signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n });\n if (!response.ok) return null;\n const body = (await response.json()) as VersionsResponse;\n\n const reports = [\n judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),\n judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body),\n ].filter((r): r is ClientVersionReport => r !== null);\n if (reports.length === 0) return null;\n\n const worst = reports.reduce((a, b) =>\n SEVERITY[b.status] > SEVERITY[a.status] ? b : a\n );\n if (worst.status !== \"up_to_date\") {\n // A build-time notice for the developer, not runtime logging.\n // eslint-disable-next-line no-console\n (options.warn ?? 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,M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M,aAAa,QAAQ,WAAW,OAAO,aAAa,IAAI;AAAA,IAChE,EAAE,OAAO,CAAC,MAAgC,MAAM,IAAI;AACpD,QAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,UAAM,QAAQ,QAAQ;AAAA,MAAO,CAAC,GAAG,MAC/B,SAAS,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,IAAI,IAAI;AAAA,IAChD;AACA,QAAI,MAAM,WAAW,cAAc;AAGjC,OAAC,QAAQ,QAAQ,QAAQ,MAAM,2BAA2B,KAAK,CAAC;AAAA,IAClE;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
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,O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,UAAU,uBAAwB,QAAO;AACrD,MAAI,IAAI,4BAA4B,KAAK,MAAM,IAAK,QAAO;AAC3D,MAAI,IAAI,YAAY,MAAM,IAAK,QAAO;AACtC,MAAI,YAAY,IAAI;AAEpB,MAAI;AACF,UAAM,QAAQ,QAAQ,QAAQ,KAAK,KAAK,iBAAiB,QAAQ,QAAQ,EAAE;AAC3E,UAAM,UAAU,QAAQ,SAAS;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,IAAI,uCAAuC;AAAA,MAC3E,SAAS,EAAE,QAAQ,mBAAmB;AAAA,MACtC,QAAQ,YAAY,QAAQ,QAAQ,aAAa,kBAAkB;AAAA,IACrE,CAAC;AACD,QAAI,CAAC,SAAS,GAAI,QAAO;AACzB,UAAM,OAAQ,MAAM,SAAS,KAAK;AAElC,UAAM,UAAU;AAAA,MACd,MAAM,aAAa,QAAQ,WAAW,OAAO,aAAa,IAAI;AAAA,MAC9D,MAAM,aAAa,QAAQ,WAAW,OAAO,aAAa,IAAI;AAAA,IAChE,EAAE,OAAO,CAAC,MAAgC,MAAM,IAAI;AACpD,QAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,UAAM,QAAQ,QAAQ;AAAA,MAAO,CAAC,GAAG,MAC/B,SAAS,EAAE,MAAM,IAAI,SAAS,EAAE,MAAM,IAAI,IAAI;AAAA,IAChD;AACA,QAAI,MAAM,WAAW,cAAc;AAGjC,OAAC,QAAQ,QAAQ,QAAQ,MAAM,2BAA2B,KAAK,CAAC;AAAA,IAClE;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/config.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { E as EnvSource, P as PublicConfig } from './schema-Dg0ZflMW.js';
2
- export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Dg0ZflMW.js';
3
- export { S as StorefrontMode, r as resolveMode } from './mode-Lm9t4qzX.js';
1
+ import { E as EnvSource, P as PublicConfig } from './schema-DIF0CZNV.js';
2
+ export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-DIF0CZNV.js';
3
+ export { S as StorefrontMode, r as resolveMode } from './mode-DXo-EhTJ.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Parses the variables of the mode `env` selects (see resolveMode). */
@@ -55,6 +55,14 @@ interface CheckClientVersionsOptions {
55
55
  sdk?: string;
56
56
  };
57
57
  }
58
+ /**
59
+ * Turns a version report into the multi-line warning that
60
+ * {@link checkClientVersions} prints: the headline, one line per advisory and
61
+ * how to update.
62
+ *
63
+ * @param report - The report to describe.
64
+ * @returns The warning text, ready for `console.warn`.
65
+ */
58
66
  declare function formatClientVersionWarning(report: ClientVersionReport): string;
59
67
  /**
60
68
  * Checks the installed kit and SDK against the platform's supported versions
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config.ts"],"sourcesContent":["// @ecomweb/storefront-kit/config: config parsing and types.\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAO5B,SAAS,kBAAkB,mBAAmB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
1
+ {"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Parsing and types for the storefront's configuration: public (client-safe)\n * settings, the deployment mode, the build-time version check and\n * `ConfigError`.\n *\n * Import from `@ecomweb/storefront-kit/config` in `next.config` and config\n * code. It has no React or server-only dependency.\n *\n * @packageDocumentation\n */\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAO5B,SAAS,kBAAkB,mBAAmB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/currency.ts"],"sourcesContent":["import currencyJs from \"currency.js\";\n\nexport type SupportedCurrency = \"VND\" | \"USD\" | \"EUR\" | \"SGD\";\n\nexport function getDefaultLocale(currency: SupportedCurrency): string {\n switch (currency) {\n case \"USD\":\n case \"EUR\":\n case \"SGD\":\n return \"en-US\";\n case \"VND\":\n return \"vi-VN\";\n default:\n return \"vi-VN\";\n }\n}\n\n/**\n * House formatting convention, one table for every currency we price in.\n *\n * A locale bundles four decisions — group separator, decimal separator,\n * symbol, and symbol placement — behind one string, and we want them from\n * different places. `vi-VN` renders 10.234.000 ₫ with a space and the dong\n * sign; the house style is 10.234.000đ, tight and with the Latin d-stroke.\n * So the table is explicit.\n *\n * Numerals are uniform across currencies: dot groups, comma decimals. Only\n * the symbol, its placement, and the precision vary.\n *\n * VND 10.234.000đ USD $1.234,50\n * EUR €1.234,50 SGD S$1.234,50\n *\n * Keep this in sync with the same table in ecomweb-dashboard/lib/currency.ts\n * and the API's src/common/utils/currency.utils.ts. The pinned tests in each\n * repo exist to catch drift between the three.\n */\nconst CURRENCY_FORMATS = {\n VND: { symbol: \"đ\", precision: 0, suffix: true },\n USD: { symbol: \"$\", precision: 2, suffix: false },\n EUR: { symbol: \"€\", precision: 2, suffix: false },\n SGD: { symbol: \"S$\", precision: 2, suffix: false },\n} as const;\n\n/** Narrows an arbitrary stored code to a currency we can price in. */\nexport function isSupportedCurrency(\n code: unknown\n): code is SupportedCurrency {\n return (\n typeof code === \"string\" &&\n Object.prototype.hasOwnProperty.call(CURRENCY_FORMATS, code)\n );\n}\n\nfunction getCurrencyOptions(_locale: string, code: SupportedCurrency | string) {\n const format =\n CURRENCY_FORMATS[code as SupportedCurrency] ?? CURRENCY_FORMATS.VND;\n\n return {\n symbol: format.symbol,\n precision: format.precision,\n // Uniform numerals: 1.234.567,89 regardless of currency.\n separator: \".\",\n decimal: \",\",\n // The sign stays outermost: -10.234.000đ and -$19,99.\n pattern: format.suffix ? \"#!\" : \"!#\",\n negativePattern: format.suffix ? \"-#!\" : \"-!#\",\n } as const;\n}\n\n/**\n * Format an amount as money in the given currency.\n *\n * `locale` is retained for call-site compatibility but no longer affects the\n * output — the house convention in CURRENCY_FORMATS is uniform across\n * locales. It still matters to formatNumber, which is not currency.\n */\nexport function formatPrice(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency | string = \"VND\"\n): string {\n const opts = getCurrencyOptions(locale, code);\n return currencyJs(amount, opts).format();\n}\n\nexport function formatNumber(amount: number, locale = \"vi-VN\"): string {\n // General number formatting (non-currency)\n return new Intl.NumberFormat(locale).format(amount);\n}\n\nexport function formatPriceRange(\n min?: number,\n max?: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n if (min == null && max == null) return \"\";\n if (max == null || min === max) return formatPrice(min || 0, locale, code);\n return `${formatPrice(min || 0, locale, code)} - ${formatPrice(max, locale, code)}`;\n}\n\n// Helper to perform safe currency calculations using currency.js\nexport const money = (\n value: number | string,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n) => currencyJs(value as any, getCurrencyOptions(locale, code));\n\n// Format for inputs (no symbol), keeps separators consistent with currency options\nexport function formatPriceWithoutSymbol(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n const base = getCurrencyOptions(locale, code);\n const opts = {\n ...base,\n symbol: \"\",\n pattern: \"#\",\n negativePattern: \"-#\",\n } as const;\n return currencyJs(amount, opts).format();\n}\n"],"mappings":"AAAA,OAAO,gBAAgB;AAIhB,SAAS,iBAAiB,UAAqC;AACpE,UAAQ,UAAU;AAAA,IAChB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAqBA,MAAM,mBAAmB;AAAA,EACvB,KAAK,EAAE,QAAQ,UAAK,WAAW,GAAG,QAAQ,KAAK;AAAA,EAC/C,KAAK,EAAE,QAAQ,KAAK,WAAW,GAAG,QAAQ,MAAM;AAAA,EAChD,KAAK,EAAE,QAAQ,UAAK,WAAW,GAAG,QAAQ,MAAM;AAAA,EAChD,KAAK,EAAE,QAAQ,MAAM,WAAW,GAAG,QAAQ,MAAM;AACnD;AAGO,SAAS,oBACd,MAC2B;AAC3B,SACE,OAAO,SAAS,YAChB,OAAO,UAAU,eAAe,KAAK,kBAAkB,IAAI;AAE/D;AAEA,SAAS,mBAAmB,SAAiB,MAAkC;AAC7E,QAAM,SACJ,iBAAiB,IAAyB,KAAK,iBAAiB;AAElE,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,WAAW,OAAO;AAAA;AAAA,IAElB,WAAW;AAAA,IACX,SAAS;AAAA;AAAA,IAET,SAAS,OAAO,SAAS,OAAO;AAAA,IAChC,iBAAiB,OAAO,SAAS,QAAQ;AAAA,EAC3C;AACF;AASO,SAAS,YACd,QACA,SAAiB,SACjB,OAAmC,OAC3B;AACR,QAAM,OAAO,mBAAmB,QAAQ,IAAI;AAC5C,SAAO,WAAW,QAAQ,IAAI,EAAE,OAAO;AACzC;AAEO,SAAS,aAAa,QAAgB,SAAS,SAAiB;AAErE,SAAO,IAAI,KAAK,aAAa,MAAM,EAAE,OAAO,MAAM;AACpD;AAEO,SAAS,iBACd,KACA,KACA,SAAiB,SACjB,OAA0B,OAClB;AACR,MAAI,OAAO,QAAQ,OAAO,KAAM,QAAO;AACvC,MAAI,OAAO,QAAQ,QAAQ,IAAK,QAAO,YAAY,OAAO,GAAG,QAAQ,IAAI;AACzE,SAAO,GAAG,YAAY,OAAO,GAAG,QAAQ,IAAI,CAAC,MAAM,YAAY,KAAK,QAAQ,IAAI,CAAC;AACnF;AAGO,MAAM,QAAQ,CACnB,OACA,SAAiB,SACjB,OAA0B,UACvB,WAAW,OAAc,mBAAmB,QAAQ,IAAI,CAAC;AAGvD,SAAS,yBACd,QACA,SAAiB,SACjB,OAA0B,OAClB;AACR,QAAM,OAAO,mBAAmB,QAAQ,IAAI;AAC5C,QAAM,OAAO;AAAA,IACX,GAAG;AAAA,IACH,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,iBAAiB;AAAA,EACnB;AACA,SAAO,WAAW,QAAQ,IAAI,EAAE,OAAO;AACzC;","names":[]}
1
+ {"version":3,"sources":["../src/currency.ts"],"sourcesContent":["import currencyJs from \"currency.js\";\n\nexport type SupportedCurrency = \"VND\" | \"USD\" | \"EUR\" | \"SGD\";\n\n/**\n * Picks the locale used to format prices in a currency: `en-US` for USD, EUR\n * and SGD, `vi-VN` for VND.\n *\n * @param currency - The store's currency code.\n * @returns A BCP 47 locale tag.\n */\nexport function getDefaultLocale(currency: SupportedCurrency): string {\n switch (currency) {\n case \"USD\":\n case \"EUR\":\n case \"SGD\":\n return \"en-US\";\n case \"VND\":\n return \"vi-VN\";\n default:\n return \"vi-VN\";\n }\n}\n\n/**\n * House formatting convention, one table for every currency we price in.\n *\n * A locale bundles four decisions — group separator, decimal separator,\n * symbol, and symbol placement — behind one string, and we want them from\n * different places. `vi-VN` renders 10.234.000 ₫ with a space and the dong\n * sign; the house style is 10.234.000đ, tight and with the Latin d-stroke.\n * So the table is explicit.\n *\n * Numerals are uniform across currencies: dot groups, comma decimals. Only\n * the symbol, its placement, and the precision vary.\n *\n * VND 10.234.000đ USD $1.234,50\n * EUR €1.234,50 SGD S$1.234,50\n *\n * Keep this in sync with the same table in ecomweb-dashboard/lib/currency.ts\n * and the API's src/common/utils/currency.utils.ts. The pinned tests in each\n * repo exist to catch drift between the three.\n */\nconst CURRENCY_FORMATS = {\n VND: { symbol: \"đ\", precision: 0, suffix: true },\n USD: { symbol: \"$\", precision: 2, suffix: false },\n EUR: { symbol: \"€\", precision: 2, suffix: false },\n SGD: { symbol: \"S$\", precision: 2, suffix: false },\n} as const;\n\n/** Narrows an arbitrary stored code to a currency we can price in. */\nexport function isSupportedCurrency(\n code: unknown\n): code is SupportedCurrency {\n return (\n typeof code === \"string\" &&\n Object.prototype.hasOwnProperty.call(CURRENCY_FORMATS, code)\n );\n}\n\nfunction getCurrencyOptions(_locale: string, code: SupportedCurrency | string) {\n const format =\n CURRENCY_FORMATS[code as SupportedCurrency] ?? CURRENCY_FORMATS.VND;\n\n return {\n symbol: format.symbol,\n precision: format.precision,\n // Uniform numerals: 1.234.567,89 regardless of currency.\n separator: \".\",\n decimal: \",\",\n // The sign stays outermost: -10.234.000đ and -$19,99.\n pattern: format.suffix ? \"#!\" : \"!#\",\n negativePattern: format.suffix ? \"-#!\" : \"-!#\",\n } as const;\n}\n\n/**\n * Format an amount as money in the given currency.\n *\n * `locale` is retained for call-site compatibility but no longer affects the\n * output — the house convention in CURRENCY_FORMATS is uniform across\n * locales. It still matters to formatNumber, which is not currency.\n */\nexport function formatPrice(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency | string = \"VND\"\n): string {\n const opts = getCurrencyOptions(locale, code);\n return currencyJs(amount, opts).format();\n}\n\n/**\n * Formats a plain number with the locale's digit grouping, without a currency\n * symbol.\n *\n * @param amount - The number to format.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @returns The formatted number.\n */\nexport function formatNumber(amount: number, locale = \"vi-VN\"): string {\n // General number formatting (non-currency)\n return new Intl.NumberFormat(locale).format(amount);\n}\n\n/**\n * Formats a price range such as a product's lowest and highest variant price.\n *\n * @param min - The lowest price.\n * @param max - The highest price.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns One formatted price when the two match or `max` is missing, `min - max` otherwise, and an empty string when both are missing.\n */\nexport function formatPriceRange(\n min?: number,\n max?: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n if (min == null && max == null) return \"\";\n if (max == null || min === max) return formatPrice(min || 0, locale, code);\n return `${formatPrice(min || 0, locale, code)} - ${formatPrice(max, locale, code)}`;\n}\n\n/**\n * Wraps a value in a currency.js object for safe money arithmetic (add,\n * subtract, multiply, format) without floating-point drift.\n *\n * @param value - The amount, as a number or numeric string.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns A currency.js value configured for that locale and currency.\n */\nexport const money = (\n value: number | string,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n) => currencyJs(value as any, getCurrencyOptions(locale, code));\n\n// Format for inputs (no symbol), keeps separators consistent with currency options\n/**\n * Formats an amount with the currency's separators but no symbol, for price\n * inputs.\n *\n * @param amount - The amount to format.\n * @param locale - BCP 47 locale tag; defaults to `vi-VN`.\n * @param code - Currency code; defaults to `VND`.\n * @returns The formatted amount.\n */\nexport function formatPriceWithoutSymbol(\n amount: number,\n locale: string = \"vi-VN\",\n code: SupportedCurrency = \"VND\"\n): string {\n const base = getCurrencyOptions(locale, code);\n const opts = {\n ...base,\n symbol: \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