@cortexkit/common-auth 0.44.0 → 0.46.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 (55) 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 +159 -11
  10. package/dist/fs/with-lock.d.ts +2 -0
  11. package/dist/fs/with-lock.js +1 -1
  12. package/dist/routing-accessor/index.d.ts +17 -0
  13. package/dist/routing-accessor/index.js +13 -0
  14. package/dist/settings/define.d.ts +35 -0
  15. package/dist/settings/define.js +52 -0
  16. package/dist/settings/descriptors.d.ts +97 -0
  17. package/dist/settings/descriptors.js +81 -0
  18. package/dist/settings/edit.d.ts +24 -0
  19. package/dist/settings/edit.js +229 -0
  20. package/dist/settings/fs.d.ts +6 -0
  21. package/dist/settings/fs.js +19 -0
  22. package/dist/settings/handle.d.ts +30 -0
  23. package/dist/settings/handle.js +228 -0
  24. package/dist/settings/index.d.ts +10 -0
  25. package/dist/settings/index.js +7 -0
  26. package/dist/settings/lock-errors.d.ts +2 -0
  27. package/dist/settings/lock-errors.js +15 -0
  28. package/dist/settings/move.d.ts +76 -0
  29. package/dist/settings/move.js +351 -0
  30. package/dist/settings/parse.d.ts +24 -0
  31. package/dist/settings/parse.js +65 -0
  32. package/dist/settings/paths.d.ts +12 -0
  33. package/dist/settings/paths.js +48 -0
  34. package/dist/settings/refusal.d.ts +7 -0
  35. package/dist/settings/refusal.js +15 -0
  36. package/dist/settings/resolve.d.ts +15 -0
  37. package/dist/settings/resolve.js +51 -0
  38. package/dist/settings/schema.d.ts +29 -0
  39. package/dist/settings/schema.js +81 -0
  40. package/dist/settings/snapshot.d.ts +24 -0
  41. package/dist/settings/snapshot.js +150 -0
  42. package/dist/settings/update.d.ts +6 -0
  43. package/dist/settings/update.js +139 -0
  44. package/dist/settings/write.d.ts +26 -0
  45. package/dist/settings/write.js +88 -0
  46. package/dist/setup/command-error.d.ts +1 -1
  47. package/dist/setup/command-error.js +3 -2
  48. package/dist/setup/command.js +5 -1
  49. package/dist/setup/enroll.js +3 -3
  50. package/dist/setup/enrollment-access.d.ts +1 -1
  51. package/dist/setup/enrollment-access.js +13 -4
  52. package/dist/setup/types.d.ts +4 -0
  53. package/dist/tui-prefs/watcher.d.ts +3 -1
  54. package/dist/tui-prefs/watcher.js +41 -18
  55. package/package.json +5 -1
@@ -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 {};
@@ -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>;