@shop-on/customer-runtime 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,12 @@
1
- //#region src/handoff-state.d.ts
2
1
  /**
3
- * Shared rules for the states that bind a handoff to the browser that started
4
- * it, used by their minters and their checkers. The formats are a shape check
5
- * only: each consumer verifies the value against its own cookie.
2
+ * Shared rules for the state that binds a handoff to the browser that started
3
+ * it, used by its minter and its checkers. The format is a shape check only:
4
+ * each consumer verifies the value against its own cookie.
6
5
  *
7
- * - `checkout_state`: `ts "." base64url(HMAC-SHA256)`, minted by checkout's
8
- * `/begin`, carried by the theme onto the cart handoff URL.
9
6
  * - `state` (theme): 32 random bytes base64url, minted by theme-server's
10
7
  * `account_state` cookie; the account `return_to` sanitizer passes it
11
8
  * through on storefront hosts.
12
9
  */
13
- export declare const CHECKOUT_STATE_FORMAT: RegExp;
14
10
  export declare const ACCOUNT_STATE_FORMAT: RegExp;
15
11
  /** Loopback: the one place a state may travel over http (local theme dev).
16
12
  * Takes `URL#hostname`, which keeps the IPv6 brackets (`[::1]`). */
@@ -21,5 +17,4 @@ export declare function isLoopback(hostname: string): boolean;
21
17
  * carry it to whatever the next page loads. Server-only; the server module is
22
18
  * imported here so a client-reachable importer of the formats stays clean.
23
19
  */
24
- export declare function markResponsePrivate(): Promise<void>;
25
- //#endregion
20
+ export declare function markResponsePrivate(): Promise<void>;
@@ -1,16 +1,13 @@
1
- //#region src/handoff-state.ts
1
+ // src/handoff-state.ts
2
2
  /**
3
- * Shared rules for the states that bind a handoff to the browser that started
4
- * it, used by their minters and their checkers. The formats are a shape check
5
- * only: each consumer verifies the value against its own cookie.
3
+ * Shared rules for the state that binds a handoff to the browser that started
4
+ * it, used by its minter and its checkers. The format is a shape check only:
5
+ * each consumer verifies the value against its own cookie.
6
6
  *
7
- * - `checkout_state`: `ts "." base64url(HMAC-SHA256)`, minted by checkout's
8
- * `/begin`, carried by the theme onto the cart handoff URL.
9
7
  * - `state` (theme): 32 random bytes base64url, minted by theme-server's
10
8
  * `account_state` cookie; the account `return_to` sanitizer passes it
11
9
  * through on storefront hosts.
12
10
  */
13
- const CHECKOUT_STATE_FORMAT = /^\d{10}\.[A-Za-z0-9_-]{43}$/;
14
11
  const ACCOUNT_STATE_FORMAT = /^[A-Za-z0-9_-]{43}$/;
15
12
  /** Loopback: the one place a state may travel over http (local theme dev).
16
13
  * Takes `URL#hostname`, which keeps the IPv6 brackets (`[::1]`). */
@@ -28,5 +25,4 @@ async function markResponsePrivate() {
28
25
  setResponseHeader("Referrer-Policy", "no-referrer");
29
26
  setResponseHeader("Cache-Control", "no-store");
30
27
  }
31
- //#endregion
32
- export { ACCOUNT_STATE_FORMAT, CHECKOUT_STATE_FORMAT, isLoopback, markResponsePrivate };
28
+ export { ACCOUNT_STATE_FORMAT, isLoopback, markResponsePrivate };
package/dist/lease.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/lease.d.ts
2
1
  export interface Lease<T> {
3
2
  run(key: string, work: () => Promise<T>): Promise<T>;
4
3
  /** A live lease exists and this request isn't the one running it. */
@@ -23,5 +22,4 @@ export interface Lease<T> {
23
22
  export declare function createLease<T>({ leaseMs, pollMs }?: {
24
23
  leaseMs?: number;
25
24
  pollMs?: number;
26
- }): Lease<T>;
27
- //#endregion
25
+ }): Lease<T>;
package/dist/lease.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { requestSlot } from "./request-scope.js";
2
- //#region src/lease.ts
3
- const isThrottled = (error) => error instanceof Error && error.response?.status === 429;
2
+ // src/lease.ts
3
+ const isThrottled = (error) => error instanceof Error && error.status === 429;
4
4
  const isLive = (lease) => lease !== void 0 && lease.until > Date.now();
5
5
  /**
6
6
  * One `work` per key across concurrent requests. The first caller takes the
@@ -84,5 +84,4 @@ function createLease({ leaseMs = 3e3, pollMs = 10 } = {}) {
84
84
  leaseCount: () => leases.size
85
85
  };
86
86
  }
87
- //#endregion
88
87
  export { createLease };
package/dist/relay.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/relay.d.ts
2
1
  /**
3
2
  * `X-Buyer-IP` from Cloudflare's `CF-Connecting-IP` on the request this call
4
3
  * runs under, plus `X-Relay-Auth` when SPN_RELAY_SECRET is set. Empty outside
@@ -17,5 +16,4 @@ export declare const SHARD_BUYER_TOKEN_HEADER = "x-shard-buyer";
17
16
  * under. Empty outside a request or when the router minted none (no
18
17
  * `CLIENT_IP_SOURCE`, no secret, or not behind a shard at all).
19
18
  */
20
- export declare function shardBuyerHeaders(): Record<string, string>;
21
- //#endregion
19
+ export declare function shardBuyerHeaders(): Record<string, string>;
package/dist/relay.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { currentRequest } from "./request-scope.js";
2
- //#region src/relay.ts
2
+ // src/relay.ts
3
3
  const IPV4_OCTET = "(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
4
4
  const IPV4 = new RegExp(`^${IPV4_OCTET}(\\.${IPV4_OCTET}){3}$`);
5
5
  function isIP(value) {
@@ -44,5 +44,4 @@ function shardBuyerHeaders() {
44
44
  const token = currentRequest()?.headers.get(SHARD_BUYER_TOKEN_HEADER);
45
45
  return token ? { "X-Shard-Buyer": token } : {};
46
46
  }
47
- //#endregion
48
47
  export { SHARD_BUYER_TOKEN_HEADER, relayHeaders, shardBuyerHeaders, staffRelayHeaders };
@@ -1,9 +1,7 @@
1
- //#region src/request-scope.d.ts
2
1
  /** The request this call runs under; undefined outside one (browser, tests, pre-handler). */
3
2
  export declare function currentRequest(): Request | undefined;
4
3
  /**
5
4
  * Per-request state under `key`, created by `init` on first use. Undefined
6
5
  * outside a request — callers fall back to not sharing at all.
7
6
  */
8
- export declare function requestSlot<T>(key: symbol, init: () => T): T | undefined;
9
- //#endregion
7
+ export declare function requestSlot<T>(key: symbol, init: () => T): T | undefined;
@@ -1,4 +1,4 @@
1
- //#region src/request-scope.ts
1
+ // src/request-scope.ts
2
2
  const EVENT_STORAGE_KEY = Symbol.for("tanstack-start:event-storage");
3
3
  /** The request this call runs under; undefined outside one (browser, tests, pre-handler). */
4
4
  function currentRequest() {
@@ -20,5 +20,4 @@ function requestSlot(key, init) {
20
20
  if (!bag.has(key)) bag.set(key, init());
21
21
  return bag.get(key);
22
22
  }
23
- //#endregion
24
23
  export { currentRequest, requestSlot };
@@ -1,4 +1,3 @@
1
- //#region src/sealed-session.d.ts
2
1
  export interface SealedSessionConfig {
3
2
  name: string;
4
3
  /** At least 32 chars. */
@@ -23,5 +22,4 @@ export interface SealedSession<T> {
23
22
  export declare class SessionTooLargeError extends Error {
24
23
  constructor(name: string, length: number);
25
24
  }
26
- export declare function openSession<T>(config: SealedSessionConfig): Promise<SealedSession<T>>;
27
- //#endregion
25
+ export declare function openSession<T>(config: SealedSessionConfig): Promise<SealedSession<T>>;
@@ -1,7 +1,7 @@
1
1
  import { requestSlot } from "./request-scope.js";
2
2
  import { deleteCookie, getCookie, setCookie } from "@tanstack/react-start/server";
3
3
  import { defaults, seal, unseal } from "iron-webcrypto";
4
- //#region src/sealed-session.ts
4
+ // src/sealed-session.ts
5
5
  /**
6
6
  * Encrypted cookie sessions, wire-compatible with the `useSession` TanStack
7
7
  * Start 1.168 shipped (h3 2.0.1-rc.20) and 1.169 removed. Both seal
@@ -150,5 +150,4 @@ async function write(config, slot, patch) {
150
150
  });
151
151
  deleteChunks(config);
152
152
  }
153
- //#endregion
154
153
  export { SessionTooLargeError, openSession };
@@ -1,4 +1,3 @@
1
- //#region src/session-cookie.d.ts
2
1
  /**
3
2
  * Host-only encrypted session cookies for the central account and checkout
4
3
  * apps. Both apps serve every shop from a single process, so we use one
@@ -52,5 +51,4 @@ export declare function createShopBoundCookieConfig(opts: {
52
51
  * `undefined`, which callers should treat as "no valid session for this
53
52
  * shop in this request" — i.e. equivalent to logged-out.
54
53
  */
55
- export declare function validateShopBinding<TData extends ShopBoundSession>(payload: Partial<TData> | undefined, expectedShopHandle: string): TData | undefined;
56
- //#endregion
54
+ export declare function validateShopBinding<TData extends ShopBoundSession>(payload: Partial<TData> | undefined, expectedShopHandle: string): TData | undefined;
@@ -1,4 +1,4 @@
1
- //#region src/session-cookie.ts
1
+ // src/session-cookie.ts
2
2
  /**
3
3
  * Storefronts on `<handle>.adorly.mn` run merchant script, and `adorly.mn` is
4
4
  * not a public suffix, so any storefront can set a same-named cookie for the
@@ -35,5 +35,4 @@ function validateShopBinding(payload, expectedShopHandle) {
35
35
  if (payload.shopHandle !== expectedShopHandle) return void 0;
36
36
  return payload;
37
37
  }
38
- //#endregion
39
38
  export { createShopBoundCookieConfig, hostOnlyCookieName, validateShopBinding };
package/dist/trace.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/trace.d.ts
2
1
  export interface TraceOptions {
3
2
  /** Continue a valid incoming `traceparent`. Only behind a proxy that started the trace (Traefik). */
4
3
  continueIncoming?: boolean;
@@ -9,5 +8,4 @@ export interface TraceOptions {
9
8
  * sampled. Empty outside a request. Send it to our own api only, never to a
10
9
  * third party.
11
10
  */
12
- export declare function traceHeaders({ continueIncoming }?: TraceOptions): Record<string, string>;
13
- //#endregion
11
+ export declare function traceHeaders({ continueIncoming }?: TraceOptions): Record<string, string>;
package/dist/trace.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { currentRequest, requestSlot } from "./request-scope.js";
2
- //#region src/trace.ts
2
+ // src/trace.ts
3
3
  const TRACEPARENT = /^00-((?!0{32})[\da-f]{32})-((?!0{16})[\da-f]{16})-[\da-f]{2}$/;
4
4
  const MINTED = Symbol("minted traceparent");
5
5
  function randomHex(bytes) {
@@ -21,5 +21,4 @@ function traceHeaders({ continueIncoming = false } = {}) {
21
21
  const traceparent = requestSlot(MINTED, () => `00-${randomHex(16)}-${randomHex(8)}-01`);
22
22
  return traceparent ? { traceparent } : {};
23
23
  }
24
- //#endregion
25
24
  export { traceHeaders };
package/package.json CHANGED
@@ -1,13 +1,12 @@
1
1
  {
2
2
  "name": "@shop-on/customer-runtime",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "license": "SEE LICENSE IN dist/LICENSE.md",
5
5
  "files": [
6
6
  "dist"
7
7
  ],
8
8
  "type": "module",
9
9
  "exports": {
10
- "./customer-session-handoff": "./dist/customer-session-handoff.js",
11
10
  "./handoff-state": "./dist/handoff-state.js",
12
11
  "./lease": "./dist/lease.js",
13
12
  "./relay": "./dist/relay.js",
@@ -18,18 +17,17 @@
18
17
  "./package.json": "./package.json"
19
18
  },
20
19
  "dependencies": {
21
- "gql.tada": "1.11.4",
22
- "graphql-request": "7.4.0",
23
20
  "iron-webcrypto": "2.0.0"
24
21
  },
25
22
  "devDependencies": {
26
- "@tanstack/react-start": "1.169.3",
27
- "@types/node": "26.6.5",
23
+ "@shop-on/api-contract": "0.0.0",
24
+ "@tanstack/react-start": "1.169.5",
25
+ "@types/node": "26.6.6",
28
26
  "typescript": "7.0.2",
29
- "vitest": "5.0.5"
27
+ "vitest": "5.1.0"
30
28
  },
31
29
  "peerDependencies": {
32
- "@tanstack/react-start": "~1.169.3"
30
+ "@tanstack/react-start": "~1.169.5"
33
31
  },
34
32
  "scripts": {
35
33
  "check-types": "tsc --noEmit",
@@ -1,15 +0,0 @@
1
- import { ConsumeResult } from "./handoff.js";
2
- //#region src/customer-session-handoff.d.ts
3
- export interface CustomerSessionHandoffPayload {
4
- shopHandle: string;
5
- customerSessionToken: string;
6
- customerSessionExpiresAt: string;
7
- /** Customer's email if Rails has one. Some accounts auth by phone, so
8
- * this can be absent; consumers fall back to the form input. */
9
- customerEmail?: string;
10
- createdAt: number;
11
- }
12
- export declare function createCustomerSessionHandoff(payload: CustomerSessionHandoffPayload): Promise<string>;
13
- export declare function consumeCustomerSessionHandoff(nonce: string): Promise<ConsumeResult<CustomerSessionHandoffPayload>>;
14
- //#endregion
15
- export type { ConsumeResult };
@@ -1,12 +0,0 @@
1
- import { internalDelete, internalPost } from "./internal-api.js";
2
- //#region src/customer-session-handoff.ts
3
- const KIND = "customer_session_handoff";
4
- async function createCustomerSessionHandoff(payload) {
5
- const { nonce } = await internalPost(`handoff/${KIND}`, { payload });
6
- return nonce;
7
- }
8
- async function consumeCustomerSessionHandoff(nonce) {
9
- return internalDelete(`handoff/${KIND}/${encodeURIComponent(nonce)}`);
10
- }
11
- //#endregion
12
- export { consumeCustomerSessionHandoff, createCustomerSessionHandoff };
package/dist/handoff.d.ts DELETED
@@ -1,9 +0,0 @@
1
- //#region src/handoff.d.ts
2
- export type ConsumeResult<P> = {
3
- ok: true;
4
- payload: P;
5
- } | {
6
- ok: false;
7
- reason: "missing_or_consumed" | "malformed";
8
- };
9
- //#endregion
@@ -1,74 +0,0 @@
1
- import { relayHeaders, shardBuyerHeaders } from "./relay.js";
2
- import { traceHeaders } from "./trace.js";
3
- //#region src/internal-api.ts
4
- function apiUrl() {
5
- return process.env.SPN_CUSTOMER_API_URL ?? "http://localhost:3003";
6
- }
7
- function internalSecret() {
8
- return process.env.SPN_INTERNAL_API_SECRET ?? "";
9
- }
10
- var InternalApiError = class extends Error {
11
- status;
12
- bodySnippet;
13
- constructor(path, status, bodySnippet) {
14
- super(`[customer-runtime/internal-api] ${path} returned ${status}: ${bodySnippet}`);
15
- this.name = "InternalApiError";
16
- this.status = status;
17
- this.bodySnippet = bodySnippet;
18
- }
19
- };
20
- function requireSecret(path) {
21
- const secret = internalSecret();
22
- if (!secret) throw new Error(`[customer-runtime/internal-api] SPN_INTERNAL_API_SECRET is unset; refusing to call ${path} without auth`);
23
- return secret;
24
- }
25
- async function readBodySnippet(res) {
26
- try {
27
- return (await res.text()).slice(0, 200);
28
- } catch {
29
- return "";
30
- }
31
- }
32
- /**
33
- * POST a JSON body to `/api/internal/customer/<path>`. Throws
34
- * `InternalApiError` on non-2xx so callers can decide how to map status →
35
- * domain outcome (e.g. token mint maps 404 → CredentialsUnavailableError).
36
- */
37
- async function internalPost(path, body, { signal } = {}) {
38
- const secret = requireSecret(path);
39
- const res = await fetch(`${apiUrl()}/api/internal/customer/${path}`, {
40
- method: "POST",
41
- headers: {
42
- "Content-Type": "application/json",
43
- "X-Internal-Auth": secret,
44
- ...traceHeaders(),
45
- ...shardBuyerHeaders(),
46
- ...relayHeaders()
47
- },
48
- body: JSON.stringify(body),
49
- signal
50
- });
51
- if (!res.ok) throw new InternalApiError(path, res.status, await readBodySnippet(res));
52
- return await res.json();
53
- }
54
- /**
55
- * DELETE `/api/internal/customer/<path>`. Used by the handoff consume path —
56
- * the endpoint always returns 200 (with `{ ok: false, reason }` on miss), so
57
- * a non-2xx here is a real error, not a domain miss.
58
- */
59
- async function internalDelete(path) {
60
- const secret = requireSecret(path);
61
- const res = await fetch(`${apiUrl()}/api/internal/customer/${path}`, {
62
- method: "DELETE",
63
- headers: {
64
- "X-Internal-Auth": secret,
65
- ...traceHeaders(),
66
- ...shardBuyerHeaders(),
67
- ...relayHeaders()
68
- }
69
- });
70
- if (!res.ok) throw new InternalApiError(path, res.status, await readBodySnippet(res));
71
- return await res.json();
72
- }
73
- //#endregion
74
- export { InternalApiError, internalDelete, internalPost };