@rathnasgala/cli 0.0.5 → 0.0.8

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": "@rathnasgala/cli",
3
- "version": "0.0.5",
3
+ "version": "0.0.8",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "src"
@@ -14,7 +14,9 @@
14
14
  },
15
15
  "scripts": {
16
16
  "test": "node --test",
17
- "lint": "node scripts/lint.js"
17
+ "lint": "node scripts/lint.js",
18
+ "preversion": "npm test && npm run lint",
19
+ "push": "node scripts/push.js"
18
20
  },
19
21
  "engines": {
20
22
  "node": ">=18"
@@ -24,7 +26,7 @@
24
26
  "url": "git+https://github.com/rathnasgala/cli.git"
25
27
  },
26
28
  "dependencies": {
27
- "@rathnasgala/content-validation": "0.0.1",
29
+ "@rathnasgala/content-validation": "0.0.2",
28
30
  "libsodium-wrappers": "0.8.4",
29
31
  "tar": "7.5.22",
30
32
  "yaml": "2.9.0"
@@ -25,6 +25,7 @@ async function json(response, operation) {
25
25
 
26
26
  export async function provisionGithubPages({
27
27
  owner, repository, accessToken, commitSha, fetchImpl = fetch,
28
+ customDomain = null,
28
29
  sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
29
30
  pollIntervalMs = 5_000, maxPolls = 120
30
31
  }) {
@@ -32,6 +33,10 @@ export async function provisionGithubPages({
32
33
  const normalizedRepository = required(repository, 'repository', SEGMENT);
33
34
  const token = required(accessToken, 'accessToken');
34
35
  const sha = required(commitSha, 'commitSha', SHA);
36
+ if (customDomain != null && (typeof customDomain !== 'string'
37
+ || !/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(customDomain))) {
38
+ throw new TypeError('customDomain is invalid');
39
+ }
35
40
  if (!Number.isSafeInteger(pollIntervalMs) || pollIntervalMs < 0) {
36
41
  throw new TypeError('pollIntervalMs must be a non-negative safe integer');
37
42
  }
@@ -69,6 +74,15 @@ export async function provisionGithubPages({
69
74
  if (configuration.source?.branch !== 'gh-pages' || configuration.source?.path !== '/') {
70
75
  throw new Error('Existing GitHub Pages configuration does not use gh-pages at /');
71
76
  }
77
+ if ((configuration.cname ?? null) !== customDomain) {
78
+ const updated = await fetchImpl(`${repositoryUrl}/pages`, {
79
+ method: 'PUT', headers: requestHeaders,
80
+ body: JSON.stringify({ cname: customDomain, source: { branch: 'gh-pages', path: '/' } })
81
+ });
82
+ if (updated.status !== 204) {
83
+ throw new Error(`GitHub Pages custom-domain update failed with HTTP ${updated.status}`);
84
+ }
85
+ }
72
86
  return Object.freeze({ created: false, url: configuration.html_url, runUrl: run.html_url });
73
87
  }
74
88
  if (current.status !== 404) {
@@ -79,5 +93,14 @@ export async function provisionGithubPages({
79
93
  body: JSON.stringify({ source: { branch: 'gh-pages', path: '/' } })
80
94
  });
81
95
  const configuration = await json(created, 'Pages activation');
96
+ if (customDomain != null) {
97
+ const updated = await fetchImpl(`${repositoryUrl}/pages`, {
98
+ method: 'PUT', headers: requestHeaders,
99
+ body: JSON.stringify({ cname: customDomain, source: { branch: 'gh-pages', path: '/' } })
100
+ });
101
+ if (updated.status !== 204) {
102
+ throw new Error(`GitHub Pages custom-domain update failed with HTTP ${updated.status}`);
103
+ }
104
+ }
82
105
  return Object.freeze({ created: true, url: configuration.html_url, runUrl: run.html_url });
83
106
  }
package/src/index.js CHANGED
@@ -75,11 +75,15 @@ if (command === 'auth') {
75
75
  return index === -1 ? undefined : args[index + 1];
76
76
  };
77
77
  const installationId = Number(valueFor('--installation-id'));
78
+ const topology = valueFor('--topology') ?? 'provider-default';
78
79
  const result = await scaffoldSite({
79
80
  owner: valueFor('--owner'),
80
81
  repository: valueFor('--repository'),
81
82
  target: valueFor('--target'),
82
83
  githubInstallationId: installationId,
84
+ topology,
85
+ canonicalBaseUrl: valueFor('--canonical-base-url'),
86
+ actionRef: valueFor('--action-ref'),
83
87
  siteOptions: parseScaffoldOptions(args),
84
88
  buildMode: valueFor('--mode') ?? 'build-and-deploy',
85
89
  emptyExistingRepository: args.includes('--empty-existing-repository'),
@@ -21,14 +21,34 @@ function segment(value, field) {
21
21
  return value;
22
22
  }
23
23
 
24
- function providerDefaultBase(owner, repository) {
25
- const rootRepository = repository.toLowerCase() === `${owner}.github.io`.toLowerCase();
26
- return `https://${owner.toLowerCase()}.github.io${rootRepository ? '/' : `/${repository}/`}`;
24
+ function providerDefaultBase(owner) {
25
+ return `https://${owner.toLowerCase()}.github.io`;
26
+ }
27
+
28
+ function registrationLocation(owner, topology, canonicalBaseUrl) {
29
+ if (topology === 'provider-default') {
30
+ if (canonicalBaseUrl != null) {
31
+ throw new TypeError('--canonical-base-url is valid only with --topology custom-domain');
32
+ }
33
+ return { topology: 'PROVIDER_DEFAULT', canonicalBaseUrl: providerDefaultBase(owner) };
34
+ }
35
+ if (topology !== 'custom-domain') {
36
+ throw new TypeError('topology must be provider-default or custom-domain');
37
+ }
38
+ if (typeof canonicalBaseUrl !== 'string') {
39
+ throw new TypeError('--canonical-base-url is required with --topology custom-domain');
40
+ }
41
+ const canonical = new URL(canonicalBaseUrl);
42
+ if (canonical.protocol !== 'https:' || canonical.username || canonical.password
43
+ || canonical.port || canonical.search || canonical.hash || canonical.pathname !== '/') {
44
+ throw new TypeError('canonicalBaseUrl must be a credential-free HTTPS origin');
45
+ }
46
+ return { topology: 'CUSTOM_DOMAIN', canonicalBaseUrl: canonical.origin };
27
47
  }
28
48
 
29
49
  export async function scaffoldSite({
30
50
  owner, repository, target, githubInstallationId, siteOptions, emptyExistingRepository = false,
31
- resumeExistingCheckout = false,
51
+ resumeExistingCheckout = false, topology = 'provider-default', canonicalBaseUrl, actionRef,
32
52
  buildMode = 'build-and-deploy', templateOwner = 'rathnasgala',
33
53
  templateRepository = 'site-template',
34
54
  readGithub = readGithubCredential, readGala = readGalaCredential,
@@ -42,6 +62,7 @@ export async function scaffoldSite({
42
62
  }) {
43
63
  const repositoryOwner = segment(owner, 'owner');
44
64
  const repositoryName = segment(repository, 'repository');
65
+ const location = registrationLocation(repositoryOwner, topology, canonicalBaseUrl);
45
66
  if (!Number.isSafeInteger(githubInstallationId) || githubInstallationId <= 0) {
46
67
  throw new TypeError('githubInstallationId must be a positive integer');
47
68
  }
@@ -77,20 +98,21 @@ export async function scaffoldSite({
77
98
  if (emptyExistingRepository) await setOrigin({ root, owner: repositoryOwner, repository: repositoryName });
78
99
  }
79
100
  const configured = await configure(root, siteOptions ?? {});
80
- const canonicalBaseUrl = providerDefaultBase(repositoryOwner, repositoryName);
81
101
  const idempotencyKey = `scaffold-${createHash('sha256').update(`${repositoryOwner.toLowerCase()}/${repositoryName.toLowerCase()}`).digest('hex')}`;
82
102
  const registration = await register({
83
103
  apiBaseUrl: gala.apiBaseUrl, galaAccessToken: gala.accessToken, idempotencyKey,
84
104
  githubInstallationId, repositoryOwner, repositoryName,
85
- topology: 'PROVIDER_DEFAULT', canonicalBaseUrl
105
+ topology: location.topology, canonicalBaseUrl: location.canonicalBaseUrl
86
106
  });
87
107
  await finalize(root, {
88
108
  siteId: registration.siteId,
89
109
  canonicalBaseUrl: registration.canonicalBaseUrl,
90
- topology: 'provider-default'
110
+ pathPrefix: registration.pathPrefix,
111
+ topology
91
112
  });
92
113
  await writeWorkflow({
93
- root, siteId: registration.siteId, timezone: configured.site.timezone, buildMode
114
+ root, siteId: registration.siteId, timezone: configured.site.timezone, buildMode,
115
+ ...(actionRef == null ? {} : { actionRef })
94
116
  });
95
117
  await installSecret({
96
118
  owner: repositoryOwner, repository: repositoryName, accessToken: github.accessToken,
@@ -102,7 +124,8 @@ export async function scaffoldSite({
102
124
  });
103
125
  const commitSha = await commit(root);
104
126
  const pages = buildMode === 'build-and-deploy' ? await provisionPages({
105
- owner: repositoryOwner, repository: repositoryName, accessToken: github.accessToken, commitSha
127
+ owner: repositoryOwner, repository: repositoryName, accessToken: github.accessToken, commitSha,
128
+ customDomain: location.topology === 'CUSTOM_DOMAIN' ? new URL(location.canonicalBaseUrl).hostname : null
106
129
  }) : null;
107
130
  return Object.freeze({
108
131
  root, fullName: generated.fullName, siteId: registration.siteId, commitSha, pages
@@ -2,12 +2,22 @@ import { lstat, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { parse, stringify } from 'yaml';
4
4
 
5
- export async function writeRegisteredSiteConfiguration(root, { siteId, canonicalBaseUrl, topology }) {
5
+ export async function writeRegisteredSiteConfiguration(root, {
6
+ siteId, canonicalBaseUrl, pathPrefix, topology
7
+ }) {
6
8
  if (!/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/.test(siteId)) throw new TypeError('siteId is invalid');
7
- if (topology !== 'provider-default') throw new TypeError('Only provider-default topology is implemented');
9
+ if (!['provider-default', 'custom-domain'].includes(topology)) {
10
+ throw new TypeError('topology is invalid');
11
+ }
8
12
  const canonical = new URL(canonicalBaseUrl);
9
- if (canonical.protocol !== 'https:' || canonical.username || canonical.password || canonical.search || canonical.hash) {
10
- throw new TypeError('canonicalBaseUrl must be credential-free HTTPS');
13
+ if (canonical.protocol !== 'https:' || canonical.username || canonical.password || canonical.search
14
+ || canonical.hash || canonical.pathname !== '/') {
15
+ throw new TypeError('canonicalBaseUrl must be a credential-free HTTPS origin; put the URL path in pathPrefix');
16
+ }
17
+ const normalizedPrefix = pathPrefix === '' ? '/' : pathPrefix;
18
+ if (typeof normalizedPrefix !== 'string'
19
+ || !/^\/(?:[^/?#]+(?:\/[^/?#]+)*)?$/.test(normalizedPrefix)) {
20
+ throw new TypeError('pathPrefix must be a normalized URL path');
11
21
  }
12
22
  const target = path.resolve(root, 'site.config.yml');
13
23
  const metadata = await lstat(target);
@@ -19,8 +29,8 @@ export async function writeRegisteredSiteConfiguration(root, { siteId, canonical
19
29
  config.site.id = siteId;
20
30
  config.hosting.provider = 'github-pages';
21
31
  config.hosting.topology = topology;
22
- config.hosting.canonicalBaseUrl = canonical.href.replace(/\/$/, '');
23
- config.hosting.pathPrefix = canonical.pathname === '/' ? '/' : canonical.pathname.replace(/\/$/, '');
32
+ config.hosting.canonicalBaseUrl = canonical.origin;
33
+ config.hosting.pathPrefix = normalizedPrefix;
24
34
  const temporary = `${target}.gala-register-${process.pid}`;
25
35
  const backup = `${target}.gala-backup-${process.pid}`;
26
36
  try {
@@ -72,9 +72,13 @@ export async function registerSite({
72
72
  }
73
73
  const canonical = new URL(payload.canonicalBaseUrl);
74
74
  if (canonical.protocol !== 'https:' || canonical.username || canonical.password
75
- || canonical.search || canonical.hash) {
75
+ || canonical.search || canonical.hash || canonical.pathname !== '/') {
76
76
  throw new TypeError('Gala site registration returned an invalid canonicalBaseUrl');
77
77
  }
78
+ if (typeof payload.pathPrefix !== 'string'
79
+ || !/^\/(?:[^/?#]+(?:\/[^/?#]+)*)?$/.test(payload.pathPrefix)) {
80
+ throw new TypeError('Gala site registration returned an invalid pathPrefix');
81
+ }
78
82
  const location = response.headers?.get?.('location');
79
83
  if (location !== `/v1/sites/${payload.siteId}`) {
80
84
  throw new TypeError('Gala site registration returned an invalid Location header');
@@ -82,6 +86,7 @@ export async function registerSite({
82
86
  return Object.freeze({
83
87
  siteId: payload.siteId,
84
88
  siteSecret: payload.siteSecret,
85
- canonicalBaseUrl: canonical.href
89
+ canonicalBaseUrl: canonical.origin,
90
+ pathPrefix: payload.pathPrefix === '' ? '/' : payload.pathPrefix
86
91
  });
87
92
  }
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
 
5
- const ACTION_REF = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/.github\/workflows\/[A-Za-z0-9_.-]+\.ya?ml@v[1-9][0-9]*$/;
5
+ const ACTION_REF = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/.github\/workflows\/[A-Za-z0-9_.-]+\.ya?ml@v(?:[1-9][0-9]*|[0-9]+\.[0-9]+\.[0-9]+)$/;
6
6
  const BRANCH = /^(?![./])(?!.*\.\.)(?!.*[~^:?*\[\\])[A-Za-z0-9._/-]+(?<![/.])$/;
7
7
 
8
8
  export function deriveNightlySchedule(siteId) {
@@ -28,7 +28,9 @@ export async function writePublishWorkflow({
28
28
  buildMode = 'build-and-deploy'
29
29
  }) {
30
30
  validateTimezone(timezone);
31
- if (!ACTION_REF.test(actionRef)) throw new TypeError('actionRef must pin a reusable workflow to a major version');
31
+ if (!ACTION_REF.test(actionRef)) {
32
+ throw new TypeError('actionRef must pin a reusable workflow to a major or immutable semver tag');
33
+ }
32
34
  if (!BRANCH.test(defaultBranch)) throw new TypeError('Invalid default branch');
33
35
  if (!['build-only', 'build-and-deploy'].includes(buildMode)) throw new TypeError('Invalid build mode');
34
36