@sixb/cli 0.2.6 → 0.2.7

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.
@@ -1,49 +0,0 @@
1
- /** The GitHub environment that holds the deploy secrets and gates the deploy job. */
2
- export declare const CI_ENVIRONMENT = "production";
3
- /** The secret a private submodule's checkout reads. */
4
- export declare const SUBMODULE_TOKEN_SECRET = "SIXB_GITHUB_TOKEN";
5
- export interface GitHubRepo {
6
- /** `owner/name`. */
7
- readonly name: string;
8
- readonly defaultBranch: string;
9
- }
10
- export interface Submodule {
11
- readonly path: string;
12
- readonly url: string;
13
- /** `owner/name` when the submodule lives on GitHub. */
14
- readonly repo: string | null;
15
- }
16
- export interface WorkflowInput {
17
- /** The deployment's name. */
18
- readonly name: string;
19
- readonly branch: string;
20
- /** The project's directory relative to the repository root, `"."` at the root. */
21
- readonly projectPath: string;
22
- /** The `package.json` that pins Bun, relative to the repository root. */
23
- readonly bunVersionFile: string | null;
24
- /** GitHub secret names, by the environment variable the install lines read. */
25
- readonly secrets: Readonly<Record<string, string>>;
26
- readonly install: readonly string[];
27
- readonly submodules: "none" | "public" | "private";
28
- }
29
- /** A GitHub Actions workflow that deploys on every push to `branch`. */
30
- export declare function renderWorkflow(input: WorkflowInput): string;
31
- /** Where the workflow for a deployment lives, relative to the repository root. */
32
- export declare function workflowPath(name: string): string;
33
- /** The GitHub secret for one of a deployment's variables; a repository may deploy several. */
34
- export declare function secretName(deployment: string, variable: string): string;
35
- /** The `package.json` that pins Bun for the project, relative to the repository root. */
36
- export declare function bunVersionFile(projectDir: string, repoRoot: string): Promise<string | null>;
37
- /** The submodules `.gitmodules` lists, with the GitHub repository behind each. */
38
- export declare function readSubmodules(repoRoot: string, repo: GitHubRepo): Promise<Submodule[]>;
39
- /** `owner/name` for a GitHub remote URL, resolving a relative one against `parent`. */
40
- export declare function githubRepoOf(url: string, parent: string): string | null;
41
- export declare function currentRepo(cwd: string): Promise<GitHubRepo>;
42
- /** Whether CI's own token cannot read `repo`. A repository this login cannot see counts. */
43
- export declare function isPrivate(repo: string): Promise<boolean>;
44
- /** Creates the environment when it is missing. An existing one keeps its protection rules. */
45
- export declare function ensureEnvironment(repo: GitHubRepo): Promise<void>;
46
- export declare function setSecret(repo: GitHubRepo, name: string, value: string): Promise<void>;
47
- /** Whether the environment or the repository has the secret. */
48
- export declare function hasSecret(repo: GitHubRepo, name: string): Promise<boolean>;
49
- //# sourceMappingURL=github-ci.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"github-ci.d.ts","sourceRoot":"","sources":["../../src/lib/github-ci.ts"],"names":[],"mappings":"AAGA,qFAAqF;AACrF,eAAO,MAAM,cAAc,eAAe,CAAA;AAE1C,uDAAuD;AACvD,eAAO,MAAM,sBAAsB,sBAAsB,CAAA;AAMzD,MAAM,WAAW,UAAU;IACzB,oBAAoB;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;CAC/B;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,uDAAuD;IACvD,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;CAC7B;AAED,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,kFAAkF;IAClF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAA;IAC5B,yEAAyE;IACzE,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;IACtC,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAClD,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM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C,CAMhF"}
@@ -1,262 +0,0 @@
1
- import { dirname, join, posix, relative } from "node:path"
2
- import { SixbCliError } from "./errors"
3
-
4
- /** The GitHub environment that holds the deploy secrets and gates the deploy job. */
5
- export const CI_ENVIRONMENT = "production"
6
-
7
- /** The secret a private submodule's checkout reads. */
8
- export const SUBMODULE_TOKEN_SECRET = "SIXB_GITHUB_TOKEN"
9
-
10
- /** Actions pinned by commit, so a moved tag cannot change what runs with the deploy key. */
11
- const CHECKOUT = "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1"
12
- const SETUP_BUN = "oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0"
13
-
14
- export interface GitHubRepo {
15
- /** `owner/name`. */
16
- readonly name: string
17
- readonly defaultBranch: string
18
- }
19
-
20
- export interface Submodule {
21
- readonly path: string
22
- readonly url: string
23
- /** `owner/name` when the submodule lives on GitHub. */
24
- readonly repo: string | null
25
- }
26
-
27
- export interface WorkflowInput {
28
- /** The deployment's name. */
29
- readonly name: string
30
- readonly branch: string
31
- /** The project's directory relative to the repository root, `"."` at the root. */
32
- readonly projectPath: string
33
- /** The `package.json` that pins Bun, relative to the repository root. */
34
- readonly bunVersionFile: string | null
35
- /** GitHub secret names, by the environment variable the install lines read. */
36
- readonly secrets: Readonly<Record<string, string>>
37
- readonly install: readonly string[]
38
- readonly submodules: "none" | "public" | "private"
39
- }
40
-
41
- /** A GitHub Actions workflow that deploys on every push to `branch`. */
42
- export function renderWorkflow(input: WorkflowInput): string {
43
- const workingDirectory =
44
- input.projectPath === "." ? [] : [` working-directory: ${input.projectPath}`]
45
- const checkoutWith = [
46
- " persist-credentials: false",
47
- ...(input.submodules === "none" ? [] : [" submodules: recursive"]),
48
- ...(input.submodules === "private"
49
- ? [` token: \${{ secrets.${SUBMODULE_TOKEN_SECRET} }}`]
50
- : []),
51
- ]
52
- const tokenCheck =
53
- input.submodules === "private"
54
- ? [
55
- " - name: Check the token for private submodules",
56
- " env:",
57
- ` HAS_TOKEN: \${{ secrets.${SUBMODULE_TOKEN_SECRET} != '' }}`,
58
- " run: |",
59
- ' if [ "$HAS_TOKEN" != true ]; then',
60
- ` echo "::error::Set the ${SUBMODULE_TOKEN_SECRET} secret in the ${CI_ENVIRONMENT} environment to a token that can read this repository's private submodules."`,
61
- " exit 1",
62
- " fi",
63
- ]
64
- : []
65
-
66
- return [
67
- `# Written by \`sixb deploy ci\`. Run it again to rotate the deploy key.`,
68
- `name: Deploy ${input.name}`,
69
- "",
70
- "on:",
71
- " push:",
72
- ` branches: [${JSON.stringify(input.branch)}]`,
73
- " workflow_dispatch:",
74
- "",
75
- "permissions:",
76
- " contents: read",
77
- "",
78
- "# One deploy at a time; a push during a deploy waits for it instead of cancelling it.",
79
- "concurrency:",
80
- ` group: sixb-deploy-${input.name}`,
81
- " cancel-in-progress: false",
82
- "",
83
- "jobs:",
84
- " deploy:",
85
- " runs-on: ubuntu-latest",
86
- ` environment: ${CI_ENVIRONMENT}`,
87
- " timeout-minutes: 30",
88
- " steps:",
89
- ...tokenCheck,
90
- ` - uses: ${CHECKOUT}`,
91
- " with:",
92
- ...checkoutWith,
93
- ` - uses: ${SETUP_BUN}`,
94
- ...(input.bunVersionFile
95
- ? [" with:", ` bun-version-file: ${input.bunVersionFile}`]
96
- : []),
97
- " - name: Install dependencies",
98
- // `sixb deploy` only loads `sixb.deploy.ts` and uploads the source; the server installs again
99
- // with lifecycle scripts. Skipping them here skips downloads such as a Playwright browser.
100
- " run: bun install --frozen-lockfile --ignore-scripts",
101
- ...workingDirectory,
102
- " - name: Install the deploy key",
103
- " env:",
104
- ...Object.entries(input.secrets).map(
105
- ([variable, secret]) => ` ${variable}: \${{ secrets.${secret} }}`
106
- ),
107
- " run: |",
108
- ...input.install.map((line) => ` ${line}`),
109
- " - name: Deploy",
110
- " run: bunx sixb deploy",
111
- ...workingDirectory,
112
- "",
113
- ].join("\n")
114
- }
115
-
116
- /** Where the workflow for a deployment lives, relative to the repository root. */
117
- export function workflowPath(name: string): string {
118
- return `.github/workflows/deploy-${name}.yml`
119
- }
120
-
121
- /** The GitHub secret for one of a deployment's variables; a repository may deploy several. */
122
- export function secretName(deployment: string, variable: string): string {
123
- return `${variable}_${deployment.toUpperCase().replaceAll("-", "_")}`
124
- }
125
-
126
- /** The `package.json` that pins Bun for the project, relative to the repository root. */
127
- export async function bunVersionFile(projectDir: string, repoRoot: string): Promise<string | null> {
128
- for (let dir = projectDir; ; dir = dirname(dir)) {
129
- const manifest = await Bun.file(join(dir, "package.json"))
130
- .json()
131
- .catch(() => null)
132
- if (
133
- typeof manifest?.packageManager === "string" &&
134
- manifest.packageManager.startsWith("bun@")
135
- ) {
136
- return relative(repoRoot, join(dir, "package.json")).split("\\").join("/")
137
- }
138
- if (dir === repoRoot || dirname(dir) === dir) return null
139
- }
140
- }
141
-
142
- /** The submodules `.gitmodules` lists, with the GitHub repository behind each. */
143
- export async function readSubmodules(repoRoot: string, repo: GitHubRepo): Promise<Submodule[]> {
144
- const output = await run(
145
- ["git", "config", "--file", ".gitmodules", "--get-regexp", "^submodule\\..*\\.(path|url)$"],
146
- { cwd: repoRoot }
147
- ).catch(() => "")
148
- const byName = new Map<string, { path?: string; url?: string }>()
149
- for (const line of output.split("\n")) {
150
- const match = line.match(/^submodule\.(.+)\.(path|url) (.+)$/)
151
- if (!match?.[1] || !match[2] || !match[3]) continue
152
- const entry = byName.get(match[1]) ?? {}
153
- entry[match[2] as "path" | "url"] = match[3]
154
- byName.set(match[1], entry)
155
- }
156
- return [...byName.values()].flatMap(({ path, url }) =>
157
- path && url ? [{ path, url, repo: githubRepoOf(url, repo.name) }] : []
158
- )
159
- }
160
-
161
- /** `owner/name` for a GitHub remote URL, resolving a relative one against `parent`. */
162
- export function githubRepoOf(url: string, parent: string): string | null {
163
- if (url.startsWith("./") || url.startsWith("../")) {
164
- const resolved = posix.normalize(posix.join(parent, url))
165
- return resolved.replace(/\.git$/, "").split("/").length === 2
166
- ? resolved.replace(/\.git$/, "")
167
- : null
168
- }
169
- const match = url.match(
170
- /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?\/?$/
171
- )
172
- return match?.[1] ?? null
173
- }
174
-
175
- export async function currentRepo(cwd: string): Promise<GitHubRepo> {
176
- const output = await gh(["repo", "view", "--json", "nameWithOwner,defaultBranchRef"], { cwd })
177
- const parsed = JSON.parse(output) as {
178
- nameWithOwner: string
179
- defaultBranchRef: { name: string } | null
180
- }
181
- return { name: parsed.nameWithOwner, defaultBranch: parsed.defaultBranchRef?.name ?? "main" }
182
- }
183
-
184
- /** Whether CI's own token cannot read `repo`. A repository this login cannot see counts. */
185
- export async function isPrivate(repo: string): Promise<boolean> {
186
- const output = await gh(["api", `repos/${repo}`, "--jq", ".private"]).catch(() => "true")
187
- return output.trim() !== "false"
188
- }
189
-
190
- /** Creates the environment when it is missing. An existing one keeps its protection rules. */
191
- export async function ensureEnvironment(repo: GitHubRepo): Promise<void> {
192
- const path = `repos/${repo.name}/environments/${CI_ENVIRONMENT}`
193
- const exists = await gh(["api", path, "--silent"]).then(
194
- () => true,
195
- () => false
196
- )
197
- if (!exists) await gh(["api", "--method", "PUT", path, "--silent"])
198
- }
199
-
200
- export async function setSecret(repo: GitHubRepo, name: string, value: string): Promise<void> {
201
- await gh(["secret", "set", name, "--env", CI_ENVIRONMENT, "--repo", repo.name], {
202
- input: value,
203
- })
204
- }
205
-
206
- /** Whether the environment or the repository has the secret. */
207
- export async function hasSecret(repo: GitHubRepo, name: string): Promise<boolean> {
208
- for (const scope of [["--env", CI_ENVIRONMENT], []]) {
209
- const list = await gh(["secret", "list", ...scope, "--repo", repo.name, "--json", "name"])
210
- if ((JSON.parse(list) as { name: string }[]).some((secret) => secret.name === name)) return true
211
- }
212
- return false
213
- }
214
-
215
- async function gh(
216
- args: readonly string[],
217
- options: { readonly cwd?: string; readonly input?: string } = {}
218
- ): Promise<string> {
219
- try {
220
- return await run(["gh", ...args], { ...options, env: ghEnvironment() })
221
- } catch (error) {
222
- const reason = error instanceof Error ? error.message : String(error)
223
- throw new SixbCliError(`[SixbDeploy] gh ${args.slice(0, 2).join(" ")} failed: ${reason}`, {
224
- remediation:
225
- "`sixb deploy ci` uses the GitHub CLI. Install it, run `gh auth login`, and make sure " +
226
- "you can change this repository's settings.",
227
- })
228
- }
229
- }
230
-
231
- /**
232
- * Bun loads the project's `.env` into this process, and a connector's `GITHUB_TOKEN` there would
233
- * take precedence over the user's `gh auth login`. `GH_TOKEN` stays: it is gh's explicit override.
234
- */
235
- function ghEnvironment(): Record<string, string | undefined> {
236
- const { GITHUB_TOKEN: _projectToken, ...env } = process.env
237
- return env
238
- }
239
-
240
- async function run(
241
- command: readonly string[],
242
- options: {
243
- readonly cwd?: string
244
- readonly input?: string
245
- readonly env?: Record<string, string | undefined>
246
- }
247
- ): Promise<string> {
248
- const child = Bun.spawn([...command], {
249
- cwd: options.cwd,
250
- ...(options.env === undefined ? {} : { env: options.env }),
251
- stdin: options.input === undefined ? "ignore" : new Blob([options.input]),
252
- stdout: "pipe",
253
- stderr: "pipe",
254
- })
255
- const [exitCode, stdout, stderr] = await Promise.all([
256
- child.exited,
257
- new Response(child.stdout).text(),
258
- new Response(child.stderr).text(),
259
- ])
260
- if (exitCode !== 0) throw new Error(stderr.trim() || `exited with code ${exitCode}`)
261
- return stdout.trim()
262
- }