@zhin.js/core 1.1.40 → 1.1.41

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 (39) hide show
  1. package/lib/built/ai-trigger.js +2 -2
  2. package/lib/built/html-segment-fallback.d.ts +4 -2
  3. package/lib/built/html-segment-fallback.js +1 -1
  4. package/lib/built/interactive-segments/resolve.js +1 -1
  5. package/lib/built/interactive-segments/types.d.ts +2 -2
  6. package/lib/built/interactive-segments/types.js +22 -2
  7. package/lib/built/outbound-content-arrays.d.ts +4 -0
  8. package/lib/built/outbound-content-arrays.js +32 -0
  9. package/lib/built/outbound-media-utils.d.ts +5 -3
  10. package/lib/built/outbound-media-utils.js +5 -3
  11. package/lib/built/segment-contract/assert.js +5 -0
  12. package/lib/built/segment-contract/json-schema.d.ts +1 -1
  13. package/lib/built/segment-contract/json-schema.js +30 -2
  14. package/lib/feature/component.d.ts +1 -0
  15. package/lib/feature/component.js +1 -0
  16. package/lib/index.d.ts +3 -2
  17. package/lib/index.js +2 -1
  18. package/lib/jsx-dev-runtime.d.ts +1 -2
  19. package/lib/jsx-dev-runtime.js +1 -2
  20. package/lib/jsx-runtime.d.ts +1 -12
  21. package/lib/jsx-runtime.js +1 -10
  22. package/lib/jsx.d.ts +1 -30
  23. package/lib/jsx.js +1 -93
  24. package/lib/message.d.ts +0 -11
  25. package/lib/plugin-runtime/im/contracts.d.ts +14 -6
  26. package/lib/plugin-runtime/im/contracts.js +28 -6
  27. package/lib/plugin-runtime/im/inbound-runtime.js +30 -6
  28. package/lib/plugin-runtime/im/message-dispatcher.js +0 -1
  29. package/lib/plugin-runtime/im/outbound-delivery-runtime.js +37 -18
  30. package/lib/plugin-runtime/im/outbound-renderer.d.ts +7 -2
  31. package/lib/plugin-runtime/im/outbound-renderer.js +31 -6
  32. package/lib/plugin-runtime/im/outbound-segments.d.ts +5 -0
  33. package/lib/plugin-runtime/im/outbound-segments.js +25 -6
  34. package/lib/types.d.ts +5 -7
  35. package/lib/utils.d.ts +4 -4
  36. package/lib/utils.js +9 -17
  37. package/package.json +14 -12
  38. package/lib/component.d.ts +0 -26
  39. package/lib/component.js +0 -583
@@ -86,7 +86,7 @@ export function isAtEndpoint(message, endpointAtIds) {
86
86
  return true;
87
87
  }
88
88
  for (const seg of messageElements(message)) {
89
- if (seg.type === 'text' && seg.data?.text && textMentionsEndpoint(seg.data.text, endpointKeys)) {
89
+ if (seg.type === 'text' && typeof seg.data?.text === 'string' && textMentionsEndpoint(seg.data.text, endpointKeys)) {
90
90
  return true;
91
91
  }
92
92
  }
@@ -126,7 +126,7 @@ export function removeAtEndpoint(message, endpointAtIds) {
126
126
  return messageElements(message)
127
127
  .filter((seg) => !isAtSegmentForEndpoint(seg, endpointKeys))
128
128
  .map((seg) => {
129
- if (seg.type !== 'text' || !seg.data?.text)
129
+ if (seg.type !== 'text' || typeof seg.data?.text !== 'string')
130
130
  return seg;
131
131
  const stripped = stripTextAtEndpoint(seg.data.text, endpointKeys).trim();
132
132
  if (!stripped)
@@ -2,5 +2,7 @@
2
2
  * Convert unresolved `html` segments to portable text content.
3
3
  * Canonical outbound rendering owns when this fallback is applied.
4
4
  */
5
- import type { SendContent } from '../types.js';
6
- export declare function coerceHtmlSegmentsToText(content: SendContent): SendContent;
5
+ import type { MessageElement } from '../types.js';
6
+ type SegmentContent = string | MessageElement | readonly SegmentContent[];
7
+ export declare function coerceHtmlSegmentsToText(content: SegmentContent): SegmentContent;
8
+ export {};
@@ -1,7 +1,7 @@
1
1
  import { segment } from '../utils.js';
2
2
  import { htmlToFallbackText } from './html-to-text.js';
3
3
  function asArray(content) {
4
- return Array.isArray(content) ? content : [content];
4
+ return Array.isArray(content) ? content.flatMap(item => asArray(item)) : [content];
5
5
  }
6
6
  function resolveHtmlSegmentText(data) {
7
7
  if (typeof data.text === 'string' && data.text.length > 0)
@@ -12,7 +12,7 @@ function toKeyboardElement(data) {
12
12
  return { type: KEYBOARD_SEGMENT_TYPE, data };
13
13
  }
14
14
  function asArray(content) {
15
- return Array.isArray(content) ? content : [content];
15
+ return Array.isArray(content) ? content.flatMap(item => asArray(item)) : [content];
16
16
  }
17
17
  function packSegments(out) {
18
18
  if (out.length === 0)
@@ -35,11 +35,11 @@ export type ActionSegmentData = {
35
35
  };
36
36
  export type InteractivePolicy = 'native' | 'text';
37
37
  export declare const DEFAULT_INTERACTIVE_POLICY: InteractivePolicy;
38
- export declare function isKeyboardSegment(item: MessageElement): item is MessageElement & {
38
+ export declare function isKeyboardSegment(item: unknown): item is MessageElement & {
39
39
  type: typeof KEYBOARD_SEGMENT_TYPE;
40
40
  data: KeyboardSegmentData;
41
41
  };
42
- export declare function isActionSegment(item: MessageElement): item is MessageElement & {
42
+ export declare function isActionSegment(item: unknown): item is MessageElement & {
43
43
  type: typeof ACTION_SEGMENT_TYPE;
44
44
  data: ActionSegmentData;
45
45
  };
@@ -2,8 +2,28 @@ export const KEYBOARD_SEGMENT_TYPE = 'keyboard';
2
2
  export const ACTION_SEGMENT_TYPE = 'action';
3
3
  export const DEFAULT_INTERACTIVE_POLICY = 'text';
4
4
  export function isKeyboardSegment(item) {
5
- return item != null && typeof item === 'object' && 'type' in item && item.type === KEYBOARD_SEGMENT_TYPE;
5
+ if (!isRecord(item) || item.type !== KEYBOARD_SEGMENT_TYPE || !isRecord(item.data))
6
+ return false;
7
+ const { rows, fallback } = item.data;
8
+ return Array.isArray(rows) && rows.every(row => Array.isArray(row) && row.every(isButtonData))
9
+ && (fallback === undefined || (isRecord(fallback) && typeof fallback.hint === 'string'
10
+ && isRecord(fallback.map) && Object.values(fallback.map).every(value => typeof value === 'string')));
6
11
  }
7
12
  export function isActionSegment(item) {
8
- return item != null && typeof item === 'object' && 'type' in item && item.type === ACTION_SEGMENT_TYPE;
13
+ return isRecord(item) && item.type === ACTION_SEGMENT_TYPE && isRecord(item.data)
14
+ && typeof item.data.id === 'string' && typeof item.data.payload === 'string'
15
+ && (item.data.sourceMessageId === undefined || typeof item.data.sourceMessageId === 'string');
16
+ }
17
+ function isRecord(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ }
20
+ function isButtonData(value) {
21
+ return isRecord(value) && typeof value.id === 'string' && typeof value.label === 'string'
22
+ && typeof value.payload === 'string'
23
+ && (value.disabled === undefined || typeof value.disabled === 'boolean')
24
+ && (value.style === undefined || value.style === 'primary' || value.style === 'danger' || value.style === 'secondary')
25
+ && (value.mode === undefined || value.mode === 'callback' || value.mode === 'command')
26
+ && (value.command === undefined || (isRecord(value.command)
27
+ && (value.command.enter === undefined || typeof value.command.enter === 'boolean')
28
+ && (value.command.reply === undefined || typeof value.command.reply === 'boolean')));
9
29
  }
@@ -0,0 +1,4 @@
1
+ /** Independent structural budget; array nesting does not spend component recursion depth. */
2
+ export declare const MAX_OUTBOUND_ARRAY_DEPTH = 512;
3
+ /** Flatten untrusted authoring/native arrays without recursion or shared-reference false positives. */
4
+ export declare function flattenOutboundArray(values: readonly unknown[]): unknown[];
@@ -0,0 +1,32 @@
1
+ /** Independent structural budget; array nesting does not spend component recursion depth. */
2
+ export const MAX_OUTBOUND_ARRAY_DEPTH = 512;
3
+ /** Flatten untrusted authoring/native arrays without recursion or shared-reference false positives. */
4
+ export function flattenOutboundArray(values) {
5
+ const output = [];
6
+ const active = new Set([values]);
7
+ const frames = [{ values, index: 0 }];
8
+ while (frames.length) {
9
+ const frame = frames[frames.length - 1];
10
+ if (frame.index >= frame.values.length) {
11
+ active.delete(frame.values);
12
+ frames.pop();
13
+ continue;
14
+ }
15
+ const index = frame.index++;
16
+ // Array.flat skips holes, but explicit undefined must remain for validation.
17
+ if (!(index in frame.values))
18
+ continue;
19
+ const value = frame.values[index];
20
+ if (!Array.isArray(value)) {
21
+ output.push(value);
22
+ continue;
23
+ }
24
+ if (active.has(value))
25
+ throw new TypeError('Cyclic SendContent array');
26
+ if (frames.length >= MAX_OUTBOUND_ARRAY_DEPTH)
27
+ throw new RangeError('SendContent array depth exceeded 512');
28
+ active.add(value);
29
+ frames.push({ values: value, index: 0 });
30
+ }
31
+ return output;
32
+ }
@@ -1,9 +1,11 @@
1
- import type { MessageElement, SendContent } from '../types.js';
1
+ import type { MessageElement } from '../types.js';
2
2
  export declare function isRemoteUrl(value: string): boolean;
3
3
  /** 从 message 段 data 提取 base64 Buffer(data: URL / base64:// / raw base64) */
4
4
  export declare function extractBase64Buffer(data: Record<string, unknown>): Buffer | undefined;
5
5
  /** 解析本地文件路径(非 http(s) / base64) */
6
6
  export declare function resolveLocalMediaPath(data: Record<string, unknown>): string | undefined;
7
- export declare function asMessageElements(content: SendContent): MessageElement[];
7
+ /** Already rendered content; JSX, component calls and raw wrappers need OutboundRenderer first. */
8
+ export type RenderedMessageContent = string | MessageElement | readonly RenderedMessageContent[];
9
+ export declare function asMessageElements(content: RenderedMessageContent): MessageElement[];
8
10
  export declare function isMediaSegmentType(type: string): boolean;
9
- export declare function collectOutboundMediaKinds(content: SendContent | undefined): string[];
11
+ export declare function collectOutboundMediaKinds(content: RenderedMessageContent | undefined): string[];
@@ -1,3 +1,4 @@
1
+ import { isSegmentContent } from '../plugin-runtime/im/contracts.js';
1
2
  const MEDIA_SEGMENT_TYPES = new Set(['image', 'audio', 'video', 'file']);
2
3
  export function isRemoteUrl(value) {
3
4
  return /^https?:\/\//i.test(value);
@@ -40,10 +41,11 @@ export function asMessageElements(content) {
40
41
  if (typeof content === 'string') {
41
42
  return [{ type: 'text', data: { text: content } }];
42
43
  }
43
- if (!Array.isArray(content)) {
44
+ if (Array.isArray(content))
45
+ return content.flatMap(item => asMessageElements(item));
46
+ if (isSegmentContent(content))
44
47
  return [content];
45
- }
46
- return content.map((item) => typeof item === 'string' ? { type: 'text', data: { text: item } } : item);
48
+ throw new TypeError('Message elements require rendered content; JSX and component calls must use the outbound renderer');
47
49
  }
48
50
  export function isMediaSegmentType(type) {
49
51
  return MEDIA_SEGMENT_TYPES.has(type);
@@ -1,4 +1,5 @@
1
1
  import { isStrictCanonicalSegment } from './validate.js';
2
+ import { isActionSegment, isKeyboardSegment } from '../interactive-segments/types.js';
2
3
  const STRICT_CANONICAL_TYPES = new Set([
3
4
  'text', 'mention', 'image', 'audio', 'video', 'file', 'reply', 'forward',
4
5
  'face', 'dice', 'rps', 'share',
@@ -26,6 +27,10 @@ export function isCanonicalSegment(value) {
26
27
  return false;
27
28
  if (STRICT_CANONICAL_TYPES.has(value.type))
28
29
  return isStrictCanonicalSegment(value);
30
+ if (value.type === 'keyboard')
31
+ return isKeyboardSegment(value);
32
+ if (value.type === 'action')
33
+ return isActionSegment(value);
29
34
  return CORE_EXTENSION_TYPES.has(value.type) || extensionTypePattern.test(value.type);
30
35
  }
31
36
  export function assertCanonicalSegments(segments) {
@@ -16,7 +16,7 @@ export declare const mediaRefJsonSchema: JsonSchemaObject;
16
16
  export declare const STRICT_OUTBOUND_SEGMENT_TYPES: readonly ["text", "mention", "image", "audio", "video", "file", "reply", "forward", "face", "dice", "rps", "share"];
17
17
  /**
18
18
  * 单条 outbound 消息段的 JSON Schema。
19
- * 严格段镜像 validate.ts 的 data 约束;宽松段走 generic 分支。
19
+ * 严格段镜像 validate.ts,交互段镜像 interactive-segments/types.ts;其他扩展段走宽松分支。
20
20
  */
21
21
  export declare const outboundSegmentJsonSchema: JsonSchemaObject;
22
22
  /**
@@ -44,13 +44,29 @@ function strictBranch(type, data) {
44
44
  function dataObject(properties, required) {
45
45
  return { type: 'object', properties, required: [...required], additionalProperties: false };
46
46
  }
47
+ /** Interactive extension guards validate known fields while preserving platform-specific extras. */
48
+ function interactiveDataObject(properties, required) {
49
+ return { type: 'object', properties, required: [...required], additionalProperties: true };
50
+ }
51
+ const buttonJsonSchema = interactiveDataObject({
52
+ id: { type: 'string' },
53
+ label: { type: 'string' },
54
+ payload: { type: 'string' },
55
+ disabled: { type: 'boolean' },
56
+ style: { type: 'string', enum: ['primary', 'danger', 'secondary'] },
57
+ mode: { type: 'string', enum: ['callback', 'command'] },
58
+ command: interactiveDataObject({
59
+ enter: { type: 'boolean' },
60
+ reply: { type: 'boolean' },
61
+ }, []),
62
+ }, ['id', 'label', 'payload']);
47
63
  /** 宽松分支:未纳入严格契约的段类型,仅约束顶层形状(与 isCanonicalSegment 宽松路径一致) */
48
64
  const looseBranch = {
49
65
  type: 'object',
50
66
  properties: {
51
67
  type: {
52
68
  type: 'string',
53
- enum: ['voice', 'record', 'link', 'markdown', 'html', 'keyboard', 'action'],
69
+ enum: ['voice', 'record', 'link', 'markdown', 'html'],
54
70
  },
55
71
  data: { type: 'object' },
56
72
  platform: platformJsonSchema,
@@ -65,7 +81,7 @@ export const STRICT_OUTBOUND_SEGMENT_TYPES = [
65
81
  ];
66
82
  /**
67
83
  * 单条 outbound 消息段的 JSON Schema。
68
- * 严格段镜像 validate.ts 的 data 约束;宽松段走 generic 分支。
84
+ * 严格段镜像 validate.ts,交互段镜像 interactive-segments/types.ts;其他扩展段走宽松分支。
69
85
  */
70
86
  export const outboundSegmentJsonSchema = {
71
87
  description: 'zhin 消息段 {type, data, platform?}',
@@ -129,6 +145,18 @@ export const outboundSegmentJsonSchema = {
129
145
  version: { type: 'string' },
130
146
  }, ['appid']),
131
147
  }, ['url', 'title'])),
148
+ strictBranch('keyboard', interactiveDataObject({
149
+ rows: { type: 'array', items: { type: 'array', items: buttonJsonSchema } },
150
+ fallback: interactiveDataObject({
151
+ hint: { type: 'string' },
152
+ map: { type: 'object', additionalProperties: { type: 'string' } },
153
+ }, ['hint', 'map']),
154
+ }, ['rows'])),
155
+ strictBranch('action', interactiveDataObject({
156
+ id: { type: 'string' },
157
+ payload: { type: 'string' },
158
+ sourceMessageId: { type: 'string' },
159
+ }, ['id', 'payload'])),
132
160
  looseBranch,
133
161
  ],
134
162
  };
@@ -1,2 +1,3 @@
1
1
  /** Authoring API for Component Feature — implementation in `@zhin.js/component`. */
2
2
  export * from '@zhin.js/component';
3
+ export { component, type ComponentCall } from '../plugin-runtime/im/contracts.js';
@@ -1,2 +1,3 @@
1
1
  /** Authoring API for Component Feature — implementation in `@zhin.js/component`. */
2
2
  export * from '@zhin.js/component';
3
+ export { component } from '../plugin-runtime/im/contracts.js';
package/lib/index.d.ts CHANGED
@@ -2,8 +2,9 @@
2
2
  * Canonical IM messages, Endpoints, rendering, and plugin-facing core types.
3
3
  * @module @zhin.js/core
4
4
  */
5
- export * from './component.js';
6
- export type { MessageChannel, MessageComponent, MessageType } from './message.js';
5
+ export { defineComponent, type ComponentDefinition, type ComponentContext } from '@zhin.js/component';
6
+ export { component, type ComponentCall, raw, type RawContent } from './plugin-runtime/im/contracts.js';
7
+ export type { MessageChannel, MessageType } from './message.js';
7
8
  export { Message, type MessageBase } from './plugin-runtime/im/contracts.js';
8
9
  export * from './im-scene.js';
9
10
  export * from './notice.js';
package/lib/index.js CHANGED
@@ -2,7 +2,8 @@
2
2
  * Canonical IM messages, Endpoints, rendering, and plugin-facing core types.
3
3
  * @module @zhin.js/core
4
4
  */
5
- export * from './component.js';
5
+ export { defineComponent } from '@zhin.js/component';
6
+ export { component, raw } from './plugin-runtime/im/contracts.js';
6
7
  export { Message } from './plugin-runtime/im/contracts.js';
7
8
  export * from './im-scene.js';
8
9
  export * from './notice.js';
@@ -1,2 +1 @@
1
- export * from './jsx-runtime.js';
2
- export { jsx as jsxDEV } from './jsx.js';
1
+ export * from '@zhin.js/jsx/jsx-dev-runtime';
@@ -1,2 +1 @@
1
- export * from './jsx-runtime.js';
2
- export { jsx as jsxDEV } from './jsx.js';
1
+ export * from '@zhin.js/jsx/jsx-dev-runtime';
@@ -1,12 +1 @@
1
- import { jsx, jsxs, Fragment, renderJSX } from './jsx.js';
2
- export { jsx, jsxs, Fragment, renderJSX };
3
- export type { JSX } from './jsx.js';
4
- declare const _default: {
5
- jsx: typeof jsx;
6
- jsxs: typeof jsxs;
7
- Fragment: import("./component.js").Component<{
8
- children?: import("./types.js").SendContent;
9
- }>;
10
- renderJSX: typeof renderJSX;
11
- };
12
- export default _default;
1
+ export * from '@zhin.js/jsx/jsx-runtime';
@@ -1,10 +1 @@
1
- // JSX 运行时入口文件
2
- import { jsx, jsxs, Fragment, renderJSX } from './jsx.js';
3
- export { jsx, jsxs, Fragment, renderJSX };
4
- // 默认导出 JSX 运行时
5
- export default {
6
- jsx,
7
- jsxs,
8
- Fragment,
9
- renderJSX
10
- };
1
+ export * from '@zhin.js/jsx/jsx-runtime';
package/lib/jsx.d.ts CHANGED
@@ -1,30 +1 @@
1
- import type { SendContent, MessageElement } from './types.js';
2
- import type { MessageComponent } from './message.js';
3
- import type { Component, ComponentContext } from './component.js';
4
- export type JSXChildren = MessageElement | string | number | boolean | null | undefined | JSXChildren[];
5
- export type JSXElementType = string | Component<any>;
6
- export type JSXProps = Record<string, any> & {
7
- children?: JSXChildren;
8
- };
9
- export { Fragment } from './component.js';
10
- export declare namespace JSX {
11
- type Element = SendContent | Promise<SendContent>;
12
- interface ElementClass {
13
- render(props: any, context?: ComponentContext): Element;
14
- }
15
- interface ElementAttributesProperty {
16
- data: {};
17
- }
18
- interface ElementChildrenAttribute {
19
- children: {};
20
- }
21
- interface IntrinsicElements {
22
- [elemName: string]: any;
23
- }
24
- interface IntrinsicAttributes {
25
- key?: string | number;
26
- }
27
- }
28
- export declare function jsx(type: JSXElementType, data: JSXProps): MessageComponent<any>;
29
- export declare function jsxs(type: JSXElementType, props: JSXProps): MessageElement;
30
- export declare function renderJSX(element: MessageComponent<any>, context?: ComponentContext): Promise<SendContent>;
1
+ export * from '@zhin.js/jsx';
package/lib/jsx.js CHANGED
@@ -1,93 +1 @@
1
- export { Fragment } from './component.js';
2
- // JSX 运行时函数 - 支持异步组件
3
- export function jsx(type, data) {
4
- return {
5
- type,
6
- data,
7
- };
8
- }
9
- // JSX Fragment 支持
10
- export function jsxs(type, props) {
11
- return jsx(type, props);
12
- }
13
- // JSX 渲染函数
14
- export async function renderJSX(element, context) {
15
- try {
16
- if (typeof element.type === 'string') {
17
- if (element.type === 'Fragment') {
18
- return await renderChildren(element.data.children, context);
19
- }
20
- // 其他内置组件处理
21
- return await renderChildren(element.data.children, context);
22
- }
23
- else if (typeof element.type === 'function') {
24
- // 函数组件
25
- const component = element.type;
26
- const result = await component(element.data, context || {});
27
- // 如果组件返回 Promise,自动 await
28
- if (result && typeof result === 'object' && 'then' in result) {
29
- return await result;
30
- }
31
- return result;
32
- }
33
- else {
34
- // 类组件或其他类型
35
- const component = element.type;
36
- const result = await component(element.data, context || {});
37
- // 如果组件返回 Promise,自动 await
38
- if (result && typeof result === 'object' && 'then' in result) {
39
- return await result;
40
- }
41
- return result;
42
- }
43
- }
44
- catch (error) {
45
- // 渲染错误时返回错误信息
46
- const errorMessage = error instanceof Error ? error.message : String(error);
47
- return `❌ 组件渲染失败: ${errorMessage}`;
48
- }
49
- }
50
- // 渲染子元素
51
- async function renderChildren(children, context) {
52
- if (children == null)
53
- return '';
54
- if (typeof children === 'string' || typeof children === 'number' || typeof children === 'boolean') {
55
- return String(children);
56
- }
57
- if (Array.isArray(children)) {
58
- const results = await Promise.all(children.map(async (child) => {
59
- if (typeof child === 'string' || typeof child === 'number' || typeof child === 'boolean') {
60
- return String(child);
61
- }
62
- if (child && typeof child === 'object' && 'type' in child) {
63
- return await renderJSX(child, context);
64
- }
65
- // 如果子元素是 Promise,自动 await
66
- if (child && typeof child === 'object' && 'then' in child) {
67
- try {
68
- return await child;
69
- }
70
- catch (error) {
71
- const errorMessage = error instanceof Error ? error.message : String(error);
72
- return `❌ 组件渲染失败: ${errorMessage}`;
73
- }
74
- }
75
- return '';
76
- }));
77
- return results.join('');
78
- }
79
- if (children && typeof children === 'object' && 'type' in children) {
80
- return await renderJSX(children, context);
81
- }
82
- // 如果子元素是 Promise,自动 await
83
- if (children && typeof children === 'object' && 'then' in children) {
84
- try {
85
- return await children;
86
- }
87
- catch (error) {
88
- const errorMessage = error instanceof Error ? error.message : String(error);
89
- return `❌ 组件渲染失败: ${errorMessage}`;
90
- }
91
- }
92
- return '';
93
- }
1
+ export * from '@zhin.js/jsx';
package/lib/message.d.ts CHANGED
@@ -1,14 +1,3 @@
1
- import type { SendContent } from "./types.js";
2
- import { Component } from "./component.js";
3
- /**
4
- * 消息组件类型:用于自定义消息结构
5
- */
6
- export type MessageComponent<T extends object> = {
7
- type: Component<T & {
8
- children?: SendContent | Promise<SendContent>;
9
- }>;
10
- data: T;
11
- };
12
1
  /**
13
2
  * 消息频道信息
14
3
  */
@@ -1,4 +1,6 @@
1
- import type { PluginId } from '@zhin.js/plugin-runtime';
1
+ import type { JSXElement } from '@zhin.js/jsx';
2
+ import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
3
+ import { operationInputBinding } from '@zhin.js/feature-kit';
2
4
  import type { ConversationRef, DeliveryReceipt, MessageRef } from '@zhin.js/im-contract';
3
5
  import type { MediaRef, Segment } from '../../built/segment-contract/types.js';
4
6
  export type { MediaRef, Segment };
@@ -15,13 +17,13 @@ export interface RawContent<TPayload = unknown> {
15
17
  }
16
18
  /**
17
19
  * 出站内容:纯文本 / canonical Segment(一等公民,媒体与富文本的统一表达)/
18
- * ComponentCall / RawContent,可任意嵌套数组。
20
+ * 惰性 JSXElement / ComponentCall / RawContent,可任意嵌套数组。
19
21
  */
20
- export type SendContent = string | Segment | ComponentCall | RawContent | readonly SendContent[];
22
+ export type SendContent = string | Segment | JSXElement | ComponentCall | RawContent | readonly SendContent[];
21
23
  export declare function component<TProps>(name: string, props: TProps): ComponentCall<TProps>;
22
24
  export declare function raw<TPayload>(payload: TPayload): RawContent<TPayload>;
23
- export declare function isComponentCall(value: SendContent): value is ComponentCall;
24
- export declare function isRawContent(value: SendContent): value is RawContent;
25
+ export declare function isComponentCall(value: unknown): value is ComponentCall;
26
+ export declare function isRawContent(value: unknown): value is RawContent;
25
27
  /** canonical Segment 一等公民判定(与 ComponentCall/RawContent 的 $content brand 互斥)。 */
26
28
  export declare function isSegmentContent(value: unknown): value is Segment;
27
29
  export interface MessageSenderRef {
@@ -153,7 +155,13 @@ export declare class RuntimeMessage implements MessageBase {
153
155
  /** 结构化入站消息身份(平台原生 message id 经 MessageRef 传递)。 */
154
156
  message?: MessageRef | undefined, endpointId?: string | undefined, mentioned?: boolean | undefined, replyTo?: {
155
157
  readonly id: string;
156
- } | undefined, client?: () => unknown, clientAdapter?: string | undefined);
158
+ } | undefined, client?: () => unknown, clientAdapter?: string | undefined, binding?: Readonly<{
159
+ requester?: PluginId;
160
+ snapshot?: RuntimeSnapshot;
161
+ assertActive?: () => void;
162
+ }>);
163
+ /** @internal A frozen view whose sends retain the current author's exact operation. */
164
+ [operationInputBinding](owner: PluginId, snapshot: RuntimeSnapshot): RuntimeMessage;
157
165
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
158
166
  get id(): string | undefined;
159
167
  readonly $reply: (content: SendContent) => Promise<DeliveryReceipt>;
@@ -1,3 +1,4 @@
1
+ import { operationInputBinding } from '@zhin.js/feature-kit';
1
2
  const componentCallBrand = 'zhin.component-call/1';
2
3
  const rawContentBrand = 'zhin.raw-content/1';
3
4
  export function component(name, props) {
@@ -46,6 +47,10 @@ export class RuntimeMessage {
46
47
  replyTo;
47
48
  clientAdapter;
48
49
  #resolveClient;
50
+ #reply;
51
+ #author;
52
+ #snapshot;
53
+ #assertActive;
49
54
  /** @internal Constructed only by the generation-owned IM Runtime. */
50
55
  constructor(conversation, content, generation, reply, sender, metadata = Object.freeze({}),
51
56
  /**
@@ -56,7 +61,7 @@ export class RuntimeMessage {
56
61
  /** 结构化入站消息身份(平台原生 message id 经 MessageRef 传递)。 */
57
62
  message, endpointId, mentioned, replyTo, client = () => {
58
63
  throw new Error('Message has no Endpoint Client context');
59
- }, clientAdapter) {
64
+ }, clientAdapter, binding = {}) {
60
65
  this.conversation = conversation;
61
66
  this.content = content;
62
67
  this.generation = generation;
@@ -69,9 +74,14 @@ export class RuntimeMessage {
69
74
  this.replyTo = replyTo;
70
75
  this.clientAdapter = clientAdapter;
71
76
  this.#resolveClient = client;
72
- this.$reply = (content) => reply(content);
77
+ this.#reply = reply;
78
+ this.#author = binding.requester;
79
+ this.#snapshot = binding.snapshot;
80
+ this.#assertActive = binding.assertActive;
81
+ const requester = binding.requester;
82
+ this.$reply = (content) => requester === undefined ? reply(content) : reply(content, requester);
73
83
  this.$replyFrom = (requester, content) => reply(content, requester);
74
- this.$sendTo = (target, content) => reply(content, undefined, target);
84
+ this.$sendTo = (target, content) => reply(content, requester, target);
75
85
  this.$replyToPrivate = (content, from) => {
76
86
  if (!sender)
77
87
  throw new Error('Cannot $replyToPrivate: message has no sender');
@@ -85,17 +95,17 @@ export class RuntimeMessage {
85
95
  else if (from != null && typeof from === 'object') {
86
96
  parent = from;
87
97
  }
88
- return reply(content, undefined, {
98
+ return reply(content, requester, {
89
99
  kind: 'private',
90
100
  id: sender.id,
91
101
  ...(parent ? { parent } : {}),
92
102
  });
93
103
  };
94
104
  this.$replyToGroup = (groupId, content) => {
95
- return reply(content, undefined, { kind: 'group', id: groupId });
105
+ return reply(content, requester, { kind: 'group', id: groupId });
96
106
  };
97
107
  this.$replyToChannel = (channelId, guildId, content, threadId) => {
98
- return reply(content, undefined, {
108
+ return reply(content, requester, {
99
109
  kind: 'channel',
100
110
  id: channelId,
101
111
  parent: { kind: 'channel', id: guildId },
@@ -104,6 +114,18 @@ export class RuntimeMessage {
104
114
  };
105
115
  Object.freeze(this);
106
116
  }
117
+ /** @internal A frozen view whose sends retain the current author's exact operation. */
118
+ [operationInputBinding](owner, snapshot) {
119
+ this.#assertActive?.();
120
+ if (snapshot.generation !== this.generation || (this.#snapshot && snapshot !== this.#snapshot)) {
121
+ throw new Error('Message author binding belongs to another generation operation');
122
+ }
123
+ if (!snapshot.tree.has(owner))
124
+ throw new Error(`Unknown Message author: ${owner}`);
125
+ if (this.#author === owner && this.#snapshot === snapshot)
126
+ return this;
127
+ return new RuntimeMessage(this.conversation, this.content, this.generation, this.#reply, this.sender, this.metadata, this.segments, this.message, this.endpointId, this.mentioned, this.replyTo, this.#resolveClient, this.clientAdapter, { requester: owner, snapshot, assertActive: this.#assertActive });
128
+ }
107
129
  /** 平台原生消息 id(`message` 未提供时为 undefined)。 */
108
130
  get id() {
109
131
  return this.message?.id;