@cortexkit/opencode-openai-auth 1.14.0 → 1.15.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.
Files changed (87) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-Cl6zEfsR.d.ts → codex-request-DYqSE0ti.d.ts} +373 -2
  3. package/dist/{index-3c9pk6zn.js → index-14x5shtc.js} +2 -2
  4. package/dist/index-1wcg7g9d.js +2 -0
  5. package/dist/index-50p400eg.js +8 -0
  6. package/dist/index-98q3mydm.js +64 -0
  7. package/dist/{index-a9tzfpxy.js → index-bhkycxbm.js} +1 -1
  8. package/dist/{index-f7t7cc9b.js → index-dzpjz8hv.js} +2 -2
  9. package/dist/{index-1abcvt9p.js → index-f7kmsdfk.js} +1 -1
  10. package/dist/{index-4tpttpjw.js → index-hnfqppx9.js} +1 -1
  11. package/dist/{index-nfbmjq6g.js → index-m8m7rakq.js} +2 -2
  12. package/dist/index-mjsmvmt4.js +76 -0
  13. package/dist/{index-xxmaf5ks.js → index-s8ghhc9z.js} +2 -2
  14. package/dist/{index-q111b2h5.js → index-t65axpta.js} +1 -1
  15. package/dist/index-xjtbg7sx.js +101 -0
  16. package/dist/index.d.ts +1 -372
  17. package/dist/index.js +1 -1
  18. package/dist/openai-auth.schema.json +400 -0
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/sidebar-state.js +1 -1
  24. package/dist/{token-6x4q5r2r.js → token-j34j1zhm.js} +1 -1
  25. package/dist/token-util-bf619nmg.js +1 -0
  26. package/dist/tui-preferences.js +3 -3
  27. package/dist/v2/server.d.ts +1 -1
  28. package/dist/v2/server.js +2 -2
  29. package/package.json +3 -3
  30. package/src/tui-compiled/raw/logger.js +8 -1
  31. package/src/tui-compiled/raw/shared/061e741c052de9c1-paths.js +48 -0
  32. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +41 -18
  33. package/src/tui-compiled/raw/shared/23300c068d0b2ffc-parse.js +65 -0
  34. package/src/tui-compiled/raw/shared/3000be4f79f20eb6-write.js +88 -0
  35. package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +229 -0
  36. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
  37. package/src/tui-compiled/raw/shared/5803fadb30af0ec0-descriptors.js +81 -0
  38. package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +52 -0
  39. package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +139 -0
  40. package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +19 -0
  41. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +28 -12
  42. package/src/tui-compiled/raw/shared/81758f9fe7c2a576-handle.js +228 -0
  43. package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +51 -0
  44. package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +1 -0
  45. package/src/tui-compiled/raw/shared/8ab1f5794e677151-move.js +351 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +9 -5
  47. package/src/tui-compiled/raw/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  48. package/src/tui-compiled/raw/shared/cc0f2d1963547799-index.js +7 -0
  49. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +48 -5
  50. package/src/tui-compiled/raw/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  52. package/src/tui-compiled/raw/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  53. package/src/tui-compiled/raw/shared/facfd8afc431d68a-refusal.js +15 -0
  54. package/src/tui-compiled/raw/shared/fc7db0c5aa764565-settings-install.js +85 -0
  55. package/src/tui-compiled/raw/shared/fcd26e77bc538838-snapshot.js +150 -0
  56. package/src/tui-compiled/runtime/logger.js +8 -1
  57. package/src/tui-compiled/runtime/shared/061e741c052de9c1-paths.js +48 -0
  58. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +41 -18
  59. package/src/tui-compiled/runtime/shared/23300c068d0b2ffc-parse.js +65 -0
  60. package/src/tui-compiled/runtime/shared/3000be4f79f20eb6-write.js +88 -0
  61. package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +229 -0
  62. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
  63. package/src/tui-compiled/runtime/shared/5803fadb30af0ec0-descriptors.js +81 -0
  64. package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +52 -0
  65. package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +139 -0
  66. package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +19 -0
  67. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +28 -12
  68. package/src/tui-compiled/runtime/shared/81758f9fe7c2a576-handle.js +228 -0
  69. package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +51 -0
  70. package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +1 -0
  71. package/src/tui-compiled/runtime/shared/8ab1f5794e677151-move.js +351 -0
  72. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +9 -5
  73. package/src/tui-compiled/runtime/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  74. package/src/tui-compiled/runtime/shared/cc0f2d1963547799-index.js +7 -0
  75. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +48 -5
  76. package/src/tui-compiled/runtime/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  77. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  78. package/src/tui-compiled/runtime/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  79. package/src/tui-compiled/runtime/shared/facfd8afc431d68a-refusal.js +15 -0
  80. package/src/tui-compiled/runtime/shared/fc7db0c5aa764565-settings-install.js +85 -0
  81. package/src/tui-compiled/runtime/shared/fcd26e77bc538838-snapshot.js +150 -0
  82. package/dist/index-4zpxwh8y.js +0 -91
  83. package/dist/index-bc2d4vma.js +0 -64
  84. package/dist/index-wap9mf5f.js +0 -2
  85. package/dist/index-yew3mp47.js +0 -76
  86. package/dist/index-zcpher1w.js +0 -8
  87. package/dist/token-util-54mhq85x.js +0 -1
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { link, lstat, mkdir, open, readFile, rename, rm, stat, } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
2
+ import { link, lstat, mkdir, open, readdir, readFile, rename, rm, stat, unlink, } from "node:fs/promises";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import { DisappearedLockRecordError, isWindowsAccessDeniedCreate, isWindowsAccessDeniedRead, readLockRecord, } from "./723b00f96290a097-lock-record.js";
5
5
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from "./375d9cca2def037d-private-files.js";
6
6
  import { LockOwnershipError, lockPathFor } from "./4825e03209d6ae3e-with-lock.js";
@@ -91,6 +91,149 @@ async function writeExclusiveText(path, text) {
91
91
  await handle.close();
92
92
  }
93
93
  }
94
+ // Lease owner records are staged in sibling files named
95
+ // `<lock file name>.<random UUID>.tmp` before they are linked or renamed into
96
+ // place: by createExclusiveText and by renewal, whose Windows branch uses
97
+ // writePrivateAtomic's default staging name of the same shape. Each writer
98
+ // removes its staging file when it finishes, but a process killed between
99
+ // creating the file and that cleanup leaves it behind for good, since nothing
100
+ // else ever reads that name. The sweep below removes only such leftovers.
101
+ const STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
102
+ // A staging file records the expiry of the lease it was about to publish,
103
+ // which is always in the future while its writer is alive. Requiring the
104
+ // expiry to be at least a lease TTL in the past, and never less than this
105
+ // floor, keeps a live writer's file safe even if wall clocks disagree.
106
+ const STAGING_SWEEP_MIN_AGE_MS = 10 * 60_000;
107
+ // Bounds the work one sweep does; any remainder is left for a later process.
108
+ const STAGING_SWEEP_MAX_CANDIDATES = 256;
109
+ // A complete owner record is under 100 bytes; anything far larger is not one.
110
+ const STAGING_SWEEP_MAX_BYTES = 4_096;
111
+ // Lock paths already swept by this process. Sweeping once per process keeps
112
+ // the directory listing off the hot path of every later acquisition.
113
+ const sweptLockPaths = new Set();
114
+ const pendingStagingSweeps = new Set();
115
+ let stagingSweepTestHooks;
116
+ /** Test-only sweep faults; not re-exported from the public fs entry point. */
117
+ export function setStagingSweepTestHooksForTest(hooks) {
118
+ stagingSweepTestHooks = hooks;
119
+ }
120
+ /** Tests only: wait for every staging sweep started so far to finish. */
121
+ export async function settleStagingSweepsForTest() {
122
+ while (pendingStagingSweeps.size > 0)
123
+ await Promise.all([...pendingStagingSweeps]);
124
+ }
125
+ /** Tests only: let the next acquisition of every lock path sweep again. */
126
+ export function forgetStagingSweepsForTest() {
127
+ sweptLockPaths.clear();
128
+ }
129
+ function isStagingName(name, lockName) {
130
+ const prefix = `${lockName}.`;
131
+ const suffix = '.tmp';
132
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
133
+ return false;
134
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
135
+ }
136
+ function sameStagingFile(a, b) {
137
+ return (a.dev === b.dev &&
138
+ a.ino === b.ino &&
139
+ a.size === b.size &&
140
+ a.mtimeMs === b.mtimeMs &&
141
+ a.birthtimeMs === b.birthtimeMs);
142
+ }
143
+ /**
144
+ * Read the owner record a staging file holds, or undefined when the path is
145
+ * not a plain file holding exactly a complete `{ownerId, expiresAt}` record.
146
+ * Returns the lstat identity the record was read from, for the unlink fence.
147
+ */
148
+ async function readStagedOwner(path) {
149
+ const before = await lstat(path);
150
+ if (!before.isFile() || before.isSymbolicLink())
151
+ return undefined;
152
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
153
+ return undefined;
154
+ const handle = await open(path, 'r');
155
+ let text;
156
+ try {
157
+ // The path could be swapped between the lstat and the open; read only
158
+ // when the opened file is the one the lstat described.
159
+ if (!sameStagingFile(before, await handle.stat()))
160
+ return undefined;
161
+ text = await handle.readFile('utf8');
162
+ }
163
+ finally {
164
+ await handle.close();
165
+ }
166
+ let record;
167
+ try {
168
+ record = JSON.parse(text);
169
+ }
170
+ catch {
171
+ return undefined;
172
+ }
173
+ if (!record || typeof record !== 'object' || Array.isArray(record))
174
+ return undefined;
175
+ const keys = Object.keys(record).sort();
176
+ if (keys.length !== 2 || keys[0] !== 'expiresAt' || keys[1] !== 'ownerId')
177
+ return undefined;
178
+ const { ownerId, expiresAt } = record;
179
+ if (typeof ownerId !== 'string' || !STAGING_UUID.test(ownerId))
180
+ return undefined;
181
+ if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt))
182
+ return undefined;
183
+ return { identity: before, expiresAt };
184
+ }
185
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
186
+ const directory = dirname(lockPath);
187
+ const lockName = basename(lockPath);
188
+ const hooks = stagingSweepTestHooks;
189
+ const names = await (hooks?.readdir ?? readdir)(directory);
190
+ const candidates = names
191
+ .filter((name) => isStagingName(name, lockName))
192
+ .slice(0, STAGING_SWEEP_MAX_CANDIDATES);
193
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
194
+ for (const name of candidates) {
195
+ const path = join(directory, name);
196
+ try {
197
+ // A file written within the margin belongs to a writer that may be
198
+ // alive, so don't even open it; the record's expiry still decides.
199
+ if (now() - (await lstat(path)).mtimeMs < marginMs)
200
+ continue;
201
+ const staged = await readStagedOwner(path);
202
+ if (!staged || !(staged.expiresAt < now() - marginMs))
203
+ continue;
204
+ if (hooks?.beforeUnlink)
205
+ await hooks.beforeUnlink(path);
206
+ // Remove only the file that was read: a name reused since then keeps
207
+ // its new contents. Inode numbers can be reused at once after an
208
+ // unlink, so the record is read again as well as the identity compared.
209
+ const current = await readStagedOwner(path);
210
+ if (!current ||
211
+ !sameStagingFile(staged.identity, current.identity) ||
212
+ !(current.expiresAt < now() - marginMs))
213
+ continue;
214
+ await (hooks?.unlink ?? unlink)(path);
215
+ }
216
+ catch {
217
+ // Each leftover is independent; a vanished or unreadable one is skipped.
218
+ }
219
+ }
220
+ }
221
+ /**
222
+ * Start a background sweep of abandoned staging files beside `lockPath`, at
223
+ * most once per process per lock path. Called after this process acquires the
224
+ * lock, so no other cooperating process sweeps the same name at that moment.
225
+ * The sweep never delays or fails the acquisition: every error is ignored.
226
+ */
227
+ function startStagingSweep(lockPath, ttlMs, now) {
228
+ if (sweptLockPaths.has(lockPath))
229
+ return;
230
+ sweptLockPaths.add(lockPath);
231
+ const sweep = Promise.resolve()
232
+ .then(() => sweepAbandonedStaging(lockPath, ttlMs, now))
233
+ .catch(() => { });
234
+ pendingStagingSweeps.add(sweep);
235
+ void sweep.finally(() => pendingStagingSweeps.delete(sweep));
236
+ }
94
237
  const setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
95
238
  const clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
96
239
  // A concurrent contender renaming the freshly-created eviction-marker directory
@@ -970,6 +1113,7 @@ export async function acquireRefreshFileLockWithClock(options) {
970
1113
  return null;
971
1114
  }
972
1115
  scheduleRenewal();
1116
+ startStagingSweep(lockPath, options.ttlMs, now);
973
1117
  return {
974
1118
  ownerId,
975
1119
  whenLost: () => lostPromise,
@@ -0,0 +1,15 @@
1
+ import { PrivateFileError } from "./375d9cca2def037d-private-files.js";
2
+ import { isChangingLockRecord, LockContentionError } from "./4825e03209d6ae3e-with-lock.js";
3
+ import { SettingsRefusal } from "./facfd8afc431d68a-refusal.js";
4
+ /** Classify against the failing lock, not the settings destination it protects. */
5
+ export function rethrowSettingsLockError(error, target, name) {
6
+ if (error instanceof LockContentionError ||
7
+ isChangingLockRecord(error, target, name)) {
8
+ throw new SettingsRefusal('settings-busy', `Settings lock is busy: ${target}`, { cause: error });
9
+ }
10
+ if (error instanceof PrivateFileError &&
11
+ (error.stage === 'safe-parent' || error.stage === 'directory')) {
12
+ throw new SettingsRefusal('settings-unavailable', `Settings lock folder is unavailable: ${target}`, { cause: error });
13
+ }
14
+ throw error;
15
+ }
@@ -0,0 +1,15 @@
1
+ export const SETTINGS_REFUSAL_CODES = Object.freeze([
2
+ 'settings-unparseable',
3
+ 'settings-newer-version',
4
+ 'settings-invalid-value',
5
+ 'settings-busy',
6
+ 'settings-unavailable',
7
+ ]);
8
+ export class SettingsRefusal extends Error {
9
+ code;
10
+ name = 'SettingsRefusal';
11
+ constructor(code, message, options) {
12
+ super(message, options);
13
+ this.code = code;
14
+ }
15
+ }
@@ -0,0 +1,85 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, posix, resolve, win32 } from "node:path";
5
+ import {
6
+ isAbsoluteForPlatform,
7
+ settingsFilePath
8
+ } from "./cc0f2d1963547799-index.js";
9
+ import {
10
+ ACCOUNT_FILE_NAME,
11
+ ACCOUNT_STATE_FILE_NAME
12
+ } from "./b85c5301fddcb98a-paths.js";
13
+ export function canonicalSettingsPath(path) {
14
+ let ancestor = resolve(path);
15
+ const remaining = [];
16
+ for (;; )
17
+ try {
18
+ return join(realpathSync.native(ancestor), ...remaining);
19
+ } catch {
20
+ const parent = dirname(ancestor);
21
+ if (parent === ancestor)
22
+ return resolve(path);
23
+ remaining.unshift(basename(ancestor));
24
+ ancestor = parent;
25
+ }
26
+ }
27
+ const identities = new Map;
28
+ export function settingsIdentity(path) {
29
+ let identity = identities.get(path);
30
+ if (identity === void 0) {
31
+ identity = canonicalSettingsPath(path);
32
+ identities.set(path, identity);
33
+ }
34
+ return identity;
35
+ }
36
+ export function resolveDefaultSettingsStores(options = {}) {
37
+ const env = options.env ?? process.env, platform = options.platform ?? process.platform, home = (options.homedir ?? homedir)(), paths = platform === "win32" ? win32 : posix, configHome = env.XDG_CONFIG_HOME, configDir = paths.join(configHome && isAbsoluteForPlatform(configHome, platform) ? configHome : paths.join(home, ".config"), "opencode"), homeConfigDir = paths.join(home, ".config", "opencode"), folderIdentity = (path) => {
38
+ try {
39
+ return realpathSync.native(path);
40
+ } catch {
41
+ return resolve(path);
42
+ }
43
+ }, key = folderIdentity(configDir), runtimeDir = paths.join(env.XDG_STATE_HOME || paths.join(home, ".local", "state"), "cortexkit", "openai-auth", key === folderIdentity(homeConfigDir) ? "opencode" : `opencode-${createHash("sha256").update(key).digest("hex").slice(0, 16)}`), stateDir = existsSync(paths.join(runtimeDir, "layout.json")) ? runtimeDir : configDir, piDir = paths.join(home, ".pi", "agent");
44
+ return [
45
+ {
46
+ host: "opencode",
47
+ configPath: paths.join(configDir, ACCOUNT_FILE_NAME),
48
+ statePath: paths.join(stateDir, ACCOUNT_STATE_FILE_NAME)
49
+ },
50
+ {
51
+ host: "pi",
52
+ configPath: paths.join(piDir, ACCOUNT_FILE_NAME),
53
+ statePath: paths.join(piDir, ACCOUNT_STATE_FILE_NAME)
54
+ }
55
+ ];
56
+ }
57
+ export function resolveSettingsInstall(options) {
58
+ const env = options.env ?? process.env, platform = options.platform ?? process.platform, home = options.homedir ?? homedir, defaults = resolveDefaultSettingsStores({
59
+ env,
60
+ platform,
61
+ homedir: home
62
+ }), ownDefault = defaults[options.host === "opencode" ? 0 : 1], configIdentity = canonicalSettingsPath(options.paths.configPath), customConfig = configIdentity !== canonicalSettingsPath(ownDefault.configPath), variable = options.host === "opencode" ? "OPENCODE_OPENAI_AUTH_SETTINGS_FILE" : "PI_OPENAI_AUTH_SETTINGS_FILE", requested = env[variable];
63
+ let optInPath = requested !== void 0 && isAbsoluteForPlatform(requested, platform) ? requested : void 0;
64
+ if (optInPath !== void 0) {
65
+ const identity = canonicalSettingsPath(optInPath);
66
+ if ([options.paths, ...defaults].some((store) => canonicalSettingsPath(store.configPath) === identity || canonicalSettingsPath(store.statePath) === identity)) {
67
+ optInPath = void 0;
68
+ (options.logger ?? console).warn(`openai-auth ignored ${variable}: the settings file must not be an account config or state file.`);
69
+ }
70
+ }
71
+ const optIn = optInPath !== void 0, separate = !optIn && customConfig;
72
+ return {
73
+ host: options.host,
74
+ configIdentity,
75
+ target: optInPath ?? settingsFilePath({
76
+ plugin: "openai-auth",
77
+ env,
78
+ platform,
79
+ homedir: home()
80
+ }),
81
+ optIn,
82
+ separate,
83
+ sources: separate ? [] : optIn ? customConfig ? [{ host: options.host, ...options.paths }] : [] : defaults.map((source) => source.host === options.host ? { host: options.host, ...options.paths } : source)
84
+ };
85
+ }
@@ -0,0 +1,150 @@
1
+ import { isOverrideKeyAllowed } from "./58bc35a3cd459085-define.js";
2
+ import { isJsonObject, validateValue, } from "./5803fadb30af0ec0-descriptors.js";
3
+ import { defineSettingsKey } from "./23300c068d0b2ffc-parse.js";
4
+ /** Validate all children even when a list or record will be skipped as a whole. */
5
+ function validateFileValue(descriptor, value, keyPath, completeObjects, unknownReason, report) {
6
+ const invalid = () => {
7
+ report(keyPath, 'invalid-value');
8
+ return { valid: false };
9
+ };
10
+ if (descriptor.kind === 'object') {
11
+ if (!isJsonObject(value))
12
+ return invalid();
13
+ const cleaned = {};
14
+ let valid = true;
15
+ for (const [key, field] of Object.entries(value)) {
16
+ if (!Object.hasOwn(descriptor.fields, key)) {
17
+ report([...keyPath, key], unknownReason);
18
+ continue;
19
+ }
20
+ const result = validateFileValue(descriptor.fields[key], field, [...keyPath, key], completeObjects, unknownReason, report);
21
+ if (result.valid)
22
+ defineSettingsKey(cleaned, key, result.value);
23
+ else
24
+ valid = false;
25
+ }
26
+ if (completeObjects) {
27
+ for (const key of Object.keys(descriptor.fields)) {
28
+ if (!Object.hasOwn(value, key)) {
29
+ report([...keyPath, key], 'invalid-value');
30
+ valid = false;
31
+ }
32
+ }
33
+ }
34
+ // Partial objects keep valid siblings; resolution supplies skipped fields.
35
+ return valid || !completeObjects
36
+ ? { valid: true, value: cleaned }
37
+ : { valid: false };
38
+ }
39
+ if (descriptor.kind === 'list') {
40
+ if (!Array.isArray(value))
41
+ return invalid();
42
+ const cleaned = [];
43
+ let valid = true;
44
+ for (const [index, item] of value.entries()) {
45
+ const result = validateFileValue(descriptor.item, item, [...keyPath, String(index)], true, unknownReason, report);
46
+ if (result.valid)
47
+ cleaned.push(result.value);
48
+ else
49
+ valid = false;
50
+ }
51
+ return valid ? { valid: true, value: cleaned } : { valid: false };
52
+ }
53
+ if (descriptor.kind === 'record') {
54
+ if (!isJsonObject(value))
55
+ return invalid();
56
+ const cleaned = {};
57
+ let valid = true;
58
+ for (const [key, item] of Object.entries(value)) {
59
+ const result = validateFileValue(descriptor.value, item, [...keyPath, key], true, unknownReason, report);
60
+ if (result.valid)
61
+ defineSettingsKey(cleaned, key, result.value);
62
+ else
63
+ valid = false;
64
+ }
65
+ return valid ? { valid: true, value: cleaned } : { valid: false };
66
+ }
67
+ return validateValue(descriptor, value) ? { valid: true, value } : invalid();
68
+ }
69
+ /** Validate all overrides now, including values for hosts not requested later. */
70
+ export function buildSettingsSnapshot(definition, file, parsed) {
71
+ const entries = [];
72
+ const reported = new Set();
73
+ const report = (keyPath, reason) => {
74
+ const identity = JSON.stringify([keyPath, reason]);
75
+ if (reported.has(identity))
76
+ return;
77
+ reported.add(identity);
78
+ entries.push({ file: { ...file }, keyPath: [...keyPath], reason });
79
+ };
80
+ const snapshot = {
81
+ file: { ...file },
82
+ settings: {},
83
+ entries,
84
+ schemaVersion: 1,
85
+ newer: false,
86
+ hasDuplicates: parsed.parseable && parsed.hasDuplicates,
87
+ parsed,
88
+ };
89
+ if (!parsed.parseable) {
90
+ report([], 'unparseable');
91
+ return snapshot;
92
+ }
93
+ for (const keyPath of parsed.duplicateKeyPaths)
94
+ report(keyPath, 'duplicate-key');
95
+ const input = parsed.value;
96
+ if (Object.hasOwn(input, 'schema_version')) {
97
+ const version = input.schema_version;
98
+ if (typeof version === 'number' &&
99
+ Number.isInteger(version) &&
100
+ version >= 1) {
101
+ snapshot.schemaVersion = version;
102
+ snapshot.newer = version > 1;
103
+ }
104
+ else {
105
+ report(['schema_version'], 'invalid-schema-version');
106
+ }
107
+ }
108
+ const unknownReason = snapshot.newer
109
+ ? 'newer-version-key-ignored'
110
+ : 'unknown-key';
111
+ for (const [name, value] of Object.entries(input)) {
112
+ if (name === 'schema_version' || name === '$schema')
113
+ continue;
114
+ if (!Object.hasOwn(definition.settings, name)) {
115
+ report([name], unknownReason);
116
+ continue;
117
+ }
118
+ const declaration = definition.settings[name];
119
+ if (!declaration)
120
+ continue;
121
+ if (file.kind !== 'user' && declaration.project !== 'allowed') {
122
+ report([name], 'user-only-in-project');
123
+ continue;
124
+ }
125
+ if (isJsonObject(value) && declaration.overrides !== undefined) {
126
+ const overrides = {};
127
+ for (const [key, entry] of Object.entries(value)) {
128
+ if (!isOverrideKeyAllowed(declaration.overrides, key)) {
129
+ report([name, key], 'override-not-allowed');
130
+ continue;
131
+ }
132
+ const result = validateFileValue(declaration.value, entry, [name, key], false, unknownReason, report);
133
+ if (result.valid)
134
+ defineSettingsKey(overrides, key, result.value);
135
+ }
136
+ defineSettingsKey(snapshot.settings, name, overrides);
137
+ continue;
138
+ }
139
+ if (isJsonObject(value) &&
140
+ declaration.value.kind !== 'object' &&
141
+ declaration.value.kind !== 'record') {
142
+ report([name], 'override-not-allowed');
143
+ continue;
144
+ }
145
+ const result = validateFileValue(declaration.value, value, [name], false, unknownReason, report);
146
+ if (result.valid)
147
+ defineSettingsKey(snapshot.settings, name, result.value);
148
+ }
149
+ return snapshot;
150
+ }