@theholocron/cli 5.0.0-alpha.329 → 5.0.0-alpha.330

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.mjs CHANGED
@@ -29,8 +29,8 @@ import { errorMessage } from "@theholocron/misc-utils";
29
29
  import { pathToFileURL } from "node:url";
30
30
  import { stringifyJson } from "@theholocron/json-utils";
31
31
  import { findRootSync, isWorkspaceRoot, walkFilesSync } from "@theholocron/fs-utils";
32
- import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
33
32
  import { createServer } from "node:http";
33
+ import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
34
34
  import { ADR_DIR, ADR_STATUSES, CLOSED_STATUSES, SPEC_DIRS, SPEC_STATUSES, WITHDRAWN_STATE, assignSpecIds, checkSpecs, classifySpecPath, discussionBody, discussionIdLine, discussionPrLine, discussionTitle, evaluateDocsPresence, isAddedDocComment, isFeat, packageOf, parseFrontmatter, parseSkipDocs, reconcileSpecStatus, specSummary, specTitle, updateFrontmatter } from "@theholocron/astromech/repo-validation";
35
35
  import { lintCommitMsgFile } from "@theholocron/astromech/lint";
36
36
  import { createGitHubClient } from "@theholocron/github-client";
@@ -483,6 +483,7 @@ const COMMAND_CONTEXTS = {
483
483
  "secrets sync": "workspace",
484
484
  "tunnel up": "workspace",
485
485
  dev: "workspace",
486
+ "dev serve": "repo-aware",
486
487
  "notifications channel add": "workspace",
487
488
  "notifications setup": "workspace",
488
489
  "notifications link": "workspace",
@@ -2846,6 +2847,13 @@ function validateDev(dev) {
2846
2847
  }
2847
2848
  if (dev.port !== void 0 && !(Number.isInteger(dev.port) && dev.port >= 1 && dev.port <= 65535)) throw new ConfigError(`\`dev.port\` must be a port from 1 to 65535, got ${JSON.stringify(dev.port)}`);
2848
2849
  if (dev.command !== void 0 && !(Array.isArray(dev.command) && dev.command.length > 0 && dev.command.every(nonEmpty))) throw new ConfigError("`dev.command` must be the program and its arguments, e.g. [\"pnpm\", \"run\", \"serve\"]");
2850
+ if (dev.serve !== void 0) {
2851
+ const { serve } = dev;
2852
+ if (!nonEmpty(serve.handler)) throw new ConfigError("`dev.serve.handler` must be the path of the module that exports the handler");
2853
+ if (serve.export !== void 0 && !nonEmpty(serve.export)) throw new ConfigError("`dev.serve.export` must be the name of the handler's export, got an empty value");
2854
+ if (serve.required !== void 0 && !(Array.isArray(serve.required) && serve.required.every(nonEmpty))) throw new ConfigError("`dev.serve.required` must be a list of variable names");
2855
+ if (serve.logging !== void 0 && !(nonEmpty(serve.logging.tokenVar) && nonEmpty(serve.logging.datasetVar))) throw new ConfigError("`dev.serve.logging` needs a `tokenVar` and a `datasetVar`, both variable names");
2856
+ }
2849
2857
  }
2850
2858
  /** The values `repoValidation.docsCoverage` accepts. */
2851
2859
  const DOCS_COVERAGE_MODES = [
@@ -5245,24 +5253,223 @@ const deployCommand = {
5245
5253
  })).status === "fail") process.exitCode = 1;
5246
5254
  }
5247
5255
  };
5256
+ // ../dagobah/dist/index.mjs
5257
+ /**
5258
+ * The environment a local app runs with: the variables already in the process, and what the 1Password
5259
+ * Environment `environment` holds for the rest (read with `op environment secret list`, the way the 1Password
5260
+ * plugin reads one, so Touch ID asks once). The process wins, so a variable exported for one run overrides the
5261
+ * Environment. The `required` ones must end up set; a message names the ones that are not, and never a
5262
+ * value. Nothing is written to disk.
5263
+ */
5264
+ function loadDevEnv(input) {
5265
+ const REQUIRED = input.required;
5266
+ const env = input.env ?? process.env;
5267
+ const present = (name) => (env[name] ?? "") !== "";
5268
+ let merged = env;
5269
+ if (!REQUIRED.every(present)) {
5270
+ const result = (input.spawn ?? spawnSync)("op", [
5271
+ "environment",
5272
+ "secret",
5273
+ "list",
5274
+ input.environment,
5275
+ "--reveal",
5276
+ "--format=dotenv"
5277
+ ], {
5278
+ encoding: "utf8",
5279
+ stdio: [
5280
+ "inherit",
5281
+ "pipe",
5282
+ "pipe"
5283
+ ]
5284
+ });
5285
+ if (result.error || result.status !== 0) {
5286
+ const why = result.error?.message ?? result.stderr.trim().split("\n")[0];
5287
+ throw new Error(`could not read the 1Password Environment "${input.environment}": ${why || "op failed"}`);
5288
+ }
5289
+ merged = {
5290
+ ...parse(String(result.stdout)),
5291
+ ...Object.fromEntries(Object.entries(env).filter(([, v]) => v !== void 0 && v !== ""))
5292
+ };
5293
+ }
5294
+ const missing = REQUIRED.filter((name) => (merged[name] ?? "") === "");
5295
+ if (missing.length > 0) throw new Error(`missing from the environment and from "${input.environment}": ${missing.join(", ")}`);
5296
+ return merged;
5297
+ }
5298
+ /**
5299
+ * One line saying where this run's structured logs go: they ship to Axiom when both variables are set. Names the
5300
+ * dataset (not a secret) and never the token, so a development run does not quietly write into production's dataset.
5301
+ */
5302
+ function describeLogging(env, options) {
5303
+ const token = env[options.tokenVar];
5304
+ const dataset = env[options.datasetVar];
5305
+ return token && dataset ? `logs: shipped to Axiom, dataset "${dataset}"` : `logs: not shipped to Axiom (${options.tokenVar} and ${options.datasetVar} are not both set)`;
5306
+ }
5307
+ const LOOPBACK$1 = "127.0.0.1";
5308
+ /** GitHub caps a webhook payload at 25 MB; anything larger is not one. */
5309
+ const MAX_BODY = 27262976;
5310
+ /** The request body, or `undefined` when it is larger than a webhook can be. */
5311
+ async function readBody(req) {
5312
+ const chunks = [];
5313
+ let size = 0;
5314
+ for await (const chunk of req) {
5315
+ size += chunk.length;
5316
+ if (size > MAX_BODY) return void 0;
5317
+ chunks.push(chunk);
5318
+ }
5319
+ return Buffer.concat(chunks);
5320
+ }
5321
+ /**
5322
+ * Serves a `(Request, env) => Response` handler over HTTP on the loopback address, for a development instance behind
5323
+ * a tunnel: the same function the Vercel entry (e.g. Sentinel's `api/webhook.mjs`) calls, with the same web-standard `Request`. Only
5324
+ * the handler's own path is served. A request is logged as one line (method, path, status) and nothing else, so no
5325
+ * signature, token or payload reaches the terminal.
5326
+ */
5327
+ async function startDevServer(input) {
5328
+ const path = input.path ?? "/api/webhook";
5329
+ const log = input.log ?? (() => {});
5330
+ const server = createServer(async (req, res) => {
5331
+ const method = req.method;
5332
+ const url = new URL(req.url, `http://${LOOPBACK$1}`);
5333
+ const reply = (status, body, headers = {}) => {
5334
+ log(`${method} ${url.pathname} ${status}`);
5335
+ res.writeHead(status, headers);
5336
+ res.end(body);
5337
+ };
5338
+ if (url.pathname !== path) return reply(404, "Not Found");
5339
+ const hasBody = method !== "GET" && method !== "HEAD";
5340
+ const body = hasBody ? await readBody(req) : void 0;
5341
+ if (hasBody && body === void 0) return reply(413, "Payload Too Large");
5342
+ const headers = new Headers();
5343
+ for (let i = 0; i < req.rawHeaders.length; i += 2) headers.append(req.rawHeaders[i], req.rawHeaders[i + 1]);
5344
+ try {
5345
+ const response = await input.handle(new Request(`http://${req.headers.host}${req.url}`, {
5346
+ method,
5347
+ headers,
5348
+ ...body ? { body } : {}
5349
+ }), input.env);
5350
+ reply(response.status, Buffer.from(await response.arrayBuffer()), Object.fromEntries(response.headers));
5351
+ } catch {
5352
+ reply(500, "Internal Server Error");
5353
+ }
5354
+ });
5355
+ await new Promise((resolve) => server.listen(input.port, LOOPBACK$1, resolve));
5356
+ const { port } = server.address();
5357
+ return {
5358
+ url: `http://${LOOPBACK$1}:${port}${path}`,
5359
+ close: () => new Promise((resolve) => {
5360
+ server.close(() => resolve());
5361
+ server.closeAllConnections();
5362
+ })
5363
+ };
5364
+ }
5365
+ /**
5366
+ * Runs a web-standard handler locally: loads its environment, puts it in `process.env`, imports the handler, serves
5367
+ * it on the loopback address and says where it is listening and where its logs go. The server stops, and the process
5368
+ * exits, on SIGINT and SIGTERM.
5369
+ *
5370
+ * @returns The running server.
5371
+ */
5372
+ async function serveHandler(input) {
5373
+ const log = input.log ?? ((line) => console.log(line));
5374
+ const settings = input.env ?? process.env;
5375
+ const env = loadDevEnv({
5376
+ environment: input.environment,
5377
+ required: input.required,
5378
+ env: settings
5379
+ });
5380
+ Object.assign(process.env, env);
5381
+ const server = await startDevServer({
5382
+ handle: await input.handler(),
5383
+ env,
5384
+ port: input.port,
5385
+ ...input.path ? { path: input.path } : {},
5386
+ log
5387
+ });
5388
+ log(`listening on ${server.url}, secrets from "${input.environment}"`);
5389
+ if (input.logging) log(describeLogging(env, input.logging));
5390
+ const stop = input.onSignal ?? ((close) => void close().then(() => process.exit(0)));
5391
+ for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => stop(server.close));
5392
+ return server;
5393
+ }
5394
+ // src/commands/dev-serve/dev-serve.ts
5395
+ /**
5396
+ * `holocron dev serve` — the application `holocron dev` runs when `dev.serve` names a handler: it loads the handler
5397
+ * and serves it on `PORT` (the tunnel's), with the variables `holocron dev` read from the vault already in its
5398
+ * environment. Run by hand it reads them from the vault environment itself, through `op`.
5399
+ */
5400
+ /** Imports a module by path, compiling TypeScript as it goes. */
5401
+ async function importWithTsx(path) {
5402
+ const { tsImport } = await import("tsx/esm/api");
5403
+ return await tsImport(pathToFileURL(path).href, import.meta.url);
5404
+ }
5405
+ /**
5406
+ * Serves the handler `dev.serve` names. The handler's module is imported after the environment is in `process.env`,
5407
+ * because one that reads `process.env` when it loads would otherwise see the wrong one.
5408
+ *
5409
+ * @throws When the module does not export a function under the configured name.
5410
+ */
5411
+ async function runDevServe(input) {
5412
+ const importModule = input.importModule ?? importWithTsx;
5413
+ const name = input.serve.export ?? "default";
5414
+ await (input.serveHandler ?? serveHandler)({
5415
+ environment: input.environment,
5416
+ required: input.serve.required ?? [],
5417
+ logging: input.serve.logging,
5418
+ port: input.port,
5419
+ handler: async () => {
5420
+ const path = resolve(input.cwd, input.serve.handler);
5421
+ const handler = (await importModule(path))[name];
5422
+ if (typeof handler !== "function") throw new Error(`\`dev.serve\`: ${path} does not export a function named "${name}"`);
5423
+ return handler;
5424
+ }
5425
+ });
5426
+ }
5427
+ // src/commands/dev-serve/dev-serve.command.ts
5428
+ const devServeCommand = {
5429
+ command: "serve",
5430
+ describe: "Serve the handler `dev.serve` names on PORT: the application `holocron dev` runs when it is configured, not usually run by hand",
5431
+ handler: async (argv) => {
5432
+ const dev = (await loadConfig(argv.cwd)).resolved.dev;
5433
+ if (!dev?.serve) {
5434
+ reportError("dev serve: needs a handler in `dev.serve` in holocron.config.ts");
5435
+ process.exitCode = 1;
5436
+ return;
5437
+ }
5438
+ try {
5439
+ await runDevServe({
5440
+ cwd: argv.cwd,
5441
+ environment: dev.environment ?? "",
5442
+ serve: dev.serve,
5443
+ port: Number(process.env["PORT"] ?? dev.port ?? 3e3)
5444
+ });
5445
+ } catch (err) {
5446
+ reportError(`dev serve: ${errorMessage(err)}`);
5447
+ process.exitCode = 1;
5448
+ }
5449
+ }
5450
+ };
5248
5451
  // src/commands/resolve-dev-options/resolve-dev-options.ts
5249
5452
  /** The port used when neither a flag nor the config gives one. */
5250
5453
  const DEFAULT_PORT = 3e3;
5251
5454
  /**
5252
5455
  * The options `holocron dev` runs with: a flag wins over the `dev` block of `holocron.config`, which wins over the
5253
5456
  * default port. Throws one message naming everything that is missing and where it could be given, so a first run does
5254
- * not have to be fixed one error at a time.
5457
+ * not have to be fixed one error at a time. `self` is how to run this CLI again, for the `dev serve` application.
5255
5458
  */
5256
- function resolveDevOptions(flags, config) {
5459
+ function resolveDevOptions(flags, config, self = [process.execPath, process.argv[1]]) {
5257
5460
  const environment = flags.environment ?? config?.environment;
5258
5461
  const name = flags.name ?? config?.tunnel?.name;
5259
5462
  const hostname = flags.hostname ?? config?.tunnel?.hostname;
5260
- const command = flags.command?.length ? flags.command : config?.command;
5463
+ const command = flags.command?.length ? flags.command : config?.command ?? (config?.serve ? [
5464
+ ...self,
5465
+ "dev",
5466
+ "serve"
5467
+ ] : void 0);
5261
5468
  const missing = [];
5262
5469
  if (!environment) missing.push("an environment (--environment, or `dev.environment`)");
5263
5470
  if (!name) missing.push("a tunnel name (--name, or `dev.tunnel.name`)");
5264
5471
  if (!hostname) missing.push("a hostname (--hostname, or `dev.tunnel.hostname`)");
5265
- if (!command?.length) missing.push("the application's command (after --, or `dev.command`)");
5472
+ if (!command?.length) missing.push("the application's command (after --, `dev.command`, or a handler in `dev.serve`)");
5266
5473
  if (missing.length > 0) throw new Error(`dev needs ${missing.join("; ")}, in holocron.config.ts or on the command line`);
5267
5474
  return {
5268
5475
  environment,
@@ -5706,7 +5913,7 @@ const devArgs = (yy) => yy.option("environment", {
5706
5913
  const devCommand = {
5707
5914
  command: "dev",
5708
5915
  describe: "Run an application locally behind its development tunnel, with its secrets from the vault (command after --)",
5709
- builder: devArgs,
5916
+ builder: (y) => devArgs(y).command(devServeCommand),
5710
5917
  handler: async (argv) => {
5711
5918
  const tokens = tokenContext(argv.token);
5712
5919
  if (!tokens) return;
@@ -5718,7 +5925,12 @@ const devCommand = {
5718
5925
  hostname: argv.hostname,
5719
5926
  port: argv.port,
5720
5927
  command: argv["--"]
5721
- }, loaded.resolved.dev);
5928
+ }, loaded.resolved.dev, [
5929
+ process.execPath,
5930
+ process.argv[1],
5931
+ "--cwd",
5932
+ argv.cwd
5933
+ ]);
5722
5934
  if ((await runDev({
5723
5935
  loaded,
5724
5936
  context: {