@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/type.ts DELETED
@@ -1,744 +0,0 @@
1
- import type { PropertySchema, TypeSchema } from "./schema.ts";
2
-
3
- // The list of JSON-LD contexts to apply heuristics that bypass the proper
4
- // JSON-LD processor.
5
- const HEURISTICS_CONTEXTS: string[] = [
6
- "https://www.w3.org/ns/activitystreams",
7
- "https://w3id.org/security/v1",
8
- "https://w3id.org/security/data-integrity/v1",
9
- "https://w3id.org/security/data-integrity/v2",
10
- "https://www.w3.org/ns/did/v1",
11
- "https://w3id.org/security/multikey/v1",
12
- "https://w3id.org/fep/ef61",
13
- ];
14
-
15
- interface ScalarType {
16
- name: string;
17
- typeGuard(variable: string): string;
18
- encoder(variable: string): string;
19
- compactEncoder?: (variable: string) => string;
20
- dataCheck(variable: string): string;
21
- decoder(variable: string, baseUrlVar: string): string;
22
- /**
23
- * Whether a value that fails `dataCheck()` should be skipped instead of
24
- * being handed to `decoder()`. Set this for types decoded from untrusted
25
- * remote input, where one malformed value must not fail the whole object.
26
- */
27
- skipUnparsable?: boolean;
28
- }
29
-
30
- const scalarTypes: Record<string, ScalarType> = {
31
- "http://www.w3.org/2001/XMLSchema#boolean": {
32
- name: "boolean",
33
- typeGuard(v) {
34
- return `typeof ${v} === "boolean"`;
35
- },
36
- encoder(v) {
37
- return `{ "@value": ${v} }`;
38
- },
39
- compactEncoder(v) {
40
- return v;
41
- },
42
- dataCheck(v) {
43
- return `typeof ${v} === "object" && "@value" in ${v}
44
- && typeof ${v}["@value"] === "boolean"`;
45
- },
46
- decoder(v) {
47
- return `${v}["@value"]`;
48
- },
49
- },
50
- "http://www.w3.org/2001/XMLSchema#integer": {
51
- name: "number",
52
- typeGuard(v) {
53
- return `typeof ${v} === "number" && Number.isInteger(${v})`;
54
- },
55
- encoder(v) {
56
- return `{
57
- "@type": "http://www.w3.org/2001/XMLSchema#integer",
58
- "@value": ${v},
59
- }`;
60
- },
61
- compactEncoder(v) {
62
- return v;
63
- },
64
- dataCheck(v) {
65
- return `typeof ${v} === "object" && "@type" in ${v}
66
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#integer"
67
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
68
- },
69
- decoder(v) {
70
- return `${v}["@value"] as number`;
71
- },
72
- },
73
- "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": {
74
- name: "number",
75
- typeGuard(v) {
76
- return `typeof ${v} === "number" && Number.isInteger(${v}) && ${v} >= 0`;
77
- },
78
- encoder(v) {
79
- return `{
80
- "@type": "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
81
- "@value": ${v},
82
- }`;
83
- },
84
- compactEncoder(v) {
85
- return v;
86
- },
87
- dataCheck(v) {
88
- return `typeof ${v} === "object" && "@type" in ${v}
89
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#nonNegativeInteger"
90
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
91
- },
92
- decoder(v) {
93
- return `${v}["@value"]`;
94
- },
95
- },
96
- "http://www.w3.org/2001/XMLSchema#float": {
97
- name: "number",
98
- typeGuard(v) {
99
- return `typeof ${v} === "number" && !Number.isNaN(${v})`;
100
- },
101
- encoder(v) {
102
- return `{
103
- "@type": "http://www.w3.org/2001/XMLSchema#float",
104
- "@value": ${v},
105
- }`;
106
- },
107
- compactEncoder(v) {
108
- return v;
109
- },
110
- dataCheck(v) {
111
- return `typeof ${v} === "object" && "@type" in ${v}
112
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#float"
113
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
114
- },
115
- decoder(v) {
116
- return `${v}["@value"]`;
117
- },
118
- },
119
- "http://www.w3.org/2001/XMLSchema#decimal": {
120
- name: "Decimal",
121
- typeGuard(v) {
122
- return `typeof ${v} === "string" && isDecimal(${v})`;
123
- },
124
- encoder(v) {
125
- return `{
126
- "@type": "http://www.w3.org/2001/XMLSchema#decimal",
127
- "@value": ${v},
128
- }`;
129
- },
130
- compactEncoder(v) {
131
- return v;
132
- },
133
- dataCheck(v) {
134
- return `typeof ${v} === "object" && "@type" in ${v}
135
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#decimal"
136
- && "@value" in ${v} && typeof ${v}["@value"] === "string"
137
- && canParseDecimal(${v}["@value"])`;
138
- },
139
- decoder(v) {
140
- return `parseDecimal(${v}["@value"])`;
141
- },
142
- },
143
- "http://www.w3.org/2001/XMLSchema#string": {
144
- name: "string",
145
- typeGuard(v) {
146
- return `typeof ${v} === "string"`;
147
- },
148
- encoder(v) {
149
- return `{ "@value": ${v} }`;
150
- },
151
- compactEncoder(v) {
152
- return v;
153
- },
154
- dataCheck(v) {
155
- return `typeof ${v} === "object" && "@value" in ${v}
156
- && typeof ${v}["@value"] === "string" && !("@language" in ${v})`;
157
- },
158
- decoder(v) {
159
- return `${v}["@value"]`;
160
- },
161
- skipUnparsable: true,
162
- },
163
- "http://www.w3.org/2001/XMLSchema#anyURI": {
164
- name: "URL",
165
- typeGuard(v) {
166
- return `${v} instanceof URL`;
167
- },
168
- encoder(v) {
169
- return `{ "@id": formatIri(${v}) }`;
170
- },
171
- compactEncoder(v) {
172
- return `formatIri(${v})`;
173
- },
174
- dataCheck(v) {
175
- return `${v} != null && typeof ${v} === "object" && "@id" in ${v}
176
- && typeof ${v}["@id"] === "string"
177
- && ${v}["@id"] !== ""`;
178
- },
179
- decoder(v, baseUrlVar) {
180
- return `parseIri(${v}["@id"], ${baseUrlVar})`;
181
- },
182
- },
183
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString": {
184
- name: "LanguageString",
185
- typeGuard(v) {
186
- return `${v} instanceof LanguageString`;
187
- },
188
- encoder(v) {
189
- return `{
190
- "@value": ${v}.toString(),
191
- "@language": ${v}.locale.baseName,
192
- }`;
193
- },
194
- dataCheck(v) {
195
- return `typeof ${v} === "object" && "@language" in ${v} && "@value" in ${v}
196
- && typeof ${v}["@language"] === "string"
197
- && typeof ${v}["@value"] === "string"
198
- && isValidLanguageTag(${v}["@language"])`;
199
- },
200
- decoder(v) {
201
- return `new LanguageString(${v}["@value"], ${v}["@language"])`;
202
- },
203
- },
204
- "http://www.w3.org/2001/XMLSchema#dateTime": {
205
- name: "Temporal.Instant",
206
- typeGuard(v) {
207
- return `isTemporalInstant(${v})`;
208
- },
209
- encoder(v) {
210
- return `{
211
- "@type": "http://www.w3.org/2001/XMLSchema#dateTime",
212
- "@value": ${v}.toString(),
213
- }`;
214
- },
215
- compactEncoder(v) {
216
- return `${v}.toString()`;
217
- },
218
- dataCheck(v) {
219
- return `typeof ${v} === "object" && "@type" in ${v}
220
- && "@value" in ${v} && typeof ${v}["@value"] === "string"
221
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#dateTime"
222
- // Check if the value is a valid RFC 3339 date-time string
223
- && new Date(${v}["@value"]).toString() !== "Invalid Date"
224
- `;
225
- },
226
- decoder(v) {
227
- return `Temporal.Instant.from(
228
- ${v}["@value"].substring(19).match(/[Z+-]/)
229
- ? ${v}["@value"]
230
- : ${v}["@value"] + "Z"
231
- )`;
232
- },
233
- },
234
- "http://www.w3.org/2001/XMLSchema#duration": {
235
- name: "Temporal.Duration",
236
- typeGuard(v) {
237
- return `isTemporalDuration(${v})`;
238
- },
239
- encoder(v) {
240
- return `{
241
- "@type": "http://www.w3.org/2001/XMLSchema#duration",
242
- "@value": ${v}.toString(),
243
- }`;
244
- },
245
- compactEncoder(v) {
246
- return `${v}.toString()`;
247
- },
248
- dataCheck(v) {
249
- return `typeof ${v} === "object" && "@type" in ${v}
250
- && "@value" in ${v} && typeof ${v}["@value"] === "string"
251
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#duration"`;
252
- },
253
- decoder(v) {
254
- return `Temporal.Duration.from(${v}["@value"])`;
255
- },
256
- },
257
- "https://w3id.org/security#cryptosuiteString": {
258
- name: '"eddsa-jcs-2022"',
259
- typeGuard(v) {
260
- return `${v} == "eddsa-jcs-2022"`;
261
- },
262
- encoder(v) {
263
- return `{ "@value": ${v} }`;
264
- },
265
- compactEncoder(v) {
266
- return v;
267
- },
268
- dataCheck(v) {
269
- return `typeof ${v} === "object" && "@value" in ${v}
270
- && !("@language" in ${v}) && ${v}["@value"] === "eddsa-jcs-2022"`;
271
- },
272
- decoder(v) {
273
- return `${v}["@value"]`;
274
- },
275
- },
276
- "https://w3id.org/security#multibase": {
277
- name: "Uint8Array",
278
- typeGuard(v) {
279
- return `${v} instanceof Uint8Array`;
280
- },
281
- encoder(v) {
282
- return `{
283
- "@type": "https://w3id.org/security#multibase",
284
- "@value": new TextDecoder().decode(encodeMultibase("base58btc", ${v})),
285
- }`;
286
- },
287
- compactEncoder(v) {
288
- return `new TextDecoder().decode(encodeMultibase("base58btc", ${v}))`;
289
- },
290
- dataCheck(v) {
291
- return `typeof ${v} === "object" && "@value" in ${v}
292
- && typeof ${v}["@value"] === "string"`;
293
- },
294
- decoder(v) {
295
- return `decodeMultibase(${v}["@value"])`;
296
- },
297
- },
298
- "fedify:langTag": {
299
- name: "Intl.Locale",
300
- typeGuard(v) {
301
- return `${v} instanceof Intl.Locale`;
302
- },
303
- encoder(v) {
304
- return `{ "@value": ${v}.baseName }`;
305
- },
306
- compactEncoder(v) {
307
- return `${v}.baseName`;
308
- },
309
- dataCheck(v) {
310
- return `typeof ${v} === "object" && "@value" in ${v}
311
- && typeof ${v}["@value"] === "string" && !("@language" in ${v})`;
312
- },
313
- decoder(v) {
314
- return `new Intl.Locale(normalizeLanguageTag(${v}["@value"]))`;
315
- },
316
- },
317
- "fedify:url": {
318
- name: "URL",
319
- typeGuard(v) {
320
- return `${v} instanceof URL`;
321
- },
322
- encoder(v) {
323
- return `{ "@value": formatIri(${v}) }`;
324
- },
325
- compactEncoder(v) {
326
- return `formatIri(${v})`;
327
- },
328
- dataCheck(v) {
329
- return `typeof ${v} === "object" &&
330
- ((typeof ${v}["@id"] === "string" && canDecodeIri(${v}["@id"])) ||
331
- (typeof ${v}["@value"] === "string" && canDecodeIri(${v}["@value"])))`;
332
- },
333
- decoder(v) {
334
- return `decodeIri(typeof ${v}["@id"] === "string" ? ${v}["@id"] : ${v}["@value"])`;
335
- },
336
- skipUnparsable: true,
337
- },
338
- "fedify:absoluteIri": {
339
- name: "URL",
340
- typeGuard(v) {
341
- return `${v} instanceof URL`;
342
- },
343
- encoder(v) {
344
- return `{ "@id": formatIri(${v}) }`;
345
- },
346
- compactEncoder(v) {
347
- return `formatIri(${v})`;
348
- },
349
- dataCheck(v) {
350
- return `isAbsoluteIriValue(${v})`;
351
- },
352
- decoder(v) {
353
- return `decodeIri(getAbsoluteIriValue(${v})!)`;
354
- },
355
- skipUnparsable: true,
356
- },
357
- "fedify:gatewayUrl": {
358
- name: "URL",
359
- typeGuard(v) {
360
- return `${v} instanceof URL && isGatewayUrl(${v})`;
361
- },
362
- encoder(v) {
363
- return `{ "@id": ${v}.origin }`;
364
- },
365
- compactEncoder(v) {
366
- return `${v}.origin`;
367
- },
368
- dataCheck(v) {
369
- return `${v} != null && typeof ${v} === "object" &&
370
- (("@id" in ${v} && typeof ${v}["@id"] === "string" &&
371
- ${v}["@id"] !== "" && ${v}["@id"] !== "/") ||
372
- ("@value" in ${v} && typeof ${v}["@value"] === "string" &&
373
- ${v}["@value"] !== "" && ${v}["@value"] !== "/"))`;
374
- },
375
- decoder(v) {
376
- return `parseGatewayUrl(typeof ${v}["@id"] === "string" ? ${v}["@id"] : ${v}["@value"])`;
377
- },
378
- },
379
- "fedify:publicKey": {
380
- name: "CryptoKey",
381
- typeGuard(v) {
382
- return `
383
- // @ts-ignore: CryptoKey exists in the global scope.
384
- ${v} instanceof CryptoKey
385
- `;
386
- },
387
- encoder(v) {
388
- return `{ "@value": await exportSpki(${v}) }`;
389
- },
390
- compactEncoder(v) {
391
- return `await exportSpki(${v})`;
392
- },
393
- dataCheck(v) {
394
- return `typeof ${v} === "object" && "@value" in ${v}
395
- && typeof ${v}["@value"] === "string"`;
396
- },
397
- decoder(v) {
398
- return `await importPem(${v}["@value"])`;
399
- },
400
- },
401
- "fedify:multibaseKey": {
402
- name: "CryptoKey",
403
- typeGuard(v) {
404
- return `
405
- // @ts-ignore: CryptoKey exists in the global scope.
406
- ${v} instanceof CryptoKey
407
- `;
408
- },
409
- encoder(v) {
410
- return `{
411
- "@type": "https://w3id.org/security#multibase",
412
- "@value": await exportMultibaseKey(${v}),
413
- }`;
414
- },
415
- compactEncoder(v) {
416
- return `await exportMultibaseKey(${v})`;
417
- },
418
- dataCheck(v) {
419
- return `typeof ${v} === "object" && "@value" in ${v}
420
- && typeof ${v}["@value"] === "string"`;
421
- },
422
- decoder(v) {
423
- return `await importMultibaseKey(${v}["@value"])`;
424
- },
425
- },
426
- "fedify:proofPurpose": {
427
- name:
428
- '"assertionMethod" | "authentication" | "capabilityInvocation" | ' +
429
- '"capabilityDelegation" | "keyAgreement"',
430
- typeGuard(v) {
431
- return `${v} === "assertionMethod" || ${v} === "authentication" ||
432
- ${v} === "capabilityInvocation" || ${v} === "capabilityDelegation" ||
433
- ${v} === "keyAgreement"`;
434
- },
435
- encoder(v) {
436
- return `{
437
- "@id": "https://w3id.org/security#" + ${v},
438
- }`;
439
- },
440
- compactEncoder(v) {
441
- return v;
442
- },
443
- dataCheck(v) {
444
- return `${v} != null && typeof ${v} === "object" && "@id" in ${v}
445
- && typeof ${v}["@id"] === "string"
446
- && ${v}["@id"].startsWith("https://w3id.org/security#")
447
- && [
448
- "assertionMethod", "authentication", "capabilityInvocation",
449
- "capabilityDelegation", "keyAgreement",
450
- ].includes(${v}["@id"].substring(26))`;
451
- },
452
- decoder(v) {
453
- return `${v}["@id"].substring(26)`;
454
- },
455
- },
456
- "fedify:units": {
457
- name: '"cm" | "feet" | "inches" | "km" | "m" | "miles"',
458
- typeGuard(v) {
459
- return (
460
- `${v} == "cm" || ${v} == "feet" || ${v} == "inches" ` +
461
- `|| ${v} == "km" || ${v} == "m" || ${v} == "miles"`
462
- );
463
- },
464
- encoder(v) {
465
- return `{ "@value": ${v} }`;
466
- },
467
- compactEncoder(v) {
468
- return v;
469
- },
470
- dataCheck(v) {
471
- return (
472
- `typeof ${v} === "object" && "@value" in ${v}
473
- && (${v}["@value"] == "cm" || ${v}["@value"] == "feet" ` +
474
- `|| ${v}["@value"] == "inches" || ${v}["@value"] == "km" ` +
475
- `|| ${v}["@value"] == "m" || ${v}["@value"] == "miles")`
476
- );
477
- },
478
- decoder(v) {
479
- return `${v}["@value"]`;
480
- },
481
- },
482
- "fedify:vocabEntityType": {
483
- name: "$EntityType",
484
- typeGuard(v) {
485
- return `isEntityType(${v})`;
486
- },
487
- encoder(v) {
488
- return `{ "@id": ${v}.typeId.href }`;
489
- },
490
- dataCheck(v) {
491
- return `${v} != null && typeof ${v} === "object" && "@id" in ${v}
492
- && typeof ${v}["@id"] === "string"
493
- && ${v}["@id"] !== ""`;
494
- },
495
- decoder(v) {
496
- return `(() => {
497
- if (${v} == null || typeof ${v} !== "object" || !("@id" in ${v}) ||
498
- typeof ${v}["@id"] !== "string" || ${v}["@id"] === "") {
499
- return undefined;
500
- }
501
- const entityType = getEntityTypeById(${v}["@id"]);
502
- if (entityType == null) {
503
- getLogger(["fedify", "vocab"]).warn(
504
- "Ignoring unknown vocabulary entity type reference: {typeId}",
505
- { typeId: ${v}["@id"] },
506
- );
507
- }
508
- return entityType;
509
- })()`;
510
- },
511
- },
512
- };
513
-
514
- export function getTypeName(
515
- typeUri: string,
516
- types: Record<string, TypeSchema>,
517
- ): string {
518
- if (typeUri in types) return types[typeUri].name;
519
- if (typeUri in scalarTypes) return scalarTypes[typeUri].name;
520
- throw new Error(`Unknown type: ${typeUri}`);
521
- }
522
-
523
- export function getTypeNames(
524
- typeUris: string[],
525
- types: Record<string, TypeSchema>,
526
- parentheses = false,
527
- ): string {
528
- if (typeUris.length < 1) return "never";
529
- else if (typeUris.length === 1) return getTypeName(typeUris[0], types);
530
- let typeNames = typeUris.map((typeUri) => getTypeName(typeUri, types));
531
- typeNames = typeNames.filter((t, i) => typeNames.indexOf(t) === i);
532
- const t = typeNames.join(" | ");
533
- return parentheses && typeNames.length > 1 ? `(${t})` : t;
534
- }
535
-
536
- export function isScalarType(
537
- typeUri: string,
538
- types: Record<string, TypeSchema>,
539
- ): boolean {
540
- if (typeUri in scalarTypes) return true;
541
- else if (typeUri in types) return !types[typeUri].entity;
542
- throw new Error(`Unknown type: ${typeUri}`);
543
- }
544
-
545
- export function areAllScalarTypes(
546
- typeUris: string[],
547
- types: Record<string, TypeSchema>,
548
- ): boolean {
549
- return typeUris.every((typeUri) => isScalarType(typeUri, types));
550
- }
551
-
552
- export function isCompactableType(
553
- typeUri: string,
554
- types: Record<string, TypeSchema>,
555
- ): boolean {
556
- if (typeUri in scalarTypes) {
557
- return scalarTypes[typeUri].compactEncoder != null;
558
- } else if (typeUri in types) {
559
- const type = types[typeUri];
560
- if (type.compactName == null) return false;
561
- else if (type.extends != null && !isCompactableType(type.extends, types)) {
562
- return false;
563
- }
564
- const defaultContext = type.defaultContext;
565
- return (
566
- (defaultContext != null &&
567
- HEURISTICS_CONTEXTS.includes(defaultContext as string)) ||
568
- (Array.isArray(defaultContext) &&
569
- (defaultContext as string[]).some(
570
- HEURISTICS_CONTEXTS.includes.bind(HEURISTICS_CONTEXTS),
571
- ))
572
- );
573
- }
574
- throw new Error(`Unknown type: ${typeUri}`);
575
- }
576
-
577
- export function getSubtypes(
578
- typeUri: string,
579
- types: Record<string, TypeSchema>,
580
- excludeSelf = false,
581
- ): string[] {
582
- const subtypes: string[] = excludeSelf ? [] : [typeUri];
583
- for (const uri in types) {
584
- const type = types[uri];
585
- if (type.extends === typeUri) subtypes.push(...getSubtypes(uri, types));
586
- }
587
- return subtypes.filter((t, i) => subtypes.indexOf(t) === i);
588
- }
589
-
590
- export function getSupertypes(
591
- typeUri: string,
592
- types: Record<string, TypeSchema>,
593
- excludeSelf = false,
594
- ): string[] {
595
- const supertypes: string[] = excludeSelf ? [] : [typeUri];
596
- const type = types[typeUri];
597
- if (type.extends) supertypes.push(...getSupertypes(type.extends, types));
598
- return supertypes;
599
- }
600
-
601
- export function* getAllProperties(
602
- typeUri: string,
603
- types: Record<string, TypeSchema>,
604
- excludeSelf = false,
605
- ): Iterable<PropertySchema> {
606
- for (const t of getSupertypes(typeUri, types, excludeSelf)) {
607
- if (!(t in types)) continue;
608
- for (const prop of types[t].properties) yield prop;
609
- }
610
- }
611
-
612
- export function getEncoder(
613
- typeUri: string,
614
- types: Record<string, TypeSchema>,
615
- variable: string,
616
- optionsVariable: string,
617
- compact = false,
618
- ): string {
619
- if (typeUri in scalarTypes) {
620
- return compact
621
- ? (scalarTypes[typeUri].compactEncoder?.(variable) ??
622
- scalarTypes[typeUri].encoder(variable))
623
- : scalarTypes[typeUri].encoder(variable);
624
- }
625
- if (typeUri in types) {
626
- return compact
627
- ? `await ${variable}.toJsonLd({
628
- ...(${optionsVariable}),
629
- format: undefined,
630
- context: undefined,
631
- })`
632
- : `await ${variable}.toJsonLd(${optionsVariable})`;
633
- }
634
- throw new Error(`Unknown type: ${typeUri}`);
635
- }
636
-
637
- export function getTypeGuard(
638
- typeUri: string,
639
- types: Record<string, TypeSchema>,
640
- variable: string,
641
- ): string {
642
- if (typeUri in scalarTypes) return scalarTypes[typeUri].typeGuard(variable);
643
- if (typeUri in types) return `${variable} instanceof ${types[typeUri].name}`;
644
- throw new Error(`Unknown type: ${typeUri}`);
645
- }
646
-
647
- export function getTypeGuards(
648
- typeUris: string[],
649
- types: Record<string, TypeSchema>,
650
- variable: string,
651
- ): string {
652
- return typeUris.map((t) => getTypeGuard(t, types, variable)).join(" || ");
653
- }
654
-
655
- export function* getEncoders(
656
- typeUris: string[],
657
- types: Record<string, TypeSchema>,
658
- variable: string,
659
- optionsVariable: string,
660
- compact = false,
661
- ): Iterable<string> {
662
- let i = typeUris.length;
663
- for (const typeUri of typeUris) {
664
- if (--i > 0) {
665
- yield getTypeGuard(typeUri, types, variable);
666
- yield " ? ";
667
- }
668
- yield getEncoder(typeUri, types, variable, optionsVariable, compact);
669
- if (i > 0) yield " : ";
670
- }
671
- }
672
-
673
- export function getDecoder(
674
- typeUri: string,
675
- types: Record<string, TypeSchema>,
676
- variable: string,
677
- optionsVariable: string,
678
- baseUrlVariable: string,
679
- ): string {
680
- if (typeUri in scalarTypes) {
681
- return scalarTypes[typeUri].decoder(variable, baseUrlVariable);
682
- }
683
- if (typeUri in types) {
684
- return `await ${types[typeUri].name}.fromJsonLd(
685
- ${variable},
686
- { ...${optionsVariable}, baseUrl: ${baseUrlVariable} }
687
- )`;
688
- }
689
- throw new Error(`Unknown type: ${typeUri}`);
690
- }
691
-
692
- export function skipsUnparsable(typeUri: string): boolean {
693
- return scalarTypes[typeUri]?.skipUnparsable ?? false;
694
- }
695
-
696
- export function getDataCheck(
697
- typeUri: string,
698
- types: Record<string, TypeSchema>,
699
- variable: string,
700
- ): string {
701
- if (typeUri in scalarTypes) return scalarTypes[typeUri].dataCheck(variable);
702
- if (typeUri in types) {
703
- const subtypes = getSubtypes(typeUri, types);
704
- return (
705
- `typeof ${variable} === "object" && "@type" in ${variable}
706
- && Array.isArray(${variable}["@type"])` +
707
- (subtypes.length > 1
708
- ? `&& ${JSON.stringify(subtypes)}.some(
709
- t => ${variable}["@type"].includes(t))`
710
- : `&& ${variable}["@type"].includes(${JSON.stringify(typeUri)})`)
711
- );
712
- }
713
- throw new Error(`Unknown type: ${typeUri}`);
714
- }
715
-
716
- export function* getDecoders(
717
- typeUris: string[],
718
- types: Record<string, TypeSchema>,
719
- variable: string,
720
- optionsVariable: string,
721
- baseUrlVariable: string,
722
- ): Iterable<string> {
723
- for (const typeUri of typeUris) {
724
- yield getDataCheck(typeUri, types, variable);
725
- yield " ? ";
726
- yield getDecoder(
727
- typeUri,
728
- types,
729
- variable,
730
- optionsVariable,
731
- baseUrlVariable,
732
- );
733
- yield " : ";
734
- }
735
- yield "undefined";
736
- }
737
-
738
- export function emitOverride(
739
- typeUri: string,
740
- types: Record<string, TypeSchema>,
741
- ): string {
742
- if (types[typeUri].extends == null) return "";
743
- return "override";
744
- }