@zhin.js/core 1.1.57 → 1.1.59

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 (89) hide show
  1. package/lib/built/user-interaction.d.ts +1 -1
  2. package/lib/feature/command.d.ts +2 -4
  3. package/lib/feature/command.js +1 -2
  4. package/lib/feature/middleware.d.ts +2 -2
  5. package/lib/feature/middleware.js +1 -1
  6. package/lib/index.d.ts +1 -1
  7. package/lib/plugin-runtime/im/command-feedback.d.ts +20 -1
  8. package/lib/plugin-runtime/im/command-feedback.js +63 -0
  9. package/lib/plugin-runtime/im/contracts.d.ts +60 -5
  10. package/lib/plugin-runtime/im/contracts.js +6 -2
  11. package/lib/plugin-runtime/im/endpoint-runtime.d.ts +2 -3
  12. package/lib/plugin-runtime/im/endpoint-runtime.js +2 -2
  13. package/lib/plugin-runtime/im/host/component-host-installer.d.ts +2 -0
  14. package/lib/plugin-runtime/im/host/component-host-installer.js +14 -0
  15. package/lib/plugin-runtime/im/host/conversation-migration.d.ts +5 -0
  16. package/lib/plugin-runtime/im/host/conversation-migration.js +75 -0
  17. package/lib/plugin-runtime/im/host/database-config.d.ts +10 -0
  18. package/lib/plugin-runtime/im/host/database-config.js +114 -0
  19. package/lib/plugin-runtime/im/host/database-host-installer.d.ts +13 -0
  20. package/lib/plugin-runtime/im/host/database-host-installer.js +389 -0
  21. package/lib/plugin-runtime/im/host/database-state.d.ts +9 -0
  22. package/lib/plugin-runtime/im/host/database-state.js +91 -0
  23. package/lib/plugin-runtime/im/host/index.d.ts +8 -0
  24. package/lib/plugin-runtime/im/host/index.js +8 -0
  25. package/lib/plugin-runtime/im/host/locale-host-installer.d.ts +3 -0
  26. package/lib/plugin-runtime/im/host/locale-host-installer.js +60 -0
  27. package/lib/plugin-runtime/im/host/outbound-host-installer.d.ts +8 -0
  28. package/lib/plugin-runtime/im/host/outbound-host-installer.js +153 -0
  29. package/lib/plugin-runtime/im/host/sender-enrichment.d.ts +33 -0
  30. package/lib/plugin-runtime/im/host/sender-enrichment.js +215 -0
  31. package/lib/plugin-runtime/im/im-runtime.d.ts +7 -3
  32. package/lib/plugin-runtime/im/im-runtime.js +9 -7
  33. package/lib/plugin-runtime/im/inbound-dedup.d.ts +32 -0
  34. package/lib/plugin-runtime/im/inbound-dedup.js +138 -1
  35. package/lib/plugin-runtime/im/inbound-origin.d.ts +24 -2
  36. package/lib/plugin-runtime/im/inbound-origin.js +108 -1
  37. package/lib/plugin-runtime/im/inbound-runtime.d.ts +10 -13
  38. package/lib/plugin-runtime/im/inbound-runtime.js +92 -412
  39. package/lib/plugin-runtime/im/inbound-spine.d.ts +194 -0
  40. package/lib/plugin-runtime/im/inbound-spine.js +333 -0
  41. package/lib/plugin-runtime/im/index.d.ts +5 -7
  42. package/lib/plugin-runtime/im/index.js +5 -6
  43. package/lib/plugin-runtime/im/interaction-runtime.d.ts +4 -7
  44. package/lib/plugin-runtime/im/interaction-runtime.js +5 -8
  45. package/lib/plugin-runtime/im/interactive-router.d.ts +31 -4
  46. package/lib/plugin-runtime/im/interactive-router.js +134 -2
  47. package/lib/plugin-runtime/im/message-dispatcher.d.ts +1 -1
  48. package/lib/plugin-runtime/im/message-dispatcher.js +1 -2
  49. package/lib/plugin-runtime/im/message-events.d.ts +33 -3
  50. package/lib/plugin-runtime/im/message-events.js +34 -0
  51. package/lib/plugin-runtime/im/outbound-delivery-runtime.d.ts +1 -2
  52. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +4 -8
  53. package/lib/plugin-runtime/im/outbound-renderer.d.ts +32 -2
  54. package/lib/plugin-runtime/im/outbound-renderer.js +95 -4
  55. package/package.json +13 -14
  56. package/lib/plugin-runtime/im/captured-endpoint-operation.d.ts +0 -34
  57. package/lib/plugin-runtime/im/captured-endpoint-operation.js +0 -1
  58. package/lib/plugin-runtime/im/command-menu-navigation.d.ts +0 -13
  59. package/lib/plugin-runtime/im/command-menu-navigation.js +0 -43
  60. package/lib/plugin-runtime/im/command-menu-presentation.d.ts +0 -14
  61. package/lib/plugin-runtime/im/command-menu-presentation.js +0 -25
  62. package/lib/plugin-runtime/im/group-rule-violation.d.ts +0 -52
  63. package/lib/plugin-runtime/im/group-rule-violation.js +0 -10
  64. package/lib/plugin-runtime/im/ingress-route.d.ts +0 -10
  65. package/lib/plugin-runtime/im/ingress-route.js +0 -10
  66. package/lib/plugin-runtime/im/interaction-operation.d.ts +0 -12
  67. package/lib/plugin-runtime/im/interaction-operation.js +0 -2
  68. package/lib/plugin-runtime/im/jsx-button-registry.d.ts +0 -31
  69. package/lib/plugin-runtime/im/jsx-button-registry.js +0 -135
  70. package/lib/plugin-runtime/im/locale.d.ts +0 -5
  71. package/lib/plugin-runtime/im/locale.js +0 -12
  72. package/lib/plugin-runtime/im/login-assist-host.d.ts +0 -6
  73. package/lib/plugin-runtime/im/login-assist-host.js +0 -6
  74. package/lib/plugin-runtime/im/member-welcome.d.ts +0 -8
  75. package/lib/plugin-runtime/im/member-welcome.js +0 -11
  76. package/lib/plugin-runtime/im/message-bus.d.ts +0 -38
  77. package/lib/plugin-runtime/im/message-bus.js +0 -40
  78. package/lib/plugin-runtime/im/operation-endpoint.d.ts +0 -6
  79. package/lib/plugin-runtime/im/operation-endpoint.js +0 -2
  80. package/lib/plugin-runtime/im/operation-resources.d.ts +0 -15
  81. package/lib/plugin-runtime/im/operation-resources.js +0 -2
  82. package/lib/plugin-runtime/im/outbound-ledger.d.ts +0 -24
  83. package/lib/plugin-runtime/im/outbound-ledger.js +0 -114
  84. package/lib/plugin-runtime/im/outbound-presentation.d.ts +0 -19
  85. package/lib/plugin-runtime/im/outbound-presentation.js +0 -41
  86. package/lib/plugin-runtime/im/outbound-projection.d.ts +0 -17
  87. package/lib/plugin-runtime/im/outbound-projection.js +0 -55
  88. package/lib/plugin-runtime/im/runtime-middleware.d.ts +0 -5
  89. package/lib/plugin-runtime/im/runtime-middleware.js +0 -18
@@ -0,0 +1,389 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { Registry, ensureDatabaseColumns } from '@zhin.js/database';
5
+ import { formatCompact, getLogger } from '@zhin.js/logger';
6
+ import { guardTransactionModel, databaseHostToken, databaseRootHostToken, PluginDatabaseHost, rootPluginId, } from '@zhin.js/plugin-runtime';
7
+ import { normalizeDatabaseHostConfig, } from './database-config.js';
8
+ import { createDatabaseState } from './database-state.js';
9
+ const logger = getLogger('Database');
10
+ function wrapModel(model, db, tableName) {
11
+ return {
12
+ ...(model.aggregate && db && ['sqlite', 'mysql', 'pg'].includes(db.dialectName) ? { aggregate: () => {
13
+ const source = model.aggregate();
14
+ const chain = {
15
+ min(field, alias) { source.min(field, alias); return chain; },
16
+ max(field, alias) { source.max(field, alias); return chain; },
17
+ groupBy(...fields) { source.groupBy(...fields); return chain; },
18
+ where(query) { source.where(query); return chain; },
19
+ then(resolve, reject) { return Promise.resolve(source).then(resolve, reject); },
20
+ };
21
+ return Object.freeze(chain);
22
+ } } : {}),
23
+ select: (...fields) => {
24
+ if (fields.includes('*')) {
25
+ throw new TypeError('select() requires explicit column names; "*" is not supported '
26
+ + '(pass real column names, e.g. select("id", "title")), or use count() for counting.');
27
+ }
28
+ const selection = model.select(...fields);
29
+ // 链式 + 可 await:console logs 页需要 orderBy/limit,插件侧 `await select().where(q)` 不变
30
+ const chain = {
31
+ where: (query) => { selection.where(query); return chain; },
32
+ orderBy: (field, direction) => { selection.orderBy?.(field, direction); return chain; },
33
+ limit: (count) => { selection.limit?.(count); return chain; },
34
+ then: (onfulfilled, onrejected) => Promise.resolve(selection)
35
+ .then(onfulfilled, onrejected),
36
+ };
37
+ return chain;
38
+ },
39
+ insert: (row) => Promise.resolve(model.insert(row)),
40
+ delete: () => ({
41
+ where: (query) => Promise.resolve(model.delete(query)),
42
+ }),
43
+ update: (patch) => ({
44
+ where: (query) => Promise.resolve(model.update(patch).where(query)),
45
+ }),
46
+ // DB 侧 count 聚合(console /api/logs/stats 不再为计数整表加载);
47
+ // 方言不支持 aggregate(如 redis/mongodb)时降级为 select('id') 计数。
48
+ count: async (where) => {
49
+ const filter = where ?? {};
50
+ if (db && tableName) {
51
+ try {
52
+ const counted = await db.aggregate(tableName).count('*', 'total').where(filter);
53
+ const total = Number(counted[0]?.total);
54
+ if (Number.isFinite(total))
55
+ return total;
56
+ }
57
+ catch {
58
+ /* fall through to select('id') */
59
+ }
60
+ }
61
+ const selection = model.select('id');
62
+ const result = Object.keys(filter).length > 0 ? selection.where(filter) : selection;
63
+ const rows = await Promise.resolve(result);
64
+ return rows.length;
65
+ },
66
+ };
67
+ }
68
+ export function createDatabaseHost(config) {
69
+ const { dialect, ...connectionConfig } = config;
70
+ const db = Registry.create(dialect, connectionConfig);
71
+ let started = false;
72
+ const state = createDatabaseState(db, config.dialect, () => started);
73
+ const wrapped = new Map();
74
+ const definedTables = new Set();
75
+ const definitions = new Map();
76
+ const additions = new Map();
77
+ const consolePort = createDatabaseConsole(db, config.dialect, () => started, definedTables, definitions);
78
+ return {
79
+ db,
80
+ state,
81
+ get dialect() {
82
+ return config.dialect;
83
+ },
84
+ get started() {
85
+ return started;
86
+ },
87
+ define(name, definition, options) {
88
+ const migration = Object.fromEntries((options?.addColumns ?? []).map(field => {
89
+ const column = Object.hasOwn(definition, field) ? definition[field] : undefined;
90
+ if (!column || typeof column !== 'object' || Array.isArray(column)
91
+ || !('type' in column) || ('primary' in column && column.primary)
92
+ || ('autoIncrement' in column && column.autoIncrement)
93
+ || (!('nullable' in column && column.nullable === true) && !('default' in column))) {
94
+ throw new TypeError(`Additive column '${field}' in '${name}' must be declared, nullable or defaulted, and not a primary key`);
95
+ }
96
+ return [field, structuredClone(column)];
97
+ }));
98
+ const existing = definitions.get(name);
99
+ // Host 跨世代共享:reload 后新世代会重复 define 同名表,
100
+ // 定义一致则幂等跳过(即使已 started),不一致才报错。
101
+ if (existing !== undefined) {
102
+ if (isDeepStrictEqual(existing, definition)) {
103
+ const previous = additions.get(name) ?? {};
104
+ const merged = { ...previous, ...migration };
105
+ if (started && !isDeepStrictEqual(previous, merged)) {
106
+ throw new Error(`DatabaseHost already started; restart to migrate table ${name}`);
107
+ }
108
+ if (Object.keys(merged).length)
109
+ additions.set(name, merged);
110
+ return;
111
+ }
112
+ throw new Error(`Table '${name}' already defined with a different definition`);
113
+ }
114
+ if (started) {
115
+ throw new Error(`DatabaseHost already started; cannot define table ${name}`);
116
+ }
117
+ definedTables.add(name);
118
+ definitions.set(name, definition);
119
+ if (Object.keys(migration).length)
120
+ additions.set(name, migration);
121
+ db.define(name, definition);
122
+ },
123
+ tables() {
124
+ return [...definedTables];
125
+ },
126
+ models: {
127
+ get(name) {
128
+ if (!started)
129
+ return undefined;
130
+ const cached = wrapped.get(name);
131
+ if (cached)
132
+ return cached;
133
+ const raw = db.models.get(name);
134
+ if (!raw)
135
+ return undefined;
136
+ const model = wrapModel(raw, db, name);
137
+ wrapped.set(name, model);
138
+ return model;
139
+ },
140
+ },
141
+ async transaction(callback) {
142
+ if (!started)
143
+ throw new Error('Database is not connected');
144
+ if (!['sqlite', 'mysql', 'pg'].includes(config.dialect))
145
+ throw new Error(`Transactions are not supported by '${config.dialect}'`);
146
+ return db.transaction(async (transaction) => {
147
+ let active = true;
148
+ try {
149
+ return await callback({ model(name) {
150
+ if (!active)
151
+ throw new Error('Database transaction is already closed');
152
+ if (!definedTables.has(name))
153
+ throw new Error(`Table '${name}' is not registered`);
154
+ return guardTransactionModel({
155
+ select: (...fields) => {
156
+ if (fields.includes('*')) {
157
+ throw new TypeError('select() requires explicit column names; "*" is not supported '
158
+ + '(pass real column names, e.g. select("id", "title")), or use count() for counting.');
159
+ }
160
+ const selection = transaction.select(name, fields);
161
+ const chain = {
162
+ where: (query) => { selection.where(query); return chain; },
163
+ orderBy: (field, direction) => { selection.orderBy?.(field, direction); return chain; },
164
+ limit: (count) => { selection.limit?.(count); return chain; },
165
+ then: (onfulfilled, onrejected) => Promise.resolve(selection)
166
+ .then(onfulfilled, onrejected),
167
+ };
168
+ return chain;
169
+ },
170
+ insert: row => transaction.insert(name, row),
171
+ update: patch => ({ where: async (query) => transaction.update(name, patch).where(query) }),
172
+ delete: () => ({ where: async (query) => transaction.delete(name).where(query) }),
173
+ }, () => { if (!active)
174
+ throw new Error('Database transaction is already closed'); });
175
+ } });
176
+ }
177
+ finally {
178
+ active = false;
179
+ }
180
+ }, { isolationLevel: 'REPEATABLE_READ' });
181
+ },
182
+ console: consolePort,
183
+ getRawDatabase() {
184
+ if (!started)
185
+ return undefined;
186
+ return db;
187
+ },
188
+ async start() {
189
+ if (started)
190
+ return;
191
+ try {
192
+ await db.start();
193
+ for (const [table, columns] of additions) {
194
+ await ensureDatabaseColumns(db, table, columns);
195
+ }
196
+ started = true;
197
+ wrapped.clear();
198
+ logger.debug(formatCompact({ op: 'database_start', dialect: config.dialect }));
199
+ }
200
+ catch (error) {
201
+ await db.stop().catch(() => undefined);
202
+ throw error;
203
+ }
204
+ },
205
+ async stop() {
206
+ if (!started)
207
+ return;
208
+ await db.stop();
209
+ started = false;
210
+ wrapped.clear();
211
+ },
212
+ };
213
+ }
214
+ function createDatabaseConsole(db, configuredDialect, isStarted, tableNames, definitions) {
215
+ const type = databaseType(configuredDialect);
216
+ const requireModel = (table) => {
217
+ if (!isStarted())
218
+ throw new Error('Database is not connected');
219
+ const model = db.models.get(table);
220
+ if (!model)
221
+ throw new Error(`Table '${table}' not found`);
222
+ return model;
223
+ };
224
+ const port = {
225
+ info: () => ({
226
+ dialect: configuredDialect,
227
+ type,
228
+ tables: [...tableNames],
229
+ connected: isStarted(),
230
+ }),
231
+ tables: () => [...tableNames].map((name) => ({
232
+ name,
233
+ columns: definitions.get(name),
234
+ })),
235
+ async select(table, page, pageSize, where) {
236
+ const model = requireModel(table);
237
+ if (type === 'keyvalue') {
238
+ if (!model.entries)
239
+ throw new Error(`Table '${table}' is not a key-value bucket`);
240
+ const all = await model.entries();
241
+ const start = (page - 1) * pageSize;
242
+ return {
243
+ rows: all.slice(start, start + pageSize).map(([key, value]) => ({ key, value })),
244
+ total: all.length,
245
+ page,
246
+ pageSize,
247
+ };
248
+ }
249
+ const filter = where ?? {};
250
+ let total;
251
+ try {
252
+ const counted = await db.aggregate(table).count('*', 'total').where(filter);
253
+ total = Number(counted[0]?.total ?? 0);
254
+ }
255
+ catch {
256
+ const all = await model.select();
257
+ total = all.length;
258
+ }
259
+ let selection = model.select();
260
+ if (Object.keys(filter).length > 0)
261
+ selection = selection.where(filter);
262
+ const rows = await selection.limit(pageSize).offset((page - 1) * pageSize);
263
+ return { rows, total, page, pageSize };
264
+ },
265
+ async insert(table, row) {
266
+ const model = requireModel(table);
267
+ if (type === 'keyvalue') {
268
+ if (!model.set || row.key == null)
269
+ throw new Error('key is required for KV insert');
270
+ await model.set(String(row.key), row.value);
271
+ }
272
+ else if (type === 'document' && model.create) {
273
+ await model.create(row);
274
+ }
275
+ else {
276
+ await model.insert(row);
277
+ }
278
+ },
279
+ async update(table, row, where) {
280
+ const model = requireModel(table);
281
+ if (type === 'keyvalue') {
282
+ if (!model.set || where.key == null)
283
+ throw new Error('key is required for KV update');
284
+ await model.set(String(where.key), row.value);
285
+ return 1;
286
+ }
287
+ if (type === 'document' && where._id != null && model.updateById) {
288
+ return await model.updateById(String(where._id), row);
289
+ }
290
+ return await model.update(row).where(where);
291
+ },
292
+ async delete(table, where) {
293
+ const model = requireModel(table);
294
+ if (type === 'keyvalue') {
295
+ if (!model.deleteByKey || where.key == null)
296
+ throw new Error('key is required for KV delete');
297
+ await model.deleteByKey(String(where.key));
298
+ return 1;
299
+ }
300
+ if (type === 'document' && where._id != null && model.deleteById) {
301
+ return await model.deleteById(String(where._id));
302
+ }
303
+ return await model.delete(where);
304
+ },
305
+ async dropTable(table) {
306
+ requireModel(table);
307
+ await db.query(db.dialect.formatDropTable(table, true));
308
+ db.models.delete(table);
309
+ db.definitions.delete(table);
310
+ tableNames.delete(table);
311
+ definitions.delete(table);
312
+ },
313
+ async kvGet(table, key) {
314
+ const model = requireModel(table);
315
+ if (!model.get)
316
+ throw new Error(`Table '${table}' is not a key-value bucket`);
317
+ return await model.get(key);
318
+ },
319
+ async kvSet(table, key, value, ttl) {
320
+ const model = requireModel(table);
321
+ if (!model.set)
322
+ throw new Error(`Table '${table}' is not a key-value bucket`);
323
+ await model.set(key, value, ttl);
324
+ },
325
+ async kvDelete(table, key) {
326
+ const model = requireModel(table);
327
+ if (!model.deleteByKey)
328
+ throw new Error(`Table '${table}' is not a key-value bucket`);
329
+ await model.deleteByKey(key);
330
+ },
331
+ async kvEntries(table) {
332
+ const model = requireModel(table);
333
+ if (!model.entries)
334
+ throw new Error(`Table '${table}' is not a key-value bucket`);
335
+ return (await model.entries()).map(([key, value]) => ({ key, value }));
336
+ },
337
+ };
338
+ return Object.freeze(port);
339
+ }
340
+ function databaseType(dialect) {
341
+ if (dialect === 'mongodb')
342
+ return 'document';
343
+ if (dialect === 'redis')
344
+ return 'keyvalue';
345
+ return 'related';
346
+ }
347
+ export async function resolveDatabaseConfig(projectRoot, config) {
348
+ const document = await readConfigDocument(config);
349
+ const configured = document && typeof document === 'object'
350
+ ? document.database
351
+ : undefined;
352
+ if (configured && typeof configured === 'object' && !Array.isArray(configured)) {
353
+ const value = configured;
354
+ const dialect = typeof value.dialect === 'string' ? value.dialect : 'sqlite';
355
+ return normalizeDatabaseHostConfig({ ...value, dialect });
356
+ }
357
+ const filename = join(projectRoot, '.zhin', 'data.sqlite');
358
+ await mkdir(dirname(filename), { recursive: true });
359
+ return Object.freeze({ dialect: 'sqlite', filename });
360
+ }
361
+ export function installDatabaseHost(host) {
362
+ return ({ resources, handoff, admission }) => {
363
+ // Domain tables (e.g. github_oauth_users) are defined by owning plugins in setup().
364
+ // Plugins receive a root-scoped facade through the historical token. The
365
+ // raw host remains available only to CLI composition through its root token.
366
+ resources.provide(databaseRootHostToken, host);
367
+ resources.provide(databaseHostToken, new PluginDatabaseHost(rootPluginId(), host, admission));
368
+ // Host 是进程级共享资源:不能随世代 dispose / 回滚 stop(旧世代仍在用)。
369
+ // start 幂等,stop 由进程退出路径(start-command control.stop)统一触发。
370
+ handoff.add({
371
+ activateNext: async (signal) => {
372
+ signal.throwIfAborted();
373
+ await host.start();
374
+ signal.throwIfAborted();
375
+ },
376
+ });
377
+ };
378
+ }
379
+ async function readConfigDocument(config) {
380
+ if (!isConfigDocumentPort(config))
381
+ return config;
382
+ return (await config.read()).document;
383
+ }
384
+ function isConfigDocumentPort(value) {
385
+ if (!value || typeof value !== 'object')
386
+ return false;
387
+ const candidate = value;
388
+ return typeof candidate.read === 'function';
389
+ }
@@ -0,0 +1,9 @@
1
+ import type { BuildQueryResult, QueryParams } from '@zhin.js/database';
2
+ import type { PersistentStatePort } from '@zhin.js/plugin-runtime';
3
+ /** Uses the process-owned database's normal builders and connection. */
4
+ export interface StateDatabase {
5
+ define(name: string, definition: unknown): void;
6
+ buildQuery(input: QueryParams<Record<string, Record<string, unknown>>, string>): BuildQueryResult<string>;
7
+ query(query: string, params?: unknown[]): Promise<unknown>;
8
+ }
9
+ export declare function createDatabaseState(db: StateDatabase, dialect: string, isStarted: () => boolean): PersistentStatePort;
@@ -0,0 +1,91 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ const table = '__zhin_persistent_state';
3
+ const definition = {
4
+ id: { type: 'text', length: 64, primary: true, nullable: false },
5
+ revision: { type: 'text', length: 36, nullable: false },
6
+ value: { type: 'text', nullable: false },
7
+ expires_at: { type: 'bigint', nullable: true },
8
+ };
9
+ export function createDatabaseState(db, dialect, isStarted) {
10
+ const supported = dialect === 'sqlite' || dialect === 'mysql' || dialect === 'pg';
11
+ if (supported)
12
+ db.define(table, dialect === 'pg' ? {
13
+ ...definition,
14
+ // PostgreSQL TEXT has no length modifier; the hashed key is already bounded.
15
+ id: { type: 'text', primary: true, nullable: false },
16
+ revision: { type: 'text', nullable: false },
17
+ } : definition);
18
+ const requireDatabase = () => {
19
+ if (!supported)
20
+ throw new Error(`Atomic persistent state is not supported by database dialect '${dialect}'`);
21
+ if (!isStarted())
22
+ throw new Error('Persistent state database is not connected');
23
+ };
24
+ const execute = async (input, returning = false) => {
25
+ const built = db.buildQuery(input);
26
+ const sql = dialect === 'pg' && returning ? `${built.query} RETURNING "id"` : built.query;
27
+ return db.query(sql, built.params);
28
+ };
29
+ const changed = (result) => {
30
+ if (typeof result === 'number')
31
+ return result === 1;
32
+ if (Array.isArray(result))
33
+ return result.length === 1;
34
+ return !!result && typeof result === 'object'
35
+ && Number(result.affectedRows) === 1;
36
+ };
37
+ return {
38
+ async read(owner, scope, key) {
39
+ requireDatabase();
40
+ const rows = await execute({ type: 'select', tableName: table,
41
+ fields: ['revision', 'value', 'expires_at'], conditions: { id: address(owner, scope, key) } });
42
+ if (!Array.isArray(rows))
43
+ throw new Error('Invalid persistent state database result');
44
+ const row = rows[0];
45
+ if (!row)
46
+ return undefined;
47
+ return { revision: row.revision, value: JSON.parse(row.value),
48
+ expiresAt: row.expires_at === null ? null : Number(row.expires_at) };
49
+ },
50
+ async compareExchange(owner, scope, key, revision, value, expiresAt) {
51
+ requireDatabase();
52
+ const id = address(owner, scope, key);
53
+ if (revision === undefined) {
54
+ if (value === undefined)
55
+ return true;
56
+ try {
57
+ await execute({ type: 'insert', tableName: table,
58
+ data: { id, revision: randomUUID(), value: JSON.stringify(value), expires_at: expiresAt } });
59
+ return true;
60
+ }
61
+ catch (error) {
62
+ if (isUniqueConflict(error))
63
+ return false;
64
+ throw error;
65
+ }
66
+ }
67
+ return changed(await execute(value === undefined
68
+ ? { type: 'delete', tableName: table, conditions: { id, revision } }
69
+ : { type: 'update', tableName: table, conditions: { id, revision },
70
+ update: { revision: randomUUID(), value: JSON.stringify(value), expires_at: expiresAt } }, true));
71
+ },
72
+ };
73
+ }
74
+ function address(owner, scope, key) {
75
+ // Tuple encoding separates owners, users, conversations, parents and threads;
76
+ // hash keeps physical keys short and excludes NUL from SQL text identifiers.
77
+ const parts = scope.kind === 'plugin' ? ['plugin']
78
+ : scope.kind === 'user' ? ['user', scope.endpoint.adapter, scope.endpoint.id, scope.senderId]
79
+ : ['conversation', scope.target.endpoint.adapter, scope.target.endpoint.id, scope.target.kind,
80
+ scope.target.id, scope.target.parent?.kind ?? null, scope.target.parent?.id ?? null, scope.target.threadId ?? null];
81
+ return createHash('sha256').update(JSON.stringify([owner, parts, key])).digest('hex');
82
+ }
83
+ function isUniqueConflict(error) {
84
+ if (!error || typeof error !== 'object')
85
+ return false;
86
+ const failure = error;
87
+ return failure.code === '23505' || failure.code === 'ER_DUP_ENTRY' || failure.errno === 1062
88
+ || failure.code === 'SQLITE_CONSTRAINT_PRIMARYKEY' || failure.code === 'SQLITE_CONSTRAINT_UNIQUE'
89
+ || (failure.code === 'ERR_SQLITE_ERROR' && (failure.errcode === 1555 || failure.errcode === 2067))
90
+ || (failure.cause !== undefined && isUniqueConflict(failure.cause));
91
+ }
@@ -0,0 +1,8 @@
1
+ export * from './component-host-installer.js';
2
+ export * from './outbound-host-installer.js';
3
+ export * from './sender-enrichment.js';
4
+ export * from './conversation-migration.js';
5
+ export * from './locale-host-installer.js';
6
+ export * from './database-config.js';
7
+ export * from './database-state.js';
8
+ export * from './database-host-installer.js';
@@ -0,0 +1,8 @@
1
+ export * from './component-host-installer.js';
2
+ export * from './outbound-host-installer.js';
3
+ export * from './sender-enrichment.js';
4
+ export * from './conversation-migration.js';
5
+ export * from './locale-host-installer.js';
6
+ export * from './database-config.js';
7
+ export * from './database-state.js';
8
+ export * from './database-host-installer.js';
@@ -0,0 +1,3 @@
1
+ import { type DatabaseHost, type RootResourceInstaller } from '@zhin.js/plugin-runtime';
2
+ /** Uses the existing SQL state port; no file or memory persistence fallback. */
3
+ export declare function installLocaleHost(database: DatabaseHost): RootResourceInstaller;
@@ -0,0 +1,60 @@
1
+ import { commandFeatureId, defineCommand } from '@zhin.js/command';
2
+ import { createMessages, isLocale, PluginStateStore, rootPluginId, userLocalePreferencesToken, } from '@zhin.js/plugin-runtime';
3
+ const messages = createMessages({
4
+ usage: { 'zh-CN': '用法:{chinese} 或 {english}', en: 'Usage: {chinese} or {english}' },
5
+ unavailable: { 'zh-CN': '个人语言设置需要 SQLite、MySQL 或 PostgreSQL 持久存储;当前仍使用项目语言。', en: 'Personal language settings require SQLite, MySQL, or PostgreSQL storage. The project language is still in use.' },
6
+ identity: { 'zh-CN': '请在有真实发送者身份的聊天中设置个人语言。', en: 'Set your language from a chat with a sender identity.' },
7
+ commandUnavailable: { 'zh-CN': '当前环境无法确定语言指令的调用方式。', en: 'The language command is unavailable in this command environment.' },
8
+ saved: { 'zh-CN': '个人语言已设置为简体中文;新操作生效,进行中的交互保持原语言。', en: 'Your language is now English. New operations use it; ongoing interactions keep their original language.' },
9
+ failed: { 'zh-CN': '无法确认个人语言已保存,请稍后重新设置。', en: 'The language setting could not be confirmed. Please try setting it again later.' },
10
+ });
11
+ /** Uses the existing SQL state port; no file or memory persistence fallback. */
12
+ export function installLocaleHost(database) {
13
+ return (context) => {
14
+ let preferences;
15
+ if (database.state && ['sqlite', 'mysql', 'pg'].includes(database.dialect)) {
16
+ const state = new PluginStateStore(rootPluginId(), database.state, undefined, context.admission);
17
+ preferences = Object.freeze({
18
+ async get(endpoint, senderId) {
19
+ const value = await state.forUser(endpoint, senderId).get('locale');
20
+ return isLocale(value) ? value : undefined;
21
+ },
22
+ async set(endpoint, senderId, locale) {
23
+ if (!isLocale(locale))
24
+ throw new TypeError('Unsupported locale');
25
+ await state.forUser(endpoint, senderId).set('locale', locale);
26
+ },
27
+ });
28
+ context.resources.provide(userLocalePreferencesToken, preferences);
29
+ }
30
+ if (!context.hasFeature?.(commandFeatureId))
31
+ return;
32
+ context.addFeature(commandFeatureId, 'language', defineCommand({
33
+ description: '设置个人语言',
34
+ descriptionI18n: { en: 'Set your language' },
35
+ execute: async (command) => {
36
+ const requested = command.args.join(' ').trim();
37
+ const input = command.input;
38
+ if (!input?.sender?.id || !input.conversation)
39
+ return messages(command.locale, 'identity');
40
+ if (!isLocale(requested)) {
41
+ const invocation = command.formatCommand('language');
42
+ if (invocation === undefined)
43
+ return messages(command.locale, 'commandUnavailable');
44
+ return messages(command.locale, 'usage', {
45
+ chinese: `${invocation} zh-CN`, english: `${invocation} en`,
46
+ });
47
+ }
48
+ if (!preferences)
49
+ return messages(command.locale, 'unavailable');
50
+ try {
51
+ await preferences.set(input.conversation.endpoint, input.sender.id, requested);
52
+ }
53
+ catch {
54
+ return messages(command.locale, 'failed');
55
+ }
56
+ return messages(requested, 'saved');
57
+ },
58
+ }));
59
+ };
60
+ }
@@ -0,0 +1,8 @@
1
+ import type { EndpointRuntime } from '../endpoint-runtime.js';
2
+ import { type OutboundRootHost, type RootResourceInstaller } from '@zhin.js/plugin-runtime';
3
+ export interface OutboundRuntimePort {
4
+ readonly endpoints: Pick<EndpointRuntime, 'captureOperation' | 'capabilities' | 'send' | 'sendTarget' | 'addReaction' | 'removeReaction' | 'recall' | 'edit' | 'typing'>;
5
+ runWithSnapshotView<T>(operation: () => Promise<T>): Promise<T>;
6
+ }
7
+ export declare function createOutboundHost(im: OutboundRuntimePort): OutboundRootHost;
8
+ export declare function installOutboundHost(im: OutboundRuntimePort): RootResourceInstaller;