@rathnasgala/cli 0.0.21 → 1.0.0

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.
Files changed (64) hide show
  1. package/README.md +66 -212
  2. package/package.json +3 -3
  3. package/src/api/gala.js +126 -0
  4. package/src/api/github.js +63 -0
  5. package/src/api/http.js +72 -0
  6. package/src/auth/gala.js +52 -0
  7. package/src/auth/github.js +78 -0
  8. package/src/auth/store.js +88 -0
  9. package/src/cli/args.js +56 -0
  10. package/src/cli/terminal.js +104 -0
  11. package/src/commands/auth.js +20 -0
  12. package/src/commands/doctor.js +98 -0
  13. package/src/commands/init.js +197 -0
  14. package/src/commands/new.js +76 -0
  15. package/src/commands/preview.js +92 -0
  16. package/src/commands/publish.js +57 -0
  17. package/src/commands-manifest.js +58 -0
  18. package/src/content.js +31 -0
  19. package/src/git.js +143 -0
  20. package/src/index.js +44 -297
  21. package/src/publication.js +37 -0
  22. package/src/assign-content-ids.js +0 -1
  23. package/src/auth-command.js +0 -36
  24. package/src/configure-site.js +0 -102
  25. package/src/content-files.js +0 -1
  26. package/src/doctor-command.js +0 -214
  27. package/src/entitlement-client.js +0 -26
  28. package/src/entitlement-command.js +0 -74
  29. package/src/evaluation-date.js +0 -1
  30. package/src/gala-credential-health.js +0 -34
  31. package/src/gala-credential-store.js +0 -115
  32. package/src/gala-device-flow.js +0 -121
  33. package/src/github-auth-command.js +0 -29
  34. package/src/github-credential-store.js +0 -65
  35. package/src/github-device-flow.js +0 -130
  36. package/src/github-empty-repository.js +0 -76
  37. package/src/github-identity.js +0 -32
  38. package/src/github-pages-provisioning.js +0 -107
  39. package/src/github-repository-secret.js +0 -82
  40. package/src/github-repository-variable.js +0 -56
  41. package/src/github-template-repository.js +0 -165
  42. package/src/hook-command.js +0 -64
  43. package/src/http-failure.js +0 -55
  44. package/src/new-command.js +0 -54
  45. package/src/open-browser.js +0 -40
  46. package/src/preview-command.js +0 -60
  47. package/src/publication-creation-client.js +0 -144
  48. package/src/publication-state.js +0 -7
  49. package/src/publish-command.js +0 -37
  50. package/src/record-deployment-command.js +0 -147
  51. package/src/refresh-command.js +0 -104
  52. package/src/repository-limits.js +0 -94
  53. package/src/scaffold-git.js +0 -41
  54. package/src/scaffold-options.js +0 -58
  55. package/src/scaffold-preflight.js +0 -147
  56. package/src/scaffold-site.js +0 -162
  57. package/src/site-config-registration.js +0 -47
  58. package/src/site-registration-client.js +0 -138
  59. package/src/theme-package.js +0 -128
  60. package/src/topology-client.js +0 -43
  61. package/src/topology-command.js +0 -70
  62. package/src/upgrade-command.js +0 -81
  63. package/src/validate-command.js +0 -5
  64. package/src/workflow-command.js +0 -87
@@ -1,165 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import path from 'node:path';
3
- import { describeHttpFailure } from './http-failure.js';
4
-
5
- const GITHUB_API_VERSION = '2026-03-10';
6
- const REPOSITORY_IDENTITY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
7
-
8
- function requiredString(value, field) {
9
- if (typeof value !== 'string' || value.trim() === '') {
10
- throw new TypeError(`${field} is required`);
11
- }
12
- return value.trim();
13
- }
14
-
15
- function repositorySegment(value, field) {
16
- const segment = requiredString(value, field);
17
- if (!/^[A-Za-z0-9_.-]+$/.test(segment)) {
18
- throw new TypeError(`${field} contains unsupported characters`);
19
- }
20
- return segment;
21
- }
22
-
23
- export async function generateRepositoryFromTemplate({
24
- accessToken,
25
- templateOwner,
26
- templateRepository,
27
- owner,
28
- repository,
29
- description,
30
- fetchImpl = fetch,
31
- sleep,
32
- readinessAttempts,
33
- readinessIntervalMs
34
- }) {
35
- const token = requiredString(accessToken, 'accessToken');
36
- const sourceOwner = repositorySegment(templateOwner, 'templateOwner');
37
- const sourceRepository = repositorySegment(templateRepository, 'templateRepository');
38
- const targetOwner = repositorySegment(owner, 'owner');
39
- const targetRepository = repositorySegment(repository, 'repository');
40
- if (description != null && typeof description !== 'string') {
41
- throw new TypeError('description must be a string');
42
- }
43
-
44
- const response = await fetchImpl(
45
- `https://api.github.com/repos/${encodeURIComponent(sourceOwner)}/${encodeURIComponent(sourceRepository)}/generate`,
46
- {
47
- method: 'POST',
48
- headers: {
49
- accept: 'application/vnd.github+json',
50
- authorization: `Bearer ${token}`,
51
- 'content-type': 'application/json',
52
- 'x-github-api-version': GITHUB_API_VERSION
53
- },
54
- body: JSON.stringify({
55
- owner: targetOwner,
56
- name: targetRepository,
57
- description: description ?? '',
58
- include_all_branches: false,
59
- private: false
60
- })
61
- }
62
- );
63
- if (response.status !== 201) {
64
- throw new Error(await describeHttpFailure(response, 'GitHub template generation'));
65
- }
66
- const payload = await response.json();
67
- if (payload == null || Array.isArray(payload) || typeof payload !== 'object') {
68
- throw new TypeError('GitHub repository response must be a JSON object');
69
- }
70
- const fullName = requiredString(payload.full_name, 'full_name');
71
- if (!REPOSITORY_IDENTITY.test(fullName)) {
72
- throw new TypeError('GitHub repository response contains an invalid full_name');
73
- }
74
- if (fullName.toLowerCase() !== `${targetOwner}/${targetRepository}`.toLowerCase()) {
75
- throw new TypeError('GitHub generated an unexpected repository');
76
- }
77
-
78
- const cloneUrl = new URL(requiredString(payload.clone_url, 'clone_url'));
79
- if (
80
- cloneUrl.protocol !== 'https:'
81
- || cloneUrl.hostname !== 'github.com'
82
- || cloneUrl.username !== ''
83
- || cloneUrl.password !== ''
84
- || cloneUrl.search !== ''
85
- || cloneUrl.hash !== ''
86
- || cloneUrl.pathname.toLowerCase() !== `/${fullName}.git`.toLowerCase()
87
- ) {
88
- throw new TypeError('GitHub repository response contains an invalid clone_url');
89
- }
90
-
91
- // Last, so a malformed response fails immediately instead of after the readiness wait.
92
- await awaitRepositoryContent({
93
- accessToken: token, owner: targetOwner, repository: targetRepository, fetchImpl,
94
- ...(sleep == null ? {} : { sleep }),
95
- ...(readinessAttempts == null ? {} : { attempts: readinessAttempts }),
96
- ...(readinessIntervalMs == null ? {} : { intervalMs: readinessIntervalMs })
97
- });
98
-
99
- return Object.freeze({ fullName, cloneUrl: cloneUrl.href });
100
- }
101
-
102
- /**
103
- * Waits for a generated repository to actually contain the template.
104
- *
105
- * Generating from a template is asynchronous: GitHub answers 201 with the repository's full name
106
- * and clone URL, and copies the content in afterwards. Cloning on the 201 produced
107
- * "warning: You appear to have cloned an empty repository", and scaffolding then failed on a
108
- * missing site.config.yml — a confusing error about a file the template certainly contains.
109
- *
110
- * Readiness is the presence of a branch. `size` is not usable: GitHub still reported 0 for a
111
- * repository that already had `main` and commits.
112
- */
113
- export async function awaitRepositoryContent({
114
- accessToken, owner, repository, fetchImpl = fetch,
115
- sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
116
- attempts = 30, intervalMs = 1_000
117
- }) {
118
- const url = `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}/branches?per_page=1`;
119
- for (let attempt = 0; attempt < attempts; attempt += 1) {
120
- if (attempt > 0) await sleep(intervalMs);
121
- const response = await fetchImpl(url, {
122
- headers: {
123
- accept: 'application/vnd.github+json',
124
- authorization: `Bearer ${accessToken}`,
125
- 'x-github-api-version': GITHUB_API_VERSION
126
- }
127
- });
128
- if (!response.ok) throw new Error(await describeHttpFailure(response, 'GitHub branch lookup'));
129
- const branches = await response.json();
130
- if (Array.isArray(branches) && branches.length > 0) return;
131
- }
132
- throw new Error(
133
- `GitHub created ${owner}/${repository} from the template but it was still empty after `
134
- + `${Math.round((attempts * intervalMs) / 1000)}s. Re-run scaffold with --resume once it has content.`
135
- );
136
- }
137
-
138
- export function cloneRepository({ cloneUrl, target, spawnProcess = spawn }) {
139
- const source = new URL(requiredString(cloneUrl, 'cloneUrl'));
140
- if (
141
- source.protocol !== 'https:'
142
- || source.hostname !== 'github.com'
143
- || source.username !== ''
144
- || source.password !== ''
145
- || source.search !== ''
146
- || source.hash !== ''
147
- ) {
148
- throw new TypeError('cloneUrl must be an uncredentialed GitHub HTTPS URL');
149
- }
150
- const resolvedTarget = path.resolve(requiredString(target, 'target'));
151
-
152
- return new Promise((resolve, reject) => {
153
- const child = spawnProcess('git', ['clone', source.href, resolvedTarget], {
154
- cwd: path.dirname(resolvedTarget),
155
- shell: false,
156
- stdio: 'inherit'
157
- });
158
- child.once('error', reject);
159
- child.once('exit', (code, signal) => {
160
- if (signal) reject(new Error(`Git clone terminated by signal ${signal}`));
161
- else if (code !== 0) reject(new Error(`Git clone exited with code ${code}`));
162
- else resolve(resolvedTarget);
163
- });
164
- });
165
- }
@@ -1,64 +0,0 @@
1
- import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
-
4
- const MARKER = '// Managed by @rathnasgala/cli. Do not edit.\n';
5
- const HOOK = `#!/usr/bin/env node
6
- ${MARKER}const { spawnSync } = require('node:child_process');
7
- const path = require('node:path');
8
-
9
- const root = process.cwd();
10
- const executable = path.join(
11
- root,
12
- 'node_modules',
13
- '.bin',
14
- process.platform === 'win32' ? 'gala.cmd' : 'gala'
15
- );
16
- const result = spawnSync(executable, ['validate', '--root', root], {
17
- cwd: root,
18
- shell: false,
19
- stdio: 'inherit'
20
- });
21
- if (result.error) {
22
- console.error('Gala validation hook failed to start:', result.error.message);
23
- process.exit(1);
24
- }
25
- process.exit(result.status ?? 1);
26
- `;
27
-
28
- async function metadata(file, allowMissing = false) {
29
- try {
30
- return await lstat(file);
31
- } catch (error) {
32
- if (allowMissing && error.code === 'ENOENT') return null;
33
- throw error;
34
- }
35
- }
36
-
37
- export async function installPrePushHook(root) {
38
- const resolvedRoot = path.resolve(root);
39
- const gitDirectory = path.join(resolvedRoot, '.git');
40
- const gitMetadata = await metadata(gitDirectory);
41
- if (!gitMetadata.isDirectory() || gitMetadata.isSymbolicLink()) {
42
- throw new TypeError('.git must be a real directory');
43
- }
44
-
45
- const hooksDirectory = path.join(gitDirectory, 'hooks');
46
- const hooksMetadata = await metadata(hooksDirectory, true);
47
- if (hooksMetadata?.isSymbolicLink() || (hooksMetadata && !hooksMetadata.isDirectory())) {
48
- throw new TypeError('.git/hooks must be a real directory');
49
- }
50
- if (!hooksMetadata) await mkdir(hooksDirectory);
51
-
52
- const target = path.join(hooksDirectory, 'pre-push');
53
- const existing = await metadata(target, true);
54
- if (existing) {
55
- if (!existing.isFile() || existing.isSymbolicLink()) {
56
- throw new TypeError('Existing pre-push hook must be a regular file');
57
- }
58
- if (await readFile(target, 'utf8') === HOOK) return { target, installed: false };
59
- throw new Error('Refusing to overwrite an existing pre-push hook');
60
- }
61
-
62
- await writeFile(target, HOOK, { encoding: 'utf8', flag: 'wx', mode: 0o755 });
63
- return { target, installed: true };
64
- }
@@ -1,55 +0,0 @@
1
- /**
2
- * What the server actually said, instead of only what it scored.
3
- *
4
- * Every failure in this CLI reported `failed with HTTP 403` and discarded the response body. GitHub
5
- * puts the reason there and nowhere else — an organisation's OAuth App restrictions, a missing
6
- * scope, a rename, a rate limit all arrive as 403 with a sentence explaining which — so the one
7
- * fact worth having was the one being thrown away. Diagnosing anything meant guessing between
8
- * causes the server had already distinguished.
9
- *
10
- * Only the response is read. Request bodies, tokens and secrets never pass through here.
11
- */
12
- const MAX_DETAIL = 400;
13
-
14
- export async function describeHttpFailure(response, action) {
15
- const status = response?.status ?? 0;
16
- let detail = '';
17
- try {
18
- // Cloned so a caller that also reads the body still can; a response whose body is already
19
- // consumed simply yields no detail rather than a second failure on top of the first.
20
- const text = await (typeof response.clone === 'function' ? response.clone() : response).text();
21
- detail = extract(text);
22
- } catch {
23
- detail = '';
24
- }
25
- return `${action} failed with HTTP ${status}${detail === '' ? '' : `: ${detail}`}`;
26
- }
27
-
28
- function extract(text) {
29
- if (typeof text !== 'string' || text.trim() === '') return '';
30
- let payload;
31
- try {
32
- payload = JSON.parse(text);
33
- } catch {
34
- return truncate(text);
35
- }
36
- if (payload == null || typeof payload !== 'object') return truncate(text);
37
- const parts = [];
38
- if (typeof payload.message === 'string' && payload.message.trim() !== '') parts.push(payload.message.trim());
39
- // GitHub's `errors` array carries the specific field or reason behind a generic message.
40
- if (Array.isArray(payload.errors)) {
41
- for (const error of payload.errors) {
42
- const reason = typeof error === 'string' ? error : error?.message ?? error?.code;
43
- if (typeof reason === 'string' && reason.trim() !== '') parts.push(reason.trim());
44
- }
45
- }
46
- if (typeof payload.error_description === 'string') parts.push(payload.error_description.trim());
47
- if (typeof payload.code === 'string' && parts.length === 0) parts.push(payload.code);
48
- if (typeof payload.documentation_url === 'string') parts.push(`See ${payload.documentation_url}`);
49
- return truncate(parts.length === 0 ? text : parts.join(' — '));
50
- }
51
-
52
- function truncate(value) {
53
- const flattened = value.replace(/\s+/g, ' ').trim();
54
- return flattened.length > MAX_DETAIL ? `${flattened.slice(0, MAX_DETAIL)}…` : flattened;
55
- }
@@ -1,54 +0,0 @@
1
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
-
4
- import {
5
- createPostMetadata,
6
- isContentId,
7
- parseFrontmatter,
8
- slugifyTitle
9
- } from '@rathnasgala/content-validation';
10
- import { stringify } from 'yaml';
11
- import { repositoryEvaluationDate } from './evaluation-date.js';
12
-
13
- export async function createPost({ root, title, language, today, now = Date.now }) {
14
- const siteRoot = path.resolve(root);
15
- const creationTimestamp = now();
16
- const publishAfterDate = today ?? await repositoryEvaluationDate({
17
- root: siteRoot,
18
- now: () => creationTimestamp
19
- });
20
- const metadata = createPostMetadata({
21
- title,
22
- language,
23
- today: publishAfterDate,
24
- timestamp: creationTimestamp
25
- });
26
- const postDirectory = path.join(siteRoot, 'content', 'posts', slugifyTitle(title));
27
- const mediaDirectory = path.join(postDirectory, 'media');
28
- const postPath = path.join(postDirectory, `index.${metadata.language}.md`);
29
-
30
- await mkdir(postDirectory, { recursive: true });
31
- const variants = (await readdir(postDirectory, { withFileTypes: true }))
32
- .filter((entry) => entry.isFile() && /^index\.[^.]+\.md$/.test(entry.name));
33
- const existingIds = new Set();
34
- for (const variant of variants) {
35
- const variantPath = path.join(postDirectory, variant.name);
36
- const parsed = parseFrontmatter(await readFile(variantPath, 'utf8'));
37
- if (parsed.errors.length > 0) {
38
- throw new Error(`Existing variant has invalid frontmatter: ${variantPath}`);
39
- }
40
- if (!isContentId(parsed.data.id)) {
41
- throw new Error(`Existing variant is missing a valid article id: ${variantPath}`);
42
- }
43
- existingIds.add(parsed.data.id);
44
- }
45
- if (existingIds.size > 1) {
46
- throw new Error(`Existing variants have conflicting article ids: ${postDirectory}`);
47
- }
48
- if (existingIds.size === 1) metadata.id = existingIds.values().next().value;
49
-
50
- await mkdir(mediaDirectory, { recursive: true });
51
- const source = `---\n${stringify(metadata).trimEnd()}\n---\n\n# ${title}\n`;
52
- await writeFile(postPath, source, { encoding: 'utf8', flag: 'wx' });
53
- return { metadata, postPath, mediaDirectory };
54
- }
@@ -1,40 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
-
3
- /**
4
- * Opens a URL in the writer's browser, best effort.
5
- *
6
- * Printing "Open https://…" and a code asks someone to copy a URL out of a terminal by hand, three
7
- * times over in one scaffold. The URL is still always printed — this only saves the copying, and it
8
- * has to keep working when it cannot: over SSH, in a container, in CI, on a machine with no browser
9
- * at all. So nothing here is allowed to fail the command.
10
- *
11
- * Deliberately not attempted when there is no terminal. A CI job that silently spawns a browser
12
- * process is a hang waiting to happen, and there is nobody there to look at it.
13
- */
14
- export function openInBrowser(url, {
15
- platform = process.platform,
16
- environment = process.env,
17
- interactive = process.stdin.isTTY === true,
18
- spawnProcess = spawn
19
- } = {}) {
20
- if (!interactive) return false;
21
- // Respected by convention across CLI tooling, and the escape hatch for anyone who does not want
22
- // their browser taken over.
23
- if (environment.GALA_NO_BROWSER || environment.CI || environment.NO_BROWSER) return false;
24
- if (!/^https:\/\//.test(url)) return false;
25
-
26
- const [command, args] = platform === 'darwin' ? ['open', [url]]
27
- : platform === 'win32' ? ['cmd', ['/c', 'start', '', url]]
28
- : ['xdg-open', [url]];
29
-
30
- try {
31
- const child = spawnProcess(command, args, { stdio: 'ignore', detached: true, shell: false });
32
- // Without this the CLI waits for the browser to exit before it can finish.
33
- child.unref?.();
34
- // A missing opener is an ordinary outcome on a headless box, not something to report.
35
- child.on?.('error', () => {});
36
- return true;
37
- } catch {
38
- return false;
39
- }
40
- }
@@ -1,60 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import path from 'node:path';
3
-
4
- import { regenerateBuildManifest } from './validate-command.js';
5
-
6
- const BUILD_WARNING_DELAY_MS = (5 * 60 * 1000) + 1;
7
- const INITIAL_BUILD_COMPLETE = /\bWrote \d+ files?\b/;
8
-
9
- export async function previewSite({
10
- root,
11
- today,
12
- spawnProcess = spawn,
13
- schedule = setTimeout,
14
- cancel = clearTimeout,
15
- output = process.stdout,
16
- warningOutput = process.stderr
17
- }) {
18
- const siteRoot = path.resolve(root);
19
- const { results: validation } = await regenerateBuildManifest({ root: siteRoot, today });
20
- const failures = validation.filter(({ errors }) => errors.length > 0);
21
- if (failures.length > 0) {
22
- throw new Error(`Preview refused: ${failures.length} post variant(s) failed validation`);
23
- }
24
-
25
- const cli = path.join(siteRoot, 'node_modules', '@11ty', 'eleventy', 'cmd.cjs');
26
- const child = spawnProcess(process.execPath, [cli, '--serve', '--watch'], {
27
- cwd: siteRoot,
28
- env: { ...process.env, GALA_EVALUATION_DATE: today },
29
- shell: false,
30
- stdio: ['inherit', 'pipe', 'pipe']
31
- });
32
-
33
- return new Promise((resolve, reject) => {
34
- let initialOutput = '';
35
- let warningTimer = schedule(() => {
36
- warningOutput.write('warning\tbuild-duration-5m\n');
37
- warningTimer = undefined;
38
- }, BUILD_WARNING_DELAY_MS);
39
- const stopTimer = () => {
40
- if (warningTimer !== undefined) cancel(warningTimer);
41
- warningTimer = undefined;
42
- };
43
- child.stdout?.on('data', (chunk) => {
44
- output.write(chunk);
45
- initialOutput = `${initialOutput}${chunk}`.slice(-256);
46
- if (INITIAL_BUILD_COMPLETE.test(initialOutput)) stopTimer();
47
- });
48
- child.stderr?.on('data', (chunk) => warningOutput.write(chunk));
49
- child.once('error', (error) => {
50
- stopTimer();
51
- reject(error);
52
- });
53
- child.once('exit', (code, signal) => {
54
- stopTimer();
55
- if (signal) reject(new Error(`Preview terminated by signal ${signal}`));
56
- else if (code !== 0) reject(new Error(`Preview exited with code ${code}`));
57
- else resolve();
58
- });
59
- });
60
- }
@@ -1,144 +0,0 @@
1
- /**
2
- * Creates the publication repository the way the browser editor does.
3
- *
4
- * The CLI used to call `POST /repos/{template}/generate` itself. That is a second, worse
5
- * implementation of something the API already does and does properly:
6
- *
7
- * - it tries the template, then falls back to creating an empty repository and seeding it, then
8
- * reports that the writer must do it by hand — the CLI's single attempt had no rung below it;
9
- * - it waits for the Gala App installation to actually reach the new repository before calling it
10
- * ready, which is why repositories the CLI created never appeared in the web UI;
11
- * - it returns the installation id, so registration cannot disagree with creation about which
12
- * installation owns the repository.
13
- *
14
- * One implementation, exercised by both clients, is the only way the two stay in step.
15
- */
16
- import { describeHttpFailure } from './http-failure.js';
17
- import { exchangeGithubAuthorization } from './site-registration-client.js';
18
-
19
- export async function createPublication({
20
- apiBaseUrl = 'https://api.gala67.com',
21
- galaAccessToken,
22
- githubAccessToken,
23
- name,
24
- fetchImpl = fetch,
25
- authorize = exchangeGithubAuthorization,
26
- notify = () => {},
27
- ask,
28
- openUrl = () => false,
29
- shareAttempts = 3,
30
- selfLogin
31
- }) {
32
- let created = false;
33
- let shareUrl = 'https://github.com/settings/installations';
34
- let repositoryOwner = selfLogin ?? '';
35
- let repositoryName = name;
36
- for (let attempt = 0; attempt < Math.max(1, shareAttempts); attempt += 1) {
37
- const result = await requestPublication({
38
- apiBaseUrl, galaAccessToken, githubAccessToken, name, fetchImpl, authorize
39
- });
40
- if (result.ready) return result.publication;
41
-
42
- /*
43
- * The repository exists with the right content; the App installation simply cannot see it,
44
- * because it is scoped to selected repositories rather than all of them. Sharing it is a click,
45
- * and asking again then returns READY — the server short-circuits on a repository it can
46
- * already see. The browser editor recovers the same way; without this the CLI dead-ends on a
47
- * state that is one click from working.
48
- *
49
- * After the first attempt the repository exists, so a further refusal reports UNSUPPORTED
50
- * rather than NEEDS_SHARING — the same situation under a different name.
51
- */
52
- const shareable = result.status === 'NEEDS_SHARING' || created;
53
- if (result.status === 'NEEDS_SHARING') {
54
- created = true;
55
- shareUrl = installationSettingsUrl(result.installationId, result.owner, selfLogin);
56
- repositoryName = result.repository ?? repositoryName;
57
- repositoryOwner = result.owner ?? repositoryOwner;
58
- }
59
- if (!shareable || typeof ask !== 'function') throw result.failure;
60
-
61
- notify(`${repositoryOwner}/${repositoryName} was created, but the Gala GitHub App cannot reach `
62
- + 'it yet — its installation covers only selected repositories, which is the right way to '
63
- + 'have it. Add this one repository to the installation; nothing else needs granting.');
64
- notify(`${openUrl(shareUrl) ? 'Opened' : 'Open'} ${shareUrl}`);
65
- await ask('Press enter once the App can access that repository. ');
66
- }
67
- throw new Error(
68
- `The Gala GitHub App still cannot reach ${repositoryOwner}/${repositoryName}. Add that `
69
- + `repository to the installation at ${shareUrl}, then run scaffold again.`
70
- );
71
- }
72
-
73
- /**
74
- * The page that grants one repository, rather than the list of every app ever installed.
75
- *
76
- * GitHub keeps user and organisation installation settings on different paths, and only the caller
77
- * knows which this is: the created owner differing from the token's own account means the
78
- * installation lives on an organisation.
79
- */
80
- export function installationSettingsUrl(installationId, owner, selfLogin) {
81
- const generic = 'https://github.com/settings/installations';
82
- if (!Number.isSafeInteger(Number(installationId)) || Number(installationId) <= 0) return generic;
83
- const isOrganization = typeof owner === 'string' && typeof selfLogin === 'string'
84
- && owner.toLowerCase() !== selfLogin.toLowerCase();
85
- return isOrganization
86
- ? `https://github.com/organizations/${encodeURIComponent(owner)}/settings/installations/${installationId}`
87
- : `https://github.com/settings/installations/${installationId}`;
88
- }
89
-
90
- async function requestPublication({
91
- apiBaseUrl, galaAccessToken, githubAccessToken, name, fetchImpl, authorize
92
- }) {
93
- const authorization = await authorize({
94
- apiBaseUrl, galaAccessToken, githubAccessToken, fetchImpl
95
- });
96
- const response = await fetchImpl(`${String(apiBaseUrl).replace(/\/$/, '')}/v1/auth/github/publications`, {
97
- method: 'POST',
98
- headers: {
99
- accept: 'application/json',
100
- authorization: `Bearer ${galaAccessToken}`,
101
- 'content-type': 'application/json',
102
- 'GitHub-Authorization': authorization
103
- },
104
- body: JSON.stringify({ name })
105
- });
106
- if (!response.ok) throw new Error(await describeHttpFailure(response, 'Gala publication creation'));
107
-
108
- const payload = await response.json();
109
- const status = payload?.status;
110
- const owner = payload?.owner;
111
- const repository = payload?.name;
112
-
113
- if (status !== 'READY') {
114
- return {
115
- ready: false, status, owner, repository,
116
- // Carried even though the repository is not in the installation yet: it is what makes the
117
- // grant a deep link rather than a hunt.
118
- installationId: payload?.installationId,
119
- failure: new Error(
120
- `Gala could not create the publication repository (${payload?.outcome ?? status}). `
121
- + 'Give the Gala GitHub App access to it at https://github.com/settings/installations, or '
122
- + 'create it from https://github.com/rathnasgala/site-template yourself and run scaffold '
123
- + 'with --empty-existing-repository.'
124
- )
125
- };
126
- }
127
- if (typeof owner !== 'string' || typeof repository !== 'string') {
128
- throw new TypeError('Gala publication creation returned no repository identity');
129
- }
130
- const installationId = Number(payload?.installationId);
131
- if (!Number.isSafeInteger(installationId) || installationId <= 0) {
132
- throw new TypeError('Gala publication creation returned no installation');
133
- }
134
-
135
- return { ready: true, status, owner, repository, publication: Object.freeze({
136
- owner,
137
- repository,
138
- installationId,
139
- outcome: payload?.outcome ?? null,
140
- // The server names the repository it actually made, which may differ from what was asked for.
141
- fullName: `${owner}/${repository}`,
142
- cloneUrl: `https://github.com/${owner}/${repository}.git`
143
- }) };
144
- }
@@ -1,7 +0,0 @@
1
- import {
2
- PUBLICATION_STATE_PATH,
3
- readPublicationState,
4
- recordSuccessfulDeployment
5
- } from '@rathnasgala/content-validation';
6
-
7
- export { PUBLICATION_STATE_PATH, readPublicationState, recordSuccessfulDeployment };
@@ -1,37 +0,0 @@
1
- import path from 'node:path';
2
- import { spawn } from 'node:child_process';
3
- import { regenerateBuildManifest } from './validate-command.js';
4
-
5
- export async function publishSite({
6
- root,
7
- today,
8
- force = false,
9
- spawnProcess = spawn,
10
- warn = (message) => process.stderr.write(`${message}\n`)
11
- }) {
12
- const siteRoot = path.resolve(root);
13
- if (!force) {
14
- const { results } = await regenerateBuildManifest({ root: siteRoot, today });
15
- const failures = results.filter(({ errors }) => errors.length > 0);
16
- if (failures.length > 0) {
17
- throw new Error(`Publish refused: ${failures.length} post variant(s) failed validation`);
18
- }
19
- for (const result of results) {
20
- for (const warning of result.warnings) warn(`${result.file}: warning: ${warning}`);
21
- }
22
- }
23
-
24
- return new Promise((resolve, reject) => {
25
- const child = spawnProcess('git', ['-C', siteRoot, 'push'], {
26
- cwd: siteRoot,
27
- shell: false,
28
- stdio: 'inherit'
29
- });
30
- child.once('error', reject);
31
- child.once('exit', (code, signal) => {
32
- if (signal) reject(new Error(`Publish terminated by signal ${signal}`));
33
- else if (code !== 0) reject(new Error(`Git push exited with code ${code}`));
34
- else resolve();
35
- });
36
- });
37
- }