@zhin.js/core 1.6.0 → 1.8.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.
Files changed (32) hide show
  1. package/lib/built/interactive-segments/types.d.ts +6 -0
  2. package/lib/built/login-assist.d.ts +317 -14
  3. package/lib/built/login-assist.js +1139 -64
  4. package/lib/built/login-captcha.d.ts +62 -0
  5. package/lib/built/login-captcha.js +107 -0
  6. package/lib/built/user-interaction.d.ts +3 -1
  7. package/lib/built/user-interaction.js +2 -0
  8. package/lib/feature/command-public-api.d.ts +1 -1
  9. package/lib/feature/command-public-api.js +1 -1
  10. package/lib/index.d.ts +1 -0
  11. package/lib/index.js +1 -0
  12. package/lib/plugin-runtime/im/command-suggestion.d.ts +13 -0
  13. package/lib/plugin-runtime/im/command-suggestion.js +32 -0
  14. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +52 -2
  15. package/lib/plugin-runtime/im/endpoint-runtime.js +74 -2
  16. package/lib/plugin-runtime/im/host/database-config.js +38 -0
  17. package/lib/plugin-runtime/im/host/database-console-schema.d.ts +79 -0
  18. package/lib/plugin-runtime/im/host/database-console-schema.js +477 -0
  19. package/lib/plugin-runtime/im/host/database-console-sql.d.ts +66 -0
  20. package/lib/plugin-runtime/im/host/database-console-sql.js +459 -0
  21. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +48 -17
  22. package/lib/plugin-runtime/im/host/database-host-installer.js +770 -46
  23. package/lib/plugin-runtime/im/im-runtime.js +1 -0
  24. package/lib/plugin-runtime/im/inbound-runtime.js +2 -0
  25. package/lib/plugin-runtime/im/inbound-spine.d.ts +6 -1
  26. package/lib/plugin-runtime/im/inbound-spine.js +51 -1
  27. package/lib/plugin-runtime/im/index.d.ts +1 -1
  28. package/lib/plugin-runtime/im/message-dispatcher.js +2 -1
  29. package/lib/plugin-runtime/im/message-events.d.ts +5 -1
  30. package/lib/plugin-runtime/im/message-events.js +38 -3
  31. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +1 -1
  32. package/package.json +13 -13
@@ -0,0 +1,477 @@
1
+ import { isProtectedConsoleTable } from './database-console-sql.js';
2
+ export class ConsoleSchemaRefusal extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ this.name = 'ConsoleSchemaRefusal';
8
+ }
9
+ }
10
+ const COLUMN_TYPES = new Set(['text', 'integer', 'bigint', 'float', 'boolean', 'date', 'json']);
11
+ const NEW_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
12
+ /** Reads one MySQL column definition (parameterised). */
13
+ export async function readMysqlColumnDefinition(query, table, column) {
14
+ const rows = await query(`SELECT COLUMN_NAME AS name, COLUMN_TYPE AS column_type, DATA_TYPE AS data_type, IS_NULLABLE AS is_nullable,
15
+ COLUMN_DEFAULT AS column_default, EXTRA AS extra, COLUMN_COMMENT AS column_comment,
16
+ CHARACTER_SET_NAME AS character_set, COLLATION_NAME AS collation_name, GENERATION_EXPRESSION AS generation
17
+ FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?`, [table, column]);
18
+ const row = rows?.[0];
19
+ if (!row)
20
+ return undefined;
21
+ const indexed = await query('SELECT 1 AS hit FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ? LIMIT 1', [table, column]);
22
+ const text = (value) => (value === null || value === undefined ? null : String(value));
23
+ const version = await query('SELECT VERSION() AS v');
24
+ return Object.freeze({
25
+ mariadb: /mariadb/iu.test(String(version?.[0]?.v ?? '')),
26
+ name: String(row.name),
27
+ columnType: String(row.column_type ?? ''),
28
+ dataType: String(row.data_type ?? '').toLowerCase(),
29
+ nullable: row.is_nullable === 'YES',
30
+ defaultValue: text(row.column_default),
31
+ extra: String(row.extra ?? ''),
32
+ comment: String(row.column_comment ?? ''),
33
+ characterSet: text(row.character_set),
34
+ collation: text(row.collation_name),
35
+ generation: text(row.generation) || null,
36
+ indexed: Array.isArray(indexed) && indexed.length > 0,
37
+ });
38
+ }
39
+ /** MySQL types whose literal defaults must be written as an expression (`DEFAULT ('x')`, MySQL 8.0.13+). */
40
+ const MYSQL_EXPRESSION_DEFAULT = /^(?:tinytext|text|mediumtext|longtext|tinyblob|blob|mediumblob|longblob|json|geometry|point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection)$/i;
41
+ /** MySQL string literal: quotes doubled and backslashes escaped (backslash escapes are on by default). */
42
+ function mysqlString(value) {
43
+ return `'${value.replaceAll('\\', '\\\\').replaceAll('\'', '\'\'')}'`;
44
+ }
45
+ /** Timestamp functions that are written without parentheses around them in `DEFAULT`. */
46
+ const TIMESTAMP_DEFAULT = /^(?:current_timestamp|now|localtime|localtimestamp)(?:\(\d*\))?$/i;
47
+ /**
48
+ * The `DEFAULT` clause for a MariaDB `COLUMN_DEFAULT`, which is already SQL: a quoted literal
49
+ * (`'it''s'`, kept verbatim; TEXT / BLOB / JSON need the expression form), a number or bit
50
+ * literal, the string `NULL` (an explicit `DEFAULT NULL`), or a bare expression.
51
+ */
52
+ function mariadbDefault(value, expressionType, nullable) {
53
+ // A nullable column without a declared default also reads `NULL` (MariaDB's implicit DEFAULT
54
+ // NULL): a NOT NULL column cannot keep it, and has no default then.
55
+ if (/^NULL$/u.test(value))
56
+ return nullable ? ['DEFAULT NULL'] : [];
57
+ if (/^'(?:[^'\\]|''|\\.)*'$/su.test(value))
58
+ return [`DEFAULT ${expressionType ? `(${value})` : value}`];
59
+ if (/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/iu.test(value) || /^b'[01]*'$/iu.test(value) || /^0x[0-9a-f]+$/iu.test(value))
60
+ return [`DEFAULT ${value}`];
61
+ return [TIMESTAMP_DEFAULT.test(value) ? `DEFAULT ${value}` : `DEFAULT (${value})`];
62
+ }
63
+ /**
64
+ * `MODIFY COLUMN` restates the whole column, so everything the change does not touch is copied
65
+ * from `information_schema`: the full type (`varchar(64)`, `unsigned`, enum values), character set
66
+ * and collation, `ON UPDATE` / `AUTO_INCREMENT` / `INVISIBLE`, the comment, and the default — an
67
+ * expression default (`CURRENT_TIMESTAMP`, `(uuid())`) stays an expression, a literal stays a
68
+ * literal (escaped), and TEXT / JSON literals become `DEFAULT ('…')`.
69
+ */
70
+ export function renderMysqlModify(current, change, host) {
71
+ if (current.generation || /\b(?:virtual|stored) generated\b/i.test(current.extra)) {
72
+ throw new ConsoleSchemaRefusal('unsupported', 'Generated columns cannot be changed here; use a SQL statement instead');
73
+ }
74
+ const quote = (name) => `\`${name.replaceAll('`', '``')}\``;
75
+ let type = current.columnType;
76
+ let dataType = current.dataType;
77
+ if (change.type) {
78
+ type = host.mapColumnType(change.type);
79
+ // TEXT cannot be part of an index without a key length: keep the column indexable.
80
+ if (/^text$/i.test(type) && current.indexed)
81
+ type = 'VARCHAR(768)';
82
+ dataType = type.toLowerCase().replace(/\(.*$/, '');
83
+ }
84
+ const parts = [`${quote(current.name)} ${type}`];
85
+ if (!change.type && current.characterSet && current.collation)
86
+ parts.push(`CHARACTER SET ${current.characterSet} COLLATE ${current.collation}`);
87
+ const nullable = change.nullable ?? current.nullable;
88
+ parts.push(nullable ? 'NULL' : 'NOT NULL');
89
+ const expressionType = MYSQL_EXPRESSION_DEFAULT.test(dataType);
90
+ if (!change.dropDefault) {
91
+ if (change.default !== undefined) {
92
+ if (change.default === null)
93
+ parts.push('DEFAULT NULL');
94
+ else {
95
+ const literal = typeof change.default === 'string' ? mysqlString(change.default) : host.formatDefaultValue(change.default);
96
+ parts.push(`DEFAULT ${expressionType ? `(${literal})` : literal}`);
97
+ }
98
+ }
99
+ else if (current.defaultValue !== null && current.mariadb) {
100
+ parts.push(...mariadbDefault(current.defaultValue, expressionType, nullable));
101
+ }
102
+ else if (current.defaultValue !== null) {
103
+ const generated = /\bdefault_generated\b/i.test(current.extra);
104
+ if (generated) {
105
+ // information_schema shows string literals of expression defaults as `_utf8mb4\'x\'`.
106
+ const expression = current.defaultValue.replaceAll("\\'", "'");
107
+ parts.push(/^(?:current_timestamp|now|localtime|localtimestamp)(?:\(\d*\))?$/i.test(expression) ? `DEFAULT ${expression}` : `DEFAULT (${expression})`);
108
+ }
109
+ else if (/^b'[01]*'$/i.test(current.defaultValue)) {
110
+ parts.push(`DEFAULT ${current.defaultValue}`);
111
+ }
112
+ else {
113
+ const literal = mysqlString(current.defaultValue);
114
+ parts.push(`DEFAULT ${expressionType ? `(${literal})` : literal}`);
115
+ }
116
+ }
117
+ else if (nullable && current.nullable) {
118
+ // No default and nullable: MySQL's implicit DEFAULT NULL, nothing to restate.
119
+ }
120
+ }
121
+ const onUpdate = /\bon update ([a-z_]+(?:\(\d*\))?)/i.exec(current.extra);
122
+ if (onUpdate)
123
+ parts.push(`ON UPDATE ${onUpdate[1]}`);
124
+ if (/\bauto_increment\b/i.test(current.extra))
125
+ parts.push('AUTO_INCREMENT');
126
+ if (/\binvisible\b/i.test(current.extra))
127
+ parts.push('INVISIBLE');
128
+ if (current.comment)
129
+ parts.push(`COMMENT ${mysqlString(current.comment)}`);
130
+ return parts.join(' ');
131
+ }
132
+ export function quoteConsoleIdentifier(dialect, name) {
133
+ return dialect === 'mysql' ? `\`${name.replaceAll('`', '``')}\`` : `"${name.replaceAll('"', '""')}"`;
134
+ }
135
+ function newName(value, what) {
136
+ const name = typeof value === 'string' ? value.trim() : '';
137
+ if (!NEW_NAME.test(name))
138
+ throw new ConsoleSchemaRefusal('invalid', `${what} must match [A-Za-z_][A-Za-z0-9_]* (max 63 characters)`);
139
+ if (isProtectedConsoleTable(name) || name.toLowerCase().startsWith('__zhin_')) {
140
+ throw new ConsoleSchemaRefusal('protected_table', `Name '${name}' is reserved`);
141
+ }
142
+ return name;
143
+ }
144
+ function existingName(value, what) {
145
+ const name = typeof value === 'string' ? value.trim() : '';
146
+ if (!name || name.length > 256 || /[\u0000-\u001f]/.test(name))
147
+ throw new ConsoleSchemaRefusal('invalid', `${what} is required`);
148
+ return name;
149
+ }
150
+ function columnSpec(value, forCreate) {
151
+ if (!value || typeof value !== 'object' || Array.isArray(value))
152
+ throw new ConsoleSchemaRefusal('invalid', 'column is required');
153
+ const raw = value;
154
+ const type = typeof raw.type === 'string' ? raw.type.toLowerCase() : '';
155
+ if (!COLUMN_TYPES.has(type))
156
+ throw new ConsoleSchemaRefusal('invalid', `Column type must be one of ${[...COLUMN_TYPES].join(', ')}`);
157
+ const spec = {
158
+ name: newName(raw.name, 'Column name'),
159
+ type: type,
160
+ ...(typeof raw.nullable === 'boolean' ? { nullable: raw.nullable } : {}),
161
+ ...(Object.hasOwn(raw, 'default') && raw.default !== undefined ? { default: defaultValue(raw.default) } : {}),
162
+ ...(forCreate && raw.primary === true ? { primary: true } : {}),
163
+ ...(forCreate && raw.autoIncrement === true ? { autoIncrement: true } : {}),
164
+ ...(forCreate && raw.unique === true ? { unique: true } : {}),
165
+ ...(typeof raw.length === 'number' && Number.isSafeInteger(raw.length) && raw.length > 0 && raw.length <= 65535 ? { length: raw.length } : {}),
166
+ };
167
+ if (spec.autoIncrement && (!spec.primary || (spec.type !== 'integer' && spec.type !== 'bigint'))) {
168
+ throw new ConsoleSchemaRefusal('invalid', 'autoIncrement needs an integer primary key');
169
+ }
170
+ return Object.freeze(spec);
171
+ }
172
+ function defaultValue(value) {
173
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
174
+ return value;
175
+ if (typeof value === 'number' && Number.isFinite(value))
176
+ return value;
177
+ throw new ConsoleSchemaRefusal('invalid', 'default must be text, a number, a boolean or null');
178
+ }
179
+ function columnSql(dialect, host, spec) {
180
+ if (host.formatColumnDefinition) {
181
+ // The dialect's own column DDL, as code-declared tables get it (length applies to text only).
182
+ const { name, length, ...column } = spec;
183
+ return host.formatColumnDefinition(name, { ...column, ...(length && spec.type === 'text' ? { length } : {}) });
184
+ }
185
+ const name = quoteConsoleIdentifier(dialect, spec.name);
186
+ let type = host.mapColumnType(spec.type);
187
+ if (spec.autoIncrement && dialect === 'pg')
188
+ type = spec.type === 'bigint' ? 'BIGSERIAL' : 'SERIAL';
189
+ if (spec.autoIncrement && dialect === 'sqlite')
190
+ type = 'INTEGER';
191
+ const length = spec.length && !spec.autoIncrement && !/\(/.test(type) && /CHAR|TEXT/i.test(type) && dialect !== 'sqlite' && !(dialect === 'pg' && type === 'TEXT') ? `(${spec.length})` : '';
192
+ const parts = [`${name} ${type}${length}`];
193
+ if (spec.primary)
194
+ parts.push('PRIMARY KEY');
195
+ if (spec.autoIncrement && dialect === 'sqlite')
196
+ parts.push('AUTOINCREMENT');
197
+ if (spec.autoIncrement && dialect === 'mysql')
198
+ parts.push('AUTO_INCREMENT');
199
+ if (spec.unique)
200
+ parts.push('UNIQUE');
201
+ if (spec.nullable === false && !spec.primary)
202
+ parts.push('NOT NULL');
203
+ if (spec.default !== undefined) {
204
+ const literal = host.formatDefaultValue(spec.default);
205
+ parts.push(`DEFAULT ${dialect === 'mysql' && spec.default !== null && MYSQL_EXPRESSION_DEFAULT.test(type) ? `(${literal})` : literal}`);
206
+ }
207
+ return parts.join(' ');
208
+ }
209
+ /** Validates a change and renders its DDL; throws {@link ConsoleSchemaRefusal}. */
210
+ export async function planConsoleSchemaChange(input, context) {
211
+ if (!input || typeof input !== 'object' || Array.isArray(input))
212
+ throw new ConsoleSchemaRefusal('invalid', 'change is required');
213
+ const raw = input;
214
+ const { dialect, host } = context;
215
+ const q = (name) => quoteConsoleIdentifier(dialect, name);
216
+ const warnings = [];
217
+ if (raw.kind === 'create-table') {
218
+ const table = newName(raw.table, 'Table name');
219
+ if (context.hasTable(table))
220
+ throw new ConsoleSchemaRefusal('invalid', `Table '${table}' already exists`);
221
+ if (!Array.isArray(raw.columns) || !raw.columns.length || raw.columns.length > 200)
222
+ throw new ConsoleSchemaRefusal('invalid', 'A table needs 1–200 columns');
223
+ const columns = raw.columns.map(column => columnSpec(column, true));
224
+ const names = new Set();
225
+ for (const column of columns) {
226
+ if (names.has(column.name.toLowerCase()))
227
+ throw new ConsoleSchemaRefusal('invalid', `Duplicate column '${column.name}'`);
228
+ names.add(column.name.toLowerCase());
229
+ }
230
+ if (columns.filter(column => column.primary).length > 1)
231
+ throw new ConsoleSchemaRefusal('invalid', 'Only one primary key column is supported');
232
+ if (!columns.some(column => column.primary))
233
+ warnings.push('no_primary_key');
234
+ const change = Object.freeze({ kind: 'create-table', table, columns: Object.freeze(columns) });
235
+ return plan(change, [`CREATE TABLE ${q(table)} (${columns.map(column => columnSql(dialect, host, column)).join(', ')})`], false, undefined, warnings);
236
+ }
237
+ const table = existingName(raw.table, 'table');
238
+ if (isProtectedConsoleTable(table))
239
+ throw new ConsoleSchemaRefusal('protected_table', `Table '${table}' is protected and cannot be changed from the Console`);
240
+ if (!context.hasTable(table))
241
+ throw new ConsoleSchemaRefusal('not_found', `Table '${table}' not found`);
242
+ const current = await context.describe(table);
243
+ const column = (name) => current.columns.find(entry => entry.name === name);
244
+ /** Renaming or dropping a column a plugin declared breaks that plugin (and its next start re-creates it). */
245
+ const refuseDeclared = (verb, name) => {
246
+ if (context.isDeclared?.(table)) {
247
+ throw new ConsoleSchemaRefusal('unsupported', `Column '${name}' of '${table}' is declared by plugin code: ${verb} it here would break the plugin that reads it (and the plugin would add it back at its next start). Change the plugin's table definition instead.`);
248
+ }
249
+ };
250
+ switch (raw.kind) {
251
+ case 'add-column': {
252
+ const spec = columnSpec(raw.column, false);
253
+ if (column(spec.name))
254
+ throw new ConsoleSchemaRefusal('invalid', `Column '${spec.name}' already exists`);
255
+ if (dialect === 'sqlite' && spec.nullable === false && spec.default === undefined) {
256
+ throw new ConsoleSchemaRefusal('unsupported', 'SQLite can only add a NOT NULL column with a default value');
257
+ }
258
+ if (dialect !== 'sqlite' && spec.nullable === false && spec.default === undefined)
259
+ warnings.push('not_null_without_default');
260
+ const change = Object.freeze({ kind: 'add-column', table, column: spec });
261
+ return plan(change, [`ALTER TABLE ${q(table)} ADD COLUMN ${columnSql(dialect, host, spec)}`], false, undefined, warnings);
262
+ }
263
+ case 'rename-column': {
264
+ const from = existingName(raw.column, 'column');
265
+ if (!column(from))
266
+ throw new ConsoleSchemaRefusal('not_found', `Column '${from}' not found`);
267
+ refuseDeclared('renaming', from);
268
+ const to = newName(raw.to, 'New column name');
269
+ if (column(to))
270
+ throw new ConsoleSchemaRefusal('invalid', `Column '${to}' already exists`);
271
+ warnings.push('code_may_reference_column');
272
+ const change = Object.freeze({ kind: 'rename-column', table, column: from, to });
273
+ return plan(change, [`ALTER TABLE ${q(table)} RENAME COLUMN ${q(from)} TO ${q(to)}`], false, undefined, warnings);
274
+ }
275
+ case 'drop-column': {
276
+ const name = existingName(raw.column, 'column');
277
+ const existing = column(name);
278
+ if (!existing)
279
+ throw new ConsoleSchemaRefusal('not_found', `Column '${name}' not found`);
280
+ refuseDeclared('dropping', name);
281
+ if (existing.primary)
282
+ throw new ConsoleSchemaRefusal('unsupported', 'The primary key column cannot be dropped');
283
+ if (current.columns.length < 2)
284
+ throw new ConsoleSchemaRefusal('unsupported', 'A table must keep at least one column');
285
+ const change = Object.freeze({ kind: 'drop-column', table, column: name });
286
+ return plan(change, [`ALTER TABLE ${q(table)} DROP COLUMN ${q(name)}`], true, name, ['data_loss']);
287
+ }
288
+ case 'alter-column': {
289
+ const name = existingName(raw.column, 'column');
290
+ const existing = column(name);
291
+ if (!existing)
292
+ throw new ConsoleSchemaRefusal('not_found', `Column '${name}' not found`);
293
+ if (dialect === 'sqlite') {
294
+ throw new ConsoleSchemaRefusal('unsupported', 'SQLite cannot change a column’s type, nullability or default in place (the table would have to be rebuilt)');
295
+ }
296
+ const type = raw.type === undefined ? undefined : String(raw.type).toLowerCase();
297
+ if (type !== undefined && !COLUMN_TYPES.has(type))
298
+ throw new ConsoleSchemaRefusal('invalid', `Column type must be one of ${[...COLUMN_TYPES].join(', ')}`);
299
+ const nullable = typeof raw.nullable === 'boolean' ? raw.nullable : undefined;
300
+ const dropDefault = raw.dropDefault === true;
301
+ const hasDefault = Object.hasOwn(raw, 'default') && raw.default !== undefined;
302
+ const value = hasDefault ? defaultValue(raw.default) : undefined;
303
+ if (type === undefined && nullable === undefined && !hasDefault && !dropDefault)
304
+ throw new ConsoleSchemaRefusal('invalid', 'Nothing to change');
305
+ if (hasDefault && dropDefault)
306
+ throw new ConsoleSchemaRefusal('invalid', 'Set a default or drop it, not both');
307
+ const change = Object.freeze({
308
+ kind: 'alter-column', table, column: name,
309
+ ...(type ? { type: type } : {}),
310
+ ...(nullable !== undefined ? { nullable } : {}),
311
+ ...(hasDefault ? { default: value } : {}),
312
+ ...(dropDefault ? { dropDefault: true } : {}),
313
+ });
314
+ if (type)
315
+ warnings.push('type_change_may_fail');
316
+ if (nullable === false)
317
+ warnings.push('not_null_requires_values');
318
+ if (dialect === 'pg') {
319
+ const clauses = [];
320
+ if (type) {
321
+ const native = host.mapColumnType(type);
322
+ clauses.push(`ALTER COLUMN ${q(name)} TYPE ${native} USING ${q(name)}::${native}`);
323
+ }
324
+ if (nullable !== undefined)
325
+ clauses.push(`ALTER COLUMN ${q(name)} ${nullable ? 'DROP' : 'SET'} NOT NULL`);
326
+ if (hasDefault)
327
+ clauses.push(`ALTER COLUMN ${q(name)} SET DEFAULT ${host.formatDefaultValue(value)}`);
328
+ if (dropDefault)
329
+ clauses.push(`ALTER COLUMN ${q(name)} DROP DEFAULT`);
330
+ return plan(change, [`ALTER TABLE ${q(table)} ${clauses.join(', ')}`], !!type, type ? name : undefined, warnings);
331
+ }
332
+ // MySQL MODIFY restates the whole column: unchanged parts come from information_schema.
333
+ if (existing.primary)
334
+ throw new ConsoleSchemaRefusal('unsupported', 'Change the primary key column with a SQL statement instead');
335
+ const definitionNow = await context.mysqlColumn?.(table, name);
336
+ if (!definitionNow)
337
+ throw new ConsoleSchemaRefusal('unsupported', `Cannot read the current definition of column '${name}'`);
338
+ warnings.push('mysql_modify_restates_column');
339
+ const definition = renderMysqlModify(definitionNow, {
340
+ ...(type ? { type } : {}),
341
+ ...(nullable !== undefined ? { nullable } : {}),
342
+ ...(hasDefault ? { default: value } : {}),
343
+ ...(dropDefault ? { dropDefault } : {}),
344
+ }, host);
345
+ return plan(change, [`ALTER TABLE ${q(table)} MODIFY COLUMN ${definition}`], !!type, type ? name : undefined, warnings);
346
+ }
347
+ case 'create-index': {
348
+ const name = newName(raw.name, 'Index name');
349
+ if (current.indexes.some(index => index.name === name))
350
+ throw new ConsoleSchemaRefusal('invalid', `Index '${name}' already exists`);
351
+ if (!Array.isArray(raw.columns) || !raw.columns.length || raw.columns.length > 16)
352
+ throw new ConsoleSchemaRefusal('invalid', 'An index needs 1–16 columns');
353
+ const columns = raw.columns.map(entry => existingName(entry, 'column'));
354
+ for (const entry of columns)
355
+ if (!column(entry))
356
+ throw new ConsoleSchemaRefusal('not_found', `Column '${entry}' not found`);
357
+ const unique = raw.unique === true;
358
+ const fields = columns.map(entry => {
359
+ const text = dialect === 'mysql' && /text|blob|json/i.test(column(entry).nativeType);
360
+ return q(entry) + (text ? '(128)' : '');
361
+ }).join(', ');
362
+ const change = Object.freeze({ kind: 'create-index', table, name, columns: Object.freeze(columns), ...(unique ? { unique } : {}) });
363
+ return plan(change, [`CREATE ${unique ? 'UNIQUE ' : ''}INDEX ${q(name)} ON ${q(table)} (${fields})`], false, undefined, warnings);
364
+ }
365
+ case 'drop-index': {
366
+ const name = existingName(raw.name, 'index');
367
+ const index = current.indexes.find(entry => entry.name === name);
368
+ if (!index)
369
+ throw new ConsoleSchemaRefusal('not_found', `Index '${name}' not found`);
370
+ if (index.primary || /^sqlite_autoindex_/i.test(name))
371
+ throw new ConsoleSchemaRefusal('unsupported', 'Primary key and constraint indexes cannot be dropped here');
372
+ const change = Object.freeze({ kind: 'drop-index', table, name });
373
+ return plan(change, [dialect === 'mysql' ? `DROP INDEX ${q(name)} ON ${q(table)}` : `DROP INDEX ${q(name)}`], true, name, warnings);
374
+ }
375
+ default:
376
+ throw new ConsoleSchemaRefusal('invalid', 'Unknown schema change kind');
377
+ }
378
+ }
379
+ function plan(change, statements, destructive, confirm, warnings) {
380
+ return Object.freeze({
381
+ change,
382
+ statements: Object.freeze(statements),
383
+ destructive,
384
+ ...(confirm ? { confirm } : {}),
385
+ warnings: Object.freeze([...new Set(warnings)]),
386
+ });
387
+ }
388
+ /** Zhin column type of a native SQL type (best effort, for filters and the schema form). */
389
+ export function zhinColumnType(native) {
390
+ const type = native.toLowerCase();
391
+ if (/^(?:tinyint\(1\)|bool|boolean)/.test(type))
392
+ return 'boolean';
393
+ if (/bigint|int8|bigserial/.test(type))
394
+ return 'bigint';
395
+ if (/int|serial/.test(type))
396
+ return 'integer';
397
+ if (/real|float|double|numeric|decimal/.test(type))
398
+ return 'float';
399
+ if (/json/.test(type))
400
+ return 'json';
401
+ if (/date|time/.test(type))
402
+ return 'date';
403
+ if (/char|text|clob|string|uuid/.test(type) || !type)
404
+ return 'text';
405
+ return type;
406
+ }
407
+ /** Reads the physical columns and indexes of a table. */
408
+ export async function introspectConsoleTable(dialect, query, table) {
409
+ const q = (name) => quoteConsoleIdentifier(dialect, name);
410
+ const rows = async (sql, params) => await query(sql, params) ?? [];
411
+ if (dialect === 'sqlite') {
412
+ const columns = (await rows(`PRAGMA table_info(${q(table)})`)).map(row => ({
413
+ name: String(row.name),
414
+ nativeType: String(row.type ?? ''),
415
+ type: zhinColumnType(String(row.type ?? '')),
416
+ nullable: Number(row.notnull) === 0 && Number(row.pk) === 0,
417
+ primary: Number(row.pk) > 0,
418
+ ...(row.dflt_value != null ? { defaultSql: String(row.dflt_value) } : {}),
419
+ }));
420
+ const indexes = [];
421
+ for (const index of await rows(`PRAGMA index_list(${q(table)})`)) {
422
+ const name = String(index.name);
423
+ const info = await rows(`PRAGMA index_info(${q(name)})`);
424
+ indexes.push({ name, columns: info.map(row => String(row.name)), unique: Number(index.unique) === 1, primary: index.origin === 'pk' });
425
+ }
426
+ return Object.freeze({ table, columns, indexes });
427
+ }
428
+ if (dialect === 'mysql') {
429
+ const columns = (await rows(`SHOW COLUMNS FROM ${q(table)}`)).map(row => ({
430
+ name: String(row.Field),
431
+ nativeType: String(row.Type ?? ''),
432
+ type: zhinColumnType(String(row.Type ?? '')),
433
+ nullable: row.Null === 'YES',
434
+ primary: row.Key === 'PRI',
435
+ ...(row.Default != null ? { defaultSql: mysqlString(String(row.Default)) } : {}),
436
+ }));
437
+ const byName = new Map();
438
+ for (const row of await rows(`SHOW INDEX FROM ${q(table)}`)) {
439
+ const name = String(row.Key_name);
440
+ const entry = byName.get(name) ?? { name, columns: [], unique: Number(row.Non_unique) === 0, primary: name === 'PRIMARY' };
441
+ entry.columns.push(String(row.Column_name));
442
+ byName.set(name, entry);
443
+ }
444
+ return Object.freeze({ table, columns, indexes: [...byName.values()] });
445
+ }
446
+ const primary = new Set((await rows(`SELECT a.attname AS name FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
447
+ WHERE i.indrelid = to_regclass($1) AND i.indisprimary`, [q(table)])).map(row => String(row.name)));
448
+ const columns = (await rows(`SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns
449
+ WHERE table_schema = current_schema() AND table_name = $1 ORDER BY ordinal_position`, [table])).map(row => ({
450
+ name: String(row.column_name),
451
+ nativeType: String(row.data_type ?? ''),
452
+ type: zhinColumnType(String(row.data_type ?? '')),
453
+ nullable: row.is_nullable === 'YES',
454
+ primary: primary.has(String(row.column_name)),
455
+ ...(row.column_default != null ? { defaultSql: String(row.column_default) } : {}),
456
+ }));
457
+ const indexes = (await rows('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = current_schema() AND tablename = $1', [table])).map(row => {
458
+ const definition = String(row.indexdef ?? '');
459
+ const list = /\(([^)]*)\)\s*$/.exec(definition)?.[1] ?? '';
460
+ return {
461
+ name: String(row.indexname),
462
+ columns: list.split(',').map(part => part.trim().replace(/^"|"$/g, '').replaceAll('""', '"')).filter(Boolean),
463
+ unique: /^CREATE UNIQUE/i.test(definition),
464
+ primary: [...primary].length > 0 && /_pkey$/.test(String(row.indexname)),
465
+ };
466
+ });
467
+ return Object.freeze({ table, columns, indexes });
468
+ }
469
+ /** Physical base tables of the current database / schema. */
470
+ export async function listPhysicalTables(dialect, query) {
471
+ const sql = dialect === 'sqlite'
472
+ ? 'SELECT name FROM sqlite_master WHERE type = \'table\' ORDER BY name'
473
+ : dialect === 'mysql'
474
+ ? 'SELECT table_name AS name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = \'BASE TABLE\' ORDER BY table_name'
475
+ : 'SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = \'BASE TABLE\' ORDER BY table_name';
476
+ return (await query(sql)).map(row => String(row.name ?? row.NAME ?? row.TABLE_NAME));
477
+ }
@@ -0,0 +1,66 @@
1
+ export type ConsoleSqlDialect = 'sqlite' | 'mysql' | 'pg';
2
+ export interface ConsoleSqlToken {
3
+ /** `word`: bare identifier / keyword; `quoted`: quoted identifier; `string`: literal; `punct`: one other character. */
4
+ readonly type: 'word' | 'quoted' | 'string' | 'punct';
5
+ /** Words lower-cased; quoted names and strings unquoted with their escapes resolved. */
6
+ readonly value: string;
7
+ }
8
+ export interface ConsoleSqlStatement {
9
+ /** Original statement text without the trailing terminator. */
10
+ readonly text: string;
11
+ /** Lower-cased text with comments removed and literals / quoted identifiers blanked. */
12
+ readonly code: string;
13
+ /** Every identifier, quoted ones unquoted (lower-cased). */
14
+ readonly identifiers: readonly string[];
15
+ /** Tokens without comments and whitespace. */
16
+ readonly tokens: readonly ConsoleSqlToken[];
17
+ /** Names called as functions (`name(` / `"name"(` / `schema.name(`), lower-cased, schema stripped. */
18
+ readonly functions: readonly string[];
19
+ }
20
+ export declare class ConsoleSqlRefusal extends Error {
21
+ readonly code: 'empty' | 'multi_statement' | 'read_only' | 'protected_table' | 'refused_statement' | 'unsupported';
22
+ constructor(code: 'empty' | 'multi_statement' | 'read_only' | 'protected_table' | 'refused_statement' | 'unsupported', message: string);
23
+ }
24
+ /**
25
+ * Splits SQL into statements on top-level `;`, honouring per dialect: strings (`E'…'` backslash
26
+ * escapes on PostgreSQL, backslashes in MySQL strings), quoted names, `--` / `#` / nested
27
+ * PostgreSQL block comments and `$tag$` bodies. Refuses what it cannot analyse safely: PostgreSQL
28
+ * `U&` escaped names and strings, MySQL executable comments (`/*! … *\/`) and optimizer hints.
29
+ */
30
+ export declare function splitConsoleSql(sql: string, dialect: ConsoleSqlDialect): ConsoleSqlStatement[];
31
+ export declare function isRefusedConsoleFunction(name: string): boolean;
32
+ /** First refused function a statement calls, if any. */
33
+ export declare function refusedFunctionIn(statement: ConsoleSqlStatement): string | undefined;
34
+ export type ConsoleSqlReadKind = 'select' | 'with' | 'explain' | 'show' | 'describe' | 'pragma' | 'values';
35
+ /**
36
+ * The read form of one statement, or null when it may write. Callers still run reads in a
37
+ * read-only transaction.
38
+ */
39
+ export declare function readStatementKind(statement: ConsoleSqlStatement, dialect: ConsoleSqlDialect): ConsoleSqlReadKind | null;
40
+ export declare function isProtectedConsoleTable(name: string): boolean;
41
+ /**
42
+ * First protected table a statement mentions, if any: identifiers are compared unquoted, with
43
+ * doubled quotes resolved and lower-cased (schema parts are separate tokens, so `main."console_x"`
44
+ * is `console_x`), string literals by content, and the raw text with escape sequences decoded.
45
+ */
46
+ export declare function protectedTableIn(statement: ConsoleSqlStatement, options: {
47
+ readonly forRead: boolean;
48
+ }): string | undefined;
49
+ /** Statements the Console refuses even for an owner (transaction control, engine settings, dynamic SQL). */
50
+ export declare function refusedWriteStatement(statement: ConsoleSqlStatement): string | undefined;
51
+ /** First refused relation a statement names (normalised identifiers), or the MySQL `mysql.` schema. */
52
+ export declare function refusedRelationIn(statement: ConsoleSqlStatement, dialect: ConsoleSqlDialect): string | undefined;
53
+ /** Validates one read-only statement for `db:query`; throws {@link ConsoleSqlRefusal}. */
54
+ export declare function readOnlyConsoleStatement(sql: string, dialect: ConsoleSqlDialect): ConsoleSqlStatement & {
55
+ readonly kind: ConsoleSqlReadKind;
56
+ };
57
+ /** Validates the statements of `db:execute`; throws {@link ConsoleSqlRefusal}. */
58
+ export declare function writeConsoleStatements(sql: string, dialect: ConsoleSqlDialect, maxStatements?: number): ConsoleSqlStatement[];
59
+ /**
60
+ * SQL text for the audit log with literal values replaced by `'…'` (strings, `E'…'`, `$tag$…$tag$`,
61
+ * MySQL double-quoted strings) and comments removed: statements may carry passwords or tokens that a
62
+ * viewer of the audit log must not read. It uses the same lexer as the Console, so quotes inside
63
+ * comments, quoted names or backticks never shift what counts as a literal. Keywords, identifiers
64
+ * and numbers stay; text the lexer cannot read is not recorded at all.
65
+ */
66
+ export declare function redactConsoleSql(sql: string, dialect: ConsoleSqlDialect): string;