@kaynooo/cli-db 0.13.3 → 0.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +82 -41
  2. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
- #!/usr/bin/env -S bun --config=/dev/null
2
- // @bun
1
+ #!/bin/sh
2
+ // @bun 2>/dev/null; exec bun --config=/dev/null "$0" "$@"
3
3
  var __esm = (fn, res, err) => () => {
4
4
  if (fn)
5
5
  try {
@@ -143,11 +143,14 @@ var init_config = __esm(() => {
143
143
  // ../kit/src/user-config.ts
144
144
  import { existsSync as existsSync2, readFileSync } from "fs";
145
145
  import { homedir } from "os";
146
- import { join as join2 } from "path";
146
+ import { isAbsolute, join as join2 } from "path";
147
147
  import process4 from "process";
148
+ function xdgFolder(value, fallback) {
149
+ return value !== undefined && isAbsolute(value) ? value : fallback;
150
+ }
148
151
  function configBase(where = {}) {
149
152
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
150
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
153
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
151
154
  }
152
155
  function userConfigPath(bin, where = {}) {
153
156
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -588,11 +591,20 @@ function wholeNumber(value, name, fallback, min = 1) {
588
591
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
589
592
  return number;
590
593
  }
594
+ function durationMs(text, unit) {
595
+ if (BARE_DURATION.test(text))
596
+ return Number(text) * UNIT_MS[unit];
597
+ if (!DURATION.test(text))
598
+ return 0;
599
+ let ms = 0;
600
+ for (const [, amount, part] of text.matchAll(DURATION_PART))
601
+ ms += Number(amount) * UNIT_MS[part];
602
+ return ms;
603
+ }
591
604
  function duration(value, name, fallback, unit = "s") {
592
605
  if (value === undefined)
593
606
  return fallback;
594
- const match = DURATION.exec(value.trim());
595
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
607
+ const ms = durationMs(value.trim(), unit);
596
608
  if (ms < 1)
597
609
  badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
598
610
  return ms;
@@ -608,12 +620,14 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
608
620
  fail(`no file ${path}`);
609
621
  return file.text();
610
622
  }
611
- var WHOLE, DURATION, UNIT_MS;
623
+ var WHOLE, BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
612
624
  var init_input = __esm(() => {
613
625
  init_args();
614
626
  WHOLE = /^\d+$/;
615
- DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
616
- UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
627
+ BARE_DURATION = /^\d+(?:\.\d+)?$/;
628
+ DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
629
+ DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
630
+ UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
617
631
  });
618
632
 
619
633
  // ../kit/src/args.ts
@@ -902,6 +916,7 @@ init_format();
902
916
  import { constants } from "os";
903
917
  import process12 from "process";
904
918
  var KILL_GRACE_MS = 2000;
919
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
905
920
  function exitCodeOf(code, signal) {
906
921
  if (code !== null)
907
922
  return code;
@@ -952,12 +967,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs,
952
967
  stop();
953
968
  continue;
954
969
  }
970
+ if (state.truncated)
971
+ continue;
972
+ let kept = data;
955
973
  if (state.kept + data.length > maxBytes) {
974
+ let cut = maxBytes - state.kept;
975
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
976
+ cut--;
977
+ kept = data.subarray(0, cut);
956
978
  state.truncated = true;
957
- continue;
958
979
  }
959
- state.kept += data.length;
960
- chunks.push({ stream: name, data });
980
+ state.kept += kept.length;
981
+ if (kept.length > 0)
982
+ chunks.push({ stream: name, data: kept });
961
983
  }
962
984
  };
963
985
  try {
@@ -974,6 +996,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs,
974
996
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
975
997
  let output;
976
998
  let text;
999
+ let stdout;
977
1000
  return {
978
1001
  code: exitCodeOf(proc.exitCode, proc.signalCode),
979
1002
  chunks,
@@ -984,6 +1007,9 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs,
984
1007
  },
985
1008
  get text() {
986
1009
  return text ??= (output ??= joined()).toString();
1010
+ },
1011
+ get stdout() {
1012
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
987
1013
  }
988
1014
  };
989
1015
  }
@@ -1133,14 +1159,16 @@ init_text2();
1133
1159
  // ../kit/src/usage.ts
1134
1160
  import { appendFileSync, mkdirSync } from "fs";
1135
1161
  import { homedir as homedir3 } from "os";
1136
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1162
+ import { dirname as dirname2, join as join4 } from "path";
1137
1163
  import process15 from "process";
1138
1164
 
1139
1165
  // ../kit/src/logs.ts
1166
+ init_user_config();
1140
1167
  var DAY_MS = 24 * 60 * 60 * 1000;
1141
1168
  var CLI_FOLDER = "kaynooo-cli";
1142
1169
 
1143
1170
  // ../kit/src/usage.ts
1171
+ init_user_config();
1144
1172
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1145
1173
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1146
1174
  var LONGEST_NAME = 40;
@@ -1149,8 +1177,7 @@ function noteUsageError(message) {
1149
1177
  usageError = message;
1150
1178
  }
1151
1179
  function stateHome(env = process15.env) {
1152
- const dir = env.XDG_STATE_HOME;
1153
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1180
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
1154
1181
  }
1155
1182
  function usagePath(env = process15.env) {
1156
1183
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
@@ -1224,6 +1251,10 @@ function takeOutputFlags(argv) {
1224
1251
  async function resolveSummary(summary) {
1225
1252
  return typeof summary === "string" ? summary : summary();
1226
1253
  }
1254
+ function lookup({ commands, aliases }, word) {
1255
+ const name = aliases !== undefined && Object.hasOwn(aliases, word) ? aliases[word] ?? word : word;
1256
+ return Object.hasOwn(commands, name) ? commands[name] : undefined;
1257
+ }
1227
1258
  function scopeOf(commands, extra, aliases) {
1228
1259
  return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1229
1260
  }
@@ -1318,12 +1349,12 @@ async function dispatch(level, typed, { version, redact }) {
1318
1349
  console.log(version);
1319
1350
  return 0;
1320
1351
  }
1321
- let command = level.commands[level.aliases?.[name] ?? name];
1352
+ let command = lookup(level, name);
1322
1353
  let rest = args;
1323
1354
  let ran = name;
1324
1355
  if (command === undefined && level.lazy.length > 0) {
1325
1356
  level = await expand(level, [...level.path.slice(1), ...argv]);
1326
- command = level.commands[level.aliases?.[name] ?? name];
1357
+ command = lookup(level, name);
1327
1358
  }
1328
1359
  if (command === undefined && level.defaultCommand !== undefined) {
1329
1360
  command = level.commands[level.defaultCommand];
@@ -1403,18 +1434,19 @@ async function leafCandidates(run, words) {
1403
1434
  async function candidates(scope, defaultCommand, words, before = []) {
1404
1435
  const [word = "", ...rest] = words;
1405
1436
  const listing = rest.length === 0 && !word.startsWith("-");
1406
- let { commands, aliases } = scope;
1407
- let command = commands[aliases?.[word] ?? word];
1437
+ let { commands } = scope;
1438
+ let command = lookup(scope, word);
1408
1439
  if (listing || command === undefined) {
1409
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1410
- command = commands[aliases?.[word] ?? word];
1440
+ const expanded = await expand(scope, [...before, ...words]);
1441
+ commands = expanded.commands;
1442
+ command = lookup(expanded, word);
1411
1443
  }
1412
1444
  if (listing) {
1413
1445
  const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1414
1446
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1415
1447
  const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1416
1448
  const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1417
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1449
+ return [...own, ...values.filter((line) => line !== FILES && !Object.hasOwn(commands, valueOf(line)))];
1418
1450
  }
1419
1451
  if (command === undefined) {
1420
1452
  const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
@@ -1479,8 +1511,7 @@ function commandPath(scope, argv) {
1479
1511
  const path = [];
1480
1512
  let level = scope;
1481
1513
  for (const word of argv.filter((each) => !each.startsWith("-"))) {
1482
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1483
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1514
+ const command = lookup(level, word);
1484
1515
  if (command === undefined)
1485
1516
  break;
1486
1517
  path.push(word);
@@ -1529,11 +1560,16 @@ init_mode();
1529
1560
  init_style();
1530
1561
  init_text2();
1531
1562
  // ../kit/src/secrets.ts
1532
- var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1563
+ var SECRET_PART = /token|secret|passw|passphrase|credential|private|dsn|apikey|accesskey|authorization|sess(?:ion)?id|connectionstring|key$/i;
1533
1564
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1534
1565
  var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
1566
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1567
+ function isSecretWord(word) {
1568
+ const lower = word.toLowerCase();
1569
+ return SECRET_WORDS.has(lower) || lower.endsWith("pass") && !NOT_PASSWORDS.has(lower);
1570
+ }
1535
1571
  function isSecretName(name) {
1536
- return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
1572
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some(isSecretWord);
1537
1573
  }
1538
1574
  // ../kit/src/sessions.ts
1539
1575
  var {Glob } = globalThis.Bun;
@@ -1718,6 +1754,7 @@ function foreignDatabases(statement, database) {
1718
1754
  }
1719
1755
  return found;
1720
1756
  }
1757
+ var EXISTENCE_WORDS = new Set(["if", "not", "exists"]);
1721
1758
  function definesServerObject(statement, dialect) {
1722
1759
  if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1723
1760
  return null;
@@ -2053,16 +2090,13 @@ async function containerService(wanted) {
2053
2090
  if (inspect.code !== 0)
2054
2091
  fail(`no container ${wanted}`);
2055
2092
  try {
2056
- return describeNamedContainer(wanted, JSON.parse(stdoutOf(inspect.chunks)));
2093
+ return describeNamedContainer(wanted, JSON.parse(inspect.stdout));
2057
2094
  } catch (error) {
2058
2095
  if (error instanceof SyntaxError)
2059
2096
  fail(`docker inspect ${wanted} did not print JSON`);
2060
2097
  throw error;
2061
2098
  }
2062
2099
  }
2063
- function stdoutOf(chunks) {
2064
- return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
2065
- }
2066
2100
  async function composeServices() {
2067
2101
  let ps;
2068
2102
  try {
@@ -2075,7 +2109,7 @@ async function composeServices() {
2075
2109
  if (rows.length === 0)
2076
2110
  return [];
2077
2111
  const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
2078
- return inspect.code === 0 ? describeServices(rows, JSON.parse(stdoutOf(inspect.chunks))) : [];
2112
+ return inspect.code === 0 ? describeServices(rows, JSON.parse(inspect.stdout)) : [];
2079
2113
  } catch {
2080
2114
  return [];
2081
2115
  }
@@ -2180,16 +2214,18 @@ function dialectOf(url) {
2180
2214
  return "mysql";
2181
2215
  return fail(`the connection URL is ${url.protocol.replace(":", "")}://, but db reads Postgres (postgres://), MySQL and MariaDB (mysql://, mariadb://) only`);
2182
2216
  }
2183
- function hostOf(url) {
2184
- const host = url.hostname === "" ? url.searchParams.get("host") ?? "" : url.hostname;
2185
- return host.replace(BRACKETS, "").toLowerCase();
2217
+ function paramValues(url, name) {
2218
+ return [...url.searchParams].filter(([key, value]) => key.toLowerCase() === name && value !== "").map(([, value]) => value);
2219
+ }
2220
+ function hostsOf(url) {
2221
+ const named = paramValues(url, "host");
2222
+ return [...named.length === 0 ? [url.hostname] : named, ...paramValues(url, "hostaddr")].map((host) => host.replace(BRACKETS, "").toLowerCase());
2186
2223
  }
2187
2224
  var isLocal = (host) => host === "" || host.startsWith("/") || LOCAL_HOSTS.has(host);
2188
2225
  var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
2189
2226
  function allowsKeyRetrieval(url) {
2190
2227
  try {
2191
- const host = hostOf(new URL(url));
2192
- return isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host);
2228
+ return hostsOf(new URL(url)).every((host) => isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host));
2193
2229
  } catch {
2194
2230
  return false;
2195
2231
  }
@@ -2212,17 +2248,22 @@ async function reachable(value, home) {
2212
2248
  fail("the connection URL does not parse");
2213
2249
  }
2214
2250
  const dialect = dialectOf(url);
2215
- const host = hostOf(url);
2216
- if (isLocal(host))
2251
+ const hosts = hostsOf(url);
2252
+ const [host = ""] = hosts;
2253
+ if (hosts.every(isLocal))
2217
2254
  return url;
2218
- const service = isIP(host) === 0 ? serviceNamed(await composeServices(), host, dialect) : undefined;
2255
+ const service = hosts.length === 1 && isIP(host) === 0 ? serviceNamed(await composeServices(), host, dialect) : undefined;
2219
2256
  if (service !== undefined) {
2257
+ for (const key of [...url.searchParams.keys()].filter((each) => ["host", "port"].includes(each.toLowerCase())))
2258
+ url.searchParams.delete(key);
2220
2259
  url.hostname = service.host.includes(":") ? `[${service.host}]` : service.host;
2221
2260
  url.port = String(service.port);
2222
2261
  return url;
2223
2262
  }
2224
- if (!((await loadSettings(home)).allowedHosts ?? []).some((allowed) => allowed.toLowerCase().replace(BRACKETS, "") === host))
2225
- fail(`${host} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
2263
+ const allowed = new Set(((await loadSettings(home)).allowedHosts ?? []).map((each) => each.toLowerCase().replace(BRACKETS, "")));
2264
+ const refused = hosts.find((each) => !isLocal(each) && !allowed.has(each));
2265
+ if (refused !== undefined)
2266
+ fail(`${refused} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
2226
2267
  return url;
2227
2268
  }
2228
2269
  async function connectionUrl({ env, service, container, database }, home) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-db",
3
3
  "type": "module",
4
- "version": "0.13.3",
4
+ "version": "0.13.5",
5
5
  "description": "db: run read-only SQL against Postgres, MySQL and MariaDB from the terminal without ever showing the connection credentials.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -24,10 +24,10 @@
24
24
  "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
25
25
  },
26
26
  "scripts": {
27
- "build": "$npm_execpath build src/cli.ts --target bun --outdir dist",
27
+ "build": "$npm_execpath build src/cli.ts --target bun --outdir dist && $npm_execpath ../../scripts/shell-shebang.ts",
28
28
  "db": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.45.1"
31
+ "@kaynooo/cli-kit": "0.46.4"
32
32
  }
33
33
  }