@fedify/vocab-tools 2.5.0-dev.2664 → 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/property.ts DELETED
@@ -1,754 +0,0 @@
1
- import { pascalCase } from "es-toolkit";
2
- import metadata from "../deno.json" with { type: "json" };
3
- import { getFieldName } from "./field.ts";
4
- import type { PropertySchema, TypeSchema } from "./schema.ts";
5
- import { hasSingularAccessor, isNonFunctionalProperty } from "./schema.ts";
6
- import { areAllScalarTypes, getTypeNames } from "./type.ts";
7
-
8
- function emitOverride(
9
- typeUri: string,
10
- types: Record<string, TypeSchema>,
11
- property: PropertySchema,
12
- ): string {
13
- const type = types[typeUri];
14
- let supertypeUri = type.extends;
15
- while (supertypeUri != null) {
16
- const st = types[supertypeUri];
17
- if (st.properties.find((p) => p.singularName === property.singularName)) {
18
- return "override";
19
- }
20
- supertypeUri = st.extends;
21
- }
22
- return "";
23
- }
24
-
25
- async function* generateProperty(
26
- type: TypeSchema,
27
- property: PropertySchema,
28
- types: Record<string, TypeSchema>,
29
- moduleVarNames: ReadonlyMap<string, string>,
30
- ): AsyncIterable<string> {
31
- const override = emitOverride(type.uri, types, property);
32
- const trustOwner = type.trustEmbeddedObjects === false ? "null" : "this.id";
33
- const doc = `\n/** ${property.description.replaceAll("\n", "\n * ")}\n */\n`;
34
- const cachedPropertyBaseUrl = `(options as { baseUrl?: URL }).baseUrl ??
35
- this._baseUrl ??
36
- (this.id != null &&
37
- (this.id.protocol === "http:" ||
38
- this.id.protocol === "https:")
39
- ? this.id
40
- : undefined)`;
41
- if (areAllScalarTypes(property.range, types)) {
42
- if (hasSingularAccessor(property)) {
43
- yield doc;
44
- yield `${override} get ${property.singularName}(): (${
45
- getTypeNames(property.range, types)
46
- } | null) {
47
- if (this._warning != null) {
48
- getLogger(this._warning.category).warn(
49
- this._warning.message,
50
- this._warning.values
51
- );
52
- }
53
- if (this.${await getFieldName(property.uri)}.length < 1) return null;
54
- return this.${await getFieldName(property.uri)}[0];
55
- }
56
- `;
57
- }
58
- if (isNonFunctionalProperty(property)) {
59
- yield doc;
60
- yield `get ${property.pluralName}(): (${
61
- getTypeNames(property.range, types, true)
62
- })[] {
63
- return this.${await getFieldName(property.uri)};
64
- }
65
- `;
66
- }
67
- } else {
68
- yield `
69
- async #fetch${pascalCase(property.singularName)}(
70
- url: URL,
71
- options: {
72
- documentLoader?: DocumentLoader,
73
- contextLoader?: DocumentLoader,
74
- suppressError?: boolean,
75
- tracerProvider?: TracerProvider,
76
- crossOrigin?: "ignore" | "throw" | "trust";
77
- gateways?: readonly (string | URL)[];
78
- verifyPortableObject?: PortableObjectVerifier;
79
- inheritPortableObjectVerifier?: boolean;
80
- } = {},
81
- ): Promise<${getTypeNames(property.range, types)} | null> {
82
- const documentLoader =
83
- options.documentLoader ?? this._documentLoader ?? getDocumentLoader();
84
- const contextLoader =
85
- options.contextLoader ?? this._contextLoader ?? getDocumentLoader();
86
- const tracerProvider = options.tracerProvider ??
87
- this._tracerProvider ?? trace.getTracerProvider();
88
- const tracer = tracerProvider.getTracer(
89
- ${JSON.stringify(metadata.name)},
90
- ${JSON.stringify(metadata.version)},
91
- );
92
- // The fetched object uses the verifier given to this call (which falls
93
- // back to the parent's own default) for its accessors by default,
94
- // unless the call keeps its verifier to itself:
95
- const childVerifier = options.inheritPortableObjectVerifier === false
96
- ? this._verifyPortableObject
97
- : options.verifyPortableObject;
98
- return await tracer.startActiveSpan("activitypub.lookup_object", async (span) => {
99
- const dereferencePortable = async (
100
- portableUrl: URL,
101
- extra: {
102
- inferredGateways?: readonly URL[];
103
- response?: RemoteDocument;
104
- contextLoader?: DocumentLoader;
105
- } = {},
106
- ) => {
107
- try {
108
- const obj = await dereferencePortableIri(portableUrl, {
109
- documentLoader,
110
- contextLoader: extra.contextLoader ?? contextLoader,
111
- tracerProvider,
112
- gateways: options.gateways,
113
- inferredGateways: extra.inferredGateways,
114
- response: extra.response,
115
- verifyPortableObject: options.verifyPortableObject,
116
- referrer: {
117
- object: this,
118
- property: ${JSON.stringify(property.uri)},
119
- },
120
- suppressError: options.suppressError,
121
- crossOrigin: options.crossOrigin,
122
- span,
123
- parse: (document, parseOptions) =>
124
- this.#${property.singularName}_fromJsonLd(document, {
125
- documentLoader,
126
- contextLoader: parseOptions.contextLoader,
127
- tracerProvider,
128
- verifyPortableObject: childVerifier,
129
- baseUrl: parseOptions.baseUrl,
130
- }),
131
- });
132
- if (obj != null) {
133
- span.setAttribute(
134
- "activitypub.object.id",
135
- (obj.id ?? portableUrl).href,
136
- );
137
- span.setAttribute(
138
- "activitypub.object.type",
139
- // @ts-ignore: obj.constructor always has a typeId.
140
- obj.constructor.typeId.href
141
- );
142
- }
143
- return obj;
144
- } catch (e) {
145
- span.setStatus({
146
- code: SpanStatusCode.ERROR,
147
- message: String(e),
148
- });
149
- throw e;
150
- } finally {
151
- span.end();
152
- }
153
- };
154
- if (isPortableIri(url)) {
155
- // A reference in a portable actor's own document, e.g., its outbox,
156
- // has no location hints, so the actor's gateways are used instead:
157
- return await dereferencePortable(
158
- url,
159
- options.gateways == null
160
- ? { inferredGateways: getReferrerGateways(this, url) }
161
- : {},
162
- );
163
- }
164
- const lookupUrl = formatIri(url);
165
- const portableMode = isPortableMode(this, options);
166
- if (portableMode) {
167
- const compatible = parseCompatibleEf61Reference(url);
168
- if (compatible === null) {
169
- span.end();
170
- return rejectMalformedCompatibleReference(lookupUrl, options);
171
- } else if (compatible != null) {
172
- return await dereferencePortable(compatible.id, {
173
- inferredGateways: [compatible.gateway],
174
- });
175
- }
176
- }
177
- let fetchResult: RemoteDocument;
178
- try {
179
- fetchResult = await documentLoader(lookupUrl, {
180
- suppressError: options.suppressError,
181
- });
182
- } catch (error) {
183
- span.setStatus({
184
- code: SpanStatusCode.ERROR,
185
- message: String(error),
186
- });
187
- span.end();
188
- if (options.suppressError) {
189
- getLogger(["fedify", "vocab"]).warn(
190
- "Failed to fetch {url}: {error}",
191
- { error, url: lookupUrl }
192
- );
193
- return null;
194
- }
195
- throw error;
196
- }
197
- const { document, documentUrl } = fetchResult;
198
- // In portable mode, the document may turn out to be a portable object,
199
- // which has to be verified with the same context documents:
200
- const snapshot = portableMode
201
- ? createSnapshotContextLoader(contextLoader, options.suppressError)
202
- : null;
203
- const scopedContext = createScopedContextLoader(
204
- snapshot?.loader ?? contextLoader,
205
- snapshot == null && options.suppressError,
206
- );
207
- try {
208
- let claim: PortableResponseClaim | null | undefined;
209
- try {
210
- const baseUrl = parseIri(documentUrl);
211
- const obj = await this.#${property.singularName}_fromJsonLd(
212
- document,
213
- {
214
- documentLoader,
215
- contextLoader: scopedContext.loader,
216
- tracerProvider,
217
- verifyPortableObject: childVerifier,
218
- baseUrl,
219
- }
220
- );
221
- if (snapshot == null) {
222
- markUnverifiedPortableClaim(obj, url, documentUrl);
223
- } else {
224
- claim = getPortableResponseClaim(documentUrl, obj.id);
225
- }
226
- if (claim === undefined) {
227
- if (
228
- obj?.id != null &&
229
- !isTrustedIriOrigin(options, obj.id, baseUrl)
230
- ) {
231
- if (options.crossOrigin === "throw") {
232
- throw new Error(
233
- "The object's @id (" + obj.id.href + ") has a different origin " +
234
- "than the document URL (" + baseUrl.href + "); refusing to return " +
235
- "the object. If you want to bypass this check and are aware of" +
236
- 'the security implications, set the crossOrigin option to "trust".'
237
- );
238
- }
239
- getLogger(["fedify", "vocab"]).warn(
240
- "The object's @id ({objectId}) has a different origin than the document " +
241
- "URL ({documentUrl}); refusing to return the object. If you want to " +
242
- "bypass this check and are aware of the security implications, " +
243
- 'set the crossOrigin option to "trust".',
244
- { ...fetchResult, objectId: obj.id.href },
245
- );
246
- span.end();
247
- return null;
248
- }
249
- span.setAttribute("activitypub.object.id", (obj.id ?? url).href);
250
- span.setAttribute(
251
- "activitypub.object.type",
252
- // @ts-ignore: obj.constructor always has a typeId.
253
- obj.constructor.typeId.href
254
- );
255
- span.end();
256
- return obj;
257
- }
258
- } catch (e) {
259
- if (options.suppressError) {
260
- getLogger(["fedify", "vocab"]).warn(
261
- "Failed to parse {url}: {error}",
262
- { error: e, url: lookupUrl }
263
- );
264
- span.end();
265
- return null;
266
- }
267
- span.setStatus({
268
- code: SpanStatusCode.ERROR,
269
- message: String(e),
270
- });
271
- span.end();
272
- throw e;
273
- }
274
- // The document stands for a portable object, so it is verified as
275
- // one instead of being trusted because of where it came from:
276
- if (claim === null) {
277
- span.end();
278
- return rejectMalformedCompatibleReference(documentUrl, options);
279
- }
280
- return await dereferencePortable(claim.id, {
281
- inferredGateways: claim.inferredGateways,
282
- response: fetchResult,
283
- contextLoader: snapshot?.loader,
284
- });
285
- } finally {
286
- scopedContext.release();
287
- snapshot?.release();
288
- }
289
- });
290
- }
291
-
292
- async #${property.singularName}_fromJsonLd(
293
- jsonLd: unknown,
294
- options: {
295
- documentLoader?: DocumentLoader,
296
- contextLoader?: DocumentLoader,
297
- tracerProvider?: TracerProvider,
298
- verifyPortableObject?: PortableObjectVerifier,
299
- baseUrl?: URL
300
- }
301
- ): Promise<${getTypeNames(property.range, types)}> {
302
- const documentLoader =
303
- options.documentLoader ?? this._documentLoader ?? getDocumentLoader();
304
- const contextLoader =
305
- options.contextLoader ?? this._contextLoader ?? getDocumentLoader();
306
- const tracerProvider = options.tracerProvider ??
307
- this._tracerProvider ?? trace.getTracerProvider();
308
- const baseUrl = options.baseUrl;
309
- const verifyPortableObject = options.verifyPortableObject;
310
- `;
311
- if (
312
- property.preprocessors != null &&
313
- property.preprocessors.length > 0
314
- ) {
315
- yield `
316
- if (jsonLd != null && typeof jsonLd === "object") {
317
- const _expanded = await jsonld.expand(jsonLd, {
318
- documentLoader: contextLoader,
319
- keepFreeFloatingNodes: true,
320
- });
321
- for (const _pp_obj of _expanded) {
322
- `;
323
- for (const pp of property.preprocessors) {
324
- const varName = moduleVarNames.get(pp.module);
325
- if (varName == null) {
326
- throw new Error(
327
- `Preprocessor module "${pp.module}" is not registered ` +
328
- `in the generated imports. Ensure all preprocessor ` +
329
- `modules used in property schemas are available.`,
330
- );
331
- }
332
- yield `
333
- {
334
- const _result = await ${varName}[${
335
- JSON.stringify(pp.function)
336
- }](_pp_obj, {
337
- documentLoader,
338
- contextLoader,
339
- tracerProvider,
340
- verifyPortableObject,
341
- baseUrl,
342
- });
343
- if (_result instanceof Error) throw _result;
344
- if (_result !== undefined) return _result as ${
345
- getTypeNames(property.range, types)
346
- };
347
- }
348
- `;
349
- }
350
- yield `
351
- }
352
- }
353
- `;
354
- }
355
- for (const range of property.range) {
356
- if (!(range in types)) continue;
357
- const rangeType = types[range];
358
- yield `
359
- try {
360
- return await ${rangeType.name}.fromJsonLd(
361
- jsonLd,
362
- {
363
- documentLoader,
364
- contextLoader,
365
- tracerProvider,
366
- verifyPortableObject,
367
- baseUrl,
368
- },
369
- );
370
- } catch (e) {
371
- if (!(e instanceof TypeError)) throw e;
372
- }
373
- `;
374
- }
375
- yield `
376
- throw new TypeError("Expected an object of any type of: " +
377
- ${JSON.stringify(property.range)}.join(", "));
378
- }
379
-
380
- `;
381
- if (hasSingularAccessor(property)) {
382
- yield `
383
- /**
384
- * Similar to
385
- * {@link ${type.name}.get${pascalCase(property.singularName)}},
386
- * but returns its \`@id\` URL instead of the object itself.
387
- */
388
- ${override} get ${property.singularName}Id(): URL | null {
389
- if (this._warning != null) {
390
- getLogger(this._warning.category).warn(
391
- this._warning.message,
392
- this._warning.values
393
- );
394
- }
395
- if (this.${await getFieldName(property.uri)}.length < 1) return null;
396
- const v = this.${await getFieldName(property.uri)}[0];
397
- if (v instanceof URL) return v;
398
- return v.id;
399
- }
400
- `;
401
- yield doc;
402
- yield `
403
- ${override} async get${pascalCase(property.singularName)}(
404
- options: {
405
- documentLoader?: DocumentLoader,
406
- contextLoader?: DocumentLoader,
407
- suppressError?: boolean,
408
- tracerProvider?: TracerProvider,
409
- crossOrigin?: "ignore" | "throw" | "trust";
410
- gateways?: readonly (string | URL)[];
411
- verifyPortableObject?: PortableObjectVerifier;
412
- /**
413
- * Whether objects that this call newly fetches use the
414
- * \`verifyPortableObject\` option of this call as their default
415
- * verifier. Defaults to \`true\`. If \`false\`, the option
416
- * applies to this call only, and fetched objects use this object's
417
- * own default verifier, if any, as their default instead. Pass
418
- * \`false\` for a temporary verifier, e.g., one that accepts
419
- * everything. Objects that were already cached in this object or
420
- * embedded in it keep their defaults either way, and this option
421
- * itself is not passed on.
422
- * @since 2.4.0
423
- */
424
- inheritPortableObjectVerifier?: boolean;
425
- } = {}
426
- ): Promise<${getTypeNames(property.range, types)} | null> {
427
- if (this._warning != null) {
428
- getLogger(this._warning.category).warn(
429
- this._warning.message,
430
- this._warning.values
431
- );
432
- }
433
- if (this.${await getFieldName(property.uri)}.length < 1) return null;
434
- if (
435
- options.verifyPortableObject == null &&
436
- this._verifyPortableObject != null
437
- ) {
438
- options = {
439
- ...options,
440
- verifyPortableObject: this._verifyPortableObject,
441
- };
442
- }
443
- let v = this.${await getFieldName(property.uri)}[0];
444
- if (!(v instanceof URL) &&
445
- !(0 < (this.${await getFieldName(
446
- property.uri,
447
- "#_trust",
448
- )}[vocabTrustPrefix] ?? 0) ||
449
- this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
450
- if (v.id == null) {
451
- if (isUnsecuredPortableObject(this)) {
452
- warnUnverifiableEmbeddedObject(this, ${
453
- JSON.stringify(property.uri)
454
- });
455
- return null;
456
- }
457
- } else if (
458
- !isTrustedIriOrigin(options, v.id, ${trustOwner}) ||
459
- isUnsecuredPortableObject(this) ||
460
- mustDereferencePortableObject(this, ${trustOwner}, v.id, options)
461
- ) {
462
- v = v.id;
463
- }
464
- }
465
- if (v instanceof URL) {
466
- const fetched =
467
- await this.#fetch${pascalCase(property.singularName)}(v, options);
468
- if (fetched == null) return null;
469
- // Not cached, so that it is verified when the portable object
470
- // policy applies later:
471
- if (isUnverifiedPortableClaim(fetched)) return fetched;
472
- this.${await getFieldName(property.uri)}[0] = fetched;
473
- this.${await getFieldName(property.uri, "#_trust")}.add(0);
474
- this._cachedJsonLd = undefined;
475
- recordPortableReferrer(this, fetched, ${
476
- JSON.stringify(property.uri)
477
- });
478
- return fetched;
479
- }
480
- `;
481
- if (property.compactName != null) {
482
- yield `
483
- if (
484
- this._cachedJsonLd != null &&
485
- typeof this._cachedJsonLd === "object" &&
486
- "@context" in this._cachedJsonLd &&
487
- ${JSON.stringify(property.compactName)} in this._cachedJsonLd
488
- ) {
489
- const prop = this._cachedJsonLd[
490
- ${JSON.stringify(property.compactName)}];
491
- const doc = Array.isArray(prop) ? prop[0] : prop;
492
- if (doc != null && typeof doc === "object" && "@context" in doc) {
493
- try {
494
- v = await this.#${property.singularName}_fromJsonLd(doc, {
495
- ...options,
496
- // Keep the parent default for embedded objects.
497
- verifyPortableObject: this._verifyPortableObject,
498
- baseUrl: ${cachedPropertyBaseUrl},
499
- });
500
- } catch (error) {
501
- if (!options.suppressError) throw error;
502
- getLogger(["fedify", "vocab"]).debug(
503
- "Failed to parse embedded value of {property}: {error}",
504
- { property: ${JSON.stringify(property.uri)}, error },
505
- );
506
- return null;
507
- }
508
- }
509
- }
510
- `;
511
- }
512
- yield `
513
- if (v?.id != null &&
514
- ((${
515
- type.trustEmbeddedObjects === false ? "" : "this.id != null && "
516
- }!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
517
- isUnsecuredPortableObject(this) ||
518
- mustDereferencePortableObject(
519
- this, ${trustOwner}, v.id, options,
520
- )) &&
521
- !(0 < (this.${await getFieldName(
522
- property.uri,
523
- "#_trust",
524
- )}[vocabTrustPrefix] ?? 0) ||
525
- this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
526
- if (options.crossOrigin === "throw") {
527
- throw new Error(
528
- "The property object's @id (" + v.id.href + ") has a different " +
529
- "origin than the property owner's @id (" + ${
530
- type.trustEmbeddedObjects === false
531
- ? '"untrusted metadata"'
532
- : "(this.id?.href ?? null)"
533
- } + "); " +
534
- "refusing to return the object. If you want to bypass this " +
535
- "check and are aware of the security implications, set the " +
536
- 'crossOrigin option to "trust".'
537
- );
538
- }
539
- getLogger(["fedify", "vocab"]).warn(
540
- "The property object's @id ({objectId}) has a different origin " +
541
- "than the property owner's @id ({parentObjectId}); refusing to " +
542
- "return the object. If you want to bypass this check and are " +
543
- "aware of the security implications, set the crossOrigin option " +
544
- 'to "trust".',
545
- { objectId: v.id.href, parentObjectId: ${
546
- type.trustEmbeddedObjects === false
547
- ? '"untrusted metadata"'
548
- : "(this.id?.href ?? null)"
549
- } },
550
- );
551
- return null;
552
- }
553
- recordPortableReferrer(this, v, ${JSON.stringify(property.uri)});
554
- return v;
555
- }
556
- `;
557
- }
558
- if (isNonFunctionalProperty(property)) {
559
- yield `
560
- /**
561
- * Similar to
562
- * {@link ${type.name}.get${pascalCase(property.pluralName)}},
563
- * but returns their \`@id\`s instead of the objects themselves.
564
- */
565
- ${override} get ${property.singularName}Ids(): URL[] {
566
- if (this._warning != null) {
567
- getLogger(this._warning.category).warn(
568
- this._warning.message,
569
- this._warning.values
570
- );
571
- }
572
- return this.${await getFieldName(property.uri)}.map((v) =>
573
- v instanceof URL ? v : v.id!
574
- ).filter(id => id !== null);
575
- }
576
- `;
577
- yield doc;
578
- yield `
579
- ${override} async* get${pascalCase(property.pluralName)}(
580
- options: {
581
- documentLoader?: DocumentLoader,
582
- contextLoader?: DocumentLoader,
583
- suppressError?: boolean,
584
- tracerProvider?: TracerProvider,
585
- crossOrigin?: "ignore" | "throw" | "trust";
586
- gateways?: readonly (string | URL)[];
587
- verifyPortableObject?: PortableObjectVerifier;
588
- /**
589
- * Whether objects that this call newly fetches use the
590
- * \`verifyPortableObject\` option of this call as their default
591
- * verifier. Defaults to \`true\`. If \`false\`, the option
592
- * applies to this call only, and fetched objects use this object's
593
- * own default verifier, if any, as their default instead. Pass
594
- * \`false\` for a temporary verifier, e.g., one that accepts
595
- * everything. Objects that were already cached in this object or
596
- * embedded in it keep their defaults either way, and this option
597
- * itself is not passed on.
598
- * @since 2.4.0
599
- */
600
- inheritPortableObjectVerifier?: boolean;
601
- } = {}
602
- ): AsyncIterable<${getTypeNames(property.range, types)}> {
603
- if (this._warning != null) {
604
- getLogger(this._warning.category).warn(
605
- this._warning.message,
606
- this._warning.values
607
- );
608
- }
609
- if (
610
- options.verifyPortableObject == null &&
611
- this._verifyPortableObject != null
612
- ) {
613
- options = {
614
- ...options,
615
- verifyPortableObject: this._verifyPortableObject,
616
- };
617
- }
618
- const vs = this.${await getFieldName(property.uri)};
619
- for (let i = 0; i < vs.length; i++) {
620
- let v = vs[i];
621
- if (!(v instanceof URL) &&
622
- !(i < (this.${await getFieldName(
623
- property.uri,
624
- "#_trust",
625
- )}[vocabTrustPrefix] ?? 0) ||
626
- this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
627
- if (v.id == null) {
628
- if (isUnsecuredPortableObject(this)) {
629
- warnUnverifiableEmbeddedObject(this, ${
630
- JSON.stringify(property.uri)
631
- });
632
- continue;
633
- }
634
- } else if (
635
- !isTrustedIriOrigin(options, v.id, ${trustOwner}) ||
636
- isUnsecuredPortableObject(this) ||
637
- mustDereferencePortableObject(this, ${trustOwner}, v.id, options)
638
- ) {
639
- v = v.id;
640
- }
641
- }
642
- if (v instanceof URL) {
643
- const fetched =
644
- await this.#fetch${pascalCase(property.singularName)}(v, options);
645
- if (fetched == null) continue;
646
- // Not cached, so that it is verified when the portable object
647
- // policy applies later:
648
- if (isUnverifiedPortableClaim(fetched)) {
649
- yield fetched;
650
- continue;
651
- }
652
- vs[i] = fetched;
653
- this.${await getFieldName(property.uri, "#_trust")}.add(i);
654
- this._cachedJsonLd = undefined;
655
- recordPortableReferrer(this, fetched, ${
656
- JSON.stringify(property.uri)
657
- });
658
- yield fetched;
659
- continue;
660
- }
661
- `;
662
- if (property.compactName != null) {
663
- yield `
664
- if (
665
- this._cachedJsonLd != null &&
666
- typeof this._cachedJsonLd === "object" &&
667
- "@context" in this._cachedJsonLd &&
668
- ${JSON.stringify(property.compactName)} in this._cachedJsonLd
669
- ) {
670
- const prop = this._cachedJsonLd[
671
- ${JSON.stringify(property.compactName)}];
672
- const obj = Array.isArray(prop) ? prop[i] : prop;
673
- if (obj != null && typeof obj === "object" && "@context" in obj) {
674
- try {
675
- v = await this.#${property.singularName}_fromJsonLd(obj, {
676
- ...options,
677
- // Keep the parent default for embedded objects.
678
- verifyPortableObject: this._verifyPortableObject,
679
- baseUrl: ${cachedPropertyBaseUrl},
680
- });
681
- } catch (error) {
682
- if (!options.suppressError) throw error;
683
- getLogger(["fedify", "vocab"]).debug(
684
- "Failed to parse embedded value of {property} at index {index}: {error}",
685
- { property: ${
686
- JSON.stringify(property.uri)
687
- }, index: i, error },
688
- );
689
- continue;
690
- }
691
- }
692
- }
693
- `;
694
- }
695
- yield `
696
- if (v?.id != null &&
697
- ((${
698
- type.trustEmbeddedObjects === false ? "" : "this.id != null && "
699
- }!isTrustedIriOrigin(options, v.id, ${trustOwner})) ||
700
- isUnsecuredPortableObject(this) ||
701
- mustDereferencePortableObject(
702
- this, ${trustOwner}, v.id, options,
703
- )) &&
704
- !(i < (this.${await getFieldName(
705
- property.uri,
706
- "#_trust",
707
- )}[vocabTrustPrefix] ?? 0) ||
708
- this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
709
- if (options.crossOrigin === "throw") {
710
- throw new Error(
711
- "The property object's @id (" + v.id.href + ") has a different " +
712
- "origin than the property owner's @id (" + ${
713
- type.trustEmbeddedObjects === false
714
- ? '"untrusted metadata"'
715
- : "(this.id?.href ?? null)"
716
- } + "); " +
717
- "refusing to return the object. If you want to bypass this " +
718
- "check and are aware of the security implications, set the " +
719
- 'crossOrigin option to "trust".'
720
- );
721
- }
722
- getLogger(["fedify", "vocab"]).warn(
723
- "The property object's @id ({objectId}) has a different origin " +
724
- "than the property owner's @id ({parentObjectId}); refusing to " +
725
- "return the object. If you want to bypass this check and are " +
726
- "aware of the security implications, set the crossOrigin " +
727
- 'option to "trust".',
728
- { objectId: v.id.href, parentObjectId: ${
729
- type.trustEmbeddedObjects === false
730
- ? '"untrusted metadata"'
731
- : "(this.id?.href ?? null)"
732
- } },
733
- );
734
- continue;
735
- }
736
- recordPortableReferrer(this, v, ${JSON.stringify(property.uri)});
737
- yield v;
738
- }
739
- }
740
- `;
741
- }
742
- }
743
- }
744
-
745
- export async function* generateProperties(
746
- typeUri: string,
747
- types: Record<string, TypeSchema>,
748
- moduleVarNames: ReadonlyMap<string, string>,
749
- ): AsyncIterable<string> {
750
- const type = types[typeUri];
751
- for (const property of type.properties) {
752
- yield* generateProperty(type, property, types, moduleVarNames);
753
- }
754
- }