@tiens.nguyen/gu-cli 1.0.853 → 1.0.855
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/budget-view.mjs +5 -2
- package/cli-token.mjs +15 -2
- package/client-expert-run.mjs +69 -1
- package/gu-repl.mjs +5 -4
- package/gu_browser.py +3 -1
- package/mongo-windows.mjs +246 -0
- package/package.json +2 -1
package/budget-view.mjs
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
export const BUDGET_TIMEOUT_MS = 15_000;
|
|
10
10
|
|
|
11
|
+
/** A web URL for a page under `base` — a URL, so never path.join (that eats the "//"; #205). */
|
|
12
|
+
const pageUrl = (base, path) => new URL(path, `${base}/`).href;
|
|
13
|
+
|
|
11
14
|
/** -> { kind: "not_logged_in" | "relogin" | "http" | "offline" | "ok", status?, body? } */
|
|
12
15
|
export async function fetchProvidersBudget({ apiBase, workerKey, fetchImpl = fetch, timeoutMs = BUDGET_TIMEOUT_MS }) {
|
|
13
16
|
if (!String(workerKey ?? "").trim() || !String(apiBase ?? "").trim()) return { kind: "not_logged_in" };
|
|
@@ -66,7 +69,7 @@ export function budgetTable(rows, now = new Date()) {
|
|
|
66
69
|
*/
|
|
67
70
|
export function budgetLines(result, { site, now = new Date() } = {}) {
|
|
68
71
|
const base = String(site || "https://gu.getmarsic.cc").replace(/\/+$/, "");
|
|
69
|
-
const providersUrl =
|
|
72
|
+
const providersUrl = pageUrl(base, "providers");
|
|
70
73
|
switch (result?.kind) {
|
|
71
74
|
case "not_logged_in":
|
|
72
75
|
return { tone: "warn", lines: ["You are not logged in — run `gu login` first, then /budget again."] };
|
|
@@ -85,7 +88,7 @@ export function budgetLines(result, { site, now = new Date() } = {}) {
|
|
|
85
88
|
}
|
|
86
89
|
const b = result.body;
|
|
87
90
|
if (b.state === "not_pro") {
|
|
88
|
-
return { tone: "warn", lines: ["Provider budgets in the terminal need the Pro plan.", `Upgrade: ${base}
|
|
91
|
+
return { tone: "warn", lines: ["Provider budgets in the terminal need the Pro plan.", `Upgrade: ${pageUrl(base, "pricing")}`] };
|
|
89
92
|
}
|
|
90
93
|
if (b.state === "no_email") {
|
|
91
94
|
return { tone: "warn", lines: ["gu does not know this account's email, so it cannot find your budget items — run `gu login` again."] };
|
package/cli-token.mjs
CHANGED
|
@@ -273,6 +273,8 @@ export async function promptForToken({
|
|
|
273
273
|
// #315: WHY the question is asked when a token exists but is no longer entitled (the computer's
|
|
274
274
|
// free time is used up, the trial ended…) — replaces the "needs a token" title, adds the way on.
|
|
275
275
|
why = "",
|
|
276
|
+
// #209: the block is the computer LIMIT (not a missing/expired plan) — a Pro token is not the way out.
|
|
277
|
+
overLimit = false,
|
|
276
278
|
// #315: a saved token must also be ENTITLED on this computer. `accept(token)` → { ok } | { ok:false, reason }
|
|
277
279
|
// — the REPL renews it from this computer (to learn its free time) and runs the licence rule.
|
|
278
280
|
accept = null,
|
|
@@ -303,13 +305,19 @@ export async function promptForToken({
|
|
|
303
305
|
];
|
|
304
306
|
if (why) {
|
|
305
307
|
const pricingUrl = `${String(site).replace(/^https?:\/\//, "")}/pricing`;
|
|
306
|
-
hint =
|
|
308
|
+
hint = overLimit
|
|
309
|
+
? [
|
|
310
|
+
`Remove the computers you no longer use at ${accountUrl}, then start gu again — or Pro allows more computers: ${pricingUrl}`,
|
|
311
|
+
`Think this is wrong? ${SUPPORT_EMAIL}`,
|
|
312
|
+
required ? "/exit or Ctrl+C quits gu." : "Enter to skip for now.",
|
|
313
|
+
]
|
|
314
|
+
: [
|
|
307
315
|
// The reason (the title) already says what happened; a "trial ended on <date>" line beside it is
|
|
308
316
|
// noise — and wrong for a computer that went straight to a free account and never had one.
|
|
309
317
|
...hint.filter((l) => !/^For a free token|^Paste it here|^The free trial on this computer ended/.test(l)),
|
|
310
318
|
`Get Pro at ${pricingUrl} · Think this is wrong? ${SUPPORT_EMAIL}`,
|
|
311
319
|
...(trialOk ? [] : ["Paste a Pro token here, then Enter."]),
|
|
312
|
-
|
|
320
|
+
];
|
|
313
321
|
}
|
|
314
322
|
};
|
|
315
323
|
await offer();
|
|
@@ -525,6 +533,10 @@ export function barNotice({ token, publicKeyB64, mode, now = new Date(), attempt
|
|
|
525
533
|
const shared = Number.isInteger(p.freeAccounts) && p.freeAccounts > 1;
|
|
526
534
|
if (left === 0) return { kind: "free-used", urgent: true, text: `free time on this computer is used up · Pro at ${pricingUrl}` };
|
|
527
535
|
const days = `${left} day${left === 1 ? "" : "s"}`;
|
|
536
|
+
// #209: over the computer limit the account is blocked — "N days left" would contradict that.
|
|
537
|
+
if (Number.isInteger(p.activeDevices) && p.activeDevices > p.deviceLimit) {
|
|
538
|
+
return { kind: "over-limit", urgent: true, text: `${planName(p.plan)}: ${computers(p.deviceLimit)} · used on ${p.activeDevices} this month · remove some at ${accountUrl}` };
|
|
539
|
+
}
|
|
528
540
|
return shared
|
|
529
541
|
? { kind: "free-shared", urgent: true, text: `More than one free account on this computer · they share ${days} of free time · Pro at ${pricingUrl}` }
|
|
530
542
|
: { kind: "free", urgent: left <= 14, text: `free · ${days} left on this computer · Pro at ${pricingUrl}` };
|
|
@@ -741,6 +753,7 @@ export function enforcementDecision({ token, publicKeyB64, now = new Date(), sit
|
|
|
741
753
|
return {
|
|
742
754
|
enforced: true,
|
|
743
755
|
allowed: false,
|
|
756
|
+
reason: "over-limit",
|
|
744
757
|
why:
|
|
745
758
|
`This account has used gu on ${computers(p.activeDevices)} in the last 30 days, and the ` +
|
|
746
759
|
`${planName(p.plan)} allows ${p.deviceLimit}. Sign out of one, or remove it at ${accountUrl}.`,
|
package/client-expert-run.mjs
CHANGED
|
@@ -21,6 +21,7 @@ import { join } from "node:path";
|
|
|
21
21
|
import { promisify } from "node:util";
|
|
22
22
|
import { createHash } from "node:crypto";
|
|
23
23
|
import { localModeNodeProblem } from "./node-version.mjs";
|
|
24
|
+
import { downloadMongodExe, startPortableMongod, portableMongoInstalled, mongoWinPaths, mongodCommandLine, MONGO_WIN_VERSION } from "./mongo-windows.mjs";
|
|
24
25
|
import {
|
|
25
26
|
apiDepsInstalled,
|
|
26
27
|
installApiDeps,
|
|
@@ -222,7 +223,11 @@ export async function probeMongo() {
|
|
|
222
223
|
if (svc && /STATE\s*:\s*4\s+RUNNING/i.test(svc)) {
|
|
223
224
|
return { running: true, how: "MongoDB service" };
|
|
224
225
|
}
|
|
225
|
-
|
|
226
|
+
const serviceInstalled = Boolean(svc && /SERVICE_NAME/i.test(svc));
|
|
227
|
+
// gu's own small mongod.exe (no MSI, no service — mongo-windows.mjs, #210). A machine that
|
|
228
|
+
// has the old MSI service keeps using it; `portable` says which of the two to start.
|
|
229
|
+
const portable = !serviceInstalled && (await portableMongoInstalled());
|
|
230
|
+
return { running: false, how: null, installed: serviceInstalled || portable, portable };
|
|
226
231
|
}
|
|
227
232
|
|
|
228
233
|
// platform-ok: unreachable on Windows — the win32 branch above returns before this line.
|
|
@@ -401,6 +406,62 @@ export function runInTerminal(cmd, { platform = process.platform, spawnFn = spaw
|
|
|
401
406
|
});
|
|
402
407
|
}
|
|
403
408
|
|
|
409
|
+
/**
|
|
410
|
+
* Windows 11 without the installer (#210): download ONLY mongod.exe (~50 MB of a ~940 MB zip) into
|
|
411
|
+
* ~/.gonext/mongodb and run it from there on 127.0.0.1 — no MSI, no Windows service, no
|
|
412
|
+
* administrator prompt. Shown, asked, then done, like the other platforms. If the download fails
|
|
413
|
+
* the winget commands are printed as the way out.
|
|
414
|
+
*/
|
|
415
|
+
export async function ensureNativeMongoWindows(ask, mongo, { log = (l) => console.log(l), plan = null, waitFor = null, download = downloadMongodExe, start = startPortableMongod } = {}) {
|
|
416
|
+
const installing = !mongo.installed;
|
|
417
|
+
const paths = mongoWinPaths();
|
|
418
|
+
const { host, port } = mongoHostPort(LOCAL_MONGO_URI);
|
|
419
|
+
if (installing) {
|
|
420
|
+
log(dim("\n It is not installed here. gu runs its own small MongoDB — no installer, no service, no administrator prompt:\n"));
|
|
421
|
+
log(` download mongod.exe ${MONGO_WIN_VERSION} (about 50 MB) into ${paths.dir}`);
|
|
422
|
+
} else {
|
|
423
|
+
log(dim("\n gu's MongoDB is installed but not running. This starts it:\n"));
|
|
424
|
+
}
|
|
425
|
+
log(" " + mongodCommandLine({ port, paths }));
|
|
426
|
+
log("");
|
|
427
|
+
const yes = await readYesNo(ask, ` ${installing ? "Install" : "Start"} MongoDB now? [Y/n]: `, true, log);
|
|
428
|
+
if (!yes) {
|
|
429
|
+
log(dim(`\n Not ${installing ? "installed" : "started"} — run the commands above yourself.`));
|
|
430
|
+
return { ok: false, explained: true };
|
|
431
|
+
}
|
|
432
|
+
log("\n " + bold(installing ? "Installing MongoDB" : "Starting MongoDB") + dim(installing ? " about 50 MB" : ""));
|
|
433
|
+
if (installing) {
|
|
434
|
+
try {
|
|
435
|
+
await download({ paths, log });
|
|
436
|
+
} catch (e) {
|
|
437
|
+
log("\n " + red("✗ ") + `could not download mongod.exe: ${e?.message ?? e}`);
|
|
438
|
+
if (plan?.commands?.length) {
|
|
439
|
+
log(dim(" The full installer instead (large, asks for administrator permission):"));
|
|
440
|
+
for (const c of plan.commands) log(" " + c);
|
|
441
|
+
}
|
|
442
|
+
return { ok: false, explained: true };
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
let started;
|
|
446
|
+
try {
|
|
447
|
+
started = await start({ port, paths });
|
|
448
|
+
} catch (e) {
|
|
449
|
+
started = { ok: false, error: e };
|
|
450
|
+
}
|
|
451
|
+
if (!started?.ok) {
|
|
452
|
+
log("\n " + red("✗ ") + `mongod.exe could not be started${started?.error ? `: ${started.error.message ?? started.error}` : ""}`);
|
|
453
|
+
return { ok: false, explained: true };
|
|
454
|
+
}
|
|
455
|
+
const wait = waitFor ?? (await import("./mongo-native.mjs")).waitForMongo;
|
|
456
|
+
if (!(await wait(host, port, { timeoutMs: 60000 }))) {
|
|
457
|
+
log("\n " + red("✗ ") + `MongoDB was ${installing ? "installed" : "started"} but is not answering at ${host}:${port} yet.`);
|
|
458
|
+
log(dim(` Its log: ${paths.log} — then run gu again.`));
|
|
459
|
+
return { ok: false, explained: true };
|
|
460
|
+
}
|
|
461
|
+
log(" " + cyan("✓ MongoDB is running") + dim(` at ${host}:${port} (started by gu — data in ${paths.data})`));
|
|
462
|
+
return { ok: true, explained: true };
|
|
463
|
+
}
|
|
464
|
+
|
|
404
465
|
/**
|
|
405
466
|
* Make a native MongoDB answer on this machine — SHOW the commands, ASK, then run them (#329).
|
|
406
467
|
* → { ok, explained }. macOS goes through Homebrew (ensureNativeMongoMac); Ubuntu through
|
|
@@ -421,6 +482,8 @@ export async function ensureNativeMongo(ask, mongo, {
|
|
|
421
482
|
runCmd = runInTerminal,
|
|
422
483
|
waitFor = null,
|
|
423
484
|
ensureMac = ensureNativeMongoMac,
|
|
485
|
+
winDownload = downloadMongodExe,
|
|
486
|
+
winStart = startPortableMongod,
|
|
424
487
|
} = {}) {
|
|
425
488
|
if (platform === "darwin") return ensureMac(ask, mongo, { log });
|
|
426
489
|
if (mongo.silentPort) {
|
|
@@ -433,6 +496,11 @@ export async function ensureNativeMongo(ask, mongo, {
|
|
|
433
496
|
}
|
|
434
497
|
const plan = mongoInstallPlan(platform, { os, isRoot });
|
|
435
498
|
if (!plan) return { ok: false, explained: false };
|
|
499
|
+
// WINDOWS: gu's own mongod.exe, not the 966 MB MSI (#210). An old MSI service still starts with
|
|
500
|
+
// `net start MongoDB` below.
|
|
501
|
+
if (platform === "win32" && (!mongo.installed || mongo.portable)) {
|
|
502
|
+
return ensureNativeMongoWindows(ask, mongo, { log, plan, waitFor, download: winDownload, start: winStart });
|
|
503
|
+
}
|
|
436
504
|
const installing = !mongo.installed;
|
|
437
505
|
const commands = installing ? plan.commands : [plan.start];
|
|
438
506
|
if (!commands.length) {
|
package/gu-repl.mjs
CHANGED
|
@@ -11746,11 +11746,11 @@ async function ensureTokenForTurn() {
|
|
|
11746
11746
|
* (Esc does nothing), one Backspace clears the default for a paste, and a valid token turns the
|
|
11747
11747
|
* row back into ">> ". → true once a token is saved.
|
|
11748
11748
|
*/
|
|
11749
|
-
async function askForCliToken(ct, dir, { why = "" } = {}) {
|
|
11749
|
+
async function askForCliToken(ct, dir, { why = "", overLimit = false } = {}) {
|
|
11750
11750
|
console.log("");
|
|
11751
11751
|
tokenPromptActive = true; // Ctrl+C now quits gu (see onInterrupt) — task #17
|
|
11752
11752
|
try {
|
|
11753
|
-
return await askForCliTokenInner(ct, dir, why);
|
|
11753
|
+
return await askForCliTokenInner(ct, dir, why, overLimit);
|
|
11754
11754
|
} finally {
|
|
11755
11755
|
tokenPromptActive = false;
|
|
11756
11756
|
}
|
|
@@ -11770,7 +11770,7 @@ function quitFromTokenPrompt() {
|
|
|
11770
11770
|
process.exit(0);
|
|
11771
11771
|
}
|
|
11772
11772
|
|
|
11773
|
-
async function askForCliTokenInner(ct, dir, why) {
|
|
11773
|
+
async function askForCliTokenInner(ct, dir, why, overLimit = false) {
|
|
11774
11774
|
const hostedBase = await tokenHostedBase();
|
|
11775
11775
|
const pk = ct.publicKey();
|
|
11776
11776
|
const site = ct.siteUrl();
|
|
@@ -11781,6 +11781,7 @@ async function askForCliTokenInner(ct, dir, why) {
|
|
|
11781
11781
|
required: true,
|
|
11782
11782
|
hostedBase,
|
|
11783
11783
|
why,
|
|
11784
|
+
overLimit, // #209: the computer limit, not a missing plan — no "paste a Pro token"
|
|
11784
11785
|
// #315: a token is only good if THIS computer may use it — renew it from here (the server then
|
|
11785
11786
|
// says how much free time the computer has), save what came back, and run the licence rule.
|
|
11786
11787
|
accept: async (token) => {
|
|
@@ -11858,7 +11859,7 @@ async function askTokenAtStart() {
|
|
|
11858
11859
|
return;
|
|
11859
11860
|
}
|
|
11860
11861
|
}
|
|
11861
|
-
await askForCliToken(ct, dir, { why: d.why });
|
|
11862
|
+
await askForCliToken(ct, dir, { why: d.why, overLimit: d.reason === "over-limit" });
|
|
11862
11863
|
}
|
|
11863
11864
|
/** The token refresh started at launch — askTokenAtStart waits for it (see there). */
|
|
11864
11865
|
let startupTokenRefresh = null;
|
package/gu_browser.py
CHANGED
|
@@ -164,8 +164,10 @@ def install_text(reason="not connected"):
|
|
|
164
164
|
"missing or broken Chrome: do NOT install, reinstall, move or delete any browser. STOP "
|
|
165
165
|
"and tell the user, with that error: update gu (npm install -g @tiens.nguyen/gu-cli@latest), "
|
|
166
166
|
"restart it, and ask again; the bridge's log is ~/.gonext/browser-bridge.log.")
|
|
167
|
-
|
|
167
|
+
no_chrome = "no chrome found" in str(reason).lower()
|
|
168
|
+
if last_seen().get("installType") == "normal" and not no_chrome:
|
|
168
169
|
# The Chrome Web Store copy is installed: never point at the developer folder again (#145).
|
|
170
|
+
# Unless there is no Chrome at all — then opening it is not something the user can do.
|
|
169
171
|
return (f"BROWSER NOT AVAILABLE ({reason}): the gu Chrome extension (Chrome Web Store) is "
|
|
170
172
|
"installed but not connected — Chrome is probably closed. STOP and ask the user to "
|
|
171
173
|
"open Chrome (the extension reconnects within 30 seconds, or its icon → Connect now), "
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MONGODB ON WINDOWS WITHOUT THE MSI (task #210).
|
|
3
|
+
*
|
|
4
|
+
* `winget install MongoDB.Server` downloads the ~966 MB installer, needs an administrator prompt
|
|
5
|
+
* and registers a Windows service. gu only needs `mongod.exe` (about 50 MB compressed): the zip
|
|
6
|
+
* on fastdl.mongodb.org is ~989 MB because of debug symbols (mongod.pdb 518 MB, mongos.pdb 357
|
|
7
|
+
* MB). The server answers HTTP Range requests (checked: 206, accept-ranges: bytes), so this
|
|
8
|
+
* module reads the zip's central directory over the wire and downloads ONLY the mongod.exe entry.
|
|
9
|
+
*
|
|
10
|
+
* Everything lives under ~/.gonext/mongodb — no service, no admin, removed by deleting the folder:
|
|
11
|
+
* bin/mongod.exe data/ mongod.log launch.log
|
|
12
|
+
*
|
|
13
|
+
* Pure parts (zip parsing, paths, the command line) are separate from the network and process
|
|
14
|
+
* parts, and both of those take their fetch / spawn as arguments so tests never touch the net.
|
|
15
|
+
*/
|
|
16
|
+
import { mkdir, rename, writeFile, rm, stat } from "node:fs/promises";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { join, dirname } from "node:path";
|
|
19
|
+
import { inflateRawSync } from "node:zlib";
|
|
20
|
+
|
|
21
|
+
// Bump on purpose, like MONGO_WINGET_VERSION: 9.0.4 is what fastdl serves today (winget has 9.0.2).
|
|
22
|
+
export const MONGO_WIN_VERSION = "9.0.4";
|
|
23
|
+
export const MONGO_WIN_ZIP_URL = `https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-${MONGO_WIN_VERSION}.zip`;
|
|
24
|
+
|
|
25
|
+
/** Where gu keeps its own mongod. `home` is injectable for tests. */
|
|
26
|
+
export function mongoWinPaths(home = homedir()) {
|
|
27
|
+
const dir = join(home, ".gonext", "mongodb");
|
|
28
|
+
return {
|
|
29
|
+
dir,
|
|
30
|
+
exe: join(dir, "bin", "mongod.exe"),
|
|
31
|
+
data: join(dir, "data"),
|
|
32
|
+
log: join(dir, "mongod.log"),
|
|
33
|
+
launchLog: join(dir, "launch.log"),
|
|
34
|
+
version: join(dir, "version.txt"),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The mongod command line gu runs — loopback only, so no Windows Firewall prompt. */
|
|
39
|
+
export function mongodArgs({ port = 27017, paths = mongoWinPaths() } = {}) {
|
|
40
|
+
return ["--dbpath", paths.data, "--bind_ip", "127.0.0.1", "--port", String(port), "--logpath", paths.log, "--logappend"];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The same thing as one line a person can paste (shown when we only print instead of run). */
|
|
44
|
+
export function mongodCommandLine({ port = 27017, paths = mongoWinPaths() } = {}) {
|
|
45
|
+
return [`"${paths.exe}"`, ...mongodArgs({ port, paths }).map((a) => (/\s/.test(a) ? `"${a}"` : a))].join(" ");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ------------------------------------------------------------------------------------ zip parsing
|
|
49
|
+
|
|
50
|
+
const u64 = (b, o) => Number(b.readBigUInt64LE(o));
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The end-of-central-directory record, found in the LAST bytes of the file.
|
|
54
|
+
* → { cdOffset, cdSize } or { zip64Offset } when the 64-bit record has to be read too.
|
|
55
|
+
*/
|
|
56
|
+
export function parseZipEnd(tail) {
|
|
57
|
+
for (let i = tail.length - 22; i >= 0; i--) {
|
|
58
|
+
if (tail.readUInt32LE(i) !== 0x06054b50) continue;
|
|
59
|
+
const cdSize = tail.readUInt32LE(i + 12);
|
|
60
|
+
const cdOffset = tail.readUInt32LE(i + 16);
|
|
61
|
+
if (cdSize === 0xffffffff || cdOffset === 0xffffffff) {
|
|
62
|
+
// The zip64 locator sits directly before the EOCD: signature, disk, 8-byte record offset.
|
|
63
|
+
const loc = i - 20;
|
|
64
|
+
if (loc >= 0 && tail.readUInt32LE(loc) === 0x07064b50) return { zip64Offset: u64(tail, loc + 8) };
|
|
65
|
+
throw new Error("zip64 archive without a locator");
|
|
66
|
+
}
|
|
67
|
+
return { cdOffset, cdSize };
|
|
68
|
+
}
|
|
69
|
+
throw new Error("not a zip file (no end-of-directory record)");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A zip64 end record (read from where the locator pointed) → { cdOffset, cdSize }. */
|
|
73
|
+
export function parseZip64End(buf) {
|
|
74
|
+
if (buf.readUInt32LE(0) !== 0x06064b50) throw new Error("bad zip64 end record");
|
|
75
|
+
return { cdSize: u64(buf, 40), cdOffset: u64(buf, 48) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The central directory → [{ name, method, crc, csize, usize, offset }]. */
|
|
79
|
+
export function parseCentralDirectory(buf) {
|
|
80
|
+
const out = [];
|
|
81
|
+
let p = 0;
|
|
82
|
+
while (p + 46 <= buf.length && buf.readUInt32LE(p) === 0x02014b50) {
|
|
83
|
+
const nameLen = buf.readUInt16LE(p + 28);
|
|
84
|
+
const extraLen = buf.readUInt16LE(p + 30);
|
|
85
|
+
const commentLen = buf.readUInt16LE(p + 32);
|
|
86
|
+
const e = {
|
|
87
|
+
name: buf.toString("utf8", p + 46, p + 46 + nameLen),
|
|
88
|
+
method: buf.readUInt16LE(p + 10),
|
|
89
|
+
crc: buf.readUInt32LE(p + 16),
|
|
90
|
+
csize: buf.readUInt32LE(p + 20),
|
|
91
|
+
usize: buf.readUInt32LE(p + 24),
|
|
92
|
+
offset: buf.readUInt32LE(p + 42),
|
|
93
|
+
};
|
|
94
|
+
// A 0xFFFFFFFF field means "see the zip64 extra" — not worth carrying for one 4 GB-limited
|
|
95
|
+
// archive; say so plainly if MongoDB ever ships one that needs it.
|
|
96
|
+
e.zip64 = e.csize === 0xffffffff || e.usize === 0xffffffff || e.offset === 0xffffffff;
|
|
97
|
+
out.push(e);
|
|
98
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The mongod.exe entry (bin/mongod.exe inside the versioned folder), or undefined. */
|
|
104
|
+
export function findMongodEntry(entries) {
|
|
105
|
+
return entries.find((e) => /(^|\/)bin\/mongod\.exe$/i.test(e.name));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A local file header → where its data starts, relative to the header. */
|
|
109
|
+
export function localHeaderDataStart(buf) {
|
|
110
|
+
if (buf.readUInt32LE(0) !== 0x04034b50) throw new Error("bad local file header");
|
|
111
|
+
return 30 + buf.readUInt16LE(26) + buf.readUInt16LE(28);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let CRC_TABLE = null;
|
|
115
|
+
export function crc32(buf) {
|
|
116
|
+
if (!CRC_TABLE) {
|
|
117
|
+
CRC_TABLE = new Uint32Array(256);
|
|
118
|
+
for (let n = 0; n < 256; n++) {
|
|
119
|
+
let c = n;
|
|
120
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
121
|
+
CRC_TABLE[n] = c >>> 0;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
let c = 0xffffffff;
|
|
125
|
+
for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
|
126
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------------------------------- network
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Bytes start..end (inclusive) of `url`. A server that ignores Range answers 200 with the WHOLE
|
|
133
|
+
* file — for a 989 MB zip that must be an error, not a download.
|
|
134
|
+
*/
|
|
135
|
+
export async function fetchRange(url, start, end, { fetchFn = fetch, onProgress = null, attempts = 3 } = {}) {
|
|
136
|
+
let lastErr;
|
|
137
|
+
for (let i = 1; i <= attempts; i++) {
|
|
138
|
+
try {
|
|
139
|
+
const res = await fetchFn(url, { headers: { Range: `bytes=${start}-${end}` } });
|
|
140
|
+
if (res.status !== 206) {
|
|
141
|
+
try { await res.body?.cancel?.(); } catch { /* the body may already be gone */ }
|
|
142
|
+
throw new Error(`the server did not honour a Range request (HTTP ${res.status})`);
|
|
143
|
+
}
|
|
144
|
+
const want = end - start + 1;
|
|
145
|
+
const chunks = [];
|
|
146
|
+
let got = 0;
|
|
147
|
+
const reader = res.body.getReader();
|
|
148
|
+
for (;;) {
|
|
149
|
+
const { done, value } = await reader.read();
|
|
150
|
+
if (done) break;
|
|
151
|
+
chunks.push(value);
|
|
152
|
+
got += value.length;
|
|
153
|
+
onProgress?.(got, want);
|
|
154
|
+
}
|
|
155
|
+
if (got !== want) throw new Error(`short read: got ${got} of ${want} bytes`);
|
|
156
|
+
return Buffer.concat(chunks);
|
|
157
|
+
} catch (e) {
|
|
158
|
+
lastErr = e;
|
|
159
|
+
if (/Range request/.test(String(e?.message))) break; // retrying cannot change that
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
throw lastErr;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function totalSize(url, fetchFn) {
|
|
166
|
+
// bytes=0-0 answers "Content-Range: bytes 0-0/<total>" — no HEAD needed.
|
|
167
|
+
const res = await fetchFn(url, { headers: { Range: "bytes=0-0" } });
|
|
168
|
+
try { await res.body?.cancel?.(); } catch { /* ignore */ }
|
|
169
|
+
const m = /\/(\d+)\s*$/.exec(res.headers.get("content-range") || "");
|
|
170
|
+
if (res.status !== 206 || !m) throw new Error(`the server did not honour a Range request (HTTP ${res.status})`);
|
|
171
|
+
return Number(m[1]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Download just mongod.exe from the zip at `url` into paths.exe. → { bytes, downloaded }.
|
|
176
|
+
* Throws with a plain reason on any failure; nothing half-written is left at paths.exe
|
|
177
|
+
* (it is written beside it and renamed, after the CRC matched).
|
|
178
|
+
*/
|
|
179
|
+
export async function downloadMongodExe({
|
|
180
|
+
url = MONGO_WIN_ZIP_URL,
|
|
181
|
+
paths = mongoWinPaths(),
|
|
182
|
+
fetchFn = fetch,
|
|
183
|
+
log = () => {},
|
|
184
|
+
version = MONGO_WIN_VERSION,
|
|
185
|
+
} = {}) {
|
|
186
|
+
const size = await totalSize(url, fetchFn);
|
|
187
|
+
const tailStart = Math.max(0, size - 65536);
|
|
188
|
+
const tail = await fetchRange(url, tailStart, size - 1, { fetchFn });
|
|
189
|
+
let end = parseZipEnd(tail);
|
|
190
|
+
if (end.zip64Offset !== undefined) end = parseZip64End(await fetchRange(url, end.zip64Offset, end.zip64Offset + 55, { fetchFn }));
|
|
191
|
+
const cd = await fetchRange(url, end.cdOffset, end.cdOffset + end.cdSize - 1, { fetchFn });
|
|
192
|
+
const entry = findMongodEntry(parseCentralDirectory(cd));
|
|
193
|
+
if (!entry) throw new Error("mongod.exe is not in that zip");
|
|
194
|
+
if (entry.zip64) throw new Error("mongod.exe needs zip64 offsets, which gu does not read");
|
|
195
|
+
if (entry.method !== 0 && entry.method !== 8) throw new Error(`unsupported zip compression method ${entry.method}`);
|
|
196
|
+
|
|
197
|
+
const head = await fetchRange(url, entry.offset, entry.offset + 29 + 1024, { fetchFn }).catch(() =>
|
|
198
|
+
fetchRange(url, entry.offset, entry.offset + 29, { fetchFn }));
|
|
199
|
+
const dataStart = entry.offset + localHeaderDataStart(head);
|
|
200
|
+
|
|
201
|
+
const mb = (n) => (n / 1048576).toFixed(0);
|
|
202
|
+
log(` downloading mongod.exe ${MONGO_WIN_VERSION === version ? version : version} — ${mb(entry.csize)} MB (the zip is ${mb(size)} MB; gu takes only this one file)`);
|
|
203
|
+
let lastShown = -1;
|
|
204
|
+
const packed = await fetchRange(url, dataStart, dataStart + entry.csize - 1, {
|
|
205
|
+
fetchFn,
|
|
206
|
+
onProgress: (got, want) => {
|
|
207
|
+
const pct = Math.floor((got / want) * 10) * 10; // every 10%
|
|
208
|
+
if (pct !== lastShown) { lastShown = pct; log(` … ${pct}% (${mb(got)} of ${mb(want)} MB)`); }
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
const exe = entry.method === 8 ? inflateRawSync(packed) : packed;
|
|
212
|
+
if (exe.length !== entry.usize) throw new Error(`unpacked ${exe.length} bytes, expected ${entry.usize}`);
|
|
213
|
+
if (crc32(exe) !== entry.crc) throw new Error("the download is damaged (CRC mismatch) — run gu again");
|
|
214
|
+
if (exe[0] !== 0x4d || exe[1] !== 0x5a) throw new Error("the download is not a Windows program (no MZ header)");
|
|
215
|
+
|
|
216
|
+
await mkdir(dirname(paths.exe), { recursive: true });
|
|
217
|
+
const part = `${paths.exe}.part`;
|
|
218
|
+
await writeFile(part, exe);
|
|
219
|
+
await rm(paths.exe, { force: true });
|
|
220
|
+
await rename(part, paths.exe);
|
|
221
|
+
await writeFile(paths.version, `${version}\n`);
|
|
222
|
+
return { bytes: exe.length, downloaded: packed.length };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ----------------------------------------------------------------------------------------- process
|
|
226
|
+
|
|
227
|
+
/** Is gu's own mongod.exe there? */
|
|
228
|
+
export async function portableMongoInstalled(paths = mongoWinPaths()) {
|
|
229
|
+
try { return (await stat(paths.exe)).isFile(); } catch { return false; }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Start gu's mongod so it OUTLIVES this terminal (and an SSH session — see spawnSurviving).
|
|
234
|
+
* → { ok, pid, how }. `spawnFn` is injectable; the default is platform-tools' spawnSurviving.
|
|
235
|
+
*/
|
|
236
|
+
export async function startPortableMongod({ port = 27017, paths = mongoWinPaths(), spawnFn = null } = {}) {
|
|
237
|
+
await mkdir(paths.data, { recursive: true });
|
|
238
|
+
const spawner = spawnFn ?? (await import("./platform-tools.mjs")).spawnSurviving;
|
|
239
|
+
return spawner({
|
|
240
|
+
cmd: paths.exe,
|
|
241
|
+
args: mongodArgs({ port, paths }),
|
|
242
|
+
cwd: paths.dir,
|
|
243
|
+
logFile: paths.launchLog,
|
|
244
|
+
taskName: "gu-local-mongod",
|
|
245
|
+
});
|
|
246
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tiens.nguyen/gu-cli",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.855",
|
|
4
4
|
"description": "Gu CLI — the gu terminal plus the local worker that runs agent / OCR / PDF / embedding jobs on your Mac (Ollama / MLX / OpenAI-compatible).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -63,6 +63,7 @@
|
|
|
63
63
|
"turn-stop.mjs",
|
|
64
64
|
"workspace-revert.mjs",
|
|
65
65
|
"mongo-native.mjs",
|
|
66
|
+
"mongo-windows.mjs",
|
|
66
67
|
"terminal-hover.mjs",
|
|
67
68
|
"terminal-layout.mjs",
|
|
68
69
|
"terminal-viewport.mjs",
|