create-heresay 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -0
  3. package/bin/create-heresay.mjs +9 -0
  4. package/package.json +38 -0
  5. package/release/VERSION +1 -0
  6. package/release/firebase.json +111 -0
  7. package/release/firestore.indexes.json +11 -0
  8. package/release/firestore.rules +10 -0
  9. package/release/functions/lib/core/handler.js +366 -0
  10. package/release/functions/lib/core/store.js +66 -0
  11. package/release/functions/lib/core/types.js +23 -0
  12. package/release/functions/lib/core/version.js +3 -0
  13. package/release/functions/lib/index.js +7 -0
  14. package/release/functions/lib/providers/firebase/admin.js +13 -0
  15. package/release/functions/lib/providers/firebase/api.js +55 -0
  16. package/release/functions/lib/providers/firebase/firestore-store.js +106 -0
  17. package/release/functions/package-lock.json +2993 -0
  18. package/release/functions/package.json +23 -0
  19. package/release/public/app/index.html +57 -0
  20. package/release/public/app-icon.svg +1 -0
  21. package/release/public/apple-touch-icon.png +0 -0
  22. package/release/public/dashboard.css +152 -0
  23. package/release/public/dashboard.js +580 -0
  24. package/release/public/demo.html +30 -0
  25. package/release/public/docs.html +152 -0
  26. package/release/public/favicon.svg +1 -0
  27. package/release/public/icon-192.png +0 -0
  28. package/release/public/index.html +166 -0
  29. package/release/public/logo-white.svg +1 -0
  30. package/release/public/logo.svg +1 -0
  31. package/release/public/mark.svg +1 -0
  32. package/release/public/sdk.js +380 -0
  33. package/release/public/site.css +150 -0
  34. package/src/cli.mjs +382 -0
  35. package/src/firebase.mjs +61 -0
  36. package/src/google.mjs +106 -0
  37. package/src/state.mjs +43 -0
  38. package/src/steps.mjs +306 -0
package/src/cli.mjs ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * npx create-heresay set up a new Heresay (or finish one that stopped)
3
+ * npx create-heresay update deploy this version to a Heresay you set up
4
+ * npx create-heresay status what's deployed where
5
+ * npx create-heresay open open a dashboard
6
+ * npx create-heresay remove delete a Heresay and its Google Cloud project
7
+ *
8
+ * The UX is specified in docs/plan/cli-ux.md.
9
+ */
10
+ import * as p from '@clack/prompts';
11
+ import pc from 'picocolors';
12
+ import { spawn } from 'node:child_process';
13
+ import { randomBytes } from 'node:crypto';
14
+ import { account } from './google.mjs';
15
+ import { firebase, logTo } from './firebase.mjs';
16
+ import * as state from './state.mjs';
17
+ import * as steps from './steps.mjs';
18
+
19
+ const peacock = (s) => `\x1b[38;2;15;118;110m${s}\x1b[39m`;
20
+ const url = (id) => `https://${id}.web.app`;
21
+
22
+ // ---- arguments --------------------------------------------------------------------------
23
+
24
+ function parseArgs(argv) {
25
+ const out = { _: [] };
26
+ for (let i = 0; i < argv.length; i++) {
27
+ const a = argv[i];
28
+ if (!a.startsWith('--')) { out._.push(a); continue; }
29
+ const [k, v] = a.slice(2).split('=');
30
+ if (v !== undefined) out[k] = v;
31
+ else if (argv[i + 1] && !argv[i + 1].startsWith('--')) out[k] = argv[++i];
32
+ else out[k] = true;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ const HELP = `
38
+ ${peacock('heresay')} every report gets a hearing
39
+
40
+ npx create-heresay Set up your own Heresay (about 5 minutes)
41
+ npx create-heresay update Deploy this version to a Heresay you set up
42
+ npx create-heresay status See what's deployed, and where
43
+ npx create-heresay open Open your dashboard
44
+ npx create-heresay remove Delete a Heresay and its Google Cloud project
45
+
46
+ Setup flags, to skip questions:
47
+ --name <name> --project-id <id> --region us-central1|asia-south1|europe-west1
48
+ --billing <account> --owner <email> --yes (take every default, never ask)
49
+ `;
50
+
51
+ // ---- small helpers ----------------------------------------------------------------------
52
+
53
+ function bail(v) {
54
+ if (p.isCancel(v)) { p.cancel('Stopped. Nothing else was changed; run this again to carry on.'); process.exit(0); }
55
+ return v;
56
+ }
57
+
58
+ function openInBrowser(target) {
59
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
60
+ const args = process.platform === 'win32' ? ['/c', 'start', '', target] : [target];
61
+ try { spawn(cmd, args, { stdio: 'ignore', detached: true }).unref(); } catch { /* the URL is printed anyway */ }
62
+ }
63
+
64
+ const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
65
+ function suggestId(name) {
66
+ const tail = randomBytes(3).toString('hex').slice(0, 4);
67
+ const base = slug(name).slice(0, 30 - 'heresay--'.length - tail.length).replace(/-+$/, '');
68
+ return `heresay-${base ? base + '-' : ''}${tail}`;
69
+ }
70
+ const validId = (id) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(id);
71
+
72
+ function fail(e, id) {
73
+ const log = id ? state.logPath(id) : null;
74
+ if (e instanceof steps.StepError) {
75
+ p.log.error(e.message);
76
+ if (e.fix) p.log.message(e.fix);
77
+ } else {
78
+ p.log.error(e.message || String(e));
79
+ p.log.message('Your progress is saved. Run the same command to carry on.');
80
+ }
81
+ if (log) p.log.message(pc.dim(`Full log: ${log}`));
82
+ p.outro(pc.red('Setup stopped'));
83
+ process.exit(1);
84
+ }
85
+
86
+ // ---- sign in to Google ------------------------------------------------------------------
87
+
88
+ async function ensureLogin(args) {
89
+ let email = await account();
90
+ if (email && !args.yes) {
91
+ const use = bail(await p.select({
92
+ message: 'Google account',
93
+ options: [{ value: 'yes', label: `Use ${email}` }, { value: 'other', label: 'Use a different account' }],
94
+ }));
95
+ if (use === 'other') {
96
+ await firebase(['logout'], {});
97
+ email = null;
98
+ }
99
+ }
100
+ if (!email) {
101
+ if (args.yes) { p.log.error('Not signed in to Google. Run without --yes to sign in.'); process.exit(1); }
102
+ p.log.step('Opening your browser to sign in to Google…');
103
+ await firebase(['login', '--reauth'], { interactive: true });
104
+ email = await account();
105
+ if (!email) { p.cancel('Setup needs a Google account. Run this again when you’re ready.'); process.exit(1); }
106
+ }
107
+ p.log.success(`Signed in as ${email}`);
108
+ return email;
109
+ }
110
+
111
+ // ---- setup ------------------------------------------------------------------------------
112
+
113
+ async function setup(args) {
114
+ const version = steps.releaseVersion();
115
+ p.intro(`${peacock(pc.bold('heresay'))} ${pc.dim('· every report gets a hearing')}`);
116
+
117
+ const [major] = process.versions.node.split('.').map(Number);
118
+ if (major < 20) {
119
+ p.log.error(`Heresay needs Node 20 or newer. You have ${process.versions.node}. Install it from https://nodejs.org, then run this again.`);
120
+ process.exit(1);
121
+ }
122
+
123
+ // Resume an unfinished one first, so a rerun never starts a second project by accident.
124
+ const all = state.load().instances;
125
+ const unfinished = Object.entries(all).filter(([, v]) => !v.done?.verify);
126
+ let ctx = null;
127
+ if (unfinished.length && !args['project-id']) {
128
+ const [id, rec] = unfinished[0];
129
+ const resume = args.yes ? true : bail(await p.confirm({ message: `Found an unfinished setup for ${pc.bold(id)}. Pick up where it stopped?` }));
130
+ if (resume) ctx = { id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version };
131
+ else if (!args.yes) {
132
+ const drop = bail(await p.confirm({ message: 'Forget it and start a new one? (The Google project stays; remove it with npx create-heresay remove.)', initialValue: false }));
133
+ if (!drop) { p.outro('Nothing changed.'); return; }
134
+ state.forget(id);
135
+ }
136
+ }
137
+
138
+ if (!ctx) {
139
+ p.note([
140
+ 'This sets up your own Heresay in your Google account:',
141
+ '',
142
+ ` ${peacock('•')} A new Firebase project, owned by you`,
143
+ ` ${peacock('•')} Its database, sign-in and hosting`,
144
+ ` ${peacock('•')} The Heresay dashboard, API and SDK, deployed to it`,
145
+ '',
146
+ 'Heresay’s API runs on Cloud Functions, which needs Firebase’s',
147
+ 'pay-as-you-go (Blaze) plan. It has a free tier; a small app pays',
148
+ 'nothing. You can set a budget alert in the Google Cloud console.',
149
+ ].join('\n'), 'About 5 minutes');
150
+ if (!args.yes) {
151
+ const go = bail(await p.confirm({ message: 'Continue?' }));
152
+ if (!go) { p.outro('Nothing changed.'); return; }
153
+ }
154
+ }
155
+
156
+ const email = await ensureLogin(args);
157
+ if (ctx) ctx.account = email;
158
+
159
+ if (!ctx) {
160
+ const defaultName = slug(email.split('@')[0]).slice(0, 20) || 'team';
161
+ const name = args.name ?? (args.yes ? defaultName : bail(await p.text({
162
+ message: 'Name your Heresay',
163
+ placeholder: defaultName, defaultValue: defaultName,
164
+ validate: (v) => (v && v.length > 20 ? 'Keep it under 20 characters' : undefined),
165
+ })));
166
+ const suggested = suggestId(name);
167
+ const id = args['project-id'] ?? (args.yes ? suggested : bail(await p.text({
168
+ message: 'Project id',
169
+ placeholder: suggested, defaultValue: suggested,
170
+ validate: (v) => (!v || validId(v) ? undefined : '6 to 30 characters: lowercase letters, digits and dashes, starting with a letter'),
171
+ })));
172
+ if (!validId(id)) { p.log.error(`${id} isn’t a valid project id.`); process.exit(1); }
173
+
174
+ const region = args.region ?? (args.yes ? 'us-central1' : bail(await p.select({
175
+ message: 'Where should data live?',
176
+ options: steps.REGIONS.map((r) => ({ value: r.value, label: r.label, hint: r.hint })),
177
+ })));
178
+ if (!steps.REGIONS.some((r) => r.value === region)) { p.log.error(`Unknown region ${region}.`); process.exit(1); }
179
+
180
+ const billing = await pickBilling(args);
181
+
182
+ const owner = args.owner ?? (args.yes ? email : bail(await p.text({
183
+ message: 'Who can sign in to the dashboard?',
184
+ placeholder: email, defaultValue: email,
185
+ validate: (v) => (!v || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? undefined : 'That isn’t an email address'),
186
+ })));
187
+
188
+ ctx = { id, name, region, billing, owner, version, account: email };
189
+ state.update(id, { name, region, billing, owner, url: url(id), created_at: new Date().toISOString(), done: {} });
190
+ if (!args.yes) p.log.message(pc.dim('You can add teammates in the dashboard later.'));
191
+ }
192
+
193
+ await build(ctx);
194
+
195
+ p.note([
196
+ pc.bold(peacock(url(ctx.id))),
197
+ '',
198
+ `Open it, sign in as ${ctx.owner}, and add your first app.`,
199
+ '',
200
+ pc.dim('Later: npx create-heresay update get new versions'),
201
+ pc.dim(' npx create-heresay status see what’s deployed'),
202
+ ].join('\n'), 'Your Heresay is live');
203
+ if (!args.yes && process.stdout.isTTY) {
204
+ const open = bail(await p.confirm({ message: 'Open it now?' }));
205
+ if (open) openInBrowser(url(ctx.id) + '/app/');
206
+ }
207
+ p.outro('Every report gets a hearing.');
208
+ }
209
+
210
+ async function pickBilling(args) {
211
+ for (;;) {
212
+ let accounts;
213
+ try { accounts = await steps.billingAccounts(); } catch (e) { fail(e); }
214
+ if (args.billing) {
215
+ const want = String(args.billing).replace(/^billingAccounts\//, '');
216
+ const hit = accounts.find((a) => a.name === `billingAccounts/${want}` || a.displayName === args.billing);
217
+ if (!hit) { p.log.error(`No open billing account matches ${args.billing}.`); process.exit(1); }
218
+ return { name: hit.name, displayName: hit.displayName };
219
+ }
220
+ if (args.yes) {
221
+ if (accounts.length === 1) return { name: accounts[0].name, displayName: accounts[0].displayName };
222
+ p.log.error(accounts.length ? 'You have several billing accounts. Pass --billing <id>.' : 'You have no billing account. Run without --yes to create one.');
223
+ process.exit(1);
224
+ }
225
+ const choice = bail(await p.select({
226
+ message: 'Billing account',
227
+ options: [
228
+ ...accounts.map((a) => ({ value: a.name, label: a.displayName, hint: a.name.replace('billingAccounts/', '') })),
229
+ { value: '__new', label: 'I need to create one', hint: 'opens the Google Cloud console' },
230
+ ],
231
+ }));
232
+ if (choice !== '__new') return { name: choice, displayName: accounts.find((a) => a.name === choice).displayName };
233
+ openInBrowser('https://console.cloud.google.com/billing/create');
234
+ p.log.message('Create a billing account in the browser window. Google asks for a card, and won’t charge it inside the free tier.');
235
+ bail(await p.text({ message: 'Press Enter when it’s done', defaultValue: 'ok' }));
236
+ }
237
+ }
238
+
239
+ const BUILD = [
240
+ ['project', 'Creating the project', 'Project created', steps.project],
241
+ ['billing', 'Linking billing', 'Billing linked', steps.billing],
242
+ ['services', 'Switching on services', 'Services switched on', steps.services],
243
+ ['database', 'Creating the database', 'Database created', steps.database],
244
+ ['signin', 'Setting up sign-in', 'Sign-in set up', steps.signIn],
245
+ ['owner', 'Adding you as owner', 'Owner added', steps.owner],
246
+ ['deploy', 'Deploying Heresay', 'Heresay deployed', steps.deploy],
247
+ ['verify', 'Checking it works', 'Checked', steps.verify],
248
+ ];
249
+
250
+ /** A spinner in a terminal; plain lines anywhere else (CI, piped to a file). */
251
+ function progress(animated) {
252
+ if (process.stdout.isTTY) return p.spinner({ indicator: animated ? 'timer' : 'dots' });
253
+ let last = '';
254
+ const line = (m) => { if (m && m !== last) { last = m; console.log(`│ ${m}…`); } };
255
+ return { start: line, message: line, stop: (m) => console.log(`◇ ${m}`), error: (m) => console.log(`■ ${m}`) };
256
+ }
257
+
258
+ async function build(ctx, only) {
259
+ const log = state.logPath(ctx.id);
260
+ logTo(log);
261
+ (await import('./firebase.mjs')).log(`\n==== ${new Date().toISOString()} ${only ? 'update' : 'setup'} ${ctx.id} (Heresay ${ctx.version})`);
262
+ p.log.step(pc.bold(only ? `Updating ${ctx.id}` : 'Building your Heresay'));
263
+ const rec = state.load().instances[ctx.id] ?? {};
264
+ for (const [key, doing, title, run] of BUILD) {
265
+ if (only && !only.includes(key)) continue;
266
+ if (!only && rec.done?.[key] && key !== 'deploy' && key !== 'verify') {
267
+ p.log.success(`${title} ${pc.dim('(done before)')}`);
268
+ continue;
269
+ }
270
+ const s = progress(key === 'deploy');
271
+ s.start(doing);
272
+ const started = Date.now();
273
+ try {
274
+ const detail = await run(ctx, (m) => s.message(m));
275
+ const secs = Math.round((Date.now() - started) / 1000);
276
+ s.stop(`${title.padEnd(22)} ${pc.dim(String(detail ?? ''))}${secs > 20 ? pc.dim(` (${secs}s)`) : ''}`);
277
+ state.markDone(ctx.id, key);
278
+ if (key === 'signin' && ctx.googleError) {
279
+ p.log.warn(`Google sign-in couldn’t be switched on (${ctx.googleError}). Email links work. To add Google later: https://console.firebase.google.com/project/${ctx.id}/authentication/providers`);
280
+ }
281
+ if (key === 'deploy') state.update(ctx.id, { version: ctx.version, url: url(ctx.id) });
282
+ } catch (e) {
283
+ s.error(`${doing}: stopped`);
284
+ fail(e, ctx.id);
285
+ }
286
+ }
287
+ }
288
+
289
+ // ---- other commands ---------------------------------------------------------------------
290
+
291
+ async function pickInstance(verb, args) {
292
+ const all = state.load().instances;
293
+ const ids = Object.keys(all);
294
+ if (args['project-id']) {
295
+ if (!all[args['project-id']]) { p.log.error(`This computer didn’t set up ${args['project-id']}.`); process.exit(1); }
296
+ return args['project-id'];
297
+ }
298
+ if (!ids.length) { p.log.error('This computer hasn’t set up a Heresay yet. Run npx create-heresay first.'); process.exit(1); }
299
+ if (ids.length === 1) return ids[0];
300
+ return bail(await p.select({ message: `Which Heresay do you want to ${verb}?`, options: ids.map((id) => ({ value: id, label: id, hint: all[id].url })) }));
301
+ }
302
+
303
+ async function health(id) {
304
+ try {
305
+ const r = await fetch(`${url(id)}/v1/health`, { signal: AbortSignal.timeout(8000) });
306
+ return r.ok ? await r.json() : null;
307
+ } catch { return null; }
308
+ }
309
+
310
+ async function update(args) {
311
+ p.intro(`${peacock(pc.bold('heresay'))} update`);
312
+ const id = await pickInstance('update', args);
313
+ const rec = state.load().instances[id];
314
+ const live = await health(id);
315
+ const version = steps.releaseVersion();
316
+ p.log.info(`${id}: ${live ? live.version : 'not answering'} → ${version}`);
317
+ if (!args.yes) {
318
+ const go = bail(await p.confirm({ message: `Deploy ${version} to ${url(id)}?` }));
319
+ if (!go) { p.outro('Nothing changed.'); return; }
320
+ }
321
+ const signedIn = await account();
322
+ await build({ id, name: rec.name, region: rec.region, billing: rec.billing, owner: rec.owner, version, account: signedIn }, ['deploy', 'verify']);
323
+ p.outro(`${url(id)} is on ${version}.`);
324
+ }
325
+
326
+ async function status() {
327
+ p.intro(`${peacock(pc.bold('heresay'))} status`);
328
+ const all = state.load().instances;
329
+ const ids = Object.keys(all);
330
+ if (!ids.length) { p.outro('No Heresay set up from this computer yet. Run npx create-heresay.'); return; }
331
+ const bundled = steps.releaseVersion();
332
+ for (const id of ids) {
333
+ const rec = all[id];
334
+ const h = await health(id);
335
+ const lines = [
336
+ `${pc.dim('Dashboard')} ${url(id)}/app/`,
337
+ `${pc.dim('Region ')} ${rec.region}`,
338
+ `${pc.dim('Version ')} ${h ? h.version : pc.red('not answering')}${h && h.version !== bundled ? pc.dim(` (${bundled} available: npx create-heresay update)`) : ''}`,
339
+ `${pc.dim('Setup ')} ${rec.done?.verify ? 'complete' : pc.yellow('unfinished: run npx create-heresay to carry on')}`,
340
+ ];
341
+ p.note(lines.join('\n'), id);
342
+ }
343
+ p.outro('Deploy a newer version with npx create-heresay update.');
344
+ }
345
+
346
+ async function open(args) {
347
+ const id = await pickInstance('open', args);
348
+ openInBrowser(`${url(id)}/app/`);
349
+ console.log(`${url(id)}/app/`);
350
+ }
351
+
352
+ async function removeCmd(args) {
353
+ p.intro(`${peacock(pc.bold('heresay'))} remove`);
354
+ const id = await pickInstance('remove', args);
355
+ p.log.warn([
356
+ `This deletes the Google Cloud project ${pc.bold(id)}: its dashboard, every app and every report.`,
357
+ 'Google keeps it recoverable for 30 days, then it is gone. Billing is unlinked straight away.',
358
+ ].join('\n'));
359
+ const typed = bail(await p.text({ message: `Type ${id} to confirm` }));
360
+ if (typed !== id) { p.outro('That didn’t match. Nothing was deleted.'); return; }
361
+ await account();
362
+ const s = p.spinner();
363
+ s.start('Deleting');
364
+ try { await steps.remove(id); } catch (e) { s.error('Couldn’t delete it'); fail(e); }
365
+ state.forget(id);
366
+ s.stop(`Deleted ${id}`);
367
+ p.outro('Done.');
368
+ }
369
+
370
+ export async function main(argv) {
371
+ const args = parseArgs(argv);
372
+ const cmd = args._[0];
373
+ if (args.help || args.h || cmd === 'help') { console.log(HELP); return; }
374
+ if (args.version || args.v) { console.log(steps.releaseVersion()); return; }
375
+ if (!cmd || cmd === 'setup' || cmd === 'create') return setup(args);
376
+ if (cmd === 'update') return update(args);
377
+ if (cmd === 'status') return status(args);
378
+ if (cmd === 'open') return open(args);
379
+ if (cmd === 'remove') return removeCmd(args);
380
+ console.log(`Unknown command: ${cmd}\n${HELP}`);
381
+ process.exit(1);
382
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Runs the Firebase tools that ship inside this package, pinned to one version. Nothing is
3
+ * installed globally, and a Firebase CLI the user already has is left alone.
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import { createRequire } from 'node:module';
7
+ import { appendFileSync } from 'node:fs';
8
+
9
+ const require = createRequire(import.meta.url);
10
+ const BIN = require.resolve('firebase-tools/lib/bin/firebase.js');
11
+
12
+ let logFile = null;
13
+ export function logTo(path) { logFile = path; }
14
+ export function log(line) { if (logFile) appendFileSync(logFile, line.endsWith('\n') ? line : line + '\n'); }
15
+
16
+ /**
17
+ * Run `firebase <args>`. Output goes to the log file; `interactive` hands the terminal over
18
+ * instead (for the browser login).
19
+ */
20
+ export function firebase(args, { cwd, interactive = false, onLine, secret = false } = {}) {
21
+ log(`\n$ firebase ${args.join(' ')}${cwd ? ` (in ${cwd})` : ''}`);
22
+ return new Promise((resolve) => {
23
+ const child = spawn(process.execPath, [BIN, ...args], {
24
+ cwd, stdio: interactive ? 'inherit' : ['ignore', 'pipe', 'pipe'],
25
+ env: { ...process.env, FORCE_COLOR: '0', CI: interactive ? process.env.CI : '1' },
26
+ });
27
+ let out = '';
28
+ const take = (d) => {
29
+ const s = d.toString();
30
+ out += s;
31
+ if (!secret) log(s);
32
+ if (onLine) for (const line of s.split('\n')) if (line.trim()) onLine(line.trim());
33
+ };
34
+ child.stdout?.on('data', take);
35
+ child.stderr?.on('data', take);
36
+ child.on('close', (code) => resolve({ code, out }));
37
+ });
38
+ }
39
+
40
+ /** Run a command with --json and return its `result`, or null if it failed. */
41
+ export async function firebaseJson(args, opts) {
42
+ const { code, out } = await firebase([...args, '--json'], opts);
43
+ try {
44
+ const start = out.indexOf('{');
45
+ const b = JSON.parse(out.slice(start));
46
+ return b.status === 'success' ? b.result : (code === 0 ? b.result : null);
47
+ } catch { return null; }
48
+ }
49
+
50
+ /** npm, for installing the API's runtime dependencies before deploy. */
51
+ export function npm(args, { cwd } = {}) {
52
+ log(`\n$ npm ${args.join(' ')} (in ${cwd})`);
53
+ return new Promise((resolve) => {
54
+ const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], shell: process.platform === 'win32' });
55
+ let out = '';
56
+ child.stdout.on('data', (d) => { out += d; log(d.toString()); });
57
+ child.stderr.on('data', (d) => { out += d; log(d.toString()); });
58
+ child.on('close', (code) => resolve({ code, out }));
59
+ child.on('error', (e) => resolve({ code: 1, out: String(e) }));
60
+ });
61
+ }
package/src/google.mjs ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Google Cloud REST calls, signed with the account the Firebase tools are logged in as.
3
+ * We reuse that login instead of asking for a second one: the refresh token it holds already
4
+ * has the cloud-platform scope, which covers billing, services, Firestore and Auth config.
5
+ */
6
+ import { createRequire } from 'node:module';
7
+ import { firebaseJson, log } from './firebase.mjs';
8
+
9
+ const require = createRequire(import.meta.url);
10
+ const fbApi = require('firebase-tools/lib/api.js');
11
+
12
+ export class GoogleError extends Error {
13
+ constructor(message, status, reason) { super(message); this.status = status; this.reason = reason; }
14
+ }
15
+
16
+ let token = null;
17
+
18
+ /** The logged-in account, or null. */
19
+ export async function account() {
20
+ // login:list prints the tokens, so its output is kept out of the log.
21
+ const r = await firebaseJson(['login:list'], { secret: true });
22
+ const first = Array.isArray(r) ? r[0] : null;
23
+ if (!first) return null;
24
+ token = { refresh: first.tokens?.refresh_token, access: null, until: 0 };
25
+ return first.user?.email ?? null;
26
+ }
27
+
28
+ async function accessToken() {
29
+ if (!token) await account();
30
+ if (!token?.refresh) throw new GoogleError('Not signed in to Google.', 401, 'unauthenticated');
31
+ if (token.access && Date.now() < token.until) return token.access;
32
+ const r = await fetch('https://oauth2.googleapis.com/token', {
33
+ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
34
+ body: new URLSearchParams({
35
+ grant_type: 'refresh_token', refresh_token: token.refresh,
36
+ client_id: fbApi.clientId(), client_secret: fbApi.clientSecret(),
37
+ }),
38
+ });
39
+ const b = await r.json();
40
+ if (!b.access_token) throw new GoogleError('Your Google sign-in has expired. Run this again to sign in.', 401, 'unauthenticated');
41
+ token.access = b.access_token;
42
+ token.until = Date.now() + (b.expires_in - 120) * 1000;
43
+ return token.access;
44
+ }
45
+
46
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
47
+
48
+ /**
49
+ * One JSON call. Retries rate limits, server errors and network blips, because fresh projects
50
+ * answer flakily for their first minutes. Returns null for 404 when `missingOk` is set.
51
+ */
52
+ export async function g(method, url, { body, project, missingOk = false, tries = 6 } = {}) {
53
+ for (let i = 0; ; i++) {
54
+ let res;
55
+ try {
56
+ res = await fetch(url, {
57
+ method,
58
+ headers: {
59
+ authorization: `Bearer ${await accessToken()}`,
60
+ 'content-type': 'application/json',
61
+ // Bill quota to the user's project, not the Firebase CLI's own OAuth project.
62
+ ...(project ? { 'x-goog-user-project': project } : {}),
63
+ },
64
+ body: body === undefined ? undefined : JSON.stringify(body),
65
+ });
66
+ } catch (e) {
67
+ if (i < tries) { await sleep(1500 * 2 ** i); continue; }
68
+ throw new GoogleError(`Couldn't reach Google (${e.cause?.code ?? e.message}). Check your connection and run this again.`, 0, 'network');
69
+ }
70
+ log(`${method} ${url.replace(/\?.*/, '')} -> ${res.status}`);
71
+ if (missingOk && res.status === 404) return null;
72
+ const text = await res.text();
73
+ let b = {};
74
+ try { b = text ? JSON.parse(text) : {}; } catch { b = { raw: text }; }
75
+ if (res.ok) return b;
76
+ if ((res.status === 429 || res.status >= 500) && i < tries) { await sleep(1500 * 2 ** i); continue; }
77
+ const err = b.error ?? {};
78
+ log(` ${err.status ?? ''} ${err.message ?? text.slice(0, 300)}`);
79
+ const reason = err.status ?? err.details?.find?.((d) => d.reason)?.reason ?? String(res.status);
80
+ throw new GoogleError(err.message ?? `${method} ${url} failed with ${res.status}`, res.status, reason);
81
+ }
82
+ }
83
+
84
+ /** Wait for a long-running operation. `base` is the API root the operation name hangs off. */
85
+ export async function op(base, operation, { project, timeoutMs = 5 * 60_000 } = {}) {
86
+ const until = Date.now() + timeoutMs;
87
+ let o = operation;
88
+ while (!o.done) {
89
+ if (Date.now() > until) throw new GoogleError(`Google is still working on ${o.name}. Run this again in a minute.`, 0, 'timeout');
90
+ await sleep(2000);
91
+ o = await g('GET', `${base}/${o.name}`, { project });
92
+ }
93
+ if (o.error) throw new GoogleError(o.error.message, o.error.code, 'operation_failed');
94
+ return o.response ?? o;
95
+ }
96
+
97
+ /** Retry `fn` while it throws, for APIs that need a moment after being switched on. */
98
+ export async function patiently(fn, { forMs = 120_000, every = 5000 } = {}) {
99
+ const until = Date.now() + forMs;
100
+ for (;;) {
101
+ try { return await fn(); } catch (e) {
102
+ if (Date.now() > until || e.status === 401) throw e;
103
+ await sleep(every);
104
+ }
105
+ }
106
+ }
package/src/state.mjs ADDED
@@ -0,0 +1,43 @@
1
+ /** ~/.heresay/config.json: every Heresay this computer has set up, and how far each got. */
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
5
+
6
+ export const HOME = process.env.HERESAY_HOME || join(homedir(), '.heresay');
7
+ const FILE = join(HOME, 'config.json');
8
+
9
+ export function load() {
10
+ if (!existsSync(FILE)) return { instances: {} };
11
+ try { return JSON.parse(readFileSync(FILE, 'utf8')); } catch { return { instances: {} }; }
12
+ }
13
+
14
+ export function save(state) {
15
+ mkdirSync(HOME, { recursive: true });
16
+ writeFileSync(FILE, JSON.stringify(state, null, 2) + '\n');
17
+ }
18
+
19
+ /** Merge `patch` into one instance's record and write it straight away. */
20
+ export function update(id, patch) {
21
+ const s = load();
22
+ s.instances[id] = { ...(s.instances[id] ?? {}), ...patch, updated_at: new Date().toISOString() };
23
+ save(s);
24
+ return s.instances[id];
25
+ }
26
+
27
+ export function markDone(id, step) {
28
+ const cur = load().instances[id] ?? {};
29
+ return update(id, { done: { ...(cur.done ?? {}), [step]: true } });
30
+ }
31
+
32
+ export function forget(id) {
33
+ const s = load();
34
+ delete s.instances[id];
35
+ save(s);
36
+ }
37
+
38
+ export function logPath(id) {
39
+ mkdirSync(join(HOME, 'logs'), { recursive: true });
40
+ return join(HOME, 'logs', `${id}.log`);
41
+ }
42
+
43
+ export function workDir(id) { return join(HOME, 'instances', id); }