@ecomweb/storefront-kit 0.14.1 → 0.16.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 (69) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +52 -1
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/server-sdk.js +41 -0
  16. package/dist/api/server-sdk.js.map +1 -0
  17. package/dist/api/store-preview-header.js.map +1 -1
  18. package/dist/auth/sdk.js +21 -6
  19. package/dist/auth/sdk.js.map +1 -1
  20. package/dist/auth/session-refresh.js +7 -4
  21. package/dist/auth/session-refresh.js.map +1 -1
  22. package/dist/cart/api.js.map +1 -1
  23. package/dist/checkout/get-payment-state.js +4 -8
  24. package/dist/checkout/get-payment-state.js.map +1 -1
  25. package/dist/checkout/initiate-gateway-payment.js +5 -7
  26. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  27. package/dist/checkout/order-handoff.js.map +1 -1
  28. package/dist/checkout/payment-redirect.js.map +1 -1
  29. package/dist/client-info.js +1 -1
  30. package/dist/config/public.js +2 -0
  31. package/dist/config/public.js.map +1 -1
  32. package/dist/config/schema.js +16 -4
  33. package/dist/config/schema.js.map +1 -1
  34. package/dist/config/secret-guard.js +20 -0
  35. package/dist/config/secret-guard.js.map +1 -0
  36. package/dist/config/server.js +15 -8
  37. package/dist/config/server.js.map +1 -1
  38. package/dist/config.d.ts +14 -4
  39. package/dist/config.js +2 -0
  40. package/dist/config.js.map +1 -1
  41. package/dist/index.d.ts +27 -68
  42. package/dist/index.js.map +1 -1
  43. package/dist/middleware/create-storefront-middleware.js +14 -3
  44. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  45. package/dist/middleware.d.ts +2 -2
  46. package/dist/{mode-DXo-EhTJ.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  47. package/dist/orders/api-client.js +3 -3
  48. package/dist/orders/api-client.js.map +1 -1
  49. package/dist/orders/bank-transfer.js +1 -1
  50. package/dist/orders/bank-transfer.js.map +1 -1
  51. package/dist/orders/use-order-status.js +2 -2
  52. package/dist/orders/use-order-status.js.map +1 -1
  53. package/dist/promotions/use-promotion-validation.js +2 -2
  54. package/dist/promotions/use-promotion-validation.js.map +1 -1
  55. package/dist/request/served-store.js +5 -0
  56. package/dist/request/served-store.js.map +1 -0
  57. package/dist/{schema-DIF0CZNV.d.ts → schema-B3nAYiwT.d.ts} +1 -1
  58. package/dist/sdk.js +3 -3
  59. package/dist/sdk.js.map +1 -1
  60. package/dist/server/routes.js +16 -9
  61. package/dist/server/routes.js.map +1 -1
  62. package/dist/server.d.ts +38 -5
  63. package/dist/server.js +2 -0
  64. package/dist/server.js.map +1 -1
  65. package/dist/shipping/use-shipping-calculation.js +2 -2
  66. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  67. package/package.json +6 -2
  68. package/dist/api/server-client.js +0 -162
  69. package/dist/api/server-client.js.map +0 -1
@@ -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\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,OAAO,EAAE,SAAS;AAAA,EACpC,0BAA0B,EAAE,OAAO,EAAE,SAAS;AAAA,EA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,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/** The message for a secret key found where the browser could read it. */\nexport const SECRET_IN_PUBLIC_MESSAGE =\n \"holds a secret key; secret keys go in server-only variables (ECOMWEB_SECRET_KEY, PLATFORM_SECRET_KEY)\";\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z\n .string()\n .min(1)\n .refine(v => !v.trim().startsWith(\"sk_\"), {\n message: SECRET_IN_PUBLIC_MESSAGE,\n }),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n /**\n * Signs every server-side call. Empty only while `next build` runs (builds\n * get no secret); read it through `storefrontSecretKey()`, which throws on\n * an empty one.\n */\n secretKey: z\n .string({ error: \"is required\" })\n .refine(v => !v.trim().startsWith(\"pk_\"), {\n message:\n \"is a publishable key; this variable takes the secret key (sk_...)\",\n }),\n clientIpForwarderSecret: z.string().min(1).optional(),\n appBaseUrl: z.string().min(1),\n appEnv: z.string().min(1),\n googleVerification: z.string().optional(),\n logLevel: z.enum(LOG_LEVELS).optional(),\n /**\n * The header carrying the shopper's IP that this server's edge sets and a\n * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it\n * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.\n */\n clientIpHeader: z.enum([\"x-forwarded-for\", \"cf-connecting-ip\"]),\n /**\n * Requests a minute to one store, on one server, above which the\n * multi-tenant middleware logs that store (log only, nothing is refused).\n * 0 turns it off.\n */\n storeTrafficLogPerMinute: z.number().int().min(0),\n});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\n\n/**\n * Thrown when the storefront's environment variables are missing or invalid.\n * The message names the variable behind every bad field.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>,\n notes: Record<string, string> = {}\n): T {\n const result = schema.safeParse(candidate);\n if (result.success) return result.data;\n const lines = result.error.issues.map(issue => {\n const field = String(issue.path[0] ?? \"\");\n const note = notes[field] ? ` ${notes[field]}` : \"\";\n return ` - ${envNameOf[field] ?? field}: ${issue.message}${note}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\n}\n\n/** A non-negative integer from `v`, else `fallback`. */\nexport function countOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\nexport function sampleRateOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1\n ? n\n : fallback;\n}\n"],"mappings":"AAAA,SAAS,SAAS;AAKlB,MAAM,aAAa,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAGvD,SAAS,SAAS,KAAgB,KAAiC;AACxE,QAAM,IAAI,IAAI,GAAG,GAAG,KAAK;AACzB,SAAO,IAAI,IAAI;AACjB;AAEO,SAAS,WAAW,GAA6C;AACtE,SAAQ,WAAiC,SAAS,KAAK,EAAE,IACpD,IACD;AACN;AAGO,MAAM,2BACX;AAGF,MAAM,UAAU,EAAE,IAAI,EAAE,UAAU,WAAW,CAAC;AAEvC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,MAAM,EAAE,KAAK,CAAC,SAAS,QAAQ,CAAC;AAAA,EAChC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACrC,QAAQ;AAAA,EACR,cAAc,EAAE,OAAO;AAAA,EACvB,QAAQ;AAAA,EACR,kBAAkB,EACf,OAAO,EACP,IAAI,CAAC,EACL,OAAO,OAAK,CAAC,EAAE,KAAK,EAAE,WAAW,KAAK,GAAG;AAAA,IACxC,SAAS;AAAA,EACX,CAAC;AAAA,EACH,sBAAsB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACjD,gBAAgB,EAAE,OAAO,EAAE,SAAS;AAAA,EACpC,0BAA0B,EAAE,OAAO,EAAE,SAAS;AAAA,EAC9C,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,UAAU,EAAE,KAAK,UAAU,EAAE,SAAS;AAAA,EACtC,qBAAqB,EAAE,OAAO,EAAE,I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sC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;AAGO,SAAS,QAAQ,GAAuB,UAA0B;AACvE,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,UAAU,CAAC,KAAK,KAAK,IAAI,IAAI;AAChE;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
@@ -0,0 +1,20 @@
1
+ import {
2
+ ConfigError,
3
+ SECRET_IN_PUBLIC_MESSAGE
4
+ } from "./schema.js";
5
+ function isSecretKeyValue(value) {
6
+ return value?.trim().startsWith("sk_") ?? false;
7
+ }
8
+ function assertNoSecretInPublicEnv(env) {
9
+ const leaked = Object.keys(env).filter((key) => key.startsWith("NEXT_PUBLIC_") && isSecretKeyValue(env[key])).sort();
10
+ if (leaked.length === 0) return;
11
+ throw new ConfigError(
12
+ `Invalid storefront configuration:
13
+ ${leaked.map((key) => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`).join("\n")}`
14
+ );
15
+ }
16
+ export {
17
+ assertNoSecretInPublicEnv,
18
+ isSecretKeyValue
19
+ };
20
+ //# sourceMappingURL=secret-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/secret-guard.ts"],"sourcesContent":["import {\n ConfigError,\n SECRET_IN_PUBLIC_MESSAGE,\n type EnvSource,\n} from \"./schema\";\n\n/** True when `value` is a secret key (`sk_` prefix, ignoring whitespace). */\nexport function isSecretKeyValue(value: string | undefined): boolean {\n return value?.trim().startsWith(\"sk_\") ?? false;\n}\n\n/**\n * Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those\n * into the browser bundle. The error names every offending variable and never\n * prints a value.\n *\n * @param env The environment to check.\n * @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.\n */\nexport function assertNoSecretInPublicEnv(env: EnvSource): void {\n const leaked = Object.keys(env)\n .filter(key => key.startsWith(\"NEXT_PUBLIC_\") && isSecretKeyValue(env[key]))\n .sort();\n if (leaked.length === 0) return;\n throw new ConfigError(\n `Invalid storefront configuration:\\n${leaked\n .map(key => ` - ${key}: ${SECRET_IN_PUBLIC_MESSAGE}`)\n .join(\"\\n\")}`\n );\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAGA,SAAS,iBAAiB,OAAoC;AACnE,SAAO,OAAO,KAAK,EAAE,WAAW,KAAK,KAAK;AAC5C;AAUO,SAAS,0BAA0B,KAAsB;AAC9D,QAAM,SAAS,OAAO,KAAK,GAAG,EAC3B,OAAO,SAAO,IAAI,WAAW,cAAc,KAAK,iBAAiB,IAAI,GAAG,CAAC,CAAC,EAC1E,KAAK;AACR,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,OACnC,IAAI,SAAO,OAAO,GAAG,KAAK,wBAAwB,EAAE,EACpD,KAAK,IAAI,CAAC;AAAA,EACf;AACF;","names":[]}
@@ -1,5 +1,6 @@
1
1
  import "server-only";
2
2
  import { resolveMode } from "./mode.js";
3
+ import { assertNoSecretInPublicEnv } from "./secret-guard.js";
3
4
  import {
4
5
  countOf,
5
6
  envValue,
@@ -7,11 +8,18 @@ import {
7
8
  parseOrThrow,
8
9
  serverConfigSchema
9
10
  } from "./schema.js";
11
+ function secretOf(env, name) {
12
+ const value = envValue(env, name);
13
+ if (value === void 0 && env.NEXT_PHASE === "phase-production-build") {
14
+ return "";
15
+ }
16
+ return value;
17
+ }
10
18
  function parseMulti(env) {
11
19
  return parseOrThrow(
12
20
  serverConfigSchema,
13
21
  {
14
- platformApiKey: envValue(env, "PLATFORM_API_KEY") ?? envValue(env, "NEXT_PUBLIC_PLATFORM_API_KEY"),
22
+ secretKey: secretOf(env, "PLATFORM_SECRET_KEY"),
15
23
  clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
16
24
  appBaseUrl: envValue(env, "APP_BASE_URL") ?? "http://localhost:3002",
17
25
  appEnv: envValue(env, "APP_ENV") ?? "unknown",
@@ -24,19 +32,17 @@ function parseMulti(env) {
24
32
  )
25
33
  },
26
34
  {
27
- platformApiKey: "PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY",
35
+ secretKey: "PLATFORM_SECRET_KEY",
28
36
  clientIpHeader: "CLIENT_IP_HEADER"
29
- }
37
+ },
38
+ envValue(env, "PLATFORM_API_KEY") ? { secretKey: "(PLATFORM_API_KEY is retired)" } : {}
30
39
  );
31
40
  }
32
41
  function parseSingle(env) {
33
42
  return parseOrThrow(
34
43
  serverConfigSchema,
35
44
  {
36
- // The key is publishable, and next.config inlines it at build time as
37
- // NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg
38
- // still runs when the runtime env does not repeat it.
39
- platformApiKey: envValue(env, "ECOMWEB_PUBLISHABLE_KEY") ?? envValue(env, "NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY"),
45
+ secretKey: secretOf(env, "ECOMWEB_SECRET_KEY"),
40
46
  clientIpForwarderSecret: envValue(env, "CLIENT_IP_FORWARDER_SECRET"),
41
47
  appBaseUrl: envValue(env, "SITE_URL") ?? "http://localhost:3000",
42
48
  appEnv: envValue(env, "APP_ENV") ?? "production",
@@ -47,12 +53,13 @@ function parseSingle(env) {
47
53
  storeTrafficLogPerMinute: 0
48
54
  },
49
55
  {
50
- platformApiKey: "ECOMWEB_PUBLISHABLE_KEY",
56
+ secretKey: "ECOMWEB_SECRET_KEY",
51
57
  clientIpHeader: "CLIENT_IP_HEADER"
52
58
  }
53
59
  );
54
60
  }
55
61
  function parseServerConfig(env) {
62
+ assertNoSecretInPublicEnv(env);
56
63
  return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
57
64
  }
58
65
  let cached;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n 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,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA,MACrD,0BAA0B;AAAA,QACxB,SAAS,KAAK,8BAA8B;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAA8B;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,MAIE,gBACE,SAAS,KAAK,yBAAyB,KACvC,SAAS,KAAK,qCAAqC;AAAA,MACrD,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,UAAU,KAAK;AAAA,MACzC,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA;AAAA,MAErD,0BAA0B;AAAA,IAC5B;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAEG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAUO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,GAAG,QAAQ;AAAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport { assertNoSecretInPublicEnv } from \"./secret-guard\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\n/**\n * The secret key, from the runtime env only (never a NEXT_PUBLIC_ fallback).\n * `next build` gets none (hosted builds hold no secret), so while it runs a\n * missing key reads as empty; `storefrontSecretKey()` throws on an empty one.\n */\nfunction secretOf(env: EnvSource, name: string): string | undefined {\n const value = envValue(env, name);\n if (value === undefined && env.NEXT_PHASE === \"phase-production-build\") {\n return \"\";\n }\n return value;\n}\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"PLATFORM_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"APP_BASE_URL\") ?? \"http://localhost:3002\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"unknown\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n storeTrafficLogPerMinute: countOf(\n envValue(env, \"STORE_TRAFFIC_LOG_PER_MINUTE\"),\n 600\n ),\n },\n {\n secretKey: \"PLATFORM_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n },\n envValue(env, \"PLATFORM_API_KEY\")\n ? { secretKey: \"(PLATFORM_API_KEY is retired)\" }\n : {}\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n secretKey: secretOf(env, \"ECOMWEB_SECRET_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"SITE_URL\") ?? \"http://localhost:3000\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"production\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n // One store per site: there are no neighbours to watch.\n storeTrafficLogPerMinute: 0,\n },\n {\n secretKey: \"ECOMWEB_SECRET_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parseServerConfig(env: EnvSource): ServerConfig {\n assertNoSecretInPublicEnv(env);\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\n\n/**\n * The server's parsed configuration, read from the environment on the first\n * call and cached. Server-only: import it from `@ecomweb/storefront-kit/server`\n * in server code, never in a client component.\n *\n * @returns The validated server config.\n * @throws ConfigError when a required variable is missing or invalid.\n */\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAOP,SAAS,SAAS,KAAgB,MAAkC;AAClE,QAAM,QAAQ,SAAS,KAAK,IAAI;AAChC,MAAI,UAAU,UAAa,IAAI,eAAe,0BAA0B;AACtE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,WAAW,SAAS,KAAK,qBAAqB;AAAA,MAC9C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK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,CAAC;AACH;","names":[]}
package/dist/config.d.ts CHANGED
@@ -1,6 +1,6 @@
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';
1
+ import { E as EnvSource, P as PublicConfig } from './schema-B3nAYiwT.js';
2
+ export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-B3nAYiwT.js';
3
+ export { S as StorefrontMode, r as resolveMode } from './mode-oVZCQxrc.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Parses the variables of the mode `env` selects (see resolveMode). */
@@ -13,6 +13,16 @@ declare function resetPublicConfigForTests(): void;
13
13
  */
14
14
  declare function publicConfig(): PublicConfig;
15
15
 
16
+ /**
17
+ * Refuses a secret key in any `NEXT_PUBLIC_*` variable: Next inlines those
18
+ * into the browser bundle. The error names every offending variable and never
19
+ * prints a value.
20
+ *
21
+ * @param env The environment to check.
22
+ * @throws ConfigError listing each `NEXT_PUBLIC_*` variable that holds a secret key.
23
+ */
24
+ declare function assertNoSecretInPublicEnv(env: EnvSource): void;
25
+
16
26
  /**
17
27
  * This package's version, baked in at build time. `dev` when the source runs
18
28
  * without the define (the API ignores a version that isn't semver).
@@ -82,4 +92,4 @@ declare function formatClientVersionWarning(report: ClientVersionReport): string
82
92
  */
83
93
  declare function checkClientVersions(options?: CheckClientVersionsOptions): Promise<ClientVersionReport | null>;
84
94
 
85
- export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
95
+ export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, assertNoSecretInPublicEnv, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
package/dist/config.js CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  } from "./config/public.js";
6
6
  import { resolveMode } from "./config/mode.js";
7
7
  import { ConfigError } from "./config/schema.js";
8
+ import { assertNoSecretInPublicEnv } from "./config/secret-guard.js";
8
9
  import { KIT_CLIENT_TOKEN, KIT_VERSION } from "./client-info.js";
9
10
  import {
10
11
  checkClientVersions,
@@ -14,6 +15,7 @@ export {
14
15
  ConfigError,
15
16
  KIT_CLIENT_TOKEN,
16
17
  KIT_VERSION,
18
+ assertNoSecretInPublicEnv,
17
19
  checkClientVersions,
18
20
  formatClientVersionWarning,
19
21
  parsePublicConfig,
@@ -1 +1 @@
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
+ {"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Parsing and types for the storefront's configuration: public (client-safe)\n * settings, the deployment mode, the build-time version check and\n * `ConfigError`.\n *\n * Import from `@ecomweb/storefront-kit/config` in `next.config` and config\n * code. It has no React or server-only dependency.\n *\n * @packageDocumentation\n */\nexport {\n parsePublicConfig,\n publicConfig,\n // For specs that stub env per test (the config is memoized on first read).\n resetPublicConfigForTests,\n} from \"./config/public\";\nexport { resolveMode } from \"./config/mode\";\nexport type { StorefrontMode } from \"./config/mode\";\nexport { ConfigError } from \"./config/schema\";\nexport { assertNoSecretInPublicEnv } from \"./config/secret-guard\";\nexport type {\n EnvSource,\n LogLevel,\n PublicConfig,\n ServerConfig,\n} from \"./config/schema\";\nexport { KIT_CLIENT_TOKEN, KIT_VERSION } from \"./client-info\";\nexport {\n checkClientVersions,\n formatClientVersionWarning,\n} from \"./config/version-check\";\nexport type {\n CheckClientVersionsOptions,\n ClientVersionReport,\n ClientVersionStatus,\n} from \"./config/version-check\";\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B,SAAS,iCAAiC;AAO1C,SAAS,kBAAkB,mBAAmB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;","names":[]}
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as react from 'react';
3
3
  import { ReactNode, ReactElement } from 'react';
4
4
  import * as _ecomweb_sdk from '@ecomweb/sdk';
5
- import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, ShippingOption, OrderStatus, Order, CreateOrderRequest, ShipmentStatus, OrderShipmentSummary, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
5
+ import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, ShippingOption, OrderStatus, Order, CreateOrderRequest, ShipmentStatus, OrderShipmentSummary, EcomwebServerSdk, EcomwebSdk, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
6
+ export { EcomwebSdk, EcomwebServerSdk } from '@ecomweb/sdk';
6
7
  import currencyJs from 'currency.js';
7
8
  import { AxiosRequestConfig, AxiosInstance } from 'axios';
8
9
  export { AnyThemeDefinition, BlogIndexSlotProps, BlogPostSlotProps, CollectionPageSlotProps, CollectionSearchParams, ContentPageSlotProps, HomePageSlotProps, LayoutSlotProps, NotFoundProps, ProductCardProps, ProductPageSlotProps, ThemeClientComponents, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
@@ -553,6 +554,8 @@ interface ApiResponse<T = any> {
553
554
  data?: T;
554
555
  error?: ApiError;
555
556
  success: boolean;
557
+ /** The response headers, names in lowercase (totals ride in `x-total-count`). */
558
+ headers?: Record<string, string>;
556
559
  }
557
560
  interface RequestConfig {
558
561
  headers?: Record<string, string>;
@@ -583,6 +586,13 @@ declare class ApiClient implements AuthenticatedApiClient {
583
586
  private setupInterceptors;
584
587
  private handleResponse;
585
588
  private handleError;
589
+ /**
590
+ * The direct, publishable-key client cannot call a private route: the API
591
+ * would refuse it, so refuse here, before the network. Logs the matched
592
+ * route pattern, never the raw path (it can carry a review token or an
593
+ * order code).
594
+ */
595
+ private refusePrivateRoute;
586
596
  get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
587
597
  post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
588
598
  put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
@@ -852,26 +862,13 @@ interface PollPaymentStateOptions {
852
862
  declare function pollPaymentState(options: PollPaymentStateOptions): Promise<PollOutcome>;
853
863
 
854
864
  /**
855
- * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.
856
- *
857
- * `sdk.payments` was added by this plan's Task 2
858
- * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),
859
- * but that SDK PR is not yet merged to `main`, and this repo's lockfile
860
- * pins an older `@ecomweb/sdk` commit that has no `payments` module at all
861
- * — see `lib/checkout/initiate-gateway-payment.ts` for the full story
862
- * (same pinned commit, same missing module). Running
863
- * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task
864
- * — it is a deliberate later step in the plan.
865
+ * Reads where a payment stands for an order, from the browser, through the
866
+ * store's backend proxy (`createStoreSdk`), which adds the secret key. Browser
867
+ * only: the proxied SDK uses a relative URL. On a server use `getServerSdk()`.
865
868
  *
866
- * This function mirrors `PaymentsApi.getPaymentState()`'s request/response
867
- * shape exactly (same path, same result shape) so that once the SDK bump
868
- * lands, the fix is: delete this file, delete this import in
869
- * `payment-state-poll`'s caller, and call
870
- * `sdk.payments.getPaymentState(...)` instead — the call site already reads
871
- * as if it were doing that today.
872
- *
873
- * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past
874
- * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.
869
+ * @param storeRef - the store's ref
870
+ * @param order_code - the order's code
871
+ * @returns the payment state of the order
875
872
  */
876
873
  declare function getPaymentState(storeRef: string, order_code: string): Promise<PaymentStateResult>;
877
874
 
@@ -914,7 +911,7 @@ declare const publicOrdersApi: {
914
911
  * `isAuth` comes from the caller's auth context — this module is not a
915
912
  * component and must not read context or an httpOnly cookie itself.
916
913
  *
917
- * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which
914
+ * When true the SDK posts to `/storefront/stores/:ref/customers/orders`, which
918
915
  * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`
919
916
  * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no
920
917
  * such fields to carry them in. The request reaches that guarded route
@@ -1027,58 +1024,20 @@ interface PromotionDescriptionData {
1027
1024
  */
1028
1025
  declare function getPromotionDescription(promotion: PromotionDescriptionData, locale?: string, currency?: string): string;
1029
1026
 
1030
- declare const sdk: {
1031
- products: _ecomweb_sdk.ProductsApi;
1032
- collections: _ecomweb_sdk.CollectionsApi;
1033
- categories: _ecomweb_sdk.CategoriesApi;
1034
- cart: _ecomweb_sdk.CartApi;
1035
- orders: _ecomweb_sdk.OrdersApi;
1036
- blog: _ecomweb_sdk.BlogApi;
1037
- stores: _ecomweb_sdk.StoresApi;
1038
- themes: _ecomweb_sdk.ThemesApi;
1039
- metaobjects: _ecomweb_sdk.MetaobjectsApi;
1040
- search: _ecomweb_sdk.SearchApi;
1041
- shipping: _ecomweb_sdk.ShippingApi;
1042
- promotions: _ecomweb_sdk.PromotionsApi;
1043
- paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
1044
- payments: _ecomweb_sdk.PaymentsApi;
1045
- reviews: _ecomweb_sdk.ReviewsApi;
1046
- customers: _ecomweb_sdk.CustomersApi;
1047
- addresses: _ecomweb_sdk.AddressesApi;
1048
- contentPages: _ecomweb_sdk.ContentPagesApi;
1049
- menus: _ecomweb_sdk.MenusApi;
1050
- redirects: _ecomweb_sdk.RedirectsApi;
1051
- };
1027
+ declare const sdk: EcomwebSdk;
1052
1028
  /**
1053
- * SDK bound to one store, whose authenticated modules (cart, orders, blog
1054
- * comments, customers, addresses) go through the same-origin proxy route so the
1055
- * httpOnly session cookie can be turned into a bearer token server-side.
1029
+ * SDK bound to one store, for the browser. Public calls go straight to the
1030
+ * API with the publishable key; every private call (cart, orders, payments,
1031
+ * customers, addresses, shopper-side blog, review and metaobject calls, rate
1032
+ * calculation, promotion validation) goes to the same-origin proxy at
1033
+ * `/store/<ref>/api/backend` (`/api/backend` on a single-store site), which
1034
+ * adds the storefront secret key and turns the httpOnly session cookie into a
1035
+ * bearer token. The secret key never reaches the browser.
1056
1036
  *
1057
1037
  * Memoised per store so the returned object is referentially stable and safe to
1058
1038
  * use in a React dependency array.
1059
1039
  */
1060
- declare function createStoreSdk(storeRef: string): {
1061
- products: _ecomweb_sdk.ProductsApi;
1062
- collections: _ecomweb_sdk.CollectionsApi;
1063
- categories: _ecomweb_sdk.CategoriesApi;
1064
- cart: _ecomweb_sdk.CartApi;
1065
- orders: _ecomweb_sdk.OrdersApi;
1066
- blog: _ecomweb_sdk.BlogApi;
1067
- stores: _ecomweb_sdk.StoresApi;
1068
- themes: _ecomweb_sdk.ThemesApi;
1069
- metaobjects: _ecomweb_sdk.MetaobjectsApi;
1070
- search: _ecomweb_sdk.SearchApi;
1071
- shipping: _ecomweb_sdk.ShippingApi;
1072
- promotions: _ecomweb_sdk.PromotionsApi;
1073
- paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
1074
- payments: _ecomweb_sdk.PaymentsApi;
1075
- reviews: _ecomweb_sdk.ReviewsApi;
1076
- customers: _ecomweb_sdk.CustomersApi;
1077
- addresses: _ecomweb_sdk.AddressesApi;
1078
- contentPages: _ecomweb_sdk.ContentPagesApi;
1079
- menus: _ecomweb_sdk.MenusApi;
1080
- redirects: _ecomweb_sdk.RedirectsApi;
1081
- };
1040
+ declare function createStoreSdk(storeRef: string): EcomwebServerSdk;
1082
1041
 
1083
1042
  /**
1084
1043
  * Renders a shipping option's price for display: the free label when the
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Client-safe hooks, providers and helpers for building a storefront on\n * ecomweb: `StorefrontKitProvider`, `useCart`, `useAuth`, `useCheckout`,\n * the store hooks, and price and order formatting.\n *\n * Import from `@ecomweb/storefront-kit` in components and pages. Server-only\n * code lives in `@ecomweb/storefront-kit/server`.\n *\n * @packageDocumentation\n */\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport {\n pickBankTransfer,\n shouldShowBankTransferDetails,\n useBankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n BankAccountView,\n BankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AAUA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAKjC,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AACxC,SAAS,kBAAkB;AAC3B,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAqB1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uCAAuC;AAChD,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Client-safe hooks, providers and helpers for building a storefront on\n * ecomweb: `StorefrontKitProvider`, `useCart`, `useAuth`, `useCheckout`,\n * the store hooks, and price and order formatting.\n *\n * Import from `@ecomweb/storefront-kit` in components and pages. Server-only\n * code lives in `@ecomweb/storefront-kit/server`.\n *\n * @packageDocumentation\n */\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport {\n pickBankTransfer,\n shouldShowBankTransferDetails,\n useBankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n BankAccountView,\n BankTransferDetails,\n} from \"./orders/bank-transfer\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { quoteChangedOptionsFrom } from \"./checkout/quote-changed\";\nexport { optionIdOf } from \"./shipping/option-id\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport {\n SHIPMENT_STATUS_LABELS,\n TRACKING_MESSAGES,\n canCustomerCancel,\n deriveShipmentTracking,\n isCarrierShipment,\n isHandedToCarrier,\n shipmentEventLabel,\n} from \"./orders/shipment-tracking\";\nexport type { ShipmentTrackingView } from \"./orders/shipment-tracking\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport type { EcomwebSdk, EcomwebServerSdk } from \"@ecomweb/sdk\";\nexport {\n formatShippingAmount,\n describeShippingOption,\n type ShippingOptionDisplay,\n} from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n COMING_SOON_STORE_DESCRIPTION,\n comingSoonStoreMetadata,\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { STORE_PREVIEW_READ_ONLY_MESSAGE } from \"./stores/store-preview-guard\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"./stores/store-coming-soon\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AAUA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAA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ACK;AACP,SAAS,uBAAuB;AAChC,SAAS,uCAAuC;AAChD,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
@@ -1,5 +1,6 @@
1
1
  import { publicNextUrl } from "../request/public-url.js";
2
2
  import { REQUEST_PATH_HEADER } from "../request/request-path.js";
3
+ import { SERVED_STORE_HEADER } from "../request/served-store.js";
3
4
  import {
4
5
  applyThemePreview,
5
6
  hasThemePreview,
@@ -75,6 +76,7 @@ function withoutInternalHeaders(req) {
75
76
  const headers = new Headers(req.headers);
76
77
  headers.delete(THEME_PREVIEW_HOST_HEADER);
77
78
  headers.delete(STORE_PREVIEW_TOKEN_HEADER);
79
+ headers.delete(SERVED_STORE_HEADER);
78
80
  return { request: { headers } };
79
81
  }
80
82
  function hasStorePreview(req, cookiePath) {
@@ -86,6 +88,11 @@ function hostLookupPreviewToken(req) {
86
88
  req.cookies.get(themePreviewCookieName("/"))?.value
87
89
  );
88
90
  }
91
+ function isLocalDevelopmentHost(host) {
92
+ if (process.env.NODE_ENV === "production") return false;
93
+ const hostname = host.startsWith("[") ? host.slice(0, host.indexOf("]") + 1) : host.split(":")[0];
94
+ return ["localhost", "127.0.0.1", "[::1]"].includes(hostname.toLowerCase());
95
+ }
89
96
  function storeRefFromPath(pathname) {
90
97
  const match = /^\/store\/([^/]+)/.exec(pathname);
91
98
  if (!match) return null;
@@ -139,7 +146,8 @@ async function multiTenant(req) {
139
146
  return NextResponse.next(withoutInternalHeaders(req));
140
147
  }
141
148
  const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
142
- const hostIdentifiesStore = !host.includes("localhost") && !host.includes("127.0.0.1") && host !== platformDomain && host !== `www.${platformDomain}`;
149
+ const isLocalDevHost = isLocalDevelopmentHost(host);
150
+ const hostIdentifiesStore = !isLocalDevHost && host !== platformDomain && host !== `www.${platformDomain}`;
143
151
  const isPlatformApex = host === platformDomain || host === `www.${platformDomain}`;
144
152
  if (isPlatformApex) {
145
153
  const apexStoreRef = storeRefFromPath(pathname);
@@ -240,7 +248,10 @@ async function multiTenant(req) {
240
248
  req,
241
249
  !!hostStoreRef,
242
250
  storeRef,
243
- rotated
251
+ rotated,
252
+ // A store host's own lookup decides (none if it failed). Only the local
253
+ // dev host is path-based; anywhere else the path names no served store.
254
+ isLocalDevHost ? storeRefFromPath(pathname) : hostIdentifiesStore ? hostStoreRef : null
244
255
  );
245
256
  downstream.set(
246
257
  REQUEST_PATH_HEADER,
@@ -309,7 +320,7 @@ async function singleStore(req) {
309
320
  const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);
310
321
  const response = NextResponse.next({
311
322
  request: {
312
- headers: downstreamRequestHeaders(req, true, storeRef, rotated)
323
+ headers: downstreamRequestHeaders(req, true, storeRef, rotated, storeRef)
313
324
  }
314
325
  });
315
326
  if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))