@baclet/cli 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1539 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { copyFile, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { checkbox, confirm, input, select } from "@inquirer/prompts";
5
+ import fg from "fast-glob";
6
+ import { findConfig, loadConfig, loadModels } from "../config.js";
7
+ import { loadCredentials } from "../credentials.js";
8
+ import { request } from "../http.js";
9
+ import { scanSource, validateModels } from "./setup-diagnostics.js";
10
+
11
+ const runtimes = {
12
+ vite: { label: "Vite or browser (VITE_*)", prefix: "VITE_BACLET_", envSource: "import.meta" },
13
+ next: { label: "Next.js (NEXT_PUBLIC_*)", prefix: "NEXT_PUBLIC_BACLET_", envSource: "process" },
14
+ nuxt: { label: "Nuxt (NUXT_PUBLIC_*)", prefix: "NUXT_PUBLIC_BACLET_", envSource: "import.meta" },
15
+ node: { label: "Node.js or other (BACLET_*)", prefix: "BACLET_", envSource: "process" },
16
+ };
17
+
18
+ const languages = {
19
+ ts: "TypeScript",
20
+ js: "JavaScript",
21
+ };
22
+
23
+ const authMethodOptions = {
24
+ email: {
25
+ label: "Email sign-in and sign-up",
26
+ imports: ["createUserWithEmailAndPassword", "signInWithEmailAndPassword"],
27
+ },
28
+ google: {
29
+ label: "Google sign-in",
30
+ imports: ["getGoogleAuthorizationURL", "signInWithGoogle", "handleOAuthRedirect", "capabilities"],
31
+ },
32
+ guest: { label: "Anonymous sign-in", imports: ["signInAnonymously"] },
33
+ session: { label: "Session helpers", imports: ["getCurrentUser", "getIdToken", "signOut"] },
34
+ recovery: { label: "Password recovery", imports: ["forgotPassword", "resetPassword"] },
35
+ };
36
+
37
+ const fieldTypes = [
38
+ "string",
39
+ "text",
40
+ "integer",
41
+ "decimal",
42
+ "boolean",
43
+ "uuid",
44
+ "timestamp",
45
+ "date",
46
+ "json",
47
+ "enum",
48
+ ];
49
+
50
+ const fieldTypeAliases = {
51
+ int: "integer",
52
+ datetime: "timestamp",
53
+ bool: "boolean",
54
+ object: "json",
55
+ array: "json",
56
+ "string[]": "json",
57
+ };
58
+
59
+ const sensitiveField = /pass(word)?|secret|token|api[-_]?key|credential|session|cookie|authorization/i;
60
+ const genericNames = new Set([
61
+ "items", "data", "list", "rows", "options", "fields", "constraints", "entries", "values",
62
+ "children", "deps", "props", "state", "array", "objects", "records", "results", "content",
63
+ ]);
64
+
65
+ const storageOperationOptions = {
66
+ upload: { label: "Upload files", imports: ["uploadBytes"] },
67
+ url: { label: "Get download URLs", imports: ["getDownloadURL"] },
68
+ remove: { label: "Delete files", imports: ["deleteObject"] },
69
+ };
70
+
71
+ const databaseOperationOptions = {
72
+ list: { label: "List records", imports: ["get", "orderByChild", "equalTo", "limitToLast", "query"] },
73
+ get: { label: "Get one record", imports: ["get"] },
74
+ create: { label: "Create records", imports: ["push"] },
75
+ set: { label: "Replace records", imports: ["set"] },
76
+ update: { label: "Patch records", imports: ["update"] },
77
+ remove: { label: "Delete records", imports: ["remove"] },
78
+ };
79
+
80
+ const validationOptions = {
81
+ strict: "Required fields and allowed fields",
82
+ basic: "Allowed fields only",
83
+ none: "No runtime validation",
84
+ };
85
+
86
+ export const defaultIntent = {
87
+ authMethods: Object.keys(authMethodOptions).filter((method) => method !== "google"),
88
+ storageOps: Object.keys(storageOperationOptions),
89
+ databaseOps: Object.keys(databaseOperationOptions),
90
+ queryOptions: true,
91
+ validation: "strict",
92
+ };
93
+
94
+ export function normalizeIntent(options = {}) {
95
+ const intent = { ...defaultIntent, ...options };
96
+ for (const [key, allowed] of [
97
+ ["authMethods", Object.keys(authMethodOptions)],
98
+ ["storageOps", Object.keys(storageOperationOptions)],
99
+ ["databaseOps", Object.keys(databaseOperationOptions)],
100
+ ]) {
101
+ if (!Array.isArray(intent[key])) throw new Error(`${key} must be an array.`);
102
+ const unknown = intent[key].filter((value) => !allowed.includes(value));
103
+ if (unknown.length) throw new Error(`Unknown ${key}: ${unknown.join(", ")}.`);
104
+ intent[key] = [...new Set(intent[key])];
105
+ }
106
+ if (!validationOptions[intent.validation]) throw new Error(`Unknown validation mode "${intent.validation}".`);
107
+ if (typeof intent.queryOptions !== "boolean") throw new Error("queryOptions must be a boolean.");
108
+ return intent;
109
+ }
110
+
111
+ async function exists(file) {
112
+ try {
113
+ await stat(file);
114
+ return true;
115
+ } catch (error) {
116
+ if (error.code === "ENOENT") return false;
117
+ throw error;
118
+ }
119
+ }
120
+
121
+ async function isDirectory(file) {
122
+ try {
123
+ return (await stat(file)).isDirectory();
124
+ } catch (error) {
125
+ if (error.code === "ENOENT") return false;
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ async function readJson(file) {
131
+ try {
132
+ return JSON.parse(await readFile(file, "utf8"));
133
+ } catch (error) {
134
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return {};
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ export function resolveInside(root, target) {
140
+ const base = path.resolve(root);
141
+ const resolved = path.resolve(base, String(target ?? ""));
142
+ if (resolved === base || !resolved.startsWith(base + path.sep)) {
143
+ throw new Error("Generated files must stay inside the project root.");
144
+ }
145
+ return resolved;
146
+ }
147
+
148
+ function slug(value) {
149
+ const result = String(value)
150
+ .toLowerCase()
151
+ .replace(/[^a-z0-9]+/g, "-")
152
+ .replace(/^-+|-+$/g, "");
153
+ return result || "model";
154
+ }
155
+
156
+ function pascal(value) {
157
+ const words = String(value).split(/[^a-zA-Z0-9]+/).filter(Boolean);
158
+ const joined = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
159
+ const cleaned = joined.replace(/[^A-Za-z0-9]/g, "");
160
+ return /^[A-Za-z]/.test(cleaned) ? cleaned : `Model${cleaned}`;
161
+ }
162
+
163
+ function propertyKey(name) {
164
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
165
+ }
166
+
167
+ function normalizeName(value, fallback = "model") {
168
+ const result = String(value ?? "")
169
+ .toLowerCase()
170
+ .replace(/[^a-z0-9]+/g, "_")
171
+ .replace(/^_+|_+$/g, "");
172
+ return result || fallback;
173
+ }
174
+
175
+ function pluralize(value) {
176
+ if (/s$/.test(value)) return value;
177
+ if (/(ch|sh|x|z)$/.test(value)) return `${value}es`;
178
+ if (/y$/.test(value) && !/[aeiou]y$/.test(value)) return `${value.slice(0, -1)}ies`;
179
+ return `${value}s`;
180
+ }
181
+
182
+ function inferType(name) {
183
+ if (/^(id|uuid|guid)$/.test(name)) return "uuid";
184
+ if (/price|amount|cost|total|rating|score|quantity|count|age|weight|height/.test(name)) {
185
+ return /quantity|count|age|rating|score/.test(name) ? "integer" : "decimal";
186
+ }
187
+ if (/created|updated|_at$|date|time|deadline/.test(name)) return "timestamp";
188
+ if (/^(is|has|can|should)_|active|enabled|published|verified|paid|available/.test(name)) return "boolean";
189
+ if (/^(status|role|state|kind|category|type)$/.test(name)) return "enum";
190
+ if (/content|description|body|message|bio|notes?|html|markdown/.test(name)) return "text";
191
+ if (/image|photo|avatar|thumbnail|picture/.test(name)) return "string";
192
+ return "string";
193
+ }
194
+
195
+ function escapeRegExp(value) {
196
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
197
+ }
198
+
199
+ function splitTopLevel(text, delimiter) {
200
+ const parts = [];
201
+ let current = "";
202
+ let depth = 0;
203
+ let quote = null;
204
+ for (const char of text) {
205
+ if (quote) {
206
+ current += char;
207
+ if (char === quote) quote = null;
208
+ continue;
209
+ }
210
+ if (char === '"' || char === "'" || char === "`") {
211
+ quote = char;
212
+ current += char;
213
+ continue;
214
+ }
215
+ if ("([{".includes(char)) depth++;
216
+ if (")]}".includes(char)) depth--;
217
+ if (char === delimiter && depth === 0) {
218
+ parts.push(current);
219
+ current = "";
220
+ continue;
221
+ }
222
+ current += char;
223
+ }
224
+ parts.push(current);
225
+ return parts;
226
+ }
227
+
228
+ function parseLiteral(value) {
229
+ const trimmed = value.trim();
230
+ try {
231
+ return JSON.parse(trimmed);
232
+ } catch {
233
+ return trimmed;
234
+ }
235
+ }
236
+
237
+ function parseFieldDraft(segment) {
238
+ const trimmed = segment.trim();
239
+ if (!trimmed) return null;
240
+ const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*([A-Za-z][A-Za-z0-9[\]]*))?([\s\S]*)$/);
241
+ if (!match) return { error: `Cannot parse field "${trimmed}".` };
242
+
243
+ const name = normalizeName(match[1], "");
244
+ if (!name) return { error: `Invalid field name in "${trimmed}".` };
245
+ if (sensitiveField.test(name)) return { warnings: [`Skipped sensitive field "${name}".`] };
246
+
247
+ const requestedType = (match[2] || "string").toLowerCase();
248
+ let type = fieldTypeAliases[requestedType] || requestedType;
249
+ let rest = (match[3] || "").trim();
250
+ if (requestedType === "ref") {
251
+ type = "string";
252
+ rest = `ref${rest}`;
253
+ }
254
+ if (!fieldTypes.includes(type)) {
255
+ return { error: `Unknown type "${requestedType}" for ${name}. Allowed: ${fieldTypes.join(", ")}.` };
256
+ }
257
+
258
+ const field = { type };
259
+ const parenthesized = rest.match(/\(([^)]*)\)/);
260
+ if (parenthesized) {
261
+ rest = rest.replace(parenthesized[0], " ").trim();
262
+ if (type === "enum") {
263
+ const values = parenthesized[1].split("|").map((value) => value.trim()).filter(Boolean);
264
+ if (!values.length) return { error: `Enum field ${name} needs values, for example ${name}:enum(admin|user).` };
265
+ field.values = values;
266
+ } else if (type === "decimal") {
267
+ const [precision, scale] = parenthesized[1].split(",").map((value) => Number(value.trim()));
268
+ if (Number.isInteger(precision) && precision > 0) field.precision = precision;
269
+ if (Number.isInteger(scale) && scale >= 0) field.scale = scale;
270
+ }
271
+ }
272
+
273
+ for (const token of rest.split(/[\s,]+/).filter(Boolean)) {
274
+ if (/^[!*+]+$/.test(token)) {
275
+ for (const flag of token) {
276
+ if (flag === "!") field.required = true;
277
+ if (flag === "*") field.unique = true;
278
+ if (flag === "+") field.index = true;
279
+ }
280
+ } else if (token === "@now") field.default = { expr: "now()" };
281
+ else if (token.startsWith("ref:")) {
282
+ const [refModel, refField] = token.slice(4).split(".");
283
+ if (!refModel) return { error: `Reference for ${name} needs a model name.` };
284
+ field.reference = { model: normalizeName(refModel), ...(refField ? { field: normalizeName(refField) } : {}) };
285
+ } else if (token.startsWith("ondelete:")) {
286
+ const onDelete = token.slice(9).replace(/_/g, " ");
287
+ if (!["cascade", "restrict", "set null"].includes(onDelete)) {
288
+ return { error: `onDelete for ${name} must be cascade, restrict, or set null.` };
289
+ }
290
+ field.reference = { ...(field.reference ?? {}), model: field.reference?.model ?? "", onDelete };
291
+ } else if (token.startsWith("default:")) {
292
+ field.default = parseLiteral(token.slice(8));
293
+ } else {
294
+ return { error: `Unknown option "${token}" for ${name}.` };
295
+ }
296
+ }
297
+ if (field.reference && !field.reference.model) {
298
+ return { error: `Reference for ${name} needs a model name.` };
299
+ }
300
+ return { name, field };
301
+ }
302
+
303
+ export function parseFieldsDraft(text) {
304
+ const fields = {};
305
+ const errors = [];
306
+ const warnings = [];
307
+ for (const segment of splitTopLevel(String(text ?? ""), ",")) {
308
+ const parsed = parseFieldDraft(segment);
309
+ if (!parsed) continue;
310
+ if (parsed.error) errors.push(parsed.error);
311
+ if (parsed.warnings) warnings.push(...parsed.warnings);
312
+ if (parsed.name) fields[parsed.name] = parsed.field;
313
+ }
314
+ return { fields, errors, warnings };
315
+ }
316
+
317
+ export function normalizeModelDraft(name, fields) {
318
+ const normalized = { name: normalizeName(name), fields: { ...fields } };
319
+ for (const [fieldName, field] of Object.entries(normalized.fields)) {
320
+ if (!/^[a-z0-9_]+$/.test(fieldName)) throw new Error(`Invalid field name "${fieldName}".`);
321
+ if (!fieldTypes.includes(field?.type)) throw new Error(`Unknown type "${field?.type}" for ${fieldName}.`);
322
+ if (field.type === "enum" && !Array.isArray(field.values)) {
323
+ throw new Error(`Enum field ${fieldName} needs a values array.`);
324
+ }
325
+ }
326
+ if (!normalized.fields.created_at) {
327
+ normalized.fields.created_at = { type: "timestamp", default: { expr: "now()" } };
328
+ }
329
+ if (!normalized.fields.updated_at) {
330
+ normalized.fields.updated_at = { type: "timestamp", default: { expr: "now()" } };
331
+ }
332
+ return normalized;
333
+ }
334
+
335
+ function renderField(field) {
336
+ const parts = [`type: ${JSON.stringify(field.type)}`];
337
+ if (field.required) parts.push("required: true");
338
+ if (field.unique) parts.push("unique: true");
339
+ if (field.index) parts.push("index: true");
340
+ if (field.values?.length) parts.push(`values: ${JSON.stringify(field.values)}`);
341
+ if (field.type === "decimal") {
342
+ if (field.precision) parts.push(`precision: ${field.precision}`);
343
+ if (field.scale !== undefined) parts.push(`scale: ${field.scale}`);
344
+ }
345
+ if (field.reference?.model) {
346
+ const reference = [`model: ${JSON.stringify(field.reference.model)}`];
347
+ if (field.reference.field) reference.push(`field: ${JSON.stringify(field.reference.field)}`);
348
+ if (field.reference.onDelete) reference.push(`onDelete: ${JSON.stringify(field.reference.onDelete)}`);
349
+ parts.push(`reference: { ${reference.join(", ")} }`);
350
+ }
351
+ if (Object.prototype.hasOwnProperty.call(field, "default")) {
352
+ parts.push(
353
+ field.default && typeof field.default === "object" && !Array.isArray(field.default)
354
+ ? `default: { expr: ${JSON.stringify(field.default.expr)} }`
355
+ : `default: ${JSON.stringify(field.default)}`,
356
+ );
357
+ }
358
+ return `{ ${parts.join(", ")} }`;
359
+ }
360
+
361
+ export function renderModelFile(model) {
362
+ const lines = [
363
+ 'import { defineModel } from "@baclet/sdk";',
364
+ "",
365
+ `export const ${pascal(model.name)} = defineModel({`,
366
+ ` name: ${JSON.stringify(model.name)},`,
367
+ " fields: {",
368
+ ];
369
+ for (const [name, field] of Object.entries(model.fields)) {
370
+ lines.push(` ${propertyKey(name)}: ${renderField(field)},`);
371
+ }
372
+ lines.push(" },", "});", "");
373
+ return lines.join("\n");
374
+ }
375
+
376
+ export function formatFieldDraft(fields = {}) {
377
+ const entries = Object.entries(fields)
378
+ .filter(([name]) => !["created_at", "updated_at"].includes(name))
379
+ .map(([name, field]) => {
380
+ let value = `${name}:${field?.type ?? "string"}`;
381
+ if (field?.values?.length) value += `(${field.values.join("|")})`;
382
+ else if (field?.type === "decimal" && field.precision) value += `(${field.precision},${field.scale ?? 0})`;
383
+ if (field?.required) value += "!";
384
+ if (field?.unique) value += "*";
385
+ if (field?.index) value += "+";
386
+ if (field?.default && typeof field.default === "object") value += " @now";
387
+ if (field?.reference?.model) {
388
+ value += ` ref:${field.reference.model}${field.reference.field ? `.${field.reference.field}` : ""}`;
389
+ }
390
+ return value;
391
+ });
392
+ return entries.join(", ");
393
+ }
394
+
395
+ export function modelDirFromPatterns(root, patterns = []) {
396
+ for (const raw of patterns) {
397
+ const cleaned = String(raw).replace(/\\/g, "/");
398
+ const parts = cleaned.split("/");
399
+ const wildcard = parts.findIndex((part) => /[*?{\[]/.test(part));
400
+ const dirParts = (wildcard >= 0 ? parts.slice(0, wildcard) : parts.slice(0, -1)).filter(Boolean);
401
+ const dir = cleaned.startsWith("/") ? path.resolve("/", ...dirParts) : path.resolve(root, ...dirParts);
402
+ try {
403
+ resolveInside(root, dir);
404
+ return { dir, ext: cleaned.match(/\.(m?[jt]s)$/)?.[1] ?? ".ts" };
405
+ } catch {
406
+ continue;
407
+ }
408
+ }
409
+ return { dir: path.join(root, "models"), ext: ".ts" };
410
+ }
411
+
412
+ export function buildModelPlan({ root, patterns = [], models = [] }) {
413
+ const { dir, ext } = modelDirFromPatterns(root, patterns);
414
+ const seen = new Set();
415
+ const plan = [];
416
+ for (const model of models) {
417
+ const fileName = `${normalizeName(model.name)}.${ext}`;
418
+ if (seen.has(fileName)) throw new Error(`Duplicate model name "${model.name}".`);
419
+ seen.add(fileName);
420
+ plan.push({
421
+ path: path.join(dir, fileName),
422
+ content: renderModelFile(model),
423
+ merge: null,
424
+ });
425
+ }
426
+ return plan;
427
+ }
428
+
429
+ const ignoredFieldNames = new Set([
430
+ "id", "key", "children", "classname", "style", "onclick", "onchange", "onsubmit",
431
+ "defaultvalue", "placeholder", "required", "disabled", "rows", "cols", "href", "src",
432
+ "alt", "props", "state", "index", "length", "constructor", "prototype", "args", "argv",
433
+ ]);
434
+
435
+ function extractFieldNames(content, names) {
436
+ const found = new Map();
437
+ const add = (raw) => {
438
+ const name = normalizeName(raw, "");
439
+ if (!name || sensitiveField.test(name) || ignoredFieldNames.has(name)) return;
440
+ if (name === "created_at" || name === "updated_at") return;
441
+ found.set(name, (found.get(name) ?? 0) + 1);
442
+ };
443
+
444
+ for (const match of content.matchAll(/<(?:input|textarea|select)\b[^>]*?\b(?:name|placeholder|aria-label|id)\s*=\s*["']([^"']+)["']/gi)) {
445
+ add(match[1]);
446
+ }
447
+ for (const match of content.matchAll(/<label\b[^>]*>([\s\S]{0,160}?)<\/label>/gi)) {
448
+ add(match[1].replace(/<[^>]+>/g, " ").trim());
449
+ }
450
+ for (const name of names) {
451
+ const singular = name.endsWith("ies") ? `${name.slice(0, -3)}y` : name.replace(/s$/, "");
452
+ const access = new RegExp(`\\b(?:${escapeRegExp(singular)}|item|row|record|entry)\\s*\\.\\s*([A-Za-z_][A-Za-z0-9_]*)`, "g");
453
+ for (const match of content.matchAll(access)) add(match[1]);
454
+ }
455
+ for (const match of content.matchAll(/(?:^|[{,\s])([A-Za-z_][A-Za-z0-9_]*)\s*:\s*[^,\n}]+/gm)) {
456
+ add(match[1]);
457
+ }
458
+
459
+ return [...found.entries()]
460
+ .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0]))
461
+ .slice(0, 12)
462
+ .map(([name]) => ({ name, type: inferType(name) }));
463
+ }
464
+
465
+ export async function suggestModels(root, options = {}) {
466
+ const files = await fg(["**/*.{ts,tsx,js,jsx,vue,svelte}"], {
467
+ cwd: root,
468
+ absolute: true,
469
+ onlyFiles: true,
470
+ suppressErrors: true,
471
+ ignore: [
472
+ "**/node_modules/**", "**/dist/**", "**/build/**", "**/.next/**", "**/.nuxt/**",
473
+ "**/coverage/**", "**/lib/**", "**/models/**", "**/*.test.*", "**/*.spec.*",
474
+ "baclet.config.*",
475
+ ],
476
+ });
477
+
478
+ const byName = new Map();
479
+ for (const file of files.slice(0, options.maxFiles ?? 60)) {
480
+ const content = await readFile(file, "utf8").catch(() => "");
481
+ if (!content || content.length > 200_000) continue;
482
+
483
+ const names = [];
484
+ const base = path.basename(file).replace(/\.[^.]+$/, "");
485
+ const cleaned = normalizeName(base.replace(/[-_](card|item|list|page|modal|panel|form|view|detail|details|table|row)$/i, ""), "");
486
+ if (cleaned && !genericNames.has(cleaned)) names.push(pluralize(cleaned));
487
+
488
+ for (const pattern of [
489
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*\[/g,
490
+ /\b([A-Za-z_$][\w$]*)\s*:\s*\[/g,
491
+ ]) {
492
+ for (const match of content.matchAll(pattern)) {
493
+ const candidate = normalizeName(match[1], "");
494
+ if (candidate && !genericNames.has(candidate)) names.push(pluralize(candidate));
495
+ }
496
+ }
497
+ for (const match of content.matchAll(/\b(?:collection|model|table|resource)\s*[:=]\s*["']([a-z0-9_]+)["']/g)) {
498
+ names.push(match[1]);
499
+ }
500
+
501
+ const fields = extractFieldNames(content, names);
502
+ if (!fields.length) continue;
503
+ for (const name of [...new Set(names)].slice(0, 3)) {
504
+ const current = byName.get(name) ?? { name, fields: {}, source: path.relative(root, file) };
505
+ for (const field of fields) {
506
+ current.fields[field.name] = field.type;
507
+ }
508
+ byName.set(name, current);
509
+ }
510
+ }
511
+
512
+ return [...byName.values()]
513
+ .map((entry) => ({
514
+ name: entry.name,
515
+ fields: Object.fromEntries(Object.entries(entry.fields).map(([name, type]) => [name, { type }])),
516
+ source: entry.source,
517
+ }))
518
+ .sort((left, right) => Object.keys(right.fields).length - Object.keys(left.fields).length)
519
+ .slice(0, options.limit ?? 6);
520
+ }
521
+
522
+ export async function checkGoogleAuth({ root, projectId, requestFn = request, credentialsFn = loadCredentials } = {}) {
523
+ const credentials = await credentialsFn();
524
+ if (!credentials?.accessToken) {
525
+ return { enabled: false, checked: false, reason: "not logged in" };
526
+ }
527
+ try {
528
+ const payload = await requestFn({
529
+ method: "GET",
530
+ path: "/api/v1/me/projects",
531
+ token: credentials.accessToken,
532
+ });
533
+ const selected = (payload?.projects ?? []).find(
534
+ (project) => project.id === projectId || project.uuid === projectId,
535
+ );
536
+ if (!selected?.workspace_slug || !selected?.slug) {
537
+ return { enabled: false, checked: false, reason: "project not found" };
538
+ }
539
+ const settings = await requestFn({
540
+ method: "GET",
541
+ path: `/api/v1/workspaces/${encodeURIComponent(selected.workspace_slug)}/projects/${encodeURIComponent(selected.slug)}/auth/settings`,
542
+ token: credentials.accessToken,
543
+ });
544
+ const provider = settings?.providers?.google;
545
+ const status = provider?.validation?.status;
546
+ const enabled = provider?.enabled === true && (status === "configuration_valid" || status === undefined);
547
+ return {
548
+ enabled,
549
+ checked: true,
550
+ reason: enabled ? "enabled" : provider?.validation?.error || "Google sign-in is disabled",
551
+ callbackUrl: settings?.callback_urls?.google,
552
+ };
553
+ } catch (error) {
554
+ return { enabled: false, checked: false, reason: error.message };
555
+ }
556
+ }
557
+
558
+ function fieldType(field) {
559
+ const type = field?.type;
560
+ if (["string", "text", "uuid"].includes(type)) return "string";
561
+ if (["integer", "decimal"].includes(type)) return "number";
562
+ if (type === "boolean") return "boolean";
563
+ if (["timestamp", "date"].includes(type)) return "string";
564
+ if (type === "json") return "unknown";
565
+ if (type === "enum") {
566
+ const values = Array.isArray(field.values) ? field.values : [];
567
+ return values.length ? values.map((value) => JSON.stringify(String(value))).join(" | ") : "string";
568
+ }
569
+ return "unknown";
570
+ }
571
+
572
+ function hasDefault(field) {
573
+ return Object.prototype.hasOwnProperty.call(field ?? {}, "default");
574
+ }
575
+
576
+ function recordType(model, language, input) {
577
+ if (language !== "ts") return "";
578
+ const lines = Object.entries(model.fields).map(([name, field]) => {
579
+ const optional = input ? !field?.required || hasDefault(field) : !field?.required;
580
+ return ` ${propertyKey(name)}${optional ? "?" : ""}: ${fieldType(field)};`;
581
+ });
582
+ if (!input) lines.push(" key?: string;");
583
+ return lines.join("\n");
584
+ }
585
+
586
+ function modelMetadata(models) {
587
+ const usedFiles = new Set();
588
+ const usedIdentifiers = new Set(["authActions", "storageActions", "baclet"]);
589
+ const usedTypes = new Set();
590
+
591
+ return models.map((model) => {
592
+ let fileBase = slug(model.name);
593
+ if (["auth", "storage", "baclet", "index"].includes(fileBase)) fileBase = `model-${fileBase}`;
594
+ let fileName = fileBase;
595
+ let fileIndex = 2;
596
+ while (usedFiles.has(fileName)) fileName = `${fileBase}-${fileIndex++}`;
597
+ usedFiles.add(fileName);
598
+
599
+ const baseName = pascal(model.name);
600
+ let identifier = `${baseName.charAt(0).toLowerCase()}${baseName.slice(1)}Actions`;
601
+ let identifierIndex = 2;
602
+ while (usedIdentifiers.has(identifier)) identifier = `${baseName}Actions${identifierIndex++}`;
603
+ usedIdentifiers.add(identifier);
604
+
605
+ let typeBase = baseName;
606
+ let typeIndex = 2;
607
+ while (usedTypes.has(typeBase)) typeBase = `${baseName}${typeIndex++}`;
608
+ usedTypes.add(typeBase);
609
+
610
+ return {
611
+ model,
612
+ fileName,
613
+ identifier,
614
+ recordName: `${typeBase}Record`,
615
+ inputName: `${typeBase}Input`,
616
+ };
617
+ });
618
+ }
619
+
620
+ function envExpression(runtime, language) {
621
+ if (runtime === "vite" || runtime === "nuxt") {
622
+ if (language === "ts") {
623
+ return "(import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}";
624
+ }
625
+ return "import.meta.env ?? {}";
626
+ }
627
+ if (language === "ts") {
628
+ return "(globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}";
629
+ }
630
+ return "globalThis.process?.env ?? {}";
631
+ }
632
+
633
+ function clientFile(runtime, language, features) {
634
+ const spec = runtimes[runtime];
635
+ const publishableKey = `${spec.prefix}PUBLISHABLE_KEY`;
636
+ const apiUrl = `${spec.prefix}API_URL`;
637
+ const storageBucket = `${spec.prefix}STORAGE_BUCKET`;
638
+ const lines = [`import { initializeBaclet } from "@baclet/sdk";`];
639
+
640
+ if (features.includes("database")) {
641
+ lines.push(`import { enableDatabasePersistence } from "@baclet/sdk/database";`);
642
+ }
643
+ lines.push("", `const env = ${envExpression(runtime, language)};`, "");
644
+ lines.push(`const publishableKey = env.${publishableKey};`);
645
+ lines.push("if (!publishableKey) {");
646
+ lines.push(` throw new Error("Missing ${publishableKey}. Copy .env.example to .env and set your BACLET publishable key.");`);
647
+ lines.push("}", "");
648
+ lines.push("export const baclet = initializeBaclet({");
649
+ lines.push(` apiUrl: env.${apiUrl} || "https://api.baclet.app",`);
650
+ lines.push(" publishableKey,");
651
+ if (features.includes("storage")) {
652
+ lines.push(` ...(env.${storageBucket} ? { storageBucket: env.${storageBucket} } : {}),`);
653
+ }
654
+ lines.push("});");
655
+ if (features.includes("database")) {
656
+ lines.push("", "enableDatabasePersistence();");
657
+ }
658
+ return `${lines.join("\n")}\n`;
659
+ }
660
+
661
+ function authFile(language, methods) {
662
+ const imports = [...new Set(["getAuth", ...methods.flatMap((method) => authMethodOptions[method].imports)])];
663
+ const entries = [];
664
+ if (methods.includes("email")) {
665
+ entries.push(
666
+ language === "ts"
667
+ ? " signIn: (email: string, password: string) => signInWithEmailAndPassword(auth, email, password),"
668
+ : " signIn: (email, password) => signInWithEmailAndPassword(auth, email, password),",
669
+ language === "ts"
670
+ ? " signUp: (email: string, password: string, fullName?: string) =>"
671
+ : " signUp: (email, password, fullName) =>",
672
+ " createUserWithEmailAndPassword(auth, email, password, fullName),",
673
+ );
674
+ }
675
+ if (methods.includes("google")) {
676
+ entries.push(
677
+ language === "ts"
678
+ ? " signInWithGoogle: (redirectTo?: string) => signInWithGoogle(auth, redirectTo ? { redirectTo } : {}),"
679
+ : " signInWithGoogle: (redirectTo) => signInWithGoogle(auth, redirectTo ? { redirectTo } : {}),",
680
+ " handleOAuthRedirect: () => handleOAuthRedirect(auth),",
681
+ language === "ts"
682
+ ? " googleAuthorizationURL: (redirectTo?: string) =>"
683
+ : " googleAuthorizationURL: (redirectTo) =>",
684
+ " getGoogleAuthorizationURL(auth, redirectTo ? { redirectTo } : {}),",
685
+ " authCapabilities: () => capabilities(auth),",
686
+ );
687
+ }
688
+ if (methods.includes("guest")) {
689
+ entries.push(" signInAsGuest: () => signInAnonymously(auth),");
690
+ }
691
+ if (methods.includes("session")) {
692
+ entries.push(
693
+ " signOut: () => signOut(auth),",
694
+ " currentUser: () => getCurrentUser(auth),",
695
+ " idToken: () => getIdToken(auth),",
696
+ );
697
+ }
698
+ if (methods.includes("recovery")) {
699
+ entries.push(
700
+ language === "ts"
701
+ ? " forgotPassword: (email: string) => forgotPassword(auth, email),"
702
+ : " forgotPassword: (email) => forgotPassword(auth, email),",
703
+ language === "ts"
704
+ ? " resetPassword: (token: string, password: string) => resetPassword(auth, token, password),"
705
+ : " resetPassword: (token, password) => resetPassword(auth, token, password),",
706
+ );
707
+ }
708
+
709
+ const lines = [
710
+ "import {",
711
+ ...imports.map((name) => ` ${name},`),
712
+ '} from "@baclet/sdk/auth";',
713
+ 'import { baclet } from "../baclet.js";',
714
+ "",
715
+ "const auth = getAuth(baclet);",
716
+ "",
717
+ "export const authActions = {",
718
+ ...entries,
719
+ "};",
720
+ ];
721
+ return `${lines.join("\n")}\n`;
722
+ }
723
+
724
+ function storageFile(language, operations) {
725
+ const imports = [...new Set(["getStorage", "ref", ...operations.flatMap((operation) => storageOperationOptions[operation].imports)])];
726
+ const entries = [];
727
+ if (operations.includes("upload")) {
728
+ entries.push(
729
+ language === "ts"
730
+ ? " upload: (path: string, file: Blob, metadata: UploadMetadata = {}) =>"
731
+ : " upload: (path, file, metadata = {}) =>",
732
+ " uploadBytes(ref(storage, path), file, metadata),",
733
+ );
734
+ }
735
+ if (operations.includes("url")) {
736
+ entries.push(
737
+ language === "ts"
738
+ ? " url: (path: string) => getDownloadURL(ref(storage, path)),"
739
+ : " url: (path) => getDownloadURL(ref(storage, path)),",
740
+ );
741
+ }
742
+ if (operations.includes("remove")) {
743
+ entries.push(
744
+ language === "ts"
745
+ ? " remove: (path: string) => deleteObject(ref(storage, path)),"
746
+ : " remove: (path) => deleteObject(ref(storage, path)),",
747
+ );
748
+ }
749
+
750
+ const lines = ["import {", ...imports.map((name) => ` ${name},`), '} from "@baclet/sdk/storage";'];
751
+ if (language === "ts" && operations.includes("upload")) {
752
+ lines.push('import type { UploadMetadata } from "@baclet/sdk/storage";');
753
+ }
754
+ lines.push(
755
+ 'import { baclet } from "../baclet.js";',
756
+ "",
757
+ "const storage = getStorage(baclet);",
758
+ "",
759
+ "export const storageActions = {",
760
+ ...entries,
761
+ "};",
762
+ );
763
+ return `${lines.join("\n")}\n`;
764
+ }
765
+
766
+ function modelFile(meta, language, intent) {
767
+ const { model, identifier, recordName, inputName } = meta;
768
+ const fields = Object.keys(model.fields);
769
+ const requiredFields = fields.filter((field) => model.fields[field]?.required === true);
770
+ const operations = intent.databaseOps;
771
+ const keyedOperations = operations.filter((operation) => ["get", "set", "update", "remove"].includes(operation));
772
+ const writeOperations = operations.filter((operation) => ["create", "set", "update"].includes(operation));
773
+ const usesQuery = operations.includes("list") && intent.queryOptions;
774
+ const validates = intent.validation !== "none" && writeOperations.length > 0;
775
+ const validatesRequired = intent.validation === "strict" && validates;
776
+ const needsAllowedFields = usesQuery || validates;
777
+
778
+ const imports = [...new Set([
779
+ "getDatabase",
780
+ "ref",
781
+ ...operations.flatMap((operation) =>
782
+ operation === "list" && !usesQuery ? ["get"] : databaseOperationOptions[operation].imports,
783
+ ),
784
+ ])];
785
+ const lines = ["import {", ...imports.map((name) => ` ${name},`), '} from "@baclet/sdk/database";'];
786
+ if (language === "ts" && usesQuery) {
787
+ lines.push('import type { QueryConstraint } from "@baclet/sdk/database";');
788
+ }
789
+ lines.push(
790
+ 'import { baclet } from "../baclet.js";',
791
+ "",
792
+ "const database = getDatabase(baclet);",
793
+ `const collection = ${JSON.stringify(model.name)};`,
794
+ );
795
+ if (needsAllowedFields) {
796
+ lines.push(
797
+ language === "ts"
798
+ ? `const allowedFields = new Set<string>(${JSON.stringify(fields)});`
799
+ : `const allowedFields = new Set(${JSON.stringify(fields)});`,
800
+ );
801
+ }
802
+ if (validatesRequired) {
803
+ lines.push(`const requiredFields = new Set(${JSON.stringify(requiredFields)});`);
804
+ }
805
+
806
+ if (keyedOperations.length) {
807
+ lines.push(
808
+ "",
809
+ language === "ts" ? "function assertKey(key: string) {" : "function assertKey(key) {",
810
+ ' if (!key || key.includes("/") || key.includes("..")) {',
811
+ ' throw new Error("Invalid BACLET record key.");',
812
+ " }",
813
+ " return key;",
814
+ "}",
815
+ );
816
+ }
817
+
818
+ if (validates) {
819
+ lines.push(
820
+ "",
821
+ language === "ts"
822
+ ? "function assertValues(values: object, requireAll: boolean) {"
823
+ : "function assertValues(values, requireAll) {",
824
+ ' if (!values || typeof values !== "object" || Array.isArray(values)) {',
825
+ ' throw new Error("Invalid BACLET record values.");',
826
+ " }",
827
+ " const entries = Object.entries(values);",
828
+ " for (const [key] of entries) {",
829
+ " if (!allowedFields.has(key)) {",
830
+ ' throw new Error(`Unknown field "${key}" for ${collection}.`);',
831
+ " }",
832
+ " }",
833
+ );
834
+ if (validatesRequired) {
835
+ lines.push(
836
+ " if (requireAll) {",
837
+ " for (const key of requiredFields) {",
838
+ " if (!entries.some(([entryKey, value]) => entryKey === key && value !== undefined)) {",
839
+ ' throw new Error(`Missing required field "${key}" for ${collection}.`);',
840
+ " }",
841
+ " }",
842
+ " }",
843
+ );
844
+ }
845
+ lines.push("}");
846
+ }
847
+
848
+ if (language === "ts") {
849
+ lines.push("", `export type ${recordName} = {`, recordType(model, language, false), "};");
850
+ lines.push("", `export type ${inputName} = {`, recordType(model, language, true), "};");
851
+ }
852
+
853
+ const entries = [];
854
+ if (operations.includes("list")) {
855
+ entries.push(
856
+ usesQuery
857
+ ? language === "ts"
858
+ ? " list: async (options: { field?: string; equalTo?: unknown; limit?: number } = {}) => {"
859
+ : " list: async (options = {}) => {"
860
+ : " list: async () => {",
861
+ " let reference = ref(database, collection);",
862
+ );
863
+ if (usesQuery) {
864
+ entries.push(
865
+ " const constraints = " + (language === "ts" ? "[] as QueryConstraint[]" : "[]") + ";",
866
+ " if (options.field) {",
867
+ " if (!allowedFields.has(options.field)) {",
868
+ ' throw new Error(`Unknown field "${options.field}" for ${collection}.`);',
869
+ " }",
870
+ " constraints.push(orderByChild(options.field));",
871
+ " } else if (options.equalTo !== undefined) {",
872
+ ' throw new Error("equalTo requires a field.");',
873
+ " }",
874
+ " if (options.equalTo !== undefined) constraints.push(equalTo(options.equalTo));",
875
+ " if (options.limit !== undefined) {",
876
+ " if (!Number.isInteger(options.limit) || options.limit < 1) {",
877
+ ' throw new Error("limit must be a positive integer.");',
878
+ " }",
879
+ " constraints.push(limitToLast(options.limit));",
880
+ " }",
881
+ " if (constraints.length) reference = query(reference, ...constraints);",
882
+ );
883
+ }
884
+ entries.push(
885
+ " const snapshot = await get(reference);",
886
+ language === "ts"
887
+ ? ` return Object.values((snapshot.val() ?? {}) as Record<string, ${recordName}>);`
888
+ : " return Object.values(snapshot.val() ?? {});",
889
+ " },",
890
+ );
891
+ }
892
+ if (operations.includes("get")) {
893
+ entries.push(
894
+ language === "ts" ? " get: async (key: string) => {" : " get: async (key) => {",
895
+ " const snapshot = await get(ref(database, `${collection}/${assertKey(key)}`));",
896
+ language === "ts"
897
+ ? ` return snapshot.exists() ? (snapshot.val() as ${recordName}) : null;`
898
+ : " return snapshot.exists() ? snapshot.val() : null;",
899
+ " },",
900
+ );
901
+ }
902
+ if (operations.includes("create")) {
903
+ entries.push(
904
+ language === "ts" ? ` create: (values: ${inputName}) => {` : " create: (values) => {",
905
+ ...(validates ? [" assertValues(values, " + (validatesRequired ? "true" : "false") + ");"] : []),
906
+ " return push(ref(database, collection), values);",
907
+ " },",
908
+ );
909
+ }
910
+ if (operations.includes("set")) {
911
+ entries.push(
912
+ language === "ts" ? ` set: (key: string, values: ${inputName}) => {` : " set: (key, values) => {",
913
+ ...(validates ? [" assertValues(values, " + (validatesRequired ? "true" : "false") + ");"] : []),
914
+ " return set(ref(database, `${collection}/${assertKey(key)}`), values);",
915
+ " },",
916
+ );
917
+ }
918
+ if (operations.includes("update")) {
919
+ entries.push(
920
+ language === "ts" ? ` update: (key: string, values: Partial<${inputName}>) => {` : " update: (key, values) => {",
921
+ ...(validates ? [" assertValues(values, false);"] : []),
922
+ language === "ts"
923
+ ? " return update(ref(database, `${collection}/${assertKey(key)}`), values as Record<string, unknown>);"
924
+ : " return update(ref(database, `${collection}/${assertKey(key)}`), values);",
925
+ " },",
926
+ );
927
+ }
928
+ if (operations.includes("remove")) {
929
+ entries.push(
930
+ language === "ts"
931
+ ? " remove: (key: string) => remove(ref(database, `${collection}/${assertKey(key)}`)),"
932
+ : " remove: (key) => remove(ref(database, `${collection}/${assertKey(key)}`)),",
933
+ );
934
+ }
935
+
936
+ lines.push("", `export const ${identifier} = {`, ...entries, "};");
937
+ return `${lines.join("\n")}\n`;
938
+ }
939
+
940
+ function indexFile(language, features, metadata) {
941
+ const lines = ['export { baclet } from "./baclet.js";'];
942
+ if (features.includes("auth")) lines.push('export { authActions } from "./actions/auth.js";');
943
+ if (features.includes("storage")) lines.push('export { storageActions } from "./actions/storage.js";');
944
+ for (const meta of metadata) {
945
+ lines.push(`export { ${meta.identifier} } from "./actions/${meta.fileName}.js";`);
946
+ if (language === "ts") {
947
+ lines.push(`export type { ${meta.inputName}, ${meta.recordName} } from "./actions/${meta.fileName}.js";`);
948
+ }
949
+ }
950
+ return `${lines.join("\n")}\n`;
951
+ }
952
+
953
+ function envKeys(runtime, storage) {
954
+ const prefix = runtimes[runtime].prefix;
955
+ const keys = [
956
+ { name: `${prefix}PUBLISHABLE_KEY`, value: "pb_your_publishable_key" },
957
+ { name: `${prefix}API_URL`, value: "https://api.baclet.app" },
958
+ ];
959
+ if (storage) keys.push({ name: `${prefix}STORAGE_BUCKET`, value: "your_storage_bucket" });
960
+ return keys;
961
+ }
962
+
963
+ export function mergeEnvExample(existing, keys) {
964
+ const present = new Set();
965
+ for (const line of existing.split(/\r?\n/)) {
966
+ const match = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
967
+ if (match) present.add(match[1]);
968
+ }
969
+ const missing = keys.filter((key) => !present.has(key.name));
970
+ if (!missing.length) return { content: existing, changed: false };
971
+ const separator = existing.length === 0 ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
972
+ const addition = `${missing.map((key) => `${key.name}=${key.value}`).join("\n")}\n`;
973
+ return { content: `${existing}${separator}${addition}`, changed: true };
974
+ }
975
+
976
+ export function mergeGitignore(existing, entries) {
977
+ const present = new Set(
978
+ existing
979
+ .split(/\r?\n/)
980
+ .map((line) => line.trim())
981
+ .filter(Boolean),
982
+ );
983
+ const missing = entries.filter((entry) => !present.has(entry));
984
+ if (!missing.length) return { content: existing, changed: false };
985
+ const separator = existing.length === 0 ? "" : existing.endsWith("\n") ? "" : "\n";
986
+ return { content: `${existing}${separator}${missing.join("\n")}\n`, changed: true };
987
+ }
988
+
989
+ export function buildPlan({ root, libDir, language, runtime, features, models, intent = {} }) {
990
+ const base = path.resolve(root);
991
+ const selected = [...new Set(features)];
992
+ const options = normalizeIntent(intent);
993
+ for (const feature of selected) {
994
+ if (!["auth", "storage", "database"].includes(feature)) {
995
+ throw new Error(`Unknown setup feature "${feature}".`);
996
+ }
997
+ }
998
+ if (!runtimes[runtime]) throw new Error(`Unknown runtime "${runtime}".`);
999
+ if (!languages[language]) throw new Error(`Unknown language "${language}".`);
1000
+ if (selected.includes("database") && !models?.length) {
1001
+ throw new Error("Database actions require at least one model.");
1002
+ }
1003
+ if (selected.includes("auth") && !options.authMethods.length) {
1004
+ throw new Error("Select at least one auth method.");
1005
+ }
1006
+ if (selected.includes("storage") && !options.storageOps.length) {
1007
+ throw new Error("Select at least one storage operation.");
1008
+ }
1009
+ if (selected.includes("database") && !options.databaseOps.length) {
1010
+ throw new Error("Select at least one database operation.");
1011
+ }
1012
+
1013
+ const resolvedLib = resolveInside(base, libDir);
1014
+ const metadata = selected.includes("database") ? modelMetadata(models) : [];
1015
+ const plan = [
1016
+ {
1017
+ path: path.join(resolvedLib, `baclet.${language}`),
1018
+ content: clientFile(runtime, language, selected),
1019
+ merge: null,
1020
+ },
1021
+ ];
1022
+
1023
+ if (selected.includes("auth")) {
1024
+ plan.push({
1025
+ path: path.join(resolvedLib, "actions", `auth.${language}`),
1026
+ content: authFile(language, options.authMethods),
1027
+ merge: null,
1028
+ });
1029
+ }
1030
+ if (selected.includes("storage")) {
1031
+ plan.push({
1032
+ path: path.join(resolvedLib, "actions", `storage.${language}`),
1033
+ content: storageFile(language, options.storageOps),
1034
+ merge: null,
1035
+ });
1036
+ }
1037
+ for (const meta of metadata) {
1038
+ plan.push({
1039
+ path: path.join(resolvedLib, "actions", `${meta.fileName}.${language}`),
1040
+ content: modelFile(meta, language, options),
1041
+ merge: null,
1042
+ });
1043
+ }
1044
+ plan.push({
1045
+ path: path.join(resolvedLib, `index.${language}`),
1046
+ content: indexFile(language, selected, metadata),
1047
+ merge: null,
1048
+ });
1049
+ const keys = envKeys(runtime, selected.includes("storage"));
1050
+ const ignoreEntries = [".env", ".env.local", ".env.*.local"];
1051
+ plan.push({
1052
+ path: path.join(base, ".env.example"),
1053
+ content: `${keys.map((key) => `${key.name}=${key.value}`).join("\n")}\n`,
1054
+ merge: "env",
1055
+ keys,
1056
+ });
1057
+ plan.push({
1058
+ path: path.join(base, ".gitignore"),
1059
+ content: `${ignoreEntries.join("\n")}\n`,
1060
+ merge: "gitignore",
1061
+ entries: ignoreEntries,
1062
+ });
1063
+
1064
+ return plan;
1065
+ }
1066
+
1067
+ async function writeAtomic(file, content) {
1068
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${randomUUID()}.tmp`);
1069
+ try {
1070
+ await writeFile(temp, content, { mode: 0o644 });
1071
+ await rename(temp, file);
1072
+ } catch (error) {
1073
+ await unlink(temp).catch(() => {});
1074
+ throw error;
1075
+ }
1076
+ }
1077
+
1078
+ export async function writeWithBackup(file, content) {
1079
+ const current = await readFile(file, "utf8").catch((error) => {
1080
+ if (error.code === "ENOENT") return null;
1081
+ throw error;
1082
+ });
1083
+ if (current !== null) await copyFile(file, `${file}.bak`);
1084
+ await writeAtomic(file, content);
1085
+ }
1086
+
1087
+ export async function writePlan(plan, options = {}) {
1088
+ const overwrite = options.overwrite === true;
1089
+ const result = { created: [], updated: [], skipped: [], merged: [] };
1090
+
1091
+ for (const item of plan) {
1092
+ await mkdir(path.dirname(item.path), { recursive: true });
1093
+ const current = await readFile(item.path, "utf8").catch((error) => {
1094
+ if (error.code === "ENOENT") return null;
1095
+ throw error;
1096
+ });
1097
+
1098
+ if (item.merge === "env") {
1099
+ const merged = mergeEnvExample(current ?? "", item.keys);
1100
+ if (current !== null && !merged.changed) {
1101
+ result.skipped.push(item.path);
1102
+ continue;
1103
+ }
1104
+ await writeAtomic(item.path, merged.content);
1105
+ if (current === null) result.created.push(item.path);
1106
+ else result.merged.push(item.path);
1107
+ continue;
1108
+ }
1109
+
1110
+ if (item.merge === "gitignore") {
1111
+ const merged = mergeGitignore(current ?? "", item.entries);
1112
+ if (current !== null && !merged.changed) {
1113
+ result.skipped.push(item.path);
1114
+ continue;
1115
+ }
1116
+ await writeAtomic(item.path, merged.content);
1117
+ if (current === null) result.created.push(item.path);
1118
+ else result.merged.push(item.path);
1119
+ continue;
1120
+ }
1121
+
1122
+ if (current !== null && !overwrite) {
1123
+ result.skipped.push(item.path);
1124
+ continue;
1125
+ }
1126
+
1127
+ await writeWithBackup(item.path, item.content);
1128
+ if (current === null) result.created.push(item.path);
1129
+ else result.updated.push(item.path);
1130
+ }
1131
+
1132
+ return result;
1133
+ }
1134
+
1135
+ export async function detectFramework(root) {
1136
+ const pkg = await readJson(path.join(root, "package.json"));
1137
+ const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
1138
+ if (dependencies.next) return { id: "next", label: "Next.js", runtime: "next" };
1139
+ if (dependencies.nuxt) return { id: "nuxt", label: "Nuxt", runtime: "nuxt" };
1140
+ if (dependencies["@sveltejs/kit"]) return { id: "sveltekit", label: "SvelteKit", runtime: "vite" };
1141
+ if (dependencies.vite) {
1142
+ if (dependencies.vue) return { id: "vite-vue", label: "Vite + Vue", runtime: "vite" };
1143
+ if (dependencies.react) return { id: "vite-react", label: "Vite + React", runtime: "vite" };
1144
+ return { id: "vite", label: "Vite", runtime: "vite" };
1145
+ }
1146
+ return { id: "node", label: "Node.js / other", runtime: "node" };
1147
+ }
1148
+
1149
+ export async function detectDefaults(project) {
1150
+ const { root, configPath, models } = project;
1151
+ const framework = await detectFramework(root);
1152
+ const usesTypeScript =
1153
+ (await exists(path.join(root, "tsconfig.json"))) || /\.m?ts$/.test(configPath ?? "");
1154
+ const libDir = (await isDirectory(path.join(root, "src"))) ? "src/lib" : "lib";
1155
+ return {
1156
+ runtime: framework.runtime,
1157
+ framework,
1158
+ language: usesTypeScript ? "ts" : "js",
1159
+ libDir,
1160
+ hasModels: models.length > 0,
1161
+ };
1162
+ }
1163
+
1164
+ function printSummary(result) {
1165
+ if (result.created.length) console.log(`Created ${result.created.length} file(s):`);
1166
+ for (const file of result.created) console.log(` + ${file}`);
1167
+ if (result.updated.length) console.log(`Updated ${result.updated.length} file(s):`);
1168
+ for (const file of result.updated) console.log(` ~ ${file}`);
1169
+ if (result.merged.length) console.log(`Updated ${result.merged.length} existing file(s):`);
1170
+ for (const file of result.merged) console.log(` ~ ${file}`);
1171
+ if (result.skipped.length) console.log(`Skipped ${result.skipped.length} existing file(s):`);
1172
+ for (const file of result.skipped) console.log(` = ${file}`);
1173
+ }
1174
+
1175
+ function printDiagnostics(scan, log) {
1176
+ log(`\n${scan.file}:`);
1177
+ for (const fix of scan.fixes) {
1178
+ log(` ! line ${fix.line}: ${fix.message}`);
1179
+ if (fix.before) log(` ${fix.before.trim()} -> ${fix.after.trim()}`);
1180
+ }
1181
+ for (const issue of scan.manual) {
1182
+ log(` !${issue.line ? ` line ${issue.line}` : ""}: ${issue.message}`);
1183
+ }
1184
+ }
1185
+
1186
+ function printModelIssues(issues) {
1187
+ if (!issues.length) return;
1188
+ console.log("\nBACLET model issues:");
1189
+ for (const issue of issues) console.log(` ! ${issue.message}`);
1190
+ console.log(" These need manual changes; nothing was rewritten.");
1191
+ }
1192
+
1193
+ export function describePlanItem(item) {
1194
+ if (item.merge === "env") return { label: "env keys", details: item.keys.map((key) => key.name) };
1195
+ if (item.merge === "gitignore") return { label: "ignore entries", details: item.entries };
1196
+ const exports = [...item.content.matchAll(/export (?:const|type) (\w+)/g)].map((match) => match[1]);
1197
+ const actionBlock = item.content.match(/export const \w+ = \{([\s\S]*)\n\};/);
1198
+ const actions = actionBlock
1199
+ ? [...actionBlock[1].matchAll(/^ (\w+):/gm)].map((match) => match[1])
1200
+ : [];
1201
+ return { exports, actions };
1202
+ }
1203
+
1204
+ function printPlanPreview(plan, full, log) {
1205
+ log("\nPlanned changes:");
1206
+ for (const item of plan) {
1207
+ const info = describePlanItem(item);
1208
+ log(` ${path.relative(process.cwd(), item.path)}`);
1209
+ if (info.actions?.length) log(` actions: ${info.actions.join(", ")}`);
1210
+ if (info.details?.length) log(` ${info.label}: ${info.details.join(", ")}`);
1211
+ if (full) {
1212
+ for (const line of item.content.split("\n")) log(` | ${line}`);
1213
+ }
1214
+ }
1215
+ }
1216
+
1217
+ export async function reviewSource(file, kind, useDefaults, ask = confirm, log = console.log) {
1218
+ const content = await readFile(file, "utf8");
1219
+ const scan = scanSource(file, content, kind);
1220
+ if (!scan.fixes.length && !scan.manual.length) return false;
1221
+ printDiagnostics(scan, log);
1222
+ if (!scan.fixes.length) return false;
1223
+ if (useDefaults) {
1224
+ log(` Skipped ${scan.fixes.length} suggested fix(es); run interactively to review them.`);
1225
+ return false;
1226
+ }
1227
+ const approved = await ask({
1228
+ message: `Apply ${scan.fixes.length} suggested fix(es) to ${path.basename(file)}?`,
1229
+ default: false,
1230
+ });
1231
+ if (!approved) {
1232
+ log(" Left unchanged.");
1233
+ return false;
1234
+ }
1235
+ await writeWithBackup(file, scan.fixed);
1236
+ log(` Applied ${scan.fixes.length} fix(es) to ${file}.`);
1237
+ return true;
1238
+ }
1239
+
1240
+ function printSuggestions(suggestions, log = console.log) {
1241
+ if (!suggestions.length) return;
1242
+ log("\nModel suggestions from your project (review before writing):");
1243
+ for (const suggestion of suggestions) {
1244
+ const fields = formatFieldDraft(suggestion.fields);
1245
+ log(` ${suggestion.name}: ${fields || "no fields detected"} (${suggestion.source})`);
1246
+ }
1247
+ }
1248
+
1249
+ async function askModelDraft({ name, initialFields = {}, usedNames }) {
1250
+ let modelName;
1251
+ while (true) {
1252
+ modelName = normalizeName(
1253
+ await input({
1254
+ message: "Model name (lowercase letters, numbers, underscores)",
1255
+ default: name,
1256
+ }),
1257
+ );
1258
+ if (!/^[a-z0-9_]+$/.test(modelName)) {
1259
+ console.log("Use lowercase letters, numbers and underscores.");
1260
+ continue;
1261
+ }
1262
+ if (usedNames.has(modelName)) {
1263
+ console.log(`Model "${modelName}" already exists. Choose a different name.`);
1264
+ continue;
1265
+ }
1266
+ break;
1267
+ }
1268
+
1269
+ while (true) {
1270
+ const text = await input({
1271
+ message: `Fields for ${modelName}\nTypes: ${fieldTypes.join(", ")}. Flags: ! required, * unique, + index, @now, enum(a|b), ref:model.field`,
1272
+ default: formatFieldDraft(initialFields),
1273
+ });
1274
+ const parsed = parseFieldsDraft(text);
1275
+ for (const warning of parsed.warnings) console.log(` ! ${warning}`);
1276
+ if (parsed.errors.length) {
1277
+ for (const error of parsed.errors) console.log(` ! ${error}`);
1278
+ continue;
1279
+ }
1280
+ if (!Object.keys(parsed.fields).length) {
1281
+ console.log("Add at least one field.");
1282
+ continue;
1283
+ }
1284
+ usedNames.add(modelName);
1285
+ return normalizeModelDraft(modelName, parsed.fields);
1286
+ }
1287
+ }
1288
+
1289
+ async function collectModelDrafts({ suggestions = [], existingModels = [] }) {
1290
+ const usedNames = new Set(existingModels.map((model) => model.name));
1291
+ const drafts = [];
1292
+ if (suggestions.length) {
1293
+ const selected = await checkbox({
1294
+ message: "Generate model files from these suggestions?",
1295
+ choices: suggestions.map((suggestion) => ({
1296
+ name: `${suggestion.name}: ${formatFieldDraft(suggestion.fields) || "no fields detected"} (${suggestion.source})`,
1297
+ value: suggestion.name,
1298
+ })),
1299
+ default: suggestions.map((suggestion) => suggestion.name),
1300
+ });
1301
+ for (const name of selected) {
1302
+ const suggestion = suggestions.find((item) => item.name === name);
1303
+ drafts.push(await askModelDraft({ name, initialFields: suggestion?.fields ?? {}, usedNames }));
1304
+ }
1305
+ }
1306
+
1307
+ while (true) {
1308
+ const custom = await input({ message: "Add another model name? (blank to finish)", default: "" });
1309
+ if (!custom.trim()) break;
1310
+ drafts.push(await askModelDraft({ name: custom, usedNames }));
1311
+ }
1312
+ return drafts;
1313
+ }
1314
+
1315
+ async function printNextSteps({ root, libDir, features, googleEnabled, hasModels }) {
1316
+ const libIndex = path.join(resolveInside(root, libDir), "index.js");
1317
+ const appRoot = (await isDirectory(path.join(root, "src"))) ? path.join(root, "src") : root;
1318
+ const relative = path.relative(appRoot, libIndex).replace(/\\/g, "/");
1319
+ const importPath = relative.startsWith(".") ? relative : `./${relative}`;
1320
+
1321
+ console.log("\nNext steps:");
1322
+ console.log(` 1. Copy .env.example to .env and set your BACLET publishable key.`);
1323
+ let step = 2;
1324
+ if (hasModels && features.includes("database")) {
1325
+ console.log(` ${step}. Run \`npx baclet db status\` then \`npx baclet db push\` to sync your models.`);
1326
+ step++;
1327
+ }
1328
+ if (googleEnabled && features.includes("auth")) {
1329
+ console.log(` ${step}. Call authActions.handleOAuthRedirect() once at app startup.`);
1330
+ step++;
1331
+ console.log(` ${step}. Add the Google callback URL to your dashboard's allowed redirects.`);
1332
+ step++;
1333
+ }
1334
+ console.log(` Import from "${importPath}". Keep the generated .js import extensions.`);
1335
+ }
1336
+
1337
+ export async function setup(args = []) {
1338
+ const useDefaults = args.includes("--yes");
1339
+ const previewOnly = args.includes("--preview");
1340
+ const nonInteractive = useDefaults || previewOnly;
1341
+ if (!nonInteractive && !process.stdin.isTTY) {
1342
+ throw new Error("baclet setup needs a terminal. Use `baclet setup --yes` or `baclet setup --preview`.");
1343
+ }
1344
+
1345
+ const configPath = await findConfig(process.cwd());
1346
+ await reviewSource(configPath, "config", nonInteractive);
1347
+ const project = await loadConfig(process.cwd());
1348
+ const modelFiles = (
1349
+ await fg(project.patterns, { cwd: project.root, absolute: true, onlyFiles: true })
1350
+ ).sort();
1351
+ for (const file of modelFiles) await reviewSource(file, "model", nonInteractive);
1352
+ let models = await loadModels(project, { allowEmpty: true });
1353
+ printModelIssues(validateModels(models));
1354
+
1355
+ const defaults = await detectDefaults({ ...project, models });
1356
+ const suggestions = await suggestModels(project.root);
1357
+ if (!nonInteractive) printSuggestions(suggestions);
1358
+ else if (suggestions.length) {
1359
+ console.log(`Found ${suggestions.length} model suggestion(s). Run \`baclet setup\` interactively to review and generate them.`);
1360
+ }
1361
+
1362
+ let drafts = [];
1363
+ if (!nonInteractive) {
1364
+ const message = models.length
1365
+ ? "Add or regenerate model files from suggestions or your own names?"
1366
+ : "No models found. Generate model files from suggestions or add your own?";
1367
+ if (await confirm({ message, default: !models.length })) {
1368
+ drafts = await collectModelDrafts({ suggestions, existingModels: models });
1369
+ }
1370
+ }
1371
+ const modelPlan = drafts.length
1372
+ ? buildModelPlan({ root: project.root, patterns: project.patterns, models: drafts })
1373
+ : [];
1374
+ const effectiveModels = drafts.length
1375
+ ? [...new Map([...models, ...drafts].map((model) => [model.name, model])).values()]
1376
+ : models;
1377
+ if (!effectiveModels.length) {
1378
+ console.log(`No models found yet. Add them to ${project.patterns.join(", ")} and rerun \`baclet setup\` for database actions.`);
1379
+ }
1380
+
1381
+ let runtime = defaults.runtime;
1382
+ let language = defaults.language;
1383
+ let libDir = defaults.libDir;
1384
+ let features = ["auth", "storage"];
1385
+ if (effectiveModels.length) features.push("database");
1386
+ const intent = normalizeIntent();
1387
+ let googleState = { enabled: false, checked: false, reason: "not checked" };
1388
+
1389
+ if (!nonInteractive) {
1390
+ const choices = [
1391
+ { name: "Auth actions", value: "auth" },
1392
+ { name: "Storage actions", value: "storage" },
1393
+ ];
1394
+ if (effectiveModels.length) {
1395
+ const count = effectiveModels.length;
1396
+ choices.push({ name: `Database actions (${count} model${count === 1 ? "" : "s"})`, value: "database" });
1397
+ }
1398
+ features = await checkbox({
1399
+ message: "What would you like to set up?",
1400
+ choices,
1401
+ default: features.filter((feature) => choices.some((choice) => choice.value === feature)),
1402
+ });
1403
+ if (features.includes("auth")) {
1404
+ intent.authMethods = await checkbox({
1405
+ message: "Which auth actions do you need?",
1406
+ choices: Object.entries(authMethodOptions).map(([value, spec]) => ({ name: spec.label, value })),
1407
+ default: intent.authMethods,
1408
+ });
1409
+ googleState = await checkGoogleAuth({ root: project.root, projectId: project.projectId });
1410
+ if (googleState.enabled && !intent.authMethods.includes("google")) {
1411
+ const includeGoogle = await confirm({
1412
+ message: googleState.callbackUrl
1413
+ ? `Google sign-in is enabled (callback: ${googleState.callbackUrl}). Include Google actions?`
1414
+ : "Google sign-in is enabled. Include Google actions?",
1415
+ default: true,
1416
+ });
1417
+ if (includeGoogle) intent.authMethods = [...intent.authMethods, "google"];
1418
+ } else if (!googleState.enabled && intent.authMethods.includes("google")) {
1419
+ console.log(`Google actions were selected, but ${googleState.reason}. Enable Google in the dashboard before using them.`);
1420
+ }
1421
+ }
1422
+ if (features.includes("storage")) {
1423
+ intent.storageOps = await checkbox({
1424
+ message: "Which storage actions do you need?",
1425
+ choices: Object.entries(storageOperationOptions).map(([value, spec]) => ({ name: spec.label, value })),
1426
+ default: intent.storageOps,
1427
+ });
1428
+ }
1429
+ if (features.includes("database")) {
1430
+ intent.databaseOps = await checkbox({
1431
+ message: "Which database actions do you need?",
1432
+ choices: Object.entries(databaseOperationOptions).map(([value, spec]) => ({ name: spec.label, value })),
1433
+ default: intent.databaseOps,
1434
+ });
1435
+ if (intent.databaseOps.includes("list")) {
1436
+ intent.queryOptions = await confirm({
1437
+ message: "Should list actions support field filters and limits?",
1438
+ default: true,
1439
+ });
1440
+ }
1441
+ intent.validation = await select({
1442
+ message: "How strict should generated value validation be?",
1443
+ choices: Object.entries(validationOptions).map(([value, name]) => ({ name, value })),
1444
+ default: intent.validation,
1445
+ });
1446
+ }
1447
+ runtime = await select({
1448
+ message: `Framework detected: ${defaults.framework.label}. Confirm the generated environment?`,
1449
+ choices: [
1450
+ { name: `Yes — ${runtimes[defaults.runtime].label}`, value: defaults.runtime },
1451
+ ...Object.entries(runtimes)
1452
+ .filter(([value]) => value !== defaults.runtime)
1453
+ .map(([value, spec]) => ({ name: spec.label, value })),
1454
+ ],
1455
+ default: defaults.runtime,
1456
+ });
1457
+ language = await select({
1458
+ message: "Which language should be generated?",
1459
+ choices: [
1460
+ { name: languages.ts, value: "ts" },
1461
+ { name: languages.js, value: "js" },
1462
+ ],
1463
+ default: language,
1464
+ });
1465
+ libDir = await input({
1466
+ message: "Where should BACLET files be written?",
1467
+ default: libDir,
1468
+ });
1469
+ } else if (useDefaults && features.includes("auth")) {
1470
+ googleState = await checkGoogleAuth({ root: project.root, projectId: project.projectId });
1471
+ if (googleState.enabled) intent.authMethods = [...new Set([...intent.authMethods, "google"])];
1472
+ }
1473
+
1474
+ if (!features.length) throw new Error("Select at least one feature to set up.");
1475
+ if (previewOnly && features.includes("auth")) {
1476
+ console.log("Google sign-in availability is not checked in preview mode.");
1477
+ }
1478
+
1479
+ const planArgs = {
1480
+ root: project.root,
1481
+ libDir,
1482
+ language,
1483
+ runtime,
1484
+ features,
1485
+ models: effectiveModels,
1486
+ intent,
1487
+ };
1488
+ const plan = [...modelPlan, ...buildPlan(planArgs)];
1489
+ printPlanPreview(plan, previewOnly, console.log);
1490
+ if (previewOnly) {
1491
+ console.log("Preview only. No files were written.");
1492
+ return;
1493
+ }
1494
+
1495
+ const existing = [];
1496
+ for (const item of plan) {
1497
+ if (item.merge !== null) continue;
1498
+ if (await exists(item.path)) existing.push(item.path);
1499
+ }
1500
+ let overwrite = false;
1501
+ if (existing.length) {
1502
+ overwrite = useDefaults
1503
+ ? false
1504
+ : await confirm({
1505
+ message: `${existing.length} file(s) already exist. Overwrite them? Backups will be saved as .bak`,
1506
+ default: false,
1507
+ });
1508
+ }
1509
+ if (!useDefaults) {
1510
+ const proceed = await confirm({
1511
+ message: `Write this plan (${plan.length} file(s))?`,
1512
+ default: true,
1513
+ });
1514
+ if (!proceed) {
1515
+ console.log("Cancelled. No files were written.");
1516
+ return;
1517
+ }
1518
+ }
1519
+
1520
+ const results = [];
1521
+ if (modelPlan.length) {
1522
+ results.push(await writePlan(modelPlan, { overwrite }));
1523
+ models = await loadModels(project, { allowEmpty: true });
1524
+ printModelIssues(validateModels(models));
1525
+ if (features.includes("database") && !models.length) {
1526
+ throw new Error("No models could be loaded after writing model files. Database actions were not generated.");
1527
+ }
1528
+ }
1529
+ const libPlan = buildPlan({ ...planArgs, models });
1530
+ results.push(await writePlan(libPlan, { overwrite }));
1531
+ for (const result of results) printSummary(result);
1532
+ await printNextSteps({
1533
+ root: project.root,
1534
+ libDir,
1535
+ features,
1536
+ googleEnabled: googleState.enabled && intent.authMethods.includes("google"),
1537
+ hasModels: models.length > 0,
1538
+ });
1539
+ }