@theholocron/cli 5.0.0-alpha.327 → 5.0.0-alpha.328

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
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
+ import { closeSync, constants, copyFileSync, existsSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
4
4
  import { LOG_LEVELS, NoopAnalyticsSink, NoopErrorSink, redactObject } from "@theholocron/observability/core";
5
5
  import yargs from "yargs";
6
6
  import { hideBin } from "yargs/helpers";
@@ -27,10 +27,10 @@ import { readGitRemote, updateGitignore } from "@theholocron/git-utils";
27
27
  import { bumpCatalogPins, discoverWorkspacePackages, parseCatalogs, readPackageJson, readPackageJsonSync, resolveWorkspaceGlobs } from "@theholocron/pkg-utils";
28
28
  import { errorMessage } from "@theholocron/misc-utils";
29
29
  import { pathToFileURL } from "node:url";
30
+ import { stringifyJson } from "@theholocron/json-utils";
30
31
  import { findRootSync, isWorkspaceRoot, walkFilesSync } from "@theholocron/fs-utils";
31
32
  import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
32
33
  import { createServer } from "node:http";
33
- import { stringifyJson } from "@theholocron/json-utils";
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";
@@ -473,6 +473,7 @@ const COMMAND_CONTEXTS = {
473
473
  run: "repo-aware",
474
474
  "run ci": "repo-aware",
475
475
  "deploy on-release": "repo-aware",
476
+ "deploy stage": "repo-aware",
476
477
  "config show": "repo-aware",
477
478
  "repo sync readme": "repo-aware",
478
479
  doctor: "workspace",
@@ -4747,6 +4748,180 @@ const cleanupPreviewCommand = {
4747
4748
  })).status === "fail") process.exitCode = 1;
4748
4749
  }
4749
4750
  };
4751
+ // src/commands/deploy-stage/deploy-stage.args.ts
4752
+ const deployStageArgs = (y) => y.option("package-dir", {
4753
+ type: "string",
4754
+ describe: "The package to stage. Default: the current directory."
4755
+ }).option("out", {
4756
+ type: "string",
4757
+ describe: "Where to write the payload. Default: `.vercel-deploy` inside the package."
4758
+ });
4759
+ // src/commands/deploy-stage/undeclared-externals.ts
4760
+ /** `"@scope/pkg/sub"` → `"@scope/pkg"`, `"pkg/sub"` → `"pkg"`. */
4761
+ function packageName(specifier) {
4762
+ const parts = specifier.split("/");
4763
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
4764
+ }
4765
+ /**
4766
+ * Lists the packages a built bundle imports that aren't declared
4767
+ * dependencies (holocron#922). `deploy stage` writes a trimmed
4768
+ * `package.json` holding only the package's own `dependencies`, and the host
4769
+ * installs exactly those. A bundler that inlines workspace packages but leaves
4770
+ * *their* npm imports external turns a new dependency of one of them into an
4771
+ * import in `dist/` that nothing installs. Caught at staging instead of as a
4772
+ * "Cannot find module" crash.
4773
+ *
4774
+ * @param source The built bundle's code.
4775
+ * @param dependencies The package's declared `dependencies`.
4776
+ * @returns Sorted package names imported but not declared; `node:` builtins excluded.
4777
+ */
4778
+ function undeclaredExternals(source, dependencies) {
4779
+ const STATIC = /^\s*(?:import|export)\b[^"'\n;]*?["']([^"'./][^"']*)["']/gm;
4780
+ const DYNAMIC = /\bimport\(\s*["']([^"'./][^"']*)["']\s*\)/g;
4781
+ const specifiers = [...source.matchAll(STATIC), ...source.matchAll(DYNAMIC)].map((m) => m[1]);
4782
+ return [...new Set(specifiers.filter((s) => !s.startsWith("node:")).map(packageName))].filter((name) => !(name in dependencies)).sort();
4783
+ }
4784
+ // src/commands/deploy-stage/vercel-engines.ts
4785
+ /**
4786
+ * Vercel only accepts a major-version `engines.node` (`"22.x"`), and fails
4787
+ * the deployment's `npm install` step with `invalid_version_value` on an
4788
+ * open range like `">=22"` (holocron#911, found live: the deploy that
4789
+ * shipped holocron#910's fix never went live because of exactly this).
4790
+ * Takes the first major number in the package's own range, its floor, and
4791
+ * pins that major rather than passing the range through verbatim.
4792
+ *
4793
+ * @param engines The package's `engines` field, if it has one.
4794
+ * @returns `engines` with `node` pinned to a major; unchanged when it has no `node`.
4795
+ */
4796
+ function vercelEngines(engines) {
4797
+ const range = engines?.["node"];
4798
+ if (!engines || !range) return engines;
4799
+ const major = /\d+/.exec(range)?.[0];
4800
+ if (!major) throw new Error(`cannot derive a Vercel Node.js major from engines.node "${range}"`);
4801
+ return {
4802
+ ...engines,
4803
+ node: `${major}.x`
4804
+ };
4805
+ }
4806
+ // src/commands/deploy-stage/deploy-stage.ts
4807
+ /**
4808
+ * `holocron deploy stage` — assembles `.vercel-deploy/`, exactly what
4809
+ * `holocron deploy --files` should upload for a Vercel Function package such as
4810
+ * Sentinel, nothing more. The package itself also holds source, tests, coverage
4811
+ * output and its own dev tooling config, none of which belongs in the payload.
4812
+ *
4813
+ * Output:
4814
+ * .vercel-deploy/
4815
+ * api/webhook.mjs — the Vercel Function entry point (checked in, copied verbatim)
4816
+ * dist/index.mjs — the package's built library (run `delivery.build` first)
4817
+ * vercel.json — checked in, copied verbatim: `functions["api/webhook.mjs"]
4818
+ * .includeFiles: "node_modules/**"` forces Vercel to ship the
4819
+ * function's ENTIRE installed node_modules, bypassing
4820
+ * `@vercel/nft`'s static file tracer. Needed because
4821
+ * commitlint's own config-resolution chain
4822
+ * (`@theholocron/commitlint-config` → `@commitlint/
4823
+ * config-conventional` → `conventional-changelog-
4824
+ * conventionalcommits` → ...) is resolved by *string name*
4825
+ * at runtime (`extends: [...]`), never through a real
4826
+ * import/require nft could trace — found live chasing one
4827
+ * "Cannot find module" at a time through that exact chain
4828
+ * (holocron#776-#778) before landing on this instead. The
4829
+ * function's node_modules is already fully controlled by the
4830
+ * trimmed `package.json` below (nothing extra to prune), so
4831
+ * there is no upside to nft's pruning here, only risk.
4832
+ * package.json — trimmed: name/version/type/engines + dependencies only,
4833
+ * each pinned to the exact version actually resolved in
4834
+ * node_modules right now (not the "workspace:" / "catalog:"
4835
+ * pnpm protocol specifiers — Vercel's `npm install` doesn't
4836
+ * understand those; it needs real, installable versions).
4837
+ * No devDependencies, no scripts.
4838
+ *
4839
+ * The `@theholocron/*` workspace packages (astromech, datapad, cli) are
4840
+ * inlined into `dist/` by the package's bundler config (holocron#922), so the
4841
+ * code it runs is the code it was built from, whatever version gets pinned
4842
+ * here. They stay in `dependencies` because a repo's own `holocron.config.ts`
4843
+ * imports `@theholocron/cli` / `astromech/config` at runtime (only
4844
+ * `defineConfig`, an identity function, so a version skew there is harmless).
4845
+ * Pinned versions still have to exist on npm: deploy from a synced `alpha`
4846
+ * checkout, not an unreleased local branch.
4847
+ */
4848
+ function installedVersion(packageDir, name) {
4849
+ const pkgPath = join(packageDir, "node_modules", name, "package.json");
4850
+ if (!existsSync(pkgPath)) throw new Error(`cannot resolve installed version of "${name}" — run \`pnpm install\` first (looked in ${pkgPath})`);
4851
+ return JSON.parse(readFileSync(pkgPath, "utf8")).version;
4852
+ }
4853
+ /**
4854
+ * Stages the deploy payload for `packageDir`. Refuses (before writing anything)
4855
+ * when the built bundle imports a package the trimmed `package.json` won't
4856
+ * install, since that payload would crash on import once deployed.
4857
+ *
4858
+ * @returns `ok` with the payload's directory and pinned dependencies, or `fail` with why.
4859
+ */
4860
+ function stageDeploy(input) {
4861
+ const { packageDir } = input;
4862
+ const outDir = input.outDir ?? join(packageDir, ".vercel-deploy");
4863
+ const print = input.print ?? (() => {});
4864
+ const resolveVersion = input.resolveVersion ?? installedVersion;
4865
+ try {
4866
+ const distIndex = join(packageDir, "dist", "index.mjs");
4867
+ if (!existsSync(distIndex)) throw new Error(`${distIndex} not found — run \`pnpm run delivery.build\` first`);
4868
+ const pkg = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
4869
+ const missing = undeclaredExternals(readFileSync(distIndex, "utf8"), pkg.dependencies ?? {});
4870
+ if (missing.length > 0) throw new Error([
4871
+ "refusing to stage: dist/index.mjs imports packages that aren't in this package's `dependencies`,",
4872
+ "so Vercel wouldn't install them —",
4873
+ ...missing.map((name) => ` - ${name}`),
4874
+ "Add each to the package's package.json (usually a new dependency of an inlined workspace package)."
4875
+ ].join("\n"));
4876
+ const dependencies = Object.fromEntries(Object.keys(pkg.dependencies ?? {}).map((name) => [name, resolveVersion(packageDir, name)]));
4877
+ rmSync(outDir, {
4878
+ recursive: true,
4879
+ force: true
4880
+ });
4881
+ mkdirSync(join(outDir, "api"), { recursive: true });
4882
+ mkdirSync(join(outDir, "dist"), { recursive: true });
4883
+ copyFileSync(join(packageDir, "api", "webhook.mjs"), join(outDir, "api", "webhook.mjs"));
4884
+ copyFileSync(distIndex, join(outDir, "dist", "index.mjs"));
4885
+ copyFileSync(join(packageDir, "vercel.json"), join(outDir, "vercel.json"));
4886
+ const deployPkg = {
4887
+ name: pkg.name,
4888
+ version: pkg.version,
4889
+ type: "module",
4890
+ engines: vercelEngines(pkg.engines),
4891
+ dependencies
4892
+ };
4893
+ writeFileSync(join(outDir, "package.json"), stringifyJson(deployPkg));
4894
+ print(`Staged deploy payload at ${outDir}`);
4895
+ print(` dependencies: ${Object.entries(dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
4896
+ return {
4897
+ status: "ok",
4898
+ outDir,
4899
+ dependencies
4900
+ };
4901
+ } catch (error) {
4902
+ return {
4903
+ status: "fail",
4904
+ message: errorMessage(error)
4905
+ };
4906
+ }
4907
+ }
4908
+ // src/commands/deploy-stage/deploy-stage.command.ts
4909
+ const deployStageCommand = {
4910
+ command: "stage",
4911
+ describe: "Assemble the payload `deploy --files` uploads for a Vercel Function package (built bundle, entry, trimmed package.json)",
4912
+ builder: deployStageArgs,
4913
+ handler: (argv) => {
4914
+ const report = stageDeploy({
4915
+ packageDir: resolve(argv.cwd, argv.packageDir ?? "."),
4916
+ ...argv.out ? { outDir: resolve(argv.cwd, argv.out) } : {},
4917
+ print: (line) => console.log(line)
4918
+ });
4919
+ if (report.status === "fail") {
4920
+ reportError(`deploy stage: ${report.message}`);
4921
+ process.exitCode = 1;
4922
+ }
4923
+ }
4924
+ };
4750
4925
  // src/commands/deploy/deploy.args.ts
4751
4926
  const deployArgs = (y) => y.positional("branch", {
4752
4927
  type: "string",
@@ -5033,7 +5208,7 @@ async function runDeployFromFiles(input) {
5033
5208
  const deployCommand = {
5034
5209
  command: "deploy [branch]",
5035
5210
  describe: "Trigger a deployment via the configured `deployment` capability",
5036
- builder: (y) => deployArgs(y).command(cleanupPreviewCommand).command(deployOnReleaseCommand),
5211
+ builder: (y) => deployArgs(y).command(cleanupPreviewCommand).command(deployOnReleaseCommand).command(deployStageCommand),
5037
5212
  handler: async (argv) => {
5038
5213
  if (!argv.projectId) {
5039
5214
  reportError("deploy: missing required argument --project-id");