@notation/factory-cli 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Notation Labs Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/factory.ts ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env bun
2
+ import { infraDown, infraUp } from "../commands/infra.ts";
3
+ import { repoInstall, repoStatus } from "../commands/repo.ts";
4
+
5
+ const usage = `Usage:
6
+ factory infra up [--dry-run] deploy the hub in this directory
7
+ factory infra down destroy the hub in this directory
8
+ factory repo install [--repo <owner/name>]
9
+ install the hub's GitHub Apps on this repo,
10
+ and wait for its outpost to deploy
11
+ factory repo status [--repo <owner/name>]
12
+ show how this repo's last deploy went`;
13
+
14
+ const flag = (args: string[], name: string) => {
15
+ const index = args.indexOf(name);
16
+ return index === -1 ? undefined : args[index + 1];
17
+ };
18
+
19
+ const [group, command, ...args] = process.argv.slice(2);
20
+ const dryRun = args.includes("--dry-run");
21
+ const repo = flag(args, "--repo");
22
+
23
+ const run = async () => {
24
+ if (group === "infra" && command === "up") return infraUp({ dryRun });
25
+ if (group === "infra" && command === "down") return infraDown();
26
+ if (group === "repo" && command === "install") return repoInstall({ repo });
27
+ if (group === "repo" && command === "status") return repoStatus({ repo });
28
+ console.error(usage);
29
+ process.exitCode = 1;
30
+ };
31
+
32
+ try {
33
+ await run();
34
+ } catch (error) {
35
+ console.error(`factory: ${error instanceof Error ? error.message : error}`);
36
+ process.exitCode = 1;
37
+ }
@@ -0,0 +1,29 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { loadConfig, shell } from "./shell.ts";
4
+
5
+ const hubDir = () => {
6
+ const dir = process.cwd();
7
+ if (!existsSync(join(dir, "factory.infra.ts"))) {
8
+ throw new Error(`There's no factory.infra.ts in ${dir}. Run this in the hub's repo.`);
9
+ }
10
+ return dir;
11
+ };
12
+
13
+ const notation = async (args: string) => {
14
+ const dir = hubDir();
15
+ const { loadEnv } = await loadConfig(dir);
16
+ await shell(`${loadEnv ? `${loadEnv} ` : ""}npx notation ${args} --pretty`, dir);
17
+ };
18
+
19
+ /** Deploys the hub. Deploy also syncs each connection with the router. */
20
+ export const infraUp = async ({ dryRun }: { dryRun: boolean }) => {
21
+ await notation(dryRun ? "plan" : "deploy");
22
+ if (!dryRun) {
23
+ console.log("\nThe hub is up. To serve a repo, run `factory repo install` in it.");
24
+ }
25
+ };
26
+
27
+ export const infraDown = async () => {
28
+ await notation("destroy");
29
+ };
@@ -0,0 +1,166 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { pathToFileURL } from "node:url";
5
+ import { appName } from "@notation/factory-github/app-name";
6
+ import { collectResourceGraph } from "@notation/resource";
7
+ import { loadConfig, openBrowser, output } from "./shell.ts";
8
+
9
+ /** The repo's `owner/name`, from its `origin` remote on GitHub. */
10
+ const githubRepo = async (dir: string) => {
11
+ const url = await output("git", ["remote", "get-url", "origin"], dir);
12
+ const match = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/);
13
+ if (!match) throw new Error(`The origin remote ${url} isn't on GitHub.`);
14
+ return `${match[1]}/${match[2]}`;
15
+ };
16
+
17
+ /** The names of the GitHub connections that `.factory/config.ts` uses. */
18
+ const githubConnections = async (config: string) => {
19
+ const graph = await collectResourceGraph(async () => {
20
+ await import(pathToFileURL(config).href);
21
+ });
22
+ return graph.resourceGroups
23
+ .filter((group) => group.type === "github/ConnectionRef")
24
+ .map((group) => (group.config as { name: string }).name);
25
+ };
26
+
27
+ /** The slug GitHub gives an App with this name: `factory--test--gh` becomes `factory-test-gh`. */
28
+ const appSlug = (name: string) =>
29
+ name
30
+ .toLowerCase()
31
+ .replace(/[^a-z0-9]+/g, "-")
32
+ .replace(/^-|-$/g, "");
33
+
34
+ const gh = async <T>(path: string) =>
35
+ JSON.parse(await output("gh", ["api", path])) as T;
36
+
37
+ /** The outpost's directory: this one if it has `.factory/config.ts`, otherwise the root of its git repo. */
38
+ const outpostDir = async () => {
39
+ if (existsSync(join(process.cwd(), ".factory", "config.ts"))) {
40
+ return process.cwd();
41
+ }
42
+ const root = await output("git", ["rev-parse", "--show-toplevel"]);
43
+ if (!existsSync(join(root, ".factory", "config.ts"))) {
44
+ throw new Error(`There's no .factory/config.ts here or in ${root}.`);
45
+ }
46
+ return root;
47
+ };
48
+
49
+ /**
50
+ * The outpost's repo: `given`, then `repo` in `factory.config.ts`, then the
51
+ * `origin` remote. The remote only names the outpost's repo when the outpost
52
+ * is at the root of the git repo.
53
+ */
54
+ const outpostRepo = async (dir: string, given?: string) => {
55
+ const repo = given ?? (await loadConfig(dir)).repo;
56
+ if (repo) return repo;
57
+ const root = await output("git", ["rev-parse", "--show-toplevel"], dir);
58
+ if (realpathSync(root) !== realpathSync(dir)) {
59
+ throw new Error(
60
+ `${dir} isn't the root of its git repo, so its origin remote may be another repo's. Pass --repo <owner/name>, or set repo in factory.config.ts.`,
61
+ );
62
+ }
63
+ return githubRepo(dir);
64
+ };
65
+
66
+ /** The outcome of the repo's last deploy, which the hub writes to the repo's `FACTORY_STATUS` variable. */
67
+ type FactoryStatus = {
68
+ state: "deployed" | "failed";
69
+ ref?: string;
70
+ error?: string;
71
+ at: string;
72
+ };
73
+
74
+ /** The repo's `FACTORY_STATUS`, if the hub has written it. */
75
+ const readStatus = async (repo: string): Promise<FactoryStatus | undefined> => {
76
+ try {
77
+ return JSON.parse(await output("gh", ["variable", "get", "FACTORY_STATUS", "--repo", repo]));
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ };
82
+
83
+ /** Prints the status, and sets a failed exit code if the deploy failed. */
84
+ const report = (repo: string, status: FactoryStatus) => {
85
+ const from = status.ref ? ` from ${status.ref.slice(0, 7)}` : "";
86
+ if (status.state === "deployed") {
87
+ console.log(`${repo}'s outpost is deployed${from}.`);
88
+ return;
89
+ }
90
+ console.log(`${repo}'s outpost failed to deploy${from}:\n${status.error ?? "no reason given"}`);
91
+ process.exitCode = 1;
92
+ };
93
+
94
+ const POLL_MS = 3000;
95
+ const WAIT_MS = 120_000;
96
+
97
+ /** Waits for a status written after `since`. */
98
+ const waitForStatus = async (repo: string, since: Date) => {
99
+ const deadline = Date.now() + WAIT_MS;
100
+ while (Date.now() < deadline) {
101
+ const status = await readStatus(repo);
102
+ if (status && new Date(status.at) > since) return status;
103
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
104
+ }
105
+ return undefined;
106
+ };
107
+
108
+ /** Prints the outpost's `FACTORY_STATUS`. */
109
+ export const repoStatus = async ({ repo: given }: { repo?: string }) => {
110
+ const repo = await outpostRepo(await outpostDir(), given);
111
+ const status = await readStatus(repo);
112
+ if (!status) {
113
+ console.log(`The hub hasn't deployed ${repo}. Run \`factory repo install\` in it.`);
114
+ return;
115
+ }
116
+ report(repo, status);
117
+ };
118
+
119
+ /**
120
+ * Installs the outpost's repo on the hub:
121
+ * 1. Opens GitHub's page to install each connection's App on the repo.
122
+ * 2. Waits for the hub to deploy the repo's outpost, which GitHub's install
123
+ * event starts, and prints the outcome.
124
+ */
125
+ export const repoInstall = async ({ repo: given }: { repo?: string }) => {
126
+ const dir = await outpostDir();
127
+ const config = join(dir, ".factory", "config.ts");
128
+ const repo = await outpostRepo(dir, given);
129
+ const since = new Date();
130
+ const names = await githubConnections(config);
131
+ if (names.length === 0) {
132
+ console.log(".factory/config.ts uses no GitHub connection, so there's nothing to install.");
133
+ return;
134
+ }
135
+ const { hub } = await loadConfig(dir);
136
+ if (!hub) {
137
+ throw new Error(
138
+ `Set hub in factory.config.ts to the hub's Notation app and stage, such as hub: { app: "factory", stage: "prod" }, which name its GitHub Apps.`,
139
+ );
140
+ }
141
+ const { id: repoId, owner } = await gh<{ id: number; owner: { id: number } }>(`repos/${repo}`);
142
+
143
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
144
+ try {
145
+ for (const name of names) {
146
+ const slug = appSlug(appName(hub, name));
147
+ await gh(`apps/${slug}`).catch(() => {
148
+ throw new Error(
149
+ `There's no GitHub App ${slug} for the connection ${name} of the hub ${hub.app}/${hub.stage}. Run \`factory infra up\` in the hub's repo first.`,
150
+ );
151
+ });
152
+ const url = `https://github.com/apps/${slug}/installations/new/permissions?suggested_target_id=${owner.id}&repository_ids[]=${repoId}`;
153
+ console.log(`Install the GitHub App ${slug} on ${repo}:\n ${url}`);
154
+ openBrowser(url);
155
+ await prompt.question("Press Enter when it's installed. ");
156
+ }
157
+ } finally {
158
+ prompt.close();
159
+ }
160
+ console.log(`\nWaiting for the hub to deploy ${repo}…`);
161
+ const status = await waitForStatus(repo, since);
162
+ if (status) return report(repo, status);
163
+ console.log(
164
+ `The hub hasn't deployed ${repo} yet. GitHub only tells the hub about a new install. If the App was already installed on ${repo}, push to .factory/ on the default branch to deploy it, then run \`factory repo status\`.`,
165
+ );
166
+ };
@@ -0,0 +1,52 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ /** Runs `command` in a shell, with the terminal's input and output. */
7
+ export const shell = (command: string, cwd = process.cwd()) =>
8
+ new Promise<void>((resolve, reject) => {
9
+ const child = spawn(command, { cwd, shell: true, stdio: "inherit" });
10
+ child.on("error", reject);
11
+ child.on("exit", (code) =>
12
+ code === 0
13
+ ? resolve()
14
+ : reject(new Error(`${command} exited with ${code}`)),
15
+ );
16
+ });
17
+
18
+ /** Runs a program and returns its output. */
19
+ export const output = (file: string, args: string[], cwd = process.cwd()) =>
20
+ new Promise<string>((resolve, reject) =>
21
+ execFile(file, args, { cwd }, (error, stdout, stderr) =>
22
+ error
23
+ ? reject(new Error(`${file} ${args.join(" ")}: ${stderr.trim() || error.message}`))
24
+ : resolve(stdout.trim()),
25
+ ),
26
+ );
27
+
28
+ export const openBrowser = (url: string) => {
29
+ const cmd =
30
+ process.platform === "darwin"
31
+ ? "open"
32
+ : process.platform === "win32"
33
+ ? "explorer"
34
+ : "xdg-open";
35
+ execFile(cmd, [url], () => {});
36
+ };
37
+
38
+ export type FactoryConfig = {
39
+ /** A command prefix that sets credentials in the environment, such as `op run --env-file .env --`. */
40
+ loadEnv?: string;
41
+ /** An outpost's repo, as `owner/name`, when its git remote doesn't name it. */
42
+ repo?: string;
43
+ /** The hub an outpost subscribes to: its Notation app and stage, which name the hub's GitHub Apps. */
44
+ hub?: { app: string; stage: string };
45
+ };
46
+
47
+ /** Reads `factory.config.ts` in `dir`, if there is one. */
48
+ export const loadConfig = async (dir: string): Promise<FactoryConfig> => {
49
+ const file = join(dir, "factory.config.ts");
50
+ if (!existsSync(file)) return {};
51
+ return ((await import(pathToFileURL(file).href)).default ?? {}) as FactoryConfig;
52
+ };
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@notation/factory-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "author": "Daniel Grant",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/notationlabs/factory.git",
9
+ "directory": "packages/cli"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "factory": "./bin/factory.ts"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "commands"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "dependencies": {
23
+ "@notation/resource": "0.28.0",
24
+ "@notation/factory-github": "0.1.1"
25
+ }
6
26
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.