create-usebecky 0.0.0-stage → 0.2.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/README.md +80 -2
- package/dist/create.js +842 -0
- package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
- package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
- package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
- package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
- package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
- package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
- package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
- package/dist/index.js +10 -0
- package/dist/keys.js +72 -0
- package/dist/platform.js +104 -0
- package/dist/pm.js +69 -0
- package/dist/prompts.js +242 -0
- package/dist/scaffold.js +108 -0
- package/dist/setup.js +130 -0
- package/dist/shared/ai.js +203 -0
- package/dist/shared/extension-skill.js +107 -0
- package/dist/shared/framework.js +460 -0
- package/dist/shared/hosted.js +8 -0
- package/dist/shared/ui.js +141 -0
- package/dist/skill/usebecky/SKILL.md +339 -0
- package/dist/skill/usebecky/references/access-rules.md +307 -0
- package/dist/skill/usebecky/references/addons.md +68 -0
- package/dist/skill/usebecky/references/analytics.md +166 -0
- package/dist/skill/usebecky/references/android.md +434 -0
- package/dist/skill/usebecky/references/auth.md +379 -0
- package/dist/skill/usebecky/references/cache.md +51 -0
- package/dist/skill/usebecky/references/components.md +127 -0
- package/dist/skill/usebecky/references/emails.md +105 -0
- package/dist/skill/usebecky/references/expo.md +147 -0
- package/dist/skill/usebecky/references/functions.md +99 -0
- package/dist/skill/usebecky/references/hosting.md +119 -0
- package/dist/skill/usebecky/references/http-api.md +233 -0
- package/dist/skill/usebecky/references/ios.md +355 -0
- package/dist/skill/usebecky/references/payments.md +493 -0
- package/dist/skill/usebecky/references/realtime.md +143 -0
- package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/dist/skill/usebecky/references/sdk.md +838 -0
- package/dist/skill/usebecky/references/storage.md +210 -0
- package/dist/skill/usebecky/references/templates.md +191 -0
- package/dist/skill/usebecky/references/wordpress.md +87 -0
- package/dist/templates.js +74 -0
- package/package.json +37 -4
- package/templates/expo/App.tsx +48 -0
- package/templates/expo/README.md +59 -0
- package/templates/expo/_env.example +4 -0
- package/templates/expo/_gitignore +12 -0
- package/templates/expo/app.json +25 -0
- package/templates/expo/assets/icon.png +0 -0
- package/templates/expo/brand.ts +7 -0
- package/templates/expo/components/Avatar.tsx +75 -0
- package/templates/expo/components/ui.tsx +57 -0
- package/templates/expo/index.ts +4 -0
- package/templates/expo/lib/theme.ts +43 -0
- package/templates/expo/lib/usebecky.ts +15 -0
- package/templates/expo/package.json +29 -0
- package/templates/expo/screens/Home.tsx +187 -0
- package/templates/expo/screens/SignIn.tsx +112 -0
- package/templates/expo/tsconfig.json +6 -0
- package/templates/expo/usebecky.template.json +36 -0
- package/templates/extension/README.md +128 -0
- package/templates/extension/_env.example +21 -0
- package/templates/extension/_gitignore +11 -0
- package/templates/extension/logo.svg +1 -0
- package/templates/extension/package.json +25 -0
- package/templates/extension/src/accounts.ts +90 -0
- package/templates/extension/src/app.ts +178 -0
- package/templates/extension/src/pages.ts +108 -0
- package/templates/extension/src/replay-guard.ts +17 -0
- package/templates/extension/src/server.ts +57 -0
- package/templates/extension/src/settings.ts +69 -0
- package/templates/extension/src/ui.ts +70 -0
- package/templates/extension/test/app.test.ts +222 -0
- package/templates/extension/tsconfig.json +16 -0
- package/templates/extension/usebecky-extension.json +36 -0
- package/templates/extension/usebecky.template.json +22 -0
- package/templates/landing/README.md +43 -0
- package/templates/landing/_env.example +4 -0
- package/templates/landing/_gitignore +9 -0
- package/templates/landing/index.html +16 -0
- package/templates/landing/package.json +28 -0
- package/templates/landing/public/icon.svg +1 -0
- package/templates/landing/src/App.tsx +97 -0
- package/templates/landing/src/components/Contact.tsx +43 -0
- package/templates/landing/src/components/Counter.tsx +34 -0
- package/templates/landing/src/components/Feedback.tsx +36 -0
- package/templates/landing/src/components/Logo.tsx +11 -0
- package/templates/landing/src/components/Receipt.tsx +128 -0
- package/templates/landing/src/components/Setup.tsx +20 -0
- package/templates/landing/src/components/fields.tsx +63 -0
- package/templates/landing/src/content.ts +22 -0
- package/templates/landing/src/index.css +119 -0
- package/templates/landing/src/lib/usebecky.ts +11 -0
- package/templates/landing/src/lib/waitlist.ts +46 -0
- package/templates/landing/src/main.tsx +12 -0
- package/templates/landing/src/vite-env.d.ts +6 -0
- package/templates/landing/tsconfig.json +19 -0
- package/templates/landing/usebecky.template.json +20 -0
- package/templates/landing/vite.config.ts +10 -0
- package/templates/notes/README.md +68 -0
- package/templates/notes/_env.example +4 -0
- package/templates/notes/_gitignore +9 -0
- package/templates/notes/index.html +15 -0
- package/templates/notes/package.json +28 -0
- package/templates/notes/public/icon.svg +1 -0
- package/templates/notes/src/App.tsx +35 -0
- package/templates/notes/src/brand.ts +7 -0
- package/templates/notes/src/components/Composer.tsx +113 -0
- package/templates/notes/src/components/NoteEntry.tsx +151 -0
- package/templates/notes/src/components/Notes.tsx +163 -0
- package/templates/notes/src/components/Setup.tsx +44 -0
- package/templates/notes/src/components/SignIn.tsx +112 -0
- package/templates/notes/src/components/icons.tsx +54 -0
- package/templates/notes/src/index.css +105 -0
- package/templates/notes/src/lib/notes.ts +68 -0
- package/templates/notes/src/lib/usebecky.ts +9 -0
- package/templates/notes/src/main.tsx +22 -0
- package/templates/notes/src/vite-env.d.ts +6 -0
- package/templates/notes/tsconfig.json +19 -0
- package/templates/notes/usebecky.template.json +34 -0
- package/templates/notes/vite.config.ts +10 -0
- package/templates/saas/README.md +69 -0
- package/templates/saas/_env.example +10 -0
- package/templates/saas/_gitignore +11 -0
- package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
- package/templates/saas/app/(app)/account/page.tsx +71 -0
- package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
- package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
- package/templates/saas/app/(app)/layout.tsx +29 -0
- package/templates/saas/app/(app)/premium/page.tsx +62 -0
- package/templates/saas/app/auth/callback/page.tsx +33 -0
- package/templates/saas/app/globals.css +143 -0
- package/templates/saas/app/icon.svg +1 -0
- package/templates/saas/app/layout.tsx +20 -0
- package/templates/saas/app/page.tsx +87 -0
- package/templates/saas/app/pricing/Plans.tsx +133 -0
- package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
- package/templates/saas/app/pricing/page.tsx +21 -0
- package/templates/saas/app/setup/page.tsx +34 -0
- package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
- package/templates/saas/app/sign-in/page.tsx +21 -0
- package/templates/saas/brand.ts +10 -0
- package/templates/saas/components/AppNav.tsx +45 -0
- package/templates/saas/components/Logo.tsx +22 -0
- package/templates/saas/components/SiteHeader.tsx +50 -0
- package/templates/saas/components/Status.tsx +15 -0
- package/templates/saas/lib/session.ts +26 -0
- package/templates/saas/lib/usebecky.ts +11 -0
- package/templates/saas/next-env.d.ts +5 -0
- package/templates/saas/next.config.ts +5 -0
- package/templates/saas/package.json +26 -0
- package/templates/saas/postcss.config.mjs +3 -0
- package/templates/saas/tsconfig.json +21 -0
- package/templates/saas/usebecky.template.json +31 -0
package/dist/create.js
ADDED
|
@@ -0,0 +1,842 @@
|
|
|
1
|
+
// `npm create usebecky@latest` / `npx create-usebecky` / `npx usebecky create`:
|
|
2
|
+
// name → starter → connect → copy → install → keys → tables → AI skill → summary.
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import net from 'node:net';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { writeKeys } from "./keys.js";
|
|
11
|
+
import { createPlatform, DEFAULT_API, offlineHint, readConfig, saveConfig, tokenFor, VERSION } from "./platform.js";
|
|
12
|
+
import { detectPackageManager, explainInstallFailure, installArgs, installCommand, PACKAGE_MANAGERS, runCommand, runScript } from "./pm.js";
|
|
13
|
+
import { createPrompts, visible } from "./prompts.js";
|
|
14
|
+
import { copyTemplate, inspectDir, toDisplayName, toSlug } from "./scaffold.js";
|
|
15
|
+
import { applySetup, missingTables } from "./setup.js";
|
|
16
|
+
import { findSkillSource, installSkill, SKILL_TARGET, writeAgentsFile } from "./shared/ai.js";
|
|
17
|
+
import { EXTENSION_SKILL_NAME, EXTENSION_SKILL_TARGET, installExtensionSkill, writeExtensionAgents } from "./shared/extension-skill.js";
|
|
18
|
+
import { c } from "./shared/ui.js";
|
|
19
|
+
import { loadTemplates, templatesDir } from "./templates.js";
|
|
20
|
+
export class UsageError extends Error {
|
|
21
|
+
}
|
|
22
|
+
const VALUE_FLAGS = {
|
|
23
|
+
'--template': 'template',
|
|
24
|
+
'-t': 'template',
|
|
25
|
+
'--project': 'project',
|
|
26
|
+
'-p': 'project',
|
|
27
|
+
'--api-url': 'apiUrl',
|
|
28
|
+
'--name': 'name',
|
|
29
|
+
'--pm': 'pm',
|
|
30
|
+
'--sdk': 'sdk',
|
|
31
|
+
};
|
|
32
|
+
export function parseArgs(argv) {
|
|
33
|
+
const flags = { newProject: false, skipConnect: false, install: true, ai: true, yes: false, help: false, version: false };
|
|
34
|
+
for (let i = 0; i < argv.length; i++) {
|
|
35
|
+
const arg = argv[i];
|
|
36
|
+
const eq = arg.startsWith('--') ? arg.indexOf('=') : -1;
|
|
37
|
+
const name = eq > 0 ? arg.slice(0, eq) : arg;
|
|
38
|
+
const field = VALUE_FLAGS[name];
|
|
39
|
+
if (field) {
|
|
40
|
+
const value = eq > 0 ? arg.slice(eq + 1) : argv[++i];
|
|
41
|
+
if (value === undefined || value === '' || (eq < 0 && value.startsWith('-')))
|
|
42
|
+
throw new UsageError(`${name} needs a value, for example: ${name} ${field === 'template' ? 'notes' : field === 'apiUrl' ? DEFAULT_API : '...'}`);
|
|
43
|
+
flags[field] = value;
|
|
44
|
+
}
|
|
45
|
+
else if (name === '--new-project')
|
|
46
|
+
flags.newProject = true;
|
|
47
|
+
else if (name === '--skip-connect' || name === '--no-connect')
|
|
48
|
+
flags.skipConnect = true;
|
|
49
|
+
else if (name === '--no-install' || name === '--skip-install')
|
|
50
|
+
flags.install = false;
|
|
51
|
+
else if (name === '--no-ai' || name === '--skip-ai')
|
|
52
|
+
flags.ai = false;
|
|
53
|
+
else if (name === '--yes' || name === '-y')
|
|
54
|
+
flags.yes = true;
|
|
55
|
+
else if (name === '--help' || name === '-h')
|
|
56
|
+
flags.help = true;
|
|
57
|
+
else if (name === '--version' || name === '-v')
|
|
58
|
+
flags.version = true;
|
|
59
|
+
else if (arg.startsWith('-'))
|
|
60
|
+
throw new UsageError(`Unknown option ${name}. Run with --help to see the options.`);
|
|
61
|
+
else if (flags.dir === undefined)
|
|
62
|
+
flags.dir = arg;
|
|
63
|
+
else
|
|
64
|
+
throw new UsageError(`Expected one folder name, got "${flags.dir}" and "${arg}". Put quotes around names with spaces.`);
|
|
65
|
+
}
|
|
66
|
+
const connect = [flags.newProject && '--new-project', flags.project && '--project', flags.skipConnect && '--skip-connect'].filter(Boolean);
|
|
67
|
+
if (connect.length > 1)
|
|
68
|
+
throw new UsageError(`Use only one of ${connect.join(', ')}.`);
|
|
69
|
+
if (flags.pm && !PACKAGE_MANAGERS.includes(flags.pm))
|
|
70
|
+
throw new UsageError(`--pm must be one of ${PACKAGE_MANAGERS.join(', ')}.`);
|
|
71
|
+
return flags;
|
|
72
|
+
}
|
|
73
|
+
export function helpText(templates) {
|
|
74
|
+
const width = Math.max(8, ...templates.map((t) => t.id.length));
|
|
75
|
+
return `
|
|
76
|
+
${c.bold(c.magenta('create-usebecky'))} ${c.dim(`v${VERSION}`)}: a working app, connected to usebecky, in one command.
|
|
77
|
+
|
|
78
|
+
${c.bold('Usage:')}
|
|
79
|
+
npm create usebecky@latest ${c.dim('[folder] -- [options]')}
|
|
80
|
+
npx create-usebecky ${c.dim('[folder] [options]')}
|
|
81
|
+
npx usebecky create ${c.dim('[folder] [options]')}
|
|
82
|
+
|
|
83
|
+
${c.bold('Starters:')}
|
|
84
|
+
${templates.map((t) => ` ${c.cyan(t.id.padEnd(width))} ${t.description} ${c.dim(`(${t.stack})`)}`).join('\n')}
|
|
85
|
+
|
|
86
|
+
${c.bold('Options:')}
|
|
87
|
+
--template <name> Which starter to use (${templates.map((t) => t.id).join(', ')})
|
|
88
|
+
--new-project Create a new usebecky project for the app
|
|
89
|
+
--project <ref> Use one of your existing projects instead
|
|
90
|
+
--skip-connect Don't connect it now (later: \`npx usebecky init\` in the folder)
|
|
91
|
+
--no-install Don't install packages
|
|
92
|
+
--no-ai Don't teach your AI assistant about usebecky
|
|
93
|
+
--api-url <url> usebecky API (env USEBECKY_API_URL, default ${DEFAULT_API})
|
|
94
|
+
--name <text> App name shown in the app (default: made from the folder name)
|
|
95
|
+
--pm <name> npm, pnpm, yarn or bun (default: the one you ran this with)
|
|
96
|
+
--sdk <path> Use the usebecky you built from the source (the .tgz from npm pack)
|
|
97
|
+
until it's on npm, e.g. --sdk ~/usebecky/packages/sdk/usebecky-0.1.0.tgz
|
|
98
|
+
-y, --yes Don't ask anything; use the defaults
|
|
99
|
+
-h, --help Show this help
|
|
100
|
+
`;
|
|
101
|
+
}
|
|
102
|
+
const MIN_NODE = [22, 18];
|
|
103
|
+
export async function create(argv, ctx = {}) {
|
|
104
|
+
const env = ctx.env ?? process.env;
|
|
105
|
+
const cwd = ctx.cwd ?? process.cwd();
|
|
106
|
+
const output = ctx.io?.output ?? process.stdout;
|
|
107
|
+
const input = ctx.io?.input ?? process.stdin;
|
|
108
|
+
const write = (s = '') => output.write(s + '\n');
|
|
109
|
+
const ok = (s) => write(`${c.green('✔')} ${s}`);
|
|
110
|
+
const info = (s) => write(`${c.blue('ℹ')} ${s}`);
|
|
111
|
+
const warn = (s) => write(`${c.yellow('!')} ${s}`);
|
|
112
|
+
const fail = (s, hint) => {
|
|
113
|
+
write(`${c.red('✖')} ${s}`);
|
|
114
|
+
if (hint)
|
|
115
|
+
write(` ${c.dim(hint)}`);
|
|
116
|
+
};
|
|
117
|
+
let templates;
|
|
118
|
+
try {
|
|
119
|
+
templates = loadTemplates(ctx.templatesDir ?? templatesDir());
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
fail(`This copy of create-usebecky is broken: ${err.message}`, 'Run it again with: npx create-usebecky@latest');
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
let flags;
|
|
126
|
+
try {
|
|
127
|
+
flags = parseArgs(argv);
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
if (!(err instanceof UsageError))
|
|
131
|
+
throw err;
|
|
132
|
+
fail(err.message);
|
|
133
|
+
return 1;
|
|
134
|
+
}
|
|
135
|
+
if (flags.version) {
|
|
136
|
+
write(VERSION);
|
|
137
|
+
return 0;
|
|
138
|
+
}
|
|
139
|
+
if (flags.help) {
|
|
140
|
+
write(helpText(templates));
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
const io = { input, output, yes: flags.yes || !!ctx.io?.yes || isTruthy(env.CI) };
|
|
144
|
+
const ui = createPrompts(io);
|
|
145
|
+
try {
|
|
146
|
+
return await flow(ui);
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
ui.close();
|
|
150
|
+
}
|
|
151
|
+
async function flow(ui) {
|
|
152
|
+
write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim(`create v${VERSION}`)}\n`);
|
|
153
|
+
const nodeVersion = ctx.nodeVersion ?? process.versions.node;
|
|
154
|
+
if (!atLeast(nodeVersion, MIN_NODE)) {
|
|
155
|
+
fail(`create-usebecky needs Node.js ${MIN_NODE.join('.')} or newer, and this computer has ${nodeVersion}.`, 'Install the LTS version from https://nodejs.org, open a new terminal, and run the command again.');
|
|
156
|
+
return 1;
|
|
157
|
+
}
|
|
158
|
+
if (!templates.length) {
|
|
159
|
+
fail('No starters were found in this copy of create-usebecky.', 'Run it again with: npx create-usebecky@latest');
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
if (flags.template && !templates.some((t) => t.id === flags.template)) {
|
|
163
|
+
fail(`There is no starter called "${flags.template}".`, `Pick one of: ${templates.map((t) => t.id).join(', ')}`);
|
|
164
|
+
return 1;
|
|
165
|
+
}
|
|
166
|
+
// --sdk: check the path before anything is created, so a typo doesn't end in a failed install.
|
|
167
|
+
const sdk = flags.sdk ? resolveSdkSpec(flags.sdk, cwd) : undefined;
|
|
168
|
+
if (sdk?.path) {
|
|
169
|
+
const problem = checkSdkPath(sdk.path);
|
|
170
|
+
if (problem) {
|
|
171
|
+
fail(problem, 'Build it first: cd ~/usebecky/packages/sdk && npm install && npm run build && npm pack, then pass the usebecky-0.1.0.tgz it makes. Nothing was changed.');
|
|
172
|
+
return 1;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (!io.yes && !flags.dir)
|
|
176
|
+
write(`${c.dim('Answer a few questions, or press Enter to take the suggestion in (brackets).')}\n`);
|
|
177
|
+
// ---- 1. Name and folder ------------------------------------------------------------
|
|
178
|
+
const folder = await askFolder(ui);
|
|
179
|
+
if (!folder)
|
|
180
|
+
return 1;
|
|
181
|
+
const { target } = folder;
|
|
182
|
+
const slug = toSlug(path.basename(target)) || 'my-app';
|
|
183
|
+
const appName = flags.name?.trim() || toDisplayName(folder.typed);
|
|
184
|
+
const shownPath = displayPath(cwd, target);
|
|
185
|
+
// ---- 2. Starter ------------------------------------------------------------------------
|
|
186
|
+
const nameWidth = Math.max(...templates.map((t) => t.name.length));
|
|
187
|
+
const manifest = flags.template
|
|
188
|
+
? templates.find((t) => t.id === flags.template)
|
|
189
|
+
: await ui.select('Pick a starter', templates.map((t) => ({ label: t.name.padEnd(nameWidth), value: t, hint: `${t.description} (${t.stack})` })), 0);
|
|
190
|
+
if (flags.template && !io.yes)
|
|
191
|
+
ok(`${c.bold('Starter')} ${c.cyan(manifest.name)}`);
|
|
192
|
+
// The extension starter isn't an app on a project: customers install extensions on theirs.
|
|
193
|
+
const usesProject = manifest.project !== false;
|
|
194
|
+
if (!usesProject && (flags.newProject || flags.project)) {
|
|
195
|
+
fail(`The ${manifest.name} starter doesn't use a usebecky project of its own: customers install extensions on their projects.`, 'Leave out --new-project and --project. Nothing was changed.');
|
|
196
|
+
return 1;
|
|
197
|
+
}
|
|
198
|
+
// ---- 3. Connect --------------------------------------------------------------------------
|
|
199
|
+
const apiUrl = (flags.apiUrl ?? env.USEBECKY_API_URL ?? DEFAULT_API).replace(/\/+$/, '');
|
|
200
|
+
if (!/^https?:\/\/[^/]+/i.test(apiUrl)) {
|
|
201
|
+
fail(`"${apiUrl}" is not a web address.`, 'Pass the API URL from Dashboard → Settings → API keys, e.g. --api-url https://api.example.com');
|
|
202
|
+
return 1;
|
|
203
|
+
}
|
|
204
|
+
const configDir = defaultConfigDir(ctx.configDir ?? env.USEBECKY_CONFIG_DIR);
|
|
205
|
+
const configFile = path.join(configDir, 'config.json');
|
|
206
|
+
const platform = createPlatform(apiUrl, ctx.fetch ?? fetch);
|
|
207
|
+
const connection = usesProject ? await connect(ui, platform, configFile, manifest, appName) : 'skip';
|
|
208
|
+
if (connection === 'abort')
|
|
209
|
+
return 1;
|
|
210
|
+
let failed = false;
|
|
211
|
+
// ---- 4. Copy -----------------------------------------------------------------------------
|
|
212
|
+
const sdkSpec = sdk?.spec;
|
|
213
|
+
try {
|
|
214
|
+
const copied = copyTemplate(path.join(ctx.templatesDir ?? templatesDir(), manifest.id), target, manifest, { appName, slug, sdkSpec });
|
|
215
|
+
ok(`Copied the ${c.bold(manifest.name)} starter into ${c.bold(shownPath)} ${c.dim(`(${copied.files} files)`)}`);
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
fail(`Could not copy the starter into ${shownPath}: ${err.message}`, 'Check that you can write to this folder, then try again.');
|
|
219
|
+
return 1;
|
|
220
|
+
}
|
|
221
|
+
// ---- 5. Install --------------------------------------------------------------------------
|
|
222
|
+
const pm = flags.pm ?? detectPackageManager(env.npm_config_user_agent);
|
|
223
|
+
let installed = false;
|
|
224
|
+
if (manifest.kind === 'node' && flags.install) {
|
|
225
|
+
const spin = ui.spinner(`Installing packages with ${pm} ${c.dim('(about a minute)')}`);
|
|
226
|
+
const result = await (ctx.runCommand ?? runCommand)(pm, installArgs(pm), target);
|
|
227
|
+
if (result.code === 0) {
|
|
228
|
+
installed = true;
|
|
229
|
+
spin.succeed(`Installed packages with ${pm} ${c.dim(`(${spin.seconds()}s)`)}`);
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
failed = true;
|
|
233
|
+
const reason = result.notFound ? `${pm} is not installed on this computer.` : explainInstallFailure(result.output);
|
|
234
|
+
spin.fail(`${reason} Your app is ready otherwise.`);
|
|
235
|
+
const tail = result.output.trim().split('\n').slice(-8);
|
|
236
|
+
if (tail.length && tail[0])
|
|
237
|
+
for (const line of tail)
|
|
238
|
+
write(` ${c.dim(line.slice(0, 160))}`);
|
|
239
|
+
write(` ${c.dim(`Fix the problem, then run ${installCommand(pm)} in ${shownPath}.`)}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else if (manifest.kind === 'node')
|
|
243
|
+
info(`Skipped installing packages ${c.dim(`(run ${installCommand(pm)} in ${shownPath} later)`)}`);
|
|
244
|
+
// ---- 6 + 7. Keys, then tables and buckets --------------------------------------------------
|
|
245
|
+
let project = null;
|
|
246
|
+
let projectUrl;
|
|
247
|
+
if (connection !== 'skip') {
|
|
248
|
+
project = connection.project;
|
|
249
|
+
const keys = await platform.keys(project.ref);
|
|
250
|
+
if (keys.error) {
|
|
251
|
+
failed = true;
|
|
252
|
+
fail(`Could not load the API keys for ${project.name}: ${keys.error.message}`, `Connect it later with: cd ${shownPath} && npx usebecky init --project ${project.ref}`);
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
const k = { url: keys.data.url, publishableKey: keys.data.publishable_key, secretKey: keys.data.secret_key };
|
|
256
|
+
projectUrl = k.url;
|
|
257
|
+
const written = await writeKeys(target, manifest, k);
|
|
258
|
+
ok(`Wrote your project's URL and keys to ${c.bold(written.file)} ${c.dim(`(${written.names.join(', ')})`)}`);
|
|
259
|
+
if (written.gitignoreAdded.length)
|
|
260
|
+
ok(`Kept ${written.gitignoreAdded.join(' and ')} out of git ${c.dim('(.gitignore)')}`);
|
|
261
|
+
const setup = await applySetup(platform, project.ref, manifest.setup);
|
|
262
|
+
// A new project made from the matching template already has most of it: only report what changed.
|
|
263
|
+
for (const step of setup.steps)
|
|
264
|
+
if (!(connection.created && step.status === 'exists'))
|
|
265
|
+
printStep(step);
|
|
266
|
+
if (!setup.ok)
|
|
267
|
+
failed = true;
|
|
268
|
+
if (Object.keys(setup.env).length) {
|
|
269
|
+
const more = await writeKeys(target, manifest, k, setup.env);
|
|
270
|
+
if (more.names.length)
|
|
271
|
+
ok(`Added ${more.names.join(', ')} to ${c.bold(more.file)}`);
|
|
272
|
+
}
|
|
273
|
+
const missing = connection.created ? [] : await missingTables(platform, project.ref, manifest.requires?.tables ?? []);
|
|
274
|
+
if (missing?.length) {
|
|
275
|
+
warn(`${project.name} has no ${listWords(missing.map((t) => `"${t}"`))} table${missing.length > 1 ? 's' : ''}, which this starter uses.`);
|
|
276
|
+
write(` ${c.dim(`Projects with the ${manifest.serverTemplate} ready-made setup have ${missing.length > 1 ? 'them' : 'it'}. Create a new project with --new-project, or add ${missing.length > 1 ? 'them' : 'it'} in the dashboard.`)}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
else if (usesProject) {
|
|
281
|
+
info(`Not connected yet. ${c.dim(`When you're ready: cd ${shownPath} && npx usebecky init`)}`);
|
|
282
|
+
}
|
|
283
|
+
// ---- 8. AI skill ---------------------------------------------------------------------------
|
|
284
|
+
if (flags.ai && manifest.skill === 'usebecky-extension') {
|
|
285
|
+
const source = ctx.extensionSkillDir ?? extensionSkillFrom(target) ?? bundledExtensionSkill();
|
|
286
|
+
if (source) {
|
|
287
|
+
try {
|
|
288
|
+
installExtensionSkill(source, target, false);
|
|
289
|
+
const agents = writeExtensionAgents(target);
|
|
290
|
+
ok(`Taught your AI assistant to build usebecky extensions ${c.dim(`(${EXTENSION_SKILL_TARGET}, ${agents.path})`)}`);
|
|
291
|
+
}
|
|
292
|
+
catch (err) {
|
|
293
|
+
warn(`Could not add the AI skill: ${err.message}. ${c.dim(`Run npx @usebecky/extension ai in ${shownPath} later.`)}`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
else
|
|
297
|
+
warn(`Skipped the AI skill ${c.dim(`(run npx @usebecky/extension ai in ${shownPath} after installing)`)}`);
|
|
298
|
+
}
|
|
299
|
+
else if (flags.ai) {
|
|
300
|
+
const source = ctx.skillDir ?? skillFrom(target) ?? bundledSkill();
|
|
301
|
+
if (source) {
|
|
302
|
+
try {
|
|
303
|
+
installSkill(source, target, false);
|
|
304
|
+
const agents = writeAgentsFile(target, false);
|
|
305
|
+
ok(`Taught your AI assistant about usebecky ${c.dim(`(${SKILL_TARGET}, ${agents.path})`)}`);
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
warn(`Could not add the AI skill: ${err.message}. ${c.dim(`Run npx usebecky ai in ${shownPath} later.`)}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
else
|
|
312
|
+
warn(`Skipped the AI skill ${c.dim(`(run npx usebecky ai in ${shownPath} after installing)`)}`);
|
|
313
|
+
}
|
|
314
|
+
// ---- 9. Summary ------------------------------------------------------------------------------
|
|
315
|
+
const cfg = project ? await platform.config() : null;
|
|
316
|
+
const dashboardBase = cfg?.data?.dashboard_url?.replace(/\/+$/, '');
|
|
317
|
+
const dashboard = project && dashboardBase ? `${dashboardBase}/project/${project.ref}` : null;
|
|
318
|
+
const port = manifest.run.port;
|
|
319
|
+
const busy = port ? !(await (ctx.portFree ?? portFree)(port)) : false;
|
|
320
|
+
// The app talks to the project's URL (or, not connected yet, to the API we used).
|
|
321
|
+
const localApi = isLocalUrl(projectUrl ?? apiUrl);
|
|
322
|
+
await summary({ manifest, appName, shownPath, target, project, dashboard, pm, installed, connected: connection !== 'skip', usesProject, busy, dashboardBase, failed, localApi });
|
|
323
|
+
return failed ? 1 : 0;
|
|
324
|
+
}
|
|
325
|
+
// -------------------------------------------------------------------------------------------
|
|
326
|
+
/** Ask for the name until it points at a missing or empty folder. Returns the folder and the name as typed. */
|
|
327
|
+
async function askFolder(ui) {
|
|
328
|
+
let suggestion = templates.find((t) => t.id === flags.template)?.defaultName ?? 'my-app';
|
|
329
|
+
let answer = flags.dir;
|
|
330
|
+
for (;;) {
|
|
331
|
+
if (answer === undefined) {
|
|
332
|
+
answer = await ui.text('What should your app be called?', {
|
|
333
|
+
default: suggestion,
|
|
334
|
+
validate: (v) => (v === '.' || toSlug(path.basename(v)) ? null : 'Use at least one letter or number.'),
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
else if (!io.yes && flags.dir === answer)
|
|
338
|
+
ok(`${c.bold('What should your app be called?')} ${c.cyan(answer)}`);
|
|
339
|
+
const typed = answer === '.' ? path.basename(cwd) : path.basename(answer);
|
|
340
|
+
const slug = toSlug(typed);
|
|
341
|
+
if (!slug) {
|
|
342
|
+
fail(`"${answer}" can't be used as a folder name.`, 'Use at least one letter or number.');
|
|
343
|
+
if (io.yes)
|
|
344
|
+
return null;
|
|
345
|
+
answer = undefined;
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const target = answer === '.' ? cwd : path.resolve(cwd, path.dirname(answer), slug);
|
|
349
|
+
if (answer !== '.' && slug !== typed)
|
|
350
|
+
info(`The folder will be called ${c.bold(slug)}`);
|
|
351
|
+
const state = inspectDir(target);
|
|
352
|
+
if (state.state === 'missing' || state.state === 'empty')
|
|
353
|
+
return { target, typed };
|
|
354
|
+
const shown = displayPath(cwd, target);
|
|
355
|
+
if (state.state === 'file')
|
|
356
|
+
fail(`${shown} is a file, not a folder.`, io.yes ? 'Pick another name. Nothing was changed.' : 'Pick another name.');
|
|
357
|
+
else {
|
|
358
|
+
const list = state.entries.slice(0, 3).join(', ') + (state.entries.length > 3 ? ` and ${state.entries.length - 3} more` : '');
|
|
359
|
+
fail(`The folder ${shown} already exists and isn't empty ${c.dim(`(${list})`)}.`, io.yes ? 'Pick another folder name, or empty that folder first. Nothing was changed.' : 'Pick another name, or press Ctrl+C to stop.');
|
|
360
|
+
}
|
|
361
|
+
if (io.yes)
|
|
362
|
+
return null;
|
|
363
|
+
suggestion = nextFreeName(cwd, slug);
|
|
364
|
+
answer = undefined;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async function connect(ui, platform, configFile, manifest, appName) {
|
|
368
|
+
const explicit = flags.newProject || !!flags.project;
|
|
369
|
+
const config = readConfig(configFile);
|
|
370
|
+
let token = tokenFor(config, platform.url, env);
|
|
371
|
+
let mode;
|
|
372
|
+
if (flags.skipConnect)
|
|
373
|
+
return 'skip';
|
|
374
|
+
if (flags.project)
|
|
375
|
+
mode = 'existing';
|
|
376
|
+
else if (flags.newProject)
|
|
377
|
+
mode = 'new';
|
|
378
|
+
else if (io.yes)
|
|
379
|
+
mode = token ? 'new' : 'skip';
|
|
380
|
+
else
|
|
381
|
+
mode = await ui.select('Connect it to usebecky?', [
|
|
382
|
+
{ label: 'Create a new project', value: 'new', hint: `with the ${manifest.serverTemplate} ready-made setup, ready for this starter (the Free plan includes 1 project)` },
|
|
383
|
+
{ label: 'Use one of my projects', value: 'existing', hint: existingHint(manifest) },
|
|
384
|
+
{ label: 'Skip for now', value: 'skip', hint: 'connect later with npx usebecky init' },
|
|
385
|
+
], 0);
|
|
386
|
+
if (mode === 'skip') {
|
|
387
|
+
if (io.yes && !token)
|
|
388
|
+
info(`Not signed in to usebecky, so the app won't be connected yet. ${c.dim('Sign in with npx usebecky login, or pass --new-project.')}`);
|
|
389
|
+
return 'skip';
|
|
390
|
+
}
|
|
391
|
+
// Is the API reachable?
|
|
392
|
+
if (!(await platform.health())) {
|
|
393
|
+
fail(`Could not reach usebecky at ${platform.url}.`, offlineHint(platform.url));
|
|
394
|
+
if (explicit) {
|
|
395
|
+
write(` ${c.dim('Nothing was created. To make the app without connecting it, use --skip-connect instead.')}`);
|
|
396
|
+
return 'abort';
|
|
397
|
+
}
|
|
398
|
+
if (io.yes) {
|
|
399
|
+
info('Making the app without connecting it.');
|
|
400
|
+
return 'skip';
|
|
401
|
+
}
|
|
402
|
+
return (await ui.confirm('Make the app without connecting it for now?', true)) ? 'skip' : 'abort';
|
|
403
|
+
}
|
|
404
|
+
// Signed in?
|
|
405
|
+
platform.setToken(token);
|
|
406
|
+
let projects = null;
|
|
407
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
408
|
+
if (!token) {
|
|
409
|
+
if (io.yes) {
|
|
410
|
+
fail("You're not signed in to usebecky.", 'Run `npx usebecky login` first (or set USEBECKY_ACCESS_TOKEN), or use --skip-connect. Nothing was created.');
|
|
411
|
+
return 'abort';
|
|
412
|
+
}
|
|
413
|
+
token = await login(ui, platform, configFile);
|
|
414
|
+
if (!token) {
|
|
415
|
+
if (await ui.confirm('Make the app without connecting it for now?', true))
|
|
416
|
+
return 'skip';
|
|
417
|
+
return 'abort';
|
|
418
|
+
}
|
|
419
|
+
platform.setToken(token);
|
|
420
|
+
}
|
|
421
|
+
const r = await platform.projects();
|
|
422
|
+
if (!r.error) {
|
|
423
|
+
projects = r.data;
|
|
424
|
+
break;
|
|
425
|
+
}
|
|
426
|
+
if (r.error.status === 401) {
|
|
427
|
+
warn(`Your usebecky login has expired${io.yes ? '' : '. Please sign in again'}.`);
|
|
428
|
+
token = undefined;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
printApiError(r.error);
|
|
432
|
+
return 'abort';
|
|
433
|
+
}
|
|
434
|
+
if (!projects)
|
|
435
|
+
return 'abort';
|
|
436
|
+
if (mode === 'existing') {
|
|
437
|
+
if (flags.project) {
|
|
438
|
+
const p = await platform.project(flags.project);
|
|
439
|
+
if (p.error) {
|
|
440
|
+
if (p.error.status === 404)
|
|
441
|
+
fail(`You have no project with the ref "${flags.project}".`, 'See your projects with `npx usebecky projects`, or use --new-project.');
|
|
442
|
+
else
|
|
443
|
+
printApiError(p.error);
|
|
444
|
+
return 'abort';
|
|
445
|
+
}
|
|
446
|
+
ok(`Using your project ${c.bold(p.data.name)} ${c.dim(p.data.ref)}`);
|
|
447
|
+
return { project: p.data, created: false };
|
|
448
|
+
}
|
|
449
|
+
if (!projects.length)
|
|
450
|
+
info("You don't have any projects yet, so let's create one.");
|
|
451
|
+
else {
|
|
452
|
+
const p = await pickProject(ui, projects, true);
|
|
453
|
+
if (p)
|
|
454
|
+
return { project: p, created: false };
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
// New project
|
|
458
|
+
const spin = ui.spinner(`Creating your project from the ${c.bold(manifest.serverTemplate)} template`);
|
|
459
|
+
const created = await platform.createProject(appName.length >= 2 ? appName : `${appName} app`, manifest.serverTemplate);
|
|
460
|
+
if (created.error) {
|
|
461
|
+
spin.fail(`Could not create the project: ${created.error.message}`);
|
|
462
|
+
if (created.error.hint)
|
|
463
|
+
write(` ${c.dim(created.error.hint)}`);
|
|
464
|
+
// Usually the plan's project limit (the Free plan includes 2, e.g. after the Quickstart and the
|
|
465
|
+
// Tutorial). One of the projects the person already has works too.
|
|
466
|
+
if (projects.length) {
|
|
467
|
+
if (!io.yes && (await ui.confirm('Use one of your projects instead?', true))) {
|
|
468
|
+
const p = (await pickProject(ui, projects, false));
|
|
469
|
+
return { project: p, created: false };
|
|
470
|
+
}
|
|
471
|
+
if (io.yes) {
|
|
472
|
+
const some = projects.slice(0, 3).map((p) => `${p.name} (${p.ref})`).join(', ') + (projects.length > 3 ? ', ...' : '');
|
|
473
|
+
write(` ${c.dim(`Or use one of your projects: run it again with --project <ref> instead. Yours: ${some}.`)}`);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
write(` ${c.dim('Nothing was copied. Try again, or add --skip-connect to make the app without a project.')}`);
|
|
477
|
+
return 'abort';
|
|
478
|
+
}
|
|
479
|
+
spin.succeed(`Created the project ${c.bold(created.data.name)} ${c.dim(`(${created.data.ref}, ${manifest.serverTemplate} template)`)}`);
|
|
480
|
+
// Sign-in emails and redirects should open this app, and emails should carry its name.
|
|
481
|
+
const patch = { app_name: appName };
|
|
482
|
+
if (manifest.run.url)
|
|
483
|
+
patch.site_url = manifest.run.url;
|
|
484
|
+
const r = await platform.request('PATCH', `/projects/${created.data.ref}/auth/config`, patch);
|
|
485
|
+
if (r.error)
|
|
486
|
+
warn(`Could not set the sign-in settings: ${r.error.message} ${c.dim('(change them in Dashboard → Auth → Settings)')}`);
|
|
487
|
+
return { project: created.data, created: true };
|
|
488
|
+
}
|
|
489
|
+
/** "Which project?" Returns null when the person picks "+ Create a new project" (only offered with `allowNew`). */
|
|
490
|
+
async function pickProject(ui, projects, allowNew) {
|
|
491
|
+
const NEW = '__new__';
|
|
492
|
+
const choices = projects.map((p) => ({ label: p.name, value: p.ref, hint: `${p.ref}${p.template && p.template !== 'blank' ? `, ${p.template} setup` : ''}` }));
|
|
493
|
+
const choice = await ui.select('Which project?', allowNew ? [...choices, { label: '+ Create a new project', value: NEW }] : choices, 0);
|
|
494
|
+
return projects.find((x) => x.ref === choice) ?? null;
|
|
495
|
+
}
|
|
496
|
+
/** Signs in through the browser like `npx usebecky login` (every account: Google, GitHub, password, passkeys,
|
|
497
|
+
* two-factor). A server without it (an older one) asks for email and password instead. */
|
|
498
|
+
async function login(ui, platform, configFile) {
|
|
499
|
+
write(`${c.bold('Sign in to usebecky')} ${c.dim(`(${platform.url})`)}`);
|
|
500
|
+
const saved = readConfig(configFile).deviceId;
|
|
501
|
+
const deviceId = saved && /^[A-Za-z0-9_-]{16,100}$/.test(saved) ? saved : crypto.randomBytes(18).toString('base64url');
|
|
502
|
+
const signedIn = (token, account, fallbackEmail) => {
|
|
503
|
+
const email = account?.email ?? fallbackEmail;
|
|
504
|
+
saveConfig(configFile, { ...readConfig(configFile), apiUrl: platform.url, token, email, deviceId });
|
|
505
|
+
ok(`Signed in as ${c.bold(email ?? 'your account')}`);
|
|
506
|
+
// A new email account: building works now; upgrading, invites and newsletters wait for the click.
|
|
507
|
+
if (account?.email_verified === false)
|
|
508
|
+
write(c.dim(' Confirm your email address: click the link we sent you.'));
|
|
509
|
+
return token;
|
|
510
|
+
};
|
|
511
|
+
const started = await platform.startCliLogin(deviceId);
|
|
512
|
+
if (started.error?.status === 404) {
|
|
513
|
+
const email = await ui.text('Email:');
|
|
514
|
+
if (!email)
|
|
515
|
+
return undefined;
|
|
516
|
+
const password = await ui.password('Password:');
|
|
517
|
+
let r = await platform.login(email, password, deviceId);
|
|
518
|
+
if (r.error?.code === 'invalid_credentials' && (await ui.confirm(`No account matched. Create a new account for ${email}?`, false))) {
|
|
519
|
+
r = await platform.signup(email, password, deviceId);
|
|
520
|
+
}
|
|
521
|
+
if (r.error) {
|
|
522
|
+
printApiError(r.error);
|
|
523
|
+
return undefined;
|
|
524
|
+
}
|
|
525
|
+
return signedIn(r.data.token, r.data.account, email);
|
|
526
|
+
}
|
|
527
|
+
if (started.error) {
|
|
528
|
+
printApiError(started.error);
|
|
529
|
+
return undefined;
|
|
530
|
+
}
|
|
531
|
+
const s = started.data;
|
|
532
|
+
// A terminal of its own opens the browser; a pipe or CI only print the link (open it on any device).
|
|
533
|
+
const open = !!output.isTTY;
|
|
534
|
+
write('');
|
|
535
|
+
write(` Code: ${c.bold(s.user_code)}`);
|
|
536
|
+
write(` ${open ? 'Opening' : 'Open'} ${c.cyan(s.verification_url)}`);
|
|
537
|
+
write('');
|
|
538
|
+
if (open)
|
|
539
|
+
(ctx.openUrl ?? openBrowser)(s.verification_url);
|
|
540
|
+
write(c.dim(' Waiting for you to click Allow… (Ctrl+C to stop)'));
|
|
541
|
+
const sleep = ctx.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
542
|
+
const deadline = Date.now() + Math.max(60, s.expires_in || 600) * 1000;
|
|
543
|
+
const interval = Math.max(1, s.interval || 2) * 1000;
|
|
544
|
+
let wait = interval;
|
|
545
|
+
let failures = 0;
|
|
546
|
+
while (Date.now() < deadline) {
|
|
547
|
+
await sleep(wait);
|
|
548
|
+
const r = await platform.pollCliLogin(s.id);
|
|
549
|
+
if (!r.error)
|
|
550
|
+
return signedIn(r.data.token, r.data.account);
|
|
551
|
+
if (r.error.code === 'authorization_pending') {
|
|
552
|
+
failures = 0;
|
|
553
|
+
wait = interval;
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (r.error.code === 'access_denied') {
|
|
557
|
+
fail('Cancelled in the browser.');
|
|
558
|
+
return undefined;
|
|
559
|
+
}
|
|
560
|
+
if (r.error.code === 'expired_token')
|
|
561
|
+
break;
|
|
562
|
+
// Offline for a moment, too many checks, the server restarting: wait longer and keep waiting.
|
|
563
|
+
if ((r.error.code === 'network_error' || r.error.code === 'timeout' || r.error.code === 'rate_limited' || r.error.status >= 500) && ++failures < 30) {
|
|
564
|
+
wait = Math.min(wait * 2, 15_000);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
printApiError(r.error);
|
|
568
|
+
return undefined;
|
|
569
|
+
}
|
|
570
|
+
fail('The sign-in expired.', 'Run it again to get a new code.');
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
function printApiError(e) {
|
|
574
|
+
fail(e.message, e.hint);
|
|
575
|
+
}
|
|
576
|
+
function printStep(step) {
|
|
577
|
+
const name = c.bold(step.name);
|
|
578
|
+
switch (`${step.kind}:${step.status}`) {
|
|
579
|
+
case 'table:created':
|
|
580
|
+
return ok(`Created the ${name} table ${c.dim(`(${step.detail})`)}`);
|
|
581
|
+
case 'table:exists':
|
|
582
|
+
return info(`The ${name} table is already there`);
|
|
583
|
+
case 'column:created':
|
|
584
|
+
return ok(`Added the column ${name}`);
|
|
585
|
+
case 'realtime:created':
|
|
586
|
+
return ok(`Turned on live updates for ${name}`);
|
|
587
|
+
case 'realtime:exists':
|
|
588
|
+
return;
|
|
589
|
+
case 'bucket:created':
|
|
590
|
+
return ok(`Created the ${name} storage bucket ${c.dim(`(${step.detail})`)}`);
|
|
591
|
+
case 'bucket:exists':
|
|
592
|
+
return info(`The ${name} bucket is already there`);
|
|
593
|
+
case 'policy:created':
|
|
594
|
+
return ok(`Added the file access rule ${name}`);
|
|
595
|
+
case 'policy:exists':
|
|
596
|
+
return;
|
|
597
|
+
case 'form:created':
|
|
598
|
+
return ok(`Created the ${name} form`);
|
|
599
|
+
case 'form:exists':
|
|
600
|
+
return info(`The ${name} form is already there`);
|
|
601
|
+
case 'form:skipped':
|
|
602
|
+
return info(`Skipped the ${name} form ${c.dim(`(${step.detail}; the starter uses its own table instead)`)}`);
|
|
603
|
+
default:
|
|
604
|
+
return fail(`Could not set up ${step.kind} ${step.name}: ${step.error?.message ?? 'unknown error'}`, step.error?.hint);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
async function summary(s) {
|
|
608
|
+
const cdPart = s.target === cwd ? '' : `cd ${quoteArg(s.shownPath)} && `;
|
|
609
|
+
const steps = [];
|
|
610
|
+
if (s.manifest.kind === 'node') {
|
|
611
|
+
if (!s.installed)
|
|
612
|
+
steps.push(installCommand(s.pm));
|
|
613
|
+
steps.push(runScript(s.pm, s.manifest.run.script ?? 'dev'));
|
|
614
|
+
}
|
|
615
|
+
else
|
|
616
|
+
steps.push(s.manifest.run.command);
|
|
617
|
+
const next = `${cdPart}${steps.join(' && ')}`;
|
|
618
|
+
const rows = [
|
|
619
|
+
['Starter', `${s.manifest.name} ${c.dim(`(${s.manifest.stack})`)}`],
|
|
620
|
+
['Folder', s.shownPath],
|
|
621
|
+
];
|
|
622
|
+
if (s.project)
|
|
623
|
+
rows.push(['Project', `${s.project.name} ${c.dim(`(${s.project.ref})`)}`]);
|
|
624
|
+
else if (s.usesProject)
|
|
625
|
+
rows.push(['Project', c.yellow('not connected yet')]);
|
|
626
|
+
if (s.dashboard)
|
|
627
|
+
rows.push(['Dashboard', c.cyan(s.dashboard)]);
|
|
628
|
+
const label = Math.max(...rows.map(([k]) => k.length)) + 3;
|
|
629
|
+
const lines = [
|
|
630
|
+
s.failed ? `${c.yellow('!')} ${c.bold(s.appName)} is almost ready` : `${c.green('✔')} ${c.bold(s.appName)} is ready`,
|
|
631
|
+
'',
|
|
632
|
+
...rows.map(([k, v]) => `${c.dim(k.padEnd(label))}${v}`),
|
|
633
|
+
'',
|
|
634
|
+
];
|
|
635
|
+
if (s.manifest.run.first)
|
|
636
|
+
lines.push(`${c.bold('First:')} ${s.manifest.run.first}`);
|
|
637
|
+
lines.push(`${c.bold('Next:')} ${c.cyan(next)}`);
|
|
638
|
+
if (s.manifest.run.url)
|
|
639
|
+
lines.push(`${' '.repeat(7)}then open ${c.cyan(s.manifest.run.url)}`);
|
|
640
|
+
if (s.manifest.run.note)
|
|
641
|
+
lines.push(`${' '.repeat(7)}${c.dim(s.manifest.run.note)}`);
|
|
642
|
+
if (s.localApi && s.manifest.run.localNote)
|
|
643
|
+
lines.push(`${' '.repeat(7)}${s.manifest.run.localNote}`);
|
|
644
|
+
write();
|
|
645
|
+
write(box(lines, output.columns || 100));
|
|
646
|
+
const after = [];
|
|
647
|
+
if (s.manifest.customize)
|
|
648
|
+
after.push(`Make it yours: the name is in ${c.bold(s.manifest.customize.name)}, the colour in ${c.bold(s.manifest.customize.colour)}.`);
|
|
649
|
+
if (!s.connected && s.usesProject)
|
|
650
|
+
after.push(`Connect it later: ${c.cyan(`${cdPart}npx usebecky init`)} ${c.dim('(the starter README lists the tables it needs)')}`);
|
|
651
|
+
if (s.busy && s.manifest.run.port)
|
|
652
|
+
after.push(`${c.yellow('Heads up:')} port ${s.manifest.run.port} is in use by another app, so the starter will pick the next free port. Use the address it prints.`);
|
|
653
|
+
const docsBase = s.dashboardBase ? `${s.dashboardBase}/docs/` : null;
|
|
654
|
+
const guide = s.manifest.docs?.[0];
|
|
655
|
+
after.push(`Read me first: ${c.bold(path.join(s.shownPath, 'README.md'))}${docsBase ? ` ${c.dim('or')} ${c.cyan(`${docsBase}getting-started/starters`)}` : ''}`);
|
|
656
|
+
if (guide && docsBase)
|
|
657
|
+
after.push(`${guide.title}: ${c.cyan(docsBase + guide.path)}`);
|
|
658
|
+
for (const line of after)
|
|
659
|
+
write(` ${line}`);
|
|
660
|
+
write();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
// ---- helpers -------------------------------------------------------------------------------
|
|
664
|
+
function isTruthy(v) {
|
|
665
|
+
return !!v && !['0', 'false', ''].includes(v.toLowerCase());
|
|
666
|
+
}
|
|
667
|
+
export function atLeast(version, min) {
|
|
668
|
+
const parts = version.replace(/^v/, '').split('.').map(Number);
|
|
669
|
+
for (let i = 0; i < min.length; i++) {
|
|
670
|
+
if ((parts[i] ?? 0) > min[i])
|
|
671
|
+
return true;
|
|
672
|
+
if ((parts[i] ?? 0) < min[i])
|
|
673
|
+
return false;
|
|
674
|
+
}
|
|
675
|
+
return true;
|
|
676
|
+
}
|
|
677
|
+
function displayPath(cwd, target) {
|
|
678
|
+
const rel = path.relative(cwd, target);
|
|
679
|
+
if (!rel)
|
|
680
|
+
return '.';
|
|
681
|
+
if (rel.startsWith('..') || path.isAbsolute(rel))
|
|
682
|
+
return target;
|
|
683
|
+
return `.${path.sep}${rel}`;
|
|
684
|
+
}
|
|
685
|
+
function quoteArg(s) {
|
|
686
|
+
return /^[\w./\\:-]+$/.test(s) ? s : `"${s}"`;
|
|
687
|
+
}
|
|
688
|
+
/** The "Use one of my projects" hint: what an existing project needs for this starter. */
|
|
689
|
+
export function existingHint(manifest) {
|
|
690
|
+
const tables = manifest.requires?.tables ?? [];
|
|
691
|
+
if (!tables.length)
|
|
692
|
+
return 'any project works; the starter adds what it needs';
|
|
693
|
+
const names = tables.map((t) => `"${t}"`);
|
|
694
|
+
const list = names.length < 2 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
695
|
+
return `needs the ${list} table${tables.length > 1 ? 's' : ''} from the ${manifest.serverTemplate} template`;
|
|
696
|
+
}
|
|
697
|
+
function listWords(items) {
|
|
698
|
+
if (items.length < 2)
|
|
699
|
+
return items.join('');
|
|
700
|
+
return `${items.slice(0, -1).join(', ')} or ${items[items.length - 1]}`;
|
|
701
|
+
}
|
|
702
|
+
function nextFreeName(cwd, base) {
|
|
703
|
+
for (let i = 2; i < 100; i++) {
|
|
704
|
+
const candidate = `${base}-${i}`;
|
|
705
|
+
const s = inspectDir(path.join(cwd, candidate));
|
|
706
|
+
if (s.state === 'missing' || s.state === 'empty')
|
|
707
|
+
return candidate;
|
|
708
|
+
}
|
|
709
|
+
return `${base}-${Date.now().toString(36)}`;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* `--sdk`: the usebecky you built from the source, until it's on npm. A path (the .tgz from `npm pack`,
|
|
713
|
+
* or the packages/sdk folder) becomes `file:<absolute path>`: a relative path is relative to where the
|
|
714
|
+
* command ran, but the app lives in another folder. Anything else (a version, a tag) is used as it is.
|
|
715
|
+
*/
|
|
716
|
+
export function resolveSdkSpec(spec, cwd, home = os.homedir()) {
|
|
717
|
+
const file = spec.startsWith('file:');
|
|
718
|
+
let p = file ? spec.slice(5) : spec;
|
|
719
|
+
// `--sdk=~/...` reaches us without the shell turning ~ into the home folder.
|
|
720
|
+
const tilde = /^~(?=[\\/]|$)/.test(p);
|
|
721
|
+
if (tilde)
|
|
722
|
+
p = path.join(home, p.slice(1));
|
|
723
|
+
const isPath = file || tilde || /\.tgz$/i.test(p) || /^\.{1,2}(?=[\\/]|$)/.test(p) || path.isAbsolute(p) || fs.existsSync(path.resolve(cwd, p));
|
|
724
|
+
if (!isPath)
|
|
725
|
+
return { spec };
|
|
726
|
+
const abs = path.resolve(cwd, p);
|
|
727
|
+
return { spec: `file:${abs}`, path: abs };
|
|
728
|
+
}
|
|
729
|
+
/** Why `--sdk <path>` can't be installed, or null when it looks right. */
|
|
730
|
+
export function checkSdkPath(p) {
|
|
731
|
+
let stat;
|
|
732
|
+
try {
|
|
733
|
+
stat = fs.statSync(p);
|
|
734
|
+
}
|
|
735
|
+
catch {
|
|
736
|
+
return `Could not find ${p} (from --sdk).`;
|
|
737
|
+
}
|
|
738
|
+
if (!stat.isDirectory())
|
|
739
|
+
return null;
|
|
740
|
+
try {
|
|
741
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(p, 'package.json'), 'utf8'));
|
|
742
|
+
if (pkg.name === 'usebecky')
|
|
743
|
+
return null;
|
|
744
|
+
}
|
|
745
|
+
catch { }
|
|
746
|
+
return `${p} (from --sdk) isn't the usebecky package. Pass the .tgz that npm pack made in packages/sdk, or the packages/sdk folder.`;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Is the API on this computer or its network (localhost, the Android emulator's 10.0.2.2, a private IP)?
|
|
750
|
+
* Only when --api-url / USEBECKY_API_URL point there (the hosted API never is): a starter's `localNote` is shown then.
|
|
751
|
+
*/
|
|
752
|
+
export function isLocalUrl(url) {
|
|
753
|
+
let host;
|
|
754
|
+
try {
|
|
755
|
+
host = new URL(url).hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
756
|
+
}
|
|
757
|
+
catch {
|
|
758
|
+
return false;
|
|
759
|
+
}
|
|
760
|
+
return (host === 'localhost' ||
|
|
761
|
+
host.endsWith('.localhost') ||
|
|
762
|
+
host.endsWith('.local') ||
|
|
763
|
+
host === '::1' ||
|
|
764
|
+
host === '0.0.0.0' ||
|
|
765
|
+
/^127\./.test(host) ||
|
|
766
|
+
/^10\./.test(host) ||
|
|
767
|
+
/^192\.168\./.test(host) ||
|
|
768
|
+
/^172\.(1[6-9]|2\d|3[01])\./.test(host));
|
|
769
|
+
}
|
|
770
|
+
/** The skill that ships with the app's own usebecky version, once installed. */
|
|
771
|
+
function skillFrom(appDir) {
|
|
772
|
+
const dir = path.join(appDir, 'node_modules', 'usebecky', 'skill', 'usebecky');
|
|
773
|
+
return fs.existsSync(path.join(dir, 'SKILL.md')) ? dir : null;
|
|
774
|
+
}
|
|
775
|
+
/** The extension kit's skill, once the starter's packages are installed. */
|
|
776
|
+
function extensionSkillFrom(appDir) {
|
|
777
|
+
const dir = path.join(appDir, 'node_modules', '@usebecky', 'extension', 'skill', EXTENSION_SKILL_NAME);
|
|
778
|
+
return fs.existsSync(path.join(dir, 'SKILL.md')) ? dir : null;
|
|
779
|
+
}
|
|
780
|
+
/** dist/extension-skill when installed from npm (scripts/build.mjs), packages/extension/skill in the monorepo. */
|
|
781
|
+
function bundledExtensionSkill() {
|
|
782
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
783
|
+
for (const dir of [path.join(here, 'extension-skill', EXTENSION_SKILL_NAME), path.resolve(here, '..', '..', 'extension', 'skill', EXTENSION_SKILL_NAME)]) {
|
|
784
|
+
if (fs.existsSync(path.join(dir, 'SKILL.md')))
|
|
785
|
+
return dir;
|
|
786
|
+
}
|
|
787
|
+
return null;
|
|
788
|
+
}
|
|
789
|
+
/** dist/skill when installed from npm, packages/sdk/skill in the monorepo. */
|
|
790
|
+
function bundledSkill() {
|
|
791
|
+
const found = findSkillSource();
|
|
792
|
+
if (found)
|
|
793
|
+
return found;
|
|
794
|
+
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'sdk', 'skill', 'usebecky');
|
|
795
|
+
return fs.existsSync(path.join(repo, 'SKILL.md')) ? repo : null;
|
|
796
|
+
}
|
|
797
|
+
function portFree(port) {
|
|
798
|
+
return new Promise((resolve) => {
|
|
799
|
+
const s = net.createServer();
|
|
800
|
+
s.once('error', () => resolve(false));
|
|
801
|
+
s.once('listening', () => s.close(() => resolve(true)));
|
|
802
|
+
s.listen(port);
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
/** A rounded box, or plain indented lines when the terminal is too narrow. */
|
|
806
|
+
export function box(lines, columns) {
|
|
807
|
+
const inner = Math.max(...lines.map((l) => visible(l).length)) + 6;
|
|
808
|
+
if (inner + 2 > columns)
|
|
809
|
+
return lines.map((l) => ` ${l}`).join('\n');
|
|
810
|
+
const pad = (l) => `${c.dim('│')} ${l}${' '.repeat(inner - 3 - visible(l).length)}${c.dim('│')}`;
|
|
811
|
+
return [c.dim(`╭${'─'.repeat(inner)}╮`), pad(''), ...lines.map(pad), pad(''), c.dim(`╰${'─'.repeat(inner)}╯`)].join('\n');
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* ~/.usebecky (or USEBECKY_CONFIG_DIR / an explicit dir). A login saved before the rename to usebecky
|
|
815
|
+
* lives in ~/.yourbaas/config.json: copy it over once so nobody has to sign in again.
|
|
816
|
+
*/
|
|
817
|
+
function defaultConfigDir(explicit) {
|
|
818
|
+
if (explicit)
|
|
819
|
+
return explicit;
|
|
820
|
+
const dir = path.join(os.homedir(), '.usebecky');
|
|
821
|
+
const legacy = path.join(os.homedir(), '.yourbaas', 'config.json');
|
|
822
|
+
try {
|
|
823
|
+
if (!fs.existsSync(path.join(dir, 'config.json')) && fs.existsSync(legacy)) {
|
|
824
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
825
|
+
fs.copyFileSync(legacy, path.join(dir, 'config.json'));
|
|
826
|
+
fs.chmodSync(path.join(dir, 'config.json'), 0o600);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
catch { }
|
|
830
|
+
return dir;
|
|
831
|
+
}
|
|
832
|
+
/** Opens the default browser (macOS open, Linux xdg-open, Windows start). Never fails: the link is printed anyway. */
|
|
833
|
+
function openBrowser(url) {
|
|
834
|
+
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
|
|
835
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
|
|
836
|
+
try {
|
|
837
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
838
|
+
child.on('error', () => { });
|
|
839
|
+
child.unref();
|
|
840
|
+
}
|
|
841
|
+
catch { }
|
|
842
|
+
}
|