@codeqlick/cli 0.0.0-stage → 0.1.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.
- package/README.md +38 -2
- package/dist/api.js +83 -0
- package/dist/cli.js +406 -0
- package/dist/config.js +38 -0
- package/dist/pack.js +124 -0
- package/package.json +36 -4
package/README.md
CHANGED
|
@@ -1,3 +1,39 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @codeqlick/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Deploy static sites to [Codeqlick Cloud](https://cloud.codeqlick.com) from your terminal or CI.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx @codeqlick/cli login # approve it in the browser
|
|
7
|
+
npx @codeqlick/cli init # link this folder to a project (codeqlick.json)
|
|
8
|
+
npx @codeqlick/cli deploy dist --prod
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Every deployment gets its own address (`https://<project>--<id>.codeqlick.app`); `--prod` also
|
|
12
|
+
publishes it at `https://<project>.codeqlick.app` and on your domains. `codeqlick rollback` goes
|
|
13
|
+
back in a second.
|
|
14
|
+
|
|
15
|
+
| Command | What it does |
|
|
16
|
+
| ------------------------------------------- | -------------------------------------------- |
|
|
17
|
+
| `login [--token <cqk_…>]` | Sign in through the browser, or save a token |
|
|
18
|
+
| `logout` / `whoami` | Forget the token / your account and teams |
|
|
19
|
+
| `init` | Link the folder to a project |
|
|
20
|
+
| `deploy [folder] [--prod] [-m <text>]` | Upload the folder as a new deployment |
|
|
21
|
+
| `deployments` / `promote <id>` / `rollback` | List, publish an earlier one, go back |
|
|
22
|
+
| `domains [add\|check\|rm <domain>]` | The project's own domains |
|
|
23
|
+
| `open` | Open the published site |
|
|
24
|
+
|
|
25
|
+
In CI, set `CODEQLICK_TOKEN` (a token from the console) and keep `codeqlick.json` in the
|
|
26
|
+
repository, or pass `--team` and `--project` (`CODEQLICK_TEAM`, `CODEQLICK_PROJECT`).
|
|
27
|
+
|
|
28
|
+
No dependencies; Node 20 or later. Full docs: https://cloud.codeqlick.com/en/docs
|
|
29
|
+
|
|
30
|
+
## Development
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
npm ci
|
|
34
|
+
npm test # node --test on the TypeScript sources (Node 24)
|
|
35
|
+
npm run build # dist/, what is published
|
|
36
|
+
CODEQLICK_API_URL=http://localhost:4000/v1 node dist/cli.js whoami
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Publishing (`npm publish --access public`, from this folder) needs the `@codeqlick` scope on npm.
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { openAsBlob } from 'node:fs';
|
|
2
|
+
/** A failed API call: the problem details' text and status. */
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(status, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.status = status;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const USER_AGENT = 'codeqlick-cli/0.1.0';
|
|
11
|
+
/** The Cloud API (`/v1/cloud`), with the token when there is one. */
|
|
12
|
+
export class Api {
|
|
13
|
+
base;
|
|
14
|
+
token;
|
|
15
|
+
constructor(base, token) {
|
|
16
|
+
this.base = base;
|
|
17
|
+
this.token = token;
|
|
18
|
+
}
|
|
19
|
+
async request(method, path, body) {
|
|
20
|
+
const headers = {
|
|
21
|
+
Accept: 'application/json',
|
|
22
|
+
'User-Agent': USER_AGENT,
|
|
23
|
+
};
|
|
24
|
+
if (this.token)
|
|
25
|
+
headers.Authorization = `Bearer ${this.token}`;
|
|
26
|
+
let payload;
|
|
27
|
+
if (body instanceof FormData)
|
|
28
|
+
payload = body;
|
|
29
|
+
else if (body !== undefined) {
|
|
30
|
+
headers['Content-Type'] = 'application/json';
|
|
31
|
+
payload = JSON.stringify(body);
|
|
32
|
+
}
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(`${this.base}${path}`, { method, headers, body: payload });
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
throw new ApiError(0, `Can't reach ${this.base} (${error.message})`);
|
|
39
|
+
}
|
|
40
|
+
if (response.status === 204)
|
|
41
|
+
return undefined;
|
|
42
|
+
const text = await response.text();
|
|
43
|
+
let data = undefined;
|
|
44
|
+
try {
|
|
45
|
+
data = text ? JSON.parse(text) : undefined;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Not JSON.
|
|
49
|
+
}
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
const problem = (data ?? {});
|
|
52
|
+
const fields = problem.errors?.map((e) => `${e.path}: ${e.message}`).join('; ');
|
|
53
|
+
throw new ApiError(response.status, problem.detail ?? fields ?? problem.title ?? `HTTP ${response.status}`);
|
|
54
|
+
}
|
|
55
|
+
return data;
|
|
56
|
+
}
|
|
57
|
+
me = () => this.request('GET', '/cloud/me');
|
|
58
|
+
projects = (team) => this.request('GET', `/cloud/teams/${encodeURIComponent(team)}/projects`).then((r) => r.items);
|
|
59
|
+
createProject = (team, name, slug) => this.request('POST', `/cloud/teams/${encodeURIComponent(team)}/projects`, {
|
|
60
|
+
name,
|
|
61
|
+
slug,
|
|
62
|
+
});
|
|
63
|
+
deployments = (project, page = 1) => this.request('GET', `/cloud/projects/${project}/deployments?page=${page}&pageSize=50`);
|
|
64
|
+
promote = (project, deployment) => this.request('POST', `/cloud/projects/${project}/deployments/${deployment}/promote`);
|
|
65
|
+
domains = (project) => this.request('GET', `/cloud/projects/${project}/domains`).then((r) => r.items);
|
|
66
|
+
addDomain = (project, name) => this.request('POST', `/cloud/projects/${project}/domains`, { name });
|
|
67
|
+
checkDomain = (project, id) => this.request('POST', `/cloud/projects/${project}/domains/${id}/check`);
|
|
68
|
+
removeDomain = (project, id) => this.request('DELETE', `/cloud/projects/${project}/domains/${id}`);
|
|
69
|
+
startDevice = (clientName, locale) => this.request('POST', `/cloud/cli/device?locale=${locale}`, { clientName });
|
|
70
|
+
pollDevice = (deviceCode) => this.request('POST', '/cloud/cli/device/token', { deviceCode });
|
|
71
|
+
async deploy(project, bundle, fields) {
|
|
72
|
+
const form = new FormData();
|
|
73
|
+
form.set('target', fields.target);
|
|
74
|
+
if (fields.message)
|
|
75
|
+
form.set('message', fields.message.slice(0, 200));
|
|
76
|
+
if (fields.commit)
|
|
77
|
+
form.set('commit', fields.commit);
|
|
78
|
+
if (fields.branch)
|
|
79
|
+
form.set('branch', fields.branch.slice(0, 100));
|
|
80
|
+
form.set('bundle', await openAsBlob(bundle, { type: 'application/gzip' }), 'site.tar.gz');
|
|
81
|
+
return this.request('POST', `/cloud/projects/${project}/deployments`, form);
|
|
82
|
+
}
|
|
83
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { execFile, spawn } from 'node:child_process';
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
import { mkdtemp, rm, stat } from 'node:fs/promises';
|
|
5
|
+
import { hostname, tmpdir } from 'node:os';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { createInterface } from 'node:readline/promises';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { parseArgs, promisify } from 'node:util';
|
|
10
|
+
import { Api, ApiError } from './api.js';
|
|
11
|
+
import { DEFAULT_API, configPath, forgetConfig, readConfig, readProjectFile, saveConfig, writeProjectFile, PROJECT_FILE, } from './config.js';
|
|
12
|
+
import { collect, pack } from './pack.js';
|
|
13
|
+
const VERSION = '0.1.0';
|
|
14
|
+
const run = promisify(execFile);
|
|
15
|
+
const tty = process.stdout.isTTY;
|
|
16
|
+
const paint = (code) => (text) => (tty ? `\x1b[${code}m${text}\x1b[0m` : text);
|
|
17
|
+
const bold = paint(1);
|
|
18
|
+
const dim = paint(2);
|
|
19
|
+
const green = paint(32);
|
|
20
|
+
const pink = paint(35);
|
|
21
|
+
class UsageError extends Error {
|
|
22
|
+
}
|
|
23
|
+
const HELP = `${bold('codeqlick')} ${VERSION} — deploy static sites to Codeqlick Cloud
|
|
24
|
+
|
|
25
|
+
Usage: codeqlick <command> [options]
|
|
26
|
+
|
|
27
|
+
Commands:
|
|
28
|
+
login [--token <cqk_…>] Sign in (approve it in the browser), or save a token
|
|
29
|
+
logout Forget the saved token
|
|
30
|
+
whoami Your account and teams
|
|
31
|
+
init Link this folder to a project (writes ${PROJECT_FILE})
|
|
32
|
+
deploy [folder] Upload a built folder as a new deployment
|
|
33
|
+
--prod publish it (otherwise it's a preview)
|
|
34
|
+
-m, --message <text> shown in the console
|
|
35
|
+
deployments The project's deployments, newest first
|
|
36
|
+
promote <id> Publish an earlier deployment (its short id)
|
|
37
|
+
rollback Publish the deployment before the current one
|
|
38
|
+
domains [add|check|rm <domain>] The project's own domains
|
|
39
|
+
open Open the published site
|
|
40
|
+
|
|
41
|
+
Options:
|
|
42
|
+
--team <slug> --project <slug> Override ${PROJECT_FILE} (or CODEQLICK_TEAM, CODEQLICK_PROJECT)
|
|
43
|
+
-h, --help -v, --version
|
|
44
|
+
|
|
45
|
+
Environment: CODEQLICK_TOKEN (CI), CODEQLICK_API_URL. Docs: https://cloud.codeqlick.com/en/docs`;
|
|
46
|
+
async function context() {
|
|
47
|
+
const stored = await readConfig();
|
|
48
|
+
const apiUrl = (process.env.CODEQLICK_API_URL || stored.apiUrl || DEFAULT_API).replace(/\/+$/, '');
|
|
49
|
+
const token = process.env.CODEQLICK_TOKEN || stored.token;
|
|
50
|
+
return { apiUrl, token, api: new Api(apiUrl, token) };
|
|
51
|
+
}
|
|
52
|
+
async function signedIn() {
|
|
53
|
+
const ctx = await context();
|
|
54
|
+
if (!ctx.token)
|
|
55
|
+
throw new UsageError('Not signed in: run `codeqlick login` (or set CODEQLICK_TOKEN).');
|
|
56
|
+
return ctx;
|
|
57
|
+
}
|
|
58
|
+
/** The project to act on: flags, then the environment, then codeqlick.json. */
|
|
59
|
+
async function target(api, options) {
|
|
60
|
+
const file = await readProjectFile();
|
|
61
|
+
const team = options.team ?? process.env.CODEQLICK_TEAM ?? file.team;
|
|
62
|
+
const slug = options.project ?? process.env.CODEQLICK_PROJECT ?? file.project;
|
|
63
|
+
if (!team || !slug) {
|
|
64
|
+
throw new UsageError(`No project: run \`codeqlick init\`, or pass --team and --project.`);
|
|
65
|
+
}
|
|
66
|
+
const project = (await api.projects(team)).find((p) => p.slug === slug);
|
|
67
|
+
if (!project)
|
|
68
|
+
throw new UsageError(`There is no project "${slug}" in the team "${team}".`);
|
|
69
|
+
return project;
|
|
70
|
+
}
|
|
71
|
+
function openBrowser(url) {
|
|
72
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
73
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
74
|
+
try {
|
|
75
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true });
|
|
76
|
+
child.on('error', () => undefined);
|
|
77
|
+
child.unref();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// No browser here: the URL is printed.
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
84
|
+
function bytes(value) {
|
|
85
|
+
if (value < 1024)
|
|
86
|
+
return `${value} B`;
|
|
87
|
+
if (value < 1024 * 1024)
|
|
88
|
+
return `${(value / 1024).toFixed(1)} KB`;
|
|
89
|
+
return `${(value / 1024 / 1024).toFixed(1)} MB`;
|
|
90
|
+
}
|
|
91
|
+
async function ask(question, fallback = '') {
|
|
92
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
93
|
+
try {
|
|
94
|
+
const answer = (await rl.question(`${question}${fallback ? dim(` (${fallback})`) : ''}: `)).trim();
|
|
95
|
+
return answer || fallback;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
rl.close();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const slugify = (text) => text
|
|
102
|
+
.normalize('NFD')
|
|
103
|
+
.replace(/[̀-ͯ]/g, '')
|
|
104
|
+
.toLowerCase()
|
|
105
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
106
|
+
.replace(/^-+|-+$/g, '')
|
|
107
|
+
.slice(0, 40)
|
|
108
|
+
.replace(/-+$/, '');
|
|
109
|
+
// ── Commands ──────────────────────────────────────────────────────────────────────────────────
|
|
110
|
+
async function login(options) {
|
|
111
|
+
const { apiUrl } = await context();
|
|
112
|
+
if (options.token) {
|
|
113
|
+
const me = await new Api(apiUrl, options.token).me();
|
|
114
|
+
await saveConfig({ ...(await readConfig()), token: options.token });
|
|
115
|
+
console.log(`${green('✓')} Signed in as ${bold(me.user.email)} with a token.`);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const api = new Api(apiUrl);
|
|
119
|
+
const machine = hostname()
|
|
120
|
+
.replace(/[^\p{L}\p{N} ._@()-]/gu, '')
|
|
121
|
+
.slice(0, 60) || 'terminal';
|
|
122
|
+
const locale = (process.env.LANG ?? '').startsWith('es') ? 'es' : 'en';
|
|
123
|
+
const start = await api.startDevice(machine, locale);
|
|
124
|
+
console.log(`Your code: ${bold(pink(start.userCode))}`);
|
|
125
|
+
console.log(`Approve it at ${start.verificationUriComplete}`);
|
|
126
|
+
openBrowser(start.verificationUriComplete);
|
|
127
|
+
const deadline = Date.now() + start.expiresIn * 1000;
|
|
128
|
+
while (Date.now() < deadline) {
|
|
129
|
+
await sleep(start.interval * 1000);
|
|
130
|
+
let result;
|
|
131
|
+
try {
|
|
132
|
+
result = await api.pollDevice(start.deviceCode);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (error instanceof ApiError && error.status === 429)
|
|
136
|
+
continue;
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
if (result.status === 'approved') {
|
|
140
|
+
await saveConfig({ ...(await readConfig()), token: result.token });
|
|
141
|
+
console.log(`${green('✓')} Signed in as ${bold(result.user.email)}. Token saved in ${dim(configPath())}`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (result.status === 'denied')
|
|
145
|
+
throw new UsageError('The sign-in was denied.');
|
|
146
|
+
if (result.status === 'expired')
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
throw new UsageError('The code expired: run `codeqlick login` again.');
|
|
150
|
+
}
|
|
151
|
+
async function logout() {
|
|
152
|
+
await forgetConfig();
|
|
153
|
+
console.log(`${green('✓')} Signed out (the token is still valid until you revoke it in the console).`);
|
|
154
|
+
}
|
|
155
|
+
async function whoami() {
|
|
156
|
+
const { api } = await signedIn();
|
|
157
|
+
const me = await api.me();
|
|
158
|
+
console.log(`${bold(me.user.name)} <${me.user.email}>${me.token ? dim(` · token "${me.token.name}"`) : ''}`);
|
|
159
|
+
for (const team of me.teams)
|
|
160
|
+
console.log(` ${team.slug} ${dim(`${team.name} · ${team.role.toLowerCase()}`)}`);
|
|
161
|
+
if (me.teams.length === 0)
|
|
162
|
+
console.log(dim(' No teams yet: create one at https://cloud.codeqlick.com'));
|
|
163
|
+
}
|
|
164
|
+
async function init() {
|
|
165
|
+
const { api } = await signedIn();
|
|
166
|
+
const me = await api.me();
|
|
167
|
+
if (me.teams.length === 0)
|
|
168
|
+
throw new UsageError('Create a team first at https://cloud.codeqlick.com');
|
|
169
|
+
const file = await readProjectFile();
|
|
170
|
+
me.teams.forEach((team, index) => console.log(` ${index + 1}. ${team.slug} ${dim(team.name)}`));
|
|
171
|
+
const pick = await ask('Team', file.team ?? me.teams[0]?.slug);
|
|
172
|
+
const team = me.teams.find((t, index) => t.slug === pick || String(index + 1) === pick);
|
|
173
|
+
if (!team)
|
|
174
|
+
throw new UsageError(`Unknown team "${pick}".`);
|
|
175
|
+
const projects = await api.projects(team.slug);
|
|
176
|
+
projects.forEach((project, index) => console.log(` ${index + 1}. ${project.slug} ${dim(project.url)}`));
|
|
177
|
+
console.log(` n. ${dim('a new project')}`);
|
|
178
|
+
const choice = await ask('Project', file.project ?? (projects.length ? '1' : 'n'));
|
|
179
|
+
let project = projects.find((p, index) => p.slug === choice || String(index + 1) === choice);
|
|
180
|
+
if (!project) {
|
|
181
|
+
const name = await ask('Name of the new project', choice === 'n' ? '' : choice);
|
|
182
|
+
if (!name)
|
|
183
|
+
throw new UsageError('A project needs a name.');
|
|
184
|
+
const slug = await ask('Address', slugify(name));
|
|
185
|
+
project = await api.createProject(team.slug, name, slug);
|
|
186
|
+
console.log(`${green('✓')} Created ${project.url}`);
|
|
187
|
+
}
|
|
188
|
+
const dir = await ask('Folder to deploy', file.dir ?? 'dist');
|
|
189
|
+
await writeProjectFile({ team: team.slug, project: project.slug, dir });
|
|
190
|
+
console.log(`${green('✓')} Linked to ${bold(project.slug)}. Saved in ${PROJECT_FILE}: commit it.`);
|
|
191
|
+
}
|
|
192
|
+
/** The commit and branch, from GitHub Actions or git, when there are any. */
|
|
193
|
+
async function gitInfo() {
|
|
194
|
+
if (process.env.GITHUB_SHA) {
|
|
195
|
+
return {
|
|
196
|
+
commit: process.env.GITHUB_SHA,
|
|
197
|
+
branch: process.env.GITHUB_HEAD_REF || process.env.GITHUB_REF_NAME,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const commit = (await run('git', ['rev-parse', 'HEAD'])).stdout.trim();
|
|
202
|
+
const branch = (await run('git', ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim();
|
|
203
|
+
return { commit, branch: branch === 'HEAD' ? undefined : branch };
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return {};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async function deploy(folder, options) {
|
|
210
|
+
const { api } = await signedIn();
|
|
211
|
+
const file = await readProjectFile();
|
|
212
|
+
const root = resolve(folder ?? file.dir ?? 'dist');
|
|
213
|
+
if (!(await stat(root).catch(() => null))?.isDirectory()) {
|
|
214
|
+
throw new UsageError(`${root} isn't a folder: build your site first, or pass the folder.`);
|
|
215
|
+
}
|
|
216
|
+
const project = await target(api, options);
|
|
217
|
+
const files = await collect(root);
|
|
218
|
+
if (!files.some((f) => f.path === 'index.html')) {
|
|
219
|
+
throw new UsageError(`There's no index.html in ${root}.`);
|
|
220
|
+
}
|
|
221
|
+
const work = await mkdtemp(join(tmpdir(), 'codeqlick-'));
|
|
222
|
+
try {
|
|
223
|
+
const bundle = join(work, 'site.tar.gz');
|
|
224
|
+
const size = await pack(files, bundle);
|
|
225
|
+
const total = files.reduce((sum, f) => sum + f.size, 0);
|
|
226
|
+
console.log(`Uploading ${files.length} files (${bytes(total)}, ${bytes(size)} compressed) to ${bold(project.slug)}…`);
|
|
227
|
+
const { commit, branch } = await gitInfo();
|
|
228
|
+
const deployment = await api.deploy(project.id, bundle, {
|
|
229
|
+
target: options.prod ? 'production' : 'preview',
|
|
230
|
+
message: options.message,
|
|
231
|
+
commit: commit && /^[0-9a-f]{4,40}$/i.test(commit) ? commit : undefined,
|
|
232
|
+
branch,
|
|
233
|
+
});
|
|
234
|
+
console.log(`${green('✓')} Deployment ${bold(deployment.shortId)}: ${deployment.url}`);
|
|
235
|
+
if (deployment.isProduction)
|
|
236
|
+
console.log(`${green('✓')} Published: ${bold(project.url)}`);
|
|
237
|
+
else
|
|
238
|
+
console.log(dim(` A preview. Publish it with: codeqlick promote ${deployment.shortId}`));
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
await rm(work, { recursive: true, force: true });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async function allDeployments(api, project) {
|
|
245
|
+
return (await api.deployments(project)).items;
|
|
246
|
+
}
|
|
247
|
+
async function deployments(options) {
|
|
248
|
+
const { api } = await signedIn();
|
|
249
|
+
const project = await target(api, options);
|
|
250
|
+
const list = await allDeployments(api, project.id);
|
|
251
|
+
if (list.length === 0)
|
|
252
|
+
console.log(dim('No deployments yet.'));
|
|
253
|
+
for (const d of list) {
|
|
254
|
+
const tag = d.isProduction ? green('published') : dim('preview ');
|
|
255
|
+
const when = new Date(d.createdAt).toLocaleString();
|
|
256
|
+
console.log(`${bold(d.shortId)} ${tag} ${when} ${d.message ?? ''}`.trimEnd());
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
async function promote(id, options) {
|
|
260
|
+
if (!id)
|
|
261
|
+
throw new UsageError('Which deployment? `codeqlick promote <id>` (see `codeqlick deployments`).');
|
|
262
|
+
const { api } = await signedIn();
|
|
263
|
+
const project = await target(api, options);
|
|
264
|
+
const found = (await allDeployments(api, project.id)).find((d) => d.shortId === id || d.id === id);
|
|
265
|
+
if (!found)
|
|
266
|
+
throw new UsageError(`No deployment "${id}" among the last 50.`);
|
|
267
|
+
await api.promote(project.id, found.id);
|
|
268
|
+
console.log(`${green('✓')} ${bold(found.shortId)} is published: ${project.url}`);
|
|
269
|
+
}
|
|
270
|
+
async function rollback(options) {
|
|
271
|
+
const { api } = await signedIn();
|
|
272
|
+
const project = await target(api, options);
|
|
273
|
+
const list = await allDeployments(api, project.id);
|
|
274
|
+
const current = list.findIndex((d) => d.isProduction);
|
|
275
|
+
const older = current === -1 ? [] : list.slice(current + 1);
|
|
276
|
+
const previous = older.find((d) => d.target === 'production') ?? older[0];
|
|
277
|
+
if (!previous)
|
|
278
|
+
throw new UsageError('There is no earlier deployment to go back to.');
|
|
279
|
+
await api.promote(project.id, previous.id);
|
|
280
|
+
console.log(`${green('✓')} Back to ${bold(previous.shortId)}: ${project.url}`);
|
|
281
|
+
}
|
|
282
|
+
async function domains(action, name, options) {
|
|
283
|
+
const { api } = await signedIn();
|
|
284
|
+
const project = await target(api, options);
|
|
285
|
+
const show = (d) => {
|
|
286
|
+
console.log(`${bold(d.name)} ${d.state === 'LIVE' ? green('live') : d.state.toLowerCase()}`);
|
|
287
|
+
if (d.state !== 'LIVE') {
|
|
288
|
+
for (const r of d.dns)
|
|
289
|
+
console.log(` ${r.ok ? green('✓') : '·'} ${r.type.padEnd(5)} ${r.name} ${r.value}`);
|
|
290
|
+
if (d.lastError)
|
|
291
|
+
console.log(dim(` ${d.lastError}`));
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
if (!action || action === 'ls' || action === 'list') {
|
|
295
|
+
const list = await api.domains(project.id);
|
|
296
|
+
if (list.length === 0)
|
|
297
|
+
console.log(dim('No domains yet: codeqlick domains add <domain>'));
|
|
298
|
+
list.forEach(show);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (!name)
|
|
302
|
+
throw new UsageError(`Which domain? codeqlick domains ${action} <domain>`);
|
|
303
|
+
const domain = name.toLowerCase();
|
|
304
|
+
if (action === 'add') {
|
|
305
|
+
show(await api.addDomain(project.id, domain));
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const found = (await api.domains(project.id)).find((d) => d.name === domain);
|
|
309
|
+
if (!found)
|
|
310
|
+
throw new UsageError(`${domain} isn't a domain of ${project.slug}.`);
|
|
311
|
+
if (action === 'check')
|
|
312
|
+
show(await api.checkDomain(project.id, found.id));
|
|
313
|
+
else if (action === 'rm' || action === 'remove') {
|
|
314
|
+
await api.removeDomain(project.id, found.id);
|
|
315
|
+
console.log(`${green('✓')} Removed ${domain}`);
|
|
316
|
+
}
|
|
317
|
+
else
|
|
318
|
+
throw new UsageError(`Unknown action "${action}": add, check or rm.`);
|
|
319
|
+
}
|
|
320
|
+
async function openSite(options) {
|
|
321
|
+
const { api } = await signedIn();
|
|
322
|
+
const project = await target(api, options);
|
|
323
|
+
console.log(project.url);
|
|
324
|
+
openBrowser(project.url);
|
|
325
|
+
}
|
|
326
|
+
// ── Entry ─────────────────────────────────────────────────────────────────────────────────────
|
|
327
|
+
export async function main(argv) {
|
|
328
|
+
const { values, positionals } = parseArgs({
|
|
329
|
+
args: argv,
|
|
330
|
+
allowPositionals: true,
|
|
331
|
+
options: {
|
|
332
|
+
team: { type: 'string' },
|
|
333
|
+
project: { type: 'string' },
|
|
334
|
+
prod: { type: 'boolean' },
|
|
335
|
+
message: { type: 'string', short: 'm' },
|
|
336
|
+
token: { type: 'string' },
|
|
337
|
+
help: { type: 'boolean', short: 'h' },
|
|
338
|
+
version: { type: 'boolean', short: 'v' },
|
|
339
|
+
},
|
|
340
|
+
});
|
|
341
|
+
if (values.version) {
|
|
342
|
+
console.log(VERSION);
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
const [command, ...rest] = positionals;
|
|
346
|
+
if (values.help || !command) {
|
|
347
|
+
console.log(HELP);
|
|
348
|
+
return values.help ? 0 : 1;
|
|
349
|
+
}
|
|
350
|
+
const options = values;
|
|
351
|
+
try {
|
|
352
|
+
switch (command) {
|
|
353
|
+
case 'login':
|
|
354
|
+
await login(options);
|
|
355
|
+
break;
|
|
356
|
+
case 'logout':
|
|
357
|
+
await logout();
|
|
358
|
+
break;
|
|
359
|
+
case 'whoami':
|
|
360
|
+
await whoami();
|
|
361
|
+
break;
|
|
362
|
+
case 'init':
|
|
363
|
+
await init();
|
|
364
|
+
break;
|
|
365
|
+
case 'deploy':
|
|
366
|
+
await deploy(rest[0], options);
|
|
367
|
+
break;
|
|
368
|
+
case 'deployments':
|
|
369
|
+
case 'ls':
|
|
370
|
+
await deployments(options);
|
|
371
|
+
break;
|
|
372
|
+
case 'promote':
|
|
373
|
+
await promote(rest[0], options);
|
|
374
|
+
break;
|
|
375
|
+
case 'rollback':
|
|
376
|
+
await rollback(options);
|
|
377
|
+
break;
|
|
378
|
+
case 'domains':
|
|
379
|
+
await domains(rest[0], rest[1], options);
|
|
380
|
+
break;
|
|
381
|
+
case 'open':
|
|
382
|
+
await openSite(options);
|
|
383
|
+
break;
|
|
384
|
+
default:
|
|
385
|
+
throw new UsageError(`Unknown command "${command}". Run codeqlick --help.`);
|
|
386
|
+
}
|
|
387
|
+
return 0;
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (error instanceof UsageError)
|
|
391
|
+
console.error(error.message);
|
|
392
|
+
else if (error instanceof ApiError) {
|
|
393
|
+
console.error(error.status === 401
|
|
394
|
+
? 'Not signed in, or the token is invalid: run `codeqlick login`.'
|
|
395
|
+
: error.message);
|
|
396
|
+
}
|
|
397
|
+
else
|
|
398
|
+
console.error(error.message);
|
|
399
|
+
return 1;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
// Run when executed, also through npm's bin link (not when imported by the tests).
|
|
403
|
+
const invoked = process.argv[1] ? realpathSync(process.argv[1]) : '';
|
|
404
|
+
if (invoked === fileURLToPath(import.meta.url)) {
|
|
405
|
+
main(process.argv.slice(2)).then((code) => process.exit(code));
|
|
406
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
/** Where the token is kept: ~/.config/codeqlick/config.json (or $XDG_CONFIG_HOME), mode 600. */
|
|
5
|
+
export function configPath(env = process.env) {
|
|
6
|
+
const base = env.XDG_CONFIG_HOME || join(homedir(), '.config');
|
|
7
|
+
return join(base, 'codeqlick', 'config.json');
|
|
8
|
+
}
|
|
9
|
+
export async function readConfig(path = configPath()) {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(await readFile(path, 'utf8'));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return {};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function saveConfig(config, path = configPath()) {
|
|
18
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
19
|
+
await writeFile(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
20
|
+
await chmod(path, 0o600);
|
|
21
|
+
}
|
|
22
|
+
export async function forgetConfig(path = configPath()) {
|
|
23
|
+
await rm(path, { force: true });
|
|
24
|
+
}
|
|
25
|
+
export const PROJECT_FILE = 'codeqlick.json';
|
|
26
|
+
export async function readProjectFile(cwd = process.cwd()) {
|
|
27
|
+
try {
|
|
28
|
+
const data = JSON.parse(await readFile(join(cwd, PROJECT_FILE), 'utf8'));
|
|
29
|
+
return typeof data === 'object' && data ? data : {};
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return {};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function writeProjectFile(file, cwd = process.cwd()) {
|
|
36
|
+
await writeFile(join(cwd, PROJECT_FILE), `${JSON.stringify(file, null, 2)}\n`);
|
|
37
|
+
}
|
|
38
|
+
export const DEFAULT_API = 'https://api.codeqlick.com/v1';
|
package/dist/pack.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { lstat, readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { join, relative, sep } from 'node:path';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { createGzip } from 'node:zlib';
|
|
7
|
+
/**
|
|
8
|
+
* `.codeqlickignore` patterns: one per line, `#` comments, `*` matches anything but `/`, `**`
|
|
9
|
+
* anything, a trailing `/` a folder. A pattern without `/` matches a name at any depth.
|
|
10
|
+
*/
|
|
11
|
+
export function ignoreMatcher(text) {
|
|
12
|
+
const rules = text
|
|
13
|
+
.split(/\r?\n/)
|
|
14
|
+
.map((line) => line.trim())
|
|
15
|
+
.filter((line) => line && !line.startsWith('#'))
|
|
16
|
+
.map((line) => {
|
|
17
|
+
const folderOnly = line.endsWith('/');
|
|
18
|
+
const pattern = line.replace(/\/+$/, '').replace(/^\/+/, '');
|
|
19
|
+
const anchored = line.replace(/\/+$/, '').includes('/');
|
|
20
|
+
const source = pattern
|
|
21
|
+
.split('**')
|
|
22
|
+
.map((part) => part
|
|
23
|
+
.split('*')
|
|
24
|
+
.map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
|
|
25
|
+
.join('[^/]*'))
|
|
26
|
+
.join('.*');
|
|
27
|
+
const regex = new RegExp(anchored ? `^${source}$` : `(^|/)${source}$`);
|
|
28
|
+
return { regex, folderOnly };
|
|
29
|
+
});
|
|
30
|
+
return (path, folder) => rules.some((rule) => (!rule.folderOnly || folder) && rule.regex.test(path));
|
|
31
|
+
}
|
|
32
|
+
/** Whether a dotfile or dot-folder is left out (all but `.well-known`). */
|
|
33
|
+
const hidden = (name) => name.startsWith('.') && name !== '.well-known';
|
|
34
|
+
/** The files to deploy from `root`, sorted, without dotfiles, links or ignored paths. */
|
|
35
|
+
export async function collect(root) {
|
|
36
|
+
let ignore = () => false;
|
|
37
|
+
try {
|
|
38
|
+
ignore = ignoreMatcher(await readFile(join(root, '.codeqlickignore'), 'utf8'));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// No ignore file.
|
|
42
|
+
}
|
|
43
|
+
const files = [];
|
|
44
|
+
const walk = async (folder) => {
|
|
45
|
+
const entries = await readdir(folder, { withFileTypes: true });
|
|
46
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (hidden(entry.name))
|
|
49
|
+
continue;
|
|
50
|
+
const absolute = join(folder, entry.name);
|
|
51
|
+
const path = relative(root, absolute).split(sep).join('/');
|
|
52
|
+
if (entry.isDirectory()) {
|
|
53
|
+
if (!ignore(path, true))
|
|
54
|
+
await walk(absolute);
|
|
55
|
+
}
|
|
56
|
+
else if (entry.isFile()) {
|
|
57
|
+
if (!ignore(path, false))
|
|
58
|
+
files.push({ path, absolute, size: (await lstat(absolute)).size });
|
|
59
|
+
}
|
|
60
|
+
// Links and anything else are left out: the server refuses them.
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
await walk(root);
|
|
64
|
+
return files;
|
|
65
|
+
}
|
|
66
|
+
const BLOCK = 512;
|
|
67
|
+
function octal(value, length) {
|
|
68
|
+
return value.toString(8).padStart(length - 1, '0') + '\0';
|
|
69
|
+
}
|
|
70
|
+
function write(buffer, offset, text, length) {
|
|
71
|
+
buffer.write(text, offset, Math.min(length, Buffer.byteLength(text)), 'utf8');
|
|
72
|
+
}
|
|
73
|
+
/** A 512-byte ustar header (type `0` file or `x` PAX extended header). */
|
|
74
|
+
function header(name, size, type, mtime) {
|
|
75
|
+
const block = Buffer.alloc(BLOCK);
|
|
76
|
+
write(block, 0, name, 100);
|
|
77
|
+
write(block, 100, octal(0o644, 8), 8);
|
|
78
|
+
write(block, 108, octal(0, 8), 8);
|
|
79
|
+
write(block, 116, octal(0, 8), 8);
|
|
80
|
+
write(block, 124, octal(size, 12), 12);
|
|
81
|
+
write(block, 136, octal(mtime, 12), 12);
|
|
82
|
+
block.fill(' ', 148, 156);
|
|
83
|
+
write(block, 156, type, 1);
|
|
84
|
+
write(block, 257, 'ustar\0', 6);
|
|
85
|
+
write(block, 263, '00', 2);
|
|
86
|
+
let sum = 0;
|
|
87
|
+
for (const byte of block)
|
|
88
|
+
sum += byte;
|
|
89
|
+
write(block, 148, `${sum.toString(8).padStart(6, '0')}\0 `, 8);
|
|
90
|
+
return block;
|
|
91
|
+
}
|
|
92
|
+
/** A PAX record: `<length> path=<value>\n`, the length counting itself. */
|
|
93
|
+
function paxRecord(key, value) {
|
|
94
|
+
const body = ` ${key}=${value}\n`;
|
|
95
|
+
let length = Buffer.byteLength(body) + 1;
|
|
96
|
+
while (String(length).length + Buffer.byteLength(body) !== length) {
|
|
97
|
+
length = String(length).length + Buffer.byteLength(body);
|
|
98
|
+
}
|
|
99
|
+
return `${length}${body}`;
|
|
100
|
+
}
|
|
101
|
+
const padding = (size) => Buffer.alloc((BLOCK - (size % BLOCK)) % BLOCK);
|
|
102
|
+
/** The tar stream of the files: a PAX header before any path that doesn't fit ustar's 100 bytes. */
|
|
103
|
+
async function* tarStream(files) {
|
|
104
|
+
const mtime = Math.floor(Date.now() / 1000);
|
|
105
|
+
for (const file of files) {
|
|
106
|
+
const fits = Buffer.byteLength(file.path) <= 100 && /^[\x20-\x7e]+$/.test(file.path);
|
|
107
|
+
if (!fits) {
|
|
108
|
+
const record = Buffer.from(paxRecord('path', file.path));
|
|
109
|
+
yield header('PaxHeader', record.length, 'x', mtime);
|
|
110
|
+
yield record;
|
|
111
|
+
yield padding(record.length);
|
|
112
|
+
}
|
|
113
|
+
const data = await readFile(file.absolute);
|
|
114
|
+
yield header(fits ? file.path : file.path.slice(0, 99).replace(/[^\x20-\x7e]/g, '_'), data.length, '0', mtime);
|
|
115
|
+
yield data;
|
|
116
|
+
yield padding(data.length);
|
|
117
|
+
}
|
|
118
|
+
yield Buffer.alloc(BLOCK * 2);
|
|
119
|
+
}
|
|
120
|
+
/** Writes the files as a gzipped tar to `target`; returns its size in bytes. */
|
|
121
|
+
export async function pack(files, target) {
|
|
122
|
+
await pipeline(Readable.from(tarStream(files)), createGzip({ level: 9 }), createWriteStream(target));
|
|
123
|
+
return (await lstat(target)).size;
|
|
124
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codeqlick/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Deploy static sites to Codeqlick Cloud from your terminal or CI",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"homepage": "https://cloud.codeqlick.com/en/docs",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"codeqlick",
|
|
10
|
+
"deploy",
|
|
11
|
+
"static",
|
|
12
|
+
"hosting",
|
|
13
|
+
"cli"
|
|
14
|
+
],
|
|
15
|
+
"bin": {
|
|
16
|
+
"codeqlick": "dist/cli.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli.js",
|
|
27
|
+
"typecheck": "tsc --noEmit",
|
|
28
|
+
"test": "node --test src/*.test.ts",
|
|
29
|
+
"format": "prettier --write .",
|
|
30
|
+
"format:check": "prettier --check .",
|
|
31
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "24.19.2",
|
|
35
|
+
"prettier": "3.9.10",
|
|
36
|
+
"typescript": "7.0.2"
|
|
37
|
+
}
|
|
38
|
+
}
|