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.
- package/LICENSE +21 -0
- package/README.md +31 -0
- package/bin/create-heresay.mjs +9 -0
- package/package.json +38 -0
- package/release/VERSION +1 -0
- package/release/firebase.json +111 -0
- package/release/firestore.indexes.json +11 -0
- package/release/firestore.rules +10 -0
- package/release/functions/lib/core/handler.js +366 -0
- package/release/functions/lib/core/store.js +66 -0
- package/release/functions/lib/core/types.js +23 -0
- package/release/functions/lib/core/version.js +3 -0
- package/release/functions/lib/index.js +7 -0
- package/release/functions/lib/providers/firebase/admin.js +13 -0
- package/release/functions/lib/providers/firebase/api.js +55 -0
- package/release/functions/lib/providers/firebase/firestore-store.js +106 -0
- package/release/functions/package-lock.json +2993 -0
- package/release/functions/package.json +23 -0
- package/release/public/app/index.html +57 -0
- package/release/public/app-icon.svg +1 -0
- package/release/public/apple-touch-icon.png +0 -0
- package/release/public/dashboard.css +152 -0
- package/release/public/dashboard.js +580 -0
- package/release/public/demo.html +30 -0
- package/release/public/docs.html +152 -0
- package/release/public/favicon.svg +1 -0
- package/release/public/icon-192.png +0 -0
- package/release/public/index.html +166 -0
- package/release/public/logo-white.svg +1 -0
- package/release/public/logo.svg +1 -0
- package/release/public/mark.svg +1 -0
- package/release/public/sdk.js +380 -0
- package/release/public/site.css +150 -0
- package/src/cli.mjs +382 -0
- package/src/firebase.mjs +61 -0
- package/src/google.mjs +106 -0
- package/src/state.mjs +43 -0
- package/src/steps.mjs +306 -0
package/src/steps.mjs
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The build steps of a Heresay. Each one checks before it acts, so running setup again after
|
|
3
|
+
* a failure picks up where it stopped instead of creating a second of anything.
|
|
4
|
+
*
|
|
5
|
+
* ctx: { id, name, region, billing, owner, version }. `say(text)` updates the spinner line.
|
|
6
|
+
*/
|
|
7
|
+
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { g, op, patiently, GoogleError } from './google.mjs';
|
|
11
|
+
import { firebase, npm } from './firebase.mjs';
|
|
12
|
+
import { workDir } from './state.mjs';
|
|
13
|
+
|
|
14
|
+
export const RELEASE = fileURLToPath(new URL('../release/', import.meta.url));
|
|
15
|
+
export const releaseVersion = () => readFileSync(join(RELEASE, 'VERSION'), 'utf8').trim();
|
|
16
|
+
|
|
17
|
+
const CRM = 'https://cloudresourcemanager.googleapis.com/v1';
|
|
18
|
+
const FB = 'https://firebase.googleapis.com/v1beta1';
|
|
19
|
+
const BILLING = 'https://cloudbilling.googleapis.com/v1';
|
|
20
|
+
const SU = 'https://serviceusage.googleapis.com/v1';
|
|
21
|
+
const FS = 'https://firestore.googleapis.com/v1';
|
|
22
|
+
const IDT = 'https://identitytoolkit.googleapis.com/admin/v2';
|
|
23
|
+
|
|
24
|
+
export const REGIONS = [
|
|
25
|
+
{ value: 'us-central1', label: 'United States', hint: 'Iowa, us-central1' },
|
|
26
|
+
{ value: 'asia-south1', label: 'India', hint: 'Mumbai, asia-south1' },
|
|
27
|
+
{ value: 'europe-west1', label: 'Europe', hint: 'Belgium, europe-west1' },
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
/** A plain-language failure: what went wrong, and what to do about it. */
|
|
31
|
+
export class StepError extends Error {
|
|
32
|
+
constructor(message, fix) { super(message); this.fix = fix; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ---- 1. project -------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
export async function project(ctx, say) {
|
|
38
|
+
const existing = await g('GET', `${CRM}/projects/${ctx.id}`, { missingOk: true }).catch((e) => {
|
|
39
|
+
if (e.status === 403) return null; // not ours, or not there: Google won't say which
|
|
40
|
+
throw e;
|
|
41
|
+
});
|
|
42
|
+
if (existing && existing.lifecycleState !== 'ACTIVE') {
|
|
43
|
+
throw new StepError(`The project ${ctx.id} is being deleted.`, 'Pick another project id and run this again.');
|
|
44
|
+
}
|
|
45
|
+
if (!existing) {
|
|
46
|
+
say('Creating the Google Cloud project');
|
|
47
|
+
let o;
|
|
48
|
+
try {
|
|
49
|
+
o = await g('POST', `${CRM}/projects`, { body: { projectId: ctx.id, name: `Heresay ${ctx.name}`.slice(0, 30) } });
|
|
50
|
+
} catch (e) {
|
|
51
|
+
if (e.status === 409) throw new StepError(`The project id ${ctx.id} is taken.`, 'Run this again and pick another id.');
|
|
52
|
+
if (/quota/i.test(e.message)) {
|
|
53
|
+
throw new StepError('Your Google account can’t create more projects.',
|
|
54
|
+
'Delete one you no longer use at https://console.cloud.google.com/cloud-resource-manager, or request more quota, then run this again.');
|
|
55
|
+
}
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
await op(CRM, o, { timeoutMs: 3 * 60_000 });
|
|
59
|
+
}
|
|
60
|
+
const fb = await g('GET', `${FB}/projects/${ctx.id}`, { missingOk: true }).catch((e) => (e.status === 403 ? null : Promise.reject(e)));
|
|
61
|
+
if (!fb) {
|
|
62
|
+
say('Adding Firebase to it');
|
|
63
|
+
try {
|
|
64
|
+
const o = await patiently(() => g('POST', `${FB}/projects/${ctx.id}:addFirebase`, { body: {} }), { forMs: 60_000 });
|
|
65
|
+
await op(FB, o, { timeoutMs: 3 * 60_000 });
|
|
66
|
+
} catch (e) {
|
|
67
|
+
if (/terms of service|tos/i.test(e.message)) {
|
|
68
|
+
throw new StepError('Your Google account hasn’t accepted the Firebase terms yet.',
|
|
69
|
+
'Open https://console.firebase.google.com once, accept the terms, then run this again.');
|
|
70
|
+
}
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return ctx.id;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- 2. billing -------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
export async function billingAccounts() {
|
|
80
|
+
const b = await g('GET', `${BILLING}/billingAccounts?pageSize=50`);
|
|
81
|
+
return (b.billingAccounts ?? []).filter((a) => a.open);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function billing(ctx, say) {
|
|
85
|
+
const cur = await g('GET', `${BILLING}/projects/${ctx.id}/billingInfo`);
|
|
86
|
+
if (cur.billingEnabled && cur.billingAccountName === ctx.billing.name) return ctx.billing.displayName;
|
|
87
|
+
say('Linking ' + ctx.billing.displayName);
|
|
88
|
+
try {
|
|
89
|
+
await g('PUT', `${BILLING}/projects/${ctx.id}/billingInfo`, { body: { billingAccountName: ctx.billing.name } });
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (e.status === 403 || e.status === 400) {
|
|
92
|
+
throw new StepError(`That billing account can’t be linked (${e.message}).`,
|
|
93
|
+
'It may be closed, or you may not be allowed to link projects to it. Run this again and pick another.');
|
|
94
|
+
}
|
|
95
|
+
throw e;
|
|
96
|
+
}
|
|
97
|
+
return ctx.billing.displayName;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---- 3. services ------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
const SERVICES = [
|
|
103
|
+
'firestore.googleapis.com', 'cloudfunctions.googleapis.com', 'run.googleapis.com',
|
|
104
|
+
'cloudbuild.googleapis.com', 'artifactregistry.googleapis.com', 'identitytoolkit.googleapis.com',
|
|
105
|
+
'firebasehosting.googleapis.com', 'firebaserules.googleapis.com',
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
export async function services(ctx, say) {
|
|
109
|
+
say('Switching on Firestore, Functions, Auth and Hosting');
|
|
110
|
+
const o = await patiently(() => g('POST', `${SU}/projects/${ctx.id}/services:batchEnable`, { body: { serviceIds: SERVICES } }), { forMs: 90_000 });
|
|
111
|
+
await op(SU, o, { timeoutMs: 6 * 60_000 });
|
|
112
|
+
return 'Firestore, Functions, Auth, Hosting';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ---- 4. database ------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
export async function database(ctx, say) {
|
|
118
|
+
const db = `${FS}/projects/${ctx.id}/databases/(default)`;
|
|
119
|
+
// Right after the API is switched on, Firestore answers 403 for a minute or two.
|
|
120
|
+
const have = await patiently(() => g('GET', db, { missingOk: true }), { forMs: 180_000 });
|
|
121
|
+
if (have) return have.locationId;
|
|
122
|
+
say('Creating the database in ' + ctx.region);
|
|
123
|
+
const o = await patiently(() => g('POST', `${FS}/projects/${ctx.id}/databases?databaseId=(default)`, {
|
|
124
|
+
body: { locationId: ctx.region, type: 'FIRESTORE_NATIVE' },
|
|
125
|
+
}), { forMs: 90_000 });
|
|
126
|
+
await op(FS, o, { timeoutMs: 5 * 60_000 });
|
|
127
|
+
return ctx.region;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ---- the release, laid out for `firebase deploy` ----------------------------------------
|
|
131
|
+
|
|
132
|
+
/** Copy the bundled release into ~/.heresay/instances/<id>/ and write its config. */
|
|
133
|
+
export function prepareRelease(ctx) {
|
|
134
|
+
const dir = workDir(ctx.id);
|
|
135
|
+
mkdirSync(dir, { recursive: true });
|
|
136
|
+
// Keep the installed runtime dependencies between deploys; replace everything else.
|
|
137
|
+
for (const f of readdirSync(dir)) if (f !== 'functions') rmSync(join(dir, f), { recursive: true, force: true });
|
|
138
|
+
if (existsSync(join(dir, 'functions'))) {
|
|
139
|
+
for (const f of readdirSync(join(dir, 'functions'))) if (f !== 'node_modules') rmSync(join(dir, 'functions', f), { recursive: true, force: true });
|
|
140
|
+
}
|
|
141
|
+
cpSync(RELEASE, dir, { recursive: true });
|
|
142
|
+
|
|
143
|
+
const cfg = JSON.parse(readFileSync(join(RELEASE, 'firebase.json'), 'utf8'));
|
|
144
|
+
delete cfg.emulators;
|
|
145
|
+
for (const fn of cfg.functions) delete fn.predeploy;
|
|
146
|
+
for (const r of cfg.hosting.rewrites) if (r.function) r.function.region = ctx.region;
|
|
147
|
+
writeFileSync(join(dir, 'firebase.json'), JSON.stringify(cfg, null, 2) + '\n');
|
|
148
|
+
writeFileSync(join(dir, '.firebaserc'), JSON.stringify({ projects: { default: ctx.id } }, null, 2) + '\n');
|
|
149
|
+
writeFileSync(join(dir, 'functions', '.env'), `HERESAY_REGION=${ctx.region}\n`);
|
|
150
|
+
return dir;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function deployError(out) {
|
|
154
|
+
const lines = out.split('\n').map((l) => l.trim()).filter(Boolean);
|
|
155
|
+
const err = lines.filter((l) => /^Error:|^⚠|failed|denied/i.test(l)).slice(-3).join(' ');
|
|
156
|
+
return err || lines.slice(-2).join(' ');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---- 5. sign-in -------------------------------------------------------------------------
|
|
160
|
+
//
|
|
161
|
+
// These calls carry the user's own project as quota project. Through the Firebase CLI they
|
|
162
|
+
// would share one quota with every Firebase CLI user in the world, and fail with 429 at busy times.
|
|
163
|
+
|
|
164
|
+
/** The web app whose config the dashboard loads from /__/firebase/init.js. */
|
|
165
|
+
async function webApp(ctx, say) {
|
|
166
|
+
const list = await patiently(() => g('GET', `${FB}/projects/${ctx.id}/webApps`, { project: ctx.id }), { forMs: 90_000 });
|
|
167
|
+
if (list.apps?.length) return list.apps[0].appId;
|
|
168
|
+
say('Registering the dashboard with Firebase');
|
|
169
|
+
const o = await patiently(() => g('POST', `${FB}/projects/${ctx.id}/webApps`, { project: ctx.id, body: { displayName: 'Heresay dashboard' } }), { forMs: 90_000 });
|
|
170
|
+
const app = await op(FB, o, { project: ctx.id });
|
|
171
|
+
return app.appId;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function signIn(ctx, say) {
|
|
175
|
+
const appId = await webApp(ctx, say);
|
|
176
|
+
const methods = [];
|
|
177
|
+
|
|
178
|
+
say('Switching on Google sign-in');
|
|
179
|
+
try {
|
|
180
|
+
const o = await patiently(() => g('POST', 'https://firebase.googleapis.com/v1alpha/firebase:provisionFirebaseApp', {
|
|
181
|
+
project: ctx.id,
|
|
182
|
+
body: {
|
|
183
|
+
appNamespace: appId, displayName: 'Heresay dashboard', parent: `projects/${ctx.id}`, webInput: {},
|
|
184
|
+
firebaseAuthInput: {
|
|
185
|
+
emailAuthProviderMode: 'PROVIDER_ENABLED',
|
|
186
|
+
googleSigninProviderMode: 'PROVIDER_ENABLED',
|
|
187
|
+
googleSigninProviderConfig: {
|
|
188
|
+
publicDisplayName: `Heresay ${ctx.name}`.slice(0, 30),
|
|
189
|
+
// Google requires the signed-in account (or a group it manages) here.
|
|
190
|
+
customerSupportEmail: ctx.account ?? ctx.owner,
|
|
191
|
+
// The firebaseapp.com handler is added by Google itself; listing it again is an error.
|
|
192
|
+
oauthRedirectUris: [`https://${ctx.id}.web.app/__/auth/handler`],
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
}), { forMs: 60_000 });
|
|
197
|
+
await op(FB, o, { project: ctx.id, timeoutMs: 3 * 60_000 });
|
|
198
|
+
methods.push('Google');
|
|
199
|
+
} catch (e) {
|
|
200
|
+
// Without Google, email links still work; set Auth up the plain way.
|
|
201
|
+
await g('POST', `https://identitytoolkit.googleapis.com/v2/projects/${ctx.id}/identityPlatform:initializeAuth`, { project: ctx.id, body: {} })
|
|
202
|
+
.catch((x) => { if (x.status !== 409 && !/already/i.test(x.message)) throw x; });
|
|
203
|
+
ctx.googleError = e.message;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Email links: for teammates without a Google account.
|
|
207
|
+
say('Switching on email links');
|
|
208
|
+
await patiently(() => g('PATCH', `${IDT}/projects/${ctx.id}/config?updateMask=signIn.email.enabled,signIn.email.passwordRequired`, {
|
|
209
|
+
project: ctx.id, body: { signIn: { email: { enabled: true, passwordRequired: false } } },
|
|
210
|
+
}), { forMs: 90_000 }).then(() => methods.push('email links')).catch((e) => {
|
|
211
|
+
if (!methods.length) {
|
|
212
|
+
throw new StepError(`Sign-in couldn’t be switched on (${e.message}).`,
|
|
213
|
+
`Open https://console.firebase.google.com/project/${ctx.id}/authentication, click Get started, then run this again.`);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
return methods.join(' and ');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- 6. owner ---------------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
const str = (v) => ({ stringValue: v });
|
|
222
|
+
|
|
223
|
+
export async function owner(ctx) {
|
|
224
|
+
const doc = `${FS}/projects/${ctx.id}/databases/(default)/documents/meta/instance`;
|
|
225
|
+
const at = new Date().toISOString();
|
|
226
|
+
const member = (email) => ({ mapValue: { fields: { email: str(email), role: str('owner'), added_at: str(at), added_by: { nullValue: null } } } });
|
|
227
|
+
const email = ctx.owner.trim().toLowerCase();
|
|
228
|
+
const cur = await patiently(() => g('GET', doc, { missingOk: true }), { forMs: 120_000 });
|
|
229
|
+
if (!cur) {
|
|
230
|
+
await g('PATCH', `${doc}?currentDocument.exists=false`, {
|
|
231
|
+
body: { fields: { created_at: str(at), members: { arrayValue: { values: [member(email)] } } } },
|
|
232
|
+
});
|
|
233
|
+
return email;
|
|
234
|
+
}
|
|
235
|
+
const values = cur.fields?.members?.arrayValue?.values ?? [];
|
|
236
|
+
if (values.some((v) => v.mapValue?.fields?.email?.stringValue === email)) return email;
|
|
237
|
+
// Whoever owns the Google project can always make themselves an owner of its Heresay.
|
|
238
|
+
await g('PATCH', `${doc}?updateMask.fieldPaths=members¤tDocument.updateTime=${encodeURIComponent(cur.updateTime)}`, {
|
|
239
|
+
body: { fields: { members: { arrayValue: { values: [...values, member(email)] } } } },
|
|
240
|
+
});
|
|
241
|
+
return email;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ---- 7. deploy --------------------------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
export async function deploy(ctx, say) {
|
|
247
|
+
const dir = prepareRelease(ctx);
|
|
248
|
+
say('Installing the API’s dependencies');
|
|
249
|
+
const inst = await npm(['install', '--omit=dev', '--no-audit', '--no-fund'], { cwd: join(dir, 'functions') });
|
|
250
|
+
if (inst.code !== 0) throw new StepError('Installing the API’s dependencies failed.', 'Check your internet connection and run this again.');
|
|
251
|
+
|
|
252
|
+
for (let attempt = 1; ; attempt++) {
|
|
253
|
+
say(attempt === 1 ? 'Uploading the dashboard, API and SDK' : `Trying the deploy again (${attempt} of 3)`);
|
|
254
|
+
// Deploy output interleaves; only ever move the status line forward.
|
|
255
|
+
const phases = [
|
|
256
|
+
[/firestore.*rules/i, 'Locking the database'],
|
|
257
|
+
[/functions:.*(creating|updating|building|source uploaded)/i, 'Building the API (the slow part, a few minutes)'],
|
|
258
|
+
[/hosting.*(uploading|found \d+ files|file upload)/i, 'Uploading the dashboard'],
|
|
259
|
+
[/release complete|Deploy complete/i, 'Finishing up'],
|
|
260
|
+
];
|
|
261
|
+
let at = -1;
|
|
262
|
+
const r = await firebase(['deploy', '--only', 'hosting,functions,firestore', '--project', ctx.id, '--non-interactive', '--force'], {
|
|
263
|
+
cwd: dir,
|
|
264
|
+
onLine: (l) => {
|
|
265
|
+
const i = phases.findIndex(([re]) => re.test(l));
|
|
266
|
+
if (i > at) { at = i; say(phases[i][1]); }
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
if (r.code === 0) return `dashboard, API, SDK`;
|
|
270
|
+
// A new project's build service account can take a minute or two to get its permissions.
|
|
271
|
+
if (attempt < 3 && /build service account|permission|403|429|Quota exceeded|RESOURCE_EXHAUSTED|Internal error|Build failed|retry|unavailable/i.test(r.out)) {
|
|
272
|
+
say('Google is still setting up the project; waiting a minute');
|
|
273
|
+
await new Promise((res) => setTimeout(res, 60_000));
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
throw new StepError(`Deploy failed: ${deployError(r.out)}`, 'Your project is fine. Run the same command to try again.');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ---- 8. verify --------------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
export async function verify(ctx, say) {
|
|
283
|
+
const base = `https://${ctx.id}.web.app`;
|
|
284
|
+
say('Calling the API');
|
|
285
|
+
const until = Date.now() + 3 * 60_000;
|
|
286
|
+
for (;;) {
|
|
287
|
+
try {
|
|
288
|
+
const h = await (await fetch(`${base}/v1/health`)).json();
|
|
289
|
+
const app = await fetch(`${base}/app/`);
|
|
290
|
+
if (h.ok && app.ok) return `API ${h.version}, dashboard loads`;
|
|
291
|
+
} catch { /* hosting can take a moment to answer on a new site */ }
|
|
292
|
+
if (Date.now() > until) {
|
|
293
|
+
throw new StepError(`${base} isn’t answering yet.`, 'New sites can take a few minutes. Run npx create-heresay status in a little while.');
|
|
294
|
+
}
|
|
295
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ---- remove -----------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
export async function remove(id) {
|
|
302
|
+
await g('PUT', `${BILLING}/projects/${id}/billingInfo`, { body: { billingAccountName: '' } }).catch(() => {});
|
|
303
|
+
await g('DELETE', `${CRM}/projects/${id}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export { GoogleError };
|