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
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
// GENERATED: copied from packages/sdk/src/cli/framework.ts by scripts/sync-shared.mjs. Edit it there, then run `npm run sync`.
|
|
2
|
+
// Framework detection + writing env files / the client file for `npx usebecky init`.
|
|
3
|
+
// Also recognises native apps (Xcode / Swift package / Gradle), which never get the secret key.
|
|
4
|
+
// Pure functions over a directory so they are easy to test.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
/** The docs site (placeholder until published; docs/PUBLISHING.md). A page is `${DOCS_URL}/<path under docs/guide without .md>`. */
|
|
9
|
+
export const DOCS_URL = 'https://usebecky.com/docs';
|
|
10
|
+
/** The Swift package customers add in Xcode (the client library is MIT; the service itself is hosted, closed source). */
|
|
11
|
+
export const SWIFT_PACKAGE_URL = 'https://github.com/usebecky/usebecky-swift';
|
|
12
|
+
/** The Kotlin client library on Maven Central. */
|
|
13
|
+
export const KOTLIN_ARTIFACT = 'com.usebecky:usebecky-kotlin';
|
|
14
|
+
/**
|
|
15
|
+
* Same text as DASHBOARD_API_KEYS in src/lib/dashboard-paths.ts. Repeated because this file is also
|
|
16
|
+
* copied into create-usebecky, which has no src/lib; test/cli-dashboard-paths.test.ts keeps them equal.
|
|
17
|
+
*/
|
|
18
|
+
const KEYS_PAGE = 'Dashboard → Settings → API keys';
|
|
19
|
+
export const FRAMEWORK_LABELS = {
|
|
20
|
+
next: 'Next.js',
|
|
21
|
+
vite: 'Vite',
|
|
22
|
+
remix: 'Remix',
|
|
23
|
+
nuxt: 'Nuxt',
|
|
24
|
+
sveltekit: 'SvelteKit',
|
|
25
|
+
expo: 'Expo (React Native)',
|
|
26
|
+
express: 'Express',
|
|
27
|
+
node: 'Node.js',
|
|
28
|
+
};
|
|
29
|
+
export function readPackageJson(dir) {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function detectFramework(dir) {
|
|
38
|
+
const pkg = readPackageJson(dir);
|
|
39
|
+
const deps = { ...(pkg?.devDependencies ?? {}), ...(pkg?.dependencies ?? {}) };
|
|
40
|
+
const has = (name) => Object.prototype.hasOwnProperty.call(deps, name);
|
|
41
|
+
let framework = 'node';
|
|
42
|
+
if (has('expo') || has('react-native'))
|
|
43
|
+
framework = 'expo';
|
|
44
|
+
else if (has('next'))
|
|
45
|
+
framework = 'next';
|
|
46
|
+
else if (Object.keys(deps).some((d) => d.startsWith('@remix-run/')))
|
|
47
|
+
framework = 'remix';
|
|
48
|
+
else if (has('nuxt') || has('nuxt3'))
|
|
49
|
+
framework = 'nuxt';
|
|
50
|
+
else if (has('@sveltejs/kit'))
|
|
51
|
+
framework = 'sveltekit';
|
|
52
|
+
else if (has('vite'))
|
|
53
|
+
framework = 'vite';
|
|
54
|
+
else if (has('express'))
|
|
55
|
+
framework = 'express';
|
|
56
|
+
const typescript = fs.existsSync(path.join(dir, 'tsconfig.json')) || has('typescript');
|
|
57
|
+
const srcDir = fs.existsSync(path.join(dir, 'src')) && fs.statSync(path.join(dir, 'src')).isDirectory();
|
|
58
|
+
return { framework, label: FRAMEWORK_LABELS[framework], typescript, srcDir, hasPackageJson: !!pkg, dependencies: deps };
|
|
59
|
+
}
|
|
60
|
+
export const NATIVE_LABELS = {
|
|
61
|
+
ios: 'an iOS app (Swift)',
|
|
62
|
+
android: 'an Android app (Kotlin)',
|
|
63
|
+
};
|
|
64
|
+
const GRADLE_FILES = ['settings.gradle.kts', 'settings.gradle', 'build.gradle.kts', 'build.gradle'];
|
|
65
|
+
/** An Xcode project or workspace, or Package.swift (iOS / Swift), or a Gradle build (Android / Kotlin), at the top of `dir`. */
|
|
66
|
+
export function detectNative(dir) {
|
|
67
|
+
let entries;
|
|
68
|
+
try {
|
|
69
|
+
entries = fs.readdirSync(dir).sort();
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
const ios = entries.filter((e) => e === 'Package.swift' || (/\.(xcodeproj|xcworkspace)$/.test(e) && !e.startsWith('.')));
|
|
75
|
+
const android = GRADLE_FILES.filter((f) => entries.includes(f));
|
|
76
|
+
const platforms = [];
|
|
77
|
+
if (ios.length)
|
|
78
|
+
platforms.push('ios');
|
|
79
|
+
if (android.length)
|
|
80
|
+
platforms.push('android');
|
|
81
|
+
return platforms.length ? { platforms, markers: [...ios, ...android] } : null;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* What kind of app lives in `dir`, checked before any Node.js fallback:
|
|
85
|
+
* a package.json with a known framework (Expo included) is JavaScript; otherwise an Xcode project,
|
|
86
|
+
* Package.swift or Gradle build makes it native (a package.json that only holds tooling doesn't turn an
|
|
87
|
+
* iOS app into a Node.js app); a package.json alone is Node.js; nothing recognisable is 'none'.
|
|
88
|
+
*/
|
|
89
|
+
export function detectProject(dir) {
|
|
90
|
+
const detected = detectFramework(dir);
|
|
91
|
+
if (detected.hasPackageJson && detected.framework !== 'node')
|
|
92
|
+
return { kind: 'js', detected };
|
|
93
|
+
const native = detectNative(dir);
|
|
94
|
+
if (native)
|
|
95
|
+
return { kind: 'native', native, detected };
|
|
96
|
+
if (detected.hasPackageJson)
|
|
97
|
+
return { kind: 'js', detected };
|
|
98
|
+
return { kind: 'none', detected };
|
|
99
|
+
}
|
|
100
|
+
/** Printed when nothing in the folder looks like an app. */
|
|
101
|
+
export const LOOKED_FOR = 'package.json (JavaScript), an Xcode project (*.xcodeproj, *.xcworkspace or Package.swift) or a Gradle build (settings.gradle(.kts) or build.gradle(.kts))';
|
|
102
|
+
const LOCAL_URL = /^(https?:\/\/)(localhost|127\.0\.0\.1)(?=[:/]|$)/i;
|
|
103
|
+
/**
|
|
104
|
+
* What a native app needs to connect: the client code with the Project URL and the publishable key
|
|
105
|
+
* (never the secret key: anyone can read every value inside an app), plus how to add the SDK.
|
|
106
|
+
*/
|
|
107
|
+
export function nativeSetup(platform, keys, cwd, _home = os.homedir()) {
|
|
108
|
+
const local = LOCAL_URL.test(keys.url);
|
|
109
|
+
if (platform === 'ios') {
|
|
110
|
+
return {
|
|
111
|
+
platform,
|
|
112
|
+
title: 'iOS (Swift)',
|
|
113
|
+
file: 'Baas.swift',
|
|
114
|
+
code: [
|
|
115
|
+
'// Baas.swift',
|
|
116
|
+
'import UseBecky',
|
|
117
|
+
'',
|
|
118
|
+
'// Your connection to usebecky. The whole app uses this one `baas`.',
|
|
119
|
+
'let baas = UseBecky(',
|
|
120
|
+
` url: "${keys.url}",`,
|
|
121
|
+
` publishableKey: "${keys.publishableKey}"`,
|
|
122
|
+
')',
|
|
123
|
+
].join('\n'),
|
|
124
|
+
notes: local ? [`${keys.url} works in the iOS Simulator, not on an iPhone: on a phone use your hosted Project URL, or your Mac's Wi-Fi address (see "Test on your phone" in the iOS guide).`] : [],
|
|
125
|
+
steps: [
|
|
126
|
+
`Add the Swift package: Xcode → File → Add Package Dependencies… → paste ${SWIFT_PACKAGE_URL} → Add Package → tick your app target`,
|
|
127
|
+
'Xcode → File → New → File from Template… → Swift File, name it Baas, paste the code above, then build (Cmd+B)',
|
|
128
|
+
`Follow the iOS guide for sign-in, data, files and payments: ${DOCS_URL}/frameworks/ios`,
|
|
129
|
+
'Teach your AI assistant (it reads references/ios.md): npx usebecky ai',
|
|
130
|
+
],
|
|
131
|
+
guide: `${DOCS_URL}/frameworks/ios`,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const appBuild = fs.existsSync(path.join(cwd, 'app', 'build.gradle')) ? 'app/build.gradle' : 'app/build.gradle.kts';
|
|
135
|
+
const url = keys.url.replace(LOCAL_URL, (_m, scheme) => `${scheme}10.0.2.2`);
|
|
136
|
+
return {
|
|
137
|
+
platform,
|
|
138
|
+
title: 'Android (Kotlin)',
|
|
139
|
+
file: 'Backend.kt',
|
|
140
|
+
code: [
|
|
141
|
+
'// Backend.kt (the Android guide shows the whole file: client, session storage, helpers)',
|
|
142
|
+
'object UseBeckyConfig {',
|
|
143
|
+
` const val URL = "${url}"`,
|
|
144
|
+
` const val PUBLISHABLE_KEY = "${keys.publishableKey}"`,
|
|
145
|
+
'}',
|
|
146
|
+
].join('\n'),
|
|
147
|
+
notes: local
|
|
148
|
+
? [`10.0.2.2 is your computer as the Android emulator sees it (on a phone, use your computer's Wi-Fi address). Plain http:// also needs android:usesCleartextTraffic="true" on <application> in AndroidManifest.xml: remove it before you publish.`]
|
|
149
|
+
: [],
|
|
150
|
+
steps: [
|
|
151
|
+
`Add the Kotlin SDK from Maven Central: ${appBuild}, in dependencies { }: implementation("${KOTLIN_ARTIFACT}:0.2.0")`,
|
|
152
|
+
'AndroidManifest.xml, inside <manifest>: <uses-permission android:name="android.permission.INTERNET" />',
|
|
153
|
+
'Put the code above in Backend.kt, next to MainActivity.kt',
|
|
154
|
+
`Follow the Android guide for sign-in, data, files and payments: ${DOCS_URL}/frameworks/android`,
|
|
155
|
+
'Teach your AI assistant (it reads references/android.md): npx usebecky ai',
|
|
156
|
+
],
|
|
157
|
+
guide: `${DOCS_URL}/frameworks/android`,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** Which env file and variable names each framework uses (docs/SDK.md). */
|
|
161
|
+
export function envPlanFor(framework, keys) {
|
|
162
|
+
const server = [
|
|
163
|
+
{ name: 'USEBECKY_URL', value: keys.url },
|
|
164
|
+
{ name: 'USEBECKY_SECRET_KEY', value: keys.secretKey },
|
|
165
|
+
];
|
|
166
|
+
switch (framework) {
|
|
167
|
+
case 'next':
|
|
168
|
+
return { file: '.env.local', vars: [{ name: 'NEXT_PUBLIC_USEBECKY_URL', value: keys.url }, { name: 'NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }, ...server] };
|
|
169
|
+
case 'vite':
|
|
170
|
+
return { file: '.env.local', vars: [{ name: 'VITE_USEBECKY_URL', value: keys.url }, { name: 'VITE_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }] };
|
|
171
|
+
case 'remix':
|
|
172
|
+
return { file: '.env', vars: [{ name: 'VITE_USEBECKY_URL', value: keys.url }, { name: 'VITE_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }, ...server] };
|
|
173
|
+
case 'nuxt':
|
|
174
|
+
return { file: '.env', vars: [{ name: 'NUXT_PUBLIC_USEBECKY_URL', value: keys.url }, { name: 'NUXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }, ...server] };
|
|
175
|
+
case 'sveltekit':
|
|
176
|
+
return { file: '.env', vars: [{ name: 'PUBLIC_USEBECKY_URL', value: keys.url }, { name: 'PUBLIC_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }, ...server] };
|
|
177
|
+
case 'expo':
|
|
178
|
+
return { file: '.env', vars: [{ name: 'EXPO_PUBLIC_USEBECKY_URL', value: keys.url }, { name: 'EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }] };
|
|
179
|
+
default:
|
|
180
|
+
return { file: '.env', vars: [{ name: 'USEBECKY_URL', value: keys.url }, { name: 'USEBECKY_PUBLISHABLE_KEY', value: keys.publishableKey }, { name: 'USEBECKY_SECRET_KEY', value: keys.secretKey }] };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const LINE_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)?$/;
|
|
184
|
+
function unquote(v) {
|
|
185
|
+
const t = v.trim();
|
|
186
|
+
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))
|
|
187
|
+
return t.slice(1, -1);
|
|
188
|
+
const hash = t.indexOf(' #');
|
|
189
|
+
return hash >= 0 ? t.slice(0, hash).trim() : t;
|
|
190
|
+
}
|
|
191
|
+
/** Parse a .env file into name → value. */
|
|
192
|
+
export function parseEnv(content) {
|
|
193
|
+
const out = {};
|
|
194
|
+
for (const line of content.split(/\r?\n/)) {
|
|
195
|
+
if (/^\s*#/.test(line))
|
|
196
|
+
continue;
|
|
197
|
+
const m = LINE_RE.exec(line);
|
|
198
|
+
if (m)
|
|
199
|
+
out[m[1]] = unquote(m[2] ?? '');
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Add variables to an env file. Existing different values are only replaced when
|
|
205
|
+
* `confirmReplace` says yes. Other lines and comments are left untouched.
|
|
206
|
+
*/
|
|
207
|
+
export async function writeEnvFile(file, vars, confirmReplace) {
|
|
208
|
+
const exists = fs.existsSync(file);
|
|
209
|
+
const original = exists ? fs.readFileSync(file, 'utf8') : '';
|
|
210
|
+
const lines = original === '' ? [] : original.split(/\r?\n/);
|
|
211
|
+
if (lines.length && lines[lines.length - 1] === '')
|
|
212
|
+
lines.pop();
|
|
213
|
+
const result = { file, created: !exists, added: [], updated: [], kept: [], unchanged: [] };
|
|
214
|
+
const toAppend = [];
|
|
215
|
+
for (const v of vars) {
|
|
216
|
+
const idx = lines.findIndex((l) => !/^\s*#/.test(l) && LINE_RE.exec(l)?.[1] === v.name);
|
|
217
|
+
if (idx === -1) {
|
|
218
|
+
toAppend.push(`${v.name}=${v.value}`);
|
|
219
|
+
result.added.push(v.name);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
const current = unquote(LINE_RE.exec(lines[idx])[2] ?? '');
|
|
223
|
+
if (current === v.value) {
|
|
224
|
+
result.unchanged.push(v.name);
|
|
225
|
+
}
|
|
226
|
+
else if (current === '' || (await confirmReplace(v.name, current, v.value))) {
|
|
227
|
+
lines[idx] = `${v.name}=${v.value}`;
|
|
228
|
+
result.updated.push(v.name);
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
result.kept.push(v.name);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (toAppend.length) {
|
|
235
|
+
if (lines.length && lines[lines.length - 1].trim() !== '')
|
|
236
|
+
lines.push('');
|
|
237
|
+
lines.push(`# usebecky: values from ${KEYS_PAGE} (written by \`npx usebecky init\`)`, ...toAppend);
|
|
238
|
+
}
|
|
239
|
+
if (result.added.length || result.updated.length || !exists)
|
|
240
|
+
fs.writeFileSync(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
function globToRegex(glob) {
|
|
244
|
+
let re = '';
|
|
245
|
+
for (const ch of glob) {
|
|
246
|
+
if (ch === '*')
|
|
247
|
+
re += '[^/]*';
|
|
248
|
+
else if (ch === '?')
|
|
249
|
+
re += '[^/]';
|
|
250
|
+
else
|
|
251
|
+
re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
252
|
+
}
|
|
253
|
+
return new RegExp(`^${re}$`);
|
|
254
|
+
}
|
|
255
|
+
/** Would git ignore `file` (a top-level file name) with these .gitignore contents? */
|
|
256
|
+
export function isIgnored(gitignore, file) {
|
|
257
|
+
let ignored = false;
|
|
258
|
+
for (const raw of gitignore.split(/\r?\n/)) {
|
|
259
|
+
let line = raw.trim();
|
|
260
|
+
if (!line || line.startsWith('#'))
|
|
261
|
+
continue;
|
|
262
|
+
const negate = line.startsWith('!');
|
|
263
|
+
if (negate)
|
|
264
|
+
line = line.slice(1);
|
|
265
|
+
line = line.replace(/^\/+/, '').replace(/^\*\*\//, '');
|
|
266
|
+
if (line.endsWith('/'))
|
|
267
|
+
continue;
|
|
268
|
+
if (globToRegex(line).test(file))
|
|
269
|
+
ignored = !negate;
|
|
270
|
+
}
|
|
271
|
+
return ignored;
|
|
272
|
+
}
|
|
273
|
+
/** Make sure the env files are listed in .gitignore (creates it if needed). */
|
|
274
|
+
export function ensureGitignore(dir, files) {
|
|
275
|
+
const file = path.join(dir, '.gitignore');
|
|
276
|
+
const exists = fs.existsSync(file);
|
|
277
|
+
const content = exists ? fs.readFileSync(file, 'utf8') : '';
|
|
278
|
+
const missing = files.filter((f) => !isIgnored(content, f));
|
|
279
|
+
if (missing.length) {
|
|
280
|
+
const prefix = content && !content.endsWith('\n') ? '\n' : '';
|
|
281
|
+
const block = `${prefix}${content ? '\n' : ''}# usebecky: keep your keys out of git\n${missing.join('\n')}\n`;
|
|
282
|
+
fs.writeFileSync(file, content + block);
|
|
283
|
+
}
|
|
284
|
+
return { file, created: !exists && missing.length > 0, added: missing };
|
|
285
|
+
}
|
|
286
|
+
/** `from` for an import in `fromFile` of the file at `target` (project-relative, forward slashes). */
|
|
287
|
+
export function relativeImport(fromFile, target) {
|
|
288
|
+
const rel = path.posix.relative(path.posix.dirname(fromFile), target);
|
|
289
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
290
|
+
}
|
|
291
|
+
/** The import line for the client file, correct relative to the file people type it in. */
|
|
292
|
+
export function clientImport(d, libPath) {
|
|
293
|
+
const noExt = libPath.replace(/\.(ts|js)$/, '');
|
|
294
|
+
const src = libPath.startsWith('src/') ? 'src/' : '';
|
|
295
|
+
const ts = d.typescript;
|
|
296
|
+
switch (d.framework) {
|
|
297
|
+
case 'next': {
|
|
298
|
+
const file = `${src}app/page.${ts ? 'tsx' : 'js'}`;
|
|
299
|
+
return { where: `a client component, like ${file} (with 'use client' at the top)`, file, from: '@/lib/usebecky', also: `without the @/ alias in ${ts ? 'tsconfig.json' : 'jsconfig.json'}: '${relativeImport(file, noExt)}'` };
|
|
300
|
+
}
|
|
301
|
+
case 'vite': {
|
|
302
|
+
const file = src ? `src/main.${ts ? 'ts' : 'js'}` : `main.${ts ? 'ts' : 'js'}`;
|
|
303
|
+
const where = src ? `files directly inside src/ (like ${file} or src/App.${ts ? 'tsx' : 'jsx'})` : `files in the project folder (like ${file})`;
|
|
304
|
+
return { where, file, from: relativeImport(file, noExt), also: `in ${src}components/: '${relativeImport(`${src}components/x.${ts ? 'tsx' : 'jsx'}`, noExt)}'` };
|
|
305
|
+
}
|
|
306
|
+
case 'remix': {
|
|
307
|
+
const file = `app/routes/_index.${ts ? 'tsx' : 'jsx'}`;
|
|
308
|
+
return { where: `a route, like ${file}`, file, from: relativeImport(file, noExt), also: `in app/root.${ts ? 'tsx' : 'jsx'}: '${relativeImport('app/root.tsx', noExt)}'` };
|
|
309
|
+
}
|
|
310
|
+
case 'nuxt':
|
|
311
|
+
// ~~ is the project folder in Nuxt 3 and 4 (~ is app/ in Nuxt 4).
|
|
312
|
+
return { where: 'a page or component, like app.vue or pages/index.vue', file: 'app.vue', from: '~~/lib/usebecky' };
|
|
313
|
+
case 'sveltekit':
|
|
314
|
+
return { where: 'any file in src/, like src/routes/+page.svelte', file: 'src/routes/+page.svelte', from: '$lib/usebecky' };
|
|
315
|
+
case 'expo': {
|
|
316
|
+
const router = Object.prototype.hasOwnProperty.call(d.dependencies, 'expo-router');
|
|
317
|
+
const file = router ? `app/index.${ts ? 'tsx' : 'js'}` : `App.${ts ? 'tsx' : 'js'}`;
|
|
318
|
+
return { where: router ? `a screen, like ${file}` : file, file, from: relativeImport(file, noExt), also: `in files inside lib/: './usebecky'` };
|
|
319
|
+
}
|
|
320
|
+
default: {
|
|
321
|
+
// Node runs ESM with the file extension in relative imports (.ts too, with Node's type stripping).
|
|
322
|
+
const file = `server.${ts ? 'ts' : 'js'}`;
|
|
323
|
+
return { where: `${file} in the project folder`, file, from: relativeImport(file, libPath), also: `in src/index.${ts ? 'ts' : 'js'}: '${relativeImport('src/index.js', libPath)}'` };
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** The `lib/usebecky.ts` (or .js) file for a framework. */
|
|
328
|
+
export function libFileFor(d) {
|
|
329
|
+
const ext = d.typescript ? 'ts' : 'js';
|
|
330
|
+
const bang = d.typescript ? '!' : '';
|
|
331
|
+
const useSrc = d.srcDir && (d.framework === 'next' || d.framework === 'vite' || d.framework === 'sveltekit' || d.framework === 'remix');
|
|
332
|
+
const dir = d.framework === 'sveltekit' ? 'src/lib' : useSrc ? 'src/lib' : 'lib';
|
|
333
|
+
const file = `${dir}/usebecky.${ext}`;
|
|
334
|
+
const imp = clientImport(d, file);
|
|
335
|
+
let content;
|
|
336
|
+
switch (d.framework) {
|
|
337
|
+
case 'next':
|
|
338
|
+
content = `// Your usebecky client for browser code ('use client' components).
|
|
339
|
+
// In server code (route handlers, server actions) use: import { baas } from 'usebecky/server'
|
|
340
|
+
import { createClient } from 'usebecky'
|
|
341
|
+
|
|
342
|
+
export const baas = createClient(
|
|
343
|
+
process.env.NEXT_PUBLIC_USEBECKY_URL${bang},
|
|
344
|
+
process.env.NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY${bang},
|
|
345
|
+
)
|
|
346
|
+
`;
|
|
347
|
+
break;
|
|
348
|
+
case 'vite':
|
|
349
|
+
case 'remix':
|
|
350
|
+
content = `// Your usebecky client. In ${imp.where}: import { baas } from '${imp.from}'
|
|
351
|
+
// (${imp.also})
|
|
352
|
+
import { createClient } from 'usebecky'
|
|
353
|
+
|
|
354
|
+
export const baas = createClient(
|
|
355
|
+
import.meta.env.VITE_USEBECKY_URL,
|
|
356
|
+
import.meta.env.VITE_USEBECKY_PUBLISHABLE_KEY,
|
|
357
|
+
)
|
|
358
|
+
`;
|
|
359
|
+
break;
|
|
360
|
+
case 'nuxt':
|
|
361
|
+
content = `// Your usebecky client. In ${imp.where}: import { useBecky } from '${imp.from}', then const baas = useBecky()
|
|
362
|
+
// nuxt.config: runtimeConfig: { public: { usebeckyUrl: '', usebeckyPublishableKey: '' } }
|
|
363
|
+
import { createClient${d.typescript ? ', type UseBeckyClient' : ''} } from 'usebecky'
|
|
364
|
+
import { useRuntimeConfig } from '#imports'
|
|
365
|
+
|
|
366
|
+
let client${d.typescript ? ': UseBeckyClient | undefined' : ''}
|
|
367
|
+
|
|
368
|
+
export function useBecky() {
|
|
369
|
+
const config = useRuntimeConfig()
|
|
370
|
+
client ??= createClient(config.public.usebeckyUrl${d.typescript ? ' as string' : ''}, config.public.usebeckyPublishableKey${d.typescript ? ' as string' : ''})
|
|
371
|
+
return client
|
|
372
|
+
}
|
|
373
|
+
`;
|
|
374
|
+
break;
|
|
375
|
+
case 'sveltekit':
|
|
376
|
+
content = `// Your usebecky client. Import it anywhere: import { baas } from '$lib/usebecky'
|
|
377
|
+
import { createClient } from 'usebecky'
|
|
378
|
+
import { PUBLIC_USEBECKY_URL, PUBLIC_USEBECKY_PUBLISHABLE_KEY } from '$env/static/public'
|
|
379
|
+
|
|
380
|
+
export const baas = createClient(PUBLIC_USEBECKY_URL, PUBLIC_USEBECKY_PUBLISHABLE_KEY)
|
|
381
|
+
`;
|
|
382
|
+
break;
|
|
383
|
+
case 'expo': {
|
|
384
|
+
const hasAsync = Object.prototype.hasOwnProperty.call(d.dependencies, '@react-native-async-storage/async-storage');
|
|
385
|
+
content = hasAsync
|
|
386
|
+
? `// Your usebecky client. Sessions are saved with AsyncStorage so users stay signed in.
|
|
387
|
+
import AsyncStorage from '@react-native-async-storage/async-storage'
|
|
388
|
+
import { createClient } from 'usebecky'
|
|
389
|
+
|
|
390
|
+
export const baas = createClient(
|
|
391
|
+
process.env.EXPO_PUBLIC_USEBECKY_URL${bang},
|
|
392
|
+
process.env.EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY${bang},
|
|
393
|
+
{ storage: AsyncStorage, detectSessionInUrl: false },
|
|
394
|
+
)
|
|
395
|
+
`
|
|
396
|
+
: `// Your usebecky client.
|
|
397
|
+
// To keep users signed in after the app restarts, run
|
|
398
|
+
// npx expo install @react-native-async-storage/async-storage
|
|
399
|
+
// then pass { storage: AsyncStorage } as the third argument below.
|
|
400
|
+
import { createClient } from 'usebecky'
|
|
401
|
+
|
|
402
|
+
export const baas = createClient(
|
|
403
|
+
process.env.EXPO_PUBLIC_USEBECKY_URL${bang},
|
|
404
|
+
process.env.EXPO_PUBLIC_USEBECKY_PUBLISHABLE_KEY${bang},
|
|
405
|
+
{ detectSessionInUrl: false },
|
|
406
|
+
)
|
|
407
|
+
`;
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
default:
|
|
411
|
+
content = `// Server-side usebecky client. It reads USEBECKY_URL and USEBECKY_SECRET_KEY from the environment.
|
|
412
|
+
// Start your app with the .env file loaded: node --env-file=.env ${imp.file}
|
|
413
|
+
//
|
|
414
|
+
// import { baas } from '${imp.from}' // in ${imp.file}; ${imp.also}
|
|
415
|
+
// app.use(baas.auth.middleware()) // req.user = the signed-in user, or null
|
|
416
|
+
// await baas.as(req).from('todos').select() // as that user (Row Level Security applies)
|
|
417
|
+
export { baas } from 'usebecky/server'
|
|
418
|
+
`;
|
|
419
|
+
}
|
|
420
|
+
return { path: file, content };
|
|
421
|
+
}
|
|
422
|
+
/** Create the client file unless it already exists. */
|
|
423
|
+
export function writeLibFile(dir, lib) {
|
|
424
|
+
const full = path.join(dir, lib.path);
|
|
425
|
+
if (fs.existsSync(full))
|
|
426
|
+
return { path: lib.path, created: false };
|
|
427
|
+
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
428
|
+
fs.writeFileSync(full, lib.content);
|
|
429
|
+
return { path: lib.path, created: true };
|
|
430
|
+
}
|
|
431
|
+
/** Copy-paste next steps for a framework. */
|
|
432
|
+
export function nextSteps(d, lib, needsInstall) {
|
|
433
|
+
const imp = clientImport(d, lib.path);
|
|
434
|
+
const use = (code) => `In ${imp.where}:\n import { baas } from '${imp.from}'\n ${code}${imp.also ? `\n (${imp.also})` : ''}`;
|
|
435
|
+
const steps = [];
|
|
436
|
+
if (needsInstall)
|
|
437
|
+
steps.push(d.framework === 'expo' ? 'npx expo install usebecky' : 'npm install usebecky');
|
|
438
|
+
switch (d.framework) {
|
|
439
|
+
case 'next':
|
|
440
|
+
steps.push(use("await baas.auth.signInWith('google')"), `In a route handler or server action, like ${imp.file.replace(/page\.(tsx|js)$/, `api/notes/route.${d.typescript ? 'ts' : 'js'}`)}:\n import { baas } from 'usebecky/server'\n const user = await baas.auth.getUser(request)`, 'Restart `npm run dev` so Next.js loads .env.local');
|
|
441
|
+
break;
|
|
442
|
+
case 'vite':
|
|
443
|
+
case 'remix':
|
|
444
|
+
steps.push(use("const { data, error } = await baas.from('todos').select()"), 'Restart `npm run dev` so Vite loads the new env file');
|
|
445
|
+
break;
|
|
446
|
+
case 'nuxt':
|
|
447
|
+
steps.push("Add to nuxt.config: runtimeConfig: { public: { usebeckyUrl: '', usebeckyPublishableKey: '' } }", `In ${imp.where}, inside <script setup>:\n import { useBecky } from '${imp.from}'\n const baas = useBecky()`, 'Restart `npm run dev`');
|
|
448
|
+
break;
|
|
449
|
+
case 'sveltekit':
|
|
450
|
+
steps.push(use("const { data, error } = await baas.from('todos').select()"), "On the server, like src/routes/+page.server.ts:\n import { createServerClient } from 'usebecky/server'\n import { USEBECKY_URL, USEBECKY_SECRET_KEY } from '$env/static/private'\n const baas = createServerClient({ url: USEBECKY_URL, secretKey: USEBECKY_SECRET_KEY })");
|
|
451
|
+
break;
|
|
452
|
+
case 'expo':
|
|
453
|
+
steps.push(use("const { data, error } = await baas.from('todos').select()"), 'Restart Expo with `npx expo start -c` so it picks up the env vars');
|
|
454
|
+
break;
|
|
455
|
+
default:
|
|
456
|
+
steps.push(use('app.use(baas.auth.middleware())'), `Start with your env file loaded: node --env-file=.env ${imp.file}`);
|
|
457
|
+
}
|
|
458
|
+
steps.push('Generate types for autocomplete: npx usebecky types');
|
|
459
|
+
return steps;
|
|
460
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// GENERATED: copied from packages/sdk/src/lib/hosted.ts by scripts/sync-shared.mjs. Edit it there, then run `npm run sync`.
|
|
2
|
+
// The one place the hosted API address lives. usebecky is a hosted service: every project runs in our
|
|
3
|
+
// cloud behind this address, so createClient("ub_pk_...") needs nothing else. The SDK, the CLI
|
|
4
|
+
// (`npx usebecky init`) and create-usebecky (copied by its scripts/sync-shared.mjs) all read it from here.
|
|
5
|
+
// An explicit URL (createClient(url, key), --api-url, USEBECKY_URL / USEBECKY_API_URL) still wins,
|
|
6
|
+
// which is how the usebecky team points everything at a local API while working on it.
|
|
7
|
+
/** The hosted usebecky API (placeholder until the final domain is set). */
|
|
8
|
+
export const HOSTED_API_URL = 'https://api.usebecky.com';
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// GENERATED: copied from packages/sdk/src/cli/ui.ts by scripts/sync-shared.mjs. Edit it there, then run `npm run sync`.
|
|
2
|
+
// Tiny terminal UI: colors and prompts with zero dependencies.
|
|
3
|
+
import readline from 'node:readline';
|
|
4
|
+
const useColor = () => !!process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
|
|
5
|
+
const wrap = (code, close = 39) => (s) => (useColor() ? `\u001b[${code}m${s}\u001b[${close}m` : s);
|
|
6
|
+
export const c = {
|
|
7
|
+
bold: wrap(1, 22),
|
|
8
|
+
dim: wrap(2, 22),
|
|
9
|
+
red: wrap(31),
|
|
10
|
+
green: wrap(32),
|
|
11
|
+
yellow: wrap(33),
|
|
12
|
+
blue: wrap(34),
|
|
13
|
+
magenta: wrap(35),
|
|
14
|
+
cyan: wrap(36),
|
|
15
|
+
gray: wrap(90),
|
|
16
|
+
};
|
|
17
|
+
export function createUi(io) {
|
|
18
|
+
const write = (s = '') => io.output.write(s + '\n');
|
|
19
|
+
let rl = null;
|
|
20
|
+
let lineQueue = [];
|
|
21
|
+
let waiting = null;
|
|
22
|
+
let closed = false;
|
|
23
|
+
function ensureRl() {
|
|
24
|
+
if (!rl) {
|
|
25
|
+
rl = readline.createInterface({ input: io.input, terminal: false });
|
|
26
|
+
rl.on('line', (line) => {
|
|
27
|
+
if (waiting) {
|
|
28
|
+
const w = waiting;
|
|
29
|
+
waiting = null;
|
|
30
|
+
w(line);
|
|
31
|
+
}
|
|
32
|
+
else
|
|
33
|
+
lineQueue.push(line);
|
|
34
|
+
});
|
|
35
|
+
rl.on('close', () => {
|
|
36
|
+
closed = true;
|
|
37
|
+
if (waiting) {
|
|
38
|
+
const w = waiting;
|
|
39
|
+
waiting = null;
|
|
40
|
+
w(null);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return rl;
|
|
45
|
+
}
|
|
46
|
+
function readLine() {
|
|
47
|
+
ensureRl();
|
|
48
|
+
if (lineQueue.length)
|
|
49
|
+
return Promise.resolve(lineQueue.shift());
|
|
50
|
+
if (closed)
|
|
51
|
+
return Promise.resolve(null);
|
|
52
|
+
return new Promise((resolve) => (waiting = resolve));
|
|
53
|
+
}
|
|
54
|
+
async function ask(question, defaultValue = '') {
|
|
55
|
+
if (io.yes)
|
|
56
|
+
return defaultValue;
|
|
57
|
+
io.output.write(`${c.cyan('?')} ${question}${defaultValue ? c.dim(` (${defaultValue})`) : ''} `);
|
|
58
|
+
const line = await readLine();
|
|
59
|
+
if (line === null)
|
|
60
|
+
return defaultValue;
|
|
61
|
+
return line.trim() || defaultValue;
|
|
62
|
+
}
|
|
63
|
+
async function askHidden(question) {
|
|
64
|
+
if (io.yes)
|
|
65
|
+
return '';
|
|
66
|
+
const input = io.input;
|
|
67
|
+
if (!input.isTTY || typeof input.setRawMode !== 'function')
|
|
68
|
+
return ask(question);
|
|
69
|
+
io.output.write(`${c.cyan('?')} ${question} `);
|
|
70
|
+
// Pause our line reader while reading raw keypresses.
|
|
71
|
+
rl?.pause();
|
|
72
|
+
return new Promise((resolve) => {
|
|
73
|
+
let value = '';
|
|
74
|
+
input.setRawMode(true);
|
|
75
|
+
input.resume();
|
|
76
|
+
const onData = (buf) => {
|
|
77
|
+
for (const ch of buf.toString('utf8')) {
|
|
78
|
+
if (ch === '\r' || ch === '\n' || ch === '\u0004') {
|
|
79
|
+
input.setRawMode(false);
|
|
80
|
+
input.removeListener('data', onData);
|
|
81
|
+
io.output.write('\n');
|
|
82
|
+
rl?.resume();
|
|
83
|
+
return resolve(value);
|
|
84
|
+
}
|
|
85
|
+
if (ch === '\u0003') {
|
|
86
|
+
input.setRawMode(false);
|
|
87
|
+
io.output.write('\n');
|
|
88
|
+
process.exit(130);
|
|
89
|
+
}
|
|
90
|
+
if (ch === '\u007f' || ch === '\b') {
|
|
91
|
+
if (value.length) {
|
|
92
|
+
value = value.slice(0, -1);
|
|
93
|
+
io.output.write('\b \b');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else if (ch >= ' ') {
|
|
97
|
+
value += ch;
|
|
98
|
+
io.output.write('*');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
input.on('data', onData);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
async function confirm(question, defaultYes = false) {
|
|
106
|
+
if (io.yes)
|
|
107
|
+
return defaultYes;
|
|
108
|
+
const answer = (await ask(`${question} ${c.dim(defaultYes ? '[Y/n]' : '[y/N]')}`)).toLowerCase();
|
|
109
|
+
if (!answer)
|
|
110
|
+
return defaultYes;
|
|
111
|
+
return answer === 'y' || answer === 'yes';
|
|
112
|
+
}
|
|
113
|
+
async function choose(question, options, defaultIndex = 0) {
|
|
114
|
+
if (io.yes || options.length === 1)
|
|
115
|
+
return options[defaultIndex].value;
|
|
116
|
+
write(`${c.cyan('?')} ${question}`);
|
|
117
|
+
options.forEach((o, i) => write(` ${c.bold(String(i + 1))}) ${o.label}`));
|
|
118
|
+
for (;;) {
|
|
119
|
+
const answer = await ask('Enter a number', String(defaultIndex + 1));
|
|
120
|
+
const n = Number(answer);
|
|
121
|
+
if (Number.isInteger(n) && n >= 1 && n <= options.length)
|
|
122
|
+
return options[n - 1].value;
|
|
123
|
+
write(c.yellow(` Please enter a number from 1 to ${options.length}.`));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
write,
|
|
128
|
+
ask,
|
|
129
|
+
askHidden,
|
|
130
|
+
confirm,
|
|
131
|
+
choose,
|
|
132
|
+
success: (s) => write(`${c.green('✔')} ${s}`),
|
|
133
|
+
info: (s) => write(`${c.blue('ℹ')} ${s}`),
|
|
134
|
+
warn: (s) => write(`${c.yellow('!')} ${s}`),
|
|
135
|
+
error: (s) => write(`${c.red('✖')} ${s}`),
|
|
136
|
+
close: () => {
|
|
137
|
+
rl?.close();
|
|
138
|
+
rl = null;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|