ezship 0.1.11 → 0.1.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 +56 -8
- package/access.d.mts +120 -0
- package/access.mjs +987 -0
- package/account.d.mts +19 -0
- package/account.mjs +91 -0
- package/bindings.mjs +136 -0
- package/commands.d.mts +672 -0
- package/commands.mjs +8098 -0
- package/connections.d.mts +61 -0
- package/connections.mjs +312 -0
- package/cron.d.mts +17 -0
- package/cron.mjs +124 -0
- package/documents.d.mts +26 -0
- package/documents.mjs +242 -0
- package/editor-types.json.gz +0 -0
- package/editor.mjs +212 -0
- package/ez.mjs +1300 -2
- package/local-fetch.mjs +57 -0
- package/package.json +82 -6
- package/schema.d.mts +369 -0
- package/schema.mjs +3099 -0
- package/session.d.mts +20 -0
- package/session.mjs +142 -0
- package/shape.d.mts +14 -0
- package/shape.mjs +312 -0
- package/signup.d.mts +11 -0
- package/signup.mjs +42 -0
- package/types.d.mts +879 -0
- package/update-check.mjs +105 -0
- package/workflow.d.mts +63 -0
- package/workflow.mjs +450 -0
package/ez.mjs
CHANGED
|
@@ -1,3 +1,1301 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
//
|
|
3
|
-
import "
|
|
2
|
+
// Instance-connected terminal adapter (ADR 0026). The shared command contract lives in commands.mjs.
|
|
3
|
+
import { localFetch } from "./local-fetch.mjs";
|
|
4
|
+
import { checkForUpdate, installedAs } from "./update-check.mjs";
|
|
5
|
+
import { editorExports, ensureEditor } from "./editor.mjs";
|
|
6
|
+
import {
|
|
7
|
+
adoptBinding,
|
|
8
|
+
bindingFile,
|
|
9
|
+
instanceFolderOf,
|
|
10
|
+
moveWorkingCopy,
|
|
11
|
+
readBinding,
|
|
12
|
+
writeBinding,
|
|
13
|
+
} from "./bindings.mjs";
|
|
14
|
+
import { passwordLogin, runAccountCommand, ACCOUNT_COMMANDS } from "./account.mjs";
|
|
15
|
+
import {
|
|
16
|
+
connectionKey,
|
|
17
|
+
instanceKey,
|
|
18
|
+
discoverInstance,
|
|
19
|
+
connectionRequest,
|
|
20
|
+
CONTRACT,
|
|
21
|
+
CONTRACT_HEADER,
|
|
22
|
+
contractNote,
|
|
23
|
+
readConnections,
|
|
24
|
+
saveConnection,
|
|
25
|
+
findConnection,
|
|
26
|
+
makePrimary,
|
|
27
|
+
forgetConnection,
|
|
28
|
+
emptyConnections,
|
|
29
|
+
extractTarget,
|
|
30
|
+
usesWorkingCopy,
|
|
31
|
+
} from "./connections.mjs";
|
|
32
|
+
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
33
|
+
import { homedir } from "node:os";
|
|
34
|
+
import { watch } from "node:fs";
|
|
35
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
36
|
+
import { spawn } from "node:child_process";
|
|
37
|
+
import { hostname } from "node:os";
|
|
38
|
+
import { createInterface } from "node:readline/promises";
|
|
39
|
+
import {
|
|
40
|
+
assetContentType,
|
|
41
|
+
CommandFailure,
|
|
42
|
+
COMMAND_NAMES,
|
|
43
|
+
countChanges,
|
|
44
|
+
GLOBAL_ID,
|
|
45
|
+
httpWorkspace,
|
|
46
|
+
localChanges,
|
|
47
|
+
parseTarget,
|
|
48
|
+
previewNameFrom,
|
|
49
|
+
runCommand,
|
|
50
|
+
siteFolderName,
|
|
51
|
+
SITES_FOLDER,
|
|
52
|
+
} from "./commands.mjs";
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @typedef {import("./connections.d.mts").Connection} Connection
|
|
56
|
+
* @typedef {import("./types.d.mts").InstanceDiscovery} InstanceDiscovery
|
|
57
|
+
* @typedef {import("./types.d.mts").InstanceSummary} InstanceSummary
|
|
58
|
+
* @typedef {import("./commands.d.mts").Workspace} Workspace
|
|
59
|
+
* @typedef {import("./commands.d.mts").Pulled} Pulled
|
|
60
|
+
* @typedef {Omit<Partial<Connection>, "site"> & {site?: string | null}} Binding
|
|
61
|
+
* @typedef {Omit<Workspace, "pulled" | "globalWorkspace"> & {pulled(): Promise<(Pulled & Binding) | null>, globalWorkspace(): Promise<DiskWorkspace>}} DiskWorkspace
|
|
62
|
+
*/
|
|
63
|
+
const CRED_DIR = process.env.EZ_CONFIG_DIR || join(homedir(), ".ez");
|
|
64
|
+
const CRED_FILE = join(CRED_DIR, "connections.json");
|
|
65
|
+
const SKIP_DIRS = new Set(["node_modules", ".git", ".ez"]);
|
|
66
|
+
const VALUE_FLAGS = [
|
|
67
|
+
"--account",
|
|
68
|
+
"--from-api",
|
|
69
|
+
"--from-instance",
|
|
70
|
+
"--global-dir",
|
|
71
|
+
"--username",
|
|
72
|
+
"--name",
|
|
73
|
+
"--site",
|
|
74
|
+
"--instance",
|
|
75
|
+
"--dir",
|
|
76
|
+
"--api",
|
|
77
|
+
"--email",
|
|
78
|
+
"--kind",
|
|
79
|
+
"--limit",
|
|
80
|
+
"--before",
|
|
81
|
+
"--version",
|
|
82
|
+
];
|
|
83
|
+
async function readCredFile() {
|
|
84
|
+
return readConnections(await readFile(CRED_FILE, "utf8").catch(() => null));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Select once. A later primary change cannot retarget an already-running command.
|
|
89
|
+
* @param {string[]} args @param {string | undefined} [dir] @param {string} [command]
|
|
90
|
+
*/
|
|
91
|
+
async function loadCreds(args = [], dir, command = "") {
|
|
92
|
+
if (process.env.EZ_API || flag(args, "--api"))
|
|
93
|
+
throw new Error(
|
|
94
|
+
"Host API connections are retired. Use ez login <Instance URL> and --instance instead.",
|
|
95
|
+
);
|
|
96
|
+
const saved = await readCredFile();
|
|
97
|
+
const explicit = extractTarget([command, ...args]);
|
|
98
|
+
const bound = dir && command !== "adopt" ? await boundTarget(dir) : null;
|
|
99
|
+
const positionalTarget =
|
|
100
|
+
command === "clone"
|
|
101
|
+
? positionals(args)[0]
|
|
102
|
+
: command === "use"
|
|
103
|
+
? parseTarget(positionals(args)[0] || "")?.instance
|
|
104
|
+
: undefined;
|
|
105
|
+
const target = explicit.instance || process.env.EZ_INSTANCE || positionalTarget;
|
|
106
|
+
if (bound && !bound.uid && !target)
|
|
107
|
+
throw new Error(
|
|
108
|
+
"This is a legacy Working Copy. Connect to its Instance, then use ez adopt with an explicit source and target.",
|
|
109
|
+
);
|
|
110
|
+
let connection;
|
|
111
|
+
try {
|
|
112
|
+
connection = findConnection(
|
|
113
|
+
saved,
|
|
114
|
+
target ||
|
|
115
|
+
(bound?.uid
|
|
116
|
+
? bound.builder && !explicit.account
|
|
117
|
+
? connectionKey({ app: bound.app ?? "", uid: bound.uid, builder: bound.builder })
|
|
118
|
+
: instanceKey({ app: bound.app ?? "", uid: bound.uid })
|
|
119
|
+
: undefined),
|
|
120
|
+
explicit.account,
|
|
121
|
+
);
|
|
122
|
+
} catch (e) {
|
|
123
|
+
// A folder bound to a forgotten connection: name where it belongs and the exact
|
|
124
|
+
// login that restores it, instead of the binding's internal key.
|
|
125
|
+
if (!target && bound?.uid)
|
|
126
|
+
throw new Error(
|
|
127
|
+
`This Working Copy belongs to ${bound.instance} (${bound.app}). That connection is not saved here. Run: ez login ${bound.app}`,
|
|
128
|
+
{ cause: e },
|
|
129
|
+
);
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
if (usesWorkingCopy([command, ...args]) && bound) assertFolder(connection, bound);
|
|
133
|
+
return process.env.EZ_TOKEN ? { ...connection, token: process.env.EZ_TOKEN } : connection;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** @param {import("./connections.d.mts").SavedConnections} file */
|
|
137
|
+
async function writeCredFile(file) {
|
|
138
|
+
await mkdir(CRED_DIR, { recursive: true });
|
|
139
|
+
const temporary = `${CRED_FILE}.${process.pid}.tmp`;
|
|
140
|
+
await writeFile(temporary, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
|
|
141
|
+
await rename(temporary, CRED_FILE);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** @param {InstanceDiscovery} descriptor @param {string} token */
|
|
145
|
+
async function saveLogin(descriptor, token) {
|
|
146
|
+
const me = await request({ ...descriptor, token }, "GET", "/api/me");
|
|
147
|
+
if (
|
|
148
|
+
me.connection?.uid !== descriptor.uid ||
|
|
149
|
+
me.connection?.app !== descriptor.app ||
|
|
150
|
+
me.connection?.instance !== descriptor.instance ||
|
|
151
|
+
!me.id ||
|
|
152
|
+
!me.email
|
|
153
|
+
)
|
|
154
|
+
throw new Error("The sign-in response does not belong to the requested Instance.");
|
|
155
|
+
const connection = { ...descriptor, token, builder: me.id, email: me.email };
|
|
156
|
+
await writeCredFile(saveConnection(await readCredFile(), connection));
|
|
157
|
+
return connection;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @param {Connection} connection @param {Binding} bound */
|
|
161
|
+
function assertFolder(connection, bound) {
|
|
162
|
+
if (!bound.uid)
|
|
163
|
+
throw new Error(
|
|
164
|
+
"This is a legacy Working Copy. Use ez adopt with its explicit source and target before changing files.",
|
|
165
|
+
);
|
|
166
|
+
if (
|
|
167
|
+
bound.uid !== connection.uid ||
|
|
168
|
+
bound.app !== connection.app ||
|
|
169
|
+
(bound.builder && bound.builder !== connection.builder)
|
|
170
|
+
)
|
|
171
|
+
throw new Error(
|
|
172
|
+
`This Working Copy belongs to ${bound.instance} (${bound.email || bound.app}). Use --dir for the target Instance's own folder.`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** @param {string} dir @param {string | null} site */
|
|
177
|
+
async function assertSiteFolder(dir, site) {
|
|
178
|
+
const bound = await boundTarget(dir);
|
|
179
|
+
if (bound?.site && bound.site !== site)
|
|
180
|
+
throw new Error(
|
|
181
|
+
`This folder belongs to Site ${bound.site}. Use --dir for ${site}'s own Working Copy.`,
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* `ez global` from a Site keeps the Global Working Copy in the Instance folder, beside `sites/`. A folder
|
|
187
|
+
* outside one would put a first `global/` next to whatever its parent holds, so that asks for a place instead.
|
|
188
|
+
* @param {string} dir @param {string | null} site @param {string | undefined} globalDir
|
|
189
|
+
*/
|
|
190
|
+
async function assertGlobalHome(dir, site, globalDir) {
|
|
191
|
+
if (site === GLOBAL_ID || globalDir) return;
|
|
192
|
+
const root = instanceFolderOf(dir);
|
|
193
|
+
const folder = join(root, GLOBAL_ID);
|
|
194
|
+
if ((await boundTarget(folder))?.site === GLOBAL_ID) return;
|
|
195
|
+
const parent = await boundTarget(root);
|
|
196
|
+
if (parent && !parent.site) return;
|
|
197
|
+
throw new Error(
|
|
198
|
+
`${resolve(dir)} is not inside an Instance folder, so the Global Working Copy would be created at ${folder}.\n` +
|
|
199
|
+
`Keep an Instance's copies together: run \`ez clone\` in an empty folder (each Site gets a folder in sites/, beside global/),\n` +
|
|
200
|
+
`or pass --global-dir <folder> for the Global Working Copy.`,
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** @param {string} url */
|
|
205
|
+
function openBrowser(url) {
|
|
206
|
+
/** @type {[string, string[]]} */
|
|
207
|
+
const cmd =
|
|
208
|
+
process.platform === "win32"
|
|
209
|
+
? ["cmd", ["/c", "start", "", url]]
|
|
210
|
+
: process.platform === "darwin"
|
|
211
|
+
? ["open", [url]]
|
|
212
|
+
: ["xdg-open", [url]];
|
|
213
|
+
// A missing opener arrives as an `error` event, not a throw; either way the printed URL remains.
|
|
214
|
+
try {
|
|
215
|
+
spawn(cmd[0], cmd[1], { detached: true, stdio: "ignore" })
|
|
216
|
+
.on("error", () => {})
|
|
217
|
+
.unref();
|
|
218
|
+
} catch {}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** @param {number} ms */
|
|
222
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
223
|
+
|
|
224
|
+
/** @param {InstanceDiscovery & {token?: string}} creds @param {string} method @param {string} path @param {unknown} [body] @param {{raw?: boolean}} [options] */
|
|
225
|
+
async function request(creds, method, path, body, { raw = false } = {}) {
|
|
226
|
+
if (!creds.api) throw new Error("Connect to an Instance with ez login first.");
|
|
227
|
+
/** @type {Record<string,string>} */
|
|
228
|
+
const headers = { [CONTRACT_HEADER]: String(CONTRACT) };
|
|
229
|
+
if (creds.token) headers.authorization = `Bearer ${creds.token}`;
|
|
230
|
+
/** @type {string | undefined} */
|
|
231
|
+
let payload;
|
|
232
|
+
if (typeof body === "string") payload = body;
|
|
233
|
+
else if (body !== undefined) {
|
|
234
|
+
headers["content-type"] = "application/json";
|
|
235
|
+
payload = JSON.stringify(body);
|
|
236
|
+
}
|
|
237
|
+
const init = { method, headers, ...(payload !== undefined ? { body: payload } : {}) };
|
|
238
|
+
const res = creds.token
|
|
239
|
+
? await connectionRequest({ ...creds, token: creds.token }, path, init, localFetch)
|
|
240
|
+
: await localFetch(creds.api + path, { ...init, credentials: "omit", redirect: "error" });
|
|
241
|
+
const text = await res.text();
|
|
242
|
+
if (!res.ok) {
|
|
243
|
+
let msg = text;
|
|
244
|
+
try {
|
|
245
|
+
msg = JSON.parse(text).error ?? text;
|
|
246
|
+
} catch {}
|
|
247
|
+
// The Host's request id (ADR 0049) is what an operator finds in the Host's log.
|
|
248
|
+
const id = res.headers.get("x-request-id");
|
|
249
|
+
throw new Error(`${res.status} ${msg}${id ? ` (request ${id})` : ""}${contractNote(res)}`);
|
|
250
|
+
}
|
|
251
|
+
if (raw) return text;
|
|
252
|
+
try {
|
|
253
|
+
return JSON.parse(text);
|
|
254
|
+
} catch {
|
|
255
|
+
return text;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Reads `--flag value` out of args; returns the value or undefined.
|
|
261
|
+
* @param {string[]} args @param {string} name @returns {string | undefined}
|
|
262
|
+
*/
|
|
263
|
+
const flag = (args, name) => {
|
|
264
|
+
const i = args.indexOf(name);
|
|
265
|
+
return i >= 0 ? args[i + 1] : undefined;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Everything that is not a `--flag`, a value flag's value, or a bare `--switch`.
|
|
270
|
+
* @param {string[]} args
|
|
271
|
+
*/
|
|
272
|
+
function positionals(args) {
|
|
273
|
+
const out = [];
|
|
274
|
+
for (let i = 0; i < args.length; i++) {
|
|
275
|
+
if (args[i].startsWith("--")) {
|
|
276
|
+
if (VALUE_FLAGS.includes(args[i])) i++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
out.push(args[i]);
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* The argv the contract sees: the command, its positionals, and its bare switches (--force, --prune).
|
|
286
|
+
* @param {string[]} args
|
|
287
|
+
*/
|
|
288
|
+
function contractArgs(args) {
|
|
289
|
+
const out = [];
|
|
290
|
+
for (let i = 0; i < args.length; i++) {
|
|
291
|
+
if (VALUE_FLAGS.includes(args[i])) {
|
|
292
|
+
i++;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
out.push(args[i]);
|
|
296
|
+
}
|
|
297
|
+
return out;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---- which Instance, which Site ---------------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Every Site the Builder may open on the current login, flattened: [{ instance, id, name, role }].
|
|
304
|
+
* @param {Connection} creds
|
|
305
|
+
*/
|
|
306
|
+
async function listTargets(creds) {
|
|
307
|
+
const instances = /** @type {InstanceSummary[]} */ (
|
|
308
|
+
await request(creds, "GET", "/api/instances")
|
|
309
|
+
);
|
|
310
|
+
return instances.flatMap((i) =>
|
|
311
|
+
i.sites.map((s) => ({ instance: i.id, id: s.id, name: s.name, role: i.role })),
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** @param {{instance: string, id: string, name: string, role: string}} t @param {string | null | undefined} current */
|
|
316
|
+
const targetLine = (t, current) =>
|
|
317
|
+
`${current === t.id ? "*" : " "} ${t.instance}/${t.id} (${t.name}, ${t.role})`;
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* What a folder already is: a Working Copy (its binding, ADR 0085) or an Instance folder (<dir>/.ez/instance.json).
|
|
321
|
+
* @param {string} dir @returns {Promise<Binding | null>}
|
|
322
|
+
*/
|
|
323
|
+
async function boundTarget(dir) {
|
|
324
|
+
const p = await readBinding(dir);
|
|
325
|
+
if (p?.instance && p.site) return p;
|
|
326
|
+
try {
|
|
327
|
+
const i = JSON.parse(await readFile(join(dir, ".ez", "instance.json"), "utf8"));
|
|
328
|
+
if (i.instance) return { ...i, site: null };
|
|
329
|
+
} catch {}
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** @param {string} instance */
|
|
334
|
+
const instanceAgentsMd = (instance) =>
|
|
335
|
+
`# ezship Instance \`${instance}\`\n\n` +
|
|
336
|
+
`Each folder in \`sites/\` is the working copy of one Site of this Instance (\`sites/<site>/\`, with \`App.tsx\` at its root);\n` +
|
|
337
|
+
`\`global/\` holds shared components, lib/ modules (shared logic Sites import as global/lib/<name>), constants, the Theme, the Shell, db/schema.sql and generated db/types.d.ts. Admins and Builders push every file of it; Limited Builders read it. Use \`ez global\` from a Site.\n` +
|
|
338
|
+
`Site folders are named after their Sites, and their bindings live in this folder's \`.ez/\`, keyed by folder name. Do not rename or move a Site folder:\n` +
|
|
339
|
+
`rename the Site (\`ez config set name\` or the Studio) and \`ez pull --all\` renames its folder.\n` +
|
|
340
|
+
`Work inside a Site's folder: \`cd sites/<site> && ez status|pull|push|deploy|dev\` -- the folder knows its Site. From here,\n` +
|
|
341
|
+
`\`ez clone\` pulls every Site you may open and \`ez pull --all\` refreshes them (folders with unpushed changes are\n` +
|
|
342
|
+
`skipped); \`ez site ls\` lists the Sites. Never \`ez push\` from this folder; push from a Site's folder.\n\n` +
|
|
343
|
+
`## Working here\n\n` +
|
|
344
|
+
`Read \`ez help\` before anything else: its instructions are how to build here, the same ones the Studio's agent\n` +
|
|
345
|
+
`follows; \`ez help <topic>\` adds the detail a piece needs and \`ez help recipes\` has complete examples. The Working Copies are files on disk: read and edit them with your own file tools (\`ez cat\`, \`ez put\`\n` +
|
|
346
|
+
`and \`ez edit\` are for shells without them), keeping \`sites/<site>/CONTEXT.md\` and \`global/CONTEXT.md\` current.\n` +
|
|
347
|
+
`\`ez dev\` in a Site's folder keeps that Site's Preview rebuilt as files change; \`ez check\` and \`ez preview\` report\n` +
|
|
348
|
+
`diagnostics. When you cannot open a Preview yourself, rely on them and give the user \`ez link --preview\`.\n`;
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Marks `dir` as the Instance folder of `instance`: .ez/instance.json plus an AGENTS.md (left alone if present).
|
|
352
|
+
* @param {string} dir @param {string} instance @param {Connection} connection
|
|
353
|
+
*/
|
|
354
|
+
async function markInstanceFolder(dir, instance, connection) {
|
|
355
|
+
await mkdir(join(dir, ".ez"), { recursive: true });
|
|
356
|
+
await writeFile(
|
|
357
|
+
join(dir, ".ez", "instance.json"),
|
|
358
|
+
JSON.stringify(
|
|
359
|
+
{
|
|
360
|
+
instance,
|
|
361
|
+
uid: connection.uid,
|
|
362
|
+
app: connection.app,
|
|
363
|
+
builder: connection.builder,
|
|
364
|
+
email: connection.email,
|
|
365
|
+
},
|
|
366
|
+
null,
|
|
367
|
+
2,
|
|
368
|
+
) + "\n",
|
|
369
|
+
);
|
|
370
|
+
try {
|
|
371
|
+
await readFile(join(dir, "AGENTS.md"), "utf8");
|
|
372
|
+
} catch {
|
|
373
|
+
await writeFile(join(dir, "AGENTS.md"), instanceAgentsMd(instance));
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* `ez clone [<instance>]` / `ez pull --all`: every Site the Builder may open, each pulled into
|
|
379
|
+
* <dir>/sites/<folder>/, and the Global Workspace into <dir>/global/ (ADR 0079). Folders with unpushed changes
|
|
380
|
+
* are skipped and reported. A Site folder directly in <dir>, from before sites/, is moved into it, and a folder
|
|
381
|
+
* whose Site was renamed moves to the new name; their bindings live in <dir>/.ez/ (ADR 0085).
|
|
382
|
+
* @param {Connection} creds @param {string[]} args @param {string} dir
|
|
383
|
+
*/
|
|
384
|
+
async function cloneInstance(creds, args, dir) {
|
|
385
|
+
const instances = /** @type {InstanceSummary[]} */ (
|
|
386
|
+
await request(creds, "GET", "/api/instances")
|
|
387
|
+
);
|
|
388
|
+
const marker = await boundTarget(dir);
|
|
389
|
+
if (marker?.site)
|
|
390
|
+
throw new Error(
|
|
391
|
+
`This folder is the working copy of ${marker.instance}/${marker.site}; run ez clone in a folder for the whole Instance.`,
|
|
392
|
+
);
|
|
393
|
+
const instance = creds.instance;
|
|
394
|
+
const mine = instances.find((i) => i.id === instance);
|
|
395
|
+
if (!mine) throw new Error(`You are not a builder of "${instance}". Run \`ez sites\`.`);
|
|
396
|
+
const sitesDir = join(dir, SITES_FOLDER);
|
|
397
|
+
const occupant = await boundTarget(sitesDir);
|
|
398
|
+
if (occupant?.site)
|
|
399
|
+
throw new Error(
|
|
400
|
+
`${sitesDir} is the working copy of ${occupant.instance}/${occupant.site}, but Site folders now live inside sites/. Rename that folder, then run this again.`,
|
|
401
|
+
);
|
|
402
|
+
await markInstanceFolder(dir, instance, creds);
|
|
403
|
+
// Bindings live in this folder's .ez/, keyed by folder name (ADR 0085): bring older ones in, and drop the
|
|
404
|
+
// ones whose folder is gone, so a new folder of that name never inherits another Site's baseline.
|
|
405
|
+
const siteFolders = (await readdir(sitesDir, { withFileTypes: true }).catch(() => []))
|
|
406
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
407
|
+
.map((entry) => entry.name);
|
|
408
|
+
for (const name of siteFolders) await adoptBinding(join(sitesDir, name));
|
|
409
|
+
await adoptBinding(join(dir, GLOBAL_ID));
|
|
410
|
+
const bindings = join(dir, ".ez", SITES_FOLDER);
|
|
411
|
+
for (const file of await readdir(bindings).catch(() => []))
|
|
412
|
+
if (file.endsWith(".json") && !siteFolders.includes(file.slice(0, -".json".length)))
|
|
413
|
+
await unlink(join(bindings, file));
|
|
414
|
+
if (!(await stat(join(dir, GLOBAL_ID)).catch(() => null)))
|
|
415
|
+
await unlink(join(dir, ".ez", "global.json")).catch(() => {});
|
|
416
|
+
/** @param {string} folder */
|
|
417
|
+
const bindingOf = async (folder) => {
|
|
418
|
+
const b = await readBinding(folder);
|
|
419
|
+
return b?.uid && b?.site ? `${b.uid}\0${b.site}` : null;
|
|
420
|
+
};
|
|
421
|
+
// Existing folders, keyed by what they are bound to (docs/adr/0034).
|
|
422
|
+
/** @type {Map<string,string>} */
|
|
423
|
+
const boundDirs = new Map();
|
|
424
|
+
const unbound = [];
|
|
425
|
+
const taken = new Set();
|
|
426
|
+
for (const entry of await readdir(sitesDir, { withFileTypes: true }).catch(() => [])) {
|
|
427
|
+
if (entry.name.startsWith(".")) continue;
|
|
428
|
+
taken.add(entry.name);
|
|
429
|
+
const key = entry.isDirectory() ? await bindingOf(join(sitesDir, entry.name)) : null;
|
|
430
|
+
if (key) boundDirs.set(key, entry.name);
|
|
431
|
+
else if (entry.isDirectory()) unbound.push(entry.name);
|
|
432
|
+
}
|
|
433
|
+
// Site folders from before sites/ sit beside global/; each one moves in.
|
|
434
|
+
/** @type {Map<string,string>} */
|
|
435
|
+
const legacyDirs = new Map();
|
|
436
|
+
for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
|
437
|
+
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
438
|
+
if (entry.name === GLOBAL_ID || entry.name === SITES_FOLDER) continue;
|
|
439
|
+
const key = await bindingOf(join(dir, entry.name));
|
|
440
|
+
if (key && !boundDirs.has(key)) legacyDirs.set(key, entry.name);
|
|
441
|
+
}
|
|
442
|
+
/** @param {string} base */
|
|
443
|
+
const claim = (base) => {
|
|
444
|
+
let candidate = base;
|
|
445
|
+
for (let n = 2; taken.has(candidate); n++) candidate = `${base}-${n}`;
|
|
446
|
+
taken.add(candidate);
|
|
447
|
+
return candidate;
|
|
448
|
+
};
|
|
449
|
+
/** Whether a folder already carries a Site's name: its slug, or the slug with a collision suffix. @param {string} folder @param {string} slug */
|
|
450
|
+
const named = (folder, slug) =>
|
|
451
|
+
folder === slug ||
|
|
452
|
+
(folder.startsWith(`${slug}-`) && /^\d+$/.test(folder.slice(slug.length + 1)));
|
|
453
|
+
// A folder is named for its Site, not its ID; collisions take -2, -3, and so on. Folders follow Site
|
|
454
|
+
// renames (ADR 0085): a bound folder whose Site was renamed moves to the new name.
|
|
455
|
+
/** @param {InstanceSummary["sites"][number]} site @returns {{name: string, from?: string}} */
|
|
456
|
+
const folderFor = (site) => {
|
|
457
|
+
const key = `${creds.uid}\0${site.id}`;
|
|
458
|
+
const slug = siteFolderName(site.name ?? site.id);
|
|
459
|
+
const known = boundDirs.get(key);
|
|
460
|
+
if (known)
|
|
461
|
+
return named(known, slug)
|
|
462
|
+
? { name: known }
|
|
463
|
+
: { name: claim(slug), from: `${SITES_FOLDER}/${known}` };
|
|
464
|
+
const legacy = legacyDirs.get(key);
|
|
465
|
+
if (legacy) return { name: claim(named(legacy, slug) ? legacy : slug), from: legacy };
|
|
466
|
+
return { name: claim(slug) };
|
|
467
|
+
};
|
|
468
|
+
const lines = [];
|
|
469
|
+
for (const s of mine.sites) {
|
|
470
|
+
const { name, from } = folderFor(s);
|
|
471
|
+
const folder = `${SITES_FOLDER}/${name}`;
|
|
472
|
+
const sub = join(sitesDir, name);
|
|
473
|
+
if (from) {
|
|
474
|
+
await moveWorkingCopy(join(dir, from), sub);
|
|
475
|
+
lines.push(`${folder}/ moved from ${from}/`);
|
|
476
|
+
}
|
|
477
|
+
const ws = diskWorkspace(creds, instance, s.id, sub);
|
|
478
|
+
const [files, pulled] = await Promise.all([ws.files(), ws.pulled()]);
|
|
479
|
+
if (pulled) assertFolder(creds, pulled);
|
|
480
|
+
if (pulled && countChanges(localChanges(files, pulled)) > 0) {
|
|
481
|
+
await ensureEditor(sub, join(dir, GLOBAL_ID));
|
|
482
|
+
lines.push(
|
|
483
|
+
`${folder}/ skipped: ${countChanges(localChanges(files, pulled))} unpushed change(s)`,
|
|
484
|
+
);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
await mkdir(sub, { recursive: true });
|
|
488
|
+
lines.push(`${folder}/ ${await runCommand(ws, ["pull"])}`);
|
|
489
|
+
}
|
|
490
|
+
// A folder renamed by hand lost its binding; its files stay where they are.
|
|
491
|
+
for (const name of unbound)
|
|
492
|
+
lines.push(
|
|
493
|
+
`${SITES_FOLDER}/${name}/ left alone: not a Working Copy (folders follow Site names; rename the Site instead)`,
|
|
494
|
+
);
|
|
495
|
+
if (mine.sites.length === 0) lines.push("(no sites you may open yet)");
|
|
496
|
+
// Every Builder needs the Global Workspace's schema and generated types beside sites/.
|
|
497
|
+
{
|
|
498
|
+
const sub = join(dir, GLOBAL_ID);
|
|
499
|
+
const ws = diskWorkspace(creds, instance, GLOBAL_ID, sub);
|
|
500
|
+
const [files, pulled] = await Promise.all([ws.files(), ws.pulled()]);
|
|
501
|
+
if (pulled) assertFolder(creds, pulled);
|
|
502
|
+
if (pulled && countChanges(localChanges(files, pulled)) > 0) {
|
|
503
|
+
await ensureEditor(sub, sub);
|
|
504
|
+
lines.push(`${GLOBAL_ID}/ skipped: unpushed change(s)`);
|
|
505
|
+
} else if (!pulled && Object.keys(files).length > 0)
|
|
506
|
+
lines.push(`${GLOBAL_ID}/ skipped: folder has files but is not a working copy`);
|
|
507
|
+
else {
|
|
508
|
+
await mkdir(sub, { recursive: true });
|
|
509
|
+
lines.push(`${GLOBAL_ID}/ ${await runCommand(ws, ["pull"])}`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return `${instance} -> ${dir}\n${lines.join("\n")}`;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* The Instance and, when `needSite`, the Site to act on: --site / EZ_SITE / `ez use` (an "<instance>/<site>"
|
|
517
|
+
* or a bare "<site>"), --instance for Instance-only commands, else implied when the Builder is in exactly one.
|
|
518
|
+
* Fails with the list when it is ambiguous. `boundSite` keeps a Site folder's Site for an Instance command
|
|
519
|
+
* that only mentions it (`ez support open`, docs/adr/0080).
|
|
520
|
+
* @param {Connection} creds @param {string[]} args @param {{needSite: boolean, boundSite?: boolean, dir?: string}} options
|
|
521
|
+
*/
|
|
522
|
+
async function resolveTarget(creds, args, { needSite, boundSite, dir }) {
|
|
523
|
+
const selected = extractTarget(args);
|
|
524
|
+
const text = selected.site || process.env.EZ_SITE;
|
|
525
|
+
const parsed = text ? parseTarget(text) : null;
|
|
526
|
+
if (text && (!parsed || (parsed.instance && parsed.instance !== creds.instance)))
|
|
527
|
+
throw new Error("The Site target does not belong to this Instance connection.");
|
|
528
|
+
const bound = dir ? await boundTarget(dir) : null;
|
|
529
|
+
const matches = bound?.uid === creds.uid && bound?.app === creds.app;
|
|
530
|
+
const site = parsed?.site || (matches ? bound.site : null) || creds.site || null;
|
|
531
|
+
if (!needSite)
|
|
532
|
+
return {
|
|
533
|
+
instance: creds.instance,
|
|
534
|
+
site: parsed?.site || (boundSite && matches ? bound.site : null) || null,
|
|
535
|
+
};
|
|
536
|
+
if (site) return { instance: creds.instance, site };
|
|
537
|
+
const mine = /** @type {InstanceSummary[]} */ (
|
|
538
|
+
await request(creds, "GET", "/api/instances")
|
|
539
|
+
).find((i) => i.id === creds.instance);
|
|
540
|
+
if (!mine) throw new Error(`You no longer have access to ${creds.instance}.`);
|
|
541
|
+
if (mine.sites.length === 1) return { instance: creds.instance, site: mine.sites[0].id };
|
|
542
|
+
throw new Error(
|
|
543
|
+
`Choose a Site in ${creds.instance} with --site or ez use:\n` +
|
|
544
|
+
mine.sites.map((s) => ` ${s.id} (${s.name})`).join("\n"),
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* A password or a secret, never an argument: piped (scripts, CI), the whole of stdin, like `ez-host
|
|
550
|
+
* create-developer`; in a terminal, a prompt that does not echo.
|
|
551
|
+
* @param {string} [label] @returns {Promise<string>}
|
|
552
|
+
*/
|
|
553
|
+
async function askPassword(label = "password") {
|
|
554
|
+
if (!process.stdin.isTTY) {
|
|
555
|
+
const input = ((await readStdin()) ?? "").replace(/\r?\n$/, "");
|
|
556
|
+
if (!input) throw new Error(`No ${label} on stdin.`);
|
|
557
|
+
return input;
|
|
558
|
+
}
|
|
559
|
+
process.stdout.write(`${label}: `);
|
|
560
|
+
process.stdin.setRawMode(true);
|
|
561
|
+
process.stdin.resume();
|
|
562
|
+
return new Promise((resolve, reject) => {
|
|
563
|
+
let value = "";
|
|
564
|
+
/** @param {Error} [error] */
|
|
565
|
+
const done = (error) => {
|
|
566
|
+
process.stdin.setRawMode(false);
|
|
567
|
+
process.stdin.pause();
|
|
568
|
+
process.stdin.off("data", onData);
|
|
569
|
+
process.stdout.write("\n");
|
|
570
|
+
if (error) reject(error);
|
|
571
|
+
else resolve(value);
|
|
572
|
+
};
|
|
573
|
+
/** @param {Buffer} chunk */
|
|
574
|
+
const onData = (chunk) => {
|
|
575
|
+
for (const c of chunk.toString()) {
|
|
576
|
+
if (c === "\u0003") return done(new Error("Cancelled."));
|
|
577
|
+
if (c === "\r" || c === "\n") return done();
|
|
578
|
+
if (c === "\u007f" || c === "\b") value = value.slice(0, -1);
|
|
579
|
+
else if (c >= " ") value += c;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
process.stdin.on("data", onData);
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** @param {string} question */
|
|
587
|
+
async function ask(question) {
|
|
588
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
589
|
+
try {
|
|
590
|
+
return await rl.question(question);
|
|
591
|
+
} finally {
|
|
592
|
+
rl.close();
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// ---- login ------------------------------------------------------------------------------------------------
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Sign in with an emailed code, mint a token (session-only endpoint), drop the session. No browser needed.
|
|
600
|
+
* @param {string[]} args
|
|
601
|
+
*/
|
|
602
|
+
async function login(args) {
|
|
603
|
+
if (flag(args, "--api"))
|
|
604
|
+
throw new Error("Use ez login <Instance URL>; --api is reserved for operator tooling.");
|
|
605
|
+
const descriptor = await discoverInstance(
|
|
606
|
+
positionals(args)[0] || process.env.EZ_INSTANCE || "",
|
|
607
|
+
localFetch,
|
|
608
|
+
);
|
|
609
|
+
const api = descriptor.api;
|
|
610
|
+
if (args.includes("--browser") && args.includes("--password"))
|
|
611
|
+
throw new Error("Choose --browser or --password.");
|
|
612
|
+
if (args.includes("--browser")) return loginWithBrowser(descriptor);
|
|
613
|
+
if (args.includes("--password")) {
|
|
614
|
+
if (!process.stdin.isTTY && !flag(args, "--username"))
|
|
615
|
+
throw new Error("A password on stdin needs --username.");
|
|
616
|
+
const username = (flag(args, "--username") ?? (await ask("username: "))).trim().toLowerCase();
|
|
617
|
+
const password = await askPassword();
|
|
618
|
+
const { token } = await passwordLogin(api, username, password, hostname(), localFetch);
|
|
619
|
+
await saveLogin(descriptor, token);
|
|
620
|
+
console.log(`Connected to ${descriptor.instance} as ${username}. Token saved to ${CRED_FILE}`);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const email = (flag(args, "--email") ?? (await ask("email: "))).trim().toLowerCase();
|
|
624
|
+
if (!email)
|
|
625
|
+
throw new Error(
|
|
626
|
+
"Usage: ez login <instance or URL> [--email you@example.com] [--browser]\nAn email address is required.",
|
|
627
|
+
);
|
|
628
|
+
const headers = { "content-type": "application/json", origin: api };
|
|
629
|
+
/** @param {string} path @param {unknown} body @param {Record<string,string>} [extra] */
|
|
630
|
+
const post = (path, body, extra = {}) =>
|
|
631
|
+
localFetch(api + path, {
|
|
632
|
+
method: "POST",
|
|
633
|
+
redirect: "error",
|
|
634
|
+
credentials: "omit",
|
|
635
|
+
headers: { ...headers, ...extra },
|
|
636
|
+
body: JSON.stringify(body),
|
|
637
|
+
});
|
|
638
|
+
/** @param {Response} res @param {string} what @returns {Promise<never>} */
|
|
639
|
+
const fail = async (res, what) => {
|
|
640
|
+
const text = await res.text();
|
|
641
|
+
let msg = text;
|
|
642
|
+
try {
|
|
643
|
+
msg = JSON.parse(text).message ?? JSON.parse(text).error ?? text;
|
|
644
|
+
} catch {}
|
|
645
|
+
const id = res.headers.get("x-request-id");
|
|
646
|
+
throw new Error(`${what}: ${res.status} ${msg}${id ? ` (request ${id})` : ""}`);
|
|
647
|
+
};
|
|
648
|
+
const sent = await post("/auth/email-otp/send-verification-otp", { email, type: "sign-in" });
|
|
649
|
+
if (!sent.ok) await fail(sent, "Could not request a code");
|
|
650
|
+
console.log(`If ${email} is a builder, a 6-digit code is on its way.`);
|
|
651
|
+
const otp = (await ask("code: ")).trim();
|
|
652
|
+
const signedIn = await post("/auth/sign-in/email-otp", { email, otp });
|
|
653
|
+
if (!signedIn.ok) await fail(signedIn, "Sign-in failed");
|
|
654
|
+
const cookie = signedIn.headers
|
|
655
|
+
.getSetCookie()
|
|
656
|
+
.map((c) => c.split(";")[0])
|
|
657
|
+
.join("; ");
|
|
658
|
+
const minted = await post("/api/tokens", { name: hostname() }, { cookie });
|
|
659
|
+
if (!minted.ok) await fail(minted, "Could not create a token");
|
|
660
|
+
const { token } = await minted.json();
|
|
661
|
+
await post("/auth/sign-out", {}, { cookie }).catch(() => {});
|
|
662
|
+
// A new login forgets the remembered target: it may belong to the previous account.
|
|
663
|
+
await saveLogin(descriptor, token);
|
|
664
|
+
console.log(`Connected to ${descriptor.instance} as ${email}. Token saved to ${CRED_FILE}`);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* The device flow: approve on /cli/activate on the platform while signed in there.
|
|
669
|
+
* @param {InstanceDiscovery} descriptor
|
|
670
|
+
*/
|
|
671
|
+
async function loginWithBrowser(descriptor) {
|
|
672
|
+
const { api } = descriptor;
|
|
673
|
+
const creds = { ...descriptor, token: undefined };
|
|
674
|
+
const start = await request(creds, "POST", "/cli/device");
|
|
675
|
+
console.log(
|
|
676
|
+
`\nOpen this URL and enter the code to authorize this machine:\n\n ${start.verificationUrl}\n\n code: ${start.userCode}\n`,
|
|
677
|
+
);
|
|
678
|
+
if (new URL(start.verificationUrl).origin !== api)
|
|
679
|
+
throw new Error("The approval page belongs to another origin.");
|
|
680
|
+
openBrowser(start.verificationUrl);
|
|
681
|
+
process.stdout.write("Waiting for approval");
|
|
682
|
+
while (Date.now() < start.expiresAt) {
|
|
683
|
+
await sleep((start.interval ?? 3) * 1000);
|
|
684
|
+
const r = await request(creds, "POST", "/cli/device/token", { deviceCode: start.deviceCode });
|
|
685
|
+
if (r.status === "approved") {
|
|
686
|
+
const me = await saveLogin(descriptor, r.token);
|
|
687
|
+
console.log(
|
|
688
|
+
`\nConnected to ${descriptor.instance} as ${me.email}. Token saved to ${CRED_FILE}`,
|
|
689
|
+
);
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (r.status === "expired") break;
|
|
693
|
+
process.stdout.write(".");
|
|
694
|
+
}
|
|
695
|
+
throw new Error("\nThe code expired before it was approved. Run `ez login` again.");
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** @param {string[]} args */
|
|
699
|
+
async function logout(args) {
|
|
700
|
+
const saved = await readCredFile();
|
|
701
|
+
if (args.includes("--all")) {
|
|
702
|
+
await writeCredFile(emptyConnections());
|
|
703
|
+
return console.log(
|
|
704
|
+
"Disconnected all saved Instance accounts. Tokens can be revoked separately.",
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
if (!Object.keys(saved.logins).length) return console.log("No saved Instance connections.");
|
|
708
|
+
const { instance, account } = extractTarget(args);
|
|
709
|
+
const connection = findConnection(saved, instance || positionals(args)[0], account);
|
|
710
|
+
await writeCredFile(forgetConnection(saved, connection));
|
|
711
|
+
console.log(`Disconnected ${connection.instance} (${connection.email}).`);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** @param {Connection} connection @param {string[]} args @param {string} dir */
|
|
715
|
+
async function adoptFolder(connection, args, dir) {
|
|
716
|
+
const bound = await boundTarget(dir);
|
|
717
|
+
if (!bound || bound.uid) throw new Error("This folder is not a legacy Working Copy.");
|
|
718
|
+
if (!flag(args, "--instance"))
|
|
719
|
+
throw new Error("Adoption requires an explicit --instance target.");
|
|
720
|
+
if (
|
|
721
|
+
flag(args, "--from-instance") !== bound.instance ||
|
|
722
|
+
(bound.api && flag(args, "--from-api") !== bound.api)
|
|
723
|
+
)
|
|
724
|
+
throw new Error(
|
|
725
|
+
`Verify the source with --from-instance ${bound.instance}` +
|
|
726
|
+
(bound.api ? ` --from-api ${bound.api}` : "") +
|
|
727
|
+
". No files have changed.",
|
|
728
|
+
);
|
|
729
|
+
const target = bound.site || null;
|
|
730
|
+
if (target)
|
|
731
|
+
await request(connection, "GET", `/api/i/${connection.instance}/s/${target}/workspace`);
|
|
732
|
+
else await request(connection, "GET", `/api/i/${connection.instance}`);
|
|
733
|
+
const file = target
|
|
734
|
+
? /** @type {string} */ (await bindingFile(dir))
|
|
735
|
+
: join(dir, ".ez", "instance.json");
|
|
736
|
+
await writeFile(file + ".legacy", await readFile(file), { flag: "wx" });
|
|
737
|
+
await writeFile(
|
|
738
|
+
file,
|
|
739
|
+
JSON.stringify(
|
|
740
|
+
{
|
|
741
|
+
...bound,
|
|
742
|
+
instance: connection.instance,
|
|
743
|
+
uid: connection.uid,
|
|
744
|
+
app: connection.app,
|
|
745
|
+
api: connection.api,
|
|
746
|
+
builder: connection.builder,
|
|
747
|
+
email: connection.email,
|
|
748
|
+
},
|
|
749
|
+
null,
|
|
750
|
+
2,
|
|
751
|
+
) + "\n",
|
|
752
|
+
);
|
|
753
|
+
console.log(
|
|
754
|
+
`Bound this folder to ${connection.instance} (${connection.email}); unpushed files retained.`,
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// ---- the working copy on disk + the Instance's and Site's HTTP API, as the contract's Workspace -----------
|
|
759
|
+
|
|
760
|
+
/** @param {string} dir @param {string} [base] @returns {Promise<string[]>} */
|
|
761
|
+
async function walk(dir, base = dir) {
|
|
762
|
+
/** @type {string[]} */
|
|
763
|
+
const out = [];
|
|
764
|
+
let entries;
|
|
765
|
+
try {
|
|
766
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
767
|
+
} catch {
|
|
768
|
+
return out;
|
|
769
|
+
}
|
|
770
|
+
for (const entry of entries) {
|
|
771
|
+
if (entry.name.startsWith(".") || SKIP_DIRS.has(entry.name)) continue;
|
|
772
|
+
if (dir === base && entry.name === "tsconfig.json") continue;
|
|
773
|
+
const full = join(dir, entry.name);
|
|
774
|
+
if (entry.isDirectory()) out.push(...(await walk(full, base)));
|
|
775
|
+
else if (entry.isFile()) out.push(relative(base, full).split(sep).join("/"));
|
|
776
|
+
}
|
|
777
|
+
return out;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** @param {Connection} creds @param {string} instance @param {string | null} site @param {string} dir @param {string} [globalDir] @returns {DiskWorkspace} */
|
|
781
|
+
function diskWorkspace(creds, instance, site, dir, globalDir) {
|
|
782
|
+
/** @param {string} p */
|
|
783
|
+
// Paths come from the server on pull: never let one leave the folder or reach .ez/ or .git/.
|
|
784
|
+
const local = (p) => {
|
|
785
|
+
const parts = p.split("/");
|
|
786
|
+
if (parts.some((s) => !s || s.startsWith(".") || /[\\:\0]/.test(s)))
|
|
787
|
+
throw new Error(`Refusing a file path outside the Working Copy: ${JSON.stringify(p)}`);
|
|
788
|
+
return join(dir, ...parts);
|
|
789
|
+
};
|
|
790
|
+
return {
|
|
791
|
+
// the API, from the contract's route table, over the bearer token
|
|
792
|
+
...httpWorkspace((method, path, body) => request(creds, method, path, body), {
|
|
793
|
+
instance,
|
|
794
|
+
site,
|
|
795
|
+
}),
|
|
796
|
+
// which target this is (the contract treats <instance>/global as the Global Workspace)
|
|
797
|
+
target: { instance, site },
|
|
798
|
+
async globalWorkspace() {
|
|
799
|
+
const folder =
|
|
800
|
+
site === GLOBAL_ID
|
|
801
|
+
? dir
|
|
802
|
+
: globalDir
|
|
803
|
+
? resolve(globalDir)
|
|
804
|
+
: join(instanceFolderOf(dir), GLOBAL_ID);
|
|
805
|
+
const global = diskWorkspace(creds, instance, GLOBAL_ID, folder);
|
|
806
|
+
const meta = await global.pulled();
|
|
807
|
+
if (
|
|
808
|
+
meta &&
|
|
809
|
+
(meta.instance !== instance ||
|
|
810
|
+
meta.site !== GLOBAL_ID ||
|
|
811
|
+
meta.uid !== creds.uid ||
|
|
812
|
+
meta.app !== creds.app ||
|
|
813
|
+
(meta.builder && meta.builder !== creds.builder))
|
|
814
|
+
)
|
|
815
|
+
throw new Error("Global Working Copy belongs to a different target.");
|
|
816
|
+
return global;
|
|
817
|
+
},
|
|
818
|
+
// `ez asset add`: the file on disk, and its bytes to the platform's ticket URL over the bearer token
|
|
819
|
+
async fileInfo(source) {
|
|
820
|
+
const file = resolve(source);
|
|
821
|
+
const info = await stat(file).catch(() => null);
|
|
822
|
+
if (!info?.isFile()) throw new Error(`No such file: ${source}`);
|
|
823
|
+
return { size: info.size, contentType: assetContentType(file), filename: basename(file) };
|
|
824
|
+
},
|
|
825
|
+
async sendFile(upload, source) {
|
|
826
|
+
const destination = new URL(upload.url);
|
|
827
|
+
if (destination.origin !== creds.api)
|
|
828
|
+
throw new Error("Upload belongs to another Instance API.");
|
|
829
|
+
const res = await connectionRequest(
|
|
830
|
+
creds,
|
|
831
|
+
destination.pathname + destination.search,
|
|
832
|
+
{
|
|
833
|
+
method: upload.method,
|
|
834
|
+
headers: upload.headers,
|
|
835
|
+
body: await readFile(resolve(source)),
|
|
836
|
+
},
|
|
837
|
+
localFetch,
|
|
838
|
+
);
|
|
839
|
+
if (!res.ok) {
|
|
840
|
+
const text = await res.text().catch(() => "");
|
|
841
|
+
let msg = text;
|
|
842
|
+
try {
|
|
843
|
+
msg = JSON.parse(text).error ?? text;
|
|
844
|
+
} catch {}
|
|
845
|
+
throw new Error(`Upload failed: ${res.status} ${msg}`);
|
|
846
|
+
}
|
|
847
|
+
},
|
|
848
|
+
// `ez db attachment --out`: the bytes from the platform's download URL over the bearer token, to disk
|
|
849
|
+
async receiveFile(download, destination) {
|
|
850
|
+
const source = new URL(download);
|
|
851
|
+
if (source.origin !== creds.api) throw new Error("Download belongs to another Instance API.");
|
|
852
|
+
const res = await connectionRequest(
|
|
853
|
+
creds,
|
|
854
|
+
source.pathname + source.search,
|
|
855
|
+
{ method: "GET" },
|
|
856
|
+
localFetch,
|
|
857
|
+
);
|
|
858
|
+
if (!res.ok) {
|
|
859
|
+
const text = await res.text().catch(() => "");
|
|
860
|
+
let msg = text;
|
|
861
|
+
try {
|
|
862
|
+
msg = JSON.parse(text).error ?? text;
|
|
863
|
+
} catch {}
|
|
864
|
+
throw new Error(`Download failed: ${res.status} ${msg}`);
|
|
865
|
+
}
|
|
866
|
+
await writeFile(resolve(destination), new Uint8Array(await res.arrayBuffer()));
|
|
867
|
+
},
|
|
868
|
+
// the working copy on disk
|
|
869
|
+
async files() {
|
|
870
|
+
/** @type {Record<string, string>} */
|
|
871
|
+
const out = {};
|
|
872
|
+
for (const p of await walk(dir)) out[p] = await readFile(local(p), "utf8");
|
|
873
|
+
return out;
|
|
874
|
+
},
|
|
875
|
+
async write(p, content) {
|
|
876
|
+
await mkdir(dirname(local(p)), { recursive: true });
|
|
877
|
+
await writeFile(local(p), content);
|
|
878
|
+
},
|
|
879
|
+
async remove(p) {
|
|
880
|
+
await unlink(local(p)).catch(() => {});
|
|
881
|
+
},
|
|
882
|
+
async pulled() {
|
|
883
|
+
return readBinding(dir);
|
|
884
|
+
},
|
|
885
|
+
async setPulled(p) {
|
|
886
|
+
await writeBinding(dir, {
|
|
887
|
+
...p,
|
|
888
|
+
api: creds.api,
|
|
889
|
+
instance,
|
|
890
|
+
site,
|
|
891
|
+
uid: creds.uid,
|
|
892
|
+
app: creds.app,
|
|
893
|
+
builder: creds.builder,
|
|
894
|
+
email: creds.email,
|
|
895
|
+
});
|
|
896
|
+
await ensureEditor(
|
|
897
|
+
dir,
|
|
898
|
+
site === GLOBAL_ID
|
|
899
|
+
? dir
|
|
900
|
+
: globalDir
|
|
901
|
+
? resolve(globalDir)
|
|
902
|
+
: join(instanceFolderOf(dir), GLOBAL_ID),
|
|
903
|
+
);
|
|
904
|
+
},
|
|
905
|
+
// the default Preview name: this folder's (a worktree per feature is a Preview per feature; docs/adr/0013)
|
|
906
|
+
async globalFiles() {
|
|
907
|
+
if (site === GLOBAL_ID) return undefined;
|
|
908
|
+
const folder = globalDir ? resolve(globalDir) : join(instanceFolderOf(dir), GLOBAL_ID);
|
|
909
|
+
const meta = await readBinding(folder);
|
|
910
|
+
if (!meta) {
|
|
911
|
+
if (globalDir) throw new Error("--global-dir must be a pulled Global Working Copy.");
|
|
912
|
+
return undefined;
|
|
913
|
+
}
|
|
914
|
+
if (
|
|
915
|
+
meta.instance !== instance ||
|
|
916
|
+
meta.site !== GLOBAL_ID ||
|
|
917
|
+
meta.uid !== creds.uid ||
|
|
918
|
+
meta.app !== creds.app ||
|
|
919
|
+
(meta.builder && meta.builder !== creds.builder)
|
|
920
|
+
)
|
|
921
|
+
throw new Error("Global Working Copy belongs to a different target.");
|
|
922
|
+
return diskWorkspace(creds, instance, GLOBAL_ID, folder).files();
|
|
923
|
+
},
|
|
924
|
+
async previewName() {
|
|
925
|
+
return previewNameFrom(basename(resolve(dir)));
|
|
926
|
+
},
|
|
927
|
+
editorExports,
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
async function readStdin() {
|
|
932
|
+
if (process.stdin.isTTY) return undefined;
|
|
933
|
+
const chunks = [];
|
|
934
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
935
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// ---- ez dev: a watcher over `ez preview` (docs/adr/0013) --------------------------------------------------
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* `ez dev [--name <preview>]`: `ez preview` once, then again after every change in this folder (debounced; a
|
|
942
|
+
* change during an upload queues one more). Nothing runs here but the watcher: the build and the app are on
|
|
943
|
+
* the Host. The Preview page reloads itself after successful builds (docs/adr/0017).
|
|
944
|
+
* @param {Connection} creds @param {string[]} args @param {string} dir
|
|
945
|
+
*/
|
|
946
|
+
async function dev(creds, args, dir) {
|
|
947
|
+
const { instance, site } = await resolveTarget(creds, args, { needSite: true, dir });
|
|
948
|
+
await assertSiteFolder(dir, site);
|
|
949
|
+
if (site === GLOBAL_ID)
|
|
950
|
+
throw new Error(
|
|
951
|
+
"ez dev runs in a Site's folder; the Global Workspace is compiled into each Site it serves.",
|
|
952
|
+
);
|
|
953
|
+
const ws = diskWorkspace(creds, instance, site, dir, flag(args, "--global-dir"));
|
|
954
|
+
if (!(await ws.pulled()))
|
|
955
|
+
throw new Error(
|
|
956
|
+
`This folder is not a working copy of ${instance}/${site} yet: run \`ez pull\` first.`,
|
|
957
|
+
);
|
|
958
|
+
const explicitGlobal = flag(args, "--global-dir");
|
|
959
|
+
const globalFolder = explicitGlobal
|
|
960
|
+
? resolve(explicitGlobal)
|
|
961
|
+
: join(instanceFolderOf(dir), GLOBAL_ID);
|
|
962
|
+
await ensureEditor(dir, globalFolder);
|
|
963
|
+
const argv = ["preview"];
|
|
964
|
+
const name = flag(args, "--name");
|
|
965
|
+
if (name) argv.push("--name", name);
|
|
966
|
+
const stamp = () => new Date().toLocaleTimeString();
|
|
967
|
+
const upload = async () => {
|
|
968
|
+
try {
|
|
969
|
+
console.log(`${stamp()} ${await runCommand(ws, argv)}`);
|
|
970
|
+
} catch (e) {
|
|
971
|
+
console.error(`${stamp()} ${e instanceof Error ? e.message : String(e)}`);
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
await upload();
|
|
975
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
976
|
+
let timer;
|
|
977
|
+
let running = false;
|
|
978
|
+
let dirty = false;
|
|
979
|
+
const flush = async () => {
|
|
980
|
+
if (running) {
|
|
981
|
+
dirty = true;
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
running = true;
|
|
985
|
+
do {
|
|
986
|
+
dirty = false;
|
|
987
|
+
await upload();
|
|
988
|
+
} while (dirty);
|
|
989
|
+
running = false;
|
|
990
|
+
};
|
|
991
|
+
const kick = () => {
|
|
992
|
+
clearTimeout(timer);
|
|
993
|
+
timer = setTimeout(() => void flush(), 300);
|
|
994
|
+
};
|
|
995
|
+
// A watcher that fails (its folder removed, the system out of watches) ends ez dev with that error.
|
|
996
|
+
/** @type {(error: Error) => void} */
|
|
997
|
+
let stop = () => {};
|
|
998
|
+
const stopped = new Promise((_, reject) => {
|
|
999
|
+
stop = reject;
|
|
1000
|
+
});
|
|
1001
|
+
watch(dir, { recursive: true }, (_, file) => {
|
|
1002
|
+
if (file === "tsconfig.json") return;
|
|
1003
|
+
if (typeof file === "string" && file.split(sep).some((s) => SKIP_DIRS.has(s))) return;
|
|
1004
|
+
kick();
|
|
1005
|
+
}).on("error", stop);
|
|
1006
|
+
if (globalFolder !== resolve(dir) && (await stat(globalFolder).catch(() => null))?.isDirectory())
|
|
1007
|
+
watch(globalFolder, { recursive: true }, (_, file) => {
|
|
1008
|
+
if (file === "tsconfig.json") return;
|
|
1009
|
+
if (typeof file === "string" && file.split(sep).some((s) => SKIP_DIRS.has(s))) return;
|
|
1010
|
+
kick();
|
|
1011
|
+
}).on("error", stop);
|
|
1012
|
+
console.log(`Watching ${dir} for changes; Ctrl-C stops.`);
|
|
1013
|
+
await stopped;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* Commands that act on an Instance alone; everything else in the contract needs a Site too.
|
|
1018
|
+
* @param {string} cmd @param {string[]} args
|
|
1019
|
+
*/
|
|
1020
|
+
function needsSite(cmd, args) {
|
|
1021
|
+
if (cmd === "site" && args[0] === "access") return true;
|
|
1022
|
+
if (cmd === "audit" || cmd === "db" || cmd === "support" || cmd === "email") return false;
|
|
1023
|
+
return !["instance", "builders", "builder", "users", "user", "site", "help", "asset"].includes(
|
|
1024
|
+
cmd,
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
async function main() {
|
|
1029
|
+
const [cmd, ...args] = process.argv.slice(2);
|
|
1030
|
+
if (cmd === "signup") {
|
|
1031
|
+
if (
|
|
1032
|
+
args.some((arg, index) => index % 2 === 0 && !["--email", "--name"].includes(arg)) ||
|
|
1033
|
+
args.length % 2
|
|
1034
|
+
)
|
|
1035
|
+
throw new Error("Usage: ez signup [--email <email>] [--name <display name>]");
|
|
1036
|
+
const { signupClient } = await import("./signup.mjs");
|
|
1037
|
+
const client = signupClient(localFetch);
|
|
1038
|
+
const email = flag(args, "--email") || (await ask("Email: "));
|
|
1039
|
+
const name = flag(args, "--name") || (await ask("Team or organization name: "));
|
|
1040
|
+
const challenge = await client.start({ email, name, source: "cli" });
|
|
1041
|
+
const result = await client.complete(
|
|
1042
|
+
challenge.receipt,
|
|
1043
|
+
await ask("Code from the verification email: "),
|
|
1044
|
+
);
|
|
1045
|
+
await saveLogin(result.connection, result.token);
|
|
1046
|
+
console.log(
|
|
1047
|
+
`Your private trial is ready, and this CLI is signed in to it.\n` +
|
|
1048
|
+
` Studio: ${result.studio} (the email's "Open my Studio" button signs you in there)\n` +
|
|
1049
|
+
` Apps: ${result.connection.app}\n` +
|
|
1050
|
+
`Next: ez site create "My first app"`,
|
|
1051
|
+
);
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
if (cmd === "login") return login(args);
|
|
1055
|
+
if (cmd === "logout") return logout(args);
|
|
1056
|
+
if (cmd === "logins") {
|
|
1057
|
+
const saved = await readCredFile();
|
|
1058
|
+
const rows = Object.entries(saved.logins).map(([key, c]) => ({
|
|
1059
|
+
instance: c.instance,
|
|
1060
|
+
address: c.app,
|
|
1061
|
+
account: c.email,
|
|
1062
|
+
primary: key === saved.primary,
|
|
1063
|
+
}));
|
|
1064
|
+
return console.log(
|
|
1065
|
+
args.includes("--json")
|
|
1066
|
+
? JSON.stringify(rows, null, 2)
|
|
1067
|
+
: rows
|
|
1068
|
+
.map((r) => `${r.primary ? "*" : " "} ${r.instance} ${r.account} ${r.address}`)
|
|
1069
|
+
.join("\n") || "No saved Instance connections. Run ez login <instance or URL>.",
|
|
1070
|
+
);
|
|
1071
|
+
}
|
|
1072
|
+
if (cmd === "switch") {
|
|
1073
|
+
const target = positionals(args)[0];
|
|
1074
|
+
if (!target) throw new Error("Usage: ez switch <instance or URL> [--account email]");
|
|
1075
|
+
const saved = makePrimary(await readCredFile(), target, flag(args, "--account"));
|
|
1076
|
+
await writeCredFile(saved);
|
|
1077
|
+
const current = findConnection(saved);
|
|
1078
|
+
return console.log(`Primary Instance: ${current.instance} (${current.email}).`);
|
|
1079
|
+
}
|
|
1080
|
+
if (cmd === "help" || !cmd || cmd === "--help") {
|
|
1081
|
+
// The connection lines open the top-level help only; a topic (`ez help rules`) is just the topic.
|
|
1082
|
+
if (!args.length)
|
|
1083
|
+
console.log(
|
|
1084
|
+
"Trial signup: ez signup [--email <email>] [--name <display name>] creates a private trial on the demo Host after email verification.\nConnections: ez login <instance or URL>; ez logins; ez switch <instance>; --instance targets one command; --account selects a saved account.\nWorking Copies stay bound to their Instance. ez adopt --instance <target> --from-instance <old-id> [--from-api <old-api>] preserves legacy files.\nAccount: ez account; ez tokens; ez token revoke <id>; ez logout [--instance <id>|--all].",
|
|
1085
|
+
);
|
|
1086
|
+
// Help does not read any Workspace methods.
|
|
1087
|
+
return console.log(await runCommand(/** @type {Workspace} */ ({}), ["help", ...args]));
|
|
1088
|
+
}
|
|
1089
|
+
const dir = resolve(flag(args, "--dir") || process.env.EZ_DIR || ".");
|
|
1090
|
+
const creds = await loadCreds(args, dir, cmd);
|
|
1091
|
+
if (cmd === "adopt") return adoptFolder(creds, args, dir);
|
|
1092
|
+
if (cmd === "account") {
|
|
1093
|
+
if (!creds.api) throw new Error("Connect to an Instance with ez login first.");
|
|
1094
|
+
const url = creds.api + (args.includes("--password") ? "/password-setup" : "/account");
|
|
1095
|
+
console.log(url);
|
|
1096
|
+
openBrowser(url);
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
const positional = positionals(args);
|
|
1100
|
+
if (ACCOUNT_COMMANDS.includes(cmd)) {
|
|
1101
|
+
console.log(
|
|
1102
|
+
await runAccountCommand(
|
|
1103
|
+
(method, path, body) => request(creds, method, path, body),
|
|
1104
|
+
extractTarget([cmd, ...args]).args,
|
|
1105
|
+
),
|
|
1106
|
+
);
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// Commands that need no Site.
|
|
1111
|
+
switch (cmd) {
|
|
1112
|
+
case "whoami":
|
|
1113
|
+
return console.log(JSON.stringify(await request(creds, "GET", "/api/me")));
|
|
1114
|
+
case "sites": {
|
|
1115
|
+
const targets = await listTargets(creds);
|
|
1116
|
+
if (targets.length === 0) return console.log("You don't belong to any instance yet.");
|
|
1117
|
+
return console.log(targets.map((t) => targetLine(t, creds.site)).join("\n"));
|
|
1118
|
+
}
|
|
1119
|
+
case "use": {
|
|
1120
|
+
const arg = positional[0];
|
|
1121
|
+
if (!arg || !parseTarget(arg))
|
|
1122
|
+
throw new Error("Usage: ez use <site> [--instance <instance>]");
|
|
1123
|
+
const { instance, site } = await resolveTarget(creds, ["--site", arg], { needSite: true });
|
|
1124
|
+
const targets = await listTargets(creds);
|
|
1125
|
+
if (!site || !targets.some((t) => t.instance === instance && t.id === site))
|
|
1126
|
+
throw new Error(`You may not open "${instance}/${site}". Run \`ez sites\`.`);
|
|
1127
|
+
await writeCredFile(saveConnection(await readCredFile(), { ...creds, site }));
|
|
1128
|
+
return console.log(`Using ${instance}/${site}.`);
|
|
1129
|
+
}
|
|
1130
|
+
case "instance":
|
|
1131
|
+
// Creating and archiving Instances is developer-only and lives in scripts/instance.mjs, not here.
|
|
1132
|
+
if (["create", "archive", "rm"].includes(positional[0]))
|
|
1133
|
+
throw new Error(
|
|
1134
|
+
"Creating and archiving instances is developer-only: bun scripts/instance.mjs create|archive ...",
|
|
1135
|
+
);
|
|
1136
|
+
break;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
if (cmd === "clone") return console.log(await cloneInstance(creds, args, dir));
|
|
1140
|
+
if (cmd === "pull" && args.includes("--all"))
|
|
1141
|
+
return console.log(
|
|
1142
|
+
await cloneInstance(
|
|
1143
|
+
creds,
|
|
1144
|
+
args.filter((a) => a !== "--all"),
|
|
1145
|
+
dir,
|
|
1146
|
+
),
|
|
1147
|
+
);
|
|
1148
|
+
|
|
1149
|
+
if (cmd === "init") {
|
|
1150
|
+
// An Instance folder: global/ and sites/<folder>/ are its Working Copies. Never inside one of them (its files get pushed).
|
|
1151
|
+
const bound = await boundTarget(dir);
|
|
1152
|
+
if (bound?.site)
|
|
1153
|
+
throw new Error(
|
|
1154
|
+
`This folder is the working copy of ${bound.instance}/${bound.site}; run ez init one level up.`,
|
|
1155
|
+
);
|
|
1156
|
+
const { instance } = await resolveTarget(creds, args, { needSite: false, dir });
|
|
1157
|
+
await mkdir(dir, { recursive: true });
|
|
1158
|
+
await markInstanceFolder(dir, instance, creds);
|
|
1159
|
+
return console.log(
|
|
1160
|
+
`${dir} is the folder for instance ${instance} (AGENTS.md written). Next: ez clone, or ez pull inside a Site's folder.`,
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
if (cmd === "dev") return dev(creds, args, dir);
|
|
1165
|
+
|
|
1166
|
+
if (cmd === "audit") {
|
|
1167
|
+
// --site here is a filter within the Instance, not the target: resolve the Instance without it, then
|
|
1168
|
+
// hand the filters to the contract. Cross-instance read is out -- one Instance per call.
|
|
1169
|
+
const filterNames = new Set(["--site", "--kind", "--limit", "--before"]);
|
|
1170
|
+
const targetArgs = [];
|
|
1171
|
+
const filterArgv = [];
|
|
1172
|
+
for (let i = 0; i < args.length; i++) {
|
|
1173
|
+
if (filterNames.has(args[i])) {
|
|
1174
|
+
filterArgv.push(args[i]);
|
|
1175
|
+
if (i + 1 < args.length && !args[i + 1].startsWith("--")) filterArgv.push(args[++i]);
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1178
|
+
targetArgs.push(args[i]);
|
|
1179
|
+
}
|
|
1180
|
+
const target = await resolveTarget(creds, targetArgs, { needSite: false, dir });
|
|
1181
|
+
const ws = diskWorkspace(creds, target.instance, target.site, dir, flag(args, "--global-dir"));
|
|
1182
|
+
if (args.includes("--json")) filterArgv.push("--json");
|
|
1183
|
+
const out = await runCommand(ws, ["audit", ...filterArgv]);
|
|
1184
|
+
if (out) process.stdout.write(out.endsWith("\n") ? out : out + "\n");
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
if (!COMMAND_NAMES.includes(cmd)) {
|
|
1189
|
+
console.log(
|
|
1190
|
+
"Usage: ez login|logout|logins|switch|adopt|whoami|sites|use|clone|init|dev|instance|site or ez help|status|pull|push|deploy|versions|check|preview|ls|cat|put|edit|delete|mv|config|builders|builder|users|user|audit|db|support|email",
|
|
1191
|
+
);
|
|
1192
|
+
process.exitCode = 1;
|
|
1193
|
+
return;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
const target = await resolveTarget(creds, args, {
|
|
1197
|
+
needSite: needsSite(cmd, args),
|
|
1198
|
+
boundSite: cmd === "support",
|
|
1199
|
+
dir,
|
|
1200
|
+
});
|
|
1201
|
+
if (usesWorkingCopy([cmd, ...args])) await assertSiteFolder(dir, target.site);
|
|
1202
|
+
if (cmd === "global") await assertGlobalHome(dir, target.site, flag(args, "--global-dir"));
|
|
1203
|
+
const ws = diskWorkspace(creds, target.instance, target.site, dir, flag(args, "--global-dir"));
|
|
1204
|
+
let argv = contractArgs([cmd, ...args]);
|
|
1205
|
+
const scopedCommand = cmd === "global" ? args[0] : cmd;
|
|
1206
|
+
if (scopedCommand === "pull" || scopedCommand === "preview") {
|
|
1207
|
+
// contractArgs strips --version and --name with the other value flags; these need them back.
|
|
1208
|
+
const v = flag(args, "--version");
|
|
1209
|
+
if (v !== undefined) argv.push("--version", v);
|
|
1210
|
+
const n = flag(args, "--name");
|
|
1211
|
+
if (scopedCommand === "preview" && n !== undefined) argv.push("--name", n);
|
|
1212
|
+
}
|
|
1213
|
+
let stdin;
|
|
1214
|
+
if (scopedCommand === "put") {
|
|
1215
|
+
// `ez put <path> [file]`: a file argument becomes the content; otherwise the content comes from stdin.
|
|
1216
|
+
const [path, file] = cmd === "global" ? positional.slice(1) : positional;
|
|
1217
|
+
stdin = file ? await readFile(file, "utf8") : await readStdin();
|
|
1218
|
+
argv = [
|
|
1219
|
+
...(cmd === "global" ? ["global"] : []),
|
|
1220
|
+
"put",
|
|
1221
|
+
...(path ? [path] : []),
|
|
1222
|
+
...(args.includes("--json") ? ["--json"] : []),
|
|
1223
|
+
];
|
|
1224
|
+
} else if (cmd === "db" && args[0] === "sql" && positional.length === 1) {
|
|
1225
|
+
// `ez db sql` with no statement argument reads it from stdin (a file of SQL, or a heredoc).
|
|
1226
|
+
stdin = await readStdin();
|
|
1227
|
+
} else if (
|
|
1228
|
+
cmd === "integration" &&
|
|
1229
|
+
(args[0] === "set" || args[0] === "preview") &&
|
|
1230
|
+
(args.includes("--header") || args.includes("--query"))
|
|
1231
|
+
) {
|
|
1232
|
+
// docs/adr/0092: a credential's value is typed at a hidden prompt or piped, never an argument.
|
|
1233
|
+
stdin = await askPassword("credential value");
|
|
1234
|
+
} else if (
|
|
1235
|
+
cmd === "integration" &&
|
|
1236
|
+
(args[0] === "set" || args[0] === "preview") &&
|
|
1237
|
+
args.includes("--basic")
|
|
1238
|
+
) {
|
|
1239
|
+
// docs/adr/0138: a basic credential's password, the same way.
|
|
1240
|
+
stdin = await askPassword("password");
|
|
1241
|
+
} else if (
|
|
1242
|
+
cmd === "integration" &&
|
|
1243
|
+
(args[0] === "set" || args[0] === "preview") &&
|
|
1244
|
+
(args.includes("--oauth") || args.includes("--preset"))
|
|
1245
|
+
) {
|
|
1246
|
+
// docs/adr/0140: the client secret, then a password grant's password: two lines piped, or two prompts.
|
|
1247
|
+
const grant = flag(args, "--oauth");
|
|
1248
|
+
stdin = process.stdin.isTTY
|
|
1249
|
+
? [
|
|
1250
|
+
await askPassword("client secret"),
|
|
1251
|
+
...(grant === "password" ? [await askPassword("password")] : []),
|
|
1252
|
+
].join("\n")
|
|
1253
|
+
: ((await readStdin()) ?? "");
|
|
1254
|
+
} else if (cmd === "integration" && args[0] === "value" && args.includes("--secret")) {
|
|
1255
|
+
// docs/adr/0138: a secret value, the same way as a credential's.
|
|
1256
|
+
stdin = await askPassword("secret value");
|
|
1257
|
+
} else if (cmd === "listener" && args[0] === "secret" && !args.includes("--remove")) {
|
|
1258
|
+
// docs/adr/0092: a Listener's secret, the same way.
|
|
1259
|
+
stdin = await askPassword("listener secret");
|
|
1260
|
+
} else if (cmd === "support" && args[0] === "open" && !args.includes("--body")) {
|
|
1261
|
+
// `ez support open <subject>` takes its body from a pipe when --body is not given.
|
|
1262
|
+
stdin = await readStdin();
|
|
1263
|
+
}
|
|
1264
|
+
const out = await runCommand(ws, argv, stdin);
|
|
1265
|
+
if (out) process.stdout.write(out.endsWith("\n") ? out : out + "\n");
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* Whether a newer `ez` is on npm (docs/adr/0111), asked alongside the command and told after it, on standard
|
|
1270
|
+
* error. `ez dev` never ends, so it is not asked. Never fails or fails a command.
|
|
1271
|
+
*/
|
|
1272
|
+
async function updateCheck() {
|
|
1273
|
+
if (process.argv[2] === "dev") return null;
|
|
1274
|
+
try {
|
|
1275
|
+
const pkg = JSON.parse(await readFile(new URL("./package.json", import.meta.url), "utf8"));
|
|
1276
|
+
return await checkForUpdate({
|
|
1277
|
+
current: pkg.version,
|
|
1278
|
+
name: installedAs(process.argv[1]),
|
|
1279
|
+
file: join(CRED_DIR, "update-check.json"),
|
|
1280
|
+
env: process.env,
|
|
1281
|
+
fetch: globalThis.fetch,
|
|
1282
|
+
});
|
|
1283
|
+
} catch {
|
|
1284
|
+
return null;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
const update = updateCheck();
|
|
1288
|
+
|
|
1289
|
+
// Neither step rejects: the command's own failure is reported here, and the update check never throws.
|
|
1290
|
+
void main()
|
|
1291
|
+
.catch((e) => {
|
|
1292
|
+
// `ez check --json` fails with its problems as JSON: that belongs on standard output, like any --json result.
|
|
1293
|
+
if (e instanceof CommandFailure && process.argv.includes("--json"))
|
|
1294
|
+
process.stdout.write(e.message.endsWith("\n") ? e.message : e.message + "\n");
|
|
1295
|
+
else console.error(e.message ?? e);
|
|
1296
|
+
process.exitCode = 1;
|
|
1297
|
+
})
|
|
1298
|
+
.then(async () => {
|
|
1299
|
+
const notice = await update;
|
|
1300
|
+
if (notice) console.error(notice);
|
|
1301
|
+
});
|