@fedify/vocab-tools 2.0.36-dev.2734 → 2.0.36-dev.2760

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/class.test.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { deepStrictEqual, match } from "node:assert";
1
+ import { deepStrictEqual, match, strictEqual } from "node:assert";
2
2
  import { basename, dirname, extname, join } from "node:path";
3
3
  import { test } from "node:test";
4
4
  import metadata from "../deno.json" with { type: "json" };
5
5
  import { generateClasses, sortTopologically } from "./class.ts";
6
- import { loadSchemaFiles } from "./schema.ts";
6
+ import { loadSchemaFiles, type TypeSchema } from "./schema.ts";
7
7
 
8
8
  test("sortTopologically()", () => {
9
9
  const sorted = sortTopologically({
@@ -70,6 +70,267 @@ test("generateClasses() imports the browser-safe jsonld entrypoint", async () =>
70
70
  });
71
71
 
72
72
  if ("Deno" in globalThis) {
73
+ Deno.test("generateClasses() resolves mixed references through the parent's type scope", async () => {
74
+ const context = "https://www.w3.org/ns/activitystreams";
75
+ const uri = `${context}#Widget`;
76
+ const types: Record<string, TypeSchema> = {
77
+ [uri]: {
78
+ uri,
79
+ name: "Widget",
80
+ compactName: "Widget",
81
+ entity: true,
82
+ description: "",
83
+ defaultContext: [context, {
84
+ ref: "https://example.com/unscoped/",
85
+ Widget: {
86
+ "@id": uri,
87
+ "@context": { ref: "https://example.com/scoped/" },
88
+ },
89
+ parts: { "@id": `${context}#parts`, "@type": "@id" },
90
+ }] as unknown as TypeSchema["defaultContext"],
91
+ properties: [{
92
+ uri: `${context}#parts`,
93
+ singularName: "part",
94
+ pluralName: "parts",
95
+ compactName: "parts",
96
+ range: [uri],
97
+ description: "",
98
+ }],
99
+ },
100
+ };
101
+ const { Widget } = await importGeneratedClasses(types);
102
+ const json = await new Widget({
103
+ parts: [new Widget({}), new URL("ref:item")],
104
+ }).toJsonLd();
105
+ deepStrictEqual(json.parts[1].id, "https://example.com/scoped/item");
106
+ });
107
+ Deno.test("generateClasses() repairs the effective type-scoped property mapping", async () => {
108
+ const [{ default: jsonld }, { getDocumentLoader }] = await Promise.all([
109
+ import("../../vocab-runtime/src/jsonld.ts"),
110
+ import("../../vocab-runtime/src/docloader.ts"),
111
+ ]);
112
+ const parts = "https://example.com/scoped/parts";
113
+ const types = getScopedWidgetTypes({
114
+ ref: "https://example.com/scoped/",
115
+ parts: { "@id": parts, "@type": "@id", "@container": "@list" },
116
+ }, { propertyUri: parts, ordered: true, security: true });
117
+ const { Widget } = await importGeneratedClasses(types);
118
+ const source = {
119
+ "@context": ["https://www.w3.org/ns/activitystreams", {
120
+ proof: "https://example.com/custom-proof",
121
+ }],
122
+ type: "Note",
123
+ proof: "extension",
124
+ };
125
+ const child = new Widget({});
126
+ child.toJsonLd = () => Promise.resolve(source);
127
+ const json = await new Widget({
128
+ parts: [child, new URL("ref:item")],
129
+ }).toJsonLd();
130
+ strictEqual(json.parts[0], source);
131
+ const expanded = await jsonld.expand(json, {
132
+ documentLoader: getDocumentLoader(),
133
+ });
134
+ deepStrictEqual(expanded[0][parts][0]["@list"][1], {
135
+ "@id": "https://example.com/scoped/item",
136
+ });
137
+ deepStrictEqual(
138
+ expanded[0][parts][0]["@list"][0][
139
+ "https://example.com/custom-proof"
140
+ ],
141
+ [{ "@value": "extension" }],
142
+ );
143
+ });
144
+ for (const propagate of [false, true]) {
145
+ Deno.test(`generateClasses() preserves contextless siblings with type scope propagation ${propagate}`, async () => {
146
+ const [{ default: jsonld }, { getDocumentLoader }] = await Promise.all([
147
+ import("../../vocab-runtime/src/jsonld.ts"),
148
+ import("../../vocab-runtime/src/docloader.ts"),
149
+ ]);
150
+ const types = getScopedWidgetTypes({
151
+ ...(propagate ? { "@propagate": true } : {}),
152
+ ref: "https://example.com/scoped/",
153
+ });
154
+ const { Widget } = await importGeneratedClasses(types);
155
+ const source = Object.freeze({
156
+ "@id": "ref:contextless",
157
+ "ref:detail": [{ "@value": "detail" }],
158
+ });
159
+ const contextless = new Widget({});
160
+ contextless.toJsonLd = () => Promise.resolve(source);
161
+ const reference = Object.freeze({ "@id": "ref:reference" });
162
+ const referenceOnly = new Widget({});
163
+ referenceOnly.toJsonLd = () => Promise.resolve(reference);
164
+ const context = Object.values(types)[0].defaultContext;
165
+ const original = {
166
+ "@context": context,
167
+ type: "Widget",
168
+ parts: [await new Widget({}).toJsonLd(), source, reference, "ref:item"],
169
+ };
170
+ const json = await new Widget({
171
+ parts: [
172
+ new Widget({}),
173
+ contextless,
174
+ referenceOnly,
175
+ new URL("ref:item"),
176
+ ],
177
+ }).toJsonLd();
178
+ const loader = getDocumentLoader();
179
+ deepStrictEqual(
180
+ await jsonld.expand(json, { documentLoader: loader }),
181
+ await jsonld.expand(original, { documentLoader: loader }),
182
+ );
183
+ deepStrictEqual(source, {
184
+ "@id": "ref:contextless",
185
+ "ref:detail": [{ "@value": "detail" }],
186
+ });
187
+ deepStrictEqual(
188
+ json.parts[3].id,
189
+ "https://example.com/scoped/item",
190
+ );
191
+ });
192
+ }
193
+ Deno.test("generateClasses() keeps equal child contexts isolated from propagating type scopes", async () => {
194
+ const [{ default: jsonld }, { getDocumentLoader }] = await Promise.all([
195
+ import("../../vocab-runtime/src/jsonld.ts"),
196
+ import("../../vocab-runtime/src/docloader.ts"),
197
+ ]);
198
+ const types = getScopedWidgetTypes({
199
+ "@propagate": true,
200
+ extra: "https://example.com/extra",
201
+ });
202
+ const { Widget } = await importGeneratedClasses(types);
203
+ const context = Object.values(types)[0].defaultContext;
204
+ const source = { "@context": context, type: "Note", extra: "ignored" };
205
+ const child = new Widget({});
206
+ child.toJsonLd = () => Promise.resolve(source);
207
+ const json = await new Widget({ parts: [child] }).toJsonLd();
208
+ const loader = getDocumentLoader();
209
+ const standalone = await jsonld.expand(source, { documentLoader: loader });
210
+ const inherited = await jsonld.expand({
211
+ "@context": context,
212
+ type: "Widget",
213
+ parts: source,
214
+ }, { documentLoader: loader });
215
+ deepStrictEqual(
216
+ inherited[0]["https://www.w3.org/ns/activitystreams#parts"][0][
217
+ "https://example.com/extra"
218
+ ],
219
+ [{ "@value": "ignored" }],
220
+ );
221
+ const expanded = await jsonld.expand(json, { documentLoader: loader });
222
+ const part = expanded[0]["https://www.w3.org/ns/activitystreams#parts"][0];
223
+ deepStrictEqual(part, standalone[0]);
224
+ strictEqual(json.parts, source);
225
+ });
226
+ Deno.test("generateClasses() leaves protected type-scoped definitions unchanged", async () => {
227
+ const types = getScopedWidgetTypes({ ref: "https://example.com/scoped/" });
228
+ const context = Object.values(types)[0].defaultContext as unknown as [
229
+ string,
230
+ Record<string, Record<string, unknown>>,
231
+ ];
232
+ context[1].Widget["@protected"] = true;
233
+ const { Widget } = await importGeneratedClasses(types);
234
+ const child = new Widget({});
235
+ const json = await new Widget({
236
+ parts: [child, new URL("ref:item")],
237
+ }).toJsonLd();
238
+ deepStrictEqual(json["@context"], context);
239
+ strictEqual(json.parts[1], "ref:item");
240
+ });
241
+ Deno.test("generateClasses() preserves array and remote type scopes", async () => {
242
+ const { getDocumentLoader } = await import(
243
+ "../../vocab-runtime/src/docloader.ts"
244
+ );
245
+ const remote = "https://example.com/widget-context";
246
+ const builtinLoader = getDocumentLoader();
247
+ const contextLoader: typeof builtinLoader = (url, options) =>
248
+ url === remote
249
+ ? Promise.resolve({
250
+ contextUrl: null,
251
+ documentUrl: remote,
252
+ document: { "@context": { ref: "https://example.com/remote/" } },
253
+ })
254
+ : builtinLoader(url, options);
255
+ for (
256
+ const [scope, expected] of [
257
+ [[
258
+ { ref: "https://example.com/first/" },
259
+ { ref: "https://example.com/last/" },
260
+ ], "https://example.com/last/item"],
261
+ [remote, "https://example.com/remote/item"],
262
+ ] as const
263
+ ) {
264
+ const { Widget } = await importGeneratedClasses(
265
+ getScopedWidgetTypes(scope),
266
+ );
267
+ const json = await new Widget({
268
+ parts: [new Widget({}), new URL("ref:item")],
269
+ }).toJsonLd({ contextLoader });
270
+ strictEqual(json.parts[1].id, expected);
271
+ }
272
+ });
273
+ Deno.test("generateClasses() retains unprotected properties inside protected type scopes", async () => {
274
+ const { Widget } = await importGeneratedClasses(getScopedWidgetTypes({
275
+ "@protected": true,
276
+ ref: "https://example.com/scoped/",
277
+ parts: {
278
+ "@id": "https://www.w3.org/ns/activitystreams#parts",
279
+ "@type": "@id",
280
+ "@protected": false,
281
+ },
282
+ }));
283
+ const json = await new Widget({
284
+ parts: [new Widget({}), new URL("ref:item")],
285
+ }).toJsonLd();
286
+ strictEqual(json.parts[1].id, "https://example.com/scoped/item");
287
+ strictEqual(
288
+ json["@context"].at(-1).Widget["@context"].parts["@protected"],
289
+ false,
290
+ );
291
+ });
292
+ // Deno can compile a generated TypeScript module directly from a data URL.
293
+ Deno.test("generateClasses() preserves prefix terms when adding a scope", async () => {
294
+ const [{ default: jsonld }, { getDocumentLoader }] = await Promise.all([
295
+ import("../../vocab-runtime/src/jsonld.ts"),
296
+ import("../../vocab-runtime/src/docloader.ts"),
297
+ ]);
298
+ const context = "https://www.w3.org/ns/activitystreams";
299
+ const uri = `${context}#Widget`;
300
+ const types: Record<string, TypeSchema> = {
301
+ [uri]: {
302
+ uri,
303
+ name: "Widget",
304
+ compactName: "as:Widget",
305
+ entity: true,
306
+ description: "",
307
+ defaultContext: context as TypeSchema["defaultContext"],
308
+ properties: [{
309
+ uri: `${context}#`,
310
+ singularName: "part",
311
+ pluralName: "parts",
312
+ compactName: "as",
313
+ range: [uri],
314
+ description: "",
315
+ }],
316
+ },
317
+ };
318
+ const code = (await Array.fromAsync(generateClasses(types))).join("")
319
+ .replace(
320
+ /from\s+"([^"]+)"/g,
321
+ (_match, specifier: string) =>
322
+ `from ${JSON.stringify(import.meta.resolve(specifier))}`,
323
+ );
324
+ const { Widget } = await import(
325
+ `data:application/typescript;base64,${btoa(code)}`
326
+ );
327
+ const json = await new Widget({ parts: [new Widget({})] }).toJsonLd();
328
+ const expanded = await jsonld.expand(json, {
329
+ documentLoader: getDocumentLoader(),
330
+ });
331
+ deepStrictEqual(expanded[0]["@type"], [uri]);
332
+ await Widget.fromJsonLd(json);
333
+ });
73
334
  const { assertSnapshot } = await import("@std/testing/snapshot");
74
335
  Deno.test("generateClasses()", async (t) => {
75
336
  const entireCode = await getEntireCode();
@@ -91,6 +352,58 @@ if ("Deno" in globalThis) {
91
352
  });
92
353
  }
93
354
 
355
+ async function importGeneratedClasses(types: Record<string, TypeSchema>) {
356
+ const code = (await Array.fromAsync(generateClasses(types))).join("")
357
+ .replace(
358
+ /from\s+"([^"]+)"/g,
359
+ (_match, specifier: string) =>
360
+ `from ${JSON.stringify(import.meta.resolve(specifier))}`,
361
+ );
362
+ return await import(`data:application/typescript;base64,${btoa(code)}`);
363
+ }
364
+
365
+ function getScopedWidgetTypes(
366
+ scope: unknown,
367
+ options: { propertyUri?: string; ordered?: boolean; security?: boolean } = {},
368
+ ): Record<string, TypeSchema> {
369
+ const context = "https://www.w3.org/ns/activitystreams";
370
+ const uri = `${context}#Widget`;
371
+ const definitions = {
372
+ ref: "https://example.com/unscoped/",
373
+ Widget: { "@id": uri, "@context": scope },
374
+ parts: {
375
+ "@id": `${context}#parts`,
376
+ "@type": "@id",
377
+ ...(options.ordered ? { "@container": "@list" } : {}),
378
+ },
379
+ };
380
+ return {
381
+ [uri]: {
382
+ uri,
383
+ name: "Widget",
384
+ compactName: "Widget",
385
+ entity: true,
386
+ description: "",
387
+ defaultContext: [
388
+ context,
389
+ ...(options.security
390
+ ? ["https://w3id.org/security/data-integrity/v1"]
391
+ : []),
392
+ definitions,
393
+ ] as unknown as TypeSchema["defaultContext"],
394
+ properties: [{
395
+ uri: options.propertyUri ?? `${context}#parts`,
396
+ singularName: "part",
397
+ pluralName: "parts",
398
+ compactName: "parts",
399
+ range: [uri],
400
+ ...(options.ordered ? { container: "list" as const } : {}),
401
+ description: "",
402
+ }],
403
+ },
404
+ };
405
+ }
406
+
94
407
  async function getEntireCode() {
95
408
  const packagesDir = dirname(dirname(import.meta.dirname!));
96
409
  const schemaDir = join(packagesDir, "vocab", "src");
package/src/class.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { generateDecoder, generateEncoder } from "./codec.ts";
2
2
  import { generateCloner, generateConstructor } from "./constructor.ts";
3
+ import { generateContextHelpers } from "./context.ts";
3
4
  import { generateFields } from "./field.ts";
4
5
  import { generateInspector, generateInspectorPostClass } from "./inspector.ts";
5
6
  import { generateProperties } from "./property.ts";
@@ -184,6 +185,7 @@ function isValidLanguageTag(language: string): boolean {
184
185
  }
185
186
  `;
186
187
  yield "\n\n";
188
+ yield generateContextHelpers();
187
189
  const sorted = sortTopologically(types);
188
190
  for (const typeUri of sorted) {
189
191
  for await (const code of generateClass(typeUri, types)) yield code;
package/src/codec.ts CHANGED
@@ -53,6 +53,10 @@ export async function* generateEncoder(
53
53
  if (isCompactableType(typeUri, types)) {
54
54
  yield `
55
55
  if (options.format == null && this.isCompactable()) {
56
+ const fromSuperclass = "_fromSuperclass" in options &&
57
+ options._fromSuperclass === true;
58
+ options = { ...options };
59
+ if ("_fromSuperclass" in options) delete options._fromSuperclass;
56
60
  `;
57
61
  if (type.extends == null) {
58
62
  yield "const result: Record<string, unknown> = {};";
@@ -62,6 +66,8 @@ export async function* generateEncoder(
62
66
  ...options,
63
67
  format: undefined,
64
68
  context: undefined,
69
+ // @ts-ignore: an internal option
70
+ _fromSuperclass: true,
65
71
  }) as Record<string, unknown>;
66
72
  `;
67
73
  const selfProperties = type.properties.map((p) => p.uri);
@@ -126,11 +132,27 @@ export async function* generateEncoder(
126
132
  }
127
133
  `;
128
134
  }
135
+ const nodeTerms = new Set<string>();
136
+ for (const property of getAllProperties(typeUri, types)) {
137
+ if (!property.range.some((range) => range in types)) continue;
138
+ if (property.compactName != null) nodeTerms.add(property.compactName);
139
+ if (property.functional && property.redundantProperties != null) {
140
+ for (const redundant of property.redundantProperties) {
141
+ if (redundant.compactName != null) {
142
+ nodeTerms.add(redundant.compactName);
143
+ }
144
+ }
145
+ }
146
+ }
129
147
  yield `
130
148
  result["type"] = ${JSON.stringify(type.compactName ?? type.uri)};
131
149
  if (this.id != null) result["id"] = this.id.href;
132
150
  result["@context"] = ${JSON.stringify(type.defaultContext)};
133
- return result;
151
+ return fromSuperclass ? result : await isolateJsonLdContexts(
152
+ result,
153
+ ${JSON.stringify([...nodeTerms])},
154
+ options.contextLoader,
155
+ );
134
156
  }
135
157
  `;
136
158
  }
package/src/context.ts ADDED
@@ -0,0 +1,205 @@
1
+ /** Generates helpers for composing independent JSON-LD documents. */
2
+ export function generateContextHelpers(): string {
3
+ return `
4
+ function hasJsonLdContext(value: unknown): boolean {
5
+ if (Array.isArray(value)) return value.some(hasJsonLdContext);
6
+ return value != null && typeof value === "object" &&
7
+ globalThis.Object.hasOwn(value, "@context");
8
+ }
9
+
10
+ function hasSupportedJsonLdScalars(value: unknown, idReferences: boolean): boolean {
11
+ if (Array.isArray(value)) {
12
+ return value.every(item => hasSupportedJsonLdScalars(item, idReferences));
13
+ }
14
+ return value === null || typeof value === "object" ||
15
+ (idReferences && typeof value === "string" && URL.canParse(value));
16
+ }
17
+
18
+ function equalJsonLdValues(left: unknown, right: unknown): boolean {
19
+ if (left === right) return true;
20
+ if (Array.isArray(left) || Array.isArray(right)) {
21
+ return Array.isArray(left) && Array.isArray(right) &&
22
+ left.length === right.length &&
23
+ left.every((item, index) => equalJsonLdValues(item, right[index]));
24
+ }
25
+ if (left === null || right === null || typeof left !== "object" ||
26
+ typeof right !== "object") return false;
27
+ const leftObject = left as Record<string, unknown>;
28
+ const rightObject = right as Record<string, unknown>;
29
+ const keys = globalThis.Object.keys(leftObject);
30
+ return keys.length === globalThis.Object.keys(rightObject).length &&
31
+ keys.every(key => globalThis.Object.hasOwn(rightObject, key) &&
32
+ equalJsonLdValues(leftObject[key], rightObject[key]));
33
+ }
34
+
35
+ async function isolateJsonLdSibling(
36
+ value: unknown,
37
+ term: string,
38
+ originalContext: unknown,
39
+ repairedContext: unknown,
40
+ parentType: unknown,
41
+ typeContext: unknown,
42
+ contextLoader: DocumentLoader | undefined,
43
+ ): Promise<{ value: unknown } | undefined> {
44
+ if (Array.isArray(value)) {
45
+ const result: unknown[] = [];
46
+ for (const item of value) {
47
+ const rewritten = await isolateJsonLdSibling(
48
+ item, term, originalContext, repairedContext, parentType, typeContext,
49
+ contextLoader,
50
+ );
51
+ if (rewritten === undefined) return undefined;
52
+ result.push(rewritten.value);
53
+ }
54
+ return { value: result };
55
+ }
56
+ if (value === null) return { value };
57
+ if (typeof value === "string") {
58
+ // These references were checked against the original term's @type:@id.
59
+ // Resolve compact IRIs and @base before removing their enclosing context.
60
+ const expanded = await jsonld.expand(
61
+ { "@context": originalContext, type: parentType, "@id": value },
62
+ { documentLoader: contextLoader, keepFreeFloatingNodes: true },
63
+ );
64
+ return { value: { "@context": { id: "@id" }, id: expanded[0]["@id"] } };
65
+ }
66
+ if (typeof value !== "object" ||
67
+ globalThis.Object.hasOwn(value, "@context")) return { value };
68
+
69
+ // Comparing equal-shaped wrappers also preserves list and graph semantics.
70
+ // Keep already independent expanded sources exactly as received: adding a
71
+ // context to a signed source can invalidate its JSON canonicalization proof.
72
+ const original = await jsonld.expand(
73
+ { "@context": originalContext, type: parentType, [term]: value },
74
+ { documentLoader: contextLoader },
75
+ );
76
+ const repaired = await jsonld.expand(
77
+ { "@context": repairedContext, type: parentType, [term]: value },
78
+ { documentLoader: contextLoader },
79
+ );
80
+ if (equalJsonLdValues(original, repaired)) return { value };
81
+ const restorationContexts = [originalContext];
82
+ if (typeContext !== undefined) {
83
+ restorationContexts.push([
84
+ ...(Array.isArray(originalContext) ? originalContext : [originalContext]),
85
+ ...(Array.isArray(typeContext) ? typeContext : [typeContext]),
86
+ ]);
87
+ }
88
+ for (const context of restorationContexts) {
89
+ const restored = { ...value, "@context": context };
90
+ const expanded = await jsonld.expand(
91
+ { "@context": repairedContext, type: parentType, [term]: restored },
92
+ { documentLoader: contextLoader },
93
+ );
94
+ if (equalJsonLdValues(original, expanded)) return { value: restored };
95
+ }
96
+ // If neither context preserves the inherited meaning, keep the whole term
97
+ // unchanged rather than committing only some of its sibling rewrites.
98
+ return undefined;
99
+ }
100
+
101
+ function copyJsonLdTermDefinition(mapping: Record<string, unknown>): Record<string, unknown> {
102
+ const definition: Record<string, unknown> = {};
103
+ for (const keyword of [
104
+ "@id", "@type", "@container", "@language", "@direction", "@index",
105
+ "@nest", "@prefix",
106
+ ]) {
107
+ if (!globalThis.Object.hasOwn(mapping, keyword)) continue;
108
+ const value = mapping[keyword];
109
+ definition[keyword] = Array.isArray(value)
110
+ ? value.length === 1 && keyword === "@container" ? value[0] : [...value]
111
+ : value;
112
+ }
113
+ // The processor stores the semantic @prefix flag under an internal name.
114
+ if (mapping._prefix === true) definition["@prefix"] = true;
115
+ return definition;
116
+ }
117
+
118
+ async function isolateJsonLdContexts(
119
+ result: Record<string, unknown>,
120
+ terms: readonly string[],
121
+ contextLoader: DocumentLoader | undefined,
122
+ ): Promise<Record<string, unknown>> {
123
+ const candidates = terms.filter(term =>
124
+ globalThis.Object.hasOwn(result, term) && hasJsonLdContext(result[term])
125
+ );
126
+ if (candidates.length === 0) return result;
127
+
128
+ const originalContext = result["@context"];
129
+ const contexts = Array.isArray(originalContext)
130
+ ? originalContext
131
+ : [originalContext];
132
+ let activeContext = await jsonld.processContext(
133
+ await jsonld.processContext({}, null),
134
+ originalContext,
135
+ { documentLoader: contextLoader },
136
+ );
137
+ const parentType = result.type;
138
+ const typeMapping = typeof parentType === "string" &&
139
+ jsonld.getContextValue(activeContext, "type", "@id") === "@type"
140
+ ? jsonld.getContextValue(activeContext, parentType) as
141
+ Record<string, unknown> | null
142
+ : null;
143
+ const typeContext = typeMapping?.["@context"];
144
+ if (typeContext !== undefined) {
145
+ // A protected type definition cannot receive an augmented scoped context.
146
+ // Leave that existing boundary unchanged, just as for protected properties.
147
+ if (typeMapping!.protected === true) return result;
148
+ activeContext = await jsonld.processContext(
149
+ activeContext, typeContext, { documentLoader: contextLoader },
150
+ );
151
+ }
152
+
153
+ function repairContext(definitions: Record<string, unknown>): unknown[] {
154
+ if (typeContext === undefined) return [...contexts, definitions];
155
+ // Preserve an object scope's @propagate semantics: replacing it with an
156
+ // array would change how the published context algorithm handles the flag.
157
+ const scopedContext = typeContext !== null && typeof typeContext === "object" &&
158
+ !Array.isArray(typeContext)
159
+ ? { ...typeContext, ...definitions }
160
+ : [...(Array.isArray(typeContext) ? typeContext : [typeContext]), definitions];
161
+ return [...contexts, {
162
+ [parentType as string]: {
163
+ ...copyJsonLdTermDefinition(typeMapping!), "@context": scopedContext,
164
+ },
165
+ }];
166
+ }
167
+ let definitions: Record<string, unknown> = {};
168
+ let siblings: Record<string, unknown> = {};
169
+ for (const term of candidates) {
170
+ const mapping = jsonld.getContextValue(activeContext, term) as
171
+ Record<string, unknown> | null;
172
+ if (mapping == null || mapping.protected === true || mapping.reverse === true ||
173
+ globalThis.Object.hasOwn(mapping, "@context") ||
174
+ mapping["@type"] === "@json" || typeof mapping["@id"] !== "string" ||
175
+ mapping["@id"].startsWith("@")) continue;
176
+
177
+ // A scalar scoped reset does not override protected definitions in the
178
+ // published expansion algorithm. Check the entire property before making
179
+ // any changes; supported URL references receive their own local context.
180
+ if (!hasSupportedJsonLdScalars(result[term], mapping["@type"] === "@id")) {
181
+ continue;
182
+ }
183
+ const definition = copyJsonLdTermDefinition(mapping);
184
+ definition["@context"] = null;
185
+ if (typeContext !== null && typeof typeContext === "object" &&
186
+ !Array.isArray(typeContext) &&
187
+ (typeContext as Record<string, unknown>)["@protected"] === true) {
188
+ definition["@protected"] = false;
189
+ }
190
+ const proposedDefinitions = { ...definitions, [term]: definition };
191
+ const repairedContext = repairContext(proposedDefinitions);
192
+ const rewritten = await isolateJsonLdSibling(
193
+ result[term], term, originalContext, repairedContext, parentType, typeContext,
194
+ contextLoader,
195
+ );
196
+ if (rewritten === undefined) continue;
197
+ definitions = proposedDefinitions;
198
+ siblings = { ...siblings, [term]: rewritten.value };
199
+ }
200
+ return globalThis.Object.keys(definitions).length === 0
201
+ ? result
202
+ : { ...result, ...siblings, "@context": repairContext(definitions) };
203
+ }
204
+ `;
205
+ }