@deepseek-ai/cordis-plugin-loader 1.0.2 → 1.0.4

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.
@@ -19,23 +19,12 @@ export class EntryGroup {
19
19
 
20
20
  async create(options: Omit<EntryOptions, 'id'>) {
21
21
  const id = this.tree.ensureId(options)
22
- const existing = this.tree.store[id]
23
- const entry: Entry = existing ?? (this.tree.store[id] = new Entry(this.ctx.loader))
24
- const previousParent = entry.parent
22
+ const entry: Entry = this.tree.store[id] ??= new Entry(this.ctx.loader)
25
23
  // Entry may be moved from another group,
26
24
  // so we need to update the parent reference.
27
25
  entry.parent = this
28
26
  // Use `create: true` to replace existing entry.options.
29
- try {
30
- await entry.update(options, true, true)
31
- } catch (error) {
32
- if (existing) {
33
- entry.parent = previousParent
34
- } else {
35
- delete this.tree.store[id]
36
- }
37
- throw error
38
- }
27
+ await entry.update(options, true, true)
39
28
  return entry.id
40
29
  }
41
30
 
@@ -45,10 +34,10 @@ export class EntryGroup {
45
34
  if (index >= 0) config.splice(index, 1)
46
35
  }
47
36
 
48
- async remove(id: string, isDispose = false) {
37
+ remove(id: string, isDispose = false) {
49
38
  const entry = this.tree.store[id]
50
39
  if (!entry) return
51
- await entry._dispose()
40
+ entry.fiber?.dispose()
52
41
  if (!isDispose) {
53
42
  this.unlink(entry.options)
54
43
  }
@@ -58,56 +47,26 @@ export class EntryGroup {
58
47
 
59
48
  async update(config: EntryOptions[]) {
60
49
  const oldConfig = this.data as EntryOptions[]
61
- const seen = new Set<string>()
62
- for (const options of config) {
63
- const id = this.tree.ensureId(options)
64
- if (seen.has(id)) throw new TypeError(`duplicate loader entry id: ${id}`)
65
- seen.add(id)
66
- }
50
+ this.data = config
67
51
  const oldMap = Object.fromEntries(oldConfig.map(options => [options.id, options]))
68
- const newMap = Object.fromEntries(config.map(options => [options.id, options]))
52
+ const newMap = Object.fromEntries(config.map(options => [options.id ?? Symbol('anonymous'), options]))
69
53
 
70
- try {
71
- const outcomes = await Promise.allSettled(config.map(options => this.create(options)))
72
- // Disposal owns termination: sibling starts can still be settling after
73
- // the containing tree has gone away, but their failures no longer
74
- // describe a live update to roll back.
75
- if (this.ctx.fiber.uid === null) return
76
- const failures = outcomes
77
- .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
78
- .map(outcome => outcome.reason)
79
- if (failures.length === 1) throw failures[0]
80
- if (failures.length > 1) throw new AggregateError(failures, 'loader entries failed to apply')
81
- for (const id of Object.keys(oldMap)) {
82
- if (!newMap[id]) await this.remove(id, true)
83
- }
84
- this.data = config
85
- } catch (error) {
86
- const rollbackErrors: unknown[] = []
87
- for (const id of Object.keys(newMap).reverse()) {
88
- if (oldMap[id]) continue
89
- try {
90
- await this.remove(id, true)
91
- } catch (rollbackError) {
92
- rollbackErrors.push(rollbackError)
93
- }
94
- }
95
- for (const options of oldConfig) {
96
- try {
97
- await this.create(options)
98
- } catch (rollbackError) {
99
- rollbackErrors.push(rollbackError)
100
- }
54
+ // update inner plugins
55
+ const ids = Reflect.ownKeys({ ...oldMap, ...newMap }) as string[]
56
+ await Promise.all(ids.map(async (id) => {
57
+ if (newMap[id]) {
58
+ await this.create(newMap[id]).catch((error) => {
59
+ this.ctx.logger.error(error)
60
+ })
61
+ } else {
62
+ this.remove(id)
101
63
  }
102
- this.data = oldConfig
103
- if (rollbackErrors.length) throw new AggregateError([error, ...rollbackErrors], 'loader entry rollback failed')
104
- throw error
105
- }
64
+ }))
106
65
  }
107
66
 
108
- async stop() {
67
+ stop() {
109
68
  for (const options of this.data) {
110
- await this.remove(options.id, true)
69
+ this.remove(options.id, true)
111
70
  }
112
71
  }
113
72
  }
@@ -119,7 +78,9 @@ export class Group extends EntryGroup {
119
78
 
120
79
  constructor(public ctx: Context, public config: EntryOptions[]) {
121
80
  super(ctx, ctx.fiber.entry!.parent.tree)
122
- ctx.on('internal/update', config => this.update(config))
81
+ ctx.on('internal/update', (config) => {
82
+ this.update(config)
83
+ })
123
84
  }
124
85
 
125
86
  async* [Service.init]() {
@@ -93,7 +93,7 @@ export default function isolate(ctx: Context) {
93
93
  entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate])
94
94
  })
95
95
 
96
- ctx.on('loader/patch-context', async (entry, next) => {
96
+ ctx.on('loader/patch-context', (entry, next) => {
97
97
  // step 1: generate new isolate map
98
98
  const newMap: Dict<symbol> = Object.create(entry.parent.ctx[Context.isolate])
99
99
  for (const name of Object.keys(entry.options.isolate ?? {})) {
@@ -126,7 +126,7 @@ export default function isolate(ctx: Context) {
126
126
  swap(entry.ctx[Context.intercept], entry.options.intercept)
127
127
 
128
128
  // step 4: reload fiber
129
- await next()
129
+ next()
130
130
 
131
131
  // step 5: replace service impl
132
132
  for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) {
@@ -39,27 +39,12 @@ export abstract class EntryTree {
39
39
  .filter(isNonNullable)
40
40
  }
41
41
 
42
- /**
43
- * Wait until this tree has no active import or lifecycle tasks.
44
- * @throws a settled fiber failure, or an aggregate when several fibers failed.
45
- */
42
+ /** Wait until this tree has no pending import or lifecycle tasks. */
46
43
  async await() {
47
44
  while (true) {
48
45
  const tasks = this.getTasks()
49
- if (tasks.length) {
50
- await Promise.allSettled(tasks)
51
- continue
52
- }
53
- const outcomes = await Promise.allSettled(
54
- [...this.entries()].map(entry => entry._await()),
55
- )
56
- const failures = outcomes
57
- .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
58
- .map(outcome => outcome.reason)
59
- if (failures.length === 1) throw failures[0]
60
- if (failures.length > 1) throw new AggregateError(failures, 'loader fibers failed')
61
- this.ctx.reflect.notify(['loader'])
62
- if (!this.getTasks().length) return
46
+ if (!tasks.length) return
47
+ await Promise.allSettled(tasks)
63
48
  }
64
49
  }
65
50
 
@@ -96,17 +81,15 @@ export abstract class EntryTree {
96
81
  /** Create an entry in the root group or a nested group. */
97
82
  async create(options: Omit<EntryOptions, 'id'>, parent: string | null = null, position = Infinity) {
98
83
  const group = this.resolveGroup(parent)
99
- const id = await group.create(options)
100
- const entry = this.resolve(id)
101
- group.data.splice(position, 0, entry.options)
84
+ group.data.splice(position, 0, options as EntryOptions)
102
85
  group.tree.write()
103
- return id
86
+ return group.create(options)
104
87
  }
105
88
 
106
89
  /** Stop and remove an entry from its parent group. */
107
- async remove(id: string) {
90
+ remove(id: string) {
108
91
  const entry = this.resolve(id)
109
- await entry.parent.remove(id)
92
+ entry.parent.remove(id)
110
93
  entry.parent.tree.write()
111
94
  }
112
95
 
@@ -114,31 +97,15 @@ export abstract class EntryTree {
114
97
  async update(id: string, options: Omit<EntryOptions, 'id' | 'name'>, parent?: string | null, position?: number) {
115
98
  const entry = this.resolve(id)
116
99
  const source = entry.parent
117
- const sourceIndex = source.data.indexOf(entry.options)
118
- let target = source
119
100
  if (parent !== undefined) {
120
- target = this.resolveGroup(parent)
101
+ const target = this.resolveGroup(parent)
121
102
  source.unlink(entry.options)
122
103
  target.data.splice(position ?? Infinity, 0, entry.options)
104
+ target.tree.write()
123
105
  entry.parent = target
124
106
  }
125
- try {
126
- await entry.update(options, false, true)
127
- } catch (error) {
128
- if (parent !== undefined) {
129
- target.unlink(entry.options)
130
- source.data.splice(sourceIndex < 0 ? source.data.length : sourceIndex, 0, entry.options)
131
- entry.parent = source
132
- try {
133
- await entry.update({}, false, true)
134
- } catch (rollbackError) {
135
- throw new AggregateError([error, rollbackError], `failed to roll back loader entry move ${id}`)
136
- }
137
- }
138
- throw error
139
- }
140
107
  source.tree.write()
141
- if (target !== source) target.tree.write()
108
+ return entry.update(options, false, true)
142
109
  }
143
110
 
144
111
  /** Import a plugin module from a specifier or `cordis:` builtin. */
@@ -8,7 +8,7 @@ export const evaluate = new Function('ctx', 'expr', `
8
8
  }
9
9
  `) as ((ctx: object, expr: string) => any)
10
10
 
11
- /** Recursively replace YAML `!js` expression nodes with evaluated values. */
11
+ /** Recursively replace YAML `!!js` expression nodes with evaluated values. */
12
12
  export function interpolate(ctx: object, value: any) {
13
13
  if (isJsExpr(value)) {
14
14
  return evaluate(ctx, value.__jsExpr)
package/src/index.ts CHANGED
@@ -26,7 +26,19 @@ declare module '@deepseek-ai/cordis' {
26
26
  'loader/config-update'(): void
27
27
  'loader/entry-init'(entry: Entry): void
28
28
  'loader/partial-dispose'(entry: Entry, legacy: Partial<EntryOptions>, active: boolean): void
29
- 'loader/patch-context'(entry: Entry, next: () => void | Promise<void>): void | Promise<void>
29
+ /**
30
+ * Volatile config values were committed into the running fiber without a remount; dispatched to the owning fiber only.
31
+ * @param paths - changed config paths as key arrays; every value is committed before dispatch.
32
+ * @mode emit
33
+ */
34
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void
35
+ /**
36
+ * Refresh entry context before applying config.
37
+ * @param entry - entry containing the new raw config and optional current fiber.
38
+ * @param next - continue context refresh and Loader's config update.
39
+ * @mode waterfall
40
+ */
41
+ 'loader/patch-context'(entry: Entry, next: () => void): void
30
42
  }
31
43
 
32
44
  interface Context {
@@ -100,12 +112,12 @@ export class Loader extends EntryTree {
100
112
  return interpolate(this.ctx, config)
101
113
  }, { global: true })
102
114
 
103
- ctx.on('internal/update', async function (config, noSave, next) {
115
+ ctx.on('internal/update', function (config, noSave, next) {
104
116
  if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next()
105
- await next()
106
117
  const unparse = this.runtime?.Config?.['simplify']
107
- this.entry.options.config = unparse ? unparse(config) : config
118
+ this.entry.options.config = unparse ? unparse.call(this.runtime!.Config, config) : config
108
119
  this.entry.parent.tree.write()
120
+ return next()
109
121
  }, { global: true, prepend: true })
110
122
 
111
123
  ctx.on('internal/update', function (config, _, next) {
@@ -143,12 +155,9 @@ export class Loader extends EntryTree {
143
155
  const treeOwner = fiber.entry.parent.tree.ctx.fiber
144
156
  if (!treeOwner.uid || treeOwner.state === FiberState.UNLOADING) return
145
157
 
146
- // case 6: Loader is replacing or removing this exact fiber
147
- if (fiber.entry._disposing) return
148
-
149
158
  this.showLog(fiber.entry, 'unload')
150
159
 
151
- // case 7: fiber is disposed by loader behavior
160
+ // case 6: fiber is disposed by loader behavior
152
161
  // such as inject checker, config file update, ancestor group disable
153
162
  if (fiber.entry.disabled) return
154
163
 
package/src/internal.ts CHANGED
@@ -117,16 +117,28 @@ export namespace ModuleLoader {
117
117
  } catch {}
118
118
  }
119
119
 
120
+ /**
121
+ * Locate and classify the running Node internal module loader.
122
+ *
123
+ * The shape is decided by which module-job API the loader owns, never by the
124
+ * Node version: v2 landed in 24.12.0, so a major-version test mistags every
125
+ * 24.0–24.11.1 loader as v2 and makes consumers call `resolveSync` with
126
+ * reversed parameters. Arity is not usable either — `resolveSync` reports 2
127
+ * under both shapes. A loader owning neither API is left unclassified rather
128
+ * than guessed, so consumers take their documented no-internals path.
129
+ * @returns the classified loader, or `undefined` when none is reachable or its shape is unknown.
130
+ */
120
131
  export function fromInternal(): ModuleLoader | undefined {
121
132
  if (_cachedLoader) return _cachedLoader
122
133
  const [major] = process.versions.node.split('.').map(Number)
123
-
124
- if (major >= 24) {
125
- const raw = requireInternal('internal/modules/esm/loader')?.getOrInitializeCascadedLoader()
126
- if (raw) return _cachedLoader = Object.assign(raw, { version: 'v2' })
127
- } else if (major >= 22) {
128
- const raw = requireInternal('internal/modules/esm/loader')?.getOrInitializeCascadedLoader()
129
- if (raw) return _cachedLoader = Object.assign(raw, { version: 'v1' })
130
- }
134
+ if (major < 22) return
135
+
136
+ const raw = requireInternal('internal/modules/esm/loader')?.getOrInitializeCascadedLoader()
137
+ if (!raw) return
138
+ const version = typeof raw.getOrCreateModuleJob === 'function'
139
+ ? 'v2'
140
+ : typeof raw.getModuleJobForImport === 'function' ? 'v1' : undefined
141
+ if (!version) return
142
+ return _cachedLoader = Object.assign(raw, { version })
131
143
  }
132
144
  }