create-insight 0.0.0-stage → 0.21.1

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.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # create-insight
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sets Insight up beside your app, with the Kaleyla key you got with your licence or trial. From your app's folder:
4
+
5
+ ```
6
+ npx create-insight
7
+ ```
8
+
9
+ It downloads Insight for your machine (Docker or Podman, Intel/AMD or ARM), adds `@kaleyla/insight` to your app,
10
+ starts Insight with its own database, and opens its console. Later, `npx create-insight upgrade` brings it to the
11
+ latest release. `npx create-insight --help` lists the options.
12
+
13
+ Insight is licensed by Kaleyla; this installer only fetches it with your key.
@@ -0,0 +1,430 @@
1
+ #!/usr/bin/env node
2
+
3
+ // installer/create-insight.mjs
4
+ import { spawnSync } from "node:child_process";
5
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
6
+ import { appendFileSync, copyFileSync, createWriteStream, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, readdirSync, renameSync, rmSync, statSync, writeFileSync as writeFileSync2 } from "node:fs";
7
+ import { createServer } from "node:net";
8
+ import { arch as hostArch, homedir, userInfo } from "node:os";
9
+ import { basename, join as join2, relative, resolve } from "node:path";
10
+ import { createInterface } from "node:readline";
11
+ import { Readable } from "node:stream";
12
+ import { pipeline } from "node:stream/promises";
13
+
14
+ // src/cli.ts
15
+ import { parseArgs } from "node:util";
16
+ function cliArgs(help, options, allowPositionals = false, argv2 = process.argv.slice(2)) {
17
+ if (argv2.includes("--help") || argv2.includes("-h")) {
18
+ console.log(help);
19
+ process.exit(0);
20
+ }
21
+ try {
22
+ return parseArgs({ args: argv2, options: options ?? {}, allowPositionals, strict: true });
23
+ } catch (error) {
24
+ console.error(`${error instanceof Error ? error.message : String(error)}
25
+
26
+ ${help}`);
27
+ process.exit(2);
28
+ }
29
+ }
30
+
31
+ // src/auth/keys.ts
32
+ import { generateKeyPairSync, randomBytes, randomUUID } from "node:crypto";
33
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
34
+ import { join } from "node:path";
35
+ var SIGNING_FILE = "insight-signing-key.json";
36
+ var PUBLIC_FILE = "insight-public-keys.json";
37
+ var APP_SECRET_FILE = "insight-app-secret";
38
+ function readAppSecret(dir2) {
39
+ const file = join(dir2, APP_SECRET_FILE);
40
+ if (!existsSync(file)) return null;
41
+ const secret = readFileSync(file, "utf8").trim();
42
+ return secret || null;
43
+ }
44
+ function ensureAppSecret(dir2) {
45
+ const kept = readAppSecret(dir2);
46
+ if (kept) return { secret: kept, made: false };
47
+ const secret = randomBytes(32).toString("hex");
48
+ writeFileSync(join(dir2, APP_SECRET_FILE), `${secret}
49
+ `, { mode: 384 });
50
+ return { secret, made: true };
51
+ }
52
+ var KeysError = class extends Error {
53
+ };
54
+ function makeKeys(dir2, options = {}) {
55
+ const signingPath = join(dir2, SIGNING_FILE);
56
+ const publicPath = join(dir2, PUBLIC_FILE);
57
+ const exists = existsSync(signingPath);
58
+ if (exists && !options.rotate) throw new KeysError(`A signing key already exists: ${signingPath}. Use --rotate to replace it (the old public key is kept so tokens already signed still work).`);
59
+ if (!exists && options.rotate) throw new KeysError(`There is no signing key to rotate in ${dir2}.`);
60
+ const prefix = (options.name ?? "app").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "app";
61
+ const kid = `${prefix}-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}-${randomUUID().slice(0, 8)}`;
62
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
63
+ const previous = options.rotate && existsSync(publicPath) ? JSON.parse(readFileSync(publicPath, "utf8")).keys ?? [] : [];
64
+ const keys = [...previous, { ...publicKey.export({ format: "jwk" }), kid }];
65
+ writeFileSync(signingPath, `${JSON.stringify({ kid, jwk: privateKey.export({ format: "jwk" }) })}
66
+ `, { mode: 384 });
67
+ chmodSync(signingPath, 384);
68
+ writeFileSync(publicPath, `${JSON.stringify({ keys }, null, 2)}
69
+ `);
70
+ return { kid, signingPath, publicPath, kids: keys.map((k) => k.kid) };
71
+ }
72
+
73
+ // src/init/compose.ts
74
+ function hostFromContainer(engine2) {
75
+ return engine2 === "podman" ? "host.containers.internal" : "host.docker.internal";
76
+ }
77
+ function defaultAppUrl(engine2) {
78
+ return `http://${hostFromContainer(engine2)}:3000`;
79
+ }
80
+ function containerNames(project2) {
81
+ return { insight: `${project2}-insight`, db: `${project2}-db` };
82
+ }
83
+ function projectName(folder) {
84
+ const slug = folder.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
85
+ return `insight-${slug || "app"}`;
86
+ }
87
+ function composeYaml(p) {
88
+ const names2 = containerNames(p.project);
89
+ const tool2 = p.engine === "podman" ? "podman compose" : "docker compose";
90
+ return `# Insight beside this app, written by Insight's installer. Start: ${tool2} up -d \xB7 Stop: ${tool2} down
91
+ # Upgrade: change the image's version, then ${tool2} up -d. Settings and secrets are in insight.env.
92
+ name: ${p.project}
93
+ services:
94
+ insight:
95
+ image: ${p.image}
96
+ container_name: ${names2.insight}
97
+ restart: unless-stopped
98
+ ports: ["127.0.0.1:${p.port}:3120"]
99
+ env_file: insight.env
100
+ volumes: ["./insight-config:/config:ro${p.selinux ? ",Z" : ""}"]
101
+ ${p.engine === "docker" ? ' extra_hosts: ["host.docker.internal:host-gateway"]\n' : ""} depends_on:
102
+ insight-db: { condition: service_healthy }
103
+ insight-db:
104
+ image: docker.io/library/postgres:16
105
+ container_name: ${names2.db}
106
+ restart: unless-stopped
107
+ env_file: insight.env
108
+ volumes: ["insight-db:/var/lib/postgresql/data"]
109
+ healthcheck:
110
+ test: ["CMD-SHELL", "pg_isready -U insight -d insight"]
111
+ interval: 3s
112
+ retries: 20
113
+ volumes:
114
+ insight-db: {}
115
+ `;
116
+ }
117
+
118
+ // bin/init-defaults.json
119
+ var init_defaults_default = {
120
+ modelUrl: "https://model.kaleyla.com/v1",
121
+ model: "gemini-3.1-flash-lite",
122
+ reviewModel: "gpt-6-luna"
123
+ };
124
+
125
+ // installer/create-insight.mjs
126
+ var DOWNLOADS = (process.env.KALEYLA_DOWNLOAD_URL ?? "https://get.kaleyla.com").replace(/\/+$/, "");
127
+ var IMAGE = "ghcr.io/kaleyla/insight";
128
+ var argv = process.argv.slice(2);
129
+ var upgrading = argv[0] === "upgrade";
130
+ var { values } = cliArgs(
131
+ `create-insight: Insight beside your app, with your Kaleyla key. Run it from your app's folder.
132
+
133
+ npx create-insight [options] set Insight up
134
+ npx create-insight upgrade [options] bring it to the latest release (the key is read from insight.env)
135
+
136
+ --key <key> your Kaleyla key (KLY-\u2026; or KALEYLA_KEY). Without it you're asked.
137
+ --release <version> a given release instead of the latest
138
+ --also <folder> another folder of your app with its own package.json (a separate frontend, say) that gets
139
+ @kaleyla/insight too; give it once per folder
140
+ --no-package don't add @kaleyla/insight to the app (an app that isn't on Node.js)
141
+ --port <n> where the console and Insight listen on this machine (default 3120, or the next free one)
142
+ --app-url <url> your app as Insight's container reaches it (default port 3000 on this machine)
143
+ --engine <name> docker or podman (default: whichever is running)
144
+ --name <name> your name, on the Owner sign-in link (default: git's user.name)
145
+ --yes ask nothing
146
+ --no-open print the sign-in link instead of opening it
147
+
148
+ Writes docker-compose.yml, insight.env (secrets, added to .gitignore), insight-config/, keys/ (the app's signing key,
149
+ added to .gitignore) and vendor/kaleyla-insight-<version>.tgz (commit this one: your CI installs from it).`,
150
+ {
151
+ key: { type: "string" },
152
+ release: { type: "string" },
153
+ also: { type: "string", multiple: true },
154
+ "no-package": { type: "boolean", default: false },
155
+ port: { type: "string" },
156
+ "app-url": { type: "string" },
157
+ engine: { type: "string" },
158
+ name: { type: "string" },
159
+ yes: { type: "boolean", default: false },
160
+ "no-open": { type: "boolean", default: false }
161
+ },
162
+ true,
163
+ upgrading ? argv.slice(1) : argv
164
+ );
165
+ var dir = process.cwd();
166
+ var say = (line = "") => console.log(line);
167
+ var done = (line) => say(`\u2713 ${line}`);
168
+ var stop = (line) => {
169
+ console.error(`\u2717 ${line}`);
170
+ process.exit(1);
171
+ };
172
+ var run = (cmd, args, opts = {}) => spawnSync(cmd, args, { cwd: dir, encoding: "utf8", ...opts });
173
+ var envFile = join2(dir, "insight.env");
174
+ var readEnv = () => Object.fromEntries(readFileSync2(envFile, "utf8").split("\n").filter((l) => /^[A-Z_]+=/.test(l)).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
175
+ if (upgrading && !existsSync2(envFile)) stop("There\u2019s no Insight here to upgrade (no insight.env). Run npx create-insight to set it up.");
176
+ if (!upgrading && existsSync2(envFile)) stop("Insight is already set up here (insight.env exists). To bring it up to date: npx create-insight upgrade");
177
+ var saved = upgrading ? readEnv() : {};
178
+ var key = (values.key ?? process.env.KALEYLA_KEY ?? saved.INSIGHT_LICENCE_KEY ?? "").trim();
179
+ if (!key && !values.yes && process.stdin.isTTY) key = (await askHidden("Your Kaleyla key (KLY-\u2026): ")).trim();
180
+ if (!key) stop("Insight needs your Kaleyla key: give it with --key, or run this again and paste it when asked.");
181
+ if (!key.startsWith("KLY-")) stop("That isn\u2019t a Kaleyla key: those start with KLY-.");
182
+ if (!upgrading && !values["no-package"]) {
183
+ for (const d of [dir, ...(values.also ?? []).map((a) => resolve(dir, a))]) {
184
+ if (!existsSync2(join2(d, "package.json"))) stop(`${relative(dir, d) || "This folder"} has no package.json. Run this from your app\u2019s folder, or add --no-package for an app that isn\u2019t on Node.js.`);
185
+ }
186
+ }
187
+ var engine = detectEngine();
188
+ var cli = engine.cli;
189
+ var tool = engine.compose.join(" ");
190
+ done(`${engine.name === "podman" ? "Podman" : "Docker"} is running (${tool}${engine.selinux ? ", SELinux on" : ""})`);
191
+ var release;
192
+ try {
193
+ const r = await fetch(`${DOWNLOADS}/v1/releases/${encodeURIComponent(values.release ?? "latest")}`, { headers: { authorization: `Bearer ${key}` } });
194
+ release = await r.json();
195
+ if (!r.ok) stop(release?.error?.message ?? `Kaleyla\u2019s download service answered ${r.status}.`);
196
+ } catch (e) {
197
+ stop(`Kaleyla\u2019s download service can\u2019t be reached (${e instanceof Error ? e.message : String(e)}). Check this machine\u2019s internet connection, then run this again.`);
198
+ }
199
+ var version = release.version;
200
+ var image = `${IMAGE}:${version}`;
201
+ if (upgrading) {
202
+ const current = /image:\s*\S+:(\S+)/.exec(readFileSync2(join2(dir, "docker-compose.yml"), "utf8"))?.[1];
203
+ if (current === version) {
204
+ done(`Insight is already at ${values.release ? "release" : "the latest release,"} ${version}`);
205
+ process.exit(0);
206
+ }
207
+ say(`Upgrading Insight ${current ?? ""} \u2192 ${version}`);
208
+ } else say(`Insight ${version}`);
209
+ var cpu = engineArch();
210
+ var imageFile = release.files.find((f) => f.kind === "image" && f.platform === `linux/${cpu}`);
211
+ if (!imageFile) stop(`Release ${version} has no image for this machine\u2019s CPU (${cpu}). Tell Kaleyla.`);
212
+ var appFile = release.files.find((f) => f.kind === "app-package");
213
+ var cache = join2(process.env.XDG_CACHE_HOME ?? join2(homedir(), ".cache"), "kaleyla", "insight", version);
214
+ mkdirSync(cache, { recursive: true });
215
+ var imagePath = await download(imageFile);
216
+ var appPath = appFile ? await download(appFile) : null;
217
+ var loaded = run(cli, ["load", "-i", imagePath]);
218
+ if (loaded.status !== 0) stop(`${cli} couldn\u2019t load the image: ${(loaded.stderr || loaded.stdout).trim()}`);
219
+ done(`Loaded Insight ${version} into ${engine.name === "podman" ? "Podman" : "Docker"} (${cpu})`);
220
+ var packageDirs = upgrading ? (saved.INSIGHT_APP_PACKAGES ?? "").split(",").filter(Boolean).map((d) => resolve(dir, d)) : values["no-package"] ? [] : [dir, ...(values.also ?? []).map((d) => resolve(dir, d))];
221
+ for (const target of packageDirs) addPackage(target);
222
+ if (upgrading) {
223
+ if (!saved.INSIGHT_APP_SECRET) {
224
+ const keysDir2 = join2(dir, "keys");
225
+ mkdirSync(keysDir2, { recursive: true });
226
+ const { secret } = ensureAppSecret(keysDir2);
227
+ appendFileSync(envFile, `${readFileSync2(envFile, "utf8").endsWith("\n") ? "" : "\n"}# Watches: the secret Insight sends your app's token route (the same as keys/insight-app-secret)
228
+ INSIGHT_APP_SECRET=${secret}
229
+ `);
230
+ done("Added the watch secret to insight.env and keys/insight-app-secret");
231
+ }
232
+ const compose = join2(dir, "docker-compose.yml");
233
+ writeFileSync2(compose, readFileSync2(compose, "utf8").replace(/(image:\s*)\S+\/insight:\S+/, `$1${image}`));
234
+ const up2 = run(engine.compose[0], [...engine.compose.slice(1), "up", "-d"], { stdio: ["ignore", "ignore", "pipe"] });
235
+ if (up2.status !== 0) stop(`${tool} up didn\u2019t start:
236
+ ${(up2.stderr ?? "").trim()}`);
237
+ const env = readEnv();
238
+ const url = env.INSIGHT_CONSOLE_URL ?? "http://127.0.0.1:3120";
239
+ if (!await healthy(`${url}/v1/health`, version, 18e4)) stop(`Insight ${version} didn\u2019t answer at ${url} within 3 minutes. See why with: ${cli} logs ${containerNames(projectName(basename(dir))).insight}`);
240
+ done(`Insight ${version} is running at ${url}`);
241
+ if (packageDirs.length) say(`Commit the new vendor/kaleyla-insight-${version}.tgz and package.json${packageDirs.length > 1 ? " files" : ""}, so your CI uses it too.`);
242
+ process.exit(0);
243
+ }
244
+ var port = values.port ? Number(values.port) : await freePort(3120);
245
+ if (!Number.isInteger(port) || port < 1 || port > 65535) stop(`--port ${values.port} isn\u2019t a port.`);
246
+ var name = values.name ?? (run("git", ["config", "user.name"]).stdout?.trim() || userInfo().username);
247
+ var project = projectName(basename(dir));
248
+ var names = containerNames(project);
249
+ var appUrl = values["app-url"] ?? defaultAppUrl(engine.name);
250
+ var dbPassword = randomBytes2(18).toString("hex");
251
+ var consoleUrl = `http://127.0.0.1:${port}`;
252
+ mkdirSync(join2(dir, "keys"), { recursive: true });
253
+ var appSecret = ensureAppSecret(join2(dir, "keys")).secret;
254
+ mkdirSync(join2(dir, "insight-config"), { recursive: true });
255
+ writeFileSync2(join2(dir, "docker-compose.yml"), composeYaml({ engine: engine.name, selinux: engine.selinux, project, image, port }));
256
+ writeFileSync2(
257
+ envFile,
258
+ [
259
+ "# Insight's settings, written by create-insight. Secrets: keep this file out of git (it is in .gitignore).",
260
+ "INSIGHT_CONFIG=/config/insight.yaml",
261
+ "INSIGHT_TRUSTED_KEYS=/config/insight-public-keys.json",
262
+ "INSIGHT_SETUP_HOST_DIR=./insight-config",
263
+ `INSIGHT_CONSOLE_SECRET=${randomBytes2(32).toString("hex")}`,
264
+ `INSIGHT_CONSOLE_URL=${consoleUrl}`,
265
+ `INSIGHT_READ_URL=${appUrl.replace(/\/+$/, "")}/api/insight/read`,
266
+ // Watches: the secret Insight sends your app's token route (the same as keys/insight-app-secret).
267
+ `INSIGHT_APP_SECRET=${appSecret}`,
268
+ // Insight's model, through Kaleyla, opened by the Kaleyla key below. Another model: the console, Settings › AI models.
269
+ `INSIGHT_MODEL_URL=${init_defaults_default.modelUrl}`,
270
+ `INSIGHT_MODEL=${init_defaults_default.model}`,
271
+ `INSIGHT_REVIEW_MODEL=${init_defaults_default.reviewModel}`,
272
+ "INSIGHT_MODEL_KEY=",
273
+ // A new key, when you renew: the console, Settings › Licence (it then wins over this one).
274
+ `INSIGHT_LICENCE_KEY=${key}`,
275
+ // Where create-insight upgrade puts the new app package.
276
+ `INSIGHT_APP_PACKAGES=${packageDirs.map((d) => relative(dir, d) || ".").join(",")}`,
277
+ `INSIGHT_STORE_URL=postgres://insight:${dbPassword}@insight-db:5432/insight`,
278
+ "# Insight's own database (the insight-db service)",
279
+ "POSTGRES_USER=insight",
280
+ "POSTGRES_DB=insight",
281
+ `POSTGRES_PASSWORD=${dbPassword}`,
282
+ ""
283
+ ].join("\n"),
284
+ { mode: 384 }
285
+ );
286
+ var ignore = join2(dir, ".gitignore");
287
+ var ignored = existsSync2(ignore) ? readFileSync2(ignore, "utf8").split("\n").map((l) => l.trim()) : [];
288
+ var add = ["insight.env", "keys/"].filter((l) => !ignored.includes(l) && !ignored.includes(`/${l}`));
289
+ if (add.length) appendFileSync(ignore, `${ignored.length && ignored.at(-1) !== "" ? "\n" : ""}# Insight: secrets and the app's signing key
290
+ ${add.join("\n")}
291
+ `);
292
+ done("Wrote docker-compose.yml, insight.env (secrets, kept out of git) and insight-config/");
293
+ var keysDir = join2(dir, "keys");
294
+ mkdirSync(keysDir, { recursive: true });
295
+ var existingKey = join2(keysDir, "insight-signing-key.json");
296
+ var keyPair = existsSync2(existingKey) ? { kid: JSON.parse(readFileSync2(existingKey, "utf8")).kid, publicPath: join2(keysDir, "insight-public-keys.json") } : makeKeys(keysDir, { name: project.replace(/^insight-/, "") });
297
+ copyFileSync(keyPair.publicPath, join2(dir, "insight-config", "insight-public-keys.json"));
298
+ done(`Made the app\u2019s signing key (${keyPair.kid}) in keys/; Insight trusts its public half. keys/ also holds the watch secret Insight shares with your app`);
299
+ say(" Starting Insight and its database\u2026");
300
+ var up = run(engine.compose[0], [...engine.compose.slice(1), "-p", project, "up", "-d"], { stdio: ["ignore", "ignore", "pipe"] });
301
+ if (up.status !== 0) stop(`${tool} up didn\u2019t start:
302
+ ${(up.stderr ?? "").trim()}`);
303
+ if (!await healthy(`${consoleUrl}/v1/health`, version, 12e4)) stop(`Insight didn\u2019t answer at ${consoleUrl} within 2 minutes. See why with: ${cli} logs ${names.insight}`);
304
+ done(`Insight is running at ${consoleUrl}, waiting for your app\u2019s setup`);
305
+ var link = run(cli, ["exec", names.insight, "insight-console", "link", "--name", name, "--role", "owner"]);
306
+ var signIn = /https?:\/\/\S+\/console\/sign-in\?t=\S+/.exec(`${link.stdout ?? ""}`)?.[0];
307
+ if (!signIn) stop(`The sign-in link couldn\u2019t be made: ${(link.stderr || link.stdout || "").trim()}`);
308
+ var opened = !values["no-open"] && openInBrowser(signIn);
309
+ done(opened ? "Opened the console, signed in as its Owner" : `Sign in to the console (one use, 10 minutes):
310
+ ${signIn}`);
311
+ say();
312
+ say("Your app\u2019s server needs two settings (in its .env, say):");
313
+ say(` INSIGHT_URL=${consoleUrl}`);
314
+ say(` INSIGHT_KEYS_DIR=${keysDir} (deploy this folder with the app: its signing key and watch secret)`);
315
+ if (packageDirs.length) say(`Commit vendor/kaleyla-insight-${version}.tgz with package.json: your CI installs Insight\u2019s package from it, with no key.`);
316
+ say("Next, in the console: Your app \u203A Connection. Choose how people will ask, then give the prompt to your coding agent.");
317
+ say(`Later: ${tool} down to stop, ${tool} up -d to start again, npx create-insight upgrade for a new release.`);
318
+ function detectEngine() {
319
+ const ok = (cmd, args) => run(cmd, args, { stdio: "ignore" }).status === 0;
320
+ const has = (cmd) => run(cmd, ["--version"], { stdio: "ignore" }).error === void 0;
321
+ const forced = (values.engine ?? process.env.INSIGHT_CONTAINER_ENGINE ?? "").trim().toLowerCase();
322
+ if (forced && forced !== "docker" && forced !== "podman") stop(`--engine ${forced}: use docker or podman.`);
323
+ const dockerIsPodman = has("docker") && /podman/i.test(run("docker", ["--version"]).stdout ?? "");
324
+ const name2 = forced || (ok("docker", ["info"]) ? dockerIsPodman ? "podman" : "docker" : ok("podman", ["info"]) ? "podman" : "");
325
+ if (!name2) stop("Neither Docker nor Podman is running. Start Docker Desktop (or the Docker service), or Podman (podman machine start on a Mac), then run this again.");
326
+ const cli2 = name2 === "podman" && has("podman") ? "podman" : "docker";
327
+ if (!ok(cli2, ["info"])) stop(name2 === "podman" ? "Podman isn\u2019t running. On a Mac: podman machine start. On Linux, check podman info." : "Docker isn\u2019t running. Start Docker Desktop (or the Docker service), then run this again.");
328
+ const compose = name2 === "docker" ? ok("docker", ["compose", "version"]) ? ["docker", "compose"] : null : ok(cli2, ["compose", "version"]) ? [cli2, "compose"] : ok("podman-compose", ["version"]) ? ["podman-compose"] : null;
329
+ if (!compose) stop(name2 === "docker" ? "Docker Compose isn\u2019t available. It comes with Docker Desktop; on Linux, install the docker-compose-plugin." : "Podman needs a compose tool: install podman-compose, then run this again.");
330
+ const selinux = process.platform === "linux" && existsSync2("/sys/fs/selinux/enforce") && readFileSync2("/sys/fs/selinux/enforce", "utf8").trim() === "1";
331
+ return { name: name2, cli: cli2, compose, selinux };
332
+ }
333
+ function engineArch() {
334
+ const out = (cli === "podman" ? run(cli, ["info", "--format", "{{.Host.Arch}}"]) : run(cli, ["info", "--format", "{{.Architecture}}"])).stdout?.trim() ?? "";
335
+ const a = out || hostArch();
336
+ return /arm64|aarch64/i.test(a) ? "arm64" : /x86_64|amd64|x64/i.test(a) ? "amd64" : a;
337
+ }
338
+ async function download(file) {
339
+ const target = join2(cache, file.name);
340
+ if (existsSync2(target) && statSync(target).size === file.size && sha256(target) === file.sha256) {
341
+ done(`${file.name} (already downloaded)`);
342
+ return target;
343
+ }
344
+ const partial = `${target}.part`;
345
+ const r = await fetch(file.url);
346
+ if (!r.ok || !r.body) stop(`${file.name} couldn\u2019t be downloaded (${r.status}). Run this again for fresh links.`);
347
+ let got = 0;
348
+ let shown = -1;
349
+ const meter = new TransformStream({
350
+ transform(chunk, controller) {
351
+ got += chunk.length;
352
+ const pct = Math.floor(got / file.size * 100);
353
+ if (process.stdout.isTTY && pct !== shown && pct % 5 === 0) {
354
+ shown = pct;
355
+ process.stdout.write(`\r Downloading ${file.name}: ${pct}%`);
356
+ }
357
+ controller.enqueue(chunk);
358
+ }
359
+ });
360
+ await pipeline(Readable.fromWeb(r.body.pipeThrough(meter)), createWriteStream(partial));
361
+ if (process.stdout.isTTY) process.stdout.write("\r\x1B[K");
362
+ if (statSync(partial).size !== file.size || sha256(partial) !== file.sha256) {
363
+ rmSync(partial, { force: true });
364
+ stop(`${file.name} didn\u2019t download whole (its checksum doesn\u2019t match). Run this again.`);
365
+ }
366
+ renameSync(partial, target);
367
+ done(`Downloaded ${file.name} (${(file.size / 1e6).toFixed(1)} MB), checksum checked`);
368
+ return target;
369
+ }
370
+ function sha256(path) {
371
+ return createHash("sha256").update(readFileSync2(path)).digest("hex");
372
+ }
373
+ function addPackage(target) {
374
+ if (!existsSync2(join2(target, "package.json"))) stop(`${relative(dir, target) || "This folder"} has no package.json. Run this from your app\u2019s folder, or add --no-package for an app that isn\u2019t on Node.js.`);
375
+ const vendor = join2(target, "vendor");
376
+ mkdirSync(vendor, { recursive: true });
377
+ for (const old of readdirSync(vendor).filter((n) => /^kaleyla-insight-.+\.tgz$/.test(n))) rmSync(join2(vendor, old));
378
+ const file = `kaleyla-insight-${version}.tgz`;
379
+ copyFileSync(appPath, join2(vendor, file));
380
+ const spec = `file:vendor/${file}`;
381
+ const lock = (n) => existsSync2(join2(target, n));
382
+ const [pm, args] = lock("pnpm-lock.yaml") ? ["pnpm", ["add", `@kaleyla/insight@${spec}`]] : lock("yarn.lock") ? ["yarn", ["add", `@kaleyla/insight@${spec}`]] : lock("bun.lockb") || lock("bun.lock") ? ["bun", ["add", `@kaleyla/insight@${spec}`]] : ["npm", ["install", "--save-exact", `@kaleyla/insight@${spec}`]];
383
+ const r = spawnSync(pm, args, { cwd: target, encoding: "utf8", shell: process.platform === "win32" });
384
+ if (r.status !== 0) stop(`${pm} couldn\u2019t add @kaleyla/insight in ${relative(dir, target) || "this folder"}:
385
+ ${(r.stderr || r.stdout || "").trim().split("\n").slice(-8).join("\n")}`);
386
+ done(`Added @kaleyla/insight ${version} to ${relative(dir, target) || "the app"} (vendor/${file}, with ${pm})`);
387
+ }
388
+ function askHidden(question) {
389
+ return new Promise((resolveAnswer) => {
390
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
391
+ let shown = false;
392
+ rl._writeToOutput = (s) => {
393
+ if (!shown) {
394
+ process.stdout.write(s);
395
+ shown = true;
396
+ } else if (s.includes("\n")) process.stdout.write("\n");
397
+ else process.stdout.write("\u2022".repeat(s.length ? 1 : 0));
398
+ };
399
+ rl.question(question, (answer) => {
400
+ rl.close();
401
+ resolveAnswer(answer);
402
+ });
403
+ });
404
+ }
405
+ function freePort(from) {
406
+ return new Promise((resolvePort) => {
407
+ const tryPort = (p) => {
408
+ const s = createServer();
409
+ s.once("error", () => tryPort(p + 1));
410
+ s.listen(p, "127.0.0.1", () => s.close(() => resolvePort(p)));
411
+ };
412
+ tryPort(from);
413
+ });
414
+ }
415
+ async function healthy(url, want, ms) {
416
+ const end = Date.now() + ms;
417
+ while (Date.now() < end) {
418
+ try {
419
+ const r = await fetch(url);
420
+ if (r.ok && (await r.json()).version === want) return true;
421
+ } catch {
422
+ }
423
+ await new Promise((r) => setTimeout(r, 1e3));
424
+ }
425
+ return false;
426
+ }
427
+ function openInBrowser(link2) {
428
+ const cmd = process.platform === "darwin" ? ["open", [link2]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", link2]] : ["xdg-open", [link2]];
429
+ return spawnSync(cmd[0], cmd[1], { stdio: "ignore" }).status === 0;
430
+ }
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "create-insight",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.21.1",
4
+ "description": "Sets Insight up beside your app, with your Kaleyla key: npx create-insight",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "create-insight": "./create-insight.mjs"
9
+ },
10
+ "files": [
11
+ "create-insight.mjs",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ }
17
+ }