@soron-ai/next 0.0.0-stage → 0.1.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.
package/dist/cli.js ADDED
@@ -0,0 +1,3679 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ try {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ } catch (e) {
12
+ throw mod = 0, e;
13
+ }
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // ../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
33
+ var require_src = __commonJS({
34
+ "../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
35
+ "use strict";
36
+ var ESC2 = "\x1B";
37
+ var CSI2 = `${ESC2}[`;
38
+ var beep = "\x07";
39
+ var cursor3 = {
40
+ to(x, y2) {
41
+ if (!y2) return `${CSI2}${x + 1}G`;
42
+ return `${CSI2}${y2 + 1};${x + 1}H`;
43
+ },
44
+ move(x, y2) {
45
+ let ret = "";
46
+ if (x < 0) ret += `${CSI2}${-x}D`;
47
+ else if (x > 0) ret += `${CSI2}${x}C`;
48
+ if (y2 < 0) ret += `${CSI2}${-y2}A`;
49
+ else if (y2 > 0) ret += `${CSI2}${y2}B`;
50
+ return ret;
51
+ },
52
+ up: (count = 1) => `${CSI2}${count}A`,
53
+ down: (count = 1) => `${CSI2}${count}B`,
54
+ forward: (count = 1) => `${CSI2}${count}C`,
55
+ backward: (count = 1) => `${CSI2}${count}D`,
56
+ nextLine: (count = 1) => `${CSI2}E`.repeat(count),
57
+ prevLine: (count = 1) => `${CSI2}F`.repeat(count),
58
+ left: `${CSI2}G`,
59
+ hide: `${CSI2}?25l`,
60
+ show: `${CSI2}?25h`,
61
+ save: `${ESC2}7`,
62
+ restore: `${ESC2}8`
63
+ };
64
+ var scroll = {
65
+ up: (count = 1) => `${CSI2}S`.repeat(count),
66
+ down: (count = 1) => `${CSI2}T`.repeat(count)
67
+ };
68
+ var erase3 = {
69
+ screen: `${CSI2}2J`,
70
+ up: (count = 1) => `${CSI2}1J`.repeat(count),
71
+ down: (count = 1) => `${CSI2}J`.repeat(count),
72
+ line: `${CSI2}2K`,
73
+ lineEnd: `${CSI2}K`,
74
+ lineStart: `${CSI2}1K`,
75
+ lines(count) {
76
+ let clear = "";
77
+ for (let i2 = 0; i2 < count; i2++)
78
+ clear += this.line + (i2 < count - 1 ? cursor3.up() : "");
79
+ if (count)
80
+ clear += cursor3.left;
81
+ return clear;
82
+ }
83
+ };
84
+ module.exports = { cursor: cursor3, scroll, erase: erase3, beep };
85
+ }
86
+ });
87
+
88
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
89
+ var require_picocolors = __commonJS({
90
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports, module) {
91
+ var p = process || {};
92
+ var argv = p.argv || [];
93
+ var env = p.env || {};
94
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
95
+ var formatter = (open, close, replace = open) => (input) => {
96
+ let string = "" + input, index = string.indexOf(close, open.length);
97
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
98
+ };
99
+ var replaceClose = (string, close, replace, index) => {
100
+ let result = "", cursor3 = 0;
101
+ do {
102
+ result += string.substring(cursor3, index) + replace;
103
+ cursor3 = index + close.length;
104
+ index = string.indexOf(close, cursor3);
105
+ } while (~index);
106
+ return result + string.substring(cursor3);
107
+ };
108
+ var createColors = (enabled = isColorSupported) => {
109
+ let f = enabled ? formatter : () => String;
110
+ return {
111
+ isColorSupported: enabled,
112
+ reset: f("\x1B[0m", "\x1B[0m"),
113
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
114
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
115
+ italic: f("\x1B[3m", "\x1B[23m"),
116
+ underline: f("\x1B[4m", "\x1B[24m"),
117
+ inverse: f("\x1B[7m", "\x1B[27m"),
118
+ hidden: f("\x1B[8m", "\x1B[28m"),
119
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
120
+ black: f("\x1B[30m", "\x1B[39m"),
121
+ red: f("\x1B[31m", "\x1B[39m"),
122
+ green: f("\x1B[32m", "\x1B[39m"),
123
+ yellow: f("\x1B[33m", "\x1B[39m"),
124
+ blue: f("\x1B[34m", "\x1B[39m"),
125
+ magenta: f("\x1B[35m", "\x1B[39m"),
126
+ cyan: f("\x1B[36m", "\x1B[39m"),
127
+ white: f("\x1B[37m", "\x1B[39m"),
128
+ gray: f("\x1B[90m", "\x1B[39m"),
129
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
130
+ bgRed: f("\x1B[41m", "\x1B[49m"),
131
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
132
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
133
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
134
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
135
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
136
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
137
+ blackBright: f("\x1B[90m", "\x1B[39m"),
138
+ redBright: f("\x1B[91m", "\x1B[39m"),
139
+ greenBright: f("\x1B[92m", "\x1B[39m"),
140
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
141
+ blueBright: f("\x1B[94m", "\x1B[39m"),
142
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
143
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
144
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
145
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
146
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
147
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
148
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
149
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
150
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
151
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
152
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
153
+ };
154
+ };
155
+ module.exports = createColors();
156
+ module.exports.createColors = createColors;
157
+ }
158
+ });
159
+
160
+ // src/cli.ts
161
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
162
+ import { join as join4 } from "node:path";
163
+ import { parseArgs } from "node:util";
164
+
165
+ // src/version.ts
166
+ function olderThan(version, floor) {
167
+ const [a2, b] = [version, floor].map((v) => v.split(/[.-]/).slice(0, 3).map(Number));
168
+ for (let i2 = 0; i2 < 3; i2++) {
169
+ const x = a2?.[i2] ?? 0;
170
+ const y2 = b?.[i2] ?? 0;
171
+ if (Number.isNaN(x)) return true;
172
+ if (x !== y2) return x < y2;
173
+ }
174
+ return false;
175
+ }
176
+
177
+ // src/protocol.ts
178
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
179
+ var CONFIG_FILE = "soron.config.json";
180
+ var VERSION_HEADER = "x-soron-version";
181
+ var IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]{0,62}$/;
182
+ var wordsOf = (name) => name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
183
+ var identifiers = (v, min, max) => {
184
+ if (!Array.isArray(v) || v.length < min || v.length > max) return void 0;
185
+ const out = [];
186
+ for (const x of v) {
187
+ if (typeof x !== "string" || !IDENTIFIER.test(x)) return void 0;
188
+ out.push(x);
189
+ }
190
+ return out;
191
+ };
192
+ var only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
193
+ var SECRET_TABLES = /* @__PURE__ */ new Set([
194
+ ...["session", "sessions", "user_session", "user_sessions", "account", "accounts", "verification", "verifications"],
195
+ ...["verificationtoken", "verification_token", "verification_tokens", "two_factor", "twofactor", "passkey", "passkeys"],
196
+ ...["apikey", "apikeys", "api_key", "api_keys", "jwks", "authenticator", "authenticators", "two_factors", "twofactors"],
197
+ ...["invitation", "invitations", "magic_link", "magic_links", "magiclink", "magiclinks"]
198
+ ]);
199
+ var SECRET_WORDS = /* @__PURE__ */ new Set([
200
+ ...["password", "passwd", "pwd", "passphrase", "token", "tokens", "secret", "secrets", "hash", "hashed", "salt"],
201
+ ...["otp", "totp", "mfa", "pin", "jwt", "key", "keys", "credential", "credentials", "passcode", "pw", "cvv", "cvc", "iban"],
202
+ ...["seed", "nonce", "hmac", "bearer", "ciphertext", "encrypted"]
203
+ ]);
204
+ var SECRET_INSIDE = /password|passwd|pwd|passcode|token|secret|apikey|privatekey|jwt|ciphertext|encrypted|card_?number|magic_?link|(recovery|backup|verification|reset|confirmation|auth|login)_codes?/;
205
+ var isSecretColumn = (name) => {
206
+ const words = wordsOf(name);
207
+ return words.split("_").some((w) => SECRET_WORDS.has(w.replace(/\d+$/, ""))) || SECRET_INSIDE.test(words) || SECRET_INSIDE.test(name.toLowerCase());
208
+ };
209
+ var isSecretTable = (table) => {
210
+ const t2 = wordsOf(table);
211
+ return SECRET_TABLES.has(t2) || SECRET_TABLES.has(table.toLowerCase()) || [...SECRET_TABLES].some((s) => t2.endsWith(`_${s}`) || t2.startsWith(`${s}_`)) || isSecretColumn(table);
212
+ };
213
+ function secretIn(reads) {
214
+ for (const { table, columns } of reads) {
215
+ if (isSecretTable(table)) return table;
216
+ const column = columns.find(isSecretColumn);
217
+ if (column !== void 0) return `${table}.${column}`;
218
+ }
219
+ return void 0;
220
+ }
221
+ function nameOutside(config) {
222
+ for (const [table, columns] of Object.entries(config.names)) {
223
+ const read = config.reads.find((r2) => r2.table === table);
224
+ const column = columns.find((c2) => !read?.columns.includes(c2));
225
+ if (column !== void 0) return `${table}.${column}`;
226
+ }
227
+ return void 0;
228
+ }
229
+ function readConfig(value) {
230
+ const config = configShape(value);
231
+ return config && secretIn(config.reads) === void 0 && nameOutside(config) === void 0 ? config : void 0;
232
+ }
233
+ function configProblem(value) {
234
+ const config = configShape(value);
235
+ if (!config) return "not valid: an unknown key, a name outside letters, digits and _, or a list past its bound";
236
+ const secret = secretIn(config.reads);
237
+ if (secret !== void 0) return `lists ${secret}, which holds a secret: Soron never reads one`;
238
+ const outside = nameOutside(config);
239
+ return outside === void 0 ? void 0 : `masks ${outside}, which it does not read: a masked name is a column of a read, spelled as the read spells it`;
240
+ }
241
+ function configShape(value) {
242
+ if (!isObject(value) || !only(value, ["$schema", "language", "reads", "names"])) return void 0;
243
+ const { $schema, language: language2, reads = [], names = {} } = value;
244
+ if ($schema !== void 0 && (typeof $schema !== "string" || $schema.length > 500)) return void 0;
245
+ if (language2 !== "fr" && language2 !== "en") return void 0;
246
+ if (!Array.isArray(reads) || reads.length > 50 || !isObject(names)) return void 0;
247
+ const config = { language: language2, reads: [], names: {} };
248
+ for (const r2 of reads) {
249
+ if (!isObject(r2) || !only(r2, ["table", "columns"]) || typeof r2["table"] !== "string" || !IDENTIFIER.test(r2["table"])) return void 0;
250
+ const columns = identifiers(r2["columns"], 1, 100);
251
+ if (!columns) return void 0;
252
+ config.reads.push({ table: r2["table"], columns });
253
+ }
254
+ for (const [table, list] of Object.entries(names)) {
255
+ const columns = identifiers(list, 0, 100);
256
+ if (!IDENTIFIER.test(table) || !columns) return void 0;
257
+ config.names[table] = columns;
258
+ }
259
+ return config;
260
+ }
261
+
262
+ // src/setup/program.ts
263
+ import { spawn } from "node:child_process";
264
+ import { existsSync } from "node:fs";
265
+ import { delimiter, extname, join } from "node:path";
266
+ var ProgramError = class extends Error {
267
+ program;
268
+ exitCode;
269
+ stderr;
270
+ constructor(program, exitCode, stderr, message) {
271
+ super(message);
272
+ this.program = program;
273
+ this.exitCode = exitCode;
274
+ this.stderr = stderr;
275
+ }
276
+ };
277
+ var windowsScript = (name, env) => {
278
+ const extensions = (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").map((e) => e.toLowerCase());
279
+ for (const dir of (env["PATH"] ?? env["Path"] ?? "").split(delimiter)) {
280
+ for (const ext of extensions) {
281
+ const file = join(dir, `${name}${ext}`);
282
+ if (existsSync(file)) return ext === ".cmd" || ext === ".bat" ? file : void 0;
283
+ }
284
+ }
285
+ return void 0;
286
+ };
287
+ var UNSAFE_FOR_CMD = /[%"\r\n]/;
288
+ var quoted = (a2) => `"${a2}"`;
289
+ function runProgram(name, args, o) {
290
+ const env = o.env ?? process.env;
291
+ const script = process.platform === "win32" && extname(name) === "" ? windowsScript(name, env) : void 0;
292
+ if (script && args.some((a2) => UNSAFE_FOR_CMD.test(a2))) return Promise.reject(new ProgramError(name, null, "", `${name}: an argument cmd.exe cannot pass as it is`));
293
+ const child = script ? spawn(env["ComSpec"] ?? "cmd.exe", ["/d", "/s", "/c", `"${[script, ...args].map(quoted).join(" ")}"`], { cwd: o.cwd, env, windowsVerbatimArguments: true, windowsHide: true, ...o.signal ? { signal: o.signal } : {} }) : spawn(name, args, { cwd: o.cwd, env, windowsHide: true, ...o.signal ? { signal: o.signal } : {} });
294
+ return new Promise((resolve2, reject) => {
295
+ const out = [];
296
+ const err = [];
297
+ child.stdout.on("data", (b) => out.push(b));
298
+ child.stderr.on("data", (b) => err.push(b));
299
+ child.on("error", (e) => reject(new ProgramError(name, null, "", "code" in e && e.code === "ENOENT" ? `${name} is not installed` : e.message)));
300
+ child.on("close", (code) => {
301
+ const stderr = Buffer.concat(err).toString("utf8");
302
+ if (code === 0) resolve2(Buffer.concat(out).toString("utf8"));
303
+ else reject(new ProgramError(name, code, stderr, `${name} ${args.slice(0, 2).join(" ")} failed (${code})`));
304
+ });
305
+ child.stdin.on("error", () => void 0);
306
+ if (o.input === void 0) child.stdin.end();
307
+ else child.stdin.end(o.input);
308
+ });
309
+ }
310
+
311
+ // ../../node_modules/.pnpm/@clack+core@1.5.1/node_modules/@clack/core/dist/index.mjs
312
+ import { styleText } from "node:util";
313
+ import { stdout, stdin } from "node:process";
314
+ import l__default from "node:readline";
315
+
316
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
317
+ var getCodePointsLength = /* @__PURE__ */ (() => {
318
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
319
+ return (input) => {
320
+ let surrogatePairsNr = 0;
321
+ SURROGATE_PAIR_RE.lastIndex = 0;
322
+ while (SURROGATE_PAIR_RE.test(input)) {
323
+ surrogatePairsNr += 1;
324
+ }
325
+ return input.length - surrogatePairsNr;
326
+ };
327
+ })();
328
+ var isFullWidth = (x) => {
329
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
330
+ };
331
+ var isWideNotCJKTNotEmoji = (x) => {
332
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
333
+ };
334
+
335
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js
336
+ var ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
337
+ var CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
338
+ var CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu;
339
+ var TAB_RE = /\t{1,1000}/y;
340
+ var EMOJI_RE = new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*", "yu");
341
+ var LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
342
+ var MODIFIER_RE = new RegExp("\\p{M}+", "gu");
343
+ var NO_TRUNCATION = { limit: Infinity, ellipsis: "" };
344
+ var getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
345
+ const LIMIT = truncationOptions.limit ?? Infinity;
346
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
347
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);
348
+ const ANSI_WIDTH = 0;
349
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
350
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
351
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
352
+ const FULL_WIDTH_WIDTH = 2;
353
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
354
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
355
+ const PARSE_BLOCKS = [
356
+ [LATIN_RE, REGULAR_WIDTH],
357
+ [ANSI_RE, ANSI_WIDTH],
358
+ [CONTROL_RE, CONTROL_WIDTH],
359
+ [TAB_RE, TAB_WIDTH],
360
+ [EMOJI_RE, EMOJI_WIDTH],
361
+ [CJKT_WIDE_RE, WIDE_WIDTH]
362
+ ];
363
+ let indexPrev = 0;
364
+ let index = 0;
365
+ let length = input.length;
366
+ let lengthExtra = 0;
367
+ let truncationEnabled = false;
368
+ let truncationIndex = length;
369
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
370
+ let unmatchedStart = 0;
371
+ let unmatchedEnd = 0;
372
+ let width = 0;
373
+ let widthExtra = 0;
374
+ outer: while (true) {
375
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
376
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
377
+ lengthExtra = 0;
378
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
379
+ const codePoint = char.codePointAt(0) || 0;
380
+ if (isFullWidth(codePoint)) {
381
+ widthExtra = FULL_WIDTH_WIDTH;
382
+ } else if (isWideNotCJKTNotEmoji(codePoint)) {
383
+ widthExtra = WIDE_WIDTH;
384
+ } else {
385
+ widthExtra = REGULAR_WIDTH;
386
+ }
387
+ if (width + widthExtra > truncationLimit) {
388
+ truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
389
+ }
390
+ if (width + widthExtra > LIMIT) {
391
+ truncationEnabled = true;
392
+ break outer;
393
+ }
394
+ lengthExtra += char.length;
395
+ width += widthExtra;
396
+ }
397
+ unmatchedStart = unmatchedEnd = 0;
398
+ }
399
+ if (index >= length) {
400
+ break outer;
401
+ }
402
+ for (let i2 = 0, l = PARSE_BLOCKS.length; i2 < l; i2++) {
403
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i2];
404
+ BLOCK_RE.lastIndex = index;
405
+ if (BLOCK_RE.test(input)) {
406
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
407
+ widthExtra = lengthExtra * BLOCK_WIDTH;
408
+ if (width + widthExtra > truncationLimit) {
409
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
410
+ }
411
+ if (width + widthExtra > LIMIT) {
412
+ truncationEnabled = true;
413
+ break outer;
414
+ }
415
+ width += widthExtra;
416
+ unmatchedStart = indexPrev;
417
+ unmatchedEnd = index;
418
+ index = indexPrev = BLOCK_RE.lastIndex;
419
+ continue outer;
420
+ }
421
+ }
422
+ index += 1;
423
+ }
424
+ return {
425
+ width: truncationEnabled ? truncationLimit : width,
426
+ index: truncationEnabled ? truncationIndex : length,
427
+ truncated: truncationEnabled,
428
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
429
+ };
430
+ };
431
+ var dist_default = getStringTruncatedWidth;
432
+
433
+ // ../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js
434
+ var NO_TRUNCATION2 = {
435
+ limit: Infinity,
436
+ ellipsis: "",
437
+ ellipsisWidth: 0
438
+ };
439
+ var fastStringWidth = (input, options = {}) => {
440
+ return dist_default(input, NO_TRUNCATION2, options).width;
441
+ };
442
+ var dist_default2 = fastStringWidth;
443
+
444
+ // ../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js
445
+ var ESC = "\x1B";
446
+ var CSI = "\x9B";
447
+ var END_CODE = 39;
448
+ var ANSI_ESCAPE_BELL = "\x07";
449
+ var ANSI_CSI = "[";
450
+ var ANSI_OSC = "]";
451
+ var ANSI_SGR_TERMINATOR = "m";
452
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
453
+ var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
454
+ var getClosingCode = (openingCode) => {
455
+ if (openingCode >= 30 && openingCode <= 37)
456
+ return 39;
457
+ if (openingCode >= 90 && openingCode <= 97)
458
+ return 39;
459
+ if (openingCode >= 40 && openingCode <= 47)
460
+ return 49;
461
+ if (openingCode >= 100 && openingCode <= 107)
462
+ return 49;
463
+ if (openingCode === 1 || openingCode === 2)
464
+ return 22;
465
+ if (openingCode === 3)
466
+ return 23;
467
+ if (openingCode === 4)
468
+ return 24;
469
+ if (openingCode === 7)
470
+ return 27;
471
+ if (openingCode === 8)
472
+ return 28;
473
+ if (openingCode === 9)
474
+ return 29;
475
+ if (openingCode === 0)
476
+ return 0;
477
+ return void 0;
478
+ };
479
+ var wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
480
+ var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
481
+ var wrapWord = (rows, word, columns) => {
482
+ const characters = word[Symbol.iterator]();
483
+ let isInsideEscape = false;
484
+ let isInsideLinkEscape = false;
485
+ let lastRow = rows.at(-1);
486
+ let visible = lastRow === void 0 ? 0 : dist_default2(lastRow);
487
+ let currentCharacter = characters.next();
488
+ let nextCharacter = characters.next();
489
+ let rawCharacterIndex = 0;
490
+ while (!currentCharacter.done) {
491
+ const character = currentCharacter.value;
492
+ const characterLength = dist_default2(character);
493
+ if (visible + characterLength <= columns) {
494
+ rows[rows.length - 1] += character;
495
+ } else {
496
+ rows.push(character);
497
+ visible = 0;
498
+ }
499
+ if (character === ESC || character === CSI) {
500
+ isInsideEscape = true;
501
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
502
+ }
503
+ if (isInsideEscape) {
504
+ if (isInsideLinkEscape) {
505
+ if (character === ANSI_ESCAPE_BELL) {
506
+ isInsideEscape = false;
507
+ isInsideLinkEscape = false;
508
+ }
509
+ } else if (character === ANSI_SGR_TERMINATOR) {
510
+ isInsideEscape = false;
511
+ }
512
+ } else {
513
+ visible += characterLength;
514
+ if (visible === columns && !nextCharacter.done) {
515
+ rows.push("");
516
+ visible = 0;
517
+ }
518
+ }
519
+ currentCharacter = nextCharacter;
520
+ nextCharacter = characters.next();
521
+ rawCharacterIndex += character.length;
522
+ }
523
+ lastRow = rows.at(-1);
524
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) {
525
+ rows[rows.length - 2] += rows.pop();
526
+ }
527
+ };
528
+ var stringVisibleTrimSpacesRight = (string) => {
529
+ const words = string.split(" ");
530
+ let last = words.length;
531
+ while (last) {
532
+ if (dist_default2(words[last - 1])) {
533
+ break;
534
+ }
535
+ last--;
536
+ }
537
+ if (last === words.length) {
538
+ return string;
539
+ }
540
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
541
+ };
542
+ var exec = (string, columns, options = {}) => {
543
+ if (options.trim !== false && string.trim() === "") {
544
+ return "";
545
+ }
546
+ let returnValue = "";
547
+ let escapeCode;
548
+ let escapeUrl;
549
+ const words = string.split(" ");
550
+ let rows = [""];
551
+ let rowLength = 0;
552
+ for (let index = 0; index < words.length; index++) {
553
+ const word = words[index];
554
+ if (options.trim !== false) {
555
+ const row = rows.at(-1) ?? "";
556
+ const trimmed = row.trimStart();
557
+ if (row.length !== trimmed.length) {
558
+ rows[rows.length - 1] = trimmed;
559
+ rowLength = dist_default2(trimmed);
560
+ }
561
+ }
562
+ if (index !== 0) {
563
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
564
+ rows.push("");
565
+ rowLength = 0;
566
+ }
567
+ if (rowLength || options.trim === false) {
568
+ rows[rows.length - 1] += " ";
569
+ rowLength++;
570
+ }
571
+ }
572
+ const wordLength = dist_default2(word);
573
+ if (options.hard && wordLength > columns) {
574
+ const remainingColumns = columns - rowLength;
575
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
576
+ const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
577
+ if (breaksStartingNextLine < breaksStartingThisLine) {
578
+ rows.push("");
579
+ }
580
+ wrapWord(rows, word, columns);
581
+ rowLength = dist_default2(rows.at(-1) ?? "");
582
+ continue;
583
+ }
584
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
585
+ if (options.wordWrap === false && rowLength < columns) {
586
+ wrapWord(rows, word, columns);
587
+ rowLength = dist_default2(rows.at(-1) ?? "");
588
+ continue;
589
+ }
590
+ rows.push("");
591
+ rowLength = 0;
592
+ }
593
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
594
+ wrapWord(rows, word, columns);
595
+ rowLength = dist_default2(rows.at(-1) ?? "");
596
+ continue;
597
+ }
598
+ rows[rows.length - 1] += word;
599
+ rowLength += wordLength;
600
+ }
601
+ if (options.trim !== false) {
602
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
603
+ }
604
+ const preString = rows.join("\n");
605
+ let inSurrogate = false;
606
+ for (let i2 = 0; i2 < preString.length; i2++) {
607
+ const character = preString[i2];
608
+ returnValue += character;
609
+ if (!inSurrogate) {
610
+ inSurrogate = character >= "\uD800" && character <= "\uDBFF";
611
+ if (inSurrogate) {
612
+ continue;
613
+ }
614
+ } else {
615
+ inSurrogate = false;
616
+ }
617
+ if (character === ESC || character === CSI) {
618
+ GROUP_REGEX.lastIndex = i2 + 1;
619
+ const groupsResult = GROUP_REGEX.exec(preString);
620
+ const groups = groupsResult?.groups;
621
+ if (groups?.code !== void 0) {
622
+ const code = Number.parseFloat(groups.code);
623
+ escapeCode = code === END_CODE ? void 0 : code;
624
+ } else if (groups?.uri !== void 0) {
625
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
626
+ }
627
+ }
628
+ if (preString[i2 + 1] === "\n") {
629
+ if (escapeUrl) {
630
+ returnValue += wrapAnsiHyperlink("");
631
+ }
632
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
633
+ if (escapeCode && closingCode) {
634
+ returnValue += wrapAnsiCode(closingCode);
635
+ }
636
+ } else if (character === "\n") {
637
+ if (escapeCode && getClosingCode(escapeCode)) {
638
+ returnValue += wrapAnsiCode(escapeCode);
639
+ }
640
+ if (escapeUrl) {
641
+ returnValue += wrapAnsiHyperlink(escapeUrl);
642
+ }
643
+ }
644
+ }
645
+ return returnValue;
646
+ };
647
+ var CRLF_OR_LF = /\r?\n/;
648
+ function wrapAnsi(string, columns, options) {
649
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
650
+ }
651
+
652
+ // ../../node_modules/.pnpm/@clack+core@1.5.1/node_modules/@clack/core/dist/index.mjs
653
+ var import_sisteransi = __toESM(require_src(), 1);
654
+ function findCursor(s, o, l) {
655
+ if (!l.some((r2) => !r2.disabled))
656
+ return s;
657
+ const t2 = s + o, n3 = Math.max(l.length - 1, 0), e = t2 < 0 ? n3 : t2 > n3 ? 0 : t2;
658
+ return l[e]?.disabled ? findCursor(e, o < 0 ? -1 : 1, l) : e;
659
+ }
660
+ var a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
661
+ var t = [
662
+ "January",
663
+ "February",
664
+ "March",
665
+ "April",
666
+ "May",
667
+ "June",
668
+ "July",
669
+ "August",
670
+ "September",
671
+ "October",
672
+ "November",
673
+ "December"
674
+ ];
675
+ var settings = {
676
+ actions: new Set(a$1),
677
+ aliases: /* @__PURE__ */ new Map([
678
+ // vim support
679
+ ["k", "up"],
680
+ ["j", "down"],
681
+ ["h", "left"],
682
+ ["l", "right"],
683
+ ["", "cancel"],
684
+ // opinionated defaults!
685
+ ["escape", "cancel"]
686
+ ]),
687
+ messages: {
688
+ cancel: "Canceled",
689
+ error: "Something went wrong"
690
+ },
691
+ withGuide: true,
692
+ accessible: void 0,
693
+ date: {
694
+ monthNames: [...t],
695
+ messages: {
696
+ required: "Please enter a valid date",
697
+ invalidMonth: "There are only 12 months in a year",
698
+ invalidDay: (n3, e) => `There are only ${n3} days in ${e}`,
699
+ afterMin: (n3) => `Date must be on or after ${n3.toISOString().slice(0, 10)}`,
700
+ beforeMax: (n3) => `Date must be on or before ${n3.toISOString().slice(0, 10)}`
701
+ }
702
+ }
703
+ };
704
+ function isAccessible(n3) {
705
+ if (n3 !== void 0) return n3;
706
+ if (settings.accessible !== void 0) return settings.accessible;
707
+ const e = process.env.ACCESSIBLE;
708
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
709
+ }
710
+ function isActionKey(n3, e) {
711
+ if (typeof n3 == "string")
712
+ return settings.aliases.get(n3) === e;
713
+ for (const s of n3)
714
+ if (s !== void 0 && isActionKey(s, e))
715
+ return true;
716
+ return false;
717
+ }
718
+ function diffLines(i2, s) {
719
+ if (i2 === s) return;
720
+ const e = i2.split(`
721
+ `), t2 = s.split(`
722
+ `), r2 = Math.max(e.length, t2.length), f = [];
723
+ for (let n3 = 0; n3 < r2; n3++)
724
+ e[n3] !== t2[n3] && f.push(n3);
725
+ return {
726
+ lines: f,
727
+ numLinesBefore: e.length,
728
+ numLinesAfter: t2.length,
729
+ numLines: r2
730
+ };
731
+ }
732
+ var R = globalThis.process.platform.startsWith("win");
733
+ var CANCEL_SYMBOL = /* @__PURE__ */ Symbol("clack:cancel");
734
+ function setRawMode(e, r2) {
735
+ const o = e;
736
+ o.isTTY && o.setRawMode(r2);
737
+ }
738
+ var getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
739
+ var getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
740
+ function wrapTextWithPrefix(e, r2, o, n3 = o, s = o, t2) {
741
+ const f = getColumns(e ?? stdout);
742
+ return wrapAnsi(r2, f - o.length, {
743
+ hard: true,
744
+ trim: false
745
+ }).split(`
746
+ `).map((c2, i2, m2) => {
747
+ const d = t2 ? t2(c2, i2) : c2;
748
+ return i2 === 0 ? `${n3}${d}` : i2 === m2.length - 1 ? `${s}${d}` : `${o}${d}`;
749
+ }).join(`
750
+ `);
751
+ }
752
+ function runValidation(e, a2) {
753
+ if ("~standard" in e) {
754
+ const n3 = e["~standard"].validate(a2);
755
+ return n3 instanceof Promise ? n3.then((r2) => r2.issues?.at(0)?.message) : n3.issues?.at(0)?.message;
756
+ }
757
+ return e(a2);
758
+ }
759
+ var y = class {
760
+ input;
761
+ output;
762
+ _abortSignal;
763
+ rl;
764
+ opts;
765
+ _render;
766
+ _track = false;
767
+ _prevFrame = "";
768
+ _subscribers = /* @__PURE__ */ new Map();
769
+ _cursor = 0;
770
+ state = "initial";
771
+ error = "";
772
+ value;
773
+ userInput = "";
774
+ /**
775
+ * Whether accessible (static, screen-reader friendly) output is enabled for
776
+ * this prompt, resolved from the `accessible` option, the global setting,
777
+ * and the `ACCESSIBLE` env var.
778
+ */
779
+ get accessible() {
780
+ return isAccessible(this.opts.accessible);
781
+ }
782
+ constructor(t2, e = true) {
783
+ const { input: i2 = stdin, output: s = stdout, render: r2, signal: n3, ...o } = t2;
784
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r2.bind(this), this._track = e, this._abortSignal = n3, this.input = i2, this.output = s;
785
+ }
786
+ /**
787
+ * Unsubscribe all listeners
788
+ */
789
+ unsubscribe() {
790
+ this._subscribers.clear();
791
+ }
792
+ /**
793
+ * Set a subscriber with opts
794
+ * @param event - The event name
795
+ */
796
+ setSubscriber(t2, e) {
797
+ const i2 = this._subscribers.get(t2) ?? [];
798
+ i2.push(e), this._subscribers.set(t2, i2);
799
+ }
800
+ /**
801
+ * Subscribe to an event
802
+ * @param event - The event name
803
+ * @param cb - The callback
804
+ */
805
+ on(t2, e) {
806
+ this.setSubscriber(t2, { cb: e });
807
+ }
808
+ /**
809
+ * Subscribe to an event once
810
+ * @param event - The event name
811
+ * @param cb - The callback
812
+ */
813
+ once(t2, e) {
814
+ this.setSubscriber(t2, { cb: e, once: true });
815
+ }
816
+ /**
817
+ * Emit an event with data
818
+ * @param event - The event name
819
+ * @param data - The data to pass to the callback
820
+ */
821
+ emit(t2, ...e) {
822
+ const i2 = this._subscribers.get(t2) ?? [], s = [];
823
+ for (const r2 of i2)
824
+ r2.cb(...e), r2.once && s.push(() => i2.splice(i2.indexOf(r2), 1));
825
+ for (const r2 of s)
826
+ r2();
827
+ }
828
+ prompt() {
829
+ return new Promise((t2) => {
830
+ if (this._abortSignal) {
831
+ if (this._abortSignal.aborted)
832
+ return this.state = "cancel", this.close(), t2(CANCEL_SYMBOL);
833
+ this._abortSignal.addEventListener(
834
+ "abort",
835
+ () => {
836
+ this.state = "cancel", this.close();
837
+ },
838
+ { once: true }
839
+ );
840
+ }
841
+ this.rl = l__default.createInterface({
842
+ input: this.input,
843
+ tabSize: 2,
844
+ prompt: "",
845
+ escapeCodeTimeout: 50,
846
+ terminal: true
847
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
848
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
849
+ }), this.once("cancel", () => {
850
+ this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
851
+ });
852
+ });
853
+ }
854
+ _isActionKey(t2, e) {
855
+ return t2 === " ";
856
+ }
857
+ _shouldSubmit(t2, e) {
858
+ return true;
859
+ }
860
+ _setValue(t2) {
861
+ this.value = t2, this.emit("value", this.value);
862
+ }
863
+ _setUserInput(t2, e) {
864
+ this.userInput = t2 ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
865
+ }
866
+ _clearUserInput() {
867
+ this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
868
+ }
869
+ async onKeypress(t2, e) {
870
+ if (this.state !== "validating") {
871
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t2, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t2 && (t2.toLowerCase() === "y" || t2.toLowerCase() === "n") && this.emit("confirm", t2.toLowerCase() === "y"), this.emit("key", t2, e), e?.name === "return" && this._shouldSubmit(t2, e)) {
872
+ if (this.opts.validate) {
873
+ const i2 = runValidation(this.opts.validate, this.value);
874
+ let s;
875
+ i2 instanceof Promise ? (this.state = "validating", this.render(), s = await i2) : s = i2, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
876
+ }
877
+ this.state !== "error" && (this.state = "submit");
878
+ }
879
+ isActionKey([t2, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
880
+ }
881
+ }
882
+ close() {
883
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
884
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
885
+ }
886
+ restoreCursor() {
887
+ const t2 = wrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`
888
+ `).length - 1;
889
+ this.output.write(import_sisteransi.cursor.move(-999, t2 * -1));
890
+ }
891
+ render() {
892
+ const t2 = wrapAnsi(this._render(this) ?? "", process.stdout.columns, {
893
+ hard: true,
894
+ trim: false
895
+ });
896
+ if (t2 !== this._prevFrame) {
897
+ if (this.state === "initial")
898
+ this.output.write(import_sisteransi.cursor.hide);
899
+ else {
900
+ const e = diffLines(this._prevFrame, t2), i2 = getRows(this.output);
901
+ if (this.restoreCursor(), e) {
902
+ const s = Math.max(0, e.numLinesAfter - i2), r2 = Math.max(0, e.numLinesBefore - i2);
903
+ let n3 = e.lines.find((o) => o >= s);
904
+ if (n3 === void 0) {
905
+ this._prevFrame = t2;
906
+ return;
907
+ }
908
+ if (e.lines.length === 1) {
909
+ this.output.write(import_sisteransi.cursor.move(0, n3 - r2)), this.output.write(import_sisteransi.erase.lines(1));
910
+ const o = t2.split(`
911
+ `);
912
+ this.output.write(o[n3]), this._prevFrame = t2, this.output.write(import_sisteransi.cursor.move(0, o.length - n3 - 1));
913
+ return;
914
+ } else if (e.lines.length > 1) {
915
+ if (s < r2)
916
+ n3 = s;
917
+ else {
918
+ const h2 = n3 - r2;
919
+ h2 > 0 && this.output.write(import_sisteransi.cursor.move(0, h2));
920
+ }
921
+ this.output.write(import_sisteransi.erase.down());
922
+ const f = t2.split(`
923
+ `).slice(n3);
924
+ this.output.write(f.join(`
925
+ `)), this._prevFrame = t2;
926
+ return;
927
+ }
928
+ }
929
+ this.output.write(import_sisteransi.erase.down());
930
+ }
931
+ this.output.write(t2), this.state === "initial" && (this.state = "active"), this._prevFrame = t2;
932
+ }
933
+ }
934
+ };
935
+ var r = class extends y {
936
+ get cursor() {
937
+ return this.value ? 0 : 1;
938
+ }
939
+ get _value() {
940
+ return this.cursor === 0;
941
+ }
942
+ constructor(t2) {
943
+ super(t2, false), this.value = !!t2.initialValue, this.on("userInput", () => {
944
+ this.value = this._value;
945
+ }), this.on("confirm", (i2) => {
946
+ this.output.write(import_sisteransi.cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
947
+ }), this.on("cursor", () => {
948
+ this.value = !this.value;
949
+ });
950
+ }
951
+ };
952
+ var a = class extends y {
953
+ options;
954
+ cursor = 0;
955
+ get _value() {
956
+ return this.options[this.cursor]?.value;
957
+ }
958
+ get _enabledOptions() {
959
+ return this.options.filter((e) => e.disabled !== true);
960
+ }
961
+ toggleAll() {
962
+ const e = this._enabledOptions, i2 = this.value !== void 0 && this.value.length === e.length;
963
+ this.value = i2 ? [] : e.map((t2) => t2.value);
964
+ }
965
+ toggleInvert() {
966
+ const e = this.value;
967
+ if (!e)
968
+ return;
969
+ const i2 = this._enabledOptions.filter((t2) => !e.includes(t2.value));
970
+ this.value = i2.map((t2) => t2.value);
971
+ }
972
+ toggleValue() {
973
+ this.value === void 0 && (this.value = []);
974
+ const e = this.value.includes(this._value);
975
+ this.value = e ? this.value.filter((i2) => i2 !== this._value) : [...this.value, this._value];
976
+ }
977
+ constructor(e) {
978
+ super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];
979
+ const i2 = Math.max(
980
+ this.options.findIndex(({ value: t2 }) => t2 === e.cursorAt),
981
+ 0
982
+ );
983
+ this.cursor = this.options[i2]?.disabled ? findCursor(i2, 1, this.options) : i2, this.on("key", (t2, l) => {
984
+ l.name === "a" && this.toggleAll(), l.name === "i" && this.toggleInvert();
985
+ }), this.on("cursor", (t2) => {
986
+ switch (t2) {
987
+ case "left":
988
+ case "up":
989
+ this.cursor = findCursor(this.cursor, -1, this.options);
990
+ break;
991
+ case "down":
992
+ case "right":
993
+ this.cursor = findCursor(this.cursor, 1, this.options);
994
+ break;
995
+ case "space":
996
+ this.toggleValue();
997
+ break;
998
+ }
999
+ });
1000
+ }
1001
+ };
1002
+ var u$1 = class u extends y {
1003
+ _mask = "\u2022";
1004
+ get cursor() {
1005
+ return this._cursor;
1006
+ }
1007
+ get masked() {
1008
+ return this.userInput.replaceAll(/./g, this._mask);
1009
+ }
1010
+ get userInputWithCursor() {
1011
+ if (this.state === "submit" || this.state === "cancel")
1012
+ return this.masked;
1013
+ const t2 = this.userInput;
1014
+ if (this.cursor >= t2.length)
1015
+ return `${this.masked}${styleText(["inverse", "hidden"], "_")}`;
1016
+ const s = this.masked, r2 = s.slice(0, this.cursor), i2 = s.slice(this.cursor, this.cursor + 1), o = s.slice(this.cursor + 1);
1017
+ return `${r2}${styleText("inverse", i2)}${o}`;
1018
+ }
1019
+ clear() {
1020
+ this._clearUserInput();
1021
+ }
1022
+ constructor({ mask: t2, ...s }) {
1023
+ super(s), this._mask = t2 ?? "\u2022", this.on("userInput", (r2) => {
1024
+ this._setValue(r2);
1025
+ }), this.on("finalize", () => {
1026
+ this.value === void 0 && (this.value = "");
1027
+ });
1028
+ }
1029
+ };
1030
+ var n$1 = class n extends y {
1031
+ options;
1032
+ cursor = 0;
1033
+ get _selectedValue() {
1034
+ return this.options[this.cursor];
1035
+ }
1036
+ changeValue() {
1037
+ const e = this._selectedValue;
1038
+ this.value = e === void 0 ? void 0 : e.value;
1039
+ }
1040
+ constructor(e) {
1041
+ super(e, false), this.options = e.options;
1042
+ const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t2 = o === -1 ? 0 : o;
1043
+ this.cursor = this.options[t2]?.disabled ? findCursor(t2, 1, this.options) : t2, this.changeValue(), this.on("cursor", (s) => {
1044
+ switch (s) {
1045
+ case "left":
1046
+ case "up":
1047
+ this.cursor = findCursor(this.cursor, -1, this.options);
1048
+ break;
1049
+ case "down":
1050
+ case "right":
1051
+ this.cursor = findCursor(this.cursor, 1, this.options);
1052
+ break;
1053
+ }
1054
+ this.changeValue();
1055
+ });
1056
+ }
1057
+ };
1058
+ var n2 = class extends y {
1059
+ get userInputWithCursor() {
1060
+ if (this.state === "submit")
1061
+ return this.userInput;
1062
+ const t2 = this.userInput;
1063
+ if (this.cursor >= t2.length)
1064
+ return `${this.userInput}\u2588`;
1065
+ const r2 = t2.slice(0, this.cursor), s = t2.slice(this.cursor, this.cursor + 1), e = t2.slice(this.cursor + 1);
1066
+ return `${r2}${styleText("inverse", s)}${e}`;
1067
+ }
1068
+ get cursor() {
1069
+ return this._cursor;
1070
+ }
1071
+ constructor(t2) {
1072
+ super({
1073
+ ...t2,
1074
+ initialUserInput: t2.initialUserInput ?? t2.initialValue
1075
+ }), this.on("userInput", (r2) => {
1076
+ this._setValue(r2);
1077
+ }), this.on("finalize", () => {
1078
+ this.value || (this.value = t2.defaultValue), this.value === void 0 && (this.value = "");
1079
+ });
1080
+ }
1081
+ };
1082
+
1083
+ // ../../node_modules/.pnpm/@clack+prompts@1.8.1/node_modules/@clack/prompts/dist/index.mjs
1084
+ import { styleText as styleText2, stripVTControlCharacters } from "node:util";
1085
+ import process$1 from "node:process";
1086
+ var import_sisteransi2 = __toESM(require_src(), 1);
1087
+ function isUnicodeSupported() {
1088
+ if (process$1.platform !== "win32") {
1089
+ return process$1.env.TERM !== "linux";
1090
+ }
1091
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
1092
+ }
1093
+ var unicode = isUnicodeSupported();
1094
+ var unicodeOr = (o, e) => unicode ? o : e;
1095
+ var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
1096
+ var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
1097
+ var S_STEP_ERROR = unicodeOr("\u25B2", "x");
1098
+ var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
1099
+ var S_BAR_START = unicodeOr("\u250C", "T");
1100
+ var S_BAR = unicodeOr("\u2502", "|");
1101
+ var S_BAR_END = unicodeOr("\u2514", "\u2014");
1102
+ var S_BAR_START_RIGHT = unicodeOr("\u2510", "T");
1103
+ var S_BAR_END_RIGHT = unicodeOr("\u2518", "\u2014");
1104
+ var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
1105
+ var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
1106
+ var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
1107
+ var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
1108
+ var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
1109
+ var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
1110
+ var S_BAR_H = unicodeOr("\u2500", "-");
1111
+ var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
1112
+ var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
1113
+ var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
1114
+ var S_CORNER_BOTTOM_LEFT = unicodeOr("\u2570", "+");
1115
+ var S_CORNER_TOP_LEFT = unicodeOr("\u256D", "+");
1116
+ var S_INFO = unicodeOr("\u25CF", "\u2022");
1117
+ var S_SUCCESS = unicodeOr("\u25C6", "*");
1118
+ var S_WARN = unicodeOr("\u25B2", "!");
1119
+ var S_ERROR = unicodeOr("\u25A0", "x");
1120
+ var symbol = (o) => {
1121
+ switch (o) {
1122
+ case "initial":
1123
+ case "active":
1124
+ return styleText2("cyan", S_STEP_ACTIVE);
1125
+ case "cancel":
1126
+ return styleText2("red", S_STEP_CANCEL);
1127
+ case "error":
1128
+ return styleText2("yellow", S_STEP_ERROR);
1129
+ case "submit":
1130
+ return styleText2("green", S_STEP_SUBMIT);
1131
+ case "validating":
1132
+ return styleText2("dim", S_STEP_ACTIVE);
1133
+ }
1134
+ };
1135
+ var symbolBar = (o) => {
1136
+ switch (o) {
1137
+ case "initial":
1138
+ case "active":
1139
+ return styleText2("cyan", S_BAR);
1140
+ case "cancel":
1141
+ return styleText2("red", S_BAR);
1142
+ case "error":
1143
+ return styleText2("yellow", S_BAR);
1144
+ case "submit":
1145
+ return styleText2("green", S_BAR);
1146
+ }
1147
+ };
1148
+ function formatInstructionFooter(o, e) {
1149
+ const r2 = [`${e ? `${styleText2("cyan", S_BAR)} ` : ""}${o.join(" \u2022 ")}`];
1150
+ return e && r2.push(styleText2("cyan", S_BAR_END)), r2;
1151
+ }
1152
+ var I = (l, e, w, p, b, C = false) => {
1153
+ let r2 = e, O = 0;
1154
+ if (C)
1155
+ for (let i2 = p - 1; i2 >= w; i2--) {
1156
+ const m2 = l[i2];
1157
+ if (m2 && (r2 -= m2.length), O++, r2 <= b) break;
1158
+ }
1159
+ else
1160
+ for (let i2 = w; i2 < p; i2++) {
1161
+ const m2 = l[i2];
1162
+ if (m2 && (r2 -= m2.length), O++, r2 <= b) break;
1163
+ }
1164
+ return { lineCount: r2, removals: O };
1165
+ };
1166
+ var limitOptions = ({
1167
+ cursor: l,
1168
+ options: e,
1169
+ style: w,
1170
+ output: p = process.stdout,
1171
+ maxItems: b = Number.POSITIVE_INFINITY,
1172
+ columnPadding: C = 0,
1173
+ rowPadding: r2 = 4
1174
+ }) => {
1175
+ const i2 = getColumns(p) - C, m2 = getRows(p), M = styleText2("dim", "..."), v = Math.max(m2 - r2, 0), a2 = Math.max(Math.min(b, v), 5);
1176
+ let f = 0;
1177
+ l >= a2 - 3 && (f = Math.max(
1178
+ Math.min(l - a2 + 3, e.length - a2),
1179
+ 0
1180
+ ));
1181
+ let d = a2 < e.length && f > 0, c2 = a2 < e.length && f + a2 < e.length;
1182
+ const W = Math.min(
1183
+ f + a2,
1184
+ e.length
1185
+ ), s = [];
1186
+ let g = 0;
1187
+ d && g++, c2 && g++;
1188
+ const T = f + (d ? 1 : 0), y2 = W - (c2 ? 1 : 0);
1189
+ for (let t2 = T; t2 < y2; t2++) {
1190
+ const n3 = e[t2], o = n3 ? w(n3, t2 === l) : "", h2 = wrapAnsi(o, i2, {
1191
+ hard: true,
1192
+ trim: false
1193
+ }).split(`
1194
+ `);
1195
+ s.push(h2), g += h2.length;
1196
+ }
1197
+ if (g > v) {
1198
+ let t2 = 0, n3 = 0, o = g;
1199
+ const h2 = l - T;
1200
+ let u4 = v;
1201
+ const L = () => I(s, o, 0, h2, u4), E = () => I(
1202
+ s,
1203
+ o,
1204
+ h2 + 1,
1205
+ s.length,
1206
+ u4,
1207
+ true
1208
+ );
1209
+ d ? ({ lineCount: o, removals: t2 } = L(), o > u4 && (c2 || (u4 -= 1), { lineCount: o, removals: n3 } = E())) : (c2 || (u4 -= 1), { lineCount: o, removals: n3 } = E(), o > u4 && (u4 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n3 > 0 && (c2 = true, s.splice(s.length - n3, n3));
1210
+ }
1211
+ const x = [];
1212
+ d && x.push(M);
1213
+ for (const t2 of s)
1214
+ for (const n3 of t2)
1215
+ x.push(n3);
1216
+ return c2 && x.push(M), x;
1217
+ };
1218
+ var confirm = (e) => {
1219
+ const a2 = e.active ?? "Yes", o = e.inactive ?? "No";
1220
+ return new r({
1221
+ active: a2,
1222
+ inactive: o,
1223
+ signal: e.signal,
1224
+ input: e.input,
1225
+ output: e.output,
1226
+ initialValue: e.initialValue ?? true,
1227
+ render() {
1228
+ const i2 = e.withGuide ?? settings.withGuide, u4 = `${symbol(this.state)} `, l = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
1229
+ e.output,
1230
+ e.message,
1231
+ l,
1232
+ u4
1233
+ ), s = `${i2 ? `${styleText2("gray", S_BAR)}
1234
+ ` : ""}${f}
1235
+ `, c2 = this.value ? a2 : o;
1236
+ switch (this.state) {
1237
+ case "submit": {
1238
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1239
+ return `${s}${r2}${styleText2("dim", c2)}`;
1240
+ }
1241
+ case "cancel": {
1242
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1243
+ return `${s}${r2}${styleText2(["strikethrough", "dim"], c2)}${i2 ? `
1244
+ ${styleText2("gray", S_BAR)}` : ""}`;
1245
+ }
1246
+ default: {
1247
+ const r2 = i2 ? `${styleText2("cyan", S_BAR)} ` : "", g = i2 ? styleText2("cyan", S_BAR_END) : "";
1248
+ return `${s}${r2}${this.value ? `${styleText2("green", S_RADIO_ACTIVE)} ${a2}` : `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", a2)}`}${e.vertical ? i2 ? `
1249
+ ${styleText2("cyan", S_BAR)} ` : `
1250
+ ` : ` ${styleText2("dim", "/")} `}${this.value ? `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", o)}` : `${styleText2("green", S_RADIO_ACTIVE)} ${o}`}
1251
+ ${g}
1252
+ `;
1253
+ }
1254
+ }
1255
+ }
1256
+ }).prompt();
1257
+ };
1258
+ var MULTISELECT_INSTRUCTIONS = [
1259
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1260
+ `${styleText2("dim", "Space:")} select`,
1261
+ `${styleText2("dim", "Enter:")} confirm`
1262
+ ];
1263
+ var m = (i2, u4) => i2.split(`
1264
+ `).map((d) => u4(d)).join(`
1265
+ `);
1266
+ var multiselect = (i2) => {
1267
+ const u4 = (t2, a2) => {
1268
+ const r2 = t2.label ?? String(t2.value);
1269
+ return a2 === "disabled" ? `${styleText2("gray", S_CHECKBOX_INACTIVE)} ${m(r2, (o) => styleText2(["strikethrough", "gray"], o))}${t2.hint ? ` ${styleText2("dim", `(${t2.hint ?? "disabled"})`)}` : ""}` : a2 === "active" ? `${styleText2("cyan", S_CHECKBOX_ACTIVE)} ${r2}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "selected" ? `${styleText2("green", S_CHECKBOX_SELECTED)} ${m(r2, (o) => styleText2("dim", o))}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "cancelled" ? `${m(r2, (o) => styleText2(["strikethrough", "dim"], o))}` : a2 === "active-selected" ? `${styleText2("green", S_CHECKBOX_SELECTED)} ${r2}${t2.hint ? ` ${styleText2("dim", `(${t2.hint})`)}` : ""}` : a2 === "submitted" ? `${m(r2, (o) => styleText2("dim", o))}` : `${styleText2("dim", S_CHECKBOX_INACTIVE)} ${m(r2, (o) => styleText2("dim", o))}`;
1270
+ }, d = i2.required ?? true, x = i2.showInstructions ?? true;
1271
+ return new a({
1272
+ options: i2.options,
1273
+ signal: i2.signal,
1274
+ input: i2.input,
1275
+ output: i2.output,
1276
+ initialValues: i2.initialValues,
1277
+ required: d,
1278
+ cursorAt: i2.cursorAt,
1279
+ validate(t2) {
1280
+ if (d && (t2 === void 0 || t2.length === 0))
1281
+ return `Please select at least one option.
1282
+ ${styleText2(
1283
+ "reset",
1284
+ styleText2(
1285
+ "dim",
1286
+ `Press ${styleText2(["gray", "bgWhite", "inverse"], " space ")} to select, ${styleText2(
1287
+ "gray",
1288
+ styleText2("bgWhite", styleText2("inverse", " enter "))
1289
+ )} to submit`
1290
+ )
1291
+ )}`;
1292
+ },
1293
+ render() {
1294
+ const t2 = i2.withGuide ?? settings.withGuide, a2 = wrapTextWithPrefix(
1295
+ i2.output,
1296
+ i2.message,
1297
+ t2 ? `${symbolBar(this.state)} ` : "",
1298
+ `${symbol(this.state)} `
1299
+ ), r2 = `${t2 ? `${styleText2("gray", S_BAR)}
1300
+ ` : ""}${a2}
1301
+ `, o = this.value ?? [], g = (n3, l) => {
1302
+ if (n3.disabled)
1303
+ return u4(n3, "disabled");
1304
+ const s = o.includes(n3.value);
1305
+ return l && s ? u4(n3, "active-selected") : s ? u4(n3, "selected") : u4(n3, l ? "active" : "inactive");
1306
+ };
1307
+ switch (this.state) {
1308
+ case "submit": {
1309
+ const n3 = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u4(s, "submitted")).join(styleText2("dim", ", ")) || styleText2("dim", "none"), l = wrapTextWithPrefix(
1310
+ i2.output,
1311
+ n3,
1312
+ t2 ? `${styleText2("gray", S_BAR)} ` : ""
1313
+ );
1314
+ return `${r2}${l}`;
1315
+ }
1316
+ case "cancel": {
1317
+ const n3 = this.options.filter(({ value: s }) => o.includes(s)).map((s) => u4(s, "cancelled")).join(styleText2("dim", ", "));
1318
+ if (n3.trim() === "")
1319
+ return `${r2}${styleText2("gray", S_BAR)}`;
1320
+ const l = wrapTextWithPrefix(
1321
+ i2.output,
1322
+ n3,
1323
+ t2 ? `${styleText2("gray", S_BAR)} ` : ""
1324
+ );
1325
+ return `${r2}${l}${t2 ? `
1326
+ ${styleText2("gray", S_BAR)}` : ""}`;
1327
+ }
1328
+ case "error": {
1329
+ const n3 = t2 ? `${styleText2("yellow", S_BAR)} ` : "", l = this.error.split(`
1330
+ `).map(
1331
+ ($, v) => v === 0 ? `${t2 ? `${styleText2("yellow", S_BAR_END)} ` : ""}${styleText2("yellow", $)}` : ` ${$}`
1332
+ ).join(`
1333
+ `), s = r2.split(`
1334
+ `).length, h2 = l.split(`
1335
+ `).length + 1;
1336
+ return `${r2}${n3}${limitOptions({
1337
+ output: i2.output,
1338
+ options: this.options,
1339
+ cursor: this.cursor,
1340
+ maxItems: i2.maxItems,
1341
+ columnPadding: n3.length,
1342
+ rowPadding: s + h2,
1343
+ style: g
1344
+ }).join(`
1345
+ ${n3}`)}
1346
+ ${l}
1347
+ `;
1348
+ }
1349
+ default: {
1350
+ const n3 = t2 ? `${styleText2("cyan", S_BAR)} ` : "", l = r2.split(`
1351
+ `).length, s = x ? formatInstructionFooter(MULTISELECT_INSTRUCTIONS, t2) : t2 ? [styleText2("cyan", S_BAR_END)] : [], h2 = s.join(`
1352
+ `), $ = s.length + 1;
1353
+ return `${r2}${n3}${limitOptions({
1354
+ output: i2.output,
1355
+ options: this.options,
1356
+ cursor: this.cursor,
1357
+ maxItems: i2.maxItems,
1358
+ columnPadding: n3.length,
1359
+ rowPadding: l + $,
1360
+ style: g
1361
+ }).join(`
1362
+ ${n3}`)}
1363
+ ${h2}
1364
+ `;
1365
+ }
1366
+ }
1367
+ }
1368
+ }).prompt();
1369
+ };
1370
+ var password = (e) => new u$1({
1371
+ validate: e.validate,
1372
+ mask: e.mask ?? S_PASSWORD_MASK,
1373
+ signal: e.signal,
1374
+ input: e.input,
1375
+ output: e.output,
1376
+ render() {
1377
+ const r2 = e.withGuide ?? settings.withGuide, o = `${r2 ? `${styleText2("gray", S_BAR)}
1378
+ ` : ""}${symbol(this.state)} ${e.message}
1379
+ `, m2 = this.userInputWithCursor, i2 = this.masked;
1380
+ switch (this.state) {
1381
+ case "error": {
1382
+ const s = r2 ? `${styleText2("yellow", S_BAR)} ` : "", n3 = r2 ? `${styleText2("yellow", S_BAR_END)} ` : "", d = i2 ?? "";
1383
+ return e.clearOnError && this.clear(), `${o.trim()}
1384
+ ${s}${d}
1385
+ ${n3}${styleText2("yellow", this.error)}
1386
+ `;
1387
+ }
1388
+ case "submit": {
1389
+ const s = r2 ? `${styleText2("gray", S_BAR)} ` : "", n3 = i2 ? styleText2("dim", i2) : "";
1390
+ return `${o}${s}${n3}`;
1391
+ }
1392
+ case "cancel": {
1393
+ const s = r2 ? `${styleText2("gray", S_BAR)} ` : "", n3 = i2 ? styleText2(["strikethrough", "dim"], i2) : "";
1394
+ return `${o}${s}${n3}${i2 && r2 ? `
1395
+ ${styleText2("gray", S_BAR)}` : ""}`;
1396
+ }
1397
+ default: {
1398
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n3 = r2 ? styleText2("cyan", S_BAR_END) : "";
1399
+ return `${o}${s}${m2}
1400
+ ${n3}
1401
+ `;
1402
+ }
1403
+ }
1404
+ }
1405
+ }).prompt();
1406
+ var u3 = {
1407
+ light: unicodeOr("\u2500", "-"),
1408
+ heavy: unicodeOr("\u2501", "="),
1409
+ block: unicodeOr("\u2588", "#")
1410
+ };
1411
+ var SELECT_INSTRUCTIONS = [
1412
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1413
+ `${styleText2("dim", "Enter:")} confirm`
1414
+ ];
1415
+ var c = (t2, o) => t2.includes(`
1416
+ `) ? t2.split(`
1417
+ `).map((d) => o(d)).join(`
1418
+ `) : o(t2);
1419
+ var select = (t2) => {
1420
+ const o = (n3, m2) => {
1421
+ if (n3 === void 0)
1422
+ return "";
1423
+ const s = n3.label ?? String(n3.value);
1424
+ switch (m2) {
1425
+ case "disabled":
1426
+ return `${styleText2("gray", S_RADIO_INACTIVE)} ${c(s, (i2) => styleText2("gray", i2))}${n3.hint ? ` ${styleText2("dim", `(${n3.hint ?? "disabled"})`)}` : ""}`;
1427
+ case "selected":
1428
+ return `${c(s, (i2) => styleText2("dim", i2))}`;
1429
+ case "active":
1430
+ return `${styleText2("green", S_RADIO_ACTIVE)} ${s}${n3.hint ? ` ${styleText2("dim", `(${n3.hint})`)}` : ""}`;
1431
+ case "cancelled":
1432
+ return `${c(s, (i2) => styleText2(["strikethrough", "dim"], i2))}`;
1433
+ default:
1434
+ return `${styleText2("dim", S_RADIO_INACTIVE)} ${c(s, (i2) => styleText2("dim", i2))}`;
1435
+ }
1436
+ }, d = t2.showInstructions ?? true;
1437
+ return new n$1({
1438
+ options: t2.options,
1439
+ signal: t2.signal,
1440
+ input: t2.input,
1441
+ output: t2.output,
1442
+ initialValue: t2.initialValue,
1443
+ render() {
1444
+ const n3 = t2.withGuide ?? settings.withGuide, m2 = `${symbol(this.state)} `, s = `${symbolBar(this.state)} `, i2 = wrapTextWithPrefix(
1445
+ t2.output,
1446
+ t2.message,
1447
+ s,
1448
+ m2
1449
+ ), u4 = `${n3 ? `${styleText2("gray", S_BAR)}
1450
+ ` : ""}${i2}
1451
+ `;
1452
+ switch (this.state) {
1453
+ case "submit": {
1454
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1455
+ t2.output,
1456
+ o(this.options[this.cursor], "selected"),
1457
+ r2
1458
+ );
1459
+ return `${u4}${a2}`;
1460
+ }
1461
+ case "cancel": {
1462
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1463
+ t2.output,
1464
+ o(this.options[this.cursor], "cancelled"),
1465
+ r2
1466
+ );
1467
+ return `${u4}${a2}${n3 ? `
1468
+ ${styleText2("gray", S_BAR)}` : ""}`;
1469
+ }
1470
+ default: {
1471
+ const r2 = n3 ? `${styleText2("cyan", S_BAR)} ` : "", a2 = u4.split(`
1472
+ `).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n3) : n3 ? [styleText2("cyan", S_BAR_END)] : [], f = p.join(`
1473
+ `), b = p.length + 1;
1474
+ return `${u4}${r2}${limitOptions({
1475
+ output: t2.output,
1476
+ cursor: this.cursor,
1477
+ options: this.options,
1478
+ maxItems: t2.maxItems,
1479
+ columnPadding: r2.length,
1480
+ rowPadding: a2 + b,
1481
+ style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
1482
+ }).join(`
1483
+ ${r2}`)}
1484
+ ${f}
1485
+ `;
1486
+ }
1487
+ }
1488
+ }
1489
+ }).prompt();
1490
+ };
1491
+ var i = `${styleText2("gray", S_BAR)} `;
1492
+ var text = (t2) => new n2({
1493
+ validate: t2.validate,
1494
+ placeholder: t2.placeholder,
1495
+ defaultValue: t2.defaultValue,
1496
+ initialValue: t2.initialValue,
1497
+ output: t2.output,
1498
+ signal: t2.signal,
1499
+ input: t2.input,
1500
+ render() {
1501
+ const r2 = t2?.withGuide ?? settings.withGuide, l = `${`${r2 ? `${styleText2("gray", S_BAR)}
1502
+ ` : ""}${symbol(this.state)} `}${t2.message}
1503
+ `, d = t2.placeholder && t2.placeholder.length > 0 ? (
1504
+ // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0
1505
+ styleText2("inverse", t2.placeholder[0]) + styleText2("dim", t2.placeholder.slice(1))
1506
+ ) : styleText2(["inverse", "hidden"], "_"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? "";
1507
+ switch (this.state) {
1508
+ case "validating": {
1509
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "", c2 = styleText2("dim", o), $ = styleText2("dim", "Validating...");
1510
+ return `${l}${n3}${c2}
1511
+ ${i2} ${$}
1512
+ `;
1513
+ }
1514
+ case "error": {
1515
+ const n3 = this.error ? ` ${styleText2("yellow", this.error)}` : "", i2 = r2 ? `${styleText2("yellow", S_BAR)} ` : "", c2 = r2 ? styleText2("yellow", S_BAR_END) : "";
1516
+ return `${l.trim()}
1517
+ ${i2}${o}
1518
+ ${c2}${n3}
1519
+ `;
1520
+ }
1521
+ case "submit": {
1522
+ const n3 = s ? `${r2 ? " " : ""}${styleText2("dim", s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1523
+ return `${l}${i2}${n3}`;
1524
+ }
1525
+ case "cancel": {
1526
+ const n3 = s ? ` ${styleText2(["strikethrough", "dim"], s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1527
+ return `${l}${i2}${n3}${s.trim() ? `
1528
+ ${i2}` : ""}`;
1529
+ }
1530
+ default: {
1531
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "";
1532
+ return `${l}${n3}${o}
1533
+ ${i2}
1534
+ `;
1535
+ }
1536
+ }
1537
+ }
1538
+ }).prompt();
1539
+
1540
+ // src/setup/screen.ts
1541
+ var import_picocolors = __toESM(require_picocolors(), 1);
1542
+
1543
+ // src/setup/journey.ts
1544
+ var RULES = {
1545
+ gh_missing: { side: "you" },
1546
+ gh_signed_out: { side: "you" },
1547
+ repo_dirty: { side: "you" },
1548
+ detached_head: { side: "you" },
1549
+ files_missing: { side: "you" },
1550
+ stack_unknown: { side: "you" },
1551
+ staff_unchecked: { side: "you" },
1552
+ too_many_reads: { side: "you" },
1553
+ secret_read: { side: "you" },
1554
+ layout_no_place: { side: "you" },
1555
+ no_lockfile: { side: "you" },
1556
+ vercel_missing: { side: "you" },
1557
+ origin_taken: { side: "you" },
1558
+ node_old: { side: "you" },
1559
+ offline: { side: "you", retry: [2, 4, 8] },
1560
+ not_github: { side: "you" },
1561
+ invite_invalid: { side: "you" },
1562
+ too_many_checks: { side: "you" },
1563
+ backoffice_unreachable: { side: "you" },
1564
+ key_missing: { side: "you" },
1565
+ key_invalid: { side: "you" },
1566
+ no_credit: { side: "you" },
1567
+ model_access: { side: "you" },
1568
+ rate_limited: { side: "anthropic", retry: [12, 12, 30] },
1569
+ overloaded: { side: "anthropic", retry: [5, 10, 20] },
1570
+ not_admin: { side: "you" },
1571
+ org_forbids_keys: { side: "you" },
1572
+ github_rate_limited: { side: "github", retry: [30] },
1573
+ service_down: { side: "us", retry: [3, 6, 12] },
1574
+ read_failed: { side: "us", retry: [2, 4, 8] },
1575
+ vercel_refused: { side: "you" },
1576
+ install_failed: { side: "you" },
1577
+ pre_commit: { side: "you" },
1578
+ pre_push: { side: "you" },
1579
+ pr_refused: { side: "github" },
1580
+ caps_invalid: { side: "you" },
1581
+ any_session_needs_human: { side: "you" },
1582
+ interrupted: { side: "you" },
1583
+ unexpected: { side: "us" }
1584
+ };
1585
+ var sideOf = (code) => rule(code).side;
1586
+ var isErrorCode = (v) => typeof v === "string" && Object.hasOwn(RULES, v);
1587
+ var rule = (code) => RULES[code];
1588
+ var MAX_READS = 50;
1589
+ var MAX_WAIT_S = 60;
1590
+ var StepError = class extends Error {
1591
+ code;
1592
+ retryAfterS;
1593
+ constructor(code, retryAfterS) {
1594
+ super(code);
1595
+ this.code = code;
1596
+ this.retryAfterS = retryAfterS;
1597
+ }
1598
+ };
1599
+ var CHECKS = ["machine", "invitation", "project", "stack", "staff", "language", "key", "backup", "caps", "timeZone", "github", "tables", "names"];
1600
+ var CREATIONS = ["draft", "readKey", "verifyRead", "hostVariable", "branch", "push", "activation", "pr"];
1601
+ var CHANGES = ["caps", "key", "backup", "environments", "reads"];
1602
+ var DEFAULT_CAPS = { question: 1, day: 20, month: 200 };
1603
+ function capsProblem(c2) {
1604
+ if (!(c2.question > 0 && c2.day > 0 && c2.month > 0)) return "not_positive";
1605
+ if (c2.day < c2.question * 2) return "day_below_high";
1606
+ if (c2.month < c2.day) return "month_below_day";
1607
+ return null;
1608
+ }
1609
+ async function journey(mode, p) {
1610
+ const made = [];
1611
+ const live = () => {
1612
+ if (p.signal.aborted) throw new StepError("interrupted");
1613
+ };
1614
+ const attempt = async (fn) => {
1615
+ for (let k = 0; ; k++) {
1616
+ live();
1617
+ try {
1618
+ const r2 = await fn();
1619
+ if (k > 0) p.say({ tone: "ok", key: "retry_ok" });
1620
+ return r2;
1621
+ } catch (e) {
1622
+ const delays = e instanceof StepError ? rule(e.code).retry ?? [] : [];
1623
+ if (!(e instanceof StepError) || k >= delays.length) throw e;
1624
+ const seconds = Math.max(delays[k] ?? 0, e.retryAfterS ?? 0);
1625
+ if (seconds > MAX_WAIT_S) throw e;
1626
+ p.say({ tone: "wait", key: "retry", detail: { code: e.code, seconds, attempt: k + 1, of: delays.length } });
1627
+ await p.wait(seconds);
1628
+ }
1629
+ }
1630
+ };
1631
+ const checked = (step) => p.say({ tone: "ok", key: "checked", detail: { step } });
1632
+ const askCaps = async (start) => {
1633
+ let proposal = start;
1634
+ let problem = null;
1635
+ for (; ; ) {
1636
+ const caps = await p.ask.caps(proposal, problem);
1637
+ problem = capsProblem(caps);
1638
+ if (!problem) return caps;
1639
+ p.say({ tone: "err", key: "caps_invalid", detail: { problem } });
1640
+ if (mode === "agent") throw new StepError("caps_invalid");
1641
+ proposal = caps;
1642
+ }
1643
+ };
1644
+ const askKey = async () => {
1645
+ const key = await p.ask.key();
1646
+ if (!key) throw new StepError("key_missing");
1647
+ await attempt(() => p.verify.key(key));
1648
+ return key;
1649
+ };
1650
+ const askReads = async () => {
1651
+ const tables = await p.ask.tables(await attempt(() => p.probe.tables()));
1652
+ if (tables.length > MAX_READS) throw new StepError("too_many_reads");
1653
+ const proposed = await attempt(() => p.probe.names(tables));
1654
+ const names = await p.ask.names(proposed);
1655
+ for (const n3 of proposed) if (n3.proposed && !names.includes(n3.name)) p.say({ tone: "warn", key: "name_in_clear", detail: { name: n3.name } });
1656
+ return { tables, names };
1657
+ };
1658
+ const checks = async () => {
1659
+ const invitation = await p.ask.invitation();
1660
+ await attempt(() => p.verify.invitation(invitation));
1661
+ checked("invitation");
1662
+ const environments = await p.ask.environments(await attempt(() => p.probe.environments()));
1663
+ await attempt(() => p.verify.environments(environments));
1664
+ checked("project");
1665
+ await attempt(() => p.probe.stack());
1666
+ checked("stack");
1667
+ const staff = await p.ask.staff(await attempt(() => p.probe.staff()));
1668
+ if (staff.kind === "any_session") {
1669
+ if (mode === "agent") throw new StepError("any_session_needs_human");
1670
+ p.say({ tone: "warn", key: "any_session" });
1671
+ }
1672
+ checked("staff");
1673
+ const language2 = await p.ask.language(await p.probe.language());
1674
+ checked("language");
1675
+ const key = await askKey();
1676
+ checked("key");
1677
+ const backupKey = await p.ask.backup();
1678
+ if (backupKey !== null) await attempt(() => p.verify.key(backupKey));
1679
+ checked("backup");
1680
+ const caps = await askCaps(DEFAULT_CAPS);
1681
+ checked("caps");
1682
+ const timeZone = await p.ask.timeZone(await p.probe.timeZone());
1683
+ checked("timeZone");
1684
+ if ((await attempt(() => p.probe.github())).oldReadKey) p.say({ tone: "info", key: "old_read_key" });
1685
+ checked("github");
1686
+ const reads = await askReads();
1687
+ checked("tables");
1688
+ checked("names");
1689
+ return { invitation, environments, staff, language: language2, key, backupKey, caps, timeZone, ...reads };
1690
+ };
1691
+ const create = async (plan) => {
1692
+ let pr = 0;
1693
+ for (const step of CREATIONS) {
1694
+ const port = p.create[step];
1695
+ const done = await attempt(() => port.run(plan));
1696
+ if (port.undo) made.push(step);
1697
+ p.say({ tone: "ok", key: done.reused ? "reused" : "created", detail: { step } });
1698
+ if (done.pr !== void 0) pr = done.pr;
1699
+ }
1700
+ return pr;
1701
+ };
1702
+ const changes2 = async () => {
1703
+ p.say({ tone: "info", key: "already_connected" });
1704
+ const picked = await p.ask.changes();
1705
+ if (picked.length === 0) {
1706
+ p.say({ tone: "ok", key: "nothing_changed" });
1707
+ return { status: "unchanged" };
1708
+ }
1709
+ await attempt(() => p.change.proveAdmin());
1710
+ p.say({ tone: "ok", key: "admin_proved" });
1711
+ for (const c2 of CHANGES.filter((x) => picked.includes(x))) {
1712
+ if (c2 === "caps") {
1713
+ const before = await attempt(() => p.change.caps());
1714
+ const after = await askCaps(before);
1715
+ await attempt(() => p.change.setCaps(after));
1716
+ const same = before.question === after.question && before.day === after.day && before.month === after.month;
1717
+ p.say({ tone: "ok", key: same ? "caps_unchanged" : "caps_changed" });
1718
+ if (!same) p.say({ tone: "info", key: "next_question" });
1719
+ }
1720
+ if (c2 === "key" || c2 === "backup") {
1721
+ const key = c2 === "key" ? await p.ask.key() : await p.ask.backup() ?? "";
1722
+ if (!key) throw new StepError("key_missing");
1723
+ await attempt(() => p.change.setKey(c2, key));
1724
+ p.say({ tone: "ok", key: "key_replaced", detail: { which: c2 } });
1725
+ }
1726
+ if (c2 === "environments") {
1727
+ const environments = await p.ask.environments(await attempt(() => p.change.environments()));
1728
+ await attempt(() => p.verify.environments(environments));
1729
+ await attempt(() => p.change.setEnvironments(environments));
1730
+ p.say({ tone: "ok", key: "environments_changed" });
1731
+ }
1732
+ if (c2 === "reads") {
1733
+ const { tables, names } = await askReads();
1734
+ const pr = await attempt(() => p.change.reads(tables, names));
1735
+ p.say({ tone: "ok", key: "config_pr", detail: { pr } });
1736
+ }
1737
+ }
1738
+ return { status: "changed", changes: picked };
1739
+ };
1740
+ try {
1741
+ await attempt(() => p.probe.machine());
1742
+ checked("machine");
1743
+ if (await attempt(() => p.probe.connected())) return await changes2();
1744
+ const plan = await checks();
1745
+ if (!await p.ask.recap(plan)) {
1746
+ p.say({ tone: "err", key: "cancelled" });
1747
+ return { status: "cancelled" };
1748
+ }
1749
+ const pr = await create(plan);
1750
+ p.say({ tone: "ok", key: "connected", detail: { pr } });
1751
+ return { status: "connected", pr };
1752
+ } catch (e) {
1753
+ const code = p.signal.aborted ? "interrupted" : e instanceof StepError ? e.code : "unexpected";
1754
+ p.say({ tone: "err", key: "error", detail: { code, side: sideOf(code) } });
1755
+ if (mode === "agent" && code === "key_missing") p.say({ tone: "agent", key: "agent_new_link" });
1756
+ const left = await undo(p, made);
1757
+ p.say({ tone: "err", key: made.length === 0 ? "nothing_created" : left.length === 0 ? "all_undone" : "some_left" });
1758
+ return { status: "stopped", code, left, ...e instanceof StepError || code === "interrupted" ? {} : { cause: e } };
1759
+ }
1760
+ }
1761
+ async function undo(p, made) {
1762
+ const left = [];
1763
+ for (const step of [...made].reverse()) {
1764
+ try {
1765
+ await p.create[step].undo?.();
1766
+ p.say({ tone: "undo", key: "undone", detail: { step } });
1767
+ } catch {
1768
+ left.push(step);
1769
+ p.say({ tone: "err", key: "undo_failed", detail: { step } });
1770
+ }
1771
+ }
1772
+ return left;
1773
+ }
1774
+
1775
+ // src/setup/staff.ts
1776
+ function staffRule(s) {
1777
+ const m2 = /^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)=(.+)$/.exec(s.trim());
1778
+ if (!m2) return void 0;
1779
+ const values = (m2[3] ?? "").split(",").map((v) => v.trim());
1780
+ if (values.some((v) => v === "")) return void 0;
1781
+ return { kind: "role", table: m2[1] ?? "", column: m2[2] ?? "", values };
1782
+ }
1783
+
1784
+ // src/setup/texts.ts
1785
+ var STEPS = /* @__PURE__ */ new Set([...CHECKS, ...CREATIONS]);
1786
+ var isStep = (v) => typeof v === "string" && STEPS.has(v);
1787
+ var stepOf = (d, t2) => isStep(d["step"]) ? t2.steps[d["step"]] : String(d["step"] ?? "");
1788
+ var errorOf = (d, t2) => isErrorCode(d["code"]) ? t2.errors[d["code"]] : { title: String(d["code"] ?? ""), gesture: "" };
1789
+ var problemOf = (d, t2) => {
1790
+ const p = d["problem"];
1791
+ return p === "not_positive" || p === "day_below_high" || p === "month_below_day" ? t2.capsProblems[p] : String(p ?? "");
1792
+ };
1793
+ var sideText = (d, t2) => isErrorCode(d["code"]) ? t2.sides[sideOf(d["code"])] : "";
1794
+ var en = {
1795
+ steps: {
1796
+ machine: "Your machine",
1797
+ invitation: "Invitation code",
1798
+ project: "Back-office reached by Soron",
1799
+ stack: "Stack",
1800
+ staff: "Who may ask",
1801
+ language: "Language",
1802
+ key: "Claude key",
1803
+ backup: "Backup key",
1804
+ caps: "Caps",
1805
+ timeZone: "Time zone",
1806
+ github: "Access to the code",
1807
+ tables: "Reads",
1808
+ names: "Masked names",
1809
+ draft: "Project drafted at Soron",
1810
+ readKey: "Read-only key on GitHub",
1811
+ verifyRead: "Soron reads the repo",
1812
+ hostVariable: "SORON_BADGE_SECRET on Vercel",
1813
+ branch: "Branch soron/setup",
1814
+ push: "Branch pushed",
1815
+ activation: "Soron is on",
1816
+ pr: "PR opened"
1817
+ },
1818
+ sides: { you: "your side", anthropic: "Anthropic's side", github: "GitHub's side", us: "our side" },
1819
+ errors: {
1820
+ gh_missing: { title: "gh is not installed", gesture: "Install it (cli.github.com), then: gh auth login" },
1821
+ gh_signed_out: { title: "gh is signed in to no account", gesture: "Run: gh auth login" },
1822
+ repo_dirty: { title: "Changes not committed", gesture: "Commit or stash them (git stash): the PR will hold Soron only" },
1823
+ detached_head: { title: "No branch checked out (detached HEAD)", gesture: "Switch to a branch: git switch main" },
1824
+ files_missing: { title: "The auth, database, schema or layout file is not found, or the database module exports no client", gesture: "Give their paths: --auth, --db, --schema, --layout" },
1825
+ stack_unknown: { title: "Soron plugs a Next.js back-office: its routes and its widget are Next.js code. Nothing was made", gesture: "Run the command in the repo of a Next.js back-office (App Router)" },
1826
+ too_many_reads: { title: "More than 50 tables to read: soron.config.json holds 50 at most", gesture: "Tick the 50 tables the staff asks about most" },
1827
+ secret_read: { title: 'A table or column to read holds a secret by its name in the schema (as password String @map("pass")): Soron never reads one', gesture: "Leave it out of --read" },
1828
+ staff_unchecked: { title: "Soron cannot check this staff rule: the schema has no such table or column, it is not on Auth.js's user table, or no Prisma or drizzle reads it", gesture: "Give a role column of the user table, by the database names (User.role=ADMIN), or let the person choose the admin area\u2019s guard" },
1829
+ layout_no_place: { title: "The admin layout shows no {children}: the widget has no place", gesture: "Point to the admin layout: --layout" },
1830
+ no_lockfile: { title: "No pnpm-lock.yaml or package-lock.json", gesture: "Install your dependencies first" },
1831
+ node_old: { title: "Node 22 or later is needed", gesture: "Update Node" },
1832
+ offline: { title: "No network", gesture: "Check your connection" },
1833
+ not_github: { title: "origin is not on GitHub", gesture: "Soron reads GitHub only for now" },
1834
+ invite_invalid: { title: "Invitation code unknown, expired or already used", gesture: "Ask the Soron team for a code" },
1835
+ too_many_checks: { title: "Too many Claude keys checked with this invitation code", gesture: "Ask the Soron team for a new code" },
1836
+ backoffice_unreachable: { title: "The back-office does not answer our service (Vercel protection, VPN?)", gesture: "Open /api/soron to server-to-server calls, then run again" },
1837
+ key_missing: { title: "No key given (or the link expired)", gesture: "Create one: console.anthropic.com/settings/keys" },
1838
+ key_invalid: { title: "Key refused: invalid or revoked", gesture: "Check it: console.anthropic.com/settings/keys" },
1839
+ no_credit: { title: "Valid key, no credit left", gesture: "Top up: console.anthropic.com/settings/billing" },
1840
+ model_access: { title: "Valid key, without access to Soron's model", gesture: "Open the access in the Anthropic Console, or use another key" },
1841
+ rate_limited: { title: "Anthropic is slowing this key down", gesture: "Try again in a few minutes" },
1842
+ overloaded: { title: "Anthropic is overloaded", gesture: "Try again in a few minutes \xB7 status.anthropic.com" },
1843
+ not_admin: { title: "You are not an admin of the repo", gesture: "An admin of the repo runs the command, or gives you the Admin role" },
1844
+ org_forbids_keys: { title: "The organization forbids deploy keys", gesture: "An owner allows them: the organization's settings \u203A Member privileges" },
1845
+ github_rate_limited: { title: "GitHub is slowing your account down", gesture: "Try again later" },
1846
+ service_down: { title: "The Soron service does not answer", gesture: "Try again in a few minutes" },
1847
+ read_failed: { title: "The service cannot read the repo yet", gesture: "Run again in a few minutes" },
1848
+ vercel_missing: { title: "vercel is not installed", gesture: "Install it (npm i -g vercel), then: vercel link" },
1849
+ vercel_refused: { title: "Vercel refuses: this account has no access to the project", gesture: "Sign in to the right account: vercel login, then vercel link" },
1850
+ origin_taken: { title: "This back-office is already connected to another Soron project", gesture: "Write to us: one address serves one project" },
1851
+ install_failed: { title: "@soron-ai/next does not install", gesture: "Run the install by hand to see why, then run again" },
1852
+ pre_commit: { title: "Your pre-commit hook refuses the commit", gesture: "Fix what it says, then run again. Soron never bypasses your hooks" },
1853
+ pre_push: { title: "Your pre-push hook refuses the push", gesture: "Fix what it says, then run again. Soron never bypasses your hooks" },
1854
+ pr_refused: { title: "GitHub refuses the PR", gesture: "Run again; if it stays: githubstatus.com" },
1855
+ caps_invalid: { title: "Caps that do not hold together", gesture: "Give three amounts: per question, per day (two questions at least), per month (a day at least)" },
1856
+ any_session_needs_human: { title: "\xAB Any session \xBB is chosen by a person only", gesture: "Run the command yourself, without an agent, for this choice" },
1857
+ interrupted: { title: "Interrupted (Ctrl+C)", gesture: "Run again whenever you like" },
1858
+ unexpected: { title: "Unexpected error of the command", gesture: "Run again; if it comes back, send us the message below" }
1859
+ },
1860
+ lines: {
1861
+ checked: (d, t2) => `\u2714 ${stepOf(d, t2)}`,
1862
+ created: (d, t2) => `\u2714 ${stepOf(d, t2)}`,
1863
+ reused: (d, t2) => `\u2714 ${stepOf(d, t2)} \xB7 taken up`,
1864
+ undone: (d, t2) => `\u21BA ${stepOf(d, t2)} \xB7 undone`,
1865
+ undo_failed: (d, t2) => `\u2716 ${stepOf(d, t2)} \xB7 not undone: remove it by hand`,
1866
+ error: (d, t2) => `\u2716 ${errorOf(d, t2).title} \xB7 ${sideText(d, t2)}
1867
+ \u2192 ${errorOf(d, t2).gesture}`,
1868
+ retry: (d, t2) => `\u25CC ${errorOf(d, t2).title} \xB7 trying again in ${d["seconds"]} s \xB7 ${d["attempt"]}/${d["of"]}`,
1869
+ retry_ok: () => "\u2714 The new try worked",
1870
+ caps_invalid: (d, t2) => `\u2716 ${problemOf(d, t2)}`,
1871
+ any_session: () => "\u26A0 Signed-in end clients will be able to ask Soron and spend your key",
1872
+ name_in_clear: (d) => `\u26A0 ${d["name"]} will reach the model in clear`,
1873
+ old_read_key: () => "An old Soron read key was found, with no active project: it will be replaced",
1874
+ cancelled: () => "Cancelled.",
1875
+ connected: (d) => `Soron is connected. Left to do: merge PR #${d["pr"]}, then deploy.`,
1876
+ already_connected: () => "This repo is already connected to Soron.",
1877
+ admin_proved: () => "\u2714 Admin of the repo \xB7 proved (a one-off key posted, read, removed)",
1878
+ nothing_changed: () => "\u2714 Nothing changed",
1879
+ caps_changed: () => "\u2714 Caps changed at Soron",
1880
+ caps_unchanged: () => "\u2714 Caps unchanged",
1881
+ next_question: () => "In effect from the next question, without a restart or a PR.",
1882
+ key_replaced: (d) => `\u2714 ${d["which"] === "backup" ? "Backup key" : "Claude key"} \xB7 checked, replaced at Soron (sealed)`,
1883
+ environments_changed: () => "\u2714 Environments changed at Soron, addresses checked",
1884
+ config_pr: (d) => `\u2714 PR #${d["pr"]} opened (soron.config.json)`,
1885
+ agent_new_link: () => "[agent] The link expired: give the person a new one. Never look for the key on the machine.",
1886
+ middleware_manual: (d) => `\u26A0 ${d["path"]}: its matcher may catch /api/soron. Leave /api/soron out of it, or our service's reads will be refused`,
1887
+ stack_found: (d) => `Stack: ${d["framework"]} \xB7 ${d["auth"] || "auth not recognised"} \xB7 ${d["orm"] || "no Prisma or drizzle"}`,
1888
+ adapter_to_complete: (d) => `\u26A0 Soron cannot read the sessions of ${d["auth"] || "this auth"}: write getStaff() in ${d["path"]} before you merge. Until then nobody gets a badge, and npx @soron-ai/next check says so`,
1889
+ code_only: () => "\u26A0 No Prisma or drizzle on Postgres: Soron answers from the code only, and reads no table",
1890
+ key_page: (d) => `[agent] Give the person this link: they paste their Claude key there, once, within ${d["minutes"]} minutes. Never look for the key yourself.
1891
+ ${d["url"]}`,
1892
+ nothing_created: () => "Nothing was made.",
1893
+ all_undone: () => "Everything is undone: nothing was left half-made.",
1894
+ some_left: () => "Undone, except what is said above."
1895
+ },
1896
+ capsProblems: {
1897
+ not_positive: "Each cap is a positive amount",
1898
+ day_below_high: "The day must hold one high question (two questions)",
1899
+ month_below_day: "The month must hold the day"
1900
+ },
1901
+ changes: { caps: "Caps", key: "Claude key", backup: "Backup key", environments: "Environments", reads: "Reads and masked names" },
1902
+ status: {
1903
+ keys: (backup) => `Claude key: held at Soron, sealed \xB7 backup key: ${backup ? "held" : "none"}`,
1904
+ caps: (q, day, month) => `Caps: $${q}/question ($${q * 2} in high) \xB7 $${day}/day \xB7 $${month}/month`,
1905
+ spend: (day, month) => `Spent: $${day.toFixed(2)} today, $${month.toFixed(2)} this month`,
1906
+ config: (problem) => problem ? `\u2716 soron.config.json ${problem}` : "\u2714 soron.config.json reads",
1907
+ version: (version, floor) => `@soron-ai/next ${version} \xB7 the oldest Soron reads through: ${floor}`
1908
+ },
1909
+ check: {
1910
+ routes: { ok: "\u2714 Soron's routes answer (/api/soron)", fail: "\u2716 Soron's routes do not answer \u2192 merge Soron's PR, then deploy" },
1911
+ secret: { ok: "\u2714 The badge secret is set", fail: "\u2716 SORON_BADGE_SECRET is missing at the host \u2192 run the command again, then redeploy" },
1912
+ adapter: { ok: "\u2714 Soron's adapter is complete", fail: "\u2716 Soron's adapter is to complete \u2192 write getStaff() in soron/adapter.ts, then deploy" },
1913
+ middleware: { ok: "\u2714 The middleware lets Soron's routes through", fail: "\u2716 The middleware redirects /api/soron \u2192 leave /api/soron out of its matcher" },
1914
+ csp: { ok: "\u2714 The page's CSP lets the widget reach Soron", fail: "\u2716 The page's CSP blocks Soron \u2192 add Soron's address to connect-src" },
1915
+ service: { ok: "\u2714 Soron sees the project", fail: "\u2716 Soron does not see this back-office \u2192 run npx @soron-ai/next again" },
1916
+ version: { ok: "\u2714 @soron-ai/next is recent enough", fail: "\u2716 @soron-ai/next is too old: Soron no longer reads through it \u2192 update it" }
1917
+ },
1918
+ ask: {
1919
+ invitation: "Soron invitation code",
1920
+ url: "Address of your back-office (https://\u2026/admin)",
1921
+ urlInvalid: "An https:// address",
1922
+ staff: "Who may ask Soron?",
1923
+ staffAny: "Any signed-in session \xB7 end clients included",
1924
+ staffEntry: "Who is staff: table.column=value1,value2",
1925
+ staffRole: (rule2) => `Whoever has ${rule2}`,
1926
+ staffGuard: (name, path) => `Whoever passes ${name}() \xB7 ${path}`,
1927
+ language: "Language of Soron's answers",
1928
+ key: "Claude key (nothing shows)",
1929
+ backup: "A backup key, for when the main one is refused?",
1930
+ backupKey: "Backup key (nothing shows)",
1931
+ caps: (q, day, month) => `Caps \xB7 $${q}/question ($${q * 2} in high) \xB7 $${day}/day \xB7 $${month}/month`,
1932
+ keep: "Keep",
1933
+ change: "Change",
1934
+ amounts: "Per question, per day, per month, in dollars (e.g. 1,20,200)",
1935
+ timeZone: "Time zone of the project (the day and month of the caps)",
1936
+ tables: "Tables Soron may read (read-only; secret columns always left out)",
1937
+ names: "Fields that hold a name, masked before the model",
1938
+ recap: "Make: the project, sealed keys and caps at Soron \xB7 a read key, a branch and a PR on GitHub \xB7 1 variable on Vercel?",
1939
+ changes: "What do you want to change? Nothing ticked: nothing changes",
1940
+ page: { title: "Soron \xB7 Claude key", label: "Your Claude key (it goes to Soron only, sealed)", button: "Send", done: "Received. Back to the terminal: you can close this page." }
1941
+ }
1942
+ };
1943
+ var fr = {
1944
+ steps: {
1945
+ machine: "Ta machine",
1946
+ invitation: "Code d'invitation",
1947
+ project: "Back-office joint par Soron",
1948
+ stack: "Stack",
1949
+ staff: "Qui peut demander",
1950
+ language: "Langue",
1951
+ key: "Cl\xE9 Claude",
1952
+ backup: "Cl\xE9 de secours",
1953
+ caps: "Plafonds",
1954
+ timeZone: "Fuseau",
1955
+ github: "Acc\xE8s au code",
1956
+ tables: "Lectures",
1957
+ names: "Noms masqu\xE9s",
1958
+ draft: "Projet r\xE9serv\xE9 chez nous",
1959
+ readKey: "Cl\xE9 de lecture sur GitHub",
1960
+ verifyRead: "Soron lit le d\xE9p\xF4t",
1961
+ hostVariable: "SORON_BADGE_SECRET chez Vercel",
1962
+ branch: "Branche soron/setup",
1963
+ push: "Branche envoy\xE9e",
1964
+ activation: "Soron activ\xE9",
1965
+ pr: "PR ouverte"
1966
+ },
1967
+ sides: { you: "de ton c\xF4t\xE9", anthropic: "c\xF4t\xE9 Anthropic", github: "c\xF4t\xE9 GitHub", us: "de notre c\xF4t\xE9" },
1968
+ errors: {
1969
+ gh_missing: { title: "gh introuvable", gesture: "Installe-le (cli.github.com), puis : gh auth login" },
1970
+ gh_signed_out: { title: "gh connect\xE9 \xE0 aucun compte", gesture: "Lance : gh auth login" },
1971
+ repo_dirty: { title: "Changements non commit\xE9s", gesture: "Commite ou range-les (git stash) : la PR ne contiendra que Soron" },
1972
+ detached_head: { title: "Aucune branche en cours (HEAD d\xE9tach\xE9)", gesture: "Passe sur une branche : git switch main" },
1973
+ files_missing: { title: "Le fichier de l'auth, de la base, du sch\xE9ma ou du layout est introuvable, ou le module de la base n'exporte aucun client", gesture: "Donne leurs chemins : --auth, --db, --schema, --layout" },
1974
+ stack_unknown: { title: "Soron branche un back-office Next.js : ses routes et son widget sont du code Next.js. Rien n'a \xE9t\xE9 cr\xE9\xE9", gesture: "Lance la commande dans le d\xE9p\xF4t d'un back-office Next.js (App Router)" },
1975
+ too_many_reads: { title: "Plus de 50 tables \xE0 lire : soron.config.json en tient 50 au plus", gesture: "Coche les 50 tables sur lesquelles le staff pose le plus de questions" },
1976
+ secret_read: { title: `Une table ou une colonne \xE0 lire tient un secret par son nom dans le sch\xE9ma (comme password String @map("pass")) : Soron n'en lit jamais`, gesture: "Retire-la de --read" },
1977
+ staff_unchecked: { title: "Soron ne peut pas v\xE9rifier cette r\xE8gle staff : le sch\xE9ma n'a pas cette table ou cette colonne, elle n'est pas sur la table des utilisateurs d'Auth.js, ou ni Prisma ni drizzle ne la lit", gesture: "Donne une colonne de r\xF4le de la table des utilisateurs, par les noms de la base (User.role=ADMIN), ou laisse la personne choisir la garde de l\u2019espace admin" },
1978
+ layout_no_place: { title: "Le layout de l'admin ne montre pas {children} : le widget n'a pas de place", gesture: "Indique le layout de l'admin : --layout" },
1979
+ no_lockfile: { title: "Ni pnpm-lock.yaml ni package-lock.json", gesture: "Installe d'abord tes d\xE9pendances" },
1980
+ node_old: { title: "Node 22 ou plus requis", gesture: "Mets Node \xE0 jour" },
1981
+ offline: { title: "Pas de r\xE9seau", gesture: "V\xE9rifie ta connexion" },
1982
+ not_github: { title: "origin n'est pas sur GitHub", gesture: "Soron lit seulement GitHub pour l'instant" },
1983
+ invite_invalid: { title: "Code d'invitation inconnu, expir\xE9 ou d\xE9j\xE0 utilis\xE9", gesture: "Demande un code \xE0 l'\xE9quipe Soron" },
1984
+ too_many_checks: { title: "Trop de cl\xE9s Claude v\xE9rifi\xE9es avec ce code d'invitation", gesture: "Demande un nouveau code \xE0 l'\xE9quipe Soron" },
1985
+ backoffice_unreachable: { title: "Le back-office ne r\xE9pond pas \xE0 notre service (protection Vercel, VPN ?)", gesture: "Ouvre /api/soron aux appels de serveur \xE0 serveur, puis relance" },
1986
+ key_missing: { title: "Aucune cl\xE9 saisie (ou lien expir\xE9)", gesture: "Cr\xE9e-en une : console.anthropic.com/settings/keys" },
1987
+ key_invalid: { title: "Cl\xE9 refus\xE9e : invalide ou r\xE9voqu\xE9e", gesture: "V\xE9rifie-la : console.anthropic.com/settings/keys" },
1988
+ no_credit: { title: "Cl\xE9 valide, cr\xE9dit \xE9puis\xE9", gesture: "Recharge : console.anthropic.com/settings/billing" },
1989
+ model_access: { title: "Cl\xE9 valide, sans acc\xE8s au mod\xE8le de Soron", gesture: "Ouvre l'acc\xE8s dans la Console Anthropic, ou prends une autre cl\xE9" },
1990
+ rate_limited: { title: "Anthropic freine cette cl\xE9", gesture: "R\xE9essaie dans quelques minutes" },
1991
+ overloaded: { title: "Anthropic surcharg\xE9", gesture: "R\xE9essaie dans quelques minutes \xB7 status.anthropic.com" },
1992
+ not_admin: { title: "Tu n'es pas admin du d\xE9p\xF4t", gesture: "Un admin du d\xE9p\xF4t lance la commande, ou te donne le r\xF4le Admin" },
1993
+ org_forbids_keys: { title: "L'organisation interdit les cl\xE9s de d\xE9ploiement", gesture: "Un owner les autorise : r\xE9glages de l'organisation \u203A Member privileges" },
1994
+ github_rate_limited: { title: "GitHub freine ton compte", gesture: "R\xE9essaie plus tard" },
1995
+ service_down: { title: "Service Soron injoignable", gesture: "R\xE9essaie dans quelques minutes" },
1996
+ read_failed: { title: "Le service ne lit pas encore le d\xE9p\xF4t", gesture: "Relance dans quelques minutes" },
1997
+ vercel_missing: { title: "vercel introuvable", gesture: "Installe-le (npm i -g vercel), puis : vercel link" },
1998
+ vercel_refused: { title: "Vercel refuse : compte sans acc\xE8s au projet", gesture: "Connecte le bon compte : vercel login, puis vercel link" },
1999
+ origin_taken: { title: "Ce back-office est d\xE9j\xE0 branch\xE9 sur un autre projet Soron", gesture: "\xC9cris-nous : une adresse sert un seul projet" },
2000
+ install_failed: { title: "@soron-ai/next ne s'installe pas", gesture: "Lance l'installation \xE0 la main pour voir pourquoi, puis relance" },
2001
+ pre_commit: { title: "Ton crochet pre-commit refuse le commit", gesture: "Corrige selon son message, puis relance. Soron ne contourne jamais tes crochets" },
2002
+ pre_push: { title: "Ton crochet pre-push refuse l'envoi", gesture: "Corrige selon son message, puis relance. Soron ne contourne jamais tes crochets" },
2003
+ pr_refused: { title: "GitHub refuse la PR", gesture: "Relance ; sinon : githubstatus.com" },
2004
+ caps_invalid: { title: "Plafonds incoh\xE9rents", gesture: "Donne trois montants : par question, par jour (deux questions au moins), par mois (un jour au moins)" },
2005
+ any_session_needs_human: { title: "\xAB Toute session \xBB ne se choisit qu'\xE0 la main", gesture: "Lance la commande toi-m\xEAme, sans agent, pour ce choix" },
2006
+ interrupted: { title: "Interrompu (Ctrl+C)", gesture: "Relance quand tu veux" },
2007
+ unexpected: { title: "Erreur impr\xE9vue de la commande", gesture: "Relance ; si elle revient, envoie-nous le message ci-dessous" }
2008
+ },
2009
+ lines: {
2010
+ checked: (d, t2) => `\u2714 ${stepOf(d, t2)}`,
2011
+ created: (d, t2) => `\u2714 ${stepOf(d, t2)}`,
2012
+ reused: (d, t2) => `\u2714 ${stepOf(d, t2)} \xB7 repris`,
2013
+ undone: (d, t2) => `\u21BA ${stepOf(d, t2)} \xB7 d\xE9fait`,
2014
+ undo_failed: (d, t2) => `\u2716 ${stepOf(d, t2)} \xB7 pas d\xE9fait : \xE0 retirer \xE0 la main`,
2015
+ error: (d, t2) => `\u2716 ${errorOf(d, t2).title} \xB7 ${sideText(d, t2)}
2016
+ \u2192 ${errorOf(d, t2).gesture}`,
2017
+ retry: (d, t2) => `\u25CC ${errorOf(d, t2).title} \xB7 nouvel essai dans ${d["seconds"]} s \xB7 ${d["attempt"]}/${d["of"]}`,
2018
+ retry_ok: () => "\u2714 Nouvel essai r\xE9ussi",
2019
+ caps_invalid: (d, t2) => `\u2716 ${problemOf(d, t2)}`,
2020
+ any_session: () => "\u26A0 Les clients finaux connect\xE9s pourront demander \xE0 Soron et d\xE9penser ta cl\xE9",
2021
+ name_in_clear: (d) => `\u26A0 ${d["name"]} partira en clair vers le mod\xE8le`,
2022
+ old_read_key: () => "Ancienne cl\xE9 de lecture Soron trouv\xE9e, sans projet actif : elle sera remplac\xE9e",
2023
+ cancelled: () => "Annul\xE9.",
2024
+ connected: (d) => `Soron est branch\xE9. Reste : fusionner la PR n\xB0 ${d["pr"]}, puis d\xE9ployer.`,
2025
+ already_connected: () => "Ce d\xE9p\xF4t est d\xE9j\xE0 branch\xE9 sur Soron.",
2026
+ admin_proved: () => "\u2714 Admin du d\xE9p\xF4t \xB7 prouv\xE9 (cl\xE9 jetable pos\xE9e, lue, retir\xE9e)",
2027
+ nothing_changed: () => "\u2714 Rien n'a chang\xE9",
2028
+ caps_changed: () => "\u2714 Plafonds chang\xE9s chez nous",
2029
+ caps_unchanged: () => "\u2714 Plafonds inchang\xE9s",
2030
+ next_question: () => "Effet \xE0 la question suivante, sans red\xE9marrage ni PR.",
2031
+ key_replaced: (d) => `\u2714 ${d["which"] === "backup" ? "Cl\xE9 de secours" : "Cl\xE9 Claude"} \xB7 v\xE9rifi\xE9e, remplac\xE9e chez nous (chiffr\xE9e)`,
2032
+ environments_changed: () => "\u2714 Environnements chang\xE9s chez nous, adresses v\xE9rifi\xE9es",
2033
+ config_pr: (d) => `\u2714 PR n\xB0 ${d["pr"]} ouverte (soron.config.json)`,
2034
+ agent_new_link: () => "[agent] Lien expir\xE9 : donne un nouveau lien \xE0 la personne. Ne cherche jamais la cl\xE9 sur la machine.",
2035
+ middleware_manual: (d) => `\u26A0 ${d["path"]} : son matcher peut prendre /api/soron. Laisse /api/soron en dehors, sinon les lectures de notre service seront refus\xE9es`,
2036
+ stack_found: (d) => `Stack : ${d["framework"]} \xB7 ${d["auth"] || "auth non reconnue"} \xB7 ${d["orm"] || "ni Prisma ni drizzle"}`,
2037
+ adapter_to_complete: (d) => `\u26A0 Soron ne sait pas lire les sessions de ${d["auth"] || "cette auth"} : \xE9cris getStaff() dans ${d["path"]} avant de fusionner. D'ici l\xE0, personne n'a de badge, et npx @soron-ai/next check le dit`,
2038
+ code_only: () => "\u26A0 Ni Prisma ni drizzle sur Postgres : Soron r\xE9pond depuis le code seul, et ne lit aucune table",
2039
+ key_page: (d) => `[agent] Donne ce lien \xE0 la personne : elle y colle sa cl\xE9 Claude, une fois, dans les ${d["minutes"]} minutes. Ne cherche jamais la cl\xE9 toi-m\xEAme.
2040
+ ${d["url"]}`,
2041
+ nothing_created: () => "Rien n'a \xE9t\xE9 cr\xE9\xE9.",
2042
+ all_undone: () => "Tout est d\xE9fait : rien n'est rest\xE9 \xE0 moiti\xE9.",
2043
+ some_left: () => "D\xE9fait, sauf ce qui est dit plus haut."
2044
+ },
2045
+ capsProblems: {
2046
+ not_positive: "Chaque plafond est un montant positif",
2047
+ day_below_high: "Le jour doit tenir une question en high (deux questions)",
2048
+ month_below_day: "Le mois doit tenir le jour"
2049
+ },
2050
+ changes: { caps: "Plafonds", key: "Cl\xE9 Claude", backup: "Cl\xE9 de secours", environments: "Environnements", reads: "Lectures et noms masqu\xE9s" },
2051
+ status: {
2052
+ keys: (backup) => `Cl\xE9 Claude : gard\xE9e chez Soron, chiffr\xE9e \xB7 cl\xE9 de secours : ${backup ? "gard\xE9e" : "aucune"}`,
2053
+ caps: (q, day, month) => `Plafonds : ${q} $/question (${q * 2} $ en high) \xB7 ${day} $/jour \xB7 ${month} $/mois`,
2054
+ spend: (day, month) => `D\xE9pens\xE9 : ${day.toFixed(2)} $ aujourd'hui, ${month.toFixed(2)} $ ce mois-ci`,
2055
+ config: (problem) => problem ? `\u2716 soron.config.json ${problem}` : "\u2714 soron.config.json se lit",
2056
+ version: (version, floor) => `@soron-ai/next ${version} \xB7 la plus ancienne que Soron lit encore : ${floor}`
2057
+ },
2058
+ check: {
2059
+ routes: { ok: "\u2714 Les routes de Soron r\xE9pondent (/api/soron)", fail: "\u2716 Les routes de Soron ne r\xE9pondent pas \u2192 fusionne la PR de Soron, puis d\xE9ploie" },
2060
+ secret: { ok: "\u2714 Le secret du badge est pos\xE9", fail: "\u2716 SORON_BADGE_SECRET manque chez l'h\xE9bergeur \u2192 relance la commande, puis red\xE9ploie" },
2061
+ adapter: { ok: "\u2714 L'adaptateur de Soron est complet", fail: "\u2716 L'adaptateur de Soron est \xE0 compl\xE9ter \u2192 \xE9cris getStaff() dans soron/adapter.ts, puis d\xE9ploie" },
2062
+ middleware: { ok: "\u2714 Le middleware laisse passer les routes de Soron", fail: "\u2716 Le middleware redirige /api/soron \u2192 laisse /api/soron en dehors de son matcher" },
2063
+ csp: { ok: "\u2714 La CSP de la page laisse le widget joindre Soron", fail: "\u2716 La CSP de la page bloque Soron \u2192 ajoute l'adresse de Soron \xE0 connect-src" },
2064
+ service: { ok: "\u2714 Soron voit le projet", fail: "\u2716 Soron ne voit pas ce back-office \u2192 relance npx @soron-ai/next" },
2065
+ version: { ok: "\u2714 @soron-ai/next est assez r\xE9cent", fail: "\u2716 @soron-ai/next est trop ancien : Soron ne lit plus \xE0 travers lui \u2192 mets-le \xE0 jour" }
2066
+ },
2067
+ ask: {
2068
+ invitation: "Code d'invitation Soron",
2069
+ url: "Adresse de ton back-office (https://\u2026/admin)",
2070
+ urlInvalid: "Une adresse https://",
2071
+ staff: "Qui peut demander \xE0 Soron ?",
2072
+ staffAny: "Toute session connect\xE9e \xB7 clients compris",
2073
+ staffEntry: "Qui est du staff : table.colonne=valeur1,valeur2",
2074
+ staffRole: (rule2) => `Qui a ${rule2}`,
2075
+ staffGuard: (name, path) => `Qui passe ${name}() \xB7 ${path}`,
2076
+ language: "Langue des r\xE9ponses de Soron",
2077
+ key: "Cl\xE9 Claude (rien ne s'affiche)",
2078
+ backup: "Une cl\xE9 de secours, si la principale est refus\xE9e ?",
2079
+ backupKey: "Cl\xE9 de secours (rien ne s'affiche)",
2080
+ caps: (q, day, month) => `Plafonds \xB7 ${q} $/question (${q * 2} $ en high) \xB7 ${day} $/jour \xB7 ${month} $/mois`,
2081
+ keep: "Garder",
2082
+ change: "Changer",
2083
+ amounts: "Par question, par jour, par mois, en dollars (ex. 1,20,200)",
2084
+ timeZone: "Fuseau du projet (le jour et le mois des plafonds)",
2085
+ tables: "Tables que Soron peut lire (lecture seule ; colonnes secr\xE8tes exclues d'office)",
2086
+ names: "Champs qui portent un nom, masqu\xE9s avant le mod\xE8le",
2087
+ recap: "Cr\xE9er : projet, cl\xE9s chiffr\xE9es et plafonds chez nous \xB7 cl\xE9 de lecture, branche et PR sur GitHub \xB7 1 variable chez Vercel ?",
2088
+ changes: "Que veux-tu changer ? Rien de coch\xE9 : rien ne change",
2089
+ page: { title: "Soron \xB7 cl\xE9 Claude", label: "Ta cl\xE9 Claude (elle part chez Soron seulement, chiffr\xE9e)", button: "Envoyer", done: "Re\xE7ue. Retour au terminal : tu peux fermer cette page." }
2090
+ }
2091
+ };
2092
+ var TEXTS = { en, fr };
2093
+ function machineLanguage(env = process.env) {
2094
+ const locale = env["LC_ALL"] || env["LC_MESSAGES"] || env["LANG"] || Intl.DateTimeFormat().resolvedOptions().locale;
2095
+ return /^fr\b|^fr[_-]/i.test(locale) ? "fr" : "en";
2096
+ }
2097
+ var textOf = (line, t2) => t2.lines[line.key](line.detail ?? {}, t2);
2098
+
2099
+ // src/setup/screen.ts
2100
+ var cancelled = () => new StepError("interrupted");
2101
+ var str = (v) => {
2102
+ if (typeof v === "symbol") throw cancelled();
2103
+ return v;
2104
+ };
2105
+ var yes = (v) => {
2106
+ if (typeof v === "symbol") throw cancelled();
2107
+ return v;
2108
+ };
2109
+ var language = (v) => {
2110
+ if (typeof v === "symbol") throw cancelled();
2111
+ return v;
2112
+ };
2113
+ var strings = (v) => {
2114
+ if (typeof v === "symbol") throw cancelled();
2115
+ return v;
2116
+ };
2117
+ var changes = (v) => {
2118
+ if (typeof v === "symbol") throw cancelled();
2119
+ return v;
2120
+ };
2121
+ var serviceAddress = (s) => {
2122
+ try {
2123
+ const u4 = new URL(s);
2124
+ return u4.protocol === "https:" || u4.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u4.hostname);
2125
+ } catch {
2126
+ return false;
2127
+ }
2128
+ };
2129
+ var CHANGES2 = ["caps", "key", "backup", "environments", "reads"];
2130
+ var ruleText = (r2, t2) => r2.kind === "role" ? t2.ask.staffRole(`${r2.table}.${r2.column} = ${r2.values.join(", ")}`) : r2.kind === "guard" ? t2.ask.staffGuard(r2.name, r2.path) : t2.ask.staffAny;
2131
+ function screenAsk(t2) {
2132
+ const secret = async (message) => str(await password({ message, mask: "\u2022" })).trim();
2133
+ return {
2134
+ invitation: () => secret(t2.ask.invitation),
2135
+ async environments(proposal) {
2136
+ const first = proposal[0] ?? { name: "production", branch: "", url: "" };
2137
+ const url = str(await text({ message: t2.ask.url, initialValue: first.url, validate: (v) => serviceAddress(v ?? "") ? void 0 : t2.ask.urlInvalid }));
2138
+ return [{ ...first, url: url.trim() }, ...proposal.slice(1)];
2139
+ },
2140
+ // The rules found (step 4 of sprint 2 finds more); « any session » comes with its adapter then.
2141
+ async staff(proposal) {
2142
+ if (proposal.length === 0) {
2143
+ const typed2 = str(await text({ message: t2.ask.staffEntry, validate: (v) => staffRule(v ?? "") ? void 0 : t2.ask.staffEntry }));
2144
+ return staffRule(typed2) ?? { kind: "any_session" };
2145
+ }
2146
+ const picked = str(await select({ message: t2.ask.staff, options: [...proposal.map((r2, i2) => ({ value: String(i2), label: ruleText(r2, t2) })), { value: "typed", label: t2.ask.staffEntry }] }));
2147
+ const chosen = proposal[Number(picked)];
2148
+ if (chosen) return chosen;
2149
+ const typed = str(await text({ message: t2.ask.staffEntry, validate: (v) => staffRule(v ?? "") ? void 0 : t2.ask.staffEntry }));
2150
+ return staffRule(typed) ?? { kind: "any_session" };
2151
+ },
2152
+ language: async (proposal) => language(
2153
+ await select({
2154
+ message: t2.ask.language,
2155
+ initialValue: proposal,
2156
+ options: [
2157
+ { value: "fr", label: "Fran\xE7ais" },
2158
+ { value: "en", label: "English" }
2159
+ ]
2160
+ })
2161
+ ),
2162
+ key: () => secret(t2.ask.key),
2163
+ async backup() {
2164
+ if (!yes(await confirm({ message: t2.ask.backup, initialValue: false }))) return null;
2165
+ return secret(t2.ask.backupKey);
2166
+ },
2167
+ async caps(proposal, problem) {
2168
+ if (problem === null) {
2169
+ const keep = str(
2170
+ await select({
2171
+ message: t2.ask.caps(proposal.question, proposal.day, proposal.month),
2172
+ options: [
2173
+ { value: "keep", label: t2.ask.keep },
2174
+ { value: "change", label: t2.ask.change }
2175
+ ]
2176
+ })
2177
+ );
2178
+ if (keep === "keep") return proposal;
2179
+ }
2180
+ const typed = str(await text({ message: t2.ask.amounts, initialValue: `${proposal.question},${proposal.day},${proposal.month}` }));
2181
+ const [question = NaN, day = NaN, month = NaN] = typed.split(",").map(Number);
2182
+ const caps = { question, day, month };
2183
+ return caps;
2184
+ },
2185
+ timeZone: async (proposal) => str(await text({ message: t2.ask.timeZone, initialValue: proposal })).trim() || proposal,
2186
+ tables: async (proposal) => strings(await multiselect({ message: t2.ask.tables, required: false, options: proposal.map((c2) => ({ value: c2.name, label: c2.name })), initialValues: proposal.filter((c2) => c2.proposed).map((c2) => c2.name) })),
2187
+ names: async (proposal) => proposal.length === 0 ? [] : strings(await multiselect({ message: t2.ask.names, required: false, options: proposal.map((c2) => ({ value: c2.name, label: c2.name })), initialValues: proposal.filter((c2) => c2.proposed).map((c2) => c2.name) })),
2188
+ recap: async () => yes(await confirm({ message: t2.ask.recap, initialValue: true })),
2189
+ changes: async () => changes(await multiselect({ message: t2.ask.changes, required: false, options: CHANGES2.map((c2) => ({ value: c2, label: t2.changes[c2] })) }))
2190
+ };
2191
+ }
2192
+ var TONES = { ok: import_picocolors.default.green, info: (s) => s, warn: import_picocolors.default.yellow, err: import_picocolors.default.red, wait: import_picocolors.default.dim, undo: import_picocolors.default.cyan, agent: import_picocolors.default.magenta };
2193
+ var screenLine = (line, t2) => TONES[line.tone](textOf(line, t2));
2194
+
2195
+ // src/setup/check.ts
2196
+ var opts = () => ({ redirect: "manual", signal: AbortSignal.timeout(15e3) });
2197
+ function cspAllows(policy, service) {
2198
+ if (!policy) return true;
2199
+ const directives = new Map(
2200
+ policy.split(";").map((d) => d.trim().split(/\s+/)).filter((d) => d[0]).map((d) => [d[0]?.toLowerCase() ?? "", d.slice(1)])
2201
+ );
2202
+ const sources = directives.get("connect-src") ?? directives.get("default-src");
2203
+ if (!sources) return true;
2204
+ const origin = new URL(service).origin;
2205
+ return sources.some((s) => s === "*" || s === "https:" || s.replace(/\/$/, "") === origin || s.startsWith("https://*.") && new URL(service).hostname.endsWith(s.slice("https://*".length)));
2206
+ }
2207
+ async function checkDeployed(o) {
2208
+ const origin = new URL(o.url).origin;
2209
+ const lines = [];
2210
+ const token = await fetch(`${origin}/api/soron/token`, { ...opts(), method: "POST", headers: { origin, "content-type": "application/json" }, body: "{}" }).catch(() => void 0);
2211
+ const status2 = token?.status ?? 0;
2212
+ const error = status2 === 503 ? await token?.json().then((b) => typeof b === "object" && b !== null && "error" in b ? b.error : void 0, () => void 0) : void 0;
2213
+ const incomplete = error === "adapter_incomplete";
2214
+ const redirected = status2 >= 300 && status2 < 400;
2215
+ lines.push({ key: "middleware", ok: !redirected });
2216
+ lines.push({ key: "routes", ok: status2 === 401 || status2 === 403 || status2 === 503 });
2217
+ lines.push({ key: "secret", ok: status2 === 401 || status2 === 403 || incomplete });
2218
+ lines.push({ key: "adapter", ok: !incomplete });
2219
+ const page2 = await fetch(o.url, { ...opts(), method: "GET" }).catch(() => void 0);
2220
+ lines.push({ key: "csp", ok: cspAllows(page2?.headers.get("content-security-policy") ?? null, o.service) });
2221
+ const state = await fetch(new URL(`/v1/state?origin=${encodeURIComponent(origin)}`, o.service), opts()).then((r2) => r2.json()).catch(() => void 0);
2222
+ const active = typeof state === "object" && state !== null && "active" in state && state.active === true;
2223
+ const floor = typeof state === "object" && state !== null && "floor" in state && typeof state.floor === "string" ? state.floor : "0.0.0";
2224
+ lines.push({ key: "service", ok: active });
2225
+ const deployed = token?.headers.get(VERSION_HEADER);
2226
+ lines.push({ key: "version", ok: typeof deployed === "string" && !olderThan(deployed, floor) });
2227
+ return lines;
2228
+ }
2229
+
2230
+ // src/setup/instructions.ts
2231
+ var INSTRUCTIONS = `# Installing Soron for a person, as an AI agent
2232
+
2233
+ Run the command with every answer as an option, and --yes:
2234
+
2235
+ npx @soron-ai/next --yes --invite <code> --url https://\u2026/admin \\
2236
+ --staff <table>.<column>=<value1>,<value2> --read <table>:<column1>,<column2> \\
2237
+ --names <table>:<column> --language en|fr --caps 1,20,200 --time-zone <zone>
2238
+
2239
+ Ask the person, never guess:
2240
+ - the invitation code Soron gave them;
2241
+ - the address of their back-office (https://\u2026/admin);
2242
+ - who is staff: the role column and its values. \xAB Any signed-in session \xBB lets end clients ask and
2243
+ spend the key: only the person chooses it, by running the command themselves;
2244
+ - the tables Soron may read, and the fields that hold a person's name (masked before the model);
2245
+ - the caps per question, per day and per month, in dollars (1,20,200 by default).
2246
+
2247
+ Tables and columns go by their names in the database: with Prisma, a model's @@map and a field's
2248
+ @map, else the model's and the field's own names. Soron plugs Next.js back-offices (App Router).
2249
+ The command finds the stack and its files; give --auth, --db, --schema or --layout only when it says
2250
+ it cannot find one. For an auth Soron cannot read, the PR carries an adapter whose getStaff() the
2251
+ person writes: tell them, and show them the command's lines.
2252
+
2253
+ The Claude key: the command prints a one-off link. Give it to the person; they paste their key there.
2254
+ Never read, search for or ask for the key yourself; never put it in a file, an option or the chat.
2255
+ In a CI only: --anthropic-key-stdin, the key on the command's input.
2256
+
2257
+ The command checks everything before it makes anything, and undoes everything at the first failure.
2258
+ Show the person its last lines: what failed, on whose side, and what to do.
2259
+ `;
2260
+
2261
+ // src/setup/setup.ts
2262
+ import { randomBytes as randomBytes2 } from "node:crypto";
2263
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
2264
+ import { dirname, join as join3 } from "node:path";
2265
+
2266
+ // src/setup/detect.ts
2267
+ import { posix } from "node:path";
2268
+ function enclosed(text2, open) {
2269
+ const pairs = { "(": ")", "{": "}", "[": "]" };
2270
+ const stack = [];
2271
+ for (let i2 = open; i2 < text2.length; i2++) {
2272
+ const c2 = text2[i2] ?? "";
2273
+ if (c2 === '"' || c2 === "'" || c2 === "`") {
2274
+ const end = text2.indexOf(c2, i2 + 1);
2275
+ if (end < 0) return void 0;
2276
+ i2 = end;
2277
+ } else if (c2 === "/" && text2[i2 + 1] === "/") i2 = text2.indexOf("\n", i2) < 0 ? text2.length : text2.indexOf("\n", i2);
2278
+ else if (c2 === "/" && text2[i2 + 1] === "*") i2 = text2.indexOf("*/", i2) < 0 ? text2.length : text2.indexOf("*/", i2) + 1;
2279
+ else if (pairs[c2]) stack.push(pairs[c2]);
2280
+ else if (c2 === stack.at(-1)) {
2281
+ stack.pop();
2282
+ if (stack.length === 0) return text2.slice(open + 1, i2);
2283
+ }
2284
+ }
2285
+ return void 0;
2286
+ }
2287
+ function uncommented(text2) {
2288
+ let out = "";
2289
+ for (let i2 = 0; i2 < text2.length; i2++) {
2290
+ const c2 = text2[i2] ?? "";
2291
+ if (c2 === '"' || c2 === "'" || c2 === "`") {
2292
+ const end = text2.indexOf(c2, i2 + 1);
2293
+ const stop = end < 0 ? text2.length : end;
2294
+ out += text2.slice(i2, stop + 1);
2295
+ i2 = stop;
2296
+ } else if (c2 === "/" && text2[i2 + 1] === "/") {
2297
+ const end = text2.indexOf("\n", i2);
2298
+ i2 = end < 0 ? text2.length : end - 1;
2299
+ } else if (c2 === "/" && text2[i2 + 1] === "*") {
2300
+ const end = text2.indexOf("*/", i2 + 2);
2301
+ i2 = end < 0 ? text2.length : end + 1;
2302
+ } else out += c2;
2303
+ }
2304
+ return out;
2305
+ }
2306
+ function entries(body) {
2307
+ const out = [];
2308
+ let depth = 0;
2309
+ let from = 0;
2310
+ for (let i2 = 0; i2 < body.length; i2++) {
2311
+ const c2 = body[i2] ?? "";
2312
+ if (c2 === '"' || c2 === "'" || c2 === "`") i2 = Math.max(i2, body.indexOf(c2, i2 + 1));
2313
+ else if ("({[".includes(c2)) depth++;
2314
+ else if (")}]".includes(c2)) depth--;
2315
+ else if (c2 === "," && depth === 0) {
2316
+ out.push(body.slice(from, i2));
2317
+ from = i2 + 1;
2318
+ }
2319
+ }
2320
+ return [...out, body.slice(from)].map((e) => e.trim()).filter(Boolean);
2321
+ }
2322
+ function drizzleSchema(source) {
2323
+ const text2 = uncommented(source);
2324
+ const tables = [];
2325
+ for (const m2 of text2.matchAll(/\bpgTable\(\s*(['"`])([^'"`]+)\1\s*,\s*\{/g)) {
2326
+ const name = m2[2] ?? "";
2327
+ const body = enclosed(text2, (m2.index ?? 0) + m2[0].length - 1);
2328
+ if (!body) continue;
2329
+ const columns = [];
2330
+ for (const e of entries(body)) {
2331
+ const c2 = /^(\w+)\s*:\s*[\w$.]+\(\s*(?:(['"`])([^'"`]+)\2)?/.exec(e);
2332
+ const key = c2?.[1];
2333
+ if (key) columns.push({ key, column: c2?.[3] ?? key });
2334
+ }
2335
+ tables.push({ name, columns });
2336
+ }
2337
+ return tables;
2338
+ }
2339
+ var PRISMA_SCALARS = /* @__PURE__ */ new Set(["String", "Int", "BigInt", "Float", "Decimal", "Boolean", "DateTime", "Json", "Bytes"]);
2340
+ function prismaModels(source) {
2341
+ const text2 = uncommented(source);
2342
+ const enums = new Set([...text2.matchAll(/\benum\s+(\w+)\s*\{/g)].map((m2) => m2[1] ?? ""));
2343
+ const models = [];
2344
+ for (const m2 of text2.matchAll(/\bmodel\s+(\w+)\s*\{/g)) {
2345
+ const body = enclosed(text2, (m2.index ?? 0) + m2[0].length - 1);
2346
+ if (body === void 0) continue;
2347
+ const model = m2[1] ?? "";
2348
+ const fields = [];
2349
+ for (const line of body.split("\n").map((l) => l.trim())) {
2350
+ const f = /^(\w+)\s+(\w+)(\[\])?\??/.exec(line);
2351
+ if (!f || line.startsWith("@@")) continue;
2352
+ const type = f[2] ?? "";
2353
+ if (f[3] || !(PRISMA_SCALARS.has(type) || enums.has(type) || type === "Unsupported")) continue;
2354
+ fields.push({ name: f[1] ?? "", column: /@map\(\s*"([^"]+)"\s*\)/.exec(line)?.[1] ?? f[1] ?? "", id: /@id\b/.test(line) });
2355
+ }
2356
+ models.push({ model, table: /@@map\(\s*"([^"]+)"\s*\)/.exec(body)?.[1] ?? model, fields });
2357
+ }
2358
+ return models;
2359
+ }
2360
+ function authjsNames(models) {
2361
+ const of = (model) => models.find((m2) => m2.model === model);
2362
+ const column = (m2, field) => m2.fields.find((f) => f.name === field)?.column;
2363
+ const user = of("User");
2364
+ const id2 = user && column(user, "id");
2365
+ if (!user || !id2) return void 0;
2366
+ const s = of("Session");
2367
+ const [token, userId, expires] = s ? [column(s, "sessionToken"), column(s, "userId"), column(s, "expires")] : [];
2368
+ return { user: { table: user.table, id: id2 }, sessions: s && token && userId && expires ? { table: s.table, token, userId, expires } : void 0 };
2369
+ }
2370
+ function dependencies(manifest) {
2371
+ let deps = {};
2372
+ try {
2373
+ const m2 = JSON.parse(manifest);
2374
+ if (typeof m2 !== "object" || m2 === null) return void 0;
2375
+ for (const k of ["dependencies", "devDependencies"]) {
2376
+ const d = Reflect.get(m2, k);
2377
+ if (typeof d === "object" && d !== null) deps = { ...deps, ...Object.fromEntries(Object.entries(d).filter((e) => typeof e[1] === "string")) };
2378
+ }
2379
+ } catch {
2380
+ return void 0;
2381
+ }
2382
+ return deps;
2383
+ }
2384
+ var authjsV5 = (version) => version !== void 0 && (/^\D*5\./.test(version) || version === "beta");
2385
+ function stackOf(manifest) {
2386
+ const deps = dependencies(manifest);
2387
+ if (!deps || !("next" in deps)) return void 0;
2388
+ if (authjsV5(deps["next-auth"]) && "@prisma/client" in deps) return "authjs-prisma";
2389
+ if ("better-auth" in deps && "drizzle-orm" in deps) return "better-auth-drizzle";
2390
+ return void 0;
2391
+ }
2392
+ var FRAMEWORKS = [
2393
+ ["next", "Next.js"],
2394
+ ["@remix-run/react", "Remix"],
2395
+ ["@react-router/dev", "React Router"],
2396
+ ["@sveltejs/kit", "SvelteKit"],
2397
+ ["nuxt", "Nuxt"],
2398
+ ["astro", "Astro"],
2399
+ ["@nestjs/core", "NestJS"],
2400
+ ["express", "Express"],
2401
+ ["vite", "Vite"]
2402
+ ];
2403
+ var AUTHS = [
2404
+ ["better-auth", "better-auth"],
2405
+ ["@clerk/nextjs", "Clerk"],
2406
+ ["@supabase/ssr", "Supabase Auth"],
2407
+ ["@supabase/auth-helpers-nextjs", "Supabase Auth"],
2408
+ ["@auth0/nextjs-auth0", "Auth0"],
2409
+ ["@kinde-oss/kinde-auth-nextjs", "Kinde"],
2410
+ ["@workos-inc/authkit-nextjs", "WorkOS AuthKit"],
2411
+ ["@stackframe/stack", "Stack Auth"],
2412
+ ["lucia", "Lucia"],
2413
+ ["iron-session", "iron-session"],
2414
+ ["remix-auth", "remix-auth"],
2415
+ ["firebase", "Firebase Auth"]
2416
+ ];
2417
+ function stackSeen(manifest) {
2418
+ const deps = dependencies(manifest);
2419
+ if (!deps) return void 0;
2420
+ const authjs = deps["next-auth"];
2421
+ return {
2422
+ framework: FRAMEWORKS.find(([p]) => p in deps)?.[1] ?? "Node.js",
2423
+ auth: authjs !== void 0 ? authjsV5(authjs) ? "Auth.js v5" : "Auth.js v4" : AUTHS.find(([p]) => p in deps)?.[1],
2424
+ orm: "@prisma/client" in deps ? "prisma" : "drizzle-orm" in deps ? "drizzle" : void 0
2425
+ };
2426
+ }
2427
+ function authjsStrategy(auth) {
2428
+ const text2 = uncommented(auth);
2429
+ const given = /\bstrategy\s*:\s*(['"`])(jwt|database)\1/.exec(text2)?.[2];
2430
+ if (given === "jwt" || given === "database") return given;
2431
+ return /\bPrismaAdapter\s*\(/.test(text2) ? "database" : "jwt";
2432
+ }
2433
+ function authjsRoute(auth) {
2434
+ const text2 = uncommented(auth);
2435
+ return {
2436
+ handlers: /\bexport\s+const\s*\{[^}]*\bhandlers\b[^}]*\}\s*=\s*NextAuth\b/.test(text2),
2437
+ basePath: /\bbasePath\s*:\s*(['"`])(\/[^'"`]*)\1/.exec(text2)?.[2]
2438
+ };
2439
+ }
2440
+ function clientExport(module) {
2441
+ const text2 = uncommented(module);
2442
+ const named3 = [...text2.matchAll(/\bexport\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g)].map((m2) => m2[1] ?? "");
2443
+ const usual = named3.find((n3) => /^(prisma|db|client|database)$/i.test(n3));
2444
+ if (usual) return usual;
2445
+ if (named3.length === 1) return named3[0];
2446
+ return /\bexport\s+default\b/.test(text2) ? "default" : void 0;
2447
+ }
2448
+ function configuredSchema(config) {
2449
+ const path = /\bschema\s*:\s*(['"`])([^'"`]+)\1/.exec(uncommented(config))?.[2];
2450
+ return path === void 0 ? void 0 : posix.normalize(path);
2451
+ }
2452
+ var prismaProvider = (source) => /datasource\s+\w+\s*\{[^}]*\bprovider\s*=\s*"([^"]+)"/.exec(uncommented(source))?.[1];
2453
+ function readableTables(tables) {
2454
+ return tables.filter((t2) => !isSecretTable(t2.name)).map((t2) => ({ name: t2.name, columns: t2.columns.filter((c2) => !isSecretColumn(c2)) })).filter((t2) => t2.columns.length > 0);
2455
+ }
2456
+ var NAME_FIELD = /(^|_)(name|firstname|first_name|lastname|last_name|fullname|full_name|displayname|display_name|surname|given_name|family_name|nickname)$/;
2457
+ var PERSON_TABLE = /(^|_)(users?|customers?|clients?|members?|contacts?|persons?|people|employees?|authors?|patients?|students?|staff|profiles?|owners?)$/;
2458
+ var PERSON_FIELD = /^(author|billing|customer|client|contact|owner|sender|recipient|buyer|seller|user|member|patient|student|employee|shipping|first|last|full|given|family|sur|nick)/;
2459
+ function nameChoices(tables) {
2460
+ return tables.flatMap(
2461
+ (t2) => t2.columns.filter((c2) => NAME_FIELD.test(wordsOf(c2))).map((c2) => ({ name: `${t2.name}.${c2}`, proposed: PERSON_TABLE.test(wordsOf(t2.name)) || PERSON_FIELD.test(wordsOf(c2)) }))
2462
+ );
2463
+ }
2464
+ function guardsIn(layout, layoutPath) {
2465
+ const found = [];
2466
+ for (const m2 of layout.matchAll(/import\s*\{([^}]*)\}\s*from\s*(['"])([^'"]+)\2/g)) {
2467
+ const from = m2[3] ?? "";
2468
+ const path = from.startsWith(".") ? `./${posix.normalize(posix.join(posix.dirname(layoutPath), from))}` : from;
2469
+ for (const spec of (m2[1] ?? "").split(",")) {
2470
+ const local = spec.trim().split(/\s+as\s+/).at(-1) ?? "";
2471
+ const name = spec.trim().split(/\s+as\s+/)[0] ?? "";
2472
+ const guardLike = (n3) => /(Admin|Staff|Role)/.test(n3) && /^(require|ensure|assert|check|guard|protect|verify|must|is|only)[A-Z]/.test(n3);
2473
+ const guard = guardLike(name) || guardLike(local);
2474
+ if (guard && new RegExp(`\\b${local}\\s*\\(`).test(layout.slice((m2.index ?? 0) + m2[0].length))) found.push({ kind: "guard", path, name });
2475
+ }
2476
+ }
2477
+ return found;
2478
+ }
2479
+ function proposalsOf(options, repo) {
2480
+ const staff = [...options.staff ? [options.staff] : [], ...guardsIn(repo.layout, repo.layoutPath)];
2481
+ if (options.reads.length > 0)
2482
+ return {
2483
+ staff,
2484
+ tables: options.reads.map((r2) => ({ name: r2.table, proposed: true })),
2485
+ columns: new Map(options.reads.map((r2) => [r2.table, r2.columns])),
2486
+ names: () => Object.entries(options.names).flatMap(([table, columns]) => columns.map((c2) => ({ name: `${table}.${c2}`, proposed: true })))
2487
+ };
2488
+ const readable = readableTables(repo.tables);
2489
+ return {
2490
+ staff,
2491
+ tables: readable.map((t2) => ({ name: t2.name, proposed: true })),
2492
+ columns: new Map(readable.map((t2) => [t2.name, t2.columns])),
2493
+ names: (tables) => nameChoices(readable.filter((t2) => tables.includes(t2.name)))
2494
+ };
2495
+ }
2496
+ var SOURCE = "/api/soron/token";
2497
+ var matches = (pattern) => {
2498
+ const source = pattern.replace(/:\w+\*/g, ".*").replace(/:\w+\+/g, ".+").replace(/:\w+/g, "[^/]+");
2499
+ try {
2500
+ return new RegExp(`^${source}$`).test(SOURCE);
2501
+ } catch {
2502
+ return true;
2503
+ }
2504
+ };
2505
+ function middlewareFix(text2) {
2506
+ const config = /export\s+const\s+config\s*=\s*\{/.exec(text2);
2507
+ if (!config) return { state: "patched", text: `${text2.trimEnd()}
2508
+
2509
+ // Soron's routes are called by our service, without the staff's cookies.
2510
+ export const config = { matcher: ['/((?!api/soron/).*)'] }
2511
+ ` };
2512
+ const block2 = enclosed(text2, config.index + config[0].length - 1) ?? "";
2513
+ const matcher = /matcher\s*:\s*(\[[^\]]*\]|(['"`])[^'"`]*\2)/.exec(block2);
2514
+ if (!matcher) return { state: "manual" };
2515
+ const patterns = [...(matcher[1] ?? "").matchAll(/(['"`])([^'"`]*)\1/g)].map((p) => p[2] ?? "");
2516
+ const hit = patterns.filter(matches);
2517
+ if (hit.length === 0) return { state: "clear" };
2518
+ if (!hit.every((p) => p.includes("(?!"))) return { state: "manual" };
2519
+ let out = text2;
2520
+ for (const p of hit) out = out.replace(p, p.replace("(?!", "(?!api/soron/|"));
2521
+ return { state: "patched", text: out };
2522
+ }
2523
+
2524
+ // src/setup/files.ts
2525
+ import { posix as posix2 } from "node:path";
2526
+ function specifier(fromFile, toFile) {
2527
+ const rel = posix2.relative(posix2.dirname(fromFile), toFile).replace(/\.(tsx?|jsx?|mjs)$/, "");
2528
+ return rel.startsWith(".") ? rel : `./${rel}`;
2529
+ }
2530
+ function placesOf(layout) {
2531
+ const parts = layout.split("/");
2532
+ const app = parts.indexOf("app");
2533
+ if (app < 0) return void 0;
2534
+ const root = parts.slice(0, app).join("/");
2535
+ const appDir = parts.slice(0, app + 1).join("/");
2536
+ return {
2537
+ app: appDir,
2538
+ adapter: posix2.join(root, "soron", "adapter.ts"),
2539
+ route: posix2.join(appDir, "api", "soron", "[door]", "route.ts"),
2540
+ widget: posix2.join(posix2.dirname(layout), "soron-widget.tsx")
2541
+ };
2542
+ }
2543
+ var configFile = (c2) => `${JSON.stringify(c2, null, 2)}
2544
+ `;
2545
+ var routeFile = (adapter) => `// Soron's routes (@soron-ai/next): token, whoami and read. Written by \`npx @soron-ai/next\`.
2546
+ import { soronRoutes } from '@soron-ai/next/routes'
2547
+ import { adapter } from ${JSON.stringify(adapter)}
2548
+
2549
+ export const runtime = 'nodejs'
2550
+ export const dynamic = 'force-dynamic'
2551
+
2552
+ const routes = soronRoutes(adapter)
2553
+ export const POST = (request: Request) => routes.POST(request)
2554
+ `;
2555
+ var widgetFile = (service) => `'use client'
2556
+
2557
+ // Soron's eye in the admin area (@soron-ai/next). Written by \`npx @soron-ai/next\`.
2558
+ import { SoronWidget } from '@soron-ai/next/widget'
2559
+ import '@soron-ai/next/styles.css'
2560
+
2561
+ export function Soron() {
2562
+ return <SoronWidget service=${JSON.stringify(service)} />
2563
+ }
2564
+ `;
2565
+ function patchLayout(text2, widget) {
2566
+ if (!text2.includes("{children}")) return void 0;
2567
+ const lines = text2.split("\n");
2568
+ const lastImport = lines.reduce((at, line, i2) => /^import\b.*['"];?\s*$/.test(line) ? i2 : at, -1);
2569
+ lines.splice(lastImport + 1, 0, `import { Soron } from ${JSON.stringify(widget)}`);
2570
+ return lines.join("\n").replace("{children}", "<Soron />{children}");
2571
+ }
2572
+
2573
+ // src/setup/key-page.ts
2574
+ import { randomBytes } from "node:crypto";
2575
+ import { createServer } from "node:http";
2576
+ var MAX_BODY = 4e3;
2577
+ var escape = (s) => s.replace(/[&<>"']/g, (c2) => `&#${c2.charCodeAt(0)};`);
2578
+ var page = (body, title) => `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)}</title><style>body{font:16px system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem}input{width:100%;padding:.5rem;font:inherit}button{margin-top:1rem;padding:.5rem 1rem;font:inherit}</style></head><body>${body}</body></html>`;
2579
+ async function keyPage(o) {
2580
+ const path = `/${randomBytes(24).toString("base64url")}`;
2581
+ let settle = () => void 0;
2582
+ const key = new Promise((ok) => settle = ok);
2583
+ const send = (res, status2, html) => {
2584
+ res.writeHead(status2, {
2585
+ "content-type": "text/html; charset=utf-8",
2586
+ "cache-control": "no-store",
2587
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
2588
+ "referrer-policy": "no-referrer"
2589
+ });
2590
+ res.end(html);
2591
+ };
2592
+ const bodyOf = async (req) => {
2593
+ const chunks = [];
2594
+ let size = 0;
2595
+ for await (const c2 of req) {
2596
+ const b = Buffer.isBuffer(c2) ? c2 : Buffer.from(String(c2));
2597
+ size += b.length;
2598
+ if (size > MAX_BODY) return void 0;
2599
+ chunks.push(b);
2600
+ }
2601
+ return Buffer.concat(chunks).toString("utf8");
2602
+ };
2603
+ let host = "";
2604
+ const server = createServer((req, res) => {
2605
+ void (async () => {
2606
+ if (req.url !== path || req.headers.host !== host) return send(res, 404, page("", o.texts.title));
2607
+ if (req.method === "GET")
2608
+ return send(
2609
+ res,
2610
+ 200,
2611
+ page(
2612
+ `<h1>${escape(o.texts.title)}</h1><form method="post"><label>${escape(o.texts.label)}<br><input name="key" type="password" autocomplete="off" autofocus required></label><br><button>${escape(o.texts.button)}</button></form>`,
2613
+ o.texts.title
2614
+ )
2615
+ );
2616
+ if (req.method !== "POST") return send(res, 405, page("", o.texts.title));
2617
+ const typed = new URLSearchParams(await bodyOf(req) ?? "").get("key")?.trim() ?? "";
2618
+ if (!typed) return send(res, 400, page("", o.texts.title));
2619
+ send(res, 200, page(`<p>${escape(o.texts.done)}</p>`, o.texts.title));
2620
+ done(typed);
2621
+ })();
2622
+ });
2623
+ const done = (typed) => {
2624
+ clearTimeout(timer);
2625
+ server.close();
2626
+ server.closeAllConnections();
2627
+ settle(typed);
2628
+ };
2629
+ const timer = setTimeout(() => done(""), o.minutes * 6e4);
2630
+ await new Promise((ok) => server.listen(0, "127.0.0.1", ok));
2631
+ const a2 = server.address();
2632
+ if (a2 === null || typeof a2 === "string") throw new Error("key page: no port");
2633
+ host = `${a2.address}:${a2.port}`;
2634
+ return { url: `http://${a2.address}:${a2.port}${path}`, key, close: () => done("") };
2635
+ }
2636
+
2637
+ // src/setup/stack.ts
2638
+ import { existsSync as existsSync2, readdirSync, readFileSync, statSync } from "node:fs";
2639
+ import { isAbsolute, join as join2, posix as posix3, relative, resolve } from "node:path";
2640
+
2641
+ // src/setup/adapter-authjs.ts
2642
+ var NAME = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
2643
+ var sqlName = (s) => {
2644
+ if (!NAME.test(s)) throw new Error(`not a database name: ${s}`);
2645
+ return `"${s}"`;
2646
+ };
2647
+ var jsName = (s) => {
2648
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(s)) throw new Error(`not a JavaScript name: ${s}`);
2649
+ return s;
2650
+ };
2651
+ var named = (name, local) => jsName(name) === local ? local : `${name} as ${local}`;
2652
+ var literal = (v) => JSON.stringify(v).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2653
+ var sql = (text2) => literal(text2);
2654
+ var prismaModule = (prisma) => `import ${prisma.name === "default" ? "db" : `{ ${named(prisma.name, "db")} }`} from ${literal(prisma.from)}
2655
+ `;
2656
+ function prismaStaff(staff, idColumn) {
2657
+ const userId = sqlName(idColumn);
2658
+ const rule2 = staff.kind === "role" ? ` // The staff rule: ${staff.table}.${staff.column} is ${staff.values.map(literal).join(", ")}.
2659
+ async isStaff(userId) {
2660
+ const found = await db.$queryRawUnsafe<unknown[]>(${sql(`select 1 from ${sqlName(staff.table)} where ${userId} = $1 and ${sqlName(staff.column)}::text = any($2) limit 1`)}, userId, [${staff.values.map(literal).join(", ")}])
2661
+ return found.length > 0
2662
+ },` : staff.kind === "guard" ? ` // Checked by ${jsName(staff.name)}() when the badge was given (L54); each question checks the session still lives.
2663
+ async isStaff() {
2664
+ return true
2665
+ },` : ` // The staff rule: any signed-in session, end clients included (a person's choice, L29, L34).
2666
+ async isStaff() {
2667
+ return true
2668
+ },`;
2669
+ const guard = staff.kind === "guard" ? ` // The staff rule: whoever passes ${jsName(staff.name)}(), as the admin area runs it, each time a badge is given.
2670
+ // It turns a person away by throwing (a redirect) or by answering false or null.
2671
+ try {
2672
+ const passed: unknown = await staffGuard()
2673
+ if (passed === false || passed === null) return false
2674
+ } catch {
2675
+ return false
2676
+ }
2677
+ return true
2678
+ ` : " return true\n";
2679
+ return { imports: staff.kind === "guard" ? `import { ${named(staff.name, "staffGuard")} } from ${literal(staff.from)}
2680
+ ` : "", isStaff: rule2, guard };
2681
+ }
2682
+ var PRISMA_ROWS = ` // Only a SELECT, in a read-only transaction: values go as parameters, names quoted.
2683
+ async rows({ table, columns, where, limit }) {
2684
+ const filters: string[] = []
2685
+ const values: unknown[] = []
2686
+ for (const [name, value] of Object.entries(where)) {
2687
+ if (value === null) filters.push(\`\${q(name)} is null\`)
2688
+ else {
2689
+ values.push(value)
2690
+ filters.push(\`\${q(name)} = $\${values.length}\`)
2691
+ }
2692
+ }
2693
+ const text = \`select \${columns.map(q).join(', ')} from \${q(table)}\${filters.length ? \` where \${filters.join(' and ')}\` : ''} limit \${Math.min(Math.max(1, limit), 50)}\`
2694
+ return db.$transaction(async (tx) => {
2695
+ await tx.$executeRawUnsafe('set transaction read only')
2696
+ return tx.$queryRawUnsafe<Record<string, unknown>[]>(text, ...values)
2697
+ })
2698
+ },
2699
+ `;
2700
+ var PRISMA_QUOTE = 'const q = (name: string) => `"${name.replace(/"/g, \'""\')}"`\n';
2701
+ var authjsKeeps = (basePath) => `
2702
+ // Where Auth.js answers: ${basePath === void 0 ? "AUTH_URL's path, else next-auth's /api/auth" : "the basePath of its config"}.
2703
+ function authBase(): string {
2704
+ ${basePath === void 0 ? ` const url = process.env['AUTH_URL'] ?? process.env['NEXTAUTH_URL']
2705
+ const path = url ? new URL(url).pathname.replace(/\\/+$/, '') : ''
2706
+ return path || '/api/auth'` : ` return ${literal(basePath.replace(/\/+$/, ""))}`}
2707
+ }
2708
+ // The project's Auth.js reads this same cookie, at this same address, with its own config: a session
2709
+ // it turns away (its jwt callback: revoked, banned) gets no badge (L58); the cookie it renews (a
2710
+ // sliding expiry, a rotated refresh token) goes back to the browser with the badge.
2711
+ async function authjsKeeps(name: string, token: string, request: Request): Promise<string[] | undefined> {
2712
+ try {
2713
+ const url = new URL(\`\${authBase()}/session\`, request.url)
2714
+ const reply = await handlers.GET(new NextRequest(url, { headers: { cookie: \`\${name}=\${token}\` } }))
2715
+ const session: unknown = reply.ok ? await reply.json() : null
2716
+ return typeof session === 'object' && session !== null && Object.keys(session).length > 0 ? reply.headers.getSetCookie() : undefined
2717
+ } catch {
2718
+ return undefined
2719
+ }
2720
+ }
2721
+ `;
2722
+ function authjsPrismaAdapter(p) {
2723
+ const user = `${sqlName(p.user.table)}`;
2724
+ const userId = sqlName(p.user.id);
2725
+ const s = p.sessions;
2726
+ const staff = p.staff;
2727
+ const { imports: guardImport, isStaff: rule2, guard } = prismaStaff(staff, p.user.id);
2728
+ return `// Soron's adapter (@soron-ai/next): who is a staff member of this back-office, and how Soron reads
2729
+ // the tables listed in soron.config.json. Written by \`npx @soron-ai/next\` for Auth.js and Prisma;
2730
+ // yours to read and change.
2731
+ import { createHash } from 'node:crypto'
2732
+ ${s ? "" : `import { decode } from 'next-auth/jwt'
2733
+ import { NextRequest } from 'next/server'
2734
+ `}import type { SoronAdapter } from '@soron-ai/next/routes'
2735
+ import config from ${literal(p.config)}
2736
+ ${prismaModule(p.prisma)}${s ? "" : `import { handlers } from ${literal(p.auth.from)}
2737
+ `}${guardImport}
2738
+ // Auth.js's session cookie (the secure one on https), split in chunks when it is long.
2739
+ const COOKIES = ['__Secure-authjs.session-token', 'authjs.session-token']
2740
+ // Of two cookies of the same name the first counts, as for Auth.js; another cookie that does not
2741
+ // decode is left alone.
2742
+ function cookie(request: Request, name: string): string | undefined {
2743
+ const jar = new Map<string, string>()
2744
+ for (const part of (request.headers.get('cookie') ?? '').split(';')) {
2745
+ const at = part.indexOf('=')
2746
+ const key = at > 0 ? part.slice(0, at).trim() : ''
2747
+ if ((key !== name && !key.startsWith(\`\${name}.\`)) || jar.has(key)) continue
2748
+ try {
2749
+ jar.set(key, decodeURIComponent(part.slice(at + 1).trim()))
2750
+ } catch {
2751
+ continue
2752
+ }
2753
+ }
2754
+ const whole = jar.get(name)
2755
+ if (whole) return whole
2756
+ const chunks: string[] = []
2757
+ for (let n = 0; jar.has(\`\${name}.\${n}\`); n++) chunks.push(jar.get(\`\${name}.\${n}\`) ?? '')
2758
+ return chunks.length > 0 ? chunks.join('') : undefined
2759
+ }
2760
+ // The badge never carries the session's own token: only its hash.
2761
+ const hashOf = (s: string) => createHash('sha256').update(s).digest('hex')
2762
+ // Names come from soron.config.json, which the routes check against their list: quoted for Postgres.
2763
+ ${PRISMA_QUOTE}
2764
+ async function staffPasses(): Promise<boolean> {
2765
+ ${guard}}
2766
+ ${s ? "" : authjsKeeps(p.auth.basePath)}
2767
+ export const adapter: SoronAdapter = {
2768
+ config,
2769
+ async session(request) {
2770
+ for (const name of COOKIES) {
2771
+ const token = cookie(request, name)
2772
+ if (!token) continue
2773
+ ${s ? ` // Database sessions: the cookie holds the session's token.
2774
+ const found = await db.$queryRawUnsafe<{ userId: string }[]>(${sql(`select ${sqlName(s.userId)} as "userId" from ${sqlName(s.table)} where ${sqlName(s.token)} = $1 and ${sqlName(s.expires)} > now() limit 1`)}, token)
2775
+ const row = found[0]
2776
+ if (!row) return null
2777
+ return (await staffPasses()) ? { sessionId: hashOf(token), userId: row.userId } : null` : ` // JWT sessions: Auth.js's own decoding, with its secret and the cookie's name as salt.
2778
+ const jwt = await decode({ token, secret: process.env['AUTH_SECRET'] ?? process.env['NEXTAUTH_SECRET'] ?? '', salt: name }).catch(() => null)
2779
+ if (!jwt?.sub || typeof jwt.exp !== 'number' || jwt.exp * 1000 <= Date.now()) return null
2780
+ const cookies = await authjsKeeps(name, token, request)
2781
+ if (!cookies) return null
2782
+ return (await staffPasses()) ? { sessionId: \`jwt.\${jwt.exp}\`, userId: jwt.sub, cookies } : null`}
2783
+ }
2784
+ return null
2785
+ },
2786
+ ${rule2}
2787
+ async sessionAlive({ sessionId, userId }) {
2788
+ ${s ? ` const tokens = await db.$queryRawUnsafe<{ token: string }[]>(${sql(`select ${sqlName(s.token)} as "token" from ${sqlName(s.table)} where ${sqlName(s.userId)} = $1 and ${sqlName(s.expires)} > now()`)}, userId)
2789
+ return tokens.some((t) => hashOf(t.token) === sessionId)` : ` // A JWT session cannot be closed: until it expires, the person must still exist (L58).
2790
+ const exp = Number(/^jwt\\.(\\d+)$/.exec(sessionId)?.[1] ?? 0)
2791
+ if (exp * 1000 <= Date.now()) return false
2792
+ const found = await db.$queryRawUnsafe<unknown[]>(${sql(`select 1 from ${user} where ${userId} = $1 limit 1`)}, userId)
2793
+ return found.length > 0`}
2794
+ },
2795
+ ${PRISMA_ROWS}}
2796
+ `;
2797
+ }
2798
+
2799
+ // src/setup/adapter.ts
2800
+ var IDENTIFIER2 = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2801
+ var id = (s) => {
2802
+ if (!IDENTIFIER2.test(s)) throw new Error(`not a JavaScript name: ${s}`);
2803
+ return s;
2804
+ };
2805
+ var named2 = (name, local) => id(name) === local ? local : `${name} as ${local}`;
2806
+ var literal2 = (v) => JSON.stringify(v).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2807
+ function staffRule2(s) {
2808
+ if (s.kind === "role") {
2809
+ const table = `schema.${id(s.table)}`;
2810
+ const values = s.values.map(literal2).join(", ");
2811
+ return {
2812
+ imports: "",
2813
+ guard: "",
2814
+ isStaff: ` // The staff rule: ${s.table}.${id(s.column)} is ${values}.
2815
+ async isStaff(userId) {
2816
+ const found = await db
2817
+ .select({ id: ${table}.id })
2818
+ .from(${table})
2819
+ .where(and(eq(${table}.id, userId), inArray(${table}.${s.column}, [${values}])))
2820
+ .limit(1)
2821
+ return found.length > 0
2822
+ },`
2823
+ };
2824
+ }
2825
+ if (s.kind === "guard")
2826
+ return {
2827
+ imports: `import { ${named2(s.name, "staffGuard")} } from ${literal2(s.from)}
2828
+ `,
2829
+ guard: ` // The staff rule: whoever passes ${id(s.name)}(), as the admin area runs it, each time a badge is given.
2830
+ // It turns a person away by throwing (a redirect) or by answering false or null.
2831
+ try {
2832
+ const passed: unknown = await staffGuard()
2833
+ if (passed === false || passed === null) return null
2834
+ } catch {
2835
+ return null
2836
+ }
2837
+ `,
2838
+ isStaff: ` // Checked by ${id(s.name)}() when the badge was given; each question checks the session still lives.
2839
+ async isStaff() {
2840
+ return true
2841
+ },`
2842
+ };
2843
+ return {
2844
+ imports: "",
2845
+ guard: "",
2846
+ isStaff: ` // The staff rule: any signed-in session, end clients included (a person's choice, L29, L34).
2847
+ async isStaff() {
2848
+ return true
2849
+ },`
2850
+ };
2851
+ }
2852
+ var drizzleImports = (o) => `import { and, eq, getTableColumns, getTableName,${o.gt ? " gt," : ""}${o.inArray ? " inArray," : ""} is, isNull, type SQL } from 'drizzle-orm'
2853
+ import { PgTable, type PgColumn } from 'drizzle-orm/pg-core'
2854
+ `;
2855
+ var drizzleModules = (db, schema) => `import { ${named2(db.name, "db")} } from ${JSON.stringify(db.from)}
2856
+ import * as schema from ${JSON.stringify(schema)}
2857
+ `;
2858
+ var DRIZZLE_TABLES = `// The tables of the schema, by their name in the database.
2859
+ const tables = new Map<string, PgTable>()
2860
+ for (const t of Object.values(schema)) if (is(t, PgTable)) tables.set(getTableName(t), t)
2861
+ const column = (table: PgTable, name: string): PgColumn | undefined => Object.values(getTableColumns(table)).find((c) => c.name === name)
2862
+ `;
2863
+ var DRIZZLE_ROWS = ` // Only a SELECT is ever built: tables and columns come from the schema, values go as parameters.
2864
+ async rows({ table, columns, where, limit }) {
2865
+ const source = tables.get(table)
2866
+ if (!source) return []
2867
+ const selection: Record<string, PgColumn> = {}
2868
+ for (const name of columns) {
2869
+ const c = column(source, name)
2870
+ if (c) selection[name] = c
2871
+ }
2872
+ const filters: SQL[] = []
2873
+ for (const [name, value] of Object.entries(where)) {
2874
+ const c = column(source, name)
2875
+ if (!c) return []
2876
+ filters.push(value === null ? isNull(c) : eq(c, value))
2877
+ }
2878
+ if (Object.keys(selection).length === 0) return []
2879
+ return db.select(selection).from(source).where(and(...filters)).limit(limit)
2880
+ },
2881
+ `;
2882
+ function betterAuthDrizzleAdapter(p) {
2883
+ const session = `schema.${id(p.session)}`;
2884
+ const rule2 = staffRule2(p.staff);
2885
+ return `// Soron's adapter (@soron-ai/next): who is a staff member of this back-office, and how Soron reads
2886
+ // the tables listed in soron.config.json. Written by \`npx @soron-ai/next\` for better-auth and drizzle;
2887
+ // yours to read and change.
2888
+ ${drizzleImports({ gt: true, inArray: p.staff.kind === "role" })}import type { SoronAdapter } from '@soron-ai/next/routes'
2889
+ import config from ${JSON.stringify(p.config)}
2890
+ import { ${named2(p.auth.name, "auth")} } from ${JSON.stringify(p.auth.from)}
2891
+ ${drizzleModules(p.db, p.schema)}${rule2.imports}
2892
+ ${DRIZZLE_TABLES}
2893
+ export const adapter: SoronAdapter = {
2894
+ config,
2895
+ async session(request) {
2896
+ const found = await auth.api.getSession({ headers: request.headers })
2897
+ if (!found) return null
2898
+ ${rule2.guard} return { sessionId: found.session.id, userId: found.user.id }
2899
+ },
2900
+ ${rule2.isStaff}
2901
+ async sessionAlive({ sessionId, userId }) {
2902
+ const found = await db
2903
+ .select({ id: ${session}.id })
2904
+ .from(${session})
2905
+ .where(and(eq(${session}.id, sessionId), eq(${session}.userId, userId), gt(${session}.expiresAt, new Date())))
2906
+ .limit(1)
2907
+ return found.length > 0
2908
+ },
2909
+ ${DRIZZLE_ROWS}}
2910
+ `;
2911
+ }
2912
+
2913
+ // src/setup/adapter-complete.ts
2914
+ var ruleText2 = (s) => s.kind === "role" ? `${s.table}.${s.column} is ${s.values.join(" or ")}` : s.kind === "guard" ? `${s.name}() lets them in` : "any signed-in person";
2915
+ function incompleteAdapter(p) {
2916
+ const orm = p.orm;
2917
+ const staff = p.staff;
2918
+ const checked = orm !== void 0 || staff.kind !== "role";
2919
+ const prisma = orm?.kind === "prisma" ? prismaStaff(staff, orm.idColumn) : void 0;
2920
+ const drizzle = orm?.kind === "drizzle" ? staffRule2(staff) : void 0;
2921
+ const guardImport = prisma?.imports ?? drizzle?.imports ?? (staff.kind === "guard" ? prismaStaff(staff, "id").imports : "");
2922
+ const isStaff = prisma?.isStaff ?? drizzle?.isStaff ?? ` // The staff rule (${ruleText2(staff)}): getStaff() answers for it, Soron reads no table here.
2923
+ async isStaff() {
2924
+ return true
2925
+ },`;
2926
+ const guard = staff.kind === "guard" ? ` // The staff rule: whoever passes the admin area's guard, each time a badge is given.
2927
+ try {
2928
+ const passed: unknown = await staffGuard()
2929
+ if (passed === false || passed === null) return null
2930
+ } catch {
2931
+ return null
2932
+ }
2933
+ ` : "";
2934
+ const imports = orm?.kind === "prisma" ? prismaModule(orm.prisma) : orm?.kind === "drizzle" ? `${drizzleImports({ gt: false, inArray: staff.kind === "role" })}${drizzleModules(orm.db, orm.schema)}` : "";
2935
+ const helpers = orm?.kind === "prisma" ? `
2936
+ ${PRISMA_QUOTE}` : orm?.kind === "drizzle" ? `
2937
+ ${DRIZZLE_TABLES}` : "";
2938
+ const rows = orm?.kind === "prisma" ? PRISMA_ROWS : orm?.kind === "drizzle" ? DRIZZLE_ROWS : ` // No ORM Soron reads with (Prisma or drizzle, on Postgres): Soron answers from the code only.
2939
+ async rows() {
2940
+ return []
2941
+ },
2942
+ `;
2943
+ return `// Soron's adapter (@soron-ai/next): who is a staff member of this back-office, and how Soron reads
2944
+ // the tables listed in soron.config.json. Written by \`npx @soron-ai/next\`, which cannot read the
2945
+ // sessions of ${p.auth ?? "this auth"}: getStaff() below is yours to write. Until it is, nobody
2946
+ // gets a badge, and \`npx @soron-ai/next check\` says so.
2947
+ import { AdapterIncomplete, type SoronAdapter } from '@soron-ai/next/routes'
2948
+ import config from ${JSON.stringify(p.config)}
2949
+ ${imports}${guardImport}${helpers}
2950
+ // TO WRITE: the staff member signed in on this request, or null for anyone else (an end client, a
2951
+ // visitor).${checked ? "" : `
2952
+ // Return them only when ${ruleText2(staff)}.`}
2953
+ // \`userId\`: their id in the database, as the staff rule reads it; \`sessionId\`: an id of this
2954
+ // sign-in, never the session's secret token itself. Soron sees nothing of the session afterwards: a
2955
+ // staff member who signs out keeps their badge 5 minutes at most.
2956
+ async function getStaff(request: Request): Promise<{ sessionId: string; userId: string } | null> {
2957
+ void request
2958
+ throw new AdapterIncomplete()
2959
+ }
2960
+
2961
+ export const adapter: SoronAdapter = {
2962
+ config,
2963
+ async session(request) {
2964
+ const staff = await getStaff(request)
2965
+ if (!staff) return null
2966
+ ${guard} return staff
2967
+ },
2968
+ ${isStaff}
2969
+ // The badge's 5 minutes bound a session Soron cannot see.
2970
+ async sessionAlive() {
2971
+ return true
2972
+ },
2973
+ ${rows}}
2974
+ `;
2975
+ }
2976
+
2977
+ // src/setup/stack.ts
2978
+ var LAYOUTS = ["src/app/admin/layout.tsx", "app/admin/layout.tsx"];
2979
+ var NAME2 = /^[A-Za-z][A-Za-z0-9_]{0,62}$/;
2980
+ var MAX_SCHEMA_FILES = 200;
2981
+ var MAX_COLUMNS = 100;
2982
+ function offered(tables) {
2983
+ const hidden = [];
2984
+ const out = [];
2985
+ for (const t2 of tables) {
2986
+ if (isSecretTable(t2.model)) {
2987
+ hidden.push(t2.table);
2988
+ continue;
2989
+ }
2990
+ for (const c2 of t2.columns) if (isSecretColumn(c2.name)) hidden.push(`${t2.table}.${c2.column}`);
2991
+ const columns = t2.columns.filter((c2) => NAME2.test(c2.column) && !isSecretColumn(c2.name)).map((c2) => c2.column);
2992
+ if (NAME2.test(t2.table) && columns.length > 0) out.push({ name: t2.table, columns: columns.slice(0, MAX_COLUMNS) });
2993
+ }
2994
+ return { tables: out, hidden };
2995
+ }
2996
+ var AUTH_FILES = {
2997
+ "better-auth-drizzle": ["src/lib/auth.ts", "lib/auth.ts", "src/auth.ts", "auth.ts"],
2998
+ "authjs-prisma": ["src/auth.ts", "auth.ts", "src/lib/auth.ts", "lib/auth.ts"]
2999
+ };
3000
+ var ORM_FILES = {
3001
+ prisma: {
3002
+ db: ["src/lib/prisma.ts", "lib/prisma.ts", "src/lib/db.ts", "lib/db.ts", "src/prisma.ts", "prisma.ts", "src/db.ts", "db.ts"],
3003
+ schema: ["prisma/schema.prisma", "schema.prisma", "prisma/schema"]
3004
+ },
3005
+ drizzle: {
3006
+ db: ["src/db/index.ts", "db/index.ts", "src/lib/db.ts", "lib/db.ts", "src/db.ts", "db.ts"],
3007
+ schema: ["src/db/schema.ts", "db/schema.ts", "src/lib/db/schema.ts", "lib/db/schema.ts", "src/schema.ts"]
3008
+ }
3009
+ };
3010
+ function findStack(cwd, given) {
3011
+ const at = (path) => join2(cwd, path);
3012
+ const read = (path) => readFileSync(at(path), "utf8");
3013
+ const manifest = existsSync2(at("package.json")) ? read("package.json") : void 0;
3014
+ const seen = manifest === void 0 ? void 0 : stackSeen(manifest);
3015
+ if (!seen || seen.framework !== "Next.js") throw new StepError("stack_unknown");
3016
+ const first = (list) => list.find((f) => existsSync2(at(f)));
3017
+ const inside = (path) => {
3018
+ const rel = relative(resolve(cwd), resolve(cwd, path));
3019
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
3020
+ };
3021
+ const pick = (name, list) => {
3022
+ const path = given[name] ?? first(list);
3023
+ if (path === void 0 || !inside(path) || !existsSync2(at(path))) throw new StepError("files_missing");
3024
+ return path;
3025
+ };
3026
+ const layoutPath = pick("layout", LAYOUTS);
3027
+ const found = { seen, stack: void 0, paths: { layout: layoutPath }, tables: [], hidden: [], layout: read(layoutPath) };
3028
+ if (!seen.orm) return found;
3029
+ const config = ["prisma.config.ts", "drizzle.config.ts"].find((f) => existsSync2(at(f)));
3030
+ const configured = config ? configuredSchema(read(config)) : void 0;
3031
+ const db = pick("db", ORM_FILES[seen.orm].db);
3032
+ const schemaPath = pick("schema", [...configured ? [configured] : [], ...ORM_FILES[seen.orm].schema]);
3033
+ const schema = statSync(at(schemaPath)).isDirectory() ? readdirSync(at(schemaPath), { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith(".prisma") && !f.split(/[\\/]/).includes("node_modules")).sort().slice(0, MAX_SCHEMA_FILES).map((f) => read(posix3.join(schemaPath, f))).join("\n") : read(schemaPath);
3034
+ const paths = { ...found.paths, db, schema: schemaPath };
3035
+ const plugged = stackOf(manifest ?? "");
3036
+ const auth = (stack) => ({ ...paths, auth: pick("auth", AUTH_FILES[stack]) });
3037
+ if (seen.orm === "drizzle") {
3038
+ const pg = drizzleSchema(schema);
3039
+ if (pg.length === 0) return found;
3040
+ const { tables: tables2, hidden: hidden2 } = offered(pg.map((t2) => ({ table: t2.name, model: t2.name, columns: t2.columns.map((c2) => ({ column: c2.column, name: c2.key })) })));
3041
+ const orm2 = { kind: "drizzle" };
3042
+ return plugged === "better-auth-drizzle" ? { ...found, stack: plugged, paths: auth(plugged), tables: tables2, hidden: hidden2, orm: orm2 } : { ...found, paths, tables: tables2, hidden: hidden2, orm: orm2 };
3043
+ }
3044
+ if (!/^postgres(ql)?$/.test(prismaProvider(schema) ?? "")) return found;
3045
+ const client = clientExport(read(db));
3046
+ if (!client) throw new StepError("files_missing");
3047
+ const models = prismaModels(schema);
3048
+ const { tables, hidden } = offered(models.map((m2) => ({ table: m2.table, model: m2.model, columns: m2.fields.map((f) => ({ column: f.column, name: f.name })) })));
3049
+ const orm = { kind: "prisma", client, models };
3050
+ if (plugged === "authjs-prisma") {
3051
+ const withAuth = auth(plugged);
3052
+ const names = authjsNames(models);
3053
+ const text2 = read(withAuth.auth);
3054
+ const strategy = authjsStrategy(text2);
3055
+ const route = authjsRoute(text2);
3056
+ if (names && (strategy === "jwt" ? route.handlers : names.sessions)) return { ...found, stack: plugged, paths: withAuth, tables, hidden, orm, authjs: { names, strategy, basePath: route.basePath } };
3057
+ }
3058
+ return { ...found, paths, tables, hidden, orm };
3059
+ }
3060
+ function adapterFor(found, place, staff) {
3061
+ const from = (path) => specifier(place, path);
3062
+ const config = from("soron.config.json");
3063
+ const { auth, db, schema } = found.paths;
3064
+ if (found.stack === "better-auth-drizzle" && auth && db && schema)
3065
+ return betterAuthDrizzleAdapter({ auth: { from: from(auth), name: "auth" }, db: { from: from(db), name: "db" }, schema: from(schema), config, session: "session", staff });
3066
+ const orm = found.orm;
3067
+ if (found.stack === "authjs-prisma" && found.authjs && orm?.kind === "prisma" && db && auth) {
3068
+ const { names, strategy, basePath } = found.authjs;
3069
+ return authjsPrismaAdapter({ prisma: { from: from(db), name: orm.client }, auth: { from: from(auth), basePath }, config, user: names.user, sessions: strategy === "database" ? names.sessions ?? null : null, staff });
3070
+ }
3071
+ const idColumn = (table) => orm?.kind === "prisma" ? orm.models.find((m2) => m2.table === table)?.fields.find((f) => f.id)?.column ?? "id" : "id";
3072
+ return incompleteAdapter({
3073
+ auth: found.seen.auth,
3074
+ config,
3075
+ orm: orm?.kind === "prisma" && db ? { kind: "prisma", prisma: { from: from(db), name: orm.client }, idColumn: idColumn(staff.kind === "role" ? staff.table : "") } : orm?.kind === "drizzle" && db && schema ? { kind: "drizzle", db: { from: from(db), name: "db" }, schema: from(schema) } : void 0,
3076
+ staff
3077
+ });
3078
+ }
3079
+ function staffUnchecked(found, staff) {
3080
+ if (staff.kind !== "role") return false;
3081
+ const orm = found.orm;
3082
+ if (!orm) return true;
3083
+ if (orm.kind === "drizzle") return false;
3084
+ const model = orm.models.find((m2) => m2.table === staff.table);
3085
+ if (!model?.fields.some((f) => f.column === staff.column)) return true;
3086
+ return found.authjs !== void 0 && staff.table !== found.authjs.names.user.table;
3087
+ }
3088
+ function secretRead(found, reads) {
3089
+ for (const r2 of reads) {
3090
+ if (found.hidden.includes(r2.table)) return r2.table;
3091
+ const column = r2.columns.find((c2) => found.hidden.includes(`${r2.table}.${c2}`));
3092
+ if (column !== void 0) return `${r2.table}.${column}`;
3093
+ }
3094
+ return void 0;
3095
+ }
3096
+
3097
+ // src/setup/setup.ts
3098
+ var BRANCH = "soron/setup";
3099
+ var SECRET = "SORON_BADGE_SECRET";
3100
+ var KEY_TITLE = "Soron (read-only)";
3101
+ var PROOF_TITLE = "Soron (admin proof, removed at once)";
3102
+ var CONFIG_BRANCH = "soron/config";
3103
+ var CONFIG_PR_BODY = "Changes what Soron reads in the back-office and which fields it masks (`soron.config.json`).";
3104
+ var PR_BODY = "Adds Soron to the admin area: its routes (`/api/soron/*`), its adapter, its widget and `soron.config.json`.";
3105
+ var toComplete = (auth, path) => `
3106
+
3107
+ Before you merge: write \`getStaff()\` in \`${path}\`. Soron cannot read the sessions of ${auth ?? "this auth"}; until it is written, nobody gets a badge, and \`npx @soron-ai/next check\` says so.`;
3108
+ var NODE_FLOOR = 22;
3109
+ var KEY_PAGE_MINUTES = 10;
3110
+ var MIDDLEWARES = ["middleware.ts", "middleware.js", "src/middleware.ts", "src/middleware.js", "proxy.ts", "proxy.js", "src/proxy.ts", "src/proxy.js"];
3111
+ var objectOf = (text2) => {
3112
+ try {
3113
+ const v = JSON.parse(text2);
3114
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? Object.fromEntries(Object.entries(v)) : {};
3115
+ } catch {
3116
+ return {};
3117
+ }
3118
+ };
3119
+ var listOf = (text2) => {
3120
+ try {
3121
+ const v = JSON.parse(text2);
3122
+ return Array.isArray(v) ? v.map((x) => objectOf(JSON.stringify(x))) : [];
3123
+ } catch {
3124
+ return [];
3125
+ }
3126
+ };
3127
+ var stderrOf = (e) => e instanceof ProgramError ? e.stderr : "";
3128
+ var missing = (e) => e instanceof ProgramError && e.exitCode === null && e.message.endsWith("is not installed");
3129
+ var offline = (e) => /could not resolve host|unable to access|network is unreachable|connection (refused|timed out|reset)/i.test(stderrOf(e));
3130
+ async function setup(o, io) {
3131
+ const c2 = portsOf(o, io);
3132
+ const outcome = await journey(io.mode, c2.ports);
3133
+ return { outcome, repo: c2.known.repo };
3134
+ }
3135
+ async function status(o, io) {
3136
+ const c2 = portsOf(o, io);
3137
+ await c2.ports.probe.machine();
3138
+ await c2.ports.change.proveAdmin();
3139
+ return c2.ok("GET", "/v1/admin");
3140
+ }
3141
+ function portsOf(o, io) {
3142
+ const { cwd, signal } = io;
3143
+ const run = (name, args, input) => runProgram(name, args, { cwd, signal, ...input === void 0 ? {} : { input } });
3144
+ const undoRun = (name, args) => runProgram(name, args, { cwd });
3145
+ const git = (...args) => run("git", args).then((s) => s.trim());
3146
+ const door = async (method, path, body, undo2 = false, auth = known.admin || known.invite) => {
3147
+ let res;
3148
+ try {
3149
+ res = await fetch(new URL(path, o.service), {
3150
+ method,
3151
+ headers: { authorization: `Bearer ${auth}`, "content-type": "application/json" },
3152
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
3153
+ redirect: "error",
3154
+ signal: undo2 ? AbortSignal.timeout(6e4) : AbortSignal.any([signal, AbortSignal.timeout(6e4)])
3155
+ });
3156
+ } catch (e) {
3157
+ if (signal.aborted && !undo2) throw e;
3158
+ throw new StepError("service_down");
3159
+ }
3160
+ const reply = objectOf(await res.text());
3161
+ if (res.status >= 500 && reply["error"] !== "anthropic_unavailable") throw new StepError("service_down");
3162
+ return { status: res.status, error: typeof reply["error"] === "string" ? reply["error"] : "", reply };
3163
+ };
3164
+ const refusal = (status2, error) => {
3165
+ const known2 = {
3166
+ invalid_code: "invite_invalid",
3167
+ key_invalid: "key_invalid",
3168
+ key_no_credit: "no_credit",
3169
+ key_forbidden: "model_access",
3170
+ key_model_closed: "model_access",
3171
+ anthropic_unavailable: "overloaded",
3172
+ backoffice_unreachable: "backoffice_unreachable",
3173
+ read_failed: "read_failed",
3174
+ origin_taken: "origin_taken",
3175
+ too_many_checks: "too_many_checks"
3176
+ };
3177
+ return new StepError(known2[error] ?? (status2 === 401 ? "invite_invalid" : "service_down"));
3178
+ };
3179
+ const ok = async (method, path, body, undo2 = false) => {
3180
+ const r2 = await door(method, path, body, undo2);
3181
+ if (r2.status >= 300) throw refusal(r2.status, r2.error);
3182
+ return r2.reply;
3183
+ };
3184
+ const known = { invite: o.invite, admin: "", repo: "", base: "", start: "", projectId: "", readKey: "", keyId: "", undo: "" };
3185
+ const environments = [{ name: "production", branch: "", url: o.url }];
3186
+ let found;
3187
+ let proposals;
3188
+ let middleware;
3189
+ const filesOf = (plan) => {
3190
+ const places = found && placesOf(found.paths.layout);
3191
+ if (!found || !places) throw new StepError("layout_no_place");
3192
+ const layout = patchLayout(found.layout, specifier(found.paths.layout, places.widget));
3193
+ if (!layout) throw new StepError("layout_no_place");
3194
+ const names = {};
3195
+ for (const n3 of plan.names) {
3196
+ const [table = "", column = ""] = n3.split(".");
3197
+ names[table] = [...names[table] ?? [], column];
3198
+ }
3199
+ const reads = plan.tables.map((table) => ({ table, columns: proposals?.columns.get(table) ?? [] })).filter((r2) => r2.columns.length > 0);
3200
+ return {
3201
+ ...middleware ? { [middleware.path]: middleware.text } : {},
3202
+ "soron.config.json": configFile({ language: plan.language, reads, names }),
3203
+ [places.adapter]: adapterFor(found, places.adapter, staffOf(plan, places.adapter)),
3204
+ [places.route]: routeFile(specifier(places.route, places.adapter)),
3205
+ [places.widget]: widgetFile(o.service),
3206
+ [found.paths.layout]: layout
3207
+ };
3208
+ };
3209
+ const staffOf = (plan, adapter) => {
3210
+ const s = plan.staff;
3211
+ if (s.kind !== "guard") return s;
3212
+ return { kind: "guard", from: s.path.startsWith("./") ? specifier(adapter, s.path.slice(2)) : s.path, name: s.name };
3213
+ };
3214
+ const manager = () => {
3215
+ if (existsSync3(join3(cwd, "pnpm-lock.yaml"))) return { name: "pnpm", lock: "pnpm-lock.yaml", add: "add" };
3216
+ if (existsSync3(join3(cwd, "package-lock.json"))) return { name: "npm", lock: "package-lock.json", add: "install" };
3217
+ throw new StepError("no_lockfile");
3218
+ };
3219
+ const soronKeys = async (title = KEY_TITLE) => listOf(await run("gh", ["repo", "deploy-key", "list", "--repo", known.repo, "--json", "id,title,key"])).filter((k) => k["title"] === title);
3220
+ const sameKey = (a2, b) => typeof a2 === "string" && a2.split(" ").slice(0, 2).join(" ") === b.split(" ").slice(0, 2).join(" ");
3221
+ const github = (e) => {
3222
+ const err = stderrOf(e);
3223
+ if (/rate limit/i.test(err)) throw new StepError("github_rate_limited");
3224
+ if (/deploy keys? (are|is) disabled/i.test(err)) throw new StepError("org_forbids_keys");
3225
+ if (/HTTP 40[34]|not accessible|must have admin/i.test(err)) throw new StepError("not_admin");
3226
+ if (offline(e)) throw new StepError("offline");
3227
+ throw e;
3228
+ };
3229
+ const creations = {
3230
+ draft: {
3231
+ async run(plan) {
3232
+ const r2 = await ok("POST", "/v1/projects", {
3233
+ repo: known.repo,
3234
+ environments: plan.environments.map((e) => ({ name: e.name, branch: e.branch, url: e.url, origins: [new URL(e.url).origin] })),
3235
+ timeZone: plan.timeZone,
3236
+ caps: { question: { medium: plan.caps.question, high: plan.caps.question * 2 }, dayUsd: plan.caps.day, monthUsd: plan.caps.month },
3237
+ keys: { primary: plan.key, ...plan.backupKey ? { backup: plan.backupKey } : {} }
3238
+ });
3239
+ if (typeof r2["id"] !== "string" || typeof r2["readKey"] !== "string") throw new StepError("service_down");
3240
+ known.projectId = r2["id"];
3241
+ known.readKey = r2["readKey"];
3242
+ return { reused: r2["reused"] === true };
3243
+ },
3244
+ undo: async () => void await ok("DELETE", `/v1/projects/${known.projectId}`, void 0, true)
3245
+ },
3246
+ readKey: {
3247
+ async run() {
3248
+ const found2 = await soronKeys().catch(github);
3249
+ const same = found2.find((k) => sameKey(k["key"], known.readKey));
3250
+ if (same) {
3251
+ known.keyId = String(same["id"]);
3252
+ return { reused: true };
3253
+ }
3254
+ for (const old of found2) await run("gh", ["repo", "deploy-key", "delete", String(old["id"]), "--repo", known.repo]).catch(github);
3255
+ await run("gh", ["repo", "deploy-key", "add", "-", "--repo", known.repo, "--title", KEY_TITLE], `${known.readKey}
3256
+ `).catch(github);
3257
+ known.keyId = String((await soronKeys().catch(github)).find((k) => sameKey(k["key"], known.readKey))?.["id"] ?? "");
3258
+ return { reused: found2.length > 0 };
3259
+ },
3260
+ undo: async () => void await undoRun("gh", ["repo", "deploy-key", "delete", known.keyId, "--repo", known.repo])
3261
+ },
3262
+ verifyRead: {
3263
+ run: async () => (await ok("POST", `/v1/projects/${known.projectId}/verify-read`, {}), { reused: false })
3264
+ },
3265
+ hostVariable: {
3266
+ async run() {
3267
+ await run("vercel", ["env", "add", SECRET, "production", "--sensitive", "--force", "--yes"], randomBytes2(32).toString("base64url")).catch((e) => {
3268
+ if (missing(e)) throw new StepError("vercel_missing");
3269
+ if (offline(e)) throw new StepError("offline");
3270
+ throw new StepError("vercel_refused");
3271
+ });
3272
+ return { reused: false };
3273
+ },
3274
+ undo: async () => void await undoRun("vercel", ["env", "rm", SECRET, "production", "--yes"])
3275
+ },
3276
+ branch: {
3277
+ async run(plan) {
3278
+ const files = filesOf(plan);
3279
+ const m2 = manager();
3280
+ const reused = await git("branch", "--list", BRANCH) !== "";
3281
+ if (reused) await git("branch", "-D", BRANCH);
3282
+ await git("switch", "-c", BRANCH);
3283
+ let committed = false;
3284
+ try {
3285
+ for (const [path, text2] of Object.entries(files)) {
3286
+ mkdirSync(dirname(join3(cwd, path)), { recursive: true });
3287
+ writeFileSync(join3(cwd, path), text2);
3288
+ }
3289
+ await run(m2.name, [m2.add, `@soron-ai/next@${o.version}`]).catch((e) => {
3290
+ if (signal.aborted) throw e;
3291
+ throw new StepError("install_failed");
3292
+ });
3293
+ await git("add", "--", ...Object.keys(files), "package.json", m2.lock);
3294
+ await git("commit", "-m", "chore: add Soron").catch((e) => {
3295
+ if (signal.aborted) throw e;
3296
+ throw new StepError("pre_commit");
3297
+ });
3298
+ committed = true;
3299
+ } finally {
3300
+ await undoRun("git", ["checkout", "-f", known.start]);
3301
+ for (const path of Object.keys(files)) {
3302
+ const tracked = await undoRun("git", ["ls-files", "--error-unmatch", "--", path]).then(() => true, () => false);
3303
+ if (!tracked) rmSync(join3(cwd, path), { force: true });
3304
+ }
3305
+ if (!committed) await undoRun("git", ["branch", "-D", BRANCH]);
3306
+ }
3307
+ return { reused };
3308
+ },
3309
+ undo: async () => void await undoRun("git", ["branch", "-D", BRANCH])
3310
+ },
3311
+ push: {
3312
+ async run() {
3313
+ await git("push", `--force-with-lease=${BRANCH}`, "-u", "origin", BRANCH).catch((e) => {
3314
+ if (signal.aborted) throw e;
3315
+ throw new StepError(offline(e) ? "offline" : "pre_push");
3316
+ });
3317
+ return { reused: false };
3318
+ },
3319
+ undo: async () => void await undoRun("git", ["push", "origin", "--delete", BRANCH])
3320
+ },
3321
+ activation: {
3322
+ async run() {
3323
+ const r2 = await ok("POST", `/v1/projects/${known.projectId}/activate`, {});
3324
+ known.undo = typeof r2["undo"] === "string" ? r2["undo"] : "";
3325
+ return { reused: false };
3326
+ },
3327
+ undo: async () => void await ok("POST", `/v1/projects/${known.projectId}/deactivate`, { undo: known.undo }, true)
3328
+ },
3329
+ pr: {
3330
+ async run() {
3331
+ const open = listOf(await run("gh", ["pr", "list", "--repo", known.repo, "--head", BRANCH, "--state", "open", "--json", "number"]).catch(github))[0];
3332
+ if (typeof open?.["number"] === "number") return { reused: true, pr: open["number"] };
3333
+ const adapter = found && !found.stack ? placesOf(found.paths.layout)?.adapter : void 0;
3334
+ const body = adapter === void 0 ? PR_BODY : `${PR_BODY}${toComplete(found?.seen.auth, adapter)}`;
3335
+ const url = await run("gh", ["pr", "create", "--repo", known.repo, "--base", known.base, "--head", BRANCH, "--title", "Add Soron", "--body-file", "-"], body).catch((e) => {
3336
+ if (signal.aborted) throw e;
3337
+ throw new StepError("pr_refused");
3338
+ });
3339
+ const pr = Number(/\/pull\/(\d+)/.exec(url)?.[1] ?? 0);
3340
+ if (!pr) throw new StepError("pr_refused");
3341
+ return { reused: false, pr };
3342
+ },
3343
+ undo: async () => void await undoRun("gh", ["pr", "close", BRANCH, "--repo", known.repo])
3344
+ }
3345
+ };
3346
+ const held = async () => {
3347
+ const r2 = await ok("GET", "/v1/admin");
3348
+ const caps = r2["caps"];
3349
+ const envs = Array.isArray(r2["environments"]) ? r2["environments"] : [];
3350
+ const num = (v) => typeof v === "number" ? v : NaN;
3351
+ const question = typeof caps === "object" && caps !== null && "question" in caps && typeof caps.question === "object" && caps.question !== null && "medium" in caps.question ? num(caps.question.medium) : NaN;
3352
+ return {
3353
+ caps: { question, day: typeof caps === "object" && caps !== null && "dayUsd" in caps ? num(caps.dayUsd) : NaN, month: typeof caps === "object" && caps !== null && "monthUsd" in caps ? num(caps.monthUsd) : NaN },
3354
+ environments: envs.map((e) => objectOf(JSON.stringify(e))).map((e) => ({ name: String(e["name"] ?? ""), branch: String(e["branch"] ?? ""), url: String(e["url"] ?? "") }))
3355
+ };
3356
+ };
3357
+ const configPr = async (tables, names) => {
3358
+ const current = objectOf(existsSync3(join3(cwd, "soron.config.json")) ? readFileSync2(join3(cwd, "soron.config.json"), "utf8") : "{}");
3359
+ const language2 = current["language"] === "fr" ? "fr" : "en";
3360
+ const byTable = {};
3361
+ for (const n3 of names) {
3362
+ const [table = "", column = ""] = n3.split(".");
3363
+ byTable[table] = [...byTable[table] ?? [], column];
3364
+ }
3365
+ const reads = tables.map((table) => ({ table, columns: proposals?.columns.get(table) ?? [] })).filter((r2) => r2.columns.length > 0);
3366
+ if (await git("branch", "--list", CONFIG_BRANCH) !== "") await git("branch", "-D", CONFIG_BRANCH);
3367
+ await git("switch", "-c", CONFIG_BRANCH, `origin/${known.base}`);
3368
+ try {
3369
+ writeFileSync(join3(cwd, "soron.config.json"), configFile({ language: language2, reads, names: byTable }));
3370
+ await git("add", "--", "soron.config.json");
3371
+ await git("commit", "-m", "chore(soron): change its reads and masked names").catch((e) => {
3372
+ if (signal.aborted) throw e;
3373
+ throw new StepError("pre_commit");
3374
+ });
3375
+ } finally {
3376
+ await undoRun("git", ["checkout", "-f", known.start]);
3377
+ }
3378
+ await git("push", `--force-with-lease=${CONFIG_BRANCH}`, "-u", "origin", CONFIG_BRANCH).catch((e) => {
3379
+ if (signal.aborted) throw e;
3380
+ throw new StepError(offline(e) ? "offline" : "pre_push");
3381
+ });
3382
+ const url = await run("gh", ["pr", "create", "--repo", known.repo, "--base", known.base, "--head", CONFIG_BRANCH, "--title", "Change what Soron reads", "--body-file", "-"], CONFIG_PR_BODY).catch(() => {
3383
+ throw new StepError("pr_refused");
3384
+ });
3385
+ return Number(/\/pull\/(\d+)/.exec(url)?.[1] ?? 0);
3386
+ };
3387
+ const changes2 = {
3388
+ // A one-off key on the repo: only its admin can post one; our service reads with it (L32).
3389
+ async proveAdmin() {
3390
+ const challenge = await ok("POST", "/v1/admin/proof", { repo: known.repo });
3391
+ if (typeof challenge["id"] !== "string" || typeof challenge["publicKey"] !== "string") throw new StepError("service_down");
3392
+ try {
3393
+ await run("gh", ["repo", "deploy-key", "add", "-", "--repo", known.repo, "--title", PROOF_TITLE], `${challenge["publicKey"]}
3394
+ `).catch(github);
3395
+ const proved = await door("POST", `/v1/admin/proof/${challenge["id"]}`, {});
3396
+ if (proved.status === 403) throw new StepError("not_admin");
3397
+ if (proved.status >= 300 || typeof proved.reply["token"] !== "string") throw refusal(proved.status, proved.error);
3398
+ known.admin = proved.reply["token"];
3399
+ } finally {
3400
+ for (const k of await soronKeys(PROOF_TITLE).catch(() => [])) await undoRun("gh", ["repo", "deploy-key", "delete", String(k["id"]), "--repo", known.repo]).catch(() => void 0);
3401
+ }
3402
+ },
3403
+ caps: async () => (await held()).caps,
3404
+ setCaps: async (c2) => void await ok("POST", "/v1/admin/caps", { question: { medium: c2.question, high: c2.question * 2 }, dayUsd: c2.day, monthUsd: c2.month }),
3405
+ environments: async () => (await held()).environments,
3406
+ setEnvironments: async (list) => void await ok("POST", "/v1/admin/environments", list.map((e) => ({ name: e.name, branch: e.branch, url: e.url, origins: [new URL(e.url).origin] }))),
3407
+ setKey: async (which, key) => void await ok("POST", "/v1/admin/keys", { slot: which === "key" ? "primary" : "backup", key }),
3408
+ reads: configPr
3409
+ };
3410
+ const asked = io.ask ?? {
3411
+ invitation: async () => o.invite,
3412
+ environments: async (proposal) => proposal,
3413
+ // No rule given: « any session », which an agent may never choose.
3414
+ staff: async (proposal) => proposal[0] ?? { kind: "any_session" },
3415
+ language: async () => o.language,
3416
+ // No key on the input: the person types it on a one-off page of this machine (L35).
3417
+ async key() {
3418
+ if (o.anthropicKey) return o.anthropicKey;
3419
+ const p = await keyPage({ minutes: KEY_PAGE_MINUTES, texts: io.page });
3420
+ signal.addEventListener("abort", () => p.close());
3421
+ io.say({ tone: "agent", key: "key_page", detail: { url: p.url, minutes: KEY_PAGE_MINUTES } });
3422
+ return p.key;
3423
+ },
3424
+ backup: async () => o.backupKey,
3425
+ caps: async () => o.caps,
3426
+ timeZone: async () => o.timeZone,
3427
+ tables: async (proposal) => proposal.map((t2) => t2.name),
3428
+ names: async (proposal) => proposal.map((n3) => n3.name),
3429
+ recap: async () => true,
3430
+ changes: async () => o.changes
3431
+ };
3432
+ const ports = {
3433
+ // A staff rule is checked against the schema as soon as it is given, before anything is made.
3434
+ ask: {
3435
+ ...asked,
3436
+ async staff(proposal) {
3437
+ const rule2 = await asked.staff(proposal);
3438
+ if (found && staffUnchecked(found, rule2)) throw new StepError("staff_unchecked");
3439
+ return rule2;
3440
+ }
3441
+ },
3442
+ probe: {
3443
+ async machine() {
3444
+ if (Number(process.versions.node.split(".")[0]) < NODE_FLOOR) throw new StepError("node_old");
3445
+ if (await git("status", "--porcelain") !== "") throw new StepError("repo_dirty");
3446
+ known.start = await git("rev-parse", "--abbrev-ref", "HEAD");
3447
+ if (known.start === "HEAD") throw new StepError("detached_head");
3448
+ const seen = existsSync3(join3(cwd, "package.json")) ? stackSeen(readFileSync2(join3(cwd, "package.json"), "utf8")) : void 0;
3449
+ if (seen && seen.framework !== "Next.js") io.say({ tone: "info", key: "stack_found", detail: { framework: seen.framework, auth: seen.auth ?? "", orm: seen.orm === "prisma" ? "Prisma" : seen.orm ?? "" } });
3450
+ found = findStack(cwd, o.paths);
3451
+ if (secretRead(found, o.reads) !== void 0) throw new StepError("secret_read");
3452
+ await run("gh", ["auth", "status"]).catch((e) => {
3453
+ throw new StepError(missing(e) ? "gh_missing" : offline(e) ? "offline" : "gh_signed_out");
3454
+ });
3455
+ const view = objectOf(await run("gh", ["repo", "view", "--json", "nameWithOwner,defaultBranchRef"]).catch(() => "{}"));
3456
+ const ref = view["defaultBranchRef"];
3457
+ const base = typeof ref === "object" && ref !== null && "name" in ref && typeof ref.name === "string" ? ref.name : "";
3458
+ if (typeof view["nameWithOwner"] !== "string" || !base) throw new StepError("not_github");
3459
+ known.repo = view["nameWithOwner"];
3460
+ known.base = base;
3461
+ for (const e of environments) e.branch = base;
3462
+ proposals = proposalsOf({ reads: o.reads, names: o.names, staff: o.staff }, { tables: found.tables, layout: found.layout, layoutPath: found.paths.layout });
3463
+ },
3464
+ // Connected: its PR open or merged.
3465
+ connected: async () => listOf(await run("gh", ["pr", "list", "--repo", known.repo, "--head", BRANCH, "--state", "all", "--json", "state"]).catch(github)).some((p) => p["state"] === "OPEN" || p["state"] === "MERGED"),
3466
+ environments: async () => environments,
3467
+ async stack() {
3468
+ if (found) {
3469
+ const { framework, auth, orm } = found.seen;
3470
+ io.say({ tone: "info", key: "stack_found", detail: { framework, auth: auth ?? "", orm: found.orm ? orm === "prisma" ? "Prisma" : "drizzle" : "" } });
3471
+ const adapter = placesOf(found.paths.layout)?.adapter;
3472
+ if (!found.stack && adapter) io.say({ tone: "warn", key: "adapter_to_complete", detail: { auth: auth ?? "", path: adapter } });
3473
+ if (!found.orm) io.say({ tone: "warn", key: "code_only" });
3474
+ }
3475
+ const path = MIDDLEWARES.find((f) => existsSync3(join3(cwd, f)));
3476
+ if (path) {
3477
+ const fix = middlewareFix(readFileSync2(join3(cwd, path), "utf8"));
3478
+ if (fix.state === "patched") middleware = { path, text: fix.text };
3479
+ if (fix.state === "manual") io.say({ tone: "warn", key: "middleware_manual", detail: { path } });
3480
+ }
3481
+ },
3482
+ staff: async () => proposals?.staff ?? [],
3483
+ language: async () => o.language,
3484
+ timeZone: async () => o.timeZone,
3485
+ github: async () => ({ oldReadKey: (await soronKeys().catch(github)).length > 0 }),
3486
+ tables: async () => proposals?.tables ?? [],
3487
+ names: async (tables) => proposals?.names(tables) ?? []
3488
+ },
3489
+ verify: {
3490
+ async invitation(code) {
3491
+ known.invite = code;
3492
+ await ok("GET", "/v1/invite");
3493
+ },
3494
+ environments: async (list) => void await ok("POST", "/v1/reach", { urls: list.map((e) => e.url) }),
3495
+ key: async (key) => void await ok("POST", "/v1/keys/check", { key })
3496
+ },
3497
+ create: creations,
3498
+ change: changes2,
3499
+ wait: io.wait ?? ((seconds) => new Promise((ok2) => setTimeout(ok2, seconds * 1e3))),
3500
+ say: io.say,
3501
+ signal
3502
+ };
3503
+ return { ports, known, ok };
3504
+ }
3505
+
3506
+ // src/cli.ts
3507
+ var OUR_SERVICE = "https://soron.systisaac.com";
3508
+ var fail = (message) => {
3509
+ process.stderr.write(`\u2717 ${message}
3510
+ `);
3511
+ process.exit(1);
3512
+ };
3513
+ var tableColumns = (s) => {
3514
+ const [table = "", columns = ""] = s.split(":");
3515
+ return { table, columns: columns.split(",").filter(Boolean) };
3516
+ };
3517
+ var pathsOf = (v) => ({
3518
+ ...v.auth === void 0 ? {} : { auth: v.auth },
3519
+ ...v.db === void 0 ? {} : { db: v.db },
3520
+ ...v.schema === void 0 ? {} : { schema: v.schema },
3521
+ ...v.layout === void 0 ? {} : { layout: v.layout }
3522
+ });
3523
+ async function main() {
3524
+ const { values, positionals } = parseArgs({
3525
+ options: {
3526
+ version: { type: "boolean" },
3527
+ yes: { type: "boolean" },
3528
+ service: { type: "string" },
3529
+ invite: { type: "string" },
3530
+ "anthropic-key-stdin": { type: "boolean" },
3531
+ "backup-key-stdin": { type: "boolean" },
3532
+ caps: { type: "string" },
3533
+ change: { type: "string" },
3534
+ url: { type: "string" },
3535
+ language: { type: "string", default: "en" },
3536
+ read: { type: "string", multiple: true, default: [] },
3537
+ names: { type: "string", multiple: true, default: [] },
3538
+ staff: { type: "string" },
3539
+ "time-zone": { type: "string" },
3540
+ // Found by the command when not given (`setup/stack.ts`).
3541
+ auth: { type: "string" },
3542
+ db: { type: "string" },
3543
+ schema: { type: "string" },
3544
+ layout: { type: "string" }
3545
+ },
3546
+ strict: true,
3547
+ allowPositionals: true
3548
+ });
3549
+ if (values.version === true) return void process.stdout.write(`${"0.1.0"}
3550
+ `);
3551
+ if (positionals[0] === "instructions") return void process.stdout.write(INSTRUCTIONS);
3552
+ if (positionals[0] === "check") {
3553
+ const t3 = TEXTS[machineLanguage()];
3554
+ const service2 = values.service ?? OUR_SERVICE;
3555
+ const url2 = values.url ?? fail("--url is missing: the address of your back-office, https://\u2026/admin.");
3556
+ if (!serviceAddress(service2)) fail("--service must be an https:// address.");
3557
+ const lines = await checkDeployed({ url: url2, service: service2 });
3558
+ for (const l of lines) process.stdout.write(`${l.ok ? t3.check[l.key].ok : t3.check[l.key].fail}
3559
+ `);
3560
+ if (lines.some((l) => !l.ok)) process.exit(1);
3561
+ return;
3562
+ }
3563
+ if (positionals[0] === "status") {
3564
+ const t3 = TEXTS[machineLanguage()];
3565
+ const service2 = values.service ?? OUR_SERVICE;
3566
+ if (!serviceAddress(service2)) fail("--service must be an https:// address.");
3567
+ const options = { service: service2, invite: "", anthropicKey: "", backupKey: null, url: "", timeZone: "", language: "en", caps: { question: 1, day: 20, month: 200 }, reads: [], names: {}, staff: null, paths: pathsOf(values), version: "0.1.0", changes: [] };
3568
+ const say = (line) => process.stdout.write(`${screenLine(line, t3)}
3569
+ `);
3570
+ try {
3571
+ const held = await status(options, { cwd: process.cwd(), say, signal: new AbortController().signal, mode: "agent", page: t3.ask.page });
3572
+ const at = (v, ...path) => path.reduce((x, k) => typeof x === "object" && x !== null && k in x ? Reflect.get(x, k) : void 0, v);
3573
+ const num = (v) => typeof v === "number" ? v : 0;
3574
+ say({ tone: "ok", key: "admin_proved" });
3575
+ process.stdout.write(`${t3.status.keys(at(held, "keys", "backup") === true)}
3576
+ `);
3577
+ process.stdout.write(`${t3.status.caps(num(at(held, "caps", "question", "medium")), num(at(held, "caps", "dayUsd")), num(at(held, "caps", "monthUsd")))}
3578
+ `);
3579
+ process.stdout.write(`${t3.status.spend(num(at(held, "spend", "dayUsd")), num(at(held, "spend", "monthUsd")))}
3580
+ `);
3581
+ const file = join4(process.cwd(), CONFIG_FILE);
3582
+ const raw = existsSync4(file) ? readFileSync3(file, "utf8") : void 0;
3583
+ let parsed;
3584
+ try {
3585
+ parsed = raw === void 0 ? void 0 : JSON.parse(raw);
3586
+ } catch {
3587
+ parsed = void 0;
3588
+ }
3589
+ process.stdout.write(`${t3.status.config(raw === void 0 ? "is missing" : configProblem(parsed))}
3590
+ `);
3591
+ process.stdout.write(`${t3.status.version("0.1.0", String(at(held, "floor") ?? "0.0.0"))}
3592
+ `);
3593
+ } catch (e) {
3594
+ if (e instanceof StepError) {
3595
+ say({ tone: "err", key: "error", detail: { code: e.code, side: sideOf(e.code) } });
3596
+ process.exit(1);
3597
+ }
3598
+ throw e;
3599
+ }
3600
+ return;
3601
+ }
3602
+ if (positionals.length > 0) fail(`Unknown command: ${positionals.join(" ")}. Run with --help, or: npx @soron-ai/next instructions`);
3603
+ const t2 = TEXTS[machineLanguage()];
3604
+ const service = values.service ?? OUR_SERVICE;
3605
+ if (!serviceAddress(service)) fail("--service must be an https:// address.");
3606
+ const human = process.stdin.isTTY === true && process.stdout.isTTY === true && values.yes !== true && values["anthropic-key-stdin"] !== true;
3607
+ const changes2 = (values.change ?? "").split(",").map((c2) => c2.trim()).filter(Boolean);
3608
+ const known = ["caps", "key", "backup", "environments", "reads"];
3609
+ const picked = known.filter((c2) => changes2.includes(c2));
3610
+ if (picked.length !== changes2.length) fail(`--change is not valid: some of ${known.join(", ")}.`);
3611
+ const relaunch = picked.length > 0;
3612
+ const invite = values.invite ?? (human || relaunch ? "" : fail("--invite is missing: ask for an invitation code."));
3613
+ const url = values.url ?? (human || relaunch ? "" : fail("--url is missing: the address of your back-office, https://\u2026/admin."));
3614
+ let anthropicKey = "";
3615
+ let backupKey = "";
3616
+ if (values["anthropic-key-stdin"] === true) {
3617
+ ;
3618
+ [anthropicKey = "", backupKey = ""] = readFileSync3(0, "utf8").split(/\r?\n/).map((l) => l.trim());
3619
+ if (!anthropicKey) fail("No Claude key on the input.");
3620
+ if (values["backup-key-stdin"] === true && !backupKey) fail("--backup-key-stdin: no backup key on the second line of the input.");
3621
+ }
3622
+ const staff = values.staff === void 0 ? null : staffRule(values.staff) ?? fail("--staff is not valid: who is staff, as table.column=value1,value2, no value empty.");
3623
+ if (!staff && !human && !relaunch) fail("--staff is missing: who is staff, as table.column=value1,value2.");
3624
+ if (!human && !relaunch && values.read.length === 0) fail("--read is missing: the tables Soron may read, as table:column1,column2 (secrets are never read).");
3625
+ const reads = values.read.map(tableColumns);
3626
+ const secret = secretIn(reads);
3627
+ if (secret !== void 0) fail(`--read lists ${secret}: Soron never reads a secret (a password, a token, a key, the sessions and accounts of the auth).`);
3628
+ const names = Object.fromEntries(values.names.map(tableColumns).map((n3) => [n3.table, n3.columns]));
3629
+ const config = readConfig({ language: values.language, reads, names });
3630
+ if (!config) fail(`--language, --read or --names is not valid: soron.config.json ${configProblem({ language: values.language, reads, names }) ?? "would not read"}. Names go as the database has them; the language is en or fr.`);
3631
+ const caps = (values.caps ?? "1,20,200").split(",").map(Number);
3632
+ const [question = NaN, day = NaN, month = NaN] = caps;
3633
+ if (caps.length !== 3) fail("--caps is not valid: three amounts in dollars, per question, day and month, as 1,20,200.");
3634
+ const language2 = config?.language ?? "en";
3635
+ const interrupt = new AbortController();
3636
+ process.on("SIGINT", () => {
3637
+ if (interrupt.signal.aborted) process.exit(130);
3638
+ interrupt.abort();
3639
+ });
3640
+ const { outcome, repo } = await setup(
3641
+ {
3642
+ service,
3643
+ invite,
3644
+ anthropicKey,
3645
+ backupKey: values["backup-key-stdin"] === true ? backupKey : null,
3646
+ url,
3647
+ timeZone: values["time-zone"] ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
3648
+ language: language2,
3649
+ caps: { question, day, month },
3650
+ reads,
3651
+ names,
3652
+ staff,
3653
+ paths: pathsOf(values),
3654
+ version: "0.1.0",
3655
+ changes: picked
3656
+ },
3657
+ { cwd: process.cwd(), say: (line) => process.stdout.write(`${screenLine(line, t2)}
3658
+ `), signal: interrupt.signal, mode: human ? "human" : "agent", page: t2.ask.page, ...human ? { ask: screenAsk(t2) } : {} }
3659
+ );
3660
+ if (outcome.status === "connected") return void process.stdout.write(`https://github.com/${repo}/pull/${outcome.pr}
3661
+ `);
3662
+ if (outcome.status === "unchanged" || outcome.status === "changed") return;
3663
+ if (outcome.status === "stopped") {
3664
+ if (outcome.left.length > 0) process.stderr.write(`Left behind: ${outcome.left.join(", ")}
3665
+ `);
3666
+ const cause = outcome.cause;
3667
+ if (cause instanceof ProgramError) process.stderr.write(`${cause.message}${cause.stderr ? `
3668
+ ${cause.stderr.trim()}` : ""}
3669
+ `);
3670
+ else if (cause !== void 0) process.stderr.write(`${cause instanceof Error ? cause.message : String(cause)}
3671
+ `);
3672
+ }
3673
+ process.exit(1);
3674
+ }
3675
+ main().catch((e) => {
3676
+ if (e instanceof ProgramError) fail(`${e.message}${e.stderr ? `
3677
+ ${e.stderr.trim()}` : ""}`);
3678
+ fail(e instanceof Error ? e.message : String(e));
3679
+ });