blankthing 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kamonsarthak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/blan.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => { process.exitCode = code; },
6
+ (err) => { console.error(`❌ ${err.message}`); process.exitCode = 1; },
7
+ );
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "blankthing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Blankthing CLI: a remote control for the blan_db service",
5
+ "keywords": [
6
+ "blankthing",
7
+ "blan",
8
+ "cli",
9
+ "database",
10
+ "database-migration",
11
+ "migration",
12
+ "zero-downtime",
13
+ "live-migration",
14
+ "postgres",
15
+ "mysql",
16
+ "mongodb",
17
+ "sqlserver",
18
+ "markdown",
19
+ "web-scraping",
20
+ "agents",
21
+ "llm"
22
+ ],
23
+ "author": "kamonsarthak",
24
+ "type": "module",
25
+ "bin": {
26
+ "blan": "bin/blan.js",
27
+ "bthing": "bin/blan.js"
28
+ },
29
+ "files": [
30
+ "bin/",
31
+ "src/"
32
+ ],
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "scripts": {
37
+ "test": "node --test",
38
+ "postinstall": "node src/postinstall.js"
39
+ },
40
+ "license": "MIT"
41
+ }
package/src/cli.js ADDED
@@ -0,0 +1,454 @@
1
+ // blan: a thin remote control for blan_db. It parses arguments, makes one
2
+ // API call and prints the reply.
3
+
4
+ import { parseArgs } from 'node:util';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { createRequire } from 'node:module';
7
+ import { makeClient, ApiError, DEFAULT_SERVER, DEFAULT_BARE_SERVER } from './client.js';
8
+ import { makeStyle, icons } from './style.js';
9
+
10
+ const { version } = createRequire(import.meta.url)('../package.json');
11
+
12
+ // Help screens, gh-style: a header with the version, a one-line intro,
13
+ // then bold sections. s is a style from makeStyle (plain text when piped).
14
+ const header = (s, name, intro) => `${name} v${version}\n${intro}`;
15
+
16
+ function mainHelp(s) {
17
+ return `${header(s, 'blan', 'Blankthing from the command line: move live databases, fetch the web as Markdown.')}
18
+
19
+ ${s.bold('USAGE')}
20
+ blan <command> <subcommand> [flags]
21
+ blan db <command> [flags]
22
+ blan bare <command> [flags]
23
+
24
+ ${s.bold('DB COMMANDS')}
25
+ db init: Register your database
26
+ db demo: Free test migration
27
+ db migrate: Migrate a live database
28
+ db status: Show databases and migrations
29
+ db retire: Retire the old database
30
+ db log: Show your audit log
31
+
32
+ ${s.bold('BARE COMMANDS')}
33
+ bare fetch: Fetch a page as Markdown
34
+ bare log: Show your audit log
35
+
36
+ ${s.bold('FLAGS')}
37
+ --server URL Use another server
38
+ --token T Your API token
39
+ --json Print the raw reply
40
+ -h, --help Show help for command
41
+ -v, --version Show blan version
42
+
43
+ ${s.bold('ENVIRONMENT')}
44
+ BLAN_DB_TOKEN Your API token, for db and bare
45
+ BLAN_DB_URL blan_db address (default ${DEFAULT_SERVER})
46
+ BLAN_BARE_URL Bare address (default ${DEFAULT_BARE_SERVER})
47
+
48
+ ${s.bold('LEARN MORE')}
49
+ Use \`blan db --help\` or \`blan bare --help\` for more about a command.
50
+ bthing is an alias for blan.`;
51
+ }
52
+
53
+ function bareHelp(s) {
54
+ return `${header(s, 'blan bare', 'Web pages as clean Markdown, for agents.')}
55
+
56
+ ${s.bold('USAGE')}
57
+ blan bare <command> [flags]
58
+
59
+ ${s.bold('COMMANDS')}
60
+ fetch: Fetch a page as Markdown
61
+ log: Show your audit log
62
+
63
+ ${s.bold('DETAILS')}
64
+ blan bare fetch URL
65
+ Fetch URL through Bare and print it as Markdown, its links numbered
66
+ [n] and listed at the end. Sites that opted out of Bare, or whose
67
+ robots.txt disallows it, are refused.
68
+
69
+ blan bare log [--limit N]
70
+ Your audit log on Bare, newest first (default 50, at most 1000): every
71
+ fetch, search and opt-out made with your token, and how it ended. Only
72
+ your own actions; never page content or search queries.
73
+
74
+ ${s.bold('FLAGS')}
75
+ --server URL Bare address (env BLAN_BARE_URL)
76
+ --token T Your API token (env BLAN_DB_TOKEN, same as blan db)
77
+ --json Print the raw reply`;
78
+ }
79
+
80
+ function dbHelp(s) {
81
+ return `${header(s, 'blan db', 'Move a database without stopping it.')}
82
+
83
+ ${s.bold('USAGE')}
84
+ blan db <command> [flags]
85
+
86
+ ${s.bold('COMMANDS')}
87
+ init: Register your database
88
+ demo: Free test migration
89
+ migrate: Migrate a live database
90
+ status: Show databases and migrations
91
+ retire: Retire the old database
92
+ log: Show your audit log
93
+
94
+ ${s.bold('DETAILS')}
95
+ blan db init postgres --name NAME --url postgres://USER:PASSWORD@HOST:PORT/DB
96
+ blan db init mysql --name NAME --url mysql://USER:PASSWORD@HOST:PORT/DB
97
+ blan db init mongodb --name NAME --url mongodb://USER:PASSWORD@HOST:PORT/DB
98
+ blan db init sqlserver --name NAME --url sqlserver://USER:PASSWORD@HOST:PORT?database=DB
99
+ Register an outside Postgres, MySQL, MongoDB or SQL Server database as
100
+ NAME. blan_db tests the connection first. The password stays in
101
+ blan_db's memory only, never on disk; after a server restart, run init
102
+ again. --url can come from BLAN_PG_URL / BLAN_MYSQL_URL /
103
+ BLAN_MONGODB_URL / BLAN_SQLSERVER_URL instead, to keep it out of your
104
+ shell history. Migrations run between two databases of the same engine.
105
+
106
+ blan db demo --from postgres://USER:PASSWORD@HOST:PORT/DB [--window 30]
107
+ The free test migration, on your own data: your Postgres source moves
108
+ into a temporary Postgres database of Blankthing's. Load your test rows
109
+ first; up to 300 are copied. While the live feed is open (--window
110
+ seconds, default 30), keep writing to your source: up to 200 writes are
111
+ carried and shown as they land. Then every row, the row counts and the
112
+ checksums are printed for you to check against your source, with a
113
+ read-only connection string to the destination so you can check it
114
+ yourself (psql "<that string>"). The destination stays up for 30
115
+ minutes, then it is deleted.
116
+ Postgres only; once per account; needs only your token, no license.
117
+ The source needs wal_level=logical and a user with REPLICATION, and
118
+ every table needs a primary key. --from can come from BLAN_PG_URL;
119
+ without either you are asked for it.
120
+
121
+ blan db migrate --from NAME --to NAME [--finish-now] [--settle 10s]
122
+ blan db migrate SOURCE [--into DEST] [--finish-now] [--settle 10s]
123
+ Real migration: blueprint, clone, link, herepoint, live copy, verify.
124
+ SOURCE keeps serving and forwards to DEST (default SOURCE-new).
125
+ Between two registered Postgres databases, the data is read from the
126
+ first, moved, written into the second in one transaction, and both
127
+ databases are compared table by table. Re-running continues.
128
+
129
+ blan db status [STORE]
130
+ Every database, or one in detail.
131
+
132
+ blan db retire SOURCE [--yes]
133
+ Once your service points at the new database: verify once more, then
134
+ retire SOURCE for good. Asks first unless --yes.
135
+
136
+ blan db log [--limit N]
137
+ Your audit log on blan_db, newest first (default 50, at most 1000):
138
+ every init, migrate, status, retire, demo and payment check made with
139
+ your token, each step, and how it ended. Only your own actions; never
140
+ passwords, connection strings or data.
141
+
142
+ ${s.bold('FLAGS')}
143
+ --server URL blan_db address (env BLAN_DB_URL)
144
+ --token T Your API token (env BLAN_DB_TOKEN)
145
+ --json Print the raw reply`;
146
+ }
147
+
148
+ const OPTIONS = {
149
+ server: { type: 'string' },
150
+ token: { type: 'string' },
151
+ json: { type: 'boolean' },
152
+ help: { type: 'boolean', short: 'h' },
153
+ version: { type: 'boolean', short: 'v' },
154
+ window: { type: 'string', short: 'w' },
155
+ into: { type: 'string' },
156
+ from: { type: 'string' },
157
+ to: { type: 'string' },
158
+ name: { type: 'string', short: 'n' },
159
+ url: { type: 'string' },
160
+ 'finish-now': { type: 'boolean' },
161
+ settle: { type: 'string' },
162
+ yes: { type: 'boolean', short: 'y' },
163
+ limit: { type: 'string', short: 'l' },
164
+ };
165
+
166
+ class UsageError extends Error {}
167
+
168
+ export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, env: process.env }) {
169
+ const out = (s = '') => io.stdout.write(s + '\n');
170
+ const err = (s) => io.stderr.write(s + '\n');
171
+ const so = makeStyle(io.stdout, io.env), se = makeStyle(io.stderr, io.env);
172
+ const fail = (m) => err(`${icons.fail} ${m}`);
173
+ const warn = (m) => err(`${icons.warn} ${m}`);
174
+ // Help on request goes to stdout (exit 0); help after a mistake to stderr (exit 2).
175
+ const help = (screen, asked) => { asked ? out(screen(so)) : err(screen(se)); return asked ? 0 : 2; };
176
+ let parsed;
177
+ try {
178
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
179
+ } catch (e) {
180
+ warn(e.message);
181
+ return 2;
182
+ }
183
+ const { values: o, positionals: pos } = parsed;
184
+
185
+ if (o.version) { out(`blan v${version}`); return 0; }
186
+ if (pos.length === 0) return help(mainHelp, o.help);
187
+ if (pos[0] === 'bare') return bareMain({ o, pos, io, out, help, warn, fail });
188
+ if (pos[0] !== 'db') { warn(`unknown command "${pos[0]}"\n`); return help(mainHelp, false); }
189
+ if (o.help || pos.length === 1) return help(dbHelp, o.help);
190
+
191
+ const client = makeClient({
192
+ server: o.server || io.env.BLAN_DB_URL || DEFAULT_SERVER,
193
+ token: o.token || io.env.BLAN_DB_TOKEN,
194
+ });
195
+ const [, cmd, ...args] = pos;
196
+ try {
197
+ const commands = { init, demo, migrate, status, retire, log };
198
+ if (!commands[cmd]) throw new UsageError(`unknown db command "${cmd}" (blan db --help)`);
199
+ const reply = await commands[cmd]({ client, o, args, io, out });
200
+ if (o.json && reply) out(JSON.stringify(reply, null, 2));
201
+ return 0;
202
+ } catch (e) {
203
+ if (e instanceof UsageError) { warn(e.message); return 2; }
204
+ if (e instanceof ApiError) {
205
+ for (const s of e.body?.steps || []) err(` ${s.step.padEnd(10)} ${s.detail}`);
206
+ if (e.body?.compare) printCompare(err, e.body.compare);
207
+ fail(e.message);
208
+ return 1;
209
+ }
210
+ throw e;
211
+ }
212
+ }
213
+
214
+ // blan bare: the same token and error handling as blan db, against Bare.
215
+ async function bareMain({ o, pos, io, out, help, warn, fail }) {
216
+ if (o.help || pos.length === 1) return help(bareHelp, o.help);
217
+ const client = makeClient({
218
+ server: o.server || io.env.BLAN_BARE_URL || DEFAULT_BARE_SERVER,
219
+ token: o.token || io.env.BLAN_DB_TOKEN,
220
+ service: 'Bare',
221
+ });
222
+ const [, cmd, ...args] = pos;
223
+ try {
224
+ const commands = { fetch: bareFetch, log: bareLog };
225
+ if (!Object.hasOwn(commands, cmd)) throw new UsageError(`unknown bare command "${cmd}" (blan bare --help)`);
226
+ const reply = await commands[cmd]({ client, o, args, out });
227
+ if (o.json && reply) out(JSON.stringify(reply, null, 2));
228
+ return 0;
229
+ } catch (e) {
230
+ if (e instanceof UsageError) { warn(e.message); return 2; }
231
+ if (e instanceof ApiError) { fail(e.message); return 1; }
232
+ throw e;
233
+ }
234
+ }
235
+
236
+ async function bareFetch({ client, o, args, out }) {
237
+ if (args.length !== 1) throw new UsageError('usage: blan bare fetch URL');
238
+ const r = await client.bareFetch(args[0]);
239
+ if (o.json) return r;
240
+ if (r.title) out(`# ${r.title}\n`);
241
+ out(`Source: <${r.url}>\n`);
242
+ out(r.markdown);
243
+ if (r.links?.length) out('\n' + r.links.map((l) => `[${l.id}]: <${l.url}>`).join('\n'));
244
+ }
245
+
246
+ async function bareLog({ client, o, args, out }) {
247
+ if (args.length) throw new UsageError('usage: blan bare log [--limit N]');
248
+ let limit;
249
+ if (o.limit !== undefined) {
250
+ limit = Number(o.limit);
251
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new UsageError('--limit must be a whole number from 1 to 1000');
252
+ }
253
+ const r = await client.bareLog(limit);
254
+ if (o.json) return r;
255
+ if (!r.entries.length) { out(`no actions recorded for ${r.actor} yet`); return; }
256
+ out(`audit log for ${r.actor}, newest first:`);
257
+ for (const e of r.entries) {
258
+ const when = e.time.replace('T', ' ').replace(/\.\d+Z$|Z$/, 'Z');
259
+ const what = e.url || e.domain || '-';
260
+ out(`${when} ${e.action.padEnd(13)} ${what.padEnd(30)} ${e.outcome.padEnd(10)} ${e.detail || ''}`.trimEnd());
261
+ }
262
+ }
263
+
264
+ async function ask(io, question) {
265
+ const rl = createInterface({ input: io.stdin, output: io.stderr });
266
+ try { return (await rl.question(question)).trim(); } finally { rl.close(); }
267
+ }
268
+
269
+ function printSteps(out, steps) {
270
+ for (const s of steps || []) out(` ${s.step.padEnd(10)} ${s.detail}`);
271
+ }
272
+
273
+ // ---- commands: each is one API call
274
+
275
+ // blan db demo: the free test migration, on your own Postgres data. Your
276
+ // source goes into a temporary database of Blankthing's; the live feed
277
+ // carries what you write meanwhile; then every row, the counts and the
278
+ // checksums are printed for you to check against your source, with a
279
+ // read-only connection string to the destination, which is deleted when
280
+ // its window (30 minutes) ends.
281
+ async function demo({ client, o, args, io, out }) {
282
+ const usage = 'usage: blan db demo --from postgres://USER:PASSWORD@HOST:PORT/DB [--window SECONDS]';
283
+ if (args.length) throw new UsageError(usage);
284
+ let from = o.from || io.env.BLAN_PG_URL;
285
+ if (!from) {
286
+ if (!io.stdin.isTTY) throw new UsageError(`${usage}\n (or set BLAN_PG_URL)`);
287
+ from = await ask(io, 'Your source Postgres connection string (postgres://USER:PASSWORD@HOST:PORT/DB): ');
288
+ if (!from) throw new UsageError('no connection string given');
289
+ }
290
+ let window;
291
+ if (o.window !== undefined) {
292
+ window = Number(o.window);
293
+ if (!Number.isInteger(window) || window < 5 || window > 300) throw new UsageError('--window must be a whole number of seconds from 5 to 300');
294
+ }
295
+ const show = o.json ? () => {} : out;
296
+ const one = (row) => JSON.stringify(row);
297
+ if (!o.json) out(`demo: your Postgres -> a temporary Blankthing database (deleted 30 minutes after the run)`);
298
+ const r = await client.demo(from, window, (ev) => {
299
+ switch (ev.event) {
300
+ case 'step': show(` ${ev.step.padEnd(11)} ${ev.detail}`); break;
301
+ case 'live': show(`\n${icons.ok} ${ev.detail}`); break;
302
+ case 'write': show(` live ${String(ev.n).padStart(3)}/${ev.cap} ${ev.op.padEnd(8)} ${ev.table} ${ev.row ? one(ev.row) : ''}`); break;
303
+ case 'cap': show(`${icons.warn} ${ev.detail}`); break;
304
+ case 'verified': if (!o.json) printDemoVerified(out, ev); break;
305
+ case 'kept': show(`\n${icons.ok} the destination is yours to check, read-only, until ${fmtUntil(ev.until)}; then it is deleted:\n\n ${ev.url}\n\n e.g. psql "${ev.url}"`); break;
306
+ default: break;
307
+ }
308
+ });
309
+ if (o.json) return r;
310
+ const fate = r.destination_url ? `the destination is deleted at ${fmtUntil(r.delete_at)} (the connection string above stops working then)`
311
+ : r.deleted ? 'the temporary destination is deleted' : 'the temporary destination could not be confirmed deleted; Blankthing will remove it';
312
+ out(`\n${r.match ? icons.ok : icons.fail} ${r.match ? 'match' : 'NO MATCH'}: ${fate}`);
313
+ out('That was your free demo (one per account). Real migrations: blan db migrate');
314
+ if (!r.match) throw new ApiError('your source and the destination differ', 0, {});
315
+ }
316
+
317
+ function fmtUntil(t) {
318
+ return String(t).replace('T', ' ').replace(/(\.\d+)?Z$/, ' UTC');
319
+ }
320
+
321
+ function printDemoVerified(out, v) {
322
+ const c = v.counts, live = v.live, pre = v.pre;
323
+ out(`\nVERIFICATION at your source's position ${v.verified_lsn}`);
324
+ out(['TABLE'.padEnd(24), 'SOURCE ROWS'.padStart(12), 'DEST ROWS'.padStart(10), ' CHECKSUM (md5, source = dest)'].join(''));
325
+ for (const t of v.tables) {
326
+ let sum;
327
+ if (t.cut) sum = 'left out: truncated on your source past the live cap';
328
+ else sum = t.match ? `${t.source_md5 || '(empty)'} match` : `${t.source_md5 || '-'} != ${t.dest_md5 || '-'}`;
329
+ out([t.table.padEnd(24), String(t.source_rows).padStart(12), String(t.dest_rows).padStart(10), ` ${sum}`].join(''));
330
+ }
331
+ out(` rows: ${c.source} on your source (those the demo copied or carried) = ${c.destination} on the destination`);
332
+ if (pre.source_rows > pre.copied) out(` pre-stored: your source held ${pre.source_rows} rows; the first ${pre.copied} were copied (cap ${pre.cap})`);
333
+ else out(` pre-stored: all ${pre.copied} of your rows were copied (cap ${pre.cap})`);
334
+ out(` live writes: ${live.carried} carried (cap ${live.cap})` +
335
+ (live.dropped ? `; ${live.dropped} more arrived past the cap and were NOT carried` : '') +
336
+ (live.outside ? `; ${live.outside} touched rows outside the first ${pre.cap} and were not carried` : ''));
337
+ if (c.excluded) out(` ${c.excluded} row(s) changed on your source after the cap; the destination keeps them as they were, so they are left out of the checksum`);
338
+ if (v.exact) out(` your whole source (${c.source_total} rows) equals the destination: an exact match`);
339
+ else out(` your whole source holds ${c.source_total} rows; the demo's caps carried ${c.source} of them, and those match`);
340
+ const tables = Object.keys(v.rows || {});
341
+ const n = tables.reduce((a, t) => a + v.rows[t].length, 0);
342
+ out(`\nFULL DATA on the destination (${n} rows), to check against your source:`);
343
+ for (const t of tables) {
344
+ out(` ${t} (${v.rows[t].length} rows)`);
345
+ for (const row of v.rows[t]) out(` ${JSON.stringify(row)}`);
346
+ }
347
+ out('');
348
+ }
349
+
350
+ async function init({ client, o, args, io, out }) {
351
+ const usage = 'usage: blan db init postgres|mysql|mongodb|sqlserver --name NAME --url postgres://... | mysql://... | mongodb://... | sqlserver://USER:PASSWORD@HOST:PORT?database=DB';
352
+ const envVar = { postgres: 'BLAN_PG_URL', mysql: 'BLAN_MYSQL_URL', mongodb: 'BLAN_MONGODB_URL', sqlserver: 'BLAN_SQLSERVER_URL' };
353
+ if (args.length !== 1) throw new UsageError(usage);
354
+ const engine = args[0];
355
+ if (!envVar[engine]) throw new UsageError(`"${engine}" isn't supported yet (supported: postgres, mysql, mongodb, sqlserver)`);
356
+ const url = o.url || io.env[envVar[engine]];
357
+ if (!o.name || !url) throw new UsageError(usage);
358
+ const r = await client.init(engine, o.name, url);
359
+ if (o.json) return r;
360
+ out(`${icons.ok} ${r.already_registered ? 're-registered' : 'registered'} ${r.name}: ${engine} ${r.server_version} at ${r.target}`);
361
+ const tables = r.tables || [];
362
+ out(` ${tables.length} table(s)${tables.length ? ': ' + tables.join(', ') : ''}`);
363
+ out(' connection tested; the password is held in blan_db\'s memory only');
364
+ }
365
+
366
+ async function migrate({ client, o, args, out }) {
367
+ const usage = 'usage: blan db migrate --from NAME --to NAME | blan db migrate SOURCE [--into DEST] [--finish-now] [--settle 10s]';
368
+ let req;
369
+ if (o.from || o.to) {
370
+ if (!o.from || !o.to || args.length || o.into) throw new UsageError(usage);
371
+ req = { source: o.from, destination: o.to };
372
+ } else {
373
+ if (args.length !== 1) throw new UsageError(usage);
374
+ req = { source: args[0] };
375
+ if (o.into) req.destination = o.into;
376
+ }
377
+ if (o['finish-now']) req.finish_now = true;
378
+ if (o.settle) req.settle = o.settle;
379
+ const r = await client.migrate(req);
380
+ if (o.json) return r;
381
+ out(`migrate ${r.source} -> ${r.destination}: ${r.phase}`);
382
+ printSteps(out, r.steps);
383
+ if (r.compare) printCompare(out, r.compare);
384
+ if (r.verified_lsn) out(`\nverified at source position ${r.verified_lsn}; carried through ${r.carried_through_lsn}`);
385
+ if (r.note) out(`\n${r.note}.`);
386
+ out(`\nnext: ${r.next}`);
387
+ }
388
+
389
+ function printCompare(out, rows) {
390
+ out('\n' + ['TABLE'.padEnd(24), 'SOURCE ROWS'.padStart(12), 'DEST ROWS'.padStart(10), ' MD5 (source = dest)'].join(''));
391
+ for (const t of rows) {
392
+ const md5 = t.match ? `${t.source_md5} match` : `${t.source_md5 || '-'} != ${t.dest_md5 || '-'}`;
393
+ out([t.table.padEnd(24), String(t.source_rows).padStart(12), String(t.dest_rows).padStart(10), ` ${md5}`].join(''));
394
+ }
395
+ }
396
+
397
+ async function status({ client, o, args, out }) {
398
+ if (args.length > 1) throw new UsageError('usage: blan db status [STORE]');
399
+ const r = await client.status(args[0]);
400
+ if (o.json) return r;
401
+ const stores = r.store ? [r.store] : r.stores;
402
+ if (!stores.length) { out('no databases on blan_db yet'); return; }
403
+ out(['STORE'.padEnd(20), 'ROWS'.padStart(8), 'POINTERS'.padStart(9), ' STATE'].join(''));
404
+ for (const s of stores) {
405
+ let state = s.state;
406
+ if (s.link) state += ` (${s.link.role === 'source' ? '->' : '<-'} ${s.link.peer})`;
407
+ out([s.name.padEnd(20), String(s.rows).padStart(8), String(s.pointers).padStart(9), ` ${state}`].join(''));
408
+ }
409
+ const h = r.store?.herepoint;
410
+ if (h) out(`\nherepoint: next write lands on line ${h.Next}; ${h.Rows} row(s) above the gap; ${h.InFlight?.length || 0} in flight`);
411
+ const lc = r.store?.live_copy;
412
+ if (lc) out(`live copy: ${lc.phase}, ${lc.copied} change(s) copied`);
413
+ const feeds = new Map();
414
+ for (const a of Object.values(r.adapters || {})) if (a?.feed) feeds.set(a.feed.from, a.feed);
415
+ if (r.adapter?.feed) feeds.set(r.adapter.feed.from, r.adapter.feed);
416
+ for (const f of feeds.values()) {
417
+ let line = `\nfeed ${f.from} -> ${f.to}: ${f.state}`;
418
+ if (f.state === 'running') line += `, ${f.forwarded_txns} write(s) forwarded, backlog ${f.backlog_txns ?? '?'}; runs until blan db retire ${f.from}`;
419
+ out(line);
420
+ if (f.error) out(` ${f.error}`);
421
+ }
422
+ }
423
+
424
+ async function retire({ client, o, args, io, out }) {
425
+ if (args.length !== 1) throw new UsageError('usage: blan db retire SOURCE [--yes]');
426
+ const src = args[0];
427
+ if (!o.yes) {
428
+ if (!io.stdin.isTTY) throw new UsageError('retire is permanent: pass --yes to confirm when not in a terminal');
429
+ const a = await ask(io, `Retire ${src} for good? Your service must already point at its new database. Type "${src}" to confirm: `);
430
+ if (a !== src) { out(`${icons.warn} not retired`); return; }
431
+ }
432
+ const r = await client.retire(src);
433
+ if (o.json) return r;
434
+ printSteps(out, r.steps);
435
+ out(`${icons.ok} ${r.already ? `${src} was already retired` : `retired ${src}; ${r.destination} is the only database`}`);
436
+ }
437
+
438
+ async function log({ client, o, args, out }) {
439
+ if (args.length) throw new UsageError('usage: blan db log [--limit N]');
440
+ let limit;
441
+ if (o.limit !== undefined) {
442
+ limit = Number(o.limit);
443
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new UsageError('--limit must be a whole number from 1 to 1000');
444
+ }
445
+ const r = await client.log(limit);
446
+ if (o.json) return r;
447
+ if (!r.entries.length) { out(`no actions recorded for ${r.actor} yet`); return; }
448
+ out(`audit log for ${r.actor}, newest first:`);
449
+ for (const e of r.entries) {
450
+ const when = e.time.replace('T', ' ').replace(/\.\d+Z$|Z$/, 'Z');
451
+ const dbs = (e.databases || []).join(', ') || '-';
452
+ out(`${when} ${e.action.padEnd(8)} ${dbs.padEnd(18)} ${e.outcome.padEnd(10)} ${e.detail || ''}`.trimEnd());
453
+ }
454
+ }
package/src/client.js ADDED
@@ -0,0 +1,132 @@
1
+ // The blan_db HTTP client. Every command is one call; no migration logic here.
2
+
3
+ import http from 'node:http';
4
+ import https from 'node:https';
5
+
6
+ export const DEFAULT_SERVER = 'https://db.blan.run';
7
+ export const DEFAULT_BARE_SERVER = 'https://bare.blan.run';
8
+
9
+ export class ApiError extends Error {
10
+ constructor(message, status, body) {
11
+ super(message);
12
+ this.status = status;
13
+ this.body = body;
14
+ }
15
+ }
16
+
17
+ function send(method, url, headers, body) {
18
+ return new Promise((resolve, reject) => {
19
+ const u = new URL(url);
20
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
21
+ if (!lib) return reject(new Error(`unsupported protocol ${u.protocol}`));
22
+ if (body !== undefined) headers['Content-Length'] = Buffer.byteLength(body);
23
+ const req = lib.request(u, { method, headers }, (res) => {
24
+ let text = '';
25
+ res.setEncoding('utf8');
26
+ res.on('data', (c) => { text += c; });
27
+ res.on('end', () => resolve({ res, text }));
28
+ res.on('error', reject);
29
+ });
30
+ req.on('error', reject);
31
+ req.end(body);
32
+ });
33
+ }
34
+
35
+ // stream POSTs body and calls onEvent with each JSON line of a streamed
36
+ // (application/x-ndjson) reply as it arrives. A plain JSON reply (a
37
+ // refusal) is returned as { res, text } for request() to read.
38
+ function stream(url, headers, body, onEvent) {
39
+ return new Promise((resolve, reject) => {
40
+ const u = new URL(url);
41
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
42
+ if (!lib) return reject(new Error(`unsupported protocol ${u.protocol}`));
43
+ headers['Content-Length'] = Buffer.byteLength(body);
44
+ const req = lib.request(u, { method: 'POST', headers }, (res) => {
45
+ const ndjson = String(res.headers['content-type'] || '').startsWith('application/x-ndjson');
46
+ let text = '';
47
+ res.setEncoding('utf8');
48
+ res.on('data', (c) => {
49
+ text += c;
50
+ if (!ndjson) return;
51
+ let i;
52
+ while ((i = text.indexOf('\n')) >= 0) {
53
+ const line = text.slice(0, i).trim();
54
+ text = text.slice(i + 1);
55
+ if (line) onEvent(JSON.parse(line));
56
+ }
57
+ });
58
+ res.on('end', () => {
59
+ if (ndjson && text.trim()) onEvent(JSON.parse(text));
60
+ resolve({ res, text: ndjson ? null : text });
61
+ });
62
+ res.on('error', reject);
63
+ });
64
+ req.on('error', reject);
65
+ req.end(body);
66
+ });
67
+ }
68
+
69
+ export function makeClient({ server = DEFAULT_SERVER, token, service = 'blan_db' } = {}) {
70
+ const base = server.replace(/\/+$/, '');
71
+
72
+ async function request(method, path, body) {
73
+ const headers = { Accept: 'application/json' };
74
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
75
+ if (token) headers.Authorization = `Bearer ${token}`;
76
+ let res, text;
77
+ try {
78
+ // node:http rather than fetch: fetch gives up on a reply after 300s,
79
+ // and a live migration of a busy database can take longer than that.
80
+ ({ res, text } = await send(method, base + path, headers, body === undefined ? undefined : JSON.stringify(body)));
81
+ } catch (err) {
82
+ throw new ApiError(`can't reach ${service} at ${base} (${err.code || err.message})`, 0);
83
+ }
84
+ res.ok = res.statusCode >= 200 && res.statusCode < 300;
85
+ res.status = res.statusCode;
86
+ let data;
87
+ try {
88
+ data = JSON.parse(text);
89
+ } catch {
90
+ throw new ApiError(`${service} sent an unreadable reply (HTTP ${res.status})`, res.status, text);
91
+ }
92
+ if (!res.ok || data.ok === false) {
93
+ throw new ApiError(data.error || `HTTP ${res.status}`, res.status, data);
94
+ }
95
+ return data;
96
+ }
97
+
98
+ // A streamed call: onEvent sees every line; the last (result or error) is returned.
99
+ async function streamed(path, body, onEvent) {
100
+ const headers = { Accept: 'application/x-ndjson, application/json', 'Content-Type': 'application/json' };
101
+ if (token) headers.Authorization = `Bearer ${token}`;
102
+ let last;
103
+ let reply;
104
+ try {
105
+ reply = await stream(base + path, headers, JSON.stringify(body), (ev) => { last = ev; onEvent(ev); });
106
+ } catch (err) {
107
+ if (err instanceof SyntaxError) throw new ApiError(`${service} sent an unreadable reply`, 0);
108
+ throw new ApiError(`can't reach ${service} at ${base} (${err.code || err.message})`, 0);
109
+ }
110
+ const { res, text } = reply;
111
+ if (text !== null) { // a plain JSON reply: a refusal before the run started
112
+ let data;
113
+ try { data = JSON.parse(text); } catch { throw new ApiError(`${service} sent an unreadable reply (HTTP ${res.statusCode})`, res.statusCode, text); }
114
+ throw new ApiError(data.error || `HTTP ${res.statusCode}`, res.statusCode, data);
115
+ }
116
+ if (!last) throw new ApiError(`${service} ended the reply early`, res.statusCode);
117
+ if (last.event === 'error') throw new ApiError(last.error, res.statusCode, last);
118
+ return last;
119
+ }
120
+
121
+ return {
122
+ init: (engine, name, url) => request('POST', '/v1/db/init', { engine, name, url }),
123
+ demo: (from, window, onEvent) => streamed('/v1/db/demo', window ? { from, window } : { from }, onEvent),
124
+ migrate: (req) => request('POST', '/v1/db/migrate', req),
125
+ status: (store) => request('GET', '/v1/db/status' + (store ? `?store=${encodeURIComponent(store)}` : '')),
126
+ retire: (source) => request('POST', '/v1/db/retire', { source }),
127
+ log: (limit) => request('GET', '/v1/db/log' + (limit ? `?limit=${limit}` : '')),
128
+ // Bare (made with service: 'Bare' and Bare's address)
129
+ bareFetch: (url) => request('GET', `/fetch?url=${encodeURIComponent(url)}`),
130
+ bareLog: (limit) => request('GET', '/log' + (limit ? `?limit=${limit}` : '')),
131
+ };
132
+ }
@@ -0,0 +1,53 @@
1
+ // Prints the install banner after `npm install -g blankthing`. Black and
2
+ // white: the version (read from package.json at run time, so it follows every
3
+ // bump) sits in grey right after the G on the banner's last line.
4
+ //
5
+ // npm 7+ hides lifecycle-script output unless a script fails, so the banner
6
+ // goes straight to the terminal (the console device on Windows, /dev/tty
7
+ // elsewhere). With no terminal (CI, Docker builds) it falls back to stdout,
8
+ // which npm discards. This script never fails the install.
9
+
10
+ import { openSync, writeSync, closeSync, readFileSync } from 'node:fs';
11
+
12
+ const LINES = String.raw`
13
+ ____ _ _ _ _ _ _______ _ _ ___ _ _ ____
14
+ | __ )| | / \ | \ | | |/ /_ _| | | |_ _| \ | |/ ___|
15
+ | _ \| | / _ \ | \| | ' / | | | |_| || || \| | | _
16
+ | |_) | |___ / ___ \| |\ | . \ | | | _ || || |\ | |_| |
17
+ |____/|_____/_/ \_\_| \_|_|\_\ |_| |_| |_|___|_| \_|\____|
18
+ `.slice(1, -1).split('\n');
19
+
20
+ function banner(tty) {
21
+ let version = '';
22
+ try {
23
+ version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
24
+ } catch {
25
+ // no version to show
26
+ }
27
+ const grey = (s) => (tty && !('NO_COLOR' in process.env) ? `\x1b[90m${s}\x1b[39m` : s);
28
+ const lines = [...LINES];
29
+ if (version) lines[lines.length - 1] += ` ${grey(`v${version}`)}`;
30
+ return `\n${lines.join('\n')}\n\nahead of the abyss\n\n`;
31
+ }
32
+
33
+ function show() {
34
+ // The device path, not a bare "CONOUT$", which Node would create as a file.
35
+ const device = process.platform === 'win32' ? '\\\\.\\CONOUT$' : '/dev/tty';
36
+ try {
37
+ const fd = openSync(device, 'w');
38
+ try {
39
+ const text = banner(true);
40
+ writeSync(fd, process.platform === 'win32' ? text.replace(/\n/g, '\r\n') : text);
41
+ } finally {
42
+ closeSync(fd);
43
+ }
44
+ } catch {
45
+ process.stdout.write(banner(Boolean(process.stdout.isTTY)));
46
+ }
47
+ }
48
+
49
+ try {
50
+ show();
51
+ } catch {
52
+ // never fail the install over a banner
53
+ }
package/src/style.js ADDED
@@ -0,0 +1,10 @@
1
+ // Black and white only: the terminal's own (white) text, with bold for
2
+ // section headers. No colour. Escapes are written only to a terminal, and
3
+ // never with NO_COLOR set, so piped output and tests stay plain text.
4
+
5
+ export const icons = { ok: '✅', fail: '❌', warn: '⚠️ ' };
6
+
7
+ export function makeStyle(stream, env = process.env) {
8
+ const on = Boolean(stream?.isTTY) && !('NO_COLOR' in env) && env.TERM !== 'dumb';
9
+ return { bold: (s) => (on ? `\x1b[1m${s}\x1b[22m` : String(s)) };
10
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.