@c1m-public/channel-client 0.2.1 → 0.4.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 +54 -13
- package/dist/index.d.ts +29 -8
- package/dist/index.js +94 -73
- package/dist/next.d.ts +96 -0
- package/dist/next.js +40 -0
- package/dist/types.d.ts +30 -8
- package/dist/webhooks.d.ts +0 -1
- package/dist/webhooks.js +0 -1
- package/package.json +19 -2
package/README.md
CHANGED
|
@@ -1,40 +1,81 @@
|
|
|
1
1
|
# `@c1m-public/channel-client`
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Typed server-side client for the C1M Channel API. One npm package exposes
|
|
4
|
+
capability-based entry points so framework behavior does not leak into the
|
|
5
|
+
transport core.
|
|
6
|
+
|
|
7
|
+
## Entry points
|
|
8
|
+
|
|
9
|
+
- `@c1m-public/channel-client` — framework-neutral transport, contracts,
|
|
10
|
+
authentication, retries, errors and request observations.
|
|
11
|
+
- `@c1m-public/channel-client/next` — Next.js server-only guard and Data Cache
|
|
12
|
+
policy layered over the same client.
|
|
13
|
+
- `@c1m-public/channel-client/webhooks` — framework-neutral webhook events and
|
|
14
|
+
signature verification.
|
|
15
|
+
|
|
16
|
+
Channel credentials resolve the tenant and workspace at the API door, so site
|
|
17
|
+
URLs never carry either identifier.
|
|
18
|
+
|
|
19
|
+
### Next.js
|
|
6
20
|
|
|
7
21
|
```ts
|
|
8
|
-
import {
|
|
22
|
+
import { createNextChannelClient } from "@c1m-public/channel-client/next";
|
|
9
23
|
|
|
10
|
-
const channel =
|
|
24
|
+
const channel = createNextChannelClient({
|
|
11
25
|
baseUrl: process.env.C1M_API_URL!,
|
|
12
26
|
token: process.env.C1M_CHANNEL_TOKEN!,
|
|
13
27
|
cache: { revalidate: 60 },
|
|
14
28
|
});
|
|
15
29
|
|
|
16
|
-
const
|
|
30
|
+
const { page } = await channel.pages.get("home");
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Other server runtimes
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { createChannelClient } from "@c1m-public/channel-client";
|
|
37
|
+
|
|
38
|
+
const channel = createChannelClient({
|
|
39
|
+
baseUrl: process.env.C1M_API_URL!,
|
|
40
|
+
token: process.env.C1M_CHANNEL_TOKEN!,
|
|
41
|
+
});
|
|
17
42
|
```
|
|
18
43
|
|
|
19
44
|
The package must only be imported from server modules. Never expose the token in
|
|
20
45
|
`NEXT_PUBLIC_*`, Client Components, browser storage, HTML, source maps, logs, or
|
|
21
|
-
asset requests.
|
|
46
|
+
asset requests. The `/next` entry point enforces Next's `server-only` boundary;
|
|
47
|
+
other runtimes must enforce their own server-module boundary.
|
|
22
48
|
|
|
23
49
|
## Behavior
|
|
24
50
|
|
|
25
|
-
-
|
|
51
|
+
- The core retries transient reads once and leaves anonymous-read caching to the
|
|
52
|
+
runtime adapter.
|
|
53
|
+
- The Next adapter supports explicit revalidation and tags.
|
|
26
54
|
- Writes are always `no-store`, are never automatically retried, and accept an
|
|
27
55
|
explicit idempotency key.
|
|
28
56
|
- Requests time out after 10 seconds by default.
|
|
29
57
|
- API failures throw `ChannelAPIError` with safe status, code, and request ID.
|
|
30
58
|
- Assets remain tokenless and are normalized with `assetUrl()`.
|
|
59
|
+
- `observe` can receive one bounded telemetry event per logical request. Events
|
|
60
|
+
contain operation, outcome, status, request ID, duration and attempt count;
|
|
61
|
+
they never contain URLs, credentials, headers, bodies or customer data.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const channel = createChannelClient({
|
|
65
|
+
baseUrl: process.env.C1M_API_URL!,
|
|
66
|
+
token: process.env.C1M_CHANNEL_TOKEN!,
|
|
67
|
+
observe(event) {
|
|
68
|
+
console.info("c1m.channel", event);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
```
|
|
31
72
|
|
|
32
73
|
## Webhooks
|
|
33
74
|
|
|
34
75
|
Verify webhook requests before parsing or acting on their payload:
|
|
35
76
|
|
|
36
77
|
```ts
|
|
37
|
-
import { parseChannelWebhookEvent } from "@c1m-public/channel-client";
|
|
78
|
+
import { parseChannelWebhookEvent } from "@c1m-public/channel-client/webhooks";
|
|
38
79
|
|
|
39
80
|
const event = await parseChannelWebhookEvent(request, {
|
|
40
81
|
secret: process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
|
|
@@ -59,7 +100,7 @@ pnpm --filter @c1m-public/channel-client pack
|
|
|
59
100
|
npm publish --access public
|
|
60
101
|
```
|
|
61
102
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
103
|
+
Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
|
|
104
|
+
`channel-client-vX.Y.Z` tag matching `package.json`; the workflow verifies,
|
|
105
|
+
packs, and publishes without a stored npm token. Published versions are
|
|
106
|
+
immutable, so increment the package version for every release.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
import "server-only";
|
|
2
1
|
export * from "./webhooks.js";
|
|
3
|
-
export type { BlogPost, BlogPostResponse, 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";
|
|
4
|
-
import type { BlogPostResponse, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
|
|
5
|
-
export type ChannelCachePolicy = "no-store" | {
|
|
6
|
-
revalidate: number;
|
|
7
|
-
tags?: string[];
|
|
8
|
-
};
|
|
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";
|
|
9
4
|
export interface ChannelRetryPolicy {
|
|
10
5
|
attempts?: number;
|
|
11
6
|
maxDelayMs?: number;
|
|
@@ -14,10 +9,26 @@ export interface CreateChannelClientOptions {
|
|
|
14
9
|
baseUrl: string;
|
|
15
10
|
token: string;
|
|
16
11
|
fetch?: typeof globalThis.fetch;
|
|
17
|
-
cache?: ChannelCachePolicy;
|
|
18
12
|
timeoutMs?: number;
|
|
19
13
|
retry?: ChannelRetryPolicy | false;
|
|
14
|
+
observe?: ChannelRequestObserver;
|
|
15
|
+
}
|
|
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";
|
|
18
|
+
export interface ChannelRequestObservation {
|
|
19
|
+
operation: ChannelOperation;
|
|
20
|
+
method: string;
|
|
21
|
+
outcome: ChannelRequestOutcome;
|
|
22
|
+
status: number;
|
|
23
|
+
requestId: string;
|
|
24
|
+
durationMs: number;
|
|
25
|
+
attempts: number;
|
|
20
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Receives bounded request telemetry. Observations deliberately exclude URLs,
|
|
29
|
+
* headers, credentials, request bodies, response bodies and customer data.
|
|
30
|
+
*/
|
|
31
|
+
export type ChannelRequestObserver = (observation: ChannelRequestObservation) => void;
|
|
21
32
|
export interface ChannelListParams {
|
|
22
33
|
cursor?: string;
|
|
23
34
|
limit?: number;
|
|
@@ -46,6 +57,16 @@ export declare class ChannelAPIError extends Error {
|
|
|
46
57
|
constructor(message: string, status: number, code: string, requestId: string);
|
|
47
58
|
}
|
|
48
59
|
export declare function createChannelClient(options: CreateChannelClientOptions): {
|
|
60
|
+
/**
|
|
61
|
+
* Verify the channel token and see what it points at.
|
|
62
|
+
*
|
|
63
|
+
* The cheapest call on the door — it does no database work server-side. Use
|
|
64
|
+
* it as a deployment health check: a 200 means C1M_CHANNEL_TOKEN is right and
|
|
65
|
+
* aimed at the workspace you expect. A ChannelAPIError with status 401 means
|
|
66
|
+
* the token is bad, revoked, or the channel is disabled (the door will not
|
|
67
|
+
* say which). A 503 means C1M is unavailable — NOT that your token is wrong.
|
|
68
|
+
*/
|
|
69
|
+
readonly ping: () => Promise<ChannelPing>;
|
|
49
70
|
readonly assetUrl: (pathOrUrl: string) => string;
|
|
50
71
|
readonly site: {
|
|
51
72
|
readonly resolve: (params?: ChannelSiteResolveParams) => Promise<SiteDocument>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import "server-only";
|
|
2
1
|
export * from "./webhooks.js";
|
|
3
2
|
const CHANNEL_TOKEN_PREFIX = "sk_chan_";
|
|
4
3
|
const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
|
|
@@ -58,10 +57,6 @@ export function createChannelClient(options) {
|
|
|
58
57
|
const fetcher = options.fetch ?? globalThis.fetch;
|
|
59
58
|
if (!fetcher)
|
|
60
59
|
throw new Error("fetch implementation is required");
|
|
61
|
-
const cachePolicy = options.cache ?? "no-store";
|
|
62
|
-
if (cachePolicy !== "no-store" && (!Number.isFinite(cachePolicy.revalidate) || cachePolicy.revalidate < 0)) {
|
|
63
|
-
throw new Error("cache.revalidate must be a non-negative finite number");
|
|
64
|
-
}
|
|
65
60
|
const timeoutMs = positiveNumber(options.timeoutMs ?? 10_000, "timeoutMs");
|
|
66
61
|
const configuredRetryAttempts = options.retry === false ? 0 : options.retry?.attempts ?? 1;
|
|
67
62
|
if (!Number.isSafeInteger(configuredRetryAttempts) || configuredRetryAttempts < 0) {
|
|
@@ -69,8 +64,14 @@ export function createChannelClient(options) {
|
|
|
69
64
|
}
|
|
70
65
|
const retryAttempts = configuredRetryAttempts;
|
|
71
66
|
const maxRetryDelayMs = positiveNumber(options.retry === false ? 2_000 : options.retry?.maxDelayMs ?? 2_000, "retry.maxDelayMs");
|
|
72
|
-
|
|
67
|
+
const observe = options.observe;
|
|
68
|
+
async function request(operation, path, init = {}, session) {
|
|
73
69
|
const method = (init.method ?? "GET").toUpperCase();
|
|
70
|
+
const startedAt = Date.now();
|
|
71
|
+
let attempts = 0;
|
|
72
|
+
let status = 0;
|
|
73
|
+
let requestId = "";
|
|
74
|
+
let outcome = "network_error";
|
|
74
75
|
const headers = new Headers(init.headers);
|
|
75
76
|
// The channel token authenticates the APP. A customer is a SECOND,
|
|
76
77
|
// separate credential — Authorization is already spoken for, so the
|
|
@@ -81,100 +82,120 @@ export function createChannelClient(options) {
|
|
|
81
82
|
if (init.body !== undefined && !headers.has("Content-Type"))
|
|
82
83
|
headers.set("Content-Type", "application/json");
|
|
83
84
|
const requestInit = { ...init, method, headers };
|
|
84
|
-
//
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
// orders from another's render. The guarantee lives here, in the library, so
|
|
88
|
-
// an app cannot lose it by constructing the client the obvious way.
|
|
89
|
-
if (method === "GET" && !session && cachePolicy !== "no-store") {
|
|
90
|
-
requestInit.next = { revalidate: cachePolicy.revalidate, ...(cachePolicy.tags ? { tags: cachePolicy.tags } : {}) };
|
|
91
|
-
}
|
|
92
|
-
else {
|
|
85
|
+
// Private reads and every mutation are non-cacheable in every runtime. An
|
|
86
|
+
// adapter may add framework caching only to anonymous GET requests.
|
|
87
|
+
if (method !== "GET" || session) {
|
|
93
88
|
requestInit.cache = "no-store";
|
|
94
89
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
try {
|
|
104
|
-
response = await fetcher(`${baseUrl}/api/v1/channel${path}`, { ...requestInit, signal: controller.signal });
|
|
105
|
-
}
|
|
106
|
-
catch (error) {
|
|
107
|
-
if (controller.signal.aborted) {
|
|
108
|
-
const code = init.signal?.aborted ? "channel_request_aborted" : "channel_request_timeout";
|
|
109
|
-
throw new ChannelAPIError(code === "channel_request_timeout" ? "Channel API request timed out" : "Channel API request aborted", 0, code, "");
|
|
90
|
+
try {
|
|
91
|
+
let response;
|
|
92
|
+
for (let attempt = 0; attempt <= retryAttempts; attempt += 1) {
|
|
93
|
+
attempts = attempt + 1;
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
96
|
+
try {
|
|
97
|
+
response = await fetcher(`${baseUrl}/api/v1/channel${path}`, { ...requestInit, signal: controller.signal });
|
|
110
98
|
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (controller.signal.aborted) {
|
|
101
|
+
outcome = "timeout";
|
|
102
|
+
throw new ChannelAPIError("Channel API request timed out", 0, "channel_request_timeout", "");
|
|
103
|
+
}
|
|
104
|
+
outcome = "network_error";
|
|
105
|
+
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
clearTimeout(timeout);
|
|
109
|
+
}
|
|
110
|
+
if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
|
|
111
|
+
break;
|
|
112
|
+
await wait(retryDelay(response, maxRetryDelayMs));
|
|
113
|
+
}
|
|
114
|
+
if (!response)
|
|
111
115
|
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
116
|
+
status = response.status;
|
|
117
|
+
requestId = response.headers.get("X-Request-ID") ?? "";
|
|
118
|
+
if (!response.ok) {
|
|
119
|
+
const payload = (await response.json().catch(() => ({})));
|
|
120
|
+
requestId = typeof payload.request_id === "string" ? payload.request_id : requestId;
|
|
121
|
+
outcome = "api_error";
|
|
122
|
+
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);
|
|
112
123
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
124
|
+
try {
|
|
125
|
+
const payload = (await response.json());
|
|
126
|
+
outcome = "success";
|
|
127
|
+
return payload;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
outcome = "invalid_response";
|
|
131
|
+
throw new ChannelAPIError("Channel API response was not valid JSON", response.status, "invalid_channel_response", requestId);
|
|
116
132
|
}
|
|
117
|
-
if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
|
|
118
|
-
break;
|
|
119
|
-
await wait(retryDelay(response, maxRetryDelayMs));
|
|
120
|
-
}
|
|
121
|
-
if (!response)
|
|
122
|
-
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
123
|
-
if (!response.ok) {
|
|
124
|
-
const payload = (await response.json().catch(() => ({})));
|
|
125
|
-
throw new ChannelAPIError(typeof payload.message === "string" ? payload.message : "Channel API request failed", response.status, typeof payload.code === "string" ? payload.code : "channel_request_failed", typeof payload.request_id === "string" ? payload.request_id : response.headers.get("X-Request-ID") ?? "");
|
|
126
|
-
}
|
|
127
|
-
try {
|
|
128
|
-
return (await response.json());
|
|
129
133
|
}
|
|
130
|
-
|
|
131
|
-
|
|
134
|
+
finally {
|
|
135
|
+
if (observe) {
|
|
136
|
+
try {
|
|
137
|
+
observe({ operation, method, outcome, status, requestId, durationMs: Math.max(0, Date.now() - startedAt), attempts });
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// Telemetry must never become part of the request's availability path.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
132
143
|
}
|
|
133
144
|
}
|
|
134
145
|
function mutationHeaders(mutation) {
|
|
135
146
|
return mutation?.idempotencyKey ? { "Idempotency-Key": mutation.idempotencyKey } : undefined;
|
|
136
147
|
}
|
|
137
148
|
return {
|
|
149
|
+
/**
|
|
150
|
+
* Verify the channel token and see what it points at.
|
|
151
|
+
*
|
|
152
|
+
* The cheapest call on the door — it does no database work server-side. Use
|
|
153
|
+
* it as a deployment health check: a 200 means C1M_CHANNEL_TOKEN is right and
|
|
154
|
+
* aimed at the workspace you expect. A ChannelAPIError with status 401 means
|
|
155
|
+
* the token is bad, revoked, or the channel is disabled (the door will not
|
|
156
|
+
* say which). A 503 means C1M is unavailable — NOT that your token is wrong.
|
|
157
|
+
*/
|
|
158
|
+
ping: () => request("channel.ping", "/ping"),
|
|
138
159
|
assetUrl: (pathOrUrl) => new URL(required(pathOrUrl, "asset URL"), `${baseUrl}/`).toString(),
|
|
139
160
|
site: {
|
|
140
|
-
resolve: (params = {}) => request(appendQuery("/site/resolve", params)),
|
|
161
|
+
resolve: (params = {}) => request("channel.site.resolve", appendQuery("/site/resolve", params)),
|
|
141
162
|
},
|
|
142
163
|
init: {
|
|
143
|
-
get: () => request("/init"),
|
|
144
|
-
light: () => request("/init/light"),
|
|
164
|
+
get: () => request("channel.init.get", "/init"),
|
|
165
|
+
light: () => request("channel.init.light", "/init/light"),
|
|
145
166
|
},
|
|
146
167
|
pages: {
|
|
147
|
-
list: (params = {}) => request(appendQuery("/pages", params)),
|
|
148
|
-
get: (slug) => request(`/pages/${encodePath(slug)}`),
|
|
168
|
+
list: (params = {}) => request("content.pages.public.list.channel", appendQuery("/pages", params)),
|
|
169
|
+
get: (slug) => request("content.pages.public.get.channel", `/pages/${encodePath(slug)}`),
|
|
149
170
|
},
|
|
150
171
|
products: {
|
|
151
|
-
list: (params = {}) => request(appendQuery("/products", params)),
|
|
152
|
-
get: (slug) => request(`/products/${encodePath(slug)}`),
|
|
153
|
-
media: (slug) => request(`/products/${encodePath(slug)}/media`),
|
|
172
|
+
list: (params = {}) => request("shop.public.products.list.channel", appendQuery("/products", params)),
|
|
173
|
+
get: (slug) => request("shop.public.products.get.channel", `/products/${encodePath(slug)}`),
|
|
174
|
+
media: (slug) => request("shop.public.products.media.channel", `/products/${encodePath(slug)}/media`),
|
|
154
175
|
},
|
|
155
176
|
reviews: {
|
|
156
|
-
list: (params = {}) => request(appendQuery("/reviews", params)),
|
|
157
|
-
summary: () => request("/reviews/summary"),
|
|
158
|
-
submit: (input, mutation) => request("/reviews", {
|
|
177
|
+
list: (params = {}) => request("reviews.public.list.channel", appendQuery("/reviews", params)),
|
|
178
|
+
summary: () => request("reviews.public.summary.channel", "/reviews/summary"),
|
|
179
|
+
submit: (input, mutation) => request("reviews.public.submit.channel", "/reviews", {
|
|
159
180
|
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
160
181
|
}),
|
|
161
182
|
},
|
|
162
183
|
theme: {
|
|
163
|
-
get: () => request("/theme"),
|
|
184
|
+
get: () => request("channel.theme.get", "/theme"),
|
|
164
185
|
},
|
|
165
186
|
menus: {
|
|
166
|
-
get: (handle) => request(`/menus/${encodePath(handle)}`),
|
|
187
|
+
get: (handle) => request("channel.menus.get", `/menus/${encodePath(handle)}`),
|
|
167
188
|
},
|
|
168
189
|
blog: {
|
|
169
|
-
get: (slug) => request(`/blog/posts/${encodePath(slug)}`),
|
|
190
|
+
get: (slug) => request("channel.blog.get", `/blog/posts/${encodePath(slug)}`),
|
|
170
191
|
},
|
|
171
192
|
// Customer sign-in. These are anonymous calls — they CREATE a session.
|
|
172
193
|
auth: {
|
|
173
|
-
check: (email) => request("/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
|
|
174
|
-
signup: (input) => request("/auth/signup", { method: "POST", body: JSON.stringify(input) }),
|
|
175
|
-
sendCode: (email) => request("/auth/send-code", { method: "POST", body: JSON.stringify({ email }) }),
|
|
176
|
-
verifyCode: (input) => request("/auth/verify-code", { method: "POST", body: JSON.stringify(input) }),
|
|
177
|
-
refresh: (refreshToken) => request("/auth/refresh", { method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) }),
|
|
194
|
+
check: (email) => request("channel.auth.check", "/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
|
|
195
|
+
signup: (input) => request("channel.auth.signup", "/auth/signup", { method: "POST", body: JSON.stringify(input) }),
|
|
196
|
+
sendCode: (email) => request("channel.auth.send_code", "/auth/send-code", { method: "POST", body: JSON.stringify({ email }) }),
|
|
197
|
+
verifyCode: (input) => request("channel.auth.verify_code", "/auth/verify-code", { method: "POST", body: JSON.stringify(input) }),
|
|
198
|
+
refresh: (refreshToken) => request("channel.auth.refresh", "/auth/refresh", { method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) }),
|
|
178
199
|
},
|
|
179
200
|
/**
|
|
180
201
|
* Scope calls to a signed-in customer.
|
|
@@ -190,18 +211,18 @@ export function createChannelClient(options) {
|
|
|
190
211
|
withCustomer(session) {
|
|
191
212
|
const customerSession = required(session, "session");
|
|
192
213
|
return {
|
|
193
|
-
me: () => request("/auth/me", {}, customerSession),
|
|
194
|
-
updateProfile: (input) => request("/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
|
|
195
|
-
logout: () => request("/auth/logout", { method: "POST" }, customerSession),
|
|
214
|
+
me: () => request("channel.auth.me", "/auth/me", {}, customerSession),
|
|
215
|
+
updateProfile: (input) => request("channel.auth.me.update", "/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
|
|
216
|
+
logout: () => request("channel.auth.logout", "/auth/logout", { method: "POST" }, customerSession),
|
|
196
217
|
orders: {
|
|
197
|
-
list: (params = {}) => request(appendQuery("/account/orders", params), {}, customerSession),
|
|
198
|
-
summary: () => request("/account/orders/summary", {}, customerSession),
|
|
199
|
-
get: (orderId) => request(`/account/orders/${encodePath(orderId)}`, {}, customerSession),
|
|
218
|
+
list: (params = {}) => request("channel.account.orders.list", appendQuery("/account/orders", params), {}, customerSession),
|
|
219
|
+
summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
|
|
220
|
+
get: (orderId) => request("channel.account.orders.get", `/account/orders/${encodePath(orderId)}`, {}, customerSession),
|
|
200
221
|
},
|
|
201
222
|
};
|
|
202
223
|
},
|
|
203
224
|
leads: {
|
|
204
|
-
create: (input, mutation) => request("/leads", {
|
|
225
|
+
create: (input, mutation) => request("growth.public_workspace.leads.capture.channel", "/leads", {
|
|
205
226
|
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
206
227
|
}),
|
|
207
228
|
},
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { type CreateChannelClientOptions } from "./index.js";
|
|
3
|
+
export type NextChannelCachePolicy = "no-store" | {
|
|
4
|
+
revalidate: number;
|
|
5
|
+
tags?: string[];
|
|
6
|
+
};
|
|
7
|
+
export interface CreateNextChannelClientOptions extends Omit<CreateChannelClientOptions, "fetch"> {
|
|
8
|
+
fetch?: typeof globalThis.fetch;
|
|
9
|
+
cache?: NextChannelCachePolicy;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Build the Channel API client with Next.js Data Cache semantics.
|
|
13
|
+
*
|
|
14
|
+
* Only anonymous GETs may receive `next.revalidate`; customer-scoped reads and
|
|
15
|
+
* mutations are forced to `no-store` by both this adapter and the core client.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createNextChannelClient(options: CreateNextChannelClientOptions): {
|
|
18
|
+
readonly ping: () => Promise<import("./types.js").ChannelPing>;
|
|
19
|
+
readonly assetUrl: (pathOrUrl: string) => string;
|
|
20
|
+
readonly site: {
|
|
21
|
+
readonly resolve: (params?: import("./index.js").ChannelSiteResolveParams) => Promise<import("./types.js").SiteDocument>;
|
|
22
|
+
};
|
|
23
|
+
readonly init: {
|
|
24
|
+
readonly get: () => Promise<import("./types.js").PublicWorkspaceInit>;
|
|
25
|
+
readonly light: () => Promise<import("./types.js").LightInitResponse>;
|
|
26
|
+
};
|
|
27
|
+
readonly pages: {
|
|
28
|
+
readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").PublicPageSummary>>;
|
|
29
|
+
readonly get: (slug: string) => Promise<{
|
|
30
|
+
page: import("./types.js").PublicPage;
|
|
31
|
+
}>;
|
|
32
|
+
};
|
|
33
|
+
readonly products: {
|
|
34
|
+
readonly list: (params?: import("./index.js").ChannelProductListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Product>>;
|
|
35
|
+
readonly get: (slug: string) => Promise<{
|
|
36
|
+
product: import("./types.js").Product;
|
|
37
|
+
}>;
|
|
38
|
+
readonly media: (slug: string) => Promise<import("./types.js").ListResponse<import("./types.js").ProductAsset>>;
|
|
39
|
+
};
|
|
40
|
+
readonly reviews: {
|
|
41
|
+
readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Review>>;
|
|
42
|
+
readonly summary: () => Promise<import("./types.js").ReviewSummaryResponse>;
|
|
43
|
+
readonly submit: (input: import("./types.js").PublicSubmitReviewInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
|
|
44
|
+
message: string;
|
|
45
|
+
}>;
|
|
46
|
+
};
|
|
47
|
+
readonly theme: {
|
|
48
|
+
readonly get: () => Promise<import("./types.js").ThemeResponse>;
|
|
49
|
+
};
|
|
50
|
+
readonly menus: {
|
|
51
|
+
readonly get: (handle: string) => Promise<import("./types.js").MenuResponse>;
|
|
52
|
+
};
|
|
53
|
+
readonly blog: {
|
|
54
|
+
readonly get: (slug: string) => Promise<import("./types.js").BlogPostResponse>;
|
|
55
|
+
};
|
|
56
|
+
readonly auth: {
|
|
57
|
+
readonly check: (email: string) => Promise<{
|
|
58
|
+
exists: boolean;
|
|
59
|
+
}>;
|
|
60
|
+
readonly signup: (input: {
|
|
61
|
+
email: string;
|
|
62
|
+
name: string;
|
|
63
|
+
phone?: string;
|
|
64
|
+
}) => Promise<import("./types.js").CustomerSignupResponse>;
|
|
65
|
+
readonly sendCode: (email: string) => Promise<import("./types.js").SendCodeResponse>;
|
|
66
|
+
readonly verifyCode: (input: {
|
|
67
|
+
email: string;
|
|
68
|
+
code: string;
|
|
69
|
+
}) => Promise<import("./types.js").CustomerSession>;
|
|
70
|
+
readonly refresh: (refreshToken: string) => Promise<import("./types.js").CustomerSession>;
|
|
71
|
+
};
|
|
72
|
+
readonly withCustomer: (session: string) => {
|
|
73
|
+
readonly me: () => Promise<import("./types.js").CustomerResponse>;
|
|
74
|
+
readonly updateProfile: (input: {
|
|
75
|
+
name?: string;
|
|
76
|
+
phone?: string;
|
|
77
|
+
}) => Promise<import("./types.js").CustomerResponse>;
|
|
78
|
+
readonly logout: () => Promise<{
|
|
79
|
+
status?: string;
|
|
80
|
+
}>;
|
|
81
|
+
readonly orders: {
|
|
82
|
+
readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Order>>;
|
|
83
|
+
readonly summary: () => Promise<{
|
|
84
|
+
summary: import("./types.js").OrderSummary;
|
|
85
|
+
}>;
|
|
86
|
+
readonly get: (orderId: string) => Promise<{
|
|
87
|
+
order: import("./types.js").Order;
|
|
88
|
+
}>;
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
readonly leads: {
|
|
92
|
+
readonly create: (input: import("./index.js").ChannelLeadInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
|
|
93
|
+
lead: import("./types.js").LeadResponse;
|
|
94
|
+
}>;
|
|
95
|
+
};
|
|
96
|
+
};
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient } from "./index.js";
|
|
3
|
+
function validateCachePolicy(policy) {
|
|
4
|
+
if (policy === "no-store")
|
|
5
|
+
return;
|
|
6
|
+
if (!Number.isFinite(policy.revalidate) || policy.revalidate < 0) {
|
|
7
|
+
throw new Error("cache.revalidate must be a non-negative finite number");
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Build the Channel API client with Next.js Data Cache semantics.
|
|
12
|
+
*
|
|
13
|
+
* Only anonymous GETs may receive `next.revalidate`; customer-scoped reads and
|
|
14
|
+
* mutations are forced to `no-store` by both this adapter and the core client.
|
|
15
|
+
*/
|
|
16
|
+
export function createNextChannelClient(options) {
|
|
17
|
+
const { cache = "no-store", fetch: suppliedFetch, ...coreOptions } = options;
|
|
18
|
+
validateCachePolicy(cache);
|
|
19
|
+
const fetcher = suppliedFetch ?? globalThis.fetch;
|
|
20
|
+
if (!fetcher)
|
|
21
|
+
throw new Error("fetch implementation is required");
|
|
22
|
+
const nextFetch = (input, init = {}) => {
|
|
23
|
+
const request = { ...init };
|
|
24
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
25
|
+
const customerScoped = new Headers(request.headers).has("X-End-User-Token");
|
|
26
|
+
if (method === "GET" && !customerScoped && cache !== "no-store") {
|
|
27
|
+
delete request.cache;
|
|
28
|
+
request.next = {
|
|
29
|
+
revalidate: cache.revalidate,
|
|
30
|
+
...(cache.tags ? { tags: cache.tags } : {}),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
delete request.next;
|
|
35
|
+
request.cache = "no-store";
|
|
36
|
+
}
|
|
37
|
+
return fetcher(input, request);
|
|
38
|
+
};
|
|
39
|
+
return createChannelClient({ ...coreOptions, fetch: nextFetch });
|
|
40
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -41,21 +41,36 @@ export interface LightInitResponse {
|
|
|
41
41
|
etag?: string;
|
|
42
42
|
}
|
|
43
43
|
export interface PublicPageSummary {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
id: string;
|
|
45
|
+
saas_app: string;
|
|
46
|
+
workspace_id: string;
|
|
47
|
+
source: string;
|
|
48
|
+
route_kind: string;
|
|
49
|
+
route_pattern: string;
|
|
47
50
|
slug: string;
|
|
48
51
|
title: string;
|
|
52
|
+
status: string;
|
|
53
|
+
status_reason: string;
|
|
49
54
|
visibility: "hidden" | "visible";
|
|
55
|
+
edit_mode: string;
|
|
56
|
+
draft_revision: number;
|
|
57
|
+
created_at: string;
|
|
58
|
+
updated_at: string;
|
|
50
59
|
}
|
|
51
60
|
export interface PublicPage extends PublicPageSummary {
|
|
52
|
-
|
|
53
|
-
|
|
61
|
+
owner_app?: string;
|
|
62
|
+
required_apps?: string[];
|
|
63
|
+
required_features?: string[];
|
|
54
64
|
seo_title?: string;
|
|
55
65
|
seo_description?: string;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
66
|
+
draft_state?: unknown;
|
|
67
|
+
layout_state?: unknown;
|
|
68
|
+
published_at?: string;
|
|
69
|
+
manifest_key?: string;
|
|
70
|
+
manifest_version?: number;
|
|
71
|
+
template_key?: string;
|
|
72
|
+
theme_id?: string;
|
|
73
|
+
default_shell_template_id?: string;
|
|
59
74
|
}
|
|
60
75
|
export interface Product {
|
|
61
76
|
id: string;
|
|
@@ -265,3 +280,10 @@ export interface OrderSummary {
|
|
|
265
280
|
total_orders: number;
|
|
266
281
|
[key: string]: unknown;
|
|
267
282
|
}
|
|
283
|
+
/** What the door reports about the token you just used. */
|
|
284
|
+
export interface ChannelPing {
|
|
285
|
+
channel_id: string;
|
|
286
|
+
workspace_id: string;
|
|
287
|
+
saas_app: string;
|
|
288
|
+
api_version: string;
|
|
289
|
+
}
|
package/dist/webhooks.d.ts
CHANGED
package/dist/webhooks.js
CHANGED
package/package.json
CHANGED
|
@@ -1,15 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@c1m-public/channel-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"description": "
|
|
6
|
+
"description": "Typed server-side client for the MML headless Channel API",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/cloud1mediaLtd/mml-js.git",
|
|
10
|
+
"directory": "packages/channel-client"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cloud1mediaLtd/mml-js/tree/main/packages/channel-client",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/cloud1mediaLtd/mml-js/issues"
|
|
15
|
+
},
|
|
7
16
|
"main": "./dist/index.js",
|
|
8
17
|
"types": "./dist/index.d.ts",
|
|
9
18
|
"exports": {
|
|
10
19
|
".": {
|
|
11
20
|
"types": "./dist/index.d.ts",
|
|
12
21
|
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./next": {
|
|
24
|
+
"types": "./dist/next.d.ts",
|
|
25
|
+
"default": "./dist/next.js"
|
|
26
|
+
},
|
|
27
|
+
"./webhooks": {
|
|
28
|
+
"types": "./dist/webhooks.d.ts",
|
|
29
|
+
"default": "./dist/webhooks.js"
|
|
13
30
|
}
|
|
14
31
|
},
|
|
15
32
|
"files": [
|