marcidb-client 0.0.10 → 0.1.1

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.
Binary file
Binary file
package/bin.js CHANGED
@@ -1,90 +1,174 @@
1
- #!/usr/bin/env node
2
-
3
- import { execFileSync } from "node:child_process";
4
- import { fileURLToPath } from "node:url";
5
- import path from "node:path";
6
- import os from "node:os";
7
- import fs from "node:fs"
8
-
9
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
-
11
- const BINS = {
12
- "linux-x64": "marci-generate-linux-x64",
13
- "darwin-arm64": "marci-generate-darwin-arm64",
14
- "win32-x64": "marci-generate-win32-x64.exe",
15
- };
16
-
17
- const COMMANDS = {
18
- generate: cmdGenerate,
19
- };
20
-
21
- function help() {
22
- console.log(`
23
- marcidb <command> [options]
24
-
25
- Commands:
26
- generate [schema] [output] Generate TypeScript types from schema
27
- schema — path to .marci file (default: schema.marci)
28
- output — output directory (default: node_modules/marci-db/generated)
29
-
30
- Examples:
31
- marcidb generate
32
- marcidb generate schema.marci
33
- marcidb generate schema.marci node_modules/.marcidb/client
34
- `);
35
- }
36
-
37
- function cmdGenerate(args) {
38
- const schema = args[0] ?? "schema.marci";
39
- const output = args[1] ?? `${import.meta.dir ?? __dirname}/../.marcidb/client` ;
40
-
41
- const key = `${os.platform()}-${os.arch()}`;
42
- const name = BINS[key];
43
-
44
- if (!name) {
45
- console.error(`marci-db: unsupported platform ${key}`);
46
- process.exit(1);
47
- }
48
-
49
- const bin = path.join(__dirname, "bin", name);
50
-
51
- // Удаляем папку перед генерацией
52
- if (fs.existsSync(output)) {
53
- fs.rmSync(output, { recursive: true, force: true });
54
- console.log(`Cleared ${output}`);
55
- }
56
-
57
- console.log(`Generating from ${schema} into ${output}...`);
58
-
59
- try {
60
- execFileSync(bin, [schema, output], { stdio: "inherit" });
61
-
62
- fs.writeFileSync(output + "/package.json", `{
63
- "name": "marci-client",
64
- "main": "index.js",
65
- "types": "index.d.ts"
66
- }`)
67
-
68
- console.log("Done.");
69
- } catch (e) {
70
- process.exit(e.status ?? 1);
71
- }
72
- }
73
- // --- main ---
74
-
75
- const [command, ...args] = process.argv.slice(2);
76
-
77
- if (!command || command === "help" || command === "--help" || command === "-h") {
78
- help();
79
- process.exit(0);
80
- }
81
-
82
- const fn = COMMANDS[command];
83
-
84
- if (!fn) {
85
- console.error(`marci: unknown command "${command}"`);
86
- help();
87
- process.exit(1);
88
- }
89
-
90
- fn(args);
1
+ #!/usr/bin/env node
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { fileURLToPath } from "node:url";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import fs from "node:fs";
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
+
11
+ const BINS = {
12
+ "linux-x64": "marci-generate-linux-x64",
13
+ "darwin-arm64": "marci-generate-darwin-arm64",
14
+ "win32-x64": "marci-generate-win32-x64.exe",
15
+ };
16
+
17
+ function binPath() {
18
+ const key = `${os.platform()}-${os.arch()}`;
19
+ const name = BINS[key];
20
+ if (!name) {
21
+ console.error(`marcidb: unsupported platform ${key}`);
22
+ process.exit(1);
23
+ }
24
+ return path.join(__dirname, "bin", name);
25
+ }
26
+
27
+ // Разбирает позиционные аргументы и флаги (--flag value | --flag)
28
+ function parseArgs(args) {
29
+ const positional = [];
30
+ const flags = {};
31
+ for (let i = 0; i < args.length; i++) {
32
+ const a = args[i];
33
+ if (a.startsWith("--")) {
34
+ const key = a.slice(2);
35
+ const next = args[i + 1];
36
+ if (next === undefined || next.startsWith("--")) {
37
+ flags[key] = true;
38
+ } else {
39
+ flags[key] = next;
40
+ i++;
41
+ }
42
+ } else {
43
+ positional.push(a);
44
+ }
45
+ }
46
+ return { positional, flags };
47
+ }
48
+
49
+ function help() {
50
+ console.log(`
51
+ marcidb <command> [options]
52
+
53
+ Commands:
54
+ generate [schema] [output] Generate TS types (always) and a migration file
55
+ --migrations <dir> migrations directory (default: migrations)
56
+ --name <name> migration name (default: migration)
57
+ --no-migrations types only, skip the migration file
58
+
59
+ migrate push <db> [options] Push migration files (.mig) to a server; it applies the new ones
60
+ --url <url> server url (default: http://localhost:3000)
61
+ --migrations <dir> migrations directory (default: migrations)
62
+
63
+ Examples:
64
+ marcidb generate
65
+ marcidb generate schema.marci --name add_users
66
+ marcidb migrate push myapp --url http://localhost:3000
67
+ `);
68
+ }
69
+
70
+ function cmdGenerate(args) {
71
+ const { positional, flags } = parseArgs(args);
72
+ const schema = positional[0] ?? "schema.marci";
73
+ const output = positional[1] ?? path.join(__dirname, "..", ".marcidb", "client");
74
+ const bin = binPath();
75
+
76
+ // 1) TypeScript-типы (всегда — без них миграция бессмысленна)
77
+ if (fs.existsSync(output)) {
78
+ fs.rmSync(output, { recursive: true, force: true });
79
+ }
80
+ console.log(`Generating types from ${schema} into ${output}...`);
81
+ execFileSync(bin, ["types", schema, output], { stdio: "inherit" });
82
+ fs.writeFileSync(path.join(output, "package.json"), `{
83
+ "name": "marci-client",
84
+ "main": "index.js",
85
+ "types": "index.d.ts"
86
+ }`);
87
+
88
+ // 2) Файл миграции (если не отключено)
89
+ if (!flags["no-migrations"]) {
90
+ const dir = flags.migrations ?? "migrations";
91
+ const name = flags.name ?? "migration";
92
+ execFileSync(bin, ["migration", schema, dir, name], { stdio: "inherit" });
93
+ }
94
+
95
+ console.log("Done.");
96
+ }
97
+
98
+ async function cmdMigrate(args) {
99
+ const [sub, ...rest] = args;
100
+ if (sub === "push") return migratePush(rest);
101
+ console.error(`marcidb migrate: unknown subcommand "${sub ?? ""}" (expected "push")`);
102
+ help();
103
+ process.exit(1);
104
+ }
105
+
106
+ // Императивный push: отправляет .mig-файлы; сервер по ledger'у применяет только новые
107
+ async function migratePush(rest) {
108
+ const { positional, flags } = parseArgs(rest);
109
+ const db = positional[0];
110
+ if (!db) {
111
+ console.error("marcidb migrate push: <db> name required");
112
+ process.exit(1);
113
+ }
114
+
115
+ const url = (flags.url ?? "http://localhost:3000").replace(/\/+$/, "");
116
+ const dir = flags.migrations ?? "migrations";
117
+
118
+ if (!fs.existsSync(dir)) {
119
+ console.error(`marcidb migrate push: migrations directory "${dir}" not found — run "marcidb generate" first`);
120
+ process.exit(1);
121
+ }
122
+
123
+ // Все .mig по порядку имён → [{ id, ops }]; id — имя файла без расширения
124
+ const migrations = fs.readdirSync(dir)
125
+ .filter((f) => f.endsWith(".mig"))
126
+ .sort()
127
+ .map((f) => ({ id: f.replace(/\.mig$/, ""), ops: fs.readFileSync(path.join(dir, f), "utf8") }));
128
+
129
+ if (migrations.length === 0) {
130
+ console.log("No migration files — nothing to push");
131
+ return;
132
+ }
133
+
134
+ const res = await fetch(`${url}/${db}/$migrate`, {
135
+ method: "POST",
136
+ headers: { "Content-Type": "application/json" },
137
+ body: JSON.stringify(migrations),
138
+ });
139
+
140
+ if (!res.ok) {
141
+ console.error(`Migration failed [${res.status}]: ${await res.text()}`);
142
+ process.exit(1);
143
+ }
144
+ const { applied } = await res.json();
145
+ if (applied && applied.length) {
146
+ console.log(`Applied ${applied.length} migration(s) to '${db}': ${applied.join(", ")}`);
147
+ } else {
148
+ console.log(`'${db}' is up to date — no new migrations`);
149
+ }
150
+ }
151
+
152
+ const COMMANDS = {
153
+ generate: cmdGenerate,
154
+ migrate: cmdMigrate,
155
+ };
156
+
157
+ // --- main ---
158
+
159
+ const [command, ...args] = process.argv.slice(2);
160
+
161
+ if (!command || command === "help" || command === "--help" || command === "-h") {
162
+ help();
163
+ process.exit(0);
164
+ }
165
+
166
+ const fn = COMMANDS[command];
167
+
168
+ if (!fn) {
169
+ console.error(`marcidb: unknown command "${command}"`);
170
+ help();
171
+ process.exit(1);
172
+ }
173
+
174
+ await fn(args);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "marcidb-client",
3
3
  "type": "module",
4
- "version": "0.0.10",
4
+ "version": "0.1.1",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "den59k"