@decocms/blocks 8.1.0-next.6 → 8.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/dist/v8/cli/check/index.d.ts +6 -2
- package/dist/v8/cli/check/index.d.ts.map +1 -1
- package/dist/v8/cli/check/index.js +34 -7
- package/dist/v8/cli/check/index.js.map +1 -1
- package/dist/v8/cli/color.d.ts +14 -0
- package/dist/v8/cli/color.d.ts.map +1 -0
- package/dist/v8/cli/color.js +14 -0
- package/dist/v8/cli/color.js.map +1 -0
- package/dist/v8/cli/content.d.ts +24 -3
- package/dist/v8/cli/content.d.ts.map +1 -1
- package/dist/v8/cli/content.js +70 -5
- package/dist/v8/cli/content.js.map +1 -1
- package/dist/v8/cli/log.d.ts +4 -0
- package/dist/v8/cli/log.d.ts.map +1 -1
- package/dist/v8/cli/log.js +9 -0
- package/dist/v8/cli/log.js.map +1 -1
- package/dist/v8/cli/run.d.ts +1 -0
- package/dist/v8/cli/run.d.ts.map +1 -1
- package/dist/v8/cli/run.js +18 -4
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cli/schema/index.d.ts.map +1 -1
- package/dist/v8/cli/schema/index.js +5 -3
- package/dist/v8/cli/schema/index.js.map +1 -1
- package/dist/v8/cli/schema/tsProgram.d.ts +1 -0
- package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
- package/dist/v8/cli/schema/tsProgram.js +1 -0
- package/dist/v8/cli/schema/tsProgram.js.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.js +50 -7
- package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
- package/dist/v8/cms.d.ts.map +1 -1
- package/dist/v8/cms.js +16 -19
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/content.d.ts +4 -5
- package/dist/v8/content.d.ts.map +1 -1
- package/dist/v8/content.js +46 -44
- package/dist/v8/content.js.map +1 -1
- package/dist/v8/draftChanges.d.ts +37 -14
- package/dist/v8/draftChanges.d.ts.map +1 -1
- package/dist/v8/draftChanges.js +66 -44
- package/dist/v8/draftChanges.js.map +1 -1
- package/dist/v8/identity.d.ts +0 -2
- package/dist/v8/identity.d.ts.map +1 -1
- package/dist/v8/identity.js +0 -10
- package/dist/v8/identity.js.map +1 -1
- package/dist/v8/matchRoute.d.ts +12 -10
- package/dist/v8/matchRoute.d.ts.map +1 -1
- package/dist/v8/matchRoute.js +60 -86
- package/dist/v8/matchRoute.js.map +1 -1
- package/dist/v8/remoteLoader.d.ts +4 -4
- package/dist/v8/remoteLoader.d.ts.map +1 -1
- package/dist/v8/remoteLoader.js +106 -96
- package/dist/v8/remoteLoader.js.map +1 -1
- package/dist/v8/routeTrie.d.ts +43 -0
- package/dist/v8/routeTrie.d.ts.map +1 -0
- package/dist/v8/routeTrie.js +88 -0
- package/dist/v8/routeTrie.js.map +1 -0
- package/dist/v8/telemetry.d.ts +7 -7
- package/dist/v8/telemetry.d.ts.map +1 -1
- package/dist/v8/telemetry.js +24 -100
- package/dist/v8/telemetry.js.map +1 -1
- package/dist/v8/types.d.ts +59 -17
- package/dist/v8/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/v8/cli/check/index.ts +32 -7
- package/src/v8/cli/color.ts +29 -0
- package/src/v8/cli/content.ts +85 -5
- package/src/v8/cli/log.ts +12 -0
- package/src/v8/cli/run.ts +19 -4
- package/src/v8/cli/schema/index.ts +5 -3
- package/src/v8/cli/schema/tsProgram.ts +2 -1
- package/src/v8/cli/schema/typeToSchema.ts +47 -7
- package/src/v8/cms.ts +17 -20
- package/src/v8/content.ts +54 -46
- package/src/v8/draftChanges.ts +79 -43
- package/src/v8/identity.ts +0 -10
- package/src/v8/matchRoute.ts +70 -106
- package/src/v8/remoteLoader.ts +112 -111
- package/src/v8/routeTrie.ts +103 -0
- package/src/v8/telemetry.ts +27 -108
- package/src/v8/types.ts +60 -15
package/src/v8/matchRoute.ts
CHANGED
|
@@ -2,30 +2,37 @@
|
|
|
2
2
|
* `matchRoute(url, items)`: finds the entry for a URL (see /next/routing and
|
|
3
3
|
* /next/router-internals).
|
|
4
4
|
*
|
|
5
|
-
* Paths compile into a segment trie, cached per array
|
|
6
|
-
* the URL's depth, not the number of routes. At every
|
|
7
|
-
* literal child, then the parameter child, then a
|
|
8
|
-
* or more remaining segments), so exact paths win
|
|
9
|
-
* parameters over a splat, per segment. Redirects are
|
|
10
|
-
* first
|
|
11
|
-
*
|
|
12
|
-
* one
|
|
5
|
+
* Paths compile into a segment trie (`routeTrie.ts`), cached per array
|
|
6
|
+
* object: a lookup costs the URL's depth, not the number of routes. At every
|
|
7
|
+
* node the walk tries the literal child, then the parameter child, then a
|
|
8
|
+
* trailing `*` (a splat: one or more remaining segments), so exact paths win
|
|
9
|
+
* over parameters and parameters over a splat, per segment. Redirects are
|
|
10
|
+
* checked first, in their own tries: one per query a `from` is scoped to
|
|
11
|
+
* (`/calcados?map=c,ft`), tried when the request's query is exactly that one,
|
|
12
|
+
* then one for the path-only sources. Two entries that reach the same leaf
|
|
13
|
+
* are a conflict `deco check` reports; here the earlier one keeps it, so a
|
|
14
|
+
* lookup never throws. No regex, no sorting.
|
|
13
15
|
*/
|
|
16
|
+
|
|
17
|
+
import type { TrieNode } from "./routeTrie.ts";
|
|
18
|
+
import {
|
|
19
|
+
buildTrie,
|
|
20
|
+
type Hit,
|
|
21
|
+
insert,
|
|
22
|
+
lookup,
|
|
23
|
+
safeDecode,
|
|
24
|
+
splitPath,
|
|
25
|
+
splitRef,
|
|
26
|
+
} from "./routeTrie.ts";
|
|
14
27
|
import type { LegacyRedirect, Match, Redirect, RedirectStatus, Route } from "./types.ts";
|
|
15
28
|
|
|
16
|
-
/**
|
|
17
|
-
type
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
param?: TrieNode<T>;
|
|
21
|
-
leaf?: Leaf<T>;
|
|
22
|
-
splat?: Leaf<T>;
|
|
23
|
-
};
|
|
24
|
-
type Hit<T> = { value: T; params: Record<string, string>; rest: string[] };
|
|
25
|
-
type NormalizedRedirect = Redirect & { status: RedirectStatus };
|
|
29
|
+
/** `query`: what `from` is scoped to, after its `?` (`""`: any query, or none). */
|
|
30
|
+
type NormalizedRedirect = Redirect & { status: RedirectStatus; query: string };
|
|
31
|
+
/** The redirect tries, by the query their sources are scoped to (`""`: path-only). */
|
|
32
|
+
type RedirectTries = Map<string, TrieNode<NormalizedRedirect>>;
|
|
26
33
|
|
|
27
34
|
const routeTries = new WeakMap<object, TrieNode<Route>>();
|
|
28
|
-
const redirectTries = new WeakMap<object,
|
|
35
|
+
const redirectTries = new WeakMap<object, RedirectTries>();
|
|
29
36
|
const STATUSES = new Set<number>([301, 302, 307, 308]);
|
|
30
37
|
|
|
31
38
|
export function matchRoute<T extends Route>(
|
|
@@ -36,21 +43,21 @@ export function matchRoute<T extends Route>(
|
|
|
36
43
|
if (target === null) return { kind: "not-found" };
|
|
37
44
|
|
|
38
45
|
const redirects: unknown[] = Array.isArray(items?.redirects) ? items.redirects : [];
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (redirect
|
|
46
|
+
const tries = cached(redirectTries, redirects, () => compileRedirects(redirects));
|
|
47
|
+
// A source scoped to the request's exact query string beats a path-only one,
|
|
48
|
+
// as Fresh's router tried `pathname + search` before `pathname`.
|
|
49
|
+
const scoped = target.search ? tries.get(target.search.slice(1)) : undefined;
|
|
50
|
+
const pathOnly = tries.get("");
|
|
51
|
+
const redirect =
|
|
52
|
+
(scoped && lookup(scoped, target.segments)) || (pathOnly && lookup(pathOnly, target.segments));
|
|
53
|
+
if (redirect) {
|
|
47
54
|
const location = buildLocation(redirect, target.search);
|
|
48
55
|
return { kind: "redirect", location, status: redirect.value.status };
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
const routes = Array.isArray(items?.routes) ? items.routes : [];
|
|
52
59
|
const trie = cached(routeTries, routes, () =>
|
|
53
|
-
routes.filter((r) => typeof r?.path === "string").map((r) => [r.path, r as Route]),
|
|
60
|
+
buildTrie(routes.filter((r) => typeof r?.path === "string").map((r) => [r.path, r as Route])),
|
|
54
61
|
);
|
|
55
62
|
const found = lookup(trie, target.segments);
|
|
56
63
|
if (found === null) return { kind: "not-found" };
|
|
@@ -70,95 +77,45 @@ function parseTarget(url: string | URL | Request): { segments: string[]; search:
|
|
|
70
77
|
}
|
|
71
78
|
}
|
|
72
79
|
|
|
73
|
-
/**
|
|
74
|
-
function
|
|
75
|
-
const query = path.indexOf("?");
|
|
76
|
-
const hash = path.indexOf("#");
|
|
77
|
-
const end = Math.min(query === -1 ? path.length : query, hash === -1 ? path.length : hash);
|
|
78
|
-
return path
|
|
79
|
-
.slice(0, end)
|
|
80
|
-
.split("/")
|
|
81
|
-
.filter((segment) => segment.length > 0);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function safeDecode(segment: string): string {
|
|
85
|
-
try {
|
|
86
|
-
return decodeURIComponent(segment);
|
|
87
|
-
} catch {
|
|
88
|
-
return segment;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** The trie for an array, built once per array object. */
|
|
93
|
-
function cached<T>(cache: WeakMap<object, TrieNode<T>>, key: object, entries: () => [string, T][]) {
|
|
80
|
+
/** Built once per array object. */
|
|
81
|
+
function cached<V>(cache: WeakMap<object, V>, key: object, build: () => V): V {
|
|
94
82
|
const hit = cache.get(key);
|
|
95
83
|
if (hit) return hit;
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return root;
|
|
84
|
+
const value = build();
|
|
85
|
+
cache.set(key, value);
|
|
86
|
+
return value;
|
|
100
87
|
}
|
|
101
88
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
if (node.splat) return node.splat.value;
|
|
110
|
-
node.splat = { value, names };
|
|
111
|
-
return undefined;
|
|
112
|
-
}
|
|
113
|
-
if (segment.startsWith(":") && segment.length > 1) {
|
|
114
|
-
names.push(segment.slice(1));
|
|
115
|
-
node = node.param ??= { literals: new Map() };
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
const literal = safeDecode(segment);
|
|
119
|
-
const child = node.literals.get(literal) ?? { literals: new Map() };
|
|
120
|
-
node.literals.set(literal, child);
|
|
121
|
-
node = child;
|
|
89
|
+
function compileRedirects(redirects: unknown[]): RedirectTries {
|
|
90
|
+
const tries: RedirectTries = new Map();
|
|
91
|
+
for (const redirect of redirects.map(normalizeRedirect)) {
|
|
92
|
+
if (redirect === null) continue;
|
|
93
|
+
const root = tries.get(redirect.query) ?? { literals: new Map() };
|
|
94
|
+
tries.set(redirect.query, root);
|
|
95
|
+
insert(root, redirect.from, redirect);
|
|
122
96
|
}
|
|
123
|
-
|
|
124
|
-
node.leaf = { value, names };
|
|
125
|
-
return undefined;
|
|
97
|
+
return tries;
|
|
126
98
|
}
|
|
127
99
|
|
|
128
100
|
/**
|
|
129
101
|
* The entries that reach a leaf an earlier entry already holds: two equal
|
|
130
|
-
* paths, or two templates of one shape (`/:slug/p` and `/:id/p`)
|
|
131
|
-
* serves the earlier one; `deco check` reports each pair.
|
|
102
|
+
* paths, or two templates of one shape (`/:slug/p` and `/:id/p`), scoped to the
|
|
103
|
+
* same query. `matchRoute` serves the earlier one; `deco check` reports each pair.
|
|
132
104
|
*/
|
|
133
105
|
export function findRouteConflicts<T extends { path: string }>(entries: readonly T[]) {
|
|
134
|
-
|
|
106
|
+
// A redirect scoped to a query (`/x?map=ft`) never meets `/x` or `/x?map=c`.
|
|
107
|
+
const roots = new Map<string, TrieNode<T>>();
|
|
135
108
|
const conflicts: { entry: T; other: T }[] = [];
|
|
136
109
|
for (const entry of entries) {
|
|
110
|
+
const query = splitRef(entry.path).query;
|
|
111
|
+
const root = roots.get(query) ?? { literals: new Map() };
|
|
112
|
+
roots.set(query, root);
|
|
137
113
|
const other = insert(root, entry.path, entry);
|
|
138
114
|
if (other !== undefined) conflicts.push({ entry, other });
|
|
139
115
|
}
|
|
140
116
|
return conflicts;
|
|
141
117
|
}
|
|
142
118
|
|
|
143
|
-
/** Walks the URL's segments: the literal child first, then the parameter child, then the splat. */
|
|
144
|
-
function lookup<T>(node: TrieNode<T>, segs: string[], i = 0, vals: string[] = []): Hit<T> | null {
|
|
145
|
-
if (i === segs.length) return node.leaf ? hit(node.leaf, vals, []) : null;
|
|
146
|
-
const literal = node.literals.get(segs[i]!);
|
|
147
|
-
let found = literal ? lookup(literal, segs, i + 1, vals) : null;
|
|
148
|
-
// A parameter is one segment and never contains a slash, even an encoded one.
|
|
149
|
-
if (!found && node.param && !segs[i]!.includes("/")) {
|
|
150
|
-
found = lookup(node.param, segs, i + 1, [...vals, segs[i]!]);
|
|
151
|
-
}
|
|
152
|
-
// A splat takes the rest (at least one segment, as there is one here).
|
|
153
|
-
return found ?? (node.splat ? hit(node.splat, vals, segs.slice(i)) : null);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function hit<T>({ value, names }: Leaf<T>, values: string[], rest: string[]): Hit<T> {
|
|
157
|
-
const params: Record<string, string> = Object.fromEntries(names.map((n, i) => [n, values[i]!]));
|
|
158
|
-
if (rest.length > 0) params["*"] = rest.join("/");
|
|
159
|
-
return { value, params, rest };
|
|
160
|
-
}
|
|
161
|
-
|
|
162
119
|
/**
|
|
163
120
|
* Both redirect shapes: the flat built-in `{ from, to, permanent, status?,
|
|
164
121
|
* discardQueryParameters? }` and the site editor's legacy nested
|
|
@@ -174,7 +131,17 @@ function normalizeRedirect(input: unknown): NormalizedRedirect | null {
|
|
|
174
131
|
if (nested) status = flat.type === "permanent" ? 301 : 307;
|
|
175
132
|
else if (STATUSES.has(flat.status as number)) status = flat.status as RedirectStatus;
|
|
176
133
|
const { from, to, discardQueryParameters } = flat;
|
|
177
|
-
|
|
134
|
+
const query = splitRef(from).query;
|
|
135
|
+
// A `to` naming the path `from` matches would match again, forever: `/a` →
|
|
136
|
+
// `/a`, `/a/` → `/a`, `/x` → `/x?utm=1` (a path-only source takes any
|
|
137
|
+
// query), `/p/:id` → `/p/:id`, and `/x?a=1` → `/x` (the query is carried
|
|
138
|
+
// over). Dropped, as Fresh's loader skipped `from === to`. Compared as
|
|
139
|
+
// written (`/café` and `/caf%C3%A9` aren't folded); `https://…` never equals.
|
|
140
|
+
const back = [splitRef(to).query, discardQueryParameters ? "" : query].filter(Boolean).join("&");
|
|
141
|
+
const loops = splitPath(from).join("/") === splitPath(to).join("/") && (!query || back === query);
|
|
142
|
+
if (to[0] === "/" && loops) return null;
|
|
143
|
+
const permanent = status === 301 || status === 308;
|
|
144
|
+
return { from, to, permanent, status, discardQueryParameters, query };
|
|
178
145
|
}
|
|
179
146
|
|
|
180
147
|
/**
|
|
@@ -185,11 +152,8 @@ function normalizeRedirect(input: unknown): NormalizedRedirect | null {
|
|
|
185
152
|
* into `//other.host` (or `/\other.host`).
|
|
186
153
|
*/
|
|
187
154
|
function buildLocation({ value: redirect, params, rest }: Hit<NormalizedRedirect>, search: string) {
|
|
188
|
-
const {
|
|
189
|
-
const
|
|
190
|
-
const queryAt = to.indexOf("?") === -1 || to.indexOf("?") > hashAt ? hashAt : to.indexOf("?");
|
|
191
|
-
const filled = to
|
|
192
|
-
.slice(0, queryAt)
|
|
155
|
+
const { path, query: written, hash } = splitRef(redirect.to);
|
|
156
|
+
const filled = path
|
|
193
157
|
.split("/")
|
|
194
158
|
.map((s) => {
|
|
195
159
|
if (s === "*" && rest.length > 0) return rest.map(encodeURIComponent).join("/");
|
|
@@ -199,6 +163,6 @@ function buildLocation({ value: redirect, params, rest }: Hit<NormalizedRedirect
|
|
|
199
163
|
})
|
|
200
164
|
.join("/");
|
|
201
165
|
const carried = redirect.discardQueryParameters ? "" : search.slice(1);
|
|
202
|
-
const query = [
|
|
203
|
-
return `${filled}${query ? `?${query}` : ""}${
|
|
166
|
+
const query = [written, carried].filter(Boolean).join("&");
|
|
167
|
+
return `${filled}${query ? `?${query}` : ""}${hash}`;
|
|
204
168
|
}
|
package/src/v8/remoteLoader.ts
CHANGED
|
@@ -1,81 +1,98 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `remoteLoader`: hosted releases from
|
|
3
|
-
* content module, or any loader). See /next/hosted-releases-internals
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* `remoteLoader`: hosted releases from `delivery.decocms.com`, over a fallback
|
|
3
|
+
* (the content module, or any loader). See /next/hosted-releases-internals.
|
|
4
|
+
* Drafts aren't a loader's job: the CMS layers a draft's changes over what
|
|
5
|
+
* `load()` returns (see ./draftChanges.ts).
|
|
6
6
|
*
|
|
7
|
-
* - `load()` never touches the network: it returns the
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
7
|
+
* - `load()` never touches the network: it returns the release this process
|
|
8
|
+
* last swapped in, or the fallback's content until then. Nothing persists
|
|
9
|
+
* across restarts: every boot starts from the fallback.
|
|
10
|
+
* - `update()` (the CMS calls it in the background, on first use and then
|
|
11
|
+
* every interval) reads `sites/<site>/latest.json`,
|
|
12
|
+
* `{ revision, schemaHash, publishedAt }`. Whoever is newer wins: when it
|
|
13
|
+
* names a revision other than the one this process last swapped in, its
|
|
14
|
+
* `schemaHash` equals the fallback's, and its `publishedAt` is later than
|
|
15
|
+
* the fallback's `committedAt` (the commit time of the git HEAD
|
|
16
|
+
* `deco content` built it from), it downloads
|
|
17
|
+
* `sites/<site>/revisions/<revision>.json`, `{ revision, schemaHash, blocks }`,
|
|
18
|
+
* and swaps it in whole. Otherwise, and on any error, memory stays as it is.
|
|
19
|
+
* A fallback without a `schemaHash` never swaps; one without a `committedAt`
|
|
20
|
+
* (a custom loader, an older content module, a build outside git) counts as
|
|
21
|
+
* the oldest. Studio writes `publishedAt` on Publish, on "Make current" (a
|
|
22
|
+
* rollback) and on Resync, so a rollback wins over the bundles of earlier
|
|
23
|
+
* commits and a deploy of a later commit wins over the rollback. Commit
|
|
24
|
+
* time, not build time: a slow build of an older commit that finishes after
|
|
25
|
+
* a publish still loses to it.
|
|
26
|
+
* Pointers aren't ordered among themselves, and the fallback's content is
|
|
27
|
+
* never compared: only the two timestamps are.
|
|
28
|
+
* - With `dev: true` (`createCMS({ dev })`), it never swaps, so local files win.
|
|
29
|
+
* The SDK reads no environment variable to decide this: the site passes it
|
|
30
|
+
* (`import.meta.env.DEV`, `process.env.NODE_ENV === "development"`).
|
|
17
31
|
* - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
|
|
18
32
|
* before it's buffered whole (a Worker isolate has 128 MB).
|
|
19
|
-
* - Without `site`
|
|
33
|
+
* - Without `site` it's a plain loader over the fallback.
|
|
20
34
|
*
|
|
21
35
|
* Instances are process-wide singletons, like `createCMS`'s.
|
|
22
36
|
*/
|
|
23
37
|
import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
|
|
24
|
-
import { computeContentRevision } from "./canonical.ts";
|
|
25
38
|
import { isSnapshot, PEEK_RELEASE, peekRelease } from "./content.ts";
|
|
26
|
-
import { clearGlobals, contentIdentity
|
|
39
|
+
import { clearGlobals, contentIdentity } from "./identity.ts";
|
|
27
40
|
import { isPlainObject } from "./json.ts";
|
|
28
41
|
import type { Loader, Snapshot } from "./types.ts";
|
|
29
42
|
|
|
30
|
-
/** The hosted delivery origin:
|
|
43
|
+
/** The hosted delivery origin: release pointers and revisions. */
|
|
31
44
|
const HOSTED_DELIVERY_ORIGIN = "https://delivery.decocms.com";
|
|
45
|
+
/** test-only: replaces the delivery origin in local end-to-end runs. Not documented, not exported. */
|
|
46
|
+
const TEST_DELIVERY_ORIGIN = Symbol.for("decocms.blocks.test.deliveryOrigin");
|
|
32
47
|
|
|
33
48
|
const INSTANCE_PREFIX = "decocms.blocks.remote:";
|
|
34
|
-
const MANIFEST_FORMAT = 1;
|
|
35
49
|
const FETCH_TIMEOUT_MS = 10_000;
|
|
36
50
|
/** The largest release accepted, in bytes of JSON. */
|
|
37
51
|
const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
|
|
52
|
+
// OPEN: a revision is the git commit SHA; only SHA-1 (40 hex) object names are accepted.
|
|
53
|
+
const REVISION = /^[0-9a-f]{40}$/;
|
|
54
|
+
const SCHEMA_HASH = /^[0-9a-f]{64}$/;
|
|
38
55
|
|
|
39
56
|
interface RemoteLoaderOptions {
|
|
40
57
|
site?: string;
|
|
41
|
-
token?: string;
|
|
42
58
|
/** ms between release checks, used when `createCMS` has no `interval` of its own. */
|
|
43
59
|
interval?: number;
|
|
60
|
+
/** Local development: never swap in a release, so local files win. */
|
|
61
|
+
dev?: boolean;
|
|
44
62
|
}
|
|
45
63
|
|
|
46
|
-
|
|
47
|
-
|
|
64
|
+
/** `sites/<site>/latest.json`: the release a site serves. */
|
|
65
|
+
interface Latest {
|
|
48
66
|
revision: string;
|
|
49
|
-
|
|
67
|
+
schemaHash: string;
|
|
68
|
+
publishedAt: string;
|
|
50
69
|
}
|
|
51
70
|
|
|
52
71
|
class RemoteLoader implements Loader {
|
|
53
72
|
readonly #site: string;
|
|
54
|
-
readonly #token: string;
|
|
55
73
|
/** The `interval` this loader was created with; `createCMS` reads it. */
|
|
56
74
|
readonly interval: number | undefined;
|
|
57
75
|
#fallback: Snapshot | Loader;
|
|
58
|
-
#fallbackRevision: string | undefined;
|
|
59
76
|
/** The fallback's content as last loaded, for a fallback that is itself a loader. */
|
|
60
77
|
#fallbackSnapshot: Snapshot | undefined;
|
|
78
|
+
/** The release this process last swapped in; `undefined` serves the fallback. */
|
|
61
79
|
#current: Snapshot | undefined;
|
|
62
|
-
#
|
|
80
|
+
readonly #dev: boolean;
|
|
63
81
|
|
|
64
82
|
constructor(
|
|
65
83
|
fallback: Snapshot | Loader,
|
|
66
|
-
options: { site: string;
|
|
84
|
+
options: { site: string; interval?: number; dev?: boolean },
|
|
67
85
|
) {
|
|
68
86
|
this.#fallback = fallback;
|
|
69
87
|
this.#site = options.site;
|
|
70
|
-
this.#token = options.token;
|
|
71
88
|
this.interval = options.interval;
|
|
89
|
+
this.#dev = options.dev === true;
|
|
72
90
|
}
|
|
73
91
|
|
|
74
92
|
/** A hot reload hands the same instance new fallback content. */
|
|
75
93
|
adopt(fallback: Snapshot | Loader): void {
|
|
76
94
|
if (fallback === this.#fallback) return;
|
|
77
95
|
this.#fallback = fallback;
|
|
78
|
-
this.#fallbackRevision = undefined;
|
|
79
96
|
this.#fallbackSnapshot = undefined;
|
|
80
97
|
}
|
|
81
98
|
|
|
@@ -90,28 +107,20 @@ class RemoteLoader implements Loader {
|
|
|
90
107
|
}
|
|
91
108
|
|
|
92
109
|
async update(): Promise<{ updated: boolean }> {
|
|
93
|
-
if (
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
let next: Snapshot | undefined;
|
|
109
|
-
if (fallbackRevision === undefined || manifest.revision !== fallbackRevision) {
|
|
110
|
-
next = await this.#release(manifest);
|
|
111
|
-
}
|
|
112
|
-
// A slower, earlier check must not undo a newer publish or rollback.
|
|
113
|
-
if (manifest.generation < this.#generation) return { updated: false };
|
|
114
|
-
this.#generation = manifest.generation;
|
|
110
|
+
if (this.#dev) return { updated: false };
|
|
111
|
+
const fallback = this.#fallbackSnapshot ?? (await this.#loadFallback());
|
|
112
|
+
if (fallback.schemaHash === undefined) return { updated: false };
|
|
113
|
+
const site = encodeURIComponent(this.#site);
|
|
114
|
+
const latest = await this.#latest(site);
|
|
115
|
+
// Another schema: keep what this process serves (the fallback, or the last swap).
|
|
116
|
+
if (latest.schemaHash !== fallback.schemaHash) return { updated: false };
|
|
117
|
+
// The bundle is newer: keep what this process serves.
|
|
118
|
+
// OPEN: a process that already swapped a release in keeps it (memory stays as it is).
|
|
119
|
+
if (!isNewer(latest.publishedAt, fallback.committedAt)) return { updated: false };
|
|
120
|
+
if (latest.revision === this.#current?.revision) return { updated: false };
|
|
121
|
+
const blocks = await this.#revision(site, latest);
|
|
122
|
+
const next: Snapshot = { revision: latest.revision, blocks, schemaHash: latest.schemaHash };
|
|
123
|
+
if (fallback.aliases !== undefined) next.aliases = fallback.aliases;
|
|
115
124
|
this.#current = next;
|
|
116
125
|
return { updated: true };
|
|
117
126
|
}
|
|
@@ -119,68 +128,54 @@ class RemoteLoader implements Loader {
|
|
|
119
128
|
async #loadFallback(): Promise<Snapshot> {
|
|
120
129
|
const fallback = this.#fallback;
|
|
121
130
|
const snapshot = isSnapshot(fallback) ? fallback : await (fallback as Loader).load();
|
|
122
|
-
if (fallback === this.#fallback)
|
|
123
|
-
this.#fallbackRevision = snapshot.revision;
|
|
124
|
-
this.#fallbackSnapshot = snapshot;
|
|
125
|
-
}
|
|
131
|
+
if (fallback === this.#fallback) this.#fallbackSnapshot = snapshot;
|
|
126
132
|
return snapshot;
|
|
127
133
|
}
|
|
128
134
|
|
|
129
|
-
async #
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const response = await fetchWithTimeout(
|
|
136
|
-
`${HOSTED_DELIVERY_ORIGIN}/sites/${site}/channels/production.json`,
|
|
137
|
-
this.#auth(),
|
|
138
|
-
);
|
|
139
|
-
if (!response.ok) throw new Error(`channel manifest: HTTP ${response.status}`);
|
|
135
|
+
async #latest(site: string): Promise<Latest> {
|
|
136
|
+
const response = await fetchWithTimeout(`${deliveryOrigin()}/sites/${site}/latest.json`);
|
|
137
|
+
if (!response.ok) {
|
|
138
|
+
await response.body?.cancel();
|
|
139
|
+
throw new Error(`latest.json: HTTP ${response.status}`);
|
|
140
|
+
}
|
|
140
141
|
const body: unknown = await response.json();
|
|
141
|
-
const prefix = `/sites/${site}/revisions/`;
|
|
142
142
|
if (
|
|
143
143
|
!isPlainObject(body) ||
|
|
144
|
-
body.format !== MANIFEST_FORMAT ||
|
|
145
|
-
!Number.isSafeInteger(body.generation) ||
|
|
146
144
|
typeof body.revision !== "string" ||
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
body.
|
|
145
|
+
!REVISION.test(body.revision) ||
|
|
146
|
+
typeof body.schemaHash !== "string" ||
|
|
147
|
+
!SCHEMA_HASH.test(body.schemaHash) ||
|
|
148
|
+
typeof body.publishedAt !== "string" ||
|
|
149
|
+
Number.isNaN(Date.parse(body.publishedAt))
|
|
151
150
|
) {
|
|
152
|
-
throw new Error("
|
|
151
|
+
throw new Error("latest.json: unexpected format");
|
|
153
152
|
}
|
|
154
|
-
return body as unknown as
|
|
153
|
+
return body as unknown as Latest;
|
|
155
154
|
}
|
|
156
155
|
|
|
157
|
-
async #
|
|
156
|
+
async #revision(site: string, latest: Latest): Promise<Record<string, unknown>> {
|
|
157
|
+
const label = `revision ${latest.revision}`;
|
|
158
158
|
const response = await fetchWithTimeout(
|
|
159
|
-
`${
|
|
160
|
-
this.#auth(),
|
|
161
|
-
);
|
|
162
|
-
if (!response.ok) throw new Error(`release ${manifest.revision}: HTTP ${response.status}`);
|
|
163
|
-
const snapshot = await readBoundedJson(
|
|
164
|
-
response,
|
|
165
|
-
`release ${manifest.revision}`,
|
|
166
|
-
MAX_SNAPSHOT_BYTES,
|
|
159
|
+
`${deliveryOrigin()}/sites/${site}/revisions/${latest.revision}.json`,
|
|
167
160
|
);
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
await response.body?.cancel();
|
|
163
|
+
throw new Error(`${label}: HTTP ${response.status}`);
|
|
164
|
+
}
|
|
165
|
+
const body = await readBoundedJson(response, label, MAX_SNAPSHOT_BYTES);
|
|
168
166
|
if (
|
|
169
|
-
!
|
|
170
|
-
|
|
171
|
-
|
|
167
|
+
!isPlainObject(body) ||
|
|
168
|
+
body.revision !== latest.revision ||
|
|
169
|
+
body.schemaHash !== latest.schemaHash ||
|
|
170
|
+
!isPlainObject(body.blocks)
|
|
172
171
|
) {
|
|
173
|
-
throw new Error(
|
|
172
|
+
throw new Error(`${label}: unexpected format, or not the revision latest.json names`);
|
|
174
173
|
}
|
|
175
|
-
return
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
#auth(): Record<string, string> {
|
|
179
|
-
return { authorization: `Bearer ${this.#token}` };
|
|
174
|
+
return body.blocks;
|
|
180
175
|
}
|
|
181
176
|
}
|
|
182
177
|
|
|
183
|
-
/** A loader over the fallback alone: `remoteLoader` without `site
|
|
178
|
+
/** A loader over the fallback alone: `remoteLoader` without `site`. */
|
|
184
179
|
class LocalLoader implements Loader {
|
|
185
180
|
#fallback: Snapshot | Loader;
|
|
186
181
|
|
|
@@ -203,16 +198,14 @@ class LocalLoader implements Loader {
|
|
|
203
198
|
}
|
|
204
199
|
|
|
205
200
|
/**
|
|
206
|
-
* Hosted releases over a fallback. `createCMS` builds it for you
|
|
207
|
-
*
|
|
208
|
-
* environment without the variables), it's a loader over the fallback alone.
|
|
201
|
+
* Hosted releases over a fallback. `createCMS` builds it for you when `site`
|
|
202
|
+
* is set. Without `site`, it's a loader over the fallback alone.
|
|
209
203
|
*/
|
|
210
204
|
export function remoteLoader(fallback: Snapshot | Loader, options: RemoteLoaderOptions): Loader {
|
|
211
|
-
const { site
|
|
212
|
-
const hosted = Boolean(site
|
|
205
|
+
const { site } = options ?? {};
|
|
206
|
+
const hosted = Boolean(site);
|
|
213
207
|
const key = Symbol.for(
|
|
214
|
-
`${INSTANCE_PREFIX}${contentIdentity(fallback)}`
|
|
215
|
-
(hosted ? `|site:${site}|token:${fnv1a(token!)}` : "|local"),
|
|
208
|
+
`${INSTANCE_PREFIX}${contentIdentity(fallback)}${hosted ? `|site:${site}` : "|local"}`,
|
|
216
209
|
);
|
|
217
210
|
const store = globalThis as unknown as Record<symbol, RemoteLoader | LocalLoader | undefined>;
|
|
218
211
|
const existing = store[key];
|
|
@@ -227,7 +220,7 @@ export function remoteLoader(fallback: Snapshot | Loader, options: RemoteLoaderO
|
|
|
227
220
|
return existing;
|
|
228
221
|
}
|
|
229
222
|
const instance = hosted
|
|
230
|
-
? new RemoteLoader(fallback, { site: site!,
|
|
223
|
+
? new RemoteLoader(fallback, { site: site!, interval: options.interval, dev: options.dev })
|
|
231
224
|
: new LocalLoader(fallback);
|
|
232
225
|
store[key] = instance;
|
|
233
226
|
return instance;
|
|
@@ -237,15 +230,23 @@ export function resetRemoteLoaders(): void {
|
|
|
237
230
|
clearGlobals(INSTANCE_PREFIX);
|
|
238
231
|
}
|
|
239
232
|
|
|
240
|
-
|
|
241
|
-
|
|
233
|
+
/**
|
|
234
|
+
* Whether a release published at `publishedAt` is newer than content built
|
|
235
|
+
* from a commit made at `committedAt`. Content without a `committedAt` is the
|
|
236
|
+
* oldest.
|
|
237
|
+
* OPEN: a `committedAt` that doesn't parse as a date counts as missing.
|
|
238
|
+
*/
|
|
239
|
+
function isNewer(publishedAt: string, committedAt: string | undefined): boolean {
|
|
240
|
+
const committed = committedAt === undefined ? Number.NaN : Date.parse(committedAt);
|
|
241
|
+
return Number.isNaN(committed) || Date.parse(publishedAt) > committed;
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
244
|
+
/** No credentials: delivery is public. */
|
|
245
|
+
function fetchWithTimeout(url: string): Promise<Response> {
|
|
246
|
+
return fetch(url, { signal: timeoutSignal(FETCH_TIMEOUT_MS) });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function deliveryOrigin(): string {
|
|
250
|
+
const override = (globalThis as Record<symbol, unknown>)[TEST_DELIVERY_ORIGIN];
|
|
251
|
+
return typeof override === "string" ? override : HOSTED_DELIVERY_ORIGIN;
|
|
251
252
|
}
|