@venturewild/workspace 0.3.8 → 0.4.1

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.
@@ -0,0 +1,295 @@
1
+ // Workspace registry — the per-install list of LOCAL workspaces (lobby M1).
2
+ //
3
+ // One install can hold many workspaces; this is the list the lobby shows and
4
+ // switches between. Stored in the GLOBAL dir (~/.wild-workspace/workspaces.json),
5
+ // NEVER inside a synced workspace folder (core principle #1: the user's repo
6
+ // folder is sacred — no system state in it).
7
+ //
8
+ // Each entry points at a folder on THIS host. The server re-roots to the chosen
9
+ // workspace per request via the X-Workspace-Id seam (see index.mjs `workspaceFor`).
10
+ // Creating/opening a workspace is a HOST action (the folder lives here); a remote
11
+ // browser only ENTERS existing ones — enforced at the route, not here.
12
+ //
13
+ // A workspace is `kind:'local'` until the owner explicitly SHARES it (sharing
14
+ // slice / design §4 decision 7): `markShared` promotes the entry to `kind:'shared'`
15
+ // and records a `shared:{slug,ownerEmail,role,sharedAt}` block — the slug is the
16
+ // workspace's first-class identity on the bmo-sync rails (membership/canvas), minted
17
+ // by `POST /api/workspaces/create`. The folder stays exactly where it is; promoting
18
+ // is a metadata flip on the LIST, never a move. `removeWorkspace` drops a folder
19
+ // from the LIST only — it never deletes files.
20
+
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import os from 'node:os';
24
+ import crypto from 'node:crypto';
25
+ import { globalDir } from './logpaths.mjs';
26
+
27
+ const FILE = 'workspaces.json';
28
+
29
+ function registryPath(env = process.env) {
30
+ return path.join(globalDir(env), FILE);
31
+ }
32
+
33
+ // Where "New workspace" (name-only, no path) creates folders — a visible home so
34
+ // the user always knows where their data lives (design §8.1). Overridable for tests.
35
+ function workspacesHome(env = process.env) {
36
+ return env.WILD_WORKSPACE_HOME || path.join(os.homedir(), 'Workspaces');
37
+ }
38
+
39
+ // A stable id derived from the absolute dir, so re-adding the same folder is
40
+ // idempotent and the id survives a display-name rename. Case-folded on win/mac
41
+ // (case-insensitive filesystems) so one folder maps to exactly one id. Exported
42
+ // so the server can compute the boot/default workspace's id WITHOUT writing the
43
+ // registry file (keeps startup side-effect-free + test-pollution-free).
44
+ export function workspaceIdForDir(dir) {
45
+ const abs = path.resolve(dir);
46
+ const key = process.platform === 'linux' ? abs : abs.toLowerCase();
47
+ return 'ws_' + crypto.createHash('sha256').update(key).digest('hex').slice(0, 12);
48
+ }
49
+ const idForDir = workspaceIdForDir;
50
+
51
+ function nameForDir(dir) {
52
+ return path.basename(path.resolve(dir)) || 'workspace';
53
+ }
54
+
55
+ // folder-name-safe slug of a display name (for the New-workspace folder).
56
+ function folderSlug(name) {
57
+ const s = String(name || '')
58
+ .trim()
59
+ .toLowerCase()
60
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
61
+ .replace(/^-+|-+$/g, '')
62
+ .slice(0, 60);
63
+ return s || 'workspace';
64
+ }
65
+
66
+ function readRaw(env) {
67
+ try {
68
+ const parsed = JSON.parse(fs.readFileSync(registryPath(env), 'utf8'));
69
+ if (Array.isArray(parsed?.workspaces)) {
70
+ return parsed.workspaces.map(sanitize).filter(Boolean);
71
+ }
72
+ } catch {
73
+ /* missing / unreadable / malformed → empty */
74
+ }
75
+ return [];
76
+ }
77
+
78
+ // A shared workspace carries a `shared` block (the rails identity + the local
79
+ // member's role). Only kept when the entry is actually `kind:'shared'` AND the
80
+ // block has a slug; anything else collapses back to a plain local entry so a
81
+ // half-written record can't masquerade as shared.
82
+ function sanitizeShared(s) {
83
+ if (!s || typeof s !== 'object' || typeof s.slug !== 'string' || !s.slug.trim()) return null;
84
+ const out = {
85
+ slug: s.slug.trim().toLowerCase(),
86
+ ownerEmail: typeof s.ownerEmail === 'string' ? s.ownerEmail : '',
87
+ role: s.role === 'owner' ? 'owner' : 'member',
88
+ sharedAt: Number(s.sharedAt) || 0,
89
+ };
90
+ // Slice 3: the file-sync project this workspace replicates through, recorded
91
+ // once the daemon is paired ("going live"). Absent until file-sync starts.
92
+ if (typeof s.projectCode === 'string' && s.projectCode.trim()) {
93
+ out.projectCode = s.projectCode.trim();
94
+ }
95
+ return out;
96
+ }
97
+
98
+ function sanitize(e) {
99
+ if (!e || typeof e !== 'object' || typeof e.dir !== 'string' || !e.dir) return null;
100
+ const dir = path.resolve(e.dir);
101
+ const shared = sanitizeShared(e.shared);
102
+ const out = {
103
+ id: typeof e.id === 'string' && e.id ? e.id : idForDir(dir),
104
+ name: typeof e.name === 'string' && e.name.trim() ? e.name.trim() : nameForDir(dir),
105
+ dir,
106
+ kind: e.kind === 'shared' && shared ? 'shared' : 'local',
107
+ createdAt: Number(e.createdAt) || nowMs(),
108
+ lastOpenedAt: Number(e.lastOpenedAt) || 0,
109
+ };
110
+ if (out.kind === 'shared') out.shared = shared;
111
+ return out;
112
+ }
113
+
114
+ function writeRaw(list, env) {
115
+ const dir = globalDir(env);
116
+ fs.mkdirSync(dir, { recursive: true });
117
+ const tmp = `${registryPath(env)}.tmp`;
118
+ fs.writeFileSync(tmp, JSON.stringify({ workspaces: list }, null, 2), { mode: 0o600 });
119
+ fs.renameSync(tmp, registryPath(env)); // atomic-ish replace
120
+ }
121
+
122
+ function nowMs() {
123
+ return Date.now();
124
+ }
125
+
126
+ // Recency ordering (listWorkspaces) needs strictly-increasing open stamps. Two
127
+ // opens in the same millisecond — easy on a fast machine or CI — would otherwise
128
+ // tie on lastOpenedAt and fall back to the createdAt tiebreak, which does NOT
129
+ // reflect open-order, so the just-touched workspace could fail to sort to the
130
+ // front. Clamp every new open stamp strictly above every existing stamp so the
131
+ // order is deterministic regardless of clock resolution.
132
+ function nextOpenStamp(list) {
133
+ let max = 0;
134
+ for (const w of list) {
135
+ if (w.lastOpenedAt > max) max = w.lastOpenedAt;
136
+ if (w.createdAt > max) max = w.createdAt;
137
+ }
138
+ return Math.max(nowMs(), max + 1);
139
+ }
140
+
141
+ // --- public API ------------------------------------------------------------
142
+
143
+ /** All workspaces, most-recently-opened first (then newest-created). */
144
+ export function listWorkspaces(env = process.env) {
145
+ return readRaw(env).sort(
146
+ (a, b) => b.lastOpenedAt - a.lastOpenedAt || b.createdAt - a.createdAt,
147
+ );
148
+ }
149
+
150
+ /** One workspace by id, or null. */
151
+ export function getWorkspace(id, env = process.env) {
152
+ return readRaw(env).find((w) => w.id === id) || null;
153
+ }
154
+
155
+ /** Find a registered workspace by its directory (idempotency helper), or null. */
156
+ export function findByDir(dir, env = process.env) {
157
+ const want = idForDir(dir);
158
+ return readRaw(env).find((w) => w.id === want) || null;
159
+ }
160
+
161
+ /**
162
+ * Ensure `dir` exists in the registry (idempotent) — used at startup to seed the
163
+ * boot/default workspace so the lobby is never blank for an existing install.
164
+ * Does NOT touch lastOpenedAt. Returns the entry.
165
+ */
166
+ export function seedDefault({ dir, name } = {}, env = process.env) {
167
+ if (!dir) return null;
168
+ const list = readRaw(env);
169
+ const existing = list.find((w) => w.id === idForDir(dir));
170
+ if (existing) return existing;
171
+ const entry = sanitize({
172
+ dir,
173
+ name: name || nameForDir(dir),
174
+ createdAt: nowMs(),
175
+ lastOpenedAt: nowMs(), // the boot workspace is "the one you were just in"
176
+ });
177
+ list.push(entry);
178
+ writeRaw(list, env);
179
+ return entry;
180
+ }
181
+
182
+ /**
183
+ * Create a NEW local workspace. With `dir` → register that existing folder
184
+ * ("Open an existing folder"). With only `name` → make a fresh folder under the
185
+ * Workspaces home ("New workspace"); collisions get a -2/-3 suffix. Idempotent on
186
+ * an already-registered dir (returns it, touched). HOST-only is enforced at the route.
187
+ */
188
+ export function createWorkspace({ name, dir } = {}, env = process.env) {
189
+ let targetDir;
190
+ let isNew = false;
191
+
192
+ if (dir) {
193
+ targetDir = path.resolve(dir);
194
+ if (!fs.existsSync(targetDir)) {
195
+ throw new Error(`folder does not exist: ${targetDir}`);
196
+ }
197
+ if (!fs.statSync(targetDir).isDirectory()) {
198
+ throw new Error(`not a folder: ${targetDir}`);
199
+ }
200
+ } else {
201
+ const home = workspacesHome(env);
202
+ fs.mkdirSync(home, { recursive: true });
203
+ const base = folderSlug(name);
204
+ let candidate = path.join(home, base);
205
+ let n = 2;
206
+ while (fs.existsSync(candidate)) {
207
+ candidate = path.join(home, `${base}-${n}`);
208
+ n += 1;
209
+ }
210
+ fs.mkdirSync(candidate, { recursive: true });
211
+ targetDir = candidate;
212
+ isNew = true;
213
+ }
214
+
215
+ const list = readRaw(env);
216
+ const id = idForDir(targetDir);
217
+ const existing = list.find((w) => w.id === id);
218
+ if (existing) {
219
+ existing.lastOpenedAt = nextOpenStamp(list);
220
+ if (name && isNew) existing.name = name;
221
+ writeRaw(list, env);
222
+ return existing;
223
+ }
224
+ const entry = sanitize({
225
+ dir: targetDir,
226
+ name: name || nameForDir(targetDir),
227
+ createdAt: nowMs(),
228
+ lastOpenedAt: nextOpenStamp(list),
229
+ });
230
+ list.push(entry);
231
+ writeRaw(list, env);
232
+ return entry;
233
+ }
234
+
235
+ /** Mark a workspace opened now (drives the recency sort + pre-select-last). */
236
+ export function touchWorkspace(id, env = process.env) {
237
+ const list = readRaw(env);
238
+ const w = list.find((x) => x.id === id);
239
+ if (!w) return null;
240
+ w.lastOpenedAt = nextOpenStamp(list);
241
+ writeRaw(list, env);
242
+ return w;
243
+ }
244
+
245
+ /**
246
+ * Promote a registered workspace to SHARED (sharing slice / design §4 decision 7).
247
+ * The workspace must already be in the registry (the boot/default workspace is
248
+ * seeded first by the caller). Records the rails identity (`slug`) + the local
249
+ * member's role; the folder is untouched. Idempotent: re-sharing updates the block.
250
+ * Returns the updated entry, or null if the id is unknown.
251
+ */
252
+ export function markShared(id, { slug, ownerEmail = '', role = 'owner' } = {}, env = process.env) {
253
+ if (!slug || typeof slug !== 'string') throw new Error('markShared requires a slug');
254
+ const list = readRaw(env);
255
+ const w = list.find((x) => x.id === id);
256
+ if (!w) return null;
257
+ w.kind = 'shared';
258
+ w.shared = sanitizeShared({
259
+ slug,
260
+ ownerEmail,
261
+ role,
262
+ sharedAt: w.shared?.sharedAt || nowMs(),
263
+ // Preserve a file-sync link already recorded (re-share/re-mark must not drop it).
264
+ projectCode: w.shared?.projectCode,
265
+ });
266
+ writeRaw(list, env);
267
+ return w;
268
+ }
269
+
270
+ /**
271
+ * Record the file-sync project a shared workspace replicates through, once the
272
+ * daemon has paired the folder (Slice 3 "going live"). The entry must already be
273
+ * `kind:'shared'`. Idempotent. Returns the updated entry, or null if the id is
274
+ * unknown / not shared.
275
+ */
276
+ export function setSyncProject(id, projectCode, env = process.env) {
277
+ if (!projectCode || typeof projectCode !== 'string') {
278
+ throw new Error('setSyncProject requires a projectCode');
279
+ }
280
+ const list = readRaw(env);
281
+ const w = list.find((x) => x.id === id);
282
+ if (!w || w.kind !== 'shared' || !w.shared) return null;
283
+ w.shared = sanitizeShared({ ...w.shared, projectCode });
284
+ writeRaw(list, env);
285
+ return w;
286
+ }
287
+
288
+ /** Remove a workspace from the LIST only. NEVER deletes the folder or its files. */
289
+ export function removeWorkspace(id, env = process.env) {
290
+ const list = readRaw(env);
291
+ const next = list.filter((w) => w.id !== id);
292
+ if (next.length === list.length) return false;
293
+ writeRaw(next, env);
294
+ return true;
295
+ }
@@ -0,0 +1,135 @@
1
+ // WorkspaceRails — the shared-workspace membership client (multi-host step 2).
2
+ //
3
+ // A thin client over bmo-sync's POST /api/workspaces/{create,list,members/add,
4
+ // members/remove} (account-token self-authed, exactly like canvas-rails.mjs).
5
+ // The caller (owner/member) is DERIVED server-side from the account token, so a
6
+ // caller can only act as itself.
7
+ //
8
+ // Unlike CanvasRails (which degrades silently to a local cache), these are
9
+ // operator/dev affordances driven by `wild-workspace workspace …`, so the
10
+ // methods SURFACE the rails' error code + message instead of collapsing to a
11
+ // bare false — the human running the command needs to see "slug_taken" /
12
+ // "not_owner" / "no_such_account". Network failures still never throw: they
13
+ // resolve to { ok:false, status:0, code:'unreachable' }.
14
+ //
15
+ // This is the FOUNDATION client — there is no App.jsx / lobby UI yet (that's the
16
+ // lobby's job). The CLI is the only consumer.
17
+
18
+ const DEFAULT_TIMEOUT_MS = 5000;
19
+
20
+ export class WorkspaceRails {
21
+ constructor({
22
+ bmoSyncUrl,
23
+ accountToken,
24
+ timeoutMs = DEFAULT_TIMEOUT_MS,
25
+ fetchImpl = (...a) => globalThis.fetch(...a),
26
+ } = {}) {
27
+ this.bmoSyncUrl = bmoSyncUrl ? bmoSyncUrl.replace(/\/$/, '') : null;
28
+ this.accountToken = accountToken || null;
29
+ this.timeoutMs = timeoutMs;
30
+ this.fetchImpl = fetchImpl;
31
+ // Inert without a token (can't key it) or without a server URL.
32
+ this.capable = Boolean(this.accountToken) && Boolean(this.bmoSyncUrl);
33
+ }
34
+
35
+ /**
36
+ * POST to a workspaces endpoint with the account token folded in.
37
+ * @returns {Promise<{ok:boolean, status:number, data:object|null, code?:string, message?:string}>}
38
+ * ok:true → 2xx; `data` is the parsed body.
39
+ * ok:false → a 4xx/5xx (carries the rails' {code,message}) OR a transport
40
+ * failure (status 0, code 'unreachable' / 'not_configured').
41
+ */
42
+ async _post(path, body) {
43
+ if (!this.capable) {
44
+ return { ok: false, status: 0, data: null, code: 'not_configured', message: 'not logged in / no rails URL' };
45
+ }
46
+ const ctrl = new AbortController();
47
+ const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
48
+ if (timer.unref) timer.unref();
49
+ try {
50
+ const r = await this.fetchImpl(`${this.bmoSyncUrl}${path}`, {
51
+ method: 'POST',
52
+ headers: { 'content-type': 'application/json' },
53
+ body: JSON.stringify({ account_token: this.accountToken, ...body }),
54
+ signal: ctrl.signal,
55
+ });
56
+ const data = await r.json().catch(() => null);
57
+ if (r.ok) return { ok: true, status: r.status, data };
58
+ return {
59
+ ok: false,
60
+ status: r.status,
61
+ data,
62
+ code: data?.code || `http_${r.status}`,
63
+ message: data?.message || `HTTP ${r.status}`,
64
+ };
65
+ } catch (e) {
66
+ return { ok: false, status: 0, data: null, code: 'unreachable', message: String(e?.message || e) };
67
+ } finally {
68
+ clearTimeout(timer);
69
+ }
70
+ }
71
+
72
+ /** Create a shared workspace. `slug` is optional (the rails auto-suggest from name). */
73
+ create(name, slug = null) {
74
+ const body = { name };
75
+ if (slug) body.slug = slug;
76
+ return this._post('/api/workspaces/create', body);
77
+ }
78
+
79
+ /** The shared workspaces this account belongs to. */
80
+ list() {
81
+ return this._post('/api/workspaces/list', {});
82
+ }
83
+
84
+ /**
85
+ * Add a member by email (owner-only). If the email has no account yet the
86
+ * rails records a PENDING invite (`data.pending === true`) instead of an
87
+ * active membership; the person claims it by signing in + Join.
88
+ */
89
+ addMember(slug, email) {
90
+ return this._post('/api/workspaces/members/add', { slug, member_email: email });
91
+ }
92
+
93
+ /**
94
+ * Claim membership at Join time. Activates a pending invite addressed to this
95
+ * account's own VERIFIED email; a no-op for an already-active member. Returns
96
+ * `{ok, data:{role, name, owner_email, claimed}}` or a 403 `not_a_member`.
97
+ */
98
+ claim(slug) {
99
+ return this._post('/api/workspaces/claim', { slug });
100
+ }
101
+
102
+ /**
103
+ * Mint a file-sync pass for a shared workspace this account belongs to
104
+ * (Slice 3). Returns `{ok, data:{project_code, invite_code, expires_at}}` — the
105
+ * daemon redeems `invite_code` to pair the folder and start replicating. The
106
+ * project is provisioned lazily server-side; the code is stable, the invite is
107
+ * one-shot (each call mints a fresh one). A non-member → 403 `not_a_member`.
108
+ */
109
+ syncCredential(slug) {
110
+ return this._post('/api/workspaces/sync-credential', { slug });
111
+ }
112
+
113
+ /** Remove a member by email or accountId (owner-only; the owner can't be removed). */
114
+ removeMember(slug, ref) {
115
+ const body = { slug };
116
+ if (ref && typeof ref === 'object') {
117
+ if (ref.accountId) body.account_id = ref.accountId;
118
+ else if (ref.email) body.member_email = ref.email;
119
+ } else if (typeof ref === 'string') {
120
+ // Heuristic: an '@' means an email, otherwise treat it as an account id.
121
+ if (ref.includes('@')) body.member_email = ref;
122
+ else body.account_id = ref;
123
+ }
124
+ return this._post('/api/workspaces/members/remove', body);
125
+ }
126
+ }
127
+
128
+ /** Build the client from server config + account (or an inert one when logged out). */
129
+ export function createWorkspaceRails(config, account, fetchImpl) {
130
+ return new WorkspaceRails({
131
+ bmoSyncUrl: config?.bmoSyncServerUrl,
132
+ accountToken: account?.accountToken,
133
+ fetchImpl,
134
+ });
135
+ }