ezship 0.1.10 → 0.1.12

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/account.d.mts ADDED
@@ -0,0 +1,19 @@
1
+ import type { Send } from "./commands.d.mts";
2
+ export function requestEmailCode(api: string, email: string, send?: typeof fetch): Promise<void>;
3
+ export function emailLogin(
4
+ api: string,
5
+ email: string,
6
+ otp: string,
7
+ name: string,
8
+ send?: typeof fetch,
9
+ ): Promise<{ token: string }>;
10
+ export const ACCOUNT_OPERATIONS: readonly string[];
11
+ export const ACCOUNT_COMMANDS: readonly string[];
12
+ export function runAccountCommand(send: Send, argv: string[]): Promise<string>;
13
+ export function passwordLogin(
14
+ api: string,
15
+ username: string,
16
+ password: string,
17
+ name: string,
18
+ send?: typeof fetch,
19
+ ): Promise<{ token: string }>;
package/account.mjs ADDED
@@ -0,0 +1,91 @@
1
+ // Host account operations are outside the Instance route table (ADRs 0009 and 0015).
2
+ /** @type {typeof import("./account.d.mts").ACCOUNT_OPERATIONS} */
3
+ export const ACCOUNT_OPERATIONS = Object.freeze([
4
+ "identity",
5
+ "instances",
6
+ "otp",
7
+ "password",
8
+ "device",
9
+ "password-change",
10
+ "tokens",
11
+ "token-revoke",
12
+ "logout",
13
+ ]);
14
+ /** @type {typeof import("./account.d.mts").ACCOUNT_COMMANDS} */
15
+ export const ACCOUNT_COMMANDS = Object.freeze(["tokens", "token"]);
16
+ /** @type {typeof import("./account.d.mts").runAccountCommand} */
17
+ export async function runAccountCommand(send, argv) {
18
+ const words = argv.filter((a) => a !== "--json");
19
+ let data;
20
+ if (words[0] === "tokens" && words.length === 1) data = await send("GET", "/api/tokens");
21
+ else if (
22
+ words[0] === "token" &&
23
+ (words[1] === "revoke" || words[1] === "rm") &&
24
+ words[2] &&
25
+ words.length === 3
26
+ )
27
+ data = await send("DELETE", "/api/tokens/" + encodeURIComponent(words[2]));
28
+ else throw new Error("Usage: ez tokens [--json] | ez token revoke <id> [--json]");
29
+ if (argv.includes("--json")) return JSON.stringify(data);
30
+ return words[0] === "tokens"
31
+ ? /** @type {import("./types.d.mts").TokenRow[]} */ (data)
32
+ .map(
33
+ (t) => `${t.id} ${t.name} ${t.prefix}… expires ${new Date(t.expiresAt).toISOString()}`,
34
+ )
35
+ .join("\n") || "No active tokens."
36
+ : "Token revoked.";
37
+ }
38
+
39
+ /**
40
+ * Sign in directly, mint a token with that session, then discard the temporary session.
41
+ * @type {typeof import("./account.d.mts").passwordLogin}
42
+ */
43
+ export async function passwordLogin(api, username, password, name, send = fetch) {
44
+ return sessionLogin(api, "/auth/sign-in/username", { username, password }, name, send);
45
+ }
46
+
47
+ /** @type {typeof import('./account.d.mts').requestEmailCode} */
48
+ export async function requestEmailCode(api, email, send = fetch) {
49
+ const response = await send(api + "/auth/email-otp/send-verification-otp", {
50
+ method: "POST",
51
+ redirect: "error",
52
+ headers: { "content-type": "application/json", origin: api },
53
+ body: JSON.stringify({ email, type: "sign-in" }),
54
+ });
55
+ if (!response.ok) throw new Error("Could not request a sign-in code.");
56
+ }
57
+
58
+ /** @type {typeof import('./account.d.mts').emailLogin} */
59
+ export async function emailLogin(api, email, otp, name, send = fetch) {
60
+ return sessionLogin(api, "/auth/sign-in/email-otp", { email, otp }, name, send);
61
+ }
62
+
63
+ /** @param {string} api @param {string} path @param {unknown} input @param {string} name @param {typeof fetch} send */
64
+ async function sessionLogin(api, path, input, name, send) {
65
+ /** @param {string} path @param {unknown} body @param {string} [cookie] */
66
+ const post = (path, body, cookie) =>
67
+ send(api + path, {
68
+ method: "POST",
69
+ redirect: "manual",
70
+ headers: { "content-type": "application/json", origin: api, ...(cookie ? { cookie } : {}) },
71
+ body: JSON.stringify(body),
72
+ });
73
+ /** @param {Response} res */
74
+ const read = async (res) => {
75
+ const data = await res.json();
76
+ if (!res.ok) throw new Error(data.message || data.error || `HTTP ${res.status}`);
77
+ return data;
78
+ };
79
+ const signed = await post(path, input);
80
+ await read(signed);
81
+ const cookie = signed.headers
82
+ .getSetCookie()
83
+ .map((c) => c.split(";")[0])
84
+ .join("; ");
85
+ if (!cookie) throw new Error("Sign-in did not return a session.");
86
+ try {
87
+ return await read(await post("/api/tokens", { name }, cookie));
88
+ } finally {
89
+ await post("/auth/sign-out", {}, cookie).catch(() => {});
90
+ }
91
+ }
package/bindings.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // Where a Working Copy's binding lives (ADR 0085). In an Instance folder the folder holds no `.ez/`: the
2
+ // Instance folder's `.ez/` keeps `sites/<folder>.json` per Site folder and `global.json`, keyed by folder name.
3
+ // A standalone Working Copy (a worktree, a Site pulled anywhere else) keeps its own `.ez/pulled.json`.
4
+ import { mkdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { GLOBAL_ID, SITES_FOLDER } from "./commands.mjs";
7
+
8
+ /**
9
+ * The Instance folder a Working Copy belongs in: `<root>/sites/<folder>` for a Site and `<root>/global` for the
10
+ * Global Workspace (ADR 0079). A Site folder directly in its Instance folder predates `sites/` and still counts.
11
+ * @param {string} dir
12
+ */
13
+ export function instanceFolderOf(dir) {
14
+ const parent = dirname(resolve(dir));
15
+ return basename(parent) === SITES_FOLDER ? dirname(parent) : parent;
16
+ }
17
+
18
+ /** @param {string} path */
19
+ async function readJson(path) {
20
+ try {
21
+ return JSON.parse(await readFile(path, "utf8"));
22
+ } catch (error) {
23
+ if (error instanceof SyntaxError) return null;
24
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
25
+ throw error;
26
+ }
27
+ }
28
+
29
+ /** @param {string} dir */
30
+ const ownFile = (dir) => join(resolve(dir), ".ez", "pulled.json");
31
+
32
+ /**
33
+ * The Instance folder's file for `dir`, when `dir` is in a place an Instance folder owns: `sites/<folder>/` or
34
+ * `global/`. Whether that Instance folder exists is the caller's question.
35
+ * @param {string} dir @returns {{root: string, file: string} | null}
36
+ */
37
+ function sharedFile(dir) {
38
+ dir = resolve(dir);
39
+ const parent = dirname(dir);
40
+ if (basename(parent) === SITES_FOLDER)
41
+ return {
42
+ root: dirname(parent),
43
+ file: join(dirname(parent), ".ez", SITES_FOLDER, `${basename(dir)}.json`),
44
+ };
45
+ if (basename(dir) === GLOBAL_ID)
46
+ return { root: parent, file: join(parent, ".ez", "global.json") };
47
+ return null;
48
+ }
49
+
50
+ /**
51
+ * The Instance folder's binding (`.ez/instance.json`), or null.
52
+ * @param {string} root
53
+ */
54
+ export const instanceBinding = (root) => readJson(join(root, ".ez", "instance.json"));
55
+
56
+ /**
57
+ * Whether a Working Copy binding belongs to the Instance folder's Instance.
58
+ * @param {{uid?: string, app?: string, instance?: string} | null} instance
59
+ * @param {{uid?: string, app?: string, instance?: string} | null} workingCopy
60
+ */
61
+ export const sameInstance = (instance, workingCopy) =>
62
+ Boolean(
63
+ instance?.uid &&
64
+ instance.app &&
65
+ workingCopy?.uid === instance.uid &&
66
+ workingCopy.app === instance.app &&
67
+ workingCopy.instance === instance.instance,
68
+ );
69
+
70
+ /**
71
+ * The file that holds `dir`'s binding now: the Instance folder's, else the folder's own; null when neither exists.
72
+ * @param {string} dir @returns {Promise<string | null>}
73
+ */
74
+ export async function bindingFile(dir) {
75
+ for (const file of [sharedFile(dir)?.file, ownFile(dir)])
76
+ if (file && (await readJson(file)) !== null) return file;
77
+ return null;
78
+ }
79
+
80
+ /**
81
+ * A Working Copy's binding and pulled baseline, or null when `dir` is not one.
82
+ * @param {string} dir
83
+ */
84
+ export async function readBinding(dir) {
85
+ const file = await bindingFile(dir);
86
+ return file ? readJson(file) : null;
87
+ }
88
+
89
+ /**
90
+ * Writes `dir`'s binding: into the Instance folder's `.ez/` when `dir` is one of its Working Copies and the binding
91
+ * is for its Instance, removing the folder's own copy; into the folder's own `.ez/` otherwise.
92
+ * @param {string} dir @param {Record<string, unknown> & {uid?: string, app?: string, instance?: string}} binding
93
+ */
94
+ export async function writeBinding(dir, binding) {
95
+ const shared = sharedFile(dir);
96
+ const home =
97
+ shared && sameInstance(await instanceBinding(shared.root), binding)
98
+ ? shared.file
99
+ : ownFile(dir);
100
+ await mkdir(dirname(home), { recursive: true });
101
+ await writeFile(home, JSON.stringify(binding, null, 2) + "\n");
102
+ if (home !== ownFile(dir)) await removeOwn(dir);
103
+ }
104
+
105
+ /** @param {string} dir */
106
+ async function removeOwn(dir) {
107
+ await unlink(ownFile(dir)).catch(() => {});
108
+ // Only an empty `.ez/` goes; a standalone editor project kept under it stays (ADR 0038).
109
+ await rmdir(dirname(ownFile(dir))).catch(() => {});
110
+ }
111
+
112
+ /**
113
+ * Moves a folder's own binding into its Instance folder, unchanged, when that is where it belongs.
114
+ * @param {string} dir
115
+ */
116
+ export async function adoptBinding(dir) {
117
+ const own = await readJson(ownFile(dir));
118
+ const shared = sharedFile(dir);
119
+ if (!own || !shared || (await readJson(shared.file)) !== null) return;
120
+ if (sameInstance(await instanceBinding(shared.root), own)) await writeBinding(dir, own);
121
+ }
122
+
123
+ /**
124
+ * Renames a Working Copy folder inside its Instance folder and carries its binding along.
125
+ * @param {string} from @param {string} to
126
+ */
127
+ export async function moveWorkingCopy(from, to) {
128
+ const file = await bindingFile(from);
129
+ const binding = file ? await readJson(file) : null;
130
+ await mkdir(dirname(to), { recursive: true });
131
+ await rename(from, to);
132
+ if (file === ownFile(from)) return adoptBinding(to);
133
+ if (!file) return;
134
+ await unlink(file);
135
+ await writeBinding(to, binding);
136
+ }