@usethrottle/builder 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,288 +1,26 @@
1
1
  import {
2
2
  BUILDER_TAGS,
3
- __publicField,
4
- fitTags,
3
+ BuilderNotFoundError,
4
+ BuilderReleaseNotFoundError,
5
+ BuilderUnavailableError,
6
+ DEFAULT_BASE_URL,
7
+ DEFAULT_TIMEOUT_MS,
8
+ PreviewExpiredError,
9
+ SUPPORTED_BUNDLE_VERSION,
10
+ UNTIL_CHANGED_REVALIDATE_S,
11
+ createBuilderClient,
5
12
  scopesToTags,
6
13
  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
- }
14
+ } from "./chunk-XYWLWXKG.js";
279
15
  export {
280
16
  BUILDER_TAGS,
281
17
  BuilderNotFoundError,
18
+ BuilderReleaseNotFoundError,
282
19
  BuilderUnavailableError,
283
20
  DEFAULT_BASE_URL,
284
21
  DEFAULT_TIMEOUT_MS,
285
22
  PreviewExpiredError,
23
+ SUPPORTED_BUNDLE_VERSION,
286
24
  UNTIL_CHANGED_REVALIDATE_S,
287
25
  createBuilderClient,
288
26
  scopesToTags,
package/dist/next.cjs CHANGED
@@ -3,7 +3,8 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkUFIR4HJAcjs = require('./chunk-UFIR4HJA.cjs');
6
+
7
+ var _chunkZLNUG6ZZcjs = require('./chunk-ZLNUG6ZZ.cjs');
7
8
 
8
9
  // src/next/index.ts
9
10
  require('server-only');
@@ -46,7 +47,7 @@ function parseNotice(rawBody) {
46
47
  if (typeof value !== "object" || value === null) return null;
47
48
  const { type, generation, scopes } = value;
48
49
  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
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkZLNUG6ZZcjs.TAG_MAX_CHARS
50
51
  ))
51
52
  return null;
52
53
  return { generation, scopes };
@@ -71,18 +72,81 @@ function createRevalidateHandler(options) {
71
72
  const now = Math.floor(Date.now() / 1e3);
72
73
  let verified = false;
73
74
  for (const secret of secrets)
74
- verified = await _chunkUFIR4HJAcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
75
+ verified = await _chunkZLNUG6ZZcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
75
76
  if (!verified) return json(401, { error: "invalid signature" });
76
77
  const notice = parseNotice(rawBody);
77
78
  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;
79
+ const mapped = _chunkZLNUG6ZZcjs.scopesToTags.call(void 0, notice.scopes);
80
+ const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkZLNUG6ZZcjs.BUILDER_TAGS.all] : mapped;
80
81
  const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag()));
81
82
  for (const tag of tags) revalidate(tag);
82
83
  return json(200, { revalidated: tags });
83
84
  };
84
85
  }
85
86
 
87
+ // src/next/watch-sync.ts
88
+ var DEFAULT_MIN_INTERVAL_MS = 2e4;
89
+ var READ_TIMEOUT_MS = 5e3;
90
+ var json2 = (status, body) => new Response(JSON.stringify(body), {
91
+ status,
92
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
93
+ });
94
+ async function defaultRevalidateTag2() {
95
+ const { revalidateTag } = await Promise.resolve().then(() => _interopRequireWildcard(require("next/cache")));
96
+ return (tag) => revalidateTag(tag, { expire: 0 });
97
+ }
98
+ function createWatchSyncHandler(options) {
99
+ const minInterval = Math.max(_nullishCoalesce(options.minIntervalMs, () => ( DEFAULT_MIN_INTERVAL_MS)), 5e3);
100
+ const now = _nullishCoalesce(options.now, () => ( Date.now));
101
+ let known;
102
+ let lastReadAt;
103
+ let running;
104
+ const run = async (key) => {
105
+ const doFetch = _nullishCoalesce(options.fetch, () => ( fetch));
106
+ const base = (_nullishCoalesce(options.baseUrl, () => ( _chunkZLNUG6ZZcjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
107
+ let generation;
108
+ try {
109
+ const response = await doFetch(`${base}/v1/site`, {
110
+ headers: { "X-Builder-Key": key },
111
+ cache: "no-store",
112
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS)
113
+ });
114
+ if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
115
+ const body = await response.json();
116
+ if (typeof body.generation !== "number" || !Number.isSafeInteger(body.generation))
117
+ throw new Error("Builder answered no generation");
118
+ generation = body.generation;
119
+ } catch (e2) {
120
+ return json2(502, { error: "The Builder could not be read." });
121
+ }
122
+ if (generation === known) return json2(200, { changed: false, generation });
123
+ const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag2()));
124
+ revalidate(_chunkZLNUG6ZZcjs.BUILDER_TAGS.all);
125
+ known = generation;
126
+ return json2(200, { changed: true, generation });
127
+ };
128
+ return () => {
129
+ const key = options.builderKey;
130
+ if (key === void 0 || key === "")
131
+ return Promise.resolve(
132
+ json2(500, {
133
+ error: "createWatchSyncHandler has no Builder key: set the publishable key (tb_pk_\u2026, for example NEXT_PUBLIC_THROTTLE_BUILDER_KEY) in this environment."
134
+ })
135
+ );
136
+ if (key.startsWith("tb_sk_"))
137
+ return Promise.resolve(json2(500, { error: "createWatchSyncHandler takes the publishable key, never a secret key." }));
138
+ if (running) return running;
139
+ const at = now();
140
+ if (lastReadAt !== void 0 && at - lastReadAt < minInterval)
141
+ return Promise.resolve(json2(200, { changed: false, throttled: true }));
142
+ lastReadAt = at;
143
+ running = run(key).finally(() => {
144
+ running = void 0;
145
+ });
146
+ return running;
147
+ };
148
+ }
149
+
86
150
  // src/next/preview.ts
87
151
  var PREVIEW_COOKIE = "throttle_builder_preview";
88
152
  var PREVIEW_PARAM = "throttle_builder_preview";
@@ -114,4 +178,5 @@ async function getPreviewToken() {
114
178
 
115
179
 
116
180
 
117
- exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkUFIR4HJAcjs.verifyBuilderNotice;
181
+
182
+ exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkZLNUG6ZZcjs.verifyBuilderNotice;
package/dist/next.d.cts CHANGED
@@ -23,6 +23,35 @@ type CreateRevalidateHandlerOptions = {
23
23
  */
24
24
  declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
25
 
26
+ type CreateWatchSyncHandlerOptions = {
27
+ /** The publishable key (`tb_pk_…`): `process.env` straight in. With none the route answers 500. */
28
+ builderKey: string | undefined;
29
+ baseUrl?: string;
30
+ /** Default 20 000 (never below 5 000). */
31
+ minIntervalMs?: number;
32
+ /** Called with the coarse Builder tag when the generation moved. Defaults to `revalidateTag` from `next/cache`. */
33
+ revalidateTag?: (tag: string) => void;
34
+ /** For tests. */
35
+ fetch?: typeof fetch;
36
+ now?: () => number;
37
+ };
38
+ /**
39
+ * The server half of the `@usethrottle/builder/watch` backstop. The watcher
40
+ * in an open tab only learns that the Builder's generation moved; it cannot
41
+ * clear the store's data cache. The tab POSTs here (a store route such as
42
+ * `app/api/throttle/builder-sync/route.ts`), and the route reads the site's
43
+ * generation uncached from the Builder with the publishable key. When it
44
+ * differs from the last one this instance saw (or this instance has seen
45
+ * none), it clears the coarse `throttle-builder` tag, and the `router.refresh()`
46
+ * that follows renders fresh. The Builder is read at most once per
47
+ * `minIntervalMs` per instance and nothing is cleared unless the generation
48
+ * really moved, so the route cannot be used to hammer the Builder or to empty
49
+ * the cache. Tags only, never a path. Answers 200 `{ changed, generation? }`
50
+ * (`throttled: true` inside the window), 500 with no key, 502 when the Builder
51
+ * cannot be read.
52
+ */
53
+ declare function createWatchSyncHandler(options: CreateWatchSyncHandlerOptions): (req?: Request) => Promise<Response>;
54
+
26
55
  /** The cookie that carries the preview token. */
27
56
  declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
57
  /**
@@ -42,4 +71,4 @@ declare function previewMiddleware(req: Request): Response | null;
42
71
  */
43
72
  declare function getPreviewToken(): Promise<string | undefined>;
44
73
 
45
- export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
74
+ export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
package/dist/next.d.ts CHANGED
@@ -23,6 +23,35 @@ type CreateRevalidateHandlerOptions = {
23
23
  */
24
24
  declare function createRevalidateHandler(options: CreateRevalidateHandlerOptions): (req: Request) => Promise<Response>;
25
25
 
26
+ type CreateWatchSyncHandlerOptions = {
27
+ /** The publishable key (`tb_pk_…`): `process.env` straight in. With none the route answers 500. */
28
+ builderKey: string | undefined;
29
+ baseUrl?: string;
30
+ /** Default 20 000 (never below 5 000). */
31
+ minIntervalMs?: number;
32
+ /** Called with the coarse Builder tag when the generation moved. Defaults to `revalidateTag` from `next/cache`. */
33
+ revalidateTag?: (tag: string) => void;
34
+ /** For tests. */
35
+ fetch?: typeof fetch;
36
+ now?: () => number;
37
+ };
38
+ /**
39
+ * The server half of the `@usethrottle/builder/watch` backstop. The watcher
40
+ * in an open tab only learns that the Builder's generation moved; it cannot
41
+ * clear the store's data cache. The tab POSTs here (a store route such as
42
+ * `app/api/throttle/builder-sync/route.ts`), and the route reads the site's
43
+ * generation uncached from the Builder with the publishable key. When it
44
+ * differs from the last one this instance saw (or this instance has seen
45
+ * none), it clears the coarse `throttle-builder` tag, and the `router.refresh()`
46
+ * that follows renders fresh. The Builder is read at most once per
47
+ * `minIntervalMs` per instance and nothing is cleared unless the generation
48
+ * really moved, so the route cannot be used to hammer the Builder or to empty
49
+ * the cache. Tags only, never a path. Answers 200 `{ changed, generation? }`
50
+ * (`throttled: true` inside the window), 500 with no key, 502 when the Builder
51
+ * cannot be read.
52
+ */
53
+ declare function createWatchSyncHandler(options: CreateWatchSyncHandlerOptions): (req?: Request) => Promise<Response>;
54
+
26
55
  /** The cookie that carries the preview token. */
27
56
  declare const PREVIEW_COOKIE = "throttle_builder_preview";
28
57
  /**
@@ -42,4 +71,4 @@ declare function previewMiddleware(req: Request): Response | null;
42
71
  */
43
72
  declare function getPreviewToken(): Promise<string | undefined>;
44
73
 
45
- export { type CreateRevalidateHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, getPreviewToken, previewMiddleware };
74
+ export { type CreateRevalidateHandlerOptions, type CreateWatchSyncHandlerOptions, PREVIEW_COOKIE, createRevalidateHandler, createWatchSyncHandler, getPreviewToken, previewMiddleware };
package/dist/next.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  BUILDER_TAGS,
3
+ DEFAULT_BASE_URL,
3
4
  TAG_MAX_CHARS,
4
5
  scopesToTags,
5
6
  verifyBuilderNotice
6
- } from "./chunk-EERLS5TR.js";
7
+ } from "./chunk-XYWLWXKG.js";
7
8
 
8
9
  // src/next/index.ts
9
10
  import "server-only";
@@ -83,6 +84,69 @@ function createRevalidateHandler(options) {
83
84
  };
84
85
  }
85
86
 
87
+ // src/next/watch-sync.ts
88
+ var DEFAULT_MIN_INTERVAL_MS = 2e4;
89
+ var READ_TIMEOUT_MS = 5e3;
90
+ var json2 = (status, body) => new Response(JSON.stringify(body), {
91
+ status,
92
+ headers: { "content-type": "application/json", "cache-control": "no-store" }
93
+ });
94
+ async function defaultRevalidateTag2() {
95
+ const { revalidateTag } = await import("next/cache");
96
+ return (tag) => revalidateTag(tag, { expire: 0 });
97
+ }
98
+ function createWatchSyncHandler(options) {
99
+ const minInterval = Math.max(options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS, 5e3);
100
+ const now = options.now ?? Date.now;
101
+ let known;
102
+ let lastReadAt;
103
+ let running;
104
+ const run = async (key) => {
105
+ const doFetch = options.fetch ?? fetch;
106
+ const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
107
+ let generation;
108
+ try {
109
+ const response = await doFetch(`${base}/v1/site`, {
110
+ headers: { "X-Builder-Key": key },
111
+ cache: "no-store",
112
+ signal: AbortSignal.timeout(READ_TIMEOUT_MS)
113
+ });
114
+ if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
115
+ const body = await response.json();
116
+ if (typeof body.generation !== "number" || !Number.isSafeInteger(body.generation))
117
+ throw new Error("Builder answered no generation");
118
+ generation = body.generation;
119
+ } catch {
120
+ return json2(502, { error: "The Builder could not be read." });
121
+ }
122
+ if (generation === known) return json2(200, { changed: false, generation });
123
+ const revalidate = options.revalidateTag ?? await defaultRevalidateTag2();
124
+ revalidate(BUILDER_TAGS.all);
125
+ known = generation;
126
+ return json2(200, { changed: true, generation });
127
+ };
128
+ return () => {
129
+ const key = options.builderKey;
130
+ if (key === void 0 || key === "")
131
+ return Promise.resolve(
132
+ json2(500, {
133
+ error: "createWatchSyncHandler has no Builder key: set the publishable key (tb_pk_\u2026, for example NEXT_PUBLIC_THROTTLE_BUILDER_KEY) in this environment."
134
+ })
135
+ );
136
+ if (key.startsWith("tb_sk_"))
137
+ return Promise.resolve(json2(500, { error: "createWatchSyncHandler takes the publishable key, never a secret key." }));
138
+ if (running) return running;
139
+ const at = now();
140
+ if (lastReadAt !== void 0 && at - lastReadAt < minInterval)
141
+ return Promise.resolve(json2(200, { changed: false, throttled: true }));
142
+ lastReadAt = at;
143
+ running = run(key).finally(() => {
144
+ running = void 0;
145
+ });
146
+ return running;
147
+ };
148
+ }
149
+
86
150
  // src/next/preview.ts
87
151
  var PREVIEW_COOKIE = "throttle_builder_preview";
88
152
  var PREVIEW_PARAM = "throttle_builder_preview";
@@ -111,6 +175,7 @@ async function getPreviewToken() {
111
175
  export {
112
176
  PREVIEW_COOKIE,
113
177
  createRevalidateHandler,
178
+ createWatchSyncHandler,
114
179
  getPreviewToken,
115
180
  previewMiddleware,
116
181
  verifyBuilderNotice
@@ -0,0 +1,28 @@
1
+ /** No store polls faster than this, whatever it asks for. */
2
+ declare const MIN_INTERVAL_MS = 30000;
3
+ declare const DEFAULT_INTERVAL_MS = 60000;
4
+ type WatchGenerationInput = {
5
+ /** Reads the current generation. A rejection is ignored until the next check. */
6
+ read: () => Promise<number>;
7
+ intervalMs?: number;
8
+ onChange: (generation: number) => void;
9
+ };
10
+ /**
11
+ * Checks every `intervalMs` (at least 30 s) while the page is visible, and at
12
+ * once when it becomes visible after being hidden for a whole interval. The
13
+ * first answer is the baseline: only a later, different one calls `onChange`.
14
+ * Returns the stop function.
15
+ */
16
+ declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
17
+ type UseGenerationWatchOptions = {
18
+ /** The publishable key (`tb_pk_…`). */
19
+ builderKey: string;
20
+ baseUrl?: string;
21
+ intervalMs?: number;
22
+ /** Called with the new generation, for example `() => router.refresh()`. */
23
+ onChange: (generation: number) => void;
24
+ };
25
+ /** Watches the Builder's generation from a client component. Nothing runs on the server. */
26
+ declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
27
+
28
+ export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
@@ -0,0 +1,28 @@
1
+ /** No store polls faster than this, whatever it asks for. */
2
+ declare const MIN_INTERVAL_MS = 30000;
3
+ declare const DEFAULT_INTERVAL_MS = 60000;
4
+ type WatchGenerationInput = {
5
+ /** Reads the current generation. A rejection is ignored until the next check. */
6
+ read: () => Promise<number>;
7
+ intervalMs?: number;
8
+ onChange: (generation: number) => void;
9
+ };
10
+ /**
11
+ * Checks every `intervalMs` (at least 30 s) while the page is visible, and at
12
+ * once when it becomes visible after being hidden for a whole interval. The
13
+ * first answer is the baseline: only a later, different one calls `onChange`.
14
+ * Returns the stop function.
15
+ */
16
+ declare function watchGeneration({ read, intervalMs, onChange, }: WatchGenerationInput): () => void;
17
+ type UseGenerationWatchOptions = {
18
+ /** The publishable key (`tb_pk_…`). */
19
+ builderKey: string;
20
+ baseUrl?: string;
21
+ intervalMs?: number;
22
+ /** Called with the new generation, for example `() => router.refresh()`. */
23
+ onChange: (generation: number) => void;
24
+ };
25
+ /** Watches the Builder's generation from a client component. Nothing runs on the server. */
26
+ declare function useGenerationWatch({ builderKey, baseUrl, intervalMs, onChange, }: UseGenerationWatchOptions): void;
27
+
28
+ export { DEFAULT_INTERVAL_MS, MIN_INTERVAL_MS, type UseGenerationWatchOptions, type WatchGenerationInput, useGenerationWatch, watchGeneration };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Headless client for Throttle Builder: read published pages, parts, slots and site settings from a storefront, with Next.js cache, revalidation and preview helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -59,7 +59,7 @@
59
59
  ],
60
60
  "dependencies": {
61
61
  "server-only": "0.0.1",
62
- "@usethrottle/builder-schema": "^0.1.0"
62
+ "@usethrottle/builder-schema": "^0.1.2"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "next": ">=14",
@@ -89,7 +89,7 @@
89
89
  "access": "public"
90
90
  },
91
91
  "scripts": {
92
- "build": "tsup",
92
+ "build": "rm -rf dist && tsup && node scripts/check-dist.mjs",
93
93
  "test": "vitest run",
94
94
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
95
95
  }