@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
@@ -1,3 +1,4 @@
1
+ import { isMiddlewareIndex, middlewareFeatureId } from '@zhin.js/middleware';
1
2
  import { isHandlerIndex, handlerFeatureId } from '../../feature/handler.js';
2
3
  import { formatCompact, getLogger, truncatePreview } from '@zhin.js/logger';
3
4
  import { RuntimeNotice } from '../../notice.js';
@@ -8,7 +9,6 @@ import { defaultCommandPrefixResolver, MessageDispatcher } from './message-dispa
8
9
  import { requireAdapters } from './endpoint-runtime.js';
9
10
  import { formatConversationLog, previewMessageContent, } from './message-events.js';
10
11
  import { resolveIngressRoute } from './ingress-route.js';
11
- import { runRuntimeMiddleware } from './runtime-middleware.js';
12
12
  const logger = getLogger('im.inbound');
13
13
  /** Owns Endpoint ingress normalization, routing, dispatch, and side-event action scopes. */
14
14
  export class InboundRuntime {
@@ -78,7 +78,10 @@ export class InboundRuntime {
78
78
  if (!active)
79
79
  throw new Error('Message Client scope has ended');
80
80
  return source.client;
81
- }, source.endpoint.adapter);
81
+ }, source.endpoint.adapter, { snapshot: lease.value, assertActive: () => {
82
+ if (!active)
83
+ throw new Error('Message author binding scope has ended');
84
+ } });
82
85
  const conversationSequence = await this.context.recordIncoming(input, enrichedSender);
83
86
  let result = Object.freeze({ matched: false });
84
87
  const claimed = await this.context.inboundClaim?.(message) === true;
@@ -90,18 +93,18 @@ export class InboundRuntime {
90
93
  }
91
94
  else {
92
95
  const interactionFactory = (value) => this.context.interactions.createFromUnknown(value);
93
- await runRuntimeMiddleware(lease.value, message, async () => {
96
+ const terminal = async () => {
94
97
  const ingressRoute = resolveIngressRoute(lease.value);
95
98
  const preRouted = await ingressRoute?.preRoute?.(message, lease, requester, conversationSequence) === true;
96
99
  if (preRouted) {
97
100
  result = Object.freeze({ matched: true, command: 'pre-route', owner: requester });
98
- return;
101
+ return { dispatch: result };
99
102
  }
100
103
  if (ingressRoute?.shouldRouteBeforeDispatch?.(message) === true) {
101
104
  const handled = await ingressRoute.route(message, lease, requester, conversationSequence);
102
105
  if (handled) {
103
106
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
104
- return;
107
+ return { dispatch: result };
105
108
  }
106
109
  }
107
110
  await this.#runHandlers(lease.value, 'message.receive', [
@@ -119,7 +122,28 @@ export class InboundRuntime {
119
122
  result = Object.freeze({ matched: true, command: 'ai', owner: requester });
120
123
  }
121
124
  }
122
- }, 'inbound');
125
+ return {
126
+ dispatch: result,
127
+ ...(result.value !== undefined && result.owner
128
+ ? { reply: { owner: result.owner, content: result.value } }
129
+ : {}),
130
+ };
131
+ };
132
+ const middleware = lease.value.projections.get(middlewareFeatureId);
133
+ const outcome = isMiddlewareIndex(middleware)
134
+ ? await middleware.runInbound(message, terminal, {
135
+ stop: (owner) => ({ dispatch: { matched: true, command: 'middleware', owner } }),
136
+ replace: (owner, value, downstream) => ({
137
+ dispatch: downstream?.dispatch.matched
138
+ ? downstream.dispatch
139
+ : { matched: true, command: 'middleware', owner },
140
+ reply: { owner, content: value },
141
+ }),
142
+ }, lease.value)
143
+ : await terminal();
144
+ result = outcome.dispatch;
145
+ if (outcome.reply)
146
+ await message.$replyFrom(outcome.reply.owner, outcome.reply.content);
123
147
  }
124
148
  if (result.matched) {
125
149
  logger.debug(formatCompact({
@@ -68,7 +68,6 @@ export class MessageDispatcher {
68
68
  command: result.command,
69
69
  owner: result.owner,
70
70
  }));
71
- await message.$replyFrom(result.owner, result.value);
72
71
  }
73
72
  else if (!result.matched) {
74
73
  logger.debug(formatCompact({
@@ -1,11 +1,13 @@
1
1
  import { htmlRendererToken, } from '@zhin.js/plugin-runtime';
2
2
  import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
3
  import { formatCompact, getLogger } from '@zhin.js/logger';
4
- import { createOutboundEnvelope } from './contracts.js';
4
+ import { isJsxElement } from '@zhin.js/jsx';
5
+ import { createOutboundEnvelope, isComponentCall, isRawContent } from './contracts.js';
5
6
  import { OutboundRenderer } from './outbound-renderer.js';
6
- import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
7
+ import { applyOutboundInteractivePolicy, applyOutboundMarkdownPolicy, normalizeOutboundPayload, resolveOutboundInteractivePolicy, resolveOutboundMarkdownPolicy, resolveOutboundMediaPolicy, resolveOutboundHtmlPolicy, resolveOutboundSupportedSegments, } from './outbound-segments.js';
7
8
  import { assertCanonicalSegments } from '../../built/segment-contract/assert.js';
8
- import { adapterTypeName, requireAdapters } from './endpoint-runtime.js';
9
+ import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
10
+ import { requireAdapters } from './endpoint-runtime.js';
9
11
  import { formatConversationLog, previewMessageContent } from './message-events.js';
10
12
  import { runRuntimeMiddleware } from './runtime-middleware.js';
11
13
  const logger = getLogger('im.outbound');
@@ -19,9 +21,10 @@ export class OutboundDeliveryRuntime {
19
21
  }
20
22
  async deliver(request, snapshot) {
21
23
  const adapter = request.conversation.endpoint.id;
24
+ const jsxCache = new WeakMap();
22
25
  let initialPayload;
23
26
  try {
24
- const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming);
27
+ const rendered = await this.#renderer.render(request.content, request.requester, snapshot, request.conversation, request.incoming, { jsxCache });
25
28
  initialPayload = await prepareOutboundPayload(rendered, request.conversation, snapshot);
26
29
  }
27
30
  catch (error) {
@@ -49,13 +52,22 @@ export class OutboundDeliveryRuntime {
49
52
  terminalEntered = true;
50
53
  let payload;
51
54
  try {
52
- payload = await prepareOutboundPayload(envelope.payload, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
55
+ // Native payload replacements remain possible; only authoring values need evaluation.
56
+ const replacement = envelope.payload;
57
+ const replaced = replacement !== initialPayload && needsAuthoringRender(replacement)
58
+ ? await this.#renderer.render(replacement, request.requester, snapshot, request.conversation, request.incoming, { jsxCache })
59
+ : replacement;
60
+ payload = await prepareOutboundPayload(replaced, request.conversation, snapshot, (map) => this.context.rememberFallback(request.conversation, snapshot.generation, map));
53
61
  }
54
62
  catch (error) {
55
63
  receipt = error instanceof EndpointDeliveryError && error.code === 'unsupported_operation' && error.disposition === 'not_sent'
56
64
  ? receiptFromEndpointError(error, false) : rejectedDeliveryReceipt('outbound_payload_rejected');
57
65
  return;
58
66
  }
67
+ if (isEmptyOutboundPayload(payload)) {
68
+ receipt = suppressedDeliveryReceipt();
69
+ return;
70
+ }
59
71
  try {
60
72
  const result = await requireAdapters(snapshot).send(adapter, {
61
73
  conversation: request.conversation,
@@ -100,6 +112,15 @@ export class OutboundDeliveryRuntime {
100
112
  return receipt ?? failedDeliveryReceipt('outbound_delivery_incomplete');
101
113
  }
102
114
  }
115
+ function isEmptyOutboundPayload(payload) {
116
+ if (payload === '')
117
+ return true;
118
+ return Array.isArray(payload) && payload.every(item => item?.type === 'text' && item.data?.text === '');
119
+ }
120
+ function needsAuthoringRender(value) {
121
+ const isAuthoring = (item) => isJsxElement(item) || isComponentCall(item) || isRawContent(item);
122
+ return Array.isArray(value) ? flattenOutboundArray(value).some(isAuthoring) : isAuthoring(value);
123
+ }
103
124
  export function failedDeliveryReceipt(code, retryable = false) {
104
125
  return Object.freeze({
105
126
  status: 'failed',
@@ -112,18 +133,21 @@ export function failedDeliveryReceipt(code, retryable = false) {
112
133
  }
113
134
  async function prepareOutboundPayload(rendered, conversation, snapshot, rememberInteractiveFallback) {
114
135
  const adapter = conversation.endpoint.id;
115
- const directHtml = isDirectHtmlConsumer(snapshot, adapter);
116
- const markdownResolved = applyOutboundMarkdownPolicy(rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
117
- let payload = directHtml
118
- ? markdownResolved
119
- : await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
120
- mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
121
- });
136
+ const markdownResolved = applyOutboundMarkdownPolicy(Array.isArray(rendered) ? flattenOutboundArray(rendered) : rendered, resolveOutboundMarkdownPolicy(adapter, snapshot));
137
+ let payload = await normalizeOutboundPayload(markdownResolved, resolveHtmlRenderer(snapshot), {
138
+ mediaPolicy: resolveOutboundMediaPolicy(adapter, snapshot),
139
+ htmlPolicy: resolveOutboundHtmlPolicy(adapter, snapshot),
140
+ onHtmlFallback: reason => logger.debug(formatCompact({ op: 'html_fallback', reason, generation: snapshot.generation })),
141
+ });
122
142
  if (rememberInteractiveFallback) {
123
143
  payload = applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot), rememberInteractiveFallback);
124
144
  }
125
- if (!directHtml && Array.isArray(payload))
145
+ if (Array.isArray(payload)) {
146
+ // Empty text carries no wire content, including HTML's empty fallback.
147
+ // Remove it before canonical validation (required strings reject '').
148
+ payload = payload.filter(item => !(item?.type === 'text' && item.data?.text === ''));
126
149
  assertCanonicalSegments(payload);
150
+ }
127
151
  const supported = resolveOutboundSupportedSegments(adapter, snapshot);
128
152
  const supportedPayload = rememberInteractiveFallback ? payload : applyOutboundInteractivePolicy(payload, resolveOutboundInteractivePolicy(adapter, snapshot));
129
153
  if (supported && Array.isArray(supportedPayload)) {
@@ -139,11 +163,6 @@ function resolveHtmlRenderer(snapshot) {
139
163
  ? host
140
164
  : undefined;
141
165
  }
142
- function isDirectHtmlConsumer(snapshot, adapter) {
143
- const owner = snapshot.capabilities.get(adapter)?.owner;
144
- const packageName = owner ? snapshot.tree.get(owner)?.packageName : undefined;
145
- return adapterTypeName(packageName) === 'sandbox';
146
- }
147
166
  function receiptFromEndpointResult(messageId, conversation) {
148
167
  if (typeof messageId !== 'string' || messageId.trim() === '') {
149
168
  return unknownDeliveryReceipt('delivery_unconfirmed');
@@ -1,7 +1,12 @@
1
- import type { PluginId, RuntimeSnapshot } from '@zhin.js/plugin-runtime';
1
+ import { type PluginId, type RuntimeSnapshot } from '@zhin.js/plugin-runtime';
2
2
  import type { ConversationRef } from '@zhin.js/im-contract';
3
+ import { type JSXElement } from '@zhin.js/jsx';
3
4
  import { type IncomingContext, type SendContent } from './contracts.js';
5
+ export interface OutboundRenderOptions {
6
+ readonly jsxCache?: WeakMap<JSXElement, Promise<string>>;
7
+ readonly signal?: AbortSignal;
8
+ }
4
9
  export declare class OutboundRenderer {
5
10
  #private;
6
- render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext): Promise<unknown>;
11
+ render(content: SendContent, requester: PluginId, snapshot: RuntimeSnapshot, conversation?: ConversationRef, incoming?: IncomingContext, options?: OutboundRenderOptions): Promise<unknown>;
7
12
  }
@@ -1,21 +1,46 @@
1
1
  import { componentHostToken } from '@zhin.js/plugin-runtime';
2
+ import { isJsxElement, renderToHtml } from '@zhin.js/jsx';
3
+ import { segment } from '../../utils.js';
4
+ import { flattenOutboundArray, MAX_OUTBOUND_ARRAY_DEPTH } from '../../built/outbound-content-arrays.js';
2
5
  import { componentFeatureId, isComponentIndex, } from '@zhin.js/component';
3
6
  import { isComponentCall, isRawContent, isSegmentContent, } from './contracts.js';
4
7
  const maxComponentDepth = 32;
5
8
  const TEMPLATE_MARKER = '${';
6
9
  export class OutboundRenderer {
7
- async render(content, requester, snapshot, conversation, incoming) {
10
+ async render(content, requester, snapshot, conversation, incoming, options = {}) {
11
+ options.signal?.throwIfAborted();
8
12
  const host = resolveComponentHost(snapshot);
9
13
  const ctx = conversation ? buildTemplateContext(conversation, incoming) : undefined;
10
- return this.#render(content, requester, snapshot, host, ctx, 0);
14
+ const rendered = await this.#render(content, requester, snapshot, host, ctx, 0, options.jsxCache ?? new WeakMap(), options.signal, new Set());
15
+ options.signal?.throwIfAborted();
16
+ return rendered;
11
17
  }
12
- async #render(content, requester, snapshot, host, ctx, depth) {
18
+ async #render(content, requester, snapshot, host, ctx, depth, jsxCache, signal, arrayAncestors) {
19
+ signal?.throwIfAborted();
13
20
  if (depth > maxComponentDepth)
14
21
  throw new Error('Component render depth exceeded 32');
15
22
  if (typeof content === 'string')
16
23
  return compileText(content, host, ctx);
17
24
  if (Array.isArray(content)) {
18
- return Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth)));
25
+ if (arrayAncestors.has(content))
26
+ throw new TypeError('Cyclic SendContent array');
27
+ if (arrayAncestors.size >= MAX_OUTBOUND_ARRAY_DEPTH)
28
+ throw new RangeError('SendContent array depth exceeded 512');
29
+ // Each parallel branch gets its own ancestry; repeated sibling arrays are valid.
30
+ const ancestors = new Set(arrayAncestors).add(content);
31
+ const items = await Promise.all(content.map((item) => this.#render(item, requester, snapshot, host, ctx, depth, jsxCache, signal, ancestors)));
32
+ signal?.throwIfAborted();
33
+ return flattenOutboundArray(items);
34
+ }
35
+ if (isJsxElement(content)) {
36
+ let html = jsxCache.get(content);
37
+ if (!html) {
38
+ html = renderToHtml(content);
39
+ jsxCache.set(content, html);
40
+ }
41
+ const rendered = await html;
42
+ signal?.throwIfAborted();
43
+ return rendered ? segment.html({ html: rendered }) : [];
19
44
  }
20
45
  if (isRawContent(content))
21
46
  return content.payload;
@@ -29,8 +54,8 @@ export class OutboundRenderer {
29
54
  return content;
30
55
  }
31
56
  if (isComponentCall(content)) {
32
- const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot });
33
- return this.#render(rendered, requester, snapshot, host, ctx, depth + 1);
57
+ const rendered = await requireComponents(snapshot).render(requester, content.name, content.props, { snapshot, ...(signal ? { signal } : {}) });
58
+ return this.#render(rendered, requester, snapshot, host, ctx, depth + 1, jsxCache, signal, arrayAncestors);
34
59
  }
35
60
  throw new TypeError('Unsupported SendContent');
36
61
  }
@@ -36,11 +36,16 @@ export interface OutboundSegmentsPolicy {
36
36
  readonly outboundMedia: readonly ('url' | 'path' | 'base64' | 'upload')[];
37
37
  readonly interactive?: InteractivePolicy;
38
38
  readonly markdown?: 'native' | 'text';
39
+ readonly html?: 'direct' | 'image' | 'text';
39
40
  }
40
41
  export interface NormalizeOutboundOptions {
41
42
  /** 缺省 `url-or-text`(未声明 adapter 的保守兜底:仅 URL 媒体可达)。 */
42
43
  readonly mediaPolicy?: OutboundMediaPolicy;
44
+ readonly htmlPolicy?: 'direct' | 'image' | 'text';
45
+ readonly onHtmlFallback?: (reason: 'renderer_unavailable' | 'renderer_failed' | 'media_unsupported') => void;
43
46
  }
47
+ /** HTML transport is an adapter capability, independent of its package name. */
48
+ export declare function resolveOutboundHtmlPolicy(adapter: CapabilityId, snapshot: RuntimeSnapshot): 'direct' | 'image' | 'text';
44
49
  /**
45
50
  * 解析端点的出站媒体策略:读 adapter definition 声明的 `segments.outboundMedia`
46
51
  * (多 endpoint 展开的 `slot~entry` id 回退到 slot id 查声明);
@@ -1,9 +1,16 @@
1
1
  import { htmlToFallbackText } from '../../built/html-to-text.js';
2
+ import { flattenOutboundArray } from '../../built/outbound-content-arrays.js';
2
3
  import { toCanonicalSegments } from '../../built/generic-segment-mapper.js';
3
4
  import { effectiveKeyboardFallbackMap, renderKeyboardAsText, } from '../../built/interactive-segments/resolve.js';
4
5
  import { DEFAULT_INTERACTIVE_POLICY, isKeyboardSegment, } from '../../built/interactive-segments/types.js';
5
6
  import { isMediaRef } from '../../built/segment-contract/index.js';
6
7
  import { markdownToPlainText } from '../../built/rich-segments/markdown-to-text.js';
8
+ /** HTML transport is an adapter capability, independent of its package name. */
9
+ export function resolveOutboundHtmlPolicy(adapter, snapshot) {
10
+ const slot = snapshot.capabilities.get(adapter) ?? snapshot.capabilities.get(baseSlotCapabilityId(adapter));
11
+ const policy = slot?.definition?.segments?.html;
12
+ return policy === 'direct' || policy === 'text' ? policy : 'image';
13
+ }
7
14
  const DEFAULT_CARD_WIDTH = 540;
8
15
  const DEFAULT_CARD_FILENAME = 'card.png';
9
16
  const DEFAULT_MEDIA_POLICY = 'url-or-text';
@@ -142,11 +149,11 @@ function adapterTypeName(packageName) {
142
149
  export async function normalizeOutboundPayload(payload, renderer, options) {
143
150
  const mediaPolicy = options?.mediaPolicy ?? DEFAULT_MEDIA_POLICY;
144
151
  if (Array.isArray(payload)) {
145
- const resolved = await Promise.all(payload.map((item) => normalizeOneSegment(item, renderer, mediaPolicy)));
152
+ const resolved = await Promise.all(flattenOutboundArray(payload).map((item) => normalizeOneSegment(item, renderer, mediaPolicy, options)));
146
153
  return applyOutboundMediaPolicy(resolved, mediaPolicy);
147
154
  }
148
155
  if (isOutboundSegment(payload)) {
149
- return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy)], mediaPolicy);
156
+ return applyOutboundMediaPolicy([await normalizeOneSegment(payload, renderer, mediaPolicy, options)], mediaPolicy);
150
157
  }
151
158
  return payload;
152
159
  }
@@ -157,16 +164,24 @@ export async function normalizeOutboundPayload(payload, renderer, options) {
157
164
  * - 其余项经 `toCanonicalSegments` 归一(字符串→text、at→mention、
158
165
  * 旧 wire 字段 `{url,file,base64}`→MediaRef)。
159
166
  */
160
- async function normalizeOneSegment(item, renderer, mediaPolicy) {
167
+ async function normalizeOneSegment(item, renderer, mediaPolicy, options) {
161
168
  if (isOutboundSegment(item) && item.type === 'html') {
162
- return renderHtmlSegment(item, renderer, mediaPolicy);
169
+ if (item.data?.html === '') {
170
+ return { type: 'text', data: { text: htmlSegmentFallbackText(item.data, '') } };
171
+ }
172
+ if (options?.htmlPolicy === 'direct')
173
+ return toCanonicalSegments([item])[0];
174
+ return renderHtmlSegment(item, renderer, mediaPolicy, options);
163
175
  }
164
176
  return toCanonicalSegments([item])[0];
165
177
  }
166
- async function renderHtmlSegment(segment, renderer, mediaPolicy) {
178
+ async function renderHtmlSegment(segment, renderer, mediaPolicy, options) {
167
179
  const data = segment.data ?? {};
168
180
  const html = typeof data.html === 'string' ? data.html : '';
169
181
  // url-or-text 端点无法投递 base64 图片(本层无上传通道),直接文本降级,跳过渲染。
182
+ if (options?.htmlPolicy === 'text') {
183
+ return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
184
+ }
170
185
  if (html && renderer && mediaPolicy !== 'url-or-text') {
171
186
  try {
172
187
  const result = await renderer.render(html, {
@@ -190,11 +205,15 @@ async function renderHtmlSegment(segment, renderer, mediaPolicy) {
190
205
  },
191
206
  };
192
207
  }
208
+ options?.onHtmlFallback?.('renderer_failed');
193
209
  }
194
210
  catch {
195
- // 渲染失败 → 文本降级
211
+ options?.onHtmlFallback?.('renderer_failed');
196
212
  }
197
213
  }
214
+ else if (html) {
215
+ options?.onHtmlFallback?.(mediaPolicy === 'url-or-text' ? 'media_unsupported' : 'renderer_unavailable');
216
+ }
198
217
  return { type: 'text', data: { text: htmlSegmentFallbackText(data, html) } };
199
218
  }
200
219
  /**
package/lib/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { MessageChannel, MessageComponent } from './message.js';
1
+ import type { MessageChannel } from './message.js';
2
2
  import type { Message } from './plugin-runtime/im/contracts.js';
3
3
  import { SystemLog } from './models/system-log.js';
4
4
  import { User } from './models/user.js';
@@ -16,11 +16,8 @@ export type ObjectItem<T extends object> = T[keyof T];
16
16
  /**
17
17
  * 消息段结构,支持 text/image/at/face 等类型
18
18
  */
19
- export interface MessageSegment {
20
- type: string;
21
- data: Record<string, any>;
22
- }
23
- export type MessageElement = MessageSegment | MessageComponent<any>;
19
+ export type { Segment as MessageSegment } from './built/segment-contract/types.js';
20
+ export type MessageElement = import('./built/segment-contract/types.js').Segment;
24
21
  /**
25
22
  * 单个或数组类型
26
23
  */
@@ -28,7 +25,8 @@ export type MaybeArray<T> = T | T[];
28
25
  /**
29
26
  * 消息发送内容类型
30
27
  */
31
- export type SendContent = MaybeArray<string | MessageElement>;
28
+ export type { SendContent } from './plugin-runtime/im/contracts.js';
29
+ import type { SendContent } from './plugin-runtime/im/contracts.js';
32
30
  /** 可选:编辑已发送消息(交互式棋盘更新) */
33
31
  export interface EditMessageOptions {
34
32
  messageId: string;
package/lib/utils.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * IM-specific utilities (compose, segment) remain here.
6
6
  */
7
7
  export { evaluate, execute, getValueWithRuntime, compiler, remove, isEmpty, Time, supportedPluginExtensions, resolveEntry, sleep, } from '@zhin.js/kernel';
8
- import { MessageMiddleware, SendContent } from "./types.js";
8
+ import { MessageElement, MessageMiddleware } from "./types.js";
9
9
  import type { Message } from "./plugin-runtime/im/contracts.js";
10
10
  import { KeyboardSegment } from "./built/interactive-segments/keyboard-segment.js";
11
11
  import { ButtonSpec, type KeyboardRowInput } from "./built/interactive-segments/button-spec.js";
@@ -126,7 +126,7 @@ export declare namespace segment {
126
126
  function keyboard(rows: KeyboardRowInput[], options?: {
127
127
  fallback?: KeyboardFallback;
128
128
  }): KeyboardSegment;
129
- function from(content: SendContent): SendContent;
130
- function raw(content: SendContent): string;
131
- function toString(content: SendContent): string;
129
+ function from(content: string | MessageElement | readonly (string | MessageElement)[]): MessageElement[];
130
+ function raw(content: string | MessageElement | readonly (string | MessageElement)[]): string;
131
+ function toString(content: string | MessageElement | readonly (string | MessageElement)[]): string;
132
132
  }
package/lib/utils.js CHANGED
@@ -125,12 +125,11 @@ export function segment(type, data) {
125
125
  }
126
126
  segment.keyboard = keyboard;
127
127
  function from(content) {
128
- if (!Array.isArray(content))
129
- content = [content];
128
+ const items = Array.isArray(content) ? content : [content];
130
129
  const toString = (template) => {
131
130
  if (typeof template !== "string")
132
131
  return [template];
133
- /** ReDoS 防护:仅约束 segment.from 的字符串模板解析,不是附件大小上限;MessageElement[] 出站应走 renderComponents 快路径避免往返 */
132
+ /** ReDoS 防护:仅约束 segment.from 的字符串模板解析,不是附件大小上限;结构化段出站直接走统一渲染链路,避免文本往返 */
134
133
  const MAX_TEMPLATE_LENGTH = 400000;
135
134
  if (template.length > MAX_TEMPLATE_LENGTH) {
136
135
  throw new Error(`Template too large: ${template.length} > ${MAX_TEMPLATE_LENGTH}`);
@@ -214,39 +213,32 @@ export function segment(type, data) {
214
213
  }
215
214
  return result;
216
215
  };
217
- return content.reduce((result, item) => {
216
+ return items.reduce((result, item) => {
218
217
  result.push(...toString(item));
219
218
  return result;
220
219
  }, []);
221
220
  }
222
221
  segment.from = from;
223
222
  function raw(content) {
224
- if (!Array.isArray(content))
225
- content = [content];
226
- return content
223
+ const items = Array.isArray(content) ? content : [content];
224
+ return items
227
225
  .map((item) => {
228
226
  if (typeof item === "string")
229
227
  return item;
230
228
  const { type, data } = item;
231
- if (typeof type === "function") {
232
- return `{${type.name || "Component"}}`;
233
- }
234
229
  return formatSegmentPreview({ type, data: data ?? {} });
235
230
  })
236
231
  .join("");
237
232
  }
238
233
  segment.raw = raw;
239
234
  function toString(content) {
240
- if (!Array.isArray(content))
241
- content = [content];
242
- return content
235
+ const items = Array.isArray(content) ? content : [content];
236
+ return items
243
237
  .map((item) => {
244
238
  if (typeof item === "string")
245
239
  return item;
246
- let { type } = item;
247
- const { data } = item;
248
- if (typeof type === "function")
249
- type = type.name;
240
+ const { type } = item;
241
+ const data = item.data;
250
242
  if (type === "text")
251
243
  return data.text;
252
244
  const keys = Object.keys(data).filter((key) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhin.js/core",
3
- "version": "1.1.40",
3
+ "version": "1.1.41",
4
4
  "description": "Zhin机器人核心框架",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -68,27 +68,29 @@
68
68
  "dependencies": {
69
69
  "qrcode": "^1.5.4",
70
70
  "segment-matcher": "^1.0.5",
71
- "@zhin.js/adapter": "1.1.16",
72
- "@zhin.js/command": "1.1.4",
73
- "@zhin.js/component": "1.1.3",
71
+ "@zhin.js/adapter": "1.1.17",
72
+ "@zhin.js/command": "1.1.5",
73
+ "@zhin.js/component": "1.1.4",
74
74
  "@zhin.js/database": "1.1.2",
75
- "@zhin.js/handler": "1.1.2",
75
+ "@zhin.js/handler": "1.1.3",
76
76
  "@zhin.js/im-contract": "1.1.3",
77
77
  "@zhin.js/interaction": "1.1.0",
78
78
  "@zhin.js/kernel": "1.1.2",
79
79
  "@zhin.js/logger": "1.1.1",
80
- "@zhin.js/middleware": "1.1.3",
81
- "@zhin.js/permission": "1.1.3",
82
- "@zhin.js/plugin-runtime": "1.1.11",
83
- "@zhin.js/schedule-feature": "1.1.2",
84
- "@zhin.js/schema": "1.1.1"
80
+ "@zhin.js/middleware": "1.1.4",
81
+ "@zhin.js/permission": "1.1.4",
82
+ "@zhin.js/plugin-runtime": "1.1.12",
83
+ "@zhin.js/schedule-feature": "1.1.3",
84
+ "@zhin.js/schema": "1.1.1",
85
+ "@zhin.js/jsx": "1.1.1",
86
+ "@zhin.js/feature-kit": "1.1.3"
85
87
  },
86
88
  "devDependencies": {
87
89
  "@types/node": "^26.1.2",
88
90
  "@types/qrcode": "^1.5.6",
89
91
  "ajv": "8.18.0",
90
92
  "typescript": "^6.0.3",
91
- "@zhin.js/ai": "1.1.36"
93
+ "@zhin.js/ai": "1.1.37"
92
94
  },
93
95
  "repository": {
94
96
  "type": "git",
@@ -143,7 +145,7 @@
143
145
  "plugins": []
144
146
  },
145
147
  "scripts": {
146
- "build": "tsc",
148
+ "build": "rimraf lib && tsc",
147
149
  "clean": "rimraf lib"
148
150
  }
149
151
  }
@@ -1,26 +0,0 @@
1
- import { Dict, SendContent, SendOptions } from './types.js';
2
- export declare const CapWithChild: unique symbol;
3
- export declare const CapWithClose: unique symbol;
4
- export type Component<P = any> = {
5
- (props: P, context: ComponentContext): SendContent | Promise<SendContent>;
6
- name: string;
7
- };
8
- export interface ComponentContext {
9
- render: (template: string, context?: Partial<ComponentContext>) => Promise<SendContent>;
10
- props: Readonly<Dict>;
11
- parent?: Readonly<ComponentContext>;
12
- root: string;
13
- children?: string;
14
- getValue: (template: string) => any;
15
- compile: (template: string) => string;
16
- }
17
- export declare function defineComponent<P = any>(component: Component<P>, name?: string): Component<P>;
18
- export declare function matchComponent<P = any>(comp: Component<P>, template: string): string;
19
- export declare function getProps<P = any>(comp: Component<P>, template: string, context?: ComponentContext): P;
20
- export declare function createComponentContext(props?: Dict, parent?: ComponentContext, root?: string): ComponentContext;
21
- export declare function renderComponent<P = any>(component: Component<P>, template: string, context: ComponentContext): Promise<SendContent>;
22
- export declare function renderComponents(componentMap: Map<string, Component>, options: SendOptions, customContext?: ComponentContext): Promise<SendOptions>;
23
- export declare const Fragment: Component<{
24
- children?: SendContent;
25
- }>;
26
- export declare const Fetch: Component<any>;