@keystrokehq/cli 0.0.21 → 0.0.23

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 (83) hide show
  1. package/dist/{accept.handler-C6KBLKmW.mjs → accept.handler-tvT9pleH.mjs} +1 -1
  2. package/dist/{admin-D2CQoZAN.mjs → admin-DsAQ0WWj.mjs} +9 -9
  3. package/dist/{agents-Bn0g5o0o.mjs → agents-Ccw0IZCx.mjs} +4 -4
  4. package/dist/{api-J9UL8pqZ.mjs → api-O5tdGdzc.mjs} +29 -3
  5. package/dist/{api-keys-BixCnZJW.mjs → api-keys-tle_m3kk.mjs} +5 -5
  6. package/dist/{auth-yCNMT8sJ.mjs → auth-DLaY5yCZ.mjs} +6 -11
  7. package/dist/{auth.handler-BedGpKh1.mjs → auth.handler-Dq2fXO3S.mjs} +16 -47
  8. package/dist/{build.handler-CyDc8jiZ.mjs → build.handler-ChqSwsT_.mjs} +3 -3
  9. package/dist/{clear-cache.handler-FmJPHdWG.mjs → clear-cache.handler-DpP1VlbR.mjs} +1 -1
  10. package/dist/{clear.handler-Cvb9chs4.mjs → clear.handler-FzohTmpU.mjs} +2 -6
  11. package/dist/{commander-9Kro0Dl3.mjs → commander-BTMzBiLq.mjs} +1 -1
  12. package/dist/{connect-DzVxjeYr.mjs → connect-BUu2ojK7.mjs} +26 -2
  13. package/dist/{connect.handler-DFQdxkWZ.mjs → connect.handler-D7oO_5WS.mjs} +38 -3
  14. package/dist/{context-B2cQ-Nt3.mjs → context-DHOTSgPb.mjs} +5 -10
  15. package/dist/{create.handler-v9B0Z9Yf.mjs → create.handler-BuxP18uj.mjs} +1 -1
  16. package/dist/{credential-env-map-Dvp00a4M.mjs → credential-env-map-CtmzNkwU.mjs} +1 -1
  17. package/dist/{credentials-Dr5lD7Hm.mjs → credentials-CELZ0QHu.mjs} +5 -5
  18. package/dist/{current-deployment-workflow-qMfOrRIu.mjs → current-deployment-workflow-CnzlDCBv.mjs} +2 -2
  19. package/dist/{current.handler-Cm_-JLyZ.mjs → current.handler-BXec-Bhy.mjs} +1 -1
  20. package/dist/{delete.handler-DtP_zUaq.mjs → delete.handler-CpYOMtsv.mjs} +1 -1
  21. package/dist/{deploy-CB6pfCuB.mjs → deploy-Cn3jN7Rl.mjs} +2 -2
  22. package/dist/{deploy.handler-Bg0dpSTj.mjs → deploy.handler-BikVS9ER.mjs} +7 -7
  23. package/dist/{diff.handler-CJPrszL1.mjs → diff.handler-C3EWVBOj.mjs} +3 -3
  24. package/dist/dist-D_KgdxW5.mjs +539 -0
  25. package/dist/{env.handler-6TrLd3fo.mjs → env.handler-BuFdzUoX.mjs} +4 -4
  26. package/dist/{init-DBMtY3eO.mjs → init-6tGGTpYO.mjs} +2 -2
  27. package/dist/{init.handler-BoYbE-6H.mjs → init.handler-Dcg9MOqx.mjs} +2 -2
  28. package/dist/{inspect.handler-Juu2vGbB.mjs → inspect.handler-BN6p2hI_.mjs} +3 -3
  29. package/dist/{integration-catalog-cYlTmOSb.mjs → integration-catalog-Cub_7xCw.mjs} +1 -1
  30. package/dist/{integrations-cwRfplNG.mjs → integrations-BRMzYHz1.mjs} +4 -4
  31. package/dist/{invites-DHyHZOY_.mjs → invites-RO4Dy-m6.mjs} +4 -4
  32. package/dist/{invites.list.handler-C-QpsG2J.mjs → invites.list.handler-B2RoiFCu.mjs} +1 -1
  33. package/dist/{invites.resend.handler-KFKbSPzR.mjs → invites.resend.handler-C4rzRkqX.mjs} +1 -1
  34. package/dist/{invites.revoke.handler-Cuz7jrGC.mjs → invites.revoke.handler-CMf6PpeL.mjs} +1 -1
  35. package/dist/keystroke.mjs +21 -21
  36. package/dist/{list.handler-DRe38pAj.mjs → list.handler-BjKZ9-QO.mjs} +2 -2
  37. package/dist/{list.handler-Cc-V1TNz.mjs → list.handler-DpdVFRYl.mjs} +1 -1
  38. package/dist/{list.handler-Do2tVOnu.mjs → list.handler-DrY5bgm1.mjs} +1 -1
  39. package/dist/{list.handler-CLGQDuo5.mjs → list.handler-cK8Y-daR.mjs} +3 -3
  40. package/dist/{list.handler-BWsl4iYw.mjs → list.handler-fcyAKTQe.mjs} +3 -3
  41. package/dist/{list.handler-6x3GVumu.mjs → list.handler-ijBH6Ow_.mjs} +1 -1
  42. package/dist/{list.handler-RtHhrTZ3.mjs → list.handler-wYGZhl1g.mjs} +1 -1
  43. package/dist/{listen-DZdSevsB.mjs → listen-CEn4PucV.mjs} +2 -2
  44. package/dist/{listen.handler-BccHe1jh.mjs → listen.handler-B7s6mz82.mjs} +1 -1
  45. package/dist/{logs-Bh_PBnu6.mjs → logs-DiH8JXn1.mjs} +1 -1
  46. package/dist/{logs.handler-DItDS1zw.mjs → logs.handler-D0sNlOz4.mjs} +1 -1
  47. package/dist/{members.add.handler-D3nQ_Ln6.mjs → members.add.handler-Dr9SCjrS.mjs} +1 -1
  48. package/dist/{members.invite.handler-rKhg5n_C.mjs → members.invite.handler-8-pTOtw_.mjs} +1 -1
  49. package/dist/{members.list.handler-C9Yh469k.mjs → members.list.handler-CUZGd-3B.mjs} +1 -1
  50. package/dist/{members.remove.handler-Dnrck-E6.mjs → members.remove.handler-BCiLt3pa.mjs} +1 -1
  51. package/dist/{members.update.handler-qo5r6arJ.mjs → members.update.handler-BAbB9ssa.mjs} +1 -1
  52. package/dist/{org-DnES84sS.mjs → org-BD4fj8Yh.mjs} +15 -15
  53. package/dist/{orgs.create.handler-DF4eEL-2.mjs → orgs.create.handler-B_7WjV3s.mjs} +1 -1
  54. package/dist/{orgs.get.handler-BmJnseQa.mjs → orgs.get.handler-BgjeDmfl.mjs} +1 -1
  55. package/dist/{orgs.list.handler-DDVvSbsT.mjs → orgs.list.handler-ZRdb-yu5.mjs} +1 -1
  56. package/dist/{paused.handler-BLUchSMD.mjs → paused.handler-CzQkBKS6.mjs} +1 -1
  57. package/dist/{projects-Cv14bBGy.mjs → projects-CgtfPFGu.mjs} +4 -4
  58. package/dist/{requirements.handler-BKFocUof.mjs → requirements.handler-ZZfHV6f0.mjs} +2 -2
  59. package/dist/{resolve-cli-credentials-DaMDaamj.mjs → resolve-cli-credentials-B4crOe_y.mjs} +5 -5
  60. package/dist/{resolve-project-Cj3MFnU0.mjs → resolve-project-DJJZIOmu.mjs} +1 -1
  61. package/dist/{run.handler-DZuUx0fi.mjs → run.handler-xeUVmlFk.mjs} +4 -4
  62. package/dist/{runs-BOo3j297.mjs → runs-CZRwB58H.mjs} +2 -2
  63. package/dist/{skills.command-B-MhRN3J.mjs → skills.command-DGIIIRX_.mjs} +1 -1
  64. package/dist/{status.handler-CW-EFhy3.mjs → status.handler-Ch_DtyBp.mjs} +4 -11
  65. package/dist/{switch.handler-BFGvj5c6.mjs → switch.handler-B3QBoSSl.mjs} +2 -2
  66. package/dist/{sync-CZ3iUPTA.mjs → sync-BlmgsC2W.mjs} +2 -2
  67. package/dist/{sync.handler-B1L8I9lF.mjs → sync.handler-xVxeG-S0.mjs} +4 -4
  68. package/dist/{task-target-build-CTgl4L42.mjs → task-target-build-CrPLSXnu.mjs} +1 -1
  69. package/dist/task-target-deploy-runner.mjs +4 -4
  70. package/dist/{test-Byq4hG3C.mjs → test-cuU0rf9C.mjs} +2 -2
  71. package/dist/{test.handler-BsrMMj5O.mjs → test.handler-B_C-T_IM.mjs} +4 -4
  72. package/dist/{test.handler-CAsVgOpT.mjs → test.handler-CLqnDqY6.mjs} +1 -1
  73. package/dist/{tool.handler-BHS5Z4J_.mjs → tool.handler-CmpzYYiC.mjs} +6 -6
  74. package/dist/{upgrade-bZVjVXnu.mjs → upgrade-B6Prb1K-.mjs} +1 -1
  75. package/dist/{upload.handler-DXVx2u3A.mjs → upload.handler-81mbKHTY.mjs} +4 -4
  76. package/dist/{users.get.handler-DqD2ELK2.mjs → users.get.handler-DoajzImx.mjs} +1 -1
  77. package/dist/{users.list.handler-DZSPvpGF.mjs → users.list.handler-CRk2J8mi.mjs} +1 -1
  78. package/dist/{users.set-role.handler-73smNUVF.mjs → users.set-role.handler-CHYjbx5M.mjs} +1 -1
  79. package/dist/{validate.handler-CmfcMX0t.mjs → validate.handler-CWG5HyO3.mjs} +3 -3
  80. package/dist/{workflow-build-Bi1Aacc5.mjs → workflow-build-CVG4DSCw.mjs} +1 -1
  81. package/dist/{workflows-C_C13Zr0.mjs → workflows-eztTnue4.mjs} +12 -12
  82. package/package.json +8 -8
  83. package/dist/dist-DuJjDZIf.mjs +0 -1094
@@ -1,1094 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { n as getKeystrokeBaseDir, t as KEYSTROKE_DIR } from "./paths-JzzFkXQA-CEipIeVl.mjs";
4
- import * as os from "node:os";
5
- import * as path$1 from "node:path";
6
- import * as fs from "node:fs/promises";
7
- import { z } from "zod";
8
- //#region ../../packages/local-memory/dist/index.mjs
9
- /**
10
- * Writes `data` to `filePath` atomically.
11
- *
12
- * The contents are first written to a sibling temp file in the same directory,
13
- * fsynced, chmodded, and then renamed onto the target path. On POSIX (and on
14
- * Windows when the source and destination are on the same volume), `fs.rename`
15
- * is atomic — readers see either the previous contents or the new contents,
16
- * never a partial write.
17
- *
18
- * The temp filename embeds the process PID and a high-resolution timestamp
19
- * (`${path}.tmp.${pid}.${ts}`) so concurrent writers do not collide.
20
- *
21
- * The parent directory is created with `recursive: true` if it does not already
22
- * exist, so callers do not need to mkdir beforehand.
23
- *
24
- * If anything fails after the temp file is created (write, fsync, rename), the
25
- * temp file is best-effort unlinked so we don't leak files.
26
- */
27
- async function atomicWriteFile(filePath, data, options = {}) {
28
- const mode = options.mode ?? 420;
29
- const dir = path$1.dirname(filePath);
30
- await fs.mkdir(dir, { recursive: true });
31
- const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 10)}`;
32
- let handleClosed = false;
33
- const handle = await fs.open(tmpPath, "w", mode);
34
- try {
35
- await handle.writeFile(data, "utf-8");
36
- await handle.sync();
37
- await handle.close();
38
- handleClosed = true;
39
- try {
40
- await fs.chmod(tmpPath, mode);
41
- } catch {}
42
- await fs.rename(tmpPath, filePath);
43
- } catch (error) {
44
- if (!handleClosed) try {
45
- await handle.close();
46
- } catch {}
47
- try {
48
- await fs.unlink(tmpPath);
49
- } catch {}
50
- throw error;
51
- }
52
- }
53
- /**
54
- * Removes `filePath`. Returns `true` if the file existed and was removed,
55
- * `false` if it did not exist (`ENOENT`). Other errors propagate.
56
- */
57
- async function unlinkFileIfExists(filePath) {
58
- try {
59
- await fs.unlink(filePath);
60
- return true;
61
- } catch (error) {
62
- if (error.code === "ENOENT") return false;
63
- throw error;
64
- }
65
- }
66
- /**
67
- * Reads a UTF-8 file and parses it as JSON.
68
- *
69
- * - Returns `null` when the file does not exist (`ENOENT`).
70
- * - Throws on any other read error.
71
- * - Throws (with the underlying `SyntaxError`) when the contents are not valid JSON.
72
- *
73
- * The return type is `unknown` — callers must validate the shape before using the
74
- * value (typically via a Zod schema).
75
- */
76
- async function readJsonFile(filePath) {
77
- let raw;
78
- try {
79
- raw = await fs.readFile(filePath, "utf-8");
80
- } catch (error) {
81
- if (error.code === "ENOENT") return null;
82
- throw error;
83
- }
84
- return JSON.parse(raw);
85
- }
86
- /**
87
- * Migrates `raw` to the current schema shape.
88
- *
89
- * Strategy:
90
- * 1. Try the current schema first. If it matches, return immediately.
91
- * 2. Otherwise find the migration whose `fromSchema` matches `raw`, run its
92
- * `up`, and re-enter the loop with the result.
93
- * 3. Continue until the current schema validates the value, or no migration
94
- * matches — in which case throw.
95
- *
96
- * This handles single-hop and chained migrations (V1 → V2 → V3 → ...) without
97
- * requiring the caller to order migrations carefully.
98
- *
99
- * Throws if the value matches no known schema. Callers typically wrap with a
100
- * descriptive error referencing the file path.
101
- */
102
- function migrateRead(raw, def) {
103
- const direct = def.schema.safeParse(raw);
104
- if (direct.success) return {
105
- value: direct.data,
106
- migrated: false
107
- };
108
- const migrations = def.migrations ?? [];
109
- if (migrations.length === 0) throw new Error("Stored value does not match the current schema and no migrations are configured.");
110
- let current = raw;
111
- const visited = /* @__PURE__ */ new Set();
112
- for (let hop = 0; hop <= migrations.length; hop++) {
113
- const match = def.schema.safeParse(current);
114
- if (match.success) return {
115
- value: match.data,
116
- migrated: hop > 0
117
- };
118
- const next = migrations.find((m) => !visited.has(m) && m.fromSchema.safeParse(current).success);
119
- if (!next) throw new Error("Stored value does not match the current schema or any known migration source.");
120
- visited.add(next);
121
- const validated = next.fromSchema.parse(current);
122
- current = next.up(validated);
123
- }
124
- throw new Error(`Migration chain did not converge after ${migrations.length} hops. Possible cycle in migrations.`);
125
- }
126
- const KEYRING_PACKAGE = ["@napi-rs", "keyring"].join("/");
127
- async function createDefaultEntry(service, account) {
128
- const { Entry } = await import(KEYRING_PACKAGE);
129
- return new Entry(service, account);
130
- }
131
- var KeychainVault = class {
132
- kind = "keychain";
133
- service;
134
- createEntry;
135
- constructor(options) {
136
- this.service = options.service;
137
- this.createEntry = options.createEntry ?? createDefaultEntry;
138
- }
139
- async get(account) {
140
- return (await this.createEntry(this.service, account)).getPassword();
141
- }
142
- async set(account, secret) {
143
- const entry = await this.createEntry(this.service, account);
144
- try {
145
- entry.setPassword(secret);
146
- return;
147
- } catch (error) {
148
- try {
149
- await this.verifyWritableKeychain(account);
150
- entry.deleteCredential();
151
- (await this.createEntry(this.service, account)).setPassword(secret);
152
- } catch (replacementError) {
153
- throw new AggregateError([error, replacementError], "Could not replace the existing keychain credential.");
154
- }
155
- }
156
- }
157
- async verifyWritableKeychain(account) {
158
- const probeAccount = `${account}:replacement-probe:${process.pid}:${Date.now()}`;
159
- const probeEntry = await this.createEntry(this.service, probeAccount);
160
- try {
161
- probeEntry.setPassword("probe");
162
- } finally {
163
- try {
164
- probeEntry.deleteCredential();
165
- } catch {}
166
- }
167
- }
168
- async delete(account) {
169
- return (await this.createEntry(this.service, account)).deleteCredential();
170
- }
171
- };
172
- const FORBIDDEN_NAME_PATTERNS = [
173
- {
174
- test: (n) => n.length === 0,
175
- message: "must not be empty"
176
- },
177
- {
178
- test: (n) => n.includes("\\"),
179
- message: "must not contain backslashes"
180
- },
181
- {
182
- test: (n) => n.split("/").some((seg) => seg === ".."),
183
- message: "must not contain \"..\" segments"
184
- },
185
- {
186
- test: (n) => n.startsWith("/"),
187
- message: "must be relative (cannot start with \"/\")"
188
- }
189
- ];
190
- function validateStoreName(name) {
191
- for (const { test, message } of FORBIDDEN_NAME_PATTERNS) if (test(name)) throw new Error(`Invalid Store name ${JSON.stringify(name)}: ${message}.`);
192
- }
193
- /**
194
- * Typed, schema-validated, atomically-written abstraction over a single JSON
195
- * file under `~/.keystroke/`.
196
- *
197
- * `Store` is an internal primitive of `@keystroke/local-memory`. It is not
198
- * exported from the package's public API — domain controllers (`Credentials`,
199
- * `Projects`, etc.) construct stores internally and expose domain-shaped methods
200
- * to consumers.
201
- */
202
- var Store = class {
203
- /** Absolute path to the file this store manages. */
204
- filePath;
205
- options;
206
- constructor(options) {
207
- validateStoreName(options.name);
208
- this.options = options;
209
- const homeDir = options.homeDir ?? os.homedir();
210
- this.filePath = path$1.join(getKeystrokeBaseDir(homeDir), ...options.name.split("/"));
211
- }
212
- /**
213
- * Returns the parsed contents of the file, or `null` when the file does not
214
- * exist. If the on-disk shape does not match the current schema, registered
215
- * migrations are applied and the upgraded value is persisted back.
216
- *
217
- * Throws when the file exists but matches no known schema, or when the file
218
- * is unreadable for reasons other than ENOENT.
219
- */
220
- async read() {
221
- const raw = await readJsonFile(this.filePath);
222
- if (raw === null) return null;
223
- let result;
224
- try {
225
- result = migrateRead(raw, {
226
- schema: this.options.schema,
227
- migrations: this.options.migrations
228
- });
229
- } catch (error) {
230
- const message = error instanceof Error ? error.message : String(error);
231
- throw new Error(`Invalid file at ${this.filePath}: ${message}`);
232
- }
233
- if (result.migrated) await this.write(result.value);
234
- return result.value;
235
- }
236
- /**
237
- * Replaces the file with `value`. Validates against the schema first (throws
238
- * synchronously on invalid input, before any I/O). The write is atomic:
239
- * write-temp + rename, never visible mid-write.
240
- */
241
- async write(value) {
242
- const validated = this.options.schema.parse(value);
243
- const json = `${JSON.stringify(validated, null, 2)}\n`;
244
- await atomicWriteFile(this.filePath, json, { mode: this.options.fileMode });
245
- }
246
- /**
247
- * Read-modify-write. Reads the current value (or `defaults` if the file does
248
- * not exist), passes it to `fn`, validates the result, and writes it back
249
- * atomically. Returns the new value.
250
- *
251
- * Throws if the file does not exist and no `defaults` were configured.
252
- */
253
- async update(fn) {
254
- const current = await this.read();
255
- let base;
256
- if (current !== null) base = current;
257
- else if (this.options.defaults !== void 0) base = this.options.defaults;
258
- else throw new Error(`Cannot update ${this.filePath}: file does not exist and no defaults are configured.`);
259
- const next = fn(base);
260
- await this.write(next);
261
- return next;
262
- }
263
- /**
264
- * Returns the value at `key`, or `undefined` if the file does not exist.
265
- * Each call re-reads the file (no caching).
266
- */
267
- async get(key) {
268
- const value = await this.read();
269
- if (value === null) return void 0;
270
- return value[key];
271
- }
272
- /**
273
- * Sets the value at `key`. Other keys are preserved. Uses `defaults` if the
274
- * file does not exist (throws if missing and no defaults).
275
- */
276
- async set(key, value) {
277
- await this.update((current) => ({
278
- ...current,
279
- [key]: value
280
- }));
281
- }
282
- /**
283
- * Returns true if the file exists and the value at `key` is not `undefined`.
284
- */
285
- async has(key) {
286
- return await this.get(key) !== void 0;
287
- }
288
- /**
289
- * Removes the file. Returns `true` if the file existed, `false` if it did
290
- * not.
291
- */
292
- async delete() {
293
- return unlinkFileIfExists(this.filePath);
294
- }
295
- };
296
- const CREDENTIAL_SECRET_STORAGE_UNAVAILABLE = "CREDENTIAL_SECRET_STORAGE_UNAVAILABLE";
297
- const CREDENTIAL_SECRET_READ_FAILED = "CREDENTIAL_SECRET_READ_FAILED";
298
- const CREDENTIAL_SECRET_WRITE_FAILED = "CREDENTIAL_SECRET_WRITE_FAILED";
299
- const CREDENTIAL_SECRET_DELETE_FAILED = "CREDENTIAL_SECRET_DELETE_FAILED";
300
- var CredentialSecretError = class extends Error {
301
- constructor(message, options) {
302
- super(message, options);
303
- this.name = new.target.name;
304
- }
305
- };
306
- var CredentialSecretStorageUnavailableError = class extends CredentialSecretError {
307
- code = CREDENTIAL_SECRET_STORAGE_UNAVAILABLE;
308
- };
309
- var CredentialSecretReadError = class extends CredentialSecretError {
310
- code = CREDENTIAL_SECRET_READ_FAILED;
311
- };
312
- var CredentialSecretWriteError = class extends CredentialSecretError {
313
- code = CREDENTIAL_SECRET_WRITE_FAILED;
314
- };
315
- var CredentialSecretDeleteError = class extends CredentialSecretError {
316
- code = CREDENTIAL_SECRET_DELETE_FAILED;
317
- };
318
- const credentialUserSchema = z.object({
319
- id: z.string().min(1),
320
- email: z.email(),
321
- name: z.string().optional()
322
- });
323
- /**
324
- * Metadata about an organization the user is authenticated against.
325
- * Note: `apiKey` is NOT in this shape — it lives in the secrets file.
326
- *
327
- * Strict on purpose: extra fields (like the legacy `apiKey`) cause the schema
328
- * to fail, which routes the read through the migration chain rather than
329
- * silently stripping the unknown field at parse time.
330
- */
331
- const orgEntrySchema = z.object({
332
- organizationId: z.uuid(),
333
- organizationName: z.string().min(1),
334
- apiKeyId: z.uuid().optional(),
335
- createdAt: z.string().min(1)
336
- }).strict();
337
- const credentialSecretStorageSchema = z.discriminatedUnion("kind", [z.object({
338
- kind: z.literal("keychain"),
339
- service: z.string().min(1)
340
- }).strict(), z.object({
341
- kind: z.literal("file"),
342
- reason: z.enum([
343
- "legacy",
344
- "insecure-storage",
345
- "test"
346
- ]).optional()
347
- }).strict()]);
348
- const credentialsMetadataSchema = z.object({
349
- version: z.literal(3),
350
- serverUrl: z.url(),
351
- webUrl: z.url(),
352
- user: credentialUserSchema.optional(),
353
- activeOrgId: z.uuid().optional(),
354
- orgs: z.array(orgEntrySchema),
355
- secretStorage: credentialSecretStorageSchema
356
- }).strict();
357
- const orgSecretsSchema = z.object({
358
- version: z.literal(1),
359
- /** Map of organizationId → API key. Empty when no orgs configured. */
360
- byOrgId: z.record(z.uuid(), z.string().min(1))
361
- });
362
- const credentialsMetadataSchemaV2 = z.object({
363
- version: z.literal(2),
364
- serverUrl: z.url(),
365
- webUrl: z.url(),
366
- user: credentialUserSchema.optional(),
367
- activeOrgId: z.uuid().optional(),
368
- orgs: z.array(orgEntrySchema)
369
- }).strict();
370
- /**
371
- * Old V2 shape: same as current metadata, but each org carried its own
372
- * `apiKey` field. Migration: strip `apiKey` from each org. The actual key
373
- * bytes are recovered separately by the controller's legacy import step.
374
- *
375
- * `oldV2OrgEntrySchema` extends the current strict org schema with a required
376
- * `apiKey`. Strict so a V2-new entry (no apiKey) does NOT match this schema.
377
- */
378
- const oldV2OrgEntrySchema = orgEntrySchema.extend({ apiKey: z.string().min(1) }).strict();
379
- const credentialsSchemaV2OldShape = z.object({
380
- version: z.literal(2),
381
- serverUrl: z.url(),
382
- webUrl: z.url(),
383
- user: credentialUserSchema.optional(),
384
- activeOrgId: z.uuid().optional(),
385
- orgs: z.array(oldV2OrgEntrySchema)
386
- }).strict();
387
- /**
388
- * V1 shape: a single embedded apiKey + organization. Migration: collapse to a
389
- * one-org metadata record. The apiKey bytes are recovered separately.
390
- */
391
- const credentialsSchemaV1 = z.object({
392
- version: z.literal(1),
393
- apiKey: z.string().min(1),
394
- apiKeyId: z.uuid().optional(),
395
- serverUrl: z.url(),
396
- webUrl: z.url(),
397
- createdAt: z.string().min(1),
398
- organizationId: z.uuid().optional(),
399
- organizationName: z.string().optional(),
400
- user: credentialUserSchema.optional()
401
- });
402
- const SECRETS_FILE = "secrets.json";
403
- const SECRETS_VERSION = 1;
404
- const SECRETS_DEFAULTS = {
405
- version: SECRETS_VERSION,
406
- byOrgId: {}
407
- };
408
- const CREDENTIAL_KEYCHAIN_SERVICE = "io.keystroke.cli";
409
- var CredentialSecrets = class {
410
- legacySecrets;
411
- vault;
412
- constructor(options = {}) {
413
- this.vault = options.vault;
414
- this.legacySecrets = new Store({
415
- name: SECRETS_FILE,
416
- version: SECRETS_VERSION,
417
- schema: orgSecretsSchema,
418
- defaults: SECRETS_DEFAULTS,
419
- fileMode: 384,
420
- homeDir: options.homeDir
421
- });
422
- }
423
- get legacySecretsFilePath() {
424
- return this.legacySecrets.filePath;
425
- }
426
- async getApiKey(ref, storageKind) {
427
- if (storageKind === "file") return (await this.legacySecrets.read())?.byOrgId[ref.orgId] ?? null;
428
- const vault = this.requireVault();
429
- try {
430
- return await vault.get(getCredentialSecretAccountName(ref));
431
- } catch (error) {
432
- throw new CredentialSecretReadError("Could not read the Keystroke API key from the credential store.", { cause: error });
433
- }
434
- }
435
- async setApiKey(ref, apiKey, storageKind) {
436
- if (storageKind === "file") {
437
- await this.legacySecrets.update((secrets) => ({
438
- ...secrets,
439
- byOrgId: {
440
- ...secrets.byOrgId,
441
- [ref.orgId]: apiKey
442
- }
443
- }));
444
- return;
445
- }
446
- const vault = this.requireVault();
447
- try {
448
- await vault.set(getCredentialSecretAccountName(ref), apiKey);
449
- } catch (error) {
450
- throw new CredentialSecretWriteError("Could not save the Keystroke API key to the credential store.", { cause: error });
451
- }
452
- }
453
- async deleteApiKey(ref, storageKind) {
454
- if (storageKind === "file") {
455
- const current = await this.legacySecrets.read();
456
- if (!current || current.byOrgId[ref.orgId] === void 0) return false;
457
- await this.legacySecrets.update((secrets) => {
458
- const { [ref.orgId]: _removed, ...rest } = secrets.byOrgId;
459
- return {
460
- ...secrets,
461
- byOrgId: rest
462
- };
463
- });
464
- return true;
465
- }
466
- const vault = this.requireVault();
467
- try {
468
- return await vault.delete(getCredentialSecretAccountName(ref));
469
- } catch (error) {
470
- throw new CredentialSecretDeleteError("Could not delete the Keystroke API key from the credential store.", { cause: error });
471
- }
472
- }
473
- async clearLegacySecrets() {
474
- return this.legacySecrets.delete();
475
- }
476
- async writeLegacySecrets(secrets) {
477
- await this.legacySecrets.write(secrets);
478
- }
479
- async readLegacySecrets() {
480
- return this.legacySecrets.read();
481
- }
482
- requireVault() {
483
- if (!this.vault) throw new CredentialSecretStorageUnavailableError("Credential store is not configured for secure secret storage.");
484
- return this.vault;
485
- }
486
- };
487
- function getCredentialSecretAccountName(ref) {
488
- return `api-key:${normalizeCredentialServerUrl(ref.serverUrl)}:${ref.orgId}`;
489
- }
490
- function normalizeCredentialServerUrl(rawUrl) {
491
- const parsed = new URL(rawUrl);
492
- parsed.protocol = parsed.protocol.toLowerCase();
493
- parsed.hostname = parsed.hostname.toLowerCase();
494
- const normalized = parsed.toString();
495
- return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
496
- }
497
- const CREDENTIALS_FILE = "credentials.json";
498
- const METADATA_VERSION = 3;
499
- const KEYCHAIN_STORAGE = {
500
- kind: "keychain",
501
- service: CREDENTIAL_KEYCHAIN_SERVICE
502
- };
503
- const TEST_FILE_STORAGE = {
504
- kind: "file",
505
- reason: "test"
506
- };
507
- const LEGACY_FILE_STORAGE = {
508
- kind: "file",
509
- reason: "legacy"
510
- };
511
- const INSECURE_FILE_STORAGE = {
512
- kind: "file",
513
- reason: "insecure-storage"
514
- };
515
- function createKeychainVault() {
516
- return new KeychainVault({ service: CREDENTIAL_KEYCHAIN_SERVICE });
517
- }
518
- function resolveDefaultSecretStorage(options) {
519
- if (options.secretStorage === "file") return TEST_FILE_STORAGE;
520
- if (options.secretStorage === "keychain") return KEYCHAIN_STORAGE;
521
- if (options.vault) return KEYCHAIN_STORAGE;
522
- return options.homeDir ? TEST_FILE_STORAGE : KEYCHAIN_STORAGE;
523
- }
524
- function toSecretStorage(preference, fallback) {
525
- if (preference === "file") return INSECURE_FILE_STORAGE;
526
- if (preference === "keychain") return KEYCHAIN_STORAGE;
527
- return fallback;
528
- }
529
- /**
530
- * Domain controller for Keystroke credentials.
531
- *
532
- * Currently backed by two files under `~/.keystroke/`:
533
- * - `credentials.json` — metadata (org list, server URLs, active org pointer)
534
- * - `secrets.json` — `{ version, byOrgId: { [orgId]: apiKey } }`
535
- *
536
- * Secret reads and writes go through `CredentialSecrets`, keeping the storage
537
- * mechanism behind this controller as PR 9 moves API keys to the OS keychain.
538
- *
539
- * Production code uses the `credentials` singleton exported below. Tests
540
- * construct a fresh instance with `homeDir` pointing at a tempdir.
541
- */
542
- var Credentials = class {
543
- metadata;
544
- secrets;
545
- defaultSecretStorage;
546
- legacyImportComplete = false;
547
- constructor(options = {}) {
548
- const defaultSecretStorage = resolveDefaultSecretStorage(options);
549
- this.defaultSecretStorage = defaultSecretStorage;
550
- this.metadata = new Store({
551
- name: CREDENTIALS_FILE,
552
- version: METADATA_VERSION,
553
- schema: credentialsMetadataSchema,
554
- fileMode: 384,
555
- homeDir: options.homeDir,
556
- migrations: [
557
- {
558
- fromVersion: 2,
559
- fromSchema: credentialsMetadataSchemaV2,
560
- up: (raw) => {
561
- const v2 = raw;
562
- return {
563
- version: METADATA_VERSION,
564
- serverUrl: v2.serverUrl,
565
- webUrl: v2.webUrl,
566
- user: v2.user,
567
- activeOrgId: v2.activeOrgId,
568
- orgs: v2.orgs,
569
- secretStorage: LEGACY_FILE_STORAGE
570
- };
571
- }
572
- },
573
- {
574
- fromVersion: 2,
575
- fromSchema: credentialsSchemaV2OldShape,
576
- up: (raw) => {
577
- const old = raw;
578
- return {
579
- version: METADATA_VERSION,
580
- serverUrl: old.serverUrl,
581
- webUrl: old.webUrl,
582
- user: old.user,
583
- activeOrgId: old.activeOrgId,
584
- orgs: old.orgs.map(({ apiKey: _apiKey, ...rest }) => rest),
585
- secretStorage: LEGACY_FILE_STORAGE
586
- };
587
- }
588
- },
589
- {
590
- fromVersion: 1,
591
- fromSchema: credentialsSchemaV1,
592
- up: (raw) => {
593
- const v1 = raw;
594
- return {
595
- version: METADATA_VERSION,
596
- serverUrl: v1.serverUrl,
597
- webUrl: v1.webUrl,
598
- user: v1.user,
599
- activeOrgId: v1.organizationId,
600
- orgs: v1.organizationId ? [{
601
- organizationId: v1.organizationId,
602
- organizationName: v1.organizationName ?? "Unknown",
603
- apiKeyId: v1.apiKeyId,
604
- createdAt: v1.createdAt
605
- }] : [],
606
- secretStorage: LEGACY_FILE_STORAGE
607
- };
608
- }
609
- }
610
- ]
611
- });
612
- this.secrets = new CredentialSecrets({
613
- homeDir: options.homeDir,
614
- vault: options.vault ?? (defaultSecretStorage.kind === "keychain" ? createKeychainVault() : void 0)
615
- });
616
- }
617
- /** Absolute path to the credentials metadata file. */
618
- get metadataFilePath() {
619
- return this.metadata.filePath;
620
- }
621
- /** Absolute path to the secrets file. */
622
- get secretsFilePath() {
623
- return this.secrets.legacySecretsFilePath;
624
- }
625
- /**
626
- * Returns the active org and its API key, or `null` when there are no
627
- * stored credentials, no active org, or no key found for the active org.
628
- */
629
- async getActiveOrg() {
630
- await this.importLegacyIfNeeded();
631
- const meta = await this.metadata.read();
632
- if (!meta?.activeOrgId) return null;
633
- const org = meta.orgs.find((o) => o.organizationId === meta.activeOrgId);
634
- if (!org) return null;
635
- const apiKey = await this.secrets.getApiKey({
636
- orgId: meta.activeOrgId,
637
- serverUrl: meta.serverUrl
638
- }, meta.secretStorage.kind);
639
- if (!apiKey) return null;
640
- return {
641
- org,
642
- apiKey
643
- };
644
- }
645
- /** All known orgs (without secrets). Empty when no credentials stored. */
646
- async listOrgs() {
647
- await this.importLegacyIfNeeded();
648
- return (await this.metadata.read())?.orgs ?? [];
649
- }
650
- /** API key for a specific org, or `null` if not stored. */
651
- async getApiKey(orgId) {
652
- await this.importLegacyIfNeeded();
653
- const meta = await this.metadata.read();
654
- if (!meta) return null;
655
- return this.secrets.getApiKey({
656
- orgId,
657
- serverUrl: meta.serverUrl
658
- }, meta.secretStorage.kind);
659
- }
660
- /** Server URLs (shared across all orgs in the file). `null` when unset. */
661
- async getServerUrls() {
662
- await this.importLegacyIfNeeded();
663
- const meta = await this.metadata.read();
664
- return meta ? {
665
- serverUrl: meta.serverUrl,
666
- webUrl: meta.webUrl
667
- } : null;
668
- }
669
- /** The user identity associated with stored credentials, if any. */
670
- async getUser() {
671
- await this.importLegacyIfNeeded();
672
- return (await this.metadata.read())?.user;
673
- }
674
- /** Active organization ID, or `undefined` when none is set. */
675
- async getActiveOrgId() {
676
- await this.importLegacyIfNeeded();
677
- return (await this.metadata.read())?.activeOrgId;
678
- }
679
- /**
680
- * Returns `true` when credential metadata contains at least one org. Callers
681
- * that need the actual API key should use `getActiveOrg()` or `getApiKey()`.
682
- */
683
- async hasStoredCredentials() {
684
- await this.importLegacyIfNeeded();
685
- const meta = await this.metadata.read();
686
- return meta !== null && meta.orgs.length > 0;
687
- }
688
- async getStorageInfo() {
689
- await this.importLegacyIfNeeded();
690
- const storage = (await this.metadata.read())?.secretStorage ?? this.defaultSecretStorage;
691
- return {
692
- metadataFilePath: this.metadata.filePath,
693
- legacySecretsFilePath: this.secrets.legacySecretsFilePath,
694
- secretStorageKind: storage.kind,
695
- ...storage.kind === "keychain" ? { keychainService: storage.service } : {},
696
- insecureFileStorage: storage.kind === "file"
697
- };
698
- }
699
- /**
700
- * Adds or replaces an org entry. Sets it as the active org. Creates both
701
- * files if neither exists. Atomic per-file (each file is a Store write).
702
- */
703
- async upsertOrg(input) {
704
- await this.importLegacyIfNeeded();
705
- const existing = await this.metadata.read();
706
- const secretStorage = toSecretStorage(input.secretStorage, this.defaultSecretStorage);
707
- if (existing?.secretStorage.kind === "file" && secretStorage.kind === "keychain") await this.migrateFileSecretsToKeychain(existing);
708
- const newMeta = existing ? {
709
- ...existing,
710
- serverUrl: input.serverUrl,
711
- webUrl: input.webUrl,
712
- user: input.user ?? existing.user,
713
- activeOrgId: input.org.organizationId,
714
- secretStorage,
715
- orgs: [...existing.orgs.filter((o) => o.organizationId !== input.org.organizationId), input.org]
716
- } : {
717
- version: METADATA_VERSION,
718
- serverUrl: input.serverUrl,
719
- webUrl: input.webUrl,
720
- user: input.user,
721
- activeOrgId: input.org.organizationId,
722
- secretStorage,
723
- orgs: [input.org]
724
- };
725
- await this.secrets.setApiKey({
726
- orgId: input.org.organizationId,
727
- serverUrl: input.serverUrl
728
- }, input.apiKey, secretStorage.kind);
729
- await this.metadata.write(newMeta);
730
- if (existing) {
731
- const previousOrg = existing.orgs.find((org) => org.organizationId === input.org.organizationId);
732
- const serverUrlChanged = normalizeCredentialServerUrl(existing.serverUrl) !== normalizeCredentialServerUrl(input.serverUrl);
733
- if (previousOrg && serverUrlChanged && (existing.secretStorage.kind === "keychain" || secretStorage.kind === "keychain")) await this.secrets.deleteApiKey({
734
- orgId: input.org.organizationId,
735
- serverUrl: existing.serverUrl
736
- }, "keychain");
737
- }
738
- }
739
- /**
740
- * Switches the active org. Throws when no credentials exist or the org is
741
- * not in the stored orgs array.
742
- */
743
- async setActiveOrg(orgId) {
744
- await this.importLegacyIfNeeded();
745
- const meta = await this.metadata.read();
746
- if (!meta) throw new Error("No stored credentials found. Run `keystroke auth` first.");
747
- if (!meta.orgs.some((o) => o.organizationId === orgId)) throw new Error(`No stored API key for organization ${orgId}. Run \`keystroke auth\` to add credentials for this org.`);
748
- await this.metadata.update((m) => ({
749
- ...m,
750
- activeOrgId: orgId
751
- }));
752
- }
753
- /**
754
- * Removes a single org. If it was the active org, switches to the first
755
- * remaining org. When the last org is removed, both files are deleted.
756
- * Returns the removed org, or `null` if not stored.
757
- */
758
- async removeOrg(orgId) {
759
- await this.importLegacyIfNeeded();
760
- const meta = await this.metadata.read();
761
- if (!meta) return null;
762
- const removed = meta.orgs.find((o) => o.organizationId === orgId);
763
- if (!removed) return null;
764
- const remaining = meta.orgs.filter((o) => o.organizationId !== orgId);
765
- await this.secrets.deleteApiKey({
766
- orgId,
767
- serverUrl: meta.serverUrl
768
- }, meta.secretStorage.kind);
769
- if (remaining.length === 0) {
770
- if (meta.secretStorage.kind === "file") await this.secrets.clearLegacySecrets();
771
- await this.metadata.delete();
772
- return removed;
773
- }
774
- const newActiveId = meta.activeOrgId === orgId ? remaining[0]?.organizationId : meta.activeOrgId;
775
- await this.metadata.write({
776
- ...meta,
777
- orgs: remaining,
778
- activeOrgId: newActiveId
779
- });
780
- return removed;
781
- }
782
- /** Wipes both files. After this, `getActiveOrg` returns `null`. */
783
- async clear() {
784
- await this.importLegacyIfNeeded();
785
- const meta = await this.metadata.read();
786
- if (meta) for (const org of meta.orgs) await this.secrets.deleteApiKey({
787
- orgId: org.organizationId,
788
- serverUrl: meta.serverUrl
789
- }, meta.secretStorage.kind);
790
- await this.secrets.clearLegacySecrets();
791
- await this.metadata.delete();
792
- this.legacyImportComplete = false;
793
- }
794
- /**
795
- * Detects pre-split shapes on disk (V1, or V2-old with embedded apiKeys) and
796
- * writes the secrets file out before the Store-level migration strips the
797
- * apiKeys from metadata. Idempotent: caches a per-instance flag so repeated
798
- * calls after the first cost only the flag check.
799
- *
800
- * Implementation note: this runs BEFORE every `metadata.read()` in the
801
- * controller's API methods. The first call detects-and-imports; subsequent
802
- * calls are no-ops. Once import is done (or skipped because the file already
803
- * matches the new shape), `metadata.read()` runs the V2-old/V1 migration
804
- * which is purely a metadata reshape.
805
- */
806
- async importLegacyIfNeeded() {
807
- if (this.legacyImportComplete) return;
808
- this.legacyImportComplete = true;
809
- let raw;
810
- try {
811
- raw = await readJsonFile(this.metadata.filePath);
812
- } catch {
813
- return;
814
- }
815
- if (raw === null) return;
816
- const v2Old = credentialsSchemaV2OldShape.safeParse(raw);
817
- if (v2Old.success) {
818
- const byOrgId = {};
819
- for (const org of v2Old.data.orgs) byOrgId[org.organizationId] = org.apiKey;
820
- const secretStorage = await this.importLegacySecrets({
821
- metadata: {
822
- version: METADATA_VERSION,
823
- serverUrl: v2Old.data.serverUrl,
824
- webUrl: v2Old.data.webUrl,
825
- user: v2Old.data.user,
826
- activeOrgId: v2Old.data.activeOrgId,
827
- orgs: v2Old.data.orgs.map(({ apiKey: _apiKey, ...rest }) => rest),
828
- secretStorage: this.defaultSecretStorage
829
- },
830
- byOrgId
831
- });
832
- await this.metadata.write({
833
- version: METADATA_VERSION,
834
- serverUrl: v2Old.data.serverUrl,
835
- webUrl: v2Old.data.webUrl,
836
- user: v2Old.data.user,
837
- activeOrgId: v2Old.data.activeOrgId,
838
- orgs: v2Old.data.orgs.map(({ apiKey: _apiKey, ...rest }) => rest),
839
- secretStorage
840
- });
841
- return;
842
- }
843
- const v2 = credentialsMetadataSchemaV2.safeParse(raw);
844
- if (v2.success) {
845
- const legacySecrets = await this.secrets.readLegacySecrets();
846
- const secretStorage = await this.importLegacySecrets({
847
- metadata: {
848
- version: METADATA_VERSION,
849
- serverUrl: v2.data.serverUrl,
850
- webUrl: v2.data.webUrl,
851
- user: v2.data.user,
852
- activeOrgId: v2.data.activeOrgId,
853
- orgs: v2.data.orgs,
854
- secretStorage: this.defaultSecretStorage
855
- },
856
- byOrgId: legacySecrets?.byOrgId ?? {}
857
- });
858
- await this.metadata.write({
859
- version: METADATA_VERSION,
860
- serverUrl: v2.data.serverUrl,
861
- webUrl: v2.data.webUrl,
862
- user: v2.data.user,
863
- activeOrgId: v2.data.activeOrgId,
864
- orgs: v2.data.orgs,
865
- secretStorage
866
- });
867
- return;
868
- }
869
- const v1 = credentialsSchemaV1.safeParse(raw);
870
- if (v1.success && v1.data.organizationId && v1.data.apiKey) {
871
- const orgs = [{
872
- organizationId: v1.data.organizationId,
873
- organizationName: v1.data.organizationName ?? "Unknown",
874
- apiKeyId: v1.data.apiKeyId,
875
- createdAt: v1.data.createdAt
876
- }];
877
- const secretStorage = await this.importLegacySecrets({
878
- metadata: {
879
- version: METADATA_VERSION,
880
- serverUrl: v1.data.serverUrl,
881
- webUrl: v1.data.webUrl,
882
- user: v1.data.user,
883
- activeOrgId: v1.data.organizationId,
884
- orgs,
885
- secretStorage: this.defaultSecretStorage
886
- },
887
- byOrgId: { [v1.data.organizationId]: v1.data.apiKey }
888
- });
889
- await this.metadata.write({
890
- version: METADATA_VERSION,
891
- serverUrl: v1.data.serverUrl,
892
- webUrl: v1.data.webUrl,
893
- user: v1.data.user,
894
- activeOrgId: v1.data.organizationId,
895
- orgs,
896
- secretStorage
897
- });
898
- }
899
- }
900
- async importLegacySecrets(input) {
901
- if (this.defaultSecretStorage.kind === "file") {
902
- await this.secrets.writeLegacySecrets({
903
- version: 1,
904
- byOrgId: input.byOrgId
905
- });
906
- return this.defaultSecretStorage;
907
- }
908
- try {
909
- await this.writeSecretsToStorage(input.metadata, input.byOrgId, "keychain");
910
- await this.secrets.clearLegacySecrets();
911
- return KEYCHAIN_STORAGE;
912
- } catch {
913
- await this.secrets.writeLegacySecrets({
914
- version: 1,
915
- byOrgId: input.byOrgId
916
- });
917
- return LEGACY_FILE_STORAGE;
918
- }
919
- }
920
- async migrateFileSecretsToKeychain(metadata) {
921
- const legacySecrets = await this.secrets.readLegacySecrets();
922
- if (!legacySecrets) return;
923
- await this.writeSecretsToStorage(metadata, legacySecrets.byOrgId, "keychain");
924
- await this.secrets.clearLegacySecrets();
925
- }
926
- async writeSecretsToStorage(metadata, byOrgId, storageKind) {
927
- for (const org of metadata.orgs) {
928
- const apiKey = byOrgId[org.organizationId];
929
- if (!apiKey) continue;
930
- const ref = {
931
- orgId: org.organizationId,
932
- serverUrl: metadata.serverUrl
933
- };
934
- await this.secrets.setApiKey(ref, apiKey, storageKind);
935
- if (await this.secrets.getApiKey(ref, storageKind) !== apiKey) throw new Error(`Could not verify stored API key for organization ${org.organizationId}.`);
936
- }
937
- }
938
- };
939
- /**
940
- * Production singleton — the primary public API for credential storage. Tests
941
- * should construct `new Credentials({ homeDir })` instead.
942
- */
943
- const credentials = new Credentials();
944
- const projectEntrySchema = z.object({
945
- lastAccessed: z.string().min(1),
946
- name: z.string().min(1).optional()
947
- });
948
- const projectsSchema = z.object({
949
- version: z.literal(1),
950
- projects: z.record(z.string(), projectEntrySchema),
951
- lastProject: z.string().optional()
952
- });
953
- const PROJECTS_FILE = "projects.json";
954
- const PROJECTS_VERSION = 1;
955
- const PROJECTS_DEFAULTS = {
956
- version: PROJECTS_VERSION,
957
- projects: {}
958
- };
959
- /**
960
- * Domain controller for tracked Keystroke projects.
961
- *
962
- * Backed by a single file under `~/.keystroke/projects.json`.
963
- *
964
- * Production code uses the `projects` singleton exported below. Tests
965
- * construct a fresh instance with `homeDir` pointing at a tempdir.
966
- */
967
- var Projects = class {
968
- store;
969
- constructor(options = {}) {
970
- this.store = new Store({
971
- name: PROJECTS_FILE,
972
- version: PROJECTS_VERSION,
973
- schema: projectsSchema,
974
- defaults: PROJECTS_DEFAULTS,
975
- homeDir: options.homeDir
976
- });
977
- }
978
- /** Absolute path to the projects file. */
979
- get filePath() {
980
- return this.store.filePath;
981
- }
982
- /**
983
- * Upsert a project entry. Fire-and-forget safe — catches all errors
984
- * internally. Never throws. Call without `await` if you don't need to wait.
985
- *
986
- * Tracking is best-effort telemetry; we never want a failed write to bubble
987
- * up to a CLI command and degrade UX.
988
- */
989
- async track(projectPath, options) {
990
- const absolutePath = path$1.resolve(projectPath);
991
- try {
992
- await this.store.update((data) => {
993
- const previous = data.projects[absolutePath];
994
- const entry = {
995
- lastAccessed: (/* @__PURE__ */ new Date()).toISOString(),
996
- ...options?.name ? { name: options.name } : previous?.name ? { name: previous.name } : {}
997
- };
998
- return {
999
- ...data,
1000
- projects: {
1001
- ...data.projects,
1002
- [absolutePath]: entry
1003
- },
1004
- lastProject: absolutePath
1005
- };
1006
- });
1007
- } catch {}
1008
- }
1009
- /**
1010
- * Removes a project from tracking. Returns `true` if the project existed,
1011
- * `false` if it was not tracked. Errors propagate (this is invoked by an
1012
- * explicit user action; the caller should know if it failed).
1013
- */
1014
- async untrack(projectPath) {
1015
- const absolutePath = path$1.resolve(projectPath);
1016
- const existing = await this.store.read();
1017
- if (!existing || !(absolutePath in existing.projects)) return false;
1018
- const { [absolutePath]: _removed, ...remaining } = existing.projects;
1019
- const newLastProject = existing.lastProject === absolutePath ? void 0 : existing.lastProject;
1020
- await this.store.write({
1021
- ...existing,
1022
- projects: remaining,
1023
- lastProject: newLastProject
1024
- });
1025
- return true;
1026
- }
1027
- /**
1028
- * Returns all tracked projects as an array of `{ path, lastAccessed, name? }`.
1029
- * Empty array when nothing is tracked or the file is missing.
1030
- *
1031
- * Note: order is not guaranteed (matches `Object.entries` over a Record).
1032
- * Callers that need a sort order should sort explicitly.
1033
- *
1034
- * Best-effort: corrupt files are treated as "no projects" rather than
1035
- * throwing, since project tracking is telemetry data.
1036
- */
1037
- async list() {
1038
- const data = await this.readSafe();
1039
- if (!data) return [];
1040
- return Object.entries(data.projects).map(([projectPath, entry]) => ({
1041
- path: projectPath,
1042
- ...entry
1043
- }));
1044
- }
1045
- /**
1046
- * Returns the most-recently-tracked project path, or `undefined` when none
1047
- * has been recorded.
1048
- */
1049
- async getLast() {
1050
- return (await this.readSafe())?.lastProject;
1051
- }
1052
- /**
1053
- * Removes the projects file. Returns `true` if the file existed, `false`
1054
- * if it did not.
1055
- */
1056
- async clear() {
1057
- return this.store.delete();
1058
- }
1059
- /**
1060
- * Reads the underlying store but treats schema/JSON errors as "no projects"
1061
- * rather than propagating. This preserves the previous best-effort contract
1062
- * for the projects file.
1063
- */
1064
- async readSafe() {
1065
- try {
1066
- return await this.store.read();
1067
- } catch (error) {
1068
- if (error instanceof SyntaxError) return null;
1069
- if (error instanceof Error && error.message.startsWith("Invalid file at")) return null;
1070
- throw error;
1071
- }
1072
- }
1073
- };
1074
- /**
1075
- * Production singleton — the primary public API for project tracking. Tests
1076
- * should construct `new Projects({ homeDir })` instead.
1077
- */
1078
- const projects = new Projects();
1079
- /**
1080
- * Returns the Keystroke temp directory path.
1081
- *
1082
- * - `getKeystrokeTmpDir({ projectRoot })` → `projectRoot/.keystroke/tmp` — for build
1083
- * artifacts that require module resolution from the project (workflow-builder).
1084
- * - `getKeystrokeTmpDir()` → `~/.keystroke/tmp` — for general temporary storage.
1085
- *
1086
- * Callers must create the directory (e.g. `mkdir(path, { recursive: true })`)
1087
- * before use.
1088
- */
1089
- function getKeystrokeTmpDir(options) {
1090
- const baseDir = options?.projectRoot ? path$1.resolve(options.projectRoot) : os.homedir();
1091
- return path$1.join(baseDir, KEYSTROKE_DIR, "tmp");
1092
- }
1093
- //#endregion
1094
- export { projects as i, credentials as n, getKeystrokeTmpDir as r, Credentials as t };