@decocms/blocks 8.0.0 → 8.1.0-next.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/bin/deco.js +13 -0
- package/package.json +39 -3
- package/src/cms/applySectionConventions.ts +26 -2
- package/src/cms/blockSource.ts +37 -0
- package/src/cms/client.ts +5 -0
- package/src/cms/deferredTrigger.ts +58 -0
- package/src/cms/draftSource.ts +171 -57
- package/src/cms/index.ts +32 -3
- package/src/cms/loader.ts +318 -59
- package/src/cms/registry.ts +22 -0
- package/src/cms/renderJson.ts +179 -0
- package/src/cms/resolve.ts +396 -95
- package/src/cms/schema.ts +9 -5
- package/src/cms/sectionLoaders.ts +106 -56
- package/src/hooks/Image.tsx +70 -6
- package/src/hooks/LiveControls.tsx +30 -8
- package/src/hooks/Stats.tsx +134 -0
- package/src/hooks/index.ts +5 -0
- package/src/hooks/useLoadMore.ts +100 -0
- package/src/index.ts +37 -0
- package/src/middleware/observability.ts +173 -16
- package/src/preview/DraftPreviewBadge.tsx +306 -0
- package/src/preview/decoMark.ts +11 -0
- package/src/preview/index.ts +8 -0
- package/src/protocol/assets.ts +124 -0
- package/src/protocol/canonical.ts +7 -0
- package/src/protocol/ciphertext.ts +6 -0
- package/src/protocol/client.ts +170 -0
- package/src/protocol/conformance/cases/assets.ts +81 -0
- package/src/protocol/conformance/cases/guards.ts +314 -0
- package/src/protocol/conformance/cases/reads.ts +168 -0
- package/src/protocol/conformance/cases/types.ts +9 -0
- package/src/protocol/conformance/cases/wire.ts +138 -0
- package/src/protocol/conformance/cases/writes.ts +345 -0
- package/src/protocol/conformance/contentHashFixtures.ts +79 -0
- package/src/protocol/conformance/context.ts +222 -0
- package/src/protocol/conformance/index.ts +140 -0
- package/src/protocol/errors.ts +142 -0
- package/src/protocol/index.ts +39 -0
- package/src/protocol/keys.ts +279 -0
- package/src/protocol/params.ts +67 -0
- package/src/protocol/secrets.ts +231 -0
- package/src/protocol/server/assets.ts +119 -0
- package/src/protocol/server/auth.ts +49 -0
- package/src/protocol/server/bodyCache.ts +84 -0
- package/src/protocol/server/content.ts +175 -0
- package/src/protocol/server/core.ts +112 -0
- package/src/protocol/server/handler.ts +102 -0
- package/src/protocol/server/http.ts +139 -0
- package/src/protocol/server/index.ts +11 -0
- package/src/protocol/server/methods/apply.ts +341 -0
- package/src/protocol/server/methods/read.ts +156 -0
- package/src/protocol/server/rpc.ts +136 -0
- package/src/protocol/storage/fs/hash.ts +21 -0
- package/src/protocol/storage/fs/index.ts +338 -0
- package/src/protocol/storage/fs/lock.ts +68 -0
- package/src/protocol/storage/fs/transaction.ts +183 -0
- package/src/protocol/storage/fs/unsupported.ts +15 -0
- package/src/protocol/storage/memory.ts +238 -0
- package/src/protocol/storage.ts +182 -0
- package/src/protocol/types.ts +172 -0
- package/src/sdk/abTesting.ts +60 -3
- package/src/sdk/analytics.ts +72 -2
- package/src/sdk/cacheHeaders.ts +210 -10
- package/src/sdk/cacheStorage.ts +287 -0
- package/src/sdk/cachedLoader.ts +143 -90
- package/src/sdk/crypto.ts +16 -2
- package/src/sdk/deepOmit.ts +52 -0
- package/src/sdk/encoding.ts +2 -5
- package/src/sdk/experiments.ts +314 -0
- package/src/sdk/fetchCache.ts +269 -0
- package/src/sdk/fetchTimeout.ts +58 -0
- package/src/sdk/flags.ts +38 -8
- package/src/sdk/index.ts +7 -0
- package/src/sdk/instrumentedFetch.ts +25 -2
- package/src/sdk/nonce.ts +46 -0
- package/src/sdk/normalizeUrls.ts +2 -2
- package/src/sdk/observability.ts +8 -1
- package/src/sdk/otel.ts +131 -25
- package/src/sdk/otelHttpLog.ts +4 -4
- package/src/sdk/otelHttpMeter.ts +39 -13
- package/src/sdk/otelHttpTracer.ts +4 -4
- package/src/sdk/redirects.ts +113 -5
- package/src/sdk/responseCache.ts +82 -0
- package/src/sdk/urlUtils.ts +49 -0
- package/src/sdk/useSuggestions.ts +1 -1
- package/src/v8/analytics.ts +50 -0
- package/src/v8/background.ts +107 -0
- package/src/v8/builtins/data.ts +23 -0
- package/src/v8/builtins/index.ts +26 -0
- package/src/v8/builtins/lazy.ts +23 -0
- package/src/v8/builtins/legacy.ts +65 -0
- package/src/v8/builtins/matchers.ts +31 -0
- package/src/v8/builtins/multivariate.ts +25 -0
- package/src/v8/builtins/secret.ts +82 -0
- package/src/v8/canonical.ts +117 -0
- package/src/v8/ciphertext.ts +158 -0
- package/src/v8/cli/builtins.ts +20 -0
- package/src/v8/cli/check/index.ts +774 -0
- package/src/v8/cli/check/messages.ts +168 -0
- package/src/v8/cli/content.ts +287 -0
- package/src/v8/cli/index.ts +17 -0
- package/src/v8/cli/log.ts +18 -0
- package/src/v8/cli/main.ts +12 -0
- package/src/v8/cli/root.ts +66 -0
- package/src/v8/cli/run.ts +236 -0
- package/src/v8/cli/schema/builtinSchemas.ts +236 -0
- package/src/v8/cli/schema/generate.ts +507 -0
- package/src/v8/cli/schema/index.ts +63 -0
- package/src/v8/cli/schema/tsProgram.ts +497 -0
- package/src/v8/cli/schema/typeToSchema.ts +689 -0
- package/src/v8/cli/serve/server.ts +303 -0
- package/src/v8/cli/watch.ts +86 -0
- package/src/v8/client.ts +147 -0
- package/src/v8/cms.ts +237 -0
- package/src/v8/content.ts +195 -0
- package/src/v8/draft.ts +136 -0
- package/src/v8/errors.ts +59 -0
- package/src/v8/fetch.ts +152 -0
- package/src/v8/identity.ts +65 -0
- package/src/v8/index.ts +39 -0
- package/src/v8/json.ts +74 -0
- package/src/v8/matchRoute.ts +204 -0
- package/src/v8/remoteLoader.ts +282 -0
- package/src/v8/resolver.ts +278 -0
- package/src/v8/secrets.ts +17 -0
- package/src/v8/telemetry.ts +533 -0
- package/src/v8/types.ts +240 -0
- package/src/cms/blockSource.test.ts +0 -76
- package/src/cms/client.browserBundle.test.ts +0 -44
- package/src/cms/draftSource.test.ts +0 -343
- package/src/cms/layoutCacheRace.test.ts +0 -181
- package/src/cms/loadDecofileDirectory.test.ts +0 -109
- package/src/cms/loader.test.ts +0 -200
- package/src/cms/registry.test.ts +0 -110
- package/src/cms/resolve.test.ts +0 -980
- package/src/cms/schema.test.ts +0 -356
- package/src/cms/sectionLoaderContext.test.ts +0 -111
- package/src/cms/sectionLoaders.test.ts +0 -533
- package/src/cms/sectionMixins.test.ts +0 -167
- package/src/cms/stickyFlags.test.ts +0 -117
- package/src/flags/flags.test.ts +0 -148
- package/src/hooks/Image.test.ts +0 -100
- package/src/hooks/RenderSection.test.tsx +0 -81
- package/src/matchers/builtins.test.ts +0 -318
- package/src/matchers/override.test.ts +0 -205
- package/src/middleware/hydrationContext.test.ts +0 -61
- package/src/middleware/observability.test.ts +0 -242
- package/src/middleware/validateSection.test.ts +0 -147
- package/src/sdk/abTesting.test.ts +0 -326
- package/src/sdk/cacheHeaders.test.ts +0 -115
- package/src/sdk/cachedLoader.test.ts +0 -122
- package/src/sdk/cachedLoaderModule.test.ts +0 -209
- package/src/sdk/cn.test.ts +0 -34
- package/src/sdk/composite.test.ts +0 -121
- package/src/sdk/cookie.test.ts +0 -108
- package/src/sdk/encoding.test.ts +0 -71
- package/src/sdk/env.test.ts +0 -33
- package/src/sdk/flags.test.ts +0 -91
- package/src/sdk/http.test.ts +0 -71
- package/src/sdk/inflightTimeout.test.ts +0 -35
- package/src/sdk/instrumentedFetch.test.ts +0 -559
- package/src/sdk/invoke.test.ts +0 -115
- package/src/sdk/logger.test.ts +0 -432
- package/src/sdk/otel.test.ts +0 -526
- package/src/sdk/otelAdapters.test.ts +0 -89
- package/src/sdk/otelHttpLog.test.ts +0 -457
- package/src/sdk/otelHttpMeter.test.ts +0 -292
- package/src/sdk/otelHttpTracer.test.ts +0 -474
- package/src/sdk/requestContextStorage.browser.test.ts +0 -29
- package/src/sdk/urlRedaction.test.ts +0 -73
- package/src/sdk/useDevice.test.ts +0 -130
- package/src/sdk/useScript.test.ts +0 -128
- package/src/sdk/useSuggestions.test.ts +0 -230
- package/tsconfig.json +0 -7
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one file-name rule for saved blocks (`@decocms/blocks/protocol/keys`).
|
|
3
|
+
*
|
|
4
|
+
* The site editor, `deco serve` and `deco content` all import this module, so
|
|
5
|
+
* an entry the site editor edits is the entry the app renders:
|
|
6
|
+
*
|
|
7
|
+
* - **Name to file:** `encodeURIComponent(name) + ".json"`, directly in
|
|
8
|
+
* `.deco/blocks` (no subfolders).
|
|
9
|
+
* - **File to name:** decode the file name, without `.json`, exactly once. If
|
|
10
|
+
* decoding fails, the raw name is the entry name.
|
|
11
|
+
* - **Two spellings of one name** (files that decode to the same name after
|
|
12
|
+
* repeated decoding): one wins — the file whose entry has a `path`, then the
|
|
13
|
+
* one that took more decoding, then the lowest file name. The others are
|
|
14
|
+
* reported as diagnostics; a write overwrites the winning spelling and
|
|
15
|
+
* deletes the others in the same commit.
|
|
16
|
+
* - **File content:** `JSON.stringify(entry, null, 2)` plus a newline, UTF-8.
|
|
17
|
+
*
|
|
18
|
+
* Ported from the v7 `blocks-cli/scripts/lib/blocks-dedupe.ts` and
|
|
19
|
+
* `blocks/src/cms/loadDecofileDirectory.ts` (`parseBlockId`), with the mtime
|
|
20
|
+
* tie-break dropped: a fresh clone gives every file the same mtime, and the
|
|
21
|
+
* rule must give the same answer on GitHub, where there is no mtime.
|
|
22
|
+
*
|
|
23
|
+
* Browser-safe: no Node APIs.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** The extension every saved-block file carries. */
|
|
27
|
+
export const BLOCK_FILE_EXTENSION = ".json";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The longest encoded name (without `.json`) the site editor can save, so the
|
|
31
|
+
* file fits a 255-byte file-name limit.
|
|
32
|
+
*/
|
|
33
|
+
export const MAX_ENCODED_NAME_BYTES = 250;
|
|
34
|
+
|
|
35
|
+
/** Windows device names: a file whose stem is one of these can't be created on Windows. */
|
|
36
|
+
const WINDOWS_DEVICE_NAMES = new Set([
|
|
37
|
+
"CON",
|
|
38
|
+
"PRN",
|
|
39
|
+
"AUX",
|
|
40
|
+
"NUL",
|
|
41
|
+
...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
|
|
42
|
+
...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/** Extensions of source modules: a saved block ending in one would shadow a module. */
|
|
46
|
+
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
|
|
47
|
+
|
|
48
|
+
const utf8 = new TextEncoder();
|
|
49
|
+
|
|
50
|
+
/** `encodeURIComponent(name) + ".json"`: the file a saved block named `name` is stored in. */
|
|
51
|
+
export function blockFileName(name: string): string {
|
|
52
|
+
return `${encodeURIComponent(name)}${BLOCK_FILE_EXTENSION}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* True when `file` is a saved-block file name: it ends in `.json`, has a stem,
|
|
57
|
+
* isn't in a folder and isn't a dotfile (hidden files are never entries).
|
|
58
|
+
*/
|
|
59
|
+
export function isBlockFileName(file: string): boolean {
|
|
60
|
+
return (
|
|
61
|
+
file.endsWith(BLOCK_FILE_EXTENSION) &&
|
|
62
|
+
!file.startsWith(".") &&
|
|
63
|
+
file.length > BLOCK_FILE_EXTENSION.length &&
|
|
64
|
+
!file.includes("/") &&
|
|
65
|
+
!file.includes("\\")
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function stem(file: string): string {
|
|
70
|
+
return file.endsWith(BLOCK_FILE_EXTENSION) ? file.slice(0, -BLOCK_FILE_EXTENSION.length) : file;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The entry name stored in `file`: the stem decoded exactly once. A stem that
|
|
75
|
+
* isn't valid percent-encoding (a page literally named `50% off`) is the name
|
|
76
|
+
* as it stands.
|
|
77
|
+
*/
|
|
78
|
+
export function blockNameFromFile(file: string): string {
|
|
79
|
+
const raw = stem(file);
|
|
80
|
+
try {
|
|
81
|
+
return decodeURIComponent(raw);
|
|
82
|
+
} catch {
|
|
83
|
+
return raw;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Decodes `file`'s stem repeatedly until it stops changing, returning the
|
|
89
|
+
* fully decoded name (the spelling-group key) and how many decodes it took.
|
|
90
|
+
*/
|
|
91
|
+
export function fullyDecodeFileName(file: string): { name: string; passes: number } {
|
|
92
|
+
let name = stem(file);
|
|
93
|
+
let passes = 0;
|
|
94
|
+
while (name.includes("%")) {
|
|
95
|
+
let next: string;
|
|
96
|
+
try {
|
|
97
|
+
next = decodeURIComponent(name);
|
|
98
|
+
} catch {
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
if (next === name) break;
|
|
102
|
+
name = next;
|
|
103
|
+
passes++;
|
|
104
|
+
}
|
|
105
|
+
return { name, passes };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The spelling-group key of a saved-block name: every file of the group decodes to it. */
|
|
109
|
+
export function spellingKey(name: string): string {
|
|
110
|
+
return fullyDecodeFileName(blockFileName(name)).name;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** `JSON.stringify(entry, null, 2)` plus a newline: the bytes a saved block is stored as. */
|
|
114
|
+
export function serializeBlock(entry: unknown): string {
|
|
115
|
+
return `${JSON.stringify(entry, null, 2)}\n`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** True when a parsed entry is a page-like entry: it has a non-empty string `path`. */
|
|
119
|
+
export function entryHasPath(entry: unknown): boolean {
|
|
120
|
+
return (
|
|
121
|
+
typeof entry === "object" &&
|
|
122
|
+
entry !== null &&
|
|
123
|
+
!Array.isArray(entry) &&
|
|
124
|
+
typeof (entry as { path?: unknown }).path === "string" &&
|
|
125
|
+
(entry as { path: string }).path.length > 0
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One file that holds (a spelling of) a saved block. */
|
|
130
|
+
export interface SpellingCandidate {
|
|
131
|
+
file: string;
|
|
132
|
+
/** Whether the file's entry has a non-empty `path`. */
|
|
133
|
+
hasPath: boolean;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Orders two spellings of one name: negative when `a` wins. */
|
|
137
|
+
export function compareSpellings(a: SpellingCandidate, b: SpellingCandidate): number {
|
|
138
|
+
if (a.hasPath !== b.hasPath) return a.hasPath ? -1 : 1;
|
|
139
|
+
const passesA = fullyDecodeFileName(a.file).passes;
|
|
140
|
+
const passesB = fullyDecodeFileName(b.file).passes;
|
|
141
|
+
if (passesA !== passesB) return passesB - passesA;
|
|
142
|
+
if (a.file === b.file) return 0;
|
|
143
|
+
return a.file < b.file ? -1 : 1;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The winner of one spelling group and the files it shadows. */
|
|
147
|
+
export interface ResolvedSpelling<T extends SpellingCandidate = SpellingCandidate> {
|
|
148
|
+
/** The entry name: the winning file's stem decoded exactly once. */
|
|
149
|
+
name: string;
|
|
150
|
+
winner: T;
|
|
151
|
+
/** The other spellings, best first. */
|
|
152
|
+
shadowed: T[];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Groups candidate files by spelling key and picks one winner per group.
|
|
157
|
+
* Returns the groups keyed by entry name, in file-name order of the winners.
|
|
158
|
+
*/
|
|
159
|
+
export function resolveSpellings<T extends SpellingCandidate>(
|
|
160
|
+
candidates: readonly T[],
|
|
161
|
+
): Map<string, ResolvedSpelling<T>> {
|
|
162
|
+
const groups = new Map<string, T[]>();
|
|
163
|
+
for (const candidate of candidates) {
|
|
164
|
+
const key = fullyDecodeFileName(candidate.file).name;
|
|
165
|
+
const group = groups.get(key);
|
|
166
|
+
if (group) group.push(candidate);
|
|
167
|
+
else groups.set(key, [candidate]);
|
|
168
|
+
}
|
|
169
|
+
const winners: ResolvedSpelling<T>[] = [];
|
|
170
|
+
for (const group of groups.values()) {
|
|
171
|
+
const [winner, ...shadowed] = [...group].sort(compareSpellings);
|
|
172
|
+
if (!winner) continue;
|
|
173
|
+
winners.push({ name: blockNameFromFile(winner.file), winner, shadowed });
|
|
174
|
+
}
|
|
175
|
+
winners.sort((a, b) =>
|
|
176
|
+
a.winner.file < b.winner.file ? -1 : a.winner.file > b.winner.file ? 1 : 0,
|
|
177
|
+
);
|
|
178
|
+
return new Map(winners.map((w) => [w.name, w]));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Why a name can't be saved. */
|
|
182
|
+
export type NameViolationReason =
|
|
183
|
+
| "empty"
|
|
184
|
+
| "invalid-character"
|
|
185
|
+
| "dot-dot"
|
|
186
|
+
| "leading-dot"
|
|
187
|
+
| "too-long"
|
|
188
|
+
| "case-collision"
|
|
189
|
+
| "device-name"
|
|
190
|
+
| "reserved"
|
|
191
|
+
| "source-extension";
|
|
192
|
+
|
|
193
|
+
export interface NameViolation {
|
|
194
|
+
reason: NameViolationReason;
|
|
195
|
+
message: string;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface NameCheckOptions {
|
|
199
|
+
/**
|
|
200
|
+
* The names of the entries that already exist. A name that isn't one of
|
|
201
|
+
* them is new, and a new name that differs from an existing one only in
|
|
202
|
+
* letter case is refused.
|
|
203
|
+
*/
|
|
204
|
+
existingNames?: Iterable<string>;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Checks whether the site editor may save an entry under `name`. Returns
|
|
209
|
+
* every rule the name breaks (empty when it can be saved).
|
|
210
|
+
*/
|
|
211
|
+
export function checkBlockName(name: string, options: NameCheckOptions = {}): NameViolation[] {
|
|
212
|
+
const violations: NameViolation[] = [];
|
|
213
|
+
if (name.length === 0) {
|
|
214
|
+
return [{ reason: "empty", message: "the name is empty" }];
|
|
215
|
+
}
|
|
216
|
+
if (name.includes("\\") || name.includes("\0")) {
|
|
217
|
+
violations.push({
|
|
218
|
+
reason: "invalid-character",
|
|
219
|
+
message: "the name contains a backslash or a NUL character",
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
if (name.includes("..")) {
|
|
223
|
+
violations.push({ reason: "dot-dot", message: 'the name contains ".."' });
|
|
224
|
+
}
|
|
225
|
+
if (name.startsWith(".")) {
|
|
226
|
+
violations.push({
|
|
227
|
+
reason: "leading-dot",
|
|
228
|
+
message: 'the name starts with ".", which would make its file hidden',
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
if (name === "__proto__") {
|
|
232
|
+
violations.push({ reason: "reserved", message: 'the name "__proto__" is reserved' });
|
|
233
|
+
}
|
|
234
|
+
const encoded = encodeURIComponent(name);
|
|
235
|
+
if (utf8.encode(encoded).byteLength > MAX_ENCODED_NAME_BYTES) {
|
|
236
|
+
violations.push({
|
|
237
|
+
reason: "too-long",
|
|
238
|
+
message: `the encoded name is over ${MAX_ENCODED_NAME_BYTES} bytes`,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
const deviceStem = encoded.split(".")[0]!.toUpperCase();
|
|
242
|
+
if (WINDOWS_DEVICE_NAMES.has(deviceStem)) {
|
|
243
|
+
violations.push({
|
|
244
|
+
reason: "device-name",
|
|
245
|
+
message: `"${deviceStem}" is a Windows device name`,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
const lower = name.toLowerCase();
|
|
249
|
+
const extension = SOURCE_EXTENSIONS.find((ext) => lower.endsWith(ext));
|
|
250
|
+
if (extension) {
|
|
251
|
+
violations.push({
|
|
252
|
+
reason: "source-extension",
|
|
253
|
+
message: `the name ends in "${extension}", which would shadow a source module`,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
if (options.existingNames) {
|
|
257
|
+
let isNew = true;
|
|
258
|
+
let collidesWith: string | undefined;
|
|
259
|
+
for (const existing of options.existingNames) {
|
|
260
|
+
if (existing === name) {
|
|
261
|
+
isNew = false;
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
if (collidesWith === undefined && existing.toLowerCase() === lower) collidesWith = existing;
|
|
265
|
+
}
|
|
266
|
+
if (isNew && collidesWith !== undefined) {
|
|
267
|
+
violations.push({
|
|
268
|
+
reason: "case-collision",
|
|
269
|
+
message: `the name differs from the existing entry "${collidesWith}" only in letter case`,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return violations;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Checks a name a write deletes: anything non-empty can be deleted. */
|
|
277
|
+
export function checkDeletedName(name: string): NameViolation[] {
|
|
278
|
+
return name.length === 0 ? [{ reason: "empty", message: "the name is empty" }] : [];
|
|
279
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parameter validation for the four methods. `params` is always an object;
|
|
3
|
+
* unknown parameters are rejected, so a guard the server doesn't understand
|
|
4
|
+
* never turns into an unguarded write.
|
|
5
|
+
*
|
|
6
|
+
* zod only checks the shape: callers keep using the raw object, because a
|
|
7
|
+
* parsed copy of a record would turn an own `__proto__` key into a prototype.
|
|
8
|
+
*/
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { invalidParams } from "./errors";
|
|
11
|
+
import type { BlocksApplyParams, MethodName, ReadParams } from "./types";
|
|
12
|
+
|
|
13
|
+
const opaque = z.string().min(1).max(1024);
|
|
14
|
+
|
|
15
|
+
const readParams = z.strictObject({
|
|
16
|
+
ref: z.string().min(1).max(255).optional(),
|
|
17
|
+
ifNoneMatch: opaque.optional(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const applyParams = z.strictObject({
|
|
21
|
+
ref: z.string().min(1).max(255).optional(),
|
|
22
|
+
requestKey: z.string().min(1).max(256).optional(),
|
|
23
|
+
ifSchemaMatch: opaque.optional(),
|
|
24
|
+
// Entry shapes are checked later and reported as InvalidBlock, all at once.
|
|
25
|
+
set: z.record(z.string(), z.unknown()).optional(),
|
|
26
|
+
delete: z.array(z.string()).optional(),
|
|
27
|
+
ifMatch: z.record(z.string(), opaque.nullable()).optional(),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const schemas: Record<MethodName, z.ZodType> = {
|
|
31
|
+
describe: z.strictObject({}),
|
|
32
|
+
"schema.get": readParams,
|
|
33
|
+
"blocks.list": readParams,
|
|
34
|
+
"blocks.apply": applyParams,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function describeIssues(error: z.ZodError): string {
|
|
38
|
+
return error.issues
|
|
39
|
+
.map((issue) => {
|
|
40
|
+
const path = issue.path.length ? issue.path.join(".") : "params";
|
|
41
|
+
if (issue.code === "unrecognized_keys") {
|
|
42
|
+
return `unknown parameter${issue.keys.length > 1 ? "s" : ""} ${issue.keys
|
|
43
|
+
.map((k) => `"${k}"`)
|
|
44
|
+
.join(", ")}`;
|
|
45
|
+
}
|
|
46
|
+
return `${path}: ${issue.message}`;
|
|
47
|
+
})
|
|
48
|
+
.join("; ");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Checks `params` for `method` and returns it as given (never a copy).
|
|
53
|
+
* Throws Invalid params (-32602) when it doesn't fit.
|
|
54
|
+
*/
|
|
55
|
+
export function validateParams(method: "describe", params: unknown): Record<string, never>;
|
|
56
|
+
export function validateParams(method: "schema.get" | "blocks.list", params: unknown): ReadParams;
|
|
57
|
+
export function validateParams(method: "blocks.apply", params: unknown): BlocksApplyParams;
|
|
58
|
+
export function validateParams(method: MethodName, params: unknown): unknown;
|
|
59
|
+
export function validateParams(method: MethodName, params: unknown): unknown {
|
|
60
|
+
const value = params === undefined ? {} : params;
|
|
61
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
62
|
+
throw invalidParams("params must be an object");
|
|
63
|
+
}
|
|
64
|
+
const result = schemas[method].safeParse(value);
|
|
65
|
+
if (!result.success) throw invalidParams(describeIssues(result.error));
|
|
66
|
+
return value;
|
|
67
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The secret guard: the content protocol refuses plain text in a `Secret`
|
|
3
|
+
* field, so the site editor and agents can't save a credential by mistake.
|
|
4
|
+
*
|
|
5
|
+
* A `Secret` field must hold a `secret` block with a well-formed
|
|
6
|
+
* `ciphertext` (`{ "__resolveType": "secret", "ciphertext": "v1.…" }`, in the
|
|
7
|
+
* format `./ciphertext` pins: three base64url segments of checked lengths), or a
|
|
8
|
+
* variant block whose every value does. Every `secret` block anywhere in an
|
|
9
|
+
* entry must carry a well-formed `ciphertext`, whatever its field.
|
|
10
|
+
*
|
|
11
|
+
* The schema marks a `Secret` field with `"format": "secret"` — the contract
|
|
12
|
+
* `deco schema` emits for the `Secret` type. Browser-safe.
|
|
13
|
+
*/
|
|
14
|
+
import { parseCiphertext } from "./ciphertext";
|
|
15
|
+
import type { BlockViolation } from "./errors";
|
|
16
|
+
import type { DecoMeta } from "./types";
|
|
17
|
+
|
|
18
|
+
/** The built-in block type that holds an encrypted value. */
|
|
19
|
+
export const SECRET_BLOCK_TYPE = "secret";
|
|
20
|
+
|
|
21
|
+
/** The JSON Schema `format` that marks a `Secret` field. */
|
|
22
|
+
export const SECRET_FORMAT = "secret";
|
|
23
|
+
|
|
24
|
+
const MULTIVARIATE_TYPES = new Set(["multivariate", "website/flags/multivariate.ts"]);
|
|
25
|
+
const LAZY_TYPE = "lazy";
|
|
26
|
+
const MAX_DEPTH = 512;
|
|
27
|
+
|
|
28
|
+
type Json = Record<string, unknown>;
|
|
29
|
+
|
|
30
|
+
const isObject = (value: unknown): value is Json =>
|
|
31
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
|
|
33
|
+
const resolveTypeOf = (value: unknown): string | undefined =>
|
|
34
|
+
isObject(value) && typeof value.__resolveType === "string" ? value.__resolveType : undefined;
|
|
35
|
+
|
|
36
|
+
const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* True when `ciphertext` is a well-formed secret ciphertext:
|
|
40
|
+
* `v1.<wrappedKey>.<iv>.<ciphertext>` with segment lengths an RSA-OAEP and
|
|
41
|
+
* AES-256-GCM encryption produces. Checking it needs no key.
|
|
42
|
+
*/
|
|
43
|
+
export function isWellFormedCiphertext(ciphertext: unknown): ciphertext is string {
|
|
44
|
+
return parseCiphertext(ciphertext) !== null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** True when a JSON Schema node describes a `Secret` field. */
|
|
48
|
+
export function isSecretFieldSchema(schema: unknown): boolean {
|
|
49
|
+
return isObject(schema) && schema.format === SECRET_FORMAT;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** True when `value` is a `secret` block with a well-formed `ciphertext`. */
|
|
53
|
+
export function isSecretBlock(value: unknown): boolean {
|
|
54
|
+
return (
|
|
55
|
+
resolveTypeOf(value) === SECRET_BLOCK_TYPE && isWellFormedCiphertext((value as Json).ciphertext)
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const blockIndexCache = new WeakMap<object, Map<string, unknown>>();
|
|
60
|
+
|
|
61
|
+
/** Every block type in the schema's manifest, by key, to the schema of its arguments. */
|
|
62
|
+
function blockIndex(meta: DecoMeta): Map<string, unknown> {
|
|
63
|
+
const cached = blockIndexCache.get(meta);
|
|
64
|
+
if (cached) return cached;
|
|
65
|
+
const index = new Map<string, unknown>();
|
|
66
|
+
for (const group of Object.values(meta.manifest?.blocks ?? {})) {
|
|
67
|
+
if (!isObject(group)) continue;
|
|
68
|
+
for (const [key, schema] of Object.entries(group)) {
|
|
69
|
+
if (!index.has(key)) index.set(key, schema);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
blockIndexCache.set(meta, index);
|
|
73
|
+
return index;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
class SecretWalker {
|
|
77
|
+
readonly violations: BlockViolation[] = [];
|
|
78
|
+
|
|
79
|
+
constructor(
|
|
80
|
+
private readonly name: string,
|
|
81
|
+
private readonly meta: DecoMeta | null,
|
|
82
|
+
) {}
|
|
83
|
+
|
|
84
|
+
private report(pointer: string, rule: string, message: string) {
|
|
85
|
+
this.violations.push({ name: this.name, pointer, rule, message });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Follows local `$ref`s into `schema.definitions`. */
|
|
89
|
+
private deref(schema: unknown): unknown {
|
|
90
|
+
let current = schema;
|
|
91
|
+
for (let hops = 0; hops < 32 && isObject(current) && typeof current.$ref === "string"; hops++) {
|
|
92
|
+
const match = /^#\/definitions\/(.+)$/.exec(current.$ref);
|
|
93
|
+
if (!match) return current;
|
|
94
|
+
const key = decodeURIComponent(match[1]!).replace(/~1/g, "/").replace(/~0/g, "~");
|
|
95
|
+
current = this.meta?.schema?.definitions?.[key];
|
|
96
|
+
}
|
|
97
|
+
return current;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The schemas of a node, flattened through `allOf`/`anyOf`/`oneOf`. */
|
|
101
|
+
private branches(schema: unknown, depth = 0): Json[] {
|
|
102
|
+
const node = this.deref(schema);
|
|
103
|
+
if (!isObject(node) || depth > 16) return [];
|
|
104
|
+
const out: Json[] = [node];
|
|
105
|
+
for (const combinator of ["allOf", "anyOf", "oneOf"] as const) {
|
|
106
|
+
const list = node[combinator];
|
|
107
|
+
if (Array.isArray(list)) for (const item of list) out.push(...this.branches(item, depth + 1));
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private isSecretField(schema: unknown): boolean {
|
|
113
|
+
return this.branches(schema).some(isSecretFieldSchema);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private propertySchema(schema: unknown, key: string): unknown {
|
|
117
|
+
for (const branch of this.branches(schema)) {
|
|
118
|
+
const properties = branch.properties;
|
|
119
|
+
if (isObject(properties) && key in properties) return properties[key];
|
|
120
|
+
}
|
|
121
|
+
for (const branch of this.branches(schema)) {
|
|
122
|
+
if (isObject(branch.additionalProperties)) return branch.additionalProperties;
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private itemSchema(schema: unknown): unknown {
|
|
128
|
+
for (const branch of this.branches(schema)) {
|
|
129
|
+
if (isObject(branch.items)) return branch.items;
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A value stored in a `Secret` field. */
|
|
135
|
+
checkSecretValue(value: unknown, pointer: string, depth: number) {
|
|
136
|
+
if (depth > MAX_DEPTH)
|
|
137
|
+
return this.report(pointer, "too-deep", "the value is nested too deeply");
|
|
138
|
+
const type = resolveTypeOf(value);
|
|
139
|
+
if (type === SECRET_BLOCK_TYPE) return this.walkBlock(value as Json, pointer, depth);
|
|
140
|
+
if (type !== undefined && MULTIVARIATE_TYPES.has(type)) {
|
|
141
|
+
const variants = (value as Json).variants;
|
|
142
|
+
if (!Array.isArray(variants)) {
|
|
143
|
+
return this.report(
|
|
144
|
+
pointer,
|
|
145
|
+
"secret-field",
|
|
146
|
+
"a Secret field holds a variant block without variants",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
for (const [index, variant] of variants.entries()) {
|
|
150
|
+
const at = `${pointer}/variants/${index}`;
|
|
151
|
+
if (!isObject(variant)) {
|
|
152
|
+
this.report(at, "secret-field", "a variant must be an object");
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (variant.rule !== undefined) this.walkAny(variant.rule, `${at}/rule`, depth + 1);
|
|
156
|
+
let inner = variant.value;
|
|
157
|
+
let innerAt = `${at}/value`;
|
|
158
|
+
if (resolveTypeOf(inner) === LAZY_TYPE) {
|
|
159
|
+
inner = (inner as Json).value;
|
|
160
|
+
innerAt = `${innerAt}/value`;
|
|
161
|
+
}
|
|
162
|
+
this.checkSecretValue(inner, innerAt, depth + 1);
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
this.report(
|
|
167
|
+
pointer,
|
|
168
|
+
"secret-field",
|
|
169
|
+
'a Secret field must hold a "secret" block with a well-formed ciphertext, never plain text',
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** A block value: its own definition (from the manifest) describes its arguments. */
|
|
174
|
+
walkBlock(block: Json, pointer: string, depth: number) {
|
|
175
|
+
const type = block.__resolveType as string;
|
|
176
|
+
if (type === SECRET_BLOCK_TYPE && !isWellFormedCiphertext(block.ciphertext)) {
|
|
177
|
+
this.report(
|
|
178
|
+
pointer,
|
|
179
|
+
"secret-ciphertext",
|
|
180
|
+
'a "secret" block must carry a well-formed "ciphertext" (v1.<wrappedKey>.<iv>.<ciphertext>)',
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const definition = this.meta ? blockIndex(this.meta).get(type) : undefined;
|
|
184
|
+
this.walkObject(block, definition, pointer, depth);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private walkObject(object: Json, schema: unknown, pointer: string, depth: number) {
|
|
188
|
+
for (const [key, child] of Object.entries(object)) {
|
|
189
|
+
if (key === "__resolveType") continue;
|
|
190
|
+
const childSchema = schema === undefined ? undefined : this.propertySchema(schema, key);
|
|
191
|
+
this.walk(child, childSchema, `${pointer}/${escapePointer(key)}`, depth + 1);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
walk(value: unknown, schema: unknown, pointer: string, depth: number) {
|
|
196
|
+
if (depth > MAX_DEPTH)
|
|
197
|
+
return this.report(pointer, "too-deep", "the value is nested too deeply");
|
|
198
|
+
if (schema !== undefined && this.isSecretField(schema)) {
|
|
199
|
+
return this.checkSecretValue(value, pointer, depth);
|
|
200
|
+
}
|
|
201
|
+
if (Array.isArray(value)) {
|
|
202
|
+
const items = schema === undefined ? undefined : this.itemSchema(schema);
|
|
203
|
+
for (const [index, item] of value.entries()) {
|
|
204
|
+
this.walk(item, items, `${pointer}/${index}`, depth + 1);
|
|
205
|
+
}
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (!isObject(value)) return;
|
|
209
|
+
// A nested block is described by its own definition, not the field's union.
|
|
210
|
+
if (resolveTypeOf(value) !== undefined) return this.walkBlock(value, pointer, depth);
|
|
211
|
+
this.walkObject(value, schema, pointer, depth);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
walkAny(value: unknown, pointer: string, depth: number) {
|
|
215
|
+
this.walk(value, undefined, pointer, depth);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Checks one entry against the secret guard. `meta` is the parsed schema;
|
|
221
|
+
* without one, only the `secret` blocks' ciphertexts can be checked.
|
|
222
|
+
*/
|
|
223
|
+
export function checkSecrets(
|
|
224
|
+
name: string,
|
|
225
|
+
entry: unknown,
|
|
226
|
+
meta: DecoMeta | null,
|
|
227
|
+
): BlockViolation[] {
|
|
228
|
+
const walker = new SecretWalker(name, meta);
|
|
229
|
+
walker.walk(entry, undefined, "", 0);
|
|
230
|
+
return walker.violations;
|
|
231
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createAssetHandler(storage)`: uploads beside the content protocol.
|
|
3
|
+
*
|
|
4
|
+
* Uploads aren't one of the four methods. The site editor sends each file to
|
|
5
|
+
* `PUT /assets/<name>` with the same token as the protocol; on that path the
|
|
6
|
+
* file's own image, video, font or PDF content type is accepted instead of
|
|
7
|
+
* JSON, and the name's extension must match it (`banner.html` sent as
|
|
8
|
+
* `image/png` is refused; a name without an extension gets the type's). SVG
|
|
9
|
+
* is refused unless `allowSvg` is set, since it can carry scripts that would
|
|
10
|
+
* run on the site's origin. The storage writes it to its asset folder, never overwriting an
|
|
11
|
+
* existing file (a taken name gets a short suffix), and the response carries
|
|
12
|
+
* the path the site editor stores in the field: always `/assets/<name>`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
type AssetTypeOptions,
|
|
17
|
+
assetNameForType,
|
|
18
|
+
isAcceptedAssetType,
|
|
19
|
+
sanitizeAssetName,
|
|
20
|
+
} from "../assets";
|
|
21
|
+
import {
|
|
22
|
+
type ContentProtocolError,
|
|
23
|
+
ErrorCode,
|
|
24
|
+
forbidden,
|
|
25
|
+
invalidRequest,
|
|
26
|
+
limitExceeded,
|
|
27
|
+
readOnly,
|
|
28
|
+
unauthorized,
|
|
29
|
+
unsupported,
|
|
30
|
+
} from "../errors";
|
|
31
|
+
import type { ContentStorage } from "../storage";
|
|
32
|
+
import { ASSETS_URL_PREFIX } from "../types";
|
|
33
|
+
import { type AuthOptions, assertAuthOptions, authenticate } from "./auth";
|
|
34
|
+
import { BodyEncodingError, BodyTooLargeError, jsonResponse, readBody } from "./http";
|
|
35
|
+
|
|
36
|
+
const STATUS: Record<number, number> = {
|
|
37
|
+
[ErrorCode.Unauthorized]: 401,
|
|
38
|
+
[ErrorCode.Forbidden]: 403,
|
|
39
|
+
[ErrorCode.ReadOnly]: 403,
|
|
40
|
+
[ErrorCode.Unsupported]: 404,
|
|
41
|
+
[ErrorCode.LimitExceeded]: 413,
|
|
42
|
+
[ErrorCode.InvalidRequest]: 400,
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type AssetHandler = (request: Request) => Promise<Response>;
|
|
46
|
+
|
|
47
|
+
export type AssetHandlerOptions = AuthOptions & AssetTypeOptions;
|
|
48
|
+
|
|
49
|
+
export function createAssetHandler(
|
|
50
|
+
storage: ContentStorage,
|
|
51
|
+
options: AssetHandlerOptions = {},
|
|
52
|
+
): AssetHandler {
|
|
53
|
+
assertAuthOptions(options);
|
|
54
|
+
const fail = (request: Request, error: ContentProtocolError, status?: number) =>
|
|
55
|
+
jsonResponse(
|
|
56
|
+
request,
|
|
57
|
+
JSON.stringify({ error: error.toJSON() }),
|
|
58
|
+
status ?? STATUS[error.code] ?? 400,
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
return async (request) => {
|
|
62
|
+
if (request.method !== "PUT") {
|
|
63
|
+
return jsonResponse(
|
|
64
|
+
request,
|
|
65
|
+
JSON.stringify({ error: invalidRequest("use PUT").toJSON() }),
|
|
66
|
+
405,
|
|
67
|
+
{
|
|
68
|
+
allow: "PUT",
|
|
69
|
+
},
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
const auth = await authenticate(request, options);
|
|
73
|
+
if (!auth.ok)
|
|
74
|
+
return fail(request, auth.reason === "unauthorized" ? unauthorized() : forbidden());
|
|
75
|
+
|
|
76
|
+
const description = await storage.describe();
|
|
77
|
+
if (description.readOnly) return fail(request, readOnly());
|
|
78
|
+
if (description.assets === null || !storage.putAsset) {
|
|
79
|
+
return fail(request, unsupported("this endpoint doesn't accept uploads"));
|
|
80
|
+
}
|
|
81
|
+
const contentType = request.headers.get("content-type");
|
|
82
|
+
if (!isAcceptedAssetType(contentType, options)) {
|
|
83
|
+
return fail(request, invalidRequest("uploads must be an image, video, font or PDF"), 415);
|
|
84
|
+
}
|
|
85
|
+
const path = new URL(request.url).pathname;
|
|
86
|
+
const marker = path.lastIndexOf(ASSETS_URL_PREFIX);
|
|
87
|
+
const sanitized =
|
|
88
|
+
marker === -1 ? null : sanitizeAssetName(path.slice(marker + ASSETS_URL_PREFIX.length));
|
|
89
|
+
if (!sanitized) return fail(request, invalidRequest("PUT /assets/<name> needs a file name"));
|
|
90
|
+
const name = assetNameForType(sanitized, contentType, options);
|
|
91
|
+
if (!name) {
|
|
92
|
+
return fail(
|
|
93
|
+
request,
|
|
94
|
+
invalidRequest(`the file name's extension doesn't match its content type (${contentType})`),
|
|
95
|
+
415,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const maxBytes = description.assets.maxBytes;
|
|
100
|
+
let body: Uint8Array;
|
|
101
|
+
try {
|
|
102
|
+
body = await readBody(request, maxBytes);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (error instanceof BodyTooLargeError) {
|
|
105
|
+
return fail(request, limitExceeded(`uploads are limited to ${maxBytes} bytes`));
|
|
106
|
+
}
|
|
107
|
+
if (error instanceof BodyEncodingError)
|
|
108
|
+
return fail(request, invalidRequest(error.message), 415);
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
if (body.byteLength === 0) return fail(request, invalidRequest("the upload is empty"));
|
|
112
|
+
const stored = await storage.putAsset(name, body);
|
|
113
|
+
return jsonResponse(
|
|
114
|
+
request,
|
|
115
|
+
JSON.stringify({ path: `${ASSETS_URL_PREFIX}${stored.name}` }),
|
|
116
|
+
201,
|
|
117
|
+
);
|
|
118
|
+
};
|
|
119
|
+
}
|