@usethrottle/builder 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,5 @@
1
1
  # @usethrottle/builder
2
2
 
3
- > `"private": true` in `package.json` keeps release-publish from publishing `0.0.0`. Task 16 (the release task) removes it together with adding the changeset.
4
-
5
3
  Headless client for Throttle Builder. A merchant storefront reads published pages,
6
4
  header and footer parts, slots and site settings with it.
7
5
 
@@ -44,3 +42,17 @@ it (it makes that render dynamic, so call it only on a preview-only route) and g
44
42
  `useGenerationWatch({ builderKey, onChange })` is a client-side backstop for a missed
45
43
  notice: it reads the site generation (at most every 30 s, only while the tab is visible)
46
44
  and calls `onChange`, for example `() => router.refresh()`.
45
+
46
+ ## Build mode
47
+
48
+ `createBuilderClient({ mode: 'build', builderKey })` reads one frozen release at build time and makes
49
+ no other Builder request. `getReleaseBundle({ release? })` calls `GET /v1/releases/latest/bundle` or
50
+ `/v1/releases/:id/bundle` once per process; the release is the argument, else the client's `release`
51
+ option, else `BUILDER_RELEASE_ID`, else the newest. The key is a build key (`tb_pk_...` of a server
52
+ channel) or a secret key with `releases:read`. `site`, `pages`, `parts`, `slots` and `bundle` are
53
+ answered from the bundle, with no cache tags, watcher or notices. A bundle is read into memory whole (up to
54
+ 48 MB), and a 2xx body that is cut short fails with "bundle truncated (too large or interrupted)". A build that
55
+ holds its bundle already (`releaseBundle`, for example the file `create-store` writes at build) makes no request
56
+ and needs no key. The announcement window is decided
57
+ on every read from the clock (`now`). A release that cannot be read throws
58
+ (`BuilderReleaseNotFoundError`, `BuilderUnavailableError`). See `/docs/developers/builder-delivery-modes`.
package/dist/index.cjs CHANGED
@@ -32,9 +32,16 @@ var PreviewExpiredError = class extends Error {
32
32
  this.name = "PreviewExpiredError";
33
33
  }
34
34
  };
35
-
36
- // src/client.ts
37
- var _builderschema = require('@usethrottle/builder-schema');
35
+ var BuilderReleaseNotFoundError = class extends Error {
36
+ constructor(release) {
37
+ super(
38
+ release === "latest" ? "This Builder site has no release yet. Press Release in the Builder, then build again." : `Builder has no release "${release}" for this site. Check BUILDER_RELEASE_ID.`
39
+ );
40
+ _chunkUFIR4HJAcjs.__publicField.call(void 0, this, "release");
41
+ this.name = "BuilderReleaseNotFoundError";
42
+ this.release = release;
43
+ }
44
+ };
38
45
 
39
46
  // src/cache.ts
40
47
  var UNTIL_CHANGED_REVALIDATE_S = 3600;
@@ -43,6 +50,31 @@ function cacheInit(tags, preview) {
43
50
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
44
51
  }
45
52
 
53
+ // src/documents.ts
54
+ var _builderschema = require('@usethrottle/builder-schema');
55
+ var MAX_NAME_CHARS = 128;
56
+ function isRecord(value) {
57
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58
+ }
59
+ function checkName(kind, value) {
60
+ if (typeof value !== "string" || value === "" || value.length > MAX_NAME_CHARS)
61
+ throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
62
+ return value;
63
+ }
64
+ function currentDocument(answer, where) {
65
+ const doc = answer.document;
66
+ if (!isRecord(doc))
67
+ throw new BuilderUnavailableError("invalid-response", `Builder ${where} answer has no document`);
68
+ if (doc.schemaVersion === _builderschema.CURRENT_SCHEMA_VERSION) return doc;
69
+ const upgraded = _builderschema.upgradeDocument.call(void 0, doc);
70
+ if (!upgraded.ok)
71
+ throw new BuilderUnavailableError(
72
+ "unsupported-document",
73
+ `Builder ${where} document cannot be read by this SDK version (${_nullishCoalesce(_optionalChain([upgraded, 'access', _ => _.issues, 'access', _2 => _2[0], 'optionalAccess', _3 => _3.code]), () => ( "invalid"))})`
74
+ );
75
+ return upgraded.doc;
76
+ }
77
+
46
78
  // src/last-good.ts
47
79
  var LAST_GOOD_MS = 10 * 60 * 1e3;
48
80
  var MAX_ENTRIES = 200;
@@ -69,92 +101,301 @@ function recallGood(key, warn) {
69
101
  return { value: entry.value };
70
102
  }
71
103
 
72
- // src/client.ts
104
+ // src/release.ts
105
+
73
106
  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);
107
+ var DEFAULT_BUNDLE_TIMEOUT_MS = 6e4;
108
+ var SUPPORTED_BUNDLE_VERSION = 1;
109
+ var RELEASE_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/u;
110
+ function fromEnvironment() {
111
+ const env = _optionalChain([globalThis, 'access', _4 => _4.process, 'optionalAccess', _5 => _5.env]);
112
+ const value = _optionalChain([env, 'optionalAccess', _6 => _6.BUILDER_RELEASE_ID, 'optionalAccess', _7 => _7.trim, 'call', _8 => _8()]);
113
+ return value === void 0 || value === "" ? void 0 : value;
78
114
  }
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("&")}`;
115
+ function releaseRef(argument, pinned) {
116
+ const given = argument !== void 0 && argument !== "" ? argument : pinned !== void 0 && pinned !== "" ? pinned : void 0;
117
+ const ref = _nullishCoalesce(_nullishCoalesce(given, () => ( fromEnvironment())), () => ( "latest"));
118
+ if (ref === "latest" || RELEASE_ID_RE.test(ref)) return ref;
119
+ throw new TypeError(
120
+ `${given !== void 0 ? "The release" : "BUILDER_RELEASE_ID"} "${ref.slice(0, 64)}" is not a Builder release id. Use the 26-character id shown in the Builder release history, or leave it unset to build the newest release.`
121
+ );
82
122
  }
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;
123
+ var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
124
+ function readDocument(value, where) {
125
+ if (!isRecord(value) || typeof value.version !== "number") throw invalid(`Builder release ${where} is malformed`);
126
+ return { version: value.version, document: currentDocument(value, where) };
87
127
  }
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 === _builderschema.CURRENT_SCHEMA_VERSION) return doc;
93
- const upgraded = _builderschema.upgradeDocument.call(void 0, doc);
94
- if (!upgraded.ok)
128
+ function readPage(value) {
129
+ if (!isRecord(value) || typeof value.slug !== "string" || typeof value.id !== "string" || typeof value.path !== "string" || typeof value.pageType !== "string" || !isRecord(value.title) || !isRecord(value.seo))
130
+ throw invalid("Builder release has a page without its fields");
131
+ return { ...value, document: currentDocument(value, `page ${value.slug}`) };
132
+ }
133
+ function readBundle(body) {
134
+ if (!isRecord(body)) throw invalid("Builder answered a release bundle that is not an object");
135
+ if (body.bundleVersion !== SUPPORTED_BUNDLE_VERSION)
95
136
  throw new BuilderUnavailableError(
96
137
  "unsupported-document",
97
- `Builder ${where} document cannot be read by this SDK version (${_nullishCoalesce(_optionalChain([upgraded, 'access', _ => _.issues, 'access', _2 => _2[0], 'optionalAccess', _3 => _3.code]), () => ( "invalid"))})`
138
+ `This SDK reads release bundle version ${String(SUPPORTED_BUNDLE_VERSION)}, and Builder sent ${String(body.bundleVersion)}. Update @usethrottle/builder.`
98
139
  );
99
- return upgraded.doc;
140
+ if (typeof body.releaseId !== "string" || typeof body.generation !== "number" || typeof body.siteVersion !== "number" || typeof body.defaultLocale !== "string" || !Array.isArray(body.pages) || !isRecord(body.site) || !isRecord(body.site[body.defaultLocale]) || !isRecord(body.slots) || !isRecord(body.redirects))
141
+ throw invalid("Builder release bundle is missing fields");
142
+ return {
143
+ ...body,
144
+ pages: body.pages.map(readPage),
145
+ header: readDocument(body.header, "header"),
146
+ footer: readDocument(body.footer, "footer"),
147
+ slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)]))
148
+ };
149
+ }
150
+ async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
151
+ const headers = { accept: "application/json" };
152
+ if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
153
+ else headers["X-Builder-Key"] = key;
154
+ const controller = new AbortController();
155
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
156
+ let status;
157
+ let body;
158
+ let unreadable;
159
+ try {
160
+ const response = await (_nullishCoalesce(doFetch, () => ( globalThis.fetch)))(`${base}/v1/releases/${ref}/bundle`, {
161
+ method: "GET",
162
+ headers,
163
+ signal: controller.signal
164
+ });
165
+ status = response.status;
166
+ try {
167
+ body = await response.json();
168
+ } catch (cause) {
169
+ if (controller.signal.aborted) throw cause;
170
+ unreadable = cause;
171
+ body = void 0;
172
+ }
173
+ } catch (cause) {
174
+ throw new BuilderUnavailableError(
175
+ controller.signal.aborted ? "timeout" : "network",
176
+ controller.signal.aborted ? `Builder did not send the release bundle within ${String(timeoutMs)} ms` : "Builder could not be reached to read the release bundle",
177
+ { cause }
178
+ );
179
+ } finally {
180
+ clearTimeout(timer);
181
+ }
182
+ if (unreadable !== void 0 && status >= 200 && status < 300)
183
+ throw new BuilderUnavailableError(
184
+ "invalid-response",
185
+ "Builder release bundle truncated (too large or interrupted). A bundle is read into memory whole, up to 48 MB; retry the build, and check that its machine has the memory.",
186
+ { cause: unreadable }
187
+ );
188
+ if (status === 404) throw new BuilderReleaseNotFoundError(ref);
189
+ if (status === 401 || status === 403)
190
+ throw new BuilderUnavailableError(
191
+ "status",
192
+ `Builder refused the key (${String(status)}). A build reads with the publishable key of a server channel (tb_pk_...) or a secret key holding releases:read, never a browser key.`,
193
+ { status }
194
+ );
195
+ if (status < 200 || status >= 300)
196
+ throw new BuilderUnavailableError("status", `Builder answered ${String(status)} for the release bundle`, { status });
197
+ return readBundle(body);
198
+ }
199
+ var STORE = /* @__PURE__ */ Symbol.for("@usethrottle/builder:release-bundles");
200
+ var stored = () => {
201
+ const holder = globalThis;
202
+ return _nullishCoalesce(holder[STORE], () => ( (holder[STORE] = /* @__PURE__ */ new Map())));
203
+ };
204
+ function loadOnce(load) {
205
+ const memo = stored();
206
+ const id = `${load.base}|${load.key}|${load.ref}`;
207
+ let held = memo.get(id);
208
+ if (held === void 0) {
209
+ held = fetchBundle(load);
210
+ memo.set(id, held);
211
+ held.catch(() => memo.delete(id));
212
+ }
213
+ return held;
214
+ }
215
+ var pick = (map, chain) => {
216
+ for (const locale of chain) {
217
+ const value = map === void 0 ? void 0 : map[locale];
218
+ if (typeof value === "string" && value !== "") return value;
219
+ }
220
+ return void 0;
221
+ };
222
+ var chainOf = (bundle, locale) => locale === void 0 || locale === bundle.defaultLocale ? [bundle.defaultLocale] : [locale, bundle.defaultLocale];
223
+ function siteFor(bundle, locale, now) {
224
+ const found = locale === void 0 ? void 0 : bundle.site[locale];
225
+ const settings = (_nullishCoalesce(found, () => ( bundle.site[bundle.defaultLocale]))).settings;
226
+ const announcement = settings.announcement;
227
+ const windowed = isRecord(announcement) ? {
228
+ ...settings,
229
+ announcement: {
230
+ ...announcement,
231
+ enabled: announcement.enabled === true && (announcement.startsAt == null || Date.parse(String(announcement.startsAt)) <= now) && (announcement.endsAt == null || now < Date.parse(String(announcement.endsAt)))
232
+ }
233
+ } : settings;
234
+ return { generation: bundle.generation, siteVersion: bundle.siteVersion, settings: windowed };
235
+ }
236
+ function summaryOf(page, chain) {
237
+ return {
238
+ id: page.id,
239
+ slug: page.slug,
240
+ pageType: page.pageType,
241
+ title: _nullishCoalesce(pick(page.title, chain), () => ( page.slug)),
242
+ updatedAt: page.publishedAt,
243
+ path: page.path,
244
+ noindex: page.seo.noindex === true
245
+ };
246
+ }
247
+ function pageFor(bundle, slug, chain) {
248
+ const page = bundle.pages.find((candidate) => candidate.slug === slug);
249
+ if (page === void 0) {
250
+ if (Object.hasOwn(bundle.redirects, slug)) return { redirectTo: bundle.redirects[slug] };
251
+ throw new BuilderNotFoundError(slug);
252
+ }
253
+ const title = pick(page.seo.title, chain);
254
+ const description = pick(page.seo.description, chain);
255
+ return {
256
+ ...summaryOf(page, chain),
257
+ generation: bundle.generation,
258
+ siteVersion: bundle.siteVersion,
259
+ version: page.version,
260
+ seo: {
261
+ ...title === void 0 ? {} : { title },
262
+ ...description === void 0 ? {} : { description },
263
+ shareImage: page.seo.shareImage,
264
+ noindex: page.seo.noindex
265
+ },
266
+ document: page.document
267
+ };
268
+ }
269
+ var documentOf = (bundle, held) => ({
270
+ generation: bundle.generation,
271
+ document: held === void 0 ? _builderschema.emptyDocument.call(void 0, ) : held.document
272
+ });
273
+ function createBuildClient(options) {
274
+ const builderKey = _nullishCoalesce(options.builderKey, () => ( ""));
275
+ if (typeof builderKey !== "string" || builderKey === "" && options.releaseBundle === void 0)
276
+ throw new TypeError("createBuilderClient needs a builderKey");
277
+ const base = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL))).replace(/\/+$/u, "");
278
+ const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( DEFAULT_BUNDLE_TIMEOUT_MS));
279
+ const clock = _nullishCoalesce(options.now, () => ( Date.now));
280
+ const getReleaseBundle = async ({ release } = {}) => {
281
+ if (options.releaseBundle !== void 0) return options.releaseBundle;
282
+ return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch });
283
+ };
284
+ return {
285
+ mode: "build",
286
+ getReleaseBundle,
287
+ site: async ({ locale } = {}) => siteFor(await getReleaseBundle(), locale, clock()),
288
+ pages: {
289
+ list: async () => {
290
+ const bundle = await getReleaseBundle();
291
+ const chain = chainOf(bundle, void 0);
292
+ return bundle.pages.map((page) => summaryOf(page, chain));
293
+ },
294
+ get: async (slug, { locale } = {}) => {
295
+ const bundle = await getReleaseBundle();
296
+ return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
297
+ }
298
+ },
299
+ parts: {
300
+ get: async (name) => {
301
+ if (name !== "header" && name !== "footer") throw new TypeError('A Builder part is "header" or "footer"');
302
+ const bundle = await getReleaseBundle();
303
+ return documentOf(bundle, bundle[name]);
304
+ }
305
+ },
306
+ slots: {
307
+ get: async (name) => {
308
+ checkName("slot name", name);
309
+ const bundle = await getReleaseBundle();
310
+ return documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0);
311
+ }
312
+ },
313
+ bundle: async ({ page: pageSlug, slots, locale } = {}) => {
314
+ const names = [...new Set(_nullishCoalesce(slots, () => ( [])))].map((name) => checkName("slot name", name)).sort();
315
+ if (pageSlug !== void 0) checkName("page slug", pageSlug);
316
+ const bundle = await getReleaseBundle();
317
+ return {
318
+ generation: bundle.generation,
319
+ site: siteFor(bundle, locale, clock()),
320
+ header: documentOf(bundle, bundle.header),
321
+ footer: documentOf(bundle, bundle.footer),
322
+ ...pageSlug === void 0 ? {} : { page: pageFor(bundle, pageSlug, chainOf(bundle, locale)) },
323
+ slots: Object.fromEntries(
324
+ names.map((name) => [name, documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0)])
325
+ )
326
+ };
327
+ }
328
+ };
329
+ }
330
+
331
+ // src/client.ts
332
+ var DEFAULT_BASE_URL2 = "https://builder.usethrottle.dev";
333
+ var DEFAULT_TIMEOUT_MS = 3e3;
334
+ function queryString(query) {
335
+ const pairs = Object.entries(query).filter((entry) => entry[1] !== void 0 && entry[1] !== "").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
336
+ return pairs.length === 0 ? "" : `?${pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")}`;
100
337
  }
101
338
  function withDocument(answer, where) {
102
339
  return { ...answer, document: currentDocument(answer, where) };
103
340
  }
104
- var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
341
+ var invalid2 = (message) => new BuilderUnavailableError("invalid-response", message);
105
342
  function generationOf(answer, where) {
106
343
  const { generation } = answer;
107
344
  if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0)
108
- throw invalid(`Builder ${where} answer has no generation`);
345
+ throw invalid2(`Builder ${where} answer has no generation`);
109
346
  return generation;
110
347
  }
111
348
  function readSite(answer) {
112
349
  generationOf(answer, "site");
113
350
  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");
351
+ throw invalid2("Builder site answer has no siteVersion");
352
+ if (!isRecord(answer.settings)) throw invalid2("Builder site answer has no settings");
116
353
  return answer;
117
354
  }
118
355
  var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
119
356
  function readPages(answer) {
120
357
  const { pages } = answer;
121
- if (!Array.isArray(pages)) throw invalid("Builder pages answer is not a list");
358
+ if (!Array.isArray(pages)) throw invalid2("Builder pages answer is not a list");
122
359
  for (const page of pages)
123
360
  if (!isRecord(page) || SUMMARY_KEYS.some((key) => typeof page[key] !== "string"))
124
- throw invalid("Builder pages answer has a page without its fields");
361
+ throw invalid2("Builder pages answer has a page without its fields");
125
362
  return pages;
126
363
  }
127
- function readDocument(answer, where) {
364
+ function readDocument2(answer, where) {
128
365
  generationOf(answer, where);
129
366
  return withDocument(answer, where);
130
367
  }
131
- function readPage(answer) {
368
+ function readPage2(answer) {
132
369
  if (typeof answer.redirectTo === "string") return { redirectTo: answer.redirectTo };
133
370
  generationOf(answer, "page");
134
- if (typeof answer.slug !== "string") throw invalid("Builder page answer has no slug");
371
+ if (typeof answer.slug !== "string") throw invalid2("Builder page answer has no slug");
135
372
  return withDocument(answer, "page");
136
373
  }
137
- function readBundle(answer) {
374
+ function readBundle2(answer) {
138
375
  const generation = generationOf(answer, "bundle");
139
376
  if (!isRecord(answer.site) || !isRecord(answer.header) || !isRecord(answer.footer))
140
- throw invalid("Builder bundle answer has no site, header or footer");
377
+ throw invalid2("Builder bundle answer has no site, header or footer");
141
378
  const slots = answer.slots === void 0 ? {} : answer.slots;
142
- if (!isRecord(slots)) throw invalid("Builder bundle answer has slots that are not an object");
379
+ if (!isRecord(slots)) throw invalid2("Builder bundle answer has slots that are not an object");
143
380
  return {
144
381
  generation,
145
382
  site: readSite(answer.site),
146
- header: readDocument(answer.header, "header"),
147
- footer: readDocument(answer.footer, "footer"),
148
- ...isRecord(answer.page) ? { page: readPage(answer.page) } : {},
383
+ header: readDocument2(answer.header, "header"),
384
+ footer: readDocument2(answer.footer, "footer"),
385
+ ...isRecord(answer.page) ? { page: readPage2(answer.page) } : {},
149
386
  slots: Object.fromEntries(
150
387
  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}`)];
388
+ if (!isRecord(value)) throw invalid2(`Builder slot ${name} answer is not an object`);
389
+ return [name, readDocument2(value, `slot ${name}`)];
153
390
  })
154
391
  )
155
392
  };
156
393
  }
157
394
  function createBuilderClient(options) {
395
+ if ("mode" in options && options.mode === "build") return createBuildClient(options);
396
+ return createLiveClient(options);
397
+ }
398
+ function createLiveClient(options) {
158
399
  const { builderKey, previewToken } = options;
159
400
  if (typeof builderKey !== "string" || builderKey === "")
160
401
  throw new TypeError("createBuilderClient needs a builderKey");
@@ -162,7 +403,7 @@ function createBuilderClient(options) {
162
403
  throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
163
404
  const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
164
405
  const preview = previewHeader !== void 0;
165
- const base = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL))).replace(/\/+$/u, "");
406
+ const base = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL2))).replace(/\/+$/u, "");
166
407
  const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( DEFAULT_TIMEOUT_MS));
167
408
  const doFetch = options.fetch;
168
409
  async function once(url, init) {
@@ -233,7 +474,7 @@ function createBuilderClient(options) {
233
474
  get: async (slug, { locale } = {}) => read(
234
475
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
235
476
  { query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.page(slug)], pageSlug: slug },
236
- readPage
477
+ readPage2
237
478
  )
238
479
  },
239
480
  parts: {
@@ -243,7 +484,7 @@ function createBuilderClient(options) {
243
484
  return read(
244
485
  `/v1/parts/${name}`,
245
486
  { query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.part(name)] },
246
- (answer) => readDocument(answer, `part ${name}`)
487
+ (answer) => readDocument2(answer, `part ${name}`)
247
488
  );
248
489
  }
249
490
  },
@@ -251,7 +492,7 @@ function createBuilderClient(options) {
251
492
  get: async (name, { locale } = {}) => read(
252
493
  `/v1/slots/${encodeURIComponent(checkName("slot name", name))}`,
253
494
  { query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.slot(name)] },
254
- (answer) => readDocument(answer, `slot ${name}`)
495
+ (answer) => readDocument2(answer, `slot ${name}`)
255
496
  )
256
497
  },
257
498
  bundle: async ({ page: pageSlug, slots, locale } = {}) => {
@@ -271,7 +512,7 @@ function createBuilderClient(options) {
271
512
  ...names.map((name) => _chunkUFIR4HJAcjs.BUILDER_TAGS.slot(name))
272
513
  ]
273
514
  },
274
- readBundle
515
+ readBundle2
275
516
  );
276
517
  }
277
518
  };
@@ -287,4 +528,6 @@ function createBuilderClient(options) {
287
528
 
288
529
 
289
530
 
290
- exports.BUILDER_TAGS = _chunkUFIR4HJAcjs.BUILDER_TAGS; exports.BuilderNotFoundError = BuilderNotFoundError; exports.BuilderUnavailableError = BuilderUnavailableError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = PreviewExpiredError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = createBuilderClient; exports.scopesToTags = _chunkUFIR4HJAcjs.scopesToTags; exports.verifyBuilderNotice = _chunkUFIR4HJAcjs.verifyBuilderNotice;
531
+
532
+
533
+ exports.BUILDER_TAGS = _chunkUFIR4HJAcjs.BUILDER_TAGS; exports.BuilderNotFoundError = BuilderNotFoundError; exports.BuilderReleaseNotFoundError = BuilderReleaseNotFoundError; exports.BuilderUnavailableError = BuilderUnavailableError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL2; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = createBuilderClient; exports.scopesToTags = _chunkUFIR4HJAcjs.scopesToTags; exports.verifyBuilderNotice = _chunkUFIR4HJAcjs.verifyBuilderNotice;
package/dist/index.d.cts CHANGED
@@ -30,6 +30,16 @@ declare class BuilderNotFoundError extends Error {
30
30
  declare class PreviewExpiredError extends Error {
31
31
  constructor();
32
32
  }
33
+ /**
34
+ * The release a build asked for does not exist (`404 RELEASE_NOT_FOUND`): a wrong
35
+ * `BUILDER_RELEASE_ID`, a release pruned from the history, or, for `latest`, a
36
+ * site that has never been released. A build with no release must fail, not
37
+ * publish an empty store.
38
+ */
39
+ declare class BuilderReleaseNotFoundError extends Error {
40
+ readonly release: string;
41
+ constructor(release: string);
42
+ }
33
43
 
34
44
  /** Published site settings resolved for one locale (localized values are strings). */
35
45
  type BuilderSite = {
@@ -44,6 +54,8 @@ type BuilderPageSummary = {
44
54
  title: string;
45
55
  updatedAt: string;
46
56
  path: string;
57
+ /** The page asks search engines to skip it (`seo.noindex`). Absent from a Worker that predates it. */
58
+ noindex?: boolean;
47
59
  };
48
60
  /** A published page: its metadata and its document (with frozen custom widgets and assets). */
49
61
  type LoadedPage = BuilderPageSummary & {
@@ -89,6 +101,8 @@ type LocaleOptions = {
89
101
  locale?: string;
90
102
  };
91
103
  type BuilderClient = {
104
+ /** `build` for a client made with `mode: 'build'`: it reads a frozen release and never the live API. */
105
+ readonly mode?: 'live' | 'build';
92
106
  site(options?: LocaleOptions): Promise<BuilderSite>;
93
107
  pages: {
94
108
  list(): Promise<BuilderPageSummary[]>;
@@ -105,11 +119,119 @@ type BuilderClient = {
105
119
  slots?: readonly string[];
106
120
  }): Promise<BuilderBundle>;
107
121
  };
122
+ /** A published part or slot as a release holds it. */
123
+ type ReleaseDocument = {
124
+ version: number;
125
+ document: PageDocument;
126
+ };
127
+ /** One page of a release. Titles and `seo` text keep their locale maps; the document does too. */
128
+ type ReleasePage = {
129
+ id: string;
130
+ slug: string;
131
+ pageType: string;
132
+ path: string;
133
+ version: number;
134
+ publishedAt: string;
135
+ title: Record<string, string>;
136
+ seo: {
137
+ title?: Record<string, string>;
138
+ description?: Record<string, string>;
139
+ shareImage: unknown;
140
+ noindex: boolean;
141
+ };
142
+ document: PageDocument;
143
+ };
144
+ /**
145
+ * The whole site as one release froze it: `GET /v1/releases/:id/bundle`. The
146
+ * same release id always gives the same bundle. `site` holds the settings
147
+ * resolved for each locale of the site; the announcement is NOT windowed in it
148
+ * (`announcement.enabled` is the merchant's switch, `startsAt` and `endsAt`
149
+ * beside it), because the moment of a visit is not known when a release is
150
+ * built. The build client decides it at every read.
151
+ */
152
+ type ReleaseBundle = {
153
+ bundleVersion: number;
154
+ releaseId: string;
155
+ kind: 'release' | 'rollback';
156
+ sourceReleaseId: string | null;
157
+ createdAt: string;
158
+ generation: number;
159
+ siteVersion: number;
160
+ defaultLocale: string;
161
+ locales: string[];
162
+ site: Record<string, {
163
+ brand: {
164
+ storeName: string;
165
+ };
166
+ settings: Record<string, unknown>;
167
+ }>;
168
+ pages: ReleasePage[];
169
+ header: ReleaseDocument;
170
+ footer: ReleaseDocument;
171
+ slots: Record<string, ReleaseDocument>;
172
+ /** An old slug and the store path of the page that lives there now. */
173
+ redirects: Record<string, string>;
174
+ /** The status each frozen custom widget had when the release was made. */
175
+ customWidgets: Record<string, 'active' | 'disabled'>;
176
+ };
177
+ type BuildClientCommon = {
178
+ mode: 'build';
179
+ /** Defaults to `https://builder.usethrottle.dev`. */
180
+ baseUrl?: string;
181
+ fetch?: typeof fetch;
182
+ /** The bundle read, body included. Default 60000 (a bundle is the whole site). */
183
+ timeoutMs?: number;
184
+ /**
185
+ * The release this client reads, instead of `BUILDER_RELEASE_ID`. A store sets it from a value Next inlines at
186
+ * build, so a page Next renders again later reads the release it was built from, not a newer one.
187
+ */
188
+ release?: string;
189
+ /** The clock that decides the announcement window at every read. Default `Date.now`. */
190
+ now?: () => number;
191
+ };
192
+ /**
193
+ * A build client needs a way to get its release: a key to read it with, or a bundle you already hold (a fixture, a
194
+ * file read at build). With neither the call does not compile.
195
+ */
196
+ type BuildClientOptions = BuildClientCommon & ({
197
+ /**
198
+ * A publishable key of a server channel (`tb_pk_...`, the build key), or a secret key holding
199
+ * `releases:read` (`tb_sk_...`). Keep it on the server and in your build; never in a `NEXT_PUBLIC_` variable.
200
+ */
201
+ builderKey: string;
202
+ /** A bundle you already hold: the client then makes no request at all. */
203
+ releaseBundle?: ReleaseBundle;
204
+ } | {
205
+ /** A bundle you already hold: the client then makes no request at all and needs no key. */
206
+ releaseBundle: ReleaseBundle;
207
+ builderKey?: string;
208
+ });
209
+ type BuildBuilderClient = BuilderClient & {
210
+ readonly mode: 'build';
211
+ /**
212
+ * The release's bundle, read once per process and kept in memory. The release
213
+ * is `release` when given, else the `BUILDER_RELEASE_ID` environment variable,
214
+ * else the newest (`latest`). Every other read of this client (`site`, `pages`,
215
+ * `parts`, `slots`, `bundle`) is answered from this bundle with no request.
216
+ */
217
+ getReleaseBundle(options?: {
218
+ release?: string;
219
+ }): Promise<ReleaseBundle>;
220
+ };
108
221
 
109
222
  declare const DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
110
223
  declare const DEFAULT_TIMEOUT_MS = 3000;
224
+ /**
225
+ * `mode: 'build'` makes the client of a build-time site: it reads one frozen
226
+ * release (`getReleaseBundle`) and answers every other read from it. Without a
227
+ * mode, the client reads the live API.
228
+ */
229
+ declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
111
230
  declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
112
231
 
232
+ /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
233
+ declare const SUPPORTED_BUNDLE_VERSION = 1;
234
+
113
235
  declare const BUILDER_TAGS: {
114
236
  readonly all: "throttle-builder";
115
237
  readonly site: "throttle-builder:site";
@@ -130,4 +252,4 @@ declare function scopesToTags(scopes: readonly string[]): string[];
130
252
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
131
253
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
132
254
 
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 };
255
+ export { BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, SUPPORTED_BUNDLE_VERSION, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags };
package/dist/index.d.ts CHANGED
@@ -30,6 +30,16 @@ declare class BuilderNotFoundError extends Error {
30
30
  declare class PreviewExpiredError extends Error {
31
31
  constructor();
32
32
  }
33
+ /**
34
+ * The release a build asked for does not exist (`404 RELEASE_NOT_FOUND`): a wrong
35
+ * `BUILDER_RELEASE_ID`, a release pruned from the history, or, for `latest`, a
36
+ * site that has never been released. A build with no release must fail, not
37
+ * publish an empty store.
38
+ */
39
+ declare class BuilderReleaseNotFoundError extends Error {
40
+ readonly release: string;
41
+ constructor(release: string);
42
+ }
33
43
 
34
44
  /** Published site settings resolved for one locale (localized values are strings). */
35
45
  type BuilderSite = {
@@ -44,6 +54,8 @@ type BuilderPageSummary = {
44
54
  title: string;
45
55
  updatedAt: string;
46
56
  path: string;
57
+ /** The page asks search engines to skip it (`seo.noindex`). Absent from a Worker that predates it. */
58
+ noindex?: boolean;
47
59
  };
48
60
  /** A published page: its metadata and its document (with frozen custom widgets and assets). */
49
61
  type LoadedPage = BuilderPageSummary & {
@@ -89,6 +101,8 @@ type LocaleOptions = {
89
101
  locale?: string;
90
102
  };
91
103
  type BuilderClient = {
104
+ /** `build` for a client made with `mode: 'build'`: it reads a frozen release and never the live API. */
105
+ readonly mode?: 'live' | 'build';
92
106
  site(options?: LocaleOptions): Promise<BuilderSite>;
93
107
  pages: {
94
108
  list(): Promise<BuilderPageSummary[]>;
@@ -105,11 +119,119 @@ type BuilderClient = {
105
119
  slots?: readonly string[];
106
120
  }): Promise<BuilderBundle>;
107
121
  };
122
+ /** A published part or slot as a release holds it. */
123
+ type ReleaseDocument = {
124
+ version: number;
125
+ document: PageDocument;
126
+ };
127
+ /** One page of a release. Titles and `seo` text keep their locale maps; the document does too. */
128
+ type ReleasePage = {
129
+ id: string;
130
+ slug: string;
131
+ pageType: string;
132
+ path: string;
133
+ version: number;
134
+ publishedAt: string;
135
+ title: Record<string, string>;
136
+ seo: {
137
+ title?: Record<string, string>;
138
+ description?: Record<string, string>;
139
+ shareImage: unknown;
140
+ noindex: boolean;
141
+ };
142
+ document: PageDocument;
143
+ };
144
+ /**
145
+ * The whole site as one release froze it: `GET /v1/releases/:id/bundle`. The
146
+ * same release id always gives the same bundle. `site` holds the settings
147
+ * resolved for each locale of the site; the announcement is NOT windowed in it
148
+ * (`announcement.enabled` is the merchant's switch, `startsAt` and `endsAt`
149
+ * beside it), because the moment of a visit is not known when a release is
150
+ * built. The build client decides it at every read.
151
+ */
152
+ type ReleaseBundle = {
153
+ bundleVersion: number;
154
+ releaseId: string;
155
+ kind: 'release' | 'rollback';
156
+ sourceReleaseId: string | null;
157
+ createdAt: string;
158
+ generation: number;
159
+ siteVersion: number;
160
+ defaultLocale: string;
161
+ locales: string[];
162
+ site: Record<string, {
163
+ brand: {
164
+ storeName: string;
165
+ };
166
+ settings: Record<string, unknown>;
167
+ }>;
168
+ pages: ReleasePage[];
169
+ header: ReleaseDocument;
170
+ footer: ReleaseDocument;
171
+ slots: Record<string, ReleaseDocument>;
172
+ /** An old slug and the store path of the page that lives there now. */
173
+ redirects: Record<string, string>;
174
+ /** The status each frozen custom widget had when the release was made. */
175
+ customWidgets: Record<string, 'active' | 'disabled'>;
176
+ };
177
+ type BuildClientCommon = {
178
+ mode: 'build';
179
+ /** Defaults to `https://builder.usethrottle.dev`. */
180
+ baseUrl?: string;
181
+ fetch?: typeof fetch;
182
+ /** The bundle read, body included. Default 60000 (a bundle is the whole site). */
183
+ timeoutMs?: number;
184
+ /**
185
+ * The release this client reads, instead of `BUILDER_RELEASE_ID`. A store sets it from a value Next inlines at
186
+ * build, so a page Next renders again later reads the release it was built from, not a newer one.
187
+ */
188
+ release?: string;
189
+ /** The clock that decides the announcement window at every read. Default `Date.now`. */
190
+ now?: () => number;
191
+ };
192
+ /**
193
+ * A build client needs a way to get its release: a key to read it with, or a bundle you already hold (a fixture, a
194
+ * file read at build). With neither the call does not compile.
195
+ */
196
+ type BuildClientOptions = BuildClientCommon & ({
197
+ /**
198
+ * A publishable key of a server channel (`tb_pk_...`, the build key), or a secret key holding
199
+ * `releases:read` (`tb_sk_...`). Keep it on the server and in your build; never in a `NEXT_PUBLIC_` variable.
200
+ */
201
+ builderKey: string;
202
+ /** A bundle you already hold: the client then makes no request at all. */
203
+ releaseBundle?: ReleaseBundle;
204
+ } | {
205
+ /** A bundle you already hold: the client then makes no request at all and needs no key. */
206
+ releaseBundle: ReleaseBundle;
207
+ builderKey?: string;
208
+ });
209
+ type BuildBuilderClient = BuilderClient & {
210
+ readonly mode: 'build';
211
+ /**
212
+ * The release's bundle, read once per process and kept in memory. The release
213
+ * is `release` when given, else the `BUILDER_RELEASE_ID` environment variable,
214
+ * else the newest (`latest`). Every other read of this client (`site`, `pages`,
215
+ * `parts`, `slots`, `bundle`) is answered from this bundle with no request.
216
+ */
217
+ getReleaseBundle(options?: {
218
+ release?: string;
219
+ }): Promise<ReleaseBundle>;
220
+ };
108
221
 
109
222
  declare const DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
110
223
  declare const DEFAULT_TIMEOUT_MS = 3000;
224
+ /**
225
+ * `mode: 'build'` makes the client of a build-time site: it reads one frozen
226
+ * release (`getReleaseBundle`) and answers every other read from it. Without a
227
+ * mode, the client reads the live API.
228
+ */
229
+ declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
111
230
  declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
112
231
 
232
+ /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
233
+ declare const SUPPORTED_BUNDLE_VERSION = 1;
234
+
113
235
  declare const BUILDER_TAGS: {
114
236
  readonly all: "throttle-builder";
115
237
  readonly site: "throttle-builder:site";
@@ -130,4 +252,4 @@ declare function scopesToTags(scopes: readonly string[]): string[];
130
252
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
131
253
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
132
254
 
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 };
255
+ export { BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, SUPPORTED_BUNDLE_VERSION, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags };
package/dist/index.js CHANGED
@@ -32,9 +32,16 @@ var PreviewExpiredError = class extends Error {
32
32
  this.name = "PreviewExpiredError";
33
33
  }
34
34
  };
35
-
36
- // src/client.ts
37
- import { CURRENT_SCHEMA_VERSION, upgradeDocument } from "@usethrottle/builder-schema";
35
+ var BuilderReleaseNotFoundError = class extends Error {
36
+ constructor(release) {
37
+ super(
38
+ release === "latest" ? "This Builder site has no release yet. Press Release in the Builder, then build again." : `Builder has no release "${release}" for this site. Check BUILDER_RELEASE_ID.`
39
+ );
40
+ __publicField(this, "release");
41
+ this.name = "BuilderReleaseNotFoundError";
42
+ this.release = release;
43
+ }
44
+ };
38
45
 
39
46
  // src/cache.ts
40
47
  var UNTIL_CHANGED_REVALIDATE_S = 3600;
@@ -43,6 +50,31 @@ function cacheInit(tags, preview) {
43
50
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
44
51
  }
45
52
 
53
+ // src/documents.ts
54
+ import { CURRENT_SCHEMA_VERSION, upgradeDocument } from "@usethrottle/builder-schema";
55
+ var MAX_NAME_CHARS = 128;
56
+ function isRecord(value) {
57
+ return typeof value === "object" && value !== null && !Array.isArray(value);
58
+ }
59
+ function checkName(kind, value) {
60
+ if (typeof value !== "string" || value === "" || value.length > MAX_NAME_CHARS)
61
+ throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
62
+ return value;
63
+ }
64
+ function currentDocument(answer, where) {
65
+ const doc = answer.document;
66
+ if (!isRecord(doc))
67
+ throw new BuilderUnavailableError("invalid-response", `Builder ${where} answer has no document`);
68
+ if (doc.schemaVersion === CURRENT_SCHEMA_VERSION) return doc;
69
+ const upgraded = upgradeDocument(doc);
70
+ if (!upgraded.ok)
71
+ throw new BuilderUnavailableError(
72
+ "unsupported-document",
73
+ `Builder ${where} document cannot be read by this SDK version (${upgraded.issues[0]?.code ?? "invalid"})`
74
+ );
75
+ return upgraded.doc;
76
+ }
77
+
46
78
  // src/last-good.ts
47
79
  var LAST_GOOD_MS = 10 * 60 * 1e3;
48
80
  var MAX_ENTRIES = 200;
@@ -69,92 +101,301 @@ function recallGood(key, warn) {
69
101
  return { value: entry.value };
70
102
  }
71
103
 
72
- // src/client.ts
104
+ // src/release.ts
105
+ import { emptyDocument } from "@usethrottle/builder-schema";
73
106
  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);
107
+ var DEFAULT_BUNDLE_TIMEOUT_MS = 6e4;
108
+ var SUPPORTED_BUNDLE_VERSION = 1;
109
+ var RELEASE_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/u;
110
+ function fromEnvironment() {
111
+ const env = globalThis.process?.env;
112
+ const value = env?.BUILDER_RELEASE_ID?.trim();
113
+ return value === void 0 || value === "" ? void 0 : value;
78
114
  }
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("&")}`;
115
+ function releaseRef(argument, pinned) {
116
+ const given = argument !== void 0 && argument !== "" ? argument : pinned !== void 0 && pinned !== "" ? pinned : void 0;
117
+ const ref = given ?? fromEnvironment() ?? "latest";
118
+ if (ref === "latest" || RELEASE_ID_RE.test(ref)) return ref;
119
+ throw new TypeError(
120
+ `${given !== void 0 ? "The release" : "BUILDER_RELEASE_ID"} "${ref.slice(0, 64)}" is not a Builder release id. Use the 26-character id shown in the Builder release history, or leave it unset to build the newest release.`
121
+ );
82
122
  }
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;
123
+ var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
124
+ function readDocument(value, where) {
125
+ if (!isRecord(value) || typeof value.version !== "number") throw invalid(`Builder release ${where} is malformed`);
126
+ return { version: value.version, document: currentDocument(value, where) };
87
127
  }
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)
128
+ function readPage(value) {
129
+ if (!isRecord(value) || typeof value.slug !== "string" || typeof value.id !== "string" || typeof value.path !== "string" || typeof value.pageType !== "string" || !isRecord(value.title) || !isRecord(value.seo))
130
+ throw invalid("Builder release has a page without its fields");
131
+ return { ...value, document: currentDocument(value, `page ${value.slug}`) };
132
+ }
133
+ function readBundle(body) {
134
+ if (!isRecord(body)) throw invalid("Builder answered a release bundle that is not an object");
135
+ if (body.bundleVersion !== SUPPORTED_BUNDLE_VERSION)
95
136
  throw new BuilderUnavailableError(
96
137
  "unsupported-document",
97
- `Builder ${where} document cannot be read by this SDK version (${upgraded.issues[0]?.code ?? "invalid"})`
138
+ `This SDK reads release bundle version ${String(SUPPORTED_BUNDLE_VERSION)}, and Builder sent ${String(body.bundleVersion)}. Update @usethrottle/builder.`
98
139
  );
99
- return upgraded.doc;
140
+ if (typeof body.releaseId !== "string" || typeof body.generation !== "number" || typeof body.siteVersion !== "number" || typeof body.defaultLocale !== "string" || !Array.isArray(body.pages) || !isRecord(body.site) || !isRecord(body.site[body.defaultLocale]) || !isRecord(body.slots) || !isRecord(body.redirects))
141
+ throw invalid("Builder release bundle is missing fields");
142
+ return {
143
+ ...body,
144
+ pages: body.pages.map(readPage),
145
+ header: readDocument(body.header, "header"),
146
+ footer: readDocument(body.footer, "footer"),
147
+ slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)]))
148
+ };
149
+ }
150
+ async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
151
+ const headers = { accept: "application/json" };
152
+ if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
153
+ else headers["X-Builder-Key"] = key;
154
+ const controller = new AbortController();
155
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
156
+ let status;
157
+ let body;
158
+ let unreadable;
159
+ try {
160
+ const response = await (doFetch ?? globalThis.fetch)(`${base}/v1/releases/${ref}/bundle`, {
161
+ method: "GET",
162
+ headers,
163
+ signal: controller.signal
164
+ });
165
+ status = response.status;
166
+ try {
167
+ body = await response.json();
168
+ } catch (cause) {
169
+ if (controller.signal.aborted) throw cause;
170
+ unreadable = cause;
171
+ body = void 0;
172
+ }
173
+ } catch (cause) {
174
+ throw new BuilderUnavailableError(
175
+ controller.signal.aborted ? "timeout" : "network",
176
+ controller.signal.aborted ? `Builder did not send the release bundle within ${String(timeoutMs)} ms` : "Builder could not be reached to read the release bundle",
177
+ { cause }
178
+ );
179
+ } finally {
180
+ clearTimeout(timer);
181
+ }
182
+ if (unreadable !== void 0 && status >= 200 && status < 300)
183
+ throw new BuilderUnavailableError(
184
+ "invalid-response",
185
+ "Builder release bundle truncated (too large or interrupted). A bundle is read into memory whole, up to 48 MB; retry the build, and check that its machine has the memory.",
186
+ { cause: unreadable }
187
+ );
188
+ if (status === 404) throw new BuilderReleaseNotFoundError(ref);
189
+ if (status === 401 || status === 403)
190
+ throw new BuilderUnavailableError(
191
+ "status",
192
+ `Builder refused the key (${String(status)}). A build reads with the publishable key of a server channel (tb_pk_...) or a secret key holding releases:read, never a browser key.`,
193
+ { status }
194
+ );
195
+ if (status < 200 || status >= 300)
196
+ throw new BuilderUnavailableError("status", `Builder answered ${String(status)} for the release bundle`, { status });
197
+ return readBundle(body);
198
+ }
199
+ var STORE = /* @__PURE__ */ Symbol.for("@usethrottle/builder:release-bundles");
200
+ var stored = () => {
201
+ const holder = globalThis;
202
+ return holder[STORE] ?? (holder[STORE] = /* @__PURE__ */ new Map());
203
+ };
204
+ function loadOnce(load) {
205
+ const memo = stored();
206
+ const id = `${load.base}|${load.key}|${load.ref}`;
207
+ let held = memo.get(id);
208
+ if (held === void 0) {
209
+ held = fetchBundle(load);
210
+ memo.set(id, held);
211
+ held.catch(() => memo.delete(id));
212
+ }
213
+ return held;
214
+ }
215
+ var pick = (map, chain) => {
216
+ for (const locale of chain) {
217
+ const value = map === void 0 ? void 0 : map[locale];
218
+ if (typeof value === "string" && value !== "") return value;
219
+ }
220
+ return void 0;
221
+ };
222
+ var chainOf = (bundle, locale) => locale === void 0 || locale === bundle.defaultLocale ? [bundle.defaultLocale] : [locale, bundle.defaultLocale];
223
+ function siteFor(bundle, locale, now) {
224
+ const found = locale === void 0 ? void 0 : bundle.site[locale];
225
+ const settings = (found ?? bundle.site[bundle.defaultLocale]).settings;
226
+ const announcement = settings.announcement;
227
+ const windowed = isRecord(announcement) ? {
228
+ ...settings,
229
+ announcement: {
230
+ ...announcement,
231
+ enabled: announcement.enabled === true && (announcement.startsAt == null || Date.parse(String(announcement.startsAt)) <= now) && (announcement.endsAt == null || now < Date.parse(String(announcement.endsAt)))
232
+ }
233
+ } : settings;
234
+ return { generation: bundle.generation, siteVersion: bundle.siteVersion, settings: windowed };
235
+ }
236
+ function summaryOf(page, chain) {
237
+ return {
238
+ id: page.id,
239
+ slug: page.slug,
240
+ pageType: page.pageType,
241
+ title: pick(page.title, chain) ?? page.slug,
242
+ updatedAt: page.publishedAt,
243
+ path: page.path,
244
+ noindex: page.seo.noindex === true
245
+ };
246
+ }
247
+ function pageFor(bundle, slug, chain) {
248
+ const page = bundle.pages.find((candidate) => candidate.slug === slug);
249
+ if (page === void 0) {
250
+ if (Object.hasOwn(bundle.redirects, slug)) return { redirectTo: bundle.redirects[slug] };
251
+ throw new BuilderNotFoundError(slug);
252
+ }
253
+ const title = pick(page.seo.title, chain);
254
+ const description = pick(page.seo.description, chain);
255
+ return {
256
+ ...summaryOf(page, chain),
257
+ generation: bundle.generation,
258
+ siteVersion: bundle.siteVersion,
259
+ version: page.version,
260
+ seo: {
261
+ ...title === void 0 ? {} : { title },
262
+ ...description === void 0 ? {} : { description },
263
+ shareImage: page.seo.shareImage,
264
+ noindex: page.seo.noindex
265
+ },
266
+ document: page.document
267
+ };
268
+ }
269
+ var documentOf = (bundle, held) => ({
270
+ generation: bundle.generation,
271
+ document: held === void 0 ? emptyDocument() : held.document
272
+ });
273
+ function createBuildClient(options) {
274
+ const builderKey = options.builderKey ?? "";
275
+ if (typeof builderKey !== "string" || builderKey === "" && options.releaseBundle === void 0)
276
+ throw new TypeError("createBuilderClient needs a builderKey");
277
+ const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
278
+ const timeoutMs = options.timeoutMs ?? DEFAULT_BUNDLE_TIMEOUT_MS;
279
+ const clock = options.now ?? Date.now;
280
+ const getReleaseBundle = async ({ release } = {}) => {
281
+ if (options.releaseBundle !== void 0) return options.releaseBundle;
282
+ return loadOnce({ base, key: builderKey, ref: releaseRef(release, options.release), timeoutMs, doFetch: options.fetch });
283
+ };
284
+ return {
285
+ mode: "build",
286
+ getReleaseBundle,
287
+ site: async ({ locale } = {}) => siteFor(await getReleaseBundle(), locale, clock()),
288
+ pages: {
289
+ list: async () => {
290
+ const bundle = await getReleaseBundle();
291
+ const chain = chainOf(bundle, void 0);
292
+ return bundle.pages.map((page) => summaryOf(page, chain));
293
+ },
294
+ get: async (slug, { locale } = {}) => {
295
+ const bundle = await getReleaseBundle();
296
+ return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
297
+ }
298
+ },
299
+ parts: {
300
+ get: async (name) => {
301
+ if (name !== "header" && name !== "footer") throw new TypeError('A Builder part is "header" or "footer"');
302
+ const bundle = await getReleaseBundle();
303
+ return documentOf(bundle, bundle[name]);
304
+ }
305
+ },
306
+ slots: {
307
+ get: async (name) => {
308
+ checkName("slot name", name);
309
+ const bundle = await getReleaseBundle();
310
+ return documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0);
311
+ }
312
+ },
313
+ bundle: async ({ page: pageSlug, slots, locale } = {}) => {
314
+ const names = [...new Set(slots ?? [])].map((name) => checkName("slot name", name)).sort();
315
+ if (pageSlug !== void 0) checkName("page slug", pageSlug);
316
+ const bundle = await getReleaseBundle();
317
+ return {
318
+ generation: bundle.generation,
319
+ site: siteFor(bundle, locale, clock()),
320
+ header: documentOf(bundle, bundle.header),
321
+ footer: documentOf(bundle, bundle.footer),
322
+ ...pageSlug === void 0 ? {} : { page: pageFor(bundle, pageSlug, chainOf(bundle, locale)) },
323
+ slots: Object.fromEntries(
324
+ names.map((name) => [name, documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0)])
325
+ )
326
+ };
327
+ }
328
+ };
329
+ }
330
+
331
+ // src/client.ts
332
+ var DEFAULT_BASE_URL2 = "https://builder.usethrottle.dev";
333
+ var DEFAULT_TIMEOUT_MS = 3e3;
334
+ function queryString(query) {
335
+ const pairs = Object.entries(query).filter((entry) => entry[1] !== void 0 && entry[1] !== "").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
336
+ return pairs.length === 0 ? "" : `?${pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")}`;
100
337
  }
101
338
  function withDocument(answer, where) {
102
339
  return { ...answer, document: currentDocument(answer, where) };
103
340
  }
104
- var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
341
+ var invalid2 = (message) => new BuilderUnavailableError("invalid-response", message);
105
342
  function generationOf(answer, where) {
106
343
  const { generation } = answer;
107
344
  if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0)
108
- throw invalid(`Builder ${where} answer has no generation`);
345
+ throw invalid2(`Builder ${where} answer has no generation`);
109
346
  return generation;
110
347
  }
111
348
  function readSite(answer) {
112
349
  generationOf(answer, "site");
113
350
  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");
351
+ throw invalid2("Builder site answer has no siteVersion");
352
+ if (!isRecord(answer.settings)) throw invalid2("Builder site answer has no settings");
116
353
  return answer;
117
354
  }
118
355
  var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
119
356
  function readPages(answer) {
120
357
  const { pages } = answer;
121
- if (!Array.isArray(pages)) throw invalid("Builder pages answer is not a list");
358
+ if (!Array.isArray(pages)) throw invalid2("Builder pages answer is not a list");
122
359
  for (const page of pages)
123
360
  if (!isRecord(page) || SUMMARY_KEYS.some((key) => typeof page[key] !== "string"))
124
- throw invalid("Builder pages answer has a page without its fields");
361
+ throw invalid2("Builder pages answer has a page without its fields");
125
362
  return pages;
126
363
  }
127
- function readDocument(answer, where) {
364
+ function readDocument2(answer, where) {
128
365
  generationOf(answer, where);
129
366
  return withDocument(answer, where);
130
367
  }
131
- function readPage(answer) {
368
+ function readPage2(answer) {
132
369
  if (typeof answer.redirectTo === "string") return { redirectTo: answer.redirectTo };
133
370
  generationOf(answer, "page");
134
- if (typeof answer.slug !== "string") throw invalid("Builder page answer has no slug");
371
+ if (typeof answer.slug !== "string") throw invalid2("Builder page answer has no slug");
135
372
  return withDocument(answer, "page");
136
373
  }
137
- function readBundle(answer) {
374
+ function readBundle2(answer) {
138
375
  const generation = generationOf(answer, "bundle");
139
376
  if (!isRecord(answer.site) || !isRecord(answer.header) || !isRecord(answer.footer))
140
- throw invalid("Builder bundle answer has no site, header or footer");
377
+ throw invalid2("Builder bundle answer has no site, header or footer");
141
378
  const slots = answer.slots === void 0 ? {} : answer.slots;
142
- if (!isRecord(slots)) throw invalid("Builder bundle answer has slots that are not an object");
379
+ if (!isRecord(slots)) throw invalid2("Builder bundle answer has slots that are not an object");
143
380
  return {
144
381
  generation,
145
382
  site: readSite(answer.site),
146
- header: readDocument(answer.header, "header"),
147
- footer: readDocument(answer.footer, "footer"),
148
- ...isRecord(answer.page) ? { page: readPage(answer.page) } : {},
383
+ header: readDocument2(answer.header, "header"),
384
+ footer: readDocument2(answer.footer, "footer"),
385
+ ...isRecord(answer.page) ? { page: readPage2(answer.page) } : {},
149
386
  slots: Object.fromEntries(
150
387
  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}`)];
388
+ if (!isRecord(value)) throw invalid2(`Builder slot ${name} answer is not an object`);
389
+ return [name, readDocument2(value, `slot ${name}`)];
153
390
  })
154
391
  )
155
392
  };
156
393
  }
157
394
  function createBuilderClient(options) {
395
+ if ("mode" in options && options.mode === "build") return createBuildClient(options);
396
+ return createLiveClient(options);
397
+ }
398
+ function createLiveClient(options) {
158
399
  const { builderKey, previewToken } = options;
159
400
  if (typeof builderKey !== "string" || builderKey === "")
160
401
  throw new TypeError("createBuilderClient needs a builderKey");
@@ -162,7 +403,7 @@ function createBuilderClient(options) {
162
403
  throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
163
404
  const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
164
405
  const preview = previewHeader !== void 0;
165
- const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
406
+ const base = (options.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/+$/u, "");
166
407
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
167
408
  const doFetch = options.fetch;
168
409
  async function once(url, init) {
@@ -233,7 +474,7 @@ function createBuilderClient(options) {
233
474
  get: async (slug, { locale } = {}) => read(
234
475
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
235
476
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
236
- readPage
477
+ readPage2
237
478
  )
238
479
  },
239
480
  parts: {
@@ -243,7 +484,7 @@ function createBuilderClient(options) {
243
484
  return read(
244
485
  `/v1/parts/${name}`,
245
486
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.part(name)] },
246
- (answer) => readDocument(answer, `part ${name}`)
487
+ (answer) => readDocument2(answer, `part ${name}`)
247
488
  );
248
489
  }
249
490
  },
@@ -251,7 +492,7 @@ function createBuilderClient(options) {
251
492
  get: async (name, { locale } = {}) => read(
252
493
  `/v1/slots/${encodeURIComponent(checkName("slot name", name))}`,
253
494
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.slot(name)] },
254
- (answer) => readDocument(answer, `slot ${name}`)
495
+ (answer) => readDocument2(answer, `slot ${name}`)
255
496
  )
256
497
  },
257
498
  bundle: async ({ page: pageSlug, slots, locale } = {}) => {
@@ -271,7 +512,7 @@ function createBuilderClient(options) {
271
512
  ...names.map((name) => BUILDER_TAGS.slot(name))
272
513
  ]
273
514
  },
274
- readBundle
515
+ readBundle2
275
516
  );
276
517
  }
277
518
  };
@@ -279,10 +520,12 @@ function createBuilderClient(options) {
279
520
  export {
280
521
  BUILDER_TAGS,
281
522
  BuilderNotFoundError,
523
+ BuilderReleaseNotFoundError,
282
524
  BuilderUnavailableError,
283
- DEFAULT_BASE_URL,
525
+ DEFAULT_BASE_URL2 as DEFAULT_BASE_URL,
284
526
  DEFAULT_TIMEOUT_MS,
285
527
  PreviewExpiredError,
528
+ SUPPORTED_BUNDLE_VERSION,
286
529
  UNTIL_CHANGED_REVALIDATE_S,
287
530
  createBuilderClient,
288
531
  scopesToTags,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.1.0",
3
+ "version": "0.2.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",