@nativescript/edge-cli 0.0.0-stage → 0.1.0-beta.13
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 +24 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +439 -0
- package/dist/sync.d.ts +37 -0
- package/dist/sync.js +67 -0
- package/dist/vite.d.ts +8 -0
- package/dist/vite.js +40 -0
- package/package.json +41 -4
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nativescript/edge-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
```sh
|
|
4
|
+
npx @nativescript/edge-cli live # a phone app: opens the IDE and prints a QR code for NativeScript Preview
|
|
5
|
+
npx @nativescript/edge-cli live --react # the same with a framework: --ng (Angular), --react, --vue, --svelte or --solid
|
|
6
|
+
npx @nativescript/edge-cli live --mac # a Mac app: opens the IDE and runs the app on this Mac, streamed into the IDE
|
|
7
|
+
npx @nativescript/edge-cli live --electron # an Electron app with native views, run the same way
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
`live` creates a project on preview.nativescript.org (`--server` or `NS_EDGE_SERVER` for another edge), saves it to `.ns-edge.json` and opens its IDE. The framework flags are `ns create`'s (`--ng`/`--angular`, `--react`, `--vue`, `--svelte`, `--solid`, `--ts`); without one a phone project is plain TypeScript with XML views. Run it again in the same folder to reopen that project (no flag needed), or add `--new` for another; a flag for a different kind of project than the folder's asks for `--new`. `--from <sample>` starts from a copy of a shared project instead: a sample's name (`--from expo-settings`; `samples [words] [--tag <t>]` lists them, and `submit <name>` offers this folder's project as one), or any project's link or bare id. While `live` runs a Mac app it restarts the app if it crashes, unless it crashes three times in a minute. Without a create token the project is free: a few hosted agent turns a day, no backend, deleted after 30 days unused. `--no-open` skips the browser; with `--mac` or `--electron`, `--allow-eval` lets the agent run code on this Mac.
|
|
11
|
+
|
|
12
|
+
## Mirror a local project
|
|
13
|
+
|
|
14
|
+
Mirror a NativeScript project into an ns-edge project from a terminal or a Vite dev server.
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm i -D @nativescript/edge-cli@beta
|
|
18
|
+
npx ns-edge create --server https://preview.nativescript.org --token <create token> # --template vue for nativescript-vue
|
|
19
|
+
npx ns-edge watch # push, then every save
|
|
20
|
+
npx ns-edge qr # print the pairing QR code again
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Also: `ns-edge push` uploads `app/` and `server/` once, `ns-edge pull` downloads the project's files.
|
|
24
|
+
|
|
25
|
+
`ns-edge create` writes `.ns-edge.json` (project id and keys; keep it out of git). In a Vite config, `@nativescript/edge-cli/vite` mirrors `app/` and `server/` on every save.
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { existsSync, watch } from 'node:fs';
|
|
4
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { dirname, join, sep } from 'node:path';
|
|
6
|
+
import { createInterface } from 'node:readline/promises';
|
|
7
|
+
import QRCode from 'qrcode';
|
|
8
|
+
import { applyChanges, collect, createProject, projectUrl, report, SYNCED } from './sync.js';
|
|
9
|
+
const CONFIG = '.ns-edge.json';
|
|
10
|
+
const DEBOUNCE_MS = 120;
|
|
11
|
+
const LIVE_SERVER = process.env.NS_EDGE_SERVER ?? 'https://preview.nativescript.org';
|
|
12
|
+
/** The hosts `live --desktop` (or `--mac`, `--windows`), `--electron` and `--expo` run; bump them with each host release this CLI is tested against. */
|
|
13
|
+
const DESKTOP_HOSTS = {
|
|
14
|
+
macos: { spec: '@nativescript/edge-desktop@0.1.0-alpha.7', bin: 'ns-edge-desktop' },
|
|
15
|
+
electron: { spec: '@nativescript/edge-electron@0.1.0-alpha.4', bin: 'ns-edge-electron' },
|
|
16
|
+
expo: { spec: '@nativescript/edge-expo-desktop@0.1.0-alpha.1', bin: 'ns-edge-expo-desktop' },
|
|
17
|
+
};
|
|
18
|
+
const DESKTOP_TEMPLATES = new Set(['macos', 'electron', 'expo']);
|
|
19
|
+
/** The macos template is the desktop one: it runs on a Mac with AppKit and on Windows with WinUI, so all three flags pick it. */
|
|
20
|
+
const DESKTOP_FLAGS = { macos: ['desktop', 'mac', 'windows'], electron: ['electron'], expo: ['expo'] };
|
|
21
|
+
/** The NativeScript CLI's `ns create` framework flags, so `live` and `create` take the same ones. */
|
|
22
|
+
const FRAMEWORK_FLAGS = {
|
|
23
|
+
angular: ['ng', 'angular'],
|
|
24
|
+
react: ['react', 'reactjs'],
|
|
25
|
+
vue: ['vue', 'vuejs'],
|
|
26
|
+
svelte: ['svelte'],
|
|
27
|
+
solid: ['solid', 'solidjs'],
|
|
28
|
+
core: ['ts', 'tsc', 'typescript'],
|
|
29
|
+
unified: ['unified'],
|
|
30
|
+
};
|
|
31
|
+
const TEMPLATE_KINDS = {
|
|
32
|
+
core: 'a phone',
|
|
33
|
+
angular: 'an Angular phone',
|
|
34
|
+
react: 'a React phone',
|
|
35
|
+
vue: 'a Vue phone',
|
|
36
|
+
svelte: 'a Svelte phone',
|
|
37
|
+
solid: 'a Solid phone',
|
|
38
|
+
macos: 'a desktop',
|
|
39
|
+
electron: 'an Electron',
|
|
40
|
+
expo: 'an Expo Desktop',
|
|
41
|
+
unified: 'a unified multi-platform',
|
|
42
|
+
};
|
|
43
|
+
const MAX_CRASHES = 3;
|
|
44
|
+
const CRASH_WINDOW_MS = 60_000;
|
|
45
|
+
const RESTART_DELAY_MS = 1000;
|
|
46
|
+
const [cmd = 'help', ...args] = process.argv.slice(2);
|
|
47
|
+
/**
|
|
48
|
+
* Editors and tools write temp, swap and backup files next to the real one
|
|
49
|
+
* (sed -i's `.!123!file`, vim's `.file.swp`, `file~`). Skipped like collect()
|
|
50
|
+
* skips dotfiles: one such path in a batch makes the edge reject the whole batch.
|
|
51
|
+
*/
|
|
52
|
+
const isScratch = (rel) => rel.split('/').some((part) => part.startsWith('.')) || rel.endsWith('~');
|
|
53
|
+
const flag = (name) => {
|
|
54
|
+
const i = args.indexOf(`--${name}`);
|
|
55
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
56
|
+
};
|
|
57
|
+
const has = (name) => args.includes(`--${name}`);
|
|
58
|
+
/** The template --template, a framework flag or a desktop flag asks for, if any; asking for two is an error. */
|
|
59
|
+
function requestedTemplate() {
|
|
60
|
+
const asked = new Set();
|
|
61
|
+
const named = flag('template');
|
|
62
|
+
if (named)
|
|
63
|
+
asked.add(named);
|
|
64
|
+
for (const [template, names] of Object.entries(FRAMEWORK_FLAGS))
|
|
65
|
+
if (names.some((name) => has(name)))
|
|
66
|
+
asked.add(template);
|
|
67
|
+
for (const [template, names] of Object.entries(DESKTOP_FLAGS))
|
|
68
|
+
if (names.some((name) => has(name)))
|
|
69
|
+
asked.add(template);
|
|
70
|
+
if (asked.size > 1)
|
|
71
|
+
throw new Error(`Pick one kind of project: this asked for ${[...asked].join(' and ')}.`);
|
|
72
|
+
return [...asked][0];
|
|
73
|
+
}
|
|
74
|
+
const root = process.cwd();
|
|
75
|
+
async function loadRef() {
|
|
76
|
+
let ref;
|
|
77
|
+
try {
|
|
78
|
+
ref = JSON.parse(await readFile(join(root, CONFIG), 'utf8'));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
throw new Error(`No ${CONFIG} here. Run \`ns-edge create --server <url>\` first.`);
|
|
82
|
+
}
|
|
83
|
+
// Copies meant to be shared (the IDE's StackBlitz export) leave the write key out of the file,
|
|
84
|
+
// so it is asked for here and kept in memory only.
|
|
85
|
+
ref.writeKey ||= process.env.NS_EDGE_WRITE_KEY || (await ask("Paste this project's write key (the IDE copied it to your clipboard): "));
|
|
86
|
+
if (!ref.writeKey)
|
|
87
|
+
throw new Error(`No write key: add it to ${CONFIG} or set NS_EDGE_WRITE_KEY.`);
|
|
88
|
+
return ref;
|
|
89
|
+
}
|
|
90
|
+
async function ask(question) {
|
|
91
|
+
if (!process.stdin.isTTY)
|
|
92
|
+
return '';
|
|
93
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
94
|
+
try {
|
|
95
|
+
return (await rl.question(question)).trim();
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
rl.close();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async function printPairing(ref) {
|
|
102
|
+
const url = projectUrl(ref);
|
|
103
|
+
const device = `${url}#${ref.deviceKey}`;
|
|
104
|
+
console.log(await QRCode.toString(`${ref.pairScheme ?? 'nsedge'}://pair?url=${encodeURIComponent(device)}`, { type: 'terminal', small: true }));
|
|
105
|
+
console.log(` device ${device}`);
|
|
106
|
+
console.log(` ide ${url}/#key=${ref.writeKey}`);
|
|
107
|
+
}
|
|
108
|
+
/** This folder's project, if it has one the server still knows. */
|
|
109
|
+
/**
|
|
110
|
+
* The project `--from` names: a link to it (its IDE, read-only or device link),
|
|
111
|
+
* a bare id, or a sample's name on this CLI's server, with what it was made as.
|
|
112
|
+
*/
|
|
113
|
+
async function sourceProject(from) {
|
|
114
|
+
let server = flag('server') ?? LIVE_SERVER;
|
|
115
|
+
let id = from;
|
|
116
|
+
if (!/^[0-9a-f]{32}$/.test(from)) {
|
|
117
|
+
if (URL.canParse(from) && /^https?:$/.test(new URL(from).protocol)) {
|
|
118
|
+
const link = new URL(from);
|
|
119
|
+
const match = link.pathname.match(/^\/p\/([0-9a-f]{32})(?:\/|$)/) ?? link.pathname.match(/^\/p\/([a-z0-9-]+)\/?$/);
|
|
120
|
+
if (!match)
|
|
121
|
+
throw new Error(`--from takes a sample's name, a project link (https://…/p/<id>) or its id, not '${from}'.`);
|
|
122
|
+
server = link.origin;
|
|
123
|
+
id = match[1];
|
|
124
|
+
}
|
|
125
|
+
if (!/^[0-9a-f]{32}$/.test(id))
|
|
126
|
+
id = await sampleId(server, id);
|
|
127
|
+
}
|
|
128
|
+
const res = await fetch(`${server}/p/${id}/details`).catch(() => null);
|
|
129
|
+
if (!res?.ok)
|
|
130
|
+
throw new Error(`There's no project ${id} on ${server} to start from.`);
|
|
131
|
+
const { template, title } = (await res.json());
|
|
132
|
+
return { server, id, template, title };
|
|
133
|
+
}
|
|
134
|
+
function describeSubmission(s) {
|
|
135
|
+
const run = `npx @nativescript/edge-cli live --from ${s.name}`;
|
|
136
|
+
switch (s.status) {
|
|
137
|
+
case 'listed':
|
|
138
|
+
return `Listed as '${s.name}'. The name is yours for good. Anyone can start from it with:\n ${run}`;
|
|
139
|
+
case 'pending':
|
|
140
|
+
return `Submitted as '${s.name}' and awaiting review. Nobody else can take the name meanwhile. Once approved, anyone can run:\n ${run}`;
|
|
141
|
+
default:
|
|
142
|
+
return `'${s.name}' was ${s.status === 'declined' ? 'not approved' : 'taken out of the samples'}.${s.reason ? ` ${s.reason}` : ''}`;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Arguments that are neither flags nor a flag's value. */
|
|
146
|
+
function positionals() {
|
|
147
|
+
const VALUED = new Set(['--server', '--token', '--template', '--from', '--title', '--description', '--tags', '--tag']);
|
|
148
|
+
return args.filter((a, i) => !a.startsWith('--') && !VALUED.has(args[i - 1]));
|
|
149
|
+
}
|
|
150
|
+
async function listSamples(server, query = '', tag = '') {
|
|
151
|
+
const params = new URLSearchParams({ ...(query && { q: query }), ...(tag && { tag }) }).toString();
|
|
152
|
+
const res = await fetch(`${server}/api/samples${params ? `?${params}` : ''}`).catch(() => null);
|
|
153
|
+
if (!res?.ok || !res.headers.get('content-type')?.includes('json'))
|
|
154
|
+
return null;
|
|
155
|
+
return (await res.json());
|
|
156
|
+
}
|
|
157
|
+
async function sampleId(server, name) {
|
|
158
|
+
const res = await fetch(`${server}/api/samples/${encodeURIComponent(name)}`).catch(() => null);
|
|
159
|
+
if (!res)
|
|
160
|
+
throw new Error(`Couldn't reach ${server} to look up the sample '${name}'.`);
|
|
161
|
+
if (res.ok && res.headers.get('content-type')?.includes('json'))
|
|
162
|
+
return (await res.json()).id;
|
|
163
|
+
const names = (await listSamples(server))?.map((s) => s.name) ?? [];
|
|
164
|
+
const known = names.length ? ` Its samples: ${names.join(', ')}.` : '';
|
|
165
|
+
throw new Error(`There's no sample named '${name}' on ${server}.${known} --from also takes a project link or its full 32-character id.`);
|
|
166
|
+
}
|
|
167
|
+
async function savedProject() {
|
|
168
|
+
if (!existsSync(join(root, CONFIG)))
|
|
169
|
+
return null;
|
|
170
|
+
const ref = JSON.parse(await readFile(join(root, CONFIG), 'utf8'));
|
|
171
|
+
if (!ref.writeKey)
|
|
172
|
+
return null;
|
|
173
|
+
const res = await fetch(`${projectUrl(ref)}/files`).catch(() => null);
|
|
174
|
+
return res?.ok ? ref : null;
|
|
175
|
+
}
|
|
176
|
+
function openInBrowser(url) {
|
|
177
|
+
const [command, ...rest] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '""', url.replace(/&/g, '^&')] : ['xdg-open', url];
|
|
178
|
+
spawn(command, rest, { stdio: 'ignore', detached: true }).on('error', () => { }).unref();
|
|
179
|
+
}
|
|
180
|
+
const COMPUTER = process.platform === 'win32' ? 'PC' : 'Mac';
|
|
181
|
+
/**
|
|
182
|
+
* How to run npx. On Windows it's npx.cmd, which Node won't spawn without a
|
|
183
|
+
* shell (and a shell would re-parse the arguments), so npm's own npx-cli.js
|
|
184
|
+
* runs with this Node instead when it's where Node's installer puts it.
|
|
185
|
+
*/
|
|
186
|
+
function npx() {
|
|
187
|
+
if (process.platform !== 'win32')
|
|
188
|
+
return ['npx'];
|
|
189
|
+
const cli = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js');
|
|
190
|
+
return existsSync(cli) ? [process.execPath, cli] : ['npx.cmd'];
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Runs the desktop host for a desktop project until it quits or Ctrl+C. A host
|
|
194
|
+
* that crashes is started again, since nothing in the browser can reach this
|
|
195
|
+
* computer to do it, unless it keeps crashing. The host says what joining allows.
|
|
196
|
+
*/
|
|
197
|
+
async function runDesktopHost(ref) {
|
|
198
|
+
const mac = process.platform === 'darwin' && process.arch === 'arm64';
|
|
199
|
+
const windows = process.platform === 'win32' && (process.arch === 'x64' || process.arch === 'arm64');
|
|
200
|
+
if (ref.template === 'expo' && !mac && !(windows && process.arch === 'x64')) {
|
|
201
|
+
throw new Error('Expo Desktop projects run on an Apple Silicon Mac (macOS 14.4 or later) or a Windows x64 PC. Run the same command on one.');
|
|
202
|
+
}
|
|
203
|
+
if (!mac && !windows) {
|
|
204
|
+
throw new Error('Desktop projects run on an Apple Silicon Mac (macOS 14.4 or later) or a Windows 10 (1903 or later) or Windows 11 PC. Run the same command there.');
|
|
205
|
+
}
|
|
206
|
+
const device = `${projectUrl(ref)}#${ref.deviceKey}`;
|
|
207
|
+
const extra = has('allow-eval') ? ['--allow-eval'] : [];
|
|
208
|
+
const host = DESKTOP_HOSTS[ref.template ?? 'macos'] ?? DESKTOP_HOSTS.macos;
|
|
209
|
+
// NS_EDGE_HOST runs another spec of the host (a version, or file:<packed .tgz>) to test a release before publishing it.
|
|
210
|
+
const spec = process.env.NS_EDGE_HOST ?? host.spec;
|
|
211
|
+
let child;
|
|
212
|
+
let stopping = false;
|
|
213
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
214
|
+
process.on(signal, () => {
|
|
215
|
+
stopping = true;
|
|
216
|
+
child?.kill(signal);
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
const crashes = [];
|
|
220
|
+
for (;;) {
|
|
221
|
+
const [command, ...prefix] = npx();
|
|
222
|
+
child = spawn(command, [...prefix, '-y', '--package', spec, '--', host.bin, device, '--yes', ...extra], { stdio: 'inherit' });
|
|
223
|
+
const exit = await new Promise((resolve, reject) => {
|
|
224
|
+
child.on('error', reject);
|
|
225
|
+
child.on('exit', (code, signal) => resolve({ code, signal }));
|
|
226
|
+
});
|
|
227
|
+
if (stopping || exit.code === 0)
|
|
228
|
+
return;
|
|
229
|
+
const now = Date.now();
|
|
230
|
+
crashes.push(now);
|
|
231
|
+
while (crashes[0] < now - CRASH_WINDOW_MS)
|
|
232
|
+
crashes.shift();
|
|
233
|
+
const why = exit.signal ?? `code ${exit.code}`;
|
|
234
|
+
if (crashes.length > MAX_CRASHES) {
|
|
235
|
+
throw new Error(`The desktop host crashed ${crashes.length} times in a minute (last: ${why}), so it wasn't restarted. Fix the error above, then run this command again.`);
|
|
236
|
+
}
|
|
237
|
+
console.log(`\nThe desktop host stopped (${why}). Starting it again…\n`);
|
|
238
|
+
await new Promise((r) => setTimeout(r, RESTART_DELAY_MS));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const commands = {
|
|
242
|
+
async live() {
|
|
243
|
+
for (const later of ['ios', 'android', 'all']) {
|
|
244
|
+
if (has(later))
|
|
245
|
+
throw new Error(`--${later} isn't available yet. Run \`live\` for a phone app, or \`live --desktop\`, \`--electron\` or \`--expo\` for a desktop app.`);
|
|
246
|
+
}
|
|
247
|
+
const fromArg = flag('from');
|
|
248
|
+
const source = fromArg ? await sourceProject(fromArg) : null;
|
|
249
|
+
let ref = has('new') || source ? null : await savedProject();
|
|
250
|
+
// Unified projects run on phones and in the desktop/Electron hosts, so --desktop or --electron picks which host to launch.
|
|
251
|
+
const unifiedDesktopHost = (source?.template === 'unified' || ref?.template === 'unified') &&
|
|
252
|
+
(DESKTOP_FLAGS.electron.some((n) => has(n)) ? 'electron' : DESKTOP_FLAGS.macos.some((n) => has(n)) ? 'macos' : undefined);
|
|
253
|
+
const requested = unifiedDesktopHost ? undefined : requestedTemplate();
|
|
254
|
+
if (source && requested && requested !== source.template) {
|
|
255
|
+
throw new Error(`--from names ${TEMPLATE_KINDS[source.template] ?? `a ${source.template}`} project, so leave out the flag asking for ${TEMPLATE_KINDS[requested] ?? `a ${requested}`} one.`);
|
|
256
|
+
}
|
|
257
|
+
// Without a template flag, this folder's project runs as whatever it was made as.
|
|
258
|
+
const template = source?.template ?? requested ?? ref?.template ?? 'core';
|
|
259
|
+
const desktopHost = unifiedDesktopHost ?? (DESKTOP_TEMPLATES.has(template) ? template : undefined);
|
|
260
|
+
if (ref && requested && (ref.template ?? 'core') !== requested) {
|
|
261
|
+
const current = TEMPLATE_KINDS[ref.template ?? 'core'] ?? `a ${ref.template}`;
|
|
262
|
+
throw new Error(`This folder's project (${CONFIG}) is ${current} project. Add --new to start ${TEMPLATE_KINDS[requested] ?? `a ${requested}`} one, or run this in another folder.`);
|
|
263
|
+
}
|
|
264
|
+
if (ref) {
|
|
265
|
+
console.log(`Opening this folder's project ${ref.id} (${CONFIG})`);
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
ref = await createProject(source?.server ?? flag('server') ?? LIVE_SERVER, flag('token') ?? process.env.NS_EDGE_CREATE_TOKEN, template, source?.id);
|
|
269
|
+
await writeFile(join(root, CONFIG), JSON.stringify(ref, null, 2) + '\n');
|
|
270
|
+
const made = source ? `your copy of ${source.title ? `"${source.title}"` : `project ${source.id}`}` : `${TEMPLATE_KINDS[template] ?? `a ${template}`} project`;
|
|
271
|
+
console.log(`Created ${made}, saved to ${CONFIG} (it holds the project's keys: keep it private and out of git).`);
|
|
272
|
+
if (ref.free) {
|
|
273
|
+
console.log(`It's a free project: ${ref.free.agentTurnsPerDay} hosted agent turn${ref.free.agentTurnsPerDay === 1 ? '' : 's'} a day, deleted after ${ref.free.idleDays} days unused. ` +
|
|
274
|
+
'For an unlimited agent, add your own API key in the agent panel or connect Claude Code from Connect agent.');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const ide = `${projectUrl(ref)}/#key=${ref.writeKey}`;
|
|
278
|
+
console.log(`\n IDE ${ide}\n`);
|
|
279
|
+
if (!has('no-open'))
|
|
280
|
+
openInBrowser(ide);
|
|
281
|
+
if (desktopHost) {
|
|
282
|
+
const first = desktopHost === 'electron' ? ' (the first run downloads Electron)' : desktopHost === 'expo' ? ' (the first run downloads the Expo Desktop shell)' : '';
|
|
283
|
+
console.log(`Starting the app on this ${COMPUTER}${first}. Its window streams to the IDE's Device pane. Press Ctrl+C to stop.\n`);
|
|
284
|
+
return runDesktopHost({ ...ref, template: desktopHost });
|
|
285
|
+
}
|
|
286
|
+
const device = `${projectUrl(ref)}#${ref.deviceKey}`;
|
|
287
|
+
console.log(await QRCode.toString(`${ref.pairScheme ?? 'nsedge'}://pair?url=${encodeURIComponent(device)}`, { type: 'terminal', small: true }));
|
|
288
|
+
console.log(`Scan with your phone's camera to open it in ${ref.pairScheme === 'nspreview' ? 'NativeScript Preview' : 'the edge shell'}, then edit in the IDE.`);
|
|
289
|
+
if (template === 'unified') {
|
|
290
|
+
console.log(`To also run this unified project on this ${COMPUTER}, run \`npx @nativescript/edge-cli live --desktop\` (or \`--electron\`) here.`);
|
|
291
|
+
}
|
|
292
|
+
console.log('Run this command again in this folder to reopen the project.');
|
|
293
|
+
},
|
|
294
|
+
async create() {
|
|
295
|
+
const server = flag('server') ?? 'http://localhost:5173';
|
|
296
|
+
const ref = await createProject(server, flag('token') ?? process.env.NS_EDGE_CREATE_TOKEN, requestedTemplate());
|
|
297
|
+
await writeFile(join(root, CONFIG), JSON.stringify(ref, null, 2) + '\n');
|
|
298
|
+
console.log(`Created project ${ref.id} (saved to ${CONFIG}; it holds the project keys, keep it out of git)`);
|
|
299
|
+
await printPairing(ref);
|
|
300
|
+
},
|
|
301
|
+
async push() {
|
|
302
|
+
const ref = await loadRef();
|
|
303
|
+
const files = await collect(root);
|
|
304
|
+
report(await applyChanges(ref, files));
|
|
305
|
+
},
|
|
306
|
+
async pull() {
|
|
307
|
+
const ref = await loadRef();
|
|
308
|
+
const list = (await (await fetch(`${projectUrl(ref)}/files`)).json());
|
|
309
|
+
const { mkdir } = await import('node:fs/promises');
|
|
310
|
+
const { dirname } = await import('node:path');
|
|
311
|
+
for (const { path } of list) {
|
|
312
|
+
const content = await (await fetch(`${projectUrl(ref)}/files/${path}`)).text();
|
|
313
|
+
await mkdir(dirname(join(root, path)), { recursive: true });
|
|
314
|
+
await writeFile(join(root, path), content);
|
|
315
|
+
console.log(` ↓ ${path}`);
|
|
316
|
+
}
|
|
317
|
+
},
|
|
318
|
+
async watch() {
|
|
319
|
+
const ref = await loadRef();
|
|
320
|
+
await printPairing(ref);
|
|
321
|
+
report(await applyChanges(ref, await collect(root)));
|
|
322
|
+
const pending = new Set();
|
|
323
|
+
let timer;
|
|
324
|
+
const flush = async () => {
|
|
325
|
+
const paths = [...pending];
|
|
326
|
+
pending.clear();
|
|
327
|
+
const changes = await Promise.all(paths.map(async (path) => ({ path, content: await readFile(join(root, path), 'utf8').catch(() => null) })));
|
|
328
|
+
report(await applyChanges(ref, changes));
|
|
329
|
+
};
|
|
330
|
+
const changed = (rel) => {
|
|
331
|
+
pending.add(rel);
|
|
332
|
+
clearTimeout(timer);
|
|
333
|
+
timer = setTimeout(() => void flush().catch((e) => console.error(` ✖ ${e.message}`)), DEBOUNCE_MS);
|
|
334
|
+
};
|
|
335
|
+
try {
|
|
336
|
+
watch(root, { recursive: true }, (_event, file) => {
|
|
337
|
+
if (!file)
|
|
338
|
+
return;
|
|
339
|
+
const rel = file.split(sep).join('/');
|
|
340
|
+
if (SYNCED.test(rel) && !isScratch(rel))
|
|
341
|
+
changed(rel);
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
// Runtimes without recursive fs.watch (some sandboxes and WebContainers) compare snapshots instead.
|
|
346
|
+
let last = new Map((await collect(root)).map((c) => [c.path, c.content]));
|
|
347
|
+
setInterval(async () => {
|
|
348
|
+
const now = new Map((await collect(root)).map((c) => [c.path, c.content]));
|
|
349
|
+
for (const [path, content] of now)
|
|
350
|
+
if (last.get(path) !== content)
|
|
351
|
+
changed(path);
|
|
352
|
+
for (const path of last.keys())
|
|
353
|
+
if (!now.has(path))
|
|
354
|
+
changed(path);
|
|
355
|
+
last = now;
|
|
356
|
+
}, 1000);
|
|
357
|
+
}
|
|
358
|
+
console.log(' watching app/ and server/ …');
|
|
359
|
+
},
|
|
360
|
+
async qr() {
|
|
361
|
+
await printPairing(await loadRef());
|
|
362
|
+
},
|
|
363
|
+
async samples() {
|
|
364
|
+
const server = flag('server') ?? LIVE_SERVER;
|
|
365
|
+
const query = positionals().join(' ');
|
|
366
|
+
const tag = flag('tag');
|
|
367
|
+
const list = await listSamples(server, query, tag);
|
|
368
|
+
if (!list)
|
|
369
|
+
throw new Error(`Couldn't list the samples on ${server}.`);
|
|
370
|
+
if (!list.length)
|
|
371
|
+
return console.log(query || tag ? `No sample on ${server} matches${query ? ` '${query}'` : ''}${tag ? ` tagged ${tag}` : ''}.` : `${server} has no named samples yet.`);
|
|
372
|
+
const width = Math.max(...list.map((s) => s.name.length));
|
|
373
|
+
for (const s of list) {
|
|
374
|
+
console.log(` ${s.name.padEnd(width)} ${s.title}`);
|
|
375
|
+
if (s.description)
|
|
376
|
+
console.log(` ${' '.repeat(width)} ${s.description.split('\n')[0].slice(0, 100)}`);
|
|
377
|
+
if (s.tags?.length)
|
|
378
|
+
console.log(` ${' '.repeat(width)} ${s.tags.map((t) => `#${t}`).join(' ')}`);
|
|
379
|
+
}
|
|
380
|
+
console.log(`\nStart from one with: npx @nativescript/edge-cli live --from <name>`);
|
|
381
|
+
console.log(`Browse them at ${server}/p/samples`);
|
|
382
|
+
},
|
|
383
|
+
async submit() {
|
|
384
|
+
const ref = await loadRef();
|
|
385
|
+
const url = `${projectUrl(ref)}/sample`;
|
|
386
|
+
const headers = { authorization: `Bearer ${ref.writeKey}`, 'content-type': 'application/json' };
|
|
387
|
+
const [name] = positionals();
|
|
388
|
+
if (has('withdraw')) {
|
|
389
|
+
const res = await fetch(url, { method: 'DELETE', headers });
|
|
390
|
+
if (!res.ok)
|
|
391
|
+
throw new Error(await res.text());
|
|
392
|
+
return console.log('Withdrawn.');
|
|
393
|
+
}
|
|
394
|
+
if (!name) {
|
|
395
|
+
const res = await fetch(url, { headers });
|
|
396
|
+
if (res.status === 404)
|
|
397
|
+
return console.log('This project has not been submitted. Run: ns-edge submit <name> [--title <t>] [--description <d>]');
|
|
398
|
+
if (!res.ok)
|
|
399
|
+
throw new Error(await res.text());
|
|
400
|
+
return console.log(describeSubmission((await res.json())));
|
|
401
|
+
}
|
|
402
|
+
const res = await fetch(url, {
|
|
403
|
+
method: 'PUT',
|
|
404
|
+
headers,
|
|
405
|
+
body: JSON.stringify({ name, title: flag('title'), description: flag('description'), tags: flag('tags')?.split(/[\s,]+/).filter(Boolean) }),
|
|
406
|
+
});
|
|
407
|
+
if (!res.ok)
|
|
408
|
+
throw new Error(await res.text());
|
|
409
|
+
console.log(describeSubmission((await res.json())));
|
|
410
|
+
},
|
|
411
|
+
async help() {
|
|
412
|
+
console.log(`ns-edge <command>
|
|
413
|
+
|
|
414
|
+
samples [words] [--tag <t>]
|
|
415
|
+
list the samples --from can start from by name, or those matching the words or tag
|
|
416
|
+
submit <name> [--title <t>] [--description <d>] [--tags macos,windows]
|
|
417
|
+
submit this folder's project to the samples under that name; once it's
|
|
418
|
+
approved the name is yours for good. \`submit\` alone shows where it stands,
|
|
419
|
+
\`submit --withdraw\` withdraws it while it awaits review
|
|
420
|
+
live [--ng|--react|--vue|--svelte|--solid|--desktop|--electron|--expo] [--new] [--from <sample>] [--no-open] [--allow-eval]
|
|
421
|
+
create a project (or reopen this folder's), open its IDE, and print a QR code
|
|
422
|
+
for your phone; --ng, --react, --vue, --svelte or --solid picks the framework
|
|
423
|
+
(plain TypeScript with XML views otherwise); --desktop (or --mac, --windows)
|
|
424
|
+
or --electron runs it on this Mac or Windows PC instead, with that OS's own
|
|
425
|
+
controls; --expo runs an Expo Desktop app on this Mac or Windows x64 PC;
|
|
426
|
+
--from starts from a copy of a shared project: a sample's name, link or id
|
|
427
|
+
create [--server <url>] [--token <t>] [--ng|--react|--vue|--svelte|--solid|--template <name>]
|
|
428
|
+
create an edge project and save .ns-edge.json
|
|
429
|
+
push upload app/ and server/ in one transaction
|
|
430
|
+
watch push, then stream every save to the edge
|
|
431
|
+
pull download the project's files here
|
|
432
|
+
qr print the pairing QR code`);
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
const run = commands[cmd] ?? commands.help;
|
|
436
|
+
run().catch((e) => {
|
|
437
|
+
console.error(e.message);
|
|
438
|
+
process.exit(1);
|
|
439
|
+
});
|
package/dist/sync.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export interface ProjectRef {
|
|
2
|
+
server: string;
|
|
3
|
+
id: string;
|
|
4
|
+
writeKey: string;
|
|
5
|
+
deviceKey: string;
|
|
6
|
+
/** URL scheme of the app the server pairs with, from its create response. */
|
|
7
|
+
pairScheme?: string;
|
|
8
|
+
template?: string;
|
|
9
|
+
/** Set on free projects: their daily agent allowance and how long they last unused. */
|
|
10
|
+
free?: {
|
|
11
|
+
agentTurnsPerDay: number;
|
|
12
|
+
idleDays: number;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export interface ApplyResult {
|
|
16
|
+
changed: string[];
|
|
17
|
+
diagnostics: {
|
|
18
|
+
path: string;
|
|
19
|
+
error: string;
|
|
20
|
+
}[];
|
|
21
|
+
version: number;
|
|
22
|
+
}
|
|
23
|
+
/** Project-relative paths that are mirrored to the edge. */
|
|
24
|
+
export declare const SYNCED: RegExp;
|
|
25
|
+
export declare function projectUrl(ref: ProjectRef): string;
|
|
26
|
+
/** With `from`, the project starts as a copy of that one, which must be a `template` project. */
|
|
27
|
+
export declare function createProject(server: string, token?: string, template?: string, from?: string): Promise<ProjectRef>;
|
|
28
|
+
/** Sends a batch as one edge transaction, so devices see one consistent update. */
|
|
29
|
+
export declare function applyChanges(ref: ProjectRef, changes: {
|
|
30
|
+
path: string;
|
|
31
|
+
content: string | null;
|
|
32
|
+
}[]): Promise<ApplyResult>;
|
|
33
|
+
export declare function collect(root: string): Promise<{
|
|
34
|
+
path: string;
|
|
35
|
+
content: string;
|
|
36
|
+
}[]>;
|
|
37
|
+
export declare function report(result: ApplyResult, log?: (s: string) => void): void;
|
package/dist/sync.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { readFile, readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
/** Project-relative paths that are mirrored to the edge. */
|
|
4
|
+
export const SYNCED = /^(app|server|web)\/.+\.(ts|tsx|mts|js|jsx|mjs|vue|svelte|xml|html|css|json|svg)$/;
|
|
5
|
+
export function projectUrl(ref) {
|
|
6
|
+
return `${ref.server.replace(/\/$/, '')}/p/${ref.id}`;
|
|
7
|
+
}
|
|
8
|
+
/** With `from`, the project starts as a copy of that one, which must be a `template` project. */
|
|
9
|
+
export async function createProject(server, token, template, from) {
|
|
10
|
+
const query = from ? `?from=${encodeURIComponent(from)}` : template ? `?template=${encodeURIComponent(template)}` : '';
|
|
11
|
+
const res = await fetch(`${server.replace(/\/$/, '')}/api/projects${query}`, {
|
|
12
|
+
method: 'POST',
|
|
13
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
14
|
+
});
|
|
15
|
+
if (res.status === 401)
|
|
16
|
+
throw new Error(`${server} creates projects only with a create token: pass --token or set NS_EDGE_CREATE_TOKEN.`);
|
|
17
|
+
if (res.status === 404 && from)
|
|
18
|
+
throw new Error(`There's no project ${from} on ${server} to start from.`);
|
|
19
|
+
if (!res.ok)
|
|
20
|
+
throw new Error(`Couldn't create a project (${res.status}): ${await res.text()}`);
|
|
21
|
+
const { id, writeKey, deviceKey, pair, free } = (await res.json());
|
|
22
|
+
return { server, id, writeKey, deviceKey, pairScheme: pair?.split('://')[0], template: template ?? 'core', ...(free && { free }) };
|
|
23
|
+
}
|
|
24
|
+
/** Sends a batch as one edge transaction, so devices see one consistent update. */
|
|
25
|
+
export async function applyChanges(ref, changes) {
|
|
26
|
+
const res = await fetch(`${projectUrl(ref)}/files`, {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
headers: { authorization: `Bearer ${ref.writeKey}`, 'content-type': 'application/json' },
|
|
29
|
+
body: JSON.stringify({ changes }),
|
|
30
|
+
});
|
|
31
|
+
if (!res.ok)
|
|
32
|
+
throw new Error(`sync failed: ${res.status} ${await res.text()}`);
|
|
33
|
+
return (await res.json());
|
|
34
|
+
}
|
|
35
|
+
export async function collect(root) {
|
|
36
|
+
const out = [];
|
|
37
|
+
const walk = async (dir) => {
|
|
38
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
39
|
+
if (entry.name === 'node_modules' || entry.name.startsWith('.'))
|
|
40
|
+
continue;
|
|
41
|
+
const full = join(dir, entry.name);
|
|
42
|
+
if (entry.isDirectory())
|
|
43
|
+
await walk(full);
|
|
44
|
+
else {
|
|
45
|
+
const rel = relative(root, full).split(sep).join('/');
|
|
46
|
+
if (SYNCED.test(rel))
|
|
47
|
+
out.push({ path: rel, content: await readFile(full, 'utf8') });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
for (const top of ['app', 'server', 'web']) {
|
|
52
|
+
const dir = join(root, top);
|
|
53
|
+
if (await stat(dir).then((s) => s.isDirectory(), () => false))
|
|
54
|
+
await walk(dir);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
export function report(result, log = console.log) {
|
|
59
|
+
if (result.diagnostics.length) {
|
|
60
|
+
for (const d of result.diagnostics)
|
|
61
|
+
log(` ✖ ${d.error}`);
|
|
62
|
+
log(' devices kept the previous version');
|
|
63
|
+
}
|
|
64
|
+
else if (result.changed.length) {
|
|
65
|
+
log(` v${result.version} ← ${result.changed.join(', ')}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Plugin } from 'vite';
|
|
2
|
+
import { type ProjectRef } from './sync.js';
|
|
3
|
+
/**
|
|
4
|
+
* Mirrors a project's app/ and server/ folders into an edge project while
|
|
5
|
+
* `vite dev` runs, so every phone paired with that project hot-reloads from
|
|
6
|
+
* the nearest Cloudflare location, not from this machine.
|
|
7
|
+
*/
|
|
8
|
+
export declare function nsEdge(ref: ProjectRef): Plugin;
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { relative, sep } from 'node:path';
|
|
3
|
+
import { applyChanges, collect, report, SYNCED } from './sync.js';
|
|
4
|
+
/**
|
|
5
|
+
* Mirrors a project's app/ and server/ folders into an edge project while
|
|
6
|
+
* `vite dev` runs, so every phone paired with that project hot-reloads from
|
|
7
|
+
* the nearest Cloudflare location, not from this machine.
|
|
8
|
+
*/
|
|
9
|
+
export function nsEdge(ref) {
|
|
10
|
+
let root = process.cwd();
|
|
11
|
+
return {
|
|
12
|
+
name: 'ns-edge',
|
|
13
|
+
apply: 'serve',
|
|
14
|
+
configResolved(config) {
|
|
15
|
+
root = config.root;
|
|
16
|
+
},
|
|
17
|
+
async configureServer(server) {
|
|
18
|
+
const log = (s) => server.config.logger.info(`[ns-edge] ${s}`, { timestamp: true });
|
|
19
|
+
report(await applyChanges(ref, await collect(root)), log);
|
|
20
|
+
const pending = new Map();
|
|
21
|
+
let timer;
|
|
22
|
+
const queue = (file, deleted) => {
|
|
23
|
+
const rel = relative(root, file).split(sep).join('/');
|
|
24
|
+
if (!SYNCED.test(rel))
|
|
25
|
+
return;
|
|
26
|
+
pending.set(rel, deleted ? null : file);
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
timer = setTimeout(async () => {
|
|
29
|
+
const batch = [...pending];
|
|
30
|
+
pending.clear();
|
|
31
|
+
const changes = await Promise.all(batch.map(async ([path, abs]) => ({ path, content: abs ? await readFile(abs, 'utf8') : null })));
|
|
32
|
+
report(await applyChanges(ref, changes), log);
|
|
33
|
+
}, 80);
|
|
34
|
+
};
|
|
35
|
+
server.watcher.on('add', (f) => queue(f, false));
|
|
36
|
+
server.watcher.on('change', (f) => queue(f, false));
|
|
37
|
+
server.watcher.on('unlink', (f) => queue(f, true));
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nativescript/edge-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-beta.13",
|
|
4
|
+
"description": "Mirror a NativeScript project into an ns-edge project from a terminal or a Vite dev server",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"ns-edge": "./dist/bin.js"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./dist/sync.js",
|
|
12
|
+
"./vite": "./dist/vite.js"
|
|
13
|
+
},
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsc -p .",
|
|
16
|
+
"typecheck": "tsc -p . --noEmit",
|
|
17
|
+
"prepack": "npm run build"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"qrcode": "^1.5.4"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^24.0.0",
|
|
24
|
+
"@types/qrcode": "^1.5.6",
|
|
25
|
+
"typescript": "^6.0.0",
|
|
26
|
+
"vite": "^8.3.5"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"vite": ">=6"
|
|
30
|
+
},
|
|
31
|
+
"peerDependenciesMeta": {
|
|
32
|
+
"vite": {
|
|
33
|
+
"optional": true
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public",
|
|
41
|
+
"tag": "beta"
|
|
42
|
+
}
|
|
43
|
+
}
|