@usethrottle/builder 0.0.0-stage → 0.1.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.
@@ -0,0 +1,133 @@
1
+ import { PageDocument } from '@usethrottle/builder-schema';
2
+ export { v as verifyBuilderNotice } from './verify-CkxGofEg.js';
3
+
4
+ type BuilderUnavailableReason = 'timeout' | 'network' | 'status' | 'invalid-response' | 'unsupported-document';
5
+ /**
6
+ * The Builder could not answer: a timeout, a network failure, a non-success
7
+ * status, a body that is not what the read API sends, or a document from a
8
+ * newer schema than this build reads. A caller with no last good answer lets
9
+ * it reach the store's error boundary instead of rendering a blank page.
10
+ */
11
+ declare class BuilderUnavailableError extends Error {
12
+ readonly reason: BuilderUnavailableReason;
13
+ /** The HTTP status, when the Builder answered. */
14
+ readonly status: number | undefined;
15
+ constructor(reason: BuilderUnavailableReason, message: string, options?: {
16
+ status?: number;
17
+ cause?: unknown;
18
+ });
19
+ }
20
+ /** A page (or a bundle's page) that is not published and has no redirect: `404 PAGE_NOT_FOUND`. */
21
+ declare class BuilderNotFoundError extends Error {
22
+ readonly slug: string | undefined;
23
+ constructor(slug?: string);
24
+ }
25
+ /**
26
+ * The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
27
+ * read never falls back to the published page: the caller shows that the link
28
+ * has expired.
29
+ */
30
+ declare class PreviewExpiredError extends Error {
31
+ constructor();
32
+ }
33
+
34
+ /** Published site settings resolved for one locale (localized values are strings). */
35
+ type BuilderSite = {
36
+ generation: number;
37
+ siteVersion: number;
38
+ settings: Record<string, unknown>;
39
+ };
40
+ type BuilderPageSummary = {
41
+ id: string;
42
+ slug: string;
43
+ pageType: string;
44
+ title: string;
45
+ updatedAt: string;
46
+ path: string;
47
+ };
48
+ /** A published page: its metadata and its document (with frozen custom widgets and assets). */
49
+ type LoadedPage = BuilderPageSummary & {
50
+ generation: number;
51
+ document: PageDocument;
52
+ [key: string]: unknown;
53
+ };
54
+ type PageRedirect = {
55
+ redirectTo: string;
56
+ };
57
+ /** A published part or slot document; an empty document when unpublished. */
58
+ type LoadedDocument = {
59
+ generation: number;
60
+ document: PageDocument;
61
+ };
62
+ type BuilderBundle = {
63
+ generation: number;
64
+ site: BuilderSite;
65
+ header: LoadedDocument;
66
+ footer: LoadedDocument;
67
+ page?: LoadedPage | PageRedirect;
68
+ /** Only the slots that were asked for. */
69
+ slots: Record<string, LoadedDocument>;
70
+ };
71
+ type PartName = 'header' | 'footer';
72
+ type BuilderClientOptions = {
73
+ /** The publishable key (`tb_pk_…`). Sent as `X-Builder-Key`. */
74
+ builderKey: string;
75
+ /** Defaults to `https://builder.usethrottle.dev`. */
76
+ baseUrl?: string;
77
+ fetch?: typeof fetch;
78
+ /** Per read, body included. Default 3000. */
79
+ timeoutMs?: number;
80
+ /**
81
+ * A preview token (`getPreviewToken()` from `@usethrottle/builder/next`).
82
+ * Every read then sends `X-Builder-Preview`, reads drafts, is never cached
83
+ * and never answers from a last good. An expired token throws
84
+ * `PreviewExpiredError`.
85
+ */
86
+ previewToken?: string | undefined;
87
+ };
88
+ type LocaleOptions = {
89
+ locale?: string;
90
+ };
91
+ type BuilderClient = {
92
+ site(options?: LocaleOptions): Promise<BuilderSite>;
93
+ pages: {
94
+ list(): Promise<BuilderPageSummary[]>;
95
+ get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
96
+ };
97
+ parts: {
98
+ get(name: PartName, options?: LocaleOptions): Promise<LoadedDocument>;
99
+ };
100
+ slots: {
101
+ get(name: string, options?: LocaleOptions): Promise<LoadedDocument>;
102
+ };
103
+ bundle(options?: LocaleOptions & {
104
+ page?: string;
105
+ slots?: readonly string[];
106
+ }): Promise<BuilderBundle>;
107
+ };
108
+
109
+ declare const DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
110
+ declare const DEFAULT_TIMEOUT_MS = 3000;
111
+ declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
112
+
113
+ declare const BUILDER_TAGS: {
114
+ readonly all: "throttle-builder";
115
+ readonly site: "throttle-builder:site";
116
+ readonly pages: "throttle-builder:pages";
117
+ readonly page: (slug: string) => string;
118
+ readonly part: (name: string) => string;
119
+ readonly slot: (name: string) => string;
120
+ };
121
+ /**
122
+ * The tags a change notice's scopes clear. `site` and `menus` clear the site,
123
+ * header and footer reads and never pages. `header` and `footer` clear their
124
+ * part, `pages` the list, `page:<slug>` and `slot:<name>` that one read. A
125
+ * scope this build does not know clears the coarse tag, so a newer Worker
126
+ * never leaves a store stale. In order, without repeats.
127
+ */
128
+ declare function scopesToTags(scopes: readonly string[]): string[];
129
+
130
+ /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
131
+ declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
132
+
133
+ export { BUILDER_TAGS, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags };
package/dist/index.js ADDED
@@ -0,0 +1,290 @@
1
+ import {
2
+ BUILDER_TAGS,
3
+ __publicField,
4
+ fitTags,
5
+ scopesToTags,
6
+ verifyBuilderNotice
7
+ } from "./chunk-EERLS5TR.js";
8
+
9
+ // src/errors.ts
10
+ var BuilderUnavailableError = class extends Error {
11
+ constructor(reason, message, options = {}) {
12
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
13
+ __publicField(this, "reason");
14
+ /** The HTTP status, when the Builder answered. */
15
+ __publicField(this, "status");
16
+ this.name = "BuilderUnavailableError";
17
+ this.reason = reason;
18
+ this.status = options.status;
19
+ }
20
+ };
21
+ var BuilderNotFoundError = class extends Error {
22
+ constructor(slug) {
23
+ super(slug === void 0 ? "Builder page not found" : `Builder page "${slug}" not found`);
24
+ __publicField(this, "slug");
25
+ this.name = "BuilderNotFoundError";
26
+ this.slug = slug;
27
+ }
28
+ };
29
+ var PreviewExpiredError = class extends Error {
30
+ constructor() {
31
+ super("The Builder preview link has expired");
32
+ this.name = "PreviewExpiredError";
33
+ }
34
+ };
35
+
36
+ // src/client.ts
37
+ import { CURRENT_SCHEMA_VERSION, upgradeDocument } from "@usethrottle/builder-schema";
38
+
39
+ // src/cache.ts
40
+ var UNTIL_CHANGED_REVALIDATE_S = 3600;
41
+ function cacheInit(tags, preview) {
42
+ if (preview) return { cache: "no-store" };
43
+ return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
44
+ }
45
+
46
+ // src/last-good.ts
47
+ var LAST_GOOD_MS = 10 * 60 * 1e3;
48
+ var MAX_ENTRIES = 200;
49
+ var store = /* @__PURE__ */ new Map();
50
+ function rememberGood(key, value) {
51
+ store.delete(key);
52
+ store.set(key, { value, at: Date.now(), warned: false });
53
+ if (store.size > MAX_ENTRIES) {
54
+ const oldest = store.keys().next();
55
+ if (!oldest.done) store.delete(oldest.value);
56
+ }
57
+ }
58
+ function recallGood(key, warn) {
59
+ const entry = store.get(key);
60
+ if (entry === void 0) return void 0;
61
+ if (Date.now() - entry.at > LAST_GOOD_MS) {
62
+ store.delete(key);
63
+ return void 0;
64
+ }
65
+ if (!entry.warned) {
66
+ entry.warned = true;
67
+ warn();
68
+ }
69
+ return { value: entry.value };
70
+ }
71
+
72
+ // src/client.ts
73
+ var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
74
+ var DEFAULT_TIMEOUT_MS = 3e3;
75
+ var MAX_NAME_CHARS = 128;
76
+ function isRecord(value) {
77
+ return typeof value === "object" && value !== null && !Array.isArray(value);
78
+ }
79
+ function queryString(query) {
80
+ const pairs = Object.entries(query).filter((entry) => entry[1] !== void 0 && entry[1] !== "").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
81
+ return pairs.length === 0 ? "" : `?${pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")}`;
82
+ }
83
+ function checkName(kind, value) {
84
+ if (typeof value !== "string" || value === "" || value.length > MAX_NAME_CHARS)
85
+ throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
86
+ return value;
87
+ }
88
+ function currentDocument(answer, where) {
89
+ const doc = answer.document;
90
+ if (!isRecord(doc))
91
+ throw new BuilderUnavailableError("invalid-response", `Builder ${where} answer has no document`);
92
+ if (doc.schemaVersion === CURRENT_SCHEMA_VERSION) return doc;
93
+ const upgraded = upgradeDocument(doc);
94
+ if (!upgraded.ok)
95
+ throw new BuilderUnavailableError(
96
+ "unsupported-document",
97
+ `Builder ${where} document cannot be read by this SDK version (${upgraded.issues[0]?.code ?? "invalid"})`
98
+ );
99
+ return upgraded.doc;
100
+ }
101
+ function withDocument(answer, where) {
102
+ return { ...answer, document: currentDocument(answer, where) };
103
+ }
104
+ var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
105
+ function generationOf(answer, where) {
106
+ const { generation } = answer;
107
+ if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0)
108
+ throw invalid(`Builder ${where} answer has no generation`);
109
+ return generation;
110
+ }
111
+ function readSite(answer) {
112
+ generationOf(answer, "site");
113
+ if (typeof answer.siteVersion !== "number" || !Number.isSafeInteger(answer.siteVersion))
114
+ throw invalid("Builder site answer has no siteVersion");
115
+ if (!isRecord(answer.settings)) throw invalid("Builder site answer has no settings");
116
+ return answer;
117
+ }
118
+ var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
119
+ function readPages(answer) {
120
+ const { pages } = answer;
121
+ if (!Array.isArray(pages)) throw invalid("Builder pages answer is not a list");
122
+ for (const page of pages)
123
+ if (!isRecord(page) || SUMMARY_KEYS.some((key) => typeof page[key] !== "string"))
124
+ throw invalid("Builder pages answer has a page without its fields");
125
+ return pages;
126
+ }
127
+ function readDocument(answer, where) {
128
+ generationOf(answer, where);
129
+ return withDocument(answer, where);
130
+ }
131
+ function readPage(answer) {
132
+ if (typeof answer.redirectTo === "string") return { redirectTo: answer.redirectTo };
133
+ generationOf(answer, "page");
134
+ if (typeof answer.slug !== "string") throw invalid("Builder page answer has no slug");
135
+ return withDocument(answer, "page");
136
+ }
137
+ function readBundle(answer) {
138
+ const generation = generationOf(answer, "bundle");
139
+ if (!isRecord(answer.site) || !isRecord(answer.header) || !isRecord(answer.footer))
140
+ throw invalid("Builder bundle answer has no site, header or footer");
141
+ const slots = answer.slots === void 0 ? {} : answer.slots;
142
+ if (!isRecord(slots)) throw invalid("Builder bundle answer has slots that are not an object");
143
+ return {
144
+ generation,
145
+ site: readSite(answer.site),
146
+ header: readDocument(answer.header, "header"),
147
+ footer: readDocument(answer.footer, "footer"),
148
+ ...isRecord(answer.page) ? { page: readPage(answer.page) } : {},
149
+ slots: Object.fromEntries(
150
+ Object.entries(slots).map(([name, value]) => {
151
+ if (!isRecord(value)) throw invalid(`Builder slot ${name} answer is not an object`);
152
+ return [name, readDocument(value, `slot ${name}`)];
153
+ })
154
+ )
155
+ };
156
+ }
157
+ function createBuilderClient(options) {
158
+ const { builderKey, previewToken } = options;
159
+ if (typeof builderKey !== "string" || builderKey === "")
160
+ throw new TypeError("createBuilderClient needs a builderKey");
161
+ if (builderKey.startsWith("tb_sk_"))
162
+ throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
163
+ const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
164
+ const preview = previewHeader !== void 0;
165
+ const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
166
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
167
+ const doFetch = options.fetch;
168
+ async function once(url, init) {
169
+ const controller = new AbortController();
170
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
171
+ try {
172
+ const response = await (doFetch ?? globalThis.fetch)(url, {
173
+ ...init,
174
+ signal: controller.signal
175
+ });
176
+ let body;
177
+ try {
178
+ body = response.status === 204 ? void 0 : await response.json();
179
+ } catch (cause) {
180
+ if (controller.signal.aborted) throw cause;
181
+ body = void 0;
182
+ }
183
+ return { body, status: response.status };
184
+ } catch (cause) {
185
+ throw new BuilderUnavailableError(
186
+ controller.signal.aborted ? "timeout" : "network",
187
+ controller.signal.aborted ? `Builder did not answer within ${String(timeoutMs)} ms` : "Builder could not be reached",
188
+ { cause }
189
+ );
190
+ } finally {
191
+ clearTimeout(timer);
192
+ }
193
+ }
194
+ async function fetchAnswer(path, read2) {
195
+ const headers = { accept: "application/json", "X-Builder-Key": builderKey };
196
+ if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
197
+ const url = `${base}${path}${queryString(read2.query ?? {})}`;
198
+ const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
199
+ const { body, status } = await once(url, init);
200
+ if (status === 401 && preview) throw new PreviewExpiredError();
201
+ if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
202
+ if (status < 200 || status >= 300)
203
+ throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
204
+ if (!isRecord(body) && !Array.isArray(body))
205
+ throw new BuilderUnavailableError("invalid-response", "Builder answered a body that is not JSON");
206
+ return Array.isArray(body) ? { pages: body } : body;
207
+ }
208
+ async function read(path, options2, shape) {
209
+ const goodKey = `${base}|${builderKey}|${path}${queryString(options2.query ?? {})}`;
210
+ try {
211
+ const value = shape(await fetchAnswer(path, options2));
212
+ if (!preview) rememberGood(goodKey, value);
213
+ return value;
214
+ } catch (error) {
215
+ if (preview || !(error instanceof BuilderUnavailableError)) throw error;
216
+ const good = recallGood(goodKey, () => {
217
+ console.warn(
218
+ `[throttle-builder] ${path} failed (${error.reason}); serving the last good answer`
219
+ );
220
+ });
221
+ if (good === void 0) throw error;
222
+ return good.value;
223
+ }
224
+ }
225
+ return {
226
+ site: ({ locale } = {}) => read("/v1/site", { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.site] }, readSite),
227
+ pages: {
228
+ list: () => read(
229
+ "/v1/pages",
230
+ { tags: [BUILDER_TAGS.all, BUILDER_TAGS.pages] },
231
+ readPages
232
+ ),
233
+ get: async (slug, { locale } = {}) => read(
234
+ `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
235
+ { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
236
+ readPage
237
+ )
238
+ },
239
+ parts: {
240
+ get: async (name, { locale } = {}) => {
241
+ if (name !== "header" && name !== "footer")
242
+ throw new TypeError('A Builder part is "header" or "footer"');
243
+ return read(
244
+ `/v1/parts/${name}`,
245
+ { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.part(name)] },
246
+ (answer) => readDocument(answer, `part ${name}`)
247
+ );
248
+ }
249
+ },
250
+ slots: {
251
+ get: async (name, { locale } = {}) => read(
252
+ `/v1/slots/${encodeURIComponent(checkName("slot name", name))}`,
253
+ { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.slot(name)] },
254
+ (answer) => readDocument(answer, `slot ${name}`)
255
+ )
256
+ },
257
+ bundle: async ({ page: pageSlug, slots, locale } = {}) => {
258
+ const names = [...new Set(slots ?? [])].map((name) => checkName("slot name", name)).sort();
259
+ if (pageSlug !== void 0) checkName("page slug", pageSlug);
260
+ return read(
261
+ "/v1/bundle",
262
+ {
263
+ query: { page: pageSlug, slots: names.join(","), locale },
264
+ pageSlug,
265
+ tags: [
266
+ BUILDER_TAGS.all,
267
+ BUILDER_TAGS.site,
268
+ BUILDER_TAGS.part("header"),
269
+ BUILDER_TAGS.part("footer"),
270
+ ...pageSlug === void 0 ? [] : [BUILDER_TAGS.page(pageSlug)],
271
+ ...names.map((name) => BUILDER_TAGS.slot(name))
272
+ ]
273
+ },
274
+ readBundle
275
+ );
276
+ }
277
+ };
278
+ }
279
+ export {
280
+ BUILDER_TAGS,
281
+ BuilderNotFoundError,
282
+ BuilderUnavailableError,
283
+ DEFAULT_BASE_URL,
284
+ DEFAULT_TIMEOUT_MS,
285
+ PreviewExpiredError,
286
+ UNTIL_CHANGED_REVALIDATE_S,
287
+ createBuilderClient,
288
+ scopesToTags,
289
+ verifyBuilderNotice
290
+ };
package/dist/next.cjs ADDED
@@ -0,0 +1,117 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+ var _chunkUFIR4HJAcjs = require('./chunk-UFIR4HJA.cjs');
7
+
8
+ // src/next/index.ts
9
+ require('server-only');
10
+
11
+ // src/next/revalidate.ts
12
+ var SIGNATURE_HEADER = "x-throttle-builder-signature";
13
+ var MAX_BODY_BYTES = 64 * 1024;
14
+ var MAX_SCOPES = 500;
15
+ var MAX_TAGS_PER_NOTICE = 20;
16
+ async function readCapped(req) {
17
+ const declared = Number(req.headers.get("content-length"));
18
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return null;
19
+ if (req.body === null) return "";
20
+ const reader = req.body.getReader();
21
+ const decoder = new TextDecoder();
22
+ let text = "";
23
+ let size = 0;
24
+ for (; ; ) {
25
+ const { done, value } = await reader.read();
26
+ if (done) return text + decoder.decode();
27
+ size += value.byteLength;
28
+ if (size > MAX_BODY_BYTES) {
29
+ await reader.cancel();
30
+ return null;
31
+ }
32
+ text += decoder.decode(value, { stream: true });
33
+ }
34
+ }
35
+ var json = (status, body) => new Response(JSON.stringify(body), {
36
+ status,
37
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
38
+ });
39
+ function parseNotice(rawBody) {
40
+ let value;
41
+ try {
42
+ value = JSON.parse(rawBody);
43
+ } catch (e) {
44
+ return null;
45
+ }
46
+ if (typeof value !== "object" || value === null) return null;
47
+ const { type, generation, scopes } = value;
48
+ if (type !== "builder.changed" || typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0 || !Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_SCOPES || !scopes.every(
49
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkUFIR4HJAcjs.TAG_MAX_CHARS
50
+ ))
51
+ return null;
52
+ return { generation, scopes };
53
+ }
54
+ async function defaultRevalidateTag() {
55
+ const { revalidateTag } = await Promise.resolve().then(() => _interopRequireWildcard(require("next/cache")));
56
+ return (tag) => revalidateTag(tag, { expire: 0 });
57
+ }
58
+ function createRevalidateHandler(options) {
59
+ return async (req) => {
60
+ const list = typeof options.secret === "string" || options.secret === void 0 ? [options.secret] : options.secret;
61
+ const secrets = list.filter(
62
+ (secret) => typeof secret === "string" && secret !== ""
63
+ );
64
+ if (secrets.length === 0)
65
+ return json(500, {
66
+ error: "createRevalidateHandler has no signing secret: set the Builder endpoint secret (for example THROTTLE_BUILDER_WEBHOOK_SECRET) in this environment."
67
+ });
68
+ const rawBody = await readCapped(req);
69
+ if (rawBody === null) return json(413, { error: "body too large" });
70
+ const header = _nullishCoalesce(req.headers.get(SIGNATURE_HEADER), () => ( ""));
71
+ const now = Math.floor(Date.now() / 1e3);
72
+ let verified = false;
73
+ for (const secret of secrets)
74
+ verified = await _chunkUFIR4HJAcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
75
+ if (!verified) return json(401, { error: "invalid signature" });
76
+ const notice = parseNotice(rawBody);
77
+ if (notice === null) return json(400, { error: "invalid body" });
78
+ const mapped = _chunkUFIR4HJAcjs.scopesToTags.call(void 0, notice.scopes);
79
+ const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkUFIR4HJAcjs.BUILDER_TAGS.all] : mapped;
80
+ const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag()));
81
+ for (const tag of tags) revalidate(tag);
82
+ return json(200, { revalidated: tags });
83
+ };
84
+ }
85
+
86
+ // src/next/preview.ts
87
+ var PREVIEW_COOKIE = "throttle_builder_preview";
88
+ var PREVIEW_PARAM = "throttle_builder_preview";
89
+ var PREVIEW_MAX_AGE_S = 3600;
90
+ var TOKEN_RE = /^[A-Za-z0-9._~+/=-]{1,2048}$/u;
91
+ function previewMiddleware(req) {
92
+ const url = new URL(req.url);
93
+ const token = url.searchParams.get(PREVIEW_PARAM);
94
+ if (token === null || !TOKEN_RE.test(token)) return null;
95
+ url.searchParams.delete(PREVIEW_PARAM);
96
+ return new Response(null, {
97
+ status: 307,
98
+ headers: {
99
+ location: url.toString(),
100
+ "set-cookie": `${PREVIEW_COOKIE}=${encodeURIComponent(token)}; Max-Age=${String(PREVIEW_MAX_AGE_S)}; Path=/; HttpOnly; Secure; SameSite=Lax`,
101
+ "cache-control": "no-store"
102
+ }
103
+ });
104
+ }
105
+ async function getPreviewToken() {
106
+ const { cookies } = await Promise.resolve().then(() => _interopRequireWildcard(require("next/headers")));
107
+ const store = await cookies();
108
+ const value = _optionalChain([store, 'access', _ => _.get, 'call', _2 => _2(PREVIEW_COOKIE), 'optionalAccess', _3 => _3.value]);
109
+ return value === void 0 || value === "" ? void 0 : value;
110
+ }
111
+
112
+
113
+
114
+
115
+
116
+
117
+ exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkUFIR4HJAcjs.verifyBuilderNotice;
@@ -0,0 +1,45 @@
1
+ export { v as verifyBuilderNotice } from './verify-CkxGofEg.cjs';
2
+
3
+ type CreateRevalidateHandlerOptions = {
4
+ /**
5
+ * The endpoint's signing secret; pass `process.env` straight in. A list
6
+ * accepts any of them, so a rotated secret can be added before the old one
7
+ * is removed. Checked on each request, not at build time. With no secret a
8
+ * request is answered 500 and nothing is revalidated.
9
+ */
10
+ secret: string | undefined | readonly (string | undefined)[];
11
+ /** Called once per tag to clear. Defaults to `revalidateTag` from `next/cache`. */
12
+ revalidateTag?: (tag: string) => void;
13
+ };
14
+ /**
15
+ * The route handler for the Builder's `builder.changed` notice. It checks the
16
+ * `X-Throttle-Builder-Signature` header (HMAC-SHA256 over
17
+ * `throttle.builder-notice.v1.<t>.<body>`, 300 s tolerance, any of the given
18
+ * secrets) and clears the cache tags of the notice's scopes (the coarse tag
19
+ * alone when they map to more than 20). It only ever calls `revalidateTag`:
20
+ * never a path. Answers 200 `{ revalidated }`, 401 for a missing, stale or
21
+ * wrong signature, 400 for a body that is not a change notice, 413 for a body
22
+ * over 64 KB and 500 when no secret is set.
23
+ */
24
+ declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
+
26
+ /** The cookie that carries the preview token. */
27
+ declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
+ /**
29
+ * For Next middleware: a request with `?throttle_builder_preview=<token>` is
30
+ * answered with a 307 to the same URL without that parameter and the token in
31
+ * an HTTP-only `SameSite=Lax; Secure` cookie (one hour). Any other request,
32
+ * and a token of an unexpected shape, returns `null`.
33
+ */
34
+ declare function previewMiddleware(req: Request): Response | null;
35
+ /**
36
+ * The preview token of the current request (the `throttle_builder_preview`
37
+ * cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
38
+ * `next/headers`, which is a promise in Next 15 and later. Call it where Next
39
+ * allows a request-scoped read; it makes that render dynamic, which is right
40
+ * for a preview and wrong for a published page, so call it only from a
41
+ * route that is preview-only (or behind your own preview check).
42
+ */
43
+ declare function getPreviewToken(): Promise<string | undefined>;
44
+
45
+ export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
package/dist/next.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ export { v as verifyBuilderNotice } from './verify-CkxGofEg.js';
2
+
3
+ type CreateRevalidateHandlerOptions = {
4
+ /**
5
+ * The endpoint's signing secret; pass `process.env` straight in. A list
6
+ * accepts any of them, so a rotated secret can be added before the old one
7
+ * is removed. Checked on each request, not at build time. With no secret a
8
+ * request is answered 500 and nothing is revalidated.
9
+ */
10
+ secret: string | undefined | readonly (string | undefined)[];
11
+ /** Called once per tag to clear. Defaults to `revalidateTag` from `next/cache`. */
12
+ revalidateTag?: (tag: string) => void;
13
+ };
14
+ /**
15
+ * The route handler for the Builder's `builder.changed` notice. It checks the
16
+ * `X-Throttle-Builder-Signature` header (HMAC-SHA256 over
17
+ * `throttle.builder-notice.v1.<t>.<body>`, 300 s tolerance, any of the given
18
+ * secrets) and clears the cache tags of the notice's scopes (the coarse tag
19
+ * alone when they map to more than 20). It only ever calls `revalidateTag`:
20
+ * never a path. Answers 200 `{ revalidated }`, 401 for a missing, stale or
21
+ * wrong signature, 400 for a body that is not a change notice, 413 for a body
22
+ * over 64 KB and 500 when no secret is set.
23
+ */
24
+ declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
+
26
+ /** The cookie that carries the preview token. */
27
+ declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
+ /**
29
+ * For Next middleware: a request with `?throttle_builder_preview=<token>` is
30
+ * answered with a 307 to the same URL without that parameter and the token in
31
+ * an HTTP-only `SameSite=Lax; Secure` cookie (one hour). Any other request,
32
+ * and a token of an unexpected shape, returns `null`.
33
+ */
34
+ declare function previewMiddleware(req: Request): Response | null;
35
+ /**
36
+ * The preview token of the current request (the `throttle_builder_preview`
37
+ * cookie), for `createBuilderClient({ previewToken })`. Reads `cookies()` from
38
+ * `next/headers`, which is a promise in Next 15 and later. Call it where Next
39
+ * allows a request-scoped read; it makes that render dynamic, which is right
40
+ * for a preview and wrong for a published page, so call it only from a
41
+ * route that is preview-only (or behind your own preview check).
42
+ */
43
+ declare function getPreviewToken(): Promise<string | undefined>;
44
+
45
+ export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };