@deepseek-ai/cordis-plugin-loader 1.0.1-rc.1

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/lib/index.js ADDED
@@ -0,0 +1,758 @@
1
+ import { createRequire } from "node:module";
2
+ import { Context, Inject, Service, composeError } from "@deepseek-ai/cordis";
3
+ import { deepEqual, defineProperty, isNonNullable, isNullable, valueMap } from "@deepseek-ai/cosmokit";
4
+ //#region lib/types/internal.js
5
+ /** Helpers for locating the current Node internal module loader. */
6
+ var ModuleLoader;
7
+ (function(ModuleLoader) {
8
+ let _cachedLoader;
9
+ function requireInternal(id) {
10
+ const require = createRequire(import.meta.url);
11
+ if (process.execArgv.includes("--expose-internals")) try {
12
+ return require(id);
13
+ } catch {}
14
+ try {
15
+ return require("node-addon-require-builtin").requireBuiltin(id);
16
+ } catch {}
17
+ }
18
+ function fromInternal() {
19
+ if (_cachedLoader) return _cachedLoader;
20
+ const [major] = process.versions.node.split(".").map(Number);
21
+ if (major >= 24) {
22
+ const raw = requireInternal("internal/modules/esm/loader")?.getOrInitializeCascadedLoader();
23
+ if (raw) return _cachedLoader = Object.assign(raw, { version: "v2" });
24
+ } else if (major >= 22) {
25
+ const raw = requireInternal("internal/modules/esm/loader")?.getOrInitializeCascadedLoader();
26
+ if (raw) return _cachedLoader = Object.assign(raw, { version: "v1" });
27
+ }
28
+ }
29
+ ModuleLoader.fromInternal = fromInternal;
30
+ })(ModuleLoader || (ModuleLoader = {}));
31
+ //#endregion
32
+ //#region lib/types/config/group.js
33
+ /** Runtime owner for a list of child loader entries. */
34
+ var EntryGroup = class {
35
+ ctx;
36
+ tree;
37
+ static key = Symbol.for("cordis.group");
38
+ data = [];
39
+ constructor(ctx, tree) {
40
+ this.ctx = ctx;
41
+ this.tree = tree;
42
+ const entry = ctx.fiber.entry;
43
+ if (entry) entry.subgroup = this;
44
+ }
45
+ get context() {
46
+ return this.ctx;
47
+ }
48
+ async create(options) {
49
+ const id = this.tree.ensureId(options);
50
+ const existing = this.tree.store[id];
51
+ const entry = existing ?? (this.tree.store[id] = new Entry(this.ctx.loader));
52
+ const previousParent = entry.parent;
53
+ entry.parent = this;
54
+ try {
55
+ await entry.update(options, true, true);
56
+ } catch (error) {
57
+ if (existing) entry.parent = previousParent;
58
+ else delete this.tree.store[id];
59
+ throw error;
60
+ }
61
+ return entry.id;
62
+ }
63
+ unlink(options) {
64
+ const config = this.data;
65
+ const index = config.indexOf(options);
66
+ if (index >= 0) config.splice(index, 1);
67
+ }
68
+ async remove(id, isDispose = false) {
69
+ const entry = this.tree.store[id];
70
+ if (!entry) return;
71
+ await entry._dispose();
72
+ if (!isDispose) this.unlink(entry.options);
73
+ delete this.tree.store[id];
74
+ this.context.emit("loader/partial-dispose", entry, entry.options, false);
75
+ }
76
+ async update(config) {
77
+ const oldConfig = this.data;
78
+ const seen = /* @__PURE__ */ new Set();
79
+ for (const options of config) {
80
+ const id = this.tree.ensureId(options);
81
+ if (seen.has(id)) throw new TypeError(`duplicate loader entry id: ${id}`);
82
+ seen.add(id);
83
+ }
84
+ const oldMap = Object.fromEntries(oldConfig.map((options) => [options.id, options]));
85
+ const newMap = Object.fromEntries(config.map((options) => [options.id, options]));
86
+ try {
87
+ const outcomes = await Promise.allSettled(config.map((options) => this.create(options)));
88
+ if (this.ctx.fiber.uid === null) return;
89
+ const failures = outcomes.filter((outcome) => outcome.status === "rejected").map((outcome) => outcome.reason);
90
+ if (failures.length === 1) throw failures[0];
91
+ if (failures.length > 1) throw new AggregateError(failures, "loader entries failed to apply");
92
+ for (const id of Object.keys(oldMap)) if (!newMap[id]) await this.remove(id, true);
93
+ this.data = config;
94
+ } catch (error) {
95
+ const rollbackErrors = [];
96
+ for (const id of Object.keys(newMap).reverse()) {
97
+ if (oldMap[id]) continue;
98
+ try {
99
+ await this.remove(id, true);
100
+ } catch (rollbackError) {
101
+ rollbackErrors.push(rollbackError);
102
+ }
103
+ }
104
+ for (const options of oldConfig) try {
105
+ await this.create(options);
106
+ } catch (rollbackError) {
107
+ rollbackErrors.push(rollbackError);
108
+ }
109
+ this.data = oldConfig;
110
+ if (rollbackErrors.length) throw new AggregateError([error, ...rollbackErrors], "loader entry rollback failed");
111
+ throw error;
112
+ }
113
+ }
114
+ async stop() {
115
+ for (const options of this.data) await this.remove(options.id, true);
116
+ }
117
+ };
118
+ /** Plugin that mounts a nested loader entry group. */
119
+ var Group = class extends EntryGroup {
120
+ ctx;
121
+ config;
122
+ static initial = [];
123
+ static [EntryGroup.key] = true;
124
+ constructor(ctx, config) {
125
+ super(ctx, ctx.fiber.entry.parent.tree);
126
+ this.ctx = ctx;
127
+ this.config = config;
128
+ ctx.on("internal/update", (config) => this.update(config));
129
+ }
130
+ async *[Service.init]() {
131
+ yield () => this.stop();
132
+ await this.update(this.config);
133
+ }
134
+ };
135
+ //#endregion
136
+ //#region lib/types/config/tree.js
137
+ var __rewriteRelativeImportExtension = function(path, preserveJsx) {
138
+ if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
139
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
140
+ });
141
+ return path;
142
+ };
143
+ /** Mutable tree of loader entries. Persistence is supplied by subclasses. */
144
+ var EntryTree = class EntryTree {
145
+ static sep = ":";
146
+ ctx;
147
+ enableLogs;
148
+ root;
149
+ store = Object.create(null);
150
+ constructor(ctx) {
151
+ this.ctx = ctx.extend({ baseUrl: ctx.baseUrl });
152
+ this.root = new EntryGroup(this.ctx, this);
153
+ const entry = this.ctx.fiber.entry;
154
+ if (entry) entry.subtree = this;
155
+ }
156
+ get context() {
157
+ return this.ctx;
158
+ }
159
+ /** Iterate entries in this tree and any nested subtrees. */
160
+ *entries() {
161
+ for (const entry of Object.values(this.store)) {
162
+ yield entry;
163
+ if (!entry.subtree) continue;
164
+ yield* entry.subtree.entries();
165
+ }
166
+ }
167
+ /** Return pending import and lifecycle tasks owned by this tree. */
168
+ getTasks() {
169
+ return [...this.entries()].map((entry) => entry._initTask || entry.fiber?.inertia).filter(isNonNullable);
170
+ }
171
+ /**
172
+ * Wait until this tree has no active import or lifecycle tasks.
173
+ * @throws a settled fiber failure, or an aggregate when several fibers failed.
174
+ */
175
+ async await() {
176
+ while (true) {
177
+ const tasks = this.getTasks();
178
+ if (tasks.length) {
179
+ await Promise.allSettled(tasks);
180
+ continue;
181
+ }
182
+ const failures = (await Promise.allSettled([...this.entries()].map((entry) => entry._await()))).filter((outcome) => outcome.status === "rejected").map((outcome) => outcome.reason);
183
+ if (failures.length === 1) throw failures[0];
184
+ if (failures.length > 1) throw new AggregateError(failures, "loader fibers failed");
185
+ this.ctx.reflect.notify(["loader"]);
186
+ if (!this.getTasks().length) return;
187
+ }
188
+ }
189
+ ensureId(options) {
190
+ if (!options.id) do
191
+ options.id = Math.random().toString(16).slice(2, 10);
192
+ while (this.store[options.id]);
193
+ return options.id;
194
+ }
195
+ /** Resolve an entry by id, including nested ids separated by `EntryTree.sep`. */
196
+ resolve(id) {
197
+ const parts = id.split(EntryTree.sep);
198
+ let tree = this;
199
+ const final = parts.pop();
200
+ for (const part of parts) {
201
+ tree = tree.store[part]?.subtree;
202
+ if (!tree) throw new Error(`cannot resolve entry ${id}`);
203
+ }
204
+ const entry = tree.store[final];
205
+ if (!entry) throw new Error(`cannot resolve entry ${id}`);
206
+ return entry;
207
+ }
208
+ resolveGroup(id) {
209
+ if (!id) return this.root;
210
+ const entry = this.resolve(id);
211
+ if (!entry.subgroup) throw new Error(`entry ${id} is not a group`);
212
+ return entry.subgroup;
213
+ }
214
+ /** Create an entry in the root group or a nested group. */
215
+ async create(options, parent = null, position = Infinity) {
216
+ const group = this.resolveGroup(parent);
217
+ const id = await group.create(options);
218
+ const entry = this.resolve(id);
219
+ group.data.splice(position, 0, entry.options);
220
+ group.tree.write();
221
+ return id;
222
+ }
223
+ /** Stop and remove an entry from its parent group. */
224
+ async remove(id) {
225
+ const entry = this.resolve(id);
226
+ await entry.parent.remove(id);
227
+ entry.parent.tree.write();
228
+ }
229
+ /** Update an entry and optionally move it to another group. */
230
+ async update(id, options, parent, position) {
231
+ const entry = this.resolve(id);
232
+ const source = entry.parent;
233
+ const sourceIndex = source.data.indexOf(entry.options);
234
+ let target = source;
235
+ if (parent !== void 0) {
236
+ target = this.resolveGroup(parent);
237
+ source.unlink(entry.options);
238
+ target.data.splice(position ?? Infinity, 0, entry.options);
239
+ entry.parent = target;
240
+ }
241
+ try {
242
+ await entry.update(options, false, true);
243
+ } catch (error) {
244
+ if (parent !== void 0) {
245
+ target.unlink(entry.options);
246
+ source.data.splice(sourceIndex < 0 ? source.data.length : sourceIndex, 0, entry.options);
247
+ entry.parent = source;
248
+ try {
249
+ await entry.update({}, false, true);
250
+ } catch (rollbackError) {
251
+ throw new AggregateError([error, rollbackError], `failed to roll back loader entry move ${id}`);
252
+ }
253
+ }
254
+ throw error;
255
+ }
256
+ source.tree.write();
257
+ if (target !== source) target.tree.write();
258
+ }
259
+ /** Import a plugin module from a specifier or `cordis:` builtin. */
260
+ import(name, getOuterStack) {
261
+ if (name.startsWith("cordis:")) return this.ctx.loader.builtins[name.slice(7)];
262
+ return composeError(async (info) => {
263
+ info.offset += 3;
264
+ if (this.ctx.loader.internal) return await this.ctx.loader.internal.import(name, this.ctx.baseUrl, {});
265
+ else if (name.startsWith(".")) return await import(__rewriteRelativeImportExtension(
266
+ /* @vite-ignore */
267
+ new URL(name, this.ctx.baseUrl).href
268
+ ));
269
+ else return await import(__rewriteRelativeImportExtension(
270
+ /* @vite-ignore */
271
+ name
272
+ ));
273
+ }, getOuterStack);
274
+ }
275
+ };
276
+ //#endregion
277
+ //#region lib/types/config/utils.js
278
+ /** Evaluate a JavaScript expression against a loader context scope. */
279
+ const evaluate = new Function("ctx", "expr", `
280
+ with (ctx) {
281
+ return eval(expr)
282
+ }
283
+ `);
284
+ /** Recursively replace YAML `!js` expression nodes with evaluated values. */
285
+ function interpolate(ctx, value) {
286
+ if (isJsExpr(value)) return evaluate(ctx, value.__jsExpr);
287
+ else if (!value || typeof value !== "object") return value;
288
+ else if (Array.isArray(value)) return value.map((item) => interpolate(ctx, item));
289
+ else return valueMap(value, (item) => interpolate(ctx, item));
290
+ }
291
+ /** Return true when a value is a serialized loader JavaScript expression. */
292
+ function isJsExpr(value) {
293
+ return value instanceof Object && "__jsExpr" in value;
294
+ }
295
+ //#endregion
296
+ //#region lib/types/config/entry.js
297
+ /** Static plugin hook for resolving a container config while preserving nested entry configs. */
298
+ const EntryConfigResolver = Symbol.for("cordis.loader.entry-config-resolver");
299
+ function updateError(stage, options, cause) {
300
+ const detail = cause instanceof Error ? cause.message : String(cause);
301
+ return new Error(`failed to ${stage} loader entry ${options.id} (${options.name}): ${detail}`, { cause });
302
+ }
303
+ function takeEntries(object, keys) {
304
+ const result = [];
305
+ for (const key of keys) {
306
+ if (!(key in object)) continue;
307
+ result.push([key, object[key]]);
308
+ delete object[key];
309
+ }
310
+ return result;
311
+ }
312
+ function sortKeys(object, prepend = ["id", "name"], append = ["config"]) {
313
+ const part1 = takeEntries(object, prepend);
314
+ const part2 = takeEntries(object, append);
315
+ const rest = takeEntries(object, Object.keys(object)).sort(([a], [b]) => a.localeCompare(b));
316
+ return Object.assign(object, Object.fromEntries([
317
+ ...part1,
318
+ ...rest,
319
+ ...part2
320
+ ]));
321
+ }
322
+ function replaceKeys(target, source) {
323
+ for (const key of Object.keys(target)) Reflect.deleteProperty(target, key);
324
+ return Object.assign(target, source);
325
+ }
326
+ /** One configured plugin node inside an `EntryTree`. */
327
+ var Entry = class Entry {
328
+ loader;
329
+ static key = Symbol.for("cordis.entry");
330
+ ctx;
331
+ fiber;
332
+ parent;
333
+ options = {};
334
+ subgroup;
335
+ subtree;
336
+ _initTask;
337
+ _disposing = 0;
338
+ runtimeEnabled = false;
339
+ runtimeEnableTask;
340
+ constructor(loader) {
341
+ this.loader = loader;
342
+ this.ctx = loader.ctx.extend({ [Entry.key]: this });
343
+ this.context.emit("loader/entry-init", this);
344
+ }
345
+ get context() {
346
+ return this.ctx;
347
+ }
348
+ get id() {
349
+ let id = this.options.id;
350
+ if (this.parent.tree.ctx.fiber.entry) id = this.parent.tree.ctx.fiber.entry.id + EntryTree.sep + id;
351
+ return id;
352
+ }
353
+ /** True when this entry or any owning parent entry is disabled. */
354
+ get disabled() {
355
+ return this._disabled(this.options);
356
+ }
357
+ _disabled(options) {
358
+ if (options.group) return false;
359
+ if (options.disabled && !this.runtimeEnabled) return true;
360
+ let entry = this.parent.ctx.fiber.entry;
361
+ while (entry) {
362
+ if (entry.options.disabled && !entry.runtimeEnabled) return true;
363
+ entry = entry.parent.ctx.fiber.entry;
364
+ }
365
+ return false;
366
+ }
367
+ /**
368
+ * Enable this in-memory entry without rewriting its configured `disabled`
369
+ * value; the override survives config reapplication for this entry object.
370
+ * @returns a promise settling after its initial activation attempt.
371
+ */
372
+ enableRuntime() {
373
+ if (this.runtimeEnableTask !== void 0) return this.runtimeEnableTask;
374
+ this.runtimeEnabled = true;
375
+ this.runtimeEnableTask = this.refresh().catch((error) => {
376
+ this.runtimeEnabled = false;
377
+ this.runtimeEnableTask = void 0;
378
+ throw error;
379
+ });
380
+ return this.runtimeEnableTask;
381
+ }
382
+ evaluate(expr) {
383
+ return evaluate(this.ctx, expr);
384
+ }
385
+ async _patchContext(diff) {
386
+ await this.context.waterfall("loader/patch-context", this, async () => {
387
+ Object.setPrototypeOf(this.ctx, this.parent.ctx);
388
+ if (this.fiber?.uid && (diff.includes("config") || this.options.group)) await this.fiber.update(this.options.config, true);
389
+ });
390
+ }
391
+ async refresh() {
392
+ if (this.fiber) return;
393
+ if (this.disabled) return;
394
+ await this.init();
395
+ }
396
+ async _dispose(fiber = this.fiber) {
397
+ if (!fiber) return;
398
+ if (this.fiber === fiber) this.fiber = void 0;
399
+ this._disposing += 1;
400
+ try {
401
+ await fiber.dispose();
402
+ } finally {
403
+ this._disposing -= 1;
404
+ }
405
+ }
406
+ /** Merge new options, restart as needed, and persist through the parent tree. */
407
+ async update(options, create = false, force = false) {
408
+ const previousOptions = this.options;
409
+ const legacy = { ...previousOptions };
410
+ const candidate = create ? options : { ...previousOptions };
411
+ if (!create) for (const [key, value] of Object.entries(options)) if (isNullable(value)) delete candidate[key];
412
+ else candidate[key] = value;
413
+ sortKeys(candidate);
414
+ const diff = Object.keys({
415
+ ...candidate,
416
+ ...legacy
417
+ }).filter((key) => !deepEqual(candidate[key], legacy[key]));
418
+ if (!diff.length && !force) return;
419
+ const commit = () => {
420
+ if (create) return;
421
+ this.options = replaceKeys(previousOptions, candidate);
422
+ };
423
+ const previous = this.fiber;
424
+ if (!previous?.uid) {
425
+ this.fiber = void 0;
426
+ this.options = candidate;
427
+ try {
428
+ if (!this._disabled(candidate)) await this.init();
429
+ } catch (error) {
430
+ this.options = previousOptions;
431
+ throw error;
432
+ }
433
+ commit();
434
+ return;
435
+ }
436
+ if (this._disabled(candidate)) {
437
+ this.options = candidate;
438
+ try {
439
+ await this._dispose(previous);
440
+ } catch (error) {
441
+ this.options = previousOptions;
442
+ throw updateError("dispose", candidate, error);
443
+ }
444
+ commit();
445
+ this.context.emit("loader/partial-dispose", this, legacy, true);
446
+ return;
447
+ }
448
+ if (!diff.some((key) => key === "name" || key === "inject" || key === "group")) {
449
+ this.options = candidate;
450
+ try {
451
+ await this._patchContext(diff);
452
+ } catch (error) {
453
+ this.options = previousOptions;
454
+ try {
455
+ await this._patchContext(diff);
456
+ } catch (rollbackError) {
457
+ throw updateError("rollback", legacy, new AggregateError([error, rollbackError]));
458
+ }
459
+ this.context.emit("loader/partial-dispose", this, candidate, true);
460
+ throw updateError("apply", candidate, error);
461
+ }
462
+ commit();
463
+ this.context.emit("loader/partial-dispose", this, legacy, true);
464
+ return;
465
+ }
466
+ let plugin;
467
+ try {
468
+ plugin = diff.includes("name") ? this.loader.unwrapExports(await this.parent.tree.import(candidate.name, this.getOuterStack)) : previous.runtime.callback;
469
+ } catch (error) {
470
+ throw updateError("import", candidate, error);
471
+ }
472
+ const previousPlugin = previous.runtime.callback;
473
+ this.options = candidate;
474
+ try {
475
+ await this._dispose(previous);
476
+ } catch (error) {
477
+ this.options = previousOptions;
478
+ throw updateError("dispose", candidate, error);
479
+ }
480
+ try {
481
+ await this._start(plugin);
482
+ } catch (error) {
483
+ this.options = previousOptions;
484
+ try {
485
+ await this._start(previousPlugin);
486
+ } catch (rollbackError) {
487
+ throw updateError("rollback", legacy, new AggregateError([error, rollbackError]));
488
+ }
489
+ this.context.emit("loader/partial-dispose", this, candidate, true);
490
+ throw updateError("apply", candidate, error);
491
+ }
492
+ commit();
493
+ this.context.emit("loader/partial-dispose", this, legacy, true);
494
+ }
495
+ getOuterStack = () => {
496
+ let entry = this;
497
+ const result = [];
498
+ do {
499
+ result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`);
500
+ entry = entry.parent.ctx.fiber.entry;
501
+ } while (entry);
502
+ return result;
503
+ };
504
+ /** Import and start the configured plugin if it is not already running. */
505
+ async init() {
506
+ try {
507
+ await (this._initTask ??= this._init());
508
+ } finally {
509
+ this._initTask = void 0;
510
+ if (!this.loader.getTasks().length) this.ctx.reflect.notify(["loader"]);
511
+ }
512
+ await this._await();
513
+ }
514
+ async _await() {
515
+ try {
516
+ await this.fiber?.await();
517
+ } catch (error) {
518
+ throw updateError("apply", this.options, error);
519
+ }
520
+ }
521
+ async _init() {
522
+ let plugin;
523
+ try {
524
+ plugin = this.loader.unwrapExports(await this.parent.tree.import(this.options.name, this.getOuterStack));
525
+ } catch (error) {
526
+ throw updateError("import", this.options, error);
527
+ }
528
+ try {
529
+ await this._start(plugin);
530
+ } catch (error) {
531
+ throw updateError("apply", this.options, error);
532
+ }
533
+ }
534
+ async _start(plugin) {
535
+ let fiber;
536
+ try {
537
+ await this._patchContext([]);
538
+ this.loader.showLog(this, "apply");
539
+ fiber = this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack);
540
+ await fiber.await();
541
+ } catch (error) {
542
+ await this._dispose(fiber);
543
+ throw error;
544
+ }
545
+ }
546
+ };
547
+ //#endregion
548
+ //#region lib/types/config/isolate.js
549
+ function swap(target, source) {
550
+ for (const key of Reflect.ownKeys(target)) Reflect.deleteProperty(target, key);
551
+ for (const key of Reflect.ownKeys(source || {})) Reflect.defineProperty(target, key, Reflect.getOwnPropertyDescriptor(source, key));
552
+ }
553
+ /** Symbol realm used to isolate service implementations by entry or label. */
554
+ var Realm = class {
555
+ store = Object.create(null);
556
+ access(key, create = false) {
557
+ if (create) return this.store[key] ??= Symbol(`${key}${this.suffix}`);
558
+ else return this.store[key] ?? Symbol(`${key}${this.suffix}`);
559
+ }
560
+ delete(key) {
561
+ delete this.store[key];
562
+ }
563
+ get size() {
564
+ return Object.keys(this.store).length;
565
+ }
566
+ };
567
+ /** Entry-local isolation realm. */
568
+ var LocalRealm = class extends Realm {
569
+ entry;
570
+ constructor(entry) {
571
+ super();
572
+ this.entry = entry;
573
+ }
574
+ get suffix() {
575
+ return "#" + this.entry.options.id;
576
+ }
577
+ };
578
+ /** Named isolation realm shared by entries that use the same label. */
579
+ var GlobalRealm = class extends Realm {
580
+ label;
581
+ constructor(label) {
582
+ super();
583
+ this.label = label;
584
+ }
585
+ get suffix() {
586
+ return "@" + this.label;
587
+ }
588
+ };
589
+ /** Install loader hooks that apply `intercept` and `isolate` entry options. */
590
+ function isolate(ctx) {
591
+ const realms = Object.create(null);
592
+ const delims = Object.create(null);
593
+ function access(entry, name, create = false) {
594
+ let realm;
595
+ const label = entry.options.isolate?.[name];
596
+ if (!label) return;
597
+ if (label === true) realm = entry.realm ??= new LocalRealm(entry);
598
+ else if (create) realm = realms[label] ??= new GlobalRealm(label);
599
+ else realm = realms[label];
600
+ return realm?.access(name, create);
601
+ }
602
+ ctx.on("loader/entry-init", (entry) => {
603
+ entry.ctx[Context.intercept] = Object.create(entry.ctx[Context.intercept]);
604
+ entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate]);
605
+ });
606
+ ctx.on("loader/patch-context", async (entry, next) => {
607
+ const newMap = Object.create(entry.parent.ctx[Context.isolate]);
608
+ for (const name of Object.keys(entry.options.isolate ?? {})) newMap[name] = access(entry, name, true);
609
+ const diff = Object.create(null);
610
+ const oldMap = entry.ctx[Context.isolate];
611
+ for (const name in {
612
+ ...newMap,
613
+ ...delims
614
+ }) {
615
+ if (newMap[name] === oldMap[name]) continue;
616
+ const delim = delims[name] ??= Symbol(`delim:${name}`);
617
+ entry.ctx[delim] = Symbol(`${name}#${entry.id}`);
618
+ for (const symbol of [oldMap[name], newMap[name]]) {
619
+ const impl = symbol && entry.ctx.reflect.store[symbol];
620
+ if (!impl) continue;
621
+ if (!impl.fiber) {
622
+ entry.ctx.logger.warn(/* @__PURE__ */ new Error(`expected service ${name} to be implemented`));
623
+ continue;
624
+ }
625
+ diff[name] = [
626
+ oldMap[name],
627
+ newMap[name],
628
+ entry.ctx[delim],
629
+ impl.fiber.ctx[delim]
630
+ ];
631
+ if (entry.ctx[delim] !== impl.fiber.ctx[delim]) break;
632
+ }
633
+ }
634
+ Object.setPrototypeOf(entry.ctx[Context.isolate], entry.parent.ctx[Context.isolate]);
635
+ Object.setPrototypeOf(entry.ctx[Context.intercept], entry.parent.ctx[Context.intercept]);
636
+ swap(entry.ctx[Context.isolate], newMap);
637
+ swap(entry.ctx[Context.intercept], entry.options.intercept);
638
+ await next();
639
+ for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) if (flag1 === flag2 && entry.ctx.reflect.store[symbol1] && !entry.ctx.reflect.store[symbol2]) {
640
+ entry.ctx.reflect.store[symbol2] = entry.ctx.reflect.store[symbol1];
641
+ delete entry.ctx.reflect.store[symbol1];
642
+ }
643
+ ctx.reflect.notify(Object.keys(diff), (ctx, name) => {
644
+ const [symbol1, symbol2, flag1, flag2] = diff[name];
645
+ const symbol3 = ctx[Context.isolate][name];
646
+ const flag3 = ctx[delims[name]];
647
+ return (symbol1 === symbol3 || symbol2 === symbol3) && flag1 === flag3 !== (flag1 === flag2);
648
+ });
649
+ for (const name in delims) if (!Reflect.ownKeys(newMap).includes(name)) delete entry.ctx[delims[name]];
650
+ });
651
+ ctx.on("loader/partial-dispose", (entry, legacy, active) => {
652
+ for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
653
+ if (label === true) continue;
654
+ if (active && entry.options.isolate?.[name] === label) continue;
655
+ const realm = realms[label];
656
+ if (!realm) continue;
657
+ for (const entry of ctx.loader.entries()) if (entry.options.isolate?.[name] === realm.label) return;
658
+ realm.delete(name);
659
+ if (!realm.size) delete realms[realm.label];
660
+ }
661
+ });
662
+ }
663
+ //#endregion
664
+ //#region lib/types/index.js
665
+ /**
666
+ * Service that owns a loader entry tree and imports configured plugins.
667
+ *
668
+ * Subclasses provide persistence by implementing `write()` on `EntryTree`.
669
+ */
670
+ var Loader = class extends EntryTree {
671
+ config;
672
+ envData = process.env.CORDIS_SHARED ? JSON.parse(process.env.CORDIS_SHARED) : { startTime: Date.now() };
673
+ name = "loader";
674
+ internal = ModuleLoader.fromInternal();
675
+ builtins = Object.create(null);
676
+ constructor(ctx, config = {}) {
677
+ super(ctx);
678
+ this.config = config;
679
+ if (config.baseUrl) this.ctx.baseUrl = config.baseUrl;
680
+ const self = this;
681
+ defineProperty(this, Service.tracker, {
682
+ associate: "loader",
683
+ property: "ctx",
684
+ noShadow: true
685
+ });
686
+ ctx.reflect.provide("loader", this, this[Service.check]);
687
+ ctx.on("internal/config", function(_config, next) {
688
+ const config = next();
689
+ if (!this.entry || this.parent.fiber?.entry === this.entry) return config;
690
+ const plugin = this.runtime?.callback;
691
+ if (plugin?.[EntryGroup.key]) return config;
692
+ const resolve = plugin?.[EntryConfigResolver];
693
+ return resolve ? resolve(this.ctx, config) : interpolate(this.ctx, config);
694
+ }, { global: true });
695
+ ctx.on("internal/update", async function(config, noSave, next) {
696
+ if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next();
697
+ await next();
698
+ const unparse = this.runtime?.Config?.["simplify"];
699
+ this.entry.options.config = unparse ? unparse(config) : config;
700
+ this.entry.parent.tree.write();
701
+ }, {
702
+ global: true,
703
+ prepend: true
704
+ });
705
+ ctx.on("internal/update", function(config, _, next) {
706
+ if (!this.entry || this.parent.fiber?.entry === this.entry) return next();
707
+ self.showLog(this.entry, "reload");
708
+ return next();
709
+ }, { global: true });
710
+ ctx.on("internal/plugin", (fiber) => {
711
+ if (fiber.parent[Entry.key] && !fiber.entry) {
712
+ fiber.entry = fiber.parent[Entry.key];
713
+ Inject.resolve(fiber.entry.options.inject, fiber.inject);
714
+ }
715
+ if (fiber.uid) return;
716
+ if (!fiber.entry) return;
717
+ if (fiber.parent.fiber?.entry === fiber.entry) return;
718
+ if (!ctx.registry.has(fiber.runtime.callback)) return;
719
+ const treeOwner = fiber.entry.parent.tree.ctx.fiber;
720
+ if (!treeOwner.uid || treeOwner.state === 5) return;
721
+ if (fiber.entry._disposing) return;
722
+ this.showLog(fiber.entry, "unload");
723
+ if (fiber.entry.disabled) return;
724
+ fiber.entry.options.disabled = true;
725
+ fiber.entry.parent.tree.write();
726
+ });
727
+ ctx.plugin(isolate);
728
+ }
729
+ write() {}
730
+ [Service.check]() {
731
+ if (Service.prototype[Service.resolveConfig].call(this).await && this.getTasks().length) return false;
732
+ return true;
733
+ }
734
+ showLog(entry, type) {
735
+ if (entry.options.group || !entry.parent.tree.enableLogs) return;
736
+ this.ctx.root.logger?.("loader").info("%s plugin %C", type, entry.options.name);
737
+ }
738
+ /** Return the loader entry id that owns `fiber`, if any. */
739
+ locate(fiber = this.ctx.fiber) {
740
+ while (1) {
741
+ if (fiber.entry) return fiber.entry.id;
742
+ const next = fiber.parent.fiber;
743
+ if (fiber === next) return;
744
+ fiber = next;
745
+ }
746
+ }
747
+ /** Hook for hosts that can restart the process on full-reload requests. */
748
+ exit() {}
749
+ /** Normalize ESM/CJS/default export shapes before applying a plugin. */
750
+ unwrapExports(exports) {
751
+ if (isNullable(exports)) return exports;
752
+ exports = exports.default ?? exports;
753
+ if (!exports.__esModule) return exports;
754
+ return exports.default ?? exports;
755
+ }
756
+ };
757
+ //#endregion
758
+ export { Entry, EntryConfigResolver, EntryGroup, EntryTree, GlobalRealm, Group, Loader, Loader as default, LocalRealm, ModuleLoader, Realm, evaluate, interpolate, isJsExpr };