@secondlayer/cli 22.3.4 → 23.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 CHANGED
@@ -33,19 +33,6 @@ var __toESM = (mod, isNodeMode, target) => {
33
33
  return to;
34
34
  };
35
35
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
36
- var __returnValue = (v) => v;
37
- function __exportSetter(name, newValue) {
38
- this[name] = __returnValue.bind(null, newValue);
39
- }
40
- var __export = (target, all) => {
41
- for (var name in all)
42
- __defProp(target, name, {
43
- get: all[name],
44
- enumerable: true,
45
- configurable: true,
46
- set: __exportSetter.bind(all, name)
47
- });
48
- };
49
36
  var __esm = (fn, res, err) => () => {
50
37
  if (fn)
51
38
  try {
@@ -2144,7 +2131,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2144
2131
  // src/lib/api-url.ts
2145
2132
  import { isHostedApiUrl } from "@secondlayer/sdk";
2146
2133
  function resolveApiUrl() {
2147
- return (process.env.SECONDLAYER_API_URL ?? process.env.SL_PLATFORM_API_URL ?? LOCAL_API_URL).replace(/\/+$/, "");
2134
+ return (process.env.SECONDLAYER_API_URL ?? LOCAL_API_URL).replace(/\/+$/, "");
2148
2135
  }
2149
2136
  function resolveArchiveOpsUrl() {
2150
2137
  return (process.env.SL_CREDITS_API_URL ?? ARCHIVE_OPS_API_URL).replace(/\/+$/, "");
@@ -29197,75 +29184,12 @@ async function sha256File(path) {
29197
29184
  var init_fs = () => {};
29198
29185
 
29199
29186
  // src/lib/config.ts
29200
- var exports_config = {};
29201
- __export(exports_config, {
29202
- clearConfig: () => clearConfig,
29203
- getConfigPath: () => getConfigPath,
29204
- getDataDir: () => getDataDir,
29205
- getDefaultConfig: () => getDefaultConfig,
29206
- isDefaultValue: () => isDefaultValue,
29207
- loadConfig: () => loadConfig2,
29208
- requireLocalNetwork: () => requireLocalNetwork,
29209
- resetConfig: () => resetConfig,
29210
- setConfigValue: () => setConfigValue
29211
- });
29212
29187
  import { homedir as homedir2 } from "node:os";
29213
29188
  import { join as join6 } from "node:path";
29214
29189
  import { z as z3 } from "zod";
29215
29190
  async function ensureConfigDir() {
29216
29191
  await ensureDir(CONFIG_DIR);
29217
29192
  }
29218
- function resolvePath(path) {
29219
- if (path.startsWith("~/")) {
29220
- return join6(homedir2(), path.slice(2));
29221
- }
29222
- return path;
29223
- }
29224
- function getDataDir(config) {
29225
- const dataDir = config?.dataDir ?? DEFAULT_CONFIG.dataDir;
29226
- return resolvePath(dataDir);
29227
- }
29228
- function migrateConfig(raw) {
29229
- if (!raw || typeof raw !== "object") {
29230
- return { ...DEFAULT_CONFIG };
29231
- }
29232
- const old = raw;
29233
- const migrated = { ...DEFAULT_CONFIG };
29234
- if (typeof old.network === "string" && ["local", "testnet", "mainnet"].includes(old.network)) {
29235
- migrated.network = old.network;
29236
- }
29237
- if (typeof old.dataDir === "string") {
29238
- migrated.dataDir = old.dataDir;
29239
- }
29240
- if (typeof old.defaultProject === "string") {
29241
- migrated.defaultProject = old.defaultProject;
29242
- }
29243
- if (typeof old.nodeInstallPath === "string" || typeof old.nodeNetwork === "string") {
29244
- migrated.node = {
29245
- installPath: old.nodeInstallPath || "",
29246
- network: old.nodeNetwork || "mainnet"
29247
- };
29248
- if (!migrated.node.installPath) {
29249
- migrated.node = undefined;
29250
- }
29251
- }
29252
- if (old.node && typeof old.node === "object") {
29253
- migrated.node = old.node;
29254
- }
29255
- if (old.ports && typeof old.ports === "object") {
29256
- migrated.ports = { ...DEFAULT_CONFIG.ports, ...old.ports };
29257
- }
29258
- if (old.database && typeof old.database === "object") {
29259
- migrated.database = {
29260
- ...DEFAULT_CONFIG.database,
29261
- ...old.database
29262
- };
29263
- }
29264
- if (typeof old.indexerPort === "number") {
29265
- migrated.ports.indexer = old.indexerPort;
29266
- }
29267
- return migrated;
29268
- }
29269
29193
  async function loadConfig2() {
29270
29194
  let config;
29271
29195
  if (!await fileExists(CONFIG_PATH)) {
@@ -29273,8 +29197,7 @@ async function loadConfig2() {
29273
29197
  } else {
29274
29198
  try {
29275
29199
  const raw = await readJsonFile(CONFIG_PATH);
29276
- const migrated = migrateConfig(raw);
29277
- config = ConfigSchema.parse(migrated);
29200
+ config = ConfigSchema.parse(raw);
29278
29201
  } catch (error) {
29279
29202
  console.error("Warning: Invalid config file, using defaults");
29280
29203
  config = { ...DEFAULT_CONFIG };
@@ -29295,27 +29218,6 @@ function applyEnvOverrides(config) {
29295
29218
  console.error(`Warning: STACKS_NETWORK=${net} is not mainnet, testnet, or devnet; using ${result.network}`);
29296
29219
  }
29297
29220
  }
29298
- if (process.env.SL_DATA_DIR) {
29299
- result.dataDir = process.env.SL_DATA_DIR;
29300
- }
29301
- if (process.env.SL_API_PORT) {
29302
- const port = Number.parseInt(process.env.SL_API_PORT, 10);
29303
- if (!Number.isNaN(port) && port > 0 && port <= 65535) {
29304
- result.ports = { ...result.ports, api: port };
29305
- }
29306
- }
29307
- if (process.env.SL_INDEXER_PORT) {
29308
- const port = Number.parseInt(process.env.SL_INDEXER_PORT, 10);
29309
- if (!Number.isNaN(port) && port > 0 && port <= 65535) {
29310
- result.ports = { ...result.ports, indexer: port };
29311
- }
29312
- }
29313
- if (process.env.STACKS_NODE_RPC_URL) {
29314
- result.nodeRpcUrl = process.env.STACKS_NODE_RPC_URL;
29315
- }
29316
- if (process.env.DATABASE_URL) {
29317
- result.database = { type: "external", url: process.env.DATABASE_URL };
29318
- }
29319
29221
  return result;
29320
29222
  }
29321
29223
  async function saveConfig(config) {
@@ -29325,45 +29227,11 @@ async function saveConfig(config) {
29325
29227
  `);
29326
29228
  }
29327
29229
  async function setConfigValue(key, value) {
29328
- const config = await loadConfig2();
29329
- const keys = key.split(".");
29330
- let current = config;
29331
- for (let i = 0;i < keys.length - 1; i++) {
29332
- const k = keys[i];
29333
- if (current[k] === undefined) {
29334
- current[k] = {};
29335
- }
29336
- current = current[k];
29337
- }
29338
- const finalKey = keys[keys.length - 1];
29339
- const parsedValue = parseValue(value);
29340
- current[finalKey] = parsedValue;
29341
- await saveConfig(config);
29342
- }
29343
- function parseValue(value) {
29344
- if (typeof value !== "string") {
29345
- return value;
29346
- }
29347
- if (value === "true")
29348
- return true;
29349
- if (value === "false")
29350
- return false;
29351
- const num = Number(value);
29352
- if (!Number.isNaN(num) && value.trim() !== "") {
29353
- return num;
29354
- }
29355
- return value;
29356
- }
29357
- function getConfigValue(config, key) {
29358
- const keys = key.split(".");
29359
- let current = config;
29360
- for (const k of keys) {
29361
- if (current === null || current === undefined || typeof current !== "object") {
29362
- return;
29363
- }
29364
- current = current[k];
29230
+ if (!(key in ConfigSchema.shape)) {
29231
+ throw new Error(`Invalid config key: ${key}`);
29365
29232
  }
29366
- return current;
29233
+ const config = await loadConfig2();
29234
+ await saveConfig({ ...config, [key]: value });
29367
29235
  }
29368
29236
  async function resetConfig() {
29369
29237
  await saveConfig({ ...DEFAULT_CONFIG });
@@ -29392,44 +29260,16 @@ async function requireLocalNetwork() {
29392
29260
  }
29393
29261
  return config;
29394
29262
  }
29395
- function isDefaultValue(config, key) {
29396
- const currentValue = getConfigValue(config, key);
29397
- const defaultValue = getConfigValue(DEFAULT_CONFIG, key);
29398
- return JSON.stringify(currentValue) === JSON.stringify(defaultValue);
29399
- }
29400
- var PortsSchema, NodeSchema, DatabaseSchema, NetworkSchema, ConfigSchema, CONFIG_DIR, CONFIG_PATH, DEFAULT_CONFIG;
29263
+ var NetworkSchema, ConfigSchema, CONFIG_DIR, CONFIG_PATH, DEFAULT_CONFIG;
29401
29264
  var init_config2 = __esm(() => {
29402
29265
  init_fs();
29403
- PortsSchema = z3.object({
29404
- api: z3.number().int().min(1).max(65535).default(3800),
29405
- indexer: z3.number().int().min(1).max(65535).default(3700)
29406
- });
29407
- NodeSchema = z3.object({
29408
- installPath: z3.string().min(1),
29409
- network: z3.enum(["mainnet", "testnet"]).default("mainnet")
29410
- });
29411
- DatabaseSchema = z3.object({
29412
- type: z3.enum(["docker", "external"]).default("docker"),
29413
- url: z3.string().url().optional()
29414
- });
29415
29266
  NetworkSchema = z3.enum(["local", "testnet", "mainnet"]);
29416
29267
  ConfigSchema = z3.object({
29417
- network: NetworkSchema.default("mainnet"),
29418
- nodeRpcUrl: z3.string().url().optional(),
29419
- dataDir: z3.string().default("~/.secondlayer/data"),
29420
- node: NodeSchema.optional(),
29421
- ports: PortsSchema.default({ api: 3800, indexer: 3700 }),
29422
- database: DatabaseSchema.default({ type: "docker" }),
29423
- defaultProject: z3.string().optional()
29268
+ network: NetworkSchema.default("mainnet")
29424
29269
  });
29425
29270
  CONFIG_DIR = join6(homedir2(), ".secondlayer");
29426
29271
  CONFIG_PATH = join6(CONFIG_DIR, "config.json");
29427
- DEFAULT_CONFIG = {
29428
- network: "mainnet",
29429
- dataDir: "~/.secondlayer/data",
29430
- ports: { api: 3800, indexer: 3700 },
29431
- database: { type: "docker" }
29432
- };
29272
+ DEFAULT_CONFIG = { network: "mainnet" };
29433
29273
  });
29434
29274
 
29435
29275
  // src/lib/filter-params.ts
@@ -31667,7 +31507,7 @@ function client() {
31667
31507
  apiKey: resolveDataPlaneKey()
31668
31508
  });
31669
31509
  }
31670
- function fail(action, err) {
31510
+ function fail2(action, err) {
31671
31511
  const message = err instanceof Error ? err.message : String(err);
31672
31512
  error(`Failed to ${action}: ${message}`);
31673
31513
  if (/\b403\b/.test(message) || /forbidden/i.test(message)) {
@@ -31758,7 +31598,7 @@ function registerIndexCommand(program) {
31758
31598
  recipient: o.recipient
31759
31599
  }), o.json);
31760
31600
  } catch (err) {
31761
- fail("list ft transfers", err);
31601
+ fail2("list ft transfers", err);
31762
31602
  }
31763
31603
  });
31764
31604
  orderFlag(rangeFlags(index.command("nft-transfers"))).description("List decoded SIP-009 non-fungible-token transfers").option("--sender <principal>", "Filter by sender").option("--recipient <principal>", "Filter by recipient").option("--asset-identifier <id>", "Filter by asset identifier").action(async (o) => {
@@ -31771,7 +31611,7 @@ function registerIndexCommand(program) {
31771
31611
  assetIdentifier: o.assetIdentifier
31772
31612
  }), o.json);
31773
31613
  } catch (err) {
31774
- fail("list nft transfers", err);
31614
+ fail2("list nft transfers", err);
31775
31615
  }
31776
31616
  });
31777
31617
  orderFlag(rangeFlags(index.command("events"))).description("List decoded events by type (stx_*, ft/nft mint/burn, print, …)").option("--event-type <type>", `decoded event type (${VALID_INDEX_TYPES.join(", ")})`).option("--types <type>", "alias for --event-type, ONE value (the Streams spelling)").option("--sender <principal>", "Filter by sender").option("--recipient <principal>", "Filter by recipient").option("--asset-identifier <id>", "Filter by asset identifier").action(async (o) => {
@@ -31785,7 +31625,7 @@ function registerIndexCommand(program) {
31785
31625
  assetIdentifier: o.assetIdentifier
31786
31626
  }), o.json);
31787
31627
  } catch (err) {
31788
- fail("list events", err);
31628
+ fail2("list events", err);
31789
31629
  }
31790
31630
  });
31791
31631
  rangeFlags(index.command("contract-calls")).description("List decoded contract calls (function, args, result)").option("--function-name <name>", "Filter by called function").option("--sender <principal>", "Filter by caller").action(async (o) => {
@@ -31796,21 +31636,21 @@ function registerIndexCommand(program) {
31796
31636
  sender: o.sender
31797
31637
  }), o.json);
31798
31638
  } catch (err) {
31799
- fail("list contract calls", err);
31639
+ fail2("list contract calls", err);
31800
31640
  }
31801
31641
  });
31802
31642
  heightFlags(index.command("canonical")).description("List the canonical Stacks block sequence (height + hash)").action(async (o) => {
31803
31643
  try {
31804
31644
  emit(await client().canonical.list(heightParams(o)), o.json);
31805
31645
  } catch (err) {
31806
- fail("list canonical blocks", err);
31646
+ fail2("list canonical blocks", err);
31807
31647
  }
31808
31648
  });
31809
31649
  const blocks = heightFlags(index.command("blocks")).description("List decoded blocks (run `blocks get <ref>` for one block)").action(async (o) => {
31810
31650
  try {
31811
31651
  emit(await client().blocks.list(heightParams(o)), o.json);
31812
31652
  } catch (err) {
31813
- fail("list blocks", err);
31653
+ fail2("list blocks", err);
31814
31654
  }
31815
31655
  });
31816
31656
  blocks.command("get <ref>").description("Get a single block by height or block hash").option("--json", "Print as JSON").action(async (ref, o) => {
@@ -31818,7 +31658,7 @@ function registerIndexCommand(program) {
31818
31658
  const block = await client().blocks.get(/^\d+$/.test(ref) ? Number.parseInt(ref, 10) : ref);
31819
31659
  emitOne(block, `block ${ref}`, o.json);
31820
31660
  } catch (err) {
31821
- fail("get block", err);
31661
+ fail2("get block", err);
31822
31662
  }
31823
31663
  });
31824
31664
  const transactions = rangeFlags(index.command("transactions")).description("List decoded transactions (run `transactions get <txId>` for one)").option("--type <type>", "Filter by transaction type").option("--sender <principal>", "Filter by sender").action(async (o) => {
@@ -31829,14 +31669,14 @@ function registerIndexCommand(program) {
31829
31669
  sender: o.sender
31830
31670
  }), o.json);
31831
31671
  } catch (err) {
31832
- fail("list transactions", err);
31672
+ fail2("list transactions", err);
31833
31673
  }
31834
31674
  });
31835
31675
  transactions.command("get <txId>").description("Get a single transaction by tx_id").option("--json", "Print as JSON").action(async (txId, o) => {
31836
31676
  try {
31837
31677
  emitOne(await client().transactions.get(txId), `tx ${txId}`, o.json);
31838
31678
  } catch (err) {
31839
- fail("get transaction", err);
31679
+ fail2("get transaction", err);
31840
31680
  }
31841
31681
  });
31842
31682
  heightFlags(index.command("stacking")).description("List decoded PoX-4 stacking actions").option("--function-name <name>", "Filter by PoX function name").option("--stacker <principal>", "Filter by stacker").option("--caller <principal>", "Filter by caller").action(async (o) => {
@@ -31848,7 +31688,7 @@ function registerIndexCommand(program) {
31848
31688
  caller: o.caller
31849
31689
  }), o.json);
31850
31690
  } catch (err) {
31851
- fail("list stacking actions", err);
31691
+ fail2("list stacking actions", err);
31852
31692
  }
31853
31693
  });
31854
31694
  const mempool = index.command("mempool").description("List pending mempool transactions (run `mempool get <txId>` for one)").option("--contract-id <id>", "Filter to pending calls to a contract").option("--function-name <name>", "Filter to pending calls to a function").option("--sender <principal>", "Filter by sender").option("--type <type>", "Filter by transaction type").option("--cursor <cursor>", "Resume token from a previous next_cursor").option("--limit <n>", "Rows per page").option("--json", "Print the full envelope as JSON").action(async (o) => {
@@ -31862,14 +31702,14 @@ function registerIndexCommand(program) {
31862
31702
  limit: o.limit ? Number.parseInt(o.limit, 10) : undefined
31863
31703
  }), o.json);
31864
31704
  } catch (err) {
31865
- fail("list mempool", err);
31705
+ fail2("list mempool", err);
31866
31706
  }
31867
31707
  });
31868
31708
  mempool.command("get <txId>").description("Get a single pending transaction by tx_id (404 once mined)").option("--json", "Print as JSON").action(async (txId, o) => {
31869
31709
  try {
31870
31710
  emitOne(await client().mempool.get(txId), `pending tx ${txId}`, o.json);
31871
31711
  } catch (err) {
31872
- fail("get mempool tx", err);
31712
+ fail2("get mempool tx", err);
31873
31713
  }
31874
31714
  });
31875
31715
  const runes = index.command("runes").description("List etched runes (Bitcoin; run `runes get <rune>` for one)").option("--search <prefix>", "Name prefix, spacers and case ignored").option("--sort <order>", "number (etch order) or mints (busiest first)").option("--cursor <cursor>", "Resume token from a previous next_cursor").option("--limit <n>", "Rows per page").option("--json", "Print the full envelope as JSON").action(async (o) => {
@@ -31881,7 +31721,7 @@ function registerIndexCommand(program) {
31881
31721
  limit: o.limit ? Number.parseInt(o.limit, 10) : undefined
31882
31722
  }), o.json);
31883
31723
  } catch (err) {
31884
- fail("list runes", err);
31724
+ fail2("list runes", err);
31885
31725
  }
31886
31726
  });
31887
31727
  runes.command("get <rune>").description("Get one rune by id (840000:3) or name, any spacing or case").option("--json", "Print as JSON").action(async (rune, _o, cmd) => {
@@ -31889,7 +31729,7 @@ function registerIndexCommand(program) {
31889
31729
  try {
31890
31730
  emitOne(await client().runes.get(rune), `rune ${rune}`, o.json);
31891
31731
  } catch (err) {
31892
- fail("get rune", err);
31732
+ fail2("get rune", err);
31893
31733
  }
31894
31734
  });
31895
31735
  runes.command("balances").description("Current rune balances by address or outpoint (Bitcoin)").option("--address <address>", "Bitcoin address").option("--outpoint <txid:vout>", "Unspent output").option("--rune <ref>", "Narrow to one rune (id or name)").option("--cursor <cursor>", "Resume token from a previous next_cursor").option("--limit <n>", "Rows per page").option("--json", "Print the full envelope as JSON").action(async (_o, cmd) => {
@@ -31902,7 +31742,7 @@ function registerIndexCommand(program) {
31902
31742
  limit: o.limit ? Number.parseInt(o.limit, 10) : undefined
31903
31743
  }), o.json);
31904
31744
  } catch (err) {
31905
- fail("list rune balances", err);
31745
+ fail2("list rune balances", err);
31906
31746
  }
31907
31747
  });
31908
31748
  runes.command("activity").description("List rune etches, mints, transfers and burns (Bitcoin)").option("--rune <ref>", "Filter by rune (id or name)").option("--address <address>", "Filter by Bitcoin address").option("--kind <kinds>", `Comma list of ${RUNE_KINDS.join(", ")}`).option("--txid <txid>", "Filter by Bitcoin transaction id").option("--from-height <n>", "Start Bitcoin block height (inclusive)").option("--to-height <n>", "End Bitcoin block height (inclusive)").option("--cursor <cursor>", "Resume token from a previous next_cursor").option("--limit <n>", "Rows per page").option("--json", "Print the full envelope as JSON").action(async (_o, cmd) => {
@@ -31916,7 +31756,7 @@ function registerIndexCommand(program) {
31916
31756
  txid: o.txid
31917
31757
  }), o.json);
31918
31758
  } catch (err) {
31919
- fail("list rune activity", err);
31759
+ fail2("list rune activity", err);
31920
31760
  }
31921
31761
  });
31922
31762
  }
@@ -31955,1995 +31795,9 @@ var init_index_api = __esm(() => {
31955
31795
  RUNE_KINDS = ["etch", "mint", "transfer", "burn"];
31956
31796
  });
31957
31797
 
31958
- // ../../node_modules/postgres/src/query.js
31959
- function cachedError(xs) {
31960
- if (originCache.has(xs))
31961
- return originCache.get(xs);
31962
- const x = Error.stackTraceLimit;
31963
- Error.stackTraceLimit = 4;
31964
- originCache.set(xs, new Error);
31965
- Error.stackTraceLimit = x;
31966
- return originCache.get(xs);
31967
- }
31968
- var originCache, originStackCache, originError, CLOSE, Query;
31969
- var init_query = __esm(() => {
31970
- originCache = new Map;
31971
- originStackCache = new Map;
31972
- originError = Symbol("OriginError");
31973
- CLOSE = {};
31974
- Query = class Query extends Promise {
31975
- constructor(strings, args, handler, canceller, options = {}) {
31976
- let resolve, reject;
31977
- super((a, b) => {
31978
- resolve = a;
31979
- reject = b;
31980
- });
31981
- this.tagged = Array.isArray(strings.raw);
31982
- this.strings = strings;
31983
- this.args = args;
31984
- this.handler = handler;
31985
- this.canceller = canceller;
31986
- this.options = options;
31987
- this.state = null;
31988
- this.statement = null;
31989
- this.resolve = (x) => (this.active = false, resolve(x));
31990
- this.reject = (x) => (this.active = false, reject(x));
31991
- this.active = false;
31992
- this.cancelled = null;
31993
- this.executed = false;
31994
- this.signature = "";
31995
- this[originError] = this.handler.debug ? new Error : this.tagged && cachedError(this.strings);
31996
- }
31997
- get origin() {
31998
- return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || "";
31999
- }
32000
- static get [Symbol.species]() {
32001
- return Promise;
32002
- }
32003
- cancel() {
32004
- return this.canceller && (this.canceller(this), this.canceller = null);
32005
- }
32006
- simple() {
32007
- this.options.simple = true;
32008
- this.options.prepare = false;
32009
- return this;
32010
- }
32011
- async readable() {
32012
- this.simple();
32013
- this.streaming = true;
32014
- return this;
32015
- }
32016
- async writable() {
32017
- this.simple();
32018
- this.streaming = true;
32019
- return this;
32020
- }
32021
- cursor(rows = 1, fn) {
32022
- this.options.simple = false;
32023
- if (typeof rows === "function") {
32024
- fn = rows;
32025
- rows = 1;
32026
- }
32027
- this.cursorRows = rows;
32028
- if (typeof fn === "function")
32029
- return this.cursorFn = fn, this;
32030
- let prev;
32031
- return {
32032
- [Symbol.asyncIterator]: () => ({
32033
- next: () => {
32034
- if (this.executed && !this.active)
32035
- return { done: true };
32036
- prev && prev();
32037
- const promise = new Promise((resolve, reject) => {
32038
- this.cursorFn = (value) => {
32039
- resolve({ value, done: false });
32040
- return new Promise((r) => prev = r);
32041
- };
32042
- this.resolve = () => (this.active = false, resolve({ done: true }));
32043
- this.reject = (x) => (this.active = false, reject(x));
32044
- });
32045
- this.execute();
32046
- return promise;
32047
- },
32048
- return() {
32049
- prev && prev(CLOSE);
32050
- return { done: true };
32051
- }
32052
- })
32053
- };
32054
- }
32055
- describe() {
32056
- this.options.simple = false;
32057
- this.onlyDescribe = this.options.prepare = true;
32058
- return this;
32059
- }
32060
- stream() {
32061
- throw new Error(".stream has been renamed to .forEach");
32062
- }
32063
- forEach(fn) {
32064
- this.forEachFn = fn;
32065
- this.handle();
32066
- return this;
32067
- }
32068
- raw() {
32069
- this.isRaw = true;
32070
- return this;
32071
- }
32072
- values() {
32073
- this.isRaw = "values";
32074
- return this;
32075
- }
32076
- async handle() {
32077
- !this.executed && (this.executed = true) && await 1 && this.handler(this);
32078
- }
32079
- execute() {
32080
- this.handle();
32081
- return this;
32082
- }
32083
- then() {
32084
- this.handle();
32085
- return super.then.apply(this, arguments);
32086
- }
32087
- catch() {
32088
- this.handle();
32089
- return super.catch.apply(this, arguments);
32090
- }
32091
- finally() {
32092
- this.handle();
32093
- return super.finally.apply(this, arguments);
32094
- }
32095
- };
32096
- });
32097
-
32098
- // ../../node_modules/postgres/src/errors.js
32099
- function connection(x, options, socket) {
32100
- const { host, port } = socket || options;
32101
- const error = Object.assign(new Error("write " + x + " " + (options.path || host + ":" + port)), {
32102
- code: x,
32103
- errno: x,
32104
- address: options.path || host
32105
- }, options.path ? {} : { port });
32106
- Error.captureStackTrace(error, connection);
32107
- return error;
32108
- }
32109
- function postgres(x) {
32110
- const error = new PostgresError(x);
32111
- Error.captureStackTrace(error, postgres);
32112
- return error;
32113
- }
32114
- function generic(code, message) {
32115
- const error = Object.assign(new Error(code + ": " + message), { code });
32116
- Error.captureStackTrace(error, generic);
32117
- return error;
32118
- }
32119
- function notSupported(x) {
32120
- const error = Object.assign(new Error(x + " (B) is not supported"), {
32121
- code: "MESSAGE_NOT_SUPPORTED",
32122
- name: x
32123
- });
32124
- Error.captureStackTrace(error, notSupported);
32125
- return error;
32126
- }
32127
- var PostgresError, Errors;
32128
- var init_errors2 = __esm(() => {
32129
- PostgresError = class PostgresError extends Error {
32130
- constructor(x) {
32131
- super(x.message);
32132
- this.name = this.constructor.name;
32133
- Object.assign(this, x);
32134
- }
32135
- };
32136
- Errors = {
32137
- connection,
32138
- postgres,
32139
- generic,
32140
- notSupported
32141
- };
32142
- });
32143
-
32144
- // ../../node_modules/postgres/src/types.js
32145
- class NotTagged {
32146
- then() {
32147
- notTagged();
32148
- }
32149
- catch() {
32150
- notTagged();
32151
- }
32152
- finally() {
32153
- notTagged();
32154
- }
32155
- }
32156
- function handleValue(x, parameters, types, options) {
32157
- let value = x instanceof Parameter ? x.value : x;
32158
- if (value === undefined) {
32159
- x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
32160
- if (value === undefined)
32161
- throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
32162
- }
32163
- return "$" + types.push(x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x)));
32164
- }
32165
- function stringify(q, string, value, parameters, types, options) {
32166
- for (let i = 1;i < q.strings.length; i++) {
32167
- string += stringifyValue(string, value, parameters, types, options) + q.strings[i];
32168
- value = q.args[i];
32169
- }
32170
- return string;
32171
- }
32172
- function stringifyValue(string, value, parameters, types, o) {
32173
- return value instanceof Builder ? value.build(string, parameters, types, o) : value instanceof Query ? fragment(value, parameters, types, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types, o), "") : handleValue(value, parameters, types, o);
32174
- }
32175
- function fragment(q, parameters, types, options) {
32176
- q.fragment = true;
32177
- return stringify(q, q.strings[0], q.args[0], parameters, types, options);
32178
- }
32179
- function valuesBuilder(first, parameters, types, columns, options) {
32180
- return first.map((row) => "(" + columns.map((column) => stringifyValue("values", row[column], parameters, types, options)).join(",") + ")").join(",");
32181
- }
32182
- function values(first, rest, parameters, types, options) {
32183
- const multi = Array.isArray(first[0]);
32184
- const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
32185
- return valuesBuilder(multi ? first : [first], parameters, types, columns, options);
32186
- }
32187
- function select2(first, rest, parameters, types, options) {
32188
- typeof first === "string" && (first = [first].concat(rest));
32189
- if (Array.isArray(first))
32190
- return escapeIdentifiers(first, options);
32191
- let value;
32192
- const columns = rest.length ? rest.flat() : Object.keys(first);
32193
- return columns.map((x) => {
32194
- value = first[x];
32195
- return (value instanceof Query ? fragment(value, parameters, types, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
32196
- }).join(",");
32197
- }
32198
- function notTagged() {
32199
- throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
32200
- }
32201
- function firstIsString(x) {
32202
- if (Array.isArray(x))
32203
- return firstIsString(x[0]);
32204
- return typeof x === "string" ? 1009 : 0;
32205
- }
32206
- function typeHandlers(types) {
32207
- return Object.keys(types).reduce((acc, k) => {
32208
- types[k].from && [].concat(types[k].from).forEach((x) => acc.parsers[x] = types[k].parse);
32209
- if (types[k].serialize) {
32210
- acc.serializers[types[k].to] = types[k].serialize;
32211
- types[k].from && [].concat(types[k].from).forEach((x) => acc.serializers[x] = types[k].serialize);
32212
- }
32213
- return acc;
32214
- }, { parsers: {}, serializers: {} });
32215
- }
32216
- function escapeIdentifiers(xs, { transform: { column } }) {
32217
- return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
32218
- }
32219
- function arrayEscape(x) {
32220
- return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, "\\\"");
32221
- }
32222
- function arrayParserLoop(s, x, parser, typarray) {
32223
- const xs = [];
32224
- const delimiter = typarray === 1020 ? ";" : ",";
32225
- for (;s.i < x.length; s.i++) {
32226
- s.char = x[s.i];
32227
- if (s.quoted) {
32228
- if (s.char === "\\") {
32229
- s.str += x[++s.i];
32230
- } else if (s.char === '"') {
32231
- xs.push(parser ? parser(s.str) : s.str);
32232
- s.str = "";
32233
- s.quoted = x[s.i + 1] === '"';
32234
- s.last = s.i + 2;
32235
- } else {
32236
- s.str += s.char;
32237
- }
32238
- } else if (s.char === '"') {
32239
- s.quoted = true;
32240
- } else if (s.char === "{") {
32241
- s.last = ++s.i;
32242
- xs.push(arrayParserLoop(s, x, parser, typarray));
32243
- } else if (s.char === "}") {
32244
- s.quoted = false;
32245
- s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
32246
- s.last = s.i + 1;
32247
- break;
32248
- } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') {
32249
- xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
32250
- s.last = s.i + 1;
32251
- }
32252
- s.p = s.char;
32253
- }
32254
- s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
32255
- return xs;
32256
- }
32257
- function createJsonTransform(fn) {
32258
- return function jsonTransform(x, column) {
32259
- return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x) => jsonTransform(x, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
32260
- };
32261
- }
32262
- var types5, Identifier, Parameter, Builder, defaultHandlers, builders, serializers, parsers, mergeUserTypes = function(types) {
32263
- const user = typeHandlers(types || {});
32264
- return {
32265
- serializers: Object.assign({}, serializers, user.serializers),
32266
- parsers: Object.assign({}, parsers, user.parsers)
32267
- };
32268
- }, escapeIdentifier = function escape(str) {
32269
- return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"';
32270
- }, inferType = function inferType(x) {
32271
- return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType(x[0]) : 0;
32272
- }, escapeBackslash, escapeQuote, arraySerializer = function arraySerializer(xs, serializer, options, typarray) {
32273
- if (Array.isArray(xs) === false)
32274
- return xs;
32275
- if (!xs.length)
32276
- return "{}";
32277
- const first = xs[0];
32278
- const delimiter = typarray === 1020 ? ";" : ",";
32279
- if (Array.isArray(first) && !first.type)
32280
- return "{" + xs.map((x) => arraySerializer(x, serializer, options, typarray)).join(delimiter) + "}";
32281
- return "{" + xs.map((x) => {
32282
- if (x === undefined) {
32283
- x = options.transform.undefined;
32284
- if (x === undefined)
32285
- throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
32286
- }
32287
- return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"';
32288
- }).join(delimiter) + "}";
32289
- }, arrayParserState, arrayParser = function arrayParser(x, parser, typarray) {
32290
- arrayParserState.i = arrayParserState.last = 0;
32291
- return arrayParserLoop(arrayParserState, x, parser, typarray);
32292
- }, toCamel = (x) => {
32293
- let str = x[0];
32294
- for (let i = 1;i < x.length; i++)
32295
- str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
32296
- return str;
32297
- }, toPascal = (x) => {
32298
- let str = x[0].toUpperCase();
32299
- for (let i = 1;i < x.length; i++)
32300
- str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
32301
- return str;
32302
- }, toKebab = (x) => x.replace(/_/g, "-"), fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase(), fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase(), fromKebab = (x) => x.replace(/-/g, "_"), camel, pascal, kebab;
32303
- var init_types4 = __esm(() => {
32304
- init_query();
32305
- init_errors2();
32306
- types5 = {
32307
- string: {
32308
- to: 25,
32309
- from: null,
32310
- serialize: (x) => "" + x
32311
- },
32312
- number: {
32313
- to: 0,
32314
- from: [21, 23, 26, 700, 701],
32315
- serialize: (x) => "" + x,
32316
- parse: (x) => +x
32317
- },
32318
- json: {
32319
- to: 114,
32320
- from: [114, 3802],
32321
- serialize: (x) => JSON.stringify(x),
32322
- parse: (x) => JSON.parse(x)
32323
- },
32324
- boolean: {
32325
- to: 16,
32326
- from: 16,
32327
- serialize: (x) => x === true ? "t" : "f",
32328
- parse: (x) => x === "t"
32329
- },
32330
- date: {
32331
- to: 1184,
32332
- from: [1082, 1114, 1184],
32333
- serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
32334
- parse: (x) => new Date(x)
32335
- },
32336
- bytea: {
32337
- to: 17,
32338
- from: 17,
32339
- serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
32340
- parse: (x) => Buffer.from(x.slice(2), "hex")
32341
- }
32342
- };
32343
- Identifier = class Identifier extends NotTagged {
32344
- constructor(value) {
32345
- super();
32346
- this.value = escapeIdentifier(value);
32347
- }
32348
- };
32349
- Parameter = class Parameter extends NotTagged {
32350
- constructor(value, type, array) {
32351
- super();
32352
- this.value = value;
32353
- this.type = type;
32354
- this.array = array;
32355
- }
32356
- };
32357
- Builder = class Builder extends NotTagged {
32358
- constructor(first, rest) {
32359
- super();
32360
- this.first = first;
32361
- this.rest = rest;
32362
- }
32363
- build(before, parameters, types, options) {
32364
- const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop();
32365
- return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types, options);
32366
- }
32367
- };
32368
- defaultHandlers = typeHandlers(types5);
32369
- builders = Object.entries({
32370
- values,
32371
- in: (...xs) => {
32372
- const x = values(...xs);
32373
- return x === "()" ? "(null)" : x;
32374
- },
32375
- select: select2,
32376
- as: select2,
32377
- returning: select2,
32378
- "\\(": select2,
32379
- update(first, rest, parameters, types, options) {
32380
- return (rest.length ? rest.flat() : Object.keys(first)).map((x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types, options));
32381
- },
32382
- insert(first, rest, parameters, types, options) {
32383
- const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
32384
- return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types, columns, options);
32385
- }
32386
- }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
32387
- serializers = defaultHandlers.serializers;
32388
- parsers = defaultHandlers.parsers;
32389
- escapeBackslash = /\\/g;
32390
- escapeQuote = /"/g;
32391
- arrayParserState = {
32392
- i: 0,
32393
- char: null,
32394
- str: "",
32395
- quoted: false,
32396
- last: 0
32397
- };
32398
- toCamel.column = { from: toCamel };
32399
- toCamel.value = { from: createJsonTransform(toCamel) };
32400
- fromCamel.column = { to: fromCamel };
32401
- camel = { ...toCamel };
32402
- camel.column.to = fromCamel;
32403
- toPascal.column = { from: toPascal };
32404
- toPascal.value = { from: createJsonTransform(toPascal) };
32405
- fromPascal.column = { to: fromPascal };
32406
- pascal = { ...toPascal };
32407
- pascal.column.to = fromPascal;
32408
- toKebab.column = { from: toKebab };
32409
- toKebab.value = { from: createJsonTransform(toKebab) };
32410
- fromKebab.column = { to: fromKebab };
32411
- kebab = { ...toKebab };
32412
- kebab.column.to = fromKebab;
32413
- });
32414
-
32415
- // ../../node_modules/postgres/src/result.js
32416
- var Result;
32417
- var init_result2 = __esm(() => {
32418
- Result = class Result extends Array {
32419
- constructor() {
32420
- super();
32421
- Object.defineProperties(this, {
32422
- count: { value: null, writable: true },
32423
- state: { value: null, writable: true },
32424
- command: { value: null, writable: true },
32425
- columns: { value: null, writable: true },
32426
- statement: { value: null, writable: true }
32427
- });
32428
- }
32429
- static get [Symbol.species]() {
32430
- return Array;
32431
- }
32432
- };
32433
- });
32434
-
32435
- // ../../node_modules/postgres/src/queue.js
32436
- function Queue(initial = []) {
32437
- let xs = initial.slice();
32438
- let index = 0;
32439
- return {
32440
- get length() {
32441
- return xs.length - index;
32442
- },
32443
- remove: (x) => {
32444
- const index = xs.indexOf(x);
32445
- return index === -1 ? null : (xs.splice(index, 1), x);
32446
- },
32447
- push: (x) => (xs.push(x), x),
32448
- shift: () => {
32449
- const out = xs[index++];
32450
- if (index === xs.length) {
32451
- index = 0;
32452
- xs = [];
32453
- } else {
32454
- xs[index - 1] = undefined;
32455
- }
32456
- return out;
32457
- }
32458
- };
32459
- }
32460
- var queue_default;
32461
- var init_queue = __esm(() => {
32462
- queue_default = Queue;
32463
- });
32464
-
32465
- // ../../node_modules/postgres/src/bytes.js
32466
- function fit(x) {
32467
- if (buffer.length - b2.i < x) {
32468
- const prev = buffer, length = prev.length;
32469
- buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
32470
- prev.copy(buffer);
32471
- }
32472
- }
32473
- function reset3() {
32474
- b2.i = 0;
32475
- return b2;
32476
- }
32477
- var size = 256, buffer, messages, b2, bytes_default;
32478
- var init_bytes = __esm(() => {
32479
- buffer = Buffer.allocUnsafe(size);
32480
- messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
32481
- const v = x.charCodeAt(0);
32482
- acc[x] = () => {
32483
- buffer[0] = v;
32484
- b2.i = 5;
32485
- return b2;
32486
- };
32487
- return acc;
32488
- }, {});
32489
- b2 = Object.assign(reset3, messages, {
32490
- N: String.fromCharCode(0),
32491
- i: 0,
32492
- inc(x) {
32493
- b2.i += x;
32494
- return b2;
32495
- },
32496
- str(x) {
32497
- const length = Buffer.byteLength(x);
32498
- fit(length);
32499
- b2.i += buffer.write(x, b2.i, length, "utf8");
32500
- return b2;
32501
- },
32502
- i16(x) {
32503
- fit(2);
32504
- buffer.writeUInt16BE(x, b2.i);
32505
- b2.i += 2;
32506
- return b2;
32507
- },
32508
- i32(x, i) {
32509
- if (i || i === 0) {
32510
- buffer.writeUInt32BE(x, i);
32511
- return b2;
32512
- }
32513
- fit(4);
32514
- buffer.writeUInt32BE(x, b2.i);
32515
- b2.i += 4;
32516
- return b2;
32517
- },
32518
- z(x) {
32519
- fit(x);
32520
- buffer.fill(0, b2.i, b2.i + x);
32521
- b2.i += x;
32522
- return b2;
32523
- },
32524
- raw(x) {
32525
- buffer = Buffer.concat([buffer.subarray(0, b2.i), x]);
32526
- b2.i = buffer.length;
32527
- return b2;
32528
- },
32529
- end(at = 1) {
32530
- buffer.writeUInt32BE(b2.i - at, at);
32531
- const out = buffer.subarray(0, b2.i);
32532
- b2.i = 0;
32533
- buffer = Buffer.allocUnsafe(size);
32534
- return out;
32535
- }
32536
- });
32537
- bytes_default = b2;
32538
- });
32539
-
32540
- // ../../node_modules/postgres/src/connection.js
32541
- import net2 from "net";
32542
- import tls from "tls";
32543
- import crypto2 from "crypto";
32544
- import Stream from "stream";
32545
- import { performance } from "perf_hooks";
32546
- function Connection(options, queues = {}, { onopen = noop5, onend = noop5, onclose = noop5 } = {}) {
32547
- const {
32548
- sslnegotiation,
32549
- ssl,
32550
- max,
32551
- user,
32552
- host,
32553
- port,
32554
- database,
32555
- parsers,
32556
- transform,
32557
- onnotice,
32558
- onnotify,
32559
- onparameter,
32560
- max_pipeline,
32561
- keep_alive,
32562
- backoff,
32563
- target_session_attrs
32564
- } = options;
32565
- const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer2(end, options.idle_timeout), lifeTimer = timer2(end, options.max_lifetime), connectTimer = timer2(connectTimedOut, options.connect_timeout);
32566
- let socket = null, cancelMessage, errorResponse = null, result = new Result, incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
32567
- const connection = {
32568
- queue: queues.closed,
32569
- idleTimer,
32570
- connect(query) {
32571
- initial = query;
32572
- reconnect();
32573
- },
32574
- terminate,
32575
- execute,
32576
- cancel,
32577
- end,
32578
- count: 0,
32579
- id
32580
- };
32581
- queues.closed && queues.closed.push(connection);
32582
- return connection;
32583
- async function createSocket() {
32584
- let x;
32585
- try {
32586
- x = options.socket ? await Promise.resolve(options.socket(options)) : new net2.Socket;
32587
- } catch (e) {
32588
- error(e);
32589
- return;
32590
- }
32591
- x.on("error", error);
32592
- x.on("close", closed);
32593
- x.on("drain", drain);
32594
- return x;
32595
- }
32596
- async function cancel({ pid, secret }, resolve, reject) {
32597
- try {
32598
- cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
32599
- await connect();
32600
- socket.once("error", reject);
32601
- socket.once("close", resolve);
32602
- } catch (error) {
32603
- reject(error);
32604
- }
32605
- }
32606
- function execute(q) {
32607
- if (terminated)
32608
- return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
32609
- if (stream)
32610
- return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
32611
- if (q.cancelled)
32612
- return;
32613
- try {
32614
- q.state = backend;
32615
- query ? sent.push(q) : (query = q, query.active = true);
32616
- build(q);
32617
- return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection));
32618
- } catch (error) {
32619
- sent.length === 0 && write(Sync);
32620
- errored(error);
32621
- return true;
32622
- }
32623
- }
32624
- function toBuffer(q) {
32625
- if (q.parameters.length >= 65534)
32626
- throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
32627
- return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
32628
- }
32629
- function describe(q) {
32630
- return Buffer.concat([
32631
- Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
32632
- Describe("S", q.statement.name)
32633
- ]);
32634
- }
32635
- function prepared(q) {
32636
- return Buffer.concat([
32637
- Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
32638
- q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed
32639
- ]);
32640
- }
32641
- function unnamed(q) {
32642
- return Buffer.concat([
32643
- Parse(q.statement.string, q.parameters, q.statement.types),
32644
- DescribeUnnamed,
32645
- prepared(q)
32646
- ]);
32647
- }
32648
- function build(q) {
32649
- const parameters = [], types = [];
32650
- const string = stringify(q, q.strings[0], q.args[0], parameters, types, options);
32651
- !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types, options));
32652
- q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
32653
- q.string = string;
32654
- q.signature = q.prepare && types + string;
32655
- q.onlyDescribe && delete statements[q.signature];
32656
- q.parameters = q.parameters || parameters;
32657
- q.prepared = q.prepare && q.signature in statements;
32658
- q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
32659
- q.statement = q.prepared ? statements[q.signature] : { string, types, name: q.prepare ? statementId + statementCount++ : "" };
32660
- typeof options.debug === "function" && options.debug(id, string, parameters, types);
32661
- }
32662
- function write(x, fn) {
32663
- chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
32664
- if (fn || chunk.length >= 1024)
32665
- return nextWrite(fn);
32666
- nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
32667
- return true;
32668
- }
32669
- function nextWrite(fn) {
32670
- const x = socket.write(chunk, fn);
32671
- nextWriteTimer !== null && clearImmediate(nextWriteTimer);
32672
- chunk = nextWriteTimer = null;
32673
- return x;
32674
- }
32675
- function connectTimedOut() {
32676
- errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
32677
- socket.destroy();
32678
- }
32679
- async function secure() {
32680
- if (sslnegotiation !== "direct") {
32681
- write(SSLRequest);
32682
- const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
32683
- if (!canSSL && ssl === "prefer")
32684
- return connected();
32685
- }
32686
- const options = {
32687
- socket,
32688
- servername: net2.isIP(socket.host) ? undefined : socket.host
32689
- };
32690
- if (sslnegotiation === "direct")
32691
- options.ALPNProtocols = ["postgresql"];
32692
- if (ssl === "require" || ssl === "allow" || ssl === "prefer")
32693
- options.rejectUnauthorized = false;
32694
- else if (typeof ssl === "object")
32695
- Object.assign(options, ssl);
32696
- socket.removeAllListeners();
32697
- socket = tls.connect(options);
32698
- socket.on("secureConnect", connected);
32699
- socket.on("error", error);
32700
- socket.on("close", closed);
32701
- socket.on("drain", drain);
32702
- }
32703
- function drain() {
32704
- !query && onopen(connection);
32705
- }
32706
- function data(x) {
32707
- if (incomings) {
32708
- incomings.push(x);
32709
- remaining -= x.length;
32710
- if (remaining > 0)
32711
- return;
32712
- }
32713
- incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
32714
- while (incoming.length > 4) {
32715
- length = incoming.readUInt32BE(1);
32716
- if (length >= incoming.length) {
32717
- remaining = length - incoming.length;
32718
- incomings = [incoming];
32719
- break;
32720
- }
32721
- try {
32722
- handle(incoming.subarray(0, length + 1));
32723
- } catch (e) {
32724
- query && (query.cursorFn || query.describeFirst) && write(Sync);
32725
- errored(e);
32726
- }
32727
- incoming = incoming.subarray(length + 1);
32728
- remaining = 0;
32729
- incomings = null;
32730
- }
32731
- }
32732
- async function connect() {
32733
- terminated = false;
32734
- backendParameters = {};
32735
- socket || (socket = await createSocket());
32736
- if (!socket)
32737
- return;
32738
- connectTimer.start();
32739
- if (options.socket)
32740
- return ssl ? secure() : connected();
32741
- socket.on("connect", ssl ? secure : connected);
32742
- if (options.path)
32743
- return socket.connect(options.path);
32744
- socket.ssl = ssl;
32745
- socket.connect(port[hostIndex], host[hostIndex]);
32746
- socket.host = host[hostIndex];
32747
- socket.port = port[hostIndex];
32748
- hostIndex = (hostIndex + 1) % port.length;
32749
- }
32750
- function reconnect() {
32751
- setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
32752
- }
32753
- function connected() {
32754
- try {
32755
- statements = {};
32756
- needsTypes = options.fetch_types;
32757
- statementId = Math.random().toString(36).slice(2);
32758
- statementCount = 1;
32759
- lifeTimer.start();
32760
- socket.on("data", data);
32761
- keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive);
32762
- const s = StartupMessage();
32763
- write(s);
32764
- } catch (err) {
32765
- error(err);
32766
- }
32767
- }
32768
- function error(err) {
32769
- if (connection.queue === queues.connecting && options.host[retries + 1])
32770
- return;
32771
- errored(err);
32772
- while (sent.length)
32773
- queryError(sent.shift(), err);
32774
- }
32775
- function errored(err) {
32776
- stream && (stream.destroy(err), stream = null);
32777
- query && queryError(query, err);
32778
- initial && (queryError(initial, err), initial = null);
32779
- }
32780
- function queryError(query, err) {
32781
- if (query.reserve)
32782
- return query.reject(err);
32783
- if (!err || typeof err !== "object")
32784
- err = new Error(err);
32785
- "query" in err || "parameters" in err || Object.defineProperties(err, {
32786
- stack: { value: err.stack + query.origin.replace(/.*\n/, `
32787
- `), enumerable: options.debug },
32788
- query: { value: query.string, enumerable: options.debug },
32789
- parameters: { value: query.parameters, enumerable: options.debug },
32790
- args: { value: query.args, enumerable: options.debug },
32791
- types: { value: query.statement && query.statement.types, enumerable: options.debug }
32792
- });
32793
- query.reject(err);
32794
- }
32795
- function end() {
32796
- return ending || (!connection.reserved && onend(connection), !connection.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r));
32797
- }
32798
- function terminate() {
32799
- terminated = true;
32800
- if (stream || query || initial || sent.length)
32801
- error(Errors.connection("CONNECTION_DESTROYED", options));
32802
- clearImmediate(nextWriteTimer);
32803
- if (socket) {
32804
- socket.removeListener("data", data);
32805
- socket.removeListener("connect", connected);
32806
- socket.readyState === "open" && socket.end(bytes_default().X().end());
32807
- }
32808
- ended && (ended(), ending = ended = null);
32809
- }
32810
- async function closed(hadError) {
32811
- incoming = Buffer.alloc(0);
32812
- remaining = 0;
32813
- incomings = null;
32814
- clearImmediate(nextWriteTimer);
32815
- socket.removeListener("data", data);
32816
- socket.removeListener("connect", connected);
32817
- idleTimer.cancel();
32818
- lifeTimer.cancel();
32819
- connectTimer.cancel();
32820
- socket.removeAllListeners();
32821
- socket = null;
32822
- if (initial)
32823
- return reconnect();
32824
- !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
32825
- closedTime = performance.now();
32826
- hadError && options.shared.retries++;
32827
- delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1000;
32828
- onclose(connection, Errors.connection("CONNECTION_CLOSED", options, socket));
32829
- }
32830
- function handle(xs, x = xs[0]) {
32831
- (x === 68 ? DataRow : x === 100 ? CopyData : x === 65 ? NotificationResponse : x === 83 ? ParameterStatus : x === 90 ? ReadyForQuery : x === 67 ? CommandComplete : x === 50 ? BindComplete : x === 49 ? ParseComplete : x === 116 ? ParameterDescription : x === 84 ? RowDescription : x === 82 ? Authentication : x === 110 ? NoData : x === 75 ? BackendKeyData : x === 69 ? ErrorResponse : x === 115 ? PortalSuspended : x === 51 ? CloseComplete : x === 71 ? CopyInResponse : x === 78 ? NoticeResponse : x === 72 ? CopyOutResponse : x === 99 ? CopyDone : x === 73 ? EmptyQueryResponse : x === 86 ? FunctionCallResponse : x === 118 ? NegotiateProtocolVersion : x === 87 ? CopyBothResponse : UnknownMessage)(xs);
32832
- }
32833
- function DataRow(x) {
32834
- let index = 7;
32835
- let length;
32836
- let column;
32837
- let value;
32838
- const row = query.isRaw ? new Array(query.statement.columns.length) : {};
32839
- for (let i = 0;i < query.statement.columns.length; i++) {
32840
- column = query.statement.columns[i];
32841
- length = x.readInt32BE(index);
32842
- index += 4;
32843
- value = length === -1 ? null : query.isRaw === true ? x.subarray(index, index += length) : column.parser === undefined ? x.toString("utf8", index, index += length) : column.parser.array === true ? column.parser(x.toString("utf8", index + 1, index += length)) : column.parser(x.toString("utf8", index, index += length));
32844
- query.isRaw ? row[i] = query.isRaw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
32845
- }
32846
- query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
32847
- }
32848
- function ParameterStatus(x) {
32849
- const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N);
32850
- backendParameters[k] = v;
32851
- if (options.parameters[k] !== v) {
32852
- options.parameters[k] = v;
32853
- onparameter && onparameter(k, v);
32854
- }
32855
- }
32856
- function ReadyForQuery(x) {
32857
- if (query) {
32858
- if (errorResponse) {
32859
- query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
32860
- } else {
32861
- query.resolve(results || result);
32862
- }
32863
- } else if (errorResponse) {
32864
- errored(errorResponse);
32865
- }
32866
- query = results = errorResponse = null;
32867
- result = new Result;
32868
- connectTimer.cancel();
32869
- if (initial) {
32870
- if (target_session_attrs) {
32871
- if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
32872
- return fetchState();
32873
- else if (tryNext(target_session_attrs, backendParameters))
32874
- return terminate();
32875
- }
32876
- if (needsTypes) {
32877
- initial.reserve && (initial = null);
32878
- return fetchArrayTypes();
32879
- }
32880
- initial && !initial.reserve && execute(initial);
32881
- options.shared.retries = retries = 0;
32882
- initial = null;
32883
- return;
32884
- }
32885
- while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
32886
- Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
32887
- if (query)
32888
- return;
32889
- connection.reserved ? !connection.reserved.release && x[5] === 73 ? ending ? terminate() : (connection.reserved = null, onopen(connection)) : connection.reserved() : ending ? terminate() : onopen(connection);
32890
- }
32891
- function CommandComplete(x) {
32892
- rows = 0;
32893
- for (let i = x.length - 1;i > 0; i--) {
32894
- if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
32895
- result.count = +x.toString("utf8", i + 1, x.length - 1);
32896
- if (x[i - 1] >= 65) {
32897
- result.command = x.toString("utf8", 5, i);
32898
- result.state = backend;
32899
- break;
32900
- }
32901
- }
32902
- final && (final(), final = null);
32903
- if (result.command === "BEGIN" && max !== 1 && !connection.reserved)
32904
- return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
32905
- if (query.options.simple)
32906
- return BindComplete();
32907
- if (query.cursorFn) {
32908
- result.count && query.cursorFn(result);
32909
- write(Sync);
32910
- }
32911
- }
32912
- function ParseComplete() {
32913
- query.parsing = false;
32914
- }
32915
- function BindComplete() {
32916
- !result.statement && (result.statement = query.statement);
32917
- result.columns = query.statement.columns;
32918
- }
32919
- function ParameterDescription(x) {
32920
- const length = x.readUInt16BE(5);
32921
- for (let i = 0;i < length; ++i)
32922
- !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
32923
- query.prepare && (statements[query.signature] = query.statement);
32924
- query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
32925
- }
32926
- function RowDescription(x) {
32927
- if (result.command) {
32928
- results = results || [result];
32929
- results.push(result = new Result);
32930
- result.count = null;
32931
- query.statement.columns = null;
32932
- }
32933
- const length = x.readUInt16BE(5);
32934
- let index = 7;
32935
- let start;
32936
- query.statement.columns = Array(length);
32937
- for (let i = 0;i < length; ++i) {
32938
- start = index;
32939
- while (x[index++] !== 0)
32940
- ;
32941
- const table = x.readUInt32BE(index);
32942
- const number = x.readUInt16BE(index + 4);
32943
- const type = x.readUInt32BE(index + 6);
32944
- query.statement.columns[i] = {
32945
- name: transform.column.from ? transform.column.from(x.toString("utf8", start, index - 1)) : x.toString("utf8", start, index - 1),
32946
- parser: parsers[type],
32947
- table,
32948
- number,
32949
- type
32950
- };
32951
- index += 18;
32952
- }
32953
- result.statement = query.statement;
32954
- if (query.onlyDescribe)
32955
- return query.resolve(query.statement), write(Sync);
32956
- }
32957
- async function Authentication(x, type = x.readUInt32BE(5)) {
32958
- (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop5)(x, type);
32959
- }
32960
- async function AuthenticationCleartextPassword() {
32961
- const payload = await Pass();
32962
- write(bytes_default().p().str(payload).z(1).end());
32963
- }
32964
- async function AuthenticationMD5Password(x) {
32965
- const payload = "md5" + await md5(Buffer.concat([
32966
- Buffer.from(await md5(await Pass() + user)),
32967
- x.subarray(9)
32968
- ]));
32969
- write(bytes_default().p().str(payload).z(1).end());
32970
- }
32971
- async function SASL() {
32972
- nonce = (await crypto2.randomBytes(18)).toString("base64");
32973
- bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N);
32974
- const i = bytes_default.i;
32975
- write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end());
32976
- }
32977
- async function SASLContinue(x) {
32978
- const res = x.toString("utf8", 9).split(",").reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {});
32979
- const saltedPassword = await crypto2.pbkdf2Sync(await Pass(), Buffer.from(res.s, "base64"), parseInt(res.i), 32, "sha256");
32980
- const clientKey = await hmac(saltedPassword, "Client Key");
32981
- const auth = "n=*,r=" + nonce + "," + "r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
32982
- serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64");
32983
- const payload = "c=biws,r=" + res.r + ",p=" + xor(clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))).toString("base64");
32984
- write(bytes_default().p().str(payload).end());
32985
- }
32986
- function SASLFinal(x) {
32987
- if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature)
32988
- return;
32989
- errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
32990
- socket.destroy();
32991
- }
32992
- function Pass() {
32993
- return Promise.resolve(typeof options.pass === "function" ? options.pass() : options.pass);
32994
- }
32995
- function NoData() {
32996
- result.statement = query.statement;
32997
- result.statement.columns = [];
32998
- if (query.onlyDescribe)
32999
- return query.resolve(query.statement), write(Sync);
33000
- }
33001
- function BackendKeyData(x) {
33002
- backend.pid = x.readUInt32BE(5);
33003
- backend.secret = x.readUInt32BE(9);
33004
- }
33005
- async function fetchArrayTypes() {
33006
- needsTypes = false;
33007
- const types = await new Query([`
33008
- select b.oid, b.typarray
33009
- from pg_catalog.pg_type a
33010
- left join pg_catalog.pg_type b on b.oid = a.typelem
33011
- where a.typcategory = 'A'
33012
- group by b.oid, b.typarray
33013
- order by b.oid
33014
- `], [], execute);
33015
- types.forEach(({ oid, typarray }) => addArrayType(oid, typarray));
33016
- }
33017
- function addArrayType(oid, typarray) {
33018
- if (!!options.parsers[typarray] && !!options.serializers[typarray])
33019
- return;
33020
- const parser = options.parsers[oid];
33021
- options.shared.typeArrayMap[oid] = typarray;
33022
- options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
33023
- options.parsers[typarray].array = true;
33024
- options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
33025
- }
33026
- function tryNext(x, xs) {
33027
- return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
33028
- }
33029
- function fetchState() {
33030
- const query = new Query([`
33031
- show transaction_read_only;
33032
- select pg_catalog.pg_is_in_recovery()
33033
- `], [], execute, null, { simple: true });
33034
- query.resolve = ([[a], [b]]) => {
33035
- backendParameters.default_transaction_read_only = a.transaction_read_only;
33036
- backendParameters.in_hot_standby = b.pg_is_in_recovery ? "on" : "off";
33037
- };
33038
- query.execute();
33039
- }
33040
- function ErrorResponse(x) {
33041
- if (query) {
33042
- (query.cursorFn || query.describeFirst) && write(Sync);
33043
- errorResponse = Errors.postgres(parseError(x));
33044
- } else {
33045
- errored(Errors.postgres(parseError(x)));
33046
- }
33047
- }
33048
- function retry(q, error) {
33049
- delete statements[q.signature];
33050
- q.retried = error;
33051
- execute(q);
33052
- }
33053
- function NotificationResponse(x) {
33054
- if (!onnotify)
33055
- return;
33056
- let index = 9;
33057
- while (x[index++] !== 0)
33058
- ;
33059
- onnotify(x.toString("utf8", 9, index - 1), x.toString("utf8", index, x.length - 1));
33060
- }
33061
- async function PortalSuspended() {
33062
- try {
33063
- const x = await Promise.resolve(query.cursorFn(result));
33064
- rows = 0;
33065
- x === CLOSE ? write(Close(query.portal)) : (result = new Result, write(Execute("", query.cursorRows)));
33066
- } catch (err) {
33067
- write(Sync);
33068
- query.reject(err);
33069
- }
33070
- }
33071
- function CloseComplete() {
33072
- result.count && query.cursorFn(result);
33073
- query.resolve(result);
33074
- }
33075
- function CopyInResponse() {
33076
- stream = new Stream.Writable({
33077
- autoDestroy: true,
33078
- write(chunk, encoding, callback) {
33079
- socket.write(bytes_default().d().raw(chunk).end(), callback);
33080
- },
33081
- destroy(error, callback) {
33082
- callback(error);
33083
- socket.write(bytes_default().f().str(error + bytes_default.N).end());
33084
- stream = null;
33085
- },
33086
- final(callback) {
33087
- socket.write(bytes_default().c().end());
33088
- final = callback;
33089
- stream = null;
33090
- }
33091
- });
33092
- query.resolve(stream);
33093
- }
33094
- function CopyOutResponse() {
33095
- stream = new Stream.Readable({
33096
- read() {
33097
- socket.resume();
33098
- }
33099
- });
33100
- query.resolve(stream);
33101
- }
33102
- function CopyBothResponse() {
33103
- stream = new Stream.Duplex({
33104
- autoDestroy: true,
33105
- read() {
33106
- socket.resume();
33107
- },
33108
- write(chunk, encoding, callback) {
33109
- socket.write(bytes_default().d().raw(chunk).end(), callback);
33110
- },
33111
- destroy(error, callback) {
33112
- callback(error);
33113
- socket.write(bytes_default().f().str(error + bytes_default.N).end());
33114
- stream = null;
33115
- },
33116
- final(callback) {
33117
- socket.write(bytes_default().c().end());
33118
- final = callback;
33119
- }
33120
- });
33121
- query.resolve(stream);
33122
- }
33123
- function CopyData(x) {
33124
- stream && (stream.push(x.subarray(5)) || socket.pause());
33125
- }
33126
- function CopyDone() {
33127
- stream && stream.push(null);
33128
- stream = null;
33129
- }
33130
- function NoticeResponse(x) {
33131
- onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
33132
- }
33133
- function EmptyQueryResponse() {}
33134
- function FunctionCallResponse() {
33135
- errored(Errors.notSupported("FunctionCallResponse"));
33136
- }
33137
- function NegotiateProtocolVersion() {
33138
- errored(Errors.notSupported("NegotiateProtocolVersion"));
33139
- }
33140
- function UnknownMessage(x) {
33141
- console.error("Postgres.js : Unknown Message:", x[0]);
33142
- }
33143
- function UnknownAuth(x, type) {
33144
- console.error("Postgres.js : Unknown Auth:", type);
33145
- }
33146
- function Bind(parameters, types, statement = "", portal = "") {
33147
- let prev, type;
33148
- bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length);
33149
- parameters.forEach((x, i) => {
33150
- if (x === null)
33151
- return bytes_default.i32(4294967295);
33152
- type = types[i];
33153
- parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
33154
- prev = bytes_default.i;
33155
- bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev);
33156
- });
33157
- bytes_default.i16(0);
33158
- return bytes_default.end();
33159
- }
33160
- function Parse(str, parameters, types, name = "") {
33161
- bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length);
33162
- parameters.forEach((x, i) => bytes_default.i32(types[i] || 0));
33163
- return bytes_default.end();
33164
- }
33165
- function Describe(x, name = "") {
33166
- return bytes_default().D().str(x).str(name + bytes_default.N).end();
33167
- }
33168
- function Execute(portal = "", rows = 0) {
33169
- return Buffer.concat([
33170
- bytes_default().E().str(portal + bytes_default.N).i32(rows).end(),
33171
- Flush
33172
- ]);
33173
- }
33174
- function Close(portal = "") {
33175
- return Buffer.concat([
33176
- bytes_default().C().str("P").str(portal + bytes_default.N).end(),
33177
- bytes_default().S().end()
33178
- ]);
33179
- }
33180
- function StartupMessage() {
33181
- return cancelMessage || bytes_default().inc(4).i16(3).z(2).str(Object.entries(Object.assign({
33182
- user,
33183
- database,
33184
- client_encoding: "UTF8"
33185
- }, options.connection)).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N)).z(2).end(0);
33186
- }
33187
- }
33188
- function parseError(x) {
33189
- const error = {};
33190
- let start = 5;
33191
- for (let i = 5;i < x.length - 1; i++) {
33192
- if (x[i] === 0) {
33193
- error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
33194
- start = i + 1;
33195
- }
33196
- }
33197
- return error;
33198
- }
33199
- function md5(x) {
33200
- return crypto2.createHash("md5").update(x).digest("hex");
33201
- }
33202
- function hmac(key, x) {
33203
- return crypto2.createHmac("sha256", key).update(x).digest();
33204
- }
33205
- function sha256(x) {
33206
- return crypto2.createHash("sha256").update(x).digest();
33207
- }
33208
- function xor(a, b) {
33209
- const length = Math.max(a.length, b.length);
33210
- const buffer = Buffer.allocUnsafe(length);
33211
- for (let i = 0;i < length; i++)
33212
- buffer[i] = a[i] ^ b[i];
33213
- return buffer;
33214
- }
33215
- function timer2(fn, seconds) {
33216
- seconds = typeof seconds === "function" ? seconds() : seconds;
33217
- if (!seconds)
33218
- return { cancel: noop5, start: noop5 };
33219
- let timer;
33220
- return {
33221
- cancel() {
33222
- timer && (clearTimeout(timer), timer = null);
33223
- },
33224
- start() {
33225
- timer && clearTimeout(timer);
33226
- timer = setTimeout(done, seconds * 1000, arguments);
33227
- }
33228
- };
33229
- function done(args) {
33230
- fn.apply(null, args);
33231
- timer = null;
33232
- }
33233
- }
33234
- var connection_default, uid = 1, Sync, Flush, SSLRequest, ExecuteUnnamed, DescribeUnnamed, noop5 = () => {}, retryRoutines, errorFields;
33235
- var init_connection = __esm(() => {
33236
- init_types4();
33237
- init_errors2();
33238
- init_result2();
33239
- init_queue();
33240
- init_query();
33241
- init_bytes();
33242
- connection_default = Connection;
33243
- Sync = bytes_default().S().end();
33244
- Flush = bytes_default().H().end();
33245
- SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
33246
- ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
33247
- DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
33248
- retryRoutines = new Set([
33249
- "FetchPreparedStatement",
33250
- "RevalidateCachedQuery",
33251
- "transformAssignedExpr"
33252
- ]);
33253
- errorFields = {
33254
- 83: "severity_local",
33255
- 86: "severity",
33256
- 67: "code",
33257
- 77: "message",
33258
- 68: "detail",
33259
- 72: "hint",
33260
- 80: "position",
33261
- 112: "internal_position",
33262
- 113: "internal_query",
33263
- 87: "where",
33264
- 115: "schema_name",
33265
- 116: "table_name",
33266
- 99: "column_name",
33267
- 100: "data type_name",
33268
- 110: "constraint_name",
33269
- 70: "file",
33270
- 76: "line",
33271
- 82: "routine"
33272
- };
33273
- });
33274
-
33275
- // ../../node_modules/postgres/src/subscribe.js
33276
- function Subscribe(postgres, options) {
33277
- const subscribers = new Map, slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
33278
- let connection, stream, ended = false;
33279
- const sql = subscribe.sql = postgres({
33280
- ...options,
33281
- transform: { column: {}, value: {}, row: {} },
33282
- max: 1,
33283
- fetch_types: false,
33284
- idle_timeout: null,
33285
- max_lifetime: null,
33286
- connection: {
33287
- ...options.connection,
33288
- replication: "database"
33289
- },
33290
- onclose: async function() {
33291
- if (ended)
33292
- return;
33293
- stream = null;
33294
- state.pid = state.secret = undefined;
33295
- connected(await init(sql, slot, options.publications));
33296
- subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
33297
- },
33298
- no_subscribe: true
33299
- });
33300
- const { end, close } = sql;
33301
- sql.end = async () => {
33302
- ended = true;
33303
- stream && await new Promise((r) => (stream.once("close", r), stream.end()));
33304
- return end();
33305
- };
33306
- sql.close = async () => {
33307
- stream && await new Promise((r) => (stream.once("close", r), stream.end()));
33308
- return close();
33309
- };
33310
- return subscribe;
33311
- async function subscribe(event, fn, onsubscribe = noop6, onerror = noop6) {
33312
- event = parseEvent(event);
33313
- if (!connection)
33314
- connection = init(sql, slot, options.publications);
33315
- const subscriber = { fn, onsubscribe };
33316
- const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, new Set([subscriber])).get(event);
33317
- const unsubscribe = () => {
33318
- fns.delete(subscriber);
33319
- fns.size === 0 && subscribers.delete(event);
33320
- };
33321
- return connection.then((x) => {
33322
- connected(x);
33323
- onsubscribe();
33324
- stream && stream.on("error", onerror);
33325
- return { unsubscribe, state, sql };
33326
- });
33327
- }
33328
- function connected(x) {
33329
- stream = x.stream;
33330
- state.pid = x.state.pid;
33331
- state.secret = x.state.secret;
33332
- }
33333
- async function init(sql, slot, publications) {
33334
- if (!publications)
33335
- throw new Error("Missing publication names");
33336
- const xs = await sql.unsafe(`CREATE_REPLICATION_SLOT ${slot} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`);
33337
- const [x] = xs;
33338
- const stream = await sql.unsafe(`START_REPLICATION SLOT ${slot} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`).writable();
33339
- const state = {
33340
- lsn: Buffer.concat(x.consistent_point.split("/").map((x) => Buffer.from(("00000000" + x).slice(-8), "hex")))
33341
- };
33342
- stream.on("data", data);
33343
- stream.on("error", error);
33344
- stream.on("close", sql.close);
33345
- return { stream, state: xs.state };
33346
- function error(e) {
33347
- console.error("Unexpected error during logical streaming - reconnecting", e);
33348
- }
33349
- function data(x) {
33350
- if (x[0] === 119) {
33351
- parse(x.subarray(25), state, sql.options.parsers, handle, options.transform);
33352
- } else if (x[0] === 107 && x[17]) {
33353
- state.lsn = x.subarray(1, 9);
33354
- pong();
33355
- }
33356
- }
33357
- function handle(a, b) {
33358
- const path = b.relation.schema + "." + b.relation.table;
33359
- call("*", a, b);
33360
- call("*:" + path, a, b);
33361
- b.relation.keys.length && call("*:" + path + "=" + b.relation.keys.map((x) => a[x.name]), a, b);
33362
- call(b.command, a, b);
33363
- call(b.command + ":" + path, a, b);
33364
- b.relation.keys.length && call(b.command + ":" + path + "=" + b.relation.keys.map((x) => a[x.name]), a, b);
33365
- }
33366
- function pong() {
33367
- const x = Buffer.alloc(34);
33368
- x[0] = 114;
33369
- x.fill(state.lsn, 1);
33370
- x.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25);
33371
- stream.write(x);
33372
- }
33373
- }
33374
- function call(x, a, b) {
33375
- subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b, x));
33376
- }
33377
- }
33378
- function Time(x) {
33379
- return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000)));
33380
- }
33381
- function parse(x, state, parsers, handle, transform) {
33382
- const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
33383
- Object.entries({
33384
- R: (x) => {
33385
- let i = 1;
33386
- const r = state[x.readUInt32BE(i)] = {
33387
- schema: x.toString("utf8", i += 4, i = x.indexOf(0, i)) || "pg_catalog",
33388
- table: x.toString("utf8", i + 1, i = x.indexOf(0, i + 1)),
33389
- columns: Array(x.readUInt16BE(i += 2)),
33390
- keys: []
33391
- };
33392
- i += 2;
33393
- let columnIndex = 0, column;
33394
- while (i < x.length) {
33395
- column = r.columns[columnIndex++] = {
33396
- key: x[i++],
33397
- name: transform.column.from ? transform.column.from(x.toString("utf8", i, i = x.indexOf(0, i))) : x.toString("utf8", i, i = x.indexOf(0, i)),
33398
- type: x.readUInt32BE(i += 1),
33399
- parser: parsers[x.readUInt32BE(i)],
33400
- atttypmod: x.readUInt32BE(i += 4)
33401
- };
33402
- column.key && r.keys.push(column);
33403
- i += 4;
33404
- }
33405
- },
33406
- Y: () => {},
33407
- O: () => {},
33408
- B: (x) => {
33409
- state.date = Time(x.readBigInt64BE(9));
33410
- state.lsn = x.subarray(1, 9);
33411
- },
33412
- I: (x) => {
33413
- let i = 1;
33414
- const relation = state[x.readUInt32BE(i)];
33415
- const { row } = tuples(x, relation.columns, i += 7, transform);
33416
- handle(row, {
33417
- command: "insert",
33418
- relation
33419
- });
33420
- },
33421
- D: (x) => {
33422
- let i = 1;
33423
- const relation = state[x.readUInt32BE(i)];
33424
- i += 4;
33425
- const key = x[i] === 75;
33426
- handle(key || x[i] === 79 ? tuples(x, relation.columns, i += 3, transform).row : null, {
33427
- command: "delete",
33428
- relation,
33429
- key
33430
- });
33431
- },
33432
- U: (x) => {
33433
- let i = 1;
33434
- const relation = state[x.readUInt32BE(i)];
33435
- i += 4;
33436
- const key = x[i] === 75;
33437
- const xs = key || x[i] === 79 ? tuples(x, relation.columns, i += 3, transform) : null;
33438
- xs && (i = xs.i);
33439
- const { row } = tuples(x, relation.columns, i + 3, transform);
33440
- handle(row, {
33441
- command: "update",
33442
- relation,
33443
- key,
33444
- old: xs && xs.row
33445
- });
33446
- },
33447
- T: () => {},
33448
- C: () => {}
33449
- }).reduce(char, {})[x[0]](x);
33450
- }
33451
- function tuples(x, columns, xi, transform) {
33452
- let type, column, value;
33453
- const row = transform.raw ? new Array(columns.length) : {};
33454
- for (let i = 0;i < columns.length; i++) {
33455
- type = x[xi++];
33456
- column = columns[i];
33457
- value = type === 110 ? null : type === 117 ? undefined : column.parser === undefined ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)));
33458
- transform.raw ? row[i] = transform.raw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
33459
- }
33460
- return { i: xi, row: transform.row.from ? transform.row.from(row) : row };
33461
- }
33462
- function parseEvent(x) {
33463
- const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
33464
- if (!xs)
33465
- throw new Error("Malformed subscribe pattern: " + x);
33466
- const [, command, path, key] = xs;
33467
- return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
33468
- }
33469
- var noop6 = () => {};
33470
-
33471
- // ../../node_modules/postgres/src/large.js
33472
- import Stream2 from "stream";
33473
- function largeObject(sql, oid, mode = 131072 | 262144) {
33474
- return new Promise(async (resolve, reject) => {
33475
- await sql.begin(async (sql) => {
33476
- let finish;
33477
- !oid && ([{ oid }] = await sql`select lo_creat(-1) as oid`);
33478
- const [{ fd }] = await sql`select lo_open(${oid}, ${mode}) as fd`;
33479
- const lo = {
33480
- writable,
33481
- readable,
33482
- close: () => sql`select lo_close(${fd})`.then(finish),
33483
- tell: () => sql`select lo_tell64(${fd})`,
33484
- read: (x) => sql`select loread(${fd}, ${x}) as data`,
33485
- write: (x) => sql`select lowrite(${fd}, ${x})`,
33486
- truncate: (x) => sql`select lo_truncate64(${fd}, ${x})`,
33487
- seek: (x, whence = 0) => sql`select lo_lseek64(${fd}, ${x}, ${whence})`,
33488
- size: () => sql`
33489
- select
33490
- lo_lseek64(${fd}, location, 0) as position,
33491
- seek.size
33492
- from (
33493
- select
33494
- lo_lseek64($1, 0, 2) as size,
33495
- tell.location
33496
- from (select lo_tell64($1) as location) tell
33497
- ) seek
33498
- `
33499
- };
33500
- resolve(lo);
33501
- return new Promise(async (r) => finish = r);
33502
- async function readable({
33503
- highWaterMark = 2048 * 8,
33504
- start = 0,
33505
- end = Infinity
33506
- } = {}) {
33507
- let max = end - start;
33508
- start && await lo.seek(start);
33509
- return new Stream2.Readable({
33510
- highWaterMark,
33511
- async read(size) {
33512
- const l = size > max ? size - max : size;
33513
- max -= size;
33514
- const [{ data }] = await lo.read(l);
33515
- this.push(data);
33516
- if (data.length < size)
33517
- this.push(null);
33518
- }
33519
- });
33520
- }
33521
- async function writable({
33522
- highWaterMark = 2048 * 8,
33523
- start = 0
33524
- } = {}) {
33525
- start && await lo.seek(start);
33526
- return new Stream2.Writable({
33527
- highWaterMark,
33528
- write(chunk, encoding, callback) {
33529
- lo.write(chunk).then(() => callback(), callback);
33530
- }
33531
- });
33532
- }
33533
- }).catch(reject);
33534
- });
33535
- }
33536
- var init_large = () => {};
33537
-
33538
- // ../../node_modules/postgres/src/index.js
33539
- import os4 from "os";
33540
- import fs7 from "fs";
33541
- function Postgres(a, b) {
33542
- const options = parseOptions(a, b), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options });
33543
- let ending = false;
33544
- const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full };
33545
- const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose }));
33546
- const sql = Sql(handler);
33547
- Object.assign(sql, {
33548
- get parameters() {
33549
- return options.parameters;
33550
- },
33551
- largeObject: largeObject.bind(null, sql),
33552
- subscribe,
33553
- CLOSE,
33554
- END: CLOSE,
33555
- PostgresError,
33556
- options,
33557
- reserve,
33558
- listen,
33559
- begin,
33560
- close,
33561
- end
33562
- });
33563
- return sql;
33564
- function Sql(handler) {
33565
- handler.debug = options.debug;
33566
- Object.entries(options.types).reduce((acc, [name, type]) => {
33567
- acc[name] = (x) => new Parameter(x, type.to);
33568
- return acc;
33569
- }, typed);
33570
- Object.assign(sql, {
33571
- types: typed,
33572
- typed,
33573
- unsafe,
33574
- notify,
33575
- array,
33576
- json,
33577
- file
33578
- });
33579
- return sql;
33580
- function typed(value, type) {
33581
- return new Parameter(value, type);
33582
- }
33583
- function sql(strings, ...args) {
33584
- const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
33585
- return query;
33586
- }
33587
- function unsafe(string, args = [], options = {}) {
33588
- arguments.length === 2 && !Array.isArray(args) && (options = args, args = []);
33589
- const query = new Query([string], args, handler, cancel, {
33590
- prepare: false,
33591
- ...options,
33592
- simple: "simple" in options ? options.simple : args.length === 0
33593
- });
33594
- return query;
33595
- }
33596
- function file(path, args = [], options = {}) {
33597
- arguments.length === 2 && !Array.isArray(args) && (options = args, args = []);
33598
- const query = new Query([], args, (query) => {
33599
- fs7.readFile(path, "utf8", (err, string) => {
33600
- if (err)
33601
- return query.reject(err);
33602
- query.strings = [string];
33603
- handler(query);
33604
- });
33605
- }, cancel, {
33606
- ...options,
33607
- simple: "simple" in options ? options.simple : args.length === 0
33608
- });
33609
- return query;
33610
- }
33611
- }
33612
- async function listen(name, fn, onlisten) {
33613
- const listener = { fn, onlisten };
33614
- const sql = listen.sql || (listen.sql = Postgres({
33615
- ...options,
33616
- max: 1,
33617
- idle_timeout: null,
33618
- max_lifetime: null,
33619
- fetch_types: false,
33620
- onclose() {
33621
- Object.entries(listen.channels).forEach(([name, { listeners }]) => {
33622
- delete listen.channels[name];
33623
- Promise.all(listeners.map((l) => listen(name, l.fn, l.onlisten).catch(() => {})));
33624
- });
33625
- },
33626
- onnotify(c, x) {
33627
- c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
33628
- }
33629
- }));
33630
- const channels = listen.channels || (listen.channels = {}), exists = name in channels;
33631
- if (exists) {
33632
- channels[name].listeners.push(listener);
33633
- const result = await channels[name].result;
33634
- listener.onlisten && listener.onlisten();
33635
- return { state: result.state, unlisten };
33636
- }
33637
- channels[name] = { result: sql`listen ${sql.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] };
33638
- const result = await channels[name].result;
33639
- listener.onlisten && listener.onlisten();
33640
- return { state: result.state, unlisten };
33641
- async function unlisten() {
33642
- if (name in channels === false)
33643
- return;
33644
- channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
33645
- if (channels[name].listeners.length)
33646
- return;
33647
- delete channels[name];
33648
- return sql`unlisten ${sql.unsafe('"' + name.replace(/"/g, '""') + '"')}`;
33649
- }
33650
- }
33651
- async function notify(channel, payload) {
33652
- return await sql`select pg_notify(${channel}, ${"" + payload})`;
33653
- }
33654
- async function reserve() {
33655
- const queue = queue_default();
33656
- const c = open.length ? open.shift() : await new Promise((resolve, reject) => {
33657
- const query = { reserve: resolve, reject };
33658
- queries.push(query);
33659
- closed.length && connect(closed.shift(), query);
33660
- });
33661
- move(c, reserved);
33662
- c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
33663
- c.reserved.release = true;
33664
- const sql = Sql(handler);
33665
- sql.release = () => {
33666
- c.reserved = null;
33667
- onopen(c);
33668
- };
33669
- return sql;
33670
- function handler(q) {
33671
- c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
33672
- }
33673
- }
33674
- async function begin(options, fn) {
33675
- !fn && (fn = options, options = "");
33676
- const queries = queue_default();
33677
- let savepoints = 0, connection, prepare = null;
33678
- try {
33679
- await sql.unsafe("begin " + options.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute();
33680
- return await Promise.race([
33681
- scope(connection, fn),
33682
- new Promise((_, reject) => connection.onclose = reject)
33683
- ]);
33684
- } catch (error) {
33685
- throw error;
33686
- }
33687
- async function scope(c, fn, name) {
33688
- const sql = Sql(handler);
33689
- sql.savepoint = savepoint;
33690
- sql.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
33691
- let uncaughtError, result;
33692
- name && await sql`savepoint ${sql(name)}`;
33693
- try {
33694
- result = await new Promise((resolve, reject) => {
33695
- const x = fn(sql);
33696
- Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
33697
- });
33698
- if (uncaughtError)
33699
- throw uncaughtError;
33700
- } catch (e) {
33701
- await (name ? sql`rollback to ${sql(name)}` : sql`rollback`);
33702
- throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
33703
- }
33704
- if (!name) {
33705
- prepare ? await sql`prepare transaction '${sql.unsafe(prepare)}'` : await sql`commit`;
33706
- }
33707
- return result;
33708
- function savepoint(name, fn) {
33709
- if (name && Array.isArray(name.raw))
33710
- return savepoint((sql) => sql.apply(sql, arguments));
33711
- arguments.length === 1 && (fn = name, name = null);
33712
- return scope(c, fn, "s" + savepoints++ + (name ? "_" + name : ""));
33713
- }
33714
- function handler(q) {
33715
- q.catch((e) => uncaughtError || (uncaughtError = e));
33716
- c.queue === full ? queries.push(q) : c.execute(q) || move(c, full);
33717
- }
33718
- }
33719
- function onexecute(c) {
33720
- connection = c;
33721
- move(c, reserved);
33722
- c.reserved = () => queries.length ? c.execute(queries.shift()) : move(c, reserved);
33723
- }
33724
- }
33725
- function move(c, queue) {
33726
- c.queue.remove(c);
33727
- queue.push(c);
33728
- c.queue = queue;
33729
- queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
33730
- return c;
33731
- }
33732
- function json(x) {
33733
- return new Parameter(x, 3802);
33734
- }
33735
- function array(x, type) {
33736
- if (!Array.isArray(x))
33737
- return array(Array.from(arguments));
33738
- return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
33739
- }
33740
- function handler(query) {
33741
- if (ending)
33742
- return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
33743
- if (open.length)
33744
- return go(open.shift(), query);
33745
- if (closed.length)
33746
- return connect(closed.shift(), query);
33747
- busy.length ? go(busy.shift(), query) : queries.push(query);
33748
- }
33749
- function go(c, query) {
33750
- return c.execute(query) ? move(c, busy) : move(c, full);
33751
- }
33752
- function cancel(query) {
33753
- return new Promise((resolve, reject) => {
33754
- query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = { resolve, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve());
33755
- });
33756
- }
33757
- async function end({ timeout = null } = {}) {
33758
- if (ending)
33759
- return ending;
33760
- await 1;
33761
- let timer;
33762
- return ending = Promise.race([
33763
- new Promise((r) => timeout !== null && (timer = setTimeout(destroy, timeout * 1000, r))),
33764
- Promise.all(connections.map((c) => c.end()).concat(listen.sql ? listen.sql.end({ timeout: 0 }) : [], subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []))
33765
- ]).then(() => clearTimeout(timer));
33766
- }
33767
- async function close() {
33768
- await Promise.all(connections.map((c) => c.end()));
33769
- }
33770
- async function destroy(resolve) {
33771
- await Promise.all(connections.map((c) => c.terminate()));
33772
- while (queries.length)
33773
- queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
33774
- resolve();
33775
- }
33776
- function connect(c, query) {
33777
- move(c, connecting);
33778
- c.connect(query);
33779
- return c;
33780
- }
33781
- function onend(c) {
33782
- move(c, ended);
33783
- }
33784
- function onopen(c) {
33785
- if (queries.length === 0)
33786
- return move(c, open);
33787
- let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
33788
- while (ready && queries.length && max-- > 0) {
33789
- const query = queries.shift();
33790
- if (query.reserve)
33791
- return query.reserve(c);
33792
- ready = c.execute(query);
33793
- }
33794
- ready ? move(c, busy) : move(c, full);
33795
- }
33796
- function onclose(c, e) {
33797
- move(c, closed);
33798
- c.reserved = null;
33799
- c.onclose && (c.onclose(e), c.onclose = null);
33800
- options.onclose && options.onclose(c.id);
33801
- queries.length && connect(c, queries.shift());
33802
- }
33803
- }
33804
- function parseOptions(a, b) {
33805
- if (a && a.shared)
33806
- return a;
33807
- const env = process.env, o = (!a || typeof a === "string" ? b : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {}), host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || "localhost", port = o.port || url.port || env.PGPORT || 5432, user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername();
33808
- o.no_prepare && (o.prepare = false);
33809
- query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
33810
- "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
33811
- query.sslrootcert === "system" && (query.ssl = "verify-full");
33812
- const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
33813
- const defaults = {
33814
- max: globalThis.Cloudflare ? 3 : 10,
33815
- ssl: false,
33816
- sslnegotiation: null,
33817
- idle_timeout: null,
33818
- connect_timeout: 30,
33819
- max_lifetime,
33820
- max_pipeline: 100,
33821
- backoff,
33822
- keep_alive: 60,
33823
- prepare: true,
33824
- debug: false,
33825
- fetch_types: true,
33826
- publications: "alltables",
33827
- target_session_attrs: null
33828
- };
33829
- return {
33830
- host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
33831
- port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
33832
- path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
33833
- database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
33834
- user,
33835
- pass: o.pass || o.password || url.password || env.PGPASSWORD || "",
33836
- ...Object.entries(defaults).reduce((acc, [k, d]) => {
33837
- const value = k in o ? o[k] : (k in query) ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
33838
- acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
33839
- return acc;
33840
- }, {}),
33841
- connection: {
33842
- application_name: env.PGAPPNAME || "postgres.js",
33843
- ...o.connection,
33844
- ...Object.entries(query).reduce((acc, [k, v]) => ((k in defaults) || (acc[k] = v), acc), {})
33845
- },
33846
- types: o.types || {},
33847
- target_session_attrs: tsa(o, url, env),
33848
- onnotice: o.onnotice,
33849
- onnotify: o.onnotify,
33850
- onclose: o.onclose,
33851
- onparameter: o.onparameter,
33852
- socket: o.socket,
33853
- transform: parseTransform(o.transform || { undefined: undefined }),
33854
- parameters: {},
33855
- shared: { retries: 0, typeArrayMap: {} },
33856
- ...mergeUserTypes(o.types)
33857
- };
33858
- }
33859
- function tsa(o, url, env) {
33860
- const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
33861
- if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x))
33862
- return x;
33863
- throw new Error("target_session_attrs " + x + " is not supported");
33864
- }
33865
- function backoff(retries) {
33866
- return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20);
33867
- }
33868
- function max_lifetime() {
33869
- return 60 * (30 + Math.random() * 30);
33870
- }
33871
- function parseTransform(x) {
33872
- return {
33873
- undefined: x.undefined,
33874
- column: {
33875
- from: typeof x.column === "function" ? x.column : x.column && x.column.from,
33876
- to: x.column && x.column.to
33877
- },
33878
- value: {
33879
- from: typeof x.value === "function" ? x.value : x.value && x.value.from,
33880
- to: x.value && x.value.to
33881
- },
33882
- row: {
33883
- from: typeof x.row === "function" ? x.row : x.row && x.row.from,
33884
- to: x.row && x.row.to
33885
- }
33886
- };
33887
- }
33888
- function parseUrl(url) {
33889
- if (!url || typeof url !== "string")
33890
- return { url: { searchParams: new Map } };
33891
- let host = url;
33892
- host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
33893
- host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
33894
- const urlObj = new URL(url.replace(host, host.split(",")[0]));
33895
- return {
33896
- url: {
33897
- username: decodeURIComponent(urlObj.username),
33898
- password: decodeURIComponent(urlObj.password),
33899
- host: urlObj.host,
33900
- hostname: urlObj.hostname,
33901
- port: urlObj.port,
33902
- pathname: urlObj.pathname,
33903
- searchParams: urlObj.searchParams
33904
- },
33905
- multihost: host.indexOf(",") > -1 && host
33906
- };
33907
- }
33908
- function osUsername() {
33909
- try {
33910
- return os4.userInfo().username;
33911
- } catch (_) {
33912
- return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
33913
- }
33914
- }
33915
- var src_default;
33916
- var init_src = __esm(() => {
33917
- init_types4();
33918
- init_connection();
33919
- init_query();
33920
- init_queue();
33921
- init_errors2();
33922
- init_large();
33923
- Object.assign(Postgres, {
33924
- PostgresError,
33925
- toPascal,
33926
- pascal,
33927
- toCamel,
33928
- camel,
33929
- toKebab,
33930
- kebab,
33931
- fromPascal,
33932
- fromCamel,
33933
- fromKebab,
33934
- BigInt: {
33935
- to: 20,
33936
- from: [20],
33937
- parse: (x) => BigInt(x),
33938
- serialize: (x) => x.toString()
33939
- }
33940
- });
33941
- src_default = Postgres;
33942
- });
33943
-
33944
31798
  // src/lib/dev-state.ts
33945
- import { homedir as homedir4 } from "node:os";
33946
- import { join as join12 } from "node:path";
31799
+ import { homedir as homedir3 } from "node:os";
31800
+ import { join as join11 } from "node:path";
33947
31801
  function getLogsDir() {
33948
31802
  return LOGS_DIR;
33949
31803
  }
@@ -33968,9 +31822,9 @@ function isProcessRunning(pid) {
33968
31822
  }
33969
31823
  var STATE_DIR, DEV_STATE_PATH, LOGS_DIR;
33970
31824
  var init_dev_state = __esm(() => {
33971
- STATE_DIR = join12(homedir4(), ".secondlayer");
33972
- DEV_STATE_PATH = join12(STATE_DIR, "dev.json");
33973
- LOGS_DIR = join12(STATE_DIR, "logs");
31825
+ STATE_DIR = join11(homedir3(), ".secondlayer");
31826
+ DEV_STATE_PATH = join11(STATE_DIR, "dev.json");
31827
+ LOGS_DIR = join11(STATE_DIR, "logs");
33974
31828
  });
33975
31829
 
33976
31830
  // ../../node_modules/commander/index.js
@@ -34034,7 +31888,7 @@ var {
34034
31888
  // package.json
34035
31889
  var package_default = {
34036
31890
  name: "@secondlayer/cli",
34037
- version: "22.3.4",
31891
+ version: "23.1.0",
34038
31892
  description: "Run a Stacks index on your own hardware — set it up, restore verified history, and keep it current.",
34039
31893
  repository: {
34040
31894
  type: "git",
@@ -34083,10 +31937,10 @@ var package_default = {
34083
31937
  "@inquirer/prompts": "^8.2.0",
34084
31938
  "@secondlayer/bundler": "^0.7.3",
34085
31939
  "@secondlayer/scaffold": "^1.6.3",
34086
- "@secondlayer/sdk": "^15.5.2",
34087
- "@secondlayer/shared": "^14.0.2",
31940
+ "@secondlayer/sdk": "^16.0.0",
31941
+ "@secondlayer/shared": "^15.0.0",
34088
31942
  "@secondlayer/stacks": "^6.5.3",
34089
- "@secondlayer/subgraphs": "^8.0.0",
31943
+ "@secondlayer/subgraphs": "^8.0.1",
34090
31944
  "@secondlayer/verify": "^0.6.1",
34091
31945
  esbuild: "^0.28.2",
34092
31946
  "smol-toml": "^1.9.1",
@@ -36692,6 +34546,144 @@ async function runRefill(opts) {
36692
34546
  }
36693
34547
  });
36694
34548
  }
34549
+ // src/commands/keys.ts
34550
+ init_http();
34551
+ init_output();
34552
+ init_session();
34553
+ import { resolveAccountKey as resolveAccountKey4 } from "@secondlayer/sdk";
34554
+ var MIN_ID_REF_LENGTH = 8;
34555
+ function rotatableKeys(keys) {
34556
+ return keys.filter((k) => k.status === "active" && k.product === "account");
34557
+ }
34558
+ function describeKey(key) {
34559
+ return `${key.id.slice(0, 8)} ${key.name ?? "(unnamed)"}`;
34560
+ }
34561
+ function resolveKeyRef(keys, ref) {
34562
+ const candidates = rotatableKeys(keys);
34563
+ const barePrefix = ref.replace(/…$/, "");
34564
+ const kinds = [
34565
+ (k) => k.id === ref || ref.length >= MIN_ID_REF_LENGTH && k.id.startsWith(ref),
34566
+ (k) => k.prefix === barePrefix,
34567
+ (k) => k.name === ref
34568
+ ];
34569
+ for (const matches of kinds) {
34570
+ const found = candidates.filter(matches);
34571
+ if (found.length === 1)
34572
+ return found[0];
34573
+ if (found.length > 1) {
34574
+ throw new Error(`"${ref}" matches ${found.length} keys: ${found.map(describeKey).join(", ")}. Use an id.`);
34575
+ }
34576
+ }
34577
+ throw new Error(`No active account key matches "${ref}". Run: secondlayer keys list`);
34578
+ }
34579
+ async function applyRotationToLogin(prefix, newKey, deps = {}) {
34580
+ const apiUrl = deps.apiUrl ?? resolveArchiveOpsUrl();
34581
+ const read = deps.readSession ?? readSession;
34582
+ const write = deps.writeSession ?? writeSession;
34583
+ const envKey = "envKey" in deps ? deps.envKey : resolveAccountKey4();
34584
+ if (!prefix)
34585
+ return { loginUpdated: false, envStale: false };
34586
+ let loginUpdated = false;
34587
+ const session = await read(apiUrl);
34588
+ if (session?.token.startsWith(prefix)) {
34589
+ await write({ ...session, token: newKey }, apiUrl);
34590
+ loginUpdated = true;
34591
+ }
34592
+ return { loginUpdated, envStale: envKey?.startsWith(prefix) ?? false };
34593
+ }
34594
+ async function saveRotatedLogin(prefix, newKey, deps = {}) {
34595
+ try {
34596
+ return await applyRotationToLogin(prefix, newKey, deps);
34597
+ } catch (err) {
34598
+ const envKey = "envKey" in deps ? deps.envKey : resolveAccountKey4();
34599
+ return {
34600
+ loginUpdated: false,
34601
+ envStale: Boolean(prefix) && (envKey?.startsWith(prefix) ?? false),
34602
+ loginError: err instanceof Error ? err.message : String(err)
34603
+ };
34604
+ }
34605
+ }
34606
+ function fail(err) {
34607
+ if (err instanceof Error) {
34608
+ error(err.message);
34609
+ process.exit(1);
34610
+ }
34611
+ throw err;
34612
+ }
34613
+ async function fetchKeys() {
34614
+ const res = await httpArchiveOps("/api/keys");
34615
+ return res.keys;
34616
+ }
34617
+ async function runList(opts) {
34618
+ let keys;
34619
+ try {
34620
+ keys = rotatableKeys(await fetchKeys());
34621
+ } catch (err) {
34622
+ fail(err);
34623
+ }
34624
+ output({
34625
+ json: opts.json,
34626
+ data: {
34627
+ keys: keys.map(({ rowsDaily: _rowsDaily, ...rest }) => rest)
34628
+ },
34629
+ human: () => {
34630
+ if (keys.length === 0) {
34631
+ note("No active account keys. Make one at https://www.secondlayer.tools/account/keys");
34632
+ return;
34633
+ }
34634
+ console.log(formatTable(["ID", "NAME", "KEY", "LAST READ", "ROWS 30D"], keys.map((k) => [
34635
+ k.id.slice(0, 8),
34636
+ k.name ?? "(unnamed)",
34637
+ `${k.prefix}…`,
34638
+ k.lastUsedAt ?? "never",
34639
+ k.rows30d.toLocaleString("en-US")
34640
+ ])));
34641
+ }
34642
+ });
34643
+ }
34644
+ async function runRotate(ref, opts) {
34645
+ let target;
34646
+ try {
34647
+ target = resolveKeyRef(await fetchKeys(), ref);
34648
+ } catch (err) {
34649
+ fail(err);
34650
+ }
34651
+ const label = target.name ?? "(unnamed)";
34652
+ const ok = await confirmDestructive({
34653
+ message: `Rotate "${label}" (${target.prefix}…)? Anything using it gets a 401 at once.`,
34654
+ yes: opts.yes
34655
+ });
34656
+ if (!ok) {
34657
+ info("Cancelled");
34658
+ return;
34659
+ }
34660
+ let rotated;
34661
+ try {
34662
+ rotated = await httpArchiveOps(`/api/keys/${target.id}/rotate`, { method: "POST", body: {} });
34663
+ } catch (err) {
34664
+ fail(err);
34665
+ }
34666
+ const { loginUpdated, envStale, loginError } = await saveRotatedLogin(target.prefix, rotated.key);
34667
+ if (opts.json) {
34668
+ writeData(JSON.stringify({ ...rotated, loginUpdated }, null, 2));
34669
+ } else {
34670
+ success(`Rotated ${blue(label)}. The old key has stopped working.`);
34671
+ writeData(rotated.key);
34672
+ note("Shown once. Copy it now.");
34673
+ }
34674
+ if (loginError) {
34675
+ warn(`Couldn't update your CLI login: ${loginError}. Run: secondlayer login --with-token`);
34676
+ }
34677
+ if (loginUpdated)
34678
+ info("Updated your CLI login to the new key.");
34679
+ if (envStale)
34680
+ warn("SECONDLAYER_API_KEY still holds the old key. Update it.");
34681
+ }
34682
+ function registerKeysCommand(program) {
34683
+ const keys = program.command("keys").description("Manage account keys");
34684
+ keys.command("list").alias("ls").description("List your active account keys").option("--json", "Output as JSON").action((opts) => runList(opts));
34685
+ keys.command("rotate <ref>").description("Replace a key's secret; the old one stops working at once").option("-y, --yes", "Skip confirmation").option("--json", "Output as JSON").action((ref, opts) => runRotate(ref, opts));
34686
+ }
36695
34687
  // src/commands/codegen.ts
36696
34688
  function registerCodegenCommand(program) {
36697
34689
  const codegen = program.command("codegen").description("Generate typed code: contracts, subgraphs, Index, clients");
@@ -36718,259 +34710,6 @@ function registerCodegenCommand(program) {
36718
34710
  }
36719
34711
  // src/commands/config.ts
36720
34712
  init_config2();
36721
-
36722
- // src/lib/detect.ts
36723
- import { homedir as homedir3 } from "node:os";
36724
- import { join as join8 } from "node:path";
36725
-
36726
- // src/lib/docker.ts
36727
- import { spawnSync as spawnSync2 } from "node:child_process";
36728
- function run2(command, args) {
36729
- const result = spawnSync2(command, args, { encoding: "utf8" });
36730
- return {
36731
- ok: !result.error && result.status === 0,
36732
- stdout: result.stdout ?? ""
36733
- };
36734
- }
36735
- async function isDockerAvailable() {
36736
- return run2("docker", ["info"]).ok;
36737
- }
36738
-
36739
- // src/lib/detect.ts
36740
- var STACKS_CONTAINER_PATTERNS = [
36741
- "stacks-blockchain",
36742
- "stacks-node",
36743
- "stacks_blockchain",
36744
- "stacks_node"
36745
- ];
36746
- async function detectRunningContainers() {
36747
- try {
36748
- const psResult = await Bun.$`docker ps --format "{{.Names}}"`.quiet().nothrow();
36749
- if (psResult.exitCode !== 0) {
36750
- return null;
36751
- }
36752
- const containers = psResult.stdout.toString().trim().split(`
36753
- `).filter(Boolean);
36754
- const stacksContainer = containers.find((name) => STACKS_CONTAINER_PATTERNS.some((pattern) => name.toLowerCase().includes(pattern.toLowerCase())));
36755
- if (!stacksContainer) {
36756
- return null;
36757
- }
36758
- const inspectResult = await Bun.$`docker inspect ${stacksContainer}`.quiet().nothrow();
36759
- if (inspectResult.exitCode !== 0) {
36760
- return null;
36761
- }
36762
- const inspectData = JSON.parse(inspectResult.stdout.toString());
36763
- if (!Array.isArray(inspectData) || inspectData.length === 0) {
36764
- return null;
36765
- }
36766
- const container = inspectData[0];
36767
- const path = await extractPathFromMounts(container);
36768
- if (!path) {
36769
- return null;
36770
- }
36771
- const network = detectNetworkFromContainer(container);
36772
- return {
36773
- path,
36774
- network,
36775
- running: true,
36776
- source: "container"
36777
- };
36778
- } catch {
36779
- return null;
36780
- }
36781
- }
36782
- async function extractPathFromMounts(container) {
36783
- if (container.Mounts && Array.isArray(container.Mounts)) {
36784
- for (const mount of container.Mounts) {
36785
- if (mount.Type === "bind" && mount.Source) {
36786
- if (mount.Source.includes("stacks-blockchain") || mount.Source.includes("stacks-node") || mount.Destination?.includes("/stacks")) {
36787
- return await findDockerComposeRoot(mount.Source);
36788
- }
36789
- }
36790
- }
36791
- }
36792
- const binds = container.HostConfig?.Binds;
36793
- if (binds && Array.isArray(binds)) {
36794
- for (const bind of binds) {
36795
- const [source] = bind.split(":");
36796
- if (source && (source.includes("stacks-blockchain") || source.includes("stacks-node"))) {
36797
- return await findDockerComposeRoot(source);
36798
- }
36799
- }
36800
- }
36801
- return null;
36802
- }
36803
- async function findDockerComposeRoot(startPath) {
36804
- let current = startPath;
36805
- while (current && current !== "/") {
36806
- try {
36807
- const composeYml = Bun.file(join8(current, "docker-compose.yml"));
36808
- const composeYaml = Bun.file(join8(current, "docker-compose.yaml"));
36809
- if (await composeYml.exists() || await composeYaml.exists()) {
36810
- return current;
36811
- }
36812
- } catch {}
36813
- current = getParentPath(current);
36814
- }
36815
- const knownPatterns = ["stacks-blockchain-docker", "stacks-node"];
36816
- for (const pattern of knownPatterns) {
36817
- const idx = startPath.indexOf(pattern);
36818
- if (idx !== -1) {
36819
- return startPath.substring(0, idx + pattern.length);
36820
- }
36821
- }
36822
- return getParentPath(startPath);
36823
- }
36824
- function getParentPath(path) {
36825
- const parts = path.split("/").filter(Boolean);
36826
- parts.pop();
36827
- return `/${parts.join("/")}`;
36828
- }
36829
- function detectNetworkFromContainer(container) {
36830
- const config = container.Config;
36831
- if (config?.Env) {
36832
- for (const env of config.Env) {
36833
- const lower = env.toLowerCase();
36834
- if (lower.includes("network=testnet") || lower.includes("stacks_network=testnet")) {
36835
- return "testnet";
36836
- }
36837
- if (lower.includes("network=mainnet") || lower.includes("stacks_network=mainnet")) {
36838
- return "mainnet";
36839
- }
36840
- }
36841
- }
36842
- if (config?.Labels) {
36843
- const networkLabel = config.Labels.network || config.Labels["stacks.network"];
36844
- if (networkLabel === "testnet") {
36845
- return "testnet";
36846
- }
36847
- }
36848
- return "mainnet";
36849
- }
36850
- var SEARCH_PATTERNS = [
36851
- "/Volumes/stacks-blockchain-docker",
36852
- "/Volumes/stacks-node",
36853
- "/Volumes/*/stacks-blockchain-docker",
36854
- "/Volumes/*/stacks-node",
36855
- `${homedir3()}/stacks-blockchain-docker`,
36856
- `${homedir3()}/stacks-node`,
36857
- `${homedir3()}/stacks-*`,
36858
- "/opt/stacks-blockchain-docker",
36859
- "/opt/stacks-node",
36860
- "/opt/stacks-*"
36861
- ];
36862
- async function scanFilesystemPaths() {
36863
- const nodes = [];
36864
- const checkedPaths = new Set;
36865
- for (const pattern of SEARCH_PATTERNS) {
36866
- const paths = await expandGlobPattern(pattern);
36867
- for (const path of paths) {
36868
- if (checkedPaths.has(path))
36869
- continue;
36870
- checkedPaths.add(path);
36871
- const isValid = await isValidStacksNodeDir(path);
36872
- if (!isValid)
36873
- continue;
36874
- const network = await detectNetworkFromFilesystem(path);
36875
- const running = await isComposeProjectRunning(path);
36876
- nodes.push({
36877
- path,
36878
- network,
36879
- running,
36880
- source: "filesystem"
36881
- });
36882
- }
36883
- }
36884
- return nodes;
36885
- }
36886
- async function expandGlobPattern(pattern) {
36887
- try {
36888
- const result = await Bun.$`bash -c ${`ls -d ${pattern} 2>/dev/null`}`.quiet().nothrow();
36889
- if (result.exitCode !== 0) {
36890
- return [];
36891
- }
36892
- return result.stdout.toString().trim().split(`
36893
- `).filter(Boolean);
36894
- } catch {
36895
- return [];
36896
- }
36897
- }
36898
- async function isValidStacksNodeDir(path) {
36899
- const dirName = path.split("/").filter(Boolean).pop() ?? "";
36900
- if (dirName.includes("stacks-blockchain") || dirName.includes("stacks-node")) {
36901
- return true;
36902
- }
36903
- try {
36904
- const composeYml = Bun.file(join8(path, "docker-compose.yml"));
36905
- const composeYaml = Bun.file(join8(path, "docker-compose.yaml"));
36906
- const hasCompose = await composeYml.exists() || await composeYaml.exists();
36907
- if (!hasCompose) {
36908
- return false;
36909
- }
36910
- const composeFile = await composeYml.exists() ? composeYml : composeYaml;
36911
- const content = await composeFile.text();
36912
- return content.includes("stacks-blockchain") || content.includes("stacks-node") || content.includes("blockstack/stacks-blockchain") || content.includes("hirosystems/stacks-blockchain");
36913
- } catch {
36914
- return false;
36915
- }
36916
- }
36917
- async function detectNetworkFromFilesystem(path) {
36918
- const envFile = Bun.file(join8(path, ".env"));
36919
- if (await envFile.exists()) {
36920
- try {
36921
- const content = await envFile.text();
36922
- if (content.includes("NETWORK=testnet") || content.includes("STACKS_NETWORK=testnet")) {
36923
- return "testnet";
36924
- }
36925
- if (content.includes("NETWORK=mainnet") || content.includes("STACKS_NETWORK=mainnet")) {
36926
- return "mainnet";
36927
- }
36928
- } catch {}
36929
- }
36930
- const testnetConfig = Bun.file(join8(path, "configurations/testnet"));
36931
- const mainnetConfig = Bun.file(join8(path, "configurations/mainnet"));
36932
- const activeConfig = Bun.file(join8(path, "configurations/active"));
36933
- if (await activeConfig.exists()) {
36934
- try {
36935
- const result = await Bun.$`readlink ${join8(path, "configurations/active")}`.quiet().nothrow();
36936
- const link = result.stdout.toString().trim();
36937
- if (link.includes("testnet"))
36938
- return "testnet";
36939
- } catch {}
36940
- }
36941
- if (path.toLowerCase().includes("testnet")) {
36942
- return "testnet";
36943
- }
36944
- return "mainnet";
36945
- }
36946
- async function isComposeProjectRunning(path) {
36947
- try {
36948
- const result = await Bun.$`docker compose -f ${join8(path, "docker-compose.yml")} ps -q`.quiet().nothrow();
36949
- return result.exitCode === 0 && result.stdout.toString().trim().length > 0;
36950
- } catch {
36951
- return false;
36952
- }
36953
- }
36954
- async function detectStacksNodes() {
36955
- const nodes = [];
36956
- if (await isDockerAvailable()) {
36957
- const containerNode = await detectRunningContainers();
36958
- if (containerNode) {
36959
- nodes.push(containerNode);
36960
- }
36961
- }
36962
- const filesystemNodes = await scanFilesystemPaths();
36963
- const seenPaths = new Set(nodes.map((n) => n.path));
36964
- for (const node of filesystemNodes) {
36965
- if (!seenPaths.has(node.path)) {
36966
- nodes.push(node);
36967
- seenPaths.add(node.path);
36968
- }
36969
- }
36970
- return nodes;
36971
- }
36972
-
36973
- // src/commands/config.ts
36974
34713
  init_output();
36975
34714
  function registerConfigCommand(program) {
36976
34715
  const config = program.command("config").description("Manage CLI configuration");
@@ -36983,25 +34722,18 @@ function registerConfigCommand(program) {
36983
34722
  }
36984
34723
  note(`Config file: ${getConfigPath()}`);
36985
34724
  console.log("");
36986
- await printConfigTree(cfg);
34725
+ printConfig(cfg);
36987
34726
  } catch (err) {
36988
34727
  error(`Failed to load config: ${err}`);
36989
34728
  process.exit(1);
36990
34729
  }
36991
34730
  });
36992
- config.command("set <key> <value>").description("Set a configuration value (supports dot notation: ports.api)").option("--no-validate", "Skip connection validation for database/redis URLs").addHelpText("after", `
34731
+ config.command("set <key> <value>").description("Set a configuration value").addHelpText("after", `
36993
34732
  Examples:
36994
- $ secondlayer config set network local
36995
- $ secondlayer config set ports.api 3800
36996
- $ secondlayer config set database.url postgres://localhost:5432/secondlayer_dev`).action(async (key, value, options) => {
34733
+ $ secondlayer config set network local`).action(async (key, value) => {
36997
34734
  try {
36998
34735
  await setConfigValue(key, value);
36999
34736
  success(`Set ${key} = ${value}`);
37000
- if (options.validate) {
37001
- if (key === "database.url") {
37002
- await validateDatabaseConnection(value);
37003
- }
37004
- }
37005
34737
  } catch (err) {
37006
34738
  if (err instanceof Error && err.message.includes("Invalid")) {
37007
34739
  error(`Invalid value for ${key}: ${err.message}`);
@@ -37044,78 +34776,12 @@ Examples:
37044
34776
  }
37045
34777
  });
37046
34778
  }
37047
- async function printConfigTree(cfg) {
37048
- const defaults = getDefaultConfig();
37049
- printValue("network", cfg.network, isDefaultValue(cfg, "network"));
37050
- if (cfg.defaultProject) {
37051
- printValue("defaultProject", cfg.defaultProject, false);
37052
- }
37053
- const resolvedDataDir = getDataDir(cfg);
37054
- const dataDirDisplay = cfg.dataDir === resolvedDataDir ? cfg.dataDir : `${cfg.dataDir} ${dim(`→ ${resolvedDataDir}`)}`;
37055
- printValue("dataDir", dataDirDisplay, isDefaultValue(cfg, "dataDir"));
37056
- if (cfg.network === "local") {
37057
- console.log("");
37058
- console.log(blue("node:"));
37059
- if (cfg.node) {
37060
- printValue(" installPath", cfg.node.installPath, false, 2);
37061
- printValue(" network", cfg.node.network, cfg.node.network === "mainnet", 2);
37062
- } else {
37063
- console.log(dim(" (not configured)"));
37064
- try {
37065
- const detected = await detectStacksNodes();
37066
- if (detected.length > 0) {
37067
- console.log("");
37068
- console.log(dim(` Detected ${detected.length} node${detected.length > 1 ? "s" : ""}:`));
37069
- for (const node of detected.slice(0, 3)) {
37070
- const status = node.running ? green("●") : dim("○");
37071
- console.log(dim(` ${status} ${node.path} (${node.network})`));
37072
- }
37073
- console.log(dim(" Run 'secondlayer init' to configure"));
37074
- }
37075
- } catch {}
37076
- }
37077
- console.log("");
37078
- console.log(blue("ports:"));
37079
- printValue(" api", cfg.ports.api, cfg.ports.api === defaults.ports.api, 2);
37080
- printValue(" indexer", cfg.ports.indexer, cfg.ports.indexer === defaults.ports.indexer, 2);
37081
- console.log("");
37082
- console.log(blue("database:"));
37083
- printValue(" type", cfg.database.type, cfg.database.type === "docker", 2);
37084
- if (cfg.database.url) {
37085
- printValue(" url", maskUrl(cfg.database.url), false, 2);
37086
- }
37087
- }
34779
+ function printConfig(cfg) {
34780
+ const isDefault = cfg.network === getDefaultConfig().network;
34781
+ const value = isDefault ? dim(cfg.network) : green(cfg.network);
34782
+ console.log(`network: ${value}${isDefault ? dim(" (default)") : ""}`);
37088
34783
  console.log("");
37089
34784
  }
37090
- function printValue(key, value, isDefault, _indent = 0) {
37091
- const valueStr = String(value);
37092
- const defaultIndicator = isDefault ? dim(" (default)") : "";
37093
- const valueColor = isDefault ? dim(valueStr) : green(valueStr);
37094
- console.log(`${key}: ${valueColor}${defaultIndicator}`);
37095
- }
37096
- function maskUrl(url) {
37097
- try {
37098
- const parsed = new URL(url);
37099
- if (parsed.password) {
37100
- parsed.password = "****";
37101
- }
37102
- return parsed.toString();
37103
- } catch {
37104
- return url;
37105
- }
37106
- }
37107
- async function validateDatabaseConnection(url) {
37108
- try {
37109
- await Promise.resolve().then(() => init_src());
37110
- const sql = src_default(url);
37111
- await sql`SELECT 1`;
37112
- await sql.end();
37113
- success("Database connection verified");
37114
- } catch (err) {
37115
- warn(`Could not connect to database: ${err instanceof Error ? err.message : err}`);
37116
- console.log(dim("The URL was saved but connection failed. Check your database settings."));
37117
- }
37118
- }
37119
34785
  // src/commands/context.ts
37120
34786
  init_http();
37121
34787
  import {
@@ -37933,9 +35599,9 @@ function registerWebhooksCommand(program) {
37933
35599
  attachWebhookSubcommands(webhooks);
37934
35600
  }
37935
35601
  // src/commands/devnet.ts
37936
- import { spawnSync as spawnSync3 } from "node:child_process";
35602
+ import { spawnSync as spawnSync2 } from "node:child_process";
37937
35603
  import { existsSync as existsSync6, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "node:fs";
37938
- import { dirname as dirname7, join as join11 } from "node:path";
35604
+ import { dirname as dirname7, join as join10 } from "node:path";
37939
35605
 
37940
35606
  // src/lib/devnet-compose.ts
37941
35607
  var DEFAULT_IMAGE_OWNER = "ryanwaits";
@@ -38090,14 +35756,14 @@ volumes:
38090
35756
 
38091
35757
  // src/lib/devnet-config.ts
38092
35758
  import { existsSync as existsSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "node:fs";
38093
- import { dirname as dirname6, join as join9, parse as parsePath } from "node:path";
35759
+ import { dirname as dirname6, join as join8, parse as parsePath } from "node:path";
38094
35760
  import { parse as parseToml } from "smol-toml";
38095
35761
  var DEFAULT_INDEXER_OBSERVER = "host.docker.internal:3700";
38096
35762
  function findClarinetProject(startDir) {
38097
35763
  let dir = startDir;
38098
35764
  const { root } = parsePath(dir);
38099
35765
  while (true) {
38100
- if (existsSync5(join9(dir, "Clarinet.toml")))
35766
+ if (existsSync5(join8(dir, "Clarinet.toml")))
38101
35767
  return dir;
38102
35768
  if (dir === root)
38103
35769
  return null;
@@ -38149,7 +35815,7 @@ init_resolve_auth();
38149
35815
  // src/commands/faucet.ts
38150
35816
  import { randomBytes as randomBytes2 } from "node:crypto";
38151
35817
  import { readFile as readFile5 } from "node:fs/promises";
38152
- import { join as join10 } from "node:path";
35818
+ import { join as join9 } from "node:path";
38153
35819
  import { http as http3, createWalletClient } from "@secondlayer/stacks";
38154
35820
  import { mnemonicToAccount } from "@secondlayer/stacks/accounts";
38155
35821
  import { devnet } from "@secondlayer/stacks/chains";
@@ -38159,7 +35825,7 @@ init_output();
38159
35825
  var DUST_LIMIT_SATS = 546n;
38160
35826
  var DEFAULT_AMOUNT_SATS = 1000000n;
38161
35827
  async function readDeployerMnemonic(projectDir) {
38162
- const path = join10(projectDir, "settings", "Devnet.toml");
35828
+ const path = join9(projectDir, "settings", "Devnet.toml");
38163
35829
  let raw;
38164
35830
  try {
38165
35831
  raw = await readFile5(path, "utf8");
@@ -38276,9 +35942,9 @@ is what makes minting possible without Bitcoin.`).action(async (opts) => {
38276
35942
  }
38277
35943
 
38278
35944
  // src/commands/devnet.ts
38279
- var COMPOSE_REL = join11(".secondlayer", "docker-compose.yml");
35945
+ var COMPOSE_REL = join10(".secondlayer", "docker-compose.yml");
38280
35946
  function ensureDocker() {
38281
- const probe = spawnSync3("docker", ["info"], { stdio: "ignore" });
35947
+ const probe = spawnSync2("docker", ["info"], { stdio: "ignore" });
38282
35948
  if (probe.error || probe.status !== 0) {
38283
35949
  error(`Docker isn't available.
38284
35950
 
@@ -38289,7 +35955,7 @@ function ensureDocker() {
38289
35955
  }
38290
35956
  }
38291
35957
  function dockerCompose(composePath, args) {
38292
- const res = spawnSync3("docker", ["compose", "-f", composePath, ...args], {
35958
+ const res = spawnSync2("docker", ["compose", "-f", composePath, ...args], {
38293
35959
  stdio: "inherit"
38294
35960
  });
38295
35961
  return res.status ?? 1;
@@ -38321,7 +35987,7 @@ function registerDevnetCommand(program) {
38321
35987
  }
38322
35988
  function resolveProject(explicit) {
38323
35989
  if (explicit) {
38324
- if (!existsSync6(join11(explicit, "Clarinet.toml"))) {
35990
+ if (!existsSync6(join10(explicit, "Clarinet.toml"))) {
38325
35991
  error(`No Clarinet.toml in ${explicit}`);
38326
35992
  process.exit(1);
38327
35993
  }
@@ -38337,7 +36003,7 @@ function resolveProject(explicit) {
38337
36003
  }
38338
36004
  async function connect(options) {
38339
36005
  const project = resolveProject(options.project);
38340
- const devnetToml = join11(project, "settings", "Devnet.toml");
36006
+ const devnetToml = join10(project, "settings", "Devnet.toml");
38341
36007
  mkdirSync3(dirname7(devnetToml), { recursive: true });
38342
36008
  const result = ensureEventObserver(devnetToml, DEFAULT_INDEXER_OBSERVER);
38343
36009
  console.log(`${green("✓")} found Clarinet.toml`);
@@ -38347,7 +36013,7 @@ async function connect(options) {
38347
36013
  console.log(`${green("✓")} ${result.status === "created" ? "created" : "patched"} settings/Devnet.toml`);
38348
36014
  console.log(dim(` + stacks_node_events_observers = ["${DEFAULT_INDEXER_OBSERVER}"]`));
38349
36015
  }
38350
- const composePath = join11(project, COMPOSE_REL);
36016
+ const composePath = join10(project, COMPOSE_REL);
38351
36017
  mkdirSync3(dirname7(composePath), { recursive: true });
38352
36018
  writeFileSync5(composePath, buildDevnetCompose({ owner: options.owner, imageTag: options.imageTag }));
38353
36019
  console.log(`${green("✓")} wrote ${COMPOSE_REL}`);
@@ -38380,7 +36046,7 @@ Stop with: secondlayer devnet down`));
38380
36046
  }
38381
36047
  async function down(options) {
38382
36048
  const project = resolveProject(options.project);
38383
- const composePath = join11(project, COMPOSE_REL);
36049
+ const composePath = join10(project, COMPOSE_REL);
38384
36050
  if (!existsSync6(composePath)) {
38385
36051
  error(`No ${COMPOSE_REL} in ${project} — nothing to stop. Run \`secondlayer devnet connect\` first.`);
38386
36052
  process.exit(1);
@@ -38395,7 +36061,7 @@ async function down(options) {
38395
36061
  }
38396
36062
  async function logs(service, options) {
38397
36063
  const project = resolveProject(options.project);
38398
- const composePath = join11(project, COMPOSE_REL);
36064
+ const composePath = join10(project, COMPOSE_REL);
38399
36065
  if (!existsSync6(composePath)) {
38400
36066
  error(`No ${COMPOSE_REL} in ${project} — run \`secondlayer devnet connect\` first.`);
38401
36067
  process.exit(1);
@@ -38654,7 +36320,7 @@ function parseMaxPages(value) {
38654
36320
  }
38655
36321
  function consumeHandlers(io) {
38656
36322
  return {
38657
- onBatch: (events, _envelope, ctx) => {
36323
+ onBatch: (events, ctx) => {
38658
36324
  for (const e of events)
38659
36325
  io.stdout(JSON.stringify(e));
38660
36326
  if (ctx.cursor)
@@ -38837,7 +36503,6 @@ init_index_api();
38837
36503
  init_config2();
38838
36504
 
38839
36505
  // src/lib/health.ts
38840
- init_config2();
38841
36506
  init_dev_state();
38842
36507
 
38843
36508
  // src/lib/network.ts
@@ -38855,96 +36520,30 @@ function networkFromId(networkId) {
38855
36520
  return "testnet";
38856
36521
  return null;
38857
36522
  }
38858
- async function validateNetworkConsistency(config) {
38859
- const issues = [];
38860
- const network = config.node?.network;
38861
- if (!network) {
38862
- return { valid: true, issues: [] };
38863
- }
38864
- const expected = CHAIN_IDS[network].decimal;
38865
- try {
38866
- const res = await fetch("http://localhost:20443/v2/info", {
38867
- signal: AbortSignal.timeout(3000)
38868
- });
38869
- if (res.ok) {
38870
- const info = await res.json();
38871
- if (info.network_id !== expected) {
38872
- const actual = networkFromId(info.network_id);
38873
- issues.push(`RPC reports network_id=${info.network_id} (${actual ?? "unknown"}) but config says ${network} (${expected})`);
38874
- }
38875
- }
38876
- } catch {}
38877
- try {
38878
- const result = await Bun.$`docker inspect --format={{.Config.Env}} stacks-blockchain`.quiet().nothrow();
38879
- if (result.exitCode === 0) {
38880
- const envStr = result.stdout.toString();
38881
- const match = envStr.match(/STACKS_CHAIN_ID=(0x[0-9a-fA-F]+|\d+)/);
38882
- if (match) {
38883
- const containerId = Number.parseInt(match[1], match[1]?.startsWith("0x") ? 16 : 10);
38884
- if (containerId !== expected) {
38885
- issues.push(`Container STACKS_CHAIN_ID=${containerId} but config expects ${expected} (${network})`);
38886
- }
38887
- }
38888
- }
38889
- } catch {}
38890
- if (config.node?.installPath) {
38891
- try {
38892
- const envFile = Bun.file(`${config.node.installPath}/.env`);
38893
- if (await envFile.exists()) {
38894
- const content = await envFile.text();
38895
- const match = content.match(/STACKS_CHAIN_ID=(0x[0-9a-fA-F]+|\d+)/);
38896
- if (match) {
38897
- const fileId = Number.parseInt(match[1], match[1]?.startsWith("0x") ? 16 : 10);
38898
- if (fileId !== expected) {
38899
- issues.push(`Node .env STACKS_CHAIN_ID=${fileId} but config expects ${expected} (${network})`);
38900
- }
38901
- }
38902
- }
38903
- } catch {}
38904
- }
38905
- return { valid: issues.length === 0, issues };
38906
- }
38907
36523
 
38908
- // src/lib/node-manager.ts
38909
- init_config2();
38910
- async function getNodeContainers() {
36524
+ // src/lib/health.ts
36525
+ async function isNodeRunning() {
38911
36526
  try {
38912
- const result = await Bun.$`docker ps --format json --filter "name=stacks"`.quiet();
36527
+ const result = await Bun.$`docker ps --format json --filter "name=stacks-blockchain"`.quiet();
38913
36528
  if (result.exitCode !== 0)
38914
- return [];
38915
- const lines = result.stdout.toString().trim().split(`
38916
- `).filter(Boolean);
38917
- const containers = [];
38918
- for (const line of lines) {
38919
- try {
38920
- const container = JSON.parse(line);
38921
- containers.push({
38922
- name: container.Names || container.Name,
38923
- status: container.Status || "unknown"
38924
- });
38925
- } catch {}
38926
- }
38927
- return containers;
36529
+ return false;
36530
+ return result.stdout.toString().trim().split(`
36531
+ `).filter(Boolean).some((line) => {
36532
+ const { Status } = JSON.parse(line);
36533
+ return !Status?.includes("Restarting");
36534
+ });
38928
36535
  } catch {
38929
- return [];
36536
+ return false;
38930
36537
  }
38931
36538
  }
38932
- async function isNodeRunning() {
38933
- const containers = await getNodeContainers();
38934
- return containers.some((c) => c.name.includes("stacks-blockchain") && !c.status.includes("Restarting"));
38935
- }
38936
-
38937
- // src/lib/health.ts
38938
36539
  async function checkHealth() {
38939
- const config = await loadConfig2();
38940
36540
  const issues = [];
38941
36541
  const node = {
38942
36542
  running: false,
38943
- network: config.node?.network ?? null,
36543
+ network: null,
38944
36544
  height: null,
38945
36545
  burnHeight: null,
38946
36546
  chainId: null,
38947
- chainIdValid: true,
38948
36547
  peers: 0,
38949
36548
  version: null
38950
36549
  };
@@ -38960,7 +36559,7 @@ async function checkHealth() {
38960
36559
  node.height = info.stacks_tip_height ?? null;
38961
36560
  node.burnHeight = info.burn_block_height ?? null;
38962
36561
  node.version = info.server_version ?? null;
38963
- node.network = networkFromId(info.network_id) ?? node.network;
36562
+ node.network = networkFromId(info.network_id);
38964
36563
  }
38965
36564
  } catch {
38966
36565
  issues.push("Node RPC not responding");
@@ -38974,9 +36573,6 @@ async function checkHealth() {
38974
36573
  node.peers = (peers.inbound?.length ?? 0) + (peers.outbound?.length ?? 0);
38975
36574
  }
38976
36575
  } catch {}
38977
- const validation = await validateNetworkConsistency(config);
38978
- node.chainIdValid = validation.valid;
38979
- issues.push(...validation.issues);
38980
36576
  }
38981
36577
  const containers = [];
38982
36578
  try {
@@ -39050,8 +36646,8 @@ async function checkHealth() {
39050
36646
  infrastructure.postgres = pg.stdout.toString().trim().length > 0;
39051
36647
  } catch {}
39052
36648
  const portsToCheck = [
39053
- { port: config.ports.api, name: "API" },
39054
- { port: config.ports.indexer, name: "Indexer" },
36649
+ { port: 3800, name: "API" },
36650
+ { port: 3700, name: "Indexer" },
39055
36651
  { port: 20443, name: "Node RPC" }
39056
36652
  ];
39057
36653
  for (const { port, name } of portsToCheck) {
@@ -39168,22 +36764,17 @@ function doctorVerdictSuffix(diagnosis) {
39168
36764
  return ` — the API reports status=${diagnosis.overall}.`;
39169
36765
  }
39170
36766
  async function runLocalDoctor(jsonOutput) {
39171
- const config = await loadConfig2();
39172
36767
  const report = await checkHealth();
39173
36768
  if (jsonOutput) {
39174
36769
  console.log(JSON.stringify(report, null, 2));
39175
36770
  return;
39176
36771
  }
39177
- const network = config.node?.network;
39178
- const chainIdHex = network ? getChainIdHex(network) : "N/A";
36772
+ const { network } = report.node;
39179
36773
  console.log("");
39180
36774
  console.log(blue("Stack"));
39181
36775
  console.log(formatKeyValue([
39182
36776
  [" Network", network ?? dim("not configured")],
39183
- [
39184
- " Chain ID",
39185
- network ? `${chainIdHex} (${report.node.chainIdValid ? green("valid") : red("MISMATCH")})` : dim("N/A")
39186
- ]
36777
+ [" Chain ID", network ? getChainIdHex(network) : dim("N/A")]
39187
36778
  ]));
39188
36779
  console.log("");
39189
36780
  console.log(blue("Node"));
@@ -39226,30 +36817,8 @@ async function runLocalDoctor(jsonOutput) {
39226
36817
  console.log(` ${report.infrastructure.postgres ? green("✓") : red("✗")} PostgreSQL`);
39227
36818
  console.log("");
39228
36819
  console.log(blue("Config"));
39229
- const configPath = (await Promise.resolve().then(() => (init_config2(), exports_config))).getConfigPath();
39230
- const dataDir = getDataDir(config);
39231
- console.log(formatKeyValue([
39232
- [" Config", dim(configPath)],
39233
- [" Data dir", dim(dataDir)],
39234
- [" Node path", dim(config.node?.installPath ?? "not set")]
39235
- ]));
36820
+ console.log(formatKeyValue([[" Config", dim(getConfigPath())]]));
39236
36821
  console.log("");
39237
- try {
39238
- const result = await Bun.$`df -h ${dataDir}`.quiet().nothrow();
39239
- if (result.exitCode === 0) {
39240
- const lines = result.stdout.toString().trim().split(`
39241
- `);
39242
- if (lines.length >= 2) {
39243
- const parts = lines[1]?.split(/\s+/);
39244
- const used = parts[2];
39245
- const avail = parts[3];
39246
- const pct = parts[4];
39247
- console.log(blue("Disk"));
39248
- console.log(` Used: ${used} Available: ${avail} (${pct})`);
39249
- console.log("");
39250
- }
39251
- }
39252
- } catch {}
39253
36822
  try {
39254
36823
  await Promise.resolve().then(() => init_dev_state());
39255
36824
  const logsDir = getLogsDir();
@@ -39279,54 +36848,9 @@ async function runLocalDoctor(jsonOutput) {
39279
36848
  }
39280
36849
  // src/commands/whoami.ts
39281
36850
  init_api_url();
39282
- init_config2();
39283
36851
  init_http();
39284
36852
  init_output();
39285
36853
  import { resolveApiKey as resolveApiKey4 } from "@secondlayer/sdk";
39286
-
39287
- // src/lib/project-file.ts
39288
- import { existsSync as existsSync7 } from "node:fs";
39289
- import { mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
39290
- import { homedir as homedir5 } from "node:os";
39291
- import { dirname as dirname9, join as join13, parse as parsePath2, resolve as resolve8 } from "node:path";
39292
- import { z as z4 } from "zod";
39293
- var ProjectFileSchema = z4.object({
39294
- slug: z4.string().min(1)
39295
- });
39296
- var FILENAME = "project";
39297
- var DIRNAME = ".secondlayer";
39298
- async function readActiveProject(cwd, globalDefault) {
39299
- let dir = resolve8(cwd);
39300
- const home = resolve8(homedir5());
39301
- const fsRoot = parsePath2(dir).root;
39302
- while (true) {
39303
- const candidate = join13(dir, DIRNAME, FILENAME);
39304
- if (existsSync7(candidate)) {
39305
- try {
39306
- const raw = await readFile6(candidate, "utf8");
39307
- const parsed = ProjectFileSchema.parse(JSON.parse(raw));
39308
- return { slug: parsed.slug, resolvedFrom: candidate };
39309
- } catch {}
39310
- }
39311
- if (existsSync7(join13(dir, ".git")))
39312
- break;
39313
- if (dir === home || dir === fsRoot)
39314
- break;
39315
- const parent = dirname9(dir);
39316
- if (parent === dir)
39317
- break;
39318
- dir = parent;
39319
- }
39320
- if (globalDefault) {
39321
- return {
39322
- slug: globalDefault,
39323
- resolvedFrom: join13(homedir5(), ".secondlayer", "config.json")
39324
- };
39325
- }
39326
- return null;
39327
- }
39328
-
39329
- // src/commands/whoami.ts
39330
36854
  async function runWhoami() {
39331
36855
  const instanceUrl = resolveApiUrl();
39332
36856
  const merchantUrl = resolveArchiveOpsUrl();
@@ -39342,8 +36866,6 @@ async function runWhoami() {
39342
36866
  merchantOk = false;
39343
36867
  }
39344
36868
  const merchantCredential = source === "env" ? "SECONDLAYER_API_KEY" : source === "session" ? "session" : null;
39345
- const config = await loadConfig2();
39346
- const active = await readActiveProject(process.cwd(), config.defaultProject);
39347
36869
  return {
39348
36870
  instance: {
39349
36871
  url: instanceUrl,
@@ -39355,8 +36877,7 @@ async function runWhoami() {
39355
36877
  credential: merchantCredential,
39356
36878
  status: merchantOk ? "set" : "missing",
39357
36879
  email
39358
- },
39359
- project: active ? { slug: active.slug, source: active.resolvedFrom } : null
36880
+ }
39360
36881
  };
39361
36882
  }
39362
36883
  function registerWhoamiCommand(program) {
@@ -39374,12 +36895,6 @@ function registerWhoamiCommand(program) {
39374
36895
  const merchantCred = result.merchant.credential ?? "SECONDLAYER_API_KEY|session";
39375
36896
  const merchantValue = result.merchant.email ? `${result.merchant.url} ${merchantCred} ${result.merchant.status} (${result.merchant.email})` : `${result.merchant.url} ${merchantCred} ${result.merchant.status}`;
39376
36897
  rows.push(["merchant", merchantValue]);
39377
- if (result.project) {
39378
- rows.push(["project", result.project.slug]);
39379
- rows.push(["project source", dim(result.project.source)]);
39380
- } else {
39381
- rows.push(["project", dim("(none)")]);
39382
- }
39383
36898
  console.log(formatKeyValue(rows));
39384
36899
  if (result.merchant.status === "missing") {
39385
36900
  note(`merchant identity missing. ${ARCHIVE_AUTH_HINT}`);
@@ -39667,13 +37182,13 @@ init_output();
39667
37182
  init_resolve_auth();
39668
37183
  import {
39669
37184
  chmodSync,
39670
- existsSync as existsSync8,
37185
+ existsSync as existsSync7,
39671
37186
  mkdirSync as mkdirSync4,
39672
37187
  readFileSync as readFileSync7,
39673
37188
  statSync as statSync2,
39674
37189
  writeFileSync as writeFileSync6
39675
37190
  } from "node:fs";
39676
- import { join as join14, resolve as resolve9 } from "node:path";
37191
+ import { join as join12, resolve as resolve8 } from "node:path";
39677
37192
  import { closeDb, getDb as getDb4, sql as sql2 } from "@secondlayer/shared/db";
39678
37193
  import {
39679
37194
  decryptBundle,
@@ -39822,10 +37337,10 @@ async function runBackup(opts) {
39822
37337
  printError(plan.reason);
39823
37338
  process.exit(BACKUP_EXIT.REFUSED);
39824
37339
  }
39825
- const outDir = resolve9(opts.out);
37340
+ const outDir = resolve8(opts.out);
39826
37341
  mkdirSync4(outDir, { recursive: true });
39827
37342
  console.error("dumping database…");
39828
- const dumpPath = join14(outDir, DB_FILE);
37343
+ const dumpPath = join12(outDir, DB_FILE);
39829
37344
  const dumpCmd = pgDumpInvocation(databaseUrl, dumpPath);
39830
37345
  const dump = await runProcess(dumpCmd.cmd, "pg_dump", dumpCmd.env);
39831
37346
  if (!dump.ok) {
@@ -39845,7 +37360,7 @@ async function runBackup(opts) {
39845
37360
  const lines = SECRET_ENV_KEYS.filter((k) => process.env[k]).map((k) => `${k}=${process.env[k]}`);
39846
37361
  const sealed = encryptBundle(lines.join(`
39847
37362
  `), passphrase);
39848
- const secretsPath = join14(outDir, SECRETS_FILE);
37363
+ const secretsPath = join12(outDir, SECRETS_FILE);
39849
37364
  writeFileSync6(secretsPath, sealed);
39850
37365
  chmodSync(secretsPath, 384);
39851
37366
  manifest.secrets = {
@@ -39854,7 +37369,7 @@ async function runBackup(opts) {
39854
37369
  canary: sealKeyCanary(secretsKey)
39855
37370
  };
39856
37371
  }
39857
- writeFileSync6(join14(outDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}
37372
+ writeFileSync6(join12(outDir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}
39858
37373
  `);
39859
37374
  output({
39860
37375
  json: opts.json,
@@ -39883,14 +37398,14 @@ function attachRestoreCommand(cmd) {
39883
37398
  }
39884
37399
  async function runRestore(opts) {
39885
37400
  const databaseUrl = requireDatabaseUrl();
39886
- const dir = resolve9(opts.from);
39887
- const manifestPath = join14(dir, MANIFEST_FILE);
39888
- if (!existsSync8(manifestPath)) {
37401
+ const dir = resolve8(opts.from);
37402
+ const manifestPath = join12(dir, MANIFEST_FILE);
37403
+ if (!existsSync7(manifestPath)) {
39889
37404
  printError(`no ${MANIFEST_FILE} in ${dir}`);
39890
37405
  process.exit(BACKUP_EXIT.REFUSED);
39891
37406
  }
39892
37407
  const manifest = JSON.parse(readFileSync7(manifestPath, "utf8"));
39893
- const dumpPath = join14(dir, manifest.db?.file ?? DB_FILE);
37408
+ const dumpPath = join12(dir, manifest.db?.file ?? DB_FILE);
39894
37409
  if (manifest.db && await sha256File(dumpPath) !== manifest.db.sha256) {
39895
37410
  printError("the database dump does not match the digest in the manifest; this bundle is corrupt or truncated");
39896
37411
  process.exit(BACKUP_EXIT.REFUSED);
@@ -39904,7 +37419,7 @@ async function runRestore(opts) {
39904
37419
  process.exit(BACKUP_EXIT.REFUSED);
39905
37420
  }
39906
37421
  try {
39907
- const env = decryptBundle(readFileSync7(join14(dir, manifest.secrets.file)), passphrase);
37422
+ const env = decryptBundle(readFileSync7(join12(dir, manifest.secrets.file)), passphrase);
39908
37423
  bundleKey = env.split(`
39909
37424
  `).find((l) => l.startsWith("SECONDLAYER_SECRETS_KEY="))?.slice("SECONDLAYER_SECRETS_KEY=".length).trim();
39910
37425
  } catch {
@@ -39982,8 +37497,8 @@ function registerRestoreCommand(program) {
39982
37497
  // src/lib/instance-init.ts
39983
37498
  init_output();
39984
37499
  import { randomBytes as randomBytes3 } from "node:crypto";
39985
- import { existsSync as existsSync9, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "node:fs";
39986
- import { resolve as resolve10 } from "node:path";
37500
+ import { existsSync as existsSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "node:fs";
37501
+ import { resolve as resolve9 } from "node:path";
39987
37502
  import { ARCHIVE_ROOT_PUBLIC_KEY_PEM } from "@secondlayer/shared/archive/root-key";
39988
37503
  import { generateEd25519KeyPair } from "@secondlayer/shared/crypto/ed25519";
39989
37504
  import { INSTANCE_NETWORKS } from "@secondlayer/shared/db/queries/instance";
@@ -40032,7 +37547,7 @@ function unescapeEnvValue(raw) {
40032
37547
  `).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
40033
37548
  }
40034
37549
  function readEnvValue(envPath, key) {
40035
- if (!existsSync9(envPath))
37550
+ if (!existsSync8(envPath))
40036
37551
  return null;
40037
37552
  const match = readFileSync8(envPath, "utf8").match(new RegExp(`^${key}=(.*)$`, "m"));
40038
37553
  return match ? unescapeEnvValue(match[1]) : null;
@@ -40080,12 +37595,12 @@ function renderInstanceEnv(env) {
40080
37595
  `);
40081
37596
  }
40082
37597
  function writeInstanceEnv(cwd, env, file = INSTANCE_ENV_FILE) {
40083
- const path = resolve10(cwd, file);
37598
+ const path = resolve9(cwd, file);
40084
37599
  writeFileSync7(path, renderInstanceEnv(env), { mode: 384 });
40085
37600
  return path;
40086
37601
  }
40087
37602
  function loadExistingInstanceEnv(cwd, file = INSTANCE_ENV_FILE) {
40088
- const path = resolve10(cwd, file);
37603
+ const path = resolve9(cwd, file);
40089
37604
  return {
40090
37605
  INSTANCE_TOKEN: readEnvValue(path, "INSTANCE_TOKEN"),
40091
37606
  SECONDLAYER_SECRETS_KEY: readEnvValue(path, "SECONDLAYER_SECRETS_KEY"),
@@ -40238,6 +37753,7 @@ registerObserverCommand(program);
40238
37753
  registerLoginCommand(program);
40239
37754
  registerLogoutCommand(program);
40240
37755
  registerWhoamiCommand(program);
37756
+ registerKeysCommand(program);
40241
37757
  program.commandsGroup("Your data:");
40242
37758
  registerSubgraphsCommand(program);
40243
37759
  registerWebhooksCommand(program);
@@ -40261,5 +37777,5 @@ registerCreditsCommand(program);
40261
37777
  registerArchiveCommand(program);
40262
37778
  program.parse();
40263
37779
 
40264
- //# debugId=59184906FD67FE5F64756E2164756E21
37780
+ //# debugId=0DC9F45DD895F4A264756E2164756E21
40265
37781
  //# sourceMappingURL=cli.js.map