@forwardimpact/libcli 0.1.12 → 0.1.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forwardimpact/libcli",
3
- "version": "0.1.12",
3
+ "version": "0.1.14",
4
4
  "description": "Agent-friendly CLIs — self-documenting entry points that humans and agents reach through the same interface.",
5
5
  "keywords": [
6
6
  "cli",
package/src/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { HelpRenderer } from "./help.js";
3
3
  import { freezeInvocationContext } from "./invocation-context.js";
4
+ import { resolveVersion } from "./version.js";
4
5
 
5
6
  /** Command-line interface that parses argv against a definition of commands, options, and help. */
6
7
  export class Cli {
@@ -180,17 +181,25 @@ export class Cli {
180
181
  }
181
182
 
182
183
  /**
183
- * Create a Cli instance. When `runtime` is provided, error,
184
- * usage-error, and help output route through `runtime.proc` instead of the
185
- * global `process`. The zero-arg form keeps reading the global `process` as a
186
- * deprecated alias for one migration cycle.
184
+ * Create a Cli instance. Error, usage-error, and help output route through the
185
+ * injected `runtime.proc`.
187
186
  * @param {object} definition - The CLI definition.
188
- * @param {object} [options]
189
- * @param {import('@forwardimpact/libutil/runtime').Runtime} [options.runtime]
187
+ * @param {object} options
188
+ * @param {import('@forwardimpact/libutil/runtime').Runtime} options.runtime
189
+ * @param {URL|string} [options.packageJsonUrl] - When provided and the definition
190
+ * carries no explicit `version`, resolve it via {@link resolveVersion} so every
191
+ * bin shares one compile-time version literal. Explicit `definition.version` wins.
190
192
  * @returns {Cli}
191
193
  */
192
- export function createCli(definition, { runtime } = {}) {
193
- const proc = runtime ? runtime.proc : process;
194
+ export function createCli(definition, { runtime, packageJsonUrl } = {}) {
195
+ if (!runtime) throw new Error("runtime is required");
196
+ if (definition.version === undefined && packageJsonUrl !== undefined) {
197
+ definition = {
198
+ ...definition,
199
+ version: resolveVersion({ packageJsonUrl, runtime }),
200
+ };
201
+ }
202
+ const proc = runtime.proc;
194
203
  const helpRenderer = new HelpRenderer({ process: proc });
195
204
  return new Cli(definition, { process: proc, helpRenderer });
196
205
  }
package/src/embed.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Embedded assets for `bun build --compile` binaries.
3
+ *
4
+ * A compiled CLI runs from Bun's virtual `/$bunfs` filesystem with no
5
+ * `node_modules` tree, so the runtime tricks that locate package data
6
+ * directories on disk — `import.meta.resolve("@scope/pkg")` plus
7
+ * `readFileSync(join(dir, name))` — both fail. The `--help` smoke gate never
8
+ * exercises those paths, so the breakage ships silently.
9
+ *
10
+ * This module is the runtime half of the fix. The build half (driven by a
11
+ * CLI's `assets` block in `build/cli-manifest.json`, see `build/gen-embed.mjs`)
12
+ * inlines each asset file's text into the bundle and calls {@link registerAssets}
13
+ * at startup. Consumers then resolve asset directories through {@link embeddedDir}
14
+ * and overlay their runtime with {@link withEmbeddedAssets} so the existing
15
+ * `fsSync`-based loaders read embedded content transparently — no loader changes.
16
+ *
17
+ * In source/npx execution nothing registers, so {@link embeddedAssetsActive}
18
+ * is false, {@link withEmbeddedAssets} is a no-op, and callers fall back to the
19
+ * on-disk resolution they already use.
20
+ */
21
+
22
+ import { normalize, sep } from "node:path";
23
+
24
+ // Sentinel root for embedded asset paths. Chosen to never collide with a real
25
+ // filesystem path. `embeddedDir(mount)` hangs logical mounts off it, and the
26
+ // fs overlay recognises this prefix to serve content from the registry.
27
+ const EMBED_ROOT = "/__fit_embed__";
28
+
29
+ /** @type {Map<string, string>} logical path (`<mount>/<relPosix>`) → file text. */
30
+ const registry = new Map();
31
+
32
+ /**
33
+ * Register a mount's files. Called by the generated barrel that the compile
34
+ * step prepends to the entry point.
35
+ *
36
+ * @param {string} mount - Logical namespace, e.g. `"libsyntheticprose/prompts"`.
37
+ * @param {Record<string, string>} files - Map of posix relative path → text.
38
+ */
39
+ export function registerAssets(mount, files) {
40
+ for (const [rel, content] of Object.entries(files)) {
41
+ registry.set(`${mount}/${rel}`, content);
42
+ }
43
+ }
44
+
45
+ /** Whether any embedded assets were registered (true only in compiled builds). */
46
+ export function embeddedAssetsActive() {
47
+ return registry.size > 0;
48
+ }
49
+
50
+ /**
51
+ * True when this process is a `bun build --compile` standalone binary.
52
+ *
53
+ * `build/build-binary.sh` passes `--define process.env.LIBCLI_IS_COMPILED="1"`,
54
+ * so Bun substitutes the literal member expression `process.env.LIBCLI_IS_COMPILED`
55
+ * with `"1"` across the whole bundle (this file included) at compile time and
56
+ * the comparison folds to `true`. In source/npx/test execution the env var is
57
+ * normally unset, so it is `false`. This mirrors the `LIBCLI_PACKAGE_VERSION`
58
+ * literal trick in version.js — an explicit, platform-independent build-time
59
+ * contract rather than sniffing Bun's internal `/$bunfs` path convention.
60
+ *
61
+ * The read must stay the literal token `process.env.LIBCLI_IS_COMPILED` — that
62
+ * is what `--define` replaces; a dynamic `process.env[name]` would not be.
63
+ *
64
+ * @type {boolean}
65
+ */
66
+ export const LIBCLI_IS_COMPILED = process.env.LIBCLI_IS_COMPILED === "1";
67
+
68
+ /**
69
+ * Virtual directory for a registered mount. Joining a filename onto it yields a
70
+ * path the {@link withEmbeddedAssets} overlay resolves from the registry, so a
71
+ * directory-based loader (`join(dir, name)` → `readFileSync`) works unchanged.
72
+ *
73
+ * @param {string} mount - Same namespace passed to {@link registerAssets}.
74
+ * @returns {string}
75
+ */
76
+ export function embeddedDir(mount) {
77
+ return `${EMBED_ROOT}/${mount}`;
78
+ }
79
+
80
+ /**
81
+ * Map a filesystem path under {@link EMBED_ROOT} to its registry key, or null
82
+ * if the path is not an embedded-asset path (normal file → delegate to disk).
83
+ */
84
+ function toLogicalKey(p) {
85
+ if (typeof p !== "string") return null;
86
+ const posix = normalize(p).split(sep).join("/");
87
+ if (posix !== EMBED_ROOT && !posix.startsWith(`${EMBED_ROOT}/`)) return null;
88
+ return posix.slice(EMBED_ROOT.length + 1);
89
+ }
90
+
91
+ /**
92
+ * Return a runtime whose `fsSync` serves embedded assets for paths under the
93
+ * sentinel root and delegates everything else to the real filesystem. No-op
94
+ * when no assets are registered, so it is safe to call unconditionally.
95
+ *
96
+ * @template {{ fsSync: object }} R
97
+ * @param {R} runtime
98
+ * @returns {R}
99
+ */
100
+ export function withEmbeddedAssets(runtime) {
101
+ if (!embeddedAssetsActive()) return runtime;
102
+ const base = runtime.fsSync;
103
+ const fsSync = {
104
+ ...base,
105
+ existsSync(p) {
106
+ const key = toLogicalKey(p);
107
+ if (key !== null && registry.has(key)) return true;
108
+ return base.existsSync(p);
109
+ },
110
+ readFileSync(p, ...rest) {
111
+ const key = toLogicalKey(p);
112
+ if (key !== null && registry.has(key)) return registry.get(key);
113
+ return base.readFileSync(p, ...rest);
114
+ },
115
+ };
116
+ return Object.freeze({ ...runtime, fsSync });
117
+ }
package/src/index.js CHANGED
@@ -1,4 +1,12 @@
1
1
  export { Cli, createCli } from "./cli.js";
2
+ export { resolveVersion } from "./version.js";
3
+ export {
4
+ registerAssets,
5
+ embeddedAssetsActive,
6
+ LIBCLI_IS_COMPILED,
7
+ embeddedDir,
8
+ withEmbeddedAssets,
9
+ } from "./embed.js";
2
10
  export { freezeInvocationContext } from "./invocation-context.js";
3
11
  export { HelpRenderer } from "./help.js";
4
12
  export { SummaryRenderer } from "./summary.js";
package/src/version.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Resolve a CLI's version string — the version of the package the binary was
3
+ * built from (e.g. fit-terrain's), which libcli merely surfaces; not libcli's
4
+ * own version. In a `bun build --compile` binary,
5
+ * `process.env.LIBCLI_PACKAGE_VERSION` is replaced at build time by
6
+ * `build/build-binary.sh`'s `--define`, so this returns the injected literal and
7
+ * the package.json read below is dead code (it never executes — and tree-shakes).
8
+ * In source/npx execution the env var is normally unset and the read supplies the
9
+ * version; setting LIBCLI_PACKAGE_VERSION in the environment overrides it (used by
10
+ * bin-smoke integration tests).
11
+ *
12
+ * The read must be written as the literal member expression
13
+ * `process.env.LIBCLI_PACKAGE_VERSION` — that is the token `bun build --define`
14
+ * substitutes across the whole bundle, including this bundled library. A dynamic
15
+ * `process.env[name]` would not be replaced.
16
+ *
17
+ * @param {object} args
18
+ * @param {URL|string} args.packageJsonUrl - `new URL("../package.json", import.meta.url)`
19
+ * @param {import('@forwardimpact/libutil/runtime').Runtime} args.runtime
20
+ * @returns {string}
21
+ */
22
+ export function resolveVersion({ packageJsonUrl, runtime }) {
23
+ const injected = process.env.LIBCLI_PACKAGE_VERSION; // literal — the --define target
24
+ if (injected) return injected;
25
+ const text = runtime.fsSync.readFileSync(packageJsonUrl, "utf8");
26
+ return JSON.parse(text).version;
27
+ }