@ecomweb/storefront-kit 0.13.1 → 0.14.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.
package/README.md CHANGED
@@ -166,3 +166,29 @@ component.
166
166
  Semver. Within 1.x no export is removed and no required prop or parameter
167
167
  is added. Before 1.0, a minor (0.x) release may break; your caret range
168
168
  (`^0.y.z`) only takes the patches of your minor.
169
+
170
+ ## Version reporting and update warnings
171
+
172
+ Every SDK request the kit makes sends
173
+ `X-Ecomweb-Client: @ecomweb/storefront-kit/<version> @ecomweb/sdk/<version>`
174
+ (versions baked in at build), so the dashboard can tell a store owner when the
175
+ storefront runs an old or insecure kit.
176
+
177
+ `checkClientVersions` (`@ecomweb/storefront-kit/config`) warns at build time.
178
+ Call it from `next.config.mjs` with Next's `phase`; it does nothing outside
179
+ `next build`, gives up after 2 s and never fails the build. Set
180
+ `ECOMWEB_SKIP_VERSION_CHECK=1` to turn it off.
181
+
182
+ ```js
183
+ import { checkClientVersions } from "@ecomweb/storefront-kit/config";
184
+
185
+ export default async function config(phase) {
186
+ await checkClientVersions({ phase, apiUrl: process.env.ECOMWEB_API_URL });
187
+ return nextConfig;
188
+ }
189
+ ```
190
+
191
+ To update: `ecomweb storefront upgrade`
192
+ ([guide](https://help.ecomweb.app/guides/storefront/upgrade-kit)); release
193
+ notes are the releases of
194
+ [ecomwebai/ecomweb-storefront-sdk](https://github.com/ecomwebai/ecomweb-storefront-sdk).
package/dist/auth/sdk.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import "server-only";
2
- import { AuthApi } from "@ecomweb/sdk";
2
+ import { AuthApi, withClientHeader } from "@ecomweb/sdk";
3
3
  import { forwardingHeaders } from "./client-ip.js";
4
+ import { KIT_CLIENT_TOKEN } from "../client-info.js";
4
5
  import { publicConfig } from "../config.js";
5
6
  import { serverConfig } from "../config/server.js";
6
7
  import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
@@ -69,7 +70,10 @@ function authHttpClient(clientIp, previewToken) {
69
70
  };
70
71
  }
71
72
  function createAuthApi(storeRef, clientIp, previewToken) {
72
- return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);
73
+ return new AuthApi(
74
+ withClientHeader(authHttpClient(clientIp, previewToken), KIT_CLIENT_TOKEN),
75
+ storeRef
76
+ );
73
77
  }
74
78
  export {
75
79
  authHttpClient,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi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B,QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI,QAAQ,eAAe,UAAU,YAAY,GAAG,QAAQ;AACrE;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\n return new AuthApi(\n withClientHeader(authHttpClient(clientIp, previewToken), KIT_CLIENT_TOKEN),\n storeRef\n );\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,SAAS,wBAAwB;AAE1C,SAAS,yBAAyB;AAClC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAQ9B,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAWO,SAAS,mBAA2B;AACzC,SAAO,aAAa,EAAE;AACxB;AAEA,eAAe,KACb,QACA,KACA,MACA,SACA,UACA,cACyB;AACzB,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,GAAG,IAAI;AAAA,MACxD;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,wBAAwB,iBAAiB;AAAA;AAAA;AAAA,QAGzC,GAAI,gBAAgB,WAAW,QAC3B,EAAE,CAAC,oBAAoB,GAAG,aAAa,IACvC,CAAC;AAAA,QACL,GAAI,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMzB,GAAG,kBAAkB,QAAQ;AAAA,MAC/B;AAAA,MACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AA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ENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;
3
+ export {
4
+ KIT_CLIENT_TOKEN,
5
+ KIT_VERSION
6
+ };
7
+ //# sourceMappingURL=client-info.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client-info.ts"],"sourcesContent":["// Replaced at build time (tsup `define`, and the workspace's Next and vitest\n// configs) with this package's version from package.json.\ndeclare const __ECOMWEB_KIT_VERSION__: string | undefined;\n\n/**\n * This package's version, baked in at build time. `dev` when the source runs\n * without the define (the API ignores a version that isn't semver).\n */\nexport const KIT_VERSION: string =\n typeof __ECOMWEB_KIT_VERSION__ === \"string\" ? __ECOMWEB_KIT_VERSION__ : \"dev\";\n\n/** The kit's token in `X-Ecomweb-Client`, put before the SDK's own. */\nexport const KIT_CLIENT_TOKEN = `@ecomweb/storefront-kit/${KIT_VERSION}`;\n"],"mappings":"AAQO,MAAM,cACX,OAA8C,WAA0B;AAGnE,MAAM,mBAAmB,2BAA2B,WAAW;","names":[]}
@@ -0,0 +1,94 @@
1
+ import { SDK_VERSION } from "@ecomweb/sdk";
2
+ import { KIT_VERSION } from "../client-info.js";
3
+ const PRODUCTION_BUILD_PHASE = "phase-production-build";
4
+ const DEFAULT_API_URL = "https://apibase.ecomweb.app/api/v1";
5
+ const DEFAULT_TIMEOUT_MS = 2e3;
6
+ const CHECKED_FLAG = "__ECOMWEB_VERSION_CHECKED";
7
+ const KIT_PACKAGE = "@ecomweb/storefront-kit";
8
+ const SDK_PACKAGE = "@ecomweb/sdk";
9
+ function parseSemver(v) {
10
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v?.trim() ?? "");
11
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
12
+ }
13
+ function isBelow(a, b) {
14
+ const x = parseSemver(a);
15
+ const y = parseSemver(b);
16
+ if (!x || !y) return false;
17
+ for (let i = 0; i < 3; i++) {
18
+ if (x[i] !== y[i]) return x[i] < y[i];
19
+ }
20
+ return false;
21
+ }
22
+ function judge(pkg, installed, body) {
23
+ if (!parseSemver(installed)) return null;
24
+ const policy = body.packages?.[pkg];
25
+ if (!policy) return null;
26
+ const advisories = (body.advisories ?? []).filter(
27
+ (a) => a.package === pkg && isBelow(installed, a.fixed_in)
28
+ );
29
+ const status = isBelow(installed, policy.security_minimum) ? "security_update" : isBelow(installed, policy.minimum_supported) ? "unsupported" : isBelow(installed, policy.latest) ? "update_available" : "up_to_date";
30
+ return {
31
+ status,
32
+ package: pkg,
33
+ installed,
34
+ latest: policy.latest,
35
+ advisories,
36
+ upgradeGuideUrl: body.upgrade_guide_url
37
+ };
38
+ }
39
+ const SEVERITY = {
40
+ up_to_date: 0,
41
+ update_available: 1,
42
+ unsupported: 2,
43
+ security_update: 3
44
+ };
45
+ function formatClientVersionWarning(report) {
46
+ const behind = `${report.package} ${report.installed}`;
47
+ const latest = report.latest ? ` (latest ${report.latest})` : "";
48
+ const headline = report.status === "security_update" ? `ecomweb: security update available: ${behind} has known security issues${latest}.` : report.status === "unsupported" ? `ecomweb: ${behind} is no longer supported${latest}.` : `ecomweb: update available: ${behind}${latest}.`;
49
+ const lines = [headline];
50
+ for (const a of report.advisories) {
51
+ const fixed = a.fixed_in ? ` (fixed in ${a.fixed_in})` : "";
52
+ lines.push(` - ${a.summary ?? a.id ?? "advisory"}${fixed}`);
53
+ }
54
+ lines.push(" Update with: ecomweb storefront upgrade");
55
+ if (report.upgradeGuideUrl) lines.push(` Guide: ${report.upgradeGuideUrl}`);
56
+ lines.push(" (Set ECOMWEB_SKIP_VERSION_CHECK=1 to skip this check.)");
57
+ return lines.join("\n");
58
+ }
59
+ async function checkClientVersions(options = {}) {
60
+ const env = options.env ?? process.env;
61
+ if (options.phase !== PRODUCTION_BUILD_PHASE) return null;
62
+ if (env.ECOMWEB_SKIP_VERSION_CHECK?.trim() === "1") return null;
63
+ if (env[CHECKED_FLAG] === "1") return null;
64
+ env[CHECKED_FLAG] = "1";
65
+ try {
66
+ const base = (options.apiUrl?.trim() || DEFAULT_API_URL).replace(/\/+$/, "");
67
+ const doFetch = options.fetch ?? fetch;
68
+ const response = await doFetch(`${base}/public/storefront-clients/versions`, {
69
+ headers: { accept: "application/json" },
70
+ signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
71
+ });
72
+ if (!response.ok) return null;
73
+ const body = await response.json();
74
+ const reports = [
75
+ judge(KIT_PACKAGE, options.installed?.kit ?? KIT_VERSION, body),
76
+ judge(SDK_PACKAGE, options.installed?.sdk ?? SDK_VERSION, body)
77
+ ].filter((r) => r !== null);
78
+ if (reports.length === 0) return null;
79
+ const worst = reports.reduce(
80
+ (a, b) => SEVERITY[b.status] > SEVERITY[a.status] ? b : a
81
+ );
82
+ if (worst.status !== "up_to_date") {
83
+ (options.warn ?? console.warn)(formatClientVersionWarning(worst));
84
+ }
85
+ return worst;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ export {
91
+ checkClientVersions,
92
+ formatClientVersionWarning
93
+ };
94
+ //# sourceMappingURL=version-check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/version-check.ts"],"sourcesContent":["import { SDK_VERSION } from \"@ecomweb/sdk\";\nimport { KIT_VERSION } from \"../client-info\";\nimport type { EnvSource } from \"./schema\";\n\n/** Next's `phase` for `next build` (next/constants PHASE_PRODUCTION_BUILD). */\nconst PRODUCTION_BUILD_PHASE = \"phase-production-build\";\nconst DEFAULT_API_URL = \"https://apibase.ecomweb.app/api/v1\";\nconst DEFAULT_TIMEOUT_MS = 2000;\n// Set once a build has checked, so Next's build workers (which load the\n// config again and inherit the env) stay quiet.\nconst CHECKED_FLAG = \"__ECOMWEB_VERSION_CHECKED\";\n\nconst KIT_PACKAGE = \"@ecomweb/storefront-kit\";\nconst SDK_PACKAGE = \"@ecomweb/sdk\";\n\ninterface PackagePolicy {\n latest?: string;\n minimum_supported?: string;\n security_minimum?: string;\n}\n\ninterface Advisory {\n id?: string;\n package?: string;\n fixed_in?: string;\n severity?: string;\n summary?: string;\n url?: string;\n}\n\ninterface VersionsResponse {\n packages?: Record<string, PackagePolicy | undefined>;\n advisories?: Advisory[];\n upgrade_guide_url?: string;\n}\n\nexport type ClientVersionStatus =\n | \"up_to_date\"\n | \"update_available\"\n | \"unsupported\"\n | \"security_update\";\n\nexport interface ClientVersionReport {\n status: ClientVersionStatus;\n /** The package judged: the kit, or the SDK when the kit is current. */\n package: string;\n installed: string;\n latest?: string;\n advisories: Advisory[];\n upgradeGuideUrl?: string;\n}\n\nexport interface CheckClientVersionsOptions {\n /** Next's config `phase`; the check runs only for `next build`. */\n phase?: string;\n /** The API base, `/api/v1` included. Defaults to production. */\n apiUrl?: string;\n env?: EnvSource;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Where the warning goes; `console.warn` by default. */\n warn?: (message: string) => void;\n /** Overrides the baked-in versions (tests). */\n installed?: { kit?: string; sdk?: string };\n}\n\ntype Semver = [number, number, number];\n\nfunction parseSemver(v: string | undefined): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(v?.trim() ?? \"\");\n return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\n/** True when `a` is a lower version than `b`; false if either isn't semver. */\nfunction isBelow(a: string, b: string | undefined): boolean {\n const x = parseSemver(a);\n const y = parseSemver(b);\n if (!x || !y) return false;\n for (let i = 0; i < 3; i++) {\n if (x[i] !== y[i]) return x[i] < y[i];\n }\n return false;\n}\n\nfunction judge(\n pkg: string,\n installed: string,\n body: VersionsResponse\n): ClientVersionReport | null {\n if (!parseSemver(installed)) return null;\n const policy = body.packages?.[pkg];\n if (!policy) return null;\n const advisories = (body.advisories ?? []).filter(\n a => a.package === pkg && isBelow(installed, a.fixed_in)\n );\n const status: ClientVersionStatus = isBelow(installed, policy.security_minimum)\n ? \"security_update\"\n : isBelow(installed, policy.minimum_supported)\n ? \"unsupported\"\n : isBelow(installed, policy.latest)\n ? \"update_available\"\n : \"up_to_date\";\n return {\n status,\n package: pkg,\n installed,\n latest: policy.latest,\n advisories,\n upgradeGuideUrl: body.upgrade_guide_url,\n };\n}\n\nconst SEVERITY: Record<ClientVersionStatus, number> = {\n up_to_date: 0,\n update_available: 1,\n unsupported: 2,\n security_update: 3,\n};\n\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,S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 
16
- export { EnvSource, PublicConfig, parsePublicConfig, publicConfig, resetPublicConfigForTests };
16
+ /**
17
+ * This package's version, baked in at build time. `dev` when the source runs
18
+ * without the define (the API ignores a version that isn't semver).
19
+ */
20
+ declare const KIT_VERSION: string;
21
+ /** The kit's token in `X-Ecomweb-Client`, put before the SDK's own. */
22
+ declare const KIT_CLIENT_TOKEN: string;
23
+
24
+ interface Advisory {
25
+ id?: string;
26
+ package?: string;
27
+ fixed_in?: string;
28
+ severity?: string;
29
+ summary?: string;
30
+ url?: string;
31
+ }
32
+ type ClientVersionStatus = "up_to_date" | "update_available" | "unsupported" | "security_update";
33
+ interface ClientVersionReport {
34
+ status: ClientVersionStatus;
35
+ /** The package judged: the kit, or the SDK when the kit is current. */
36
+ package: string;
37
+ installed: string;
38
+ latest?: string;
39
+ advisories: Advisory[];
40
+ upgradeGuideUrl?: string;
41
+ }
42
+ interface CheckClientVersionsOptions {
43
+ /** Next's config `phase`; the check runs only for `next build`. */
44
+ phase?: string;
45
+ /** The API base, `/api/v1` included. Defaults to production. */
46
+ apiUrl?: string;
47
+ env?: EnvSource;
48
+ timeoutMs?: number;
49
+ fetch?: typeof fetch;
50
+ /** Where the warning goes; `console.warn` by default. */
51
+ warn?: (message: string) => void;
52
+ /** Overrides the baked-in versions (tests). */
53
+ installed?: {
54
+ kit?: string;
55
+ sdk?: string;
56
+ };
57
+ }
58
+ declare function formatClientVersionWarning(report: ClientVersionReport): string;
59
+ /**
60
+ * Checks the installed kit and SDK against the platform's supported versions
61
+ * and prints a warning when they are behind. For `next.config.mjs`:
62
+ *
63
+ * ```js
64
+ * export default async function config(phase) {
65
+ * await checkClientVersions({ phase, apiUrl: API_URL });
66
+ * return nextConfig;
67
+ * }
68
+ * ```
69
+ *
70
+ * Runs during `next build` only, once per build, and never fails or slows it
71
+ * beyond the timeout (2 s): any error is ignored. Off with
72
+ * `ECOMWEB_SKIP_VERSION_CHECK=1`. Returns the report, or null when it did not
73
+ * check.
74
+ */
75
+ declare function checkClientVersions(options?: CheckClientVersionsOptions): Promise<ClientVersionReport | null>;
76
+
77
+ export { type CheckClientVersionsOptions, type ClientVersionReport, type ClientVersionStatus, EnvSource, KIT_CLIENT_TOKEN, KIT_VERSION, PublicConfig, checkClientVersions, formatClientVersionWarning, parsePublicConfig, publicConfig, resetPublicConfigForTests };
package/dist/config.js CHANGED
@@ -5,8 +5,17 @@ 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 { KIT_CLIENT_TOKEN, KIT_VERSION } from "./client-info.js";
9
+ import {
10
+ checkClientVersions,
11
+ formatClientVersionWarning
12
+ } from "./config/version-check.js";
8
13
  export {
9
14
  ConfigError,
15
+ KIT_CLIENT_TOKEN,
16
+ KIT_VERSION,
17
+ checkClientVersions,
18
+ formatClientVersionWarning,
10
19
  parsePublicConfig,
11
20
  publicConfig,
12
21
  resetPublicConfigForTests,
@@ -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\";\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;","names":[]}
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":[]}
package/dist/sdk.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createEcomwebSdk } from "@ecomweb/sdk";
2
2
  import { createStoreApiClient, publicApiClient } from "./api/client.js";
3
+ import { KIT_CLIENT_TOKEN } from "./client-info.js";
3
4
  function requireStoreScopedSdk() {
4
5
  const fail = async () => ({
5
6
  success: false,
@@ -13,7 +14,8 @@ function requireStoreScopedSdk() {
13
14
  }
14
15
  const sdk = createEcomwebSdk({
15
16
  publicHttp: publicApiClient,
16
- authHttp: requireStoreScopedSdk()
17
+ authHttp: requireStoreScopedSdk(),
18
+ clientInfo: KIT_CLIENT_TOKEN
17
19
  });
18
20
  const storeSdks = /* @__PURE__ */ new Map();
19
21
  function createStoreSdk(storeRef) {
@@ -21,7 +23,8 @@ function createStoreSdk(storeRef) {
21
23
  if (cached) return cached;
22
24
  const created = createEcomwebSdk({
23
25
  publicHttp: publicApiClient,
24
- authHttp: createStoreApiClient(storeRef)
26
+ authHttp: createStoreApiClient(storeRef),
27
+ clientInfo: KIT_CLIENT_TOKEN
25
28
  });
26
29
  storeSdks.set(storeRef, created);
27
30
  return created;
package/dist/sdk.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AAQtD,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAClC,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,EACzC,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/sdk.ts"],"sourcesContent":["import { createEcomwebSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient } from \"@ecomweb/sdk\";\nimport { createStoreApiClient, publicApiClient } from \"./api/client\";\nimport { KIT_CLIENT_TOKEN } from \"./client-info\";\n\n/**\n * The module-level `sdk` below has no store in scope, so it cannot build the\n * store-scoped proxy URL an authenticated call needs. Rather than let such a\n * call go out silently unauthenticated and 401 at the backend, its `authHttp`\n * fails here with an actionable message.\n */\nfunction requireStoreScopedSdk(): IHttpClient {\n const fail = async (): Promise<ApiResponse<never>> => ({\n success: false,\n error: {\n message:\n \"This endpoint requires a signed-in shopper. Use createStoreSdk(storeRef) instead of the module-level sdk.\",\n statusCode: 401,\n error: \"SDK_STORE_SCOPE_REQUIRED\",\n },\n });\n\n return { get: fail, post: fail, put: fail, patch: fail, delete: fail };\n}\n\n// ApiClient satisfies IHttpClient structurally at runtime; cast resolves the\n// AxiosRequestConfig vs RequestOptions type mismatch.\nexport const sdk = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: requireStoreScopedSdk(),\n clientInfo: KIT_CLIENT_TOKEN,\n});\n\nconst storeSdks = new Map<string, ReturnType<typeof createEcomwebSdk>>();\n\n/**\n * SDK bound to one store, whose authenticated modules (cart, orders, blog\n * comments, customers, addresses) go through the same-origin proxy route so the\n * httpOnly session cookie can be turned into a bearer token server-side.\n *\n * Memoised per store so the returned object is referentially stable and safe to\n * use in a React dependency array.\n */\nexport function createStoreSdk(storeRef: string) {\n const cached = storeSdks.get(storeRef);\n if (cached) return cached;\n\n const created = createEcomwebSdk({\n publicHttp: publicApiClient as any,\n authHttp: createStoreApiClient(storeRef) as any,\n clientInfo: KIT_CLIENT_TOKEN,\n });\n\n storeSdks.set(storeRef, created);\n return created;\n}\n"],"mappings":"AAAA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB,uBAAuB;AACtD,SAAS,wBAAwB;AAQjC,SAAS,wBAAqC;AAC5C,QAAM,OAAO,aAA0C;AAAA,IACrD,SAAS;AAAA,IACT,OAAO;AAAA,MACL,SACE;AAAA,MACF,YAAY;AAAA,MACZ,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,EAAE,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,OAAO,MAAM,QAAQ,KAAK;AACvE;AAIO,MAAM,MAAM,iBAAiB;AAAA,EAClC,YAAY;AAAA,EACZ,UAAU,sBAAsB;AAAA,EAChC,YAAY;AACd,CAAC;AAED,MAAM,YAAY,oBAAI,IAAiD;AAUhE,SAAS,eAAe,UAAkB;AAC/C,QAAM,SAAS,UAAU,IAAI,QAAQ;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,UAAU,iBAAiB;AAAA,IAC/B,YAAY;AAAA,IACZ,UAAU,qBAAqB,QAAQ;AAAA,IACvC,YAAY;AAAA,EACd,CAAC;AAED,YAAU,IAAI,UAAU,OAAO;AAC/B,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,15 +1,17 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.13.1",
3
+ "version": "0.14.0",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/ecomwebai/ecomweb-storefront.git",
10
+ "url": "https://github.com/ecomwebai/ecomweb-storefront-sdk.git",
11
11
  "directory": "packages/storefront-kit"
12
12
  },
13
+ "homepage": "https://github.com/ecomwebai/ecomweb-storefront-sdk/tree/main/packages/storefront-kit#readme",
14
+ "bugs": "https://github.com/ecomwebai/ecomweb-storefront-sdk/issues",
13
15
  "main": "./dist/index.js",
14
16
  "types": "./dist/index.d.ts",
15
17
  "exports": {
@@ -47,7 +49,7 @@
47
49
  "currency.js": "^2.0.4",
48
50
  "server-only": "^0.0.1",
49
51
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.13.1"
52
+ "@ecomweb/sdk": "^0.14.0"
51
53
  },
52
54
  "peerDependencies": {
53
55
  "next": ">=16",