@zhin.js/core 1.6.0 → 1.7.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.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Hosted captcha helper (ADR 0058 §验证引导与辅助材料). Pure and browser-safe: shared by the Console,
3
+ * SDKs and tests. No Node built-ins.
4
+ *
5
+ * The opener (Console) opens `${helperUrl}#${payload}` in a popup. The helper page runs on its own
6
+ * origin, loads the provider's captcha with `payload.q`, and on success posts
7
+ * `{ type: LOGIN_CAPTCHA_MESSAGE_TYPE, nonce, ticket, randstr }` to `window.opener` at `payload.o`.
8
+ * The opener accepts it only from the helper origin and with its own nonce.
9
+ */
10
+ /** `postMessage` type the helper page sends back. */
11
+ export declare const LOGIN_CAPTCHA_MESSAGE_TYPE: "zhin.login-assist.captcha";
12
+ /** Default hosted helper page (separate origin from any Console). */
13
+ export declare const DEFAULT_CAPTCHA_HELPER_URL = "https://zhin.js.org/login-assist/tcaptcha.html";
14
+ /** `media.captcha` of a slider challenge. */
15
+ export interface LoginCaptchaMedia {
16
+ readonly provider: 'tencent';
17
+ /** Query string of the platform's slider URL, verbatim. */
18
+ readonly query: string;
19
+ /** Overrides the default (or host-configured) helper page. */
20
+ readonly helperUrl?: string;
21
+ }
22
+ /** Fragment payload of the helper URL. */
23
+ export interface LoginCaptchaHelperPayload {
24
+ /** Provider query string. */
25
+ readonly q: string;
26
+ /** Opener nonce, echoed back. */
27
+ readonly n: string;
28
+ /** Opener origin, the only `postMessage` target. */
29
+ readonly o: string;
30
+ }
31
+ export interface BuildCaptchaHelperUrlInput {
32
+ readonly helperUrl?: string;
33
+ readonly query: string;
34
+ readonly nonce: string;
35
+ /** Origin of the opener (`location.origin`). */
36
+ readonly origin: string;
37
+ }
38
+ /**
39
+ * `${helperUrl}#${base64url(JSON {q, n, o})}`. The payload goes in the fragment so it never reaches
40
+ * a server log. Throws on a non-https helper (http only for localhost) or an invalid origin.
41
+ */
42
+ export declare function buildCaptchaHelperUrl(input: BuildCaptchaHelperUrlInput): string;
43
+ /** Decodes the fragment payload on the helper page (`location.hash`); `null` when malformed. */
44
+ export declare function parseCaptchaHelperPayload(hash: string): LoginCaptchaHelperPayload | null;
45
+ /**
46
+ * Accepts a helper `message` event only from `helperOrigin` and with the expected nonce.
47
+ * Returns the ticket and randstr, or `null`.
48
+ */
49
+ export declare function parseCaptchaHelperMessage(event: {
50
+ readonly origin: string;
51
+ readonly data: unknown;
52
+ }, expected: {
53
+ readonly helperOrigin: string;
54
+ readonly nonce: string;
55
+ }): {
56
+ readonly ticket: string;
57
+ readonly randstr: string;
58
+ } | null;
59
+ /** Origin of a helper URL (for `parseCaptchaHelperMessage`); `null` when invalid. */
60
+ export declare function captchaHelperOrigin(helperUrl?: string): string | null;
61
+ /** Whether a configured helper URL is usable (https, or http on localhost). */
62
+ export declare function isValidCaptchaHelperUrl(value: unknown): value is string;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Hosted captcha helper (ADR 0058 §验证引导与辅助材料). Pure and browser-safe: shared by the Console,
3
+ * SDKs and tests. No Node built-ins.
4
+ *
5
+ * The opener (Console) opens `${helperUrl}#${payload}` in a popup. The helper page runs on its own
6
+ * origin, loads the provider's captcha with `payload.q`, and on success posts
7
+ * `{ type: LOGIN_CAPTCHA_MESSAGE_TYPE, nonce, ticket, randstr }` to `window.opener` at `payload.o`.
8
+ * The opener accepts it only from the helper origin and with its own nonce.
9
+ */
10
+ /** `postMessage` type the helper page sends back. */
11
+ export const LOGIN_CAPTCHA_MESSAGE_TYPE = 'zhin.login-assist.captcha';
12
+ /** Default hosted helper page (separate origin from any Console). */
13
+ export const DEFAULT_CAPTCHA_HELPER_URL = 'https://zhin.js.org/login-assist/tcaptcha.html';
14
+ /**
15
+ * `${helperUrl}#${base64url(JSON {q, n, o})}`. The payload goes in the fragment so it never reaches
16
+ * a server log. Throws on a non-https helper (http only for localhost) or an invalid origin.
17
+ */
18
+ export function buildCaptchaHelperUrl(input) {
19
+ const helper = validHelperUrl(input.helperUrl ?? DEFAULT_CAPTCHA_HELPER_URL);
20
+ if (!helper)
21
+ throw new TypeError('captcha helper URL must be https (http only on localhost)');
22
+ const origin = validOrigin(input.origin);
23
+ if (!origin)
24
+ throw new TypeError('opener origin is invalid');
25
+ if (typeof input.nonce !== 'string' || input.nonce.length < 8)
26
+ throw new TypeError('nonce must have at least 8 characters');
27
+ const query = typeof input.query === 'string' ? input.query.replace(/^\?/u, '') : '';
28
+ if (!query)
29
+ throw new TypeError('captcha query is required');
30
+ helper.hash = encodeBase64Url(JSON.stringify({ q: query, n: input.nonce, o: origin }));
31
+ return helper.toString();
32
+ }
33
+ /** Decodes the fragment payload on the helper page (`location.hash`); `null` when malformed. */
34
+ export function parseCaptchaHelperPayload(hash) {
35
+ try {
36
+ const parsed = JSON.parse(decodeBase64Url(hash.replace(/^#/u, '')));
37
+ if (typeof parsed.q !== 'string' || !parsed.q || typeof parsed.n !== 'string' || !parsed.n)
38
+ return null;
39
+ const origin = typeof parsed.o === 'string' ? validOrigin(parsed.o) : null;
40
+ return origin ? Object.freeze({ q: parsed.q, n: parsed.n, o: origin }) : null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ /**
47
+ * Accepts a helper `message` event only from `helperOrigin` and with the expected nonce.
48
+ * Returns the ticket and randstr, or `null`.
49
+ */
50
+ export function parseCaptchaHelperMessage(event, expected) {
51
+ if (!event || event.origin !== expected.helperOrigin || !expected.nonce)
52
+ return null;
53
+ const data = event.data;
54
+ if (!data || typeof data !== 'object' || data.type !== LOGIN_CAPTCHA_MESSAGE_TYPE || data.nonce !== expected.nonce)
55
+ return null;
56
+ const ticket = typeof data.ticket === 'string' ? data.ticket.trim() : '';
57
+ const randstr = typeof data.randstr === 'string' ? data.randstr.trim() : '';
58
+ if (!ticket || /[\s,]/u.test(ticket) || /[\s,]/u.test(randstr) || ticket.length > 4096 || randstr.length > 256)
59
+ return null;
60
+ return Object.freeze({ ticket, randstr });
61
+ }
62
+ /** Origin of a helper URL (for `parseCaptchaHelperMessage`); `null` when invalid. */
63
+ export function captchaHelperOrigin(helperUrl = DEFAULT_CAPTCHA_HELPER_URL) {
64
+ return validHelperUrl(helperUrl)?.origin ?? null;
65
+ }
66
+ /** Whether a configured helper URL is usable (https, or http on localhost). */
67
+ export function isValidCaptchaHelperUrl(value) {
68
+ return typeof value === 'string' && validHelperUrl(value) !== null;
69
+ }
70
+ function validHelperUrl(value) {
71
+ try {
72
+ const url = new URL(value);
73
+ const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
74
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local))
75
+ return null;
76
+ if (url.username || url.password)
77
+ return null;
78
+ url.hash = '';
79
+ return url;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ function validOrigin(value) {
86
+ try {
87
+ const url = new URL(value);
88
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
89
+ return null;
90
+ return url.origin === value.replace(/\/$/u, '') ? url.origin : null;
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ }
96
+ function encodeBase64Url(text) {
97
+ const bytes = new TextEncoder().encode(text);
98
+ let binary = '';
99
+ for (const byte of bytes)
100
+ binary += String.fromCharCode(byte);
101
+ return btoa(binary).replace(/\+/gu, '-').replace(/\//gu, '_').replace(/=+$/u, '');
102
+ }
103
+ function decodeBase64Url(text) {
104
+ const base64 = text.replace(/-/gu, '+').replace(/_/gu, '/');
105
+ const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));
106
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
107
+ }
package/lib/index.d.ts CHANGED
@@ -28,6 +28,7 @@ export * from './im-session-id.js';
28
28
  export * from './built/ai-trigger.js';
29
29
  export * from './built/ai-access.js';
30
30
  export * from './built/login-assist.js';
31
+ export * from './built/login-captcha.js';
31
32
  export * from './built/generated-qrcode.js';
32
33
  export { markdownToPlainText } from './built/rich-segments/markdown-to-text.js';
33
34
  export * from './built/interactive-segments/index.js';
package/lib/index.js CHANGED
@@ -28,6 +28,7 @@ export * from './im-session-id.js';
28
28
  export * from './built/ai-trigger.js';
29
29
  export * from './built/ai-access.js';
30
30
  export * from './built/login-assist.js';
31
+ export * from './built/login-captcha.js';
31
32
  export * from './built/generated-qrcode.js';
32
33
  export { markdownToPlainText } from './built/rich-segments/markdown-to-text.js';
33
34
  export * from './built/interactive-segments/index.js';
@@ -1,7 +1,8 @@
1
1
  import type { OutboundDeliveryExecution } from './outbound-delivery-runtime.js';
2
2
  import { type CaptureEndpointOperationInput, type CapturedEndpointOperation, type ConversationAddress, type SendRequest } from './contracts.js';
3
3
  export type { CaptureEndpointOperationInput, CapturedEndpointOperation } from './contracts.js';
4
- import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability } from '@zhin.js/adapter';
4
+ import { AdapterIndex, type AdapterEndpointPhase, type AdapterOperation, type AdapterEndpointSummary, type EndpointTransportState, type EndpointManagement, type EndpointManagementCapability, type AdapterLoginDeclaration, type EndpointLoginControl } from '@zhin.js/adapter';
5
+ import type { LoginFlowSnapshot } from '../../built/login-assist.js';
5
6
  import { type DeliveryTarget, type PluginId, type RuntimeSnapshot, type SnapshotLease, type Locale } from '@zhin.js/plugin-runtime';
6
7
  import { type ConversationRef, type DeliveryReceipt, type EndpointCapabilities, type MessageRef } from '@zhin.js/im-contract';
7
8
  export interface EndpointRuntimeSummary {
@@ -18,6 +19,21 @@ export interface EndpointRuntimeSummary {
18
19
  readonly phase: AdapterEndpointPhase;
19
20
  readonly operations: readonly AdapterOperation[];
20
21
  readonly managementCapabilities: readonly EndpointManagementCapability[];
22
+ /** ADR 0058: an unfinished login flow of this Endpoint waits for a person. */
23
+ readonly pendingLogin: boolean;
24
+ /** ADR 0058: where the unfinished login flow is (1-based step of the timeline). */
25
+ readonly loginStep?: Readonly<{
26
+ index: number;
27
+ total: number;
28
+ title: string;
29
+ }>;
30
+ /** ADR 0058: the Adapter's login declaration (absent = no Console login actions). */
31
+ readonly login?: AdapterLoginDeclaration;
32
+ }
33
+ /** Login facts of one Endpoint for `login.relogin` / `login.refresh`. */
34
+ export interface EndpointLoginAccess {
35
+ readonly declaration?: AdapterLoginDeclaration;
36
+ readonly control?: EndpointLoginControl;
21
37
  }
22
38
  export type EndpointRuntimeDetail = Omit<EndpointRuntimeSummary, 'id' | 'owner'>;
23
39
  export interface RuntimeEndpointSendInput {
@@ -53,6 +69,8 @@ interface EndpointRuntimeContext {
53
69
  retain(): SnapshotLease;
54
70
  release(lease: SnapshotLease): void;
55
71
  send(request: SendRequest, snapshot: RuntimeSnapshot, execution?: OutboundDeliveryExecution): Promise<DeliveryReceipt>;
72
+ /** ADR 0058: latest login flow per Endpoint (LoginAssist). */
73
+ loginFlows?(): readonly LoginFlowSnapshot[];
56
74
  }
57
75
  /** Owns generation-leased Endpoint discovery, control, management, and Console delivery. */
58
76
  export declare class EndpointRuntime {
@@ -83,6 +101,11 @@ export declare class EndpointRuntime {
83
101
  recall(input: RuntimeEndpointMessageInput): Promise<void>;
84
102
  edit(input: RuntimeEndpointEditInput): Promise<string | null>;
85
103
  typing(input: RuntimeEndpointTypingInput): Promise<void>;
104
+ /**
105
+ * ADR 0058: run with the Endpoint's login declaration and lease-scoped login control port.
106
+ * `null` when the Endpoint is unknown or the snapshot is gone.
107
+ */
108
+ withLogin<T>(adapter: string, endpointKey: string, run: (login: EndpointLoginAccess) => T | Promise<T>): Promise<T | null>;
86
109
  withManagement<T>(adapter: string, endpointKey: string, run: (management: EndpointManagement) => T | Promise<T>): Promise<T | null>;
87
110
  }
88
111
  export declare function requireAdapters(snapshot: RuntimeSnapshot): AdapterIndex;
@@ -11,7 +11,9 @@ export class EndpointRuntime {
11
11
  this.context = context;
12
12
  }
13
13
  list() {
14
+ const flows = this.#loginFlows();
14
15
  return this.#withLease((snapshot) => requireAdapters(snapshot).describe().map((row) => Object.freeze({
16
+ ...loginFacts(flows, row, adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name, requireAdapters(snapshot).loginDeclaration(row.id)),
15
17
  id: String(row.id),
16
18
  endpoint: Object.freeze({ id: String(row.id), adapter: requireAdapters(snapshot).clientAdapter(row.id) }),
17
19
  name: row.name,
@@ -35,6 +37,7 @@ export class EndpointRuntime {
35
37
  }, undefined);
36
38
  }
37
39
  get(adapter, endpointKey) {
40
+ const flows = this.#loginFlows();
38
41
  return this.#withLease((snapshot) => {
39
42
  const index = requireAdapters(snapshot);
40
43
  const id = index.resolve(adapter, endpointKey);
@@ -44,6 +47,7 @@ export class EndpointRuntime {
44
47
  if (!row)
45
48
  return null;
46
49
  return Object.freeze({
50
+ ...loginFacts(flows, row, adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name, index.loginDeclaration(row.id)),
47
51
  name: row.name,
48
52
  endpoint: Object.freeze({ id: String(row.id), adapter: index.clientAdapter(row.id) }),
49
53
  adapter: adapterTypeName(snapshot.tree.get(row.owner)?.packageName) ?? row.name,
@@ -273,6 +277,42 @@ export class EndpointRuntime {
273
277
  await this.#withControl({ target: input.conversation, method: 'typing',
274
278
  run: control => control.typing({ conversation: input.conversation, active: input.active }) });
275
279
  }
280
+ /**
281
+ * ADR 0058: run with the Endpoint's login declaration and lease-scoped login control port.
282
+ * `null` when the Endpoint is unknown or the snapshot is gone.
283
+ */
284
+ async withLogin(adapter, endpointKey, run) {
285
+ let lease;
286
+ try {
287
+ lease = this.context.acquire();
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ try {
293
+ const index = requireAdapters(lease.value);
294
+ const id = index.resolve(adapter, endpointKey);
295
+ if (!id)
296
+ return null;
297
+ const declaration = index.loginDeclaration(id);
298
+ const control = index.loginControl(id, { assertActive: () => {
299
+ if (!lease.active)
300
+ throw new EndpointDeliveryError('operation_scope_ended', 'Login operation scope has ended', 'not_sent');
301
+ } });
302
+ return await run(Object.freeze({ ...(declaration ? { declaration } : {}), ...(control ? { control } : {}) }));
303
+ }
304
+ finally {
305
+ this.context.release(lease);
306
+ }
307
+ }
308
+ #loginFlows() {
309
+ try {
310
+ return this.context.loginFlows?.() ?? [];
311
+ }
312
+ catch {
313
+ return [];
314
+ }
315
+ }
276
316
  async withManagement(adapter, endpointKey, run) {
277
317
  let lease;
278
318
  try {
@@ -379,3 +419,16 @@ function assertSameEndpoint(expected, actual) {
379
419
  throw new EndpointDeliveryError('endpoint_identity_mismatch', 'Message reference belongs to another Endpoint.', 'not_sent');
380
420
  }
381
421
  }
422
+ /** ADR 0058: pending-login facts of one Endpoint row from the latest login flows. */
423
+ function loginFacts(flows, row, adapter, declaration) {
424
+ const flow = flows.find((item) => item.endpointIdentity?.canonicalId === String(row.id))
425
+ ?? flows.find((item) => !item.endpointIdentity && item.adapter === adapter
426
+ && (item.endpointKey === row.name || item.endpointKey === String(row.id)));
427
+ const unfinished = !!flow && (flow.state === 'active' || flow.state === 'expired');
428
+ const index = unfinished && flow.currentStep ? flow.steps.findIndex((step) => step.id === flow.currentStep) : -1;
429
+ return {
430
+ pendingLogin: unfinished && !!flow.activeTaskId,
431
+ ...(index >= 0 ? { loginStep: Object.freeze({ index: index + 1, total: flow.steps.length, title: flow.steps[index].title }) } : {}),
432
+ ...(declaration ? { login: declaration } : {}),
433
+ };
434
+ }
@@ -45,6 +45,36 @@ function normalizeRedisDatabase(value) {
45
45
  }
46
46
  return normalized;
47
47
  }
48
+ /**
49
+ * `database.console` (ADR 0059 §4): the restricted account raw Console SQL runs on, PostgreSQL /
50
+ * MySQL only. Both fields required; the password belongs in `.env`
51
+ * (`password: ${ZHIN_DB_CONSOLE_PASSWORD}`). Other dialects need none and ignore the block.
52
+ */
53
+ function normalizeConsoleCredential(config) {
54
+ if (!('console' in config) || config.console === undefined)
55
+ return;
56
+ const value = config.console;
57
+ if (!value || typeof value !== 'object' || Array.isArray(value))
58
+ throw configurationError('database.console', '必须是对象 { user, password }');
59
+ const block = { ...value };
60
+ // `${ZHIN_DB_CONSOLE_*}` not set (yet): no restricted account — raw SQL stays off, the rest works.
61
+ if ((block.user === undefined || block.user === '') && (block.password === undefined || block.password === '')) {
62
+ delete config.console;
63
+ return;
64
+ }
65
+ normalizeRequiredText(block, 'user', 'database.console.user', 'ZHIN_DB_CONSOLE_USER=zhin_console_xxxxxxxx');
66
+ if (typeof block.password !== 'string' || block.password === '') {
67
+ throw configurationError('database.console.password', '不能为空', 'ZHIN_DB_CONSOLE_PASSWORD=…(zhin db console-role 生成)');
68
+ }
69
+ if (String(block.user) === String(config.user ?? '')) {
70
+ throw configurationError('database.console.user', '不能与主账号 database.user 相同(原始 SQL 只在受限账号上执行)');
71
+ }
72
+ for (const key of Object.keys(block)) {
73
+ if (key !== 'user' && key !== 'password')
74
+ throw configurationError(`database.console.${key}`, '不支持(只有 user 与 password)');
75
+ }
76
+ config.console = Object.freeze({ user: block.user, password: block.password });
77
+ }
48
78
  /**
49
79
  * Validate and normalize the expanded Root database configuration before a
50
80
  * third-party driver sees it. Dotenv expansion produces strings, while the
@@ -58,6 +88,9 @@ export function normalizeDatabaseHostConfig(input) {
58
88
  + '可选值为 sqlite、mysql、pg、mongodb、redis、memory。');
59
89
  }
60
90
  const config = { ...input, dialect };
91
+ // Only PostgreSQL / MySQL use a restricted Console account.
92
+ if (dialect !== 'pg' && dialect !== 'mysql')
93
+ delete config.console;
61
94
  switch (dialect) {
62
95
  case 'mysql':
63
96
  normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
@@ -67,6 +100,7 @@ export function normalizeDatabaseHostConfig(input) {
67
100
  config.port = normalizePort(config.port, 'database.port', 'DB_PORT=3306');
68
101
  if (config.port === undefined)
69
102
  delete config.port;
103
+ normalizeConsoleCredential(config);
70
104
  break;
71
105
  case 'pg':
72
106
  normalizeOptionalText(config, 'host', 'database.host', 'DB_HOST=127.0.0.1');
@@ -76,6 +110,7 @@ export function normalizeDatabaseHostConfig(input) {
76
110
  config.port = normalizePort(config.port, 'database.port', 'DB_PORT=5432');
77
111
  if (config.port === undefined)
78
112
  delete config.port;
113
+ normalizeConsoleCredential(config);
79
114
  break;
80
115
  case 'mongodb':
81
116
  normalizeRequiredText(config, 'url', 'database.url', 'DB_URL=mongodb://127.0.0.1:27017');
@@ -106,6 +141,9 @@ export function normalizeDatabaseHostConfig(input) {
106
141
  if (config.filename === undefined)
107
142
  config.filename = './data/bot.db';
108
143
  normalizeOptionalText(config, 'filename', 'database.filename');
144
+ // ADR 0059 §2: the instance's connection never attaches another file (.zhin/gateway.db);
145
+ // not configurable.
146
+ config.denyAttach = true;
109
147
  break;
110
148
  case 'memory':
111
149
  break;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Console schema editor (`db:schema:*`): validates a structured change and renders the DDL the
3
+ * Host will run, so the Console previews exactly what is applied. Identifiers of new objects are
4
+ * restricted to `[A-Za-z_][A-Za-z0-9_]*`; existing names are quoted with their quotes escaped.
5
+ */
6
+ import type { DatabaseHostSchemaPlan, DatabaseHostTableSchema } from '@zhin.js/plugin-runtime';
7
+ import { type ConsoleSqlDialect } from './database-console-sql.js';
8
+ export declare class ConsoleSchemaRefusal extends Error {
9
+ readonly code: 'invalid' | 'unsupported' | 'protected_table' | 'not_found' | 'confirm_required';
10
+ constructor(code: 'invalid' | 'unsupported' | 'protected_table' | 'not_found' | 'confirm_required', message: string);
11
+ }
12
+ /** The subset of a `@zhin.js/database` dialect the renderer needs. */
13
+ export interface SchemaDialect {
14
+ readonly name: string;
15
+ mapColumnType(type: string): string;
16
+ formatDefaultValue(value: unknown): string;
17
+ /** The dialect's own column DDL (`@zhin.js/database`): text keys, `(expr)` defaults, identity. */
18
+ formatColumnDefinition?(field: string, column: Record<string, unknown>): string;
19
+ }
20
+ /** A MySQL column as `information_schema.columns` describes it (for `MODIFY COLUMN`). */
21
+ export interface MysqlColumnDefinition {
22
+ readonly name: string;
23
+ /** Full type, e.g. `varchar(64)`, `int unsigned`, `enum('a','b')`. */
24
+ readonly columnType: string;
25
+ readonly dataType: string;
26
+ readonly nullable: boolean;
27
+ /** `COLUMN_DEFAULT`: the literal value, or the expression when `extra` has `DEFAULT_GENERATED`. */
28
+ readonly defaultValue: string | null;
29
+ /** `EXTRA`: `auto_increment`, `on update CURRENT_TIMESTAMP`, `DEFAULT_GENERATED`, `VIRTUAL GENERATED`, `INVISIBLE`, … */
30
+ readonly extra: string;
31
+ readonly comment: string;
32
+ readonly characterSet: string | null;
33
+ readonly collation: string | null;
34
+ readonly generation: string | null;
35
+ /** The column is part of an index (a TEXT type would need a key length). */
36
+ readonly indexed: boolean;
37
+ /**
38
+ * MariaDB writes `COLUMN_DEFAULT` differently (10.2.7+): a literal as a quoted SQL literal
39
+ * (`'it''s'`), an expression bare (`current_timestamp()`, `uuid()`), an explicit `DEFAULT NULL`
40
+ * as the string `NULL`; MySQL shows the bare literal and marks expressions `DEFAULT_GENERATED`.
41
+ */
42
+ readonly mariadb?: boolean;
43
+ }
44
+ /** Reads one MySQL column definition (parameterised). */
45
+ export declare function readMysqlColumnDefinition(query: (sql: string, params?: unknown[]) => Promise<unknown>, table: string, column: string): Promise<MysqlColumnDefinition | undefined>;
46
+ /**
47
+ * `MODIFY COLUMN` restates the whole column, so everything the change does not touch is copied
48
+ * from `information_schema`: the full type (`varchar(64)`, `unsigned`, enum values), character set
49
+ * and collation, `ON UPDATE` / `AUTO_INCREMENT` / `INVISIBLE`, the comment, and the default — an
50
+ * expression default (`CURRENT_TIMESTAMP`, `(uuid())`) stays an expression, a literal stays a
51
+ * literal (escaped), and TEXT / JSON literals become `DEFAULT ('…')`.
52
+ */
53
+ export declare function renderMysqlModify(current: MysqlColumnDefinition, change: {
54
+ readonly type?: string;
55
+ readonly nullable?: boolean;
56
+ readonly default?: string | number | boolean | null;
57
+ readonly dropDefault?: boolean;
58
+ }, host: SchemaDialect): string;
59
+ export declare function quoteConsoleIdentifier(dialect: ConsoleSqlDialect, name: string): string;
60
+ export interface SchemaPlanContext {
61
+ readonly dialect: ConsoleSqlDialect;
62
+ readonly host: SchemaDialect;
63
+ /** True when the table exists (declared, discovered or physical). */
64
+ hasTable(table: string): boolean;
65
+ /** True when plugin code declares the table (its columns are read by that code). */
66
+ isDeclared?(table: string): boolean;
67
+ /** MySQL: the full current definition of a column, for `MODIFY COLUMN`. */
68
+ mysqlColumn?(table: string, column: string): Promise<MysqlColumnDefinition | undefined>;
69
+ /** Current columns of an existing table, for checks and MySQL `MODIFY`. */
70
+ describe(table: string): Promise<DatabaseHostTableSchema>;
71
+ }
72
+ /** Validates a change and renders its DDL; throws {@link ConsoleSchemaRefusal}. */
73
+ export declare function planConsoleSchemaChange(input: unknown, context: SchemaPlanContext): Promise<DatabaseHostSchemaPlan>;
74
+ /** Zhin column type of a native SQL type (best effort, for filters and the schema form). */
75
+ export declare function zhinColumnType(native: string): string;
76
+ /** Reads the physical columns and indexes of a table. */
77
+ export declare function introspectConsoleTable(dialect: ConsoleSqlDialect, query: (sql: string, params?: unknown[]) => Promise<unknown>, table: string): Promise<DatabaseHostTableSchema>;
78
+ /** Physical base tables of the current database / schema. */
79
+ export declare function listPhysicalTables(dialect: ConsoleSqlDialect, query: (sql: string, params?: unknown[]) => Promise<unknown>): Promise<string[]>;