| 1 | import { composeError, Context } from '@deepseek-ai/cordis' |
| 2 | import { isNonNullable, type Dict } from '@deepseek-ai/cosmokit' |
| 3 | import { Entry, type EntryOptions } from './entry.ts' |
| 4 | import { EntryGroup } from './group.ts' |
| 5 | |
| 6 | /** |
| 7 | * One tree-side mutation, reported to `EntryTree.commit()` synchronously after |
| 8 | * it has been applied to `entry.options` / `group.data`. |
| 9 | * |
| 10 | * - `options` absent: the entry was removed from `group`. |
| 11 | * - `legacy` absent: the entry was created in `group`. |
| 12 | * - both present: the entry was updated and now lives in `group`; `from` is |
| 13 | * the group it left if the update moved it within the same tree. A move to |
| 14 | * another tree reports a removal to the source tree and a creation to the |
| 15 | * destination tree. |
| 16 | * |
| 17 | * `id` is local to the receiving tree; `Entry.id` prefixes it with the parent |
| 18 | * tree's path. Only `EntryTree` mutation methods and explicit Fiber saves |
| 19 | * report changes; file-driven `EntryGroup` reconciliation does not. |
| 20 | */ |
| 21 | export interface EntryChange { |
| 22 | id: string |
| 23 | group: EntryGroup |
| 24 | from?: EntryGroup |
| 25 | options?: EntryOptions |
| 26 | legacy?: EntryOptions |
| 27 | } |
| 28 | |
| 29 | /** The entry and the same-tree members of its group, recursively. */ |
| 30 | function members(entry: Entry): Entry[] { |
| 31 | const { tree } = entry.parent |
| 32 | const result = [entry] |
| 33 | const group = entry.subgroup |
| 34 | if (group?.tree !== tree) return result |
| 35 | for (const options of group.data) { |
| 36 | const member = tree.store[options.id] |
| 37 | if (member?.parent === group) result.push(...members(member)) |
| 38 | } |
| 39 | return result |
| 40 | } |
| 41 | |
| 42 | /** Mutable tree of loader entries. Persistence is supplied by subclasses. */ |
| 43 | export abstract class EntryTree { |
| 44 | static readonly sep = ':' |
| 45 | |
| 46 | public ctx: Context |
| 47 | public enableLogs?: boolean |
| 48 | public root: EntryGroup |
| 49 | public store: Dict<Entry> = Object.create(null) |
| 50 | |
| 51 | constructor(ctx: Context) { |
| 52 | this.ctx = ctx.extend({ baseUrl: ctx.baseUrl }) |
| 53 | this.root = new EntryGroup(this.ctx, this) |
| 54 | const entry = this.ctx.fiber.entry |
| 55 | if (entry) entry.subtree = this |
| 56 | } |
| 57 | |
| 58 | get context(): Context { |
| 59 | return this.ctx |
| 60 | } |
| 61 | |
| 62 | /** Iterate entries in this tree and any nested subtrees. */ |
| 63 | * entries(): Generator<Entry, void, void> { |
| 64 | for (const entry of Object.values(this.store)) { |
| 65 | yield entry |
| 66 | if (!entry.subtree) continue |
| 67 | yield* entry.subtree.entries() |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /** Return pending import and lifecycle tasks owned by this tree. */ |
| 72 | getTasks() { |
| 73 | return [...this.entries()] |
| 74 | .map(entry => entry._initTask || entry.fiber?.inertia) |
| 75 | .filter(isNonNullable) |
| 76 | } |
| 77 | |
| 78 | /** Wait until this tree has no pending import or lifecycle tasks. */ |
| 79 | async await() { |
| 80 | while (true) { |
| 81 | const tasks = this.getTasks() |
| 82 | if (!tasks.length) return |
| 83 | await Promise.allSettled(tasks) |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Assign a random tree-local id when `options.id` is absent. Explicit ids |
| 89 | * may contain `EntryTree.sep`; `resolve()` and `resolveGroup()` cannot |
| 90 | * address such entries by nested path. |
| 91 | * @param options - Entry options; a generated id is written to `options.id`. |
| 92 | * @returns The existing or generated id. |
| 93 | */ |
| 94 | ensureId(options: Partial<EntryOptions>) { |
| 95 | if (!options.id) { |
| 96 | do { |
| 97 | options.id = Math.random().toString(16).slice(2, 10) |
| 98 | } while (this.store[options.id]) |
| 99 | } |
| 100 | return options.id! |
| 101 | } |
| 102 | |
| 103 | /** Resolve an entry by id, including nested ids separated by `EntryTree.sep`. */ |
| 104 | resolve(id: string) { |
| 105 | const parts = id.split(EntryTree.sep) |
| 106 | let tree: EntryTree | undefined = this |
| 107 | const final = parts.pop()! |
| 108 | for (const part of parts) { |
| 109 | tree = tree.store[part]?.subtree |
| 110 | if (!tree) throw new Error(`cannot resolve entry ${id}`) |
| 111 | } |
| 112 | const entry = tree.store[final] |
| 113 | if (!entry) throw new Error(`cannot resolve entry ${id}`) |
| 114 | return entry |
| 115 | } |
| 116 | |
| 117 | resolveGroup(id: string | null) { |
| 118 | if (!id) return this.root |
| 119 | const entry = this.resolve(id) |
| 120 | if (!entry.subgroup) throw new Error(`entry ${id} is not a group`) |
| 121 | return entry.subgroup |
| 122 | } |
| 123 | |
| 124 | /** Create an entry in the root group or a nested group. */ |
| 125 | async create(options: Omit<EntryOptions, 'id'>, parent: string | null = null, position = Infinity) { |
| 126 | const group = this.resolveGroup(parent) |
| 127 | const id = group.tree.ensureId(options) |
| 128 | group.data.splice(position, 0, options as EntryOptions) |
| 129 | group.tree.commit({ id, group, options: options as EntryOptions }) |
| 130 | return group.create(options) |
| 131 | } |
| 132 | |
| 133 | /** Stop and remove an entry from its parent group. */ |
| 134 | remove(id: string) { |
| 135 | const entry = this.resolve(id) |
| 136 | const group = entry.parent |
| 137 | const legacy = entry.options |
| 138 | group.remove(legacy.id) |
| 139 | group.tree.commit({ id: legacy.id, group, legacy }) |
| 140 | } |
| 141 | |
| 142 | /** Update an entry and optionally move it to another group. */ |
| 143 | async update(id: string, options: Omit<EntryOptions, 'id' | 'name'>, parent?: string | null, position?: number) { |
| 144 | const entry = this.resolve(id) |
| 145 | const source = entry.parent |
| 146 | const legacy = { ...entry.options } |
| 147 | if (parent !== undefined) { |
| 148 | const target = this.resolveGroup(parent) |
| 149 | const moved = target.tree === source.tree ? [] : members(entry) |
| 150 | for (const member of moved) { |
| 151 | const { id } = member.options |
| 152 | if (target.tree.store[id]) throw new Error(`entry ${id} already exists in the target tree`) |
| 153 | } |
| 154 | source.unlink(entry.options) |
| 155 | target.data.splice(position ?? Infinity, 0, entry.options) |
| 156 | entry.parent = target |
| 157 | // The target tree owns the moved entries from now on, so that it adopts |
| 158 | // them instead of creating new ones when it reconciles its source. |
| 159 | for (const member of moved) { |
| 160 | delete source.tree.store[member.options.id] |
| 161 | target.tree.store[member.options.id] = member |
| 162 | if (member.subgroup?.tree === source.tree) member.subgroup.tree = target.tree |
| 163 | } |
| 164 | } |
| 165 | // `Entry.update` assigns the new options before its first `await`, so the |
| 166 | // change is fully visible to `commit()` once the call returns. |
| 167 | const task = entry.update(options, false, true) |
| 168 | if (entry.parent.tree !== source.tree) { |
| 169 | // a move across trees removes the entry from the source tree and |
| 170 | // creates it in the target tree |
| 171 | source.tree.commit({ id: legacy.id, group: source, legacy }) |
| 172 | entry.parent.tree.commit({ id: legacy.id, group: entry.parent, options: entry.options }) |
| 173 | } else { |
| 174 | const from = entry.parent === source ? undefined : source |
| 175 | entry.parent.tree.commit({ id: legacy.id, group: entry.parent, from, options: entry.options, legacy }) |
| 176 | } |
| 177 | return task |
| 178 | } |
| 179 | |
| 180 | /** Import a plugin module from a specifier or `cordis:` builtin. */ |
| 181 | import(name: string, getOuterStack?: () => string[]) { |
| 182 | if (name.startsWith('cordis:')) { |
| 183 | return this.ctx.loader.builtins[name.slice(7)] |
| 184 | } |
| 185 | return composeError(async (info) => { |
| 186 | // ModuleJob.run |
| 187 | // onImport.tracePromise.__proto__ |
| 188 | // internal.import |
| 189 | info.offset += 3 |
| 190 | if (this.ctx.loader.internal) { |
| 191 | return await this.ctx.loader.internal.import(name, this.ctx.baseUrl!, {}) |
| 192 | } else if (name.startsWith('.')) { |
| 193 | return await import(/* @vite-ignore */new URL(name, this.ctx.baseUrl).href) |
| 194 | } else { |
| 195 | return await import(/* @vite-ignore */name) |
| 196 | } |
| 197 | }, getOuterStack) |
| 198 | } |
| 199 | |
| 200 | /** Report an applied mutation synchronously. In-memory trees may use a no-op. */ |
| 201 | abstract commit(change: EntryChange): void |
| 202 | } |
| 203 |