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

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