@quxkit/quxcloud 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # quxcloud
2
+
3
+ Work on a QuxCloud project in your own editor.
4
+
5
+ ```
6
+ npx @quxkit/quxcloud login # opens your browser; approve the code shown
7
+ npx @quxkit/quxcloud link # pick the project this folder is
8
+ npx @quxkit/quxcloud pull # bring it down
9
+ npx @quxkit/quxcloud watch # every save goes back
10
+ ```
11
+
12
+ Nothing is typed into your shell. `login` prints a short code, opens QuxCloud
13
+ in your browser, and waits while you approve it there — so no key reaches your
14
+ history, your scrollback, or a screen share. The terminal receives an ordinary
15
+ workspace API key, listed under **API keys** and revocable there.
16
+
17
+ ## What does not come down
18
+
19
+ The `@quxkit` packages are licensed through your workspace and stay there, so
20
+ `pnpm install` has nothing to install locally. The loop this supports is **edit
21
+ locally, preview in the cloud**: a push lands in the project and the live
22
+ preview hot-reloads it. An enterprise licence includes a registry token if you
23
+ need to run the whole thing on your own machine.
24
+
25
+ ## In CI
26
+
27
+ `QUXCLOUD_KEY` and `QUXCLOUD_PROJECT` still work and take precedence, so the
28
+ same CLI runs unattended without an interactive login.
29
+
30
+ ## Where things are kept
31
+
32
+ | | |
33
+ |---|---|
34
+ | `~/.config/quxcloud/config.json` | the key, mode 0600, one per machine |
35
+ | `./.quxcloud` | which project this folder is — no secrets, commit it or don't |
36
+
37
+ The bridge is on the paid plans.
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@quxkit/quxcloud",
3
+ "version": "0.1.0",
4
+ "description": "Work on a QuxCloud project in your own editor.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "quxcloud": "./src/index.mjs"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "keywords": [
19
+ "quxkit",
20
+ "quxcloud",
21
+ "cli"
22
+ ],
23
+ "scripts": {
24
+ "test": "node --test test/*.test.mjs"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/QuxKit/quxcloud.git",
29
+ "directory": "cli"
30
+ },
31
+ "homepage": "https://cloud.quxkit.ai"
32
+ }
package/src/api.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Talking to QuxCloud.
2
+
3
+ export class ApiError extends Error {
4
+ constructor(message, status) {
5
+ super(message);
6
+ this.status = status;
7
+ }
8
+ }
9
+
10
+ export async function request(url, path, { method = 'GET', key, body } = {}) {
11
+ const res = await fetch(`${url}${path}`, {
12
+ method,
13
+ headers: {
14
+ ...(key ? { authorization: `Bearer ${key}` } : {}),
15
+ ...(body ? { 'content-type': 'application/json' } : {}),
16
+ },
17
+ ...(body ? { body: JSON.stringify(body) } : {}),
18
+ });
19
+ const text = await res.text();
20
+ let json = {};
21
+ try {
22
+ json = text ? JSON.parse(text) : {};
23
+ } catch {
24
+ // A non-JSON body is reported as itself below rather than swallowed.
25
+ }
26
+ if (!res.ok && res.status !== 202) {
27
+ throw new ApiError(json.error ?? text.slice(0, 200) ?? `${method} ${path} failed (${res.status})`, res.status);
28
+ }
29
+ return { status: res.status, json };
30
+ }
@@ -0,0 +1,192 @@
1
+ // What the CLI does.
2
+ //
3
+ // The sync half is the same logic the single-file bridge had, kept because it
4
+ // was right: the licence boundary is the server's, unchanged files are not
5
+ // sent, and a push says what it was based on so it cannot overwrite work
6
+ // nobody saw. What is new is that nothing has to be typed into a shell — no
7
+ // key, no project id, no base URL.
8
+
9
+ import { createHash } from 'node:crypto';
10
+ import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
11
+ import { basename, dirname, join, relative, sep } from 'node:path';
12
+
13
+ import { request } from './api.mjs';
14
+ import { clearConfig, configPath, DEFAULT_URL, readConfig, readLink, resolve, writeConfig, writeLink } from './config.mjs';
15
+ import { ask, bold, choose, cyan, dim, die, green, openBrowser, say, spinner } from './ui.mjs';
16
+
17
+ const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
18
+
19
+ /* ------------------------------------------------------------------ login -- */
20
+
21
+ export async function login(argv) {
22
+ const url = argv.url ?? process.env.QUXCLOUD_URL ?? readConfig().url ?? DEFAULT_URL;
23
+ const { json: device } = await request(url, '/api/cli/device', {
24
+ method: 'POST',
25
+ body: { client: `quxcloud-cli on ${process.platform}` },
26
+ });
27
+
28
+ say('');
29
+ say(` Your code is ${bold(cyan(device.userCode))}`);
30
+ say('');
31
+ say(` Approve it at ${dim(device.verifyUrl)}`);
32
+ say('');
33
+
34
+ await openBrowser(device.verifyUrl);
35
+ const spin = spinner('waiting for approval');
36
+
37
+ const deadline = Date.now() + device.expiresIn * 1000;
38
+ for (;;) {
39
+ if (Date.now() > deadline) {
40
+ spin.stop();
41
+ die('that code expired before it was approved. Run `quxcloud login` again.');
42
+ }
43
+ await new Promise((r) => setTimeout(r, (device.interval ?? 3) * 1000));
44
+ let result;
45
+ try {
46
+ result = await request(url, '/api/cli/token', { method: 'POST', body: { deviceCode: device.deviceCode } });
47
+ } catch (e) {
48
+ spin.stop();
49
+ die(e.message);
50
+ }
51
+ if (result.status === 202) continue;
52
+ if (result.json.status !== 'approved') {
53
+ spin.stop();
54
+ die(result.json.error ?? 'that sign-in did not complete.');
55
+ }
56
+ spin.stop();
57
+ writeConfig({ ...readConfig(), url, key: result.json.key });
58
+ say(`${green('Signed in.')} The key is in ${dim(configPath())} and listed under API keys, revocable there.`);
59
+ say(`Next: ${bold('quxcloud link')} in your project folder.`);
60
+ return;
61
+ }
62
+ }
63
+
64
+ export function logout() {
65
+ clearConfig();
66
+ say('Signed out on this machine. Revoke the key itself under API keys if it was shared.');
67
+ }
68
+
69
+ export async function whoami() {
70
+ const at = resolve({ needProject: false });
71
+ if (at.error) die(at.error);
72
+ const { json } = await request(at.url, '/api/cli/projects', { key: at.key });
73
+ const workspaces = [...new Set(json.projects.map((p) => p.workspace))];
74
+ say(`Signed in to ${bold(at.url)}`);
75
+ say(`Workspaces: ${workspaces.join(', ') || 'none'}`);
76
+ const link = readLink();
77
+ say(link.project ? `This folder: ${bold(link.name ?? link.project)}` : dim('This folder is not linked.'));
78
+ }
79
+
80
+ /* ------------------------------------------------------------------- link -- */
81
+
82
+ export async function link() {
83
+ const at = resolve({ needProject: false });
84
+ if (at.error) die(at.error);
85
+ const { json } = await request(at.url, '/api/cli/projects', { key: at.key });
86
+ const projects = json.projects ?? [];
87
+ if (projects.length === 0) die('there are no projects on this account yet — create one in QuxCloud first.');
88
+
89
+ say('');
90
+ const picked = projects.length === 1
91
+ ? projects[0]
92
+ : await choose(projects, (p) => `${bold(p.name)} ${dim(p.workspace)}${p.bridge ? '' : dim(' (needs a paid plan)')}`);
93
+ if (!picked) die('nothing chosen.');
94
+ if (!picked.bridge) {
95
+ die(`${picked.workspace} is on the free plan — the bridge is a paid feature. Upgrade under Plan & billing.`);
96
+ }
97
+
98
+ writeLink({ project: picked.id, name: picked.name, workspace: picked.workspace });
99
+ say(`\n${green('Linked')} this folder to ${bold(picked.name)}.`);
100
+ say(`Next: ${bold('quxcloud pull')}`);
101
+ }
102
+
103
+ /* ------------------------------------------------------------------- sync -- */
104
+
105
+ const SKIP = new Set(['node_modules', '.next', '.git', 'vendor', 'dist', 'build']);
106
+ const SELF = new Set(['.quxcloud', basename(process.argv[1] ?? '')]);
107
+
108
+ function walk(root, dir = root, out = []) {
109
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
110
+ if (entry.name.startsWith('.') && entry.name !== '.env.example') continue;
111
+ if (SKIP.has(entry.name) || SELF.has(entry.name)) continue;
112
+ const full = join(dir, entry.name);
113
+ if (entry.isDirectory()) walk(root, full, out);
114
+ else if (statSync(full).size < 512_000) out.push(relative(root, full).split(sep).join('/'));
115
+ }
116
+ return out;
117
+ }
118
+
119
+ export async function pull() {
120
+ const at = resolve();
121
+ if (at.error) die(at.error);
122
+ const spin = spinner('pulling');
123
+ const { json } = await request(at.url, `/api/bridge/${at.project}`, { key: at.key });
124
+ spin.stop();
125
+
126
+ const root = process.cwd();
127
+ for (const file of json.files) {
128
+ const target = join(root, file.path);
129
+ mkdirSync(dirname(target), { recursive: true });
130
+ writeFileSync(target, file.content);
131
+ }
132
+ writeLink({ ...readLink(), digest: json.digest, files: Object.fromEntries(json.files.map((f) => [f.path, sha(f.content)])) });
133
+
134
+ say(`${green('Pulled')} ${json.files.length} files.`);
135
+ if (json.withheld?.length) say(dim(`${json.withheld.length} path(s) stayed in QuxCloud.`));
136
+ say('');
137
+ say(dim(json.note ?? ''));
138
+ say(`Edit here; QuxCloud runs it. ${bold('quxcloud watch')} pushes every save.`);
139
+ }
140
+
141
+ export async function push({ quiet = false } = {}) {
142
+ const at = resolve();
143
+ if (at.error) die(at.error);
144
+ const link = readLink();
145
+ if (!link.digest) die('run `quxcloud pull` first — a push has to know what it is based on.');
146
+
147
+ const root = process.cwd();
148
+ const files = [];
149
+ for (const path of walk(root)) {
150
+ const content = readFileSync(join(root, path), 'utf8');
151
+ if (link.files?.[path] === sha(content)) continue;
152
+ files.push({ path, content });
153
+ }
154
+ if (files.length === 0) {
155
+ if (!quiet) say('Nothing to push.');
156
+ return;
157
+ }
158
+
159
+ const { json } = await request(at.url, `/api/bridge/${at.project}`, {
160
+ method: 'PUT',
161
+ key: at.key,
162
+ body: { files, basedOn: link.digest },
163
+ });
164
+ const next = { ...link, digest: json.digest, files: { ...link.files } };
165
+ for (const f of files) next.files[f.path] = sha(f.content);
166
+ writeLink(next);
167
+ say(`${green('Pushed')} ${json.written} file(s)${json.refused?.length ? dim(`, refused ${json.refused.join(', ')}`) : ''}`);
168
+ }
169
+
170
+ export async function watch() {
171
+ const at = resolve();
172
+ if (at.error) die(at.error);
173
+ say(`Watching ${bold(at.name ?? at.project)} — every save goes up. ${dim('ctrl-c to stop')}`);
174
+ const root = process.cwd();
175
+ const seen = new Map();
176
+ for (const path of walk(root)) seen.set(path, statSync(join(root, path)).mtimeMs);
177
+ for (;;) {
178
+ await new Promise((r) => setTimeout(r, 1200));
179
+ let changed = false;
180
+ for (const path of walk(root)) {
181
+ const m = statSync(join(root, path)).mtimeMs;
182
+ if (seen.get(path) !== m) {
183
+ seen.set(path, m);
184
+ changed = true;
185
+ }
186
+ }
187
+ // A failed push must not end the watch: the usual cause is someone else
188
+ // pushing, and the fix is a pull — which they can do while this keeps
189
+ // running.
190
+ if (changed) await push({ quiet: true }).catch((e) => say(`${dim('push failed:')} ${e.message}`));
191
+ }
192
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,68 @@
1
+ // Where the CLI keeps what it knows.
2
+ //
3
+ // Two files, deliberately in different places.
4
+ //
5
+ // ~/.config/quxcloud/config.json the key. One per machine, mode 0600, and
6
+ // NEVER in the project — a credential in a
7
+ // working tree is a credential in a commit.
8
+ // ./.quxcloud which project this directory is. Belongs
9
+ // with the code, holds nothing secret, and
10
+ // is what makes `pull` work with no
11
+ // arguments in the right folder.
12
+
13
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
14
+ import { homedir } from 'node:os';
15
+ import { dirname, join } from 'node:path';
16
+
17
+ const CONFIG_DIR = process.env.QUXCLOUD_CONFIG_DIR ?? join(homedir(), '.config', 'quxcloud');
18
+ const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
19
+ const LINK_FILE = '.quxcloud';
20
+
21
+ export const DEFAULT_URL = 'https://cloud.quxkit.ai';
22
+
23
+ const readJson = (path) => {
24
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return {}; }
25
+ };
26
+
27
+ export function readConfig() {
28
+ return readJson(CONFIG_FILE);
29
+ }
30
+
31
+ export function writeConfig(next) {
32
+ mkdirSync(dirname(CONFIG_FILE), { recursive: true });
33
+ writeFileSync(CONFIG_FILE, `${JSON.stringify(next, null, 2)}\n`);
34
+ // The key lives here. Anything readable by other accounts on the machine is
35
+ // a key shared with them.
36
+ try { chmodSync(CONFIG_FILE, 0o600); } catch { /* Windows has no mode bits */ }
37
+ }
38
+
39
+ export function clearConfig() {
40
+ if (existsSync(CONFIG_FILE)) writeConfig({});
41
+ }
42
+
43
+ export const configPath = () => CONFIG_FILE;
44
+
45
+ export function readLink(root = process.cwd()) {
46
+ return readJson(join(root, LINK_FILE));
47
+ }
48
+
49
+ export function writeLink(link, root = process.cwd()) {
50
+ writeFileSync(join(root, LINK_FILE), `${JSON.stringify(link, null, 2)}\n`);
51
+ }
52
+
53
+ /**
54
+ * Everything a command needs, or a clear reason why not.
55
+ *
56
+ * Environment variables still win, so CI can run the same CLI without an
57
+ * interactive login — but they are the exception now rather than the interface.
58
+ */
59
+ export function resolve({ needProject = true } = {}) {
60
+ const config = readConfig();
61
+ const link = readLink();
62
+ const url = process.env.QUXCLOUD_URL ?? config.url ?? DEFAULT_URL;
63
+ const key = process.env.QUXCLOUD_KEY ?? config.key;
64
+ const project = process.env.QUXCLOUD_PROJECT ?? link.project;
65
+ if (!key) return { error: 'Not signed in. Run `quxcloud login`.' };
66
+ if (needProject && !project) return { error: 'This folder is not linked to a project. Run `quxcloud link`.' };
67
+ return { url, key, project, name: link.name };
68
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ // quxcloud — work on a QuxCloud project in your own editor.
3
+ //
4
+ // npx @quxkit/quxcloud login sign in through the browser
5
+ // npx @quxkit/quxcloud link point this folder at a project
6
+ // npx @quxkit/quxcloud pull bring it down
7
+ // npx @quxkit/quxcloud watch push every save
8
+ //
9
+ // npm rather than a downloadable binary, and the reason is Gatekeeper. An
10
+ // unsigned Mac binary opens to "cannot be opened because the developer cannot
11
+ // be verified" and an unsigned Windows exe meets SmartScreen; a signed one
12
+ // needs an Apple Developer ID, notarisation and an Authenticode certificate.
13
+ // Anyone building a Next.js app already has Node, so `npx` is one command on
14
+ // all three platforms, needs no download, and updates itself.
15
+
16
+ import { link, login, logout, pull, push, watch, whoami } from './commands.mjs';
17
+ import { bold, die, dim, say } from './ui.mjs';
18
+
19
+ const COMMANDS = {
20
+ login: { run: login, blurb: 'sign in through your browser' },
21
+ logout: { run: logout, blurb: 'forget the key on this machine' },
22
+ whoami: { run: whoami, blurb: 'who this terminal is signed in as' },
23
+ link: { run: link, blurb: 'point this folder at a project' },
24
+ pull: { run: pull, blurb: 'bring the project down' },
25
+ push: { run: push, blurb: 'send your edits back' },
26
+ watch: { run: watch, blurb: 'push on every save' },
27
+ };
28
+
29
+ function usage() {
30
+ say(`${bold('quxcloud')} — your editor, QuxCloud's runtime\n`);
31
+ for (const [name, { blurb }] of Object.entries(COMMANDS)) {
32
+ say(` ${bold(name.padEnd(8))} ${blurb}`);
33
+ }
34
+ say(`\n${dim('Start with')} ${bold('quxcloud login')}${dim(', then')} ${bold('quxcloud link')}${dim(' in your project folder.')}`);
35
+ }
36
+
37
+ const [, , command, ...rest] = process.argv;
38
+ if (!command || command === 'help' || command === '--help' || command === '-h') {
39
+ usage();
40
+ process.exit(0);
41
+ }
42
+ if (command === '--version' || command === '-v') {
43
+ const { readFileSync } = await import('node:fs');
44
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
45
+ say(pkg.version);
46
+ process.exit(0);
47
+ }
48
+
49
+ const entry = COMMANDS[command];
50
+ if (!entry) {
51
+ say(`${dim('unknown command')} ${command}\n`);
52
+ usage();
53
+ process.exit(1);
54
+ }
55
+
56
+ // One place where an unexpected failure becomes a sentence rather than a stack
57
+ // trace. A CLI that prints a stack is telling its user to read its source.
58
+ try {
59
+ const urlFlag = rest.indexOf('--url');
60
+ await entry.run({ url: urlFlag === -1 ? undefined : rest[urlFlag + 1] });
61
+ } catch (error) {
62
+ die(error?.message ?? String(error));
63
+ }
package/src/ui.mjs ADDED
@@ -0,0 +1,80 @@
1
+ // Terminal manners.
2
+ //
3
+ // Colour only when the output is a terminal: piped into a file or a CI log,
4
+ // escape codes are noise somebody has to strip. NO_COLOR is honoured because
5
+ // it is the standard and costs one condition.
6
+
7
+ const ESC = '[';
8
+ const plain = !process.stdout.isTTY || process.env.NO_COLOR !== undefined;
9
+
10
+ const wrap = (code) => (s) => (plain ? s : `${ESC}${code}m${s}${ESC}0m`);
11
+ export const bold = wrap('1');
12
+ export const dim = wrap('2');
13
+ export const red = wrap('31');
14
+ export const green = wrap('32');
15
+ export const cyan = wrap('36');
16
+
17
+ export const say = (...parts) => console.log(...parts);
18
+ export const die = (message) => {
19
+ console.error(`${red('quxcloud')} ${message}`);
20
+ process.exit(1);
21
+ };
22
+
23
+ /** A spinner that degrades to one line when nobody is watching. */
24
+ export function spinner(text) {
25
+ if (plain) {
26
+ console.log(`${text}...`);
27
+ return { stop() {} };
28
+ }
29
+ const frames = ['|', '/', '-', '\\'];
30
+ let i = 0;
31
+ const timer = setInterval(() => {
32
+ process.stdout.write(`\r${cyan(frames[i++ % frames.length])} ${text}`);
33
+ }, 90);
34
+ return {
35
+ stop(final) {
36
+ clearInterval(timer);
37
+ process.stdout.write(`\r${' '.repeat(text.length + 4)}\r`);
38
+ if (final) console.log(final);
39
+ },
40
+ };
41
+ }
42
+
43
+ /** Ask a question. Returns '' when there is nobody to ask. */
44
+ export async function ask(question) {
45
+ if (!process.stdin.isTTY) return '';
46
+ const { createInterface } = await import('node:readline/promises');
47
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
48
+ try {
49
+ return (await rl.question(question)).trim();
50
+ } finally {
51
+ rl.close();
52
+ }
53
+ }
54
+
55
+ /** Pick one of a list, by number. */
56
+ export async function choose(items, render) {
57
+ items.forEach((item, i) => say(` ${dim(String(i + 1).padStart(2))} ${render(item)}`));
58
+ const answer = await ask(`\nWhich one? ${dim('[1]')} `);
59
+ const index = answer === '' ? 0 : Number(answer) - 1;
60
+ return items[index] ?? null;
61
+ }
62
+
63
+ /**
64
+ * Open a URL in the person's browser.
65
+ *
66
+ * Best effort, and the caller always prints the URL as well: a headless box, a
67
+ * container, an ssh session with no display — in all of them this does nothing
68
+ * and the printed link is the only way through.
69
+ */
70
+ export async function openBrowser(url) {
71
+ const { spawn } = await import('node:child_process');
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
+ spawn(command, args, { stdio: 'ignore', detached: true }).unref();
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }