@ecomweb/storefront-kit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +85 -3
  2. package/dist/api/client.js +32 -1
  3. package/dist/api/client.js.map +1 -1
  4. package/dist/api/proxy.js +29 -4
  5. package/dist/api/proxy.js.map +1 -1
  6. package/dist/api/store-preview-header.js +42 -0
  7. package/dist/api/store-preview-header.js.map +1 -0
  8. package/dist/auth/error-copy.js +5 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/session-refresh.js +2 -0
  11. package/dist/auth/session-refresh.js.map +1 -1
  12. package/dist/cart/server-context.js +26 -0
  13. package/dist/cart/server-context.js.map +1 -1
  14. package/dist/checkout/quote-changed.js +16 -0
  15. package/dist/checkout/quote-changed.js.map +1 -0
  16. package/dist/checkout/use-checkout.js +45 -5
  17. package/dist/checkout/use-checkout.js.map +1 -1
  18. package/dist/index.d.ts +152 -5
  19. package/dist/index.js +39 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/middleware/create-storefront-middleware.js +58 -11
  22. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  23. package/dist/middleware.d.ts +5 -2
  24. package/dist/orders/index.js +17 -1
  25. package/dist/orders/index.js.map +1 -1
  26. package/dist/orders/shipment-tracking.js +80 -0
  27. package/dist/orders/shipment-tracking.js.map +1 -0
  28. package/dist/provider.js +22 -0
  29. package/dist/provider.js.map +1 -1
  30. package/dist/redirects/lookup-redirect.js +2 -1
  31. package/dist/redirects/lookup-redirect.js.map +1 -1
  32. package/dist/server.d.ts +20 -1
  33. package/dist/server.js +4 -0
  34. package/dist/server.js.map +1 -1
  35. package/dist/shipping/format-shipping-option.js +28 -0
  36. package/dist/shipping/format-shipping-option.js.map +1 -1
  37. package/dist/shipping/messages.js +2 -0
  38. package/dist/shipping/messages.js.map +1 -1
  39. package/dist/shipping/option-id.js +7 -0
  40. package/dist/shipping/option-id.js.map +1 -0
  41. package/dist/shipping/shipping-calculation-reducer.js +60 -12
  42. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  43. package/dist/shipping/use-shipping-calculation.js +38 -5
  44. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  45. package/dist/stores/get-store-by-host.js +34 -7
  46. package/dist/stores/get-store-by-host.js.map +1 -1
  47. package/dist/stores/metadata.js +17 -0
  48. package/dist/stores/metadata.js.map +1 -1
  49. package/dist/stores/read-store-preview-token.js +10 -0
  50. package/dist/stores/read-store-preview-token.js.map +1 -0
  51. package/dist/stores/resolve-coming-soon.js +30 -0
  52. package/dist/stores/resolve-coming-soon.js.map +1 -0
  53. package/dist/stores/store-coming-soon.js +21 -0
  54. package/dist/stores/store-coming-soon.js.map +1 -0
  55. package/dist/stores/store-preview-cookie.js +64 -0
  56. package/dist/stores/store-preview-cookie.js.map +1 -0
  57. package/dist/stores/store-preview-guard.js +12 -0
  58. package/dist/stores/store-preview-guard.js.map +1 -0
  59. package/dist/stores/store-subdomain.js +10 -5
  60. package/dist/stores/store-subdomain.js.map +1 -1
  61. package/package.json +2 -2
@@ -1,19 +1,36 @@
1
+ import {
2
+ comingSoonStoreNameOf,
3
+ isStoreComingSoonError
4
+ } from "./store-coming-soon.js";
1
5
  import { isStoreSuspendedError } from "./store-suspension.js";
6
+ const COMING_SOON_STORE_DESCRIPTION = "C\u1EEDa h\xE0ng \u0111ang chu\u1EA9n b\u1ECB v\xE0 s\u1EBD s\u1EDBm m\u1EDF c\u1EEDa.";
2
7
  const SUSPENDED_STORE_METADATA = {
3
8
  title: "Store suspended",
4
9
  description: "This store is temporarily unavailable. If you are the store owner, contact support.",
5
10
  robots: "noindex, nofollow"
6
11
  };
12
+ function comingSoonStoreMetadata(name) {
13
+ return {
14
+ title: name ? `${name} s\u1EAFp ra m\u1EAFt` : "S\u1EAFp ra m\u1EAFt",
15
+ description: COMING_SOON_STORE_DESCRIPTION,
16
+ robots: "noindex, nofollow"
17
+ };
18
+ }
7
19
  async function withSuspendedStoreMetadataFallback(fn) {
8
20
  try {
9
21
  return await fn();
10
22
  } catch (error) {
11
23
  if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;
24
+ if (isStoreComingSoonError(error)) {
25
+ return comingSoonStoreMetadata(comingSoonStoreNameOf(error));
26
+ }
12
27
  throw error;
13
28
  }
14
29
  }
15
30
  export {
31
+ COMING_SOON_STORE_DESCRIPTION,
16
32
  SUSPENDED_STORE_METADATA,
33
+ comingSoonStoreMetadata,
17
34
  withSuspendedStoreMetadataFallback
18
35
  };
19
36
  //# sourceMappingURL=metadata.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/metadata.ts"],"sourcesContent":["import type { Metadata } from \"next\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\n\n/**\n * The metadata Next.js shows for a store's suspended pages. Never includes\n * `platform_suspension_reason` -- it's internal, written by an admin for\n * other admins.\n */\nexport const SUSPENDED_STORE_METADATA: Metadata = {\n title: \"Store suspended\",\n description:\n \"This store is temporarily unavailable. If you are the store owner, contact support.\",\n robots: \"noindex, nofollow\",\n};\n\n/**\n * Wraps a leaf page's `generateMetadata` body so a STORE_SUSPENDED lookup\n * doesn't crash the whole route.\n *\n * Next.js resolves every matched segment's `generateMetadata` unconditionally\n * to build <head> -- this happens independently of whatever the parent\n * `StoreLayout` eventually renders (it can skip rendering `children` for a\n * suspended store, but that doesn't stop Next from having already awaited\n * this segment's own `generateMetadata`). So each page that calls\n * `getCachedStore` in its own `generateMetadata` needs this, not just the\n * layout's.\n */\nexport async function withSuspendedStoreMetadataFallback(\n fn: () => Promise<Metadata>\n): Promise<Metadata> {\n try {\n return await fn();\n } catch (error) {\n if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;\n throw error;\n }\n}\n"],"mappings":"AACA,SAAS,6BAA6B;AAO/B,MAAM,2BAAqC;AAAA,EAChD,OAAO;AAAA,EACP,aACE;AAAA,EACF,QAAQ;AACV;AAcA,eAAsB,mCACpB,IACmB;AACnB,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,EAAG,QAAO;AACzC,UAAM;AAAA,EACR;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/metadata.ts"],"sourcesContent":["import type { Metadata } from \"next\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\n\n/** Shared copy: the coming soon metadata description and the coming soon page. */\nexport const COMING_SOON_STORE_DESCRIPTION =\n \"Cửa hàng đang chuẩn bị và sẽ sớm mở cửa.\";\n\n/**\n * The metadata Next.js shows for a store's suspended pages. Never includes\n * `platform_suspension_reason` -- it's internal, written by an admin for\n * other admins.\n */\nexport const SUSPENDED_STORE_METADATA: Metadata = {\n title: \"Store suspended\",\n description:\n \"This store is temporarily unavailable. If you are the store owner, contact support.\",\n robots: \"noindex, nofollow\",\n};\n\n/**\n * The metadata for a store the merchant has not opened yet. `name` comes from\n * the coming soon error's details and may be missing.\n */\nexport function comingSoonStoreMetadata(name: string | null): Metadata {\n return {\n title: name ? `${name} sắp ra mắt` : \"Sắp ra mắt\",\n description: COMING_SOON_STORE_DESCRIPTION,\n robots: \"noindex, nofollow\",\n };\n}\n\n/**\n * Wraps a leaf page's `generateMetadata` body so a STORE_SUSPENDED lookup\n * doesn't crash the whole route. A STORE_COMING_SOON lookup gets\n * `comingSoonStoreMetadata` the same way.\n *\n * Next.js resolves every matched segment's `generateMetadata` unconditionally\n * to build <head> -- this happens independently of whatever the parent\n * `StoreLayout` eventually renders (it can skip rendering `children` for a\n * suspended store, but that doesn't stop Next from having already awaited\n * this segment's own `generateMetadata`). So each page that calls\n * `getCachedStore` in its own `generateMetadata` needs this, not just the\n * layout's.\n */\nexport async function withSuspendedStoreMetadataFallback(\n fn: () => Promise<Metadata>\n): Promise<Metadata> {\n try {\n return await fn();\n } catch (error) {\n if (isStoreSuspendedError(error)) return SUSPENDED_STORE_METADATA;\n if (isStoreComingSoonError(error)) {\n return comingSoonStoreMetadata(comingSoonStoreNameOf(error));\n }\n throw error;\n }\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAG/B,MAAM,gCACX;AAOK,MAAM,2BAAqC;AAAA,EAChD,OAAO;AAAA,EACP,aACE;AAAA,EACF,QAAQ;AACV;AAMO,SAAS,wBAAwB,MAA+B;AACrE,SAAO;AAAA,IACL,OAAO,OAAO,GAAG,IAAI,0BAAgB;AAAA,IACrC,aAAa;AAAA,IACb,QAAQ;AAAA,EACV;AACF;AAeA,eAAsB,mCACpB,IACmB;AACnB,MAAI;AACF,WAAO,MAAM,GAAG;AAAA,EAClB,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,EAAG,QAAO;AACzC,QAAI,uBAAuB,KAAK,GAAG;AACjC,aAAO,wBAAwB,sBAAsB,KAAK,CAAC;AAAA,IAC7D;AACA,UAAM;AAAA,EACR;AACF;","names":[]}
@@ -0,0 +1,10 @@
1
+ import "server-only";
2
+ import { cookies, headers } from "next/headers";
3
+ import { storePreviewTokenFrom } from "./store-preview-cookie.js";
4
+ async function readStorePreviewToken() {
5
+ return storePreviewTokenFrom(await cookies(), { headers: await headers() });
6
+ }
7
+ export {
8
+ readStorePreviewToken
9
+ };
10
+ //# sourceMappingURL=read-store-preview-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/read-store-preview-token.ts"],"sourcesContent":["import \"server-only\";\nimport { cookies, headers } from \"next/headers\";\nimport { storePreviewTokenFrom } from \"./store-preview-cookie\";\n\n/**\n * The token this request sends as `X-Store-Preview` (server components\n * only): a preview host's token the middleware stamped, else the store\n * preview cookie, else the theme preview cookie. The layout passes it to\n * `StorefrontKitProvider` while the store is coming soon.\n */\nexport async function readStorePreviewToken(): Promise<string | null> {\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,SAAS,eAAe;AACjC,SAAS,6BAA6B;AAQtC,eAAsB,wBAAgD;AACpE,SAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAC5E;","names":[]}
@@ -0,0 +1,30 @@
1
+ import "server-only";
2
+ import { headers } from "next/headers";
3
+ import { publicConfig } from "../config/public.js";
4
+ import { getCachedStore } from "./cached.js";
5
+ import { getStoreByHost } from "./get-store-by-host.js";
6
+ import {
7
+ comingSoonStoreNameOf,
8
+ isStoreComingSoonError
9
+ } from "./store-coming-soon.js";
10
+ async function resolveComingSoonStore() {
11
+ const config = publicConfig();
12
+ if (config.mode === "single") {
13
+ try {
14
+ await getCachedStore(config.storeRef);
15
+ return null;
16
+ } catch (error) {
17
+ if (isStoreComingSoonError(error)) {
18
+ return { name: comingSoonStoreNameOf(error) };
19
+ }
20
+ throw error;
21
+ }
22
+ }
23
+ const host = (await headers()).get("host") ?? "";
24
+ const lookup = await getStoreByHost(host);
25
+ return lookup.comingSoon ? { name: lookup.comingSoonName } : null;
26
+ }
27
+ export {
28
+ resolveComingSoonStore
29
+ };
30
+ //# sourceMappingURL=resolve-coming-soon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/resolve-coming-soon.ts"],"sourcesContent":["import \"server-only\";\nimport { headers } from \"next/headers\";\nimport { publicConfig } from \"../config/public\";\nimport { getCachedStore } from \"./cached\";\nimport { getStoreByHost } from \"./get-store-by-host\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\n\n/**\n * Whether the store this request belongs to is coming soon, and its name\n * (null when the API gave none). Null when the store is not coming soon.\n *\n * The name only ever comes from the API lookup, never from the request, so\n * the /coming-soon page cannot be made to show text a visitor chose.\n */\nexport async function resolveComingSoonStore(): Promise<{\n name: string | null;\n} | null> {\n const config = publicConfig();\n if (config.mode === \"single\") {\n try {\n await getCachedStore(config.storeRef as string);\n return null;\n } catch (error) {\n if (isStoreComingSoonError(error)) {\n return { name: comingSoonStoreNameOf(error) };\n }\n throw error;\n }\n }\n const host = (await headers()).get(\"host\") ?? \"\";\n const lookup = await getStoreByHost(host);\n return lookup.comingSoon ? { name: lookup.comingSoonName } : null;\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,eAAe;AACxB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,eAAsB,yBAEZ;AACR,QAAM,SAAS,aAAa;AAC5B,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI;AACF,YAAM,eAAe,OAAO,QAAkB;AAC9C,aAAO;AAAA,IACT,SAAS,OAAO;AACd,UAAI,uBAAuB,KAAK,GAAG;AACjC,eAAO,EAAE,MAAM,sBAAsB,KAAK,EAAE;AAAA,MAC9C;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACA,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,MAAM,KAAK;AAC9C,QAAM,SAAS,MAAM,eAAe,IAAI;AACxC,SAAO,OAAO,aAAa,EAAE,MAAM,OAAO,eAAe,IAAI;AAC/D;","names":[]}
@@ -0,0 +1,21 @@
1
+ import { ApiClientError } from "@ecomweb/sdk";
2
+ function isStoreComingSoonError(error) {
3
+ return error instanceof ApiClientError && error.code === "STORE_COMING_SOON";
4
+ }
5
+ function comingSoonStoreNameOf(error) {
6
+ if (!isStoreComingSoonError(error)) return null;
7
+ const details = error.details;
8
+ const name = typeof details === "object" && details !== null ? details.name : void 0;
9
+ return typeof name === "string" && name.length > 0 ? name : null;
10
+ }
11
+ const STORE_COMING_SOON_REDIRECT_PATH = "/coming-soon";
12
+ function isStoreComingSoonResponseBody(data) {
13
+ return typeof data === "object" && data !== null && data.code === "STORE_COMING_SOON";
14
+ }
15
+ export {
16
+ STORE_COMING_SOON_REDIRECT_PATH,
17
+ comingSoonStoreNameOf,
18
+ isStoreComingSoonError,
19
+ isStoreComingSoonResponseBody
20
+ };
21
+ //# sourceMappingURL=store-coming-soon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/store-coming-soon.ts"],"sourcesContent":["import { ApiClientError } from \"@ecomweb/sdk\";\n\n/**\n * True when `error` is the backend's signal that the merchant has not opened\n * this store yet (`STORE_COMING_SOON`, 403, details `{ name }`). Unlike\n * `STORE_SUSPENDED`, this is a merchant-controlled state, and the API lifts\n * it for a request carrying a valid `X-Store-Preview` token.\n *\n * Both `getCachedStore` and `getStoreByHost` surface it as an\n * `ApiClientError`, so this is the one place that decides \"was that coming\n * soon\" for both entry points.\n */\nexport function isStoreComingSoonError(error: unknown): boolean {\n return error instanceof ApiClientError && error.code === \"STORE_COMING_SOON\";\n}\n\n/**\n * The store name the API puts in a coming soon error's `details`, or null\n * when the error is not coming soon or carries no usable name.\n */\nexport function comingSoonStoreNameOf(error: unknown): string | null {\n if (!isStoreComingSoonError(error)) return null;\n const details = (error as ApiClientError).details;\n const name =\n typeof details === \"object\" && details !== null\n ? (details as { name?: unknown }).name\n : undefined;\n return typeof name === \"string\" && name.length > 0 ? name : null;\n}\n\n/**\n * Where the axios interceptor (lib/api/client.ts) sends the browser when a\n * client-side call discovers mid-session that the store is coming soon.\n */\nexport const STORE_COMING_SOON_REDIRECT_PATH = \"/coming-soon\";\n\n/**\n * True when a raw HTTP error body (`{ code, message, details, timestamp }`)\n * is a STORE_COMING_SOON response. The raw-body twin of\n * `isStoreComingSoonError`, for the axios interceptor, which sees the error\n * before the SDK constructs an `ApiClientError`. Internal to the kit.\n */\nexport function isStoreComingSoonResponseBody(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { code?: unknown }).code === \"STORE_COMING_SOON\"\n );\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAYxB,SAAS,uBAAuB,OAAyB;AAC9D,SAAO,iBAAiB,kBAAkB,MAAM,SAAS;AAC3D;AAMO,SAAS,sBAAsB,OAA+B;AACnE,MAAI,CAAC,uBAAuB,KAAK,EAAG,QAAO;AAC3C,QAAM,UAAW,MAAyB;AAC1C,QAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAA+B,OAChC;AACN,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO;AAC9D;AAMO,MAAM,kCAAkC;AAQxC,SAAS,8BAA8B,MAAwB;AACpE,SACE,OAAO,SAAS,YAChB,SAAS,QACR,KAA4B,SAAS;AAE1C;","names":[]}
@@ -0,0 +1,64 @@
1
+ import { NextResponse } from "next/server";
2
+ import {
3
+ hostOnlyCookieName,
4
+ isHostMappedRequest,
5
+ secureCookies
6
+ } from "../auth/cookies.js";
7
+ import { publicNextUrl } from "../request/public-url.js";
8
+ import {
9
+ THEME_PREVIEW_COOKIE,
10
+ themePreviewCookieName
11
+ } from "../theme/preview-cookie.js";
12
+ const STORE_PREVIEW_COOKIE = "ecw_store_preview";
13
+ const STORE_PREVIEW_PATH = "/preview";
14
+ const STORE_PREVIEW_PARAM = "token";
15
+ const STORE_PREVIEW_HEADER = "x-store-preview";
16
+ const STORE_PREVIEW_TOKEN_HEADER = "x-ecomweb-store-preview-token";
17
+ const MAX_TOKEN_LENGTH = 2048;
18
+ const MAX_AGE_SECONDS = 24 * 60 * 60;
19
+ function storePreviewCookieName(cookiePath) {
20
+ return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);
21
+ }
22
+ function applyStorePreview(req, cookiePath, storeRoot) {
23
+ const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? "";
24
+ const url = publicNextUrl(req);
25
+ url.pathname = storeRoot;
26
+ url.search = "";
27
+ const res = NextResponse.redirect(url, 307);
28
+ const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;
29
+ res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : "", {
30
+ httpOnly: true,
31
+ secure: secureCookies(),
32
+ sameSite: "lax",
33
+ path: cookiePath,
34
+ maxAge: valid ? MAX_AGE_SECONDS : 0
35
+ });
36
+ return res;
37
+ }
38
+ function storePreviewTokenFrom(jar, request) {
39
+ const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);
40
+ if (stamped) return stamped;
41
+ const hostMapped = isHostMappedRequest(request);
42
+ const storeCookie = hostMapped ? storePreviewCookieName("/") : STORE_PREVIEW_COOKIE;
43
+ const themeCookie = hostMapped ? themePreviewCookieName("/") : THEME_PREVIEW_COOKIE;
44
+ return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;
45
+ }
46
+ const SKIP_STORE_PREVIEW = Object.freeze({
47
+ skipStorePreview: true
48
+ });
49
+ function skipsStorePreview(options) {
50
+ return options?.skipStorePreview === true;
51
+ }
52
+ export {
53
+ SKIP_STORE_PREVIEW,
54
+ STORE_PREVIEW_COOKIE,
55
+ STORE_PREVIEW_HEADER,
56
+ STORE_PREVIEW_PARAM,
57
+ STORE_PREVIEW_PATH,
58
+ STORE_PREVIEW_TOKEN_HEADER,
59
+ applyStorePreview,
60
+ skipsStorePreview,
61
+ storePreviewCookieName,
62
+ storePreviewTokenFrom
63
+ };
64
+ //# sourceMappingURL=store-preview-cookie.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/store-preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n hostOnlyCookieName,\n isHostMappedRequest,\n secureCookies,\n} from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n THEME_PREVIEW_COOKIE,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\n\n// No `next/headers` here: the browser bundle reaches this module (through\n// the API client), so readers take the jar and the request as arguments.\n\n/** Holds a coming soon store's preview token (the dashboard's preview link). */\nexport const STORE_PREVIEW_COOKIE = \"ecw_store_preview\";\n/** The preview link's route under the store's root. */\nexport const STORE_PREVIEW_PATH = \"/preview\";\n/** The preview link's query param carrying the token. */\nexport const STORE_PREVIEW_PARAM = \"token\";\n/** The API's request header (`X-Store-Preview`) that opens a coming soon store. */\nexport const STORE_PREVIEW_HEADER = \"x-store-preview\";\n/**\n * Internal request header carrying a theme preview host's (`p-<slug>`) store\n * preview token from the host lookup to the render, in place of the cookie.\n * Only the middleware sets it, and it deletes any value the client sent on\n * every request it lets through, as it does for `THEME_PREVIEW_HOST_HEADER`,\n * so a reader can trust it on any path the matcher covers. Root `/api/*` is\n * outside the matcher; the backend proxy ignores it there.\n */\nexport const STORE_PREVIEW_TOKEN_HEADER = \"x-ecomweb-store-preview-token\";\n\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/** The store preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function storePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);\n}\n\n/**\n * The dashboard's preview link (`<store root>/preview?token=<t>`) becomes an\n * httpOnly cookie scoped to the store, then a 307 to the store's home, so the\n * token never stays in the address bar or in shared links. A missing, empty\n * or oversized token clears the cookie instead. The API validates the token\n * on every request. SameSite=Lax: the link is a top-level navigation and the\n * store is never framed during a store preview.\n */\nexport function applyStorePreview(\n req: NextRequest,\n cookiePath: string,\n storeRoot: string\n): NextResponse {\n const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? \"\";\n const url = publicNextUrl(req);\n url.pathname = storeRoot;\n url.search = \"\";\n const res = NextResponse.redirect(url, 307);\n const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : \"\", {\n httpOnly: true,\n secure: secureCookies(),\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `headers()`-backed requests and `NextRequest`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/**\n * The token to send as `X-Store-Preview` for this request, or null. In order:\n * the preview host's token the middleware stamped (`STORE_PREVIEW_TOKEN_HEADER`),\n * the store preview cookie, then the theme preview cookie (`?preview_theme=`\n * on the store's own host), which the API accepts too. Cookies are read under\n * the name their writer used: `/` on a host-mapped request (the `__Host-` name\n * in production, never the bare one a sibling store could plant), else the\n * bare path-scoped name. An empty value counts as none at every step.\n *\n * Trusts `STORE_PREVIEW_TOKEN_HEADER`, so call it only on a request that went\n * through the middleware (server components, route handlers), never on the\n * middleware's own incoming request.\n */\nexport function storePreviewTokenFrom(\n jar: CookieReader,\n request: HeaderReader\n): string | null {\n const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);\n if (stamped) return stamped;\n const hostMapped = isHostMappedRequest(request);\n const storeCookie = hostMapped\n ? storePreviewCookieName(\"/\")\n : STORE_PREVIEW_COOKIE;\n const themeCookie = hostMapped\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;\n}\n\n/**\n * Request option that forbids the kit's API client from attaching the\n * request's ambient preview token (`storePreviewTokenFrom`) as\n * `X-Store-Preview`. Spread it into the SDK call's options (the SDK's\n * `RequestOptions` takes extra keys and the kit's ApiClient hands them to\n * axios unchanged). A plain `getStoreByHost(host)` sets it, because its\n * result is cached per host for every visitor and must be the public answer.\n * An explicit `X-Store-Preview` header in the same options still goes out.\n */\nexport const SKIP_STORE_PREVIEW = Object.freeze({\n skipStorePreview: true,\n} as const);\n\n/** True when request options (or an axios config) carry SKIP_STORE_PREVIEW. */\nexport function skipsStorePreview(options: object | undefined): boolean {\n return (\n (options as { skipStorePreview?: unknown } | undefined)\n ?.skipStorePreview === true\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMA,MAAM,uBAAuB;AAE7B,MAAM,qBAAqB;AAE3B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAS7B,MAAM,6BAA6B;AAE1C,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,KAAK,KAAK;AAG3B,SAAS,uBAAuB,YAA4B;AACjE,SAAO,mBAAmB,sBAAsB,UAAU;AAC5D;AAUO,SAAS,kBACd,KACA,YACA,WACc;AACd,QAAM,QAAQ,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAAK;AACnE,QAAM,MAAM,cAAc,GAAG;AAC7B,MAAI,WAAW;AACf,MAAI,SAAS;AACb,QAAM,MAAM,aAAa,SAAS,KAAK,GAAG;AAC1C,QAAM,QAAQ,MAAM,SAAS,KAAK,MAAM,UAAU;AAClD,MAAI,QAAQ,IAAI,uBAAuB,UAAU,GAAG,QAAQ,QAAQ,IAAI;AAAA,IACtE,UAAU;AAAA,IACV,QAAQ,cAAc;AAAA,IACtB,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,QAAQ,kBAAkB;AAAA,EACpC,CAAC;AACD,SAAO;AACT;AAyBO,SAAS,sBACd,KACA,SACe;AACf,QAAM,UAAU,QAAQ,QAAQ,IAAI,0BAA0B;AAC9D,MAAI,QAAS,QAAO;AACpB,QAAM,aAAa,oBAAoB,OAAO;AAC9C,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,QAAM,cAAc,aAChB,uBAAuB,GAAG,IAC1B;AACJ,SAAO,IAAI,IAAI,WAAW,GAAG,SAAS,IAAI,IAAI,WAAW,GAAG,SAAS;AACvE;AAWO,MAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,kBAAkB;AACpB,CAAU;AAGH,SAAS,kBAAkB,SAAsC;AACtE,SACG,SACG,qBAAqB;AAE7B;","names":[]}
@@ -0,0 +1,12 @@
1
+ const STORE_PREVIEW_READ_ONLY_MESSAGE = "\u0110ang xem tr\u01B0\u1EDBc: ch\u01B0a th\u1EC3 \u0111\u1EB7t h\xE0ng khi c\u1EEDa h\xE0ng ch\u01B0a m\u1EDF c\u1EEDa.";
2
+ const STORE_PREVIEW_READ_ONLY_NOTICE = {
3
+ kind: "info",
4
+ code: "store_preview.read_only",
5
+ title: "\u0110ang xem tr\u01B0\u1EDBc",
6
+ description: "Ch\u01B0a th\u1EC3 \u0111\u1EB7t h\xE0ng khi c\u1EEDa h\xE0ng ch\u01B0a m\u1EDF c\u1EEDa."
7
+ };
8
+ export {
9
+ STORE_PREVIEW_READ_ONLY_MESSAGE,
10
+ STORE_PREVIEW_READ_ONLY_NOTICE
11
+ };
12
+ //# sourceMappingURL=store-preview-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/stores/store-preview-guard.ts"],"sourcesContent":["import type { Notice } from \"../notices\";\n\n/**\n * What the shopper sees when a store preview refuses a write. A preview is\n * read-only: the API opens GET and HEAD for a preview token and answers\n * every write on a coming soon store with `STORE_COMING_SOON`. So the cart\n * and checkout refuse in the browser first, without sending the request\n * (`isBrowserStorePreview()` in `api/store-preview-header.ts`).\n *\n * `placeOrder` returns the message; the cart writes notify the notice.\n */\nexport const STORE_PREVIEW_READ_ONLY_MESSAGE =\n \"Đang xem trước: chưa thể đặt hàng khi cửa hàng chưa mở cửa.\";\n\nexport const STORE_PREVIEW_READ_ONLY_NOTICE: Notice = {\n kind: \"info\",\n code: \"store_preview.read_only\",\n title: \"Đang xem trước\",\n description: \"Chưa thể đặt hàng khi cửa hàng chưa mở cửa.\",\n};\n"],"mappings":"AAWO,MAAM,kCACX;AAEK,MAAM,iCAAyC;AAAA,EACpD,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AACf;","names":[]}
@@ -1,4 +1,5 @@
1
1
  import { sdk } from "../sdk.js";
2
+ import { SKIP_STORE_PREVIEW } from "./store-preview-cookie.js";
2
3
  import { TtlCache } from "./ttl-cache.js";
3
4
  const TTL_MS = 6e4;
4
5
  const MAX_REFS = 1e4;
@@ -9,11 +10,15 @@ function clearStoreSubdomainCache() {
9
10
  async function getStoreSubdomain(storeRef) {
10
11
  const cached = byRef.get(storeRef);
11
12
  if (cached !== void 0) return cached;
12
- const store = await sdk.stores.getById(storeRef, {
13
- includeConfig: true,
14
- includeSettings: false,
15
- includeEmbeddedScripts: false
16
- });
13
+ const store = await sdk.stores.getById(
14
+ storeRef,
15
+ {
16
+ includeConfig: true,
17
+ includeSettings: false,
18
+ includeEmbeddedScripts: false
19
+ },
20
+ SKIP_STORE_PREVIEW
21
+ );
17
22
  const subdomain = store?.config?.subdomain || null;
18
23
  byRef.set(storeRef, subdomain, TTL_MS);
19
24
  return subdomain;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/store-subdomain.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { TtlCache } from \"./ttl-cache\";\n\nconst TTL_MS = 60_000;\nconst MAX_REFS = 10_000;\n\nconst byRef = new TtlCache<string | null>(MAX_REFS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreSubdomainCache(): void {\n byRef.clear();\n}\n\n/**\n * The platform subdomain label of the store `storeRef`, or null when there\n * is no such store or it has none. Throws when the API cannot be reached, so\n * the caller can tell \"no store\" from \"don't know\" (only the former is\n * cached).\n */\nexport async function getStoreSubdomain(\n storeRef: string\n): Promise<string | null> {\n const cached = byRef.get(storeRef);\n if (cached !== undefined) return cached;\n\n const store = await sdk.stores.getById(storeRef, {\n includeConfig: true,\n includeSettings: false,\n includeEmbeddedScripts: false,\n });\n const subdomain = store?.config?.subdomain || null;\n byRef.set(storeRef, subdomain, TTL_MS);\n return subdomain;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,gBAAgB;AAEzB,MAAM,SAAS;AACf,MAAM,WAAW;AAEjB,MAAM,QAAQ,IAAI,SAAwB,QAAQ;AAG3C,SAAS,2BAAiC;AAC/C,QAAM,MAAM;AACd;AAQA,eAAsB,kBACpB,UACwB;AACxB,QAAM,SAAS,MAAM,IAAI,QAAQ;AACjC,MAAI,WAAW,OAAW,QAAO;AAEjC,QAAM,QAAQ,MAAM,IAAI,OAAO,QAAQ,UAAU;AAAA,IAC/C,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,wBAAwB;AAAA,EAC1B,CAAC;AACD,QAAM,YAAY,OAAO,QAAQ,aAAa;AAC9C,QAAM,IAAI,UAAU,WAAW,MAAM;AACrC,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/store-subdomain.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { SKIP_STORE_PREVIEW } from \"./store-preview-cookie\";\nimport { TtlCache } from \"./ttl-cache\";\n\nconst TTL_MS = 60_000;\nconst MAX_REFS = 10_000;\n\nconst byRef = new TtlCache<string | null>(MAX_REFS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreSubdomainCache(): void {\n byRef.clear();\n}\n\n/**\n * The platform subdomain label of the store `storeRef`, or null when there\n * is no such store or it has none. Throws when the API cannot be reached, so\n * the caller can tell \"no store\" from \"don't know\" (only the former is\n * cached).\n */\nexport async function getStoreSubdomain(\n storeRef: string\n): Promise<string | null> {\n const cached = byRef.get(storeRef);\n if (cached !== undefined) return cached;\n\n // Cached for every visitor, and called from the middleware, where\n // `next/headers` is the raw incoming request: never with the ambient\n // preview token (as for a plain getStoreByHost).\n const store = await sdk.stores.getById(\n storeRef,\n {\n includeConfig: true,\n includeSettings: false,\n includeEmbeddedScripts: false,\n },\n SKIP_STORE_PREVIEW\n );\n const subdomain = store?.config?.subdomain || null;\n byRef.set(storeRef, subdomain, TTL_MS);\n return subdomain;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,0BAA0B;AACnC,SAAS,gBAAgB;AAEzB,MAAM,SAAS;AACf,MAAM,WAAW;AAEjB,MAAM,QAAQ,IAAI,SAAwB,QAAQ;AAG3C,SAAS,2BAAiC;AAC/C,QAAM,MAAM;AACd;AAQA,eAAsB,kBACpB,UACwB;AACxB,QAAM,SAAS,MAAM,IAAI,QAAQ;AACjC,MAAI,WAAW,OAAW,QAAO;AAKjC,QAAM,QAAQ,MAAM,IAAI,OAAO;AAAA,IAC7B;AAAA,IACA;AAAA,MACE,eAAe;AAAA,MACf,iBAAiB;AAAA,MACjB,wBAAwB;AAAA,IAC1B;AAAA,IACA;AAAA,EACF;AACA,QAAM,YAAY,OAAO,QAAQ,aAAa;AAC9C,QAAM,IAAI,UAAU,WAAW,MAAM;AACrC,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -47,7 +47,7 @@
47
47
  "currency.js": "^2.0.4",
48
48
  "server-only": "^0.0.1",
49
49
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.9.0"
50
+ "@ecomweb/sdk": "^0.11.0"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "next": ">=16",