| 1 | import { Context, Inject, Service } from '@deepseek-ai/cordis' |
| 2 | import { defineProperty, isNullable, type Awaitable, type Dict } from '@deepseek-ai/cosmokit' |
| 3 | import { ModuleLoader } from './internal.ts' |
| 4 | import { Entry, type EntryOptions } from './config/entry.ts' |
| 5 | import { EntryGroup } from './config/group.ts' |
| 6 | import isolate from './config/isolate.ts' |
| 7 | import { EntryTree, type EntryChange } from './config/tree.ts' |
| 8 | import { interpolate } from './config/utils.ts' |
| 9 | import { FiberState } from '../../../fiber-state.ts' |
| 10 | |
| 11 | /** Re-export entry node APIs. */ |
| 12 | export * from './config/entry.ts' |
| 13 | /** Re-export nested entry group APIs. */ |
| 14 | export * from './config/group.ts' |
| 15 | /** Re-export service isolation helpers. */ |
| 16 | export * from './config/isolate.ts' |
| 17 | /** Re-export entry tree persistence APIs. */ |
| 18 | export * from './config/tree.ts' |
| 19 | /** Re-export loader config expression helpers. */ |
| 20 | export * from './config/utils.ts' |
| 21 | /** Re-export Node internal module loader compatibility types. */ |
| 22 | export * from './internal.ts' |
| 23 | |
| 24 | declare module '@deepseek-ai/cordis' { |
| 25 | interface Events { |
| 26 | 'exit'(signal: NodeJS.Signals): Promise<void> |
| 27 | 'loader/config-update'(): void |
| 28 | 'loader/entry-init'(entry: Entry): void |
| 29 | 'loader/partial-dispose'(entry: Entry, legacy: Partial<EntryOptions>, active: boolean): void |
| 30 | /** |
| 31 | * Volatile config values were committed into the running fiber without a remount; dispatched to the owning fiber only. |
| 32 | * @param paths - changed config paths as key arrays; every value is committed before dispatch. |
| 33 | * @mode emit |
| 34 | */ |
| 35 | 'loader/volatile-update'(paths: readonly (readonly string[])[]): void |
| 36 | /** |
| 37 | * Refresh entry context before applying config. |
| 38 | * @param entry - entry containing the new raw config and optional current fiber. |
| 39 | * @param next - continue context refresh and Loader's config update. |
| 40 | * @mode waterfall |
| 41 | */ |
| 42 | 'loader/patch-context'(entry: Entry, next: () => Awaitable<void>): Awaitable<void> |
| 43 | } |
| 44 | |
| 45 | interface Context { |
| 46 | loader: Loader |
| 47 | [Entry.key]?: Entry |
| 48 | } |
| 49 | |
| 50 | interface EnvData { |
| 51 | startTime?: number |
| 52 | } |
| 53 | |
| 54 | interface Fiber { |
| 55 | entry?: Entry |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** Loader config and dependency intercept namespace. */ |
| 60 | export namespace Loader { |
| 61 | /** Root loader configuration. */ |
| 62 | export interface Config { |
| 63 | /** Base URL used to resolve relative plugin specifiers and config paths. */ |
| 64 | baseUrl?: string |
| 65 | } |
| 66 | |
| 67 | /** Intercept config used when other plugins depend on `loader`. */ |
| 68 | export interface Intercept { |
| 69 | /** Keep dependent plugins pending while loader entries are still loading. */ |
| 70 | await?: boolean |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Service that owns a loader entry tree and imports configured plugins. |
| 76 | * |
| 77 | * Subclasses provide persistence by implementing `commit(change)` on `EntryTree`. |
| 78 | */ |
| 79 | export class Loader extends EntryTree { |
| 80 | declare [Service.config]: Loader.Intercept |
| 81 | |
| 82 | public envData = process.env.CORDIS_SHARED |
| 83 | ? JSON.parse(process.env.CORDIS_SHARED) |
| 84 | : { startTime: Date.now() } |
| 85 | |
| 86 | public name = 'loader' |
| 87 | // Codewhale host delta: native internals/addon probing is unavailable. |
| 88 | // EntryTree retains upstream's documented native ESM fallback. |
| 89 | public internal: ModuleLoader | undefined = undefined |
| 90 | |
| 91 | public builtins: Dict<any> = Object.create(null) |
| 92 | |
| 93 | constructor(ctx: Context, public config: Loader.Config = {}) { |
| 94 | super(ctx) |
| 95 | if (config.baseUrl) { |
| 96 | this.ctx.baseUrl = config.baseUrl |
| 97 | } |
| 98 | const self = this |
| 99 | |
| 100 | defineProperty(this, Service.tracker, { |
| 101 | associate: 'loader', |
| 102 | property: 'ctx', |
| 103 | noShadow: true, |
| 104 | }) |
| 105 | |
| 106 | ctx.reflect.provide('loader', this, this[Service.check]) |
| 107 | |
| 108 | ctx.on('internal/config', (fiber, next) => { |
| 109 | const config = next() |
| 110 | if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return config |
| 111 | // Tree carriers preserve the expressions owned by their child entries. |
| 112 | if ((fiber.runtime?.callback as Record<PropertyKey, unknown> | undefined)?.[EntryGroup.key]) return config |
| 113 | return interpolate(fiber.ctx, config) |
| 114 | }) |
| 115 | |
| 116 | ctx.on('internal/commit', (fiber, config) => { |
| 117 | if (!fiber.entry || fiber.parent.fiber?.entry === fiber.entry) return |
| 118 | const schema = fiber.runtime?.Config |
| 119 | const unparse = (schema as { simplify?: (value: any) => any } | undefined)?.simplify |
| 120 | const { entry } = fiber |
| 121 | const legacy = { ...entry.options } |
| 122 | entry.options.config = unparse ? unparse.call(schema, config) : config |
| 123 | entry.parent.tree.commit({ id: entry.options.id, group: entry.parent, options: entry.options, legacy }) |
| 124 | }) |
| 125 | |
| 126 | ctx.on('internal/update', function (config, next) { |
| 127 | if (!this.entry || this.parent.fiber?.entry === this.entry) return next() |
| 128 | self.showLog(this.entry, 'reload') |
| 129 | return next() |
| 130 | }, { global: true }) |
| 131 | |
| 132 | ctx.on('internal/plugin', (fiber) => { |
| 133 | // 1. set `fiber.entry` |
| 134 | if (fiber.parent[Entry.key] && !fiber.entry) { |
| 135 | fiber.entry = fiber.parent[Entry.key] |
| 136 | // FIXME merge config |
| 137 | Inject.resolve(fiber.entry!.options.inject, fiber.inject) |
| 138 | } |
| 139 | |
| 140 | // 2. handle self-dispose |
| 141 | // We only care about `ctx.fiber.dispose()`, so we need to filter out other cases. |
| 142 | |
| 143 | // case 1: fiber is created |
| 144 | if (fiber.uid) return |
| 145 | |
| 146 | // case 2: fiber is not tracked by loader |
| 147 | if (!fiber.entry) return |
| 148 | |
| 149 | // case 3: fiber is a child plugin under the entry (not the entry's root fiber) |
| 150 | if (fiber.parent.fiber?.entry === fiber.entry) return |
| 151 | |
| 152 | // case 4: fiber is disposed on behalf of plugin deletion (such as plugin hmr) |
| 153 | // self-dispose: ctx.fiber.dispose() -> fiber / runtime dispose -> delete(plugin) |
| 154 | // plugin hmr: delete(plugin) -> runtime dispose -> fiber dispose |
| 155 | if (!ctx.registry.has(fiber.runtime!.callback)) return |
| 156 | |
| 157 | // case 5: the entry's tree is being disposed |
| 158 | if (!fiber.entry.parent.tree.ctx.fiber.uid) return |
| 159 | |
| 160 | const { entry } = fiber |
| 161 | this.showLog(entry, 'unload') |
| 162 | |
| 163 | // case 6: the entry's parent is being unloaded, which takes the entry with it |
| 164 | // (the parent may still be registered, e.g. when it has lost a dependency) |
| 165 | if (fiber.parent.fiber.state === FiberState.UNLOADING) return |
| 166 | |
| 167 | // case 7: the entry is being removed by the loader (`EntryGroup.remove` |
| 168 | // unregisters it before disposing the fiber) |
| 169 | if (entry.parent.tree.store[entry.options.id] !== entry) return |
| 170 | |
| 171 | // case 8: fiber is disposed by loader behavior |
| 172 | // such as inject checker, config file update, ancestor group disable |
| 173 | if (entry.disabled) return |
| 174 | |
| 175 | const legacy = { ...entry.options } |
| 176 | entry.options.disabled = true |
| 177 | entry.parent.tree.commit({ id: entry.options.id, group: entry.parent, options: entry.options, legacy }) |
| 178 | }) |
| 179 | |
| 180 | ctx.plugin(isolate) |
| 181 | } |
| 182 | |
| 183 | commit(_change: EntryChange) { |
| 184 | // Loader's root tree is in-memory; commits are no-ops. |
| 185 | } |
| 186 | |
| 187 | [Service.check]() { |
| 188 | const config: Loader.Intercept = Service.prototype[Service.resolveConfig].call(this) |
| 189 | if (config.await && this.getTasks().length) return false |
| 190 | return true |
| 191 | } |
| 192 | |
| 193 | showLog(entry: Entry, type: string) { |
| 194 | if (entry.options.group || !entry.parent.tree.enableLogs) return |
| 195 | this.ctx.root.logger?.('loader').info('%s plugin %C', type, entry.options.name) |
| 196 | } |
| 197 | |
| 198 | /** Return the loader entry id that owns `fiber`, if any. */ |
| 199 | locate(fiber = this.ctx.fiber) { |
| 200 | while (1) { |
| 201 | if (fiber.entry) return fiber.entry.id |
| 202 | const next = fiber.parent.fiber |
| 203 | if (fiber === next) return |
| 204 | fiber = next |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | /** Hook for hosts that can restart the process on full-reload requests. */ |
| 209 | exit() { |
| 210 | } |
| 211 | |
| 212 | /** Normalize ESM/CJS/default export shapes before applying a plugin. */ |
| 213 | unwrapExports(exports: any) { |
| 214 | if (isNullable(exports)) return exports |
| 215 | exports = exports.default ?? exports |
| 216 | // https://github.com/evanw/esbuild/issues/2623 |
| 217 | // https://esbuild.github.io/content-types/#default-interop |
| 218 | if (!exports.__esModule) return exports |
| 219 | return exports.default ?? exports |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | export default Loader |
| 224 |