@usethrottle/builder 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -2
- package/dist/chunk-EERLS5TR.js +98 -0
- package/dist/chunk-UFIR4HJA.cjs +98 -0
- package/dist/index.cjs +290 -0
- package/dist/index.d.cts +133 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +290 -0
- package/dist/next.cjs +117 -0
- package/dist/next.d.cts +45 -0
- package/dist/next.d.ts +45 -0
- package/dist/next.js +117 -0
- package/dist/verify-CkxGofEg.d.cts +15 -0
- package/dist/verify-CkxGofEg.d.ts +15 -0
- package/dist/watch.cjs +103 -0
- package/dist/watch.js +83 -0
- package/package.json +93 -3
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @usethrottle/builder
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> `"private": true` in `package.json` keeps release-publish from publishing `0.0.0`. Task 16 (the release task) removes it together with adding the changeset.
|
|
4
|
+
|
|
5
|
+
Headless client for Throttle Builder. A merchant storefront reads published pages,
|
|
6
|
+
header and footer parts, slots and site settings with it.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { createBuilderClient } from '@usethrottle/builder';
|
|
10
|
+
|
|
11
|
+
const builder = createBuilderClient({ builderKey: process.env.THROTTLE_BUILDER_KEY! });
|
|
12
|
+
const page = await builder.pages.get('about', { locale: 'en' }); // LoadedPage | { redirectTo }
|
|
13
|
+
const { site, header, footer, slots } = await builder.bundle({ page: 'about', slots: ['shop.above'], locale: 'en' });
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Errors: `BuilderUnavailableError` (timeout after 3 s, network, 5xx), `BuilderNotFoundError`
|
|
17
|
+
(an unpublished page), `PreviewExpiredError`. A read that fails within 10 minutes of a
|
|
18
|
+
good one answers the good one (per process) and logs once.
|
|
19
|
+
|
|
20
|
+
## Caching (Next.js)
|
|
21
|
+
|
|
22
|
+
Every published read is `until-changed`: `next: { revalidate: 3600, tags }`. The hour is
|
|
23
|
+
only a safety net; a change notice clears the tags sooner. There is no option for a
|
|
24
|
+
shorter time. Tags: `throttle-builder` on every read, plus `throttle-builder:site`,
|
|
25
|
+
`:pages`, `:page:<slug>`, `:part:<name>` and `:slot:<name>` for what the read holds. A
|
|
26
|
+
preview or draft read is `no-store`. Nothing here calls `revalidatePath`.
|
|
27
|
+
|
|
28
|
+
## `@usethrottle/builder/next`
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
// app/api/builder/revalidate/route.ts
|
|
32
|
+
import { createRevalidateHandler } from '@usethrottle/builder/next';
|
|
33
|
+
export const POST = createRevalidateHandler({ secret: process.env.THROTTLE_BUILDER_WEBHOOK_SECRET });
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`verifyBuilderNotice({ rawBody, header, secret, now })` checks the
|
|
37
|
+
`X-Throttle-Builder-Signature` header (`now` is unix seconds). `previewMiddleware(req)`
|
|
38
|
+
moves `?throttle_builder_preview=` into an HTTP-only cookie; `getPreviewToken()` reads
|
|
39
|
+
it (it makes that render dynamic, so call it only on a preview-only route) and goes to
|
|
40
|
+
`createBuilderClient({ previewToken })`.
|
|
41
|
+
|
|
42
|
+
## `@usethrottle/builder/watch`
|
|
43
|
+
|
|
44
|
+
`useGenerationWatch({ builderKey, onChange })` is a client-side backstop for a missed
|
|
45
|
+
notice: it reads the site generation (at most every 30 s, only while the tab is visible)
|
|
46
|
+
and calls `onChange`, for example `() => router.refresh()`.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
|
|
5
|
+
// src/tags.ts
|
|
6
|
+
var TAG = "throttle-builder";
|
|
7
|
+
var TAG_MAX_CHARS = 256;
|
|
8
|
+
var BUILDER_TAGS = {
|
|
9
|
+
all: TAG,
|
|
10
|
+
site: `${TAG}:site`,
|
|
11
|
+
pages: `${TAG}:pages`,
|
|
12
|
+
page: (slug) => `${TAG}:page:${slug}`,
|
|
13
|
+
part: (name) => `${TAG}:part:${name}`,
|
|
14
|
+
slot: (name) => `${TAG}:slot:${name}`
|
|
15
|
+
};
|
|
16
|
+
function fitTags(tags) {
|
|
17
|
+
return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
|
|
18
|
+
}
|
|
19
|
+
function scopesToTags(scopes) {
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const scope of scopes) {
|
|
22
|
+
const colon = scope.indexOf(":");
|
|
23
|
+
const name = colon < 0 ? scope : scope.slice(0, colon);
|
|
24
|
+
const rest = colon < 0 ? "" : scope.slice(colon + 1);
|
|
25
|
+
if (colon < 0 && (scope === "site" || scope === "menus"))
|
|
26
|
+
out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
|
|
27
|
+
else if (colon < 0 && (scope === "header" || scope === "footer"))
|
|
28
|
+
out.push(BUILDER_TAGS.part(scope));
|
|
29
|
+
else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
|
|
30
|
+
else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
|
|
31
|
+
else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
|
|
32
|
+
else out.push(BUILDER_TAGS.all);
|
|
33
|
+
}
|
|
34
|
+
return fitTags(out);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/next/verify.ts
|
|
38
|
+
var SIGNATURE_LABEL = "throttle.builder-notice.v1";
|
|
39
|
+
var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
|
|
40
|
+
var TOLERANCE_SECONDS = 300;
|
|
41
|
+
var MAX_V1 = 8;
|
|
42
|
+
var MAX_HEADER_BYTES = 1024;
|
|
43
|
+
var encoder = new TextEncoder();
|
|
44
|
+
async function hmac(secret, payload) {
|
|
45
|
+
const key = await crypto.subtle.importKey(
|
|
46
|
+
"raw",
|
|
47
|
+
encoder.encode(secret),
|
|
48
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
49
|
+
false,
|
|
50
|
+
["sign"]
|
|
51
|
+
);
|
|
52
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
|
|
53
|
+
}
|
|
54
|
+
function fromHex(hex) {
|
|
55
|
+
return Uint8Array.from(
|
|
56
|
+
{ length: hex.length / 2 },
|
|
57
|
+
(_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
function constantTimeEqual(left, right) {
|
|
61
|
+
const length = Math.max(left.length, right.length);
|
|
62
|
+
let difference = left.length ^ right.length;
|
|
63
|
+
for (let i = 0; i < length; i += 1) difference |= (left[i] ?? 0) ^ (right[i] ?? 0);
|
|
64
|
+
return difference === 0;
|
|
65
|
+
}
|
|
66
|
+
async function verifyBuilderNotice(input) {
|
|
67
|
+
try {
|
|
68
|
+
const { rawBody, header, secret, now } = input;
|
|
69
|
+
if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
|
|
70
|
+
return false;
|
|
71
|
+
const parts = header.split(",").map((part) => part.split("="));
|
|
72
|
+
if (parts.some((part) => part.length !== 2)) return false;
|
|
73
|
+
const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => v ?? "");
|
|
74
|
+
const digests = parts.filter(([k]) => k === "v1").map(([, v]) => v ?? "");
|
|
75
|
+
if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
|
|
76
|
+
return false;
|
|
77
|
+
const timestampText = timestamps[0] ?? "";
|
|
78
|
+
if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
|
|
79
|
+
const timestamp = Number(timestampText);
|
|
80
|
+
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
|
|
81
|
+
return false;
|
|
82
|
+
const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
|
|
83
|
+
let matched = false;
|
|
84
|
+
for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
|
|
85
|
+
return matched;
|
|
86
|
+
} catch {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export {
|
|
92
|
+
__publicField,
|
|
93
|
+
TAG_MAX_CHARS,
|
|
94
|
+
BUILDER_TAGS,
|
|
95
|
+
fitTags,
|
|
96
|
+
scopesToTags,
|
|
97
|
+
verifyBuilderNotice
|
|
98
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
+
|
|
5
|
+
// src/tags.ts
|
|
6
|
+
var TAG = "throttle-builder";
|
|
7
|
+
var TAG_MAX_CHARS = 256;
|
|
8
|
+
var BUILDER_TAGS = {
|
|
9
|
+
all: TAG,
|
|
10
|
+
site: `${TAG}:site`,
|
|
11
|
+
pages: `${TAG}:pages`,
|
|
12
|
+
page: (slug) => `${TAG}:page:${slug}`,
|
|
13
|
+
part: (name) => `${TAG}:part:${name}`,
|
|
14
|
+
slot: (name) => `${TAG}:slot:${name}`
|
|
15
|
+
};
|
|
16
|
+
function fitTags(tags) {
|
|
17
|
+
return [...new Set(tags)].filter((tag) => tag.length <= TAG_MAX_CHARS);
|
|
18
|
+
}
|
|
19
|
+
function scopesToTags(scopes) {
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const scope of scopes) {
|
|
22
|
+
const colon = scope.indexOf(":");
|
|
23
|
+
const name = colon < 0 ? scope : scope.slice(0, colon);
|
|
24
|
+
const rest = colon < 0 ? "" : scope.slice(colon + 1);
|
|
25
|
+
if (colon < 0 && (scope === "site" || scope === "menus"))
|
|
26
|
+
out.push(BUILDER_TAGS.site, BUILDER_TAGS.part("header"), BUILDER_TAGS.part("footer"));
|
|
27
|
+
else if (colon < 0 && (scope === "header" || scope === "footer"))
|
|
28
|
+
out.push(BUILDER_TAGS.part(scope));
|
|
29
|
+
else if (colon < 0 && scope === "pages") out.push(BUILDER_TAGS.pages);
|
|
30
|
+
else if (rest !== "" && name === "page") out.push(BUILDER_TAGS.page(rest));
|
|
31
|
+
else if (rest !== "" && name === "slot") out.push(BUILDER_TAGS.slot(rest));
|
|
32
|
+
else out.push(BUILDER_TAGS.all);
|
|
33
|
+
}
|
|
34
|
+
return fitTags(out);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/next/verify.ts
|
|
38
|
+
var SIGNATURE_LABEL = "throttle.builder-notice.v1";
|
|
39
|
+
var HEX_SHA256 = /^[0-9a-fA-F]{64}$/u;
|
|
40
|
+
var TOLERANCE_SECONDS = 300;
|
|
41
|
+
var MAX_V1 = 8;
|
|
42
|
+
var MAX_HEADER_BYTES = 1024;
|
|
43
|
+
var encoder = new TextEncoder();
|
|
44
|
+
async function hmac(secret, payload) {
|
|
45
|
+
const key = await crypto.subtle.importKey(
|
|
46
|
+
"raw",
|
|
47
|
+
encoder.encode(secret),
|
|
48
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
49
|
+
false,
|
|
50
|
+
["sign"]
|
|
51
|
+
);
|
|
52
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(payload)));
|
|
53
|
+
}
|
|
54
|
+
function fromHex(hex) {
|
|
55
|
+
return Uint8Array.from(
|
|
56
|
+
{ length: hex.length / 2 },
|
|
57
|
+
(_, i) => Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16)
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
function constantTimeEqual(left, right) {
|
|
61
|
+
const length = Math.max(left.length, right.length);
|
|
62
|
+
let difference = left.length ^ right.length;
|
|
63
|
+
for (let i = 0; i < length; i += 1) difference |= (_nullishCoalesce(left[i], () => ( 0))) ^ (_nullishCoalesce(right[i], () => ( 0)));
|
|
64
|
+
return difference === 0;
|
|
65
|
+
}
|
|
66
|
+
async function verifyBuilderNotice(input) {
|
|
67
|
+
try {
|
|
68
|
+
const { rawBody, header, secret, now } = input;
|
|
69
|
+
if (secret.length === 0 || rawBody.length === 0 || header.length === 0 || !Number.isFinite(now) || encoder.encode(header).byteLength > MAX_HEADER_BYTES)
|
|
70
|
+
return false;
|
|
71
|
+
const parts = header.split(",").map((part) => part.split("="));
|
|
72
|
+
if (parts.some((part) => part.length !== 2)) return false;
|
|
73
|
+
const timestamps = parts.filter(([k]) => k === "t").map(([, v]) => _nullishCoalesce(v, () => ( "")));
|
|
74
|
+
const digests = parts.filter(([k]) => k === "v1").map(([, v]) => _nullishCoalesce(v, () => ( "")));
|
|
75
|
+
if (parts.some(([k]) => k !== "t" && k !== "v1") || timestamps.length !== 1 || digests.length === 0 || digests.length > MAX_V1 || digests.some((d) => !HEX_SHA256.test(d)))
|
|
76
|
+
return false;
|
|
77
|
+
const timestampText = _nullishCoalesce(timestamps[0], () => ( ""));
|
|
78
|
+
if (!/^(?:0|[1-9][0-9]*)$/u.test(timestampText)) return false;
|
|
79
|
+
const timestamp = Number(timestampText);
|
|
80
|
+
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > TOLERANCE_SECONDS)
|
|
81
|
+
return false;
|
|
82
|
+
const expected = await hmac(secret, `${SIGNATURE_LABEL}.${timestampText}.${rawBody}`);
|
|
83
|
+
let matched = false;
|
|
84
|
+
for (const digest of digests) matched = constantTimeEqual(expected, fromHex(digest)) || matched;
|
|
85
|
+
return matched;
|
|
86
|
+
} catch (e) {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
exports.__publicField = __publicField; exports.TAG_MAX_CHARS = TAG_MAX_CHARS; exports.BUILDER_TAGS = BUILDER_TAGS; exports.fitTags = fitTags; exports.scopesToTags = scopesToTags; exports.verifyBuilderNotice = verifyBuilderNotice;
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
var _chunkUFIR4HJAcjs = require('./chunk-UFIR4HJA.cjs');
|
|
8
|
+
|
|
9
|
+
// src/errors.ts
|
|
10
|
+
var BuilderUnavailableError = class extends Error {
|
|
11
|
+
constructor(reason, message, options = {}) {
|
|
12
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
13
|
+
_chunkUFIR4HJAcjs.__publicField.call(void 0, this, "reason");
|
|
14
|
+
/** The HTTP status, when the Builder answered. */
|
|
15
|
+
_chunkUFIR4HJAcjs.__publicField.call(void 0, this, "status");
|
|
16
|
+
this.name = "BuilderUnavailableError";
|
|
17
|
+
this.reason = reason;
|
|
18
|
+
this.status = options.status;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var BuilderNotFoundError = class extends Error {
|
|
22
|
+
constructor(slug) {
|
|
23
|
+
super(slug === void 0 ? "Builder page not found" : `Builder page "${slug}" not found`);
|
|
24
|
+
_chunkUFIR4HJAcjs.__publicField.call(void 0, this, "slug");
|
|
25
|
+
this.name = "BuilderNotFoundError";
|
|
26
|
+
this.slug = slug;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var PreviewExpiredError = class extends Error {
|
|
30
|
+
constructor() {
|
|
31
|
+
super("The Builder preview link has expired");
|
|
32
|
+
this.name = "PreviewExpiredError";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// src/client.ts
|
|
37
|
+
var _builderschema = require('@usethrottle/builder-schema');
|
|
38
|
+
|
|
39
|
+
// src/cache.ts
|
|
40
|
+
var UNTIL_CHANGED_REVALIDATE_S = 3600;
|
|
41
|
+
function cacheInit(tags, preview) {
|
|
42
|
+
if (preview) return { cache: "no-store" };
|
|
43
|
+
return { next: { revalidate: UNTIL_CHANGED_REVALIDATE_S, tags: [...tags] } };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/last-good.ts
|
|
47
|
+
var LAST_GOOD_MS = 10 * 60 * 1e3;
|
|
48
|
+
var MAX_ENTRIES = 200;
|
|
49
|
+
var store = /* @__PURE__ */ new Map();
|
|
50
|
+
function rememberGood(key, value) {
|
|
51
|
+
store.delete(key);
|
|
52
|
+
store.set(key, { value, at: Date.now(), warned: false });
|
|
53
|
+
if (store.size > MAX_ENTRIES) {
|
|
54
|
+
const oldest = store.keys().next();
|
|
55
|
+
if (!oldest.done) store.delete(oldest.value);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function recallGood(key, warn) {
|
|
59
|
+
const entry = store.get(key);
|
|
60
|
+
if (entry === void 0) return void 0;
|
|
61
|
+
if (Date.now() - entry.at > LAST_GOOD_MS) {
|
|
62
|
+
store.delete(key);
|
|
63
|
+
return void 0;
|
|
64
|
+
}
|
|
65
|
+
if (!entry.warned) {
|
|
66
|
+
entry.warned = true;
|
|
67
|
+
warn();
|
|
68
|
+
}
|
|
69
|
+
return { value: entry.value };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/client.ts
|
|
73
|
+
var DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
|
|
74
|
+
var DEFAULT_TIMEOUT_MS = 3e3;
|
|
75
|
+
var MAX_NAME_CHARS = 128;
|
|
76
|
+
function isRecord(value) {
|
|
77
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
78
|
+
}
|
|
79
|
+
function queryString(query) {
|
|
80
|
+
const pairs = Object.entries(query).filter((entry) => entry[1] !== void 0 && entry[1] !== "").sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
81
|
+
return pairs.length === 0 ? "" : `?${pairs.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&")}`;
|
|
82
|
+
}
|
|
83
|
+
function checkName(kind, value) {
|
|
84
|
+
if (typeof value !== "string" || value === "" || value.length > MAX_NAME_CHARS)
|
|
85
|
+
throw new TypeError(`A Builder ${kind} is a non-empty string of at most ${String(MAX_NAME_CHARS)} characters`);
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
function currentDocument(answer, where) {
|
|
89
|
+
const doc = answer.document;
|
|
90
|
+
if (!isRecord(doc))
|
|
91
|
+
throw new BuilderUnavailableError("invalid-response", `Builder ${where} answer has no document`);
|
|
92
|
+
if (doc.schemaVersion === _builderschema.CURRENT_SCHEMA_VERSION) return doc;
|
|
93
|
+
const upgraded = _builderschema.upgradeDocument.call(void 0, doc);
|
|
94
|
+
if (!upgraded.ok)
|
|
95
|
+
throw new BuilderUnavailableError(
|
|
96
|
+
"unsupported-document",
|
|
97
|
+
`Builder ${where} document cannot be read by this SDK version (${_nullishCoalesce(_optionalChain([upgraded, 'access', _ => _.issues, 'access', _2 => _2[0], 'optionalAccess', _3 => _3.code]), () => ( "invalid"))})`
|
|
98
|
+
);
|
|
99
|
+
return upgraded.doc;
|
|
100
|
+
}
|
|
101
|
+
function withDocument(answer, where) {
|
|
102
|
+
return { ...answer, document: currentDocument(answer, where) };
|
|
103
|
+
}
|
|
104
|
+
var invalid = (message) => new BuilderUnavailableError("invalid-response", message);
|
|
105
|
+
function generationOf(answer, where) {
|
|
106
|
+
const { generation } = answer;
|
|
107
|
+
if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 0)
|
|
108
|
+
throw invalid(`Builder ${where} answer has no generation`);
|
|
109
|
+
return generation;
|
|
110
|
+
}
|
|
111
|
+
function readSite(answer) {
|
|
112
|
+
generationOf(answer, "site");
|
|
113
|
+
if (typeof answer.siteVersion !== "number" || !Number.isSafeInteger(answer.siteVersion))
|
|
114
|
+
throw invalid("Builder site answer has no siteVersion");
|
|
115
|
+
if (!isRecord(answer.settings)) throw invalid("Builder site answer has no settings");
|
|
116
|
+
return answer;
|
|
117
|
+
}
|
|
118
|
+
var SUMMARY_KEYS = ["id", "slug", "pageType", "title", "updatedAt", "path"];
|
|
119
|
+
function readPages(answer) {
|
|
120
|
+
const { pages } = answer;
|
|
121
|
+
if (!Array.isArray(pages)) throw invalid("Builder pages answer is not a list");
|
|
122
|
+
for (const page of pages)
|
|
123
|
+
if (!isRecord(page) || SUMMARY_KEYS.some((key) => typeof page[key] !== "string"))
|
|
124
|
+
throw invalid("Builder pages answer has a page without its fields");
|
|
125
|
+
return pages;
|
|
126
|
+
}
|
|
127
|
+
function readDocument(answer, where) {
|
|
128
|
+
generationOf(answer, where);
|
|
129
|
+
return withDocument(answer, where);
|
|
130
|
+
}
|
|
131
|
+
function readPage(answer) {
|
|
132
|
+
if (typeof answer.redirectTo === "string") return { redirectTo: answer.redirectTo };
|
|
133
|
+
generationOf(answer, "page");
|
|
134
|
+
if (typeof answer.slug !== "string") throw invalid("Builder page answer has no slug");
|
|
135
|
+
return withDocument(answer, "page");
|
|
136
|
+
}
|
|
137
|
+
function readBundle(answer) {
|
|
138
|
+
const generation = generationOf(answer, "bundle");
|
|
139
|
+
if (!isRecord(answer.site) || !isRecord(answer.header) || !isRecord(answer.footer))
|
|
140
|
+
throw invalid("Builder bundle answer has no site, header or footer");
|
|
141
|
+
const slots = answer.slots === void 0 ? {} : answer.slots;
|
|
142
|
+
if (!isRecord(slots)) throw invalid("Builder bundle answer has slots that are not an object");
|
|
143
|
+
return {
|
|
144
|
+
generation,
|
|
145
|
+
site: readSite(answer.site),
|
|
146
|
+
header: readDocument(answer.header, "header"),
|
|
147
|
+
footer: readDocument(answer.footer, "footer"),
|
|
148
|
+
...isRecord(answer.page) ? { page: readPage(answer.page) } : {},
|
|
149
|
+
slots: Object.fromEntries(
|
|
150
|
+
Object.entries(slots).map(([name, value]) => {
|
|
151
|
+
if (!isRecord(value)) throw invalid(`Builder slot ${name} answer is not an object`);
|
|
152
|
+
return [name, readDocument(value, `slot ${name}`)];
|
|
153
|
+
})
|
|
154
|
+
)
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function createBuilderClient(options) {
|
|
158
|
+
const { builderKey, previewToken } = options;
|
|
159
|
+
if (typeof builderKey !== "string" || builderKey === "")
|
|
160
|
+
throw new TypeError("createBuilderClient needs a builderKey");
|
|
161
|
+
if (builderKey.startsWith("tb_sk_"))
|
|
162
|
+
throw new TypeError("createBuilderClient takes the publishable Builder key (tb_pk_\u2026), never a secret key");
|
|
163
|
+
const previewHeader = previewToken !== void 0 && previewToken !== "" ? previewToken : void 0;
|
|
164
|
+
const preview = previewHeader !== void 0;
|
|
165
|
+
const base = (_nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL))).replace(/\/+$/u, "");
|
|
166
|
+
const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( DEFAULT_TIMEOUT_MS));
|
|
167
|
+
const doFetch = options.fetch;
|
|
168
|
+
async function once(url, init) {
|
|
169
|
+
const controller = new AbortController();
|
|
170
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
171
|
+
try {
|
|
172
|
+
const response = await (_nullishCoalesce(doFetch, () => ( globalThis.fetch)))(url, {
|
|
173
|
+
...init,
|
|
174
|
+
signal: controller.signal
|
|
175
|
+
});
|
|
176
|
+
let body;
|
|
177
|
+
try {
|
|
178
|
+
body = response.status === 204 ? void 0 : await response.json();
|
|
179
|
+
} catch (cause) {
|
|
180
|
+
if (controller.signal.aborted) throw cause;
|
|
181
|
+
body = void 0;
|
|
182
|
+
}
|
|
183
|
+
return { body, status: response.status };
|
|
184
|
+
} catch (cause) {
|
|
185
|
+
throw new BuilderUnavailableError(
|
|
186
|
+
controller.signal.aborted ? "timeout" : "network",
|
|
187
|
+
controller.signal.aborted ? `Builder did not answer within ${String(timeoutMs)} ms` : "Builder could not be reached",
|
|
188
|
+
{ cause }
|
|
189
|
+
);
|
|
190
|
+
} finally {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async function fetchAnswer(path, read2) {
|
|
195
|
+
const headers = { accept: "application/json", "X-Builder-Key": builderKey };
|
|
196
|
+
if (previewHeader !== void 0) headers["X-Builder-Preview"] = previewHeader;
|
|
197
|
+
const url = `${base}${path}${queryString(_nullishCoalesce(read2.query, () => ( {})))}`;
|
|
198
|
+
const init = { method: "GET", headers, ...cacheInit(_chunkUFIR4HJAcjs.fitTags.call(void 0, read2.tags), preview) };
|
|
199
|
+
const { body, status } = await once(url, init);
|
|
200
|
+
if (status === 401 && preview) throw new PreviewExpiredError();
|
|
201
|
+
if (status === 404 && read2.pageSlug !== void 0) throw new BuilderNotFoundError(read2.pageSlug);
|
|
202
|
+
if (status < 200 || status >= 300)
|
|
203
|
+
throw new BuilderUnavailableError("status", `Builder answered ${String(status)}`, { status });
|
|
204
|
+
if (!isRecord(body) && !Array.isArray(body))
|
|
205
|
+
throw new BuilderUnavailableError("invalid-response", "Builder answered a body that is not JSON");
|
|
206
|
+
return Array.isArray(body) ? { pages: body } : body;
|
|
207
|
+
}
|
|
208
|
+
async function read(path, options2, shape) {
|
|
209
|
+
const goodKey = `${base}|${builderKey}|${path}${queryString(_nullishCoalesce(options2.query, () => ( {})))}`;
|
|
210
|
+
try {
|
|
211
|
+
const value = shape(await fetchAnswer(path, options2));
|
|
212
|
+
if (!preview) rememberGood(goodKey, value);
|
|
213
|
+
return value;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (preview || !(error instanceof BuilderUnavailableError)) throw error;
|
|
216
|
+
const good = recallGood(goodKey, () => {
|
|
217
|
+
console.warn(
|
|
218
|
+
`[throttle-builder] ${path} failed (${error.reason}); serving the last good answer`
|
|
219
|
+
);
|
|
220
|
+
});
|
|
221
|
+
if (good === void 0) throw error;
|
|
222
|
+
return good.value;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
site: ({ locale } = {}) => read("/v1/site", { query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.site] }, readSite),
|
|
227
|
+
pages: {
|
|
228
|
+
list: () => read(
|
|
229
|
+
"/v1/pages",
|
|
230
|
+
{ tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.pages] },
|
|
231
|
+
readPages
|
|
232
|
+
),
|
|
233
|
+
get: async (slug, { locale } = {}) => read(
|
|
234
|
+
`/v1/pages/${encodeURIComponent(checkName("page slug", slug))}`,
|
|
235
|
+
{ query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.page(slug)], pageSlug: slug },
|
|
236
|
+
readPage
|
|
237
|
+
)
|
|
238
|
+
},
|
|
239
|
+
parts: {
|
|
240
|
+
get: async (name, { locale } = {}) => {
|
|
241
|
+
if (name !== "header" && name !== "footer")
|
|
242
|
+
throw new TypeError('A Builder part is "header" or "footer"');
|
|
243
|
+
return read(
|
|
244
|
+
`/v1/parts/${name}`,
|
|
245
|
+
{ query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.part(name)] },
|
|
246
|
+
(answer) => readDocument(answer, `part ${name}`)
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
},
|
|
250
|
+
slots: {
|
|
251
|
+
get: async (name, { locale } = {}) => read(
|
|
252
|
+
`/v1/slots/${encodeURIComponent(checkName("slot name", name))}`,
|
|
253
|
+
{ query: { locale }, tags: [_chunkUFIR4HJAcjs.BUILDER_TAGS.all, _chunkUFIR4HJAcjs.BUILDER_TAGS.slot(name)] },
|
|
254
|
+
(answer) => readDocument(answer, `slot ${name}`)
|
|
255
|
+
)
|
|
256
|
+
},
|
|
257
|
+
bundle: async ({ page: pageSlug, slots, locale } = {}) => {
|
|
258
|
+
const names = [...new Set(_nullishCoalesce(slots, () => ( [])))].map((name) => checkName("slot name", name)).sort();
|
|
259
|
+
if (pageSlug !== void 0) checkName("page slug", pageSlug);
|
|
260
|
+
return read(
|
|
261
|
+
"/v1/bundle",
|
|
262
|
+
{
|
|
263
|
+
query: { page: pageSlug, slots: names.join(","), locale },
|
|
264
|
+
pageSlug,
|
|
265
|
+
tags: [
|
|
266
|
+
_chunkUFIR4HJAcjs.BUILDER_TAGS.all,
|
|
267
|
+
_chunkUFIR4HJAcjs.BUILDER_TAGS.site,
|
|
268
|
+
_chunkUFIR4HJAcjs.BUILDER_TAGS.part("header"),
|
|
269
|
+
_chunkUFIR4HJAcjs.BUILDER_TAGS.part("footer"),
|
|
270
|
+
...pageSlug === void 0 ? [] : [_chunkUFIR4HJAcjs.BUILDER_TAGS.page(pageSlug)],
|
|
271
|
+
...names.map((name) => _chunkUFIR4HJAcjs.BUILDER_TAGS.slot(name))
|
|
272
|
+
]
|
|
273
|
+
},
|
|
274
|
+
readBundle
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
exports.BUILDER_TAGS = _chunkUFIR4HJAcjs.BUILDER_TAGS; exports.BuilderNotFoundError = BuilderNotFoundError; exports.BuilderUnavailableError = BuilderUnavailableError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS; exports.PreviewExpiredError = PreviewExpiredError; exports.UNTIL_CHANGED_REVALIDATE_S = UNTIL_CHANGED_REVALIDATE_S; exports.createBuilderClient = createBuilderClient; exports.scopesToTags = _chunkUFIR4HJAcjs.scopesToTags; exports.verifyBuilderNotice = _chunkUFIR4HJAcjs.verifyBuilderNotice;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { PageDocument } from '@usethrottle/builder-schema';
|
|
2
|
+
export { v as verifyBuilderNotice } from './verify-CkxGofEg.cjs';
|
|
3
|
+
|
|
4
|
+
type BuilderUnavailableReason = 'timeout' | 'network' | 'status' | 'invalid-response' | 'unsupported-document';
|
|
5
|
+
/**
|
|
6
|
+
* The Builder could not answer: a timeout, a network failure, a non-success
|
|
7
|
+
* status, a body that is not what the read API sends, or a document from a
|
|
8
|
+
* newer schema than this build reads. A caller with no last good answer lets
|
|
9
|
+
* it reach the store's error boundary instead of rendering a blank page.
|
|
10
|
+
*/
|
|
11
|
+
declare class BuilderUnavailableError extends Error {
|
|
12
|
+
readonly reason: BuilderUnavailableReason;
|
|
13
|
+
/** The HTTP status, when the Builder answered. */
|
|
14
|
+
readonly status: number | undefined;
|
|
15
|
+
constructor(reason: BuilderUnavailableReason, message: string, options?: {
|
|
16
|
+
status?: number;
|
|
17
|
+
cause?: unknown;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/** A page (or a bundle's page) that is not published and has no redirect: `404 PAGE_NOT_FOUND`. */
|
|
21
|
+
declare class BuilderNotFoundError extends Error {
|
|
22
|
+
readonly slug: string | undefined;
|
|
23
|
+
constructor(slug?: string);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The preview token is expired or not valid (`401 PREVIEW_EXPIRED`). A preview
|
|
27
|
+
* read never falls back to the published page: the caller shows that the link
|
|
28
|
+
* has expired.
|
|
29
|
+
*/
|
|
30
|
+
declare class PreviewExpiredError extends Error {
|
|
31
|
+
constructor();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Published site settings resolved for one locale (localized values are strings). */
|
|
35
|
+
type BuilderSite = {
|
|
36
|
+
generation: number;
|
|
37
|
+
siteVersion: number;
|
|
38
|
+
settings: Record<string, unknown>;
|
|
39
|
+
};
|
|
40
|
+
type BuilderPageSummary = {
|
|
41
|
+
id: string;
|
|
42
|
+
slug: string;
|
|
43
|
+
pageType: string;
|
|
44
|
+
title: string;
|
|
45
|
+
updatedAt: string;
|
|
46
|
+
path: string;
|
|
47
|
+
};
|
|
48
|
+
/** A published page: its metadata and its document (with frozen custom widgets and assets). */
|
|
49
|
+
type LoadedPage = BuilderPageSummary & {
|
|
50
|
+
generation: number;
|
|
51
|
+
document: PageDocument;
|
|
52
|
+
[key: string]: unknown;
|
|
53
|
+
};
|
|
54
|
+
type PageRedirect = {
|
|
55
|
+
redirectTo: string;
|
|
56
|
+
};
|
|
57
|
+
/** A published part or slot document; an empty document when unpublished. */
|
|
58
|
+
type LoadedDocument = {
|
|
59
|
+
generation: number;
|
|
60
|
+
document: PageDocument;
|
|
61
|
+
};
|
|
62
|
+
type BuilderBundle = {
|
|
63
|
+
generation: number;
|
|
64
|
+
site: BuilderSite;
|
|
65
|
+
header: LoadedDocument;
|
|
66
|
+
footer: LoadedDocument;
|
|
67
|
+
page?: LoadedPage | PageRedirect;
|
|
68
|
+
/** Only the slots that were asked for. */
|
|
69
|
+
slots: Record<string, LoadedDocument>;
|
|
70
|
+
};
|
|
71
|
+
type PartName = 'header' | 'footer';
|
|
72
|
+
type BuilderClientOptions = {
|
|
73
|
+
/** The publishable key (`tb_pk_…`). Sent as `X-Builder-Key`. */
|
|
74
|
+
builderKey: string;
|
|
75
|
+
/** Defaults to `https://builder.usethrottle.dev`. */
|
|
76
|
+
baseUrl?: string;
|
|
77
|
+
fetch?: typeof fetch;
|
|
78
|
+
/** Per read, body included. Default 3000. */
|
|
79
|
+
timeoutMs?: number;
|
|
80
|
+
/**
|
|
81
|
+
* A preview token (`getPreviewToken()` from `@usethrottle/builder/next`).
|
|
82
|
+
* Every read then sends `X-Builder-Preview`, reads drafts, is never cached
|
|
83
|
+
* and never answers from a last good. An expired token throws
|
|
84
|
+
* `PreviewExpiredError`.
|
|
85
|
+
*/
|
|
86
|
+
previewToken?: string | undefined;
|
|
87
|
+
};
|
|
88
|
+
type LocaleOptions = {
|
|
89
|
+
locale?: string;
|
|
90
|
+
};
|
|
91
|
+
type BuilderClient = {
|
|
92
|
+
site(options?: LocaleOptions): Promise<BuilderSite>;
|
|
93
|
+
pages: {
|
|
94
|
+
list(): Promise<BuilderPageSummary[]>;
|
|
95
|
+
get(slug: string, options?: LocaleOptions): Promise<LoadedPage | PageRedirect>;
|
|
96
|
+
};
|
|
97
|
+
parts: {
|
|
98
|
+
get(name: PartName, options?: LocaleOptions): Promise<LoadedDocument>;
|
|
99
|
+
};
|
|
100
|
+
slots: {
|
|
101
|
+
get(name: string, options?: LocaleOptions): Promise<LoadedDocument>;
|
|
102
|
+
};
|
|
103
|
+
bundle(options?: LocaleOptions & {
|
|
104
|
+
page?: string;
|
|
105
|
+
slots?: readonly string[];
|
|
106
|
+
}): Promise<BuilderBundle>;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
declare const DEFAULT_BASE_URL = "https://builder.usethrottle.dev";
|
|
110
|
+
declare const DEFAULT_TIMEOUT_MS = 3000;
|
|
111
|
+
declare function createBuilderClient(options: BuilderClientOptions): BuilderClient;
|
|
112
|
+
|
|
113
|
+
declare const BUILDER_TAGS: {
|
|
114
|
+
readonly all: "throttle-builder";
|
|
115
|
+
readonly site: "throttle-builder:site";
|
|
116
|
+
readonly pages: "throttle-builder:pages";
|
|
117
|
+
readonly page: (slug: string) => string;
|
|
118
|
+
readonly part: (name: string) => string;
|
|
119
|
+
readonly slot: (name: string) => string;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* The tags a change notice's scopes clear. `site` and `menus` clear the site,
|
|
123
|
+
* header and footer reads and never pages. `header` and `footer` clear their
|
|
124
|
+
* part, `pages` the list, `page:<slug>` and `slot:<name>` that one read. A
|
|
125
|
+
* scope this build does not know clears the coarse tag, so a newer Worker
|
|
126
|
+
* never leaves a store stale. In order, without repeats.
|
|
127
|
+
*/
|
|
128
|
+
declare function scopesToTags(scopes: readonly string[]): string[];
|
|
129
|
+
|
|
130
|
+
/** Next's `revalidate` for a published read: only a safety net behind the change notices. */
|
|
131
|
+
declare const UNTIL_CHANGED_REVALIDATE_S = 3600;
|
|
132
|
+
|
|
133
|
+
export { BUILDER_TAGS, type BuilderBundle, type BuilderClient, type BuilderClientOptions, BuilderNotFoundError, type BuilderPageSummary, type BuilderSite, BuilderUnavailableError, type BuilderUnavailableReason, DEFAULT_BASE_URL, DEFAULT_TIMEOUT_MS, type LoadedDocument, type LoadedPage, type LocaleOptions, type PageRedirect, type PartName, PreviewExpiredError, UNTIL_CHANGED_REVALIDATE_S, createBuilderClient, scopesToTags };
|