@darkrymit/crunes-cli 0.5.10 → 0.7.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 (70) hide show
  1. package/README.md +5 -5
  2. package/dist/chunks/add-OWYVF3IE.js +22 -0
  3. package/dist/chunks/apply-OMEVXCHC.js +183 -0
  4. package/dist/chunks/args-32BVYW77.js +42 -0
  5. package/dist/chunks/benchmark-CLUBISCR.js +164 -0
  6. package/dist/chunks/browse-COH6IJEX.js +34 -0
  7. package/dist/chunks/check-BS6TZGRR.js +144 -0
  8. package/dist/chunks/chunk-2Q24YPGL.js +369 -0
  9. package/dist/chunks/chunk-3TM6B4E5.js +70 -0
  10. package/dist/chunks/chunk-67I2J474.js +153 -0
  11. package/dist/chunks/chunk-6XLT25GS.js +50 -0
  12. package/dist/chunks/chunk-BVY5LN7X.js +25091 -0
  13. package/dist/chunks/chunk-CGZL5SSH.js +926 -0
  14. package/dist/chunks/chunk-DMMC4X27.js +1836 -0
  15. package/dist/chunks/chunk-G3U4V32O.js +46 -0
  16. package/dist/chunks/chunk-GHQOK4L7.js +59 -0
  17. package/dist/chunks/chunk-H3BVJCIL.js +105 -0
  18. package/dist/chunks/chunk-HMU2J25D.js +63 -0
  19. package/dist/chunks/chunk-HOH7WZX4.js +95 -0
  20. package/dist/chunks/chunk-L72BG6DS.js +225 -0
  21. package/dist/chunks/chunk-NXSDVVTW.js +181 -0
  22. package/dist/chunks/chunk-QLDB3FO2.js +73059 -0
  23. package/dist/chunks/chunk-QMWGQXEZ.js +26 -0
  24. package/dist/chunks/chunk-TPK5AGRA.js +54 -0
  25. package/dist/chunks/chunk-UGN3FFEF.js +8379 -0
  26. package/dist/chunks/chunk-WCODTMDN.js +508 -0
  27. package/dist/chunks/chunk-XIXND2M4.js +296 -0
  28. package/dist/chunks/chunk-XXUNHQIB.js +129 -0
  29. package/dist/chunks/chunk-ZXIP4Z5V.js +281 -0
  30. package/dist/chunks/clear-Y5POLIMF.js +32 -0
  31. package/dist/chunks/completions-2MSEWWTG.js +232 -0
  32. package/dist/chunks/create-5FXQYCGM.js +165 -0
  33. package/dist/chunks/create-I6BNYZ5Q.js +247 -0
  34. package/dist/chunks/create-O3HMODSL.js +130 -0
  35. package/dist/chunks/delete-7CQFYIXS.js +40 -0
  36. package/dist/chunks/delete-UB5SXO5I.js +40 -0
  37. package/dist/chunks/disable-FCBW7WVG.js +47 -0
  38. package/dist/chunks/doctor-DS57HDLJ.js +53 -0
  39. package/dist/chunks/enable-IXRVUXJM.js +47 -0
  40. package/dist/chunks/esm-7MEWZCHY.js +5162 -0
  41. package/dist/chunks/globals-YCJ2DGWC.js +60 -0
  42. package/dist/chunks/init-WGKQVAZE.js +59 -0
  43. package/dist/chunks/install-BCTBOPBS.js +57 -0
  44. package/dist/chunks/intro-2UDWF6D4.js +1482 -0
  45. package/dist/chunks/kill-LWRXZVM5.js +37 -0
  46. package/dist/chunks/list-5DVVP7HX.js +50 -0
  47. package/dist/chunks/list-6WL5LGIZ.js +80 -0
  48. package/dist/chunks/list-NGOCMJXE.js +104 -0
  49. package/dist/chunks/list-TTKLNJKI.js +28 -0
  50. package/dist/chunks/list-WUAOSO3M.js +110 -0
  51. package/dist/chunks/list-YPI7YDKK.js +80 -0
  52. package/dist/chunks/list-ZBYPMUID.js +23 -0
  53. package/dist/chunks/manifest-7RVNKBOH.js +9 -0
  54. package/dist/chunks/output-RJ6JSNY7.js +12 -0
  55. package/dist/chunks/promise-DUSIQMA2.js +19400 -0
  56. package/dist/chunks/query-NY4SCO77.js +41 -0
  57. package/dist/chunks/registry-W5XFI5T6.js +16 -0
  58. package/dist/chunks/remove-WEAZFZCO.js +22 -0
  59. package/dist/chunks/run-I6TZX347.js +23 -0
  60. package/dist/chunks/run-MVIZQVJ6.js +36 -0
  61. package/dist/chunks/rune-TAX26NH2.js +76 -0
  62. package/dist/chunks/search-XENXL3GC.js +25 -0
  63. package/dist/chunks/uninstall-MX5PLGDI.js +49 -0
  64. package/dist/chunks/unset-KQOZYVTE.js +28 -0
  65. package/dist/chunks/update-7XDTVFZ3.js +39 -0
  66. package/dist/chunks/update-IEE54GPY.js +79 -0
  67. package/dist/chunks/utils-PO3ZK53L.js +50 -0
  68. package/dist/chunks/version-DIEA5FVV.js +145 -0
  69. package/dist/cli.js +3360 -125840
  70. package/package.json +23 -15
@@ -0,0 +1,369 @@
1
+ import {
2
+ Ce,
3
+ R,
4
+ le
5
+ } from "./chunk-CGZL5SSH.js";
6
+ import {
7
+ loadRegistry,
8
+ registerPlugin,
9
+ removePlugin
10
+ } from "./chunk-GHQOK4L7.js";
11
+ import {
12
+ ensureStoreDirs,
13
+ getPluginCacheDir,
14
+ getPnpmStorePath
15
+ } from "./chunk-HMU2J25D.js";
16
+ import {
17
+ loadPluginJson
18
+ } from "./chunk-G3U4V32O.js";
19
+ import {
20
+ init_require_shim
21
+ } from "./chunk-TPK5AGRA.js";
22
+
23
+ // src/plugin/install.js
24
+ init_require_shim();
25
+ import fs2 from "node:fs/promises";
26
+ import path2 from "node:path";
27
+ import os from "node:os";
28
+ import { execFile as execFile2 } from "node:child_process";
29
+ import { promisify as promisify2 } from "node:util";
30
+
31
+ // src/plugin/deps.js
32
+ init_require_shim();
33
+ import { execFile } from "node:child_process";
34
+ import { promisify } from "node:util";
35
+ import fs from "node:fs/promises";
36
+ import path from "node:path";
37
+ var execFileAsync = promisify(execFile);
38
+ async function which(cmd) {
39
+ try {
40
+ const shell = process.platform === "win32";
41
+ const { stdout } = await execFileAsync(
42
+ process.platform === "win32" ? "where" : "which",
43
+ [cmd],
44
+ { shell }
45
+ );
46
+ return stdout.trim().split(/\r?\n/)[0] || null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ var _detectedPm = void 0;
52
+ async function detectPackageManager() {
53
+ if (_detectedPm !== void 0) return _detectedPm;
54
+ if (await which("pnpm")) {
55
+ _detectedPm = "pnpm";
56
+ return "pnpm";
57
+ }
58
+ if (await which("bun")) {
59
+ _detectedPm = "bun";
60
+ return "bun";
61
+ }
62
+ _detectedPm = "npm";
63
+ return "npm";
64
+ }
65
+ async function installDeps(pluginCacheDir, dependencies) {
66
+ if (!dependencies || Object.keys(dependencies).length === 0) return;
67
+ const pm = await detectPackageManager();
68
+ const deps = Object.entries(dependencies).map(([name, ver]) => `${name}@${ver}`);
69
+ if (pm === "pnpm") {
70
+ await execFileAsync("pnpm", [
71
+ "add",
72
+ ...deps,
73
+ "--dir",
74
+ pluginCacheDir,
75
+ "--ignore-scripts",
76
+ "--store-dir",
77
+ getPnpmStorePath()
78
+ ], { shell: process.platform === "win32" });
79
+ } else if (pm === "bun") {
80
+ await execFileAsync("bun", [
81
+ "add",
82
+ ...deps,
83
+ "--cwd",
84
+ pluginCacheDir,
85
+ "--ignore-scripts"
86
+ ], { shell: process.platform === "win32" });
87
+ } else {
88
+ await installDepsViaNpm(pluginCacheDir, dependencies);
89
+ console.warn("Hint: install pnpm or bun for smaller plugin storage.\n npm install -g pnpm");
90
+ }
91
+ }
92
+ async function installDepsViaNpm(pluginCacheDir, dependencies) {
93
+ const nodeModulesDir = path.join(pluginCacheDir, "node_modules");
94
+ await fs.mkdir(nodeModulesDir, { recursive: true });
95
+ const packageJsonPath = path.join(pluginCacheDir, "package.json");
96
+ const packageLockJsonPath = path.join(pluginCacheDir, "package-lock.json");
97
+ await fs.writeFile(
98
+ packageJsonPath,
99
+ JSON.stringify({ dependencies }, null, 2),
100
+ "utf8"
101
+ );
102
+ try {
103
+ await execFileAsync("npm", [
104
+ "install",
105
+ "--no-audit",
106
+ "--no-fund",
107
+ "--omit=dev"
108
+ ], {
109
+ cwd: pluginCacheDir,
110
+ shell: process.platform === "win32"
111
+ });
112
+ } finally {
113
+ await fs.rm(packageJsonPath, { force: true });
114
+ await fs.rm(packageLockJsonPath, { force: true });
115
+ }
116
+ }
117
+
118
+ // src/plugin/consent.js
119
+ init_require_shim();
120
+ function collectAllow(permissions) {
121
+ const all = [];
122
+ for (const lifecycle of Object.values(permissions ?? {})) {
123
+ for (const perm of lifecycle?.allow ?? []) {
124
+ if (!all.includes(perm)) all.push(perm);
125
+ }
126
+ }
127
+ return all;
128
+ }
129
+ function formatConsentScreen(pluginName, pluginJson) {
130
+ const lines = [`${pluginName} requests the following permissions:
131
+ `];
132
+ for (const [runeKey, rune] of Object.entries(pluginJson.runes)) {
133
+ const allow = collectAllow(rune.permissions);
134
+ if (allow.length === 0) continue;
135
+ lines.push(` ${runeKey}`);
136
+ for (const perm of allow) {
137
+ lines.push(` ${perm}`);
138
+ }
139
+ lines.push("");
140
+ }
141
+ return lines.join("\n");
142
+ }
143
+ async function promptConsent(pluginName, pluginJson, { yes = false } = {}) {
144
+ const isYes = yes || !process.stdout.isTTY;
145
+ if (isYes) return true;
146
+ Ce(formatConsentScreen(pluginName, pluginJson), "Permissions requested");
147
+ const answer = await le({ message: "Allow these permissions?" });
148
+ if (R(answer)) return false;
149
+ return answer === true;
150
+ }
151
+ function diffPermissions(oldConsented, newPluginJson) {
152
+ const added = {};
153
+ for (const [runeKey, rune] of Object.entries(newPluginJson.runes)) {
154
+ const newPerms = collectAllow(rune.permissions);
155
+ const oldPerms = oldConsented[runeKey] ?? [];
156
+ const newOnes = newPerms.filter((perm) => !oldPerms.includes(perm));
157
+ if (newOnes.length > 0) added[runeKey] = newOnes;
158
+ }
159
+ return added;
160
+ }
161
+ async function promptReConsent(pluginName, diff, { yes = false } = {}) {
162
+ const isYes = yes || !process.stdout.isTTY;
163
+ if (isYes) return true;
164
+ const lines = [`${pluginName} has added new permissions:
165
+ `];
166
+ for (const [runeKey, perms] of Object.entries(diff)) {
167
+ lines.push(` ${runeKey}`);
168
+ for (const perm of perms) {
169
+ lines.push(` ${perm}`);
170
+ }
171
+ lines.push("");
172
+ }
173
+ Ce(lines.join("\n"), "New permissions");
174
+ const answer = await le({ message: "Allow these new permissions?" });
175
+ if (R(answer)) return false;
176
+ return answer === true;
177
+ }
178
+
179
+ // src/plugin/install.js
180
+ var execFileAsync2 = promisify2(execFile2);
181
+ function collectAllowFromRune(rune) {
182
+ const all = [];
183
+ for (const lifecycle of Object.values(rune.permissions ?? {})) {
184
+ for (const perm of lifecycle?.allow ?? []) {
185
+ if (!all.includes(perm)) all.push(perm);
186
+ }
187
+ }
188
+ return all;
189
+ }
190
+ function classifySource(source) {
191
+ if (source.startsWith(".") || source.startsWith("/") || source.startsWith("~") || /^[A-Za-z]:[/\\]/.test(source)) {
192
+ return { type: "local", resolved: source.replace(/^~/, os.homedir()) };
193
+ }
194
+ if (source.startsWith("https://") || source.startsWith("git+")) {
195
+ return { type: "git", resolved: source };
196
+ }
197
+ if (/^[\w-]+\/[\w.-]+$/.test(source) || source.startsWith("github:")) {
198
+ const repo = source.replace(/^github:/, "");
199
+ return { type: "github", resolved: `https://github.com/${repo}` };
200
+ }
201
+ return { type: "npm", resolved: source };
202
+ }
203
+ async function downloadGitHub(repoUrl, destDir) {
204
+ const apiUrl = repoUrl.replace("https://github.com/", "https://api.github.com/repos/") + "/tarball";
205
+ const res = await fetch(apiUrl, { headers: { "User-Agent": "crunes-cli" } });
206
+ if (!res.ok) throw new Error(`Failed to download ${repoUrl}: HTTP ${res.status}`);
207
+ const buf = Buffer.from(await res.arrayBuffer());
208
+ const tarPath = path2.join(destDir, "plugin.tar.gz");
209
+ await fs2.writeFile(tarPath, buf);
210
+ await execFileAsync2("tar", ["-xzf", tarPath, "-C", destDir, "--strip-components=1"], { shell: process.platform === "win32" });
211
+ await fs2.rm(tarPath);
212
+ }
213
+ async function downloadGit(gitUrl, destDir) {
214
+ await execFileAsync2("git", ["clone", "--depth=1", gitUrl, destDir]);
215
+ }
216
+ async function downloadNpm(packageName, destDir) {
217
+ const tmp = destDir + ".tmp-npm";
218
+ await fs2.mkdir(tmp, { recursive: true });
219
+ try {
220
+ await execFileAsync2("npm", ["pack", packageName, "--pack-destination", tmp], { shell: process.platform === "win32" });
221
+ const files = await fs2.readdir(tmp);
222
+ const tarball = files.find((f) => f.endsWith(".tgz"));
223
+ if (!tarball) throw new Error(`npm pack produced no tarball for ${packageName}`);
224
+ await fs2.mkdir(destDir, { recursive: true });
225
+ await execFileAsync2("tar", ["-xzf", path2.join(tmp, tarball), "-C", destDir, "--strip-components=1"], { shell: process.platform === "win32" });
226
+ } finally {
227
+ await fs2.rm(tmp, { recursive: true, force: true });
228
+ }
229
+ }
230
+ async function installPlugin(source, projectDir, provenance = {}, options = {}) {
231
+ const { yes = false } = options;
232
+ if (!provenance.marketplaceName) {
233
+ throw new Error("Direct installs are not allowed. Use: crunes plugin install <marketplace>@<plugin>");
234
+ }
235
+ await ensureStoreDirs();
236
+ const { type, resolved } = classifySource(source);
237
+ let stagingDir;
238
+ if (type === "local") {
239
+ stagingDir = path2.resolve(resolved);
240
+ } else {
241
+ stagingDir = path2.join(os.tmpdir(), `crunes-install-${Date.now()}`);
242
+ await fs2.mkdir(stagingDir, { recursive: true });
243
+ }
244
+ try {
245
+ if (type === "github") await downloadGitHub(resolved, stagingDir);
246
+ else if (type === "git") await downloadGit(resolved, stagingDir);
247
+ else if (type === "npm") await downloadNpm(resolved, stagingDir);
248
+ const pluginJson = await loadPluginJson(stagingDir);
249
+ const name = provenance.pluginName;
250
+ const version = provenance.version;
251
+ if (!name || !version) {
252
+ throw new Error(`Provenance missing plugin identity: name="${name}", version="${version}"`);
253
+ }
254
+ const pluginKey = `${provenance.marketplaceName}@${name}`;
255
+ const registry = await loadRegistry();
256
+ const existing = registry.plugins?.[pluginKey];
257
+ if (existing) {
258
+ return await updatePlugin(pluginKey, stagingDir, pluginJson, projectDir, type === "local", provenance, { yes });
259
+ }
260
+ const isLocal = type === "local";
261
+ const cacheDir = getPluginCacheDir(name, version, provenance.marketplaceName);
262
+ if (!isLocal) {
263
+ await fs2.cp(stagingDir, cacheDir, { recursive: true });
264
+ } else {
265
+ await fs2.mkdir(cacheDir, { recursive: true });
266
+ }
267
+ await installDeps(cacheDir, pluginJson.dependencies);
268
+ const consented = await promptConsent(name, pluginJson, { yes });
269
+ if (!consented) {
270
+ await fs2.rm(cacheDir, { recursive: true, force: true });
271
+ return { installed: false, name };
272
+ }
273
+ const consentedPermissions = {};
274
+ for (const [key, rune] of Object.entries(pluginJson.runes)) {
275
+ consentedPermissions[key] = collectAllowFromRune(rune);
276
+ }
277
+ await registerPlugin({ name, version, path: isLocal ? stagingDir : cacheDir, cacheDir, local: isLocal, consentedPermissions, ...provenance });
278
+ await addPluginToProjectConfig(projectDir, pluginKey);
279
+ return { installed: true, name: pluginKey, version };
280
+ } finally {
281
+ if (type !== "local") {
282
+ await fs2.rm(stagingDir, { recursive: true, force: true }).catch(() => {
283
+ });
284
+ }
285
+ }
286
+ }
287
+ async function updatePlugin(pluginKey, newPluginDir, newPluginJson, projectDir, isLocal, provenance = {}, options = {}) {
288
+ const { yes = false } = options;
289
+ const registry = await loadRegistry();
290
+ const existing = registry.plugins[pluginKey];
291
+ if (!existing) throw new Error(`Plugin "${pluginKey}" is not installed.`);
292
+ const diff = diffPermissions(existing.consentedPermissions ?? {}, newPluginJson);
293
+ if (Object.keys(diff).length > 0) {
294
+ const consented = await promptReConsent(pluginKey, diff, { yes });
295
+ if (!consented) return { installed: false, name: pluginKey };
296
+ }
297
+ const name = provenance.pluginName;
298
+ const version = provenance.version;
299
+ if (!name || !version) {
300
+ throw new Error(`Provenance missing plugin identity during update: name="${name}", version="${version}"`);
301
+ }
302
+ const cacheDir = getPluginCacheDir(name, version, provenance.marketplaceName);
303
+ if (!isLocal) {
304
+ await fs2.cp(newPluginDir, cacheDir, { recursive: true });
305
+ } else {
306
+ await fs2.mkdir(cacheDir, { recursive: true });
307
+ }
308
+ await installDeps(cacheDir, newPluginJson.dependencies);
309
+ const consentedPermissions = {};
310
+ for (const [key, rune] of Object.entries(newPluginJson.runes)) {
311
+ consentedPermissions[key] = collectAllowFromRune(rune);
312
+ }
313
+ await registerPlugin({ name, version, path: isLocal ? newPluginDir : cacheDir, cacheDir, local: isLocal, consentedPermissions, ...provenance });
314
+ await addPluginToProjectConfig(projectDir, pluginKey);
315
+ return { installed: true, name: pluginKey, version, updated: true };
316
+ }
317
+ async function addPluginToProjectConfig(projectDir, pluginName) {
318
+ if (!projectDir) return;
319
+ const configPath = path2.join(projectDir, ".crunes", "config.json");
320
+ try {
321
+ const raw = await fs2.readFile(configPath, "utf8");
322
+ const config = JSON.parse(raw);
323
+ const plugins = config.plugins ?? [];
324
+ if (!plugins.includes(pluginName)) {
325
+ config.plugins = [...plugins, pluginName];
326
+ const tmp = configPath + "." + Date.now() + Math.random().toString(36).slice(2) + ".tmp";
327
+ await fs2.writeFile(tmp, JSON.stringify(config, null, 2), "utf8");
328
+ await fs2.rename(tmp, configPath);
329
+ }
330
+ } catch {
331
+ }
332
+ }
333
+ async function uninstallPlugin(pluginKey, projectDir) {
334
+ const registry = await loadRegistry();
335
+ const entry = registry.plugins?.[pluginKey];
336
+ if (!entry) throw new Error(`Plugin "${pluginKey}" is not installed.`);
337
+ try {
338
+ const dirToRemove = entry.cacheDir ?? (entry.local ? null : entry.path);
339
+ if (dirToRemove) {
340
+ const stat = await fs2.lstat(dirToRemove);
341
+ if (stat.isSymbolicLink()) {
342
+ await fs2.unlink(dirToRemove);
343
+ } else {
344
+ await fs2.rm(dirToRemove, { recursive: true, force: true });
345
+ }
346
+ }
347
+ } catch {
348
+ }
349
+ await removePlugin(pluginKey);
350
+ await removePluginFromProjectConfig(projectDir, pluginKey);
351
+ }
352
+ async function removePluginFromProjectConfig(projectDir, pluginName) {
353
+ if (!projectDir) return;
354
+ const configPath = path2.join(projectDir, ".crunes", "config.json");
355
+ try {
356
+ const raw = await fs2.readFile(configPath, "utf8");
357
+ const config = JSON.parse(raw);
358
+ config.plugins = (config.plugins ?? []).filter((p) => p !== pluginName);
359
+ const tmp = configPath + "." + Date.now() + Math.random().toString(36).slice(2) + ".tmp";
360
+ await fs2.writeFile(tmp, JSON.stringify(config, null, 2), "utf8");
361
+ await fs2.rename(tmp, configPath);
362
+ } catch {
363
+ }
364
+ }
365
+
366
+ export {
367
+ installPlugin,
368
+ uninstallPlugin
369
+ };
@@ -0,0 +1,70 @@
1
+ import {
2
+ getProjectsJsonPath
3
+ } from "./chunk-HMU2J25D.js";
4
+ import {
5
+ init_require_shim
6
+ } from "./chunk-TPK5AGRA.js";
7
+
8
+ // src/project/index.js
9
+ init_require_shim();
10
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
11
+ import { dirname } from "node:path";
12
+ import { createHash } from "node:crypto";
13
+ import path from "node:path";
14
+ function shortHash(str) {
15
+ return createHash("sha1").update(str).digest("hex").slice(0, 8);
16
+ }
17
+ async function ensureProjectIdentity(dir) {
18
+ const localJsonPath = path.join(dir, ".crunes", "project.local.json");
19
+ try {
20
+ const raw = await readFile(localJsonPath, "utf8");
21
+ return JSON.parse(raw);
22
+ } catch {
23
+ }
24
+ let alias = path.basename(dir);
25
+ try {
26
+ const config = JSON.parse(await readFile(path.join(dir, ".crunes", "config.json"), "utf8"));
27
+ if (typeof config.name === "string" && config.name.length > 0) alias = config.name;
28
+ } catch {
29
+ }
30
+ const id = `${path.basename(dir).slice(0, 15)}-${shortHash(dir + "-" + Math.random())}`;
31
+ const identity = { id, alias };
32
+ await mkdir(path.join(dir, ".crunes"), { recursive: true });
33
+ await writeFile(localJsonPath, JSON.stringify(identity, null, 2), "utf8");
34
+ return identity;
35
+ }
36
+ async function loadProjects() {
37
+ try {
38
+ const raw = await readFile(getProjectsJsonPath(), "utf8");
39
+ return JSON.parse(raw);
40
+ } catch {
41
+ return { format: "1", projects: {} };
42
+ }
43
+ }
44
+ async function upsertProject(id, projectDir) {
45
+ const data = await loadProjects();
46
+ let alias = path.basename(projectDir);
47
+ try {
48
+ const raw = await readFile(path.join(projectDir, ".crunes", "project.local.json"), "utf8");
49
+ const parsed = JSON.parse(raw);
50
+ if (typeof parsed.alias === "string" && parsed.alias.length > 0) alias = parsed.alias;
51
+ } catch {
52
+ }
53
+ const existing = data.projects[id];
54
+ data.projects[id] = {
55
+ path: projectDir,
56
+ alias,
57
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString(),
58
+ firstSeenAt: existing?.firstSeenAt ?? (/* @__PURE__ */ new Date()).toISOString()
59
+ };
60
+ const p = getProjectsJsonPath();
61
+ await mkdir(dirname(p), { recursive: true });
62
+ await writeFile(p, JSON.stringify(data, null, 2), "utf8");
63
+ }
64
+
65
+ export {
66
+ shortHash,
67
+ ensureProjectIdentity,
68
+ loadProjects,
69
+ upsertProject
70
+ };
@@ -0,0 +1,153 @@
1
+ import {
2
+ storageKey
3
+ } from "./chunk-QMWGQXEZ.js";
4
+ import {
5
+ getSqliteBasePath,
6
+ getSqliteJsonPath
7
+ } from "./chunk-HMU2J25D.js";
8
+ import {
9
+ init_require_shim
10
+ } from "./chunk-TPK5AGRA.js";
11
+
12
+ // src/sqlite/index.js
13
+ init_require_shim();
14
+ import { readFile, readdir, writeFile, mkdir, rm } from "node:fs/promises";
15
+ import { dirname } from "node:path";
16
+ import path from "node:path";
17
+ async function loadDatabase() {
18
+ try {
19
+ const { default: Database } = await import("better-sqlite3");
20
+ return Database;
21
+ } catch {
22
+ throw new Error(
23
+ "better-sqlite3 is not installed.\nRun: npm install -g better-sqlite3"
24
+ );
25
+ }
26
+ }
27
+ function getSqlitePluginDir(pluginId) {
28
+ return path.join(getSqliteBasePath(), "plugins", pluginId);
29
+ }
30
+ function getSqliteProjectDir(key) {
31
+ return path.join(getSqliteBasePath(), "projects", key);
32
+ }
33
+ function getSqliteProjectPluginDir(key, pluginId) {
34
+ return path.join(getSqliteBasePath(), "project-plugins", key, pluginId);
35
+ }
36
+ async function loadSqliteDbs() {
37
+ try {
38
+ return JSON.parse(await readFile(getSqliteJsonPath(), "utf8"));
39
+ } catch {
40
+ return { format: "1", databases: {} };
41
+ }
42
+ }
43
+ async function upsertSqliteDb(resolvedPath, { scope, projectId, pluginId, location, name }) {
44
+ const data = await loadSqliteDbs();
45
+ const effectiveProjectId = projectId ?? null;
46
+ const key = storageKey(scope, { projectId: effectiveProjectId, pluginId, name });
47
+ data.databases[key] = {
48
+ path: resolvedPath,
49
+ scope,
50
+ projectKey: effectiveProjectId,
51
+ pluginId: pluginId ?? null,
52
+ location,
53
+ name,
54
+ firstSeenAt: data.databases[key]?.firstSeenAt ?? (/* @__PURE__ */ new Date()).toISOString()
55
+ };
56
+ const p = getSqliteJsonPath();
57
+ await mkdir(dirname(p), { recursive: true });
58
+ await writeFile(p, JSON.stringify(data, null, 2), "utf8");
59
+ }
60
+ function scopedDatabases(data, projectKey) {
61
+ if (projectKey === void 0) return data.databases;
62
+ return Object.fromEntries(
63
+ Object.entries(data.databases).filter(
64
+ ([, e]) => (e.scope === "global-project" || e.scope === "global-project-plugin") && e.projectKey === projectKey
65
+ )
66
+ );
67
+ }
68
+ async function listSqliteDbs(projectKey = void 0) {
69
+ const data = await loadSqliteDbs();
70
+ return Object.entries(scopedDatabases(data, projectKey)).map(([key, entry]) => ({ key, ...entry }));
71
+ }
72
+ async function listLocalSqliteDbs(projectDir) {
73
+ let projectId;
74
+ try {
75
+ const raw = await readFile(path.join(projectDir, ".crunes", "project.local.json"), "utf8");
76
+ projectId = JSON.parse(raw).id;
77
+ } catch {
78
+ return [];
79
+ }
80
+ const results = [];
81
+ const localSqliteDir = path.join(projectDir, ".crunes", "sqlite");
82
+ async function scanScope(scopeDir, scope, pluginId = null) {
83
+ let entries;
84
+ try {
85
+ entries = await readdir(scopeDir, { withFileTypes: true });
86
+ } catch {
87
+ return;
88
+ }
89
+ for (const entry of entries) {
90
+ if (!entry.isFile() || !entry.name.endsWith(".sqlite")) continue;
91
+ const name = entry.name.slice(0, -".sqlite".length);
92
+ const key = storageKey(scope, { projectId, pluginId, name });
93
+ const location = pluginId ? `@local-project-plugin-sqlite/${pluginId}/${name}` : `@local-project-sqlite/${name}`;
94
+ results.push({ key, scope, projectKey: projectId, pluginId, location, name, firstSeenAt: null, path: path.join(scopeDir, entry.name) });
95
+ }
96
+ }
97
+ await scanScope(path.join(localSqliteDir, "project"), "local-project");
98
+ const pluginsDir = path.join(localSqliteDir, "project-plugins");
99
+ let pluginEntries;
100
+ try {
101
+ pluginEntries = await readdir(pluginsDir, { withFileTypes: true });
102
+ } catch {
103
+ pluginEntries = [];
104
+ }
105
+ for (const pluginEntry of pluginEntries) {
106
+ if (!pluginEntry.isDirectory()) continue;
107
+ await scanScope(path.join(pluginsDir, pluginEntry.name), "local-project-plugin", pluginEntry.name);
108
+ }
109
+ return results;
110
+ }
111
+ function resolveKey(id, databases) {
112
+ if (id in databases) return id;
113
+ const matches = Object.keys(databases).filter((k) => k.startsWith(id));
114
+ if (matches.length === 1) return matches[0];
115
+ if (matches.length === 0) throw new Error(`No SQLite database matching "${id}".`);
116
+ throw new Error(`Ambiguous id "${id}" \u2014 matches: ${matches.join(", ")}.`);
117
+ }
118
+ async function deleteSqliteDb(id, projectKey = void 0) {
119
+ const data = await loadSqliteDbs();
120
+ const key = resolveKey(id, scopedDatabases(data, projectKey));
121
+ const { path: dbPath, name } = data.databases[key];
122
+ await rm(dbPath, { force: true });
123
+ await rm(dbPath + "-wal", { force: true });
124
+ await rm(dbPath + "-shm", { force: true });
125
+ delete data.databases[key];
126
+ const p = getSqliteJsonPath();
127
+ await mkdir(dirname(p), { recursive: true });
128
+ await writeFile(p, JSON.stringify(data, null, 2), "utf8");
129
+ return { name };
130
+ }
131
+ async function querySqliteDb(id, sql, projectKey = void 0) {
132
+ const Database = await loadDatabase();
133
+ const data = await loadSqliteDbs();
134
+ const key = resolveKey(id, scopedDatabases(data, projectKey));
135
+ const { path: dbPath } = data.databases[key];
136
+ const db = new Database(dbPath, { readonly: true });
137
+ try {
138
+ return db.prepare(sql).all();
139
+ } finally {
140
+ db.close();
141
+ }
142
+ }
143
+
144
+ export {
145
+ getSqlitePluginDir,
146
+ getSqliteProjectDir,
147
+ getSqliteProjectPluginDir,
148
+ upsertSqliteDb,
149
+ listSqliteDbs,
150
+ listLocalSqliteDbs,
151
+ deleteSqliteDb,
152
+ querySqliteDb
153
+ };
@@ -0,0 +1,50 @@
1
+ import {
2
+ source_default
3
+ } from "./chunk-WCODTMDN.js";
4
+ import {
5
+ init_require_shim
6
+ } from "./chunk-TPK5AGRA.js";
7
+
8
+ // src/shared/output.js
9
+ init_require_shim();
10
+ var _plain = false;
11
+ var isVerbose = false;
12
+ function configure({ plain = false, verbose = false } = {}) {
13
+ _plain = plain;
14
+ isVerbose = verbose;
15
+ if (plain) source_default.level = 0;
16
+ }
17
+ var sym = {
18
+ ok: () => _plain ? "[ok]" : source_default.green("\u2713"),
19
+ err: () => _plain ? "[err]" : source_default.red("\u2717"),
20
+ warn: () => _plain ? "[warn]" : source_default.yellow("\u26A0"),
21
+ info: () => _plain ? "[info]" : source_default.blue("\u2139")
22
+ };
23
+ var output = {
24
+ header(label) {
25
+ if (_plain) {
26
+ console.log(`=== ${label} ===`);
27
+ } else {
28
+ console.log(source_default.dim("\u2500".repeat(40)));
29
+ console.log(source_default.bold(label));
30
+ }
31
+ },
32
+ success(msg) {
33
+ console.log(`${sym.ok()} ${msg}`);
34
+ },
35
+ error(msg) {
36
+ console.error(`${sym.err()} ${msg}`);
37
+ },
38
+ warn(msg) {
39
+ console.warn(`${sym.warn()} ${msg}`);
40
+ },
41
+ info(msg) {
42
+ console.log(`${sym.info()} ${msg}`);
43
+ }
44
+ };
45
+
46
+ export {
47
+ isVerbose,
48
+ configure,
49
+ output
50
+ };