@cortexkit/common-auth 0.43.0 → 0.45.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 (59) hide show
  1. package/dist/claustrum/enrollment.d.ts +25 -4
  2. package/dist/claustrum/enrollment.js +81 -4
  3. package/dist/claustrum/index.d.ts +1 -1
  4. package/dist/claustrum/index.js +1 -1
  5. package/dist/commands/builtins.d.ts +20 -1
  6. package/dist/commands/builtins.js +28 -12
  7. package/dist/commands/index.d.ts +1 -1
  8. package/dist/commands/menu.d.ts +6 -1
  9. package/dist/commands/menu.js +1 -0
  10. package/dist/fs/file-read-cache.d.ts +3 -0
  11. package/dist/fs/file-read-cache.js +9 -5
  12. package/dist/fs/refresh-file-lock.d.ts +11 -0
  13. package/dist/fs/refresh-file-lock.js +146 -2
  14. package/dist/fs/with-lock.d.ts +2 -0
  15. package/dist/fs/with-lock.js +1 -1
  16. package/dist/settings/define.d.ts +35 -0
  17. package/dist/settings/define.js +52 -0
  18. package/dist/settings/descriptors.d.ts +97 -0
  19. package/dist/settings/descriptors.js +81 -0
  20. package/dist/settings/edit.d.ts +24 -0
  21. package/dist/settings/edit.js +229 -0
  22. package/dist/settings/fs.d.ts +6 -0
  23. package/dist/settings/fs.js +19 -0
  24. package/dist/settings/handle.d.ts +30 -0
  25. package/dist/settings/handle.js +228 -0
  26. package/dist/settings/index.d.ts +10 -0
  27. package/dist/settings/index.js +7 -0
  28. package/dist/settings/lock-errors.d.ts +2 -0
  29. package/dist/settings/lock-errors.js +15 -0
  30. package/dist/settings/move.d.ts +76 -0
  31. package/dist/settings/move.js +351 -0
  32. package/dist/settings/parse.d.ts +24 -0
  33. package/dist/settings/parse.js +65 -0
  34. package/dist/settings/paths.d.ts +12 -0
  35. package/dist/settings/paths.js +48 -0
  36. package/dist/settings/refusal.d.ts +7 -0
  37. package/dist/settings/refusal.js +15 -0
  38. package/dist/settings/resolve.d.ts +15 -0
  39. package/dist/settings/resolve.js +51 -0
  40. package/dist/settings/schema.d.ts +29 -0
  41. package/dist/settings/schema.js +81 -0
  42. package/dist/settings/snapshot.d.ts +24 -0
  43. package/dist/settings/snapshot.js +150 -0
  44. package/dist/settings/update.d.ts +6 -0
  45. package/dist/settings/update.js +139 -0
  46. package/dist/settings/write.d.ts +26 -0
  47. package/dist/settings/write.js +88 -0
  48. package/dist/setup/command-error.d.ts +1 -1
  49. package/dist/setup/command-error.js +4 -2
  50. package/dist/setup/command.js +23 -6
  51. package/dist/setup/enroll.d.ts +2 -2
  52. package/dist/setup/enroll.js +13 -3
  53. package/dist/setup/enrollment-access.d.ts +7 -0
  54. package/dist/setup/enrollment-access.js +86 -0
  55. package/dist/setup/index.d.ts +1 -1
  56. package/dist/setup/types.d.ts +16 -1
  57. package/dist/tui-prefs/watcher.d.ts +3 -1
  58. package/dist/tui-prefs/watcher.js +41 -18
  59. package/package.json +6 -2
@@ -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 './lock-record.js';
5
5
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, isWindowsSharingViolation, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
6
6
  import { LockOwnershipError, lockPathFor } from './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,
@@ -1,3 +1,4 @@
1
+ import { type PrivateFileError } from './private-files.js';
1
2
  import { acquireRefreshFileLock } from './refresh-file-lock.js';
2
3
  export declare function lockPathFor(target: string, name: string): string;
3
4
  export declare class LockContentionError extends Error {
@@ -32,6 +33,7 @@ export interface LockOptions {
32
33
  onStep?: Parameters<typeof acquireRefreshFileLock>[0]['onStep'];
33
34
  onRenewalTimer?: Parameters<typeof acquireRefreshFileLock>[0]['onRenewalTimer'];
34
35
  }
36
+ export declare function isChangingLockRecord(error: unknown, target: string, name: string): error is PrivateFileError;
35
37
  export declare function withLock<T>(target: string, options: LockOptions, fn: (lock: {
36
38
  assertOwned(): Promise<void>;
37
39
  }) => Promise<T>): Promise<T>;
@@ -21,7 +21,7 @@ export class LockOwnershipError extends Error {
21
21
  this.details = details;
22
22
  }
23
23
  }
24
- function isChangingLockRecord(error, target, name) {
24
+ export function isChangingLockRecord(error, target, name) {
25
25
  const path = resolve(lockPathFor(target, name));
26
26
  const paths = [path, join(path, 'owner.json')];
27
27
  return (((isWindowsSharingViolation(error) ||
@@ -0,0 +1,35 @@
1
+ import { type ValueDescriptor, type ValueOf, type ValueValidationOptions } from './descriptors.js';
2
+ export interface SettingDeclaration<D extends ValueDescriptor = ValueDescriptor> {
3
+ readonly value: D;
4
+ readonly default: ValueDescriptor extends D ? unknown : ValueOf<D>;
5
+ readonly hosts: 'both' | 'opencode' | 'pi' | string;
6
+ readonly overrides?: {
7
+ readonly host?: true;
8
+ readonly model?: true;
9
+ };
10
+ readonly project?: 'user-only' | 'allowed';
11
+ readonly legacy?: readonly {
12
+ readonly source: string;
13
+ readonly path: readonly string[];
14
+ }[];
15
+ }
16
+ type Declarations = Readonly<Record<string, SettingDeclaration>>;
17
+ export interface SettingsDefinition<S extends Declarations = Declarations> {
18
+ readonly plugin: string;
19
+ readonly settings: {
20
+ readonly [K in keyof S]: S[K] & {
21
+ readonly project: S[K] extends {
22
+ readonly project: infer P;
23
+ } ? P : 'project' extends keyof S[K] ? Exclude<S[K]['project'], undefined> | 'user-only' : 'user-only';
24
+ };
25
+ };
26
+ }
27
+ export declare function defineSettings<const S extends Declarations>(definition: {
28
+ readonly plugin: string;
29
+ readonly settings: S;
30
+ }): SettingsDefinition<S>;
31
+ /** Internal helper: host names are reserved and never count as model ids. */
32
+ export declare function isOverrideKeyAllowed(overrides: NonNullable<SettingDeclaration['overrides']>, key: string): boolean;
33
+ /** Validate a file, update or map value, including any permitted override object. */
34
+ export declare function validateSettingValue(declaration: Pick<SettingDeclaration, 'value' | 'overrides'>, value: unknown, options?: ValueValidationOptions): boolean;
35
+ export {};
@@ -0,0 +1,52 @@
1
+ import { deepFreeze, isJsonObject, validateValue, } from './descriptors.js';
2
+ export function defineSettings(definition) {
3
+ for (const [name, declaration] of Object.entries(definition.settings)) {
4
+ if (name === 'schema_version' || name === '$schema') {
5
+ throw new TypeError(`Reserved setting name: ${name}`);
6
+ }
7
+ if (!/^[a-z][a-z0-9_]*$/.test(name) || /\s/.test(name)) {
8
+ throw new TypeError(`Setting name must be snake_case: ${name}`);
9
+ }
10
+ if (name === 'sidebar' && declaration.value.kind !== 'object') {
11
+ throw new TypeError('The sidebar setting must use an object descriptor');
12
+ }
13
+ if (declaration.overrides !== undefined &&
14
+ (declaration.value.kind === 'object' ||
15
+ declaration.value.kind === 'record')) {
16
+ throw new TypeError(`Object and record settings cannot use overrides: ${name}`);
17
+ }
18
+ if (!Object.hasOwn(declaration, 'default') ||
19
+ !validateValue(declaration.value, declaration.default, {
20
+ completeObjects: true,
21
+ })) {
22
+ throw new TypeError(`Invalid default for setting: ${name}`);
23
+ }
24
+ }
25
+ // Copy before freezing so the caller can still use its original default values.
26
+ return deepFreeze({
27
+ plugin: definition.plugin,
28
+ settings: Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
29
+ name,
30
+ structuredClone({
31
+ ...declaration,
32
+ project: declaration.project ?? 'user-only',
33
+ }),
34
+ ])),
35
+ });
36
+ }
37
+ /** Internal helper: host names are reserved and never count as model ids. */
38
+ export function isOverrideKeyAllowed(overrides, key) {
39
+ if (key === 'default')
40
+ return true;
41
+ if (key === 'opencode' || key === 'pi')
42
+ return overrides.host === true;
43
+ return overrides.model === true;
44
+ }
45
+ /** Validate a file, update or map value, including any permitted override object. */
46
+ export function validateSettingValue(declaration, value, options = {}) {
47
+ if (declaration.overrides !== undefined && isJsonObject(value)) {
48
+ return Object.entries(value).every(([key, entry]) => isOverrideKeyAllowed(declaration.overrides ?? {}, key) &&
49
+ validateValue(declaration.value, entry, options));
50
+ }
51
+ return validateValue(declaration.value, value, options);
52
+ }
@@ -0,0 +1,97 @@
1
+ export type ValueDescriptor = {
2
+ readonly kind: 'boolean';
3
+ } | {
4
+ readonly kind: 'integer';
5
+ readonly min?: number;
6
+ readonly max?: number;
7
+ } | {
8
+ readonly kind: 'number';
9
+ readonly min?: number;
10
+ readonly max?: number;
11
+ } | {
12
+ readonly kind: 'string';
13
+ } | {
14
+ readonly kind: 'oneOf';
15
+ readonly values: readonly string[];
16
+ } | {
17
+ readonly kind: 'list';
18
+ readonly item: ValueDescriptor;
19
+ } | {
20
+ readonly kind: 'object';
21
+ readonly fields: Readonly<Record<string, ValueDescriptor>>;
22
+ } | {
23
+ readonly kind: 'record';
24
+ readonly value: ValueDescriptor;
25
+ };
26
+ type SettingsValue = boolean | number | string | SettingsValue[] | {
27
+ [key: string]: SettingsValue;
28
+ };
29
+ export type ValueOf<D extends ValueDescriptor> = ValueDescriptor extends D ? SettingsValue : D extends {
30
+ kind: 'boolean';
31
+ } ? boolean : D extends {
32
+ kind: 'integer' | 'number';
33
+ } ? number : D extends {
34
+ kind: 'string';
35
+ } ? string : D extends {
36
+ kind: 'oneOf';
37
+ values: infer V extends readonly string[];
38
+ } ? V[number] : D extends {
39
+ kind: 'list';
40
+ item: infer I extends ValueDescriptor;
41
+ } ? ValueOf<I>[] : D extends {
42
+ kind: 'object';
43
+ fields: infer F extends Readonly<Record<string, ValueDescriptor>>;
44
+ } ? {
45
+ -readonly [K in keyof F]: ValueOf<F[K]>;
46
+ } : D extends {
47
+ kind: 'record';
48
+ value: infer V extends ValueDescriptor;
49
+ } ? Record<string, ValueOf<V>> : never;
50
+ type Bounds = {
51
+ readonly min?: number;
52
+ readonly max?: number;
53
+ };
54
+ export declare function boolean(): Readonly<{
55
+ readonly kind: 'boolean';
56
+ }>;
57
+ export declare function integer({ min, max }?: Bounds): Readonly<{
58
+ readonly kind: 'integer';
59
+ readonly min: number | undefined;
60
+ readonly max: number | undefined;
61
+ }>;
62
+ export declare function number({ min, max }?: Bounds): Readonly<{
63
+ readonly kind: 'number';
64
+ readonly min: number | undefined;
65
+ readonly max: number | undefined;
66
+ }>;
67
+ export declare function string(): Readonly<{
68
+ readonly kind: 'string';
69
+ }>;
70
+ export declare function oneOf<const V extends readonly string[]>(values: V): Readonly<{
71
+ readonly kind: 'oneOf';
72
+ readonly values: Readonly<V>;
73
+ }>;
74
+ export declare function list<const D extends ValueDescriptor>(item: D): {
75
+ readonly kind: 'list';
76
+ readonly item: D;
77
+ };
78
+ export declare function object<const F extends Readonly<Record<string, ValueDescriptor>>>(fields: F): {
79
+ readonly kind: 'object';
80
+ readonly fields: F;
81
+ };
82
+ export declare function record<const D extends ValueDescriptor>(value: D): {
83
+ readonly kind: 'record';
84
+ readonly value: D;
85
+ };
86
+ /** Internal validation policy shared by file readers, updates and migration maps. */
87
+ export interface ValueValidationOptions {
88
+ readonly completeObjects?: boolean;
89
+ readonly allowUnknownFields?: boolean;
90
+ }
91
+ /** JSON objects exclude arrays and objects such as Date that serialize differently. */
92
+ export declare function isJsonObject(value: unknown): value is Record<string, unknown>;
93
+ /** Missing fields can be filled from lower levels, but list and record objects must be complete. */
94
+ export declare function validateValue(descriptor: ValueDescriptor, value: unknown, options?: ValueValidationOptions): boolean;
95
+ /** Internal helper; definitions and descriptor payloads are immutable at runtime. */
96
+ export declare function deepFreeze<T>(value: T): T;
97
+ export {};
@@ -0,0 +1,81 @@
1
+ export function boolean() {
2
+ return Object.freeze({ kind: 'boolean' });
3
+ }
4
+ export function integer({ min, max } = {}) {
5
+ return Object.freeze({ kind: 'integer', min, max });
6
+ }
7
+ export function number({ min, max } = {}) {
8
+ return Object.freeze({ kind: 'number', min, max });
9
+ }
10
+ export function string() {
11
+ return Object.freeze({ kind: 'string' });
12
+ }
13
+ export function oneOf(values) {
14
+ return Object.freeze({
15
+ kind: 'oneOf',
16
+ values: Object.freeze([...values]),
17
+ });
18
+ }
19
+ export function list(item) {
20
+ return deepFreeze({ kind: 'list', item });
21
+ }
22
+ export function object(fields) {
23
+ return deepFreeze({ kind: 'object', fields: { ...fields } });
24
+ }
25
+ export function record(value) {
26
+ return deepFreeze({ kind: 'record', value });
27
+ }
28
+ /** JSON objects exclude arrays and objects such as Date that serialize differently. */
29
+ export function isJsonObject(value) {
30
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
31
+ return false;
32
+ }
33
+ const prototype = Object.getPrototypeOf(value);
34
+ return prototype === Object.prototype || prototype === null;
35
+ }
36
+ /** Missing fields can be filled from lower levels, but list and record objects must be complete. */
37
+ export function validateValue(descriptor, value, options = {}) {
38
+ switch (descriptor.kind) {
39
+ case 'boolean':
40
+ return typeof value === 'boolean';
41
+ case 'integer':
42
+ case 'number':
43
+ return (typeof value === 'number' &&
44
+ Number.isFinite(value) &&
45
+ (descriptor.kind !== 'integer' || Number.isInteger(value)) &&
46
+ (descriptor.min === undefined || value >= descriptor.min) &&
47
+ (descriptor.max === undefined || value <= descriptor.max));
48
+ case 'string':
49
+ return typeof value === 'string';
50
+ case 'oneOf':
51
+ return typeof value === 'string' && descriptor.values.includes(value);
52
+ case 'list':
53
+ return (Array.isArray(value) &&
54
+ Array.from(value).every((item) => validateValue(descriptor.item, item, {
55
+ ...options,
56
+ completeObjects: true,
57
+ })));
58
+ case 'object':
59
+ return (isJsonObject(value) &&
60
+ Object.entries(value).every(([key, field]) => Object.hasOwn(descriptor.fields, key)
61
+ ? validateValue(descriptor.fields[key], field, options)
62
+ : options.allowUnknownFields === true) &&
63
+ (!options.completeObjects ||
64
+ Object.keys(descriptor.fields).every((key) => Object.hasOwn(value, key))));
65
+ case 'record':
66
+ return (isJsonObject(value) &&
67
+ Object.values(value).every((item) => validateValue(descriptor.value, item, {
68
+ ...options,
69
+ completeObjects: true,
70
+ })));
71
+ }
72
+ }
73
+ /** Internal helper; definitions and descriptor payloads are immutable at runtime. */
74
+ export function deepFreeze(value) {
75
+ if (value && typeof value === 'object') {
76
+ for (const child of Object.values(value))
77
+ deepFreeze(child);
78
+ Object.freeze(value);
79
+ }
80
+ return value;
81
+ }
@@ -0,0 +1,24 @@
1
+ import type { SettingsDefinition } from './define.js';
2
+ export type SettingsEdit = {
3
+ setting: string;
4
+ path?: readonly string[];
5
+ } & ({
6
+ value: unknown;
7
+ remove?: never;
8
+ } | {
9
+ remove: true;
10
+ value?: never;
11
+ });
12
+ export interface UpdateResult {
13
+ outcome: 'updated' | 'unchanged';
14
+ }
15
+ interface EditContext {
16
+ host: string;
17
+ model?: string;
18
+ }
19
+ /** Pure JSONC edit engine; the writer restores the BOM and owns durable I/O. */
20
+ export declare function applySettingsEdits(definition: SettingsDefinition, source: string, edits: readonly SettingsEdit[], context: EditContext): UpdateResult & {
21
+ text: string;
22
+ hasBom: boolean;
23
+ };
24
+ export {};