@deepseek-ai/cordis-plugin-include 1.0.10 → 1.0.11-alpha.2
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/README.md +10 -0
- package/lib/index.js +648 -150
- package/lib/types/index.d.ts +54 -59
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/journal.d.ts +69 -0
- package/lib/types/journal.d.ts.map +1 -0
- package/lib/types/patch.d.ts +68 -0
- package/lib/types/patch.d.ts.map +1 -0
- package/package.json +4 -4
- package/src/index.ts +363 -241
- package/src/journal.ts +242 -0
- package/src/patch.ts +261 -0
package/lib/index.js
CHANGED
|
@@ -1,61 +1,223 @@
|
|
|
1
1
|
import { EntryGroup, EntryTree, isJsExpr } from "@deepseek-ai/cordis-plugin-loader";
|
|
2
2
|
import { Service } from "@deepseek-ai/cordis";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { deepEqual, omit } 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 } from "node:timers/promises";
|
|
6
7
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
8
|
import * as yaml from "js-yaml";
|
|
8
|
-
//#region lib/types/
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
//#region lib/types/journal.js
|
|
10
|
+
function diffOptions(legacy, options) {
|
|
11
|
+
const changes = {};
|
|
12
|
+
for (const key of new Set([...Object.keys(legacy), ...Object.keys(options)])) {
|
|
13
|
+
if (key === "id") continue;
|
|
14
|
+
if (deepEqual(legacy[key], options[key])) continue;
|
|
15
|
+
changes[key] = options[key];
|
|
16
|
+
}
|
|
17
|
+
return changes;
|
|
18
|
+
}
|
|
19
|
+
/** Fold a later record into an earlier one for the same entry. */
|
|
20
|
+
function mergeRecords(older, newer) {
|
|
21
|
+
if (!older) return newer;
|
|
22
|
+
if (newer.kind === "remove") return older.kind === "upsert" && older.created ? void 0 : newer;
|
|
23
|
+
if (older.kind === "remove") return {
|
|
24
|
+
...newer,
|
|
25
|
+
created: false
|
|
26
|
+
};
|
|
27
|
+
const relocated = newer.parent !== void 0;
|
|
28
|
+
return {
|
|
29
|
+
kind: "upsert",
|
|
30
|
+
created: older.created,
|
|
31
|
+
parent: relocated ? newer.parent : older.parent,
|
|
32
|
+
position: relocated ? newer.position : older.position,
|
|
33
|
+
changes: {
|
|
34
|
+
...older.changes,
|
|
35
|
+
...newer.changes
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function merge(journal, id, record) {
|
|
40
|
+
const merged = mergeRecords(journal.get(id), record);
|
|
41
|
+
if (merged) journal.set(id, merged);
|
|
42
|
+
else journal.delete(id);
|
|
43
|
+
}
|
|
44
|
+
function record(journal, change, parent) {
|
|
45
|
+
const { id, options, legacy } = change;
|
|
46
|
+
if (!options) return merge(journal, id, { kind: "remove" });
|
|
47
|
+
const position = change.group.data.indexOf(options);
|
|
48
|
+
if (!legacy) return merge(journal, id, {
|
|
49
|
+
kind: "upsert",
|
|
50
|
+
created: true,
|
|
51
|
+
parent,
|
|
52
|
+
position,
|
|
53
|
+
changes: omit(options, ["id"])
|
|
12
54
|
});
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
55
|
+
merge(journal, id, {
|
|
56
|
+
kind: "upsert",
|
|
57
|
+
created: false,
|
|
58
|
+
parent: change.from ? parent : void 0,
|
|
59
|
+
position,
|
|
60
|
+
changes: diffOptions(legacy, options)
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Index every entry (including nested group members) by id. */
|
|
64
|
+
function flatten(data, parent = null, result = /* @__PURE__ */ new Map()) {
|
|
65
|
+
data.forEach((options, position) => {
|
|
66
|
+
if (options.id) result.set(options.id, {
|
|
67
|
+
parent,
|
|
68
|
+
position,
|
|
69
|
+
options,
|
|
70
|
+
list: data
|
|
71
|
+
});
|
|
72
|
+
if (options.group && Array.isArray(options.config)) flatten(options.config, options.id ?? null, result);
|
|
73
|
+
});
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
function applyChanges(options, changes, filter) {
|
|
77
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
78
|
+
if (filter && !filter(key)) continue;
|
|
79
|
+
if (value === void 0) delete options[key];
|
|
80
|
+
else options[key] = value;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function detach(data, id) {
|
|
84
|
+
const flat = flatten(data).get(id);
|
|
85
|
+
if (!flat) return;
|
|
86
|
+
flat.list.splice(flat.list.indexOf(flat.options), 1);
|
|
87
|
+
return flat.options;
|
|
88
|
+
}
|
|
22
89
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* mounts.
|
|
90
|
+
* Insert `options` under `parent` (a group id, or `null` for the root) at
|
|
91
|
+
* `position`, clamped to the group's length. Returns false when the parent
|
|
92
|
+
* group does not exist.
|
|
27
93
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const WRITE_RETRY_DELAY_MS = 50;
|
|
38
|
-
function retryableWriteError(error) {
|
|
39
|
-
const code = error?.code;
|
|
40
|
-
return code === "EACCES" || code === "EBUSY" || code === "EPERM";
|
|
94
|
+
function place(data, options, parent, position) {
|
|
95
|
+
let list = data;
|
|
96
|
+
if (parent !== null) {
|
|
97
|
+
const group = flatten(data).get(parent);
|
|
98
|
+
if (!group?.options.group) return false;
|
|
99
|
+
list = group.options.config ??= [];
|
|
100
|
+
}
|
|
101
|
+
list.splice(Math.min(position, list.length), 0, options);
|
|
102
|
+
return true;
|
|
41
103
|
}
|
|
42
104
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* (
|
|
46
|
-
* is never mutated: patching shared entry objects would bake earlier patch
|
|
47
|
-
* values into the cached parse, so repeated application (config hot-reloads)
|
|
48
|
-
* could never revert a removed or changed patch. Inserted entries are indexed
|
|
49
|
-
* as they are added, so a later patch in the same list can target a row an
|
|
50
|
-
* earlier patch inserted. A patch that matches nothing warns and is skipped.
|
|
51
|
-
* @param data - the parsed entry list (JSON-safe plain data).
|
|
52
|
-
* @param patches - the patch list to apply, in order.
|
|
53
|
-
* @param warn - sink for skipped-patch diagnostics (printf-style, `%C` = code).
|
|
54
|
-
* @returns a detached entry list with every applicable patch applied.
|
|
105
|
+
* Overlay a journal onto `data` in place. `filter(id, key)` restricts which
|
|
106
|
+
* changes apply; `key` is `null` when asking about the entry as a whole
|
|
107
|
+
* (creation, removal, relocation).
|
|
55
108
|
*/
|
|
56
|
-
function
|
|
57
|
-
|
|
109
|
+
function applyJournal(data, journal, filter = () => true, warn = () => {}) {
|
|
110
|
+
for (const [id, record] of journal) {
|
|
111
|
+
if (!filter(id, null)) continue;
|
|
112
|
+
if (record.kind === "remove") {
|
|
113
|
+
detach(data, id);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const flat = flatten(data).get(id);
|
|
117
|
+
if (!flat) {
|
|
118
|
+
const options = { id };
|
|
119
|
+
applyChanges(options, record.changes, (key) => filter(id, key));
|
|
120
|
+
const parent = record.parent ?? null;
|
|
121
|
+
if (!place(data, options, parent, record.position)) warn("cannot place entry %C: group %C not found", id, parent);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
applyChanges(flat.options, record.changes, (key) => filter(id, key));
|
|
125
|
+
if (record.parent !== void 0 && flat.parent !== record.parent) {
|
|
126
|
+
detach(data, id);
|
|
127
|
+
if (!place(data, flat.options, record.parent, record.position)) {
|
|
128
|
+
warn("cannot move entry %C: group %C not found", id, record.parent);
|
|
129
|
+
place(data, flat.options, flat.parent, flat.position);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return data;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Three-way reconciliation of a journal against a new file state. The file
|
|
137
|
+
* wins every conflict: conflicting keys are dropped from the journal so that
|
|
138
|
+
* the tree follows the file, and each drop is reported.
|
|
139
|
+
*
|
|
140
|
+
* `fileOwned(id, key)` scopes the check to what the file can actually express
|
|
141
|
+
* (patch-owned keys and patch-inserted entries live elsewhere).
|
|
142
|
+
*/
|
|
143
|
+
function reconcile(journal, base, theirs, fileOwned) {
|
|
144
|
+
const conflicts = [];
|
|
145
|
+
for (const [id, record] of journal) {
|
|
146
|
+
if (!fileOwned(id, null)) continue;
|
|
147
|
+
const b = base.get(id);
|
|
148
|
+
const t = theirs.get(id);
|
|
149
|
+
if (record.kind === "remove") {
|
|
150
|
+
if (!t) journal.delete(id);
|
|
151
|
+
else if (!b || !deepEqual(t.options, b.options)) {
|
|
152
|
+
conflicts.push({
|
|
153
|
+
id,
|
|
154
|
+
reason: b ? "modified in file, removed at runtime" : "added in file, removed at runtime"
|
|
155
|
+
});
|
|
156
|
+
journal.delete(id);
|
|
157
|
+
}
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (!t) {
|
|
161
|
+
if (b) {
|
|
162
|
+
conflicts.push({
|
|
163
|
+
id,
|
|
164
|
+
reason: "removed in file, modified at runtime"
|
|
165
|
+
});
|
|
166
|
+
journal.delete(id);
|
|
167
|
+
}
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (record.created) record.created = false;
|
|
171
|
+
for (const key of Object.keys(record.changes)) {
|
|
172
|
+
if (!fileOwned(id, key)) continue;
|
|
173
|
+
const bv = b?.options[key];
|
|
174
|
+
const tv = t.options[key];
|
|
175
|
+
if (deepEqual(bv, tv) || deepEqual(tv, record.changes[key])) continue;
|
|
176
|
+
conflicts.push({
|
|
177
|
+
id,
|
|
178
|
+
reason: `key "${key}" modified both in file and at runtime`
|
|
179
|
+
});
|
|
180
|
+
delete record.changes[key];
|
|
181
|
+
}
|
|
182
|
+
if (record.parent !== void 0 && b && t.parent !== b.parent && t.parent !== record.parent) {
|
|
183
|
+
conflicts.push({
|
|
184
|
+
id,
|
|
185
|
+
reason: "moved both in file and at runtime"
|
|
186
|
+
});
|
|
187
|
+
record.parent = void 0;
|
|
188
|
+
}
|
|
189
|
+
const moved = record.parent !== void 0 && record.parent !== t.parent;
|
|
190
|
+
if (!Object.keys(record.changes).length && !moved) journal.delete(id);
|
|
191
|
+
}
|
|
192
|
+
return conflicts;
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region lib/types/patch.js
|
|
196
|
+
function randomId(used) {
|
|
197
|
+
let id;
|
|
198
|
+
do
|
|
199
|
+
id = Math.random().toString(16).slice(2, 10);
|
|
200
|
+
while (used(id));
|
|
201
|
+
return id;
|
|
202
|
+
}
|
|
203
|
+
/** Give every entry (nested groups included) an id, in place. */
|
|
204
|
+
function ensureIds(entries, used) {
|
|
205
|
+
for (const entry of entries) {
|
|
206
|
+
if (!entry.id) entry.id = randomId(used);
|
|
207
|
+
if (entry.group && Array.isArray(entry.config)) ensureIds(entry.config, used);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/** Runtime changes are routed back to an inserted entry by its id, so every insert needs one. */
|
|
211
|
+
function ensureInsertIds(patches, used) {
|
|
212
|
+
for (const patch of patches ?? []) if (patch.insert) ensureIds(patch.insert, used);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Overlay `patches` onto a fresh clone of `data`. Inserted entries are cloned
|
|
216
|
+
* too, so the tree owns every object it mounts.
|
|
217
|
+
*/
|
|
218
|
+
function applyPatches(data, patches, warn) {
|
|
58
219
|
data = structuredClone(data);
|
|
220
|
+
if (!patches?.length) return data;
|
|
59
221
|
const entryMap = /* @__PURE__ */ new Map();
|
|
60
222
|
const buildMap = (entries) => {
|
|
61
223
|
for (const entry of entries) {
|
|
@@ -67,6 +229,7 @@ function applyEntryPatches(data, patches, warn) {
|
|
|
67
229
|
for (const patch of patches) {
|
|
68
230
|
const { id, insert, name, ...overrides } = patch;
|
|
69
231
|
if (insert) {
|
|
232
|
+
const clone = structuredClone(insert);
|
|
70
233
|
if (id) {
|
|
71
234
|
const target = entryMap.get(id);
|
|
72
235
|
if (!target) {
|
|
@@ -78,9 +241,9 @@ function applyEntryPatches(data, patches, warn) {
|
|
|
78
241
|
continue;
|
|
79
242
|
}
|
|
80
243
|
if (!Array.isArray(target.config)) target.config = [];
|
|
81
|
-
target.config.push(...
|
|
82
|
-
} else data.push(...
|
|
83
|
-
buildMap(
|
|
244
|
+
target.config.push(...clone);
|
|
245
|
+
} else data.push(...clone);
|
|
246
|
+
buildMap(clone);
|
|
84
247
|
continue;
|
|
85
248
|
}
|
|
86
249
|
if (!id) {
|
|
@@ -103,144 +266,479 @@ function applyEntryPatches(data, patches, warn) {
|
|
|
103
266
|
}
|
|
104
267
|
return data;
|
|
105
268
|
}
|
|
106
|
-
|
|
269
|
+
var PatchIndex = class {
|
|
270
|
+
patches;
|
|
271
|
+
keys = /* @__PURE__ */ new Map();
|
|
272
|
+
inserts = /* @__PURE__ */ new Map();
|
|
273
|
+
constructor(patches) {
|
|
274
|
+
this.patches = patches;
|
|
275
|
+
patches.forEach((patch, index) => {
|
|
276
|
+
const { id, insert } = patch;
|
|
277
|
+
if (insert) {
|
|
278
|
+
const walk = (list, parent) => {
|
|
279
|
+
for (const options of list) {
|
|
280
|
+
this.inserts.set(options.id, {
|
|
281
|
+
type: "insert",
|
|
282
|
+
index,
|
|
283
|
+
list,
|
|
284
|
+
options,
|
|
285
|
+
parent
|
|
286
|
+
});
|
|
287
|
+
if (options.group && Array.isArray(options.config)) walk(options.config, options.id);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
walk(insert, id ?? null);
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (!id) return;
|
|
294
|
+
const keys = this.keys.get(id) ?? /* @__PURE__ */ new Map();
|
|
295
|
+
for (const key of Object.keys(omit(patch, [
|
|
296
|
+
"id",
|
|
297
|
+
"insert",
|
|
298
|
+
"name"
|
|
299
|
+
]))) keys.set(key, index);
|
|
300
|
+
this.keys.set(id, keys);
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
/** Owner of the entry as a whole. */
|
|
304
|
+
entry(id) {
|
|
305
|
+
if (id === null) return { type: "file" };
|
|
306
|
+
return this.inserts.get(id) ?? { type: "file" };
|
|
307
|
+
}
|
|
308
|
+
/** Owner of one key of an entry. */
|
|
309
|
+
key(id, key) {
|
|
310
|
+
const insert = this.inserts.get(id);
|
|
311
|
+
if (insert) return insert;
|
|
312
|
+
const index = this.keys.get(id)?.get(key);
|
|
313
|
+
return index === void 0 ? { type: "file" } : {
|
|
314
|
+
type: "patch",
|
|
315
|
+
index
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
fileOwned(id, key) {
|
|
319
|
+
return (key === null ? this.entry(id) : this.key(id, key)).type === "file";
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Route a journal to its owners: file-owned changes are applied to `data`,
|
|
324
|
+
* patch-owned ones to `patches`. Both are mutated in place, so pass clones.
|
|
325
|
+
* Returns whether any patch changed.
|
|
326
|
+
*/
|
|
327
|
+
function routeJournal(journal, data, patches, warn) {
|
|
328
|
+
const index = new PatchIndex(patches);
|
|
329
|
+
let patched = false;
|
|
330
|
+
const insertList = (owner) => owner.options.config ??= [];
|
|
331
|
+
const placeAt = (options, parent, position) => {
|
|
332
|
+
const owner = index.entry(parent);
|
|
333
|
+
if (owner.type === "insert") {
|
|
334
|
+
const list = insertList(owner);
|
|
335
|
+
list.splice(Math.min(position, list.length), 0, options);
|
|
336
|
+
patched = true;
|
|
337
|
+
} else if (!place(data, options, parent, position)) warn("cannot place entry %C: group %C not found", options.id, parent);
|
|
338
|
+
};
|
|
339
|
+
for (const [id, record] of journal) {
|
|
340
|
+
const owner = index.entry(id);
|
|
341
|
+
if (record.kind === "remove") {
|
|
342
|
+
if (owner.type === "insert") {
|
|
343
|
+
owner.list.splice(owner.list.indexOf(owner.options), 1);
|
|
344
|
+
patched = true;
|
|
345
|
+
} else detach(data, id);
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const current = owner.type === "insert" ? owner : flatten(data).get(id);
|
|
349
|
+
if (!current) {
|
|
350
|
+
const options = { id };
|
|
351
|
+
applyChanges(options, record.changes);
|
|
352
|
+
placeAt(options, record.parent ?? null, record.position);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (record.parent !== void 0 && current.parent !== record.parent) {
|
|
356
|
+
if (owner.type === "insert") {
|
|
357
|
+
owner.list.splice(owner.list.indexOf(owner.options), 1);
|
|
358
|
+
patched = true;
|
|
359
|
+
} else detach(data, id);
|
|
360
|
+
applyChanges(current.options, record.changes);
|
|
361
|
+
placeAt(current.options, record.parent, record.position);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
if (owner.type === "insert") {
|
|
365
|
+
applyChanges(current.options, record.changes);
|
|
366
|
+
patched = true;
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const patchChanges = {};
|
|
370
|
+
applyChanges(current.options, record.changes, (key) => {
|
|
371
|
+
const keyOwner = index.key(id, key);
|
|
372
|
+
if (keyOwner.type !== "patch") return true;
|
|
373
|
+
(patchChanges[keyOwner.index] ??= {})[key] = record.changes[key];
|
|
374
|
+
return false;
|
|
375
|
+
});
|
|
376
|
+
for (const [i, changes] of Object.entries(patchChanges)) {
|
|
377
|
+
applyChanges(patches[i], changes);
|
|
378
|
+
patched = true;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return patched;
|
|
382
|
+
}
|
|
383
|
+
//#endregion
|
|
384
|
+
//#region lib/types/index.js
|
|
385
|
+
const JsExpr = new yaml.Type("tag:yaml.org,2002:js", {
|
|
386
|
+
kind: "scalar",
|
|
387
|
+
resolve: (data) => typeof data === "string",
|
|
388
|
+
construct: (data) => ({ __jsExpr: data }),
|
|
389
|
+
predicate: isJsExpr,
|
|
390
|
+
represent: (data) => data["__jsExpr"]
|
|
391
|
+
});
|
|
392
|
+
/** YAML dialect preserving child-owned JavaScript expression nodes. */
|
|
393
|
+
const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr);
|
|
394
|
+
const schema = entryListSchema;
|
|
395
|
+
const types = {
|
|
396
|
+
".json": "application/json",
|
|
397
|
+
".yaml": "application/yaml",
|
|
398
|
+
".yml": "application/yaml"
|
|
399
|
+
};
|
|
400
|
+
var ConfigFileError = class extends Error {
|
|
401
|
+
stage;
|
|
402
|
+
name = "ConfigFileError";
|
|
403
|
+
constructor(stage, path, cause) {
|
|
404
|
+
super(`failed to ${stage} config file ${path}`, { cause });
|
|
405
|
+
this.stage = stage;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
/** The file changed under us between the pre-check and the rename. */
|
|
409
|
+
var StaleWriteError = class extends Error {
|
|
410
|
+
name = "StaleWriteError";
|
|
411
|
+
};
|
|
412
|
+
function isENOENT(error) {
|
|
413
|
+
return error?.code === "ENOENT";
|
|
414
|
+
}
|
|
415
|
+
const RENAME_RETRIES = 10;
|
|
416
|
+
const RENAME_BACKOFF = 20;
|
|
417
|
+
/**
|
|
418
|
+
* On Windows a rename over a file that another process holds open (typically
|
|
419
|
+
* an antivirus scanning what we just wrote) fails with one of these; the lock
|
|
420
|
+
* is normally gone within milliseconds. A bounded retry is cheap enough to
|
|
421
|
+
* apply on every platform.
|
|
422
|
+
*/
|
|
423
|
+
function isTransientRenameError(error) {
|
|
424
|
+
const code = error?.code;
|
|
425
|
+
return code === "EACCES" || code === "EPERM" || code === "EBUSY";
|
|
426
|
+
}
|
|
107
427
|
var Include = class extends EntryTree {
|
|
108
428
|
config;
|
|
109
429
|
static inject = ["loader"];
|
|
110
430
|
static [EntryGroup.key] = true;
|
|
111
431
|
filename;
|
|
112
432
|
type;
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
433
|
+
/** The last file state we read or wrote. */
|
|
434
|
+
cache;
|
|
435
|
+
/** Tree-side changes that have not reached the file yet. */
|
|
436
|
+
journal = /* @__PURE__ */ new Map();
|
|
437
|
+
/** Ids we assigned to entries the file leaves anonymous. */
|
|
438
|
+
anonymous = /* @__PURE__ */ new Map();
|
|
439
|
+
dirtyRead = false;
|
|
440
|
+
dirtyWrite = false;
|
|
441
|
+
_draining;
|
|
442
|
+
/** Only the latest intended tree is ever applied; older ones are skipped. */
|
|
443
|
+
_pendingTree;
|
|
444
|
+
_applyTask;
|
|
445
|
+
_disposed = false;
|
|
446
|
+
_seq = 0;
|
|
447
|
+
persistenceError;
|
|
119
448
|
constructor(ctx, config) {
|
|
120
449
|
super(ctx);
|
|
121
450
|
this.config = config;
|
|
122
451
|
this.enableLogs = config.enableLogs ?? ctx.fiber.entry?.parent.tree.enableLogs ?? false;
|
|
123
452
|
this.filename = fileURLToPath(new URL(this.config.path, this.ctx.baseUrl));
|
|
124
453
|
const ext = extname(this.filename);
|
|
125
|
-
if (!
|
|
126
|
-
this.type =
|
|
127
|
-
this.readonly = !this.type;
|
|
454
|
+
if (!types[ext]) throw new Error(`extension "${ext}" not supported`);
|
|
455
|
+
this.type = types[ext];
|
|
128
456
|
this.ctx.baseUrl = new URL(".", pathToFileURL(this.filename)).href;
|
|
129
|
-
|
|
457
|
+
ensureInsertIds(config.patches, (id) => !!this.store[id]);
|
|
458
|
+
ctx.on("internal/update", (config, next) => {
|
|
130
459
|
if (config.path !== this.config.path) return next();
|
|
131
460
|
this.config = config;
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
});
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
async checkAccess() {
|
|
139
|
-
if (!this.type) return;
|
|
140
|
-
try {
|
|
141
|
-
await access(this.filename, constants.W_OK);
|
|
142
|
-
} catch {
|
|
143
|
-
this.readonly = true;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
async read(forced = false) {
|
|
147
|
-
const content = await readFile(this.filename, "utf8");
|
|
148
|
-
if (!forced && this.content === content) return false;
|
|
149
|
-
let data;
|
|
150
|
-
if (this.type === "application/yaml") data = yaml.load(content, { schema: entryListSchema });
|
|
151
|
-
else if (this.type === "application/json") data = JSON.parse(content);
|
|
152
|
-
else {
|
|
153
|
-
const module = await import(__rewriteRelativeImportExtension(
|
|
154
|
-
/* @vite-ignore */
|
|
155
|
-
this.filename
|
|
156
|
-
));
|
|
157
|
-
data = module.default || module;
|
|
158
|
-
}
|
|
159
|
-
if (!Array.isArray(data)) throw new TypeError(`config file must be a top-level array of entries: ${this.filename}`);
|
|
160
|
-
this.content = content;
|
|
161
|
-
this.data = data;
|
|
162
|
-
await this.checkAccess();
|
|
163
|
-
return true;
|
|
164
|
-
}
|
|
165
|
-
applyPatches(data, patches = this.config.patches) {
|
|
166
|
-
return applyEntryPatches(data, patches, (message, ...args) => {
|
|
167
|
-
this.ctx.root.logger?.("loader").warn(message, ...args);
|
|
461
|
+
ensureInsertIds(config.patches, (id) => !!this.store[id]);
|
|
462
|
+
this._scheduleApply();
|
|
463
|
+
return this._applyTask;
|
|
168
464
|
});
|
|
169
465
|
}
|
|
466
|
+
warn = (format, ...args) => {
|
|
467
|
+
this.ctx.root.logger?.("loader").warn(format, ...args);
|
|
468
|
+
};
|
|
170
469
|
async *[Service.init]() {
|
|
171
470
|
try {
|
|
172
|
-
await this.
|
|
471
|
+
await this._read();
|
|
173
472
|
} catch (error) {
|
|
174
|
-
if (error
|
|
175
|
-
if (this.config.initial) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
473
|
+
if (!isENOENT(error instanceof ConfigFileError && error.stage === "read" ? error.cause : void 0)) throw error;
|
|
474
|
+
if (!this.config.initial) throw new Error(`config file not found: ${this.filename}`);
|
|
475
|
+
const initial = structuredClone(this.config.initial);
|
|
476
|
+
ensureIds(initial, (id) => !!this.store[id]);
|
|
477
|
+
await this._writeText(this.dump(initial));
|
|
478
|
+
await this._read();
|
|
179
479
|
}
|
|
180
480
|
yield () => this.stop();
|
|
181
|
-
await this.
|
|
481
|
+
await this._applyTask;
|
|
182
482
|
}
|
|
183
483
|
async stop() {
|
|
484
|
+
this._disposed = true;
|
|
485
|
+
this._pendingTree = void 0;
|
|
486
|
+
if (this.journal.size) {
|
|
487
|
+
this.dirtyWrite = true;
|
|
488
|
+
this._drain();
|
|
489
|
+
}
|
|
184
490
|
try {
|
|
185
|
-
await this.
|
|
491
|
+
await this.flush();
|
|
186
492
|
} finally {
|
|
187
493
|
this.root.stop();
|
|
188
|
-
await this.flushWrite();
|
|
189
494
|
}
|
|
190
495
|
}
|
|
191
496
|
/**
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
* tree: a hot-reload of a live app must never take the process down.
|
|
497
|
+
* Resolves once every pending read and write has been processed and the
|
|
498
|
+
* tree reflects the outcome. Retries pending writes and rejects while changes remain unsaved.
|
|
195
499
|
*/
|
|
196
|
-
async
|
|
500
|
+
async flush() {
|
|
501
|
+
if (this.journal.size && !this._draining) {
|
|
502
|
+
this.dirtyWrite = true;
|
|
503
|
+
this._drain();
|
|
504
|
+
}
|
|
505
|
+
while (this._draining || this._applyTask) {
|
|
506
|
+
await this._draining;
|
|
507
|
+
await this._applyTask;
|
|
508
|
+
}
|
|
509
|
+
if (this.journal.size) throw this.persistenceError ?? /* @__PURE__ */ new Error(`config file ${this.filename} has ${this.journal.size} unsaved change(s)`);
|
|
510
|
+
this.persistenceError = void 0;
|
|
511
|
+
}
|
|
512
|
+
/** Re-read the file and reconcile the tree with it. */
|
|
513
|
+
refresh() {
|
|
514
|
+
this.dirtyRead = true;
|
|
515
|
+
this._drain();
|
|
516
|
+
return this.flush();
|
|
517
|
+
}
|
|
518
|
+
/** Called synchronously by the loader once a tree-side change is in place. */
|
|
519
|
+
commit(change) {
|
|
520
|
+
this.context.emit("loader/config-update");
|
|
521
|
+
const parent = change.group === this.root ? null : change.group.ctx.fiber.entry.options.id;
|
|
522
|
+
record(this.journal, change, parent);
|
|
523
|
+
this.dirtyWrite = true;
|
|
524
|
+
this._drain();
|
|
525
|
+
}
|
|
526
|
+
_drain() {
|
|
527
|
+
if (this._draining) return;
|
|
528
|
+
this._draining = this._loop().finally(() => {
|
|
529
|
+
this._draining = void 0;
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
async _loop() {
|
|
533
|
+
while (this.dirtyRead || this.dirtyWrite) {
|
|
534
|
+
if (this.dirtyRead) {
|
|
535
|
+
this.dirtyRead = false;
|
|
536
|
+
try {
|
|
537
|
+
await this._read();
|
|
538
|
+
} catch (error) {
|
|
539
|
+
this.persistenceError = error;
|
|
540
|
+
this.ctx.logger.warn(error);
|
|
541
|
+
if (this.dirtyRead) continue;
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (this.dirtyWrite) {
|
|
546
|
+
this.dirtyWrite = false;
|
|
547
|
+
try {
|
|
548
|
+
await this._write();
|
|
549
|
+
} catch (error) {
|
|
550
|
+
this.persistenceError = error;
|
|
551
|
+
this.ctx.logger.error(error);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
async _read() {
|
|
557
|
+
let content;
|
|
558
|
+
try {
|
|
559
|
+
content = await readFile(this.filename, "utf8");
|
|
560
|
+
} catch (error) {
|
|
561
|
+
throw new ConfigFileError("read", this.filename, error);
|
|
562
|
+
}
|
|
563
|
+
if (content === this.cache?.content) return;
|
|
564
|
+
let data;
|
|
197
565
|
try {
|
|
198
|
-
|
|
199
|
-
await this.root.update(this.applyPatches(this.data));
|
|
566
|
+
data = this.type === "application/yaml" ? yaml.load(content, { schema }) : JSON.parse(content);
|
|
200
567
|
} catch (error) {
|
|
201
|
-
|
|
202
|
-
this.ctx.logger.warn(error);
|
|
568
|
+
throw new ConfigFileError("parse", this.filename, error);
|
|
203
569
|
}
|
|
570
|
+
if (!Array.isArray(data)) throw new ConfigFileError("validate", this.filename, /* @__PURE__ */ new TypeError("config file must be a top-level array"));
|
|
571
|
+
this._assignIds(data);
|
|
572
|
+
if (this.cache) {
|
|
573
|
+
const index = new PatchIndex(this.config.patches ?? []);
|
|
574
|
+
const conflicts = reconcile(this.journal, flatten(this.cache.data), flatten(data), (id, key) => index.fileOwned(id, key));
|
|
575
|
+
for (const { id, reason } of conflicts) this.ctx.logger.error("config conflict in %C: entry %C %s; file wins", this.filename, id, reason);
|
|
576
|
+
}
|
|
577
|
+
this.cache = {
|
|
578
|
+
content,
|
|
579
|
+
data
|
|
580
|
+
};
|
|
581
|
+
this._scheduleApply();
|
|
582
|
+
if (this.journal.size) this.dirtyWrite = true;
|
|
204
583
|
}
|
|
205
|
-
async
|
|
206
|
-
if (this.
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
584
|
+
async _write() {
|
|
585
|
+
if (!this.cache || !this.journal.size) return;
|
|
586
|
+
const current = await readFile(this.filename, "utf8").catch((error) => {
|
|
587
|
+
if (isENOENT(error)) return void 0;
|
|
588
|
+
throw error;
|
|
589
|
+
});
|
|
590
|
+
if (current === void 0) {
|
|
591
|
+
this.ctx.logger.warn("config file %C is missing, %d pending change(s) kept in memory", this.filename, this.journal.size);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (current !== this.cache.content) {
|
|
595
|
+
this.dirtyRead = true;
|
|
596
|
+
this.dirtyWrite = true;
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
const batch = this.journal;
|
|
600
|
+
this.journal = /* @__PURE__ */ new Map();
|
|
601
|
+
const restore = () => {
|
|
602
|
+
for (const [id, record] of this.journal) merge(batch, id, record);
|
|
603
|
+
this.journal = batch;
|
|
604
|
+
};
|
|
605
|
+
const data = structuredClone(this.cache.data);
|
|
606
|
+
const patches = structuredClone(this.config.patches ?? []);
|
|
607
|
+
if (routeJournal(batch, data, patches, this.warn)) {
|
|
608
|
+
this.config = {
|
|
609
|
+
...this.config,
|
|
610
|
+
patches
|
|
611
|
+
};
|
|
612
|
+
if (this.ctx.fiber.entry) try {
|
|
613
|
+
Promise.resolve(this.ctx.fiber.update(this.config)).catch((error) => {
|
|
614
|
+
this.ctx.logger.error(error);
|
|
615
|
+
});
|
|
616
|
+
} catch (error) {
|
|
617
|
+
this.ctx.logger.error(error);
|
|
618
|
+
}
|
|
619
|
+
else this.ctx.logger.warn("patches of %C changed at runtime but cannot be persisted", this.filename);
|
|
620
|
+
}
|
|
621
|
+
if (deepEqual(data, this.cache.data)) {
|
|
622
|
+
this._scheduleApply();
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
const text = this.dump(data);
|
|
626
|
+
try {
|
|
627
|
+
await access(this.filename, constants.W_OK);
|
|
628
|
+
} catch {
|
|
629
|
+
restore();
|
|
630
|
+
this.ctx.logger.warn("config file %C is read-only, %d pending change(s) kept in memory", this.filename, this.journal.size);
|
|
212
631
|
return;
|
|
632
|
+
}
|
|
633
|
+
try {
|
|
634
|
+
await this._writeText(text, this.cache.content);
|
|
213
635
|
} catch (error) {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
this.
|
|
228
|
-
const config = this.pendingWrite;
|
|
229
|
-
this.pendingWrite = void 0;
|
|
230
|
-
if (config === void 0) return this.writeQueue;
|
|
231
|
-
const run = this.writeQueue.then(() => this._writeFile(config), () => this._writeFile(config));
|
|
232
|
-
this.writeQueue = run;
|
|
233
|
-
run.catch((error) => {
|
|
234
|
-
this.ctx.root.logger?.("loader").warn("failed to write config file %C", this.filename);
|
|
235
|
-
this.ctx.root.logger?.("loader").warn(error);
|
|
236
|
-
});
|
|
237
|
-
return run;
|
|
636
|
+
restore();
|
|
637
|
+
if (error instanceof StaleWriteError) {
|
|
638
|
+
this.dirtyRead = true;
|
|
639
|
+
this.dirtyWrite = true;
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
this.ctx.logger.warn("failed to write config file %C, %d pending change(s) kept in memory", this.filename, this.journal.size);
|
|
643
|
+
throw error;
|
|
644
|
+
}
|
|
645
|
+
this.cache = {
|
|
646
|
+
content: text,
|
|
647
|
+
data
|
|
648
|
+
};
|
|
649
|
+
this._scheduleApply();
|
|
238
650
|
}
|
|
239
|
-
/**
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
651
|
+
/**
|
|
652
|
+
* Write through a temp file and a rename, so that no reader ever sees a
|
|
653
|
+
* truncated file. When `expected` is given, the rename (and every retry of
|
|
654
|
+
* it) only goes ahead while the file still holds that content.
|
|
655
|
+
*/
|
|
656
|
+
async _writeText(text, expected) {
|
|
657
|
+
const tmp = join(dirname(this.filename), `.${basename(this.filename)}.${process.pid}.${this._seq++}.tmp`);
|
|
658
|
+
try {
|
|
659
|
+
await writeFile(tmp, text);
|
|
660
|
+
for (let attempt = 0;; attempt++) {
|
|
661
|
+
if (expected !== void 0) {
|
|
662
|
+
if (await readFile(this.filename, "utf8").catch((error) => {
|
|
663
|
+
if (isENOENT(error)) return void 0;
|
|
664
|
+
throw error;
|
|
665
|
+
}) !== expected) throw new StaleWriteError();
|
|
666
|
+
}
|
|
667
|
+
try {
|
|
668
|
+
await rename(tmp, this.filename);
|
|
669
|
+
return;
|
|
670
|
+
} catch (error) {
|
|
671
|
+
if (attempt >= RENAME_RETRIES || !isTransientRenameError(error)) throw error;
|
|
672
|
+
}
|
|
673
|
+
await setTimeout(RENAME_BACKOFF * (attempt + 1));
|
|
674
|
+
}
|
|
675
|
+
} catch (error) {
|
|
676
|
+
await rm(tmp, { force: true }).catch(() => {});
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
dump(data) {
|
|
681
|
+
return this.type === "application/yaml" ? yaml.dump(data, { schema }) : JSON.stringify(data, null, 2);
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Entries the file leaves anonymous get an id here, before the loader sees
|
|
685
|
+
* them. One that looks exactly like an entry we named on the previous read
|
|
686
|
+
* keeps that id, so editing a neighbor does not restart it; anything else
|
|
687
|
+
* gets a fresh id. Assigned ids stay in memory until the next write.
|
|
688
|
+
*/
|
|
689
|
+
_assignIds(data) {
|
|
690
|
+
const used = /* @__PURE__ */ new Set();
|
|
691
|
+
const pending = [];
|
|
692
|
+
const walk = (entries, parent) => {
|
|
693
|
+
for (const options of entries) {
|
|
694
|
+
if (options.id) used.add(options.id);
|
|
695
|
+
else pending.push({
|
|
696
|
+
options,
|
|
697
|
+
parent
|
|
698
|
+
});
|
|
699
|
+
if (options.group && Array.isArray(options.config)) walk(options.config, options.id ?? null);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
walk(data, null);
|
|
703
|
+
const previous = this.anonymous;
|
|
704
|
+
this.anonymous = /* @__PURE__ */ new Map();
|
|
705
|
+
for (const { options, parent } of pending) {
|
|
706
|
+
let id;
|
|
707
|
+
for (const [candidate, info] of previous) {
|
|
708
|
+
if (info.parent !== parent || !deepEqual(info.options, options)) continue;
|
|
709
|
+
id = candidate;
|
|
710
|
+
previous.delete(candidate);
|
|
711
|
+
break;
|
|
712
|
+
}
|
|
713
|
+
if (!id) do
|
|
714
|
+
id = Math.random().toString(16).slice(2, 10);
|
|
715
|
+
while (used.has(id) || this.store[id]);
|
|
716
|
+
used.add(id);
|
|
717
|
+
this.anonymous.set(id, {
|
|
718
|
+
parent,
|
|
719
|
+
options: structuredClone(options)
|
|
720
|
+
});
|
|
721
|
+
const rest = { ...options };
|
|
722
|
+
for (const key of Object.keys(options)) delete options[key];
|
|
723
|
+
Object.assign(options, { id }, rest);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
_scheduleApply() {
|
|
727
|
+
if (this._disposed || !this.cache) return;
|
|
728
|
+
const tree = applyPatches(this.cache.data, this.config.patches, this.warn);
|
|
729
|
+
this._pendingTree = applyJournal(tree, this.journal, void 0, this.warn);
|
|
730
|
+
this._applyTask ??= (async () => {
|
|
731
|
+
try {
|
|
732
|
+
while (this._pendingTree) {
|
|
733
|
+
const tree = this._pendingTree;
|
|
734
|
+
this._pendingTree = void 0;
|
|
735
|
+
await this.root.update(tree);
|
|
736
|
+
}
|
|
737
|
+
} finally {
|
|
738
|
+
this._applyTask = void 0;
|
|
739
|
+
}
|
|
740
|
+
})();
|
|
243
741
|
}
|
|
244
742
|
};
|
|
245
743
|
//#endregion
|
|
246
|
-
export { Include, Include as default, applyEntryPatches, entryListSchema };
|
|
744
|
+
export { ConfigFileError, Include, Include as default, applyPatches as applyEntryPatches, entryListSchema };
|