@fedify/vocab-tools 2.5.0-dev.2687 → 2.5.0-dev.2710

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/src/codec.test.ts DELETED
@@ -1,512 +0,0 @@
1
- import { deepStrictEqual, match, ok, rejects } from "node:assert/strict";
2
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { test } from "node:test";
6
- import { pathToFileURL } from "node:url";
7
- import { generateClasses } from "./class.ts";
8
- import type { PropertySchema, TypeSchema } from "./schema.ts";
9
-
10
- const NS = "https://example.com/";
11
- const AS = "https://www.w3.org/ns/activitystreams";
12
- const CONTEXT = `${NS}context`;
13
- const XSD = "http://www.w3.org/2001/XMLSchema#";
14
- const context = {
15
- type: "@type",
16
- id: "@id",
17
- Fixture: `${NS}Fixture`,
18
- Value: `${NS}Value`,
19
- label: `${NS}label`,
20
- value: `${NS}value`,
21
- first: `${NS}first`,
22
- second: `${NS}second`,
23
- };
24
-
25
- interface Instance {
26
- values: unknown[];
27
- value: unknown;
28
- toJsonLd(options?: Record<string, unknown>): Promise<Record<string, unknown>>;
29
- }
30
- interface FixtureClass {
31
- new (values?: Record<string, unknown>): Instance;
32
- fromJsonLd(
33
- document: unknown,
34
- options?: Record<string, unknown>,
35
- ): Promise<Instance>;
36
- }
37
-
38
- async function withFixture(
39
- options: Partial<PropertySchema>,
40
- run: (
41
- Fixture: FixtureClass,
42
- loader: (url: string) => Promise<unknown>,
43
- source: string,
44
- ) => Promise<void>,
45
- ) {
46
- const property = {
47
- singularName: "value",
48
- pluralName: "values",
49
- uri: `${NS}value`,
50
- compactName: "value",
51
- description: "A value.",
52
- range: [`${XSD}string`],
53
- redundantProperties: [
54
- { uri: `${NS}first`, compactName: "first" },
55
- { uri: `${NS}second`, compactName: "second" },
56
- ],
57
- ...options,
58
- } as PropertySchema;
59
- const terms: Record<string, unknown> = { ...context };
60
- for (const name of ["value", "first", "second"]) {
61
- const term: Record<string, unknown> = { "@id": `${NS}${name}` };
62
- if (
63
- property.range[0] === `${XSD}anyURI` ||
64
- property.range[0] === "fedify:absoluteIri"
65
- ) {
66
- term["@type"] = "@id";
67
- }
68
- if ("container" in property && property.container != null) {
69
- term["@container"] = `@${property.container}`;
70
- }
71
- terms[name] = term;
72
- }
73
- const loader = (url: string) => {
74
- if (url !== AS && url !== CONTEXT) {
75
- throw new Error(`Unexpected context: ${url}`);
76
- }
77
- return Promise.resolve({
78
- contextUrl: null,
79
- documentUrl: url,
80
- document: {
81
- "@context": url === AS ? { type: "@type", id: "@id" } : terms,
82
- },
83
- });
84
- };
85
- const types: Record<string, TypeSchema> = {
86
- [`${NS}Fixture`]: {
87
- name: "Fixture",
88
- uri: `${NS}Fixture`,
89
- compactName: "Fixture",
90
- entity: false,
91
- description: "A fixture.",
92
- defaultContext: [AS, CONTEXT] as unknown as TypeSchema["defaultContext"],
93
- properties: [property],
94
- },
95
- [`${NS}Value`]: {
96
- name: "Value",
97
- uri: `${NS}Value`,
98
- compactName: "Value",
99
- entity: false,
100
- description: "An embedded value.",
101
- defaultContext: [AS, CONTEXT] as unknown as TypeSchema["defaultContext"],
102
- properties: [
103
- {
104
- singularName: "label",
105
- functional: true,
106
- uri: `${NS}label`,
107
- compactName: "label",
108
- description: "A label.",
109
- range: [`${XSD}string`],
110
- },
111
- ],
112
- },
113
- };
114
- const source = (await Array.fromAsync(generateClasses(types))).join("");
115
- const resolved = source.replace(
116
- /from\s+"([^"]+)"/g,
117
- (_, specifier: string) =>
118
- `from ${JSON.stringify(import.meta.resolve(specifier))}`,
119
- );
120
- const dir = await mkdtemp(join(tmpdir(), "fedify-codec-"));
121
- try {
122
- const file = join(dir, "fixture.mts");
123
- await writeFile(file, resolved);
124
- const { Fixture } = await import(pathToFileURL(file).href);
125
- await run(Fixture, loader, source);
126
- } finally {
127
- await rm(dir, { recursive: true, force: true });
128
- }
129
- }
130
-
131
- const literal = (value: unknown) => ({ "@value": value });
132
- const document = (properties: Record<string, unknown>) => ({
133
- "@type": [`${NS}Fixture`],
134
- ...properties,
135
- });
136
-
137
- test("redundant properties select the first non-empty entire set", async () => {
138
- await withFixture({}, async (Fixture, contextLoader) => {
139
- for (const [properties, expected] of [
140
- [
141
- { [`${NS}first`]: [literal("a"), literal("b"), literal("a")] },
142
- ["a", "b", "a"],
143
- ],
144
- [{ [`${NS}value`]: [], [`${NS}first`]: [literal("a")] }, ["a"]],
145
- [{ [`${NS}first`]: [], [`${NS}second`]: [literal("b")] }, ["b"]],
146
- [
147
- { [`${NS}value`]: [literal("c")], [`${NS}first`]: [literal("a")] },
148
- ["c"],
149
- ],
150
- [
151
- { [`${NS}first`]: [literal("a")], [`${NS}second`]: [literal("b")] },
152
- ["a"],
153
- ],
154
- [{}, []],
155
- ] as const) {
156
- const parsed = await Fixture.fromJsonLd(document(properties), {
157
- contextLoader,
158
- });
159
- deepStrictEqual(parsed.values, expected);
160
- }
161
- const parsed = await Fixture.fromJsonLd(
162
- {
163
- "@context": termsForRead(),
164
- type: "Fixture",
165
- alternate: ["a", "b", "a"],
166
- },
167
- { contextLoader },
168
- );
169
- deepStrictEqual(parsed.values, ["a", "b", "a"]);
170
- });
171
- });
172
-
173
- function termsForRead() {
174
- return { ...context, alternate: `${NS}first` };
175
- }
176
-
177
- test("redundant properties do not retry invalid canonical values", async () => {
178
- await withFixture(
179
- {
180
- range: [
181
- `${XSD}string`,
182
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",
183
- ],
184
- },
185
- async (Fixture, contextLoader) => {
186
- const parsed = await Fixture.fromJsonLd(
187
- document({
188
- [`${NS}value`]: [literal(42)],
189
- [`${NS}first`]: [literal("fallback")],
190
- }),
191
- { contextLoader },
192
- );
193
- deepStrictEqual(parsed.values, []);
194
- },
195
- );
196
- await withFixture(
197
- { range: ["fedify:url"] },
198
- async (Fixture, contextLoader) => {
199
- const parsed = await Fixture.fromJsonLd(
200
- document({
201
- [`${NS}value`]: [literal("http://[")],
202
- [`${NS}first`]: [literal("https://example.com/fallback")],
203
- }),
204
- { contextLoader },
205
- );
206
- deepStrictEqual(parsed.values, []);
207
- },
208
- );
209
- await withFixture(
210
- { range: [`${XSD}anyURI`] },
211
- async (Fixture, contextLoader) => {
212
- await rejects(
213
- Fixture.fromJsonLd(
214
- document({
215
- [`${NS}value`]: [{ "@id": "http://[" }],
216
- [`${NS}first`]: [{ "@id": "https://example.com/fallback" }],
217
- }),
218
- { contextLoader },
219
- ),
220
- );
221
- },
222
- );
223
- });
224
-
225
- for (const policy of [undefined, "all", "canonical"] as const) {
226
- test(`redundant properties write policy ${policy ?? "default"}`, async () => {
227
- await withFixture(
228
- { redundantPropertiesWrite: policy },
229
- async (Fixture, contextLoader) => {
230
- for (const values of [[], ["a"], ["a", "b", "a"]]) {
231
- const instance = new Fixture({ values });
232
- const compact = await instance.toJsonLd({
233
- format: "compact",
234
- contextLoader,
235
- });
236
- deepStrictEqual(await instance.toJsonLd({ contextLoader }), compact);
237
- const expanded = (await instance.toJsonLd({
238
- format: "expand",
239
- contextLoader,
240
- })) as unknown as Record<string, unknown>[];
241
- for (const alias of ["first", "second"]) {
242
- if (policy === "canonical" || values.length === 0) {
243
- ok(!(alias in compact));
244
- ok(!(`${NS}${alias}` in expanded[0]));
245
- } else {
246
- deepStrictEqual(compact[alias], compact.value);
247
- deepStrictEqual(
248
- expanded[0][`${NS}${alias}`],
249
- expanded[0][`${NS}value`],
250
- );
251
- }
252
- }
253
- const custom = await instance.toJsonLd({
254
- format: "compact",
255
- contextLoader,
256
- context: { ...context, renamed: `${NS}value` },
257
- });
258
- deepStrictEqual(
259
- (await Fixture.fromJsonLd(custom, { contextLoader })).values,
260
- values,
261
- );
262
- }
263
- const aliasOnly = await Fixture.fromJsonLd(
264
- document({ [`${NS}first`]: [literal("read")] }),
265
- { contextLoader },
266
- );
267
- deepStrictEqual(aliasOnly.values, ["read"]);
268
- },
269
- );
270
- });
271
- }
272
-
273
- for (const container of ["list", "graph"] as const) {
274
- for (const policy of ["all", "canonical"] as const) {
275
- test(`redundant ${container} containers with ${policy} writes`, async () => {
276
- await withFixture(
277
- {
278
- container,
279
- redundantPropertiesWrite: policy,
280
- range: container === "graph" ? [`${NS}Value`] : [`${XSD}string`],
281
- },
282
- async (Fixture, contextLoader) => {
283
- const items =
284
- container === "list"
285
- ? [literal("a"), literal("b"), literal("a")]
286
- : [
287
- { "@type": [`${NS}Value`], [`${NS}label`]: [literal("a")] },
288
- { "@type": [`${NS}Value`], [`${NS}label`]: [literal("b")] },
289
- ];
290
- const set =
291
- container === "list"
292
- ? [{ "@list": items }]
293
- : items.map((item) => ({ "@graph": [item] }));
294
- const parsed = await Fixture.fromJsonLd(
295
- document({
296
- [`${NS}first`]: set,
297
- [`${NS}second`]: [{ "@list": [literal("other")] }],
298
- }),
299
- { contextLoader },
300
- );
301
- deepStrictEqual(
302
- container === "list"
303
- ? parsed.values
304
- : parsed.values.map((v) => (v as { label: string }).label),
305
- container === "list" ? ["a", "b", "a"] : ["a", "b"],
306
- );
307
- const instance = new Fixture({ values: parsed.values });
308
- const compact = await instance.toJsonLd({
309
- format: "compact",
310
- contextLoader,
311
- });
312
- if (container === "list" || policy === "all") {
313
- deepStrictEqual(
314
- await instance.toJsonLd({ contextLoader }),
315
- compact,
316
- );
317
- } else {
318
- // Parsed children retain expanded caches in the heuristic path.
319
- const defaultOutput = await instance.toJsonLd({ contextLoader });
320
- const decoded = await Fixture.fromJsonLd(defaultOutput, {
321
- contextLoader,
322
- });
323
- deepStrictEqual(
324
- decoded.values.map((v) => (v as { label: string }).label),
325
- ["a", "b"],
326
- );
327
- }
328
- const expanded = (await instance.toJsonLd({
329
- format: "expand",
330
- contextLoader,
331
- })) as unknown as Record<string, unknown>[];
332
- for (const alias of ["first", "second"]) {
333
- if (policy === "canonical") {
334
- ok(!(`${NS}${alias}` in expanded[0]));
335
- ok(!(alias in compact));
336
- } else {
337
- deepStrictEqual(
338
- expanded[0][`${NS}${alias}`],
339
- expanded[0][`${NS}value`],
340
- );
341
- deepStrictEqual(compact[alias], compact.value);
342
- }
343
- }
344
- const roundtrip = await Fixture.fromJsonLd(compact, {
345
- contextLoader,
346
- });
347
- deepStrictEqual(
348
- container === "list"
349
- ? roundtrip.values
350
- : roundtrip.values.map((v) => (v as { label: string }).label),
351
- container === "list" ? ["a", "b", "a"] : ["a", "b"],
352
- );
353
- const empty = await Fixture.fromJsonLd(
354
- document({
355
- [`${NS}value`]: [{ [`@${container}`]: [] }],
356
- [`${NS}first`]: set,
357
- }),
358
- { contextLoader },
359
- );
360
- deepStrictEqual(empty.values, []);
361
- },
362
- );
363
- });
364
- }
365
- }
366
-
367
- for (const functional of [false, true]) {
368
- test(`URI-only aliases and portable read keys (functional=${functional})`, async () => {
369
- for (const policy of ["all", "canonical"] as const) {
370
- await withFixture(
371
- {
372
- ...(functional ? { functional: true } : {}),
373
- range: [`${XSD}anyURI`],
374
- redundantPropertiesWrite: policy,
375
- redundantProperties: [{ uri: `${NS}first` }],
376
- },
377
- async (Fixture, contextLoader, source) => {
378
- ok(!source.includes("result[undefined]"));
379
- match(source, /PORTABLE_IRI_KEYS[^\n]+https:\/\/example.com\/first/);
380
- const url = new URL("https://example.com/object");
381
- const instance = new Fixture(
382
- functional ? { value: url } : { values: [url] },
383
- );
384
- const compact = await instance.toJsonLd({
385
- format: "compact",
386
- contextLoader,
387
- });
388
- deepStrictEqual(await instance.toJsonLd({ contextLoader }), compact);
389
- const expanded = (await instance.toJsonLd({
390
- format: "expand",
391
- contextLoader,
392
- })) as unknown as Record<string, unknown>[];
393
- if (policy === "all") {
394
- deepStrictEqual(expanded[0][`${NS}first`], [{ "@id": url.href }]);
395
- } else ok(!(`${NS}first` in expanded[0]));
396
- const custom = await instance.toJsonLd({
397
- format: "compact",
398
- contextLoader,
399
- context: {
400
- type: "@type",
401
- Fixture: `${NS}Fixture`,
402
- value: { "@id": `${NS}value`, "@type": "@id" },
403
- },
404
- });
405
- if (policy === "all") {
406
- deepStrictEqual(custom[`${NS}first`], { "@id": url.href });
407
- } else {
408
- ok(!(`${NS}first` in custom));
409
- }
410
- const parsed = await Fixture.fromJsonLd(
411
- document({
412
- [`${NS}first`]: [{ "@id": "ap://did:key:z6Mkabc/objects/1" }],
413
- }),
414
- { contextLoader },
415
- );
416
- const value = functional ? parsed.value : parsed.values[0];
417
- ok(value instanceof URL);
418
- const cached = await parsed.toJsonLd({ contextLoader });
419
- deepStrictEqual(cached[`${NS}first`], [
420
- {
421
- "@id": "ap+ef61://did:key:z6Mkabc/objects/1",
422
- },
423
- ]);
424
- const compactInput = await Fixture.fromJsonLd(
425
- {
426
- "@context": [AS, CONTEXT],
427
- type: "Fixture",
428
- first: "ap://did:key:z6Mkabc/objects/1",
429
- },
430
- { contextLoader },
431
- );
432
- const compactCache = await compactInput.toJsonLd({ contextLoader });
433
- deepStrictEqual(
434
- compactCache.first,
435
- "ap+ef61://did:key:z6Mkabc/objects/1",
436
- );
437
- },
438
- );
439
- }
440
- });
441
- }
442
-
443
- test("absolute IRIs are read from nodes and plain literals without a base", async () => {
444
- await withFixture(
445
- {
446
- range: ["fedify:absoluteIri"],
447
- redundantPropertiesWrite: "canonical",
448
- redundantProperties: [{ uri: `${NS}first` }],
449
- },
450
- async (Fixture, contextLoader, source) => {
451
- match(source, /PORTABLE_IRI_KEYS[^\n]+https:\/\/example.com\/value/);
452
- match(source, /PORTABLE_IRI_KEYS[^\n]+https:\/\/example.com\/first/);
453
- const values = [
454
- { "@id": "https://example.com/node" },
455
- literal("urn:example:literal"),
456
- { "@value": "https://example.com/any-uri", "@type": `${XSD}anyURI` },
457
- { "@value": "https://example.com/string", "@type": `${XSD}string` },
458
- // A context's default language tags uncoerced strings:
459
- { "@value": "https://example.com/tagged", "@language": "und" },
460
- // Relative IRIs are never resolved against the object's ID:
461
- { "@id": "CC-BY-4.0" },
462
- { "@id": "_:b0" },
463
- literal("Creative Commons Attribution 4.0 International"),
464
- { "@value": "https://example.com/date", "@type": `${XSD}date` },
465
- ];
466
- const expected = [
467
- new URL("https://example.com/node"),
468
- new URL("urn:example:literal"),
469
- new URL("https://example.com/any-uri"),
470
- new URL("https://example.com/string"),
471
- new URL("https://example.com/tagged"),
472
- ];
473
- for (const key of ["value", "first"]) {
474
- const parsed = await Fixture.fromJsonLd(
475
- {
476
- "@id": "https://example.com/objects/1",
477
- ...document({ [`${NS}${key}`]: values }),
478
- },
479
- { contextLoader, baseUrl: new URL("https://example.com/base/") },
480
- );
481
- deepStrictEqual(parsed.values, expected);
482
- }
483
- // An invalid canonical set is not replaced by a synonym:
484
- const invalid = await Fixture.fromJsonLd(
485
- document({
486
- [`${NS}value`]: [{ "@id": "CC-BY-4.0" }],
487
- [`${NS}first`]: [{ "@id": "https://example.com/fallback" }],
488
- }),
489
- { contextLoader },
490
- );
491
- deepStrictEqual(invalid.values, []);
492
- const instance = new Fixture({ values: expected });
493
- const expanded = (await instance.toJsonLd({
494
- format: "expand",
495
- contextLoader,
496
- })) as unknown as Record<string, unknown>[];
497
- deepStrictEqual(
498
- expanded[0][`${NS}value`],
499
- expected.map((url) => ({ "@id": url.href })),
500
- );
501
- ok(!(`${NS}first` in expanded[0]));
502
- const compact = await instance.toJsonLd({
503
- format: "compact",
504
- contextLoader,
505
- });
506
- deepStrictEqual(
507
- compact.value,
508
- expected.map((url) => url.href),
509
- );
510
- },
511
- );
512
- });