@deepseek-ai/cordis-plugin-include 1.0.11-alpha.1 → 1.1.0

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/src/index.ts CHANGED
@@ -1,10 +1,17 @@
1
- import { EntryGroup, EntryTree, isJsExpr, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
1
+ import { type EntryChange, type EntryOptions, EntryTree, EntryGroup, isJsExpr } from '@deepseek-ai/cordis-plugin-loader'
2
2
  import { Context, Service } from '@deepseek-ai/cordis'
3
- import { extname } from 'node:path'
4
- import { access, constants, readFile, rename, writeFile } from 'node:fs/promises'
5
- import { setTimeout as delay } from 'node:timers/promises'
3
+ import { deepEqual } from '@deepseek-ai/cosmokit'
4
+ import { basename, dirname, extname, join } from 'node:path'
5
+ import { access, constants, readFile, rename, rm, writeFile } from 'node:fs/promises'
6
+ import { setTimeout as sleep } from 'node:timers/promises'
6
7
  import { fileURLToPath, pathToFileURL } from 'node:url'
7
8
  import * as yaml from 'js-yaml'
9
+ import { applyJournal, flatten, type Journal, merge, reconcile, record } from './journal.ts'
10
+ import { applyPatches, ensureIds, ensureInsertIds, PatchIndex, type PatchOptions, routeJournal } from './patch.ts'
11
+ /** Shared patch semantics used by config dumps and mounting. */
12
+ export { applyPatches as applyEntryPatches } from './patch.ts'
13
+ /** Serialized entry patch options. */
14
+ export type { PatchOptions } from './patch.ts'
8
15
 
9
16
  const JsExpr = new yaml.Type('tag:yaml.org,2002:js', {
10
17
  kind: 'scalar',
@@ -14,329 +21,444 @@ const JsExpr = new yaml.Type('tag:yaml.org,2002:js', {
14
21
  represent: (data) => data['__jsExpr'],
15
22
  })
16
23
 
17
- /**
18
- * The entry-list YAML dialect: `!!js` scalars round-trip as expression nodes
19
- * the Loader evaluates at entry activation. Exported so config tooling
20
- * (`dsh --dump-config`) parses and prints exactly the dialect this include
21
- * mounts.
22
- */
24
+ /** YAML dialect preserving child-owned JavaScript expression nodes. */
23
25
  export const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr)
24
-
25
26
  const schema = entryListSchema
26
27
 
27
- const writable: Record<string, string> = {
28
+ const types: Record<string, string> = {
28
29
  '.json': 'application/json',
29
30
  '.yaml': 'application/yaml',
30
31
  '.yml': 'application/yaml',
31
32
  }
32
33
 
33
- const supported = new Set(Object.keys(writable))
34
-
35
- const WRITE_RETRY_LIMIT = 10
36
- const WRITE_RETRY_DELAY_MS = 50
34
+ type ConfigStage = 'read' | 'parse' | 'validate'
37
35
 
38
- function retryableWriteError(error: unknown): boolean {
39
- const code = (error as NodeJS.ErrnoException | null)?.code
40
- return code === 'EACCES' || code === 'EBUSY' || code === 'EPERM'
36
+ interface Snapshot {
37
+ content: string
38
+ data: EntryOptions[]
41
39
  }
42
40
 
43
- /**
44
- * Apply patch lists to an entry list — THE patch semantics of this include,
45
- * shared by mounting (`applyPatches`) and offline config tooling
46
- * (`dsh --dump-config`) so a dump can never drift from what boots. The input
47
- * is never mutated: patching shared entry objects would bake earlier patch
48
- * values into the cached parse, so repeated application (config hot-reloads)
49
- * could never revert a removed or changed patch. Inserted entries are indexed
50
- * as they are added, so a later patch in the same list can target a row an
51
- * earlier patch inserted. A patch that matches nothing warns and is skipped.
52
- * @param data - the parsed entry list (JSON-safe plain data).
53
- * @param patches - the patch list to apply, in order.
54
- * @param warn - sink for skipped-patch diagnostics (printf-style, `%C` = code).
55
- * @returns a detached entry list with every applicable patch applied.
56
- */
57
- export function applyEntryPatches(
58
- data: EntryOptions[],
59
- patches: PatchOptions[] | undefined,
60
- warn: (message: string, ...args: any[]) => void,
61
- ): EntryOptions[] {
62
- if (!patches?.length) return [...data]
63
- data = structuredClone(data)
64
-
65
- const entryMap = new Map<string, EntryOptions>()
66
- const buildMap = (entries: EntryOptions[]) => {
67
- for (const entry of entries) {
68
- if (entry.id) entryMap.set(entry.id, entry)
69
- if (entry.group && Array.isArray(entry.config)) {
70
- buildMap(entry.config)
71
- }
72
- }
73
- }
74
- buildMap(data)
75
-
76
- for (const patch of patches) {
77
- const { id, insert, name, ...overrides } = patch
78
-
79
- if (insert) {
80
- if (id) {
81
- const target = entryMap.get(id)
82
- if (!target) {
83
- warn('patch insert: entry %C not found', id)
84
- continue
85
- }
86
- if (!target.group) {
87
- warn('patch insert: entry %C is not a group', id)
88
- continue
89
- }
90
- if (!Array.isArray(target.config)) target.config = []
91
- target.config.push(...insert)
92
- } else {
93
- data.push(...insert)
94
- }
95
- // Index what this patch added so a LATER patch in the same list can
96
- // target it. Patch lists compose one layer per source (each bundle
97
- // layer, then the user's, then `--patch` overlays), and a layer must be
98
- // able to configure or disable a row an earlier layer inserted; without
99
- // this, inserted rows were silently unpatchable.
100
- buildMap(insert)
101
- continue
102
- }
41
+ export class ConfigFileError extends Error {
42
+ name = 'ConfigFileError'
103
43
 
104
- if (!id) {
105
- warn('patch: id is required for non-insert patches')
106
- continue
107
- }
108
-
109
- const target = entryMap.get(id)
110
- if (!target) {
111
- warn('patch: entry %C not found', id)
112
- continue
113
- }
44
+ constructor(public stage: ConfigStage, path: string, cause: unknown) {
45
+ super(`failed to ${stage} config file ${path}`, { cause })
46
+ }
47
+ }
114
48
 
115
- if (name && name !== target.name) {
116
- warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name)
117
- continue
118
- }
49
+ /** The file changed under us between the pre-check and the rename. */
50
+ class StaleWriteError extends Error {
51
+ name = 'StaleWriteError'
52
+ }
119
53
 
120
- for (const [key, value] of Object.entries(overrides)) {
121
- if (key === 'id') continue
122
- target[key] = value
123
- }
124
- }
54
+ interface Anonymous {
55
+ parent: string | null
56
+ options: EntryOptions
57
+ }
125
58
 
126
- return data
59
+ function isENOENT(error: unknown) {
60
+ return (error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'
127
61
  }
128
62
 
129
- /** Runtime patch applied to entries loaded from an included config file. */
130
- export interface PatchOptions {
131
- id?: string
132
- insert?: EntryOptions[]
133
- name?: string
134
- config?: any
135
- group?: boolean | null
136
- disabled?: boolean | null
137
- inject?: any
138
- intercept?: any
139
- isolate?: any
140
- [key: string]: any
63
+ const RENAME_RETRIES = 10
64
+ const RENAME_BACKOFF = 20
65
+
66
+ /**
67
+ * On Windows a rename over a file that another process holds open (typically
68
+ * an antivirus scanning what we just wrote) fails with one of these; the lock
69
+ * is normally gone within milliseconds. A bounded retry is cheap enough to
70
+ * apply on every platform.
71
+ */
72
+ function isTransientRenameError(error: unknown) {
73
+ const code = (error as NodeJS.ErrnoException | undefined)?.code
74
+ return code === 'EACCES' || code === 'EPERM' || code === 'EBUSY'
141
75
  }
142
76
 
143
- /** Config namespace for the file-backed include loader. */
144
77
  export namespace Include {
145
- /** Config for a file-backed loader subtree. */
146
78
  export interface Config {
147
- /** YAML or JSON path resolved from `ctx.baseUrl`. */
148
79
  path: string
149
- /** Entry list written when the file does not already exist. */
150
80
  initial?: any[]
151
- /** Runtime patches applied after reading the file. */
152
81
  patches?: PatchOptions[]
153
- /** Enables loader apply/reload/unload logs for this subtree. */
154
82
  enableLogs?: boolean
155
83
  }
156
84
  }
157
85
 
158
- /** Loader entry tree backed by a YAML or JSON file. */
159
86
  export class Include extends EntryTree {
160
87
  static inject = ['loader']
161
88
 
162
- // Tree-carrier marker (the Group plugin declares the same): this config is
163
- // entry and patch lists, so the Loader's `internal/config` interpolation
164
- // keeps it literal — a `!!js` expression inside a nested row's config
165
- // belongs to that row's fiber, resolving lazily in the row's own context.
166
- // Include's own fields (`path`, `enableLogs`) therefore stay literal too.
89
+ // Child entries evaluate their expressions against their own injections.
167
90
  static readonly [EntryGroup.key] = true
168
91
 
169
92
  public filename: string
170
- private type?: string
171
- private readonly: boolean
172
- private content?: string
173
- private data?: EntryOptions[]
174
- private writeTask?: NodeJS.Timeout | undefined
175
- private pendingWrite?: EntryOptions[]
176
- private writeQueue: Promise<void> = Promise.resolve()
93
+ private type: string
94
+
95
+ /** The last file state we read or wrote. */
96
+ private cache?: Snapshot
97
+ /** Tree-side changes that have not reached the file yet. */
98
+ private journal: Journal = new Map()
99
+ /** Ids we assigned to entries the file leaves anonymous. */
100
+ private anonymous = new Map<string, Anonymous>()
101
+
102
+ private dirtyRead = false
103
+ private dirtyWrite = false
104
+ private _draining?: Promise<void>
105
+
106
+ /** Only the latest intended tree is ever applied; older ones are skipped. */
107
+ private _pendingTree?: EntryOptions[]
108
+ private _applyTask?: Promise<void>
109
+
110
+ private _disposed = false
111
+ private _seq = 0
112
+ private persistenceError: unknown
177
113
 
178
114
  constructor(ctx: Context, public config: Include.Config) {
179
115
  super(ctx)
180
116
  this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false
181
117
  this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl))
182
118
  const ext = extname(this.filename)
183
- if (!supported.has(ext)) {
119
+ if (!types[ext]) {
184
120
  throw new Error(`extension "${ext}" not supported`)
185
121
  }
186
- this.type = writable[ext]
187
- this.readonly = !this.type
122
+ this.type = types[ext]
188
123
  this.ctx.baseUrl = new URL('.', pathToFileURL(this.filename)).href
124
+ ensureInsertIds(config.patches, id => !!this.store[id])
189
125
 
190
- ctx.on('internal/update', (config, _, next) => {
126
+ ctx.on('internal/update', (config, next) => {
191
127
  if (config.path !== this.config.path) return next()
192
- // Veto the fiber restart (children update in place), but persist the new
193
- // config ourselves — `Fiber.update` only assigns `this.config` behind
194
- // `next()`, and a stale `this.config.patches` would make the next
195
- // `refresh()` re-apply the old overlay.
196
128
  this.config = config
197
- this.root.update(this.applyPatches(this.data!, config.patches)).catch((error) => {
198
- this.ctx.logger.warn('config update at %C failed', this.filename)
199
- this.ctx.logger.warn(error)
200
- })
129
+ ensureInsertIds(config.patches, id => !!this.store[id])
130
+ this._scheduleApply()
131
+ return this._applyTask
201
132
  })
202
133
  }
203
134
 
204
- private async checkAccess() {
205
- if (!this.type) return
206
- try {
207
- await access(this.filename, constants.W_OK)
208
- } catch {
209
- this.readonly = true
210
- }
211
- }
212
-
213
- private async read(forced = false) {
214
- const content = await readFile(this.filename, 'utf8')
215
- if (!forced && this.content === content) return false
216
- let data: any
217
- if (this.type === 'application/yaml') {
218
- data = yaml.load(content, { schema: entryListSchema })
219
- } else if (this.type === 'application/json') {
220
- data = JSON.parse(content)
221
- } else {
222
- const module = await import(/* @vite-ignore */ this.filename)
223
- data = module.default || module
224
- }
225
- // An empty or truncated file (common mid-edit: editors and `sed -i` write
226
- // through temp states) parses to `undefined`, not an error; reject every
227
- // non-array shape here so callers see one "invalid file" signal. Content
228
- // and data commit only on success, so an edit that is later reverted to
229
- // the exact last good content correctly reads as "unchanged".
230
- if (!Array.isArray(data)) {
231
- throw new TypeError(`config file must be a top-level array of entries: ${this.filename}`)
232
- }
233
- this.content = content
234
- this.data = data
235
- await this.checkAccess()
236
- return true
237
- }
238
-
239
- private applyPatches(data: EntryOptions[], patches = this.config.patches): EntryOptions[] {
240
- return applyEntryPatches(data, patches, (message, ...args) => {
241
- this.ctx.root.logger?.('loader').warn(message, ...args)
242
- })
135
+ private warn = (format: string, ...args: any[]) => {
136
+ this.ctx.root.logger?.('loader').warn(format, ...args)
243
137
  }
244
138
 
245
139
  async* [Service.init]() {
246
140
  try {
247
- await this.read()
141
+ await this._read()
248
142
  } catch (error) {
249
- // Only a missing file falls back to `initial` (or the not-found error):
250
- // an existing-but-invalid file must fail loud with its real parse error,
251
- // never be mislabelled as absent or silently overwritten.
252
- if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') throw error
253
- if (this.config.initial) {
254
- await this._writeFile(this.config.initial as any)
255
- await this.read(true)
256
- } else {
143
+ // only a missing file falls back to `initial`
144
+ const cause = error instanceof ConfigFileError && error.stage === 'read' ? error.cause : undefined
145
+ if (!isENOENT(cause)) throw error
146
+ if (!this.config.initial) {
257
147
  throw new Error(`config file not found: ${this.filename}`)
258
148
  }
149
+ const initial = structuredClone(this.config.initial) as EntryOptions[]
150
+ ensureIds(initial, id => !!this.store[id])
151
+ await this._writeText(this.dump(initial))
152
+ await this._read()
259
153
  }
260
154
 
261
155
  yield () => this.stop()
262
- await this.root.update(this.applyPatches(this.data!))
156
+ await this._applyTask
263
157
  }
264
158
 
265
159
  async stop() {
160
+ this._disposed = true
161
+ this._pendingTree = undefined
162
+ // Flush what the user last did before the tree goes away; this is also the
163
+ // last attempt for changes a failed write left in the journal.
164
+ if (this.journal.size) {
165
+ this.dirtyWrite = true
166
+ this._drain()
167
+ }
266
168
  try {
267
- await this.flushWrite()
169
+ await this.flush()
268
170
  } finally {
269
171
  this.root.stop()
270
- await this.flushWrite()
271
172
  }
272
173
  }
273
174
 
274
175
  /**
275
- * Re-read the file and refresh child entries when content changed. An
276
- * unreadable or unparsable file logs a warning and keeps the last good
277
- * tree: a hot-reload of a live app must never take the process down.
176
+ * Resolves once every pending read and write has been processed and the
177
+ * tree reflects the outcome. Retries pending writes and rejects while changes remain unsaved.
278
178
  */
279
- async refresh() {
179
+ async flush() {
180
+ if (this.journal.size && !this._draining) {
181
+ this.dirtyWrite = true
182
+ this._drain()
183
+ }
184
+ while (this._draining || this._applyTask) {
185
+ await this._draining
186
+ await this._applyTask
187
+ }
188
+ if (this.journal.size) {
189
+ throw this.persistenceError ?? new Error(`config file ${this.filename} has ${this.journal.size} unsaved change(s)`)
190
+ }
191
+ this.persistenceError = undefined
192
+ }
193
+
194
+ /** Re-read the file and reconcile the tree with it. */
195
+ refresh() {
196
+ this.dirtyRead = true
197
+ this._drain()
198
+ return this.flush()
199
+ }
200
+
201
+ /** Called synchronously by the loader once a tree-side change is in place. */
202
+ commit(change: EntryChange) {
203
+ this.context.emit('loader/config-update')
204
+ const parent = change.group === this.root ? null : change.group.ctx.fiber.entry!.options.id
205
+ record(this.journal, change, parent)
206
+ this.dirtyWrite = true
207
+ this._drain()
208
+ }
209
+
210
+ private _drain() {
211
+ if (this._draining) return
212
+ this._draining = this._loop().finally(() => {
213
+ this._draining = undefined
214
+ })
215
+ }
216
+
217
+ private async _loop() {
218
+ while (this.dirtyRead || this.dirtyWrite) {
219
+ if (this.dirtyRead) {
220
+ this.dirtyRead = false
221
+ try {
222
+ await this._read()
223
+ } catch (error) {
224
+ // Half-written files are routine while the user is editing, hence
225
+ // only a warning. With the file in an unknown state there is nothing
226
+ // safe to write: unless another read is due, stop here and leave
227
+ // `dirtyWrite` set for the next trigger.
228
+ this.persistenceError = error
229
+ this.ctx.logger.warn(error)
230
+ if (this.dirtyRead) continue
231
+ return
232
+ }
233
+ }
234
+ if (this.dirtyWrite) {
235
+ this.dirtyWrite = false
236
+ try {
237
+ await this._write()
238
+ } catch (error) {
239
+ this.persistenceError = error
240
+ this.ctx.logger.error(error)
241
+ }
242
+ }
243
+ }
244
+ }
245
+
246
+ private async _read() {
247
+ let content: string
248
+ try {
249
+ content = await readFile(this.filename, 'utf8')
250
+ } catch (error) {
251
+ throw new ConfigFileError('read', this.filename, error)
252
+ }
253
+ if (content === this.cache?.content) return
254
+
255
+ let data: any
280
256
  try {
281
- if (!await this.read()) return
282
- await this.root.update(this.applyPatches(this.data!))
257
+ data = this.type === 'application/yaml'
258
+ ? yaml.load(content, { schema })
259
+ : JSON.parse(content)
283
260
  } catch (error) {
284
- this.ctx.logger.warn('config reload at %C failed; keeping the running tree', this.filename)
285
- this.ctx.logger.warn(error)
261
+ throw new ConfigFileError('parse', this.filename, error)
262
+ }
263
+ // An empty or truncated file (routine mid-edit) parses to `undefined`, so
264
+ // every non-array shape is rejected here as one "invalid file" signal.
265
+ if (!Array.isArray(data)) {
266
+ throw new ConfigFileError('validate', this.filename, new TypeError('config file must be a top-level array'))
286
267
  }
268
+
269
+ this._assignIds(data)
270
+
271
+ if (this.cache) {
272
+ const index = new PatchIndex(this.config.patches ?? [])
273
+ const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key))
274
+ for (const { id, reason } of conflicts) {
275
+ this.ctx.logger.error('config conflict in %C: entry %C %s; file wins', this.filename, id, reason)
276
+ }
277
+ }
278
+
279
+ this.cache = { content, data }
280
+ this._scheduleApply()
281
+ // the file changed while tree-side changes were pending: write the merge
282
+ if (this.journal.size) this.dirtyWrite = true
287
283
  }
288
284
 
289
- private async _writeFile(config: EntryOptions[]) {
290
- if (this.readonly) {
291
- throw new Error(`cannot overwrite readonly config`)
285
+ private async _write() {
286
+ if (!this.cache || !this.journal.size) return
287
+ const current = await readFile(this.filename, 'utf8').catch((error) => {
288
+ if (isENOENT(error)) return undefined
289
+ throw error
290
+ })
291
+ if (current === undefined) {
292
+ this.ctx.logger.warn('config file %C is missing, %d pending change(s) kept in memory', this.filename, this.journal.size)
293
+ return
292
294
  }
293
- if (this.type === 'application/yaml') {
294
- this.content = yaml.dump(config, { schema })
295
- } else if (this.type === 'application/json') {
296
- this.content = JSON.stringify(config, null, 2)
295
+ if (current !== this.cache.content) {
296
+ // someone else wrote the file: merge first, then come back
297
+ this.dirtyRead = true
298
+ this.dirtyWrite = true
299
+ return
297
300
  }
298
- await writeFile(this.filename + '.tmp', this.content!)
299
- for (let retry = 0; ; retry++) {
300
- try {
301
- await rename(this.filename + '.tmp', this.filename)
301
+
302
+ // Snapshot and swap: changes reported while we are writing belong to the
303
+ // next round.
304
+ const batch = this.journal
305
+ this.journal = new Map()
306
+ const restore = () => {
307
+ for (const [id, record] of this.journal) merge(batch, id, record)
308
+ this.journal = batch
309
+ }
310
+
311
+ const data = structuredClone(this.cache.data)
312
+ const patches = structuredClone(this.config.patches ?? [])
313
+ if (routeJournal(batch, data, patches, this.warn)) {
314
+ // Take the new patches now so that the tree scheduled below already
315
+ // reflects them; the round trip through the parent only persists them.
316
+ this.config = { ...this.config, patches }
317
+ if (this.ctx.fiber.entry) {
318
+ // Not awaited: the returned promise is the tree reconciliation, and
319
+ // the drain loop must not block on fibers.
320
+ try {
321
+ Promise.resolve(this.ctx.fiber.update(this.config)).catch((error) => {
322
+ this.ctx.logger.error(error)
323
+ })
324
+ } catch (error) {
325
+ this.ctx.logger.error(error)
326
+ }
327
+ } else {
328
+ this.ctx.logger.warn('patches of %C changed at runtime but cannot be persisted', this.filename)
329
+ }
330
+ }
331
+
332
+ // nothing for the file itself (patch-only changes, or ids we assigned to
333
+ // anonymous entries that are already part of the cache)
334
+ if (deepEqual(data, this.cache.data)) {
335
+ this._scheduleApply()
336
+ return
337
+ }
338
+ const text = this.dump(data)
339
+
340
+ try {
341
+ await access(this.filename, constants.W_OK)
342
+ } catch {
343
+ restore()
344
+ this.ctx.logger.warn('config file %C is read-only, %d pending change(s) kept in memory', this.filename, this.journal.size)
345
+ return
346
+ }
347
+
348
+ try {
349
+ await this._writeText(text, this.cache.content)
350
+ } catch (error) {
351
+ restore()
352
+ if (error instanceof StaleWriteError) {
353
+ this.dirtyRead = true
354
+ this.dirtyWrite = true
302
355
  return
303
- } catch (error) {
304
- if (!retryableWriteError(error) || retry >= WRITE_RETRY_LIMIT) throw error
305
- await delay((retry + 1) * WRITE_RETRY_DELAY_MS)
306
356
  }
357
+ this.ctx.logger.warn('failed to write config file %C, %d pending change(s) kept in memory', this.filename, this.journal.size)
358
+ throw error
307
359
  }
360
+ this.cache = { content: text, data }
361
+ this._scheduleApply()
308
362
  }
309
363
 
310
- private writeFile(config: EntryOptions[]) {
311
- clearTimeout(this.writeTask)
312
- this.pendingWrite = config
313
- this.writeTask = setTimeout(() => {
314
- void this.flushWrite()
315
- }, 0)
364
+ /**
365
+ * Write through a temp file and a rename, so that no reader ever sees a
366
+ * truncated file. When `expected` is given, the rename (and every retry of
367
+ * it) only goes ahead while the file still holds that content.
368
+ */
369
+ private async _writeText(text: string, expected?: string) {
370
+ const tmp = join(dirname(this.filename), `.${basename(this.filename)}.${process.pid}.${this._seq++}.tmp`)
371
+ try {
372
+ await writeFile(tmp, text)
373
+ for (let attempt = 0; ; attempt++) {
374
+ if (expected !== undefined) {
375
+ const current = await readFile(this.filename, 'utf8').catch((error) => {
376
+ if (isENOENT(error)) return undefined
377
+ throw error
378
+ })
379
+ if (current !== expected) throw new StaleWriteError()
380
+ }
381
+ try {
382
+ await rename(tmp, this.filename)
383
+ return
384
+ } catch (error) {
385
+ if (attempt >= RENAME_RETRIES || !isTransientRenameError(error)) throw error
386
+ }
387
+ await sleep(RENAME_BACKOFF * (attempt + 1))
388
+ }
389
+ } catch (error) {
390
+ await rm(tmp, { force: true }).catch(() => {})
391
+ throw error
392
+ }
316
393
  }
317
394
 
318
- private flushWrite(): Promise<void> {
319
- clearTimeout(this.writeTask)
320
- this.writeTask = undefined
321
- const config = this.pendingWrite
322
- this.pendingWrite = undefined
323
- if (config === undefined) return this.writeQueue
324
- const run = this.writeQueue.then(
325
- () => this._writeFile(config),
326
- () => this._writeFile(config),
327
- )
328
- this.writeQueue = run
329
- void run.catch((error) => {
330
- this.ctx.root.logger?.('loader').warn('failed to write config file %C', this.filename)
331
- this.ctx.root.logger?.('loader').warn(error)
332
- })
333
- return run
395
+ private dump(data: EntryOptions[]) {
396
+ return this.type === 'application/yaml'
397
+ ? yaml.dump(data, { schema })
398
+ : JSON.stringify(data, null, 2)
334
399
  }
335
400
 
336
- /** Schedule a write of the current root entry data. */
337
- write() {
338
- this.context.emit('loader/config-update')
339
- return this.writeFile(this.root.data)
401
+ /**
402
+ * Entries the file leaves anonymous get an id here, before the loader sees
403
+ * them. One that looks exactly like an entry we named on the previous read
404
+ * keeps that id, so editing a neighbor does not restart it; anything else
405
+ * gets a fresh id. Assigned ids stay in memory until the next write.
406
+ */
407
+ private _assignIds(data: EntryOptions[]) {
408
+ const used = new Set<string>()
409
+ const pending: { options: EntryOptions; parent: string | null }[] = []
410
+ const walk = (entries: EntryOptions[], parent: string | null) => {
411
+ for (const options of entries) {
412
+ if (options.id) {
413
+ used.add(options.id)
414
+ } else {
415
+ pending.push({ options, parent })
416
+ }
417
+ if (options.group && Array.isArray(options.config)) {
418
+ walk(options.config, options.id ?? null)
419
+ }
420
+ }
421
+ }
422
+ walk(data, null)
423
+
424
+ const previous = this.anonymous
425
+ this.anonymous = new Map()
426
+ for (const { options, parent } of pending) {
427
+ let id: string | undefined
428
+ for (const [candidate, info] of previous) {
429
+ if (info.parent !== parent || !deepEqual(info.options, options)) continue
430
+ id = candidate
431
+ previous.delete(candidate)
432
+ break
433
+ }
434
+ if (!id) {
435
+ do {
436
+ id = Math.random().toString(16).slice(2, 10)
437
+ } while (used.has(id) || this.store[id])
438
+ }
439
+ used.add(id)
440
+ this.anonymous.set(id, { parent, options: structuredClone(options) })
441
+ const rest = { ...options }
442
+ for (const key of Object.keys(options)) delete options[key]
443
+ Object.assign(options, { id }, rest)
444
+ }
445
+ }
446
+
447
+ private _scheduleApply() {
448
+ if (this._disposed || !this.cache) return
449
+ const tree = applyPatches(this.cache.data, this.config.patches, this.warn)
450
+ this._pendingTree = applyJournal(tree, this.journal, undefined, this.warn)
451
+ this._applyTask ??= (async () => {
452
+ try {
453
+ while (this._pendingTree) {
454
+ const tree = this._pendingTree
455
+ this._pendingTree = undefined
456
+ await this.root.update(tree)
457
+ }
458
+ } finally {
459
+ this._applyTask = undefined
460
+ }
461
+ })()
340
462
  }
341
463
  }
342
464