@c1m-public/channel-client 0.6.0 → 0.8.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
@@ -32,13 +32,13 @@ const { page } = await channel.pages.get("home");
32
32
  const { order: cart } = await channel.cart.addItem({ product_id: "product-id", quantity: 1 });
33
33
 
34
34
  // Checkout is addressed by the ORDER the cart became (every cart call returns
35
- // its order.id). The idempotency key is DETERMINISTIC on purpose: a fresh
36
- // random key per retry is the exact duplicate-charge hazard idempotency exists
37
- // to prevent.
35
+ // its order.id). One key belongs to one logical payment attempt. Keep it stable
36
+ // while retrying that attempt; mint a new key after a correctable checkout
37
+ // failure so the server does not replay the old 4xx response.
38
38
  const checkout = await channel.checkout.pay(
39
39
  cart.id,
40
40
  { cart_token: cart.cart_token!, return_url: "https://example.com/checkout/complete" },
41
- { idempotencyKey: `pay:${cart.id}` },
41
+ { idempotencyKey: paymentAttemptId },
42
42
  );
43
43
  ```
44
44
 
@@ -69,6 +69,8 @@ other runtimes must enforce their own server-module boundary.
69
69
  continues to resolve tenant and workspace identity at the API door.
70
70
  - Requests time out after 10 seconds by default.
71
71
  - API failures throw `ChannelAPIError` with safe status, code, and request ID.
72
+ - Use `isChannelAPIError(error)` instead of `instanceof`; it remains correct
73
+ when a server bundle contains more than one package instance.
72
74
  - Assets remain tokenless and are normalized with `assetUrl()`.
73
75
  - `observe` can receive one bounded telemetry event per logical request. Events
74
76
  contain operation, outcome, status, request ID, duration and attempt count;
@@ -136,6 +138,28 @@ export const POST = createChannelWebhookRoute({
136
138
  });
137
139
  ```
138
140
 
141
+ Out of the box that route keeps your cache honest with no configuration:
142
+ `page.published` revalidates the published path plus `CHANNEL_SITE_CACHE_TAG`,
143
+ and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`. Tag your
144
+ catalog reads with it and a merchant's price edit reaches the storefront on the
145
+ next request instead of at the end of a TTL — the difference between a correct
146
+ price and a stale one at checkout.
147
+
148
+ ```ts
149
+ // A client whose reads are filed under the catalog tag the webhook route busts.
150
+ const catalog = createNextChannelClient({
151
+ baseUrl: process.env.C1M_API_URL!,
152
+ token: process.env.C1M_CHANNEL_TOKEN!,
153
+ cache: { revalidate: 3600, tags: [CHANNEL_CATALOG_CACHE_TAG] },
154
+ });
155
+ const products = await catalog.products.list();
156
+ ```
157
+
158
+ The core also exposes the complete current channel door: published blog lists,
159
+ giving entries and checkout start, Quick Print settings/quotes/multipart intake,
160
+ and assembled dining menus. `pnpm contract:check` compares the client inventory
161
+ with the canonical server OpenAPI document when both repositories are present.
162
+
139
163
  ```ts
140
164
  // session: cookie codec + the contested-vs-expired refresh decision
141
165
  const session = createCustomerSession({ client: getChannelClient });
@@ -151,5 +175,5 @@ await cart.addItem({ cart_token, product_id, quantity: 1 });
151
175
  const { redirect_url } = await cart.checkout.pay(orderId, {
152
176
  cart_token,
153
177
  return_url: "https://your-site.example/thanks", // must be on the channel's registered site
154
- });
178
+ }, { idempotencyKey: paymentAttemptId });
155
179
  ```
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./webhooks.js";
2
- export type { BlogPost, BlogPostResponse, AddCartItemInput, CartResponse, CheckoutAddress, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatus, CheckoutStatusResponse, ChannelPing, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderItem, OrderSummary, MergeCartInput, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, PaymentMethodOption, PaymentReadiness, ShippingMethodOption, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, UpdateCartItemInput, } from "./types";
3
- import type { BlogPostResponse, AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, ChannelPing, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, MergeCartInput, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse, UpdateCartItemInput } from "./types";
2
+ export type * from "./types.js";
3
+ export type { BlogPost, BlogPostResponse, DiningMenu, GivingEntry, GivingIntent, AddCartItemInput, CartResponse, CheckoutAddress, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatus, CheckoutStatusResponse, ChannelPing, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderItem, OrderSummary, MergeCartInput, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, PaymentMethodOption, PaymentReadiness, ShippingMethodOption, SiteDocument, SiteGatedDocument, SiteResolvedDocument, StartGivingInput, StartGivingResponse, ThemeResponse, UpdateCartItemInput, } from "./types";
4
+ import type { BlogPostResponse, DiningMenu, GivingEntry, AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, ChannelPing, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, MergeCartInput, SendCodeResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, StartGivingInput, StartGivingResponse, ThemeResponse, UpdateCartItemInput } from "./types";
4
5
  export interface ChannelRetryPolicy {
5
6
  attempts?: number;
6
7
  maxDelayMs?: number;
@@ -12,9 +13,11 @@ export interface CreateChannelClientOptions {
12
13
  timeoutMs?: number;
13
14
  retry?: ChannelRetryPolicy | false;
14
15
  observe?: ChannelRequestObserver;
16
+ /** Optional request-scope cancellation signal, combined with the timeout. */
17
+ signal?: AbortSignal;
15
18
  }
16
- export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response";
17
- export type ChannelOperation = "channel.ping" | "channel.site.resolve" | "channel.init.get" | "channel.init.light" | "content.pages.public.list.channel" | "content.pages.public.get.channel" | "shop.public.products.list.channel" | "shop.public.products.get.channel" | "shop.public.products.media.channel" | "reviews.public.list.channel" | "reviews.public.summary.channel" | "reviews.public.submit.channel" | "channel.theme.get" | "channel.menus.get" | "channel.blog.get" | "channel.auth.check" | "channel.auth.signup" | "channel.auth.send_code" | "channel.auth.verify_code" | "channel.auth.refresh" | "channel.auth.me" | "channel.auth.me.update" | "channel.auth.logout" | "channel.account.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "channel.cart.get" | "channel.cart.items.add" | "channel.cart.items.update" | "channel.cart.items.remove" | "channel.cart.clear" | "channel.cart.merge" | "channel.checkout.options" | "channel.checkout.status" | "channel.checkout.customer" | "channel.checkout.addresses" | "channel.checkout.fulfillment" | "channel.checkout.pay" | "growth.public_workspace.leads.capture.channel";
19
+ export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
20
+ export type ChannelOperation = "channel.ping" | "channel.site.resolve" | "channel.init.get" | "channel.init.light" | "content.pages.public.list.channel" | "content.pages.public.get.channel" | "shop.public.products.list.channel" | "shop.public.products.get.channel" | "shop.public.products.media.channel" | "reviews.public.list.channel" | "reviews.public.summary.channel" | "reviews.public.submit.channel" | "channel.theme.get" | "channel.menus.get" | "channel.blog.get" | "channel.blog.list" | "channel.giving.entries.list" | "channel.giving.entries.get" | "channel.giving.start" | "channel.print.settings" | "channel.print.quote" | "channel.print.intake" | "dining.public.board_menu.channel" | "channel.auth.check" | "channel.auth.signup" | "channel.auth.send_code" | "channel.auth.verify_code" | "channel.auth.refresh" | "channel.auth.me" | "channel.auth.me.update" | "channel.auth.logout" | "channel.account.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "channel.cart.get" | "channel.cart.items.add" | "channel.cart.items.update" | "channel.cart.items.remove" | "channel.cart.clear" | "channel.cart.merge" | "channel.checkout.options" | "channel.checkout.status" | "channel.checkout.customer.set" | "channel.checkout.addresses.set" | "channel.checkout.fulfillment.set" | "channel.checkout.pay" | "growth.public_workspace.leads.capture.channel";
18
21
  export interface ChannelRequestObservation {
19
22
  operation: ChannelOperation;
20
23
  method: string;
@@ -35,6 +38,10 @@ export interface ChannelListParams {
35
38
  }
36
39
  export interface ChannelProductListParams extends ChannelListParams {
37
40
  currency?: string;
41
+ search?: string;
42
+ category_id?: string;
43
+ brand_id?: string;
44
+ type_id?: string;
38
45
  }
39
46
  export interface ChannelSiteResolveParams {
40
47
  route?: string;
@@ -60,6 +67,8 @@ export declare class ChannelAPIError extends Error {
60
67
  readonly requestId: string;
61
68
  constructor(message: string, status: number, code: string, requestId: string);
62
69
  }
70
+ /** Works across duplicate package instances and transformed test bundles. */
71
+ export declare function isChannelAPIError(error: unknown): error is ChannelAPIError;
63
72
  export declare function createChannelClient(options: CreateChannelClientOptions): {
64
73
  /**
65
74
  * Verify the channel token and see what it points at.
@@ -122,8 +131,30 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
122
131
  readonly get: (handle: string) => Promise<MenuResponse>;
123
132
  };
124
133
  readonly blog: {
134
+ readonly list: (params?: ChannelListParams) => Promise<ListResponse<import("./types.js").BlogPost>>;
125
135
  readonly get: (slug: string) => Promise<BlogPostResponse>;
126
136
  };
137
+ readonly giving: {
138
+ readonly entries: {
139
+ readonly list: () => Promise<{
140
+ items: GivingEntry[];
141
+ }>;
142
+ readonly get: (slug: string) => Promise<{
143
+ entry: GivingEntry;
144
+ }>;
145
+ };
146
+ readonly start: (input: StartGivingInput, mutation?: ChannelMutationOptions) => Promise<StartGivingResponse>;
147
+ };
148
+ readonly print: {
149
+ readonly settings: () => Promise<PrintSettingsResponse>;
150
+ readonly quote: (input: PrintOptionsSelection) => Promise<PrintQuoteResponse>;
151
+ readonly intake: (input: PrintIntakeInput, mutation?: ChannelMutationOptions) => Promise<{
152
+ job: PrintJob;
153
+ }>;
154
+ };
155
+ readonly dining: {
156
+ readonly menu: (boardSlug: string) => Promise<DiningMenu>;
157
+ };
127
158
  readonly auth: {
128
159
  readonly check: (email: string) => Promise<{
129
160
  exists: boolean;
@@ -169,6 +200,9 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
169
200
  order: Order;
170
201
  }>;
171
202
  };
203
+ readonly giving: {
204
+ readonly start: (input: StartGivingInput, mutation?: ChannelMutationOptions) => Promise<StartGivingResponse>;
205
+ };
172
206
  };
173
207
  readonly leads: {
174
208
  readonly create: (input: ChannelLeadInput, mutation?: ChannelMutationOptions) => Promise<{
package/dist/index.js CHANGED
@@ -13,6 +13,15 @@ export class ChannelAPIError extends Error {
13
13
  this.name = "ChannelAPIError";
14
14
  }
15
15
  }
16
+ /** Works across duplicate package instances and transformed test bundles. */
17
+ export function isChannelAPIError(error) {
18
+ return (error instanceof ChannelAPIError ||
19
+ (typeof error === "object" && error !== null &&
20
+ error.name === "ChannelAPIError" &&
21
+ typeof error.status === "number" &&
22
+ typeof error.code === "string" &&
23
+ typeof error.requestId === "string"));
24
+ }
16
25
  function required(value, label) {
17
26
  const normalized = value.trim();
18
27
  if (!normalized)
@@ -49,6 +58,17 @@ function retryDelay(response, maxDelayMs) {
49
58
  function wait(ms) {
50
59
  return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
51
60
  }
61
+ function combineSignals(...signals) {
62
+ const active = signals.filter((signal) => Boolean(signal));
63
+ if (active.length === 0)
64
+ return undefined;
65
+ if (active.length === 1)
66
+ return active[0];
67
+ return AbortSignal.any(active);
68
+ }
69
+ function isFormDataBody(body) {
70
+ return typeof FormData !== "undefined" && body instanceof FormData;
71
+ }
52
72
  export function createChannelClient(options) {
53
73
  const baseUrl = required(options.baseUrl, "baseUrl").replace(/\/+$/, "");
54
74
  const token = required(options.token, "token");
@@ -79,8 +99,9 @@ export function createChannelClient(options) {
79
99
  headers.set("Authorization", `Bearer ${token}`);
80
100
  if (session)
81
101
  headers.set("X-End-User-Token", session);
82
- if (init.body !== undefined && !headers.has("Content-Type"))
102
+ if (init.body !== undefined && !isFormDataBody(init.body) && !headers.has("Content-Type")) {
83
103
  headers.set("Content-Type", "application/json");
104
+ }
84
105
  const requestInit = { ...init, method, headers };
85
106
  // Private reads and every mutation are non-cacheable in every runtime. An
86
107
  // adapter may add framework caching only to anonymous GET requests.
@@ -94,14 +115,25 @@ export function createChannelClient(options) {
94
115
  const controller = new AbortController();
95
116
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
96
117
  try {
97
- response = await fetcher(`${baseUrl}/api/v1/channel${path}`, { ...requestInit, signal: controller.signal });
118
+ response = await fetcher(`${baseUrl}/api/v1/channel${path}`, {
119
+ ...requestInit,
120
+ signal: combineSignals(options.signal, requestInit.signal, controller.signal),
121
+ });
98
122
  }
99
- catch (error) {
123
+ catch {
100
124
  if (controller.signal.aborted) {
101
125
  outcome = "timeout";
102
126
  throw new ChannelAPIError("Channel API request timed out", 0, "channel_request_timeout", "");
103
127
  }
128
+ if (options.signal?.aborted || requestInit.signal?.aborted) {
129
+ outcome = "cancelled";
130
+ throw new ChannelAPIError("Channel API request was cancelled", 0, "channel_request_cancelled", "");
131
+ }
104
132
  outcome = "network_error";
133
+ if (method === "GET" && attempt < retryAttempts) {
134
+ await wait(Math.min(250, maxRetryDelayMs));
135
+ continue;
136
+ }
105
137
  throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
106
138
  }
107
139
  finally {
@@ -122,8 +154,13 @@ export function createChannelClient(options) {
122
154
  throw new ChannelAPIError(typeof payload.message === "string" ? payload.message : "Channel API request failed", response.status, typeof payload.code === "string" ? payload.code : "channel_request_failed", requestId);
123
155
  }
124
156
  try {
125
- const payload = (await response.json());
126
157
  outcome = "success";
158
+ if (response.status === 204)
159
+ return undefined;
160
+ const text = await response.text();
161
+ if (!text)
162
+ return undefined;
163
+ const payload = JSON.parse(text);
127
164
  return payload;
128
165
  }
129
166
  catch {
@@ -206,13 +243,13 @@ export function createChannelClient(options) {
206
243
  cart_token: params.cartToken,
207
244
  checkout_session_id: params.checkoutSessionId,
208
245
  })),
209
- setCustomer: (orderId, input, mutation) => request("channel.checkout.customer", `/checkout/${encodePath(orderId)}/customer`, {
246
+ setCustomer: (orderId, input, mutation) => request("channel.checkout.customer.set", `/checkout/${encodePath(orderId)}/customer`, {
210
247
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
211
248
  }),
212
- setAddresses: (orderId, input, mutation) => request("channel.checkout.addresses", `/checkout/${encodePath(orderId)}/addresses`, {
249
+ setAddresses: (orderId, input, mutation) => request("channel.checkout.addresses.set", `/checkout/${encodePath(orderId)}/addresses`, {
213
250
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
214
251
  }),
215
- setFulfillment: (orderId, input, mutation) => request("channel.checkout.fulfillment", `/checkout/${encodePath(orderId)}/fulfillment`, {
252
+ setFulfillment: (orderId, input, mutation) => request("channel.checkout.fulfillment.set", `/checkout/${encodePath(orderId)}/fulfillment`, {
216
253
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
217
254
  }),
218
255
  pay: (orderId, input, mutation) => request("channel.checkout.pay", `/checkout/${encodePath(orderId)}/pay`, {
@@ -233,8 +270,43 @@ export function createChannelClient(options) {
233
270
  get: (handle) => request("channel.menus.get", `/menus/${encodePath(handle)}`),
234
271
  },
235
272
  blog: {
273
+ list: (params = {}) => request("channel.blog.list", appendQuery("/blog/posts", params)),
236
274
  get: (slug) => request("channel.blog.get", `/blog/posts/${encodePath(slug)}`),
237
275
  },
276
+ giving: {
277
+ entries: {
278
+ list: () => request("channel.giving.entries.list", "/giving/entries"),
279
+ get: (slug) => request("channel.giving.entries.get", `/giving/entries/${encodePath(slug)}`),
280
+ },
281
+ start: (input, mutation) => request("channel.giving.start", "/give/start", {
282
+ method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
283
+ }),
284
+ },
285
+ print: {
286
+ settings: () => request("channel.print.settings", "/print/settings"),
287
+ quote: (input) => request("channel.print.quote", "/print/quote", {
288
+ method: "POST", body: JSON.stringify(input),
289
+ }),
290
+ intake: (input, mutation) => {
291
+ const form = new FormData();
292
+ form.set("name", input.name);
293
+ if (input.email)
294
+ form.set("email", input.email);
295
+ if (input.phone)
296
+ form.set("phone", input.phone);
297
+ if (input.notes)
298
+ form.set("notes", input.notes);
299
+ form.set("options", JSON.stringify(input.options));
300
+ for (const file of input.files)
301
+ form.append("files", file.blob, file.filename);
302
+ return request("channel.print.intake", "/print/intake", {
303
+ method: "POST", headers: mutationHeaders(mutation), body: form,
304
+ });
305
+ },
306
+ },
307
+ dining: {
308
+ menu: (boardSlug) => request("dining.public.board_menu.channel", `/dining/boards/${encodePath(boardSlug)}/menu`),
309
+ },
238
310
  // Customer sign-in. These are anonymous calls — they CREATE a session.
239
311
  auth: {
240
312
  check: (email) => request("channel.auth.check", "/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
@@ -265,6 +337,11 @@ export function createChannelClient(options) {
265
337
  summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
266
338
  get: (orderId) => request("channel.account.orders.get", `/account/orders/${encodePath(orderId)}`, {}, customerSession),
267
339
  },
340
+ giving: {
341
+ start: (input, mutation) => request("channel.giving.start", "/give/start", {
342
+ method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
343
+ }, customerSession),
344
+ },
268
345
  };
269
346
  },
270
347
  leads: {
@@ -1,5 +1,5 @@
1
1
  import "server-only";
2
- import { createChannelClient, type ChannelCheckoutStatusParams } from "./index.js";
2
+ import { createChannelClient, type ChannelCheckoutStatusParams, type ChannelMutationOptions } from "./index.js";
3
3
  import type { AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, Order } from "./types.js";
4
4
  export interface CartCookieAttributes {
5
5
  httpOnly: true;
@@ -67,6 +67,8 @@ export declare function createCart(options: CreateCartOptions): {
67
67
  */
68
68
  readonly pay: (orderId: string, input: CheckoutPayInput & {
69
69
  return_url: string;
70
+ }, attempt: ChannelMutationOptions & {
71
+ idempotencyKey: string;
70
72
  }) => Promise<CheckoutPayResponse>;
71
73
  };
72
74
  };
package/dist/next-cart.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "server-only";
2
- import { createChannelClient } from "./index.js";
2
+ import { createChannelClient, isChannelAPIError, } from "./index.js";
3
3
  function inProduction() {
4
4
  return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
5
5
  }
@@ -39,8 +39,10 @@ export function createCart(options) {
39
39
  const { order } = await resolve().cart.get(cartToken);
40
40
  return order ?? null;
41
41
  }
42
- catch {
43
- return null;
42
+ catch (error) {
43
+ if (isChannelAPIError(error) && error.status === 404)
44
+ return null;
45
+ throw error;
44
46
  }
45
47
  },
46
48
  async addItem(input) {
@@ -79,7 +81,7 @@ export function createCart(options) {
79
81
  * must be on the channel's registered site_url — the server refuses
80
82
  * anything else, because an unchecked return URL is an open redirect.
81
83
  */
82
- pay: (orderId, input) => resolve().checkout.pay(orderId, input, { idempotencyKey: `pay:${orderId}` }),
84
+ pay: (orderId, input, attempt) => resolve().checkout.pay(orderId, input, attempt),
83
85
  },
84
86
  };
85
87
  }
@@ -1,5 +1,5 @@
1
1
  import "server-only";
2
- import { ChannelAPIError, createChannelClient } from "./index.js";
2
+ import { createChannelClient, isChannelAPIError } from "./index.js";
3
3
  function inProduction() {
4
4
  return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
5
5
  }
@@ -62,23 +62,6 @@ export const sessionCookie = {
62
62
  };
63
63
  /** The server's code for "another request rotated this token moments ago". */
64
64
  const CONTESTED = "refresh_contested";
65
- /**
66
- * Structural, not instanceof: a published package can be instantiated twice in
67
- * one process (pnpm strictness, bundler duplication, test transforms), and
68
- * `instanceof` across instances silently fails — which here would misclassify a
69
- * DEAD session as a transient wobble and keep a corpse cookie forever.
70
- */
71
- function asChannelAPIError(error) {
72
- if (error instanceof ChannelAPIError)
73
- return error;
74
- if (typeof error === "object" && error !== null &&
75
- error.name === "ChannelAPIError" &&
76
- typeof error.status === "number" &&
77
- typeof error.code === "string") {
78
- return error;
79
- }
80
- return null;
81
- }
82
65
  function normalizeCustomer(customer) {
83
66
  return {
84
67
  id: customer.id,
@@ -127,8 +110,7 @@ export function createCustomerSession(options) {
127
110
  }
128
111
  catch (error) {
129
112
  // A wrong code is an ordinary thing a person does, not a failure.
130
- const api = asChannelAPIError(error);
131
- if (api && (api.status === 401 || api.status === 400)) {
113
+ if (isChannelAPIError(error) && error.code === "invalid_code") {
132
114
  return { state: "invalid-code" };
133
115
  }
134
116
  return { state: "failed" };
@@ -153,14 +135,13 @@ export function createCustomerSession(options) {
153
135
  };
154
136
  }
155
137
  catch (error) {
156
- const api = asChannelAPIError(error);
157
- if (api) {
138
+ if (isChannelAPIError(error)) {
158
139
  // Lost a race with the customer's own other tab: the session is alive
159
140
  // and that tab already stored a good token. KEEP the cookie.
160
- if (api.code === CONTESTED)
141
+ if (error.code === CONTESTED)
161
142
  return { action: "keep" };
162
143
  // Genuinely dead — logged out, revoked, or aged out. Clear it.
163
- if (api.status === 401)
144
+ if (error.status === 401)
164
145
  return { action: "clear" };
165
146
  }
166
147
  // An upstream wobble is not evidence anyone's session is dead.
@@ -16,6 +16,12 @@ import { type ChannelWebhookEvent, type ChannelWebhookEventDataMap } from "./web
16
16
  */
17
17
  /** The cache tag every anonymous site read is filed under. */
18
18
  export declare const CHANNEL_SITE_CACHE_TAG = "channel:site";
19
+ /**
20
+ * The cache tag catalog reads (product list, product detail) are filed under.
21
+ * `product.*` events bust this tag by default, so a merchant's price edit
22
+ * reaches the storefront on the next request instead of at the end of a TTL.
23
+ */
24
+ export declare const CHANNEL_CATALOG_CACHE_TAG = "channel:catalog";
19
25
  export interface ChannelCacheInvalidator {
20
26
  revalidatePath(path: string): void;
21
27
  revalidateTag(tag: string): void;
@@ -1,5 +1,5 @@
1
1
  import "server-only";
2
- import { ChannelWebhookVerificationError, parseChannelWebhookEvent, } from "./webhooks.js";
2
+ import { ChannelWebhookVerificationError, isChannelWebhookEventType, parseChannelWebhookEvent, } from "./webhooks.js";
3
3
  /**
4
4
  * Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
5
5
  *
@@ -16,6 +16,12 @@ import { ChannelWebhookVerificationError, parseChannelWebhookEvent, } from "./we
16
16
  */
17
17
  /** The cache tag every anonymous site read is filed under. */
18
18
  export const CHANNEL_SITE_CACHE_TAG = "channel:site";
19
+ /**
20
+ * The cache tag catalog reads (product list, product detail) are filed under.
21
+ * `product.*` events bust this tag by default, so a merchant's price edit
22
+ * reaches the storefront on the next request instead of at the end of a TTL.
23
+ */
24
+ export const CHANNEL_CATALOG_CACHE_TAG = "channel:catalog";
19
25
  /**
20
26
  * A route_pattern arrives from the network; it is input, not truth. Reject
21
27
  * anything that is not a plain absolute path before handing it to the cache.
@@ -36,14 +42,23 @@ function isVerificationError(error) {
36
42
  typeof error.code === "string");
37
43
  }
38
44
  function defaultBehavior(event, invalidate) {
39
- if (event.type !== "page.published")
45
+ if (event.type === "page.published") {
46
+ const path = safePublishedPath(event.data.route_pattern);
47
+ if (!path)
48
+ throw new Error("page.published contains an invalid route_pattern");
49
+ invalidate.revalidateTag(CHANNEL_SITE_CACHE_TAG);
50
+ invalidate.revalidatePath(path);
51
+ return path;
52
+ }
53
+ // A catalog edit with no cache bust means the site serves the old price
54
+ // until its TTL expires — so product.* busts the catalog tag by default,
55
+ // with no configuration. Tag your product reads with
56
+ // CHANNEL_CATALOG_CACHE_TAG and a price change lands on the next request.
57
+ if (event.type === "product.created" || event.type === "product.updated" || event.type === "product.deleted") {
58
+ invalidate.revalidateTag(CHANNEL_CATALOG_CACHE_TAG);
40
59
  return undefined;
41
- const path = safePublishedPath(event.data.route_pattern);
42
- if (!path)
43
- throw new Error("page.published contains an invalid route_pattern");
44
- invalidate.revalidateTag(CHANNEL_SITE_CACHE_TAG);
45
- invalidate.revalidatePath(path);
46
- return path;
60
+ }
61
+ return undefined;
47
62
  }
48
63
  /** Build the POST handler for the channel webhook endpoint. */
49
64
  export function createChannelWebhookRoute(options) {
@@ -65,17 +80,22 @@ export function createChannelWebhookRoute(options) {
65
80
  return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
66
81
  }
67
82
  try {
68
- const handler = options.onEvent?.[event.type];
83
+ if (!isChannelWebhookEventType(event.type)) {
84
+ logger.info("channel_webhook_ignored", { eventId: event.id, eventType: event.type });
85
+ return new Response(null, { status: 204 });
86
+ }
87
+ const knownEvent = event;
88
+ const handler = options.onEvent?.[knownEvent.type];
69
89
  let revalidatedPath;
70
90
  if (handler) {
71
- await handler(event, options.invalidate);
91
+ await handler(knownEvent, options.invalidate);
72
92
  }
73
93
  else {
74
- revalidatedPath = defaultBehavior(event, options.invalidate);
94
+ revalidatedPath = defaultBehavior(knownEvent, options.invalidate);
75
95
  }
76
96
  logger.info("channel_webhook_processed", {
77
97
  eventId: event.id,
78
- eventType: event.type,
98
+ eventType: knownEvent.type,
79
99
  ...(revalidatedPath ? { revalidatedPath } : {}),
80
100
  });
81
101
  return new Response(null, { status: 204 });
package/dist/next.d.ts CHANGED
@@ -67,8 +67,30 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
67
67
  readonly get: (handle: string) => Promise<import("./types.js").MenuResponse>;
68
68
  };
69
69
  readonly blog: {
70
+ readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").BlogPost>>;
70
71
  readonly get: (slug: string) => Promise<import("./types.js").BlogPostResponse>;
71
72
  };
73
+ readonly giving: {
74
+ readonly entries: {
75
+ readonly list: () => Promise<{
76
+ items: import("./types.js").GivingEntry[];
77
+ }>;
78
+ readonly get: (slug: string) => Promise<{
79
+ entry: import("./types.js").GivingEntry;
80
+ }>;
81
+ };
82
+ readonly start: (input: import("./types.js").StartGivingInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").StartGivingResponse>;
83
+ };
84
+ readonly print: {
85
+ readonly settings: () => Promise<import("./types.js").PrintSettingsResponse>;
86
+ readonly quote: (input: import("./types.js").PrintOptionsSelection) => Promise<import("./types.js").PrintQuoteResponse>;
87
+ readonly intake: (input: import("./types.js").PrintIntakeInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
88
+ job: import("./types.js").PrintJob;
89
+ }>;
90
+ };
91
+ readonly dining: {
92
+ readonly menu: (boardSlug: string) => Promise<import("./types.js").DiningMenu>;
93
+ };
72
94
  readonly auth: {
73
95
  readonly check: (email: string) => Promise<{
74
96
  exists: boolean;
@@ -103,6 +125,9 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
103
125
  order: import("./types.js").Order;
104
126
  }>;
105
127
  };
128
+ readonly giving: {
129
+ readonly start: (input: import("./types.js").StartGivingInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").StartGivingResponse>;
130
+ };
106
131
  };
107
132
  readonly leads: {
108
133
  readonly create: (input: import("./index.js").ChannelLeadInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
package/dist/types.d.ts CHANGED
@@ -232,6 +232,320 @@ export interface BlogPost {
232
232
  export interface BlogPostResponse {
233
233
  post: BlogPost;
234
234
  }
235
+ export interface GivingEntry {
236
+ id: string;
237
+ workspace_id: string;
238
+ slug: string;
239
+ title: string;
240
+ subtitle?: string;
241
+ variant: string;
242
+ default_amount_cents: number;
243
+ suggested_amounts_cents?: number[];
244
+ allow_custom_amount: boolean;
245
+ cta_label?: string;
246
+ is_active: boolean;
247
+ created_at: string;
248
+ updated_at: string;
249
+ }
250
+ export interface GivingIntent {
251
+ id: string;
252
+ workspace_id: string;
253
+ status: string;
254
+ variant: string;
255
+ title: string;
256
+ description?: string;
257
+ currency: string;
258
+ amount_cents: number;
259
+ is_recurring: boolean;
260
+ is_anonymous: boolean;
261
+ display_name?: string;
262
+ email?: string;
263
+ message?: string;
264
+ session_id?: string;
265
+ recurring_agreement_id?: string;
266
+ source_invoice_id?: string;
267
+ created_at: string;
268
+ updated_at: string;
269
+ refunded_at?: string;
270
+ }
271
+ export interface StartGivingInput {
272
+ variant?: string;
273
+ title?: string;
274
+ description?: string;
275
+ amount_cents: number;
276
+ currency?: string;
277
+ is_recurring?: boolean;
278
+ is_anonymous?: boolean;
279
+ display_name?: string;
280
+ email?: string;
281
+ message?: string;
282
+ success_url?: string;
283
+ cancel_url?: string;
284
+ }
285
+ export interface StartGivingResponse {
286
+ giving: GivingIntent;
287
+ session: {
288
+ session_id: string;
289
+ url: string;
290
+ payment_intent_id?: string;
291
+ };
292
+ }
293
+ export interface PrintPerPagePricing {
294
+ bw_cents: number;
295
+ colour_cents: number;
296
+ }
297
+ export interface PrintPaperSize {
298
+ key: string;
299
+ label: string;
300
+ surcharge_cents: number;
301
+ enabled: boolean;
302
+ }
303
+ export interface PrintPricingOption {
304
+ key: string;
305
+ label: string;
306
+ type: string;
307
+ surcharge_cents: number;
308
+ }
309
+ export interface PrintPricing {
310
+ base_fee_cents: number;
311
+ per_page: PrintPerPagePricing;
312
+ paper_sizes: PrintPaperSize[];
313
+ options: PrintPricingOption[];
314
+ min_total_cents: number;
315
+ }
316
+ export interface PrintBranding {
317
+ display_name?: string;
318
+ logo_url?: string;
319
+ accent?: string;
320
+ instructions?: string;
321
+ }
322
+ export interface PrintIntakeLimits {
323
+ max_files: number;
324
+ max_file_bytes: number;
325
+ max_total_bytes: number;
326
+ allowed_extensions: string[];
327
+ }
328
+ export interface PrintSettingsResponse {
329
+ accepting: boolean;
330
+ currency: string;
331
+ retention_days: number;
332
+ pricing: PrintPricing;
333
+ branding: PrintBranding;
334
+ intake_limits: PrintIntakeLimits;
335
+ }
336
+ export interface PrintOptionsSelection {
337
+ paper_size: string;
338
+ colour: boolean;
339
+ pages: number;
340
+ copies: number;
341
+ extras?: Record<string, boolean>;
342
+ }
343
+ export interface PrintPriceLine {
344
+ label: string;
345
+ amount_cents: number;
346
+ }
347
+ export interface PrintPriceBreakdown {
348
+ lines: PrintPriceLine[];
349
+ total_cents: number;
350
+ currency: string;
351
+ }
352
+ export interface PrintQuoteResponse {
353
+ price_cents: number;
354
+ currency: string;
355
+ breakdown: PrintPriceBreakdown;
356
+ }
357
+ export interface PrintIntakeInput {
358
+ name: string;
359
+ email?: string;
360
+ phone?: string;
361
+ notes?: string;
362
+ options: PrintOptionsSelection;
363
+ files: Array<{
364
+ blob: Blob;
365
+ filename: string;
366
+ }>;
367
+ }
368
+ export interface PrintJobFile {
369
+ id: string;
370
+ job_id: string;
371
+ file_name: string;
372
+ mime_type: string;
373
+ size_bytes: number;
374
+ page_count?: number;
375
+ sort_order: number;
376
+ created_at: string;
377
+ }
378
+ export interface PrintJob {
379
+ id: string;
380
+ workspace_id: string;
381
+ reference: string;
382
+ customer_name: string;
383
+ customer_email?: string;
384
+ customer_phone?: string;
385
+ status: string;
386
+ payment_status: string;
387
+ payment_method: string;
388
+ options: PrintOptionsSelection;
389
+ price_cents: number;
390
+ currency: string;
391
+ price_breakdown: PrintPriceBreakdown;
392
+ notes?: string;
393
+ file_count?: number;
394
+ version: number;
395
+ files?: PrintJobFile[];
396
+ created_at: string;
397
+ updated_at: string;
398
+ }
399
+ export interface DiningAvailabilityRule {
400
+ days?: string[];
401
+ start?: string;
402
+ end?: string;
403
+ starts_on?: string;
404
+ ends_on?: string;
405
+ }
406
+ export interface DiningAvailability {
407
+ timezone?: string;
408
+ rules?: DiningAvailabilityRule[];
409
+ is_available_now: boolean;
410
+ next_change_at?: string;
411
+ }
412
+ export interface DiningItemSize {
413
+ id: string;
414
+ name: string;
415
+ price_cents: number;
416
+ is_default: boolean;
417
+ sort_order: number;
418
+ is_active: boolean;
419
+ }
420
+ export interface DiningModifier {
421
+ id: string;
422
+ name: string;
423
+ description?: string;
424
+ price_delta_cents: number;
425
+ is_default: boolean;
426
+ sort_order: number;
427
+ is_active: boolean;
428
+ }
429
+ export interface DiningModifierGroup {
430
+ id: string;
431
+ name: string;
432
+ description?: string;
433
+ selection_type: string;
434
+ is_required: boolean;
435
+ min_selections: number;
436
+ max_selections?: number;
437
+ sort_order: number;
438
+ is_active: boolean;
439
+ modifiers: DiningModifier[];
440
+ }
441
+ export interface DiningOfferBadge {
442
+ offer_id: string;
443
+ label: string;
444
+ type: string;
445
+ is_featured: boolean;
446
+ display_priority: number;
447
+ }
448
+ export interface DiningComboChoice {
449
+ id: string;
450
+ item: {
451
+ id: string;
452
+ slug: string;
453
+ name: string;
454
+ description?: string;
455
+ base_price_cents: number;
456
+ image_url?: string;
457
+ image_alt: string;
458
+ badges: string[];
459
+ status: string;
460
+ dietary_flags: string[];
461
+ allergens: string[];
462
+ calories?: number;
463
+ prep_time_mins?: number;
464
+ spice_level?: number;
465
+ kitchen_station?: string;
466
+ sizes: DiningItemSize[];
467
+ modifier_groups: DiningModifierGroup[];
468
+ };
469
+ label_override?: string;
470
+ description_override?: string;
471
+ price_delta_cents: number;
472
+ is_default: boolean;
473
+ sort_order: number;
474
+ is_active: boolean;
475
+ is_available: boolean;
476
+ }
477
+ export interface DiningComboGroup {
478
+ id: string;
479
+ name: string;
480
+ description?: string;
481
+ min_selections: number;
482
+ max_selections?: number;
483
+ allow_repeats: boolean;
484
+ sort_order: number;
485
+ is_active: boolean;
486
+ choices: DiningComboChoice[];
487
+ }
488
+ export interface DiningOffer {
489
+ id: string;
490
+ name: string;
491
+ badge_label?: string;
492
+ type: string;
493
+ code?: string;
494
+ is_featured: boolean;
495
+ display_priority: number;
496
+ image_url?: string;
497
+ availability?: DiningAvailability;
498
+ is_active: boolean;
499
+ }
500
+ export interface DiningMenuItem {
501
+ id: string;
502
+ slug: string;
503
+ name: string;
504
+ description?: string;
505
+ item_kind: string;
506
+ price_cents: number;
507
+ price_from_cents: number;
508
+ image_url?: string;
509
+ image_alt: string;
510
+ badges: string[];
511
+ is_featured: boolean;
512
+ is_available: boolean;
513
+ status: string;
514
+ dietary_flags: string[];
515
+ allergens: string[];
516
+ calories?: number;
517
+ prep_time_mins?: number;
518
+ spice_level?: number;
519
+ sizes: DiningItemSize[];
520
+ modifier_groups: DiningModifierGroup[];
521
+ offer_badges: DiningOfferBadge[];
522
+ combo_groups?: DiningComboGroup[];
523
+ }
524
+ export interface DiningMenu {
525
+ saas_app: string;
526
+ workspace_id: string;
527
+ board: {
528
+ id: string;
529
+ slug: string;
530
+ name: string;
531
+ description?: string;
532
+ currency: string;
533
+ applicable_order_types: string[];
534
+ availability?: DiningAvailability;
535
+ is_active: boolean;
536
+ };
537
+ sections: Array<{
538
+ id: string;
539
+ name: string;
540
+ description?: string;
541
+ sort_order: number;
542
+ availability?: DiningAvailability;
543
+ is_active: boolean;
544
+ items: DiningMenuItem[];
545
+ }>;
546
+ offers: DiningOffer[];
547
+ generated_at: string;
548
+ }
235
549
  /** The published theme, as served to a channel that owns its own routing and
236
550
  * therefore never calls `site.resolve` (which otherwise bundles it). */
237
551
  export interface ThemeResponse {
@@ -9,7 +9,7 @@
9
9
  * PII-free fields; fetch the detail back through the channel client. Data POSTed
10
10
  * to your server can never be reached by a GDPR erasure on ours.
11
11
  */
12
- export declare const CHANNEL_WEBHOOK_EVENT_TYPES: readonly ["order.created", "order.paid", "lead.created", "review.submitted", "page.published"];
12
+ export declare const CHANNEL_WEBHOOK_EVENT_TYPES: readonly ["order.created", "order.paid", "order.updated", "order.cancelled", "order.refunded", "lead.created", "review.submitted", "review.published", "page.published", "product.created", "product.updated", "product.deleted"];
13
13
  export type ChannelWebhookEventType = (typeof CHANNEL_WEBHOOK_EVENT_TYPES)[number];
14
14
  export interface OrderEventData {
15
15
  order_id: string;
@@ -35,18 +35,46 @@ export interface ReviewSubmittedEventData {
35
35
  source: string;
36
36
  submitted_at: string;
37
37
  }
38
+ /**
39
+ * Fired when a review clears moderation. Unlike `review.submitted` this one
40
+ * carries the review id — it is the event a reviews page revalidates on.
41
+ */
42
+ export interface ReviewPublishedEventData {
43
+ review_id: string;
44
+ rating: number;
45
+ source: string;
46
+ published_at?: string;
47
+ }
38
48
  export interface PagePublishedEventData {
39
49
  page_id: string;
40
50
  route_pattern: string;
41
51
  title: string;
42
52
  published_at?: string;
43
53
  }
54
+ /**
55
+ * The catalog-change signal. Thin by design: `slug` locates the cached product
56
+ * page, `status` says whether it is still publicly visible. Fetch price and
57
+ * stock back through the channel client — a webhook body is a cache-busting
58
+ * signal, not a data feed.
59
+ */
60
+ export interface ProductEventData {
61
+ product_id: string;
62
+ slug?: string;
63
+ status?: string;
64
+ }
44
65
  export interface ChannelWebhookEventDataMap {
45
66
  "order.created": OrderEventData;
46
67
  "order.paid": OrderEventData;
68
+ "order.updated": OrderEventData;
69
+ "order.cancelled": OrderEventData;
70
+ "order.refunded": OrderEventData;
47
71
  "lead.created": LeadCreatedEventData;
48
72
  "review.submitted": ReviewSubmittedEventData;
73
+ "review.published": ReviewPublishedEventData;
49
74
  "page.published": PagePublishedEventData;
75
+ "product.created": ProductEventData;
76
+ "product.updated": ProductEventData;
77
+ "product.deleted": ProductEventData;
50
78
  }
51
79
  export interface ChannelWebhookEvent<T extends ChannelWebhookEventType = ChannelWebhookEventType> {
52
80
  /** The originating event id. Delivery is AT-LEAST-ONCE — use this to dedupe. */
@@ -62,7 +90,19 @@ export interface ChannelWebhookEvent<T extends ChannelWebhookEventType = Channel
62
90
  export type AnyChannelWebhookEvent = {
63
91
  [T in ChannelWebhookEventType]: ChannelWebhookEvent<T>;
64
92
  }[ChannelWebhookEventType];
93
+ /** A valid signed envelope for an event introduced by a newer API version. */
94
+ export interface UnknownChannelWebhookEvent {
95
+ id: string;
96
+ type: string;
97
+ api_version: string;
98
+ occurred_at: string;
99
+ workspace_id: string;
100
+ channel_id?: string;
101
+ data: unknown;
102
+ }
103
+ export type ParsedChannelWebhookEvent = AnyChannelWebhookEvent | UnknownChannelWebhookEvent;
65
104
  export declare function isChannelWebhookEventType(value: string): value is ChannelWebhookEventType;
105
+ export declare function isKnownChannelWebhookEvent(event: ParsedChannelWebhookEvent): event is AnyChannelWebhookEvent;
66
106
  export type ChannelWebhookVerificationCode = "missing_signature" | "missing_timestamp" | "invalid_timestamp" | "timestamp_out_of_tolerance" | "invalid_signature" | "invalid_payload";
67
107
  export declare class ChannelWebhookVerificationError extends Error {
68
108
  readonly code: ChannelWebhookVerificationCode;
@@ -126,4 +166,4 @@ export interface ParseChannelWebhookEventOptions {
126
166
  *
127
167
  * @throws {ChannelWebhookVerificationError} if the request is not authentic.
128
168
  */
129
- export declare function parseChannelWebhookEvent(request: Request, options: ParseChannelWebhookEventOptions): Promise<AnyChannelWebhookEvent>;
169
+ export declare function parseChannelWebhookEvent(request: Request, options: ParseChannelWebhookEventOptions): Promise<ParsedChannelWebhookEvent>;
package/dist/webhooks.js CHANGED
@@ -12,13 +12,23 @@
12
12
  export const CHANNEL_WEBHOOK_EVENT_TYPES = [
13
13
  "order.created",
14
14
  "order.paid",
15
+ "order.updated",
16
+ "order.cancelled",
17
+ "order.refunded",
15
18
  "lead.created",
16
19
  "review.submitted",
20
+ "review.published",
17
21
  "page.published",
22
+ "product.created",
23
+ "product.updated",
24
+ "product.deleted",
18
25
  ];
19
26
  export function isChannelWebhookEventType(value) {
20
27
  return CHANNEL_WEBHOOK_EVENT_TYPES.includes(value);
21
28
  }
29
+ export function isKnownChannelWebhookEvent(event) {
30
+ return isChannelWebhookEventType(event.type);
31
+ }
22
32
  export class ChannelWebhookVerificationError extends Error {
23
33
  code;
24
34
  constructor(message, code) {
@@ -50,7 +60,7 @@ function timingSafeEqual(a, b) {
50
60
  return diff === 0;
51
61
  }
52
62
  function decodeHex(value) {
53
- if (value.length === 0 || value.length % 2 !== 0)
63
+ if (value.length === 0 || value.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(value))
54
64
  return null;
55
65
  const out = new Uint8Array(value.length / 2);
56
66
  for (let i = 0; i < out.length; i += 1) {
@@ -150,8 +160,57 @@ export async function parseChannelWebhookEvent(request, options) {
150
160
  catch {
151
161
  throw new ChannelWebhookVerificationError("body is not valid JSON", "invalid_payload");
152
162
  }
153
- if (!event || typeof event.id !== "string" || typeof event.type !== "string") {
163
+ if (!isEventEnvelope(event)) {
154
164
  throw new ChannelWebhookVerificationError("body is not a channel event", "invalid_payload");
155
165
  }
166
+ if (!isChannelWebhookEventType(event.type))
167
+ return event;
168
+ if (!isKnownEventData(event.type, event.data)) {
169
+ throw new ChannelWebhookVerificationError("body contains invalid event data", "invalid_payload");
170
+ }
156
171
  return event;
157
172
  }
173
+ function isRecord(value) {
174
+ return typeof value === "object" && value !== null && !Array.isArray(value);
175
+ }
176
+ function isEventEnvelope(value) {
177
+ if (!isRecord(value) || !isRecord(value.data))
178
+ return false;
179
+ for (const key of ["id", "type", "api_version", "occurred_at", "workspace_id"]) {
180
+ if (typeof value[key] !== "string" || value[key].trim() === "")
181
+ return false;
182
+ }
183
+ return value.channel_id === undefined || typeof value.channel_id === "string";
184
+ }
185
+ function hasStrings(data, keys) {
186
+ return keys.every((key) => typeof data[key] === "string");
187
+ }
188
+ function isKnownEventData(type, value) {
189
+ if (!isRecord(value))
190
+ return false;
191
+ switch (type) {
192
+ case "order.created":
193
+ case "order.paid":
194
+ case "order.updated":
195
+ case "order.cancelled":
196
+ case "order.refunded":
197
+ return hasStrings(value, ["order_id", "order_number", "status", "payment_status", "currency", "created_at"]) &&
198
+ typeof value.total_cents === "number";
199
+ case "lead.created":
200
+ return hasStrings(value, ["lead_id", "source", "created_at"]);
201
+ case "review.submitted":
202
+ return hasStrings(value, ["source", "submitted_at"]) && typeof value.rating === "number";
203
+ case "review.published":
204
+ return hasStrings(value, ["review_id", "source"]) && typeof value.rating === "number" &&
205
+ (value.published_at === undefined || typeof value.published_at === "string");
206
+ case "page.published":
207
+ return hasStrings(value, ["page_id", "route_pattern", "title"]) &&
208
+ (value.published_at === undefined || typeof value.published_at === "string");
209
+ case "product.created":
210
+ case "product.updated":
211
+ case "product.deleted":
212
+ return typeof value.product_id === "string" &&
213
+ (value.slug === undefined || typeof value.slug === "string") &&
214
+ (value.status === undefined || typeof value.status === "string");
215
+ }
216
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Typed server-side client for the MML headless Channel API",