@c1m-public/channel-client 0.12.0 → 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 +24 -8
- package/dist/dash-next.d.ts +11 -0
- package/dist/dash-next.js +12 -0
- package/dist/dash.d.ts +23 -0
- package/dist/dash.js +16 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +19 -0
- package/dist/index.d.ts +16 -3
- package/dist/index.js +23 -12
- package/dist/next-webhooks.js +8 -11
- package/dist/next.d.ts +15 -1
- package/dist/next.js +26 -4
- package/dist/types.d.ts +54 -0
- package/dist/webhooks.d.ts +6 -0
- package/dist/webhooks.js +13 -1
- package/package.json +17 -9
package/README.md
CHANGED
|
@@ -200,6 +200,10 @@ Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
|
|
|
200
200
|
packs, and publishes without a stored npm token. Published versions are
|
|
201
201
|
immutable, so increment the package version for every release.
|
|
202
202
|
|
|
203
|
+
The release workflow also accepts a manual dispatch with an existing release
|
|
204
|
+
tag. This is only a safe retry mechanism: it checks out that immutable tag and
|
|
205
|
+
verifies the package version before publishing.
|
|
206
|
+
|
|
203
207
|
## The `/next` kits
|
|
204
208
|
|
|
205
209
|
The ~600 lines of plumbing every headless site was copy-pasting, shipped once.
|
|
@@ -219,20 +223,32 @@ export const POST = createChannelWebhookRoute({
|
|
|
219
223
|
|
|
220
224
|
Out of the box that route keeps your cache honest with no configuration:
|
|
221
225
|
`page.published` revalidates the published path plus `CHANNEL_SITE_CACHE_TAG`,
|
|
222
|
-
and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`.
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
+
and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`. Since
|
|
227
|
+
0.14.0 the Next adapter files reads under those tags for you: product,
|
|
228
|
+
category, collection and brand reads carry `channel:catalog`, every other
|
|
229
|
+
anonymous read carries `channel:site` — so a merchant's price edit reaches the
|
|
230
|
+
storefront on the next request instead of at the end of a TTL. Pass
|
|
231
|
+
`cache.tags` to add your own on top, or `cache.tagsFor(pathname)` to replace
|
|
232
|
+
the classifier (`defaultChannelCacheTags` is exported to compose with).
|
|
226
233
|
|
|
227
234
|
```ts
|
|
228
|
-
|
|
229
|
-
const catalog = createNextChannelClient({
|
|
235
|
+
const channel = createNextChannelClient({
|
|
230
236
|
token: process.env.C1M_CHANNEL_TOKEN!,
|
|
231
|
-
cache: { revalidate: 3600, tags
|
|
237
|
+
cache: { revalidate: 3600 }, // products.list() → tags ["channel:catalog"]
|
|
232
238
|
});
|
|
233
|
-
const products = await catalog.products.list();
|
|
234
239
|
```
|
|
235
240
|
|
|
241
|
+
### One-call bootstrap
|
|
242
|
+
|
|
243
|
+
`init.light()` is the shell payload: identity, branding, features,
|
|
244
|
+
`preferences{currency,locale,timezone}`, `seo{title,description}` and
|
|
245
|
+
`site{url,source,channel_id}` — the workspace's public origin resolved
|
|
246
|
+
server-side (verified hostname › channel site URL › managed host). Use
|
|
247
|
+
`site.url` for `metadataBase`, canonical/OG URLs, robots and sitemaps instead
|
|
248
|
+
of a hardcoded base URL. Navigation (`menus.get`) and theme (`theme.get`) stay
|
|
249
|
+
separate, parallel reads. `dash.init()` is the same shape for dash sites
|
|
250
|
+
(`branding`, `locale`, `seo`, `site`).
|
|
251
|
+
|
|
236
252
|
The core also exposes the complete current channel door: public category,
|
|
237
253
|
collection and brand navigation; published blog and giving reads; cart and
|
|
238
254
|
checkout; Quick Print settings, quotes and multipart intake; assembled dining
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { type DashChannelClient } from "./dash.js";
|
|
3
|
+
import { type CreateNextChannelClientOptions } from "./next.js";
|
|
4
|
+
/**
|
|
5
|
+
* Dash-scoped client with Next.js Data Cache semantics — the factory a
|
|
6
|
+
* dash-site base should use. Anonymous dash GETs may receive `next.revalidate`;
|
|
7
|
+
* visitor-signed calls (geo, lead capture) should go through a `no-store`
|
|
8
|
+
* client so per-visitor answers are never cached under a shared tag.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createNextDashChannelClient(options: CreateNextChannelClientOptions): DashChannelClient;
|
|
11
|
+
export type { DashChannelClient } from "./dash.js";
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { narrowToDash } from "./dash.js";
|
|
3
|
+
import { createNextChannelClient } from "./next.js";
|
|
4
|
+
/**
|
|
5
|
+
* Dash-scoped client with Next.js Data Cache semantics — the factory a
|
|
6
|
+
* dash-site base should use. Anonymous dash GETs may receive `next.revalidate`;
|
|
7
|
+
* visitor-signed calls (geo, lead capture) should go through a `no-store`
|
|
8
|
+
* client so per-visitor answers are never cached under a shared tag.
|
|
9
|
+
*/
|
|
10
|
+
export function createNextDashChannelClient(options) {
|
|
11
|
+
return narrowToDash(createNextChannelClient(options));
|
|
12
|
+
}
|
package/dist/dash.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient, type ChannelVisitor, type CreateChannelClientOptions } from "./index.js";
|
|
3
|
+
/**
|
|
4
|
+
* The dash-scoped surface of the Channel API: what a dash marketing site
|
|
5
|
+
* (localprint.app, greatremovals…) is allowed to call. It is a TYPE PROJECTION
|
|
6
|
+
* of the full client — same transport, same retries, same visitor signing,
|
|
7
|
+
* same release train — narrowed so dash-site code cannot express a workspace
|
|
8
|
+
* call (cart, checkout, account, products…). The server enforces scope on
|
|
9
|
+
* every request regardless (a dash token gets a uniform 404 on the workspace
|
|
10
|
+
* surface); this narrows the *authoring* surface so the mistake never compiles.
|
|
11
|
+
*
|
|
12
|
+
* `ping` and `geo` are deliberately included: both are scope-agnostic on the
|
|
13
|
+
* door (the credential self-check must answer for either scope, and geo lets
|
|
14
|
+
* a dash site localise pricing).
|
|
15
|
+
*/
|
|
16
|
+
export type DashChannelClient = Pick<ReturnType<typeof createChannelClient>, "ping" | "geo" | "dash" | "assetUrl"> & {
|
|
17
|
+
/** Request-scoped clone carrying signed visitor metadata (see ChannelVisitor). */
|
|
18
|
+
withVisitor(visitor: ChannelVisitor): DashChannelClient;
|
|
19
|
+
};
|
|
20
|
+
declare function narrow(client: ReturnType<typeof createChannelClient>): DashChannelClient;
|
|
21
|
+
/** Dash-scoped client over plain fetch (no framework cache semantics). */
|
|
22
|
+
export declare function createDashChannelClient(options: CreateChannelClientOptions): DashChannelClient;
|
|
23
|
+
export { narrow as narrowToDash };
|
package/dist/dash.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient } from "./index.js";
|
|
3
|
+
function narrow(client) {
|
|
4
|
+
return {
|
|
5
|
+
ping: client.ping,
|
|
6
|
+
geo: client.geo,
|
|
7
|
+
dash: client.dash,
|
|
8
|
+
assetUrl: client.assetUrl,
|
|
9
|
+
withVisitor: (visitor) => narrow(client.withVisitor(visitor)),
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** Dash-scoped client over plain fetch (no framework cache semantics). */
|
|
13
|
+
export function createDashChannelClient(options) {
|
|
14
|
+
return narrow(createChannelClient(options));
|
|
15
|
+
}
|
|
16
|
+
export { narrow as narrowToDash };
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ChannelConfigurationError is thrown for a misconfigured client — missing or
|
|
3
|
+
* malformed token, invalid retry/timeout/cache options, missing fetch, missing
|
|
4
|
+
* webhook secret — as opposed to ChannelAPIError, which describes what the
|
|
5
|
+
* network or the API did. Callers can branch on this without string-matching
|
|
6
|
+
* messages; both starters previously invented a local equivalent.
|
|
7
|
+
*/
|
|
8
|
+
export declare class ChannelConfigurationError extends Error {
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
|
11
|
+
/** Works across duplicate package instances and transformed test bundles. */
|
|
12
|
+
export declare function isChannelConfigurationError(error: unknown): error is ChannelConfigurationError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ChannelConfigurationError is thrown for a misconfigured client — missing or
|
|
3
|
+
* malformed token, invalid retry/timeout/cache options, missing fetch, missing
|
|
4
|
+
* webhook secret — as opposed to ChannelAPIError, which describes what the
|
|
5
|
+
* network or the API did. Callers can branch on this without string-matching
|
|
6
|
+
* messages; both starters previously invented a local equivalent.
|
|
7
|
+
*/
|
|
8
|
+
export class ChannelConfigurationError extends Error {
|
|
9
|
+
constructor(message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "ChannelConfigurationError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Works across duplicate package instances and transformed test bundles. */
|
|
15
|
+
export function isChannelConfigurationError(error) {
|
|
16
|
+
return (error instanceof ChannelConfigurationError ||
|
|
17
|
+
(typeof error === "object" && error !== null &&
|
|
18
|
+
error.name === "ChannelConfigurationError"));
|
|
19
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import "server-only";
|
|
1
2
|
export * from "./webhooks.js";
|
|
3
|
+
export * from "./errors.js";
|
|
2
4
|
export type * from "./types.js";
|
|
3
5
|
import type { CatalogBrand, CatalogCategory, CatalogCollection, CatalogProductsResponse, BlogPostResponse, DiningMenu, DashDirectoryEntry, DashDirectoryProfileResponse, DashDirectoryRegion, DashInitResponse, DashLead, DashPlansResponse, DashProfileResponse, GivingEntry, GivingIntentListResponse, AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, ChannelPing, CustomerResponse, CustomerAuthSession, CustomerSecurityActivityPage, ChannelGeo, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, MergeCartInput, SendCodeResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SavedAddress, SavedAddressDefaultKind, SavedAddressInput, SavedAddressResponse, SavedAddressUpdateInput, SavedPaymentMethod, SiteDocument, StartGivingInput, StartGivingResponse, PaymentMethodConfirmInput, PaymentMethodMutationResponse, PaymentMethodSetupInput, PaymentMethodSetupResult, SubscriptionAgreementResponse, SubscriptionInvoiceListResponse, SubscriptionInvoiceResponse, SubscriptionListResponse, SubscriptionSourceResponse, ThemeResponse, UpdateCartItemInput } from "./types.js";
|
|
4
6
|
export declare const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
|
|
@@ -11,7 +13,19 @@ export interface CreateChannelClientOptions {
|
|
|
11
13
|
baseUrl?: string;
|
|
12
14
|
token: string;
|
|
13
15
|
fetch?: typeof globalThis.fetch;
|
|
16
|
+
/**
|
|
17
|
+
* Per-ATTEMPT timeout (default 10 000 ms), not a whole-call budget: with
|
|
18
|
+
* `retry.attempts` retries the worst-case wall clock is roughly
|
|
19
|
+
* `(attempts + 1) × timeoutMs` plus backoff. Pass `signal` to bound the
|
|
20
|
+
* whole call to the caller's own deadline.
|
|
21
|
+
*/
|
|
14
22
|
timeoutMs?: number;
|
|
23
|
+
/**
|
|
24
|
+
* GET-only retries on 429/502/503/504 and network errors (mutations are
|
|
25
|
+
* retried only by the caller, under an Idempotency-Key). Backoff honours
|
|
26
|
+
* Retry-After when present; otherwise it grows exponentially from 250 ms
|
|
27
|
+
* with jitter, capped at `maxDelayMs` (default 2 000).
|
|
28
|
+
*/
|
|
15
29
|
retry?: ChannelRetryPolicy | false;
|
|
16
30
|
observe?: ChannelRequestObserver;
|
|
17
31
|
/** Optional request-scope cancellation signal, combined with the timeout. */
|
|
@@ -79,8 +93,7 @@ export interface ChannelSubscriptionListParams extends ChannelListParams {
|
|
|
79
93
|
export interface ChannelSubscriptionCancelParams {
|
|
80
94
|
immediate?: boolean;
|
|
81
95
|
}
|
|
82
|
-
export interface ChannelInvoiceListParams {
|
|
83
|
-
limit?: number;
|
|
96
|
+
export interface ChannelInvoiceListParams extends ChannelListParams {
|
|
84
97
|
}
|
|
85
98
|
export declare class ChannelAPIError extends Error {
|
|
86
99
|
readonly status: number;
|
|
@@ -200,7 +213,7 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
|
|
|
200
213
|
};
|
|
201
214
|
readonly print: {
|
|
202
215
|
readonly settings: () => Promise<PrintSettingsResponse>;
|
|
203
|
-
readonly quote: (input: PrintOptionsSelection) => Promise<PrintQuoteResponse>;
|
|
216
|
+
readonly quote: (input: PrintOptionsSelection, mutation?: ChannelMutationOptions) => Promise<PrintQuoteResponse>;
|
|
204
217
|
readonly intake: (input: PrintIntakeInput, mutation?: ChannelMutationOptions) => Promise<{
|
|
205
218
|
job: PrintJob;
|
|
206
219
|
}>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import "server-only";
|
|
1
2
|
export * from "./webhooks.js";
|
|
3
|
+
export * from "./errors.js";
|
|
4
|
+
import { ChannelConfigurationError } from "./errors.js";
|
|
2
5
|
const CHANNEL_TOKEN_PREFIX = "sk_chan_";
|
|
3
6
|
export const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
|
|
4
7
|
const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
|
|
@@ -26,12 +29,12 @@ export function isChannelAPIError(error) {
|
|
|
26
29
|
function required(value, label) {
|
|
27
30
|
const normalized = value.trim();
|
|
28
31
|
if (!normalized)
|
|
29
|
-
throw new
|
|
32
|
+
throw new ChannelConfigurationError(`${label} is required`);
|
|
30
33
|
return normalized;
|
|
31
34
|
}
|
|
32
35
|
function positiveNumber(value, label) {
|
|
33
36
|
if (!Number.isFinite(value) || value <= 0)
|
|
34
|
-
throw new
|
|
37
|
+
throw new ChannelConfigurationError(`${label} must be a positive finite number`);
|
|
35
38
|
return value;
|
|
36
39
|
}
|
|
37
40
|
function encodePath(value) {
|
|
@@ -46,15 +49,23 @@ function appendQuery(path, values) {
|
|
|
46
49
|
const encoded = query.toString();
|
|
47
50
|
return encoded ? `${path}?${encoded}` : path;
|
|
48
51
|
}
|
|
49
|
-
|
|
52
|
+
// backoffDelay is the no-Retry-After default: exponential from 250 ms with
|
|
53
|
+
// full jitter, capped. A flat 250 ms with no jitter (the previous behaviour)
|
|
54
|
+
// turns `attempts: 5` on a 429 into five requests a quarter-second apart into
|
|
55
|
+
// the very limiter that just refused you — a thundering herd in miniature.
|
|
56
|
+
function backoffDelay(attempt, maxDelayMs) {
|
|
57
|
+
const base = Math.min(250 * 2 ** Math.max(attempt, 0), maxDelayMs);
|
|
58
|
+
return Math.floor(Math.random() * base);
|
|
59
|
+
}
|
|
60
|
+
function retryDelay(response, attempt, maxDelayMs) {
|
|
50
61
|
const value = response.headers.get("Retry-After");
|
|
51
62
|
if (!value)
|
|
52
|
-
return
|
|
63
|
+
return backoffDelay(attempt, maxDelayMs);
|
|
53
64
|
const seconds = Number(value);
|
|
54
65
|
if (Number.isFinite(seconds))
|
|
55
66
|
return Math.min(Math.max(seconds * 1_000, 0), maxDelayMs);
|
|
56
67
|
const date = Date.parse(value);
|
|
57
|
-
return Number.isNaN(date) ?
|
|
68
|
+
return Number.isNaN(date) ? backoffDelay(attempt, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
|
|
58
69
|
}
|
|
59
70
|
function wait(ms) {
|
|
60
71
|
return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -99,14 +110,14 @@ export function createChannelClient(options) {
|
|
|
99
110
|
: required(options.baseUrl, "baseUrl")).replace(/\/+$/, "");
|
|
100
111
|
const token = required(options.token, "token");
|
|
101
112
|
if (!token.startsWith(CHANNEL_TOKEN_PREFIX))
|
|
102
|
-
throw new
|
|
113
|
+
throw new ChannelConfigurationError("token must start with sk_chan_");
|
|
103
114
|
const fetcher = options.fetch ?? globalThis.fetch;
|
|
104
115
|
if (!fetcher)
|
|
105
|
-
throw new
|
|
116
|
+
throw new ChannelConfigurationError("fetch implementation is required");
|
|
106
117
|
const timeoutMs = positiveNumber(options.timeoutMs ?? 10_000, "timeoutMs");
|
|
107
118
|
const configuredRetryAttempts = options.retry === false ? 0 : options.retry?.attempts ?? 1;
|
|
108
119
|
if (!Number.isSafeInteger(configuredRetryAttempts) || configuredRetryAttempts < 0) {
|
|
109
|
-
throw new
|
|
120
|
+
throw new ChannelConfigurationError("retry.attempts must be a non-negative safe integer");
|
|
110
121
|
}
|
|
111
122
|
const retryAttempts = configuredRetryAttempts;
|
|
112
123
|
const maxRetryDelayMs = positiveNumber(options.retry === false ? 2_000 : options.retry?.maxDelayMs ?? 2_000, "retry.maxDelayMs");
|
|
@@ -162,7 +173,7 @@ export function createChannelClient(options) {
|
|
|
162
173
|
}
|
|
163
174
|
outcome = "network_error";
|
|
164
175
|
if (method === "GET" && attempt < retryAttempts) {
|
|
165
|
-
await wait(
|
|
176
|
+
await wait(backoffDelay(attempt, maxRetryDelayMs));
|
|
166
177
|
continue;
|
|
167
178
|
}
|
|
168
179
|
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
@@ -172,7 +183,7 @@ export function createChannelClient(options) {
|
|
|
172
183
|
}
|
|
173
184
|
if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
|
|
174
185
|
break;
|
|
175
|
-
await wait(retryDelay(response, maxRetryDelayMs));
|
|
186
|
+
await wait(retryDelay(response, attempt, maxRetryDelayMs));
|
|
176
187
|
}
|
|
177
188
|
if (!response)
|
|
178
189
|
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
@@ -347,8 +358,8 @@ export function createChannelClient(options) {
|
|
|
347
358
|
},
|
|
348
359
|
print: {
|
|
349
360
|
settings: () => request("channel.print.settings", "/print/settings"),
|
|
350
|
-
quote: (input) => request("channel.print.quote", "/print/quote", {
|
|
351
|
-
method: "POST", body: JSON.stringify(input),
|
|
361
|
+
quote: (input, mutation) => request("channel.print.quote", "/print/quote", {
|
|
362
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
352
363
|
}),
|
|
353
364
|
intake: (input, mutation) => {
|
|
354
365
|
const form = new FormData();
|
package/dist/next-webhooks.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "server-only";
|
|
2
|
-
import {
|
|
2
|
+
import { isChannelWebhookVerificationError, 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
|
*
|
|
@@ -33,13 +33,8 @@ export function safePublishedPath(path) {
|
|
|
33
33
|
}
|
|
34
34
|
return normalized;
|
|
35
35
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
if (error instanceof ChannelWebhookVerificationError)
|
|
39
|
-
return true;
|
|
40
|
-
return (typeof error === "object" && error !== null &&
|
|
41
|
-
error.name === "ChannelWebhookVerificationError" &&
|
|
42
|
-
typeof error.code === "string");
|
|
36
|
+
function errorMessage(error) {
|
|
37
|
+
return error instanceof Error ? error.message : String(error);
|
|
43
38
|
}
|
|
44
39
|
function defaultBehavior(event, invalidate) {
|
|
45
40
|
if (event.type === "page.published") {
|
|
@@ -70,13 +65,15 @@ export function createChannelWebhookRoute(options) {
|
|
|
70
65
|
event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
|
|
71
66
|
}
|
|
72
67
|
catch (error) {
|
|
73
|
-
if (
|
|
68
|
+
if (isChannelWebhookVerificationError(error)) {
|
|
74
69
|
// An unverifiable request is noise or an attack; log the code, say
|
|
75
70
|
// nothing useful back.
|
|
76
71
|
logger.warn("channel_webhook_rejected", { code: error.code });
|
|
77
72
|
return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
|
|
78
73
|
}
|
|
79
|
-
|
|
74
|
+
// Log a message, never the raw error object: a thrown value could carry
|
|
75
|
+
// configuration (a secret in a message string) into the log verbatim.
|
|
76
|
+
logger.error("channel_webhook_failed", { message: errorMessage(error) });
|
|
80
77
|
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
81
78
|
}
|
|
82
79
|
try {
|
|
@@ -105,7 +102,7 @@ export function createChannelWebhookRoute(options) {
|
|
|
105
102
|
// A 500 makes the server retry on its ladder — which is what you want
|
|
106
103
|
// when the failure is transient, and visible in delivery history when
|
|
107
104
|
// it is not.
|
|
108
|
-
logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, error });
|
|
105
|
+
logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, message: errorMessage(error) });
|
|
109
106
|
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
110
107
|
}
|
|
111
108
|
};
|
package/dist/next.d.ts
CHANGED
|
@@ -1,13 +1,27 @@
|
|
|
1
1
|
import "server-only";
|
|
2
2
|
import { type CreateChannelClientOptions } from "./index.js";
|
|
3
|
+
/**
|
|
4
|
+
* Cache policy for anonymous GETs. `tags` are applied to every cached read;
|
|
5
|
+
* `tagsFor` (or the default classifier) adds per-request tags so a webhook
|
|
6
|
+
* can bust one family of reads without the whole site: catalog reads carry
|
|
7
|
+
* `channel:catalog` (busted by `product.*` events), everything else carries
|
|
8
|
+
* `channel:site` (busted by `page.published`). Without this the kit's default
|
|
9
|
+
* `product.*` handler invalidates a tag no fetch carries.
|
|
10
|
+
*/
|
|
3
11
|
export type NextChannelCachePolicy = "no-store" | {
|
|
4
12
|
revalidate: number;
|
|
5
13
|
tags?: string[];
|
|
14
|
+
tagsFor?: (pathname: string) => string[];
|
|
6
15
|
};
|
|
7
16
|
export interface CreateNextChannelClientOptions extends Omit<CreateChannelClientOptions, "fetch"> {
|
|
8
17
|
fetch?: typeof globalThis.fetch;
|
|
9
18
|
cache?: NextChannelCachePolicy;
|
|
10
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Default classifier: catalog reads → `channel:catalog`, all other anonymous
|
|
22
|
+
* reads → `channel:site`. Exported so a site can compose it with its own tags.
|
|
23
|
+
*/
|
|
24
|
+
export declare function defaultChannelCacheTags(pathname: string): string[];
|
|
11
25
|
/**
|
|
12
26
|
* Build the Channel API client with Next.js Data Cache semantics.
|
|
13
27
|
*
|
|
@@ -113,7 +127,7 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
|
|
|
113
127
|
};
|
|
114
128
|
readonly print: {
|
|
115
129
|
readonly settings: () => Promise<import("./types.js").PrintSettingsResponse>;
|
|
116
|
-
readonly quote: (input: import("./types.js").PrintOptionsSelection) => Promise<import("./types.js").PrintQuoteResponse>;
|
|
130
|
+
readonly quote: (input: import("./types.js").PrintOptionsSelection, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").PrintQuoteResponse>;
|
|
117
131
|
readonly intake: (input: import("./types.js").PrintIntakeInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
|
|
118
132
|
job: import("./types.js").PrintJob;
|
|
119
133
|
}>;
|
package/dist/next.js
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
import "server-only";
|
|
2
|
-
import { createChannelClient } from "./index.js";
|
|
2
|
+
import { ChannelConfigurationError, createChannelClient } from "./index.js";
|
|
3
|
+
/** Cache tags — mirrored from next-webhooks so the two files agree by name. */
|
|
4
|
+
const SITE_TAG = "channel:site";
|
|
5
|
+
const CATALOG_TAG = "channel:catalog";
|
|
6
|
+
const CATALOG_PATH = /^\/api\/v1\/channel\/(products|categories|collections|brands)(\/|$|\?)/;
|
|
7
|
+
/**
|
|
8
|
+
* Default classifier: catalog reads → `channel:catalog`, all other anonymous
|
|
9
|
+
* reads → `channel:site`. Exported so a site can compose it with its own tags.
|
|
10
|
+
*/
|
|
11
|
+
export function defaultChannelCacheTags(pathname) {
|
|
12
|
+
return CATALOG_PATH.test(pathname) ? [CATALOG_TAG] : [SITE_TAG];
|
|
13
|
+
}
|
|
14
|
+
function pathnameOf(input) {
|
|
15
|
+
try {
|
|
16
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
17
|
+
return new URL(url, "http://placeholder.invalid").pathname;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return "";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
3
23
|
function validateCachePolicy(policy) {
|
|
4
24
|
if (policy === "no-store")
|
|
5
25
|
return;
|
|
6
26
|
if (!Number.isFinite(policy.revalidate) || policy.revalidate < 0) {
|
|
7
|
-
throw new
|
|
27
|
+
throw new ChannelConfigurationError("cache.revalidate must be a non-negative finite number");
|
|
8
28
|
}
|
|
9
29
|
}
|
|
10
30
|
/**
|
|
@@ -18,16 +38,18 @@ export function createNextChannelClient(options) {
|
|
|
18
38
|
validateCachePolicy(cache);
|
|
19
39
|
const fetcher = suppliedFetch ?? globalThis.fetch;
|
|
20
40
|
if (!fetcher)
|
|
21
|
-
throw new
|
|
41
|
+
throw new ChannelConfigurationError("fetch implementation is required");
|
|
22
42
|
const nextFetch = (input, init = {}) => {
|
|
23
43
|
const request = { ...init };
|
|
24
44
|
const method = (request.method ?? "GET").toUpperCase();
|
|
25
45
|
const customerScoped = new Headers(request.headers).has("X-End-User-Token");
|
|
26
46
|
if (method === "GET" && !customerScoped && cache !== "no-store") {
|
|
27
47
|
delete request.cache;
|
|
48
|
+
const classify = cache.tagsFor ?? defaultChannelCacheTags;
|
|
49
|
+
const tags = Array.from(new Set([...(cache.tags ?? []), ...classify(pathnameOf(input))]));
|
|
28
50
|
request.next = {
|
|
29
51
|
revalidate: cache.revalidate,
|
|
30
|
-
...(
|
|
52
|
+
...(tags.length ? { tags } : {}),
|
|
31
53
|
};
|
|
32
54
|
}
|
|
33
55
|
else {
|
package/dist/types.d.ts
CHANGED
|
@@ -29,15 +29,44 @@ export interface PublicWorkspaceInit {
|
|
|
29
29
|
max_age?: number;
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* The public origin of a dash or workspace, resolved server-side once:
|
|
34
|
+
* verified hostname (external → the channel bound to it) > active channel
|
|
35
|
+
* site_url > hosted managed host. Use it for `metadataBase`, canonical/OG
|
|
36
|
+
* URLs, robots and sitemaps instead of a hardcoded base URL.
|
|
37
|
+
*/
|
|
38
|
+
export interface SiteRef {
|
|
39
|
+
/** Absolute https origin, no trailing slash. */
|
|
40
|
+
url: string;
|
|
41
|
+
source: "hostname" | "channel" | "hosted";
|
|
42
|
+
/** The external channel that renders the site, when one does. */
|
|
43
|
+
channel_id?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The headless bootstrap payload — one cached call carries identity,
|
|
47
|
+
* branding, features, locale, SEO defaults and the public origin. Navigation
|
|
48
|
+
* (`menus.get`) and theme (`theme.get`) stay separate, parallel reads.
|
|
49
|
+
*/
|
|
32
50
|
export interface LightInitResponse {
|
|
33
51
|
workspace_id: string;
|
|
34
52
|
workspace_name: string;
|
|
53
|
+
workspace_slug?: string;
|
|
35
54
|
primary_color: string;
|
|
36
55
|
logo_url?: string;
|
|
37
56
|
logo_light_url?: string;
|
|
38
57
|
logo_dark_url?: string;
|
|
39
58
|
logo_square_url?: string;
|
|
40
59
|
enabled_features: string[];
|
|
60
|
+
preferences?: {
|
|
61
|
+
currency?: string;
|
|
62
|
+
locale?: string;
|
|
63
|
+
timezone?: string;
|
|
64
|
+
};
|
|
65
|
+
site?: SiteRef;
|
|
66
|
+
seo?: {
|
|
67
|
+
title?: string;
|
|
68
|
+
description?: string;
|
|
69
|
+
};
|
|
41
70
|
etag?: string;
|
|
42
71
|
}
|
|
43
72
|
export interface DashTenantInfo {
|
|
@@ -56,9 +85,34 @@ export interface DashPublicProfileInfo {
|
|
|
56
85
|
header_media_url?: string;
|
|
57
86
|
pricing_summary?: string;
|
|
58
87
|
}
|
|
88
|
+
export interface DashBrandingInfo {
|
|
89
|
+
primary_color?: string;
|
|
90
|
+
logo_url?: string;
|
|
91
|
+
logo_square_url?: string;
|
|
92
|
+
favicon_url?: string;
|
|
93
|
+
cover_url?: string;
|
|
94
|
+
}
|
|
95
|
+
export interface DashLocaleInfo {
|
|
96
|
+
region?: string;
|
|
97
|
+
currency?: string;
|
|
98
|
+
locale?: string;
|
|
99
|
+
timezone?: string;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The dash bootstrap — one call for a marketing site's shell: identity,
|
|
103
|
+
* public profile, branding, locale, SEO defaults and the public origin.
|
|
104
|
+
* `dash.profile()` remains for the full profile page (gallery, about template).
|
|
105
|
+
*/
|
|
59
106
|
export interface DashInitResponse {
|
|
60
107
|
tenant: DashTenantInfo;
|
|
61
108
|
public_profile: DashPublicProfileInfo;
|
|
109
|
+
branding?: DashBrandingInfo;
|
|
110
|
+
locale?: DashLocaleInfo;
|
|
111
|
+
seo?: {
|
|
112
|
+
title?: string;
|
|
113
|
+
description?: string;
|
|
114
|
+
};
|
|
115
|
+
site?: SiteRef;
|
|
62
116
|
}
|
|
63
117
|
export interface DashPublicPage {
|
|
64
118
|
profile: DashPublicProfileInfo & {
|
package/dist/webhooks.d.ts
CHANGED
|
@@ -108,6 +108,12 @@ export declare class ChannelWebhookVerificationError extends Error {
|
|
|
108
108
|
readonly code: ChannelWebhookVerificationCode;
|
|
109
109
|
constructor(message: string, code: ChannelWebhookVerificationCode);
|
|
110
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Structural, not instanceof — works across duplicate package instances and
|
|
113
|
+
* transformed test bundles. Exported so any consumer writing its own route
|
|
114
|
+
* handler can branch on "unverifiable request" without re-deriving this.
|
|
115
|
+
*/
|
|
116
|
+
export declare function isChannelWebhookVerificationError(error: unknown): error is ChannelWebhookVerificationError;
|
|
111
117
|
export declare const CHANNEL_WEBHOOK_SIGNATURE_HEADER = "X-C1M-Signature";
|
|
112
118
|
export declare const CHANNEL_WEBHOOK_TIMESTAMP_HEADER = "X-C1M-Timestamp";
|
|
113
119
|
export declare const CHANNEL_WEBHOOK_EVENT_ID_HEADER = "X-C1M-Event-ID";
|
package/dist/webhooks.js
CHANGED
|
@@ -9,6 +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
|
+
import { ChannelConfigurationError } from "./errors.js";
|
|
12
13
|
export const CHANNEL_WEBHOOK_EVENT_TYPES = [
|
|
13
14
|
"order.created",
|
|
14
15
|
"order.paid",
|
|
@@ -37,6 +38,17 @@ export class ChannelWebhookVerificationError extends Error {
|
|
|
37
38
|
this.name = "ChannelWebhookVerificationError";
|
|
38
39
|
}
|
|
39
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Structural, not instanceof — works across duplicate package instances and
|
|
43
|
+
* transformed test bundles. Exported so any consumer writing its own route
|
|
44
|
+
* handler can branch on "unverifiable request" without re-deriving this.
|
|
45
|
+
*/
|
|
46
|
+
export function isChannelWebhookVerificationError(error) {
|
|
47
|
+
return (error instanceof ChannelWebhookVerificationError ||
|
|
48
|
+
(typeof error === "object" && error !== null &&
|
|
49
|
+
error.name === "ChannelWebhookVerificationError" &&
|
|
50
|
+
typeof error.code === "string"));
|
|
51
|
+
}
|
|
40
52
|
export const CHANNEL_WEBHOOK_SIGNATURE_HEADER = "X-C1M-Signature";
|
|
41
53
|
export const CHANNEL_WEBHOOK_TIMESTAMP_HEADER = "X-C1M-Timestamp";
|
|
42
54
|
export const CHANNEL_WEBHOOK_EVENT_ID_HEADER = "X-C1M-Event-ID";
|
|
@@ -87,7 +99,7 @@ export async function verifyChannelWebhookSignature(options) {
|
|
|
87
99
|
const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
88
100
|
const now = options.now ?? Date.now;
|
|
89
101
|
if (!secret)
|
|
90
|
-
throw new
|
|
102
|
+
throw new ChannelConfigurationError("secret is required");
|
|
91
103
|
if (!signature) {
|
|
92
104
|
throw new ChannelWebhookVerificationError(`missing ${CHANNEL_WEBHOOK_SIGNATURE_HEADER} header`, "missing_signature");
|
|
93
105
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@c1m-public/channel-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Typed server-side client for the MML headless Channel API",
|
|
@@ -31,6 +31,14 @@
|
|
|
31
31
|
"./renderer": {
|
|
32
32
|
"types": "./dist/renderer.d.ts",
|
|
33
33
|
"default": "./dist/renderer.js"
|
|
34
|
+
},
|
|
35
|
+
"./dash": {
|
|
36
|
+
"types": "./dist/dash.d.ts",
|
|
37
|
+
"default": "./dist/dash.js"
|
|
38
|
+
},
|
|
39
|
+
"./dash/next": {
|
|
40
|
+
"types": "./dist/dash-next.d.ts",
|
|
41
|
+
"default": "./dist/dash-next.js"
|
|
34
42
|
}
|
|
35
43
|
},
|
|
36
44
|
"files": [
|
|
@@ -43,6 +51,13 @@
|
|
|
43
51
|
"publishConfig": {
|
|
44
52
|
"access": "public"
|
|
45
53
|
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"server-only": "0.0.1"
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"typescript": "5.9.3",
|
|
59
|
+
"vitest": "^4.1.4"
|
|
60
|
+
},
|
|
46
61
|
"scripts": {
|
|
47
62
|
"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
48
63
|
"build": "pnpm clean && tsc -p tsconfig.build.json",
|
|
@@ -50,12 +65,5 @@
|
|
|
50
65
|
"test": "vitest",
|
|
51
66
|
"test:run": "vitest run",
|
|
52
67
|
"type-check": "tsc -p tsconfig.json --noEmit"
|
|
53
|
-
},
|
|
54
|
-
"dependencies": {
|
|
55
|
-
"server-only": "0.0.1"
|
|
56
|
-
},
|
|
57
|
-
"devDependencies": {
|
|
58
|
-
"typescript": "5.9.3",
|
|
59
|
-
"vitest": "^4.1.4"
|
|
60
68
|
}
|
|
61
|
-
}
|
|
69
|
+
}
|