compivia 0.0.0-stage → 0.0.1128
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/bin/compivia.mjs +40 -0
- package/dist/compivia.mjs +16787 -0
- package/dist/files.json +1 -0
- package/dist/loader.mjs +681 -0
- package/dist/plugin/host-entry.mjs +192 -0
- package/package.json +37 -4
- package/README.md +0 -3
package/dist/files.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
["compivia.mjs","loader.mjs","plugin/host-entry.mjs"]
|
package/dist/loader.mjs
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
// src/loader/run.ts
|
|
2
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
3
|
+
import { dirname as dirname2, join as join5 } from "node:path";
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
// ../plan-checks/src/redact.ts
|
|
7
|
+
var SECRET_PATTERNS = [
|
|
8
|
+
// Учётные данные в URL: scheme://user:password@host
|
|
9
|
+
[/([a-z][a-z0-9+.-]{0,32}:\/\/[^/\s:@]{1,512}:)[^\s@]{1,512}@/giu, "$1***@"],
|
|
10
|
+
// Токен как единственный userinfo: scheme://<opaque-token>@host
|
|
11
|
+
[/([a-z][a-z0-9+.-]{0,32}:\/\/)[^\s/@:]{8,512}@/giu, "$1***@"],
|
|
12
|
+
// Пароль без пользователя: scheme://:password@host (канонический DSN Redis)
|
|
13
|
+
[/([a-z][a-z0-9+.-]{0,32}:\/\/:)[^\s@/]{1,512}@/giu, "$1***@"],
|
|
14
|
+
// Закавычкованный аргумент -u/--user целиком: внутри может быть user:pass
|
|
15
|
+
// с любыми символами — маскируется весь аргумент.
|
|
16
|
+
[/((?:-u|--user)\s+)("[^"]{0,512}"|'[^']{0,512}')/giu, "$1***"],
|
|
17
|
+
// curl -u/--user user:password — с host и без (canonical basic-auth);
|
|
18
|
+
// значение — кавычкованное целиком или без пробелов. Без `/`: маскируются
|
|
19
|
+
// учётные данные, но не пути URL (`-u redis://:***@host` после URL-паттернов
|
|
20
|
+
// не трогается повторно).
|
|
21
|
+
[/(-u\s+|--user\s+)([^\s"@:]{1,512}):("[^"]{0,512}"|'[^']{0,512}'|[^\s"@/]{1,512})/giu, "$1$2:***"],
|
|
22
|
+
// sshpass/mysql/docker -p password; значение — кавычкованное целиком или без пробелов
|
|
23
|
+
[/((?:sshpass\s+|mysql\s+|docker\s+login\s+[^\n]*?)-p\s*)("[^"]{0,512}"|'[^']{0,512}'|["']?[^\s"']{1,512})/giu, "$1***"],
|
|
24
|
+
// Секретное поле в JSON-теле запроса: "password": "…" и родственные имена.
|
|
25
|
+
// Значение — до неэкранированной закрывающей кавычки (чётное число
|
|
26
|
+
// непосредственно предшествующих обратных косых черт) или до конца строки:
|
|
27
|
+
// `\"` и пары `\\` не завершают секрет, хвост за экранированной кавычкой не
|
|
28
|
+
// утекает; прежний потолок 512 снят — граница ищется до конца. Ветви
|
|
29
|
+
// различимы по первому символу — линейный проход, без катастрофического
|
|
30
|
+
// backtracking; набор ключей, регистронезависимость и одинарные
|
|
31
|
+
// value-формы прежние.
|
|
32
|
+
[/(["'](?:password|passwd|secret|token|passphrase|api[-_]?key|auth[-_]?token|secret[-_]?access[-_]?key)["']\s*:\s*)("(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$))/giu, "$1***"],
|
|
33
|
+
// Значение заголовка авторизации/аутентификации — до закрывающей кавычки
|
|
34
|
+
// или конца строки, схема значения (Bearer/Token/…) не различается
|
|
35
|
+
[/((?<!--)(?<!\s-)(?<!^-)(?:authorization|x-api-key|private-token|x-auth-token|cookie|set-cookie)['"]?\s*[:=]\s*)[^"']{1,4096}/giu, "$1***"],
|
|
36
|
+
// Guard-ы перед ключевым словом: флаг-контекст (`--cookie=…`, маска
|
|
37
|
+
// `--cookie=***` на повторном проходе) — не заголовок, иначе повторное
|
|
38
|
+
// маскирование съедает хвост ссылки как форму `cookie: значение`. Только
|
|
39
|
+
// флаг-формы блокируются: составные имена заголовков (proxy-authorization,
|
|
40
|
+
// X-Custom-Cookie) маскируются как раньше.
|
|
41
|
+
// curl cookie argv: -b/--cookie VALUE, --cookie=VALUE, приклеенная -bVALUE.
|
|
42
|
+
// Значение целиком → *** (флаг и разделитель сохраняются): аргумент может
|
|
43
|
+
// нести несколько пар, `;`, пробелы и `=`. Кавычкованное — до неэкранированной
|
|
44
|
+
// закрывающей кавычки, незакрытая — до конца строки (потолок 512 не
|
|
45
|
+
// применяется к этой форме); unquoted — до пробела. Границы флага: пробел/
|
|
46
|
+
// начало строки перед ним и тип символа после не путают --cookie-jar,
|
|
47
|
+
// --cookieish, -B, фрагменты имён/URL; регистр значим. После паттерна
|
|
48
|
+
// заголовков: маска `--cookie=***` иначе выглядит для него как форма
|
|
49
|
+
// `cookie: значение` — съедается хвост строки за значением.
|
|
50
|
+
[/((?:^|\s)--cookie=)("(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$)|[^\s"']+)/gu, "$1***"],
|
|
51
|
+
[/((?:^|\s)--cookie\s+)("(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$)|[^\s"']+)/gu, "$1***"],
|
|
52
|
+
[/((?:^|\s)-b\s+)("(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$)|[^\s"']+)/gu, "$1***"],
|
|
53
|
+
[/((?:^|\s)-b)("(?:\\[\s\S]|[^"\\])*(?:"|$)|'[^']*(?:'|$)|[^\s"']+)/gu, "$1***"],
|
|
54
|
+
// =-форма значений (флаги и env): --token=…, AWS_SECRET_ACCESS_KEY=…;
|
|
55
|
+
// значение — кавычкованное целиком или без пробелов
|
|
56
|
+
[/((?:--?)?(?:secret[-_]?access[-_]?key|access[-_]?key|aws[-_]?secret[-_]?key|password|passwd|token|secret|passphrase|api[-_]?key|auth[-_]?token)=)"([^"]{0,512})"/giu, "$1***"],
|
|
57
|
+
[/((?:--?)?(?:secret[-_]?access[-_]?key|access[-_]?key|aws[-_]?secret[-_]?key|password|passwd|token|secret|passphrase|api[-_]?key|auth[-_]?token)=)'([^']{0,512})'/giu, "$1***"],
|
|
58
|
+
[/((?:--?)?(?:secret[-_]?access[-_]?key|access[-_]?key|aws[-_]?secret[-_]?key|password|passwd|token|secret|passphrase|api[-_]?key|auth[-_]?token)=(?:["']?))[^\s'"]{1,512}/giu, "$1***"],
|
|
59
|
+
// Пробельная форма — только у long-опций (`--token …`) и UPPERCASE-ключей
|
|
60
|
+
// (`TOKEN …`), без флага `i`: голое слово после `secret` — подкоманда
|
|
61
|
+
// (`create secret generic`), не значение; значение — кавычкованное целиком
|
|
62
|
+
// или без пробелов
|
|
63
|
+
[/((?:--(?:secret[-_]?access[-_]?key|access[-_]?key|aws[-_]?secret[-_]?key|password|passwd|token|secret|passphrase|api[-_]?key|auth[-_]?token)|\b(?:AWS[-_]?SECRET[-_]?ACCESS[-_]?KEY|SECRET[-_]?ACCESS[-_]?KEY|ACCESS[-_]?KEY|AWS[-_]?SECRET[-_]?KEY|PASSWORD|PASSWD|TOKEN|SECRET|PASSPHRASE|API[-_]?KEY|AUTH[-_]?TOKEN))\s+)("[^"]{0,512}"|'[^']{0,512}'|["']?[^\s"']{1,512})/gu, "$1***"],
|
|
64
|
+
// Известные формы токенов провайдеров
|
|
65
|
+
[/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,512}\b/gu, "***"],
|
|
66
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,512}\b/gu, "***"],
|
|
67
|
+
[/\bglpat-[A-Za-z0-9_-]{16,512}\b/gu, "***"],
|
|
68
|
+
[/\bsk-[A-Za-z0-9_-]{16,512}\b/gu, "***"],
|
|
69
|
+
[/\bAKIA[0-9A-Z]{16}\b/gu, "***"],
|
|
70
|
+
[/\bxox[baprs]-[A-Za-z0-9-]{10,512}\b/gu, "***"],
|
|
71
|
+
// Голая Bearer-форма без имени ключа: текст ошибки/заголовка, попавший в
|
|
72
|
+
// произвольное строковое поле (перенос из локального redactSecrets
|
|
73
|
+
// runner-core, снятого миграцией #590 — выравнивание покрытия #609).
|
|
74
|
+
// Потолок 8+ символов отсекает прозу («Bearer tokens are…»).
|
|
75
|
+
[/\bBearer\s+[^\s,;]{8,512}/giu, "Bearer ***"]
|
|
76
|
+
];
|
|
77
|
+
var SNAKE_SUFFIX = /[-_](?:key|token|secret|password|passwd|passphrase)$/u;
|
|
78
|
+
var SECRET_LIKE = /^(?=.*[A-Z0-9]).{8,512}$/u;
|
|
79
|
+
function redactSecrets(reference) {
|
|
80
|
+
let result = reference;
|
|
81
|
+
for (const [pattern, replacement] of SECRET_PATTERNS) result = result.replace(pattern, replacement);
|
|
82
|
+
return redactMachinePaths(redactSnakeValues(result));
|
|
83
|
+
}
|
|
84
|
+
var MACHINE_PATHS = /(?:\/(?:Users|home|root|private\/var|var\/folders|tmp)\/)[^\s'"]{0,512}/gu;
|
|
85
|
+
function redactMachinePaths(result) {
|
|
86
|
+
return result.replace(MACHINE_PATHS, "/***");
|
|
87
|
+
}
|
|
88
|
+
function redactSnakeValues(result) {
|
|
89
|
+
const tokens = result.split(/(\s+)/);
|
|
90
|
+
for (let index = 0; index + 2 < tokens.length; index += 2) {
|
|
91
|
+
const name = tokens[index];
|
|
92
|
+
const value = tokens[index + 2];
|
|
93
|
+
if (/^[a-z0-9_-]{3,512}$/u.test(name) && SNAKE_SUFFIX.test(name) && SECRET_LIKE.test(value)) tokens[index + 2] = "***";
|
|
94
|
+
}
|
|
95
|
+
return tokens.join("");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ../log/src/redact.ts
|
|
99
|
+
var SENSITIVE_KEY = /(?:api[_ -]?key|token|secret|password|authorization|credential|cookie|session)/iu;
|
|
100
|
+
var REDACTED = "[redacted]";
|
|
101
|
+
function redactLogFields(fields) {
|
|
102
|
+
return Object.fromEntries(Object.entries(fields).map(([key, value]) => [key, redactEntry(key, value)]));
|
|
103
|
+
}
|
|
104
|
+
function redactEntry(key, value) {
|
|
105
|
+
if (SENSITIVE_KEY.test(key)) return REDACTED;
|
|
106
|
+
return redactValue(value);
|
|
107
|
+
}
|
|
108
|
+
function redactValue(value) {
|
|
109
|
+
if (typeof value === "string") return redactSecrets(value);
|
|
110
|
+
if (Array.isArray(value)) return value.map(redactValue);
|
|
111
|
+
if (value !== null && typeof value === "object") {
|
|
112
|
+
const toJSON = value.toJSON;
|
|
113
|
+
if (typeof toJSON === "function") {
|
|
114
|
+
const serialized = toJSON.call(value);
|
|
115
|
+
return typeof serialized === "string" ? redactSecrets(serialized) : redactValue(serialized);
|
|
116
|
+
}
|
|
117
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, redactEntry(key, inner)]));
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ../log/src/serialize-error.ts
|
|
123
|
+
var MAX_DEPTH = 5;
|
|
124
|
+
function serializeError(error, level) {
|
|
125
|
+
return serialize(error, level, 1);
|
|
126
|
+
}
|
|
127
|
+
function serialize(value, level, depth) {
|
|
128
|
+
if (!(value instanceof Error)) {
|
|
129
|
+
return { name: typeof value === "string" ? value : "non-error", message: String(value) };
|
|
130
|
+
}
|
|
131
|
+
const out = { name: value.name, message: value.message };
|
|
132
|
+
if (level === "debug" || level === "trace") out.stack = value.stack;
|
|
133
|
+
if (depth < MAX_DEPTH) {
|
|
134
|
+
if (value.cause !== void 0 && value.cause !== null) out.cause = serialize(value.cause, level, depth + 1);
|
|
135
|
+
if (value instanceof AggregateError && value.errors.length > 0) {
|
|
136
|
+
out.errors = value.errors.map((item) => serialize(item, level, depth + 1));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ../log/src/logger.ts
|
|
143
|
+
var LEVEL_ORDER = { trace: 0, debug: 1, info: 2, warn: 3, error: 4 };
|
|
144
|
+
var LEVELS = new Set(Object.keys(LEVEL_ORDER));
|
|
145
|
+
var PROTECTED_KEYS = /* @__PURE__ */ new Set(["ts", "level", "msg", "component"]);
|
|
146
|
+
function resolveLogLevel(raw) {
|
|
147
|
+
if (raw === void 0) return "info";
|
|
148
|
+
const value = raw.toLowerCase();
|
|
149
|
+
return LEVELS.has(value) ? value : "info";
|
|
150
|
+
}
|
|
151
|
+
function createLogger(options) {
|
|
152
|
+
const threshold = options.level ?? resolveLogLevel(process.env.LOG_LEVEL);
|
|
153
|
+
const write = options.write ?? ((line) => process.stdout.write(line));
|
|
154
|
+
return build(options.component, {}, threshold, write);
|
|
155
|
+
}
|
|
156
|
+
function build(component, bindings, threshold, write) {
|
|
157
|
+
const emit = (level, msg, fields) => {
|
|
158
|
+
if (LEVEL_ORDER[level] < LEVEL_ORDER[threshold]) return;
|
|
159
|
+
const merged = {};
|
|
160
|
+
for (const [key, value] of Object.entries(bindings)) if (!PROTECTED_KEYS.has(key)) merged[key] = value;
|
|
161
|
+
for (const [key, value] of Object.entries(fields ?? {})) if (!PROTECTED_KEYS.has(key)) merged[key] = value;
|
|
162
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
163
|
+
let line;
|
|
164
|
+
try {
|
|
165
|
+
for (const [key, value] of Object.entries(merged)) {
|
|
166
|
+
if (value instanceof Error) merged[key] = serializeError(value, level);
|
|
167
|
+
}
|
|
168
|
+
line = JSON.stringify({ ts, level, msg, component, ...redactLogFields(merged) }) + "\n";
|
|
169
|
+
} catch {
|
|
170
|
+
line = JSON.stringify({ ts, level, msg, component, fields_dropped: true }) + "\n";
|
|
171
|
+
}
|
|
172
|
+
write(line);
|
|
173
|
+
};
|
|
174
|
+
return {
|
|
175
|
+
trace: (msg, fields) => emit("trace", msg, fields),
|
|
176
|
+
debug: (msg, fields) => emit("debug", msg, fields),
|
|
177
|
+
info: (msg, fields) => emit("info", msg, fields),
|
|
178
|
+
warn: (msg, fields) => emit("warn", msg, fields),
|
|
179
|
+
error: (msg, fields) => emit("error", msg, fields),
|
|
180
|
+
child: (extra) => {
|
|
181
|
+
const nextBindings = { ...bindings };
|
|
182
|
+
let nextComponent = component;
|
|
183
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
184
|
+
if (key === "component") {
|
|
185
|
+
if (typeof value === "string") nextComponent = value;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (!PROTECTED_KEYS.has(key)) nextBindings[key] = value;
|
|
189
|
+
}
|
|
190
|
+
return build(nextComponent, nextBindings, threshold, write);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ../log/src/noop.ts
|
|
196
|
+
var noop = () => void 0;
|
|
197
|
+
var noopLogger = {
|
|
198
|
+
trace: noop,
|
|
199
|
+
debug: noop,
|
|
200
|
+
info: noop,
|
|
201
|
+
warn: noop,
|
|
202
|
+
error: noop,
|
|
203
|
+
child: () => noopLogger
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
// src/log.ts
|
|
207
|
+
var KNOWN_LEVELS = /* @__PURE__ */ new Set(["trace", "debug", "info", "warn", "error"]);
|
|
208
|
+
function createWrapperLogger(env = process.env) {
|
|
209
|
+
const requested = env.LOG_LEVEL?.toLowerCase();
|
|
210
|
+
const level = requested !== void 0 && KNOWN_LEVELS.has(requested) ? requested : "error";
|
|
211
|
+
return createLogger({ component: "cli", level, write: (line) => process.stderr.write(line) });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/loader/errors.ts
|
|
215
|
+
var LoaderError = class extends Error {
|
|
216
|
+
};
|
|
217
|
+
function describeError(error) {
|
|
218
|
+
return error instanceof Error ? error.message : String(error);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/loader/home.ts
|
|
222
|
+
import { join, resolve } from "node:path";
|
|
223
|
+
function resolveCompiviaHome(env, logger = noopLogger) {
|
|
224
|
+
const override = env.COMPIVIA_HOME;
|
|
225
|
+
if (override !== void 0 && override !== "") {
|
|
226
|
+
const resolved2 = resolve(override);
|
|
227
|
+
logger.debug("compivia home resolved", { decision: "env_override", reason: "compivia_home_set", path: resolved2 });
|
|
228
|
+
return resolved2;
|
|
229
|
+
}
|
|
230
|
+
const home = env.HOME;
|
|
231
|
+
if (home === void 0 || home === "") {
|
|
232
|
+
throw new LoaderError("COMPIVIA_HOME is not set and HOME is empty; set COMPIVIA_HOME or HOME");
|
|
233
|
+
}
|
|
234
|
+
const resolved = resolve(join(home, ".compivia"));
|
|
235
|
+
logger.debug("compivia home resolved", { decision: "home_default", reason: "compivia_home_unset", path: resolved });
|
|
236
|
+
return resolved;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// src/loader/layout.ts
|
|
240
|
+
import { accessSync, constants } from "node:fs";
|
|
241
|
+
import { basename, join as join2 } from "node:path";
|
|
242
|
+
function homeLayout(home) {
|
|
243
|
+
return {
|
|
244
|
+
home,
|
|
245
|
+
binDir: join2(home, "bin"),
|
|
246
|
+
binPath: join2(home, "bin", "compivia"),
|
|
247
|
+
versionsDir: join2(home, "versions"),
|
|
248
|
+
currentPath: join2(home, "current")
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function setDirName(version) {
|
|
252
|
+
return `wrapper-${version}`;
|
|
253
|
+
}
|
|
254
|
+
function parseSetManifest(raw) {
|
|
255
|
+
let parsed;
|
|
256
|
+
try {
|
|
257
|
+
parsed = JSON.parse(raw);
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
if (typeof parsed !== "object" || parsed === null) return null;
|
|
262
|
+
const record = parsed;
|
|
263
|
+
if (typeof record.set !== "string" || record.set === "") return null;
|
|
264
|
+
const wrapper = record.wrapper;
|
|
265
|
+
if (typeof wrapper !== "object" || wrapper === null) return null;
|
|
266
|
+
const wrapperRecord = wrapper;
|
|
267
|
+
if (typeof wrapperRecord.name !== "string" || typeof wrapperRecord.version !== "string") return null;
|
|
268
|
+
if (!Array.isArray(record.components)) return null;
|
|
269
|
+
const components = [];
|
|
270
|
+
for (const entry of record.components) {
|
|
271
|
+
if (typeof entry !== "object" || entry === null) return null;
|
|
272
|
+
const entryRecord = entry;
|
|
273
|
+
if (typeof entryRecord.name !== "string" || typeof entryRecord.version !== "string") return null;
|
|
274
|
+
components.push({ name: entryRecord.name, version: entryRecord.version });
|
|
275
|
+
}
|
|
276
|
+
return { set: record.set, wrapper: { name: wrapperRecord.name, version: wrapperRecord.version }, components };
|
|
277
|
+
}
|
|
278
|
+
function renderShim(nodeExecPath, home) {
|
|
279
|
+
const bundlePath = join2(home, "current", "compivia.mjs");
|
|
280
|
+
return [
|
|
281
|
+
`#!${nodeExecPath}`,
|
|
282
|
+
'import { pathToFileURL } from "node:url";',
|
|
283
|
+
"try {",
|
|
284
|
+
` await import(pathToFileURL(${JSON.stringify(bundlePath)}).href);`,
|
|
285
|
+
"} catch (error) {",
|
|
286
|
+
` process.stderr.write(${JSON.stringify(`compivia: installation is missing or corrupt in ${home}; run npx compivia@latest doctor
|
|
287
|
+
`)});`,
|
|
288
|
+
" process.exit(1);",
|
|
289
|
+
"}",
|
|
290
|
+
""
|
|
291
|
+
].join("\n");
|
|
292
|
+
}
|
|
293
|
+
function isExecutable(path) {
|
|
294
|
+
try {
|
|
295
|
+
accessSync(path, constants.X_OK);
|
|
296
|
+
return true;
|
|
297
|
+
} catch {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function spacedNodeHint(execPath, binPath) {
|
|
302
|
+
if (!/\s/.test(execPath)) return null;
|
|
303
|
+
return `compivia: the Node path contains a space (${execPath}); shim ${binPath} with such a shebang cannot be executed by the kernel \u2014 diagnose with: npx compivia@latest doctor
|
|
304
|
+
`;
|
|
305
|
+
}
|
|
306
|
+
function pathContains(pathEnv, binDir) {
|
|
307
|
+
if (pathEnv === void 0 || pathEnv === "") return false;
|
|
308
|
+
return pathEnv.split(":").includes(binDir);
|
|
309
|
+
}
|
|
310
|
+
function shDoubleQuote(path) {
|
|
311
|
+
return path.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\$/g, "\\$").replace(/`/g, "\\`");
|
|
312
|
+
}
|
|
313
|
+
function shSingleQuote(path) {
|
|
314
|
+
return path.replace(/'/g, `'\\''`);
|
|
315
|
+
}
|
|
316
|
+
function fishQuote(path) {
|
|
317
|
+
if (/^[A-Za-z0-9_./:+=-]+$/.test(path)) return path;
|
|
318
|
+
return `'${path.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
319
|
+
}
|
|
320
|
+
function pathHintCommand(shellBase, binDir) {
|
|
321
|
+
const shell = shellBase === void 0 || shellBase === "" ? "" : basename(shellBase);
|
|
322
|
+
if (shell === "fish") return `fish_add_path ${fishQuote(binDir)}`;
|
|
323
|
+
if (shell === "zsh" || shell === "bash") {
|
|
324
|
+
const line = `export PATH="${shDoubleQuote(binDir)}:$PATH"`;
|
|
325
|
+
return `echo '${shSingleQuote(line)}' >> ~/.${shell}rc`;
|
|
326
|
+
}
|
|
327
|
+
return `export PATH="${shDoubleQuote(binDir)}:$PATH"`;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/loader/install.ts
|
|
331
|
+
import { chmodSync, copyFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
332
|
+
import { randomBytes } from "node:crypto";
|
|
333
|
+
import { dirname, join as join4 } from "node:path";
|
|
334
|
+
|
|
335
|
+
// src/loader/inspect.ts
|
|
336
|
+
import { existsSync, readFileSync, readlinkSync, statSync } from "node:fs";
|
|
337
|
+
import { basename as basename2, isAbsolute, join as join3 } from "node:path";
|
|
338
|
+
function readSetManifest(setDir, logger = noopLogger) {
|
|
339
|
+
let bundleSize = 0;
|
|
340
|
+
try {
|
|
341
|
+
bundleSize = statSync(join3(setDir, "compivia.mjs")).size;
|
|
342
|
+
} catch (error) {
|
|
343
|
+
logger.debug("version set rejected", { decision: "invalid_set", reason: "bundle_missing", set_dir: setDir, err: error });
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
if (bundleSize === 0) {
|
|
347
|
+
logger.debug("version set rejected", { decision: "invalid_set", reason: "bundle_empty", set_dir: setDir });
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
let raw;
|
|
351
|
+
try {
|
|
352
|
+
raw = readFileSync(join3(setDir, "set.json"), "utf8");
|
|
353
|
+
} catch (error) {
|
|
354
|
+
logger.debug("version set rejected", { decision: "invalid_set", reason: "manifest_unreadable", set_dir: setDir, err: error });
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
const manifest = parseSetManifest(raw);
|
|
358
|
+
if (manifest === null || manifest.set !== basename2(setDir)) {
|
|
359
|
+
logger.debug("version set rejected", {
|
|
360
|
+
decision: "invalid_set",
|
|
361
|
+
reason: manifest === null ? "manifest_invalid" : "manifest_set_mismatch",
|
|
362
|
+
set_dir: setDir
|
|
363
|
+
});
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
return manifest;
|
|
367
|
+
}
|
|
368
|
+
function inspectInstall(home, logger = noopLogger) {
|
|
369
|
+
const state = inspectInstallState(home, logger);
|
|
370
|
+
logger.debug("install inspected", {
|
|
371
|
+
decision: state.kind,
|
|
372
|
+
...state.kind === "partial" ? { reason: state.reason } : {},
|
|
373
|
+
...state.kind === "installed" ? { set: state.manifest.set, version: state.manifest.wrapper.version } : {}
|
|
374
|
+
});
|
|
375
|
+
return state;
|
|
376
|
+
}
|
|
377
|
+
function inspectInstallState(home, logger) {
|
|
378
|
+
const layout = homeLayout(home);
|
|
379
|
+
let linkTarget = null;
|
|
380
|
+
let currentReason = null;
|
|
381
|
+
try {
|
|
382
|
+
linkTarget = readlinkSync(layout.currentPath);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
const code = error.code;
|
|
385
|
+
if (code === "EINVAL") {
|
|
386
|
+
currentReason = `current is not a symbolic link (${layout.currentPath})`;
|
|
387
|
+
} else if (code !== void 0 && code !== "ENOENT") {
|
|
388
|
+
currentReason = `current is not accessible (${code})`;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const currentExists = linkTarget !== null || currentReason !== null;
|
|
392
|
+
const shimExists = existsSync(layout.binPath);
|
|
393
|
+
if (!currentExists && !shimExists) return { kind: "missing" };
|
|
394
|
+
const setDir = linkTarget !== null ? isAbsolute(linkTarget) ? linkTarget : join3(home, linkTarget) : null;
|
|
395
|
+
const manifest = setDir !== null ? readSetManifest(setDir, logger) : null;
|
|
396
|
+
if (manifest !== null) {
|
|
397
|
+
let shimReason = null;
|
|
398
|
+
if (!shimExists) {
|
|
399
|
+
shimReason = `shim ${layout.binPath} is missing`;
|
|
400
|
+
} else if (!isExecutable(layout.binPath)) {
|
|
401
|
+
shimReason = `shim ${layout.binPath} is not executable`;
|
|
402
|
+
}
|
|
403
|
+
if (shimReason === null) return { kind: "installed", setDir, manifest };
|
|
404
|
+
return { kind: "partial", reason: shimReason };
|
|
405
|
+
}
|
|
406
|
+
const reason = currentReason ?? (linkTarget === null ? `current is missing (${layout.currentPath})` : `current does not resolve to a valid version set (${setDir ?? layout.currentPath})`);
|
|
407
|
+
return { kind: "partial", reason };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// src/loader/install.ts
|
|
411
|
+
function readDistManifest(distDir) {
|
|
412
|
+
let raw;
|
|
413
|
+
try {
|
|
414
|
+
raw = readFileSync2(join4(distDir, "files.json"), "utf8");
|
|
415
|
+
} catch (error) {
|
|
416
|
+
const code = error.code ?? String(error);
|
|
417
|
+
throw new LoaderError(`dist/files.json is missing or corrupt (${code}) \u2014 run pnpm build`);
|
|
418
|
+
}
|
|
419
|
+
let parsed;
|
|
420
|
+
try {
|
|
421
|
+
parsed = JSON.parse(raw);
|
|
422
|
+
} catch {
|
|
423
|
+
throw new LoaderError("dist/files.json is missing or corrupt (not JSON) \u2014 run pnpm build");
|
|
424
|
+
}
|
|
425
|
+
if (!Array.isArray(parsed) || parsed.some(
|
|
426
|
+
(entry) => typeof entry !== "string" || entry === "" || entry.startsWith("/") || entry.split("/").includes("..")
|
|
427
|
+
)) {
|
|
428
|
+
throw new LoaderError("dist/files.json is missing or corrupt (expected an array of non-empty relative paths) \u2014 run pnpm build");
|
|
429
|
+
}
|
|
430
|
+
return parsed;
|
|
431
|
+
}
|
|
432
|
+
function randomSuffix() {
|
|
433
|
+
return randomBytes(8).toString("hex");
|
|
434
|
+
}
|
|
435
|
+
function isRenameCollision(error) {
|
|
436
|
+
const code = error.code;
|
|
437
|
+
return code === "EEXIST" || code === "ENOTEMPTY";
|
|
438
|
+
}
|
|
439
|
+
function bootstrapInstall(home, distDir, files, manifest, opts = {}) {
|
|
440
|
+
const logger = opts.logger ?? noopLogger;
|
|
441
|
+
const startedAt = Date.now();
|
|
442
|
+
const layout = homeLayout(home);
|
|
443
|
+
mkdirSync(layout.versionsDir, { recursive: true });
|
|
444
|
+
mkdirSync(layout.binDir, { recursive: true });
|
|
445
|
+
const target = join4(layout.versionsDir, manifest.set);
|
|
446
|
+
const targetExists = existsSync2(target);
|
|
447
|
+
const targetValid = targetExists && readSetManifest(target, logger) !== null;
|
|
448
|
+
if (targetValid && opts.force !== true) {
|
|
449
|
+
logger.debug("version set reused", { decision: "reuse_set", reason: "valid_set_present", set: manifest.set, set_dir: target });
|
|
450
|
+
} else {
|
|
451
|
+
const from = !targetExists ? "absent" : targetValid ? "valid" : "invalid";
|
|
452
|
+
try {
|
|
453
|
+
buildSetDir(layout.versionsDir, target, distDir, files, manifest, logger);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
if (!isRenameCollision(error)) throw error;
|
|
456
|
+
const winnerValid = existsSync2(target) && readSetManifest(target, logger) !== null;
|
|
457
|
+
logger.warn("version set rename collision", {
|
|
458
|
+
operation: "build_set",
|
|
459
|
+
reason: "rename_collision",
|
|
460
|
+
decision: winnerValid ? "keep_winner" : "rebuild_once",
|
|
461
|
+
set: manifest.set,
|
|
462
|
+
attempt: 1,
|
|
463
|
+
err: error
|
|
464
|
+
});
|
|
465
|
+
if (!winnerValid) {
|
|
466
|
+
buildSetDir(layout.versionsDir, target, distDir, files, manifest, logger);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
logger.info("version set installed", {
|
|
470
|
+
operation: "bootstrap_install",
|
|
471
|
+
from,
|
|
472
|
+
to: "installed",
|
|
473
|
+
reason: opts.force === true ? "repair" : "bootstrap",
|
|
474
|
+
set: manifest.set,
|
|
475
|
+
files_count: files.length,
|
|
476
|
+
duration_ms: Date.now() - startedAt
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
const tmpLink = join4(layout.versionsDir, `.tmp-link-${randomSuffix()}`);
|
|
480
|
+
symlinkSync(join4("versions", manifest.set), tmpLink);
|
|
481
|
+
renameSync(tmpLink, layout.currentPath);
|
|
482
|
+
if (!existsSync2(layout.binPath)) {
|
|
483
|
+
const tmpShim = join4(layout.binDir, `.tmp-shim-${randomSuffix()}`);
|
|
484
|
+
writeFileSync(tmpShim, renderShim(process.execPath, home));
|
|
485
|
+
chmodSync(tmpShim, 493);
|
|
486
|
+
renameSync(tmpShim, layout.binPath);
|
|
487
|
+
logger.info("shim created", { operation: "bootstrap_install", from: "absent", to: "installed", path: layout.binPath });
|
|
488
|
+
} else {
|
|
489
|
+
logger.debug("shim kept", { decision: "keep_shim", reason: "shim_present", path: layout.binPath });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function buildSetDir(versionsDir, target, distDir, files, manifest, logger) {
|
|
493
|
+
if (existsSync2(target)) {
|
|
494
|
+
const bad = join4(versionsDir, `.tmp-bad-${randomSuffix()}`);
|
|
495
|
+
try {
|
|
496
|
+
renameSync(target, bad);
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (error.code !== "ENOENT") throw error;
|
|
499
|
+
logger.debug("invalid set already moved", { decision: "build_own_set", reason: "competitor_moved_target", set_dir: target, err: error });
|
|
500
|
+
}
|
|
501
|
+
rmSync(bad, { recursive: true, force: true });
|
|
502
|
+
}
|
|
503
|
+
const tmp = join4(versionsDir, `.tmp-${randomSuffix()}`);
|
|
504
|
+
try {
|
|
505
|
+
mkdirSync(tmp, { recursive: true });
|
|
506
|
+
for (const file of files) {
|
|
507
|
+
const destination = join4(tmp, file);
|
|
508
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
509
|
+
try {
|
|
510
|
+
copyFileSync(join4(distDir, file), destination);
|
|
511
|
+
} catch (error) {
|
|
512
|
+
throw new LoaderError(`${destination}: ${describeError(error)}`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
writeFileSync(join4(tmp, "set.json"), `${JSON.stringify(manifest, null, 2)}
|
|
517
|
+
`);
|
|
518
|
+
} catch (error) {
|
|
519
|
+
throw new LoaderError(`${join4(tmp, "set.json")}: ${describeError(error)}`);
|
|
520
|
+
}
|
|
521
|
+
renameSync(tmp, target);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/loader/run.ts
|
|
529
|
+
function ownPackage(distDir) {
|
|
530
|
+
const raw = readFileSync3(join5(distDir, "..", "package.json"), "utf8");
|
|
531
|
+
const parsed = JSON.parse(raw);
|
|
532
|
+
if (typeof parsed.name !== "string" || typeof parsed.version !== "string") {
|
|
533
|
+
throw new LoaderError("package.json lacks name or version");
|
|
534
|
+
}
|
|
535
|
+
return { name: parsed.name, version: parsed.version };
|
|
536
|
+
}
|
|
537
|
+
function ensureInstalled(home, distDir, files, own, logger) {
|
|
538
|
+
const layout = homeLayout(home);
|
|
539
|
+
const state = inspectInstall(home, logger);
|
|
540
|
+
if (state.kind === "installed") {
|
|
541
|
+
logger.debug("bootstrap skipped", { decision: "skip_bootstrap", reason: "already_installed", set: state.manifest.set });
|
|
542
|
+
return { kind: "ok", state };
|
|
543
|
+
}
|
|
544
|
+
const manifest = {
|
|
545
|
+
set: setDirName(own.version),
|
|
546
|
+
wrapper: { name: own.name, version: own.version },
|
|
547
|
+
components: []
|
|
548
|
+
};
|
|
549
|
+
const from = state.kind;
|
|
550
|
+
try {
|
|
551
|
+
bootstrapInstall(home, distDir, files, manifest, { logger });
|
|
552
|
+
} catch (error) {
|
|
553
|
+
process.stderr.write(`compivia: install failed: ${describeError(error)}
|
|
554
|
+
`);
|
|
555
|
+
process.exitCode = 1;
|
|
556
|
+
logger.error("install failed", { operation: "bootstrap_install", reason: "fs_failure", from, set: manifest.set, err: error });
|
|
557
|
+
return { kind: "fatal" };
|
|
558
|
+
}
|
|
559
|
+
const verified = inspectInstall(home, logger);
|
|
560
|
+
if (verified.kind !== "installed") {
|
|
561
|
+
const reason = verified.kind === "partial" ? verified.reason : home;
|
|
562
|
+
const hint = verified.kind === "partial" && verified.reason.includes("shim") ? "; run compivia doctor --fix" : "";
|
|
563
|
+
process.stderr.write(`compivia: install failed: ${reason}${hint}
|
|
564
|
+
`);
|
|
565
|
+
process.exitCode = 1;
|
|
566
|
+
logger.error("install verification failed", {
|
|
567
|
+
operation: "bootstrap_install",
|
|
568
|
+
reason: verified.kind === "partial" ? verified.reason : "state_not_installed",
|
|
569
|
+
from,
|
|
570
|
+
to: verified.kind,
|
|
571
|
+
set: manifest.set
|
|
572
|
+
});
|
|
573
|
+
return { kind: "fatal" };
|
|
574
|
+
}
|
|
575
|
+
logger.info("installation bootstrapped", { operation: "bootstrap_install", from, to: "installed", set: manifest.set, version: own.version });
|
|
576
|
+
printPostInstallHints(layout, logger);
|
|
577
|
+
return { kind: "ok", state: verified };
|
|
578
|
+
}
|
|
579
|
+
function printPostInstallHints(layout, logger) {
|
|
580
|
+
if (!pathContains(process.env.PATH, layout.binDir)) {
|
|
581
|
+
process.stderr.write(
|
|
582
|
+
`compivia: ${layout.binDir} is not on PATH; run:${pathHintCommand(process.env.SHELL, layout.binDir)}
|
|
583
|
+
`
|
|
584
|
+
);
|
|
585
|
+
logger.debug("path hint printed", { decision: "print_path_hint", reason: "bin_dir_not_on_path", path: layout.binDir });
|
|
586
|
+
} else {
|
|
587
|
+
logger.debug("path hint skipped", { decision: "skip_path_hint", reason: "bin_dir_on_path", path: layout.binDir });
|
|
588
|
+
}
|
|
589
|
+
const spacedHint = spacedNodeHint(process.execPath, layout.binPath);
|
|
590
|
+
if (spacedHint !== null) {
|
|
591
|
+
process.stderr.write(spacedHint);
|
|
592
|
+
logger.debug("spaced node hint printed", { decision: "print_spaced_node_hint", reason: "node_path_has_whitespace" });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
async function runLoader(options = {}) {
|
|
596
|
+
const logger = options.logger ?? createWrapperLogger();
|
|
597
|
+
const distDir = dirname2(fileURLToPath(new URL("./files.json", import.meta.url)));
|
|
598
|
+
let own;
|
|
599
|
+
let files;
|
|
600
|
+
try {
|
|
601
|
+
files = readDistManifest(distDir);
|
|
602
|
+
own = ownPackage(distDir);
|
|
603
|
+
} catch (error) {
|
|
604
|
+
if (!(error instanceof LoaderError)) throw error;
|
|
605
|
+
fail(error, "dist_manifest_invalid", logger);
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
let home;
|
|
609
|
+
try {
|
|
610
|
+
home = resolveCompiviaHome(process.env, logger);
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (!(error instanceof LoaderError)) throw error;
|
|
613
|
+
fail(error, "home_unresolved", logger);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
logger.debug("loader started", { operation: "run_loader", version: own.version, files_count: files.length, path: home });
|
|
617
|
+
const ensured = ensureInstalled(home, distDir, files, own, logger);
|
|
618
|
+
if (ensured.kind === "fatal") return;
|
|
619
|
+
await delegate(ensured.state, { home, distDir, files, own }, logger);
|
|
620
|
+
}
|
|
621
|
+
async function delegate(installed, context, logger) {
|
|
622
|
+
const bundlePath = join5(installed.setDir, "compivia.mjs");
|
|
623
|
+
const delegation = { operation: "delegate", target: bundlePath, version: installed.manifest.wrapper.version };
|
|
624
|
+
const startedAt = Date.now();
|
|
625
|
+
logger.debug("delegating to installed bundle", { ...delegation, decision: "delegate", reason: "installation_valid" });
|
|
626
|
+
try {
|
|
627
|
+
await import(pathToFileURL(bundlePath).href);
|
|
628
|
+
logger.info("delegation completed", { ...delegation, duration_ms: Date.now() - startedAt });
|
|
629
|
+
return;
|
|
630
|
+
} catch (error) {
|
|
631
|
+
if (installed.manifest.wrapper.version !== context.own.version) {
|
|
632
|
+
process.stderr.write(
|
|
633
|
+
`compivia: failed to load ${bundlePath}: ${describeError(error)}; installed version ${installed.manifest.wrapper.version}, loader version ${context.own.version}; there is no automatic update (compivia update is not installed yet) \u2014 remove ${installed.setDir} and ${homeLayout(context.home).currentPath} and retry
|
|
634
|
+
`
|
|
635
|
+
);
|
|
636
|
+
process.exitCode = 1;
|
|
637
|
+
logger.error("delegation failed", {
|
|
638
|
+
...delegation,
|
|
639
|
+
reason: "foreign_set_not_upgraded",
|
|
640
|
+
loader_version: context.own.version,
|
|
641
|
+
duration_ms: Date.now() - startedAt,
|
|
642
|
+
err: error
|
|
643
|
+
});
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
logger.warn("bundle import failed, repairing set", {
|
|
647
|
+
...delegation,
|
|
648
|
+
reason: "bundle_import_failed",
|
|
649
|
+
decision: "repair_set",
|
|
650
|
+
attempt: 1,
|
|
651
|
+
err: error
|
|
652
|
+
});
|
|
653
|
+
try {
|
|
654
|
+
bootstrapInstall(context.home, context.distDir, context.files, installed.manifest, { force: true, logger });
|
|
655
|
+
} catch (repairError) {
|
|
656
|
+
process.stderr.write(`compivia: repair of set ${installed.setDir} failed: ${describeError(repairError)}
|
|
657
|
+
`);
|
|
658
|
+
process.exitCode = 1;
|
|
659
|
+
logger.error("set repair failed", { ...delegation, reason: "repair_failed", attempt: 1, err: repairError });
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
await import(`${pathToFileURL(bundlePath).href}?retry=1`);
|
|
664
|
+
logger.info("delegation completed after repair", { ...delegation, from: "corrupt", to: "installed", attempt: 1, duration_ms: Date.now() - startedAt });
|
|
665
|
+
} catch (retryError) {
|
|
666
|
+
process.stderr.write(`compivia: repair of set ${installed.setDir} failed: ${describeError(retryError)}
|
|
667
|
+
`);
|
|
668
|
+
process.exitCode = 1;
|
|
669
|
+
logger.error("delegation failed after repair", { ...delegation, reason: "retry_failed", attempt: 1, duration_ms: Date.now() - startedAt, err: retryError });
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function fail(error, reason, logger) {
|
|
674
|
+
process.stderr.write(`compivia: ${describeError(error)}
|
|
675
|
+
`);
|
|
676
|
+
process.exitCode = 1;
|
|
677
|
+
logger.warn("loader refused", { operation: "run_loader", reason, decision: "refuse", err: error });
|
|
678
|
+
}
|
|
679
|
+
export {
|
|
680
|
+
runLoader
|
|
681
|
+
};
|