@c1m-public/channel-client 0.4.0 → 0.6.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 +49 -0
- package/dist/index.d.ts +23 -3
- package/dist/index.js +46 -0
- package/dist/next-cart.d.ts +74 -0
- package/dist/next-cart.js +85 -0
- package/dist/next-session.d.ts +109 -0
- package/dist/next-session.js +197 -0
- package/dist/next-webhooks.d.ts +52 -0
- package/dist/next-webhooks.js +92 -0
- package/dist/next.d.ts +19 -0
- package/dist/next.js +7 -0
- package/dist/types.d.ts +126 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,6 +28,18 @@ const channel = createNextChannelClient({
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
const { page } = await channel.pages.get("home");
|
|
31
|
+
|
|
32
|
+
const { order: cart } = await channel.cart.addItem({ product_id: "product-id", quantity: 1 });
|
|
33
|
+
|
|
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.
|
|
38
|
+
const checkout = await channel.checkout.pay(
|
|
39
|
+
cart.id,
|
|
40
|
+
{ cart_token: cart.cart_token!, return_url: "https://example.com/checkout/complete" },
|
|
41
|
+
{ idempotencyKey: `pay:${cart.id}` },
|
|
42
|
+
);
|
|
31
43
|
```
|
|
32
44
|
|
|
33
45
|
### Other server runtimes
|
|
@@ -53,6 +65,8 @@ other runtimes must enforce their own server-module boundary.
|
|
|
53
65
|
- The Next adapter supports explicit revalidation and tags.
|
|
54
66
|
- Writes are always `no-store`, are never automatically retried, and accept an
|
|
55
67
|
explicit idempotency key.
|
|
68
|
+
- Cart and checkout operations use an opaque `cart_token`; the channel token
|
|
69
|
+
continues to resolve tenant and workspace identity at the API door.
|
|
56
70
|
- Requests time out after 10 seconds by default.
|
|
57
71
|
- API failures throw `ChannelAPIError` with safe status, code, and request ID.
|
|
58
72
|
- Assets remain tokenless and are normalized with `assetUrl()`.
|
|
@@ -104,3 +118,38 @@ Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
|
|
|
104
118
|
`channel-client-vX.Y.Z` tag matching `package.json`; the workflow verifies,
|
|
105
119
|
packs, and publishes without a stored npm token. Published versions are
|
|
106
120
|
immutable, so increment the package version for every release.
|
|
121
|
+
|
|
122
|
+
## The `/next` kits
|
|
123
|
+
|
|
124
|
+
The ~600 lines of plumbing every headless site was copy-pasting, shipped once.
|
|
125
|
+
No `next` imports — apps inject `next/cache` and apply cookies where Next allows
|
|
126
|
+
writes (a Server Component cannot write cookies; proxy.ts and Server Actions can).
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// app/api/webhooks/c1m/route.ts — the whole file
|
|
130
|
+
import { revalidatePath, revalidateTag } from "next/cache";
|
|
131
|
+
import { createChannelWebhookRoute } from "@c1m-public/channel-client/next";
|
|
132
|
+
|
|
133
|
+
export const POST = createChannelWebhookRoute({
|
|
134
|
+
secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
|
|
135
|
+
invalidate: { revalidatePath, revalidateTag },
|
|
136
|
+
});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
// session: cookie codec + the contested-vs-expired refresh decision
|
|
141
|
+
const session = createCustomerSession({ client: getChannelClient });
|
|
142
|
+
const result = await session.refresh(rawCookie); // keep | write | clear
|
|
143
|
+
// `keep` on refresh_contested is the load-bearing case: the customer's other
|
|
144
|
+
// tab already stored a fresh token — clearing would log out a live session.
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// cart: server-side cart, client-held token, hosted checkout
|
|
149
|
+
const cart = createCart({ client: getChannelClient });
|
|
150
|
+
await cart.addItem({ cart_token, product_id, quantity: 1 });
|
|
151
|
+
const { redirect_url } = await cart.checkout.pay(orderId, {
|
|
152
|
+
cart_token,
|
|
153
|
+
return_url: "https://your-site.example/thanks", // must be on the channel's registered site
|
|
154
|
+
});
|
|
155
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export * from "./webhooks.js";
|
|
2
|
-
export type { BlogPost, BlogPostResponse, ChannelPing, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderSummary, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, } from "./types";
|
|
3
|
-
import type { BlogPostResponse, ChannelPing, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
|
|
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";
|
|
4
4
|
export interface ChannelRetryPolicy {
|
|
5
5
|
attempts?: number;
|
|
6
6
|
maxDelayMs?: number;
|
|
@@ -14,7 +14,7 @@ export interface CreateChannelClientOptions {
|
|
|
14
14
|
observe?: ChannelRequestObserver;
|
|
15
15
|
}
|
|
16
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" | "growth.public_workspace.leads.capture.channel";
|
|
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";
|
|
18
18
|
export interface ChannelRequestObservation {
|
|
19
19
|
operation: ChannelOperation;
|
|
20
20
|
method: string;
|
|
@@ -50,6 +50,10 @@ export interface ChannelLeadInput {
|
|
|
50
50
|
export interface ChannelMutationOptions {
|
|
51
51
|
idempotencyKey?: string;
|
|
52
52
|
}
|
|
53
|
+
export interface ChannelCheckoutStatusParams {
|
|
54
|
+
cartToken?: string;
|
|
55
|
+
checkoutSessionId?: string;
|
|
56
|
+
}
|
|
53
57
|
export declare class ChannelAPIError extends Error {
|
|
54
58
|
readonly status: number;
|
|
55
59
|
readonly code: string;
|
|
@@ -88,6 +92,22 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
|
|
|
88
92
|
}>;
|
|
89
93
|
readonly media: (slug: string) => Promise<ListResponse<ProductAsset>>;
|
|
90
94
|
};
|
|
95
|
+
readonly cart: {
|
|
96
|
+
readonly get: (cartToken: string) => Promise<CartResponse>;
|
|
97
|
+
readonly addItem: (input: AddCartItemInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
98
|
+
readonly updateItem: (itemId: string, input: UpdateCartItemInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
99
|
+
readonly removeItem: (itemId: string, cartToken: string, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
100
|
+
readonly clear: (cartToken: string, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
101
|
+
readonly merge: (input: MergeCartInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
102
|
+
};
|
|
103
|
+
readonly checkout: {
|
|
104
|
+
readonly options: (orderId: string, cartToken: string) => Promise<CheckoutOptions>;
|
|
105
|
+
readonly status: (orderId: string, params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
|
|
106
|
+
readonly setCustomer: (orderId: string, input: CheckoutCustomerInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
107
|
+
readonly setAddresses: (orderId: string, input: CheckoutAddressesInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
108
|
+
readonly setFulfillment: (orderId: string, input: CheckoutFulfillmentInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
109
|
+
readonly pay: (orderId: string, input: CheckoutPayInput, mutation?: ChannelMutationOptions) => Promise<CheckoutPayResponse>;
|
|
110
|
+
};
|
|
91
111
|
readonly reviews: {
|
|
92
112
|
readonly list: (params?: ChannelListParams) => Promise<ListResponse<Review>>;
|
|
93
113
|
readonly summary: () => Promise<ReviewSummaryResponse>;
|
package/dist/index.js
CHANGED
|
@@ -173,6 +173,52 @@ export function createChannelClient(options) {
|
|
|
173
173
|
get: (slug) => request("shop.public.products.get.channel", `/products/${encodePath(slug)}`),
|
|
174
174
|
media: (slug) => request("shop.public.products.media.channel", `/products/${encodePath(slug)}/media`),
|
|
175
175
|
},
|
|
176
|
+
cart: {
|
|
177
|
+
get: (cartToken) => request("channel.cart.get", appendQuery("/cart", { cart_token: required(cartToken, "cartToken") })),
|
|
178
|
+
addItem: (input, mutation) => request("channel.cart.items.add", "/cart/items", {
|
|
179
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
180
|
+
}),
|
|
181
|
+
updateItem: (itemId, input, mutation) => request("channel.cart.items.update", `/cart/items/${encodePath(itemId)}`, {
|
|
182
|
+
method: "PATCH", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
183
|
+
}),
|
|
184
|
+
removeItem: (itemId, cartToken, mutation) => request("channel.cart.items.remove", appendQuery(`/cart/items/${encodePath(itemId)}`, {
|
|
185
|
+
cart_token: required(cartToken, "cartToken"),
|
|
186
|
+
}), {
|
|
187
|
+
method: "DELETE", headers: mutationHeaders(mutation),
|
|
188
|
+
}),
|
|
189
|
+
clear: (cartToken, mutation) => request("channel.cart.clear", appendQuery("/cart", { cart_token: required(cartToken, "cartToken") }), {
|
|
190
|
+
method: "DELETE", headers: mutationHeaders(mutation),
|
|
191
|
+
}),
|
|
192
|
+
merge: (input, mutation) => request("channel.cart.merge", "/cart/merge", {
|
|
193
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
194
|
+
}),
|
|
195
|
+
},
|
|
196
|
+
// Checkout is addressed by the ORDER the cart became: the server mounts
|
|
197
|
+
// /checkout/{order_id}/... (the cart is an orders row, and every cart call
|
|
198
|
+
// returns its order.id). 0.5.0 shipped these without the order_id segment,
|
|
199
|
+
// so every checkout call 404'd — the signature change is safe because the
|
|
200
|
+
// old shape never worked.
|
|
201
|
+
checkout: {
|
|
202
|
+
options: (orderId, cartToken) => request("channel.checkout.options", appendQuery(`/checkout/${encodePath(orderId)}/options`, {
|
|
203
|
+
cart_token: required(cartToken, "cartToken"),
|
|
204
|
+
})),
|
|
205
|
+
status: (orderId, params = {}) => request("channel.checkout.status", appendQuery(`/checkout/${encodePath(orderId)}/status`, {
|
|
206
|
+
cart_token: params.cartToken,
|
|
207
|
+
checkout_session_id: params.checkoutSessionId,
|
|
208
|
+
})),
|
|
209
|
+
setCustomer: (orderId, input, mutation) => request("channel.checkout.customer", `/checkout/${encodePath(orderId)}/customer`, {
|
|
210
|
+
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
211
|
+
}),
|
|
212
|
+
setAddresses: (orderId, input, mutation) => request("channel.checkout.addresses", `/checkout/${encodePath(orderId)}/addresses`, {
|
|
213
|
+
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
214
|
+
}),
|
|
215
|
+
setFulfillment: (orderId, input, mutation) => request("channel.checkout.fulfillment", `/checkout/${encodePath(orderId)}/fulfillment`, {
|
|
216
|
+
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
217
|
+
}),
|
|
218
|
+
pay: (orderId, input, mutation) => request("channel.checkout.pay", `/checkout/${encodePath(orderId)}/pay`, {
|
|
219
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
220
|
+
}),
|
|
221
|
+
},
|
|
176
222
|
reviews: {
|
|
177
223
|
list: (params = {}) => request("reviews.public.list.channel", appendQuery("/reviews", params)),
|
|
178
224
|
summary: () => request("reviews.public.summary.channel", "/reviews/summary"),
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient, type ChannelCheckoutStatusParams } from "./index.js";
|
|
3
|
+
import type { AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, Order } from "./types.js";
|
|
4
|
+
export interface CartCookieAttributes {
|
|
5
|
+
httpOnly: true;
|
|
6
|
+
secure: boolean;
|
|
7
|
+
sameSite: "lax";
|
|
8
|
+
path: "/";
|
|
9
|
+
maxAge: number;
|
|
10
|
+
}
|
|
11
|
+
export declare const cartCookie: {
|
|
12
|
+
readonly name: "cart_token";
|
|
13
|
+
readonly attributes: (isProduction?: boolean) => CartCookieAttributes;
|
|
14
|
+
/**
|
|
15
|
+
* The client mints the token (the server accepts any sufficiently-random
|
|
16
|
+
* bearer key and creates the cart row on first use).
|
|
17
|
+
*/
|
|
18
|
+
readonly mint: () => string;
|
|
19
|
+
/** Tolerant read: an absent or garbage cookie means "no cart yet". */
|
|
20
|
+
readonly parse: (raw: string | undefined) => string | null;
|
|
21
|
+
};
|
|
22
|
+
type CartClient = Pick<ReturnType<typeof createChannelClient>, "cart" | "checkout">;
|
|
23
|
+
export interface CreateCartOptions {
|
|
24
|
+
/** The channel client, or a lazy resolver (the singleton pattern). */
|
|
25
|
+
client: CartClient | (() => CartClient);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Cart + checkout, with the token threading done for you. Every method returns
|
|
29
|
+
* the cart's underlying ORDER — checkout steps are addressed by its id.
|
|
30
|
+
*/
|
|
31
|
+
export declare function createCart(options: CreateCartOptions): {
|
|
32
|
+
readonly cookie: {
|
|
33
|
+
readonly name: "cart_token";
|
|
34
|
+
readonly attributes: (isProduction?: boolean) => CartCookieAttributes;
|
|
35
|
+
/**
|
|
36
|
+
* The client mints the token (the server accepts any sufficiently-random
|
|
37
|
+
* bearer key and creates the cart row on first use).
|
|
38
|
+
*/
|
|
39
|
+
readonly mint: () => string;
|
|
40
|
+
/** Tolerant read: an absent or garbage cookie means "no cart yet". */
|
|
41
|
+
readonly parse: (raw: string | undefined) => string | null;
|
|
42
|
+
};
|
|
43
|
+
/** Null when the token has no cart yet — a new visitor, not an error. */
|
|
44
|
+
readonly get: (cartToken: string) => Promise<Order | null>;
|
|
45
|
+
readonly addItem: (input: AddCartItemInput) => Promise<CartResponse>;
|
|
46
|
+
readonly updateItem: (itemId: string, cartToken: string, quantity: number) => Promise<CartResponse>;
|
|
47
|
+
readonly removeItem: (itemId: string, cartToken: string) => Promise<CartResponse>;
|
|
48
|
+
readonly clear: (cartToken: string) => Promise<CartResponse>;
|
|
49
|
+
/**
|
|
50
|
+
* Call in the same Server Action that sets the session cookie: the guest's
|
|
51
|
+
* cart follows the customer into their account instead of evaporating at
|
|
52
|
+
* the sign-in door.
|
|
53
|
+
*/
|
|
54
|
+
readonly mergeOnSignIn: (guestCartToken: string, customerCartToken: string) => Promise<CartResponse>;
|
|
55
|
+
/** Checkout steps, addressed by the order the cart became. */
|
|
56
|
+
readonly checkout: {
|
|
57
|
+
readonly options: (orderId: string, cartToken: string) => Promise<CheckoutOptions>;
|
|
58
|
+
readonly status: (orderId: string, params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
|
|
59
|
+
readonly setCustomer: (orderId: string, input: CheckoutCustomerInput) => Promise<CartResponse>;
|
|
60
|
+
readonly setAddresses: (orderId: string, input: CheckoutAddressesInput) => Promise<CartResponse>;
|
|
61
|
+
readonly setFulfillment: (orderId: string, input: CheckoutFulfillmentInput) => Promise<CartResponse>;
|
|
62
|
+
/**
|
|
63
|
+
* Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
|
|
64
|
+
* channel checkout (our API's host means nothing to your shopper) and
|
|
65
|
+
* must be on the channel's registered site_url — the server refuses
|
|
66
|
+
* anything else, because an unchecked return URL is an open redirect.
|
|
67
|
+
*/
|
|
68
|
+
readonly pay: (orderId: string, input: CheckoutPayInput & {
|
|
69
|
+
return_url: string;
|
|
70
|
+
}) => Promise<CheckoutPayResponse>;
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
export type CartKit = ReturnType<typeof createCart>;
|
|
74
|
+
export {};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient } from "./index.js";
|
|
3
|
+
function inProduction() {
|
|
4
|
+
return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
|
|
5
|
+
}
|
|
6
|
+
/** Carts live as long as sessions do; an abandoned cart is cleaned server-side. */
|
|
7
|
+
const CART_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
|
8
|
+
export const cartCookie = {
|
|
9
|
+
name: "cart_token",
|
|
10
|
+
attributes(isProduction = inProduction()) {
|
|
11
|
+
return { httpOnly: true, secure: isProduction, sameSite: "lax", path: "/", maxAge: CART_MAX_AGE_SECONDS };
|
|
12
|
+
},
|
|
13
|
+
/**
|
|
14
|
+
* The client mints the token (the server accepts any sufficiently-random
|
|
15
|
+
* bearer key and creates the cart row on first use).
|
|
16
|
+
*/
|
|
17
|
+
mint() {
|
|
18
|
+
return globalThis.crypto.randomUUID();
|
|
19
|
+
},
|
|
20
|
+
/** Tolerant read: an absent or garbage cookie means "no cart yet". */
|
|
21
|
+
parse(raw) {
|
|
22
|
+
const trimmed = raw?.trim() ?? "";
|
|
23
|
+
if (!trimmed || trimmed.length > 120)
|
|
24
|
+
return null;
|
|
25
|
+
return trimmed;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Cart + checkout, with the token threading done for you. Every method returns
|
|
30
|
+
* the cart's underlying ORDER — checkout steps are addressed by its id.
|
|
31
|
+
*/
|
|
32
|
+
export function createCart(options) {
|
|
33
|
+
const resolve = typeof options.client === "function" ? options.client : () => options.client;
|
|
34
|
+
return {
|
|
35
|
+
cookie: cartCookie,
|
|
36
|
+
/** Null when the token has no cart yet — a new visitor, not an error. */
|
|
37
|
+
async get(cartToken) {
|
|
38
|
+
try {
|
|
39
|
+
const { order } = await resolve().cart.get(cartToken);
|
|
40
|
+
return order ?? null;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
async addItem(input) {
|
|
47
|
+
return resolve().cart.addItem(input);
|
|
48
|
+
},
|
|
49
|
+
async updateItem(itemId, cartToken, quantity) {
|
|
50
|
+
return resolve().cart.updateItem(itemId, { cart_token: cartToken, quantity });
|
|
51
|
+
},
|
|
52
|
+
async removeItem(itemId, cartToken) {
|
|
53
|
+
return resolve().cart.removeItem(itemId, cartToken);
|
|
54
|
+
},
|
|
55
|
+
async clear(cartToken) {
|
|
56
|
+
return resolve().cart.clear(cartToken);
|
|
57
|
+
},
|
|
58
|
+
/**
|
|
59
|
+
* Call in the same Server Action that sets the session cookie: the guest's
|
|
60
|
+
* cart follows the customer into their account instead of evaporating at
|
|
61
|
+
* the sign-in door.
|
|
62
|
+
*/
|
|
63
|
+
async mergeOnSignIn(guestCartToken, customerCartToken) {
|
|
64
|
+
return resolve().cart.merge({
|
|
65
|
+
source_cart_token: guestCartToken,
|
|
66
|
+
target_cart_token: customerCartToken,
|
|
67
|
+
});
|
|
68
|
+
},
|
|
69
|
+
/** Checkout steps, addressed by the order the cart became. */
|
|
70
|
+
checkout: {
|
|
71
|
+
options: (orderId, cartToken) => resolve().checkout.options(orderId, cartToken),
|
|
72
|
+
status: (orderId, params) => resolve().checkout.status(orderId, params),
|
|
73
|
+
setCustomer: (orderId, input) => resolve().checkout.setCustomer(orderId, input),
|
|
74
|
+
setAddresses: (orderId, input) => resolve().checkout.setAddresses(orderId, input),
|
|
75
|
+
setFulfillment: (orderId, input) => resolve().checkout.setFulfillment(orderId, input),
|
|
76
|
+
/**
|
|
77
|
+
* Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
|
|
78
|
+
* channel checkout (our API's host means nothing to your shopper) and
|
|
79
|
+
* must be on the channel's registered site_url — the server refuses
|
|
80
|
+
* anything else, because an unchecked return URL is an open redirect.
|
|
81
|
+
*/
|
|
82
|
+
pay: (orderId, input) => resolve().checkout.pay(orderId, input, { idempotencyKey: `pay:${orderId}` }),
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient } from "./index.js";
|
|
3
|
+
/** What the session cookie holds. `expiresAt` is the ACCESS token's expiry. */
|
|
4
|
+
export interface SessionTokens {
|
|
5
|
+
accessToken: string;
|
|
6
|
+
refreshToken: string;
|
|
7
|
+
expiresAt: string;
|
|
8
|
+
}
|
|
9
|
+
/** A signed-in customer, normalized for rendering. */
|
|
10
|
+
export interface SessionCustomer {
|
|
11
|
+
id: string;
|
|
12
|
+
email: string;
|
|
13
|
+
name: string;
|
|
14
|
+
}
|
|
15
|
+
export interface SessionCookieAttributes {
|
|
16
|
+
httpOnly: true;
|
|
17
|
+
secure: boolean;
|
|
18
|
+
sameSite: "lax";
|
|
19
|
+
path: "/";
|
|
20
|
+
maxAge: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The one definition of the session cookie. A second definition is how a cookie
|
|
24
|
+
* ends up readable on one path and not another.
|
|
25
|
+
*/
|
|
26
|
+
export declare const sessionCookie: {
|
|
27
|
+
readonly name: "c1m_session";
|
|
28
|
+
readonly attributes: (isProduction?: boolean) => SessionCookieAttributes;
|
|
29
|
+
readonly serialize: (tokens: SessionTokens) => string;
|
|
30
|
+
/**
|
|
31
|
+
* A cookie is attacker-controlled input: truncated, stale-shaped, or
|
|
32
|
+
* hand-written. Anything unreadable is "not signed in", never a crash.
|
|
33
|
+
*/
|
|
34
|
+
readonly parse: (raw: string | undefined) => SessionTokens | null;
|
|
35
|
+
readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
|
|
36
|
+
};
|
|
37
|
+
export type RequestCodeOutcome = {
|
|
38
|
+
state: "sent";
|
|
39
|
+
} | {
|
|
40
|
+
state: "failed";
|
|
41
|
+
};
|
|
42
|
+
export type SignInOutcome = {
|
|
43
|
+
state: "signed-in";
|
|
44
|
+
customer: SessionCustomer;
|
|
45
|
+
tokens: SessionTokens;
|
|
46
|
+
/** Ready to hand to cookies().set(...) — name, value, attributes. */
|
|
47
|
+
cookie: {
|
|
48
|
+
name: string;
|
|
49
|
+
value: string;
|
|
50
|
+
attributes: SessionCookieAttributes;
|
|
51
|
+
};
|
|
52
|
+
} | {
|
|
53
|
+
state: "invalid-code";
|
|
54
|
+
} | {
|
|
55
|
+
state: "failed";
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* What to do with the session cookie after a refresh attempt.
|
|
59
|
+
*
|
|
60
|
+
* `keep` and `clear` are NOT interchangeable. Clearing when the customer merely
|
|
61
|
+
* lost a race with their own second tab discards the fresh token that tab just
|
|
62
|
+
* stored — logging them out of a live session. The server keeps the token
|
|
63
|
+
* family alive for a short rotation grace window and reports the loser as
|
|
64
|
+
* `refresh_contested` precisely so clients can tell the two apart.
|
|
65
|
+
*/
|
|
66
|
+
export type SessionRefreshResult = {
|
|
67
|
+
action: "keep";
|
|
68
|
+
} | {
|
|
69
|
+
action: "write";
|
|
70
|
+
value: string;
|
|
71
|
+
attributes: SessionCookieAttributes;
|
|
72
|
+
} | {
|
|
73
|
+
action: "clear";
|
|
74
|
+
};
|
|
75
|
+
type SessionClient = Pick<ReturnType<typeof createChannelClient>, "auth" | "withCustomer">;
|
|
76
|
+
export interface CreateCustomerSessionOptions {
|
|
77
|
+
/** The channel client, or a lazy resolver (the singleton pattern). */
|
|
78
|
+
client: SessionClient | (() => SessionClient);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The session surface a site actually needs, mapped to intentional outcomes —
|
|
82
|
+
* a route renders "that code was wrong" without ever seeing an HTTP status.
|
|
83
|
+
*/
|
|
84
|
+
export declare function createCustomerSession(options: CreateCustomerSessionOptions): {
|
|
85
|
+
readonly cookie: {
|
|
86
|
+
readonly name: "c1m_session";
|
|
87
|
+
readonly attributes: (isProduction?: boolean) => SessionCookieAttributes;
|
|
88
|
+
readonly serialize: (tokens: SessionTokens) => string;
|
|
89
|
+
/**
|
|
90
|
+
* A cookie is attacker-controlled input: truncated, stale-shaped, or
|
|
91
|
+
* hand-written. Anything unreadable is "not signed in", never a crash.
|
|
92
|
+
*/
|
|
93
|
+
readonly parse: (raw: string | undefined) => SessionTokens | null;
|
|
94
|
+
readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
|
|
95
|
+
};
|
|
96
|
+
readonly requestCode: (email: string) => Promise<RequestCodeOutcome>;
|
|
97
|
+
readonly signIn: (email: string, code: string) => Promise<SignInOutcome>;
|
|
98
|
+
/**
|
|
99
|
+
* Decide what this request should do to the session cookie. Designed to be
|
|
100
|
+
* the whole body of proxy.ts.
|
|
101
|
+
*/
|
|
102
|
+
readonly refresh: (raw: string | undefined) => Promise<SessionRefreshResult>;
|
|
103
|
+
/** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
|
|
104
|
+
readonly getCustomer: (raw: string | undefined) => Promise<SessionCustomer | null>;
|
|
105
|
+
/** Best-effort server logout; the caller clears the cookie REGARDLESS. */
|
|
106
|
+
readonly signOut: (raw: string | undefined) => Promise<void>;
|
|
107
|
+
};
|
|
108
|
+
export type CustomerSessionKit = ReturnType<typeof createCustomerSession>;
|
|
109
|
+
export {};
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { ChannelAPIError, createChannelClient } from "./index.js";
|
|
3
|
+
function inProduction() {
|
|
4
|
+
return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
|
|
5
|
+
}
|
|
6
|
+
/** Match the refresh token's life (~30 days), not the access token's (~15 min). */
|
|
7
|
+
const MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
|
8
|
+
/** Refresh slightly BEFORE expiry: a token that dies mid-render fails the request it was meant to serve. */
|
|
9
|
+
const REFRESH_SKEW_MS = 60_000;
|
|
10
|
+
/**
|
|
11
|
+
* The one definition of the session cookie. A second definition is how a cookie
|
|
12
|
+
* ends up readable on one path and not another.
|
|
13
|
+
*/
|
|
14
|
+
export const sessionCookie = {
|
|
15
|
+
name: "c1m_session",
|
|
16
|
+
attributes(isProduction = inProduction()) {
|
|
17
|
+
return {
|
|
18
|
+
// Never readable from JavaScript: an XSS bug must not become a stolen session.
|
|
19
|
+
httpOnly: true,
|
|
20
|
+
secure: isProduction,
|
|
21
|
+
// Lax, not Strict: the session must survive a customer arriving from an
|
|
22
|
+
// emailed link. Not None — that would ship the cookie cross-site.
|
|
23
|
+
sameSite: "lax",
|
|
24
|
+
path: "/",
|
|
25
|
+
maxAge: MAX_AGE_SECONDS,
|
|
26
|
+
};
|
|
27
|
+
},
|
|
28
|
+
serialize(tokens) {
|
|
29
|
+
return JSON.stringify(tokens);
|
|
30
|
+
},
|
|
31
|
+
/**
|
|
32
|
+
* A cookie is attacker-controlled input: truncated, stale-shaped, or
|
|
33
|
+
* hand-written. Anything unreadable is "not signed in", never a crash.
|
|
34
|
+
*/
|
|
35
|
+
parse(raw) {
|
|
36
|
+
if (!raw)
|
|
37
|
+
return null;
|
|
38
|
+
try {
|
|
39
|
+
const parsed = JSON.parse(raw);
|
|
40
|
+
if (!parsed || typeof parsed !== "object")
|
|
41
|
+
return null;
|
|
42
|
+
const { accessToken, refreshToken, expiresAt } = parsed;
|
|
43
|
+
if (typeof accessToken !== "string" || !accessToken)
|
|
44
|
+
return null;
|
|
45
|
+
if (typeof refreshToken !== "string" || !refreshToken)
|
|
46
|
+
return null;
|
|
47
|
+
if (typeof expiresAt !== "string" || !expiresAt)
|
|
48
|
+
return null;
|
|
49
|
+
return { accessToken, refreshToken, expiresAt };
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
needsRefresh(tokens, now = Date.now()) {
|
|
56
|
+
const expiresAt = Date.parse(tokens.expiresAt);
|
|
57
|
+
// Unparseable expiry: refresh and find out, rather than trusting it forever.
|
|
58
|
+
if (Number.isNaN(expiresAt))
|
|
59
|
+
return true;
|
|
60
|
+
return expiresAt - now <= REFRESH_SKEW_MS;
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
/** The server's code for "another request rotated this token moments ago". */
|
|
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
|
+
function normalizeCustomer(customer) {
|
|
83
|
+
return {
|
|
84
|
+
id: customer.id,
|
|
85
|
+
email: customer.email,
|
|
86
|
+
name: customer.name?.trim() || customer.email,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function toTokens(session) {
|
|
90
|
+
return {
|
|
91
|
+
accessToken: session.access_token,
|
|
92
|
+
refreshToken: session.refresh_token,
|
|
93
|
+
expiresAt: session.expires_at,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The session surface a site actually needs, mapped to intentional outcomes —
|
|
98
|
+
* a route renders "that code was wrong" without ever seeing an HTTP status.
|
|
99
|
+
*/
|
|
100
|
+
export function createCustomerSession(options) {
|
|
101
|
+
const resolve = typeof options.client === "function" ? options.client : () => options.client;
|
|
102
|
+
return {
|
|
103
|
+
cookie: sessionCookie,
|
|
104
|
+
async requestCode(email) {
|
|
105
|
+
try {
|
|
106
|
+
await resolve().auth.sendCode(email);
|
|
107
|
+
return { state: "sent" };
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return { state: "failed" };
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
async signIn(email, code) {
|
|
114
|
+
try {
|
|
115
|
+
const session = await resolve().auth.verifyCode({ email, code });
|
|
116
|
+
const tokens = toTokens(session);
|
|
117
|
+
return {
|
|
118
|
+
state: "signed-in",
|
|
119
|
+
customer: normalizeCustomer(session.end_user),
|
|
120
|
+
tokens,
|
|
121
|
+
cookie: {
|
|
122
|
+
name: sessionCookie.name,
|
|
123
|
+
value: sessionCookie.serialize(tokens),
|
|
124
|
+
attributes: sessionCookie.attributes(),
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
// 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)) {
|
|
132
|
+
return { state: "invalid-code" };
|
|
133
|
+
}
|
|
134
|
+
return { state: "failed" };
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
/**
|
|
138
|
+
* Decide what this request should do to the session cookie. Designed to be
|
|
139
|
+
* the whole body of proxy.ts.
|
|
140
|
+
*/
|
|
141
|
+
async refresh(raw) {
|
|
142
|
+
const session = sessionCookie.parse(raw);
|
|
143
|
+
if (!session)
|
|
144
|
+
return { action: "keep" };
|
|
145
|
+
if (!sessionCookie.needsRefresh(session))
|
|
146
|
+
return { action: "keep" };
|
|
147
|
+
try {
|
|
148
|
+
const rotated = await resolve().auth.refresh(session.refreshToken);
|
|
149
|
+
return {
|
|
150
|
+
action: "write",
|
|
151
|
+
value: sessionCookie.serialize(toTokens(rotated)),
|
|
152
|
+
attributes: sessionCookie.attributes(),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
const api = asChannelAPIError(error);
|
|
157
|
+
if (api) {
|
|
158
|
+
// Lost a race with the customer's own other tab: the session is alive
|
|
159
|
+
// and that tab already stored a good token. KEEP the cookie.
|
|
160
|
+
if (api.code === CONTESTED)
|
|
161
|
+
return { action: "keep" };
|
|
162
|
+
// Genuinely dead — logged out, revoked, or aged out. Clear it.
|
|
163
|
+
if (api.status === 401)
|
|
164
|
+
return { action: "clear" };
|
|
165
|
+
}
|
|
166
|
+
// An upstream wobble is not evidence anyone's session is dead.
|
|
167
|
+
return { action: "keep" };
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
/** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
|
|
171
|
+
async getCustomer(raw) {
|
|
172
|
+
const session = sessionCookie.parse(raw);
|
|
173
|
+
if (!session)
|
|
174
|
+
return null;
|
|
175
|
+
try {
|
|
176
|
+
const { end_user } = await resolve().withCustomer(session.accessToken).me();
|
|
177
|
+
return normalizeCustomer(end_user);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
/** Best-effort server logout; the caller clears the cookie REGARDLESS. */
|
|
184
|
+
async signOut(raw) {
|
|
185
|
+
const session = sessionCookie.parse(raw);
|
|
186
|
+
if (!session)
|
|
187
|
+
return;
|
|
188
|
+
try {
|
|
189
|
+
await resolve().withCustomer(session.accessToken).logout();
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// A customer who clicks "sign out" must end up signed out of this
|
|
193
|
+
// browser even if the API is down.
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { type ChannelWebhookEvent, type ChannelWebhookEventDataMap } from "./webhooks.js";
|
|
3
|
+
/**
|
|
4
|
+
* Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
|
|
5
|
+
*
|
|
6
|
+
* import { revalidatePath, revalidateTag } from "next/cache";
|
|
7
|
+
* export const POST = createChannelWebhookRoute({
|
|
8
|
+
* secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
|
|
9
|
+
* invalidate: { revalidatePath, revalidateTag },
|
|
10
|
+
* });
|
|
11
|
+
*
|
|
12
|
+
* The invalidator is injected rather than imported here on purpose: it keeps
|
|
13
|
+
* this module free of `next` (bundler-safe, unit-testable with a fake), and it
|
|
14
|
+
* is the app's two-line import — not eighty lines of verification, dispatch,
|
|
15
|
+
* path-safety and error-mapping boilerplate.
|
|
16
|
+
*/
|
|
17
|
+
/** The cache tag every anonymous site read is filed under. */
|
|
18
|
+
export declare const CHANNEL_SITE_CACHE_TAG = "channel:site";
|
|
19
|
+
export interface ChannelCacheInvalidator {
|
|
20
|
+
revalidatePath(path: string): void;
|
|
21
|
+
revalidateTag(tag: string): void;
|
|
22
|
+
}
|
|
23
|
+
export interface ChannelWebhookRouteLogger {
|
|
24
|
+
info(message: string, context?: Record<string, unknown>): void;
|
|
25
|
+
warn(message: string, context?: Record<string, unknown>): void;
|
|
26
|
+
error(message: string, context?: Record<string, unknown>): void;
|
|
27
|
+
}
|
|
28
|
+
export type ChannelWebhookHandlers = {
|
|
29
|
+
[T in keyof ChannelWebhookEventDataMap]?: (event: ChannelWebhookEvent<T>, invalidate: ChannelCacheInvalidator) => void | Promise<void>;
|
|
30
|
+
};
|
|
31
|
+
export interface CreateChannelWebhookRouteOptions {
|
|
32
|
+
/** The whsec_ signing secret, or a lazy resolver (resolved per request so builds without env pass). */
|
|
33
|
+
secret: string | (() => string);
|
|
34
|
+
/** Next's cache invalidation, injected: `{ revalidatePath, revalidateTag }` from next/cache. */
|
|
35
|
+
invalidate: ChannelCacheInvalidator;
|
|
36
|
+
/**
|
|
37
|
+
* Per-event handlers. A handler REPLACES the built-in behavior for that type;
|
|
38
|
+
* types without a handler get the default (page.published revalidates the
|
|
39
|
+
* site tag + the published path; everything else is acknowledged and ignored
|
|
40
|
+
* — delivery is at-least-once, so an unhandled event must still 204 or the
|
|
41
|
+
* server will retry it for hours).
|
|
42
|
+
*/
|
|
43
|
+
onEvent?: ChannelWebhookHandlers;
|
|
44
|
+
logger?: ChannelWebhookRouteLogger;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A route_pattern arrives from the network; it is input, not truth. Reject
|
|
48
|
+
* anything that is not a plain absolute path before handing it to the cache.
|
|
49
|
+
*/
|
|
50
|
+
export declare function safePublishedPath(path: string): string | undefined;
|
|
51
|
+
/** Build the POST handler for the channel webhook endpoint. */
|
|
52
|
+
export declare function createChannelWebhookRoute(options: CreateChannelWebhookRouteOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { ChannelWebhookVerificationError, parseChannelWebhookEvent, } from "./webhooks.js";
|
|
3
|
+
/**
|
|
4
|
+
* Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
|
|
5
|
+
*
|
|
6
|
+
* import { revalidatePath, revalidateTag } from "next/cache";
|
|
7
|
+
* export const POST = createChannelWebhookRoute({
|
|
8
|
+
* secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
|
|
9
|
+
* invalidate: { revalidatePath, revalidateTag },
|
|
10
|
+
* });
|
|
11
|
+
*
|
|
12
|
+
* The invalidator is injected rather than imported here on purpose: it keeps
|
|
13
|
+
* this module free of `next` (bundler-safe, unit-testable with a fake), and it
|
|
14
|
+
* is the app's two-line import — not eighty lines of verification, dispatch,
|
|
15
|
+
* path-safety and error-mapping boilerplate.
|
|
16
|
+
*/
|
|
17
|
+
/** The cache tag every anonymous site read is filed under. */
|
|
18
|
+
export const CHANNEL_SITE_CACHE_TAG = "channel:site";
|
|
19
|
+
/**
|
|
20
|
+
* A route_pattern arrives from the network; it is input, not truth. Reject
|
|
21
|
+
* anything that is not a plain absolute path before handing it to the cache.
|
|
22
|
+
*/
|
|
23
|
+
export function safePublishedPath(path) {
|
|
24
|
+
const normalized = path.trim();
|
|
25
|
+
if (!normalized.startsWith("/") || normalized.startsWith("//") || normalized.length > 1024) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
return normalized;
|
|
29
|
+
}
|
|
30
|
+
/** Structural, not instanceof — see the session kit for why. */
|
|
31
|
+
function isVerificationError(error) {
|
|
32
|
+
if (error instanceof ChannelWebhookVerificationError)
|
|
33
|
+
return true;
|
|
34
|
+
return (typeof error === "object" && error !== null &&
|
|
35
|
+
error.name === "ChannelWebhookVerificationError" &&
|
|
36
|
+
typeof error.code === "string");
|
|
37
|
+
}
|
|
38
|
+
function defaultBehavior(event, invalidate) {
|
|
39
|
+
if (event.type !== "page.published")
|
|
40
|
+
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;
|
|
47
|
+
}
|
|
48
|
+
/** Build the POST handler for the channel webhook endpoint. */
|
|
49
|
+
export function createChannelWebhookRoute(options) {
|
|
50
|
+
const logger = options.logger ?? console;
|
|
51
|
+
const resolveSecret = typeof options.secret === "function" ? options.secret : () => options.secret;
|
|
52
|
+
return async (request) => {
|
|
53
|
+
let event;
|
|
54
|
+
try {
|
|
55
|
+
event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (isVerificationError(error)) {
|
|
59
|
+
// An unverifiable request is noise or an attack; log the code, say
|
|
60
|
+
// nothing useful back.
|
|
61
|
+
logger.warn("channel_webhook_rejected", { code: error.code });
|
|
62
|
+
return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
|
|
63
|
+
}
|
|
64
|
+
logger.error("channel_webhook_failed", { error });
|
|
65
|
+
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const handler = options.onEvent?.[event.type];
|
|
69
|
+
let revalidatedPath;
|
|
70
|
+
if (handler) {
|
|
71
|
+
await handler(event, options.invalidate);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
revalidatedPath = defaultBehavior(event, options.invalidate);
|
|
75
|
+
}
|
|
76
|
+
logger.info("channel_webhook_processed", {
|
|
77
|
+
eventId: event.id,
|
|
78
|
+
eventType: event.type,
|
|
79
|
+
...(revalidatedPath ? { revalidatedPath } : {}),
|
|
80
|
+
});
|
|
81
|
+
return new Response(null, { status: 204 });
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
// A handler failure is OURS: the signature verified, the event is real.
|
|
85
|
+
// A 500 makes the server retry on its ladder — which is what you want
|
|
86
|
+
// when the failure is transient, and visible in delivery history when
|
|
87
|
+
// it is not.
|
|
88
|
+
logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, error });
|
|
89
|
+
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
package/dist/next.d.ts
CHANGED
|
@@ -37,6 +37,22 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
|
|
|
37
37
|
}>;
|
|
38
38
|
readonly media: (slug: string) => Promise<import("./types.js").ListResponse<import("./types.js").ProductAsset>>;
|
|
39
39
|
};
|
|
40
|
+
readonly cart: {
|
|
41
|
+
readonly get: (cartToken: string) => Promise<import("./types.js").CartResponse>;
|
|
42
|
+
readonly addItem: (input: import("./types.js").AddCartItemInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
43
|
+
readonly updateItem: (itemId: string, input: import("./types.js").UpdateCartItemInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
44
|
+
readonly removeItem: (itemId: string, cartToken: string, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
45
|
+
readonly clear: (cartToken: string, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
46
|
+
readonly merge: (input: import("./types.js").MergeCartInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
47
|
+
};
|
|
48
|
+
readonly checkout: {
|
|
49
|
+
readonly options: (orderId: string, cartToken: string) => Promise<import("./types.js").CheckoutOptions>;
|
|
50
|
+
readonly status: (orderId: string, params?: import("./index.js").ChannelCheckoutStatusParams) => Promise<import("./types.js").CheckoutStatusResponse>;
|
|
51
|
+
readonly setCustomer: (orderId: string, input: import("./types.js").CheckoutCustomerInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
52
|
+
readonly setAddresses: (orderId: string, input: import("./types.js").CheckoutAddressesInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
53
|
+
readonly setFulfillment: (orderId: string, input: import("./types.js").CheckoutFulfillmentInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
|
|
54
|
+
readonly pay: (orderId: string, input: import("./types.js").CheckoutPayInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CheckoutPayResponse>;
|
|
55
|
+
};
|
|
40
56
|
readonly reviews: {
|
|
41
57
|
readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Review>>;
|
|
42
58
|
readonly summary: () => Promise<import("./types.js").ReviewSummaryResponse>;
|
|
@@ -94,3 +110,6 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
|
|
|
94
110
|
}>;
|
|
95
111
|
};
|
|
96
112
|
};
|
|
113
|
+
export * from "./next-session.js";
|
|
114
|
+
export * from "./next-webhooks.js";
|
|
115
|
+
export * from "./next-cart.js";
|
package/dist/next.js
CHANGED
|
@@ -38,3 +38,10 @@ export function createNextChannelClient(options) {
|
|
|
38
38
|
};
|
|
39
39
|
return createChannelClient({ ...coreOptions, fetch: nextFetch });
|
|
40
40
|
}
|
|
41
|
+
// The kits: the ~600 lines of plumbing every headless site was copy-pasting —
|
|
42
|
+
// session cookie + refresh decision, the webhook route, the cart's token
|
|
43
|
+
// threading — shipped once, injection-shaped, framework-honest (no `next`
|
|
44
|
+
// imports; apps pass next/cache + apply cookies where Next allows writes).
|
|
45
|
+
export * from "./next-session.js";
|
|
46
|
+
export * from "./next-webhooks.js";
|
|
47
|
+
export * from "./next-cart.js";
|
package/dist/types.d.ts
CHANGED
|
@@ -267,12 +267,138 @@ export interface CustomerResponse {
|
|
|
267
267
|
}
|
|
268
268
|
export interface Order {
|
|
269
269
|
id: string;
|
|
270
|
+
workspace_id?: string;
|
|
270
271
|
order_number: string;
|
|
272
|
+
cart_token?: string;
|
|
273
|
+
channel_id?: string;
|
|
271
274
|
status: string;
|
|
272
275
|
payment_status: string;
|
|
273
276
|
currency: string;
|
|
277
|
+
source?: string;
|
|
278
|
+
customer_email?: string;
|
|
279
|
+
customer_name?: string;
|
|
280
|
+
subtotal_cents?: number;
|
|
281
|
+
shipping_amount_cents?: number;
|
|
282
|
+
tax_amount_cents?: number;
|
|
274
283
|
total_cents: number;
|
|
284
|
+
items?: OrderItem[];
|
|
285
|
+
version?: number;
|
|
275
286
|
created_at: string;
|
|
287
|
+
updated_at?: string;
|
|
288
|
+
[key: string]: unknown;
|
|
289
|
+
}
|
|
290
|
+
export interface OrderItem {
|
|
291
|
+
id: string;
|
|
292
|
+
order_id: string;
|
|
293
|
+
product_id?: string;
|
|
294
|
+
variant_id?: string;
|
|
295
|
+
product_slug?: string;
|
|
296
|
+
variant_title?: string;
|
|
297
|
+
thumbnail_url?: string;
|
|
298
|
+
title: string;
|
|
299
|
+
quantity: number;
|
|
300
|
+
unit_price_cents: number;
|
|
301
|
+
line_total_cents: number;
|
|
302
|
+
[key: string]: unknown;
|
|
303
|
+
}
|
|
304
|
+
export interface CartResponse {
|
|
305
|
+
order: Order;
|
|
306
|
+
}
|
|
307
|
+
export interface AddCartItemInput {
|
|
308
|
+
cart_token?: string;
|
|
309
|
+
currency?: string;
|
|
310
|
+
product_id: string;
|
|
311
|
+
variant_id?: string;
|
|
312
|
+
quantity: number;
|
|
313
|
+
}
|
|
314
|
+
export interface UpdateCartItemInput {
|
|
315
|
+
cart_token: string;
|
|
316
|
+
quantity: number;
|
|
317
|
+
}
|
|
318
|
+
export interface MergeCartInput {
|
|
319
|
+
source_cart_token: string;
|
|
320
|
+
target_cart_token: string;
|
|
321
|
+
currency?: string;
|
|
322
|
+
}
|
|
323
|
+
export interface CheckoutCustomerInput {
|
|
324
|
+
cart_token: string;
|
|
325
|
+
email: string;
|
|
326
|
+
name: string;
|
|
327
|
+
}
|
|
328
|
+
export interface CheckoutAddress {
|
|
329
|
+
name?: string;
|
|
330
|
+
phone?: string;
|
|
331
|
+
line1: string;
|
|
332
|
+
line2?: string;
|
|
333
|
+
city: string;
|
|
334
|
+
region?: string;
|
|
335
|
+
postal_code?: string;
|
|
336
|
+
country_code: string;
|
|
337
|
+
}
|
|
338
|
+
export interface CheckoutAddressesInput {
|
|
339
|
+
cart_token: string;
|
|
340
|
+
shipping: CheckoutAddress;
|
|
341
|
+
billing?: CheckoutAddress;
|
|
342
|
+
}
|
|
343
|
+
export interface CheckoutFulfillmentInput {
|
|
344
|
+
cart_token: string;
|
|
345
|
+
method: "shipping" | "pickup";
|
|
346
|
+
shipping_method_id?: string;
|
|
347
|
+
}
|
|
348
|
+
export interface CheckoutPayInput {
|
|
349
|
+
cart_token: string;
|
|
350
|
+
return_url?: string;
|
|
351
|
+
}
|
|
352
|
+
export interface PaymentMethodOption {
|
|
353
|
+
provider: string;
|
|
354
|
+
name: string;
|
|
355
|
+
type: string;
|
|
356
|
+
is_available: boolean;
|
|
357
|
+
[key: string]: unknown;
|
|
358
|
+
}
|
|
359
|
+
export interface PaymentReadiness {
|
|
360
|
+
ready: boolean;
|
|
361
|
+
mode: string;
|
|
362
|
+
reasons?: string[];
|
|
363
|
+
providers_available?: string[];
|
|
364
|
+
connect_required?: boolean;
|
|
365
|
+
connect_configured?: boolean;
|
|
366
|
+
}
|
|
367
|
+
export interface ShippingMethodOption {
|
|
368
|
+
id: string;
|
|
369
|
+
name?: string;
|
|
370
|
+
code?: string;
|
|
371
|
+
amount_cents?: number;
|
|
372
|
+
[key: string]: unknown;
|
|
373
|
+
}
|
|
374
|
+
export interface CheckoutOptions {
|
|
375
|
+
checkout_variant: string;
|
|
376
|
+
order: Order;
|
|
377
|
+
shipping_methods?: ShippingMethodOption[];
|
|
378
|
+
payment_methods?: PaymentMethodOption[];
|
|
379
|
+
payment_ready?: boolean;
|
|
380
|
+
payment_readiness?: PaymentReadiness;
|
|
381
|
+
[key: string]: unknown;
|
|
382
|
+
}
|
|
383
|
+
export type CheckoutStatus = "finalizing" | "completed" | "failed" | "not_found";
|
|
384
|
+
export interface CheckoutStatusResponse {
|
|
385
|
+
status: CheckoutStatus;
|
|
386
|
+
order_status?: string;
|
|
387
|
+
payment_status?: string;
|
|
388
|
+
payment_reference?: string;
|
|
389
|
+
updated_at?: string;
|
|
390
|
+
reasons?: string[];
|
|
391
|
+
[key: string]: unknown;
|
|
392
|
+
}
|
|
393
|
+
export interface CheckoutPayResponse {
|
|
394
|
+
order: Order;
|
|
395
|
+
session?: Record<string, unknown>;
|
|
396
|
+
checkout_variant?: string;
|
|
397
|
+
payment?: Record<string, unknown>;
|
|
398
|
+
status?: string;
|
|
399
|
+
provider_ref?: string;
|
|
400
|
+
checkout_session_id?: string;
|
|
401
|
+
redirect_url?: string;
|
|
276
402
|
[key: string]: unknown;
|
|
277
403
|
}
|
|
278
404
|
export interface OrderSummary {
|