@usethrottle/builder 0.5.1 → 0.7.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.
@@ -22,6 +22,15 @@ var BuilderNotFoundError = class extends Error {
22
22
  this.slug = slug;
23
23
  }
24
24
  };
25
+ var BuilderValidationError = class extends Error {
26
+ constructor(message, status = 400) {
27
+ super(message);
28
+ /** The HTTP status, always 400 today. */
29
+ __publicField(this, "status");
30
+ this.name = "BuilderValidationError";
31
+ this.status = status;
32
+ }
33
+ };
25
34
  var PreviewExpiredError = class extends Error {
26
35
  constructor() {
27
36
  super("The Builder preview link has expired");
@@ -46,11 +55,20 @@ function cacheInit(tags, preview) {
46
55
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
47
56
  }
48
57
 
58
+ // src/schema-min.ts
59
+ var BUILDER_SCHEMA_MIN = "0.4.0";
60
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
61
+
49
62
  // src/release.ts
50
- import { emptyDocument } from "@usethrottle/builder-schema";
63
+ import { emptyDocument as emptyDocument2 } from "@usethrottle/builder-schema";
51
64
 
52
65
  // src/documents.ts
53
- import { CURRENT_SCHEMA_VERSION, upgradeDocument } from "@usethrottle/builder-schema";
66
+ import {
67
+ CURRENT_SCHEMA_VERSION,
68
+ TEMPLATE_NAMES,
69
+ emptyDocument,
70
+ upgradeDocument
71
+ } from "@usethrottle/builder-schema";
54
72
  var MAX_NAME_CHARS = 128;
55
73
  function isRecord(value) {
56
74
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -60,6 +78,24 @@ function checkName(kind, value) {
60
78
  throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
61
79
  return value;
62
80
  }
81
+ function checkPath(value) {
82
+ if (typeof value !== "string" || !value.startsWith("/") || value.length > 512)
83
+ throw new TypeError('A Builder page path starts with "/" and has at most 512 characters');
84
+ return value;
85
+ }
86
+ function checkTemplateName(value) {
87
+ if (!TEMPLATE_NAMES.includes(value))
88
+ throw new TypeError(`A Builder template is one of: ${TEMPLATE_NAMES.join(", ")}`);
89
+ return value;
90
+ }
91
+ function emptyTemplate() {
92
+ return {
93
+ document: emptyDocument(),
94
+ meta: {},
95
+ customWidgets: {},
96
+ code: { enabled: false, scriptOrigin: "", codeSiteId: null }
97
+ };
98
+ }
63
99
  function currentDocument(answer, where) {
64
100
  const doc = answer.document;
65
101
  if (!isRecord(doc))
@@ -116,11 +152,19 @@ function readBundle(body) {
116
152
  pages: body.pages.map(readPage),
117
153
  header: readDocument(body.header, "header"),
118
154
  footer: readDocument(body.footer, "footer"),
119
- slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)]))
155
+ slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)])),
156
+ ...isRecord(body.templates) ? {
157
+ templates: Object.fromEntries(
158
+ Object.entries(body.templates).map(([name, value]) => [
159
+ name,
160
+ { ...readDocument(value, `template ${name}`), ...isRecord(value) && isRecord(value.meta) ? { meta: value.meta } : {} }
161
+ ])
162
+ )
163
+ } : {}
120
164
  };
121
165
  }
122
166
  async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
123
- const headers = { accept: "application/json" };
167
+ const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
124
168
  if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
125
169
  else headers["X-Builder-Key"] = key;
126
170
  const controller = new AbortController();
@@ -203,8 +247,19 @@ function siteFor(bundle, locale, now) {
203
247
  enabled: announcement.enabled === true && (announcement.startsAt == null || Date.parse(String(announcement.startsAt)) <= now) && (announcement.endsAt == null || now < Date.parse(String(announcement.endsAt)))
204
248
  }
205
249
  } : settings;
206
- return { generation: bundle.generation, siteVersion: bundle.siteVersion, settings: windowed };
250
+ return {
251
+ generation: bundle.generation,
252
+ siteVersion: bundle.siteVersion,
253
+ settings: windowed,
254
+ catalogInstalled: typeof bundle.catalogInstalled === "boolean" ? bundle.catalogInstalled : null,
255
+ ...isRecord(bundle.theme) ? { theme: bundle.theme } : {}
256
+ };
207
257
  }
258
+ function templateFor(bundle, name) {
259
+ const held = Object.hasOwn(bundle.templates ?? {}, name) ? bundle.templates[name] : void 0;
260
+ return { ...documentOf(bundle, held), meta: held?.meta ?? {} };
261
+ }
262
+ var templatesOf = (bundle, names) => names.length === 0 ? {} : { templates: Object.fromEntries(names.map((name) => [name, templateFor(bundle, name)])) };
208
263
  function summaryOf(page, chain) {
209
264
  return {
210
265
  id: page.id,
@@ -242,7 +297,7 @@ function pageFor(bundle, slug, chain) {
242
297
  var sharedOf = (bundle) => isRecord(bundle.savedSections) ? { savedSections: bundle.savedSections } : {};
243
298
  var documentOf = (bundle, held) => ({
244
299
  generation: bundle.generation,
245
- document: held === void 0 ? emptyDocument() : held.document,
300
+ document: held === void 0 ? emptyDocument2() : held.document,
246
301
  ...sharedOf(bundle)
247
302
  });
248
303
  function createBuildClient(options) {
@@ -269,6 +324,17 @@ function createBuildClient(options) {
269
324
  get: async (slug, { locale } = {}) => {
270
325
  const bundle = await getReleaseBundle();
271
326
  return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
327
+ },
328
+ // The bundle holds each page's `path`; an old slug's redirect (`redirects`) answers its `/{slug}` path. A
329
+ // release made before pages carried a path has none to match, and every path answers not found.
330
+ getByPath: async (path, { locale } = {}) => {
331
+ checkPath(path);
332
+ const bundle = await getReleaseBundle();
333
+ const page = bundle.pages.find((candidate) => candidate.path === path);
334
+ if (page !== void 0) return pageFor(bundle, page.slug, chainOf(bundle, locale));
335
+ const old = path.slice(1);
336
+ if (!old.includes("/") && Object.hasOwn(bundle.redirects, old)) return { redirectTo: bundle.redirects[old] };
337
+ throw new BuilderNotFoundError(path);
272
338
  }
273
339
  },
274
340
  parts: {
@@ -285,8 +351,13 @@ function createBuildClient(options) {
285
351
  return documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0);
286
352
  }
287
353
  },
288
- bundle: async ({ page: pageSlug, slots, locale } = {}) => {
354
+ getTemplate: async (name) => {
355
+ checkTemplateName(name);
356
+ return templateFor(await getReleaseBundle(), name);
357
+ },
358
+ bundle: async ({ page: pageSlug, slots, templates, locale } = {}) => {
289
359
  const names = [...new Set(slots ?? [])].map((name) => checkName("slot name", name)).sort();
360
+ const templateNames = [...new Set(templates ?? [])].map(checkTemplateName).sort();
290
361
  if (pageSlug !== void 0) checkName("page slug", pageSlug);
291
362
  const bundle = await getReleaseBundle();
292
363
  return {
@@ -298,6 +369,7 @@ function createBuildClient(options) {
298
369
  slots: Object.fromEntries(
299
370
  names.map((name) => [name, documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0)])
300
371
  ),
372
+ ...templatesOf(bundle, templateNames),
301
373
  ...sharedOf(bundle)
302
374
  };
303
375
  }
@@ -311,10 +383,14 @@ var BUILDER_TAGS = {
311
383
  all: TAG,
312
384
  site: `${TAG}:site`,
313
385
  pages: `${TAG}:pages`,
386
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
387
+ paths: `${TAG}:paths`,
314
388
  page: (slug) => `${TAG}:page:${slug}`,
315
389
  part: (name) => `${TAG}:part:${name}`,
316
- slot: (name) => `${TAG}:slot:${name}`
390
+ slot: (name) => `${TAG}:slot:${name}`,
391
+ template: (name) => `${TAG}:template:${name}`
317
392
  };
393
+ var templateTag = (name) => BUILDER_TAGS.template(name);
318
394
  function fitTags(tags) {
319
395
  return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
320
396
  }
@@ -328,9 +404,10 @@ function scopesToTags(scopes) {
328
404
  out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
329
405
  else if (colon < 0 && (scope === "header" || scope === "footer"))
330
406
  out.push(BUILDER_TAGS.part(scope));
331
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
332
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
407
+ else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages, BUILDER_TAGS.paths);
408
+ else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest), BUILDER_TAGS.paths);
333
409
  else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
410
+ else if (rest !== "" && name === "template") out.push(BUILDER_TAGS.template(rest));
334
411
  else out.push(BUILDER_TAGS.all);
335
412
  }
336
413
  return fitTags(out);
@@ -384,7 +461,12 @@ function readSite(answer) {
384
461
  if (typeof answer.siteVersion !== "number" || !Number.isSafeInteger(answer.siteVersion))
385
462
  throw invalid2("Builder site answer has no siteVersion");
386
463
  if (!isRecord(answer.settings)) throw invalid2("Builder site answer has no settings");
387
- return answer;
464
+ return { ...answer, catalogInstalled: typeof answer.catalogInstalled === "boolean" ? answer.catalogInstalled : null };
465
+ }
466
+ function readTemplate(answer, name) {
467
+ const meta = answer.meta === void 0 ? {} : answer.meta;
468
+ if (!isRecord(meta)) throw invalid2(`Builder template ${name} answer has meta that is not an object`);
469
+ return { ...answer, document: currentDocument(answer, `template ${name}`), meta };
388
470
  }
389
471
  var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
390
472
  function readPages(answer) {
@@ -411,9 +493,19 @@ function readBundle2(answer) {
411
493
  throw invalid2("Builder bundle answer has no site, header or footer");
412
494
  const slots = answer.slots === void 0 ? {} : answer.slots;
413
495
  if (!isRecord(slots)) throw invalid2("Builder bundle answer has slots that are not an object");
496
+ const templates = answer.templates === void 0 ? {} : answer.templates;
497
+ if (!isRecord(templates)) throw invalid2("Builder bundle answer has templates that are not an object");
414
498
  return {
415
499
  generation,
416
500
  site: readSite(answer.site),
501
+ ...answer.templates === void 0 ? {} : {
502
+ templates: Object.fromEntries(
503
+ Object.entries(templates).map(([name, value]) => {
504
+ if (!isRecord(value)) throw invalid2(`Builder template ${name} answer is not an object`);
505
+ return [name, readTemplate(value, name)];
506
+ })
507
+ )
508
+ },
417
509
  header: readDocument2(answer.header, "header"),
418
510
  footer: readDocument2(answer.footer, "footer"),
419
511
  ...isRecord(answer.page) ? { page: readPage2(answer.page) } : {},
@@ -470,13 +562,19 @@ function createLiveClient(options) {
470
562
  }
471
563
  }
472
564
  async function fetchAnswer(path, read2) {
473
- const headers = { accept: "application/json", "X-Builder-Key": builderKey };
565
+ const headers = {
566
+ accept: "application/json",
567
+ "X-Builder-Key": builderKey,
568
+ [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
569
+ };
474
570
  if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
475
571
  const url = `${base}${path}${queryString(read2.query ?? {})}`;
476
572
  const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
477
573
  const { body, status } = await once(url, init);
478
574
  if (status === 401 && preview) throw new PreviewExpiredError();
479
575
  if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
576
+ if (status === 400 && read2.validated === true)
577
+ throw new BuilderValidationError(`Builder refused the request for ${path} (400)`);
480
578
  if (status < 200 || status >= 300)
481
579
  throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
482
580
  if (!isRecord(body) && !Array.isArray(body))
@@ -512,6 +610,17 @@ function createLiveClient(options) {
512
610
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
513
611
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
514
612
  readPage2
613
+ ),
614
+ getByPath: async (path, { locale } = {}) => read(
615
+ "/v1/page-by-path",
616
+ {
617
+ query: { path: checkPath(path), locale },
618
+ // The page's own tag is not known before the answer: `paths` is cleared by a `pages` and by any `page:<slug>` change.
619
+ tags: [BUILDER_TAGS.all, BUILDER_TAGS.pages, BUILDER_TAGS.paths],
620
+ pageSlug: path,
621
+ validated: true
622
+ },
623
+ readPage2
515
624
  )
516
625
  },
517
626
  parts: {
@@ -532,19 +641,34 @@ function createLiveClient(options) {
532
641
  (answer) => readDocument2(answer, `slot ${name}`)
533
642
  )
534
643
  },
535
- bundle: async ({ page: pageSlug, slots, locale } = {}) => {
644
+ getTemplate: async (name, { locale } = {}) => {
645
+ checkTemplateName(name);
646
+ try {
647
+ return await read(
648
+ `/v1/templates/${name}`,
649
+ { query: { locale }, tags: [BUILDER_TAGS.all, templateTag(name)] },
650
+ (answer) => readTemplate(answer, name)
651
+ );
652
+ } catch (error) {
653
+ if (error instanceof BuilderUnavailableError && error.status === 404) return emptyTemplate();
654
+ throw error;
655
+ }
656
+ },
657
+ bundle: async ({ page: pageSlug, slots, templates, locale } = {}) => {
536
658
  const names = [...new Set(slots ?? [])].map((name) => checkName("slot name", name)).sort();
659
+ const templateNames = [...new Set(templates ?? [])].map(checkTemplateName).sort();
537
660
  if (pageSlug !== void 0) checkName("page slug", pageSlug);
538
661
  return read(
539
662
  "/v1/bundle",
540
663
  {
541
- query: { page: pageSlug, slots: names.join(","), locale },
664
+ query: { page: pageSlug, slots: names.join(","), templates: templateNames.join(","), locale },
542
665
  pageSlug,
543
666
  tags: [
544
667
  BUILDER_TAGS.all,
545
668
  BUILDER_TAGS.site,
546
669
  BUILDER_TAGS.part("header"),
547
670
  BUILDER_TAGS.part("footer"),
671
+ ...templateNames.map((name) => templateTag(name)),
548
672
  ...pageSlug === void 0 ? [] : [BUILDER_TAGS.page(pageSlug)],
549
673
  ...names.map((name) => BUILDER_TAGS.slot(name))
550
674
  ]
@@ -612,12 +736,16 @@ async function verifyBuilderNotice(input) {
612
736
  export {
613
737
  BuilderUnavailableError,
614
738
  BuilderNotFoundError,
739
+ BuilderValidationError,
615
740
  PreviewExpiredError,
616
741
  BuilderReleaseNotFoundError,
617
742
  UNTIL_CHANGED_REVALIDATE_S,
743
+ BUILDER_SCHEMA_MIN,
744
+ SCHEMA_MIN_HEADER,
618
745
  SUPPORTED_BUNDLE_VERSION,
619
746
  TAG_MAX_CHARS,
620
747
  BUILDER_TAGS,
748
+ templateTag,
621
749
  scopesToTags,
622
750
  DEFAULT_BASE_URL2 as DEFAULT_BASE_URL,
623
751
  DEFAULT_TIMEOUT_MS,
@@ -22,6 +22,15 @@ var BuilderNotFoundError = class extends Error {
22
22
  this.slug = slug;
23
23
  }
24
24
  };
25
+ var BuilderValidationError = class extends Error {
26
+ constructor(message, status = 400) {
27
+ super(message);
28
+ /** The HTTP status, always 400 today. */
29
+ __publicField(this, "status");
30
+ this.name = "BuilderValidationError";
31
+ this.status = status;
32
+ }
33
+ };
25
34
  var PreviewExpiredError = class extends Error {
26
35
  constructor() {
27
36
  super("The Builder preview link has expired");
@@ -46,11 +55,20 @@ function cacheInit(tags, preview) {
46
55
  return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
47
56
  }
48
57
 
58
+ // src/schema-min.ts
59
+ var BUILDER_SCHEMA_MIN = "0.4.0";
60
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
61
+
49
62
  // src/release.ts
50
63
  var _builderschema = require('@usethrottle/builder-schema');
51
64
 
52
65
  // src/documents.ts
53
66
 
67
+
68
+
69
+
70
+
71
+
54
72
  var MAX_NAME_CHARS = 128;
55
73
  function isRecord(value) {
56
74
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -60,6 +78,24 @@ function checkName(kind, value) {
60
78
  throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
61
79
  return value;
62
80
  }
81
+ function checkPath(value) {
82
+ if (typeof value !== "string" || !value.startsWith("/") || value.length > 512)
83
+ throw new TypeError('A Builder page path starts with "/" and has at most 512 characters');
84
+ return value;
85
+ }
86
+ function checkTemplateName(value) {
87
+ if (!_builderschema.TEMPLATE_NAMES.includes(value))
88
+ throw new TypeError(`A Builder template is one of: ${_builderschema.TEMPLATE_NAMES.join(", ")}`);
89
+ return value;
90
+ }
91
+ function emptyTemplate() {
92
+ return {
93
+ document: _builderschema.emptyDocument.call(void 0, ),
94
+ meta: {},
95
+ customWidgets: {},
96
+ code: { enabled: false, scriptOrigin: "", codeSiteId: null }
97
+ };
98
+ }
63
99
  function currentDocument(answer, where) {
64
100
  const doc = answer.document;
65
101
  if (!isRecord(doc))
@@ -116,11 +152,19 @@ function readBundle(body) {
116
152
  pages: body.pages.map(readPage),
117
153
  header: readDocument(body.header, "header"),
118
154
  footer: readDocument(body.footer, "footer"),
119
- slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)]))
155
+ slots: Object.fromEntries(Object.entries(body.slots).map(([name, value]) => [name, readDocument(value, `slot ${name}`)])),
156
+ ...isRecord(body.templates) ? {
157
+ templates: Object.fromEntries(
158
+ Object.entries(body.templates).map(([name, value]) => [
159
+ name,
160
+ { ...readDocument(value, `template ${name}`), ...isRecord(value) && isRecord(value.meta) ? { meta: value.meta } : {} }
161
+ ])
162
+ )
163
+ } : {}
120
164
  };
121
165
  }
122
166
  async function fetchBundle({ base, key, ref, timeoutMs, doFetch }) {
123
- const headers = { accept: "application/json" };
167
+ const headers = { accept: "application/json", [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN };
124
168
  if (key.startsWith("tb_sk_")) headers.authorization = `Bearer ${key}`;
125
169
  else headers["X-Builder-Key"] = key;
126
170
  const controller = new AbortController();
@@ -203,8 +247,19 @@ function siteFor(bundle, locale, now) {
203
247
  enabled: announcement.enabled === true && (announcement.startsAt == null || Date.parse(String(announcement.startsAt)) <= now) && (announcement.endsAt == null || now < Date.parse(String(announcement.endsAt)))
204
248
  }
205
249
  } : settings;
206
- return { generation: bundle.generation, siteVersion: bundle.siteVersion, settings: windowed };
250
+ return {
251
+ generation: bundle.generation,
252
+ siteVersion: bundle.siteVersion,
253
+ settings: windowed,
254
+ catalogInstalled: typeof bundle.catalogInstalled === "boolean" ? bundle.catalogInstalled : null,
255
+ ...isRecord(bundle.theme) ? { theme: bundle.theme } : {}
256
+ };
257
+ }
258
+ function templateFor(bundle, name) {
259
+ const held = Object.hasOwn(_nullishCoalesce(bundle.templates, () => ( {})), name) ? bundle.templates[name] : void 0;
260
+ return { ...documentOf(bundle, held), meta: _nullishCoalesce(_optionalChain([held, 'optionalAccess', _10 => _10.meta]), () => ( {})) };
207
261
  }
262
+ var templatesOf = (bundle, names) => names.length === 0 ? {} : { templates: Object.fromEntries(names.map((name) => [name, templateFor(bundle, name)])) };
208
263
  function summaryOf(page, chain) {
209
264
  return {
210
265
  id: page.id,
@@ -269,6 +324,17 @@ function createBuildClient(options) {
269
324
  get: async (slug, { locale } = {}) => {
270
325
  const bundle = await getReleaseBundle();
271
326
  return pageFor(bundle, checkName("page slug", slug), chainOf(bundle, locale));
327
+ },
328
+ // The bundle holds each page's `path`; an old slug's redirect (`redirects`) answers its `/{slug}` path. A
329
+ // release made before pages carried a path has none to match, and every path answers not found.
330
+ getByPath: async (path, { locale } = {}) => {
331
+ checkPath(path);
332
+ const bundle = await getReleaseBundle();
333
+ const page = bundle.pages.find((candidate) => candidate.path === path);
334
+ if (page !== void 0) return pageFor(bundle, page.slug, chainOf(bundle, locale));
335
+ const old = path.slice(1);
336
+ if (!old.includes("/") && Object.hasOwn(bundle.redirects, old)) return { redirectTo: bundle.redirects[old] };
337
+ throw new BuilderNotFoundError(path);
272
338
  }
273
339
  },
274
340
  parts: {
@@ -285,8 +351,13 @@ function createBuildClient(options) {
285
351
  return documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0);
286
352
  }
287
353
  },
288
- bundle: async ({ page: pageSlug, slots, locale } = {}) => {
354
+ getTemplate: async (name) => {
355
+ checkTemplateName(name);
356
+ return templateFor(await getReleaseBundle(), name);
357
+ },
358
+ bundle: async ({ page: pageSlug, slots, templates, locale } = {}) => {
289
359
  const names = [...new Set(_nullishCoalesce(slots, () => ( [])))].map((name) => checkName("slot name", name)).sort();
360
+ const templateNames = [...new Set(_nullishCoalesce(templates, () => ( [])))].map(checkTemplateName).sort();
290
361
  if (pageSlug !== void 0) checkName("page slug", pageSlug);
291
362
  const bundle = await getReleaseBundle();
292
363
  return {
@@ -298,6 +369,7 @@ function createBuildClient(options) {
298
369
  slots: Object.fromEntries(
299
370
  names.map((name) => [name, documentOf(bundle, Object.hasOwn(bundle.slots, name) ? bundle.slots[name] : void 0)])
300
371
  ),
372
+ ...templatesOf(bundle, templateNames),
301
373
  ...sharedOf(bundle)
302
374
  };
303
375
  }
@@ -311,10 +383,14 @@ var BUILDER_TAGS = {
311
383
  all: TAG,
312
384
  site: `${TAG}:site`,
313
385
  pages: `${TAG}:pages`,
386
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
387
+ paths: `${TAG}:paths`,
314
388
  page: (slug) => `${TAG}:page:${slug}`,
315
389
  part: (name) => `${TAG}:part:${name}`,
316
- slot: (name) => `${TAG}:slot:${name}`
390
+ slot: (name) => `${TAG}:slot:${name}`,
391
+ template: (name) => `${TAG}:template:${name}`
317
392
  };
393
+ var templateTag = (name) => BUILDER_TAGS.template(name);
318
394
  function fitTags(tags) {
319
395
  return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
320
396
  }
@@ -328,9 +404,10 @@ function scopesToTags(scopes) {
328
404
  out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
329
405
  else if (colon < 0 && (scope === "header" || scope === "footer"))
330
406
  out.push(BUILDER_TAGS.part(scope));
331
- else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
332
- else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
407
+ else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages, BUILDER_TAGS.paths);
408
+ else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest), BUILDER_TAGS.paths);
333
409
  else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
410
+ else if (rest !== "" && name === "template") out.push(BUILDER_TAGS.template(rest));
334
411
  else out.push(BUILDER_TAGS.all);
335
412
  }
336
413
  return fitTags(out);
@@ -384,7 +461,12 @@ function readSite(answer) {
384
461
  if (typeof answer.siteVersion !== "number" || !Number.isSafeInteger(answer.siteVersion))
385
462
  throw invalid2("Builder site answer has no siteVersion");
386
463
  if (!isRecord(answer.settings)) throw invalid2("Builder site answer has no settings");
387
- return answer;
464
+ return { ...answer, catalogInstalled: typeof answer.catalogInstalled === "boolean" ? answer.catalogInstalled : null };
465
+ }
466
+ function readTemplate(answer, name) {
467
+ const meta = answer.meta === void 0 ? {} : answer.meta;
468
+ if (!isRecord(meta)) throw invalid2(`Builder template ${name} answer has meta that is not an object`);
469
+ return { ...answer, document: currentDocument(answer, `template ${name}`), meta };
388
470
  }
389
471
  var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
390
472
  function readPages(answer) {
@@ -411,9 +493,19 @@ function readBundle2(answer) {
411
493
  throw invalid2("Builder bundle answer has no site, header or footer");
412
494
  const slots = answer.slots === void 0 ? {} : answer.slots;
413
495
  if (!isRecord(slots)) throw invalid2("Builder bundle answer has slots that are not an object");
496
+ const templates = answer.templates === void 0 ? {} : answer.templates;
497
+ if (!isRecord(templates)) throw invalid2("Builder bundle answer has templates that are not an object");
414
498
  return {
415
499
  generation,
416
500
  site: readSite(answer.site),
501
+ ...answer.templates === void 0 ? {} : {
502
+ templates: Object.fromEntries(
503
+ Object.entries(templates).map(([name, value]) => {
504
+ if (!isRecord(value)) throw invalid2(`Builder template ${name} answer is not an object`);
505
+ return [name, readTemplate(value, name)];
506
+ })
507
+ )
508
+ },
417
509
  header: readDocument2(answer.header, "header"),
418
510
  footer: readDocument2(answer.footer, "footer"),
419
511
  ...isRecord(answer.page) ? { page: readPage2(answer.page) } : {},
@@ -470,13 +562,19 @@ function createLiveClient(options) {
470
562
  }
471
563
  }
472
564
  async function fetchAnswer(path, read2) {
473
- const headers = { accept: "application/json", "X-Builder-Key": builderKey };
565
+ const headers = {
566
+ accept: "application/json",
567
+ "X-Builder-Key": builderKey,
568
+ [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN
569
+ };
474
570
  if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
475
571
  const url = `${base}${path}${queryString(_nullishCoalesce(read2.query, () => ( {})))}`;
476
572
  const init = { method: "GET", headers, ...cacheInit(fitTags(read2.tags), preview) };
477
573
  const { body, status } = await once(url, init);
478
574
  if (status === 401 && preview) throw new PreviewExpiredError();
479
575
  if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
576
+ if (status === 400 && read2.validated === true)
577
+ throw new BuilderValidationError(`Builder refused the request for ${path} (400)`);
480
578
  if (status < 200 || status >= 300)
481
579
  throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
482
580
  if (!isRecord(body) && !Array.isArray(body))
@@ -512,6 +610,17 @@ function createLiveClient(options) {
512
610
  `/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
513
611
  { query: { locale }, tags: [BUILDER_TAGS.all, BUILDER_TAGS.page(slug)], pageSlug: slug },
514
612
  readPage2
613
+ ),
614
+ getByPath: async (path, { locale } = {}) => read(
615
+ "/v1/page-by-path",
616
+ {
617
+ query: { path: checkPath(path), locale },
618
+ // The page's own tag is not known before the answer: `paths` is cleared by a `pages` and by any `page:<slug>` change.
619
+ tags: [BUILDER_TAGS.all, BUILDER_TAGS.pages, BUILDER_TAGS.paths],
620
+ pageSlug: path,
621
+ validated: true
622
+ },
623
+ readPage2
515
624
  )
516
625
  },
517
626
  parts: {
@@ -532,19 +641,34 @@ function createLiveClient(options) {
532
641
  (answer) => readDocument2(answer, `slot ${name}`)
533
642
  )
534
643
  },
535
- bundle: async ({ page: pageSlug, slots, locale } = {}) => {
644
+ getTemplate: async (name, { locale } = {}) => {
645
+ checkTemplateName(name);
646
+ try {
647
+ return await read(
648
+ `/v1/templates/${name}`,
649
+ { query: { locale }, tags: [BUILDER_TAGS.all, templateTag(name)] },
650
+ (answer) => readTemplate(answer, name)
651
+ );
652
+ } catch (error) {
653
+ if (error instanceof BuilderUnavailableError && error.status === 404) return emptyTemplate();
654
+ throw error;
655
+ }
656
+ },
657
+ bundle: async ({ page: pageSlug, slots, templates, locale } = {}) => {
536
658
  const names = [...new Set(_nullishCoalesce(slots, () => ( [])))].map((name) => checkName("slot name", name)).sort();
659
+ const templateNames = [...new Set(_nullishCoalesce(templates, () => ( [])))].map(checkTemplateName).sort();
537
660
  if (pageSlug !== void 0) checkName("page slug", pageSlug);
538
661
  return read(
539
662
  "/v1/bundle",
540
663
  {
541
- query: { page: pageSlug, slots: names.join(","), locale },
664
+ query: { page: pageSlug, slots: names.join(","), templates: templateNames.join(","), locale },
542
665
  pageSlug,
543
666
  tags: [
544
667
  BUILDER_TAGS.all,
545
668
  BUILDER_TAGS.site,
546
669
  BUILDER_TAGS.part("header"),
547
670
  BUILDER_TAGS.part("footer"),
671
+ ...templateNames.map((name) => templateTag(name)),
548
672
  ...pageSlug === void 0 ? [] : [BUILDER_TAGS.page(pageSlug)],
549
673
  ...names.map((name) => BUILDER_TAGS.slot(name))
550
674
  ]
@@ -623,4 +747,8 @@ async function verifyBuilderNotice(input) {
623
747
 
624
748
 
625
749
 
626
- exports.BuilderUnavailableError = BuilderUnavailableError; exports.BuilderNotFoundError = BuilderNotFoundError; exports.PreviewExpiredError = PreviewExpiredError; exports.BuilderReleaseNotFoundError = BuilderReleaseNotFoundError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.SUPPORTED_BUNDLE_VERSION = SUPPORTED_BUNDLE_VERSION; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.scopesToTags = scopesToTags; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL2; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.createBuilderClient = createBuilderClient; exports.verifyBuilderNotice = verifyBuilderNotice;
750
+
751
+
752
+
753
+
754
+ exports.BuilderUnavailableError = BuilderUnavailableError; exports.BuilderNotFoundError = BuilderNotFoundError; exports.BuilderValidationError = BuilderValidationError; exports.PreviewExpiredError = PreviewExpiredError; exports.BuilderReleaseNotFoundError = BuilderReleaseNotFoundError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.BUILDER_SCHEMA_MIN = BUILDER_SCHEMA_MIN; exports.SCHEMA_MIN_HEADER = SCHEMA_MIN_HEADER; exports.SUPPORTED_BUNDLE_VERSION = SUPPORTED_BUNDLE_VERSION; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.templateTag = templateTag; exports.scopesToTags = scopesToTags; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL2; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.createBuilderClient = createBuilderClient; exports.verifyBuilderNotice = verifyBuilderNotice;
package/dist/index.cjs CHANGED
@@ -11,10 +11,10 @@
11
11
 
12
12
 
13
13
 
14
- var _chunkCYA6NLSCcjs = require('./chunk-CYA6NLSC.cjs');
15
14
 
16
15
 
17
16
 
17
+ var _chunkKNA3T4M6cjs = require('./chunk-KNA3T4M6.cjs');
18
18
 
19
19
 
20
20
 
@@ -25,4 +25,10 @@ var _chunkCYA6NLSCcjs = require('./chunk-CYA6NLSC.cjs');
25
25
 
26
26
 
27
27
 
28
- exports.BUILDER_TAGS = _chunkCYA6NLSCcjs.BUILDER_TAGS; exports.BuilderNotFoundError = _chunkCYA6NLSCcjs.BuilderNotFoundError; exports.BuilderReleaseNotFoundError = _chunkCYA6NLSCcjs.BuilderReleaseNotFoundError; exports.BuilderUnavailableError = _chunkCYA6NLSCcjs.BuilderUnavailableError; exports.DEFAULT_BASE_URL = _chunkCYA6NLSCcjs.DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = _chunkCYA6NLSCcjs.DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = _chunkCYA6NLSCcjs.PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = _chunkCYA6NLSCcjs.SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = _chunkCYA6NLSCcjs.UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = _chunkCYA6NLSCcjs.createBuilderClient; exports.scopesToTags = _chunkCYA6NLSCcjs.scopesToTags; exports.verifyBuilderNotice = _chunkCYA6NLSCcjs.verifyBuilderNotice;
28
+
29
+
30
+
31
+
32
+
33
+
34
+ exports.BUILDER_SCHEMA_MIN = _chunkKNA3T4M6cjs.BUILDER_SCHEMA_MIN; exports.BUILDER_TAGS = _chunkKNA3T4M6cjs.BUILDER_TAGS; exports.BuilderNotFoundError = _chunkKNA3T4M6cjs.BuilderNotFoundError; exports.BuilderReleaseNotFoundError = _chunkKNA3T4M6cjs.BuilderReleaseNotFoundError; exports.BuilderUnavailableError = _chunkKNA3T4M6cjs.BuilderUnavailableError; exports.BuilderValidationError = _chunkKNA3T4M6cjs.BuilderValidationError; exports.DEFAULT_BASE_URL = _chunkKNA3T4M6cjs.DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = _chunkKNA3T4M6cjs.DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = _chunkKNA3T4M6cjs.PreviewExpiredError; exports.SUPPORTED_BUNDLE_VERSION = _chunkKNA3T4M6cjs.SUPPORTED_BUNDLE_VERSION; exports.UNTIL_CHANGED_REVALIDATE_S = _chunkKNA3T4M6cjs.UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = _chunkKNA3T4M6cjs.createBuilderClient; exports.scopesToTags = _chunkKNA3T4M6cjs.scopesToTags; exports.templateTag = _chunkKNA3T4M6cjs.templateTag; exports.verifyBuilderNotice = _chunkKNA3T4M6cjs.verifyBuilderNotice;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { PageDocument, SavedSectionsAnswer, CodeRuntimeAnswer } from '@usethrottle/builder-schema';
1
+ import { PageDocument, SavedSectionsAnswer, CodeRuntimeAnswer, TemplateName, TemplateMeta, AnyCustomWidgetSnapshot } from '@usethrottle/builder-schema';
2
2
  export { v as verifyBuilderNotice } from './verify-CkxGofEg.cjs';
3
3
 
4
4
  type BuilderUnavailableReason = 'timeout' | 'network' | 'status' | 'invalid-response' | 'unsupported-document';
@@ -22,6 +22,15 @@ declare class BuilderNotFoundError extends Error {
22
22
  readonly slug: string | undefined;
23
23
  constructor(slug?: string);
24
24
  }
25
+ /**
26
+ * The Builder refused a read as invalid (`400`), for example a path it cannot match. It is an answer about the
27
+ * request, not an outage: it is never softened to a last good answer, and a route treats it as not found.
28
+ */
29
+ declare class BuilderValidationError extends Error {
30
+ /** The HTTP status, always 400 today. */
31
+ readonly status: number;
32
+ constructor(message: string, status?: number);
33
+ }
25
34
  /**
26
35
  * The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
27
36
  * read never falls back to the published page: the caller shows that the link
@@ -46,6 +55,16 @@ type BuilderSite = {
46
55
  generation: number;
47
56
  siteVersion: number;
48
57
  settings: Record<string, unknown>;
58
+ /**
59
+ * Whether the Product Catalog is installed (the Worker's presence check). `null` is unknown, and an
60
+ * older Worker that sends nothing reads as `null`; routing counts `null` as installed.
61
+ */
62
+ catalogInstalled: boolean | null;
63
+ /** Site theme output. `customCssHref` is the stylesheet of the merchant's custom CSS, when there is one. */
64
+ theme?: {
65
+ customCssHref?: string;
66
+ [key: string]: unknown;
67
+ };
49
68
  };
50
69
  type BuilderPageSummary = {
51
70
  id: string;
@@ -79,6 +98,14 @@ type LoadedDocument = {
79
98
  /** Whether the store runs code widgets and where their scripts come from. */
80
99
  code?: CodeRuntimeAnswer;
81
100
  };
101
+ /** A published template (`GET /v1/templates/:name`); an empty document and `{}` meta when unpublished. */
102
+ type TemplateAnswer = Omit<LoadedDocument, 'generation'> & {
103
+ /** Not part of the Worker's template answer; present only if a Worker sends one. */
104
+ generation?: number;
105
+ meta: TemplateMeta;
106
+ /** The custom widgets the template frozen at publish, when the Worker sends them. */
107
+ customWidgets?: Record<string, AnyCustomWidgetSnapshot>;
108
+ };
82
109
  type BuilderBundle = {
83
110
  generation: number;
84
111
  site: BuilderSite;
@@ -87,6 +114,8 @@ type BuilderBundle = {
87
114
  page?: LoadedPage | PageRedirect;
88
115
  /** Only the slots that were asked for. */
89
116
  slots: Record<string, LoadedDocument>;
117
+ /** Every published template by name, when the Builder sends them with the bundle. */
118
+ templates?: Partial<Record<TemplateName, TemplateAnswer>>;
90
119
  /** Saved sections of every document in the answer, when the Builder sends them once for all. */
91
120
  savedSections?: SavedSectionsAnswer;
92
121
  /** The code runtime of the store, when the Builder sends it once for all. */
@@ -119,6 +148,14 @@ type BuilderClient = {
119
148
  pages: {
120
149
  list(): Promise<BuilderPageSummary[]>;
121
150
  get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
151
+ /**
152
+ * The page that answers at its own path (`/about`), or a redirect when the path is an old one of a page
153
+ * (`slug_redirects`). Optional in this type so a custom client may omit it (a route then reads `list()`, whose
154
+ * summaries carry `path`); every client `createBuilderClient` makes has it (`PageByPathClient`).
155
+ * Rejects with `BuilderNotFoundError` when no page has the path, and with `BuilderValidationError` when the
156
+ * Builder refuses the path (`400`).
157
+ */
158
+ getByPath?(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
122
159
  };
123
160
  parts: {
124
161
  get(name: PartName, options?: LocaleOptions): Promise<LoadedDocument>;
@@ -126,16 +163,29 @@ type BuilderClient = {
126
163
  slots: {
127
164
  get(name: string, options?: LocaleOptions): Promise<LoadedDocument>;
128
165
  };
166
+ getTemplate(name: TemplateName, options?: LocaleOptions): Promise<TemplateAnswer>;
167
+ /** `templates` names the templates to answer (and to tag the read with); without it the answer has none. */
129
168
  bundle(options?: LocaleOptions & {
130
169
  page?: string;
131
170
  slots?: readonly string[];
171
+ templates?: readonly TemplateName[];
132
172
  }): Promise<BuilderBundle>;
133
173
  };
174
+ /** A `BuilderClient` that has `pages.getByPath`: what `createBuilderClient` returns. */
175
+ type PageByPathClient = BuilderClient & {
176
+ pages: {
177
+ getByPath(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
178
+ };
179
+ };
134
180
  /** A published part or slot as a release holds it. */
135
181
  type ReleaseDocument = {
136
182
  version: number;
137
183
  document: PageDocument;
138
184
  };
185
+ /** A published template as a release holds it. */
186
+ type ReleaseTemplate = ReleaseDocument & {
187
+ meta?: TemplateMeta;
188
+ };
139
189
  /** One page of a release. Titles and `seo` text keep their locale maps; the document does too. */
140
190
  type ReleasePage = {
141
191
  id: string;
@@ -181,6 +231,12 @@ type ReleaseBundle = {
181
231
  header: ReleaseDocument;
182
232
  footer: ReleaseDocument;
183
233
  slots: Record<string, ReleaseDocument>;
234
+ /** The published templates by name. Absent from a release made before templates. */
235
+ templates?: Partial<Record<TemplateName, ReleaseTemplate>>;
236
+ /** The catalog-installed signal at release time. Absent reads as `null` (unknown). */
237
+ catalogInstalled?: boolean | null;
238
+ /** Site theme output (`customCssHref`), when the release holds one. */
239
+ theme?: BuilderSite['theme'];
184
240
  /** The published saved sections the release's documents reference, by the id of their document. */
185
241
  savedSections?: SavedSectionsAnswer;
186
242
  /** An old slug and the store path of the page that lives there now. */
@@ -220,7 +276,7 @@ type BuildClientOptions = BuildClientCommon & ({
220
276
  releaseBundle: ReleaseBundle;
221
277
  builderKey?: string;
222
278
  });
223
- type BuildBuilderClient = BuilderClient & {
279
+ type BuildBuilderClient = PageByPathClient & {
224
280
  readonly mode: 'build';
225
281
  /**
226
282
  * The release's bundle, read once per process and kept in memory. The release
@@ -241,7 +297,7 @@ declare const DEFAULT_TIMEOUT_MS = 3000;
241
297
  * mode, the client reads the live API.
242
298
  */
243
299
  declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
244
- declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
300
+ declare function createBuilderClient(options: BuilderClientOptions): PageByPathClient;
245
301
 
246
302
  /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
247
303
  declare const SUPPORTED_BUNDLE_VERSION = 1;
@@ -250,10 +306,14 @@ declare const BUILDER_TAGS: {
250
306
  readonly all: "throttle-builder";
251
307
  readonly site: "throttle-builder:site";
252
308
  readonly pages: "throttle-builder:pages";
309
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
310
+ readonly paths: "throttle-builder:paths";
253
311
  readonly page: (slug: string) => string;
254
312
  readonly part: (name: string) => string;
255
313
  readonly slot: (name: string) => string;
314
+ readonly template: (name: string) => string;
256
315
  };
316
+ declare const templateTag: (name: string) => string;
257
317
  /**
258
318
  * The tags a change notice's scopes clear. `site` and `menus` clear the site,
259
319
  * header and footer reads and never pages. `header` and `footer` clear their
@@ -266,4 +326,12 @@ declare function scopesToTags(scopes: readonly string[]): string[];
266
326
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
267
327
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
268
328
 
269
- 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 };
329
+ /**
330
+ * The `x-builder-schema-min` request header: the builder-schema version this package reads. The Builder Worker
331
+ * serves v2 published site settings only to a client that sends a version of at least 0.4.0 (R2); one that sends
332
+ * none gets the v1 downgrade. Kept equal to `packages/builder-schema/package.json` by `schema-min-header.test.ts`:
333
+ * bump both together.
334
+ */
335
+ declare const BUILDER_SCHEMA_MIN = "0.4.0";
336
+
337
+ export { BUILDER_SCHEMA_MIN, BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, BuilderValidationError, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageByPathClient, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PageDocument, SavedSectionsAnswer, CodeRuntimeAnswer } from '@usethrottle/builder-schema';
1
+ import { PageDocument, SavedSectionsAnswer, CodeRuntimeAnswer, TemplateName, TemplateMeta, AnyCustomWidgetSnapshot } from '@usethrottle/builder-schema';
2
2
  export { v as verifyBuilderNotice } from './verify-CkxGofEg.js';
3
3
 
4
4
  type BuilderUnavailableReason = 'timeout' | 'network' | 'status' | 'invalid-response' | 'unsupported-document';
@@ -22,6 +22,15 @@ declare class BuilderNotFoundError extends Error {
22
22
  readonly slug: string | undefined;
23
23
  constructor(slug?: string);
24
24
  }
25
+ /**
26
+ * The Builder refused a read as invalid (`400`), for example a path it cannot match. It is an answer about the
27
+ * request, not an outage: it is never softened to a last good answer, and a route treats it as not found.
28
+ */
29
+ declare class BuilderValidationError extends Error {
30
+ /** The HTTP status, always 400 today. */
31
+ readonly status: number;
32
+ constructor(message: string, status?: number);
33
+ }
25
34
  /**
26
35
  * The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
27
36
  * read never falls back to the published page: the caller shows that the link
@@ -46,6 +55,16 @@ type BuilderSite = {
46
55
  generation: number;
47
56
  siteVersion: number;
48
57
  settings: Record<string, unknown>;
58
+ /**
59
+ * Whether the Product Catalog is installed (the Worker's presence check). `null` is unknown, and an
60
+ * older Worker that sends nothing reads as `null`; routing counts `null` as installed.
61
+ */
62
+ catalogInstalled: boolean | null;
63
+ /** Site theme output. `customCssHref` is the stylesheet of the merchant's custom CSS, when there is one. */
64
+ theme?: {
65
+ customCssHref?: string;
66
+ [key: string]: unknown;
67
+ };
49
68
  };
50
69
  type BuilderPageSummary = {
51
70
  id: string;
@@ -79,6 +98,14 @@ type LoadedDocument = {
79
98
  /** Whether the store runs code widgets and where their scripts come from. */
80
99
  code?: CodeRuntimeAnswer;
81
100
  };
101
+ /** A published template (`GET /v1/templates/:name`); an empty document and `{}` meta when unpublished. */
102
+ type TemplateAnswer = Omit<LoadedDocument, 'generation'> & {
103
+ /** Not part of the Worker's template answer; present only if a Worker sends one. */
104
+ generation?: number;
105
+ meta: TemplateMeta;
106
+ /** The custom widgets the template frozen at publish, when the Worker sends them. */
107
+ customWidgets?: Record<string, AnyCustomWidgetSnapshot>;
108
+ };
82
109
  type BuilderBundle = {
83
110
  generation: number;
84
111
  site: BuilderSite;
@@ -87,6 +114,8 @@ type BuilderBundle = {
87
114
  page?: LoadedPage | PageRedirect;
88
115
  /** Only the slots that were asked for. */
89
116
  slots: Record<string, LoadedDocument>;
117
+ /** Every published template by name, when the Builder sends them with the bundle. */
118
+ templates?: Partial<Record<TemplateName, TemplateAnswer>>;
90
119
  /** Saved sections of every document in the answer, when the Builder sends them once for all. */
91
120
  savedSections?: SavedSectionsAnswer;
92
121
  /** The code runtime of the store, when the Builder sends it once for all. */
@@ -119,6 +148,14 @@ type BuilderClient = {
119
148
  pages: {
120
149
  list(): Promise<BuilderPageSummary[]>;
121
150
  get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
151
+ /**
152
+ * The page that answers at its own path (`/about`), or a redirect when the path is an old one of a page
153
+ * (`slug_redirects`). Optional in this type so a custom client may omit it (a route then reads `list()`, whose
154
+ * summaries carry `path`); every client `createBuilderClient` makes has it (`PageByPathClient`).
155
+ * Rejects with `BuilderNotFoundError` when no page has the path, and with `BuilderValidationError` when the
156
+ * Builder refuses the path (`400`).
157
+ */
158
+ getByPath?(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
122
159
  };
123
160
  parts: {
124
161
  get(name: PartName, options?: LocaleOptions): Promise<LoadedDocument>;
@@ -126,16 +163,29 @@ type BuilderClient = {
126
163
  slots: {
127
164
  get(name: string, options?: LocaleOptions): Promise<LoadedDocument>;
128
165
  };
166
+ getTemplate(name: TemplateName, options?: LocaleOptions): Promise<TemplateAnswer>;
167
+ /** `templates` names the templates to answer (and to tag the read with); without it the answer has none. */
129
168
  bundle(options?: LocaleOptions & {
130
169
  page?: string;
131
170
  slots?: readonly string[];
171
+ templates?: readonly TemplateName[];
132
172
  }): Promise<BuilderBundle>;
133
173
  };
174
+ /** A `BuilderClient` that has `pages.getByPath`: what `createBuilderClient` returns. */
175
+ type PageByPathClient = BuilderClient & {
176
+ pages: {
177
+ getByPath(path: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
178
+ };
179
+ };
134
180
  /** A published part or slot as a release holds it. */
135
181
  type ReleaseDocument = {
136
182
  version: number;
137
183
  document: PageDocument;
138
184
  };
185
+ /** A published template as a release holds it. */
186
+ type ReleaseTemplate = ReleaseDocument & {
187
+ meta?: TemplateMeta;
188
+ };
139
189
  /** One page of a release. Titles and `seo` text keep their locale maps; the document does too. */
140
190
  type ReleasePage = {
141
191
  id: string;
@@ -181,6 +231,12 @@ type ReleaseBundle = {
181
231
  header: ReleaseDocument;
182
232
  footer: ReleaseDocument;
183
233
  slots: Record<string, ReleaseDocument>;
234
+ /** The published templates by name. Absent from a release made before templates. */
235
+ templates?: Partial<Record<TemplateName, ReleaseTemplate>>;
236
+ /** The catalog-installed signal at release time. Absent reads as `null` (unknown). */
237
+ catalogInstalled?: boolean | null;
238
+ /** Site theme output (`customCssHref`), when the release holds one. */
239
+ theme?: BuilderSite['theme'];
184
240
  /** The published saved sections the release's documents reference, by the id of their document. */
185
241
  savedSections?: SavedSectionsAnswer;
186
242
  /** An old slug and the store path of the page that lives there now. */
@@ -220,7 +276,7 @@ type BuildClientOptions = BuildClientCommon & ({
220
276
  releaseBundle: ReleaseBundle;
221
277
  builderKey?: string;
222
278
  });
223
- type BuildBuilderClient = BuilderClient & {
279
+ type BuildBuilderClient = PageByPathClient & {
224
280
  readonly mode: 'build';
225
281
  /**
226
282
  * The release's bundle, read once per process and kept in memory. The release
@@ -241,7 +297,7 @@ declare const DEFAULT_TIMEOUT_MS = 3000;
241
297
  * mode, the client reads the live API.
242
298
  */
243
299
  declare function createBuilderClient(options: BuildClientOptions): BuildBuilderClient;
244
- declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
300
+ declare function createBuilderClient(options: BuilderClientOptions): PageByPathClient;
245
301
 
246
302
  /** The bundle format this SDK reads (`BUNDLE_VERSION` of the Builder). */
247
303
  declare const SUPPORTED_BUNDLE_VERSION = 1;
@@ -250,10 +306,14 @@ declare const BUILDER_TAGS: {
250
306
  readonly all: "throttle-builder";
251
307
  readonly site: "throttle-builder:site";
252
308
  readonly pages: "throttle-builder:pages";
309
+ /** Every read by path: its page is not known before the answer, so a change to any page clears these. */
310
+ readonly paths: "throttle-builder:paths";
253
311
  readonly page: (slug: string) => string;
254
312
  readonly part: (name: string) => string;
255
313
  readonly slot: (name: string) => string;
314
+ readonly template: (name: string) => string;
256
315
  };
316
+ declare const templateTag: (name: string) => string;
257
317
  /**
258
318
  * The tags a change notice's scopes clear. `site` and `menus` clear the site,
259
319
  * header and footer reads and never pages. `header` and `footer` clear their
@@ -266,4 +326,12 @@ declare function scopesToTags(scopes: readonly string[]): string[];
266
326
  /** Next's `revalidate` for a published read: only a safety net behind the change notices. */
267
327
  declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
268
328
 
269
- 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 };
329
+ /**
330
+ * The `x-builder-schema-min` request header: the builder-schema version this package reads. The Builder Worker
331
+ * serves v2 published site settings only to a client that sends a version of at least 0.4.0 (R2); one that sends
332
+ * none gets the v1 downgrade. Kept equal to `packages/builder-schema/package.json` by `schema-min-header.test.ts`:
333
+ * bump both together.
334
+ */
335
+ declare const BUILDER_SCHEMA_MIN = "0.4.0";
336
+
337
+ export { BUILDER_SCHEMA_MIN, BUILDER_TAGS, type BuildBuilderClient, type BuildClientOptions, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, BuilderReleaseNotFoundError, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, BuilderValidationError, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageByPathClient, type PageRedirect, type PartName, PreviewExpiredError, type ReleaseBundle, type ReleaseDocument, type ReleasePage, type ReleaseTemplate, SUPPORTED_BUNDLE_VERSION, type TemplateAnswer, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags, templateTag };
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
+ BUILDER_SCHEMA_MIN,
2
3
  BUILDER_TAGS,
3
4
  BuilderNotFoundError,
4
5
  BuilderReleaseNotFoundError,
5
6
  BuilderUnavailableError,
7
+ BuilderValidationError,
6
8
  DEFAULT_BASE_URL,
7
9
  DEFAULT_TIMEOUT_MS,
8
10
  PreviewExpiredError,
@@ -10,13 +12,16 @@ import {
10
12
  UNTIL_CHANGED_REVALIDATE_S,
11
13
  createBuilderClient,
12
14
  scopesToTags,
15
+ templateTag,
13
16
  verifyBuilderNotice
14
- } from "./chunk-TWEYA32T.js";
17
+ } from "./chunk-3PRNCLZO.js";
15
18
  export {
19
+ BUILDER_SCHEMA_MIN,
16
20
  BUILDER_TAGS,
17
21
  BuilderNotFoundError,
18
22
  BuilderReleaseNotFoundError,
19
23
  BuilderUnavailableError,
24
+ BuilderValidationError,
20
25
  DEFAULT_BASE_URL,
21
26
  DEFAULT_TIMEOUT_MS,
22
27
  PreviewExpiredError,
@@ -24,5 +29,6 @@ export {
24
29
  UNTIL_CHANGED_REVALIDATE_S,
25
30
  createBuilderClient,
26
31
  scopesToTags,
32
+ templateTag,
27
33
  verifyBuilderNotice
28
34
  };
package/dist/next.cjs CHANGED
@@ -4,7 +4,9 @@
4
4
 
5
5
 
6
6
 
7
- var _chunkCYA6NLSCcjs = require('./chunk-CYA6NLSC.cjs');
7
+
8
+
9
+ var _chunkKNA3T4M6cjs = require('./chunk-KNA3T4M6.cjs');
8
10
 
9
11
  // src/next/index.ts
10
12
  require('server-only');
@@ -47,7 +49,7 @@ function parseNotice(rawBody) {
47
49
  if (typeof value !== "object" || value === null) return null;
48
50
  const { type, generation, scopes } = value;
49
51
  if (type !== "builder.changed" || typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0 || !Array.isArray(scopes) || scopes.length === 0 || scopes.length > MAX_SCOPES || !scopes.every(
50
- (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkCYA6NLSCcjs.TAG_MAX_CHARS
52
+ (scope) => typeof scope === "string" && scope.length > 0 && scope.length <= _chunkKNA3T4M6cjs.TAG_MAX_CHARS
51
53
  ))
52
54
  return null;
53
55
  return { generation, scopes };
@@ -72,12 +74,12 @@ function createRevalidateHandler(options) {
72
74
  const now = Math.floor(Date.now() / 1e3);
73
75
  let verified = false;
74
76
  for (const secret of secrets)
75
- verified = await _chunkCYA6NLSCcjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
77
+ verified = await _chunkKNA3T4M6cjs.verifyBuilderNotice.call(void 0, { rawBody, header, secret, now }) || verified;
76
78
  if (!verified) return json(401, { error: "invalid signature" });
77
79
  const notice = parseNotice(rawBody);
78
80
  if (notice === null) return json(400, { error: "invalid body" });
79
- const mapped = _chunkCYA6NLSCcjs.scopesToTags.call(void 0, notice.scopes);
80
- const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkCYA6NLSCcjs.BUILDER_TAGS.all] : mapped;
81
+ const mapped = _chunkKNA3T4M6cjs.scopesToTags.call(void 0, notice.scopes);
82
+ const tags = mapped.length > MAX_TAGS_PER_NOTICE ? [_chunkKNA3T4M6cjs.BUILDER_TAGS.all] : mapped;
81
83
  const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag()));
82
84
  for (const tag of tags) revalidate(tag);
83
85
  return json(200, { revalidated: tags });
@@ -102,10 +104,10 @@ function createWatchSyncHandler(options) {
102
104
  let running;
103
105
  const run = async (key) => {
104
106
  const doFetch = _nullishCoalesce(options.fetch, () => ( fetch));
105
- const base = (_nullishCoalesce(options.baseUrl, () => ( _chunkCYA6NLSCcjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
107
+ const base = (_nullishCoalesce(options.baseUrl, () => ( _chunkKNA3T4M6cjs.DEFAULT_BASE_URL))).replace(/\/+$/u, "");
106
108
  const read = async (init) => {
107
109
  const response = await doFetch(`${base}/v1/site`, {
108
- headers: { "X-Builder-Key": key },
110
+ headers: { "X-Builder-Key": key, [_chunkKNA3T4M6cjs.SCHEMA_MIN_HEADER]: _chunkKNA3T4M6cjs.BUILDER_SCHEMA_MIN },
109
111
  signal: AbortSignal.timeout(READ_TIMEOUT_MS),
110
112
  ...init
111
113
  });
@@ -118,14 +120,14 @@ function createWatchSyncHandler(options) {
118
120
  let generation;
119
121
  let recorded;
120
122
  try {
121
- recorded = await read({ next: { tags: [_chunkCYA6NLSCcjs.BUILDER_TAGS.all], revalidate: false } });
123
+ recorded = await read({ next: { tags: [_chunkKNA3T4M6cjs.BUILDER_TAGS.all], revalidate: false } });
122
124
  generation = await read({ cache: "no-store" });
123
125
  } catch (e2) {
124
126
  return json2(502, { error: "The Builder could not be read." });
125
127
  }
126
128
  if (generation === recorded) return json2(200, { changed: false, generation });
127
129
  const revalidate = await _asyncNullishCoalesce(options.revalidateTag, async () => ( await defaultRevalidateTag2()));
128
- revalidate(_chunkCYA6NLSCcjs.BUILDER_TAGS.all);
130
+ revalidate(_chunkKNA3T4M6cjs.BUILDER_TAGS.all);
129
131
  return json2(200, { changed: true, generation });
130
132
  };
131
133
  return () => {
@@ -182,4 +184,4 @@ async function getPreviewToken() {
182
184
 
183
185
 
184
186
 
185
- exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkCYA6NLSCcjs.verifyBuilderNotice;
187
+ exports.PREVIEW_COOKIE = PREVIEW_COOKIE; exports.createRevalidateHandler = createRevalidateHandler; exports.createWatchSyncHandler = createWatchSyncHandler; exports.getPreviewToken = getPreviewToken; exports.previewMiddleware = previewMiddleware; exports.verifyBuilderNotice = _chunkKNA3T4M6cjs.verifyBuilderNotice;
package/dist/next.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
+ BUILDER_SCHEMA_MIN,
2
3
  BUILDER_TAGS,
3
4
  DEFAULT_BASE_URL,
5
+ SCHEMA_MIN_HEADER,
4
6
  TAG_MAX_CHARS,
5
7
  scopesToTags,
6
8
  verifyBuilderNotice
7
- } from "./chunk-TWEYA32T.js";
9
+ } from "./chunk-3PRNCLZO.js";
8
10
 
9
11
  // src/next/index.ts
10
12
  import "server-only";
@@ -105,7 +107,7 @@ function createWatchSyncHandler(options) {
105
107
  const base = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
106
108
  const read = async (init) => {
107
109
  const response = await doFetch(`${base}/v1/site`, {
108
- headers: { "X-Builder-Key": key },
110
+ headers: { "X-Builder-Key": key, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
109
111
  signal: AbortSignal.timeout(READ_TIMEOUT_MS),
110
112
  ...init
111
113
  });
package/dist/watch.cjs CHANGED
@@ -28,6 +28,12 @@ __export(generation_watch_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(generation_watch_exports);
30
30
  var import_react = require("react");
31
+
32
+ // src/schema-min.ts
33
+ var BUILDER_SCHEMA_MIN = "0.4.0";
34
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
35
+
36
+ // src/generation-watch.ts
31
37
  var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
32
38
  var MIN_INTERVAL_MS = 3e4;
33
39
  var DEFAULT_INTERVAL_MS = 6e4;
@@ -74,7 +80,7 @@ function watchGeneration({
74
80
  }
75
81
  async function readSiteGeneration(baseUrl, builderKey) {
76
82
  const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
77
- headers: { "X-Builder-Key": builderKey },
83
+ headers: { "X-Builder-Key": builderKey, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
78
84
  cache: "no-cache"
79
85
  });
80
86
  if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
package/dist/watch.js CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  // src/generation-watch.ts
4
4
  import { useEffect, useRef } from "react";
5
+
6
+ // src/schema-min.ts
7
+ var BUILDER_SCHEMA_MIN = "0.4.0";
8
+ var SCHEMA_MIN_HEADER = "x-builder-schema-min";
9
+
10
+ // src/generation-watch.ts
5
11
  var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
6
12
  var MIN_INTERVAL_MS = 3e4;
7
13
  var DEFAULT_INTERVAL_MS = 6e4;
@@ -48,7 +54,7 @@ function watchGeneration({
48
54
  }
49
55
  async function readSiteGeneration(baseUrl, builderKey) {
50
56
  const response = await fetch(`${baseUrl.replace(/\/+$/u, "")}/v1/site`, {
51
- headers: { "X-Builder-Key": builderKey },
57
+ headers: { "X-Builder-Key": builderKey, [SCHEMA_MIN_HEADER]: BUILDER_SCHEMA_MIN },
52
58
  cache: "no-cache"
53
59
  });
54
60
  if (!response.ok) throw new Error(`Builder answered ${String(response.status)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usethrottle/builder",
3
- "version": "0.5.1",
3
+ "version": "0.7.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.3.0"
62
+ "@usethrottle/builder-schema": "^0.4.1"
63
63
  },
64
64
  "peerDependencies": {
65
65
  "next": ">=14",