@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.
@@ -0,0 +1,322 @@
1
+ import { Context, Fiber, Inject } from '@deepseek-ai/cordis'
2
+ import { deepEqual, isNullable } from '@deepseek-ai/cosmokit'
3
+ import { Loader } from '../index.ts'
4
+ import { EntryGroup } from './group.ts'
5
+ import { EntryTree } from './tree.ts'
6
+ import { evaluate } from './utils.ts'
7
+
8
+ /** Static plugin hook for resolving a container config while preserving nested entry configs. */
9
+ export const EntryConfigResolver = Symbol.for('cordis.loader.entry-config-resolver')
10
+
11
+ /**
12
+ * Resolve a container's own config while preserving any nested entry configs.
13
+ * @param ctx - the container plugin context.
14
+ * @param config - the container's raw config.
15
+ * @returns the config to validate for this activation.
16
+ */
17
+ export type EntryConfigResolver = (ctx: Context, config: any) => any
18
+
19
+ /** Serialized plugin entry options stored in loader config files. */
20
+ export interface EntryOptions {
21
+ /** Stable id inside the containing entry tree. */
22
+ id: string
23
+ /** Module specifier imported by the entry tree. */
24
+ name: string
25
+ /** Config passed to the plugin. */
26
+ config?: any
27
+ /** Marks this entry as a nested group. */
28
+ group?: boolean | null
29
+ /** Prevents this entry and descendants from running. */
30
+ disabled?: boolean | null
31
+ /** Required services or service intercept config for this entry. */
32
+ inject?: Inject | null
33
+ }
34
+
35
+ function updateError(stage: 'import' | 'dispose' | 'apply' | 'rollback', options: EntryOptions, cause: unknown) {
36
+ const detail = cause instanceof Error ? cause.message : String(cause)
37
+ return new Error(`failed to ${stage} loader entry ${options.id} (${options.name}): ${detail}`, { cause })
38
+ }
39
+
40
+ function takeEntries(object: {}, keys: string[]) {
41
+ const result: [string, any][] = []
42
+ for (const key of keys) {
43
+ if (!(key in object)) continue
44
+ result.push([key, object[key]])
45
+ delete object[key]
46
+ }
47
+ return result
48
+ }
49
+
50
+ function sortKeys<T extends {}>(object: T, prepend = ['id', 'name'], append = ['config']): T {
51
+ const part1 = takeEntries(object, prepend)
52
+ const part2 = takeEntries(object, append)
53
+ const rest = takeEntries(object, Object.keys(object)).sort(([a], [b]) => a.localeCompare(b))
54
+ return Object.assign(object, Object.fromEntries([...part1, ...rest, ...part2]))
55
+ }
56
+
57
+ function replaceKeys<T extends {}>(target: T, source: T): T {
58
+ for (const key of Object.keys(target)) Reflect.deleteProperty(target, key)
59
+ return Object.assign(target, source)
60
+ }
61
+
62
+ /** One configured plugin node inside an `EntryTree`. */
63
+ export class Entry {
64
+ static readonly key = Symbol.for('cordis.entry')
65
+
66
+ public ctx: Context
67
+ public fiber?: Fiber
68
+ public parent!: EntryGroup
69
+ // safety: call `entry.update()` immediately after creating an entry
70
+ public options = {} as EntryOptions
71
+ public subgroup?: EntryGroup
72
+ public subtree?: EntryTree
73
+
74
+ _initTask?: Promise<void>
75
+ _disposing = 0
76
+ private runtimeEnabled = false
77
+ private runtimeEnableTask?: Promise<void>
78
+
79
+ constructor(public loader: Loader) {
80
+ this.ctx = loader.ctx.extend({ [Entry.key]: this })
81
+ this.context.emit('loader/entry-init', this)
82
+ }
83
+
84
+ get context(): Context {
85
+ return this.ctx
86
+ }
87
+
88
+ get id() {
89
+ let id = this.options.id
90
+ if (this.parent.tree.ctx.fiber.entry) {
91
+ id = this.parent.tree.ctx.fiber.entry.id + EntryTree.sep + id
92
+ }
93
+ return id
94
+ }
95
+
96
+ /** True when this entry or any owning parent entry is disabled. */
97
+ get disabled() {
98
+ return this._disabled(this.options)
99
+ }
100
+
101
+ private _disabled(options: EntryOptions) {
102
+ // group is always enabled
103
+ if (options.group) return false
104
+ if (options.disabled && !this.runtimeEnabled) return true
105
+ let entry = this.parent.ctx.fiber.entry
106
+ while (entry) {
107
+ if (entry.options.disabled && !entry.runtimeEnabled) return true
108
+ entry = entry.parent.ctx.fiber.entry
109
+ }
110
+ return false
111
+ }
112
+
113
+ /**
114
+ * Enable this in-memory entry without rewriting its configured `disabled`
115
+ * value; the override survives config reapplication for this entry object.
116
+ * @returns a promise settling after its initial activation attempt.
117
+ */
118
+ enableRuntime(): Promise<void> {
119
+ if (this.runtimeEnableTask !== undefined) return this.runtimeEnableTask
120
+ this.runtimeEnabled = true
121
+ this.runtimeEnableTask = this.refresh().catch((error: unknown) => {
122
+ this.runtimeEnabled = false
123
+ this.runtimeEnableTask = undefined
124
+ throw error
125
+ })
126
+ return this.runtimeEnableTask
127
+ }
128
+
129
+ evaluate(expr: string) {
130
+ return evaluate(this.ctx, expr)
131
+ }
132
+
133
+ private async _patchContext(diff: string[]) {
134
+ await this.context.waterfall('loader/patch-context', this, async () => {
135
+ Object.setPrototypeOf(this.ctx, this.parent.ctx)
136
+
137
+ if (this.fiber?.uid && (diff.includes('config') || this.options.group)) {
138
+ await this.fiber.update(this.options.config, true)
139
+ }
140
+ })
141
+ }
142
+
143
+ async refresh() {
144
+ if (this.fiber) return
145
+ if (this.disabled) return
146
+ await this.init()
147
+ }
148
+
149
+ async _dispose(fiber = this.fiber) {
150
+ if (!fiber) return
151
+ if (this.fiber === fiber) this.fiber = undefined
152
+ this._disposing += 1
153
+ try {
154
+ await fiber.dispose()
155
+ } finally {
156
+ this._disposing -= 1
157
+ }
158
+ }
159
+
160
+ /** Merge new options, restart as needed, and persist through the parent tree. */
161
+ async update(options: Partial<EntryOptions>, create = false, force = false) {
162
+ const previousOptions = this.options
163
+ const legacy = { ...previousOptions }
164
+ const candidate = create ? options as EntryOptions : { ...previousOptions }
165
+ if (!create) {
166
+ for (const [key, value] of Object.entries(options)) {
167
+ if (isNullable(value)) {
168
+ delete candidate[key as keyof EntryOptions]
169
+ } else {
170
+ candidate[key as keyof EntryOptions] = value as never
171
+ }
172
+ }
173
+ }
174
+ sortKeys(candidate)
175
+
176
+ const diff = Object
177
+ .keys({ ...candidate, ...legacy })
178
+ .filter(key => !deepEqual(candidate[key as keyof EntryOptions], legacy[key as keyof EntryOptions]))
179
+ if (!diff.length && !force) return
180
+
181
+ const commit = () => {
182
+ if (create) return
183
+ this.options = replaceKeys(previousOptions, candidate)
184
+ }
185
+
186
+ const previous = this.fiber
187
+ if (!previous?.uid) {
188
+ this.fiber = undefined
189
+ this.options = candidate
190
+ try {
191
+ if (!this._disabled(candidate)) await this.init()
192
+ } catch (error) {
193
+ this.options = previousOptions
194
+ throw error
195
+ }
196
+ commit()
197
+ return
198
+ }
199
+
200
+ if (this._disabled(candidate)) {
201
+ this.options = candidate
202
+ try {
203
+ await this._dispose(previous)
204
+ } catch (error) {
205
+ this.options = previousOptions
206
+ throw updateError('dispose', candidate, error)
207
+ }
208
+ commit()
209
+ this.context.emit('loader/partial-dispose', this, legacy, true)
210
+ return
211
+ }
212
+
213
+ const replace = diff.some(key => key === 'name' || key === 'inject' || key === 'group')
214
+ if (!replace) {
215
+ this.options = candidate
216
+ try {
217
+ await this._patchContext(diff)
218
+ } catch (error) {
219
+ this.options = previousOptions
220
+ try {
221
+ await this._patchContext(diff)
222
+ } catch (rollbackError) {
223
+ throw updateError('rollback', legacy, new AggregateError([error, rollbackError]))
224
+ }
225
+ this.context.emit('loader/partial-dispose', this, candidate, true)
226
+ throw updateError('apply', candidate, error)
227
+ }
228
+ commit()
229
+ this.context.emit('loader/partial-dispose', this, legacy, true)
230
+ return
231
+ }
232
+
233
+ let plugin: any
234
+ try {
235
+ plugin = diff.includes('name')
236
+ ? this.loader.unwrapExports(await this.parent.tree.import(candidate.name, this.getOuterStack))
237
+ : previous.runtime!.callback
238
+ } catch (error) {
239
+ throw updateError('import', candidate, error)
240
+ }
241
+
242
+ const previousPlugin = previous.runtime!.callback
243
+ this.options = candidate
244
+ try {
245
+ await this._dispose(previous)
246
+ } catch (error) {
247
+ this.options = previousOptions
248
+ throw updateError('dispose', candidate, error)
249
+ }
250
+
251
+ try {
252
+ await this._start(plugin)
253
+ } catch (error) {
254
+ this.options = previousOptions
255
+ try {
256
+ await this._start(previousPlugin)
257
+ } catch (rollbackError) {
258
+ throw updateError('rollback', legacy, new AggregateError([error, rollbackError]))
259
+ }
260
+ this.context.emit('loader/partial-dispose', this, candidate, true)
261
+ throw updateError('apply', candidate, error)
262
+ }
263
+ commit()
264
+ this.context.emit('loader/partial-dispose', this, legacy, true)
265
+ }
266
+
267
+ getOuterStack = () => {
268
+ let entry: Entry | undefined = this
269
+ const result: string[] = []
270
+ do {
271
+ result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`)
272
+ entry = entry.parent.ctx.fiber.entry
273
+ } while (entry)
274
+ return result
275
+ }
276
+
277
+ /** Import and start the configured plugin if it is not already running. */
278
+ async init() {
279
+ try {
280
+ await (this._initTask ??= this._init())
281
+ } finally {
282
+ this._initTask = undefined
283
+ if (!this.loader.getTasks().length) this.ctx.reflect.notify(['loader'])
284
+ }
285
+ await this._await()
286
+ }
287
+
288
+ async _await() {
289
+ try {
290
+ await this.fiber?.await()
291
+ } catch (error) {
292
+ throw updateError('apply', this.options, error)
293
+ }
294
+ }
295
+
296
+ private async _init() {
297
+ let plugin: any
298
+ try {
299
+ plugin = this.loader.unwrapExports(await this.parent.tree.import(this.options.name, this.getOuterStack))
300
+ } catch (error) {
301
+ throw updateError('import', this.options, error)
302
+ }
303
+ try {
304
+ await this._start(plugin)
305
+ } catch (error) {
306
+ throw updateError('apply', this.options, error)
307
+ }
308
+ }
309
+
310
+ private async _start(plugin: any) {
311
+ let fiber: Fiber | undefined
312
+ try {
313
+ await this._patchContext([])
314
+ this.loader.showLog(this, 'apply')
315
+ fiber = this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack)
316
+ await fiber.await()
317
+ } catch (error) {
318
+ await this._dispose(fiber)
319
+ throw error
320
+ }
321
+ }
322
+ }
@@ -0,0 +1,129 @@
1
+ import { Context, Service } from '@deepseek-ai/cordis'
2
+ import { Entry, type EntryOptions } from './entry.ts'
3
+ import { EntryTree } from './tree.ts'
4
+
5
+ /** Runtime owner for a list of child loader entries. */
6
+ export class EntryGroup {
7
+ static readonly key = Symbol.for('cordis.group')
8
+
9
+ public data: EntryOptions[] = []
10
+
11
+ constructor(public ctx: Context, public tree: EntryTree) {
12
+ const entry = ctx.fiber.entry
13
+ if (entry) entry.subgroup = this
14
+ }
15
+
16
+ get context(): Context {
17
+ return this.ctx
18
+ }
19
+
20
+ async create(options: Omit<EntryOptions, 'id'>) {
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
25
+ // Entry may be moved from another group,
26
+ // so we need to update the parent reference.
27
+ entry.parent = this
28
+ // 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
+ }
39
+ return entry.id
40
+ }
41
+
42
+ unlink(options: EntryOptions) {
43
+ const config = this.data
44
+ const index = config.indexOf(options)
45
+ if (index >= 0) config.splice(index, 1)
46
+ }
47
+
48
+ async remove(id: string, isDispose = false) {
49
+ const entry = this.tree.store[id]
50
+ if (!entry) return
51
+ await entry._dispose()
52
+ if (!isDispose) {
53
+ this.unlink(entry.options)
54
+ }
55
+ delete this.tree.store[id]
56
+ this.context.emit('loader/partial-dispose', entry, entry.options, false)
57
+ }
58
+
59
+ async update(config: EntryOptions[]) {
60
+ 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
+ }
67
+ const oldMap = Object.fromEntries(oldConfig.map(options => [options.id, options]))
68
+ const newMap = Object.fromEntries(config.map(options => [options.id, options]))
69
+
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
+ }
101
+ }
102
+ this.data = oldConfig
103
+ if (rollbackErrors.length) throw new AggregateError([error, ...rollbackErrors], 'loader entry rollback failed')
104
+ throw error
105
+ }
106
+ }
107
+
108
+ async stop() {
109
+ for (const options of this.data) {
110
+ await this.remove(options.id, true)
111
+ }
112
+ }
113
+ }
114
+
115
+ /** Plugin that mounts a nested loader entry group. */
116
+ export class Group extends EntryGroup {
117
+ static initial: Omit<EntryOptions, 'id'>[] = []
118
+ static readonly [EntryGroup.key] = true
119
+
120
+ constructor(public ctx: Context, public config: EntryOptions[]) {
121
+ super(ctx, ctx.fiber.entry!.parent.tree)
122
+ ctx.on('internal/update', config => this.update(config))
123
+ }
124
+
125
+ async* [Service.init]() {
126
+ yield () => this.stop()
127
+ await this.update(this.config)
128
+ }
129
+ }
@@ -0,0 +1,173 @@
1
+ import { Context } from '@deepseek-ai/cordis'
2
+ import type { Dict } from '@deepseek-ai/cosmokit'
3
+ import { Entry } from './entry.ts'
4
+
5
+ declare module './entry.ts' {
6
+ interface EntryOptions {
7
+ intercept?: Dict | null
8
+ isolate?: Dict<true | string> | null
9
+ }
10
+
11
+ interface Entry {
12
+ realm: LocalRealm
13
+ }
14
+ }
15
+
16
+ function swap<T extends {}>(target: T, source?: T | null) {
17
+ for (const key of Reflect.ownKeys(target)) {
18
+ Reflect.deleteProperty(target, key)
19
+ }
20
+ for (const key of Reflect.ownKeys(source || {})) {
21
+ Reflect.defineProperty(target, key, Reflect.getOwnPropertyDescriptor(source!, key)!)
22
+ }
23
+ }
24
+
25
+ /** Symbol realm used to isolate service implementations by entry or label. */
26
+ export abstract class Realm {
27
+ protected store: Dict<symbol> = Object.create(null)
28
+
29
+ abstract get suffix(): string
30
+
31
+ access(key: string, create = false) {
32
+ if (create) {
33
+ return this.store[key] ??= Symbol(`${key}${this.suffix}`)
34
+ } else {
35
+ return this.store[key] ?? Symbol(`${key}${this.suffix}`)
36
+ }
37
+ }
38
+
39
+ delete(key: string) {
40
+ delete this.store[key]
41
+ }
42
+
43
+ get size() {
44
+ return Object.keys(this.store).length
45
+ }
46
+ }
47
+
48
+ /** Entry-local isolation realm. */
49
+ export class LocalRealm extends Realm {
50
+ constructor(private entry: Entry) {
51
+ super()
52
+ }
53
+
54
+ get suffix() {
55
+ return '#' + this.entry.options.id
56
+ }
57
+ }
58
+
59
+ /** Named isolation realm shared by entries that use the same label. */
60
+ export class GlobalRealm extends Realm {
61
+ constructor(public label: string) {
62
+ super()
63
+ }
64
+
65
+ get suffix() {
66
+ return '@' + this.label
67
+ }
68
+ }
69
+
70
+ /** Install loader hooks that apply `intercept` and `isolate` entry options. */
71
+ export default function isolate(ctx: Context) {
72
+ const realms: Dict<GlobalRealm> = Object.create(null)
73
+ const delims: Dict<symbol> = Object.create(null)
74
+
75
+ function access(entry: Entry, name: string, create: true): symbol
76
+ function access(entry: Entry, name: string, create?: boolean): symbol | undefined
77
+ function access(entry: Entry, name: string, create = false) {
78
+ let realm: Realm | undefined
79
+ const label = entry.options.isolate?.[name]
80
+ if (!label) return
81
+ if (label === true) {
82
+ realm = entry.realm ??= new LocalRealm(entry)
83
+ } else if (create) {
84
+ realm = realms[label] ??= new GlobalRealm(label)
85
+ } else {
86
+ realm = realms[label]
87
+ }
88
+ return realm?.access(name, create)
89
+ }
90
+
91
+ ctx.on('loader/entry-init', (entry) => {
92
+ entry.ctx[Context.intercept] = Object.create(entry.ctx[Context.intercept])
93
+ entry.ctx[Context.isolate] = Object.create(entry.ctx[Context.isolate])
94
+ })
95
+
96
+ ctx.on('loader/patch-context', async (entry, next) => {
97
+ // step 1: generate new isolate map
98
+ const newMap: Dict<symbol> = Object.create(entry.parent.ctx[Context.isolate])
99
+ for (const name of Object.keys(entry.options.isolate ?? {})) {
100
+ newMap[name] = access(entry, name, true)
101
+ }
102
+
103
+ // step 2: generate service diff
104
+ const diff: Dict<[symbol, symbol, symbol, symbol]> = Object.create(null)
105
+ const oldMap = entry.ctx[Context.isolate]
106
+ for (const name in { ...newMap, ...delims }) {
107
+ if (newMap[name] === oldMap[name]) continue
108
+ const delim = delims[name] ??= Symbol(`delim:${name}`)
109
+ entry.ctx[delim] = Symbol(`${name}#${entry.id}`)
110
+ for (const symbol of [oldMap[name], newMap[name]]) {
111
+ const impl = symbol && entry.ctx.reflect.store[symbol]
112
+ if (!impl) continue
113
+ if (!impl.fiber) {
114
+ entry.ctx.logger.warn(new Error(`expected service ${name} to be implemented`))
115
+ continue
116
+ }
117
+ diff[name] = [oldMap[name], newMap[name], entry.ctx[delim], impl.fiber.ctx[delim]]
118
+ if (entry.ctx[delim] !== impl.fiber.ctx[delim]) break
119
+ }
120
+ }
121
+
122
+ // step 3: set prototype for transferred context
123
+ Object.setPrototypeOf(entry.ctx[Context.isolate], entry.parent.ctx[Context.isolate])
124
+ Object.setPrototypeOf(entry.ctx[Context.intercept], entry.parent.ctx[Context.intercept])
125
+ swap(entry.ctx[Context.isolate], newMap)
126
+ swap(entry.ctx[Context.intercept], entry.options.intercept)
127
+
128
+ // step 4: reload fiber
129
+ await next()
130
+
131
+ // step 5: replace service impl
132
+ for (const [symbol1, symbol2, flag1, flag2] of Object.values(diff)) {
133
+ if (flag1 === flag2 && entry.ctx.reflect.store[symbol1] && !entry.ctx.reflect.store[symbol2]) {
134
+ entry.ctx.reflect.store[symbol2] = entry.ctx.reflect.store[symbol1]
135
+ delete entry.ctx.reflect.store[symbol1]
136
+ }
137
+ }
138
+
139
+ // step 6: reflect notify
140
+ ctx.reflect.notify(Object.keys(diff), (ctx, name) => {
141
+ const [symbol1, symbol2, flag1, flag2] = diff[name]
142
+ const symbol3 = ctx[Context.isolate][name]
143
+ const flag3 = ctx[delims[name]]
144
+ return (symbol1 === symbol3 || symbol2 === symbol3) && (flag1 === flag3) !== (flag1 === flag2)
145
+ })
146
+
147
+ // step 7: clean up delimiters
148
+ for (const name in delims) {
149
+ if (!Reflect.ownKeys(newMap).includes(name)) {
150
+ delete entry.ctx[delims[name]]
151
+ }
152
+ }
153
+ })
154
+
155
+ ctx.on('loader/partial-dispose', (entry, legacy, active) => {
156
+ for (const [name, label] of Object.entries(legacy.isolate ?? {})) {
157
+ if (label === true) continue
158
+ if (active && entry.options.isolate?.[name] === label) continue
159
+ const realm = realms[label]
160
+ if (!realm) continue
161
+
162
+ // realm garbage collection
163
+ for (const entry of ctx.loader.entries()) {
164
+ // has reference to this realm
165
+ if (entry.options.isolate?.[name] === realm.label) return
166
+ }
167
+ realm.delete(name)
168
+ if (!realm.size) {
169
+ delete realms[realm.label]
170
+ }
171
+ }
172
+ })
173
+ }