@usethrottle/builder-react 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/next.cjs CHANGED
@@ -1,13 +1,21 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
4
 
5
5
 
6
6
 
7
- var _chunkXHTZWZPNcjs = require('./chunk-XHTZWZPN.cjs');
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+ var _chunkUNL4JWZScjs = require('./chunk-UNL4JWZS.cjs');
8
16
 
9
17
  // src/next/index.ts
10
- var _react = require('react');
18
+ var _react = require('react'); var React = _interopRequireWildcard(_react);
11
19
  var _navigation = require('next/navigation');
12
20
  var _builder = require('@usethrottle/builder');
13
21
  var _builderreact = require('@usethrottle/builder-react');
@@ -31,6 +39,362 @@ function sitePath(to) {
31
39
  return _builderschema.safeUrl.call(void 0, to, "href", { mediaOrigin: "" });
32
40
  }
33
41
 
42
+ // src/next/route.tsx
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+ var _jsxruntime = require('react/jsx-runtime');
53
+ var DEFAULT_CATALOG_TEMPLATE_PATHS = {
54
+ shop: "/shop",
55
+ collection: "/collections/{handle}",
56
+ category: "/c/{handle}",
57
+ tag: "/tags/{tag}",
58
+ search: "/search",
59
+ product: "/p/{handle}"
60
+ };
61
+ var DEFAULT_STORE_TEMPLATE_PATHS = {
62
+ cart: "/cart",
63
+ account: "/account",
64
+ "account-verify": "/account/verify",
65
+ "sign-in": "/sign-in",
66
+ "sign-up": "/sign-up",
67
+ "order-complete": "/order/complete"
68
+ };
69
+ var BuilderUnavailablePageError = class extends Error {
70
+ constructor(template) {
71
+ super(`The ${template} template cannot be served: its data source is unavailable`);
72
+ this.template = template;
73
+ _chunkUNL4JWZScjs.__publicField.call(void 0, this, "name", "BuilderUnavailablePageError");
74
+ }
75
+ };
76
+ var isRec = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
77
+ var isNamed = (error, name) => typeof error === "object" && error !== null && error.name === name;
78
+ var isNotFound = (error) => error instanceof _builder.BuilderNotFoundError || isNamed(error, "BuilderNotFoundError");
79
+ var isUnavailable = (error) => error instanceof _builder.BuilderUnavailableError || isNamed(error, "BuilderUnavailableError");
80
+ var isNavigation = (error) => {
81
+ const digest = isRec(error) ? error.digest : void 0;
82
+ return typeof digest === "string" && /^NEXT_(HTTP_ERROR_FALLBACK|NOT_FOUND|REDIRECT)/.test(digest);
83
+ };
84
+ var cache2 = _nullishCoalesce(React.cache, () => ( ((fn) => fn)));
85
+ function pathOf(options, params) {
86
+ const value = params[_nullishCoalesce(options.pathParam, () => ( "path"))];
87
+ const segments = value === void 0 ? [] : Array.isArray(value) ? value : [value];
88
+ try {
89
+ const path = `/${segments.map((segment) => decodeURIComponent(segment)).join("/")}`;
90
+ return path.includes("\0") ? null : path;
91
+ } catch (e2) {
92
+ return null;
93
+ }
94
+ }
95
+ function matchTemplate(template, path) {
96
+ if (!template.startsWith("/")) return null;
97
+ const names = [];
98
+ const pattern = template.split(/(\{[A-Za-z][A-Za-z0-9]*\})/).map((part) => {
99
+ const named = /^\{([A-Za-z][A-Za-z0-9]*)\}$/.exec(part);
100
+ if (named === null) return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
101
+ names.push(named[1]);
102
+ return "([^/]+)";
103
+ }).join("").replace(/\/+$/, "");
104
+ const match = new RegExp(`^${pattern === "" ? "/" : pattern}$`).exec(
105
+ path.length > 1 ? path.replace(/\/+$/, "") : path
106
+ );
107
+ return match === null ? null : Object.fromEntries(names.map((name, i) => [name, match[i + 1]]));
108
+ }
109
+ function redirectRows(settings) {
110
+ const seo = isRec(settings.seo) ? settings.seo : {};
111
+ if (!Array.isArray(seo.redirects)) return [];
112
+ return seo.redirects.flatMap((row) => {
113
+ if (!isRec(row) || typeof row.from !== "string" || typeof row.to !== "string") return [];
114
+ return [
115
+ { from: row.from, to: row.to, status: typeof row.status === "number" ? row.status : 308 }
116
+ ];
117
+ });
118
+ }
119
+ function redirectFor(settings, path) {
120
+ const row = _builderschema.matchRedirect.call(void 0, path, redirectRows(settings));
121
+ if (row === null) return null;
122
+ const to = _nullishCoalesce(sitePath(row.to), () => ( (/^https?:\/\/[^\s\\]+$/iu.test(row.to) ? row.to : null)));
123
+ if (to === null) return null;
124
+ return { kind: "redirect", to, permanent: row.status === 301 || row.status === 308 };
125
+ }
126
+ function storeRoutesOf(settings, config) {
127
+ const routes = isRec(settings.routes) ? settings.routes : {};
128
+ const store = isRec(routes.store) ? routes.store : {};
129
+ const own = Object.fromEntries(
130
+ Object.entries(store).filter(([, value]) => typeof value === "string")
131
+ );
132
+ return { ...DEFAULT_STORE_TEMPLATE_PATHS, ...config.storeRoutes, ...own };
133
+ }
134
+ function createBuilderRoute(options) {
135
+ const packs = options.packs;
136
+ function loaderFor(name) {
137
+ const own = _optionalChain([options, 'access', _ => _.loaders, 'optionalAccess', _2 => _2[name]]);
138
+ if (own !== void 0) return own;
139
+ for (const pack of packs) {
140
+ const found = _optionalChain([pack, 'access', _3 => _3.templates, 'optionalAccess', _4 => _4.find, 'call', _5 => _5((template) => template.name === name)]);
141
+ if (found !== void 0) return found.loader;
142
+ }
143
+ return void 0;
144
+ }
145
+ async function localeOf2(params) {
146
+ if (typeof options.locale === "function") return options.locale(params);
147
+ if (options.locale !== void 0) return options.locale;
148
+ return typeof params.locale === "string" ? params.locale : "en";
149
+ }
150
+ async function resolve(path, locale, currency) {
151
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
152
+ const bundle = await _chunkUNL4JWZScjs.getBundle.call(void 0, { client, locale, slots: options.slots });
153
+ const settings = bundle.site.settings;
154
+ const read = {
155
+ client: options.client,
156
+ builderKey: options.builderKey,
157
+ locale,
158
+ packs,
159
+ slots: options.slots,
160
+ ...currency === void 0 ? {} : { currency }
161
+ };
162
+ const moved = redirectFor(settings, path);
163
+ if (moved !== null) return moved;
164
+ const catalogOn = bundle.site.catalogInstalled !== false;
165
+ const catalog = { ...DEFAULT_CATALOG_TEMPLATE_PATHS, ...options.catalogRoutes };
166
+ const store = storeRoutesOf(settings, options);
167
+ const all = { ...catalog, ...store };
168
+ const served = Object.entries(all).filter(
169
+ ([name]) => catalogOn || !_builderschema.CATALOG_TEMPLATES.includes(name)
170
+ );
171
+ const matched = served.flatMap(([name, template]) => {
172
+ const params = matchTemplate(template, path);
173
+ return params === null ? [] : [{ name, params }];
174
+ })[0];
175
+ const routeTable = _chunkUNL4JWZScjs.buildRouteTable.call(void 0, store, catalog);
176
+ if (path === "/") {
177
+ try {
178
+ const home = await _chunkUNL4JWZScjs.loadBuilderPage.call(void 0, { ...read, slug: "home" });
179
+ if (home.kind === "redirect") return redirectTo(home.redirectTo);
180
+ return { kind: "page", slug: "home", page: home, path, own: false };
181
+ } catch (error) {
182
+ if (!isNotFound(error)) throw error;
183
+ }
184
+ }
185
+ const pageRoute = isRec(settings.routes) && typeof settings.routes.page === "string" ? settings.routes.page : "/pages/{handle}";
186
+ const handle = _optionalChain([matchTemplate, 'call', _6 => _6(pageRoute, path), 'optionalAccess', _7 => _7.handle]);
187
+ if (matched === void 0 && handle === void 0 && path !== "/" && _builderschema.PAGE_PATH_RE.test(path)) {
188
+ try {
189
+ const found = await _chunkUNL4JWZScjs.loadBuilderPageByPath.call(void 0, { ...read, path });
190
+ if (found.kind === "redirect") return redirectTo(found.redirectTo);
191
+ return { kind: "page", slug: found.slug, page: found, path, own: true };
192
+ } catch (error) {
193
+ if (!isNotFound(error)) throw error;
194
+ }
195
+ }
196
+ if (handle !== void 0) {
197
+ try {
198
+ const found = await _chunkUNL4JWZScjs.loadBuilderPage.call(void 0, { ...read, slug: handle });
199
+ if (found.kind === "redirect") return redirectTo(found.redirectTo);
200
+ if (_chunkUNL4JWZScjs.isOwnPath.call(void 0, found.path)) return { kind: "redirect", to: found.path, permanent: true };
201
+ return { kind: "page", slug: handle, page: found, path, own: false };
202
+ } catch (error) {
203
+ if (!isNotFound(error)) throw error;
204
+ }
205
+ }
206
+ if (matched === void 0) return { kind: "notFound" };
207
+ return { kind: "matched", name: matched.name, params: matched.params, routeTable, path };
208
+ }
209
+ async function finish(matched, queryJson, locale, currency) {
210
+ const { name, path, routeTable } = matched;
211
+ const query = JSON.parse(queryJson);
212
+ const bundle = await _chunkUNL4JWZScjs.getBundle.call(void 0, { client: _chunkUNL4JWZScjs.clientOf.call(void 0, options), locale, slots: options.slots });
213
+ const read = {
214
+ client: options.client,
215
+ builderKey: options.builderKey,
216
+ locale,
217
+ packs,
218
+ slots: options.slots,
219
+ ...currency === void 0 ? {} : { currency }
220
+ };
221
+ const route = { path, params: matched.params, query };
222
+ const loader = loaderFor(name);
223
+ if (loader === void 0 && _builderschema.CATALOG_TEMPLATES.includes(name))
224
+ return { kind: "notFound" };
225
+ const loaded = await runLoader(loader, { ...matched.params }, query, route);
226
+ if (loaded.status === "not-found") return { kind: "notFound" };
227
+ if (loaded.status === "redirect") return redirectTo(loaded.to);
228
+ const unavailable = loaded.status === "unavailable";
229
+ const context = unavailable ? { route, unavailable: true } : loaded.context;
230
+ const shared = {
231
+ ...bundle.savedSections === void 0 ? {} : { savedSections: bundle.savedSections },
232
+ ...bundle.code === void 0 ? {} : { code: bundle.code }
233
+ };
234
+ try {
235
+ const { part, meta } = await _chunkUNL4JWZScjs.loadBuilderTemplate.call(void 0, { ...read, name, shared });
236
+ return { kind: "template", name, part, context, meta, routeTable, path, unavailable };
237
+ } catch (error) {
238
+ const contribution = packs.flatMap((pack) => _nullishCoalesce(pack.templates, () => ( []))).find((entry) => entry.name === name);
239
+ if (!isUnavailable(error) || contribution === void 0) throw error;
240
+ const sections = contribution.defaultComposition();
241
+ const part = {
242
+ document: { schemaVersion: 1, sections },
243
+ assets: {},
244
+ initialData: {}
245
+ };
246
+ return {
247
+ kind: "template",
248
+ name,
249
+ part,
250
+ context,
251
+ meta: void 0,
252
+ routeTable,
253
+ path,
254
+ unavailable
255
+ };
256
+ }
257
+ }
258
+ function redirectTo(to) {
259
+ const path = _nullishCoalesce(sitePath(to), () => ( (/^https?:\/\/[^\s\\]+$/iu.test(to) ? to : null)));
260
+ return path === null ? { kind: "notFound" } : { kind: "redirect", to: path, permanent: true };
261
+ }
262
+ async function runLoader(loader, params, query, route) {
263
+ if (loader === void 0) return { status: "ok", context: { route } };
264
+ try {
265
+ return await loader({ params, searchParams: query, route });
266
+ } catch (error) {
267
+ if (isUnavailable(error)) return { status: "unavailable" };
268
+ throw error;
269
+ }
270
+ }
271
+ const resolveCached = cache2(resolve);
272
+ const finishCached = cache2(finish);
273
+ async function request(props) {
274
+ const params = await props.params;
275
+ const path = pathOf(options, params);
276
+ const locale = await localeOf2(params);
277
+ const currency = typeof options.currency === "function" ? await options.currency(params) : options.currency;
278
+ const first = path === null ? { kind: "notFound" } : await resolveCached(path, locale, currency);
279
+ let query = {};
280
+ let resolved;
281
+ if (first.kind === "matched") {
282
+ const searchParams = await _asyncNullishCoalesce(await props.searchParams, async () => ( {}));
283
+ query = Object.fromEntries(
284
+ Object.entries(searchParams).filter(([, value]) => value !== void 0)
285
+ );
286
+ resolved = await finishCached(first, JSON.stringify(query), locale, currency);
287
+ } else resolved = first;
288
+ const search = new URLSearchParams(
289
+ Object.entries(query).flatMap(
290
+ ([key, value]) => (Array.isArray(value) ? value : [value]).map((v) => [key, v])
291
+ )
292
+ ).toString();
293
+ return { resolved, params, locale, search: search === "" ? "" : `?${search}` };
294
+ }
295
+ function templateBody(resolved) {
296
+ const view = /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _builderreact.BuilderTemplateView, { name: resolved.name, part: resolved.part, context: resolved.context });
297
+ const Root = _chunkUNL4JWZScjs.templateRootOf.call(void 0, packs, resolved.name);
298
+ if (Root === void 0) return view;
299
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Root, { context: resolved.context, document: resolved.part.document, children: view });
300
+ }
301
+ async function Page(props) {
302
+ const { resolved } = await request(props);
303
+ switch (resolved.kind) {
304
+ case "redirect":
305
+ return resolved.permanent ? _navigation.permanentRedirect.call(void 0, resolved.to) : _navigation.redirect.call(void 0, resolved.to);
306
+ case "notFound":
307
+ return _navigation.notFound.call(void 0, );
308
+ case "page":
309
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _builderreact.BuilderRouteScope, { ...resolved.own ? { allowPath: resolved.path } : {}, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _builderreact.BuilderPageView, { page: resolved.page }) });
310
+ case "template":
311
+ if (resolved.unavailable) {
312
+ if (options.unavailable === "error") throw new BuilderUnavailablePageError(resolved.name);
313
+ _optionalChain([options, 'access', _8 => _8.onUnavailable, 'optionalCall', _9 => _9({
314
+ status: 503,
315
+ headers: { "Retry-After": String(_nullishCoalesce(options.retryAfterSeconds, () => ( 30))) }
316
+ })]);
317
+ return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _builderreact.BuilderRouteScope, { templateName: resolved.name, routeTable: resolved.routeTable, children: [
318
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "meta", { name: "robots", content: "noindex" }),
319
+ templateBody(resolved)
320
+ ] });
321
+ }
322
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _builderreact.BuilderRouteScope, { templateName: resolved.name, routeTable: resolved.routeTable, children: templateBody(resolved) });
323
+ }
324
+ }
325
+ async function generateMetadata(props) {
326
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
327
+ try {
328
+ const { resolved, params, locale, search } = await request(props);
329
+ if (resolved.kind === "redirect" || resolved.kind === "notFound") return {};
330
+ const bundle = await _chunkUNL4JWZScjs.getBundle.call(void 0, { client, locale, slots: options.slots });
331
+ const settings = bundle.site.settings;
332
+ if (resolved.kind === "page") {
333
+ const shared = await _chunkUNL4JWZScjs.getBundle.call(void 0, {
334
+ client,
335
+ locale,
336
+ page: resolved.slug,
337
+ slots: options.slots
338
+ });
339
+ const page = shared.page;
340
+ if (page === void 0 || "redirectTo" in page) return {};
341
+ return _chunkUNL4JWZScjs.metadataOf.call(void 0, page, {
342
+ settings: shared.site.settings,
343
+ mediaOrigin: _nullishCoalesce(options.mediaOrigin, () => ( "")),
344
+ storeUrl: options.storeUrl,
345
+ pagePath: _nullishCoalesce(options.pagePath, () => ( ((entry) => entry.pageType === "home" ? "/" : entry.path))),
346
+ routeLocale: options.locale === void 0 && typeof params.locale === "string" ? params.locale : void 0
347
+ });
348
+ }
349
+ return _chunkUNL4JWZScjs.templateMetadataOf.call(void 0, resolved.name, {
350
+ settings,
351
+ storeUrl: options.storeUrl,
352
+ mediaOrigin: _nullishCoalesce(options.mediaOrigin, () => ( "")),
353
+ path: resolved.path,
354
+ search,
355
+ // An unavailable answer has no product or listing to name: the store's own title, `noindex`.
356
+ context: resolved.unavailable ? void 0 : resolved.context,
357
+ meta: resolved.meta,
358
+ ...resolved.unavailable ? { noindex: true } : {}
359
+ });
360
+ } catch (error) {
361
+ if (isNavigation(error) || isNotFound(error)) return {};
362
+ if (isUnavailable(error) && client.mode !== "build") return {};
363
+ throw error;
364
+ }
365
+ }
366
+ return { Page, generateMetadata };
367
+ }
368
+
369
+ // src/next/template.tsx
370
+
371
+
372
+
373
+ async function BuilderTemplate({
374
+ name,
375
+ packs,
376
+ locale = "en",
377
+ context,
378
+ ...client
379
+ }) {
380
+ try {
381
+ const { part } = await _chunkUNL4JWZScjs.loadBuilderTemplate.call(void 0, {
382
+ ...client,
383
+ name,
384
+ locale,
385
+ ...packs === void 0 ? {} : { packs }
386
+ });
387
+ const templateContext = _nullishCoalesce(context, () => ( { route: { path: "", params: {}, query: {} } }));
388
+ const view = _react.createElement.call(void 0, _builderreact.BuilderTemplateView, { name, part, context: templateContext });
389
+ const Root = _chunkUNL4JWZScjs.templateRootOf.call(void 0, packs, name);
390
+ return Root === void 0 ? view : _react.createElement.call(void 0, Root, { context: templateContext, document: part.document, children: view });
391
+ } catch (error) {
392
+ if (error instanceof _builder.BuilderUnavailableError || _optionalChain([error, 'optionalAccess', _10 => _10.name]) === "BuilderUnavailableError")
393
+ return null;
394
+ throw error;
395
+ }
396
+ }
397
+
34
398
  // src/next/index.ts
35
399
  function slugOf(options, params) {
36
400
  if ("slug" in options) return options.slug;
@@ -42,7 +406,7 @@ function slugOf(options, params) {
42
406
  async function currencyOf(options, params) {
43
407
  return typeof options.currency === "function" ? options.currency(params) : options.currency;
44
408
  }
45
- var isNamed = (error, name) => typeof error === "object" && error !== null && error.name === name;
409
+ var isNamed2 = (error, name) => typeof error === "object" && error !== null && error.name === name;
46
410
  async function localeOf(options, params) {
47
411
  if (typeof options.locale === "function") return options.locale(params);
48
412
  if (options.locale !== void 0) return options.locale;
@@ -55,13 +419,13 @@ function createBuilderPage(options) {
55
419
  const slug = slugOf(options, params);
56
420
  const currency = await currencyOf(options, params);
57
421
  const { currency: _currency, ...rest } = options;
58
- const loaded = await _chunkXHTZWZPNcjs.loadBuilderPage.call(void 0, {
422
+ const loaded = await _chunkUNL4JWZScjs.loadBuilderPage.call(void 0, {
59
423
  ...rest,
60
424
  slug,
61
425
  locale: await localeOf(options, params),
62
426
  ...currency === void 0 ? {} : { currency }
63
427
  }).catch((error) => {
64
- if (error instanceof _builder.BuilderNotFoundError || isNamed(error, "BuilderNotFoundError")) _navigation.notFound.call(void 0, );
428
+ if (error instanceof _builder.BuilderNotFoundError || isNamed2(error, "BuilderNotFoundError")) _navigation.notFound.call(void 0, );
65
429
  throw error;
66
430
  });
67
431
  if (loaded.kind === "redirect") {
@@ -75,12 +439,12 @@ function createBuilderPage(options) {
75
439
  const params = await props.params;
76
440
  const slug = slugOf(options, params);
77
441
  const locale = await localeOf(options, params);
78
- const client = _chunkXHTZWZPNcjs.clientOf.call(void 0, options);
442
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
79
443
  try {
80
- const bundle = await _chunkXHTZWZPNcjs.getBundle.call(void 0, { client, locale, page: slug, slots: options.slots });
444
+ const bundle = await _chunkUNL4JWZScjs.getBundle.call(void 0, { client, locale, page: slug, slots: options.slots });
81
445
  const page = bundle.page;
82
- if (page === void 0 || _chunkXHTZWZPNcjs.isRedirect.call(void 0, page)) return {};
83
- return _chunkXHTZWZPNcjs.metadataOf.call(void 0, page, {
446
+ if (page === void 0 || _chunkUNL4JWZScjs.isRedirect.call(void 0, page)) return {};
447
+ return _chunkUNL4JWZScjs.metadataOf.call(void 0, page, {
84
448
  settings: bundle.site.settings,
85
449
  mediaOrigin: _nullishCoalesce(options.mediaOrigin, () => ( "")),
86
450
  storeUrl: options.storeUrl,
@@ -88,8 +452,8 @@ function createBuilderPage(options) {
88
452
  routeLocale: options.locale === void 0 && typeof params.locale === "string" ? params.locale : void 0
89
453
  });
90
454
  } catch (error) {
91
- if (error instanceof _builder.BuilderNotFoundError || isNamed(error, "BuilderNotFoundError")) return {};
92
- if ((error instanceof _builder.BuilderUnavailableError || isNamed(error, "BuilderUnavailableError")) && client.mode !== "build") return {};
455
+ if (error instanceof _builder.BuilderNotFoundError || isNamed2(error, "BuilderNotFoundError")) return {};
456
+ if ((error instanceof _builder.BuilderUnavailableError || isNamed2(error, "BuilderUnavailableError")) && client.mode !== "build") return {};
93
457
  throw error;
94
458
  }
95
459
  }
@@ -97,4 +461,10 @@ function createBuilderPage(options) {
97
461
  }
98
462
 
99
463
 
100
- exports.createBuilderPage = createBuilderPage;
464
+
465
+
466
+
467
+
468
+
469
+
470
+ exports.BuilderTemplate = BuilderTemplate; exports.BuilderUnavailablePageError = BuilderUnavailablePageError; exports.DEFAULT_CATALOG_TEMPLATE_PATHS = DEFAULT_CATALOG_TEMPLATE_PATHS; exports.DEFAULT_STORE_TEMPLATE_PATHS = DEFAULT_STORE_TEMPLATE_PATHS; exports.canonicalFor = _chunkUNL4JWZScjs.canonicalFor; exports.createBuilderPage = createBuilderPage; exports.createBuilderRoute = createBuilderRoute;
package/dist/next.d.cts CHANGED
@@ -1,9 +1,98 @@
1
1
  import { ReactNode } from 'react';
2
2
  import { Metadata } from 'next';
3
- import { C as ClientOptions, W as WidgetPack, P as PagePathResolver } from './seo-CNZ9DrlU.cjs';
4
- import '@usethrottle/builder-schema';
3
+ import { B as BuilderRouteConfig, b as ClientOptions, P as PagePathResolver, W as WidgetPack, T as TemplateContext } from './seo-iX2POfOp.cjs';
4
+ export { C as CanonicalKind, f as canonicalFor } from './seo-iX2POfOp.cjs';
5
+ import { TemplateName } from '@usethrottle/builder-schema';
5
6
  import '@usethrottle/builder';
6
7
 
8
+ type Params$1 = Record<string, string | string[] | undefined>;
9
+ type PageProps$1 = {
10
+ params: Promise<Params$1> | Params$1;
11
+ searchParams?: Promise<Params$1> | Params$1;
12
+ };
13
+ /** The catalog templates a store has unless it passes `catalogRoutes` (`{name}` is one path segment). */
14
+ declare const DEFAULT_CATALOG_TEMPLATE_PATHS: Partial<Record<TemplateName, string>>;
15
+ /** The store templates (`routes.store`) a site has unless the merchant renamed them. */
16
+ declare const DEFAULT_STORE_TEMPLATE_PATHS: Partial<Record<TemplateName, string>>;
17
+ /** What an unavailable answer would carry as a response. REPORT ONLY: this package cannot send it (see `onUnavailable`). */
18
+ type UnavailableResponse = {
19
+ status: 503;
20
+ headers: {
21
+ 'Retry-After': string;
22
+ };
23
+ };
24
+ /**
25
+ * Thrown by `Page` for an unavailable template when the route is made with `unavailable: 'error'`, so the store's
26
+ * `error.tsx` answers (a 5xx) instead of a 200 page. Tagged by name like the Builder's own errors.
27
+ */
28
+ declare class BuilderUnavailablePageError extends Error {
29
+ readonly template: TemplateName;
30
+ name: string;
31
+ constructor(template: TemplateName);
32
+ }
33
+ type CreateBuilderRouteOptions = Omit<BuilderRouteConfig, 'site' | 'loaders'> & Partial<Pick<BuilderRouteConfig, 'site' | 'loaders'>> & ClientOptions & {
34
+ /** The route param holding the path segments (`app/(store)/[[...path]]`). Default `path`. */
35
+ pathParam?: string;
36
+ locale?: string | ((params: Params$1) => string | Promise<string>);
37
+ currency?: string | ((params: Params$1) => string | undefined | Promise<string | undefined>);
38
+ slots?: readonly string[];
39
+ storeUrl?: string;
40
+ mediaOrigin?: string;
41
+ pagePath?: PagePathResolver;
42
+ /** Seconds in the `Retry-After` of an unavailable template. Default 30. */
43
+ retryAfterSeconds?: number;
44
+ /**
45
+ * What an unavailable template (E3: its loader answered `unavailable`) does.
46
+ *
47
+ * - `'render'` (default): the template document is drawn with `context.unavailable === true` and `noindex`, and
48
+ * the response is HTTP **200**. DEVIATION from E3 (503 + `Retry-After`): a Next server component cannot set a
49
+ * status or a header, and a streamed 200 is already committed.
50
+ * - `'error'`: `Page` throws `BuilderUnavailablePageError`, so the store's `error.tsx` answers a 5xx.
51
+ */
52
+ unavailable?: 'render' | 'error';
53
+ /**
54
+ * REPORT ONLY. Called once per request that renders an unavailable template with the 503 + `Retry-After` the
55
+ * response ought to carry. Nothing here sends it: a store that wants the real status wires its own proxy or
56
+ * route layer from this call, or uses `unavailable: 'error'`.
57
+ */
58
+ onUnavailable?: (response: UnavailableResponse) => void;
59
+ };
60
+ /**
61
+ * The one route of a Builder store (`app/(store)/[[...path]]/page.tsx`), resolving a path in this order: SEO redirects,
62
+ * `/` (the home page), a page at its own path, `/pages/{handle}` (308 to the page's own path), an older path of a page
63
+ * (308), the template table (catalog templates only when the catalog is installed or unknown), `notFound()`.
64
+ *
65
+ * ```ts
66
+ * const route = createBuilderRoute({ builderKey, packs });
67
+ * export default route.Page;
68
+ * export const generateMetadata = route.generateMetadata;
69
+ * ```
70
+ *
71
+ * `Page` renders through `BuilderProvider`, so the layout has one above it. A template's loader comes from its pack
72
+ * (`packs[].templates`; `loaders` overrides by name). Loader answers: `ok` renders the template, `not-found` is
73
+ * `notFound()` (Next draws the store's `not-found.tsx`, a `<BuilderTemplate name="not-found" />`, inside the layout),
74
+ * `redirect` is a 308, `unavailable` renders the unavailable state with `noindex` and reports 503 + `Retry-After`.
75
+ * The reads are the Builder client's (tag-invalidated); this file sets no revalidate time and never purges a path.
76
+ */
77
+ declare function createBuilderRoute(options: CreateBuilderRouteOptions): {
78
+ Page: (props: PageProps$1) => Promise<ReactNode>;
79
+ generateMetadata: (props: PageProps$1) => Promise<Metadata>;
80
+ };
81
+
82
+ type BuilderTemplateProps = ClientOptions & {
83
+ name: TemplateName;
84
+ packs?: readonly WidgetPack[];
85
+ /** Default `en`. */
86
+ locale?: string;
87
+ context?: TemplateContext;
88
+ };
89
+ /**
90
+ * A published template drawn on its own: `app/(store)/not-found.tsx` is `<BuilderTemplate name="not-found" ... />`, which
91
+ * Next renders inside the layout, so the header and footer stay around it. A template that cannot be read draws
92
+ * nothing rather than failing the 404 (the layout's parts still render).
93
+ */
94
+ declare function BuilderTemplate({ name, packs, locale, context, ...client }: BuilderTemplateProps): Promise<ReactNode>;
95
+
7
96
  type Params = Record<string, string | string[] | undefined>;
8
97
  type CreateBuilderPageOptions = ({
9
98
  slug: string;
@@ -51,4 +140,4 @@ declare function createBuilderPage(options: CreateBuilderPageOptions): {
51
140
  generateMetadata: (props: PageProps) => Promise<Metadata>;
52
141
  };
53
142
 
54
- export { type CreateBuilderPageOptions, createBuilderPage };
143
+ export { BuilderTemplate, type BuilderTemplateProps, BuilderUnavailablePageError, type CreateBuilderPageOptions, type CreateBuilderRouteOptions, DEFAULT_CATALOG_TEMPLATE_PATHS, DEFAULT_STORE_TEMPLATE_PATHS, type UnavailableResponse, createBuilderPage, createBuilderRoute };
package/dist/next.d.ts CHANGED
@@ -1,9 +1,98 @@
1
1
  import { ReactNode } from 'react';
2
2
  import { Metadata } from 'next';
3
- import { C as ClientOptions, W as WidgetPack, P as PagePathResolver } from './seo-CNZ9DrlU.js';
4
- import '@usethrottle/builder-schema';
3
+ import { B as BuilderRouteConfig, b as ClientOptions, P as PagePathResolver, W as WidgetPack, T as TemplateContext } from './seo-iX2POfOp.js';
4
+ export { C as CanonicalKind, f as canonicalFor } from './seo-iX2POfOp.js';
5
+ import { TemplateName } from '@usethrottle/builder-schema';
5
6
  import '@usethrottle/builder';
6
7
 
8
+ type Params$1 = Record<string, string | string[] | undefined>;
9
+ type PageProps$1 = {
10
+ params: Promise<Params$1> | Params$1;
11
+ searchParams?: Promise<Params$1> | Params$1;
12
+ };
13
+ /** The catalog templates a store has unless it passes `catalogRoutes` (`{name}` is one path segment). */
14
+ declare const DEFAULT_CATALOG_TEMPLATE_PATHS: Partial<Record<TemplateName, string>>;
15
+ /** The store templates (`routes.store`) a site has unless the merchant renamed them. */
16
+ declare const DEFAULT_STORE_TEMPLATE_PATHS: Partial<Record<TemplateName, string>>;
17
+ /** What an unavailable answer would carry as a response. REPORT ONLY: this package cannot send it (see `onUnavailable`). */
18
+ type UnavailableResponse = {
19
+ status: 503;
20
+ headers: {
21
+ 'Retry-After': string;
22
+ };
23
+ };
24
+ /**
25
+ * Thrown by `Page` for an unavailable template when the route is made with `unavailable: 'error'`, so the store's
26
+ * `error.tsx` answers (a 5xx) instead of a 200 page. Tagged by name like the Builder's own errors.
27
+ */
28
+ declare class BuilderUnavailablePageError extends Error {
29
+ readonly template: TemplateName;
30
+ name: string;
31
+ constructor(template: TemplateName);
32
+ }
33
+ type CreateBuilderRouteOptions = Omit<BuilderRouteConfig, 'site' | 'loaders'> & Partial<Pick<BuilderRouteConfig, 'site' | 'loaders'>> & ClientOptions & {
34
+ /** The route param holding the path segments (`app/(store)/[[...path]]`). Default `path`. */
35
+ pathParam?: string;
36
+ locale?: string | ((params: Params$1) => string | Promise<string>);
37
+ currency?: string | ((params: Params$1) => string | undefined | Promise<string | undefined>);
38
+ slots?: readonly string[];
39
+ storeUrl?: string;
40
+ mediaOrigin?: string;
41
+ pagePath?: PagePathResolver;
42
+ /** Seconds in the `Retry-After` of an unavailable template. Default 30. */
43
+ retryAfterSeconds?: number;
44
+ /**
45
+ * What an unavailable template (E3: its loader answered `unavailable`) does.
46
+ *
47
+ * - `'render'` (default): the template document is drawn with `context.unavailable === true` and `noindex`, and
48
+ * the response is HTTP **200**. DEVIATION from E3 (503 + `Retry-After`): a Next server component cannot set a
49
+ * status or a header, and a streamed 200 is already committed.
50
+ * - `'error'`: `Page` throws `BuilderUnavailablePageError`, so the store's `error.tsx` answers a 5xx.
51
+ */
52
+ unavailable?: 'render' | 'error';
53
+ /**
54
+ * REPORT ONLY. Called once per request that renders an unavailable template with the 503 + `Retry-After` the
55
+ * response ought to carry. Nothing here sends it: a store that wants the real status wires its own proxy or
56
+ * route layer from this call, or uses `unavailable: 'error'`.
57
+ */
58
+ onUnavailable?: (response: UnavailableResponse) => void;
59
+ };
60
+ /**
61
+ * The one route of a Builder store (`app/(store)/[[...path]]/page.tsx`), resolving a path in this order: SEO redirects,
62
+ * `/` (the home page), a page at its own path, `/pages/{handle}` (308 to the page's own path), an older path of a page
63
+ * (308), the template table (catalog templates only when the catalog is installed or unknown), `notFound()`.
64
+ *
65
+ * ```ts
66
+ * const route = createBuilderRoute({ builderKey, packs });
67
+ * export default route.Page;
68
+ * export const generateMetadata = route.generateMetadata;
69
+ * ```
70
+ *
71
+ * `Page` renders through `BuilderProvider`, so the layout has one above it. A template's loader comes from its pack
72
+ * (`packs[].templates`; `loaders` overrides by name). Loader answers: `ok` renders the template, `not-found` is
73
+ * `notFound()` (Next draws the store's `not-found.tsx`, a `<BuilderTemplate name="not-found" />`, inside the layout),
74
+ * `redirect` is a 308, `unavailable` renders the unavailable state with `noindex` and reports 503 + `Retry-After`.
75
+ * The reads are the Builder client's (tag-invalidated); this file sets no revalidate time and never purges a path.
76
+ */
77
+ declare function createBuilderRoute(options: CreateBuilderRouteOptions): {
78
+ Page: (props: PageProps$1) => Promise<ReactNode>;
79
+ generateMetadata: (props: PageProps$1) => Promise<Metadata>;
80
+ };
81
+
82
+ type BuilderTemplateProps = ClientOptions & {
83
+ name: TemplateName;
84
+ packs?: readonly WidgetPack[];
85
+ /** Default `en`. */
86
+ locale?: string;
87
+ context?: TemplateContext;
88
+ };
89
+ /**
90
+ * A published template drawn on its own: `app/(store)/not-found.tsx` is `<BuilderTemplate name="not-found" ... />`, which
91
+ * Next renders inside the layout, so the header and footer stay around it. A template that cannot be read draws
92
+ * nothing rather than failing the 404 (the layout's parts still render).
93
+ */
94
+ declare function BuilderTemplate({ name, packs, locale, context, ...client }: BuilderTemplateProps): Promise<ReactNode>;
95
+
7
96
  type Params = Record<string, string | string[] | undefined>;
8
97
  type CreateBuilderPageOptions = ({
9
98
  slug: string;
@@ -51,4 +140,4 @@ declare function createBuilderPage(options: CreateBuilderPageOptions): {
51
140
  generateMetadata: (props: PageProps) => Promise<Metadata>;
52
141
  };
53
142
 
54
- export { type CreateBuilderPageOptions, createBuilderPage };
143
+ export { BuilderTemplate, type BuilderTemplateProps, BuilderUnavailablePageError, type CreateBuilderPageOptions, type CreateBuilderRouteOptions, DEFAULT_CATALOG_TEMPLATE_PATHS, DEFAULT_STORE_TEMPLATE_PATHS, type UnavailableResponse, createBuilderPage, createBuilderRoute };