@c1m-public/channel-client 0.19.0 → 0.20.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
@@ -14,6 +14,11 @@ transport core.
14
14
  signature verification.
15
15
  - `@c1m-public/channel-client/renderer` — framework-neutral canonical document
16
16
  traversal, responsive CSS safety, and injected block registries.
17
+ - `@c1m-public/channel-client/dash` and `/dash/next` — the dash-scoped surface
18
+ (profile, directory, plans, leads, lead portal) with the same neutral/Next
19
+ split; see [The `/next` kits](#the-next-kits).
20
+ - `@c1m-public/channel-client/moving-lead-model` — the moving-quote domain
21
+ model shared by dash sites and SaaSDash; no transport, optional `zod` peer.
17
22
 
18
23
  Channel credentials resolve the tenant and scope at the API door (plus the
19
24
  workspace for workspace-scoped channels), so site URLs never carry those
@@ -145,14 +150,20 @@ other runtimes must enforce their own server-module boundary.
145
150
 
146
151
  ## Behavior
147
152
 
148
- - The core retries transient reads once and leaves anonymous-read caching to the
149
- runtime adapter.
153
+ - The core retries transient reads once (`retry.attempts`, default 1) on
154
+ network failure and on 429/502/503/504, with jittered exponential backoff
155
+ from 250 ms capped by `retry.maxDelayMs` (default 2000); a server's
156
+ `Retry-After` wins over the backoff but never exceeds the cap. Anonymous-read
157
+ caching is left to the runtime adapter.
150
158
  - The Next adapter supports explicit revalidation and tags.
151
- - Writes are always `no-store`, are never automatically retried, and accept an
152
- explicit idempotency key.
159
+ - Writes are always `no-store` and accept an explicit idempotency key. A write
160
+ that carries one is retried on the same terms as a read — the key makes the
161
+ replay safe by definition (`retry.idempotentWrites`, default on). A write
162
+ without a key is never retried.
163
+ - `timeoutMs` (default 10000) bounds each attempt, not the whole request; a
164
+ retried request can take up to `attempts + 1` timeouts plus the waits.
153
165
  - Cart and checkout operations use an opaque `cart_token`; the channel token
154
166
  continues to resolve tenant and workspace identity at the API door.
155
- - Requests time out after 10 seconds by default.
156
167
  - API failures throw `ChannelAPIError` with safe status, code, and request ID.
157
168
  - Use `isChannelAPIError(error)` instead of `instanceof`; it remains correct
158
169
  when a server bundle contains more than one package instance.
@@ -0,0 +1,334 @@
1
+ import { isChannelAPIError, createChannelClient } from './chunk-AX6L2XH3.js';
2
+ import { parseChannelWebhookEvent, isChannelWebhookVerificationError, isChannelWebhookEventType, ChannelConfigurationError } from './chunk-RJQ4YEZV.js';
3
+ import 'server-only';
4
+
5
+ var MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
6
+ var REFRESH_SKEW_MS = 6e4;
7
+ var sessionCookie = {
8
+ name: "__Host-c1m_session",
9
+ // The optional argument remains source-compatible with 0.14 callers. A
10
+ // __Host- cookie is Secure in every environment, including local HTTPS.
11
+ attributes(_isProduction) {
12
+ return {
13
+ // Never readable from JavaScript: an XSS bug must not become a stolen session.
14
+ httpOnly: true,
15
+ secure: true,
16
+ // Lax, not Strict: the session must survive a customer arriving from an
17
+ // emailed link. Not None — that would ship the cookie cross-site.
18
+ sameSite: "lax",
19
+ path: "/",
20
+ maxAge: MAX_AGE_SECONDS
21
+ };
22
+ },
23
+ serialize(tokens) {
24
+ return JSON.stringify(tokens);
25
+ },
26
+ /**
27
+ * A cookie is attacker-controlled input: truncated, stale-shaped, or
28
+ * hand-written. Anything unreadable is "not signed in", never a crash.
29
+ */
30
+ parse(raw) {
31
+ if (!raw) return null;
32
+ try {
33
+ const parsed = JSON.parse(raw);
34
+ if (!parsed || typeof parsed !== "object") return null;
35
+ const { accessToken, refreshToken, expiresAt } = parsed;
36
+ if (typeof accessToken !== "string" || !accessToken) return null;
37
+ if (typeof refreshToken !== "string" || !refreshToken) return null;
38
+ if (typeof expiresAt !== "string" || !expiresAt) return null;
39
+ return { accessToken, refreshToken, expiresAt };
40
+ } catch {
41
+ return null;
42
+ }
43
+ },
44
+ needsRefresh(tokens, now = Date.now()) {
45
+ const expiresAt = Date.parse(tokens.expiresAt);
46
+ if (Number.isNaN(expiresAt)) return true;
47
+ return expiresAt - now <= REFRESH_SKEW_MS;
48
+ }
49
+ };
50
+ var CONTESTED = "refresh_contested";
51
+ function normalizeCustomer(customer) {
52
+ return {
53
+ id: customer.id,
54
+ email: customer.email,
55
+ name: customer.name?.trim() || customer.email
56
+ };
57
+ }
58
+ function toTokens(session) {
59
+ return {
60
+ accessToken: session.access_token,
61
+ refreshToken: session.refresh_token,
62
+ expiresAt: session.expires_at
63
+ };
64
+ }
65
+ function createCustomerSession(options) {
66
+ const resolve = typeof options.client === "function" ? options.client : () => options.client;
67
+ return {
68
+ cookie: sessionCookie,
69
+ async requestCode(email) {
70
+ try {
71
+ await resolve().auth.sendCode(email);
72
+ return { state: "sent" };
73
+ } catch {
74
+ return { state: "failed" };
75
+ }
76
+ },
77
+ async signIn(email, code) {
78
+ try {
79
+ const session = await resolve().auth.verifyCode({ email, code });
80
+ const tokens = toTokens(session);
81
+ return {
82
+ state: "signed-in",
83
+ customer: normalizeCustomer(session.end_user),
84
+ tokens,
85
+ cookie: {
86
+ name: sessionCookie.name,
87
+ value: sessionCookie.serialize(tokens),
88
+ attributes: sessionCookie.attributes()
89
+ }
90
+ };
91
+ } catch (error) {
92
+ if (isChannelAPIError(error) && error.code === "invalid_code") {
93
+ return { state: "invalid-code" };
94
+ }
95
+ return { state: "failed" };
96
+ }
97
+ },
98
+ /**
99
+ * Decide what this request should do to the session cookie. Designed to be
100
+ * the whole body of proxy.ts.
101
+ */
102
+ async refresh(raw) {
103
+ const session = sessionCookie.parse(raw);
104
+ if (!session) return { action: "keep" };
105
+ if (!sessionCookie.needsRefresh(session)) return { action: "keep" };
106
+ try {
107
+ const rotated = await resolve().auth.refresh(session.refreshToken);
108
+ return {
109
+ action: "write",
110
+ value: sessionCookie.serialize(toTokens(rotated)),
111
+ attributes: sessionCookie.attributes()
112
+ };
113
+ } catch (error) {
114
+ if (isChannelAPIError(error)) {
115
+ if (error.code === CONTESTED) return { action: "keep" };
116
+ if (error.status === 401) return { action: "clear" };
117
+ }
118
+ return { action: "keep" };
119
+ }
120
+ },
121
+ /** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
122
+ async getCustomer(raw) {
123
+ const session = sessionCookie.parse(raw);
124
+ if (!session) return null;
125
+ try {
126
+ const { end_user } = await resolve().withCustomer(session.accessToken).me();
127
+ return normalizeCustomer(end_user);
128
+ } catch {
129
+ return null;
130
+ }
131
+ },
132
+ /** Best-effort server logout; the caller clears the cookie REGARDLESS. */
133
+ async signOut(raw) {
134
+ const session = sessionCookie.parse(raw);
135
+ if (!session) return;
136
+ try {
137
+ await resolve().withCustomer(session.accessToken).logout();
138
+ } catch {
139
+ }
140
+ }
141
+ };
142
+ }
143
+ var CHANNEL_SITE_CACHE_TAG = "channel:site";
144
+ var CHANNEL_CATALOG_CACHE_TAG = "channel:catalog";
145
+ function safePublishedPath(path) {
146
+ const normalized = path.trim();
147
+ if (!normalized.startsWith("/") || normalized.startsWith("//") || normalized.length > 1024) {
148
+ return void 0;
149
+ }
150
+ return normalized;
151
+ }
152
+ function errorMessage(error) {
153
+ return error instanceof Error ? error.message : String(error);
154
+ }
155
+ function defaultBehavior(event, invalidate) {
156
+ if (event.type === "page.published") {
157
+ const path = safePublishedPath(event.data.route_pattern);
158
+ if (!path) throw new Error("page.published contains an invalid route_pattern");
159
+ invalidate.revalidateTag(CHANNEL_SITE_CACHE_TAG);
160
+ invalidate.revalidatePath(path);
161
+ return path;
162
+ }
163
+ if (event.type === "product.created" || event.type === "product.updated" || event.type === "product.deleted") {
164
+ invalidate.revalidateTag(CHANNEL_CATALOG_CACHE_TAG);
165
+ return void 0;
166
+ }
167
+ return void 0;
168
+ }
169
+ function createChannelWebhookRoute(options) {
170
+ const logger = options.logger ?? console;
171
+ const resolveSecret = typeof options.secret === "function" ? options.secret : () => options.secret;
172
+ return async (request) => {
173
+ let event;
174
+ try {
175
+ event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
176
+ } catch (error) {
177
+ if (isChannelWebhookVerificationError(error)) {
178
+ logger.warn("channel_webhook_rejected", { code: error.code });
179
+ return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
180
+ }
181
+ logger.error("channel_webhook_failed", { message: errorMessage(error) });
182
+ return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
183
+ }
184
+ try {
185
+ if (!isChannelWebhookEventType(event.type)) {
186
+ logger.info("channel_webhook_ignored", { eventId: event.id, eventType: event.type });
187
+ return new Response(null, { status: 204 });
188
+ }
189
+ const knownEvent = event;
190
+ const handler = options.onEvent?.[knownEvent.type];
191
+ let revalidatedPath;
192
+ if (handler) {
193
+ await handler(knownEvent, options.invalidate);
194
+ } else {
195
+ revalidatedPath = defaultBehavior(knownEvent, options.invalidate);
196
+ }
197
+ logger.info("channel_webhook_processed", {
198
+ eventId: event.id,
199
+ eventType: knownEvent.type,
200
+ ...revalidatedPath ? { revalidatedPath } : {}
201
+ });
202
+ return new Response(null, { status: 204 });
203
+ } catch (error) {
204
+ logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, message: errorMessage(error) });
205
+ return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
206
+ }
207
+ };
208
+ }
209
+ function inProduction() {
210
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
211
+ }
212
+ var CART_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
213
+ var cartCookie = {
214
+ name: "cart_token",
215
+ attributes(isProduction = inProduction()) {
216
+ return { httpOnly: true, secure: isProduction, sameSite: "lax", path: "/", maxAge: CART_MAX_AGE_SECONDS };
217
+ },
218
+ /**
219
+ * The client mints the token (the server accepts any sufficiently-random
220
+ * bearer key and creates the cart row on first use).
221
+ */
222
+ mint() {
223
+ return globalThis.crypto.randomUUID();
224
+ },
225
+ /** Tolerant read: an absent or garbage cookie means "no cart yet". */
226
+ parse(raw) {
227
+ const trimmed = raw?.trim() ?? "";
228
+ if (!trimmed || trimmed.length > 120) return null;
229
+ return trimmed;
230
+ }
231
+ };
232
+ function createCart(options) {
233
+ const resolve = typeof options.client === "function" ? options.client : () => options.client;
234
+ return {
235
+ cookie: cartCookie,
236
+ /** Null when the token has no cart yet — a new visitor, not an error. */
237
+ async get(cartToken) {
238
+ try {
239
+ const { order } = await resolve().cart.get(cartToken);
240
+ return order ?? null;
241
+ } catch (error) {
242
+ if (isChannelAPIError(error) && error.status === 404) return null;
243
+ throw error;
244
+ }
245
+ },
246
+ async addItem(input) {
247
+ return resolve().cart.addItem(input);
248
+ },
249
+ async updateItem(itemId, cartToken, quantity) {
250
+ return resolve().cart.updateItem(itemId, { cart_token: cartToken, quantity });
251
+ },
252
+ async removeItem(itemId, cartToken) {
253
+ return resolve().cart.removeItem(itemId, cartToken);
254
+ },
255
+ async clear(cartToken) {
256
+ return resolve().cart.clear(cartToken);
257
+ },
258
+ /**
259
+ * Call in the same Server Action that sets the session cookie: the guest's
260
+ * cart follows the customer into their account instead of evaporating at
261
+ * the sign-in door.
262
+ */
263
+ async mergeOnSignIn(guestCartToken, customerCartToken) {
264
+ return resolve().cart.merge({
265
+ source_cart_token: guestCartToken,
266
+ target_cart_token: customerCartToken
267
+ });
268
+ },
269
+ /** Checkout steps, addressed by the order the cart became. */
270
+ checkout: {
271
+ options: (orderId, cartToken) => resolve().checkout.options(orderId, cartToken),
272
+ status: (orderId, params) => resolve().checkout.status(orderId, params),
273
+ setCustomer: (orderId, input) => resolve().checkout.setCustomer(orderId, input),
274
+ setAddresses: (orderId, input) => resolve().checkout.setAddresses(orderId, input),
275
+ setFulfillment: (orderId, input) => resolve().checkout.setFulfillment(orderId, input),
276
+ /**
277
+ * Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
278
+ * channel checkout (our API's host means nothing to your shopper) and
279
+ * must be on the channel's registered site_url — the server refuses
280
+ * anything else, because an unchecked return URL is an open redirect.
281
+ */
282
+ pay: (orderId, input, attempt) => resolve().checkout.pay(orderId, input, attempt)
283
+ }
284
+ };
285
+ }
286
+
287
+ // src/next.ts
288
+ var SITE_TAG = "channel:site";
289
+ var CATALOG_TAG = "channel:catalog";
290
+ var CATALOG_PATH = /^\/api\/v1\/channel\/(products|categories|collections|brands)(\/|$|\?)/;
291
+ function defaultChannelCacheTags(pathname) {
292
+ return CATALOG_PATH.test(pathname) ? [CATALOG_TAG] : [SITE_TAG];
293
+ }
294
+ function pathnameOf(input) {
295
+ try {
296
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
297
+ return new URL(url, "http://placeholder.invalid").pathname;
298
+ } catch {
299
+ return "";
300
+ }
301
+ }
302
+ function validateCachePolicy(policy) {
303
+ if (policy === "no-store") return;
304
+ if (!Number.isFinite(policy.revalidate) || policy.revalidate < 0) {
305
+ throw new ChannelConfigurationError("cache.revalidate must be a non-negative finite number");
306
+ }
307
+ }
308
+ function createNextChannelClient(options) {
309
+ const { cache = "no-store", fetch: suppliedFetch, ...coreOptions } = options;
310
+ validateCachePolicy(cache);
311
+ const fetcher = suppliedFetch ?? globalThis.fetch;
312
+ if (!fetcher) throw new ChannelConfigurationError("fetch implementation is required");
313
+ const nextFetch = (input, init = {}) => {
314
+ const request = { ...init };
315
+ const method = (request.method ?? "GET").toUpperCase();
316
+ const customerScoped = new Headers(request.headers).has("X-End-User-Token");
317
+ if (method === "GET" && !customerScoped && cache !== "no-store") {
318
+ delete request.cache;
319
+ const classify = cache.tagsFor ?? defaultChannelCacheTags;
320
+ const tags = Array.from(/* @__PURE__ */ new Set([...cache.tags ?? [], ...classify(pathnameOf(input))]));
321
+ request.next = {
322
+ revalidate: cache.revalidate,
323
+ ...tags.length ? { tags } : {}
324
+ };
325
+ } else {
326
+ delete request.next;
327
+ request.cache = "no-store";
328
+ }
329
+ return fetcher(input, request);
330
+ };
331
+ return createChannelClient({ ...coreOptions, fetch: nextFetch });
332
+ }
333
+
334
+ export { CHANNEL_CATALOG_CACHE_TAG, CHANNEL_SITE_CACHE_TAG, cartCookie, createCart, createChannelWebhookRoute, createCustomerSession, createNextChannelClient, defaultChannelCacheTags, safePublishedPath, sessionCookie };