@spillway-cms/client 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Accorbis
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @spillway-cms/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed, dependency-free fetch client for the [Spillway CMS](https://github.com/kwall-llc/spillway-cms) public content API. Runs in Node 18+, edge runtimes and browsers. MIT licensed.
4
+
5
+ ```ts
6
+ import { createClient } from '@spillway-cms/client';
7
+
8
+ const spillway = createClient({ baseUrl: 'https://cms.example.org' });
9
+ const page = await spillway.render('/about'); // resolved blocks, SEO, menus, cache tags
10
+ const posts = await spillway.collection('stories', { filters: [{ field: 'category', op: 'eq', value: 'news' }] });
11
+ const menu = await spillway.menu('main', { path: '/about' });
12
+ ```
13
+
14
+ - `render`, `page`, `entity`, `collection`, `menu`, `site`, `search`, `media`, `paths`; errors are `SpillwayError` with the API's status and code.
15
+ - Previews: `previewFromRequest(req)` reads a release share link (`?release=&token=`, or the former `?workstream=`) or the `spillway_preview` cookie; `client.withPreview(state)` sends it.
16
+ - `@spillway-cms/client/webhook`: `readWebhook(request, secret)` verifies Spillway's signed publish webhooks with Web Crypto; `affectedByWebhook(payload)` lists the paths and cache tags to purge.
17
+
18
+ Full documentation: `docs/adapters.md` and `docs/api.md` ("Headless") in the Spillway repository.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @spillway-cms/client: a typed fetch client for the Spillway CMS public content API.
3
+ *
4
+ * Dependency-free: `fetch`, `URL` and `Headers` are all it uses, so it runs in Node 18+,
5
+ * edge runtimes and browsers. Every method returns the JSON the server sends, typed with
6
+ * the contract in `@spillway-cms/shared`; errors are `SpillwayError`s carrying the status and
7
+ * the API error code. The endpoints are documented in docs/api.md ("Headless") and the
8
+ * adapters that build on this client in docs/adapters.md.
9
+ */
10
+ import type { CollectionFilter, CollectionItem, Entity, MediaItem, Paginated, PublicMenu, PublicPath, PublicRender, PublicSite, SearchResponse } from '@spillway-cms/shared';
11
+ export type { CollectionFilter, CollectionItem, Entity, MediaItem, Paginated, PublicMenu, PublicMenuItem, PublicPath, PublicPathsResponse, PublicRender, PublicSeo, PublicSite, PuckData, SearchResponse, SearchResult, WebhookPayload, WebhookEntity, } from '@spillway-cms/shared';
12
+ /** The cookie the preview helpers read and set (`workstream=<id>&token=<share token>`, URL-encoded). */
13
+ export declare const PREVIEW_COOKIE = "spillway_preview";
14
+ export declare const WORKSTREAM_HEADER = "x-spillway-workstream";
15
+ export declare const SITE_HEADER = "x-spillway-site";
16
+ export declare const PREVIEW_TOKEN_QUERY = "token";
17
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
18
+ export interface ClientOptions {
19
+ /** The Spillway origin, e.g. `https://cms.example.org` (a trailing slash is fine). */
20
+ baseUrl: string;
21
+ /** An API token (`spw_...`). Needed for previews (content.view_drafts) and to pick a site with `site`; never ship it to a browser. */
22
+ token?: string;
23
+ /** Multisite: the site id or key to read, sent as X-Spillway-Site (honoured for a token that may open that site). */
24
+ site?: string;
25
+ /** Narrow reads to one locale (`?locale=`); paths with a locale prefix win over it. */
26
+ locale?: string;
27
+ /**
28
+ * Read inside a release, by id or key; needs `token` with content.view_drafts or a share-link `previewToken`. Sent as
29
+ * X-Spillway-Workstream, the header's former name, which every Spillway version accepts (newer ones also read X-Spillway-Release).
30
+ */
31
+ workstream?: string;
32
+ /** A release share-link token (`?token=`), the stakeholder preview credential. */
33
+ previewToken?: string;
34
+ /** Render the latest revision of any status (`?preview=1`); needs an API token with content.view_drafts. */
35
+ preview?: boolean;
36
+ /** The fetch to use: Next's tagged fetch, an in-process Hono app in tests, a retrying wrapper. Defaults to the global one. */
37
+ fetch?: FetchLike;
38
+ /** Extra headers on every request. */
39
+ headers?: Record<string, string>;
40
+ /** Extra fields merged into every RequestInit (for example Next's `next: { revalidate }`). */
41
+ requestInit?: RequestInit & Record<string, unknown>;
42
+ }
43
+ /** What a preview helper extracts from a request: the release to read (`workstream`) and the credential that allows it. */
44
+ export interface PreviewState {
45
+ workstream?: string;
46
+ token?: string;
47
+ preview?: boolean;
48
+ }
49
+ export interface RequestOptions {
50
+ /** Query parameters to add. Arrays repeat the key. */
51
+ query?: Record<string, string | number | boolean | undefined | null | (string | number)[]>;
52
+ /** Per-call fields merged into the RequestInit after the client's own. */
53
+ init?: RequestInit & Record<string, unknown>;
54
+ signal?: AbortSignal;
55
+ }
56
+ export interface RenderOptions extends RequestOptions {
57
+ /** Query parameters the page's blocks read (exposed filters, `page`, `month`). */
58
+ params?: Record<string, string | number | undefined>;
59
+ locale?: string;
60
+ /** Preview credentials for this call only (what `previewFromRequest` returns). */
61
+ previewState?: PreviewState | null;
62
+ }
63
+ export interface CollectionOptions extends RequestOptions {
64
+ /** Extra filters applied on top of the collection's saved ones (max 20). */
65
+ filters?: CollectionFilter[];
66
+ page?: number;
67
+ limit?: number;
68
+ locale?: string;
69
+ /** Keyword search within the collection. */
70
+ q?: string;
71
+ }
72
+ export interface SearchOptions extends RequestOptions {
73
+ type?: string;
74
+ term?: string;
75
+ locale?: string;
76
+ page?: number;
77
+ limit?: number;
78
+ }
79
+ export interface MenuOptions extends RequestOptions {
80
+ locale?: string;
81
+ /** The page being rendered, so the matching item is marked `current`. */
82
+ path?: string;
83
+ }
84
+ export interface PathsOptions extends RequestOptions {
85
+ type?: string;
86
+ locale?: string;
87
+ }
88
+ /** The response with the headers the caching layers care about. */
89
+ export interface Result<T> {
90
+ data: T;
91
+ response: Response;
92
+ /** The server's `Cache-Tag` header split into tags (`entity:<id>`, `type:<key>`, `site:<id>`, `collection:<id>`, `menu:<key>`, ...). */
93
+ cacheTags: string[];
94
+ }
95
+ export declare class SpillwayError extends Error {
96
+ readonly status: number;
97
+ readonly code: string;
98
+ readonly details: unknown;
99
+ readonly url: string;
100
+ constructor(status: number, code: string, message: string, url: string, details?: unknown);
101
+ get isNotFound(): boolean;
102
+ }
103
+ /** The tags in a `Cache-Tag` header, or none. */
104
+ export declare function cacheTagsOf(response: Response | Headers): string[];
105
+ export declare class SpillwayClient {
106
+ readonly options: Readonly<ClientOptions>;
107
+ readonly baseUrl: string;
108
+ private readonly fetchImpl;
109
+ constructor(options: ClientOptions);
110
+ /** A client with some options changed (a locale, a release, a preview credential), sharing the rest. */
111
+ with(overrides: Partial<ClientOptions>): SpillwayClient;
112
+ /** The same client reading what a preview request asked for (see `previewFromRequest`). */
113
+ withPreview(state: PreviewState | null | undefined): SpillwayClient;
114
+ /** An absolute URL on the Spillway origin for a site path or a relative media URL. */
115
+ url(path: string): string;
116
+ /**
117
+ * The page at a public path as resolved data: the published snapshot, every block's server-resolved props, SEO, menus,
118
+ * the site and the cache tags. `/`, `/about`, `/es/about` and query parameters for exposed filters all work.
119
+ */
120
+ render(path: string, opts?: RenderOptions): Promise<PublicRender>;
121
+ renderWithResponse(path: string, opts?: RenderOptions): Promise<Result<PublicRender>>;
122
+ /**
123
+ * The entity at a public path (`GET /api/entities/by-path`): the published snapshot for a visitor, the latest draft for a
124
+ * token with content.view_drafts. Prefer `render()` for pages; this is the raw record.
125
+ */
126
+ page(path: string, opts?: RequestOptions & {
127
+ locale?: string;
128
+ }): Promise<Entity>;
129
+ /** One published entity by id or slug. */
130
+ entity(type: string, idOrSlug: string, opts?: RequestOptions & {
131
+ locale?: string;
132
+ }): Promise<Entity>;
133
+ /** The items of a saved collection (by key or id), with optional extra filters, keyword and paging. */
134
+ collection(key: string, opts?: CollectionOptions): Promise<Paginated<CollectionItem>>;
135
+ /** A menu resolved to links (`main`, `footer` or any key). */
136
+ menu(key: string, opts?: MenuOptions): Promise<PublicMenu>;
137
+ /** The visitor-safe site settings: name, locales, home page, theme (and the theme as CSS), SEO defaults, origin. */
138
+ site(opts?: RequestOptions): Promise<PublicSite>;
139
+ /** Site search over published content. */
140
+ search(q: string, opts?: SearchOptions): Promise<SearchResponse>;
141
+ /** A media item with absolute URLs (the file itself is at `item.url`). */
142
+ media(id: string, opts?: RequestOptions): Promise<MediaItem>;
143
+ /** Every published public path, for static builds. */
144
+ paths(opts?: PathsOptions): Promise<PublicPath[]>;
145
+ /** Builds the request the client would send: URL (with the client's locale, preview and token parameters) and init. */
146
+ prepare(path: string, opts?: RequestOptions): {
147
+ url: string;
148
+ init: RequestInit;
149
+ };
150
+ /** A GET against the API with the client's auth, site, release and preview settings; JSON in, typed JSON out. */
151
+ request<T>(path: string, opts?: RequestOptions): Promise<Result<T>>;
152
+ }
153
+ export declare function createClient(options: ClientOptions): SpillwayClient;
154
+ interface CookieReader {
155
+ get(name: string): {
156
+ value: string;
157
+ } | string | undefined | null;
158
+ }
159
+ /** What `previewFromRequest` accepts: a Fetch `Request`, Next's `cookies()`/`headers()` stores, Astro's `Astro` global, or plain parts. */
160
+ export interface PreviewSource {
161
+ url?: string | URL;
162
+ headers?: Headers | Record<string, string | string[] | undefined>;
163
+ cookies?: CookieReader;
164
+ /** Next's draftMode().isEnabled, or any flag that says "this is a preview session". */
165
+ draft?: boolean;
166
+ }
167
+ /** Serialises a preview state for the `spillway_preview` cookie (the value only; set path, httpOnly and sameSite yourself). */
168
+ export declare function previewCookieValue(state: PreviewState): string;
169
+ export declare function parsePreviewCookie(value: string | undefined | null): PreviewState | null;
170
+ /**
171
+ * Reads the preview credentials a request carries: `?release=&token=` (or the former `?workstream=`; a share link opened on the front end, or
172
+ * `?preview=1`), else the `spillway_preview` cookie set by the preview route. Null for an ordinary visitor. Pass the
173
+ * result to `client.withPreview()` or `client.render(path, { previewState })`.
174
+ */
175
+ export declare function previewFromRequest(req: Request | PreviewSource): PreviewState | null;
package/dist/index.js ADDED
@@ -0,0 +1,304 @@
1
+ /** The cookie the preview helpers read and set (`workstream=<id>&token=<share token>`, URL-encoded). */
2
+ export const PREVIEW_COOKIE = 'spillway_preview';
3
+ export const WORKSTREAM_HEADER = 'x-spillway-workstream';
4
+ export const SITE_HEADER = 'x-spillway-site';
5
+ export const PREVIEW_TOKEN_QUERY = 'token';
6
+ const PUBLIC_PREFIX = '/api/public';
7
+ export class SpillwayError extends Error {
8
+ status;
9
+ code;
10
+ details;
11
+ url;
12
+ constructor(status, code, message, url, details) {
13
+ super(message);
14
+ this.name = 'SpillwayError';
15
+ this.status = status;
16
+ this.code = code;
17
+ this.details = details;
18
+ this.url = url;
19
+ }
20
+ get isNotFound() {
21
+ return this.status === 404;
22
+ }
23
+ }
24
+ /** The tags in a `Cache-Tag` header, or none. */
25
+ export function cacheTagsOf(response) {
26
+ const headers = response instanceof Headers ? response : response.headers;
27
+ const raw = headers.get('cache-tag') ?? '';
28
+ return raw
29
+ .split(',')
30
+ .map((t) => t.trim())
31
+ .filter(Boolean);
32
+ }
33
+ function normalisePath(path) {
34
+ let p = (path || '/').replace(/\/{2,}/g, '/');
35
+ if (!p.startsWith('/'))
36
+ p = '/' + p;
37
+ if (p.length > 1 && p.endsWith('/'))
38
+ p = p.slice(0, -1);
39
+ return p;
40
+ }
41
+ function encodePath(path) {
42
+ return normalisePath(path)
43
+ .split('/')
44
+ .map((seg) => encodeURIComponent(seg))
45
+ .join('/');
46
+ }
47
+ function isPlainObject(v) {
48
+ return !!v && typeof v === 'object' && !Array.isArray(v);
49
+ }
50
+ export class SpillwayClient {
51
+ options;
52
+ baseUrl;
53
+ fetchImpl;
54
+ constructor(options) {
55
+ if (!options || typeof options.baseUrl !== 'string' || !options.baseUrl)
56
+ throw new TypeError('createClient: baseUrl is required');
57
+ this.options = Object.freeze({ ...options });
58
+ this.baseUrl = options.baseUrl.replace(/\/+$/, '');
59
+ const f = options.fetch ?? (typeof fetch === 'function' ? fetch : undefined);
60
+ if (!f)
61
+ throw new TypeError('createClient: no fetch available; pass one in options.fetch');
62
+ this.fetchImpl = f;
63
+ }
64
+ /** A client with some options changed (a locale, a release, a preview credential), sharing the rest. */
65
+ with(overrides) {
66
+ return new SpillwayClient({ ...this.options, ...overrides });
67
+ }
68
+ /** The same client reading what a preview request asked for (see `previewFromRequest`). */
69
+ withPreview(state) {
70
+ if (!state)
71
+ return this;
72
+ return this.with({ workstream: state.workstream ?? this.options.workstream, previewToken: state.token ?? this.options.previewToken, preview: state.preview ?? this.options.preview });
73
+ }
74
+ /** An absolute URL on the Spillway origin for a site path or a relative media URL. */
75
+ url(path) {
76
+ return `${this.baseUrl}${normalisePath(path)}`;
77
+ }
78
+ /**
79
+ * The page at a public path as resolved data: the published snapshot, every block's server-resolved props, SEO, menus,
80
+ * the site and the cache tags. `/`, `/about`, `/es/about` and query parameters for exposed filters all work.
81
+ */
82
+ render(path, opts = {}) {
83
+ return this.renderWithResponse(path, opts).then((r) => r.data);
84
+ }
85
+ async renderWithResponse(path, opts = {}) {
86
+ const client = opts.previewState ? this.withPreview(opts.previewState) : this;
87
+ const query = { ...(opts.params ?? {}), ...(opts.query ?? {}) };
88
+ if (opts.locale)
89
+ query.locale = opts.locale;
90
+ return client.request(`${PUBLIC_PREFIX}/render${encodePath(path)}`, { ...opts, query });
91
+ }
92
+ /**
93
+ * The entity at a public path (`GET /api/entities/by-path`): the published snapshot for a visitor, the latest draft for a
94
+ * token with content.view_drafts. Prefer `render()` for pages; this is the raw record.
95
+ */
96
+ page(path, opts = {}) {
97
+ return this.request('/api/entities/by-path', { ...opts, query: { path: normalisePath(path), ...(opts.locale ? { locale: opts.locale } : {}), ...(opts.query ?? {}) } }).then((r) => r.data);
98
+ }
99
+ /** One published entity by id or slug. */
100
+ entity(type, idOrSlug, opts = {}) {
101
+ return this.request(`${PUBLIC_PREFIX}/entities/${encodeURIComponent(type)}/${encodeURIComponent(idOrSlug)}`, { ...opts, query: { ...(opts.locale ? { locale: opts.locale } : {}), ...(opts.query ?? {}) } }).then((r) => r.data);
102
+ }
103
+ /** The items of a saved collection (by key or id), with optional extra filters, keyword and paging. */
104
+ collection(key, opts = {}) {
105
+ const query = { ...(opts.query ?? {}) };
106
+ if (opts.page)
107
+ query.page = opts.page;
108
+ if (opts.limit)
109
+ query.limit = opts.limit;
110
+ if (opts.locale)
111
+ query.locale = opts.locale;
112
+ if (opts.q)
113
+ query.q = opts.q;
114
+ if (opts.filters?.length)
115
+ query.filters = JSON.stringify(opts.filters);
116
+ return this.request(`${PUBLIC_PREFIX}/collections/${encodeURIComponent(key)}/items`, { ...opts, query }).then((r) => r.data);
117
+ }
118
+ /** A menu resolved to links (`main`, `footer` or any key). */
119
+ menu(key, opts = {}) {
120
+ return this.request(`${PUBLIC_PREFIX}/menus/${encodeURIComponent(key)}`, { ...opts, query: { ...(opts.locale ? { locale: opts.locale } : {}), ...(opts.path ? { path: normalisePath(opts.path) } : {}), ...(opts.query ?? {}) } }).then((r) => r.data);
121
+ }
122
+ /** The visitor-safe site settings: name, locales, home page, theme (and the theme as CSS), SEO defaults, origin. */
123
+ site(opts = {}) {
124
+ return this.request(`${PUBLIC_PREFIX}/site`, opts).then((r) => r.data);
125
+ }
126
+ /** Site search over published content. */
127
+ search(q, opts = {}) {
128
+ const query = { q, ...(opts.query ?? {}) };
129
+ for (const k of ['type', 'term', 'locale', 'page', 'limit'])
130
+ if (opts[k] !== undefined)
131
+ query[k] = opts[k];
132
+ return this.request('/api/search', { ...opts, query }).then((r) => r.data);
133
+ }
134
+ /** A media item with absolute URLs (the file itself is at `item.url`). */
135
+ media(id, opts = {}) {
136
+ return this.request(`${PUBLIC_PREFIX}/media/${encodeURIComponent(id)}`, opts).then((r) => r.data);
137
+ }
138
+ /** Every published public path, for static builds. */
139
+ paths(opts = {}) {
140
+ return this.request(`${PUBLIC_PREFIX}/paths`, { ...opts, query: { ...(opts.type ? { type: opts.type } : {}), ...(opts.locale ? { locale: opts.locale } : {}), ...(opts.query ?? {}) } }).then((r) => r.data.items);
141
+ }
142
+ /** Builds the request the client would send: URL (with the client's locale, preview and token parameters) and init. */
143
+ prepare(path, opts = {}) {
144
+ const url = new URL(`${this.baseUrl}${path}`);
145
+ for (const [k, v] of Object.entries(opts.query ?? {})) {
146
+ if (v === undefined || v === null)
147
+ continue;
148
+ if (Array.isArray(v))
149
+ for (const item of v)
150
+ url.searchParams.append(k, String(item));
151
+ else
152
+ url.searchParams.set(k, String(v));
153
+ }
154
+ if (this.options.locale && !url.searchParams.has('locale') && path.startsWith(PUBLIC_PREFIX))
155
+ url.searchParams.set('locale', this.options.locale);
156
+ if (this.options.preview)
157
+ url.searchParams.set('preview', '1');
158
+ if (this.options.previewToken)
159
+ url.searchParams.set(PREVIEW_TOKEN_QUERY, this.options.previewToken);
160
+ const headers = new Headers(this.options.headers ?? {});
161
+ headers.set('accept', 'application/json');
162
+ if (this.options.token)
163
+ headers.set('authorization', `Bearer ${this.options.token}`);
164
+ if (this.options.site)
165
+ headers.set(SITE_HEADER, this.options.site);
166
+ if (this.options.workstream)
167
+ headers.set(WORKSTREAM_HEADER, this.options.workstream);
168
+ const extra = new Headers(opts.init?.headers ?? {});
169
+ extra.forEach((v, k) => headers.set(k, v));
170
+ const init = { ...(this.options.requestInit ?? {}), ...(opts.init ?? {}), method: 'GET', headers };
171
+ if (opts.signal)
172
+ init.signal = opts.signal;
173
+ // `next: { tags }` style options merge rather than replace, so a per-call tag adds to the client's.
174
+ const a = this.options.requestInit?.next;
175
+ const b = opts.init?.next;
176
+ if (isPlainObject(a) && isPlainObject(b))
177
+ init.next = { ...a, ...b, ...(Array.isArray(a.tags) || Array.isArray(b.tags) ? { tags: [...new Set([...(a.tags ?? []), ...(b.tags ?? [])])] } : {}) };
178
+ return { url: url.toString(), init };
179
+ }
180
+ /** A GET against the API with the client's auth, site, release and preview settings; JSON in, typed JSON out. */
181
+ async request(path, opts = {}) {
182
+ const { url, init } = this.prepare(path, opts);
183
+ let response;
184
+ try {
185
+ response = await this.fetchImpl(url, init);
186
+ }
187
+ catch (err) {
188
+ throw new SpillwayError(0, 'network_error', `Could not reach ${this.baseUrl}: ${err instanceof Error ? err.message : String(err)}`, url);
189
+ }
190
+ if (!response.ok)
191
+ throw await errorFrom(response, url);
192
+ const data = (await response.json());
193
+ return { data, response, cacheTags: cacheTagsOf(response) };
194
+ }
195
+ }
196
+ async function errorFrom(response, url) {
197
+ let body = null;
198
+ try {
199
+ body = await response.json();
200
+ }
201
+ catch {
202
+ /* not JSON */
203
+ }
204
+ const err = isPlainObject(body) && isPlainObject(body.error) ? body.error : null;
205
+ const code = typeof err?.code === 'string' ? err.code : response.status === 404 ? 'not_found' : `http_${response.status}`;
206
+ const message = typeof err?.message === 'string' ? err.message : `${response.status} ${response.statusText}`.trim();
207
+ return new SpillwayError(response.status, code, message, url, err?.details);
208
+ }
209
+ export function createClient(options) {
210
+ return new SpillwayClient(options);
211
+ }
212
+ function headerValue(headers, name) {
213
+ if (!headers)
214
+ return undefined;
215
+ if (headers instanceof Headers)
216
+ return headers.get(name) ?? undefined;
217
+ const v = headers[name] ?? headers[name.toLowerCase()];
218
+ return Array.isArray(v) ? v[0] : v;
219
+ }
220
+ function cookieValue(src, name) {
221
+ if (src.cookies) {
222
+ const got = src.cookies.get(name);
223
+ if (typeof got === 'string')
224
+ return got;
225
+ if (got && typeof got === 'object' && typeof got.value === 'string')
226
+ return got.value;
227
+ }
228
+ const raw = headerValue(src.headers, 'cookie');
229
+ if (!raw)
230
+ return undefined;
231
+ for (const part of raw.split(';')) {
232
+ const [k, ...rest] = part.trim().split('=');
233
+ if (k === name) {
234
+ try {
235
+ return decodeURIComponent(rest.join('='));
236
+ }
237
+ catch {
238
+ return rest.join('=');
239
+ }
240
+ }
241
+ }
242
+ return undefined;
243
+ }
244
+ /** Serialises a preview state for the `spillway_preview` cookie (the value only; set path, httpOnly and sameSite yourself). */
245
+ export function previewCookieValue(state) {
246
+ const sp = new URLSearchParams();
247
+ if (state.workstream)
248
+ sp.set('workstream', state.workstream);
249
+ if (state.token)
250
+ sp.set('token', state.token);
251
+ if (state.preview)
252
+ sp.set('preview', '1');
253
+ return sp.toString();
254
+ }
255
+ export function parsePreviewCookie(value) {
256
+ if (!value)
257
+ return null;
258
+ const sp = new URLSearchParams(value);
259
+ const state = {};
260
+ const ws = sp.get('workstream');
261
+ const token = sp.get('token');
262
+ if (ws)
263
+ state.workstream = ws;
264
+ if (token)
265
+ state.token = token;
266
+ if (sp.get('preview') === '1')
267
+ state.preview = true;
268
+ return state.workstream || state.token || state.preview ? state : null;
269
+ }
270
+ /**
271
+ * Reads the preview credentials a request carries: `?release=&token=` (or the former `?workstream=`; a share link opened on the front end, or
272
+ * `?preview=1`), else the `spillway_preview` cookie set by the preview route. Null for an ordinary visitor. Pass the
273
+ * result to `client.withPreview()` or `client.render(path, { previewState })`.
274
+ */
275
+ export function previewFromRequest(req) {
276
+ const src = req instanceof Request ? { url: req.url, headers: req.headers } : req;
277
+ let url = null;
278
+ if (src.url) {
279
+ try {
280
+ url = src.url instanceof URL ? src.url : new URL(src.url, 'http://localhost');
281
+ }
282
+ catch {
283
+ url = null;
284
+ }
285
+ }
286
+ const fromQuery = {};
287
+ if (url) {
288
+ const ws = url.searchParams.get('release') ?? url.searchParams.get('workstream');
289
+ const token = url.searchParams.get(PREVIEW_TOKEN_QUERY);
290
+ if (ws)
291
+ fromQuery.workstream = ws;
292
+ if (token)
293
+ fromQuery.token = token;
294
+ if (url.searchParams.get('preview') === '1')
295
+ fromQuery.preview = true;
296
+ }
297
+ if (fromQuery.workstream || fromQuery.token || fromQuery.preview)
298
+ return fromQuery;
299
+ const fromCookie = parsePreviewCookie(cookieValue(src, PREVIEW_COOKIE));
300
+ if (fromCookie)
301
+ return fromCookie;
302
+ return src.draft ? { preview: true } : null;
303
+ }
304
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA2CA,wGAAwG;AACxG,MAAM,CAAC,MAAM,cAAc,GAAG,kBAAkB,CAAC;AACjD,MAAM,CAAC,MAAM,iBAAiB,GAAG,uBAAuB,CAAC;AACzD,MAAM,CAAC,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAC7C,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC;AAC3C,MAAM,aAAa,GAAG,aAAa,CAAC;AA0FpC,MAAM,OAAO,aAAc,SAAQ,KAAK;IAC7B,MAAM,CAAS;IACf,IAAI,CAAS;IACb,OAAO,CAAU;IACjB,GAAG,CAAS;IACrB,YAAY,MAAc,EAAE,IAAY,EAAE,OAAe,EAAE,GAAW,EAAE,OAAiB;QACvF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;QAC5B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IACD,IAAI,UAAU;Q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ACnF,MAAM,UAAU,GAAG,kBAAkB,CAAC,WAAW,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC;IACxE,IAAI,UAAU;QAAE,OAAO,UAAU,CAAC;IAClC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Webhook helpers for front ends that revalidate on Spillway's `entity.published`, `entity.unpublished` and
3
+ * `entity.deleted` notifications: HMAC-SHA256 verification over the raw body with Web Crypto (Node 18+, edge
4
+ * runtimes) and the payload shape. See docs/adapters.md and the Notifications section of docs/api.md.
5
+ */
6
+ import type { WebhookPayload } from '@spillway-cms/shared';
7
+ export type { WebhookPayload, WebhookEntity } from '@spillway-cms/shared';
8
+ export declare const SIGNATURE_HEADER = "x-spillway-signature";
9
+ export declare const EVENT_HEADER = "x-spillway-event";
10
+ export declare const DELIVERY_HEADER = "x-spillway-delivery";
11
+ /** The events a content webhook may carry; anything else is ignored by the revalidation handlers. */
12
+ export declare const CONTENT_EVENTS: readonly ["entity.published", "entity.unpublished", "entity.deleted"];
13
+ export type ContentEvent = (typeof CONTENT_EVENTS)[number];
14
+ /** `sha256=<hex HMAC-SHA256 of body>`, what the server sends in X-Spillway-Signature. */
15
+ export declare function signWebhookBody(body: string, secret: string): Promise<string>;
16
+ /** True when `signature` (the X-Spillway-Signature header) matches the raw body under `secret`. */
17
+ export declare function verifyWebhookSignature(body: string, signature: string | null | undefined, secret: string): Promise<boolean>;
18
+ export declare class WebhookError extends Error {
19
+ readonly status: number;
20
+ constructor(status: number, message: string);
21
+ }
22
+ /**
23
+ * Reads and verifies a webhook request: the method, the signature over the raw body and the JSON shape.
24
+ * Throws a `WebhookError` with the status to answer (405, 401, 400).
25
+ */
26
+ export declare function readWebhook(request: Request, secret: string): Promise<WebhookPayload>;
27
+ /**
28
+ * What a payload says should be purged: the public path of the entity and the server's cache tags
29
+ * (`entity:<id>`, `type:<key>`, `site:<id>`, `list:<type>`, `tgroup:<id>`). Test sends and other events give an empty result.
30
+ */
31
+ export declare function affectedByWebhook(payload: WebhookPayload): {
32
+ paths: string[];
33
+ tags: string[];
34
+ event: string;
35
+ test: boolean;
36
+ };
@@ -0,0 +1,78 @@
1
+ export const SIGNATURE_HEADER = 'x-spillway-signature';
2
+ export const EVENT_HEADER = 'x-spillway-event';
3
+ export const DELIVERY_HEADER = 'x-spillway-delivery';
4
+ /** The events a content webhook may carry; anything else is ignored by the revalidation handlers. */
5
+ export const CONTENT_EVENTS = ['entity.published', 'entity.unpublished', 'entity.deleted'];
6
+ function hex(buf) {
7
+ return Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, '0')).join('');
8
+ }
9
+ function timingSafeEqual(a, b) {
10
+ if (a.length !== b.length)
11
+ return false;
12
+ let diff = 0;
13
+ for (let i = 0; i < a.length; i++)
14
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
15
+ return diff === 0;
16
+ }
17
+ /** `sha256=<hex HMAC-SHA256 of body>`, what the server sends in X-Spillway-Signature. */
18
+ export async function signWebhookBody(body, secret) {
19
+ const subtle = globalThis.crypto?.subtle;
20
+ if (!subtle)
21
+ throw new Error('Web Crypto is not available in this runtime');
22
+ const key = await subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
23
+ return 'sha256=' + hex(await subtle.sign('HMAC', key, new TextEncoder().encode(body)));
24
+ }
25
+ /** True when `signature` (the X-Spillway-Signature header) matches the raw body under `secret`. */
26
+ export async function verifyWebhookSignature(body, signature, secret) {
27
+ if (!signature || !secret)
28
+ return false;
29
+ const expected = await signWebhookBody(body, secret);
30
+ return timingSafeEqual(signature.trim(), expected);
31
+ }
32
+ export class WebhookError extends Error {
33
+ status;
34
+ constructor(status, message) {
35
+ super(message);
36
+ this.status = status;
37
+ this.name = 'WebhookError';
38
+ }
39
+ }
40
+ /**
41
+ * Reads and verifies a webhook request: the method, the signature over the raw body and the JSON shape.
42
+ * Throws a `WebhookError` with the status to answer (405, 401, 400).
43
+ */
44
+ export async function readWebhook(request, secret) {
45
+ if (request.method !== 'POST')
46
+ throw new WebhookError(405, 'Method not allowed');
47
+ const body = await request.text();
48
+ if (!(await verifyWebhookSignature(body, request.headers.get(SIGNATURE_HEADER), secret)))
49
+ throw new WebhookError(401, 'Bad signature');
50
+ let payload;
51
+ try {
52
+ payload = JSON.parse(body);
53
+ }
54
+ catch {
55
+ throw new WebhookError(400, 'Body is not JSON');
56
+ }
57
+ if (!payload || typeof payload !== 'object' || typeof payload.event !== 'string')
58
+ throw new WebhookError(400, 'Not a Spillway webhook payload');
59
+ return payload;
60
+ }
61
+ /**
62
+ * What a payload says should be purged: the public path of the entity and the server's cache tags
63
+ * (`entity:<id>`, `type:<key>`, `site:<id>`, `list:<type>`, `tgroup:<id>`). Test sends and other events give an empty result.
64
+ */
65
+ export function affectedByWebhook(payload) {
66
+ const e = payload.data?.entity;
67
+ const content = CONTENT_EVENTS.includes(payload.event);
68
+ if (!e || !content)
69
+ return { paths: [], tags: [], event: payload.event, test: Boolean(payload.data?.test) };
70
+ const paths = new Set();
71
+ if (e.publicPath)
72
+ paths.add(e.publicPath);
73
+ else if (e.path)
74
+ paths.add(e.path);
75
+ const tags = new Set(e.cacheTags ?? [`entity:${e.id}`, `type:${e.type}`, `list:${e.type}`]);
76
+ return { paths: [...paths], tags: [...tags], event: payload.event, test: Boolean(payload.data?.test) };
77
+ }
78
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.js","sourceRoot":"","sources":["../src/webhook.ts"],"names":[],"mappings":"AASA,MAAM,CAAC,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AACvD,MAAM,CAAC,MAAM,YAAY,GAAG,kBAAkB,CAAC;AAC/C,MAAM,CAAC,MAAM,eAAe,GAAG,qBAAqB,CAAC;AAErD,qGAAqG;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E,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC;AACzG,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@spillway-cms/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Typed fetch client for the Spillway CMS public content API: pages as resolved block data, entities, collections, menus, search, media, previews and webhook verification. No dependencies; runs in Node 18+, edge runtimes and browsers.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kwall-llc/spillway-cms.git",
9
+ "directory": "packages/client"
10
+ },
11
+ "homepage": "https://github.com/kwall-llc/spillway-cms/tree/main/packages/client#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/kwall-llc/spillway-cms/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "./webhook": {
25
+ "types": "./dist/webhook.d.ts",
26
+ "import": "./dist/webhook.js",
27
+ "default": "./dist/webhook.js"
28
+ }
29
+ },
30
+ "sideEffects": false,
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "dependencies": {
37
+ "@spillway-cms/shared": "0.1.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.0.0",
41
+ "typescript": "^5.9.0",
42
+ "vitest": "^3.0.0",
43
+ "@spillway-cms/core": "0.1.1"
44
+ },
45
+ "engines": {
46
+ "node": ">=18"
47
+ },
48
+ "scripts": {
49
+ "build": "rm -rf dist && tsc -p tsconfig.json",
50
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
51
+ "test": "vitest run"
52
+ }
6
53
  }