@procedures/media 0.0.0-stage → 0.68.17

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.
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Media documents: a small JSON record first, and its files after it.
3
+ *
4
+ * A media document has two parts. `$data` is the record of the app. `$media` is the table of its files: each key is the
5
+ * id of a file, the SHA-256 of its bytes as 64 lowercase hex characters. Each entry tells where the file is in `$data`
6
+ * (a JSON Pointer, RFC 6901), its media type, its size and its state. At that pointer, `$data` holds the id.
7
+ *
8
+ * The states are these:
9
+ *
10
+ * - `pending`: the store has no bytes of the file.
11
+ * - `partial`: the store has `received` bytes, more than 0 and fewer than `size`.
12
+ * - `complete`: the store has all the bytes.
13
+ * - `embedded`: the bytes are in the entry, as the canonical base64 text `base64`.
14
+ * - `linked`: the bytes are at the URL `url` (http or https).
15
+ *
16
+ * Thus a reader can show the record before its files are complete. Because the id is the hash of the bytes, an upload
17
+ * is idempotent, and a store can examine each file that it gets.
18
+ */
19
+
20
+ import { ok, err, type Result } from "@mark1russell7/optional";
21
+ import { assertJson, formatPointer, lookup, parsePointer, type JsonValue } from "@procedures/json";
22
+ import { base64Size, decodeBase64 } from "./base64.js";
23
+ import { urlProtocol } from "./web.js";
24
+
25
+ /** The states of a file, in the order of an upload. */
26
+ export const MEDIA_STATES = ["pending", "partial", "complete", "embedded", "linked"] as const;
27
+
28
+ /** The state of a file. */
29
+ export type MediaState = (typeof MEDIA_STATES)[number];
30
+
31
+ /** The fields that each entry has. */
32
+ export interface MediaEntryBase {
33
+ /** The JSON Pointer of the file in `$data`. */
34
+ readonly path: string;
35
+ /** The media type (RFC 6838), in lowercase, for example `image/jpeg`. */
36
+ readonly type: string;
37
+ /** The number of bytes of the file. */
38
+ readonly size: number;
39
+ /** The SHA-256 of the bytes, as 64 lowercase hex characters. It is equal to the key of the entry. */
40
+ readonly sha256: string;
41
+ }
42
+
43
+ /** An entry of the media table. The state selects the other fields. */
44
+ export type MediaEntry =
45
+ | (MediaEntryBase & { readonly state: "pending" })
46
+ | (MediaEntryBase & { readonly state: "partial"; readonly received: number })
47
+ | (MediaEntryBase & { readonly state: "complete" })
48
+ | (MediaEntryBase & { readonly state: "embedded"; readonly base64: string })
49
+ | (MediaEntryBase & { readonly state: "linked"; readonly url: string });
50
+
51
+ /** The media table: each file by its id. */
52
+ export type MediaTable = Readonly<Record<string, MediaEntry>>;
53
+
54
+ /** A media document: the record of the app in `$data`, and the table of its files in `$media`. */
55
+ export interface MediaDocument<D extends JsonValue = JsonValue> {
56
+ readonly $media: MediaTable;
57
+ readonly $data: D;
58
+ }
59
+
60
+ /** The kind of a problem in a media document. */
61
+ export type MediaIssueCode =
62
+ | "NOT_OBJECT"
63
+ | "MISSING_FIELD"
64
+ | "UNKNOWN_FIELD"
65
+ | "NOT_JSON"
66
+ | "BAD_ID"
67
+ | "ID_MISMATCH"
68
+ | "BAD_TYPE"
69
+ | "BAD_SIZE"
70
+ | "BAD_STATE"
71
+ | "BAD_PATH"
72
+ | "PATH_NOT_FOUND"
73
+ | "PATH_NOT_ID"
74
+ | "PATH_SHARED"
75
+ | "BAD_RECEIVED"
76
+ | "BAD_BASE64"
77
+ | "SIZE_MISMATCH"
78
+ | "BAD_URL";
79
+
80
+ /** A problem in a media document. `at` is the JSON Pointer of the bad value in the document. */
81
+ export interface MediaIssue {
82
+ readonly at: string;
83
+ readonly code: MediaIssueCode;
84
+ readonly message: string;
85
+ }
86
+
87
+ const ID = /^[0-9a-f]{64}$/;
88
+
89
+ /** This function tells if a text is a media id: 64 lowercase hex characters. */
90
+ export function isMediaId(text: unknown): text is string {
91
+ return typeof text === "string" && ID.test(text);
92
+ }
93
+
94
+ // RFC 6838, section 4.2: a name has 1 to 127 characters, and starts with a letter or a digit.
95
+ const NAME = "[a-z0-9][a-z0-9!#$&^_.+-]{0,126}";
96
+ const TOKEN = "[a-z0-9!#$%&'*+.^_`|~-]+";
97
+ const QUOTED = '"(?:[^"\\\\\\r\\n]|\\\\.)*"';
98
+ const MEDIA_TYPE = new RegExp(`^${NAME}/${NAME}(?:; ?${TOKEN}=(?:[A-Za-z0-9!#$%&'*+.^_\`|~-]+|${QUOTED}))*$`);
99
+
100
+ /** This function tells if a text is a media type in lowercase, with optional parameters (`text/plain; charset=utf-8`). */
101
+ export function isMediaType(text: unknown): text is string {
102
+ return typeof text === "string" && MEDIA_TYPE.test(text);
103
+ }
104
+
105
+ /** This function tells if a text is an absolute http or https URL. */
106
+ export function isMediaUrl(text: unknown): text is string {
107
+ if (typeof text !== "string") return false;
108
+ try {
109
+ const protocol = urlProtocol(text);
110
+ return protocol === "https:" || protocol === "http:";
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /** The fields of each state, after the base fields. */
117
+ const STATE_FIELDS: Readonly<Record<MediaState, readonly string[]>> = {
118
+ pending: [],
119
+ partial: ["received"],
120
+ complete: [],
121
+ embedded: ["base64"],
122
+ linked: ["url"],
123
+ };
124
+
125
+ const BASE_FIELDS = ["path", "type", "size", "sha256", "state"] as const;
126
+
127
+ function isObject(value: unknown): value is Record<string, unknown> {
128
+ return value !== null && typeof value === "object" && !Array.isArray(value);
129
+ }
130
+
131
+ function isState(value: unknown): value is MediaState {
132
+ return typeof value === "string" && (MEDIA_STATES as readonly string[]).includes(value);
133
+ }
134
+
135
+ /** The text of an unknown value in a message. */
136
+ function shown(value: unknown): string {
137
+ const text = typeof value === "string" ? JSON.stringify(value) : String(value);
138
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
139
+ }
140
+
141
+ /**
142
+ * This function examines a value as a media document. It gives the document, or each problem that it found. A problem
143
+ * in one entry does not stop the examination of the other entries.
144
+ */
145
+ export function checkMediaDocument(value: unknown): Result<MediaDocument, readonly MediaIssue[]> {
146
+ const issues: MediaIssue[] = [];
147
+ const add = (tokens: readonly (string | number)[], code: MediaIssueCode, message: string): void => {
148
+ issues.push({ at: formatPointer(tokens), code, message });
149
+ };
150
+ if (!isObject(value)) {
151
+ add([], "NOT_OBJECT", "A media document is an object with the fields $media and $data");
152
+ return err(issues);
153
+ }
154
+ for (const key of Object.keys(value)) {
155
+ if (key !== "$media" && key !== "$data") add([key], "UNKNOWN_FIELD", `A media document has only $media and $data, not ${shown(key)}`);
156
+ }
157
+ if (!(Object.hasOwn(value, "$data"))) add(["$data"], "MISSING_FIELD", "A media document needs the field $data");
158
+ if (!(Object.hasOwn(value, "$media"))) add(["$media"], "MISSING_FIELD", "A media document needs the field $media");
159
+ const data = value["$data"];
160
+ let dataIsJson = Object.hasOwn(value, "$data");
161
+ if (dataIsJson) {
162
+ try {
163
+ assertJson(data, "$data");
164
+ } catch (error) {
165
+ dataIsJson = false;
166
+ add(["$data"], "NOT_JSON", error instanceof Error ? error.message : String(error));
167
+ }
168
+ }
169
+ const media = value["$media"];
170
+ if (Object.hasOwn(value, "$media") && !isObject(media)) add(["$media"], "NOT_OBJECT", "The field $media is an object: each file by its id");
171
+ if (isObject(media)) {
172
+ const owners = new Map<string, string>();
173
+ for (const [id, entry] of Object.entries(media)) {
174
+ checkEntry(id, entry, dataIsJson ? (data as JsonValue) : undefined, owners, add);
175
+ }
176
+ }
177
+ return issues.length === 0 ? ok(value as unknown as MediaDocument) : err(issues);
178
+ }
179
+
180
+ type Add = (tokens: readonly (string | number)[], code: MediaIssueCode, message: string) => void;
181
+
182
+ function checkEntry(id: string, entry: unknown, data: JsonValue | undefined, owners: Map<string, string>, add: Add): void {
183
+ const at = ["$media", id];
184
+ if (!isMediaId(id)) add(at, "BAD_ID", `The id ${shown(id)} is not a SHA-256 in 64 lowercase hex characters`);
185
+ if (!isObject(entry)) {
186
+ add(at, "NOT_OBJECT", "An entry of $media is an object with path, type, size, sha256 and state");
187
+ return;
188
+ }
189
+ for (const field of BASE_FIELDS) {
190
+ if (!Object.hasOwn(entry, field)) add([...at, field], "MISSING_FIELD", `An entry of $media needs the field ${field}`);
191
+ }
192
+ const { path, type, size, sha256, state } = entry;
193
+ if (Object.hasOwn(entry, "sha256") && sha256 !== id) add([...at, "sha256"], "ID_MISMATCH", "The field sha256 of an entry is equal to its id");
194
+ if (Object.hasOwn(entry, "type") && !isMediaType(type)) add([...at, "type"], "BAD_TYPE", `The type ${shown(type)} is not a media type in lowercase, for example image/jpeg`);
195
+ const sizeIsGood = Number.isSafeInteger(size) && (size as number) >= 0;
196
+ if (Object.hasOwn(entry, "size") && !sizeIsGood) add([...at, "size"], "BAD_SIZE", `The size ${shown(size)} is not a safe integer of 0 or more`);
197
+ if (Object.hasOwn(entry, "state") && !isState(state)) add([...at, "state"], "BAD_STATE", `The state ${shown(state)} is not one of ${MEDIA_STATES.join(", ")}`);
198
+ if (Object.hasOwn(entry, "path")) checkPath(id, path, data, owners, [...at, "path"], add);
199
+ if (!isState(state)) return;
200
+ const allowed = new Set<string>([...BASE_FIELDS, ...STATE_FIELDS[state]]);
201
+ for (const field of Object.keys(entry)) {
202
+ if (!allowed.has(field)) add([...at, field], "UNKNOWN_FIELD", `An entry in the state ${state} has no field ${shown(field)}`);
203
+ }
204
+ for (const field of STATE_FIELDS[state]) {
205
+ if (!Object.hasOwn(entry, field)) add([...at, field], "MISSING_FIELD", `An entry in the state ${state} needs the field ${field}`);
206
+ }
207
+ if (state === "partial" && Object.hasOwn(entry, "received")) {
208
+ const received = entry["received"];
209
+ const good = Number.isSafeInteger(received) && (received as number) > 0 && (!sizeIsGood || (received as number) < (size as number));
210
+ if (!good) add([...at, "received"], "BAD_RECEIVED", `The count received ${shown(received)} of a partial file is more than 0 and less than its size`);
211
+ }
212
+ if (state === "embedded" && Object.hasOwn(entry, "base64")) {
213
+ const text = entry["base64"];
214
+ if (typeof text !== "string" || decodeBase64(text) === undefined) {
215
+ add([...at, "base64"], "BAD_BASE64", "The field base64 is the canonical base64 text of the bytes (RFC 4648, with padding)");
216
+ } else if (sizeIsGood && base64Size(text) !== size) {
217
+ add([...at, "base64"], "SIZE_MISMATCH", `The base64 text has ${base64Size(text)} bytes, but the size is ${String(size)}`);
218
+ }
219
+ }
220
+ if (state === "linked" && Object.hasOwn(entry, "url") && !isMediaUrl(entry["url"])) {
221
+ add([...at, "url"], "BAD_URL", `The url ${shown(entry["url"])} is not an absolute http or https URL`);
222
+ }
223
+ }
224
+
225
+ function checkPath(id: string, path: unknown, data: JsonValue | undefined, owners: Map<string, string>, at: readonly string[], add: Add): void {
226
+ if (typeof path !== "string" || path.startsWith("#")) {
227
+ add(at, "BAD_PATH", `The path ${shown(path)} is not a JSON Pointer: it is "" or starts with "/"`);
228
+ return;
229
+ }
230
+ let tokens: string[];
231
+ try {
232
+ tokens = parsePointer(path, "path");
233
+ } catch (error) {
234
+ add(at, "BAD_PATH", error instanceof Error ? error.message : String(error));
235
+ return;
236
+ }
237
+ const owner = owners.get(path);
238
+ if (owner !== undefined) add(at, "PATH_SHARED", `The path ${shown(path)} is also the path of the file ${owner}`);
239
+ else owners.set(path, id);
240
+ if (data === undefined) return;
241
+ const found = lookup(data, tokens);
242
+ if (!found.found) add(at, "PATH_NOT_FOUND", `The path ${shown(path)} is not in $data`);
243
+ else if (found.value !== id) add(at, "PATH_NOT_ID", `At the path ${shown(path)}, $data holds ${shown(found.value)}, not the id of the file`);
244
+ }
245
+
246
+ /** This function gives the document, or throws a `MediaDocumentError` with each problem. */
247
+ export function assertMediaDocument(value: unknown): MediaDocument {
248
+ const result = checkMediaDocument(value);
249
+ if (result.tag === "err") throw new MediaDocumentError(result.error);
250
+ return result.value;
251
+ }
252
+
253
+ /** The error of a value that is not a media document. It has the list of the problems. */
254
+ export class MediaDocumentError extends Error {
255
+ readonly issues: readonly MediaIssue[];
256
+ constructor(issues: readonly MediaIssue[]) {
257
+ const first = issues[0];
258
+ const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
259
+ super(first === undefined ? "The value is not a media document" : `${first.at || "/"}: ${first.message}${more}`);
260
+ this.name = "MediaDocumentError";
261
+ this.issues = issues;
262
+ }
263
+ }
@@ -0,0 +1,168 @@
1
+ // The edge cases of the core, with fixed inputs. The property tests of media.test.ts draw random files, so a run can
2
+ // miss a branch, and the coverage of a run moves (client main, 11-28: branches 85.11 in CI, 86.04 on the build machine).
3
+ // Each branch here has a fixed case, so the coverage does not depend on the draws.
4
+ import { describe, expect, it } from "vitest";
5
+ import { createRegistry } from "@procedures/client";
6
+ import {
7
+ DEFAULT_MAX_EMBEDDED_BYTES,
8
+ MediaDocumentError,
9
+ addMedia,
10
+ checkMediaDocument,
11
+ embedMedia,
12
+ encodeBase64,
13
+ isMediaUrl,
14
+ isStored,
15
+ linkMedia,
16
+ mediaModule,
17
+ missingIds,
18
+ registerMediaProcedures,
19
+ stripMedia,
20
+ withReceived,
21
+ type MediaDocument,
22
+ type MediaEntry,
23
+ type MediaIssueCode,
24
+ } from "./index.js";
25
+
26
+ const A = "a".repeat(64);
27
+ const B = "b".repeat(64);
28
+ const C = "c".repeat(64);
29
+
30
+ const codes = (value: unknown): MediaIssueCode[] => {
31
+ const result = checkMediaDocument(value);
32
+ return result.tag === "err" ? result.error.map((issue) => issue.code) : [];
33
+ };
34
+
35
+ const pending = (path: string, sha256: string, size = 3): MediaEntry => ({ path, type: "image/png", size, sha256, state: "pending" });
36
+
37
+ /** A document with three files: A is pending, B is linked, C is embedded. */
38
+ function sample(): MediaDocument {
39
+ return {
40
+ $media: {
41
+ [A]: pending("/a", A),
42
+ [B]: { path: "/b", type: "image/png", size: 3, sha256: B, state: "linked", url: "https://example.com/b.png" },
43
+ [C]: { path: "/c", type: "image/png", size: 2, sha256: C, state: "embedded", base64: encodeBase64(new Uint8Array([1, 2])) },
44
+ },
45
+ $data: { a: A, b: B, c: C },
46
+ };
47
+ }
48
+
49
+ describe("the transfer steps at their edges", () => {
50
+ it("embeds only a known, stored file that is small enough, and refuses bytes of the wrong size", () => {
51
+ const document = sample();
52
+ const files = new Map([
53
+ ["f".repeat(64), new Uint8Array(3)],
54
+ [B, new Uint8Array(3)],
55
+ [C, new Uint8Array(2)],
56
+ ]);
57
+ expect(embedMedia(document, files)).toBe(document);
58
+ expect(embedMedia(document, new Map([[A, new Uint8Array(3)]]), { maxBytes: 2 })).toBe(document);
59
+ expect(embedMedia(document, new Map([[A, new Uint8Array(3)]])).$media[A]).toMatchObject({ state: "embedded", base64: "AAAA" });
60
+ expect(() => embedMedia(document, new Map([[A, new Uint8Array(4)]]))).toThrow(/has 3 bytes, but the bytes to embed are 4/);
61
+ expect(DEFAULT_MAX_EMBEDDED_BYTES).toBe(65536);
62
+ });
63
+
64
+ it("strips the embedded bytes, and refuses a base64 text that is not canonical", () => {
65
+ const stripped = stripMedia(sample());
66
+ expect(stripped.files.get(C)).toEqual(new Uint8Array([1, 2]));
67
+ expect(stripped.document.$media[C]!.state).toBe("pending");
68
+ expect(stripped.document.$media[B]!.state).toBe("linked");
69
+ const bad = { ...sample(), $media: { ...sample().$media, [C]: { ...sample().$media[C]!, base64: "A" } as MediaEntry } };
70
+ expect(() => stripMedia(bad)).toThrow(/not canonical/);
71
+ });
72
+
73
+ it("links a file only to an http or https URL, and only a file that the document has", () => {
74
+ expect(linkMedia(sample(), A, "http://example.com/a").$media[A]).toMatchObject({ state: "linked", url: "http://example.com/a" });
75
+ expect(() => linkMedia(sample(), A, "ftp://example.com/a")).toThrow(/not an absolute http or https URL/);
76
+ expect(() => linkMedia(sample(), "f".repeat(64), "https://example.com/")).toThrow(/has no file with the id/);
77
+ expect(isMediaUrl(42)).toBe(false);
78
+ expect(isMediaUrl("not a url")).toBe(false);
79
+ });
80
+
81
+ it("sets the state from each count, and refuses a count for an embedded or a linked file", () => {
82
+ const document = sample();
83
+ expect(withReceived(document, A, 0).$media[A]!.state).toBe("pending");
84
+ expect(withReceived(document, A, 1).$media[A]).toMatchObject({ state: "partial", received: 1 });
85
+ expect(withReceived(document, A, 3).$media[A]!.state).toBe("complete");
86
+ for (const count of [-1, 4, 1.5, Number.NaN]) expect(() => withReceived(document, A, count)).toThrow(/not an integer from 0 to its size 3/);
87
+ expect(() => withReceived(document, B, 1)).toThrow(/is linked/);
88
+ expect(() => withReceived(document, C, 1)).toThrow(/is embedded/);
89
+ expect(isStored(document.$media[A]!)).toBe(true);
90
+ expect(missingIds(document, () => false)).toEqual([A]);
91
+ expect(missingIds(document, (id) => id === A)).toEqual([]);
92
+ });
93
+
94
+ it("adds a file at a field of an object, and refuses a bad hash, a missing parent and a bad index", () => {
95
+ const empty: MediaDocument = { $media: {}, $data: { photos: {}, list: [] } };
96
+ const added = addMedia(empty, { path: "/photos/one", type: "image/jpeg", size: 1, sha256: A });
97
+ expect(added.$data).toEqual({ photos: { one: A }, list: [] });
98
+ expect(() => addMedia(empty, { path: "/photos/one", type: "image/jpeg", size: 1, sha256: "A".repeat(64) })).toThrow(/not a SHA-256/);
99
+ expect(() => addMedia(empty, { path: "/nothing/one", type: "image/jpeg", size: 1, sha256: A })).toThrow(/parent of the path/);
100
+ expect(() => addMedia(empty, { path: "/list/x", type: "image/jpeg", size: 1, sha256: A })).toThrow(/not an index of its array/);
101
+ // The root path "" replaces all of $data with the id, and the result is a document of one file.
102
+ expect(addMedia({ $media: {}, $data: {} }, { path: "", type: "image/jpeg", size: 1, sha256: A }).$data).toBe(A);
103
+ // A bad type makes a bad entry, and the check of the result throws a MediaDocumentError with the problems.
104
+ const error = (() => {
105
+ try {
106
+ addMedia(empty, { path: "/photos/two", type: "Image/JPEG", size: 1, sha256: B });
107
+ } catch (caught) {
108
+ return caught;
109
+ }
110
+ return undefined;
111
+ })();
112
+ expect(error).toBeInstanceOf(MediaDocumentError);
113
+ expect((error as MediaDocumentError).issues.map((issue) => issue.code)).toEqual(["BAD_TYPE"]);
114
+ });
115
+ });
116
+
117
+ describe("the check at its edges", () => {
118
+ it("refuses a $media that is not an object, an entry that is not an object, and an entry with no fields", () => {
119
+ expect(codes({ $media: [], $data: {} })).toEqual(["NOT_OBJECT"]);
120
+ expect(codes({ $media: { [A]: "x" }, $data: {} })).toEqual(["NOT_OBJECT"]);
121
+ expect(codes({ $media: { [A]: {} }, $data: {} })).toEqual(["MISSING_FIELD", "MISSING_FIELD", "MISSING_FIELD", "MISSING_FIELD", "MISSING_FIELD"]);
122
+ });
123
+
124
+ it("refuses an entry that lacks the field of its state", () => {
125
+ const base = { path: "/a", type: "image/png", size: 3, sha256: A };
126
+ const data = { a: A };
127
+ expect(codes({ $media: { [A]: { ...base, state: "partial" } }, $data: data })).toEqual(["MISSING_FIELD"]);
128
+ expect(codes({ $media: { [A]: { ...base, state: "embedded" } }, $data: data })).toEqual(["MISSING_FIELD"]);
129
+ expect(codes({ $media: { [A]: { ...base, state: "linked" } }, $data: data })).toEqual(["MISSING_FIELD"]);
130
+ expect(codes({ $media: { [A]: { ...base, state: "embedded", base64: 7 } }, $data: data })).toEqual(["BAD_BASE64"]);
131
+ // With a bad size, the count of a partial file is checked only for more than 0.
132
+ expect(codes({ $media: { [A]: { ...base, size: -1, state: "partial", received: 2 } }, $data: data })).toEqual(["BAD_SIZE"]);
133
+ expect(codes({ $media: { [A]: { ...base, size: -1, state: "partial", received: 0 } }, $data: data })).toEqual(["BAD_SIZE", "BAD_RECEIVED"]);
134
+ // With a bad size, the size of the base64 text is not compared.
135
+ expect(codes({ $media: { [A]: { ...base, size: -1, state: "embedded", base64: "AAAA" } }, $data: data })).toEqual(["BAD_SIZE"]);
136
+ });
137
+
138
+ it("refuses a path that is not a JSON Pointer, and does not look up a path in a $data that is not JSON", () => {
139
+ const entry = (path: unknown): unknown => ({ $media: { [A]: { ...pending("/a", A), path } }, $data: { a: A } });
140
+ expect(codes(entry(5))).toEqual(["BAD_PATH"]);
141
+ expect(codes(entry("#/a"))).toEqual(["BAD_PATH"]);
142
+ expect(codes(entry("a"))).toEqual(["BAD_PATH"]);
143
+ expect(codes({ $media: { [A]: pending("/nowhere", A) }, $data: { when: new Date(0) } })).toEqual(["NOT_JSON"]);
144
+ });
145
+
146
+ it("gives a message for an error with no problems, and names the count of the other problems", () => {
147
+ expect(new MediaDocumentError([]).message).toBe("The value is not a media document");
148
+ const error = new MediaDocumentError([
149
+ { at: "", code: "NOT_OBJECT", message: "one" },
150
+ { at: "/$media", code: "NOT_OBJECT", message: "two" },
151
+ ]);
152
+ expect(error.message).toBe("/: one (and 1 more)");
153
+ expect(error.name).toBe("MediaDocumentError");
154
+ });
155
+
156
+ it("shows a long value in a message in a short form", () => {
157
+ const result = checkMediaDocument({ $media: {}, $data: {}, ["x".repeat(100)]: 1 });
158
+ expect(result.tag === "err" && result.error[0]!.message.endsWith("...")).toBe(true);
159
+ });
160
+ });
161
+
162
+ describe("the module", () => {
163
+ it("has no procedures yet, and registers in a registry with no error", () => {
164
+ const registry = createRegistry();
165
+ expect(() => registerMediaProcedures(registry)).not.toThrow();
166
+ expect(mediaModule).toBeDefined();
167
+ });
168
+ });
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ // The root registers nothing: import "<package>/register", or give the module to createRegistry()
2
+ export * from "./module.js";
3
+ export * from "./types.js";
4
+
5
+ // The pure core of media documents. It has no Node.js import, so it runs in a browser too.
6
+ export {
7
+ MEDIA_STATES,
8
+ assertMediaDocument,
9
+ checkMediaDocument,
10
+ isMediaId,
11
+ isMediaType,
12
+ isMediaUrl,
13
+ MediaDocumentError,
14
+ type MediaDocument,
15
+ type MediaEntry,
16
+ type MediaEntryBase,
17
+ type MediaIssue,
18
+ type MediaIssueCode,
19
+ type MediaState,
20
+ type MediaTable,
21
+ } from "./document.js";
22
+ export {
23
+ DEFAULT_MAX_EMBEDDED_BYTES,
24
+ addMedia,
25
+ embedMedia,
26
+ isStored,
27
+ linkMedia,
28
+ mediaIds,
29
+ missingIds,
30
+ stripMedia,
31
+ withReceived,
32
+ type EmbedOptions,
33
+ type NewMedia,
34
+ type StrippedMedia,
35
+ } from "./transfer.js";
36
+ export { addRange, isByteRange, missingRanges, normalizeRanges, planChunks, rangeBytes, type ByteRange } from "./ranges.js";
37
+ export { base64Size, decodeBase64, encodeBase64 } from "./base64.js";
@@ -0,0 +1,190 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import fc from "fast-check";
3
+ import {
4
+ addMedia,
5
+ checkMediaDocument,
6
+ encodeBase64,
7
+ embedMedia,
8
+ linkMedia,
9
+ mediaIds,
10
+ missingIds,
11
+ stripMedia,
12
+ withReceived,
13
+ type MediaDocument,
14
+ type MediaIssueCode,
15
+ } from "./index.js";
16
+
17
+ // A fixed seed: each run draws the same files, so a change of the coverage is a change of the code (11-28).
18
+ const RUNS = { numRuns: 200, seed: 20_261_128 };
19
+
20
+ const hex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
21
+
22
+ /** A file with random bytes and a random id. The core has no hash, so the id need not be the hash of the bytes. */
23
+ const fileArb = fc.record({
24
+ id: fc.uint8Array({ minLength: 32, maxLength: 32 }).map(hex),
25
+ bytes: fc.uint8Array({ maxLength: 96 }),
26
+ type: fc.constantFrom("image/jpeg", "image/png", "application/pdf", "text/plain; charset=utf-8", "application/vnd.example+json"),
27
+ // A name with "~" and "/" makes the escapes of the pointer (RFC 6901) part of the test.
28
+ name: fc.option(fc.string({ unit: fc.constantFrom("a", "b", "~", "/", "0", "1", " "), minLength: 1, maxLength: 6 }), { nil: undefined }),
29
+ });
30
+
31
+ type FileValue = { readonly id: string; readonly bytes: Uint8Array; readonly type: string; readonly name: string | undefined };
32
+
33
+ const escape = (token: string): string => token.replace(/~/g, "~0").replace(/\//g, "~1");
34
+
35
+ /** A list of files with distinct ids and distinct names. */
36
+ const filesArb = fc.uniqueArray(fileArb, { maxLength: 8, selector: (file) => file.id }).map((files) => {
37
+ const names = new Set<string>();
38
+ return files.map((file) => {
39
+ if (file.name === undefined || names.has(file.name)) return { ...file, name: undefined };
40
+ names.add(file.name);
41
+ return file;
42
+ });
43
+ });
44
+
45
+ function build(files: readonly FileValue[]): MediaDocument {
46
+ let document: MediaDocument = { $media: {}, $data: { title: "a record", list: [], byName: {} } };
47
+ for (const file of files) {
48
+ const path = file.name === undefined ? "/list/-" : `/byName/${escape(file.name)}`;
49
+ document = addMedia(document, { path, type: file.type, size: file.bytes.length, sha256: file.id });
50
+ }
51
+ return document;
52
+ }
53
+
54
+ function codes(value: unknown): MediaIssueCode[] {
55
+ const result = checkMediaDocument(value);
56
+ return result.tag === "ok" ? [] : result.error.map((issue) => issue.code);
57
+ }
58
+
59
+ describe("media documents", () => {
60
+ it("a built document passes the check, also after a JSON round trip", () => {
61
+ fc.assert(
62
+ fc.property(filesArb, (files) => {
63
+ const document = build(files);
64
+ expect(codes(document)).toEqual([]);
65
+ const copy: unknown = JSON.parse(JSON.stringify(document));
66
+ expect(codes(copy)).toEqual([]);
67
+ expect(mediaIds(document)).toEqual(files.map((file) => file.id).sort());
68
+ }),
69
+ RUNS,
70
+ );
71
+ });
72
+
73
+ it("strip after embed gives the pending document and the bytes of each small file", () => {
74
+ fc.assert(
75
+ fc.property(filesArb, fc.integer({ min: 0, max: 100 }), (files, maxBytes) => {
76
+ const document = build(files);
77
+ const bytes = new Map(files.map((file) => [file.id, file.bytes]));
78
+ const embedded = embedMedia(document, bytes, { maxBytes });
79
+ expect(codes(embedded)).toEqual([]);
80
+ const small = files.filter((file) => file.bytes.length <= maxBytes);
81
+ for (const file of files) expect(embedded.$media[file.id]!.state).toBe(file.bytes.length <= maxBytes ? "embedded" : "pending");
82
+ const stripped = stripMedia(embedded);
83
+ expect(stripped.document).toEqual(document);
84
+ expect([...stripped.files.keys()].sort()).toEqual(small.map((file) => file.id).sort());
85
+ for (const file of small) expect(Array.from(stripped.files.get(file.id)!)).toEqual(Array.from(file.bytes));
86
+ }),
87
+ RUNS,
88
+ );
89
+ });
90
+
91
+ it("the missing ids are the stored files that the store does not have, in sorted order", () => {
92
+ fc.assert(
93
+ fc.property(filesArb, fc.func(fc.boolean()), fc.func(fc.constantFrom("embed", "link", "keep")), (files, has, kind) => {
94
+ let document = build(files);
95
+ const stored = new Set<string>();
96
+ for (const file of files) {
97
+ const choice = kind(file.id);
98
+ if (choice === "embed") document = embedMedia(document, new Map([[file.id, file.bytes]]), { maxBytes: 1000 });
99
+ else if (choice === "link") document = linkMedia(document, file.id, `https://example.com/${file.id}`);
100
+ else stored.add(file.id);
101
+ }
102
+ expect(codes(document)).toEqual([]);
103
+ const missing = missingIds(document, (id) => has(id));
104
+ expect(missing).toEqual([...stored].filter((id) => !has(id)).sort());
105
+ expect(missingIds(document, (id) => stored.has(id))).toEqual([]);
106
+ }),
107
+ RUNS,
108
+ );
109
+ });
110
+
111
+ it("the count of received bytes sets the state, and the last count wins", () => {
112
+ fc.assert(
113
+ fc.property(
114
+ filesArb.filter((files) => files.length > 0),
115
+ fc.array(fc.double({ min: 0, max: 1, noNaN: true }), { minLength: 1, maxLength: 5 }),
116
+ (files, shares) => {
117
+ const file = files[0]!;
118
+ const size = file.bytes.length;
119
+ let document = build(files);
120
+ let count = 0;
121
+ for (const share of shares) {
122
+ count = Math.round(share * size);
123
+ document = withReceived(document, file.id, count);
124
+ expect(codes(document)).toEqual([]);
125
+ }
126
+ const entry = document.$media[file.id]!;
127
+ expect(entry.state).toBe(count === 0 ? "pending" : count === size ? "complete" : "partial");
128
+ if (entry.state === "partial") expect(entry.received).toBe(count);
129
+ },
130
+ ),
131
+ RUNS,
132
+ );
133
+ });
134
+
135
+ it("the check finds each kind of damage", () => {
136
+ fc.assert(
137
+ fc.property(filesArb.filter((files) => files.length > 0), (files) => {
138
+ const document = build(files);
139
+ const id = files[0]!.id;
140
+ const entry = document.$media[id]!;
141
+ const damage = (change: (copy: { $media: Record<string, Record<string, unknown>>; $data: unknown }) => void): MediaIssueCode[] => {
142
+ const copy = JSON.parse(JSON.stringify(document)) as { $media: Record<string, Record<string, unknown>>; $data: unknown };
143
+ change(copy);
144
+ return codes(copy);
145
+ };
146
+ expect(damage((copy) => (copy.$media[id]!["sha256"] = "0".repeat(64)))).toContain("ID_MISMATCH");
147
+ expect(damage((copy) => (copy.$media[id]!["size"] = -1))).toContain("BAD_SIZE");
148
+ expect(damage((copy) => (copy.$media[id]!["type"] = "Image/JPEG"))).toContain("BAD_TYPE");
149
+ expect(damage((copy) => (copy.$media[id]!["state"] = "done"))).toContain("BAD_STATE");
150
+ expect(damage((copy) => (copy.$media[id]!["url"] = "https://example.com/"))).toContain("UNKNOWN_FIELD");
151
+ expect(damage((copy) => (copy.$media[id]!["path"] = "/nowhere/at/all"))).toContain("PATH_NOT_FOUND");
152
+ expect(damage((copy) => (copy.$media[id]!["path"] = "no-slash"))).toContain("BAD_PATH");
153
+ expect(damage((copy) => (copy.$data = JSON.parse(JSON.stringify(copy.$data).split(id).join("f".repeat(64)))))).toContain("PATH_NOT_ID");
154
+ expect(damage((copy) => {
155
+ copy.$media[id.toUpperCase()] = copy.$media[id]!;
156
+ delete copy.$media[id];
157
+ })).toContain("BAD_ID");
158
+ expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "partial", received: entry.size }))).toContain("BAD_RECEIVED");
159
+ expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "linked", url: "javascript:alert(1)" }))).toContain("BAD_URL");
160
+ expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "embedded", base64: "A" }))).toContain("BAD_BASE64");
161
+ expect(damage((copy) => (copy.$media[id] = { ...copy.$media[id]!, state: "embedded", base64: encodeBase64(new Uint8Array(entry.size + 1)) }))).toContain("SIZE_MISMATCH");
162
+ }),
163
+ RUNS,
164
+ );
165
+ });
166
+
167
+ it("two files at one path, a non-JSON $data and other fields are refused", () => {
168
+ const one = "a".repeat(64);
169
+ const two = "b".repeat(64);
170
+ const entry = { type: "image/png", size: 1, state: "pending" };
171
+ expect(codes({ $media: { [one]: { ...entry, path: "/x", sha256: one }, [two]: { ...entry, path: "/x", sha256: two } }, $data: { x: one } })).toContain("PATH_SHARED");
172
+ expect(codes({ $media: {}, $data: { when: new Date(0) } })).toContain("NOT_JSON");
173
+ expect(codes({ $media: {}, $data: {}, extra: 1 })).toEqual(["UNKNOWN_FIELD"]);
174
+ expect(codes({ $data: {} })).toEqual(["MISSING_FIELD"]);
175
+ expect(codes([])).toEqual(["NOT_OBJECT"]);
176
+ });
177
+
178
+ it("an add at an array index that exists replaces the value, so the other paths stay true", () => {
179
+ const one = "1".repeat(64);
180
+ const two = "2".repeat(64);
181
+ let document: MediaDocument = { $media: {}, $data: { list: ["old", "keep"] } };
182
+ document = addMedia(document, { path: "/list/0", type: "image/png", size: 3, sha256: one });
183
+ document = addMedia(document, { path: "/list/-", type: "image/png", size: 4, sha256: two });
184
+ expect(document.$data).toEqual({ list: [one, "keep", two] });
185
+ expect(document.$media[two]!.path).toBe("/list/2");
186
+ expect(() => addMedia(document, { path: "/list/9", type: "image/png", size: 1, sha256: "3".repeat(64) })).toThrow(RangeError);
187
+ // A new file over the path of a file makes that file lose its path, and the check refuses it.
188
+ expect(() => addMedia(document, { path: "/list/2", type: "image/png", size: 1, sha256: "3".repeat(64) })).toThrow(/holds/);
189
+ });
190
+ });