@decocms/blocks 8.9.1 → 8.10.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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/protocol/channel.d.ts +98 -0
- package/dist/protocol/channel.d.ts.map +1 -0
- package/dist/protocol/channel.js +58 -0
- package/dist/protocol/channel.js.map +1 -0
- package/dist/protocol/client.js +2 -2
- package/dist/protocol/client.js.map +1 -1
- package/dist/protocol/conformance/blockMetaVectors.json +214 -0
- package/dist/protocol/conformance/contentHashFixtures.d.ts +22 -0
- package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
- package/dist/protocol/conformance/contentHashFixtures.js +55 -0
- package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
- package/dist/protocol/conformance/index.d.ts +2 -1
- package/dist/protocol/conformance/index.d.ts.map +1 -1
- package/dist/protocol/conformance/index.js +2 -1
- package/dist/protocol/conformance/index.js.map +1 -1
- package/dist/protocol/conformance/vectors.d.ts +33 -0
- package/dist/protocol/conformance/vectors.d.ts.map +1 -0
- package/dist/protocol/conformance/vectors.js +3 -0
- package/dist/protocol/conformance/vectors.js.map +1 -0
- package/dist/protocol/index.d.ts +11 -1
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js +11 -1
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/keys.d.ts +1 -1
- package/dist/protocol/keys.js +1 -1
- package/dist/v8/background.d.ts +13 -0
- package/dist/v8/background.d.ts.map +1 -1
- package/dist/v8/background.js +41 -0
- package/dist/v8/background.js.map +1 -1
- package/dist/v8/blockMeta.d.ts +27 -0
- package/dist/v8/blockMeta.d.ts.map +1 -0
- package/dist/v8/blockMeta.js +75 -0
- package/dist/v8/blockMeta.js.map +1 -0
- package/dist/v8/blockStore.d.ts +43 -0
- package/dist/v8/blockStore.d.ts.map +1 -0
- package/dist/v8/blockStore.js +95 -0
- package/dist/v8/blockStore.js.map +1 -0
- package/dist/v8/boundedJson.d.ts +5 -0
- package/dist/v8/boundedJson.d.ts.map +1 -1
- package/dist/v8/boundedJson.js +10 -2
- package/dist/v8/boundedJson.js.map +1 -1
- package/dist/v8/boundedMap.d.ts +19 -0
- package/dist/v8/boundedMap.d.ts.map +1 -0
- package/dist/v8/boundedMap.js +52 -0
- package/dist/v8/boundedMap.js.map +1 -0
- package/dist/v8/builtins/data.d.ts +18 -2
- package/dist/v8/builtins/data.d.ts.map +1 -1
- package/dist/v8/builtins/data.js +17 -1
- package/dist/v8/builtins/data.js.map +1 -1
- package/dist/v8/builtins/index.d.ts.map +1 -1
- package/dist/v8/builtins/index.js +2 -1
- package/dist/v8/builtins/index.js.map +1 -1
- package/dist/v8/builtins/legacy.d.ts +6 -3
- package/dist/v8/builtins/legacy.d.ts.map +1 -1
- package/dist/v8/builtins/legacy.js +6 -3
- package/dist/v8/builtins/legacy.js.map +1 -1
- package/dist/v8/canonical.d.ts +8 -0
- package/dist/v8/canonical.d.ts.map +1 -1
- package/dist/v8/canonical.js +15 -0
- package/dist/v8/canonical.js.map +1 -1
- package/dist/v8/cli/builtins.d.ts.map +1 -1
- package/dist/v8/cli/builtins.js +1 -0
- package/dist/v8/cli/builtins.js.map +1 -1
- package/dist/v8/cli/check/index.d.ts +10 -0
- package/dist/v8/cli/check/index.d.ts.map +1 -1
- package/dist/v8/cli/check/index.js +91 -7
- package/dist/v8/cli/check/index.js.map +1 -1
- package/dist/v8/cli/content.d.ts +12 -25
- package/dist/v8/cli/content.d.ts.map +1 -1
- package/dist/v8/cli/content.js +46 -75
- package/dist/v8/cli/content.js.map +1 -1
- package/dist/v8/cli/index.d.ts +1 -2
- package/dist/v8/cli/index.d.ts.map +1 -1
- package/dist/v8/cli/index.js +1 -2
- package/dist/v8/cli/index.js.map +1 -1
- package/dist/v8/cli/remote/commands.d.ts +71 -0
- package/dist/v8/cli/remote/commands.d.ts.map +1 -0
- package/dist/v8/cli/remote/commands.js +644 -0
- package/dist/v8/cli/remote/commands.js.map +1 -0
- package/dist/v8/cli/remote/diff.d.ts +15 -0
- package/dist/v8/cli/remote/diff.d.ts.map +1 -0
- package/dist/v8/cli/remote/diff.js +102 -0
- package/dist/v8/cli/remote/diff.js.map +1 -0
- package/dist/v8/cli/remote/env.d.ts +35 -0
- package/dist/v8/cli/remote/env.d.ts.map +1 -0
- package/dist/v8/cli/remote/env.js +84 -0
- package/dist/v8/cli/remote/env.js.map +1 -0
- package/dist/v8/cli/remote/http.d.ts +149 -0
- package/dist/v8/cli/remote/http.d.ts.map +1 -0
- package/dist/v8/cli/remote/http.js +381 -0
- package/dist/v8/cli/remote/http.js.map +1 -0
- package/dist/v8/cli/remote/local.d.ts +90 -0
- package/dist/v8/cli/remote/local.d.ts.map +1 -0
- package/dist/v8/cli/remote/local.js +309 -0
- package/dist/v8/cli/remote/local.js.map +1 -0
- package/dist/v8/cli/root.d.ts +29 -0
- package/dist/v8/cli/root.d.ts.map +1 -1
- package/dist/v8/cli/root.js +28 -0
- package/dist/v8/cli/root.js.map +1 -1
- package/dist/v8/cli/run.d.ts +11 -1
- package/dist/v8/cli/run.d.ts.map +1 -1
- package/dist/v8/cli/run.js +281 -124
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
- package/dist/v8/cli/schema/builtinSchemas.js +28 -10
- package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
- package/dist/v8/cli/schema/generate.js +1 -1
- package/dist/v8/cli/schema/generate.js.map +1 -1
- package/dist/v8/client.d.ts +9 -9
- package/dist/v8/client.d.ts.map +1 -1
- package/dist/v8/client.js +138 -50
- package/dist/v8/client.js.map +1 -1
- package/dist/v8/cms.d.ts +2 -1
- package/dist/v8/cms.d.ts.map +1 -1
- package/dist/v8/cms.js +55 -46
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/content.d.ts +39 -78
- package/dist/v8/content.d.ts.map +1 -1
- package/dist/v8/content.js +155 -195
- package/dist/v8/content.js.map +1 -1
- package/dist/v8/contentIndex.d.ts +71 -0
- package/dist/v8/contentIndex.d.ts.map +1 -0
- package/dist/v8/contentIndex.js +137 -0
- package/dist/v8/contentIndex.js.map +1 -0
- package/dist/v8/draft.d.ts +7 -7
- package/dist/v8/draft.d.ts.map +1 -1
- package/dist/v8/draft.js +10 -9
- package/dist/v8/draft.js.map +1 -1
- package/dist/v8/draftChanges.d.ts +59 -32
- package/dist/v8/draftChanges.d.ts.map +1 -1
- package/dist/v8/draftChanges.js +139 -75
- package/dist/v8/draftChanges.js.map +1 -1
- package/dist/v8/errors.d.ts +21 -0
- package/dist/v8/errors.d.ts.map +1 -1
- package/dist/v8/errors.js +22 -0
- package/dist/v8/errors.js.map +1 -1
- package/dist/v8/hostedSource.d.ts +57 -0
- package/dist/v8/hostedSource.d.ts.map +1 -0
- package/dist/v8/hostedSource.js +18 -0
- package/dist/v8/hostedSource.js.map +1 -0
- package/dist/v8/identity.d.ts +1 -1
- package/dist/v8/identity.js +1 -1
- package/dist/v8/index.d.ts +1 -0
- package/dist/v8/index.d.ts.map +1 -1
- package/dist/v8/index.js +1 -0
- package/dist/v8/index.js.map +1 -1
- package/dist/v8/matchRoute.js +7 -4
- package/dist/v8/matchRoute.js.map +1 -1
- package/dist/v8/pin.d.ts +34 -0
- package/dist/v8/pin.d.ts.map +1 -0
- package/dist/v8/pin.js +156 -0
- package/dist/v8/pin.js.map +1 -0
- package/dist/v8/preview/StudioBridge.d.ts +8 -8
- package/dist/v8/preview/StudioBridge.d.ts.map +1 -1
- package/dist/v8/preview/StudioBridge.js +8 -10
- package/dist/v8/preview/StudioBridge.js.map +1 -1
- package/dist/v8/preview/StudioChannel.d.ts +51 -0
- package/dist/v8/preview/StudioChannel.d.ts.map +1 -0
- package/dist/v8/preview/StudioChannel.js +104 -0
- package/dist/v8/preview/StudioChannel.js.map +1 -0
- package/dist/v8/preview/index.d.ts +3 -0
- package/dist/v8/preview/index.d.ts.map +1 -1
- package/dist/v8/preview/index.js +3 -0
- package/dist/v8/preview/index.js.map +1 -1
- package/dist/v8/remoteLoader.d.ts +42 -5
- package/dist/v8/remoteLoader.d.ts.map +1 -1
- package/dist/v8/remoteLoader.js +317 -259
- package/dist/v8/remoteLoader.js.map +1 -1
- package/dist/v8/resolver.d.ts +22 -8
- package/dist/v8/resolver.d.ts.map +1 -1
- package/dist/v8/resolver.js +37 -32
- package/dist/v8/resolver.js.map +1 -1
- package/dist/v8/revisionId.d.ts +11 -0
- package/dist/v8/revisionId.d.ts.map +1 -0
- package/dist/v8/revisionId.js +13 -0
- package/dist/v8/revisionId.js.map +1 -0
- package/dist/v8/settings.d.ts +6 -6
- package/dist/v8/settings.d.ts.map +1 -1
- package/dist/v8/settings.js +8 -7
- package/dist/v8/settings.js.map +1 -1
- package/dist/v8/telemetry.d.ts +4 -2
- package/dist/v8/telemetry.d.ts.map +1 -1
- package/dist/v8/telemetry.js +2 -2
- package/dist/v8/telemetry.js.map +1 -1
- package/dist/v8/types.d.ts +52 -40
- package/dist/v8/types.d.ts.map +1 -1
- package/dist/v8/variants.d.ts +7 -2
- package/dist/v8/variants.d.ts.map +1 -1
- package/dist/v8/variants.js +21 -24
- package/dist/v8/variants.js.map +1 -1
- package/dist/v8/vite/index.d.ts +2 -2
- package/dist/v8/vite/index.js +1 -1
- package/dist/v8/vite/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +2 -0
- package/src/protocol/channel.ts +127 -0
- package/src/protocol/client.ts +2 -2
- package/src/protocol/conformance/blockMetaVectors.json +214 -0
- package/src/protocol/conformance/contentHashFixtures.ts +74 -0
- package/src/protocol/conformance/index.ts +9 -1
- package/src/protocol/conformance/vectors.ts +36 -0
- package/src/protocol/index.ts +32 -0
- package/src/protocol/keys.ts +1 -1
- package/src/v8/background.ts +42 -0
- package/src/v8/blockMeta.ts +100 -0
- package/src/v8/blockStore.ts +124 -0
- package/src/v8/boundedJson.ts +20 -2
- package/src/v8/boundedMap.ts +53 -0
- package/src/v8/builtins/data.ts +26 -2
- package/src/v8/builtins/index.ts +2 -1
- package/src/v8/builtins/legacy.ts +6 -3
- package/src/v8/canonical.ts +15 -0
- package/src/v8/cli/builtins.ts +1 -0
- package/src/v8/cli/check/index.ts +97 -7
- package/src/v8/cli/content.ts +49 -91
- package/src/v8/cli/index.ts +1 -2
- package/src/v8/cli/remote/commands.ts +834 -0
- package/src/v8/cli/remote/diff.ts +100 -0
- package/src/v8/cli/remote/env.ts +107 -0
- package/src/v8/cli/remote/http.ts +484 -0
- package/src/v8/cli/remote/local.ts +343 -0
- package/src/v8/cli/root.ts +40 -0
- package/src/v8/cli/run.ts +333 -136
- package/src/v8/cli/schema/builtinSchemas.ts +29 -10
- package/src/v8/cli/schema/generate.ts +1 -1
- package/src/v8/client.ts +162 -60
- package/src/v8/cms.ts +62 -53
- package/src/v8/content.ts +179 -229
- package/src/v8/contentIndex.ts +183 -0
- package/src/v8/draft.ts +15 -14
- package/src/v8/draftChanges.ts +151 -85
- package/src/v8/errors.ts +37 -0
- package/src/v8/hostedSource.ts +67 -0
- package/src/v8/identity.ts +1 -1
- package/src/v8/index.ts +1 -0
- package/src/v8/matchRoute.ts +7 -4
- package/src/v8/pin.ts +176 -0
- package/src/v8/preview/StudioBridge.ts +8 -10
- package/src/v8/preview/StudioChannel.ts +116 -0
- package/src/v8/preview/index.ts +3 -0
- package/src/v8/remoteLoader.ts +350 -286
- package/src/v8/resolver.ts +56 -33
- package/src/v8/revisionId.ts +14 -0
- package/src/v8/settings.ts +10 -9
- package/src/v8/telemetry.ts +3 -3
- package/src/v8/types.ts +52 -40
- package/src/v8/variants.ts +30 -26
- package/src/v8/vite/index.ts +3 -3
- package/dist/v8/cli/serve/server.d.ts +0 -29
- package/dist/v8/cli/serve/server.d.ts.map +0 -1
- package/dist/v8/cli/serve/server.js +0 -296
- package/dist/v8/cli/serve/server.js.map +0 -1
- package/src/v8/cli/serve/server.ts +0 -348
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A line diff of two blocks as `.deco/blocks` stores them
|
|
3
|
+
* (`serializeBlock`: two-space JSON), for `deco diff`, `deco publish` and
|
|
4
|
+
* push conflicts. No dependency: common prefix and suffix, then an LCS of
|
|
5
|
+
* what's left (a whole replace when that would be too large to compute).
|
|
6
|
+
*/
|
|
7
|
+
import { serializeBlock } from "../../../protocol/keys.ts";
|
|
8
|
+
import { paint } from "../color.ts";
|
|
9
|
+
|
|
10
|
+
/** Above this many cells the middle is shown as removed then added. */
|
|
11
|
+
const MAX_LCS_CELLS = 4_000_000;
|
|
12
|
+
|
|
13
|
+
export type DiffLine = { op: " " | "-" | "+"; text: string };
|
|
14
|
+
|
|
15
|
+
function lines(block: unknown): string[] {
|
|
16
|
+
if (block === undefined) return [];
|
|
17
|
+
return serializeBlock(block).replace(/\n$/, "").split("\n");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function diffLines(a: string[], b: string[]): DiffLine[] {
|
|
21
|
+
let start = 0;
|
|
22
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
23
|
+
let endA = a.length;
|
|
24
|
+
let endB = b.length;
|
|
25
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
26
|
+
endA--;
|
|
27
|
+
endB--;
|
|
28
|
+
}
|
|
29
|
+
const head = a.slice(0, start).map((text) => ({ op: " " as const, text }));
|
|
30
|
+
const tail = a.slice(endA).map((text) => ({ op: " " as const, text }));
|
|
31
|
+
const midA = a.slice(start, endA);
|
|
32
|
+
const midB = b.slice(start, endB);
|
|
33
|
+
const middle: DiffLine[] = [];
|
|
34
|
+
if (midA.length * midB.length > MAX_LCS_CELLS) {
|
|
35
|
+
for (const text of midA) middle.push({ op: "-", text });
|
|
36
|
+
for (const text of midB) middle.push({ op: "+", text });
|
|
37
|
+
} else {
|
|
38
|
+
const n = midA.length;
|
|
39
|
+
const m = midB.length;
|
|
40
|
+
const table: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
41
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
42
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
43
|
+
table[i]![j] =
|
|
44
|
+
midA[i] === midB[j]
|
|
45
|
+
? table[i + 1]![j + 1]! + 1
|
|
46
|
+
: Math.max(table[i + 1]![j]!, table[i]![j + 1]!);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
let i = 0;
|
|
50
|
+
let j = 0;
|
|
51
|
+
while (i < n && j < m) {
|
|
52
|
+
if (midA[i] === midB[j]) {
|
|
53
|
+
middle.push({ op: " ", text: midA[i]! });
|
|
54
|
+
i++;
|
|
55
|
+
j++;
|
|
56
|
+
} else if (table[i + 1]![j]! >= table[i]![j + 1]!) {
|
|
57
|
+
middle.push({ op: "-", text: midA[i++]! });
|
|
58
|
+
} else {
|
|
59
|
+
middle.push({ op: "+", text: midB[j++]! });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
while (i < n) middle.push({ op: "-", text: midA[i++]! });
|
|
63
|
+
while (j < m) middle.push({ op: "+", text: midB[j++]! });
|
|
64
|
+
}
|
|
65
|
+
return [...head, ...middle, ...tail];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The diff of `from` to `to` as text: changed lines with up to `context`
|
|
70
|
+
* unchanged lines around them, `-` for `from`, `+` for `to`. `undefined` is
|
|
71
|
+
* no block (a creation or a deletion). Empty when they are equal.
|
|
72
|
+
*/
|
|
73
|
+
export function formatBlockDiff(
|
|
74
|
+
from: unknown,
|
|
75
|
+
to: unknown,
|
|
76
|
+
options: { color?: boolean; context?: number } = {},
|
|
77
|
+
): string {
|
|
78
|
+
const c = paint(options.color);
|
|
79
|
+
const context = options.context ?? 3;
|
|
80
|
+
const diff = diffLines(lines(from), lines(to));
|
|
81
|
+
const show = new Array<boolean>(diff.length).fill(false);
|
|
82
|
+
diff.forEach((line, index) => {
|
|
83
|
+
if (line.op === " ") return;
|
|
84
|
+
for (let k = Math.max(0, index - context); k <= Math.min(diff.length - 1, index + context); k++)
|
|
85
|
+
show[k] = true;
|
|
86
|
+
});
|
|
87
|
+
const out: string[] = [];
|
|
88
|
+
let skipped = false;
|
|
89
|
+
diff.forEach((line, index) => {
|
|
90
|
+
if (!show[index]) {
|
|
91
|
+
skipped = true;
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (skipped && out.length > 0) out.push(c.dim(" …"));
|
|
95
|
+
skipped = false;
|
|
96
|
+
const text = `${line.op} ${line.text}`;
|
|
97
|
+
out.push(line.op === "-" ? c.red(text) : line.op === "+" ? c.green(text) : text);
|
|
98
|
+
});
|
|
99
|
+
return out.join("\n");
|
|
100
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the remote commands go and who they go as (spec: cli › The deco CLI):
|
|
3
|
+
* `DECO_STUDIO_URL` (default `https://studio.decocms.com`), the bearer token
|
|
4
|
+
* from `DECO_TOKEN` or else from Studio's CLI (`npx decocms auth token
|
|
5
|
+
* --target=<url>`), and the public CDN. The blocks CLI has no login of its
|
|
6
|
+
* own: the session is Studio CLI's.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { CliError, EXIT } from "../root.ts";
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_STUDIO_URL = "https://studio.decocms.com";
|
|
12
|
+
export const DEFAULT_DELIVERY_URL = "https://delivery.decocms.com";
|
|
13
|
+
|
|
14
|
+
export type Env = Record<string, string | undefined>;
|
|
15
|
+
|
|
16
|
+
function withoutTrailingSlash(url: string): string {
|
|
17
|
+
return url.replace(/\/+$/, "");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The Studio API base, `DECO_STUDIO_URL` with no trailing `/`. */
|
|
21
|
+
export function studioUrl(env: Env): string {
|
|
22
|
+
const value = env.DECO_STUDIO_URL?.trim();
|
|
23
|
+
return withoutTrailingSlash(value ? value : DEFAULT_STUDIO_URL);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The public CDN base. `DECO_DELIVERY_URL` is for tests only (it may carry a
|
|
28
|
+
* key prefix path); it isn't documented.
|
|
29
|
+
*/
|
|
30
|
+
export function deliveryUrl(env: Env): string {
|
|
31
|
+
const value = env.DECO_DELIVERY_URL?.trim();
|
|
32
|
+
return withoutTrailingSlash(value ? value : DEFAULT_DELIVERY_URL);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What `deco login` prints, and what a missing session tells you to run. */
|
|
36
|
+
export function loginCommand(env: Env): string {
|
|
37
|
+
return `npx decocms auth login --target=${studioUrl(env)}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Runs a command and resolves with its stdout; rejects when it can't start or
|
|
42
|
+
* exits non-zero. Tests replace it.
|
|
43
|
+
*/
|
|
44
|
+
export type CommandRunner = (file: string, args: string[]) => Promise<string>;
|
|
45
|
+
|
|
46
|
+
export const runCommand: CommandRunner = (file, args) =>
|
|
47
|
+
new Promise((resolve, reject) => {
|
|
48
|
+
const command = commandFor(file, args);
|
|
49
|
+
execFile(
|
|
50
|
+
command.file,
|
|
51
|
+
command.args,
|
|
52
|
+
{
|
|
53
|
+
encoding: "utf8",
|
|
54
|
+
timeout: 120_000,
|
|
55
|
+
maxBuffer: 1024 * 1024,
|
|
56
|
+
windowsHide: true,
|
|
57
|
+
shell: command.shell,
|
|
58
|
+
},
|
|
59
|
+
(error, stdout) => (error ? reject(error) : resolve(stdout)),
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* How to start `file` on this platform. On Windows `npx` is `npx.cmd`, a
|
|
65
|
+
* batch file, which only runs through a shell: there each argument is quoted
|
|
66
|
+
* (MSVC rules), so a `--target` URL reaches it whole.
|
|
67
|
+
*/
|
|
68
|
+
export function commandFor(
|
|
69
|
+
file: string,
|
|
70
|
+
args: string[],
|
|
71
|
+
platform: NodeJS.Platform = process.platform,
|
|
72
|
+
): { file: string; args: string[]; shell: boolean } {
|
|
73
|
+
if (platform !== "win32") return { file, args, shell: false };
|
|
74
|
+
return { file: file === "npx" ? "npx.cmd" : file, args: args.map(quoteWindowsArg), shell: true };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function quoteWindowsArg(arg: string): string {
|
|
78
|
+
const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1");
|
|
79
|
+
return `"${escaped}"`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The bearer token: `DECO_TOKEN` when set, else the trimmed stdout of
|
|
84
|
+
* `npx decocms auth token --target=<DECO_STUDIO_URL>`, which refreshes and
|
|
85
|
+
* saves the Studio CLI session. No token is exit 3.
|
|
86
|
+
*/
|
|
87
|
+
export async function resolveToken(env: Env, run: CommandRunner = runCommand): Promise<string> {
|
|
88
|
+
const fromEnv = env.DECO_TOKEN?.trim();
|
|
89
|
+
if (fromEnv) return fromEnv;
|
|
90
|
+
const target = studioUrl(env);
|
|
91
|
+
let out: string;
|
|
92
|
+
try {
|
|
93
|
+
out = await run("npx", ["decocms", "auth", "token", `--target=${target}`]);
|
|
94
|
+
} catch {
|
|
95
|
+
throw notLoggedIn(env);
|
|
96
|
+
}
|
|
97
|
+
const token = out.trim();
|
|
98
|
+
if (!token) throw notLoggedIn(env);
|
|
99
|
+
return token;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function notLoggedIn(env: Env): CliError {
|
|
103
|
+
return new CliError(`not logged in to ${studioUrl(env)}; run: ${loginCommand(env)}`, {
|
|
104
|
+
exitCode: EXIT.auth,
|
|
105
|
+
code: "not_logged_in",
|
|
106
|
+
});
|
|
107
|
+
}
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two services the remote commands talk to: the Studio content API (the
|
|
3
|
+
* only writer, site-keyed at `/api/cms/<site>`) and the public CDN
|
|
4
|
+
* (`latest.json`, the revision index; `blocks/<hash>.json`; `revisions/<id>/index.json`;
|
|
5
|
+
* draft folders; read with no credential). Every
|
|
6
|
+
* answer is mapped to an exit code here (spec: cli › Exit codes); the CLI
|
|
7
|
+
* never retries.
|
|
8
|
+
*/
|
|
9
|
+
import { ErrorCode } from "../../../protocol/errors.ts";
|
|
10
|
+
import { spellingKey } from "../../../protocol/keys.ts";
|
|
11
|
+
import { draftFileName } from "../../draftChanges.ts";
|
|
12
|
+
import { isRevisionId } from "../../revisionId.ts";
|
|
13
|
+
import { CliError, EXIT, packageVersion } from "../root.ts";
|
|
14
|
+
|
|
15
|
+
export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
16
|
+
|
|
17
|
+
/** Per CDN fetch, as the SDK's (headers and body). */
|
|
18
|
+
const CDN_TIMEOUT_MS = 10_000;
|
|
19
|
+
/** Per Studio request: a publish of a large site takes seconds, never minutes. */
|
|
20
|
+
const STUDIO_TIMEOUT_MS = 120_000;
|
|
21
|
+
|
|
22
|
+
function isTimeout(error: unknown): boolean {
|
|
23
|
+
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function networkError(what: string, error: unknown): CliError {
|
|
27
|
+
const why = isTimeout(error)
|
|
28
|
+
? "timed out"
|
|
29
|
+
: `unreachable (${(error as Error)?.message ?? error})`;
|
|
30
|
+
return new CliError(`${what} ${why}`, { exitCode: EXIT.network, code: "network" });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Studio
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
export interface Draft {
|
|
38
|
+
name: string;
|
|
39
|
+
slug: string;
|
|
40
|
+
createdBy: string;
|
|
41
|
+
via: string;
|
|
42
|
+
createdAt: string;
|
|
43
|
+
etag: string | null;
|
|
44
|
+
pointer: string | null;
|
|
45
|
+
previewUrl: string | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface DraftRow {
|
|
49
|
+
name: string;
|
|
50
|
+
slug: string;
|
|
51
|
+
createdBy: string;
|
|
52
|
+
via: string;
|
|
53
|
+
createdAt: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A Releases row (contract §4.10); an `unreadable` one has no `meta`. */
|
|
57
|
+
export interface ReleaseRow {
|
|
58
|
+
id: string;
|
|
59
|
+
/** `current`: the one latest.json names; `listed`: any other. */
|
|
60
|
+
status: "current" | "listed" | "unreadable";
|
|
61
|
+
meta?: Record<string, unknown>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ReleasesPage {
|
|
65
|
+
live: string | null;
|
|
66
|
+
revisions: ReleaseRow[];
|
|
67
|
+
nextCursor: string | null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type PublishResult =
|
|
71
|
+
| { result: "published"; revision: string; previous: string | null; draftEmptied: boolean }
|
|
72
|
+
| { result: "up-to-date"; revision: string | null; draftEmptied: boolean };
|
|
73
|
+
|
|
74
|
+
/** A JSON-RPC error answer of `blocks.apply`. */
|
|
75
|
+
export class RpcError extends Error {
|
|
76
|
+
constructor(
|
|
77
|
+
readonly code: number,
|
|
78
|
+
message: string,
|
|
79
|
+
readonly data: unknown,
|
|
80
|
+
) {
|
|
81
|
+
super(message);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface StudioOptions {
|
|
86
|
+
base: string;
|
|
87
|
+
site: string;
|
|
88
|
+
token: () => Promise<string>;
|
|
89
|
+
fetch?: Fetch;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface ApplyParams {
|
|
93
|
+
set: Record<string, unknown>;
|
|
94
|
+
delete: string[];
|
|
95
|
+
ifMatch: Record<string, string | null>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface ApplyResult {
|
|
99
|
+
revision: string;
|
|
100
|
+
versions: Record<string, string | null>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The exit code for a non-2xx Studio answer (spec: cli › Exit codes). */
|
|
104
|
+
export function exitCodeForStatus(status: number, code: string | undefined): number {
|
|
105
|
+
if (status === 401 || status === 403) return EXIT.auth;
|
|
106
|
+
if (status === 429) return EXIT.busy;
|
|
107
|
+
if (status === 409 && code === "production_moved") return EXIT.busy;
|
|
108
|
+
if (status === 503 && code === "unavailable") return EXIT.busy;
|
|
109
|
+
if (status >= 500) return EXIT.network;
|
|
110
|
+
return EXIT.failed;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The exit code for a JSON-RPC error of the content protocol. */
|
|
114
|
+
export function exitCodeForRpc(code: number): number {
|
|
115
|
+
if (code === ErrorCode.Conflict) return EXIT.conflict;
|
|
116
|
+
if (code === ErrorCode.Unavailable) return EXIT.busy;
|
|
117
|
+
if (code === ErrorCode.Unauthorized || code === ErrorCode.Forbidden) return EXIT.auth;
|
|
118
|
+
return EXIT.failed;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export class Studio {
|
|
122
|
+
readonly #options: StudioOptions;
|
|
123
|
+
readonly #fetch: Fetch;
|
|
124
|
+
|
|
125
|
+
constructor(options: StudioOptions) {
|
|
126
|
+
this.#options = options;
|
|
127
|
+
this.#fetch = options.fetch ?? fetch;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The site's API root, `<studio>/api/cms/<site>` (Studio finds the site's org). */
|
|
131
|
+
get root(): string {
|
|
132
|
+
const { base, site } = this.#options;
|
|
133
|
+
return `${base}/api/cms/${encodeURIComponent(site)}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async #request(
|
|
137
|
+
method: string,
|
|
138
|
+
path: string,
|
|
139
|
+
body?: { json: unknown } | { bytes: Uint8Array | string },
|
|
140
|
+
): Promise<{ status: number; json: any }> {
|
|
141
|
+
const token = await this.#options.token();
|
|
142
|
+
const headers: Record<string, string> = {
|
|
143
|
+
authorization: `Bearer ${token}`,
|
|
144
|
+
accept: "application/json",
|
|
145
|
+
"user-agent": `deco-cli/${packageVersion()}`,
|
|
146
|
+
};
|
|
147
|
+
let payload: BodyInit | undefined;
|
|
148
|
+
if (body) {
|
|
149
|
+
headers["content-type"] = "application/json";
|
|
150
|
+
payload = "json" in body ? JSON.stringify(body.json) : (body.bytes as BodyInit);
|
|
151
|
+
}
|
|
152
|
+
let response: Response;
|
|
153
|
+
let text: string;
|
|
154
|
+
try {
|
|
155
|
+
response = await this.#fetch(`${this.root}${path}`, {
|
|
156
|
+
method,
|
|
157
|
+
headers,
|
|
158
|
+
body: payload,
|
|
159
|
+
signal: AbortSignal.timeout(STUDIO_TIMEOUT_MS),
|
|
160
|
+
});
|
|
161
|
+
text = await response.text();
|
|
162
|
+
} catch (error) {
|
|
163
|
+
throw networkError(`Studio (${this.#options.base})`, error);
|
|
164
|
+
}
|
|
165
|
+
let json: any;
|
|
166
|
+
try {
|
|
167
|
+
json = text === "" ? null : JSON.parse(text);
|
|
168
|
+
} catch {
|
|
169
|
+
json = null;
|
|
170
|
+
}
|
|
171
|
+
if (response.status < 200 || response.status > 299) {
|
|
172
|
+
const code = typeof json?.code === "string" ? json.code : undefined;
|
|
173
|
+
const exitCode = exitCodeForStatus(response.status, code);
|
|
174
|
+
const message =
|
|
175
|
+
typeof json?.error === "string"
|
|
176
|
+
? json.error
|
|
177
|
+
: typeof json?.error?.message === "string"
|
|
178
|
+
? json.error.message
|
|
179
|
+
: `HTTP ${response.status}`;
|
|
180
|
+
const hint =
|
|
181
|
+
exitCode === EXIT.auth && response.status === 401
|
|
182
|
+
? " (check DECO_TOKEN, or log in again with npx decocms auth login)"
|
|
183
|
+
: "";
|
|
184
|
+
throw new CliError(`Studio answered ${response.status}: ${message}${hint}`, {
|
|
185
|
+
exitCode,
|
|
186
|
+
code: code ?? (exitCode === EXIT.auth ? "unauthorized" : `http_${response.status}`),
|
|
187
|
+
details: { status: response.status },
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return { status: response.status, json };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
static draftPath(name: string): string {
|
|
194
|
+
return `/drafts/${encodeURIComponent(name)}`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async listDrafts(): Promise<DraftRow[]> {
|
|
198
|
+
return (await this.#request("GET", "/drafts")).json.drafts ?? [];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async ensureDraft(name: string): Promise<Draft & { created: boolean }> {
|
|
202
|
+
return (await this.#request("POST", "/drafts", { json: { name } })).json;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async resolveDraft(name: string): Promise<Draft> {
|
|
206
|
+
return (await this.#request("GET", Studio.draftPath(name))).json;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async discardDraft(name: string): Promise<void> {
|
|
210
|
+
await this.#request("DELETE", Studio.draftPath(name));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* One `blocks.apply` on the draft. `body` is the serialized JSON-RPC
|
|
215
|
+
* request (push measures it against the 8 MiB cap). A JSON-RPC error is
|
|
216
|
+
* thrown as `RpcError`.
|
|
217
|
+
*/
|
|
218
|
+
async apply(name: string, body: string): Promise<ApplyResult> {
|
|
219
|
+
const { json } = await this.#request("POST", `${Studio.draftPath(name)}/rpc`, { bytes: body });
|
|
220
|
+
if (json?.error) {
|
|
221
|
+
throw new RpcError(
|
|
222
|
+
Number(json.error.code),
|
|
223
|
+
String(json.error.message ?? ""),
|
|
224
|
+
json.error.data,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
if (!json || typeof json.result !== "object" || json.result === null) {
|
|
228
|
+
throw new CliError("Studio answered blocks.apply with no result", { code: "bad_answer" });
|
|
229
|
+
}
|
|
230
|
+
return json.result;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async publish(name: string, message: string | undefined): Promise<PublishResult> {
|
|
234
|
+
const body = message === undefined ? {} : { message };
|
|
235
|
+
return (await this.#request("POST", `${Studio.draftPath(name)}/publish`, { json: body })).json;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async releases(cursor: string | undefined): Promise<ReleasesPage> {
|
|
239
|
+
const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
|
|
240
|
+
return (await this.#request("GET", `/releases${query}`)).json;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
async pushSchema(text: string): Promise<{ etag: string; blocksMajor: number | null }> {
|
|
244
|
+
return (await this.#request("PUT", "/schema", { bytes: text })).json;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** One `blocks.apply` request, serialized as `deco push` sends it. */
|
|
249
|
+
export function applyRequestBody(params: ApplyParams): string {
|
|
250
|
+
return JSON.stringify({ jsonrpc: "2.0", id: 1, method: "blocks.apply", params });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
// The CDN
|
|
255
|
+
// ---------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
/** A revision index as the CDN serves it: name → the body's hash (and the inline `CMS` body). */
|
|
258
|
+
export interface RemoteIndex {
|
|
259
|
+
revision: string;
|
|
260
|
+
sequence: number;
|
|
261
|
+
blocks: Record<string, { version: string; data?: Record<string, unknown> }>;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** A block's hash: `blockVersion`, 22 base64url characters. */
|
|
265
|
+
const HASH = /^[A-Za-z0-9_-]{22}$/;
|
|
266
|
+
/** CDN reads in flight at once, for a pull of every block (contract A-31). */
|
|
267
|
+
const PARALLELISM = 16;
|
|
268
|
+
|
|
269
|
+
export interface DraftBody {
|
|
270
|
+
set: Record<string, unknown>;
|
|
271
|
+
delete: string[];
|
|
272
|
+
editors: Record<string, { userId: string; at: number }>;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
276
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Reads the public bucket: no credentials, never a cached answer. */
|
|
280
|
+
export class Delivery {
|
|
281
|
+
readonly #base: string;
|
|
282
|
+
readonly #site: string;
|
|
283
|
+
readonly #fetch: Fetch;
|
|
284
|
+
|
|
285
|
+
constructor(base: string, site: string, fetchImpl: Fetch = fetch) {
|
|
286
|
+
this.#base = base;
|
|
287
|
+
this.#site = site;
|
|
288
|
+
this.#fetch = fetchImpl;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
#url(key: string): string {
|
|
292
|
+
return `${this.#base}/sites/${encodeURIComponent(this.#site)}/${key}`;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** `null` on 404. */
|
|
296
|
+
async #getJson(url: string, what: string): Promise<unknown | null> {
|
|
297
|
+
let response: Response;
|
|
298
|
+
let text: string;
|
|
299
|
+
try {
|
|
300
|
+
response = await this.#fetch(url, {
|
|
301
|
+
cache: "no-store",
|
|
302
|
+
credentials: "omit",
|
|
303
|
+
headers: { accept: "application/json" },
|
|
304
|
+
signal: AbortSignal.timeout(CDN_TIMEOUT_MS),
|
|
305
|
+
});
|
|
306
|
+
if (response.status === 404) {
|
|
307
|
+
await response.body?.cancel();
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
text = await response.text();
|
|
311
|
+
} catch (error) {
|
|
312
|
+
throw networkError(`the CDN (${what})`, error);
|
|
313
|
+
}
|
|
314
|
+
if (response.status !== 200) {
|
|
315
|
+
throw new CliError(`the CDN answered ${response.status} for ${what}`, {
|
|
316
|
+
exitCode: response.status >= 500 ? EXIT.network : EXIT.failed,
|
|
317
|
+
code: response.status >= 500 ? "network" : `http_${response.status}`,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
return JSON.parse(text);
|
|
322
|
+
} catch {
|
|
323
|
+
throw new CliError(`the CDN's ${what} isn't JSON`, { code: "bad_answer" });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** A revision index (`latest.json` or `revisions/<id>/index.json`); `null` on 404. */
|
|
328
|
+
async #index(key: string, what: string): Promise<RemoteIndex | null> {
|
|
329
|
+
const body = await this.#getJson(this.#url(key), what);
|
|
330
|
+
if (body === null) return null;
|
|
331
|
+
const bad = (why: string) => new CliError(`the CDN's ${what} ${why}`, { code: "bad_answer" });
|
|
332
|
+
if (!isObject(body) || !isRevisionId(body.revision)) throw bad("names no valid revision");
|
|
333
|
+
const sequence = body.sequence;
|
|
334
|
+
if (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence < 1) {
|
|
335
|
+
throw bad("has no valid sequence");
|
|
336
|
+
}
|
|
337
|
+
if (!isObject(body.blocks)) throw bad("has no blocks");
|
|
338
|
+
const blocks: RemoteIndex["blocks"] = Object.create(null);
|
|
339
|
+
for (const [name, entry] of Object.entries(body.blocks)) {
|
|
340
|
+
if (!isObject(entry) || typeof entry.version !== "string" || !HASH.test(entry.version)) {
|
|
341
|
+
throw bad(`has no valid version for "${name}"`);
|
|
342
|
+
}
|
|
343
|
+
blocks[name] = isObject(entry.data)
|
|
344
|
+
? { version: entry.version, data: entry.data }
|
|
345
|
+
: { version: entry.version };
|
|
346
|
+
}
|
|
347
|
+
return { revision: body.revision, sequence, blocks };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The live index (`latest.json`), or `null` before the site's first publish. */
|
|
351
|
+
latestIndex(): Promise<RemoteIndex | null> {
|
|
352
|
+
return this.#index("latest.json", "latest.json");
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** The live revision id, or `null` before the site's first publish. */
|
|
356
|
+
async latest(): Promise<string | null> {
|
|
357
|
+
return (await this.latestIndex())?.revision ?? null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* The bodies of `names` (every name by default) in an index: inline ones
|
|
362
|
+
* from the index, the others by hash, at most 16 fetches at a time.
|
|
363
|
+
*/
|
|
364
|
+
async bodies(index: RemoteIndex, names?: readonly string[]): Promise<Record<string, unknown>> {
|
|
365
|
+
const wanted = (names ?? Object.keys(index.blocks)).filter((name) =>
|
|
366
|
+
Object.hasOwn(index.blocks, name),
|
|
367
|
+
);
|
|
368
|
+
const blocks: Record<string, unknown> = Object.create(null);
|
|
369
|
+
await inParallel(wanted, PARALLELISM, async (name) => {
|
|
370
|
+
const entry = index.blocks[name]!;
|
|
371
|
+
if (entry.data !== undefined) {
|
|
372
|
+
blocks[name] = entry.data;
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const what = `block "${name}" (${entry.version})`;
|
|
376
|
+
const body = await this.#getJson(this.#url(`blocks/${entry.version}.json`), what);
|
|
377
|
+
if (body === null) {
|
|
378
|
+
throw new CliError(`the CDN doesn't have ${what}, which revision ${index.revision} names`, {
|
|
379
|
+
code: "block_not_found",
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
blocks[name] = body;
|
|
383
|
+
});
|
|
384
|
+
// In the index's order, not the order the fetches finished in.
|
|
385
|
+
const ordered: Record<string, unknown> = Object.create(null);
|
|
386
|
+
for (const name of wanted) ordered[name] = blocks[name];
|
|
387
|
+
return ordered;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** A revision's blocks; `null` when there's no such revision. */
|
|
391
|
+
async revision(id: string): Promise<Record<string, unknown> | null> {
|
|
392
|
+
const index = await this.#index(`revisions/${id}/index.json`, `revision ${id}`);
|
|
393
|
+
return index === null ? null : this.bodies(index);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Production now: the live revision and its blocks (empty before a first publish). */
|
|
397
|
+
async production(): Promise<{ revision: string | null; blocks: Record<string, unknown> }> {
|
|
398
|
+
const index = await this.latestIndex();
|
|
399
|
+
if (index === null) return { revision: null, blocks: Object.create(null) };
|
|
400
|
+
return { revision: index.revision, blocks: await this.bodies(index) };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* A draft, by slug (the empty draft when Studio has none, `etag` null): its
|
|
405
|
+
* folder's `index.json`, then every file it names. A missing file or a
|
|
406
|
+
* `published` marker is no change; a `set` file's body replaces the name,
|
|
407
|
+
* a `delete` file deletes it.
|
|
408
|
+
*/
|
|
409
|
+
async draft(slug: string, etag: string | null): Promise<DraftBody> {
|
|
410
|
+
const empty = (): DraftBody => ({ set: Object.create(null), delete: [], editors: {} });
|
|
411
|
+
if (etag === null) return empty();
|
|
412
|
+
const folder = `drafts/${slug}/`;
|
|
413
|
+
const index = await this.#getJson(this.#url(`${folder}index.json`), "the draft's index");
|
|
414
|
+
if (index === null) return empty();
|
|
415
|
+
if (!isObject(index) || !Array.isArray(index.names)) {
|
|
416
|
+
throw new CliError("the CDN's draft index isn't {names}", { code: "bad_answer" });
|
|
417
|
+
}
|
|
418
|
+
const names = [...new Set(index.names.filter((n): n is string => typeof n === "string"))];
|
|
419
|
+
const files: Record<string, unknown> = Object.create(null);
|
|
420
|
+
await inParallel(names, PARALLELISM, async (name) => {
|
|
421
|
+
const url = this.#url(`${folder}${encodeURIComponent(draftFileName(name))}`);
|
|
422
|
+
files[name] = await this.#getJson(url, `the draft's file for "${name}"`);
|
|
423
|
+
});
|
|
424
|
+
const draft = empty();
|
|
425
|
+
for (const name of names) {
|
|
426
|
+
const file = files[name];
|
|
427
|
+
if (file === null || file === undefined) continue;
|
|
428
|
+
const bad = () =>
|
|
429
|
+
new CliError(`the CDN's draft file for "${name}" isn't a set, delete or published`, {
|
|
430
|
+
code: "bad_answer",
|
|
431
|
+
});
|
|
432
|
+
if (!isObject(file)) throw bad();
|
|
433
|
+
if (file.operation === "published") continue;
|
|
434
|
+
if (file.operation === "set") {
|
|
435
|
+
if (!isObject(file.data)) throw bad();
|
|
436
|
+
draft.set[name] = file.data;
|
|
437
|
+
} else if (file.operation === "delete") {
|
|
438
|
+
draft.delete.push(name);
|
|
439
|
+
} else throw bad();
|
|
440
|
+
if (typeof file.user === "string" && typeof file.at === "number") {
|
|
441
|
+
draft.editors[name] = { userId: file.user, at: file.at };
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return draft;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Runs `task` over `items`, at most `limit` at a time; rejects with the first failure. */
|
|
449
|
+
async function inParallel<T>(
|
|
450
|
+
items: readonly T[],
|
|
451
|
+
limit: number,
|
|
452
|
+
task: (item: T) => Promise<void>,
|
|
453
|
+
): Promise<void> {
|
|
454
|
+
let next = 0;
|
|
455
|
+
const worker = async () => {
|
|
456
|
+
while (next < items.length) await task(items[next++]!);
|
|
457
|
+
};
|
|
458
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** A copy with no prototype, so a block named `__proto__` is just a name. */
|
|
462
|
+
export function toMap(record: Record<string, unknown>): Record<string, unknown> {
|
|
463
|
+
const map: Record<string, unknown> = Object.create(null);
|
|
464
|
+
for (const [name, value] of Object.entries(record)) map[name] = value;
|
|
465
|
+
return map;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Production with a draft applied, as Studio applies it (`applyDraftToBlocks`):
|
|
470
|
+
* a name the draft sets replaces every spelling of it, a name it deletes hides
|
|
471
|
+
* every spelling (`spellingKey`), and its blocks are taken whole.
|
|
472
|
+
*/
|
|
473
|
+
export function layer(
|
|
474
|
+
production: Record<string, unknown>,
|
|
475
|
+
draft: { set: Record<string, unknown>; delete: string[] },
|
|
476
|
+
): Record<string, unknown> {
|
|
477
|
+
const touched = new Set([...Object.keys(draft.set), ...draft.delete].map(spellingKey));
|
|
478
|
+
const blocks: Record<string, unknown> = Object.create(null);
|
|
479
|
+
for (const [name, block] of Object.entries(production)) {
|
|
480
|
+
if (!touched.has(spellingKey(name))) blocks[name] = block;
|
|
481
|
+
}
|
|
482
|
+
for (const [name, block] of Object.entries(draft.set)) blocks[name] = block;
|
|
483
|
+
return blocks;
|
|
484
|
+
}
|