@baclet/cli 0.1.5 → 0.1.7

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 CHANGED
@@ -28,10 +28,12 @@ Node.js 18 or later is required.
28
28
  | `baclet logout` | Remove local credentials and revoke the CLI token. |
29
29
  | `baclet whoami` | Show the authorized user's name and email. |
30
30
  | `baclet init [--publishable-key KEY]` | Create `baclet.config.ts`, selecting a project when logged in. |
31
+ | `baclet setup [--yes\|--preview]` | Generate env-driven lib files and actions from your models. |
31
32
  | `baclet projects list` | List projects you can access. |
32
33
  | `baclet db status` | Print the schema diff without applying it. |
33
34
  | `baclet db push [--yes]` | Apply the schema diff after confirmation. |
34
35
  | `baclet db migrate [--yes]` | Alias for `db push`. |
36
+ | `baclet upgrade` | Upgrade `@baclet/cli` to the latest npm version. |
35
37
  | `baclet --version` | Print the CLI version. |
36
38
 
37
39
  ## Login
@@ -44,6 +46,25 @@ The CLI prints an activation link, a verification code, and a QR code. Open the
44
46
 
45
47
  Tokens are stored in `~/.config/baclet/credentials.json` with `0600` permissions. `XDG_CONFIG_HOME` changes the parent directory. Tokens are valid for 30 days and `baclet logout` revokes them.
46
48
 
49
+ ## Setup
50
+
51
+ ```bash
52
+ baclet init --publishable-key pb_...
53
+ baclet setup
54
+ ```
55
+
56
+ `baclet setup` reads `baclet.config.ts`, detects your environment and language, then asks which features you need. For each chosen feature it asks sharper questions: auth methods (email, guest, session, recovery), storage operations (upload, URL, delete), and database operations (list, get, create, set, update, remove) with optional filters and validation strictness. It writes a client initialization file, an `actions/` directory, a barrel export, `.env.example`, and `.env` ignore rules into the chosen lib directory. Database actions are generated from the models matched by `schema.models`; if no models exist yet, auth and storage can still be generated.
57
+
58
+ Every planned file, export, and action is previewed before writing, and the final write requires confirmation. `baclet setup --preview` prints the full generated content and writes nothing. `baclet setup --yes` uses all detected defaults and skips prompts; code-fix suggestions are still skipped because they always require confirmation.
59
+
60
+ Before generating files, `baclet setup` checks `baclet.config.ts` and every matched model file for common BACLET syntax mistakes (wrong field type aliases, quoted booleans, `default: "now()"`, string enum values, missing helper imports, and more). Unambiguous fixes are shown with before/after text and applied only after you confirm per file; declined or manual-only issues are left untouched. Fixes are backed up as `.bak`. Generated code reads only public configuration from the environment (publishable key, optional API URL, optional storage bucket), and no secret key is ever written to source or `.env.example`.
61
+
62
+ Import features from the generated index file:
63
+
64
+ ```ts
65
+ import { baclet, authActions, productActions } from "./lib/index.js";
66
+ ```
67
+
47
68
  ## Schema push
48
69
 
49
70
  Run `baclet init` while logged in to select a project and write the config automatically. Pass `--publishable-key pb_...` to supply the key directly. The CLI extracts the project UUID from the key before each request.
@@ -82,6 +103,14 @@ baclet db push
82
103
 
83
104
  Pushes are additive: new tables, columns, constraints, and indexes are applied in one transaction. Columns that exist in the database but not in your models are reported as warnings and are never dropped.
84
105
 
106
+ ## Updates
107
+
108
+ BACLET CLI checks npm for a newer `@baclet/cli` version at most every 12 hours (TTY only). When an update is available, it prints a notice. Disable with `BACLET_NO_UPDATE_NOTIFIER=1`.
109
+
110
+ ```bash
111
+ baclet upgrade
112
+ ```
113
+
85
114
  ## Environment
86
115
 
87
116
  | Variable | Default | Purpose |
@@ -89,3 +118,4 @@ Pushes are additive: new tables, columns, constraints, and indexes are applied i
89
118
  | `BACLET_API_URL` | `https://api.baclet.app` | API host. |
90
119
  | `BACLET_DASHBOARD_URL` | `https://baclet.app` | Fallback activation link host. |
91
120
  | `XDG_CONFIG_HOME` | `~/.config` | Parent directory for credentials. |
121
+ | `BACLET_NO_UPDATE_NOTIFIER` | unset | Set to `1` to disable update checks. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baclet/cli",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "BACLET command line tool for authentication and schema pushes",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,184 @@
1
+ const fieldTypeAliases = {
2
+ int: "integer",
3
+ datetime: "timestamp",
4
+ bool: "boolean",
5
+ object: "json",
6
+ array: "json",
7
+ "string[]": "json",
8
+ };
9
+
10
+ const validFieldTypes = new Set([
11
+ "string",
12
+ "text",
13
+ "integer",
14
+ "decimal",
15
+ "boolean",
16
+ "uuid",
17
+ "timestamp",
18
+ "date",
19
+ "json",
20
+ "enum",
21
+ ]);
22
+
23
+ const modelDetectors = [
24
+ {
25
+ pattern: /\btype:\s*(["']?)(int|datetime|bool|object|array|string\[\])\1/g,
26
+ message: (match) => `Use "${fieldTypeAliases[match[2]]}" instead of "${match[2]}" for a BACLET field type.`,
27
+ replacement: (match) => {
28
+ const quote = match[1] || '"';
29
+ return `type: ${quote}${fieldTypeAliases[match[2]]}${quote}`;
30
+ },
31
+ },
32
+ {
33
+ pattern: /\b(required|unique|index):\s*(["'])(true|false)\2/g,
34
+ message: (match) => `Use a boolean instead of "${match[3]}" for ${match[1]}.`,
35
+ replacement: (match) => `${match[1]}: ${match[3]}`,
36
+ },
37
+ {
38
+ pattern: /\bdefault:\s*(["'])now\(\)\1/g,
39
+ message: () => 'Use { expr: "now()" } for a BACLET default expression.',
40
+ replacement: () => 'default: { expr: "now()" }',
41
+ },
42
+ {
43
+ pattern: /\bvalues:\s*(["'])([^"'\r\n]+)\1/g,
44
+ message: () => "Use an array of strings for enum values.",
45
+ replacement: (match) => {
46
+ const values = match[2]
47
+ .split(",")
48
+ .map((value) => JSON.stringify(value.trim()))
49
+ .filter((value) => value !== '""');
50
+ return `values: [${values.join(", ")}]`;
51
+ },
52
+ },
53
+ {
54
+ pattern: /\breference:\s*(["'])([^"'\r\n]+)\1/g,
55
+ message: () => 'Use { model: "..." } for a BACLET reference.',
56
+ replacement: (match) => `reference: { model: ${match[1]}${match[2]}${match[1]} }`,
57
+ },
58
+ ];
59
+
60
+ const configDetectors = [
61
+ {
62
+ pattern: /\bschema:(\s*)\{\s*model:/g,
63
+ message: () => "Use schema.models instead of schema.model.",
64
+ replacement: (match) => `schema:${match[1]}{ models:`,
65
+ },
66
+ ];
67
+
68
+ function lineOf(content, index) {
69
+ return content.slice(0, index ?? 0).split("\n").length;
70
+ }
71
+
72
+ function suggestion(value) {
73
+ return (
74
+ String(value)
75
+ .trim()
76
+ .toLowerCase()
77
+ .replace(/[^a-z0-9]+/g, "_")
78
+ .replace(/^_+|_+$/g, "") || "model"
79
+ );
80
+ }
81
+
82
+ export function applyFixes(content, fixes) {
83
+ let result = content;
84
+ for (const fix of fixes) {
85
+ if (fix.insert || !result.includes(fix.before)) continue;
86
+ result = result.replace(fix.before, fix.after);
87
+ }
88
+ const inserts = [...new Set(fixes.filter((fix) => fix.insert).map((fix) => fix.insert))];
89
+ if (inserts.length) result = `${inserts.join("")}${result}`;
90
+ return result;
91
+ }
92
+
93
+ export function scanSource(file, content, kind = "model") {
94
+ const fixes = [];
95
+ const manual = [];
96
+ const detectors = kind === "config" ? configDetectors : modelDetectors;
97
+
98
+ for (const detector of detectors) {
99
+ for (const match of content.matchAll(detector.pattern)) {
100
+ fixes.push({
101
+ line: lineOf(content, match.index),
102
+ message: detector.message(match),
103
+ before: match[0],
104
+ after: detector.replacement(match),
105
+ });
106
+ }
107
+ }
108
+
109
+ const importName = kind === "config" ? "defineConfig" : "defineModel";
110
+ const usesHelper = new RegExp(`\\b${importName}\\s*\\(`).test(content);
111
+ const importsHelper = new RegExp(`\\bimport[^;]*\\b${importName}\\b`).test(content);
112
+ if (usesHelper && !importsHelper) {
113
+ fixes.push({
114
+ line: 1,
115
+ message: `Import ${importName} from "@baclet/sdk".`,
116
+ insert: `import { ${importName} } from "@baclet/sdk";\n`,
117
+ });
118
+ }
119
+
120
+ if (kind === "config") {
121
+ for (const match of content.matchAll(/publishableKey:\s*(["'])sk_/g)) {
122
+ manual.push({
123
+ line: lineOf(content, match.index),
124
+ message: "publishableKey must be a pb_... key. Never put a secret key in client config.",
125
+ });
126
+ }
127
+ if (/\bdefineConfig\s*\(\s*["']/.test(content)) {
128
+ manual.push({ line: null, message: "defineConfig takes one config object, not positional arguments." });
129
+ }
130
+ } else {
131
+ for (const match of content.matchAll(/\btype:\s*(["'])([^"'\r\n]+)\1/g)) {
132
+ if (!validFieldTypes.has(match[2]) && !fieldTypeAliases[match[2]]) {
133
+ manual.push({
134
+ line: lineOf(content, match.index),
135
+ message: `"${match[2]}" is not a BACLET field type. Use one of: ${[...validFieldTypes].join(", ")}.`,
136
+ });
137
+ }
138
+ }
139
+ for (const match of content.matchAll(/\btype:\s*([A-Za-z][A-Za-z0-9]*)/g)) {
140
+ if (!validFieldTypes.has(match[1]) && !fieldTypeAliases[match[1]]) {
141
+ manual.push({
142
+ line: lineOf(content, match.index),
143
+ message: `"${match[1]}" is not a BACLET field type. Use one of: ${[...validFieldTypes].join(", ")}.`,
144
+ });
145
+ }
146
+ }
147
+ if (/\bdefineModel\s*\(\s*["']/.test(content)) {
148
+ manual.push({ line: null, message: "defineModel takes one object with name and fields, not positional arguments." });
149
+ }
150
+ if (/\bfields:\s*\[/.test(content)) {
151
+ manual.push({ line: null, message: "fields must be an object keyed by field name, not an array." });
152
+ }
153
+ }
154
+
155
+ return { file, content, fixes, manual, fixed: applyFixes(content, fixes) };
156
+ }
157
+
158
+ export function validateModels(models) {
159
+ const issues = [];
160
+ for (const model of models) {
161
+ if (!/^[a-z0-9_]+$/.test(model.name)) {
162
+ issues.push({
163
+ message: `Model name "${model.name}" should use lowercase letters, numbers and underscores, for example "${suggestion(model.name)}".`,
164
+ });
165
+ }
166
+ for (const [name, field] of Object.entries(model.fields ?? {})) {
167
+ if (!/^[a-z0-9_]+$/.test(name)) {
168
+ issues.push({
169
+ message: `Field name "${name}" in ${model.name} should use lowercase letters, numbers and underscores, for example "${suggestion(name)}".`,
170
+ });
171
+ }
172
+ const type = field?.type;
173
+ if (typeof type === "string" && !validFieldTypes.has(type) && !fieldTypeAliases[type]) {
174
+ issues.push({
175
+ message: `"${type}" is not a BACLET field type in ${model.name}.${name}.`,
176
+ });
177
+ }
178
+ if (type === "enum" && !Array.isArray(field?.values)) {
179
+ issues.push({ message: `Enum field ${model.name}.${name} needs a values array.` });
180
+ }
181
+ }
182
+ }
183
+ return issues;
184
+ }
@@ -0,0 +1,83 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { applyFixes, scanSource, validateModels } from "./setup-diagnostics.js";
4
+
5
+ test("scanSource fixes unambiguous BACLET model syntax mistakes", () => {
6
+ const source = `export const Product = defineModel({
7
+ name: "products",
8
+ fields: {
9
+ name: { type: "string", required: "true" },
10
+ count: { type: "int" },
11
+ created_at: { type: "datetime", default: "now()" },
12
+ status: { type: "enum", values: "draft,live" },
13
+ user: { type: "uuid", reference: "users" },
14
+ },
15
+ });`;
16
+
17
+ const scan = scanSource("models/product.ts", source, "model");
18
+ assert.equal(scan.fixes.length, 7);
19
+ assert.equal(applyFixes(source, scan.fixes), scan.fixed);
20
+ assert.match(scan.fixed, /^import \{ defineModel \} from "@baclet\/sdk";\n/);
21
+ assert.match(scan.fixed, /type: "integer"/);
22
+ assert.match(scan.fixed, /required: true/);
23
+ assert.match(scan.fixed, /type: "timestamp"/);
24
+ assert.match(scan.fixed, /default: \{ expr: "now\(\)" \}/);
25
+ assert.match(scan.fixed, /values: \["draft", "live"\]/);
26
+ assert.match(scan.fixed, /reference: \{ model: "users" \}/);
27
+ assert.equal(scan.manual.length, 0);
28
+ });
29
+
30
+ test("scanSource fixes config typos and flags secret keys without rewriting them", () => {
31
+ const source = `const config = { publishableKey: "sk_not_a_publishable_key", schema: { model: "./models/*.ts" } };
32
+ export default defineConfig(config);`;
33
+
34
+ const scan = scanSource("baclet.config.ts", source, "config");
35
+ assert.equal(scan.fixes.length, 2);
36
+ assert.match(scan.fixed, /^import \{ defineConfig \} from "@baclet\/sdk";\n/);
37
+ assert.match(scan.fixed, /schema: \{ models:/);
38
+ assert.match(scan.fixed, /sk_not_a_publishable_key/);
39
+ assert.equal(scan.manual.length, 1);
40
+ assert.match(scan.manual[0].message, /pb_\.\.\./);
41
+ });
42
+
43
+ test("scanSource leaves already-correct multiline imports alone", () => {
44
+ const source = `import {
45
+ defineModel,
46
+ } from "@baclet/sdk";
47
+
48
+ export const Product = defineModel({ name: "products", fields: { name: { type: "string" } } });`;
49
+ const scan = scanSource("models/product.ts", source, "model");
50
+ assert.equal(scan.fixes.length, 0);
51
+ assert.equal(scan.fixed, source);
52
+ });
53
+
54
+ test("scanSource reports issues that need manual changes", () => {
55
+ const source = `export const Product = defineModel("products", {
56
+ fields: [{ name: "name", type: "float" }],
57
+ });`;
58
+ const scan = scanSource("models/product.ts", source, "model");
59
+ assert.equal(scan.fixes.length, 1);
60
+ assert.match(scan.fixed, /import \{ defineModel \}/);
61
+ assert.equal(scan.manual.length, 3);
62
+ assert.match(scan.manual.map((issue) => issue.message).join("\n"), /defineModel takes one object/);
63
+ assert.match(scan.manual.map((issue) => issue.message).join("\n"), /fields must be an object/);
64
+ assert.match(scan.manual.map((issue) => issue.message).join("\n"), /not a BACLET field type/);
65
+ });
66
+
67
+ test("validateModels reports invalid names, types, and enum values", () => {
68
+ const issues = validateModels([
69
+ {
70
+ name: "User Profiles",
71
+ fields: {
72
+ "first name": { type: "string" },
73
+ status: { type: "enum" },
74
+ count: { type: "float" },
75
+ },
76
+ },
77
+ ]);
78
+ const messages = issues.map((issue) => issue.message).join("\n");
79
+ assert.match(messages, /user_profiles/);
80
+ assert.match(messages, /first_name/);
81
+ assert.match(messages, /Enum field/);
82
+ assert.match(messages, /not a BACLET field type/);
83
+ });