@cortexkit/common-auth 0.44.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 (53) hide show
  1. package/dist/commands/builtins.d.ts +20 -1
  2. package/dist/commands/builtins.js +28 -12
  3. package/dist/commands/index.d.ts +1 -1
  4. package/dist/commands/menu.d.ts +6 -1
  5. package/dist/commands/menu.js +1 -0
  6. package/dist/fs/file-read-cache.d.ts +3 -0
  7. package/dist/fs/file-read-cache.js +9 -5
  8. package/dist/fs/refresh-file-lock.d.ts +11 -0
  9. package/dist/fs/refresh-file-lock.js +146 -2
  10. package/dist/fs/with-lock.d.ts +2 -0
  11. package/dist/fs/with-lock.js +1 -1
  12. package/dist/settings/define.d.ts +35 -0
  13. package/dist/settings/define.js +52 -0
  14. package/dist/settings/descriptors.d.ts +97 -0
  15. package/dist/settings/descriptors.js +81 -0
  16. package/dist/settings/edit.d.ts +24 -0
  17. package/dist/settings/edit.js +229 -0
  18. package/dist/settings/fs.d.ts +6 -0
  19. package/dist/settings/fs.js +19 -0
  20. package/dist/settings/handle.d.ts +30 -0
  21. package/dist/settings/handle.js +228 -0
  22. package/dist/settings/index.d.ts +10 -0
  23. package/dist/settings/index.js +7 -0
  24. package/dist/settings/lock-errors.d.ts +2 -0
  25. package/dist/settings/lock-errors.js +15 -0
  26. package/dist/settings/move.d.ts +76 -0
  27. package/dist/settings/move.js +351 -0
  28. package/dist/settings/parse.d.ts +24 -0
  29. package/dist/settings/parse.js +65 -0
  30. package/dist/settings/paths.d.ts +12 -0
  31. package/dist/settings/paths.js +48 -0
  32. package/dist/settings/refusal.d.ts +7 -0
  33. package/dist/settings/refusal.js +15 -0
  34. package/dist/settings/resolve.d.ts +15 -0
  35. package/dist/settings/resolve.js +51 -0
  36. package/dist/settings/schema.d.ts +29 -0
  37. package/dist/settings/schema.js +81 -0
  38. package/dist/settings/snapshot.d.ts +24 -0
  39. package/dist/settings/snapshot.js +150 -0
  40. package/dist/settings/update.d.ts +6 -0
  41. package/dist/settings/update.js +139 -0
  42. package/dist/settings/write.d.ts +26 -0
  43. package/dist/settings/write.js +88 -0
  44. package/dist/setup/command-error.d.ts +1 -1
  45. package/dist/setup/command-error.js +3 -2
  46. package/dist/setup/command.js +5 -1
  47. package/dist/setup/enroll.js +3 -3
  48. package/dist/setup/enrollment-access.d.ts +1 -1
  49. package/dist/setup/enrollment-access.js +13 -4
  50. package/dist/setup/types.d.ts +4 -0
  51. package/dist/tui-prefs/watcher.d.ts +3 -1
  52. package/dist/tui-prefs/watcher.js +41 -18
  53. package/package.json +5 -1
@@ -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 {};
@@ -0,0 +1,229 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { applyEdits, createScanner, findNodeAtLocation, modify, } from 'jsonc-parser';
3
+ import { isJsonObject, validateValue, } from './descriptors.js';
4
+ import { parseSettings } from './parse.js';
5
+ import { SettingsRefusal } from './refusal.js';
6
+ // jsonc-parser declares these scanner tokens as an ambient const enum, which
7
+ // cannot be imported as a value with verbatimModuleSyntax enabled.
8
+ const SyntaxKind = {
9
+ CommaToken: 5,
10
+ LineCommentTrivia: 12,
11
+ BlockCommentTrivia: 13,
12
+ Trivia: 15,
13
+ EOF: 17,
14
+ };
15
+ function invalid() {
16
+ throw new SettingsRefusal('settings-invalid-value', 'The settings edit does not match its declared value');
17
+ }
18
+ function parseForEdit(text) {
19
+ const parsed = parseSettings(text);
20
+ if (!parsed.parseable || parsed.hasDuplicates) {
21
+ throw new SettingsRefusal('settings-unparseable', 'Settings must be an object without duplicate keys');
22
+ }
23
+ return parsed;
24
+ }
25
+ function descriptorAtPath(descriptor, path) {
26
+ let current = descriptor;
27
+ for (const key of path) {
28
+ if (current.kind === 'object' && Object.hasOwn(current.fields, key)) {
29
+ current = current.fields[key];
30
+ }
31
+ else if (current.kind === 'record') {
32
+ current = current.value;
33
+ }
34
+ else {
35
+ invalid();
36
+ }
37
+ }
38
+ return current;
39
+ }
40
+ function destination(declaration, setting, value, { host, model }) {
41
+ if (declaration.overrides !== undefined && isJsonObject(value)) {
42
+ if (declaration.overrides.model &&
43
+ model !== undefined &&
44
+ model !== 'default' &&
45
+ model !== 'opencode' &&
46
+ model !== 'pi' &&
47
+ Object.hasOwn(value, model)) {
48
+ return [setting, model];
49
+ }
50
+ if (declaration.overrides.host &&
51
+ (host === 'opencode' || host === 'pi') &&
52
+ Object.hasOwn(value, host)) {
53
+ return [setting, host];
54
+ }
55
+ return [setting, 'default'];
56
+ }
57
+ return [setting];
58
+ }
59
+ function resolutionUnit(descriptor, destination, path) {
60
+ let current = descriptor;
61
+ const unitPath = [...destination];
62
+ for (const key of path) {
63
+ // Records and lists resolve whole, even when the edit changes one leaf.
64
+ if (current.kind === 'record' || current.kind === 'list')
65
+ break;
66
+ current = descriptorAtPath(current, [key]);
67
+ unitPath.push(key);
68
+ }
69
+ return { path: unitPath, descriptor: current };
70
+ }
71
+ function checkPath(parsed, path) {
72
+ for (let length = 1; length < path.length; length++) {
73
+ const node = parsed.tree && findNodeAtLocation(parsed.tree, path.slice(0, length));
74
+ if (node && node.type !== 'object')
75
+ invalid();
76
+ }
77
+ }
78
+ /** Remove only the member's own tokens; intervening comment lines belong to neither neighbor. */
79
+ function removeMember(text, tree, path) {
80
+ const property = tree && findNodeAtLocation(tree, path)?.parent;
81
+ const parent = property?.parent;
82
+ if (property?.type !== 'property' || !parent?.children)
83
+ return text;
84
+ const scanner = createScanner(text, false);
85
+ const end = property.offset + property.length;
86
+ const index = parent.children.indexOf(property);
87
+ const next = parent.children[index + 1];
88
+ const followingEnd = next?.offset ?? parent.offset + parent.length - 1;
89
+ let comma;
90
+ scanner.setPosition(end);
91
+ while (scanner.getPosition() < followingEnd) {
92
+ const token = scanner.scan();
93
+ if (token === SyntaxKind.CommaToken) {
94
+ comma = { start: scanner.getTokenOffset(), end: scanner.getPosition() };
95
+ break;
96
+ }
97
+ if (token === SyntaxKind.EOF)
98
+ break;
99
+ }
100
+ if (!comma && index > 0) {
101
+ const previous = parent.children[index - 1];
102
+ scanner.setPosition(previous.offset + previous.length);
103
+ while (scanner.getPosition() < property.offset) {
104
+ const token = scanner.scan();
105
+ if (token === SyntaxKind.CommaToken) {
106
+ comma = { start: scanner.getTokenOffset(), end: scanner.getPosition() };
107
+ break;
108
+ }
109
+ if (token === SyntaxKind.EOF)
110
+ break;
111
+ }
112
+ }
113
+ let removeEnd = end;
114
+ scanner.setPosition(end);
115
+ while (scanner.getPosition() < followingEnd) {
116
+ const token = scanner.scan();
117
+ if (token === SyntaxKind.Trivia || token === SyntaxKind.CommaToken)
118
+ continue;
119
+ if (token !== SyntaxKind.LineCommentTrivia &&
120
+ token !== SyntaxKind.BlockCommentTrivia)
121
+ break;
122
+ removeEnd = scanner.getPosition();
123
+ // A multiline trailing comment belongs to the member, but comments starting
124
+ // on subsequent lines do not.
125
+ if (/[\r\n]/.test(scanner.getTokenValue()))
126
+ break;
127
+ }
128
+ if (comma &&
129
+ comma.start >= end &&
130
+ !/[\r\n]/.test(text.slice(end, comma.start))) {
131
+ removeEnd = Math.max(removeEnd, comma.end);
132
+ }
133
+ const lineStart = Math.max(text.lastIndexOf('\n', property.offset - 1), text.lastIndexOf('\r', property.offset - 1)) + 1;
134
+ let removeStart = property.offset;
135
+ const lineBreak = /^[\t ]*(\r\n|\r|\n)/.exec(text.slice(removeEnd));
136
+ if (/^[\t ]*$/.test(text.slice(lineStart, property.offset)) && lineBreak) {
137
+ removeStart = lineStart;
138
+ removeEnd += lineBreak[0].length;
139
+ }
140
+ const edits = [
141
+ { offset: removeStart, length: removeEnd - removeStart, content: '' },
142
+ ];
143
+ // The last member's comma can be separated from it by preserved comment lines.
144
+ if (comma && (comma.start < removeStart || comma.start >= removeEnd)) {
145
+ edits.push({
146
+ offset: comma.start,
147
+ length: comma.end - comma.start,
148
+ content: '',
149
+ });
150
+ }
151
+ return applyEdits(text, edits);
152
+ }
153
+ /** Pure JSONC edit engine; the writer restores the BOM and owns durable I/O. */
154
+ export function applySettingsEdits(definition, source, edits, context) {
155
+ // Validate the entire request before changing even the private working text.
156
+ for (const edit of edits) {
157
+ if (!Object.hasOwn(definition.settings, edit.setting))
158
+ invalid();
159
+ const declaration = definition.settings[edit.setting];
160
+ if (edit.path !== undefined &&
161
+ declaration.value.kind !== 'object' &&
162
+ declaration.value.kind !== 'record')
163
+ invalid();
164
+ const descriptor = descriptorAtPath(declaration.value, edit.path ?? []);
165
+ if (edit.remove !== true && !validateValue(descriptor, edit.value))
166
+ invalid();
167
+ }
168
+ const start = parseForEdit(source);
169
+ let working = start;
170
+ const units = [];
171
+ for (const edit of edits) {
172
+ const declaration = definition.settings[edit.setting];
173
+ const base = edit.path !== undefined
174
+ ? [edit.setting]
175
+ : destination(declaration, edit.setting, working.value[edit.setting], context);
176
+ const path = [...base, ...(edit.path ?? [])];
177
+ checkPath(working, path);
178
+ units.push(resolutionUnit(declaration.value, base, edit.path ?? []));
179
+ const node = working.tree && findNodeAtLocation(working.tree, path);
180
+ let text;
181
+ if (edit.remove === true) {
182
+ if (!node)
183
+ continue;
184
+ text = removeMember(working.text, working.tree, path);
185
+ let removed = parseForEdit(text);
186
+ const remaining = removed.value[edit.setting];
187
+ if (base.length === 2 &&
188
+ isJsonObject(remaining) &&
189
+ Object.keys(remaining).length === 0) {
190
+ text = removeMember(text, removed.tree, [edit.setting]);
191
+ removed = parseForEdit(text);
192
+ }
193
+ working = removed;
194
+ }
195
+ else {
196
+ if (node && isDeepStrictEqual(valueAt(working.value, path), edit.value))
197
+ continue;
198
+ text = applyEdits(working.text, modify(working.text, path, edit.value, {
199
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
200
+ }));
201
+ working = parseForEdit(text);
202
+ }
203
+ }
204
+ for (const unit of units) {
205
+ const node = working.tree && findNodeAtLocation(working.tree, unit.path);
206
+ if (node &&
207
+ !validateValue(unit.descriptor, valueAt(working.value, unit.path), {
208
+ allowUnknownFields: true,
209
+ }))
210
+ invalid();
211
+ }
212
+ if (isDeepStrictEqual(start.value, working.value)) {
213
+ return { outcome: 'unchanged', text: start.text, hasBom: start.hasBom };
214
+ }
215
+ return {
216
+ outcome: 'updated',
217
+ text: working.text,
218
+ hasBom: start.hasBom,
219
+ };
220
+ }
221
+ function valueAt(value, path) {
222
+ let current = value;
223
+ for (const key of path) {
224
+ if (!isJsonObject(current) || !Object.hasOwn(current, key))
225
+ return undefined;
226
+ current = current[key];
227
+ }
228
+ return current;
229
+ }
@@ -0,0 +1,6 @@
1
+ import * as fs from 'node:fs/promises';
2
+ type SettingsFs = Pick<typeof fs, 'readFile' | 'stat' | 'lstat' | 'realpath' | 'open' | 'rename' | 'link' | 'unlink' | 'mkdir' | 'readdir'>;
3
+ export declare const SettingsFs: SettingsFs;
4
+ /** Internal test hook; omitted methods always use the native implementation. */
5
+ export declare function setSettingsFsForTest(overrides?: Partial<SettingsFs>): void;
6
+ export {};
@@ -0,0 +1,19 @@
1
+ import * as fs from 'node:fs/promises';
2
+ const defaults = {
3
+ readFile: fs.readFile,
4
+ stat: fs.stat,
5
+ lstat: fs.lstat,
6
+ realpath: fs.realpath,
7
+ open: fs.open,
8
+ rename: fs.rename,
9
+ link: fs.link,
10
+ unlink: fs.unlink,
11
+ mkdir: fs.mkdir,
12
+ readdir: fs.readdir,
13
+ };
14
+ // Keep one object so readers, writers and directory sync use the same filesystem.
15
+ export const SettingsFs = { ...defaults };
16
+ /** Internal test hook; omitted methods always use the native implementation. */
17
+ export function setSettingsFsForTest(overrides) {
18
+ Object.assign(SettingsFs, defaults, overrides);
19
+ }
@@ -0,0 +1,30 @@
1
+ import type { ChannelLogger } from '../logger/engine.js';
2
+ import type { SettingDeclaration, SettingsDefinition } from './define.js';
3
+ import { type ValueOf } from './descriptors.js';
4
+ import type { SettingsEdit, UpdateResult } from './edit.js';
5
+ import { type GetOptions } from './resolve.js';
6
+ import { type ReportEntry } from './snapshot.js';
7
+ export interface LegacyProjectSource {
8
+ readonly path: string;
9
+ read(text: string): unknown;
10
+ }
11
+ export interface OpenSettingsOptions {
12
+ readonly file: string;
13
+ readonly log: Pick<ChannelLogger, 'warn' | 'info'>;
14
+ readonly separateInstall: boolean;
15
+ readonly createMissing?: boolean;
16
+ readonly lockTimeoutMs?: number;
17
+ readonly legacyProject?: (project: string) => LegacyProjectSource | undefined;
18
+ }
19
+ export interface SettingsHandle<S extends Readonly<Record<string, SettingDeclaration>> = Readonly<Record<string, SettingDeclaration>>> {
20
+ read(options?: {
21
+ readonly project?: string;
22
+ }): Promise<void>;
23
+ get<K extends keyof S & string>(name: K, options: GetOptions): Promise<ValueOf<S[K]['value']>>;
24
+ report(): ReportEntry[];
25
+ update(edits: readonly SettingsEdit[], options: Pick<GetOptions, 'host' | 'model'>): Promise<UpdateResult>;
26
+ watch(onChange: () => void): () => void;
27
+ }
28
+ /** Internal test hook; not part of the settings package exports. */
29
+ export declare function resetSettingsReportedForTest(): void;
30
+ export declare function openSettings<S extends Readonly<Record<string, SettingDeclaration>>>(definition: SettingsDefinition<S>, options: OpenSettingsOptions): SettingsHandle<S>;
@@ -0,0 +1,228 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { FileReadCache } from '../fs/file-read-cache.js';
3
+ import { watchSettings } from '../tui-prefs/watcher.js';
4
+ import { isJsonObject } from './descriptors.js';
5
+ import { SettingsFs } from './fs.js';
6
+ import { parseSettings } from './parse.js';
7
+ import { resolveSetting } from './resolve.js';
8
+ import { buildSettingsSnapshot, } from './snapshot.js';
9
+ import { updateSettings } from './update.js';
10
+ const reportedKey = Symbol.for('cortexkit.common-auth.settings.reported.v1');
11
+ function reportedEntries() {
12
+ let reported = Reflect.get(globalThis, reportedKey);
13
+ if (!reported) {
14
+ reported = new Set();
15
+ Reflect.set(globalThis, reportedKey, reported);
16
+ }
17
+ return reported;
18
+ }
19
+ /** Internal test hook; not part of the settings package exports. */
20
+ export function resetSettingsReportedForTest() {
21
+ reportedEntries().clear();
22
+ }
23
+ export function openSettings(definition, options) {
24
+ options = { createMissing: false, lockTimeoutMs: 2_000, ...options };
25
+ const userPath = resolve(options.file);
26
+ const cacheOptions = {
27
+ followSymlinks: true,
28
+ // Read SettingsFs at call time so setSettingsFsForTest reaches open handles.
29
+ stat: (path) => SettingsFs.stat(path),
30
+ lstat: (path) => SettingsFs.lstat(path),
31
+ };
32
+ const userCache = new FileReadCache(cacheOptions);
33
+ const projectCache = new FileReadCache(cacheOptions);
34
+ let user;
35
+ const projects = new Map();
36
+ // A project's report and resolution use only the source selected by its read.
37
+ const projectLevels = new Map();
38
+ const projectSequences = new Map();
39
+ let sequence = 0;
40
+ // Keep ordering metadata after eviction so an older in-flight read cannot win.
41
+ const committedSequences = new Map();
42
+ const projectPath = (project) => resolve(join(project, '.cortexkit', `${definition.plugin}.jsonc`));
43
+ // Windows reads every time (below), so remember each file's last bytes to
44
+ // tell a changed file from an unchanged one, as the cache does elsewhere.
45
+ const windows = process.platform === 'win32';
46
+ const windowsSeen = new Map();
47
+ const unreadFile = {
48
+ missing: Symbol('missing'),
49
+ unreadable: Symbol('unreadable'),
50
+ };
51
+ async function load(file, reader) {
52
+ const currentSequence = ++sequence;
53
+ const cache = file.kind === 'user' ? userCache : projectCache;
54
+ let loaded = false;
55
+ const seen = (path, content) => {
56
+ if (!windows) {
57
+ // The cache calls this reader only when the file changed.
58
+ loaded = true;
59
+ return;
60
+ }
61
+ loaded = windowsSeen.get(path) !== content;
62
+ windowsSeen.set(path, content);
63
+ };
64
+ const readFile = async ([path]) => {
65
+ let text;
66
+ try {
67
+ text = await SettingsFs.readFile(path, 'utf8');
68
+ }
69
+ catch (error) {
70
+ const status = error.code === 'ENOENT'
71
+ ? 'missing'
72
+ : 'unreadable';
73
+ seen(path, unreadFile[status]);
74
+ return { status };
75
+ }
76
+ seen(path, text);
77
+ let parsed;
78
+ if (reader) {
79
+ let value;
80
+ try {
81
+ value = reader(text);
82
+ }
83
+ catch {
84
+ return { status: 'unreadable' };
85
+ }
86
+ if (!isJsonObject(value))
87
+ return { status: 'unparseable' };
88
+ // Legacy readers return an object keyed by setting name, not JSONC text.
89
+ parsed = {
90
+ parseable: true,
91
+ text,
92
+ hasBom: false,
93
+ tree: undefined,
94
+ value,
95
+ duplicateKeyPaths: [],
96
+ hasDuplicates: false,
97
+ };
98
+ }
99
+ else {
100
+ parsed = parseSettings(text);
101
+ }
102
+ return parsed.parseable
103
+ ? {
104
+ status: 'snapshot',
105
+ snapshot: buildSettingsSnapshot(definition, file, parsed),
106
+ }
107
+ : { status: 'unparseable' };
108
+ };
109
+ // On Windows a quick same-size rewrite can keep the size and timestamps
110
+ // the cache compares, so read the file every time instead of using the cache.
111
+ const outcome = process.platform === 'win32'
112
+ ? await readFile([file.path])
113
+ : await cache.read([file.path], readFile);
114
+ const key = JSON.stringify([file.kind, file.path]);
115
+ if (currentSequence <= (committedSequences.get(key) ?? 0))
116
+ return;
117
+ committedSequences.set(key, currentSequence);
118
+ const previous = file.kind === 'user' ? user : projects.get(file.path);
119
+ const snapshot = outcome.status === 'snapshot'
120
+ ? outcome.snapshot
121
+ : outcome.status === 'missing'
122
+ ? undefined
123
+ : previous?.snapshot;
124
+ const entries = [...(snapshot?.entries ?? [])];
125
+ if (outcome.status === 'unparseable' || outcome.status === 'unreadable') {
126
+ entries.unshift({
127
+ file: { ...file },
128
+ keyPath: [],
129
+ reason: outcome.status,
130
+ });
131
+ }
132
+ const state = { status: outcome.status, snapshot, entries };
133
+ if (file.kind === 'user') {
134
+ user = state;
135
+ }
136
+ else {
137
+ // Cache hits do not refresh insertion order; changed files do.
138
+ if (loaded)
139
+ projects.delete(file.path);
140
+ if (!projects.has(file.path) && projects.size >= 64) {
141
+ const oldest = projects.keys().next().value;
142
+ if (oldest !== undefined) {
143
+ projects.delete(oldest);
144
+ windowsSeen.delete(oldest);
145
+ for (const [project, selected] of projectLevels) {
146
+ if (selected === oldest)
147
+ projectLevels.delete(project);
148
+ }
149
+ }
150
+ }
151
+ projects.set(file.path, state);
152
+ }
153
+ const reported = reportedEntries();
154
+ for (const entry of entries) {
155
+ const identity = JSON.stringify([
156
+ entry.file.path,
157
+ entry.keyPath,
158
+ entry.reason,
159
+ ]);
160
+ if (reported.has(identity))
161
+ continue;
162
+ reported.add(identity);
163
+ options.log.warn(`Settings ${entry.reason}: ${entry.file.path} (${entry.keyPath.join('.') || '<root>'})`, structuredClone(entry));
164
+ }
165
+ }
166
+ async function readProject(project) {
167
+ const path = projectPath(project);
168
+ const currentSequence = ++sequence;
169
+ await load({ kind: 'project', path });
170
+ if (currentSequence <= (projectSequences.get(path) ?? 0))
171
+ return;
172
+ let selected = path;
173
+ if (projects.get(path)?.status === 'missing') {
174
+ const source = options.legacyProject?.(project);
175
+ if (source) {
176
+ selected = resolve(source.path);
177
+ await load({ kind: 'legacy-project', path: selected }, (text) => source.read(text));
178
+ }
179
+ }
180
+ // A slow legacy reader must not replace a newer read's project-file choice.
181
+ if (currentSequence <= (projectSequences.get(path) ?? 0))
182
+ return;
183
+ projectSequences.set(path, currentSequence);
184
+ projectLevels.set(path, selected);
185
+ }
186
+ const handle = {
187
+ async read({ project } = {}) {
188
+ if (options.separateInstall)
189
+ return;
190
+ await Promise.all([
191
+ load({ kind: 'user', path: userPath }),
192
+ ...(project === undefined ? [] : [readProject(project)]),
193
+ ]);
194
+ },
195
+ async get(name, getOptions) {
196
+ if (!Object.hasOwn(definition.settings, name)) {
197
+ throw new TypeError(`Undeclared setting: ${name}`);
198
+ }
199
+ await handle.read({ project: getOptions.project });
200
+ return resolveSetting(definition, name, getOptions, {
201
+ user: user?.snapshot,
202
+ project: getOptions.project === undefined
203
+ ? undefined
204
+ : projects.get(projectLevels.get(projectPath(getOptions.project)) ?? '')?.snapshot,
205
+ });
206
+ },
207
+ report() {
208
+ return structuredClone([
209
+ ...(user?.entries ?? []),
210
+ ...Array.from(new Set(projectLevels.values())).flatMap((path) => projects.get(path)?.entries ?? []),
211
+ ]);
212
+ },
213
+ update(edits, context) {
214
+ return updateSettings(definition, { ...options, file: userPath }, edits, context);
215
+ },
216
+ watch(onChange) {
217
+ if (options.separateInstall)
218
+ return () => { };
219
+ return watchSettings(userPath, onChange, {
220
+ fs: {
221
+ stat: (path) => SettingsFs.stat(path),
222
+ readFile: (path) => SettingsFs.readFile(path, 'utf8'),
223
+ },
224
+ });
225
+ },
226
+ };
227
+ return handle;
228
+ }
@@ -0,0 +1,10 @@
1
+ export { defineSettings, type SettingDeclaration, type SettingsDefinition, } from './define.js';
2
+ export { boolean, integer, list, number, object, oneOf, record, string, type ValueDescriptor, type ValueOf, } from './descriptors.js';
3
+ export type { SettingsEdit, UpdateResult } from './edit.js';
4
+ export { type LegacyProjectSource, type OpenSettingsOptions, openSettings, type SettingsHandle, } from './handle.js';
5
+ export { type LegacySource, type MapResult, type MoveOptions, type MoveOutcome, type MoveResult, type MoveSource, moveSettingsOnce, } from './move.js';
6
+ export { cortexkitConfigDir, isAbsoluteForPlatform, settingsFilePath, } from './paths.js';
7
+ export { SETTINGS_REFUSAL_CODES, SettingsRefusal, type SettingsRefusalCode, } from './refusal.js';
8
+ export type { GetOptions } from './resolve.js';
9
+ export { settingsJsonSchema } from './schema.js';
10
+ export type { ReportEntry, ReportReason } from './snapshot.js';
@@ -0,0 +1,7 @@
1
+ export { defineSettings, } from './define.js';
2
+ export { boolean, integer, list, number, object, oneOf, record, string, } from './descriptors.js';
3
+ export { openSettings, } from './handle.js';
4
+ export { moveSettingsOnce, } from './move.js';
5
+ export { cortexkitConfigDir, isAbsoluteForPlatform, settingsFilePath, } from './paths.js';
6
+ export { SETTINGS_REFUSAL_CODES, SettingsRefusal, } from './refusal.js';
7
+ export { settingsJsonSchema } from './schema.js';
@@ -0,0 +1,2 @@
1
+ /** Classify against the failing lock, not the settings destination it protects. */
2
+ export declare function rethrowSettingsLockError(error: unknown, target: string, name: string): never;
@@ -0,0 +1,15 @@
1
+ import { PrivateFileError } from '../fs/private-files.js';
2
+ import { isChangingLockRecord, LockContentionError } from '../fs/with-lock.js';
3
+ import { SettingsRefusal } from './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
+ }