@lark-base-open/base-site-channel 0.1.5 → 0.1.6
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.
- package/README.md +25 -0
- package/dist/capabilities.d.ts +12 -0
- package/dist/capabilities.js +1 -0
- package/dist/capabilities.mjs +1 -0
- package/dist/runtime-contract.d.ts +25 -5
- package/dist/runtime-contract.mjs +1 -1
- package/dist/runtime.d.ts +11 -9
- package/dist/runtime.mjs +4 -4
- package/package.json +6 -1
package/README.md
CHANGED
|
@@ -797,3 +797,28 @@ stopListenThemeChange();
|
|
|
797
797
|
- Keep `instanceId` unique for each iframe instance.
|
|
798
798
|
- Call `destroy` when the Host page unmounts, navigates away, or remounts.
|
|
799
799
|
- Start business calls only after the iframe is ready.
|
|
800
|
+
|
|
801
|
+
## AI Function 统一调用
|
|
802
|
+
|
|
803
|
+
`@lark-base-open/base-site-channel/runtime` 的 `callSiteAIFunction` 使用
|
|
804
|
+
`/space/api/bitable/site/v1/:token/functions/:key/invoke`。普通文本调用等待服务端聚合结果;
|
|
805
|
+
媒体受理的 HTTP 202 返回 `image_task` / `video_task`,用 `getSiteAIFunctionTask` 查询原任务。
|
|
806
|
+
SDK 将 HTTP `task_id` 映射为 `taskId`,查询成功不表示任务已成功。
|
|
807
|
+
|
|
808
|
+
```ts
|
|
809
|
+
const result = await callSiteAIFunction(
|
|
810
|
+
{
|
|
811
|
+
functionKey: 'recommend',
|
|
812
|
+
params: { menu: '美式、拿铁' },
|
|
813
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: '推荐一杯咖啡' }] }],
|
|
814
|
+
},
|
|
815
|
+
{ siteToken, env: 'preview', signal: controller.signal },
|
|
816
|
+
);
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
主字段使用 `params`;弃用的 `variables` 仅作 SDK 输入别名,两者互斥,网络请求与 iframe
|
|
820
|
+
stream open 均只发送 `params`。显式 `invokeSiteAIFunctionStream` 保留流式回调和
|
|
821
|
+
`handle.destroy()` 取消;direct 模式使用 streaming 前缀下的 `functions/:key/invoke`,
|
|
822
|
+
iframe 模式由宿主 broker 转发。宿主需要支持新的 HTTP 白名单与 `params` 协议。
|
|
823
|
+
普通 invoke / task 请求可用 `options.signal` 取消,不自动重发。错误保留 `code`,
|
|
824
|
+
Schema 诊断见 `issues`,HTTP 业务错误的完整诊断见 `details`。
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
declare const CAPABILITY_CATALOG: Readonly<Record<string, {
|
|
2
|
+
readonly required: readonly string[];
|
|
3
|
+
readonly baseline: boolean;
|
|
4
|
+
}>>;
|
|
5
|
+
declare const buildSiteCapabilities: (registered: ReadonlySet<string>) => {
|
|
6
|
+
[k: string]: {
|
|
7
|
+
version: number;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
declare const capabilityNames: (key: string, params: any) => string[];
|
|
11
|
+
|
|
12
|
+
export { CAPABILITY_CATALOG, buildSiteCapabilities, capabilityNames };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var l=(n,t)=>{for(var i in t)c(n,i,{get:t[i],enumerable:!0})},S=(n,t,i,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of m(t))!d.call(n,r)&&r!==i&&c(n,r,{get:()=>t[r],enumerable:!(o=p(t,r))||o.enumerable});return n};var A=n=>S(c({},"__esModule",{value:!0}),n);var f={};l(f,{CAPABILITY_CATALOG:()=>u,buildSiteCapabilities:()=>I,capabilityNames:()=>T});module.exports=A(f);var e={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},a={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},s={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"};var g={"runtime.context":[e.RuntimeContext],"http.request":[e.HttpRequest],"http.binary":[e.HttpRequest],"http.cancel":[e.HttpRequestCancel],"function.invoke":[e.FunctionInvoke],"runtime.user":[e.FunctionInvoke,"function.runtime.getCurrentUser"],"runtime.logout":[e.FunctionInvoke,"function.runtime.logout"],"runtime.requestEdit":[e.FunctionInvoke,"function.runtime.requestEdit"],"attachment.upload":[e.AttachmentUpload],"attachment.cancel":[e.AttachmentUploadCancel],"chatbot.stream":[e.StreamOpen,e.StreamClose,a.StreamMessage,a.StreamError],"ai.function.stream":["site.v1.ai.function.stream.open","site.v1.ai.function.stream.close","site.v1.ai.function.stream.message","site.v1.ai.function.stream.error","site.v1.ai.function.stream.done"],"runtime.lifecycle":[a.LifecycleReady,a.LifecycleLoadFailed],"runtime.mode":[a.ModeChanged],"attachment.progress":[e.AttachmentUpload,a.AttachmentUploadProgress],"link.open":[e.OpenLink]},u=Object.fromEntries(Object.entries(g).map(([n,t])=>[n,{required:t,baseline:!0}])),I=n=>Object.fromEntries(Object.entries(u).filter(([,t])=>t.required.every(i=>n.has(i))).map(([t])=>[t,{version:1}])),T=(n,t)=>{var i,o,r;return n===e.RuntimeContext?[]:n===e.HttpRequest?["http.request",...((i=t==null?void 0:t.init)==null?void 0:i.responseType)==="arrayBuffer"?["http.binary"]:[]]:n===e.FunctionInvoke?["function.invoke",...(o={[s.GetCurrentUser]:["runtime.user"],[s.Logout]:["runtime.logout"],[s.RequestEdit]:["runtime.requestEdit"]}[t==null?void 0:t.functionName])!=null?o:[]]:(r={[e.HttpRequestCancel]:["http.cancel"],[e.AttachmentUpload]:["attachment.upload"],[e.AttachmentUploadCancel]:["attachment.cancel"],[e.OpenLink]:["link.open"],[e.StreamOpen]:["chatbot.stream"],[e.StreamClose]:["chatbot.stream"],"site.v1.ai.function.stream.open":["ai.function.stream"],"site.v1.ai.function.stream.close":["ai.function.stream"],"site.v1.lifecycle.ready":["runtime.lifecycle"],"site.v1.lifecycle.load-failed":["runtime.lifecycle"]}[n])!=null?r:[]};0&&(module.exports={CAPABILITY_CATALOG,buildSiteCapabilities,capabilityNames});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},i={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},a={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"};var c={"runtime.context":[e.RuntimeContext],"http.request":[e.HttpRequest],"http.binary":[e.HttpRequest],"http.cancel":[e.HttpRequestCancel],"function.invoke":[e.FunctionInvoke],"runtime.user":[e.FunctionInvoke,"function.runtime.getCurrentUser"],"runtime.logout":[e.FunctionInvoke,"function.runtime.logout"],"runtime.requestEdit":[e.FunctionInvoke,"function.runtime.requestEdit"],"attachment.upload":[e.AttachmentUpload],"attachment.cancel":[e.AttachmentUploadCancel],"chatbot.stream":[e.StreamOpen,e.StreamClose,i.StreamMessage,i.StreamError],"ai.function.stream":["site.v1.ai.function.stream.open","site.v1.ai.function.stream.close","site.v1.ai.function.stream.message","site.v1.ai.function.stream.error","site.v1.ai.function.stream.done"],"runtime.lifecycle":[i.LifecycleReady,i.LifecycleLoadFailed],"runtime.mode":[i.ModeChanged],"attachment.progress":[e.AttachmentUpload,i.AttachmentUploadProgress],"link.open":[e.OpenLink]},u=Object.fromEntries(Object.entries(c).map(([n,t])=>[n,{required:t,baseline:!0}])),d=n=>Object.fromEntries(Object.entries(u).filter(([,t])=>t.required.every(r=>n.has(r))).map(([t])=>[t,{version:1}])),l=(n,t)=>{var r,o,s;return n===e.RuntimeContext?[]:n===e.HttpRequest?["http.request",...((r=t==null?void 0:t.init)==null?void 0:r.responseType)==="arrayBuffer"?["http.binary"]:[]]:n===e.FunctionInvoke?["function.invoke",...(o={[a.GetCurrentUser]:["runtime.user"],[a.Logout]:["runtime.logout"],[a.RequestEdit]:["runtime.requestEdit"]}[t==null?void 0:t.functionName])!=null?o:[]]:(s={[e.HttpRequestCancel]:["http.cancel"],[e.AttachmentUpload]:["attachment.upload"],[e.AttachmentUploadCancel]:["attachment.cancel"],[e.OpenLink]:["link.open"],[e.StreamOpen]:["chatbot.stream"],[e.StreamClose]:["chatbot.stream"],"site.v1.ai.function.stream.open":["ai.function.stream"],"site.v1.ai.function.stream.close":["ai.function.stream"],"site.v1.lifecycle.ready":["runtime.lifecycle"],"site.v1.lifecycle.load-failed":["runtime.lifecycle"]}[n])!=null?s:[]};export{u as CAPABILITY_CATALOG,d as buildSiteCapabilities,l as capabilityNames};
|
|
@@ -247,23 +247,42 @@ interface SiteAITextDelta {
|
|
|
247
247
|
declare const readSiteAITextDelta: (delta: SiteAIStreamDelta) => SiteAITextDelta;
|
|
248
248
|
interface SiteAIFunctionError extends Error {
|
|
249
249
|
code: string;
|
|
250
|
+
issues?: SiteFunctionValidationIssue[];
|
|
251
|
+
details?: unknown;
|
|
252
|
+
retryable?: boolean;
|
|
253
|
+
}
|
|
254
|
+
interface SiteFunctionValidationIssue {
|
|
255
|
+
path: string;
|
|
256
|
+
keyword: string;
|
|
257
|
+
constraint: unknown;
|
|
258
|
+
message: string;
|
|
250
259
|
}
|
|
251
|
-
type
|
|
252
|
-
|
|
260
|
+
type SiteAIFunctionParams = Record<string, unknown>;
|
|
261
|
+
/** @deprecated 使用 SiteAIFunctionParams。 */
|
|
262
|
+
type SiteAIFunctionVariables = SiteAIFunctionParams;
|
|
263
|
+
/** SDK 输入别名;发送前转换为 params,二者不能同时提供。 */
|
|
264
|
+
type SiteAIFunctionArguments = {
|
|
265
|
+
params?: SiteAIFunctionParams;
|
|
266
|
+
variables?: never;
|
|
267
|
+
} | {
|
|
268
|
+
params?: never; /** @deprecated 使用 params。 */
|
|
269
|
+
variables?: SiteAIFunctionVariables;
|
|
270
|
+
};
|
|
271
|
+
type SiteAIFunctionStreamOpenRequest = SiteAIFunctionArguments & {
|
|
253
272
|
env?: SiteProjectEnv;
|
|
254
273
|
functionKey: string;
|
|
255
274
|
messages?: SiteAIStreamMessageParam[];
|
|
256
275
|
requestId?: string;
|
|
257
276
|
siteToken?: string;
|
|
258
277
|
subscriptionId: string;
|
|
259
|
-
|
|
260
|
-
}
|
|
278
|
+
};
|
|
261
279
|
interface SiteAIFunctionStreamCloseRequest {
|
|
262
280
|
subscriptionId: string;
|
|
263
281
|
}
|
|
264
282
|
type SiteAIFunctionStreamMessage = SiteChatbotStreamMessage<SiteAIStreamDelta | string>;
|
|
265
283
|
interface SiteAIFunctionStreamError extends SiteChatbotStreamError {
|
|
266
284
|
message?: string;
|
|
285
|
+
issues?: SiteFunctionValidationIssue[];
|
|
267
286
|
}
|
|
268
287
|
interface SiteAIFunctionStreamDone {
|
|
269
288
|
subscriptionId: string;
|
|
@@ -303,6 +322,7 @@ type SiteAIFunctionResult = {
|
|
|
303
322
|
content: string;
|
|
304
323
|
requestId: string;
|
|
305
324
|
type: 'text';
|
|
325
|
+
firstTokenMs?: number;
|
|
306
326
|
} | {
|
|
307
327
|
assets: SiteAIImageAsset[];
|
|
308
328
|
requestId: string;
|
|
@@ -349,4 +369,4 @@ interface SiteOpenLinkResult {
|
|
|
349
369
|
opened: boolean;
|
|
350
370
|
}
|
|
351
371
|
|
|
352
|
-
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteAIAudioContentPart, SiteAICapabilityType, SiteAIFileContentPart, SiteAIFunctionError, SiteAIFunctionResult, SiteAIFunctionStreamCloseRequest, SiteAIFunctionStreamDone, SiteAIFunctionStreamError, SiteAIFunctionStreamMessage, SiteAIFunctionStreamOpenRequest, SiteAIFunctionVariables, SiteAIImageAsset, SiteAIImageContentPart, SiteAIImageTask, SiteAIMediaTask, SiteAIMediaTaskBase, SiteAIMessageContentPart, SiteAIStreamDelta, SiteAIStreamMessageParam, SiteAITaskStatus, SiteAITextContentPart, SiteAITextDelta, SiteAITextMessageParam, SiteAIUserMessageParam, SiteAIVideoAsset, SiteAIVideoContentPart, SiteAIVideoTask, SiteAttachmentTarget, SiteAttachmentUploadCancelRequest, SiteAttachmentUploadOptions, SiteAttachmentUploadPayload, SiteAttachmentUploadProgress, SiteAttachmentUploadRequest, SiteAttachmentUploadResult, SiteChatbotStreamCloseRequest, SiteChatbotStreamError, SiteChatbotStreamMessage, SiteChatbotStreamOpenRequest, SiteFunctionDefinition, SiteFunctionInvokeRequest, SiteHttpCancelRequest, SiteHttpMethod, SiteHttpRequest, SiteHttpRequestInit, SiteHttpRequestOptions, SiteHttpResponse, SiteHttpResponseType, SiteOpenLinkRequest, SiteOpenLinkResult, SiteProjectEnv, SiteRuntimeApi, SiteRuntimeContext, SiteRuntimeError, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, SiteRuntimeLoadFailedEvent, SiteRuntimeModeChangedEvent, SiteRuntimeReadyEvent, SiteRuntimeUserInfo, isValidSiteFunctionName, readSiteAITextDelta };
|
|
372
|
+
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteAIAudioContentPart, SiteAICapabilityType, SiteAIFileContentPart, SiteAIFunctionArguments, SiteAIFunctionError, SiteAIFunctionParams, SiteAIFunctionResult, SiteAIFunctionStreamCloseRequest, SiteAIFunctionStreamDone, SiteAIFunctionStreamError, SiteAIFunctionStreamMessage, SiteAIFunctionStreamOpenRequest, SiteAIFunctionVariables, SiteAIImageAsset, SiteAIImageContentPart, SiteAIImageTask, SiteAIMediaTask, SiteAIMediaTaskBase, SiteAIMessageContentPart, SiteAIStreamDelta, SiteAIStreamMessageParam, SiteAITaskStatus, SiteAITextContentPart, SiteAITextDelta, SiteAITextMessageParam, SiteAIUserMessageParam, SiteAIVideoAsset, SiteAIVideoContentPart, SiteAIVideoTask, SiteAttachmentTarget, SiteAttachmentUploadCancelRequest, SiteAttachmentUploadOptions, SiteAttachmentUploadPayload, SiteAttachmentUploadProgress, SiteAttachmentUploadRequest, SiteAttachmentUploadResult, SiteChatbotStreamCloseRequest, SiteChatbotStreamError, SiteChatbotStreamMessage, SiteChatbotStreamOpenRequest, SiteFunctionDefinition, SiteFunctionInvokeRequest, SiteFunctionValidationIssue, SiteHttpCancelRequest, SiteHttpMethod, SiteHttpRequest, SiteHttpRequestInit, SiteHttpRequestOptions, SiteHttpResponse, SiteHttpResponseType, SiteOpenLinkRequest, SiteOpenLinkResult, SiteProjectEnv, SiteRuntimeApi, SiteRuntimeContext, SiteRuntimeError, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, SiteRuntimeLoadFailedEvent, SiteRuntimeModeChangedEvent, SiteRuntimeReadyEvent, SiteRuntimeUserInfo, isValidSiteFunctionName, readSiteAITextDelta };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r="site.v1",a={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},s={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},o={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"},p={AttachmentUnavailable:"ATTACHMENT_UNAVAILABLE",AttachmentUploadCanceled:"ATTACHMENT_UPLOAD_CANCELED",AttachmentUploadFailed:"ATTACHMENT_UPLOAD_FAILED",AttachmentUploadStalled:"ATTACHMENT_UPLOAD_STALLED",ChannelDestroyed:"CHANNEL_DESTROYED",FunctionNotAllowed:"FUNCTION_NOT_ALLOWED",FunctionRequestFailed:"FUNCTION_REQUEST_FAILED",InvalidAIFunctionTask:"INVALID_AI_FUNCTION_TASK",HttpRequestFailed:"HTTP_REQUEST_FAILED",HttpResponseTypeUnsupported:"HTTP_RESPONSE_TYPE_UNSUPPORTED",HttpRequestCanceled:"HTTP_REQUEST_CANCELED",InvalidAttachmentTarget:"INVALID_ATTACHMENT_TARGET",InvalidFunctionName:"INVALID_FUNCTION_NAME",InvalidHttpHeader:"INVALID_HTTP_HEADER",InvalidHttpUrl:"INVALID_HTTP_URL",InvalidLinkUrl:"INVALID_LINK_URL",LinkCheckUnavailable:"LINK_CHECK_UNAVAILABLE",LogoutFailed:"LOGOUT_FAILED",ProtocolMismatch:"PROTOCOL_MISMATCH",RequestTimeout:"REQUEST_TIMEOUT",StreamDisconnected:"STREAM_DISCONNECTED",StreamHealthTimeout:"STREAM_HEALTH_TIMEOUT",StreamInterrupted:"STREAM_INTERRUPTED",StreamOpenFailed:"STREAM_OPEN_FAILED",StreamSeqGap:"STREAM_SEQ_GAP",StreamUnavailable:"STREAM_UNAVAILABLE",UnsupportedHttpBody:"UNSUPPORTED_HTTP_BODY",UserInfoUnavailable:"USER_INFO_UNAVAILABLE"},c=e=>{var t,n;return{answer:(t=e.content)!=null?t:"",reasoning:(n=e.reasoningContent)!=null?n:""}},i=/^function(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,
|
|
1
|
+
var r="site.v1",a={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},s={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},o={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"},p={AttachmentUnavailable:"ATTACHMENT_UNAVAILABLE",AttachmentUploadCanceled:"ATTACHMENT_UPLOAD_CANCELED",AttachmentUploadFailed:"ATTACHMENT_UPLOAD_FAILED",AttachmentUploadStalled:"ATTACHMENT_UPLOAD_STALLED",ChannelDestroyed:"CHANNEL_DESTROYED",FunctionNotAllowed:"FUNCTION_NOT_ALLOWED",FunctionRequestFailed:"FUNCTION_REQUEST_FAILED",InvalidAIFunctionTask:"INVALID_AI_FUNCTION_TASK",HttpRequestFailed:"HTTP_REQUEST_FAILED",HttpResponseTypeUnsupported:"HTTP_RESPONSE_TYPE_UNSUPPORTED",HttpRequestCanceled:"HTTP_REQUEST_CANCELED",InvalidAttachmentTarget:"INVALID_ATTACHMENT_TARGET",InvalidFunctionName:"INVALID_FUNCTION_NAME",InvalidHttpHeader:"INVALID_HTTP_HEADER",InvalidHttpUrl:"INVALID_HTTP_URL",InvalidLinkUrl:"INVALID_LINK_URL",LinkCheckUnavailable:"LINK_CHECK_UNAVAILABLE",LogoutFailed:"LOGOUT_FAILED",ProtocolMismatch:"PROTOCOL_MISMATCH",RequestTimeout:"REQUEST_TIMEOUT",StreamDisconnected:"STREAM_DISCONNECTED",StreamHealthTimeout:"STREAM_HEALTH_TIMEOUT",StreamInterrupted:"STREAM_INTERRUPTED",StreamOpenFailed:"STREAM_OPEN_FAILED",StreamSeqGap:"STREAM_SEQ_GAP",StreamUnavailable:"STREAM_UNAVAILABLE",UnsupportedHttpBody:"UNSUPPORTED_HTTP_BODY",UserInfoUnavailable:"USER_INFO_UNAVAILABLE"},c=e=>{var t,n;return{answer:(t=e.content)!=null?t:"",reasoning:(n=e.reasoningContent)!=null?n:""}},i=/^function(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,u=e=>i.test(e);export{r as SITE_RUNTIME_PROTOCOL_VERSION,a as SiteRuntimeApi,p as SiteRuntimeErrorCode,s as SiteRuntimeEvent,o as SiteRuntimeFunction,u as isValidSiteFunctionName,c as readSiteAITextDelta};
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { SiteAttachmentUploadOptions, SiteAttachmentUploadResult, SiteHttpRequestOptions, SiteOpenLinkResult, SiteRuntimeContext, SiteRuntimeUserInfo, SiteRuntimeModeChangedEvent, SiteFunctionDefinition, SiteProjectEnv,
|
|
2
|
-
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteAIAudioContentPart, SiteAICapabilityType, SiteAIFileContentPart, SiteAIFunctionStreamCloseRequest, SiteAIFunctionStreamDone, SiteAIFunctionStreamError, SiteAIFunctionStreamMessage, SiteAIFunctionStreamOpenRequest, SiteAIImageAsset, SiteAIImageContentPart, SiteAIImageTask, SiteAIMediaTaskBase, SiteAIMessageContentPart, SiteAITaskStatus, SiteAITextContentPart, SiteAITextDelta, SiteAITextMessageParam, SiteAIUserMessageParam, SiteAIVideoAsset, SiteAIVideoContentPart, SiteAIVideoTask, SiteAttachmentTarget, SiteAttachmentUploadCancelRequest, SiteAttachmentUploadPayload, SiteAttachmentUploadProgress, SiteAttachmentUploadRequest, SiteChatbotStreamCloseRequest, SiteChatbotStreamMessage, SiteChatbotStreamOpenRequest, SiteFunctionInvokeRequest, SiteHttpCancelRequest, SiteHttpMethod, SiteHttpRequest, SiteHttpRequestInit, SiteHttpResponse, SiteHttpResponseType, SiteOpenLinkRequest, SiteRuntimeApi, SiteRuntimeError, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, SiteRuntimeLoadFailedEvent, SiteRuntimeReadyEvent, isValidSiteFunctionName, readSiteAITextDelta } from './runtime-contract.js';
|
|
1
|
+
import { SiteAttachmentUploadOptions, SiteAttachmentUploadResult, SiteHttpRequestOptions, SiteOpenLinkResult, SiteRuntimeContext, SiteRuntimeUserInfo, SiteRuntimeModeChangedEvent, SiteFunctionDefinition, SiteProjectEnv, SiteAIFunctionArguments, SiteAIStreamMessageParam, SiteAIFunctionError, SiteAIStreamDelta, SiteAIMediaTask, SiteAIFunctionResult } from './runtime-contract.js';
|
|
2
|
+
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteAIAudioContentPart, SiteAICapabilityType, SiteAIFileContentPart, SiteAIFunctionParams, SiteAIFunctionStreamCloseRequest, SiteAIFunctionStreamDone, SiteAIFunctionStreamError, SiteAIFunctionStreamMessage, SiteAIFunctionStreamOpenRequest, SiteAIFunctionVariables, SiteAIImageAsset, SiteAIImageContentPart, SiteAIImageTask, SiteAIMediaTaskBase, SiteAIMessageContentPart, SiteAITaskStatus, SiteAITextContentPart, SiteAITextDelta, SiteAITextMessageParam, SiteAIUserMessageParam, SiteAIVideoAsset, SiteAIVideoContentPart, SiteAIVideoTask, SiteAttachmentTarget, SiteAttachmentUploadCancelRequest, SiteAttachmentUploadPayload, SiteAttachmentUploadProgress, SiteAttachmentUploadRequest, SiteChatbotStreamCloseRequest, SiteChatbotStreamMessage, SiteChatbotStreamOpenRequest, SiteFunctionInvokeRequest, SiteFunctionValidationIssue, SiteHttpCancelRequest, SiteHttpMethod, SiteHttpRequest, SiteHttpRequestInit, SiteHttpResponse, SiteHttpResponseType, SiteOpenLinkRequest, SiteRuntimeApi, SiteRuntimeError, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, SiteRuntimeLoadFailedEvent, SiteRuntimeReadyEvent, isValidSiteFunctionName, readSiteAITextDelta } from './runtime-contract.js';
|
|
3
3
|
|
|
4
4
|
interface RuntimeChannel {
|
|
5
5
|
emitEvent: <T>(key: string, params: T) => Promise<void>;
|
|
@@ -20,6 +20,8 @@ declare class SiteRuntimeInvocationError extends Error {
|
|
|
20
20
|
declare class SiteRuntimeClient<Map = FunctionMap> {
|
|
21
21
|
private readonly channel;
|
|
22
22
|
constructor(channel: RuntimeChannel);
|
|
23
|
+
/** Reuse the existing transport without starting another handshake. */
|
|
24
|
+
getChannel: () => RuntimeChannel;
|
|
23
25
|
uploadAttachment: ({ onProgress, ...request }: SiteAttachmentUploadOptions) => Promise<SiteAttachmentUploadResult>;
|
|
24
26
|
invokeHttp: (request: SiteHttpRequestOptions) => Promise<Response>;
|
|
25
27
|
invokeApi: <Name extends FunctionName<Map>>(functionName: Name, params: FunctionParams<Map, Name>) => Promise<FunctionResult<Map, Name>>;
|
|
@@ -77,11 +79,10 @@ interface SiteAIVideoGenerationInput {
|
|
|
77
79
|
image_url?: string;
|
|
78
80
|
prompt?: string;
|
|
79
81
|
}
|
|
80
|
-
|
|
82
|
+
type CallSiteAIFunctionBaseParams = SiteAIFunctionArguments & {
|
|
81
83
|
functionKey: string;
|
|
82
84
|
messages?: SiteAIStreamMessageParam[];
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
+
};
|
|
85
86
|
type CallSiteAIFunctionParams = CallSiteAIFunctionBaseParams & ({
|
|
86
87
|
capability: 'image';
|
|
87
88
|
input?: SiteAIImageGenerationInput;
|
|
@@ -97,12 +98,13 @@ interface SiteAIFunctionOptions {
|
|
|
97
98
|
env?: SiteProjectEnv;
|
|
98
99
|
requestId?: string;
|
|
99
100
|
siteToken?: string;
|
|
101
|
+
/** 取消普通 invoke / task 请求;流式使用 handle.destroy()。 */
|
|
102
|
+
signal?: AbortSignal;
|
|
100
103
|
}
|
|
101
|
-
|
|
104
|
+
type InvokeSiteAIFunctionStreamParams = SiteAIFunctionArguments & {
|
|
102
105
|
functionKey: string;
|
|
103
106
|
messages: SiteAIStreamMessageParam[];
|
|
104
|
-
|
|
105
|
-
}
|
|
107
|
+
};
|
|
106
108
|
interface SiteAIFunctionStreamHandle {
|
|
107
109
|
destroy(): void;
|
|
108
110
|
onDone(cb: () => void): void;
|
|
@@ -121,4 +123,4 @@ interface LinkGuardOptions {
|
|
|
121
123
|
/** Install once per page. Repeated calls return the same idempotent cleanup. */
|
|
122
124
|
declare const installLinkGuard: (options?: LinkGuardOptions) => (() => void);
|
|
123
125
|
|
|
124
|
-
export { CallSiteAIFunctionParams, FunctionMap, InvokeSiteAIFunctionStreamParams, LinkGuardOptions, RuntimeChannel, SiteAIFunctionError, SiteAIFunctionOptions, SiteAIFunctionResult, SiteAIFunctionStreamHandle,
|
|
126
|
+
export { CallSiteAIFunctionParams, FunctionMap, InvokeSiteAIFunctionStreamParams, LinkGuardOptions, RuntimeChannel, SiteAIFunctionArguments, SiteAIFunctionError, SiteAIFunctionOptions, SiteAIFunctionResult, SiteAIFunctionStreamHandle, SiteAIImageGenerationInput, SiteAIMediaTask, SiteAIStreamDelta, SiteAIStreamMessageParam, SiteAIVideoGenerationInput, SiteAttachmentUploadOptions, SiteAttachmentUploadResult, SiteChatbotStreamAdapter, SiteChatbotStreamError, SiteFunctionDefinition, SiteHttpRequestOptions, SiteOpenLinkResult, SiteProjectEnv, SiteRuntimeClient, SiteRuntimeContext, SiteRuntimeInvocationError, SiteRuntimeModeChangedEvent, SiteRuntimeUserInfo, callSiteAIFunction, createSiteAIFunctionTask, createSiteRuntimeClient, createSiteRuntimeFetch, fetch, getCurrentUser, getSiteAIFunctionTask, installLinkGuard, invokeApi, invokeHttp, invokeSiteAIFunctionStream, logout, openLink, requestEdit, siteRuntime, uploadAttachment };
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ut=Object.defineProperty,lt=Object.defineProperties;var pt=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,Ce=Object.prototype.propertyIsEnumerable;var be=(t,e,n)=>e in t?ut(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,c=(t,e)=>{for(var n in e||(e={}))Te.call(e,n)&&be(t,n,e[n]);if(D)for(var n of D(e))Ce.call(e,n)&&be(t,n,e[n]);return t},S=(t,e)=>lt(t,pt(e));var ke=(t,e)=>{var n={};for(var r in t)Te.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&D)for(var r of D(t))e.indexOf(r)<0&&Ce.call(t,r)&&(n[r]=t[r]);return n};var m=(t,e,n)=>new Promise((r,i)=>{var o=s=>{try{d(n.next(s))}catch(l){i(l)}},a=s=>{try{d(n.throw(s))}catch(l){i(l)}},d=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,a);d((n=n.apply(t,e)).next())});import{uniqueId as ie}from"lodash-es";var J="same-origin",Re="__internal_fetchBinaryList__",xe="__internal_cancelBinaryFetch__",_e="__internal_binaryFetchProgress__";function X(t){return Number.isFinite(t)?Math.max(1,Math.floor(t)):4}function Q(t){return t==="omit"||t==="include"?t:J}var B=(i=>(i.IFRAME_LOAD_ERROR="iframeLoadError",i.NOT_ALLOWED_URL="notAllowedUrl",i.HANDSHAKE_TIME_OUT="handshakeTimeout",i.CHANNEL_UNAVAILABLE="channelUnavailable",i))(B||{});var k=class extends Error{constructor(n,r){super(r);this.code=n,this.name="ChannelCallbackError"}};function we(t){return new k(10004,`api "${t}" is not registered`)}function Fe(t){return new k(10005,`api "${t}" timed out`)}function Z(){return new k(10006,"channel has been destroyed")}function Le(t){return new k(10008,`request "${t}" was superseded by a new one`)}var ht="unknown error";function He(t){return typeof t=="object"&&t!==null}function mt(t){if(typeof t=="string"&&t)return t;if(t instanceof k&&t.message||t instanceof Error&&t.message)return t.message;if(He(t)){let{msg:e,message:n}=t;if(typeof e=="string"&&e)return e;if(typeof n=="string"&&n)return n}return ht}function ft(t){if(t instanceof k)return t.code;if(!He(t))return-1;let{code:e}=t;return typeof e=="string"&&e||typeof e=="number"&&Number.isFinite(e)?e:-1}function v(t){return{code:ft(t),msg:mt(t)}}function Me(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof Blob!="undefined"&&t instanceof Blob}function gt(t){return Me(t)||Object.values(t).some(e=>Me(e))}function Ne(t){return t&&typeof t=="object"?gt(t)?t:JSON.parse(JSON.stringify(t)):t}var St={["iframeLoadError"]:10001,["notAllowedUrl"]:10002,["handshakeTimeout"]:10003,["channelUnavailable"]:10009};function It(t){return typeof t=="object"&&t!==null}function yt(t){if(!It(t))return!1;let{type:e}=t;return typeof e=="string"&&Object.values(B).includes(e)}function ee(t){return yt(t)?{code:St[t.type],msg:t.message||t.type}:v(t)}function te(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var N=class{constructor(e,n){this._target=e,this._options=n}sendMsg(e,n){if(!this._target)throw new Error("target window is not found");this._target.postMessage(e,this._options.targetOrigin,n!=null?n:[])}listenMsg(e){this._eventHandler=n=>{n.source===this._options.sourceWindow&&this._options.allowedOrigins.includes(n.origin)&&e(n)},typeof window!="undefined"&&window.addEventListener("message",this._eventHandler)}destroy(){typeof window!="undefined"&&this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}};var M=class{constructor(e,n,r){e==="host"?this.channelManager=new N(n,r):e==="client"&&(this.channelManager=new N(window.parent,r))}static createInstance(e,n,r){return new M(e,n,r)}sendMsg(e,n){var r;(r=this.channelManager)==null||r.sendMsg(e,n)}listenMsg(e){var n;(n=this.channelManager)==null||n.listenMsg(e)}destroy(){var e;(e=this.channelManager)==null||e.destroy()}};var q=class{constructor(){this.requests=new Map}create(e,n,r=3e4){return this.reject(e,v(Le(e))),new Promise((i,o)=>{let a=setTimeout(()=>{var d;((d=this.requests.get(e))==null?void 0:d.timeout)===a&&(this.requests.delete(e),o(v(Fe(n))))},r);this.requests.set(e,{reject:o,resolve:i,timeout:a})})}resolve(e,n){let r=this.take(e);return r?(r.resolve(n),!0):!1}reject(e,n){let r=this.take(e);return r?(r.reject(n),!0):!1}rejectAll(e){for(let n of this.requests.keys())this.reject(n,e)}take(e){let n=this.requests.get(e);if(n)return this.requests.delete(e),clearTimeout(n.timeout),n}};var ne=t=>typeof t=="object"&&t!==null,vt=new Set(["blockId","expectedPrefixId","id","jobId","prefixId","url"]),R=t=>{let e={};for(let[n,r]of Object.entries(t))if(!(n==="inputParams"||n==="outputParams")){if(vt.has(n)){e[`${n}Present`]=!!r;continue}if(n==="error"){Object.assign(e,x(r));continue}if(n==="errorInfo"&&ne(r)){e.errorType=typeof r.type=="string"?r.type:"object";continue}(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[n]=r)}return e},P=t=>{let e={idPresent:!!t.id,type:t.type},n=ne(t.payload)?t.payload:{};return typeof n.key=="string"&&(e.key=n.key),t.type==="callback"&&typeof n.code=="number"&&(e.callbackCode=n.code),t.type==="handshake"&&typeof n.proactive=="boolean"&&(e.proactive=n.proactive),e},re=t=>t.type!=="invoke"&&t.type!=="callback",x=t=>{if(!ne(t))return{errorType:typeof t};let e={errorType:t instanceof Error?t.name:"object"};return(typeof t.code=="number"||typeof t.code=="string")&&(e.errorCode=t.code),e};var bt=()=>{let t=Reflect.get(globalThis,"BearWebSlardarWeb");return typeof t=="function"?t:void 0},Tt=t=>{let e={};for(let[n,r]of Object.entries(R(t)))typeof r=="string"||typeof r=="number"?e[n]=r:typeof r=="boolean"&&(e[n]=String(r));return e},Oe=(t,e,n,r)=>{console[e](`[base-site-channel][${t}]`,n,r)},K=(t,e,n,r={})=>{if(e==="info")return;let i=R(r),o=bt();if(!o){Oe(t,e,n,i);return}try{o("sendLog",{content:`[base-site-channel][${t}] ${n}`,extra:c({event_name:"Runtime_SiteChannel_Message",bizType:"Runtime",subType:"SiteChannel",action:"Message",channel_side:t,channel_message:n},Tt(i)),level:e})}catch(a){Oe(t,e,n,S(c({},i),{slardarFallback:!0,slardarErrorType:a instanceof Error?a.name:typeof a}))}};var Rt=()=>{var n;if(typeof window=="undefined")return null;let e=((n=window.location.ancestorOrigins)==null?void 0:n[0])||document.referrer;if(!e)return null;try{return new URL(e).origin}catch(r){return null}},xt=t=>{try{return new URL(t).origin}catch(e){return null}},oe=class{constructor(e={}){this.pendingRequests=new q;this.eventMap=new Map;this.eventHandlerMap=new Map;this._msgChannel=null;this._invokeId="";this._handshakePromise=te({type:"channelUnavailable",message:"channel handshake is not initialized"});this._handshakeResolve=null;this._handshakeReject=null;this._handshakeRetryTimes=0;this._handshakeStatus=0;this._handshakeTimeout=null;this._prefixId="";this._destroyed=!1;let n=e.hostOrigin?xt(e.hostOrigin):null;if(this.hostOrigin=n!=null?n:Rt(),e.hostOrigin&&!n&&this.logWarn("invalid hostOrigin, fallback to parent origin"),typeof window=="undefined"||window.parent===window){this.failHandshake("invalid window context",{hasWindow:typeof window!="undefined",isTopWindow:typeof window!="undefined"?window.parent===window:!0});return}if(!this.hostOrigin){this.failHandshake("host origin unavailable");return}this._msgChannel=M.createInstance("client",window.parent,{allowedOrigins:[this.hostOrigin],sourceWindow:window.parent,targetOrigin:this.hostOrigin}),this.listeningHostMsg(),this.startHandshake()}logInfo(e,n={}){K("client","info",e,c({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},R(n)))}logWarn(e,n={}){K("client","warn",e,c({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},R(n)))}logError(e,n={}){K("client","error",e,c({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},R(n)))}failHandshake(e,n={}){this._handshakeStatus=2,this._handshakePromise=te({type:"channelUnavailable",message:e}),this.logError(`init failed: ${e}`,n)}sendProactiveHandshakeMsg(){var n;let e={id:ie("handshake-"),type:"handshake",payload:{proactive:!0}};this.logInfo("send proactive handshake",P(e)),(n=this._msgChannel)==null||n.sendMsg(e)}_initHandshake(){this._handshakeRetryTimes=0,clearTimeout(this._handshakeTimeout),this._handshakeStatus=0,this.logInfo("init handshake"),this._handshakePromise=new Promise((e,n)=>{this._handshakeResolve=e,this._handshakeReject=n,this._handshakeTimeout=setTimeout(()=>this.retryHandshake(n),2e3)})}startHandshake(){this._initHandshake(),this._handshakePromise.then(()=>{this._handshakeStatus=1,this.logInfo("handshake success")}).catch(e=>{this._handshakeStatus=2,this.logError("handshake failed",{error:e})}),this.sendProactiveHandshakeMsg()}retryHandshake(e){this._handshakeStatus===0&&(this._handshakeRetryTimes<5?(this.logWarn("retry handshake",{retryTimes:this._handshakeRetryTimes+1}),this.sendProactiveHandshakeMsg(),this._handshakeRetryTimes++,this._handshakeTimeout=setTimeout(()=>this.retryHandshake(e),2e3+2**this._handshakeRetryTimes)):(this.logError("handshake retry timeout",{retryTimes:this._handshakeRetryTimes}),e({type:"handshakeTimeout",message:"iframe handshake time out"})))}updateInvokeId(){this._invokeId=ie(`${this._prefixId}-invoke-`)}handleChannelMessage(e){let{data:n}=e;re(n)&&this.logInfo("receive host message",P(n));let{type:r}=n;r==="callback"?this.handleHostCallback(n):r==="handshake"?this.handleHandshakeCallback(n):r==="invoke"?this.handleHostInvoke(n).catch(i=>{this.logError("handle host invoke error",c(c({},P(n)),x(i)))}):r==="event"&&this.handleHostEvent(n).catch(i=>{this.logError("handle host event error",c(c({},P(n)),x(i)))})}handleHostCallback(e){let{id:n,payload:r}=e,i={logId:n,key:r.key,callbackCode:r.code};if(r.code===1){if(this.pendingRequests.reject(n,r.res)){this.logWarn("api response received",i);return}}else if(this.pendingRequests.resolve(n,r.res)){this.logInfo("api response received",i);return}this.logWarn("host callback request not found",{id:n,key:r.key})}handleHostInvoke(e){return m(this,null,function*(){yield this._handshakePromise;let{id:n,payload:r}=e,{key:i,params:o,prefixId:a}=r;if(a!==this._prefixId){this.logWarn("ignore host invoke because prefixId mismatch",{id:n,key:i,prefixId:a,expectedPrefixId:this._prefixId});return}let d=this.eventMap.get(i);if(typeof d!="function"){this.logWarn("host invoke handler not found",{id:n,key:i}),this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:v(we(i)),code:1}});return}this.logInfo("handle host invoke",{id:n,key:i});try{let s=Ne(yield d(o));this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:s,code:0}}),this.logInfo("host invoke success",{id:n,key:i})}catch(s){this.logError("host invoke failed",c({id:n,key:i},x(s))),this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:v(s),code:1}})}})}handleHostEvent(e){return m(this,null,function*(){yield this._handshakePromise;let{payload:n}=e,{key:r,params:i,prefixId:o}=n;if(o!==this._prefixId){this.logWarn("ignore host event because prefixId mismatch",{key:r,prefixId:o,expectedPrefixId:this._prefixId});return}let a=this.eventHandlerMap.get(r);if(!(a!=null&&a.size)){this.logWarn("host event handler not found",{key:r});return}this.logInfo("handle host event",{key:r,handlerCount:a.size}),yield Promise.allSettled(Array.from(a,d=>d(i)))})}handleHandshakeCallback(e){var o,a;let{id:n,payload:r}=e;this._prefixId=(o=r==null?void 0:r.prefixId)!=null?o:"",this.logInfo("receive handshake callback",{id:n,prefixId:this._prefixId}),(a=this._handshakeResolve)==null||a.call(this);let i={id:n,type:"handshake",payload:{proactive:!1,info:{isHandshakeSuccess:!0}}};this.sendMsg2Host(i)}listeningHostMsg(){var e;this.logInfo("start listening host messages"),(e=this._msgChannel)==null||e.listenMsg(this.handleChannelMessage.bind(this))}sendMsg2Host(e,n){var r;re(e)&&this.logInfo("send message to host",P(e)),(r=this._msgChannel)==null||r.sendMsg(e,n)}invokeApi(e,n,r){return m(this,null,function*(){if(this._destroyed)return Promise.reject(v(Z()));try{yield this._handshakePromise}catch(a){return this.logError("invoke api blocked by handshake error",c({key:e},x(a))),Promise.reject(ee(a))}this._invokeId||this.updateInvokeId();let i=this._invokeId,o=this.pendingRequests.create(i,e,r==null?void 0:r.timeoutMs);return this.logInfo("api request sent",{key:e,logId:i}),this.sendMsg2Host({type:"invoke",id:i,payload:{key:e,params:n,prefixId:this._prefixId}}),this.updateInvokeId(),o})}registerApi(e,n){if(this.eventMap.has(e)){this.logWarn("register api ignored because key already exists",{key:e});return}this.eventMap.set(e,n),this.logInfo("register api",{key:e})}emitEvent(e,n){return m(this,null,function*(){try{yield this._handshakePromise}catch(r){return this.logError("emit event blocked by handshake error",c({key:e},x(r))),Promise.reject(ee(r))}this.logInfo("emit event",{key:e}),this.sendMsg2Host({type:"event",id:ie(`${this._prefixId}-event-`),payload:{key:e,params:n,prefixId:this._prefixId}})})}fetchBinaryList(e){return m(this,null,function*(){var n;return this.logInfo("invoke built-in binary fetch",{status:"start",itemCount:e.items.length,concurrency:X(e.concurrency),credentials:Q(e.credentials)}),this.invokeApi(Re,{items:e.items,concurrency:X(e.concurrency),credentials:Q((n=e.credentials)!=null?n:J)})})}subscribeBinaryFetchProgress(e){return this.subscribeEvent(_e,e)}cancelBinaryFetch(e){return m(this,null,function*(){this.logInfo("invoke built-in binary fetch cancel",{jobId:e,status:"cancel-requested"}),yield this.invokeApi(xe,{jobId:e})})}destroy(){var n,r;if(this._destroyed)return;this._destroyed=!0,this.logInfo("destroy client"),(n=this._msgChannel)==null||n.destroy(),clearTimeout(this._handshakeTimeout);let e=v(Z());(r=this._handshakeReject)==null||r.call(this,{type:"handshakeTimeout",message:e.msg}),this.pendingRequests.rejectAll(e),this.eventMap.clear(),this.eventHandlerMap.clear()}subscribeEvent(e,n){var i;let r=(i=this.eventHandlerMap.get(e))!=null?i:new Set;return r.add(n),this.eventHandlerMap.set(e,r),this.logInfo("subscribe event",{key:e,handlerCount:r.size}),()=>this.unsubscribeEvent(e,n)}unsubscribeEvent(e,n){let r=this.eventHandlerMap.get(e);if(!r){this.logWarn("unsubscribe event ignored because key is not subscribed",{key:e});return}if(!n){this.eventHandlerMap.delete(e),this.logInfo("unsubscribe all event handlers",{key:e,handlerCount:0});return}r.delete(n),r.size===0&&this.eventHandlerMap.delete(e),this.logInfo("unsubscribe event",{key:e,handlerCount:r.size})}},_t=t=>new oe(t),_=_t();var De="site.v1",g={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},E={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},j={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"},u={AttachmentUnavailable:"ATTACHMENT_UNAVAILABLE",AttachmentUploadCanceled:"ATTACHMENT_UPLOAD_CANCELED",AttachmentUploadFailed:"ATTACHMENT_UPLOAD_FAILED",AttachmentUploadStalled:"ATTACHMENT_UPLOAD_STALLED",ChannelDestroyed:"CHANNEL_DESTROYED",FunctionNotAllowed:"FUNCTION_NOT_ALLOWED",FunctionRequestFailed:"FUNCTION_REQUEST_FAILED",InvalidAIFunctionTask:"INVALID_AI_FUNCTION_TASK",HttpRequestFailed:"HTTP_REQUEST_FAILED",HttpResponseTypeUnsupported:"HTTP_RESPONSE_TYPE_UNSUPPORTED",HttpRequestCanceled:"HTTP_REQUEST_CANCELED",InvalidAttachmentTarget:"INVALID_ATTACHMENT_TARGET",InvalidFunctionName:"INVALID_FUNCTION_NAME",InvalidHttpHeader:"INVALID_HTTP_HEADER",InvalidHttpUrl:"INVALID_HTTP_URL",InvalidLinkUrl:"INVALID_LINK_URL",LinkCheckUnavailable:"LINK_CHECK_UNAVAILABLE",LogoutFailed:"LOGOUT_FAILED",ProtocolMismatch:"PROTOCOL_MISMATCH",RequestTimeout:"REQUEST_TIMEOUT",StreamDisconnected:"STREAM_DISCONNECTED",StreamHealthTimeout:"STREAM_HEALTH_TIMEOUT",StreamInterrupted:"STREAM_INTERRUPTED",StreamOpenFailed:"STREAM_OPEN_FAILED",StreamSeqGap:"STREAM_SEQ_GAP",StreamUnavailable:"STREAM_UNAVAILABLE",UnsupportedHttpBody:"UNSUPPORTED_HTTP_BODY",UserInfoUnavailable:"USER_INFO_UNAVAILABLE"},Pr=t=>{var e,n;return{answer:(e=t.content)!=null?e:"",reasoning:(n=t.reasoningContent)!=null?n:""}},Mt=/^function(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,Be=t=>Mt.test(t);var Pt=0,qe=(i,o)=>m(void 0,[i,o],function*(t,{init:e,url:n,signal:r}){if((e==null?void 0:e.responseType)!==void 0&&!["text","arrayBuffer"].includes(e.responseType))throw new y(u.HttpResponseTypeUnsupported,"Unsupported HTTP response type; use text or arrayBuffer");let a=()=>new DOMException("The operation was aborted","AbortError");if(r!=null&&r.aborted)throw a();let d=typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`http-${Date.now()}-${++Pt}`,s=()=>{},l=new Promise((p,f)=>{s=()=>{f(a()),t.invokeApi(g.HttpRequestCancel,{requestId:d}).catch(()=>{})}});r==null||r.addEventListener("abort",s,{once:!0});try{let p=yield Promise.race([t.invokeApi(g.HttpRequest,{requestId:d,url:n,init:e},{timeoutMs:(e==null?void 0:e.timeoutMs)===void 0?void 0:Math.min(e.timeoutMs,6e4)+1e3}),l]);if((e==null?void 0:e.responseType)==="arrayBuffer"&&(p.bodyType!=="arrayBuffer"||!(p.body instanceof ArrayBuffer)))throw new y(u.HttpResponseTypeUnsupported,"The current host does not support binary HTTP responses; upgrade the host");return new Response([204,205,304].includes(p.status)?null:p.body,{headers:p.headers,status:p.status,statusText:p.statusText})}finally{r==null||r.removeEventListener("abort",s)}});var y=class extends Error{constructor(n,r){super(r);this.code=n;this.name="SiteRuntimeInvocationError"}},Ke=t=>typeof t=="string"&&t.trim().length>0,wt=t=>typeof File!="undefined"&&t instanceof File,je=12e4,Ft=2*60*60*1e3,Ve=0,Lt=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Ve+=1,`site-upload-${Ve}`),Ht=t=>typeof t=="object"&&t!==null&&"code"in t?t.code:void 0,Nt=t=>{if(t instanceof Error&&t.message)return t.message;if(typeof t=="object"&&t!==null){if("message"in t&&typeof t.message=="string")return t.message;if("msg"in t&&typeof t.msg=="string")return t.msg}return String(t)},Ot=new Set([u.AttachmentUnavailable,u.AttachmentUploadCanceled,u.AttachmentUploadFailed,u.AttachmentUploadStalled,u.InvalidAttachmentTarget]),Ut=(t,e)=>{if(t instanceof y)return t;let n=Ht(t),r=Nt(t);return String(n)===String(10004)?new y(u.AttachmentUnavailable,r):typeof n=="string"&&Ot.has(n)?new y(n,r):new y(e,r)},V=(t,e,n)=>m(void 0,null,function*(){if(!Be(e))throw new y(u.InvalidFunctionName,"Function name must be a dot-separated path beginning with function (for example, function.orders.list)");return t.invokeApi(g.FunctionInvoke,{functionName:e,params:n})}),z=class{constructor(e){this.channel=e;this.uploadAttachment=r=>m(this,null,function*(){var i=r,{onProgress:e}=i,n=ke(i,["onProgress"]);if(!Ke(n==null?void 0:n.baseToken)||!Ke(n==null?void 0:n.tableId)||!wt(n==null?void 0:n.file))throw new y(u.InvalidAttachmentTarget,"Attachment upload requires nonempty baseToken and tableId values and a File");let o=Lt(),a,d=()=>{},s=()=>{this.channel.invokeApi(g.AttachmentUploadCancel,{uploadId:o}).catch(()=>{})},l=new Promise((p,f)=>{let T=()=>{clearTimeout(a),a=setTimeout(()=>{s(),f(new y(u.AttachmentUploadStalled,`Attachment upload made no progress for more than ${je/1e3} seconds`))},je)};d=this.channel.subscribeEvent(E.AttachmentUploadProgress,C=>{(C==null?void 0:C.uploadId)===o&&(T(),Promise.resolve(e==null?void 0:e(C)).catch(()=>{console.error("[base-site-channel][runtime] Attachment progress callback failed")}))})});try{return yield Promise.race([this.channel.invokeApi(g.AttachmentUpload,S(c({},n),{uploadId:o}),{timeoutMs:Ft}),l])}catch(p){throw Ut(p,u.AttachmentUploadFailed)}finally{clearTimeout(a),d()}});this.invokeHttp=e=>qe(this.channel,e);this.invokeApi=(e,n)=>V(this.channel,e,n);this.openLink=e=>this.channel.invokeApi(g.OpenLink,{url:e});this.getRuntimeContext=()=>this.channel.invokeApi(g.RuntimeContext,void 0);this.getCurrentUser=()=>V(this.channel,j.GetCurrentUser,void 0);this.logout=()=>V(this.channel,j.Logout,void 0);this.requestEdit=()=>V(this.channel,j.RequestEdit,void 0);this.ready=()=>this.channel.emitEvent(E.LifecycleReady,{protocolVersion:De});this.reportLoadFailed=e=>this.channel.emitEvent(E.LifecycleLoadFailed,{code:e});this.subscribeModeChanged=e=>this.channel.subscribeEvent(E.ModeChanged,({mode:n})=>e(n))}},W=(t=_)=>new z(t),b=W(),Dt=b.invokeHttp,Bt=b.invokeApi,qt=b.getCurrentUser,Kt=b.logout,jt=b.requestEdit,Vt=b.uploadAttachment,se=b.openLink;var zt=new Set(["open.feishu.cn","open.feishu-pre.cn","open.feishu-boe.cn"]),ze="/open-apis",Wt="/base-site/api/openapi",Gt=new Set(["DELETE","GET","PATCH","POST","PUT"]),$t=()=>(typeof globalThis.location=="undefined"?"":globalThis.location.pathname).replace(/^\/+/,"").startsWith("preview")?[["x-project-env","preview"]]:[],Yt=t=>{if(typeof Request!="undefined"&&t instanceof Request)throw new TypeError("Site Runtime fetch does not accept a Request object; pass a URL instead");let e=String(t);if(e.startsWith("//"))throw new TypeError("Site Runtime fetch does not accept a scheme-relative URL");if(e.startsWith("/"))return e;let n=new URL(e);if(zt.has(n.hostname)&&n.pathname.startsWith(ze))return`${Wt}${n.pathname.slice(ze.length)}${n.search}`;throw new TypeError("Site Runtime fetch accepts only relative business paths or supported Feishu OpenAPI URLs")},Jt=t=>{let e=new Headers(t);$t().forEach(([r,i])=>e.set(r,i));let n={};return e.forEach((r,i)=>{n[i]=r}),n},Xt=(t,e)=>{var r,i,o;let n=(i=(r=t==null?void 0:t.method)==null?void 0:r.toUpperCase())!=null?i:"GET";if(!Gt.has(n))throw new TypeError(`Site Runtime fetch does not support the ${n} method`);if((t==null?void 0:t.body)!==void 0&&t.body!==null&&typeof t.body!="string")throw new TypeError("Site Runtime fetch requires a string request body");if((o=t==null?void 0:t.signal)!=null&&o.aborted)throw new DOMException("The operation was aborted","AbortError");return{body:typeof(t==null?void 0:t.body)=="string"?t.body:void 0,headers:Jt(t==null?void 0:t.headers),method:n,timeoutMs:e}},G=(t=b,e)=>(n,r)=>t.invokeHttp(S(c({init:Xt(r,e)},r!=null&&r.signal?{signal:r.signal}:{}),{url:Yt(n)})),Qt=G();var We=0,Zt=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(We+=1,`site-chatbot-${We}`),$=(t,e)=>{try{t==null||t(e)}catch(n){console.error("[base-site-channel][runtime] Chatbot callback failed")}},w=class extends Error{constructor(n,r){super(`Chatbot stream error: ${n}`);this.code=n;this.retryable=r;this.name="SiteChatbotStreamError"}},ae=class{constructor(e){this.options=e;this.init=e=>{this.destroy();let n=Zt(),r={lastSeq:0,subscriptionId:n,unsubscribeError:()=>{},unsubscribeMessage:()=>{}};r.unsubscribeMessage=this.channel.subscribeEvent(E.StreamMessage,i=>{i.subscriptionId!==n||i.seq<=r.lastSeq||(i.seq>r.lastSeq+1&&$(this.onErrorCallback,new w(u.StreamSeqGap,!0)),r.lastSeq=i.seq,$(this.onMessageCallback,i.data))}),r.unsubscribeError=this.channel.subscribeEvent(E.StreamError,i=>{i.subscriptionId===n&&$(this.onErrorCallback,new w(i.code,i.retryable))}),this.current=r,this.channel.invokeApi(g.StreamOpen,{chatbotId:this.options.chatbotId,subscriptionId:n,threadId:e}).catch(()=>{var i;((i=this.current)==null?void 0:i.subscriptionId)===n&&$(this.onErrorCallback,new w(u.StreamOpenFailed,!0))})};this.onMessage=e=>{this.onMessageCallback=e};this.onError=e=>{this.onErrorCallback=e};this.destroy=()=>{let e=this.current;e&&(e.unsubscribeMessage(),e.unsubscribeError(),this.current=void 0,this.channel.invokeApi(g.StreamClose,{subscriptionId:e.subscriptionId}).catch(()=>console.error("[base-site-channel][runtime] Chatbot stream close failed")))};var n;this.channel=(n=e.channel)!=null?n:_}};var de="prod",Ge=0,Je=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Ge+=1,`site-ai-fn-${Ge}`),A=(t,e)=>{try{t==null||t(e)}catch(n){console.error("[base-site-channel][runtime] AI function callback failed")}},h=(t,e)=>{let n=new Error(e||`AI function error: ${t}`);return n.name="SiteAIFunctionError",n.code=t,n},Xe=()=>h(u.InvalidHttpUrl,"siteToken is required to invoke site AI function"),ue=()=>typeof window!="undefined"&&window.parent!==window,le=t=>{if(typeof queueMicrotask=="function"){queueMicrotask(t);return}Promise.resolve().then(t)},pe=t=>{let e={data:[],event:"message"};for(let n of t.split(/\r?\n/))n.startsWith("event:")?e.event=n.slice(6).trim():n.startsWith("data:")&&e.data.push(n.slice(5).trimStart());return e},ce=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="string")return r}},Qe=t=>{let e=[t];if(t&&typeof t=="object"){let n=t;e.push(n.response,n.data)}for(let n of e){if(!n||typeof n!="object")continue;let r=ce(n,["request_id","requestId","RequestID","id"]);if(r)return r}},Ze=t=>{if(!t||typeof t!="object")return{};let e=t;return{content:ce(e,["content","text","answer"]),reasoningContent:ce(e,["reasoning_content","reasoningContent","reasoning"])}},en=t=>{if(!t||typeof t!="object")return{};let e=t.choices;if(!Array.isArray(e))return{};for(let n of e){let r=n.delta,{content:i,reasoningContent:o}=Ze(r);if(i!==void 0||o!==void 0)return{content:i,reasoningContent:o}}return{}},et=t=>{var n;let e=[t];if(t&&typeof t=="object"){let r=t;e.push(r.response,r.data)}for(let r of e){let i=en(r);if(i.content!==void 0||i.reasoningContent!==void 0)return i;let o=Ze(r&&typeof r=="object"&&(n=r.delta)!=null?n:r);if(o.content!==void 0||o.reasoningContent!==void 0)return o}return{}},Y=t=>{try{let e=JSON.parse(t),n=et(e),r=Qe(e);return S(c(c(c({},n.content!==void 0?{content:n.content}:{}),n.reasoningContent!==void 0?{reasoningContent:n.reasoningContent}:{}),r?{requestId:r}:{}),{raw:e})}catch(e){return{content:t,raw:t}}},tt=t=>{if(typeof t=="string")return Y(t);let e=et(t),n=Qe(t),r=t&&typeof t=="object"&&"raw"in t?t.raw:t;return S(c(c(c({},e.content!==void 0?{content:e.content}:{}),e.reasoningContent!==void 0?{reasoningContent:e.reasoningContent}:{}),n?{requestId:n}:{}),{raw:r})},tn=t=>{var e,n;try{let r=JSON.parse(t),i=(e=r.Code)!=null?e:r.code,o=(n=r.Message)!=null?n:r.message,a=typeof i=="string"||typeof i=="number"?String(i):"STREAM_FAILED";return h(a||"STREAM_FAILED",typeof o=="string"&&o?o:t)}catch(r){return h("STREAM_FAILED",t)}},he=()=>({text:""}),nn=t=>/(^|\n)(data|event|id|retry):/.test(t),$e=t=>{if(!t||t==="[DONE]")return!!t;try{return JSON.parse(t),!0}catch(e){return!1}},rn=t=>{if(t){if(nn(t)){let n=pe(t).data.join(`
|
|
2
|
-
`);return
|
|
3
|
-
`)).filter(Boolean),i=
|
|
4
|
-
`);if(r.event==="error")return A(n.onError,tn(i)),!0;for(let o of me(e,i))if(on(o,n))return!0;return!1},nt=(t,e)=>m(void 0,null,function*(){var a;if(!t.body)throw h(u.StreamUnavailable,"SSE body missing");let n=t.body.getReader(),r=new TextDecoder,i=he(),o="";try{for(;;){let{done:d,value:s}=yield n.read();o+=r.decode(s,{stream:!d});let l=o.split(/\r?\n\r?\n/);o=(a=l.pop())!=null?a:"";for(let p of l)if(Ye(p,i,e))return;if(d){if(o&&Ye(o,i,e))return;A(e.onError,h(u.StreamInterrupted,"SSE stream ended without [DONE]"));return}}}finally{n.releaseLock()}}),fe=()=>{var n;let t=typeof globalThis.location=="undefined"?"":globalThis.location.pathname,e=/^\/?(preview\/)?app\/([^/]+)(\/|$)/.exec(t);return e?{env:e[1]?"preview":de,siteToken:decodeURIComponent((n=e[2])!=null?n:"")}:{}},rt=(t,e,n)=>{if(!t.startsWith("/")||t.startsWith("//"))throw h(u.InvalidHttpUrl,"AI function endpoint must be a same-origin relative path");let r=t.replace("{siteToken}",encodeURIComponent(e.siteToken)).replace(":token",encodeURIComponent(e.siteToken)).replace("{functionKey}","").replace(":function_key",""),i=new URL(r,"https://base.site");if(i.searchParams.set("env",e.env),n)for(let[o,a]of Object.entries(n))i.searchParams.set(o,a);return`${i.pathname}${i.search}`};var sn="/space/api/bitable/streaming/site/v1/:token/ai_functions/:function_key/invoke",ot="/space/api/bitable/site/v1/:token/ai_functions/:function_key/tasks",an=6e4,cn=/^([1-9][0-9]{1,4})x([1-9][0-9]{1,4})$/i,dn=3686400,un=16777216,ln=14,pn=t=>{let e=t.trim().replace("\xD7","x");if(/^[234]K$/i.test(e))return!0;let n=cn.exec(e);if(!n)return!1;let r=Number(n[1]),i=Number(n[2]),o=r*i;return o>=dn&&o<=un&&r<=i*16&&i<=r*16},hn=t=>{if(!t)return;let e=typeof t.image=="string"?[t.image]:t.image;if(e&&(e.length<1||e.length>ln||e.some(n=>!n.trim())))throw h(u.InvalidAIFunctionTask,"input.image must contain 1 to 14 non-empty strings");if(t.size!==void 0&&!pn(t.size))throw h(u.InvalidAIFunctionTask,"input.size must follow the Seedream 5.0 lite size limits")},Ee=t=>{var n;let e=(n=t.siteToken)==null?void 0:n.trim();return c(c(c({},t.env?{env:t.env}:{}),t.requestId?{requestId:t.requestId}:{}),e?{siteToken:e}:{})},Ae=t=>{var r,i,o;let e=fe(),n=((r=t.siteToken)==null?void 0:r.trim())||e.siteToken;if(!n)throw Xe();return{env:(o=(i=t.env)!=null?i:e.env)!=null?o:de,requestId:t.requestId,siteToken:n}},ve=(t,e,n)=>rt(t.replace(":function_key",encodeURIComponent(e)),n),st=t=>S(c({},t.requestId?{"X-Request-Id":t.requestId}:{}),{Accept:"application/json","Content-Type":"application/json"}),at=t=>{var e;return!t.channel&&!ue()?globalThis.fetch:G(W((e=t.channel)!=null?e:_),an)},Se=class{constructor(e,n){this.params=e;this.context=n;this.callbacks={};this.controller=new AbortController;this.closed=!1;this.onMessage=e=>{this.callbacks.onMessage=e};this.onError=e=>{this.callbacks.onError=e};this.onDone=e=>{this.callbacks.onDone=e};this.destroy=()=>{this.closed||(this.closed=!0,this.controller.abort())};le(()=>{this.start()})}start(){return m(this,null,function*(){var e;if(!this.closed)try{let n=yield fetch(ve(sn,this.params.functionKey,this.context),{body:JSON.stringify({messages:this.params.messages,variables:(e=this.params.variables)!=null?e:{}}),credentials:"include",headers:S(c({},this.context.requestId?{"X-Request-Id":this.context.requestId}:{}),{Accept:"text/event-stream","Content-Type":"application/json"}),method:"POST",signal:this.controller.signal});if(!n.ok)throw h("HTTP_ERROR",`${n.status} ${n.statusText}`);yield nt(n,this.callbacks)}catch(n){this.closed||A(this.callbacks.onError,n instanceof Error?n:h("STREAM_FAILED"))}})}},Ie=class{constructor(e){this.options=e;this.closed=!1;this.onMessage=e=>{this.onMessageCallback=e};this.onError=e=>{this.onErrorCallback=e};this.onDone=e=>{this.onDoneCallback=e};this.destroy=()=>{this.closed=!0;let e=this.current;e&&(this.cleanup(),this.channel.invokeApi(g.AIFunctionStreamClose,{subscriptionId:e.subscriptionId}).catch(()=>console.error("[base-site-channel][runtime] AI function stream close failed")))};var n;this.channel=(n=e.channel)!=null?n:_,le(()=>this.init())}init(){var i;if(this.closed)return;this.cleanup();let e=Je(),n={lastSeq:0,subscriptionId:e,unsubscribeDone:()=>{},unsubscribeError:()=>{},unsubscribeMessage:()=>{},upstream:he()};n.unsubscribeMessage=this.channel.subscribeEvent(E.AIFunctionStreamMessage,o=>this.handleMessage(o,n)),n.unsubscribeError=this.channel.subscribeEvent(E.AIFunctionStreamError,o=>this.handleError(o,e)),n.unsubscribeDone=this.channel.subscribeEvent(E.AIFunctionStreamDone,o=>this.handleDone(o,e)),this.current=n;let r=c(c(c({functionKey:this.options.params.functionKey,messages:this.options.params.messages,subscriptionId:e,variables:(i=this.options.params.variables)!=null?i:{}},this.options.context.env?{env:this.options.context.env}:{}),this.options.context.requestId?{requestId:this.options.context.requestId}:{}),this.options.context.siteToken?{siteToken:this.options.context.siteToken}:{});this.channel.invokeApi(g.AIFunctionStreamOpen,r).catch(()=>{var o;((o=this.current)==null?void 0:o.subscriptionId)===e&&A(this.onErrorCallback,h(u.StreamOpenFailed))})}handleMessage(e,n){if(e.subscriptionId===n.subscriptionId&&!(e.seq<=n.lastSeq)){if(e.seq>n.lastSeq+1&&A(this.onErrorCallback,h(u.StreamSeqGap)),n.lastSeq=e.seq,typeof e.data!="string"){A(this.onMessageCallback,tt(e.data));return}me(n.upstream,e.data).forEach(r=>{r!=="[DONE]"&&A(this.onMessageCallback,Y(r))})}}handleError(e,n){e.subscriptionId===n&&(A(this.onErrorCallback,h(e.code,e.message)),this.cleanup())}handleDone(e,n){e.subscriptionId===n&&(A(this.onDoneCallback,void 0),this.cleanup())}cleanup(){let e=this.current;e&&(e.unsubscribeMessage(),e.unsubscribeError(),e.unsubscribeDone(),this.current=void 0)}},ct=(t,e={})=>{var r;if(!((r=t.functionKey)!=null&&r.trim()))throw h(u.InvalidFunctionName,"functionKey is required");let n=c(c({},fe()),Ee(e));return e.channel||ue()?new Ie({channel:e.channel,context:n,params:t}):new Se(t,Ae(e))},mn=t=>m(void 0,null,function*(){if(!t.ok){let e=yield t.text().catch(()=>"");throw h("HTTP_ERROR",`${t.status} ${t.statusText} ${e}`)}try{return yield t.json()}catch(e){throw h(u.InvalidAIFunctionTask,"AI function task response is invalid")}}),O=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),fn=t=>t==="cancelled"||t==="failed"||t==="queued"||t==="running"||t==="succeeded",I=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r}},gn=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r}},Sn=t=>{let e=I(t,["capabilityType","capability_type","CapabilityType"]);return e==="image"||e==="video"?e:void 0},In=t=>{if(Array.isArray(t))return t.filter(O).map(e=>{var o;let n=I(e,["size","Size"]),r=I(e,["token","Token"]),i=I(e,["url","URL"]);return c(c(c({safetyStatus:(o=I(e,["safetyStatus","safety_status","SafetyStatus"]))!=null?o:""},n?{size:n}:{}),r?{token:r}:{}),i?{url:i}:{})})},yn=t=>{var i,o;if(!O(t))return;let e=(o=(i=t.durationSeconds)!=null?i:t.duration_seconds)!=null?o:t.DurationSeconds,n=I(t,["token","Token"]),r=I(t,["url","URL"]);return c(c(c({},typeof e=="number"?{durationSeconds:e}:{}),n?{token:n}:{}),r?{url:r}:{})},ge=t=>{var f,T,C,F,L,H;if(!O(t))throw h(u.InvalidAIFunctionTask,"AI function task response is invalid");let e=I(t,["type","Type"]),n=I(t,["taskId","task_id","TaskID"]),r=(f=t.status)!=null?f:t.Status;if(e!=="image_task"&&e!=="video_task"||!n||!fn(r))throw h(u.InvalidAIFunctionTask,"AI function task response is invalid");let i=(T=I(t,["requestId","request_id","RequestID"]))!=null?T:"",o=gn(t,["progress","Progress"]),a=Sn(t),d=I(t,["errCode","err_code","ErrCode"]),s=I(t,["errMessage","err_message","ErrMessage"]),l=In((F=(C=t.imageAssets)!=null?C:t.image_assets)!=null?F:t.ImageAssets),p=yn((H=(L=t.videoAsset)!=null?L:t.video_asset)!=null?H:t.VideoAsset);return S(c(c(c(c(c(c({},a?{capabilityType:a}:{}),d?{errCode:d}:{}),s?{errMessage:s}:{}),l?{imageAssets:l}:{}),o!==void 0?{progress:o}:{}),p?{videoAsset:p}:{}),{requestId:i,status:r,taskId:n,type:e})},En=t=>{var i,o,a,d,s,l,p;let e=(i=t.code)!=null?i:t.Code;if(typeof e=="number"&&e!==0||typeof e=="string"&&e&&e!=="0")return{code:String(e),message:(o=I(t,["msg","message","Message"]))!=null?o:"AI function task failed"};let n=(d=(a=t.BaseResp)!=null?a:t.base_resp)!=null?d:t.baseResp;if(!O(n))return;let r=(l=(s=n.StatusCode)!=null?s:n.status_code)!=null?l:n.statusCode;if(typeof r=="number"&&r!==0||typeof r=="string"&&r&&r!=="0")return{code:String(r),message:(p=I(n,["StatusMessage","status_message","statusMessage"]))!=null?p:"AI function task failed"}},An=t=>{if(!O(t))return ge(t);let e=En(t);if(e)throw h(e.code,e.message);return"data"in t&&t.data!==void 0?ge(t.data):ge(t)},dt=t=>m(void 0,null,function*(){return An(yield mn(t))}),ye=(n,...r)=>m(void 0,[n,...r],function*(t,e={}){var a,d,s;if(!((a=t.functionKey)!=null&&a.trim()))throw h(u.InvalidFunctionName,"functionKey is required");t.capability==="image"&&hn(t.input);let i=Ae(c(c({},e),Ee(e))),o=yield at(e)(ve(ot,t.functionKey,i),{body:JSON.stringify({input:(d=t.input)!=null?d:{},variables:(s=t.variables)!=null?s:{}}),credentials:"include",headers:st(i),method:"POST"});return dt(o)}),vn=(r,i,...o)=>m(void 0,[r,i,...o],function*(t,e,n={}){if(!(t!=null&&t.trim()))throw h(u.InvalidFunctionName,"functionKey is required");if(typeof e!="string"||!e.trim())throw h(u.InvalidAIFunctionTask,"taskId is required");let a=Ae(c(c({},n),Ee(n))),d=ve(ot,t,a),s=d.includes("?")?`${d.replace("?",`/${encodeURIComponent(e)}?`)}`:`${d}/${encodeURIComponent(e)}`,l=yield at(n)(s,{credentials:"include",headers:st(a),method:"GET"});return dt(l)}),it=(t,e)=>new Promise((n,r)=>{var d;let i="",o="",a=ct({functionKey:t.functionKey,messages:(d=t.messages)!=null?d:[],variables:t.variables},e);a.onMessage(s=>{typeof s.content=="string"&&(i+=s.content),!o&&typeof s.requestId=="string"&&s.requestId&&(o=s.requestId)}),a.onError(s=>{a.destroy(),r(s)}),a.onDone(()=>{a.destroy(),n({content:i,requestId:o||e.requestId||"",type:"text"})})}),bn=(n,...r)=>m(void 0,[n,...r],function*(t,e={}){var i;if(!((i=t.functionKey)!=null&&i.trim()))throw h(u.InvalidFunctionName,"functionKey is required");return t.capability==="image"||t.capability==="video"?ye(t,e):t.capability==="text"||t.capability==="vision"?it(t,e):t.input&&!t.messages?ye(t,e):it(t,e)});var U,Tn=(t={})=>{if(U)return U;if(typeof window=="undefined"||typeof document=="undefined")return()=>{};let e=window.open,n=s=>{t.onError?t.onError(s):console.warn("[Site Runtime] Unable to open link")},r=s=>{se(s).then(l=>{l.opened||n(new Error("Link was not opened"))},n)},i=s=>{try{return new URL(s,document.baseURI||window.location.href)}catch(l){return}},o=s=>{var F,L,H;if(s.defaultPrevented||(s.type==="auxclick"?s.button!==1:s.button!==0))return;let l=s.target instanceof Element?s.target:null,p=l==null?void 0:l.closest("a[href]");if(!p||p.hasAttribute("download"))return;let f=(L=(F=p.getAttribute("href"))==null?void 0:F.trim())!=null?L:"";if(!f||f.startsWith("#"))return;let T=i(f);!T||!["http:","https:"].includes(T.protocol)||((H=p.getAttribute("target"))==null?void 0:H.toLowerCase())!=="_blank"&&T.origin===window.location.origin&&!s.ctrlKey&&!s.metaKey&&!s.shiftKey&&s.button!==1||(s.preventDefault(),r(T.href))},a=(s,l,p)=>{if(s===void 0||!String(s).trim())return null;if(String(s).trim().startsWith("#"))return e.call(window,s,l,p);let f=i(String(s));return!f||!["http:","https:","mailto:","tel:"].includes(f.protocol)?null:f.origin===window.location.origin&&(l==null?void 0:l.toLowerCase())==="_self"?e.call(window,s,l,p):(r(f.href),null)};document.addEventListener("click",o,!0),document.addEventListener("auxclick",o,!0),window.open=a;let d=()=>{U===d&&(document.removeEventListener("click",o,!0),document.removeEventListener("auxclick",o,!0),window.open===a&&(window.open=e),U=void 0)};return U=d,d};export{De as SITE_RUNTIME_PROTOCOL_VERSION,ae as SiteChatbotStreamAdapter,w as SiteChatbotStreamError,g as SiteRuntimeApi,z as SiteRuntimeClient,u as SiteRuntimeErrorCode,E as SiteRuntimeEvent,j as SiteRuntimeFunction,y as SiteRuntimeInvocationError,bn as callSiteAIFunction,ye as createSiteAIFunctionTask,W as createSiteRuntimeClient,G as createSiteRuntimeFetch,Qt as fetch,qt as getCurrentUser,vn as getSiteAIFunctionTask,Tn as installLinkGuard,Bt as invokeApi,Dt as invokeHttp,ct as invokeSiteAIFunctionStream,Be as isValidSiteFunctionName,Kt as logout,se as openLink,Pr as readSiteAITextDelta,jt as requestEdit,b as siteRuntime,Vt as uploadAttachment};
|
|
1
|
+
var ut=Object.defineProperty,dt=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var ve=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var be=(t,e,n)=>e in t?ut(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,s=(t,e)=>{for(var n in e||(e={}))ve.call(e,n)&&be(t,n,e[n]);if(D)for(var n of D(e))ke.call(e,n)&&be(t,n,e[n]);return t},g=(t,e)=>dt(t,lt(e));var Te=(t,e)=>{var n={};for(var r in t)ve.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&D)for(var r of D(t))e.indexOf(r)<0&&ke.call(t,r)&&(n[r]=t[r]);return n};var m=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{u(n.next(c))}catch(l){i(l)}},a=c=>{try{u(n.throw(c))}catch(l){i(l)}},u=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,a);u((n=n.apply(t,e)).next())});import{uniqueId as oe}from"lodash-es";var X="same-origin",Ce="__internal_fetchBinaryList__",Re="__internal_cancelBinaryFetch__",xe="__internal_binaryFetchProgress__";function Q(t){return Number.isFinite(t)?Math.max(1,Math.floor(t)):4}function Z(t){return t==="omit"||t==="include"?t:X}var B=(i=>(i.IFRAME_LOAD_ERROR="iframeLoadError",i.NOT_ALLOWED_URL="notAllowedUrl",i.HANDSHAKE_TIME_OUT="handshakeTimeout",i.CHANNEL_UNAVAILABLE="channelUnavailable",i))(B||{});var C=class extends Error{constructor(n,r){super(r);this.code=n,this.name="ChannelCallbackError"}};function Fe(t){return new C(10004,`api "${t}" is not registered`)}function Pe(t){return new C(10005,`api "${t}" timed out`)}function ee(){return new C(10006,"channel has been destroyed")}function we(t){return new C(10008,`request "${t}" was superseded by a new one`)}var pt="unknown error";function Le(t){return typeof t=="object"&&t!==null}function ht(t){if(typeof t=="string"&&t)return t;if(t instanceof C&&t.message||t instanceof Error&&t.message)return t.message;if(Le(t)){let{msg:e,message:n}=t;if(typeof e=="string"&&e)return e;if(typeof n=="string"&&n)return n}return pt}function mt(t){if(t instanceof C)return t.code;if(!Le(t))return-1;let{code:e}=t;return typeof e=="string"&&e||typeof e=="number"&&Number.isFinite(e)?e:-1}function b(t){return{code:mt(t),msg:ht(t)}}function _e(t){return t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof Blob!="undefined"&&t instanceof Blob}function ft(t){return _e(t)||Object.values(t).some(e=>_e(e))}function He(t){return t&&typeof t=="object"?ft(t)?t:JSON.parse(JSON.stringify(t)):t}var gt={["iframeLoadError"]:10001,["notAllowedUrl"]:10002,["handshakeTimeout"]:10003,["channelUnavailable"]:10009};function St(t){return typeof t=="object"&&t!==null}function yt(t){if(!St(t))return!1;let{type:e}=t;return typeof e=="string"&&Object.values(B).includes(e)}function te(t){return yt(t)?{code:gt[t.type],msg:t.message||t.type}:b(t)}function ne(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var O=class{constructor(e,n){this._target=e,this._options=n}sendMsg(e,n){if(!this._target)throw new Error("target window is not found");this._target.postMessage(e,this._options.targetOrigin,n!=null?n:[])}listenMsg(e){this._eventHandler=n=>{n.source===this._options.sourceWindow&&this._options.allowedOrigins.includes(n.origin)&&e(n)},typeof window!="undefined"&&window.addEventListener("message",this._eventHandler)}destroy(){typeof window!="undefined"&&this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}};var F=class{constructor(e,n,r){e==="host"?this.channelManager=new O(n,r):e==="client"&&(this.channelManager=new O(window.parent,r))}static createInstance(e,n,r){return new F(e,n,r)}sendMsg(e,n){var r;(r=this.channelManager)==null||r.sendMsg(e,n)}listenMsg(e){var n;(n=this.channelManager)==null||n.listenMsg(e)}destroy(){var e;(e=this.channelManager)==null||e.destroy()}};var q=class{constructor(){this.requests=new Map}create(e,n,r=3e4){return this.reject(e,b(we(e))),new Promise((i,o)=>{let a=setTimeout(()=>{var u;((u=this.requests.get(e))==null?void 0:u.timeout)===a&&(this.requests.delete(e),o(b(Pe(n))))},r);this.requests.set(e,{reject:o,resolve:i,timeout:a})})}resolve(e,n){let r=this.take(e);return r?(r.resolve(n),!0):!1}reject(e,n){let r=this.take(e);return r?(r.reject(n),!0):!1}rejectAll(e){for(let n of this.requests.keys())this.reject(n,e)}take(e){let n=this.requests.get(e);if(n)return this.requests.delete(e),clearTimeout(n.timeout),n}};var re=t=>typeof t=="object"&&t!==null,At=new Set(["blockId","expectedPrefixId","id","jobId","prefixId","url"]),x=t=>{let e={};for(let[n,r]of Object.entries(t))if(!(n==="inputParams"||n==="outputParams")){if(At.has(n)){e[`${n}Present`]=!!r;continue}if(n==="error"){Object.assign(e,_(r));continue}if(n==="errorInfo"&&re(r)){e.errorType=typeof r.type=="string"?r.type:"object";continue}(typeof r=="string"||typeof r=="number"||typeof r=="boolean")&&(e[n]=r)}return e},P=t=>{let e={idPresent:!!t.id,type:t.type},n=re(t.payload)?t.payload:{};return typeof n.key=="string"&&(e.key=n.key),t.type==="callback"&&typeof n.code=="number"&&(e.callbackCode=n.code),t.type==="handshake"&&typeof n.proactive=="boolean"&&(e.proactive=n.proactive),e},ie=t=>t.type!=="invoke"&&t.type!=="callback",_=t=>{if(!re(t))return{errorType:typeof t};let e={errorType:t instanceof Error?t.name:"object"};return(typeof t.code=="number"||typeof t.code=="string")&&(e.errorCode=t.code),e};var bt=()=>{let t=Reflect.get(globalThis,"BearWebSlardarWeb");return typeof t=="function"?t:void 0},vt=t=>{let e={};for(let[n,r]of Object.entries(x(t)))typeof r=="string"||typeof r=="number"?e[n]=r:typeof r=="boolean"&&(e[n]=String(r));return e},Ne=(t,e,n,r)=>{console[e](`[base-site-channel][${t}]`,n,r)},j=(t,e,n,r={})=>{if(e==="info")return;let i=x(r),o=bt();if(!o){Ne(t,e,n,i);return}try{o("sendLog",{content:`[base-site-channel][${t}] ${n}`,extra:s({event_name:"Runtime_SiteChannel_Message",bizType:"Runtime",subType:"SiteChannel",action:"Message",channel_side:t,channel_message:n},vt(i)),level:e})}catch(a){Ne(t,e,n,g(s({},i),{slardarFallback:!0,slardarErrorType:a instanceof Error?a.name:typeof a}))}};var Ct=()=>{var n;if(typeof window=="undefined")return null;let e=((n=window.location.ancestorOrigins)==null?void 0:n[0])||document.referrer;if(!e)return null;try{return new URL(e).origin}catch(r){return null}},Rt=t=>{try{return new URL(t).origin}catch(e){return null}},se=class{constructor(e={}){this.pendingRequests=new q;this.eventMap=new Map;this.eventHandlerMap=new Map;this._msgChannel=null;this._invokeId="";this._handshakePromise=ne({type:"channelUnavailable",message:"channel handshake is not initialized"});this._handshakeResolve=null;this._handshakeReject=null;this._handshakeRetryTimes=0;this._handshakeStatus=0;this._handshakeTimeout=null;this._prefixId="";this._destroyed=!1;let n=e.hostOrigin?Rt(e.hostOrigin):null;if(this.hostOrigin=n!=null?n:Ct(),e.hostOrigin&&!n&&this.logWarn("invalid hostOrigin, fallback to parent origin"),typeof window=="undefined"||window.parent===window){this.failHandshake("invalid window context",{hasWindow:typeof window!="undefined",isTopWindow:typeof window!="undefined"?window.parent===window:!0});return}if(!this.hostOrigin){this.failHandshake("host origin unavailable");return}this._msgChannel=F.createInstance("client",window.parent,{allowedOrigins:[this.hostOrigin],sourceWindow:window.parent,targetOrigin:this.hostOrigin}),this.listeningHostMsg(),this.startHandshake()}logInfo(e,n={}){j("client","info",e,s({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},x(n)))}logWarn(e,n={}){j("client","warn",e,s({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},x(n)))}logError(e,n={}){j("client","error",e,s({hasPrefixId:!!this._prefixId,handshakeStatus:this._handshakeStatus},x(n)))}failHandshake(e,n={}){this._handshakeStatus=2,this._handshakePromise=ne({type:"channelUnavailable",message:e}),this.logError(`init failed: ${e}`,n)}sendProactiveHandshakeMsg(){var n;let e={id:oe("handshake-"),type:"handshake",payload:{proactive:!0}};this.logInfo("send proactive handshake",P(e)),(n=this._msgChannel)==null||n.sendMsg(e)}_initHandshake(){this._handshakeRetryTimes=0,clearTimeout(this._handshakeTimeout),this._handshakeStatus=0,this.logInfo("init handshake"),this._handshakePromise=new Promise((e,n)=>{this._handshakeResolve=e,this._handshakeReject=n,this._handshakeTimeout=setTimeout(()=>this.retryHandshake(n),2e3)})}startHandshake(){this._initHandshake(),this._handshakePromise.then(()=>{this._handshakeStatus=1,this.logInfo("handshake success")}).catch(e=>{this._handshakeStatus=2,this.logError("handshake failed",{error:e})}),this.sendProactiveHandshakeMsg()}retryHandshake(e){this._handshakeStatus===0&&(this._handshakeRetryTimes<5?(this.logWarn("retry handshake",{retryTimes:this._handshakeRetryTimes+1}),this.sendProactiveHandshakeMsg(),this._handshakeRetryTimes++,this._handshakeTimeout=setTimeout(()=>this.retryHandshake(e),2e3+2**this._handshakeRetryTimes)):(this.logError("handshake retry timeout",{retryTimes:this._handshakeRetryTimes}),e({type:"handshakeTimeout",message:"iframe handshake time out"})))}updateInvokeId(){this._invokeId=oe(`${this._prefixId}-invoke-`)}handleChannelMessage(e){let{data:n}=e;ie(n)&&this.logInfo("receive host message",P(n));let{type:r}=n;r==="callback"?this.handleHostCallback(n):r==="handshake"?this.handleHandshakeCallback(n):r==="invoke"?this.handleHostInvoke(n).catch(i=>{this.logError("handle host invoke error",s(s({},P(n)),_(i)))}):r==="event"&&this.handleHostEvent(n).catch(i=>{this.logError("handle host event error",s(s({},P(n)),_(i)))})}handleHostCallback(e){let{id:n,payload:r}=e,i={logId:n,key:r.key,callbackCode:r.code};if(r.code===1){if(this.pendingRequests.reject(n,r.res)){this.logWarn("api response received",i);return}}else if(this.pendingRequests.resolve(n,r.res)){this.logInfo("api response received",i);return}this.logWarn("host callback request not found",{id:n,key:r.key})}handleHostInvoke(e){return m(this,null,function*(){yield this._handshakePromise;let{id:n,payload:r}=e,{key:i,params:o,prefixId:a}=r;if(a!==this._prefixId){this.logWarn("ignore host invoke because prefixId mismatch",{id:n,key:i,prefixId:a,expectedPrefixId:this._prefixId});return}let u=this.eventMap.get(i);if(typeof u!="function"){this.logWarn("host invoke handler not found",{id:n,key:i}),this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:b(Fe(i)),code:1}});return}this.logInfo("handle host invoke",{id:n,key:i});try{let c=He(yield u(o));this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:c,code:0}}),this.logInfo("host invoke success",{id:n,key:i})}catch(c){this.logError("host invoke failed",s({id:n,key:i},_(c))),this.sendMsg2Host({id:n,type:"callback",payload:{key:i,res:b(c),code:1}})}})}handleHostEvent(e){return m(this,null,function*(){yield this._handshakePromise;let{payload:n}=e,{key:r,params:i,prefixId:o}=n;if(o!==this._prefixId){this.logWarn("ignore host event because prefixId mismatch",{key:r,prefixId:o,expectedPrefixId:this._prefixId});return}let a=this.eventHandlerMap.get(r);if(!(a!=null&&a.size)){this.logWarn("host event handler not found",{key:r});return}this.logInfo("handle host event",{key:r,handlerCount:a.size}),yield Promise.allSettled(Array.from(a,u=>u(i)))})}handleHandshakeCallback(e){var o,a;let{id:n,payload:r}=e;this._prefixId=(o=r==null?void 0:r.prefixId)!=null?o:"",this.logInfo("receive handshake callback",{id:n,prefixId:this._prefixId}),(a=this._handshakeResolve)==null||a.call(this);let i={id:n,type:"handshake",payload:{proactive:!1,info:{isHandshakeSuccess:!0}}};this.sendMsg2Host(i)}listeningHostMsg(){var e;this.logInfo("start listening host messages"),(e=this._msgChannel)==null||e.listenMsg(this.handleChannelMessage.bind(this))}sendMsg2Host(e,n){var r;ie(e)&&this.logInfo("send message to host",P(e)),(r=this._msgChannel)==null||r.sendMsg(e,n)}invokeApi(e,n,r){return m(this,null,function*(){if(this._destroyed)return Promise.reject(b(ee()));try{yield this._handshakePromise}catch(a){return this.logError("invoke api blocked by handshake error",s({key:e},_(a))),Promise.reject(te(a))}this._invokeId||this.updateInvokeId();let i=this._invokeId,o=this.pendingRequests.create(i,e,r==null?void 0:r.timeoutMs);return this.logInfo("api request sent",{key:e,logId:i}),this.sendMsg2Host({type:"invoke",id:i,payload:{key:e,params:n,prefixId:this._prefixId}}),this.updateInvokeId(),o})}registerApi(e,n){if(this.eventMap.has(e)){this.logWarn("register api ignored because key already exists",{key:e});return}this.eventMap.set(e,n),this.logInfo("register api",{key:e})}emitEvent(e,n){return m(this,null,function*(){try{yield this._handshakePromise}catch(r){return this.logError("emit event blocked by handshake error",s({key:e},_(r))),Promise.reject(te(r))}this.logInfo("emit event",{key:e}),this.sendMsg2Host({type:"event",id:oe(`${this._prefixId}-event-`),payload:{key:e,params:n,prefixId:this._prefixId}})})}fetchBinaryList(e){return m(this,null,function*(){var n;return this.logInfo("invoke built-in binary fetch",{status:"start",itemCount:e.items.length,concurrency:Q(e.concurrency),credentials:Z(e.credentials)}),this.invokeApi(Ce,{items:e.items,concurrency:Q(e.concurrency),credentials:Z((n=e.credentials)!=null?n:X)})})}subscribeBinaryFetchProgress(e){return this.subscribeEvent(xe,e)}cancelBinaryFetch(e){return m(this,null,function*(){this.logInfo("invoke built-in binary fetch cancel",{jobId:e,status:"cancel-requested"}),yield this.invokeApi(Re,{jobId:e})})}destroy(){var n,r;if(this._destroyed)return;this._destroyed=!0,this.logInfo("destroy client"),(n=this._msgChannel)==null||n.destroy(),clearTimeout(this._handshakeTimeout);let e=b(ee());(r=this._handshakeReject)==null||r.call(this,{type:"handshakeTimeout",message:e.msg}),this.pendingRequests.rejectAll(e),this.eventMap.clear(),this.eventHandlerMap.clear()}subscribeEvent(e,n){var i;let r=(i=this.eventHandlerMap.get(e))!=null?i:new Set;return r.add(n),this.eventHandlerMap.set(e,r),this.logInfo("subscribe event",{key:e,handlerCount:r.size}),()=>this.unsubscribeEvent(e,n)}unsubscribeEvent(e,n){let r=this.eventHandlerMap.get(e);if(!r){this.logWarn("unsubscribe event ignored because key is not subscribed",{key:e});return}if(!n){this.eventHandlerMap.delete(e),this.logInfo("unsubscribe all event handlers",{key:e,handlerCount:0});return}r.delete(n),r.size===0&&this.eventHandlerMap.delete(e),this.logInfo("unsubscribe event",{key:e,handlerCount:r.size})}},xt=t=>new se(t),M=xt();var Ue="site.v1",S={AIFunctionStreamClose:"site.v1.ai.function.stream.close",AIFunctionStreamOpen:"site.v1.ai.function.stream.open",AttachmentUpload:"site.v1.attachment.upload",AttachmentUploadCancel:"site.v1.attachment.upload.cancel",FunctionInvoke:"site.v1.function.invoke",HttpRequest:"site.v1.http.request",HttpRequestCancel:"site.v1.http.request.cancel",OpenLink:"site.v1.link.open",RuntimeContext:"site.v1.runtime.context",StreamClose:"site.v1.chatbot.stream.close",StreamOpen:"site.v1.chatbot.stream.open"},A={AIFunctionStreamDone:"site.v1.ai.function.stream.done",AIFunctionStreamError:"site.v1.ai.function.stream.error",AIFunctionStreamMessage:"site.v1.ai.function.stream.message",AttachmentUploadProgress:"site.v1.attachment.upload.progress",LifecycleLoadFailed:"site.v1.lifecycle.load-failed",LifecycleReady:"site.v1.lifecycle.ready",ModeChanged:"site.v1.runtime.mode-changed",StreamError:"site.v1.chatbot.stream.error",StreamMessage:"site.v1.chatbot.stream.message"},K={GetCurrentUser:"function.runtime.getCurrentUser",Logout:"function.runtime.logout",RequestEdit:"function.runtime.requestEdit"},d={AttachmentUnavailable:"ATTACHMENT_UNAVAILABLE",AttachmentUploadCanceled:"ATTACHMENT_UPLOAD_CANCELED",AttachmentUploadFailed:"ATTACHMENT_UPLOAD_FAILED",AttachmentUploadStalled:"ATTACHMENT_UPLOAD_STALLED",ChannelDestroyed:"CHANNEL_DESTROYED",FunctionNotAllowed:"FUNCTION_NOT_ALLOWED",FunctionRequestFailed:"FUNCTION_REQUEST_FAILED",InvalidAIFunctionTask:"INVALID_AI_FUNCTION_TASK",HttpRequestFailed:"HTTP_REQUEST_FAILED",HttpResponseTypeUnsupported:"HTTP_RESPONSE_TYPE_UNSUPPORTED",HttpRequestCanceled:"HTTP_REQUEST_CANCELED",InvalidAttachmentTarget:"INVALID_ATTACHMENT_TARGET",InvalidFunctionName:"INVALID_FUNCTION_NAME",InvalidHttpHeader:"INVALID_HTTP_HEADER",InvalidHttpUrl:"INVALID_HTTP_URL",InvalidLinkUrl:"INVALID_LINK_URL",LinkCheckUnavailable:"LINK_CHECK_UNAVAILABLE",LogoutFailed:"LOGOUT_FAILED",ProtocolMismatch:"PROTOCOL_MISMATCH",RequestTimeout:"REQUEST_TIMEOUT",StreamDisconnected:"STREAM_DISCONNECTED",StreamHealthTimeout:"STREAM_HEALTH_TIMEOUT",StreamInterrupted:"STREAM_INTERRUPTED",StreamOpenFailed:"STREAM_OPEN_FAILED",StreamSeqGap:"STREAM_SEQ_GAP",StreamUnavailable:"STREAM_UNAVAILABLE",UnsupportedHttpBody:"UNSUPPORTED_HTTP_BODY",UserInfoUnavailable:"USER_INFO_UNAVAILABLE"},wr=t=>{var e,n;return{answer:(e=t.content)!=null?e:"",reasoning:(n=t.reasoningContent)!=null?n:""}},_t=/^function(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/,De=t=>_t.test(t);var Mt=0,Be=(i,o)=>m(void 0,[i,o],function*(t,{init:e,url:n,signal:r}){if((e==null?void 0:e.responseType)!==void 0&&!["text","arrayBuffer"].includes(e.responseType))throw new E(d.HttpResponseTypeUnsupported,"Unsupported HTTP response type; use text or arrayBuffer");let a=()=>new DOMException("The operation was aborted","AbortError");if(r!=null&&r.aborted)throw a();let u=typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`http-${Date.now()}-${++Mt}`,c=()=>{},l=new Promise((p,f)=>{c=()=>{f(a()),t.invokeApi(S.HttpRequestCancel,{requestId:u}).catch(()=>{})}});r==null||r.addEventListener("abort",c,{once:!0});try{let p=yield Promise.race([t.invokeApi(S.HttpRequest,{requestId:u,url:n,init:e},{timeoutMs:(e==null?void 0:e.timeoutMs)===void 0?void 0:Math.min(e.timeoutMs,6e4)+1e3}),l]);if((e==null?void 0:e.responseType)==="arrayBuffer"&&(p.bodyType!=="arrayBuffer"||!(p.body instanceof ArrayBuffer)))throw new E(d.HttpResponseTypeUnsupported,"The current host does not support binary HTTP responses; upgrade the host");return new Response([204,205,304].includes(p.status)?null:p.body,{headers:p.headers,status:p.status,statusText:p.statusText})}finally{r==null||r.removeEventListener("abort",c)}});var E=class extends Error{constructor(n,r){super(r);this.code=n;this.name="SiteRuntimeInvocationError"}},qe=t=>typeof t=="string"&&t.trim().length>0,Ft=t=>typeof File!="undefined"&&t instanceof File,je=12e4,Pt=2*60*60*1e3,Ke=0,wt=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Ke+=1,`site-upload-${Ke}`),Lt=t=>typeof t=="object"&&t!==null&&"code"in t?t.code:void 0,Ht=t=>{if(t instanceof Error&&t.message)return t.message;if(typeof t=="object"&&t!==null){if("message"in t&&typeof t.message=="string")return t.message;if("msg"in t&&typeof t.msg=="string")return t.msg}return String(t)},Nt=new Set([d.AttachmentUnavailable,d.AttachmentUploadCanceled,d.AttachmentUploadFailed,d.AttachmentUploadStalled,d.InvalidAttachmentTarget]),Ot=(t,e)=>{if(t instanceof E)return t;let n=Lt(t),r=Ht(t);return String(n)===String(10004)?new E(d.AttachmentUnavailable,r):typeof n=="string"&&Nt.has(n)?new E(n,r):new E(e,r)},V=(t,e,n)=>m(void 0,null,function*(){if(!De(e))throw new E(d.InvalidFunctionName,"Function name must be a dot-separated path beginning with function (for example, function.orders.list)");return t.invokeApi(S.FunctionInvoke,{functionName:e,params:n})}),z=class{constructor(e){this.channel=e;this.getChannel=()=>this.channel;this.uploadAttachment=r=>m(this,null,function*(){var i=r,{onProgress:e}=i,n=Te(i,["onProgress"]);if(!qe(n==null?void 0:n.baseToken)||!qe(n==null?void 0:n.tableId)||!Ft(n==null?void 0:n.file))throw new E(d.InvalidAttachmentTarget,"Attachment upload requires nonempty baseToken and tableId values and a File");let o=wt(),a,u=()=>{},c=()=>{this.channel.invokeApi(S.AttachmentUploadCancel,{uploadId:o}).catch(()=>{})},l=new Promise((p,f)=>{let k=()=>{clearTimeout(a),a=setTimeout(()=>{c(),f(new E(d.AttachmentUploadStalled,`Attachment upload made no progress for more than ${je/1e3} seconds`))},je)};u=this.channel.subscribeEvent(A.AttachmentUploadProgress,T=>{(T==null?void 0:T.uploadId)===o&&(k(),Promise.resolve(e==null?void 0:e(T)).catch(()=>{console.error("[base-site-channel][runtime] Attachment progress callback failed")}))})});try{return yield Promise.race([this.channel.invokeApi(S.AttachmentUpload,g(s({},n),{uploadId:o}),{timeoutMs:Pt}),l])}catch(p){throw Ot(p,d.AttachmentUploadFailed)}finally{clearTimeout(a),u()}});this.invokeHttp=e=>Be(this.channel,e);this.invokeApi=(e,n)=>V(this.channel,e,n);this.openLink=e=>this.channel.invokeApi(S.OpenLink,{url:e});this.getRuntimeContext=()=>this.channel.invokeApi(S.RuntimeContext,void 0);this.getCurrentUser=()=>V(this.channel,K.GetCurrentUser,void 0);this.logout=()=>V(this.channel,K.Logout,void 0);this.requestEdit=()=>V(this.channel,K.RequestEdit,void 0);this.ready=()=>this.channel.emitEvent(A.LifecycleReady,{protocolVersion:Ue});this.reportLoadFailed=e=>this.channel.emitEvent(A.LifecycleLoadFailed,{code:e});this.subscribeModeChanged=e=>this.channel.subscribeEvent(A.ModeChanged,({mode:n})=>e(n))}},W=(t=M)=>new z(t),v=W(),Ut=v.invokeHttp,Dt=v.invokeApi,Bt=v.getCurrentUser,qt=v.logout,jt=v.requestEdit,Kt=v.uploadAttachment,ae=v.openLink;var Vt=new Set(["open.feishu.cn","open.feishu-pre.cn","open.feishu-boe.cn"]),Ve="/open-apis",zt="/base-site/api/openapi",Wt=new Set(["DELETE","GET","PATCH","POST","PUT"]),Gt=()=>(typeof globalThis.location=="undefined"?"":globalThis.location.pathname).replace(/^\/+/,"").startsWith("preview")?[["x-project-env","preview"]]:[],$t=t=>{if(typeof Request!="undefined"&&t instanceof Request)throw new TypeError("Site Runtime fetch does not accept a Request object; pass a URL instead");let e=String(t);if(e.startsWith("//"))throw new TypeError("Site Runtime fetch does not accept a scheme-relative URL");if(e.startsWith("/"))return e;let n=new URL(e);if(Vt.has(n.hostname)&&n.pathname.startsWith(Ve))return`${zt}${n.pathname.slice(Ve.length)}${n.search}`;throw new TypeError("Site Runtime fetch accepts only relative business paths or supported Feishu OpenAPI URLs")},Yt=t=>{let e=new Headers(t);Gt().forEach(([r,i])=>e.set(r,i));let n={};return e.forEach((r,i)=>{n[i]=r}),n},Jt=(t,e)=>{var r,i,o;let n=(i=(r=t==null?void 0:t.method)==null?void 0:r.toUpperCase())!=null?i:"GET";if(!Wt.has(n))throw new TypeError(`Site Runtime fetch does not support the ${n} method`);if((t==null?void 0:t.body)!==void 0&&t.body!==null&&typeof t.body!="string")throw new TypeError("Site Runtime fetch requires a string request body");if((o=t==null?void 0:t.signal)!=null&&o.aborted)throw new DOMException("The operation was aborted","AbortError");return{body:typeof(t==null?void 0:t.body)=="string"?t.body:void 0,headers:Yt(t==null?void 0:t.headers),method:n,timeoutMs:e}},G=(t=v,e)=>(n,r)=>t.invokeHttp(g(s({init:Jt(r,e)},r!=null&&r.signal?{signal:r.signal}:{}),{url:$t(n)})),Xt=G();var ze=0,Qt=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(ze+=1,`site-chatbot-${ze}`),$=(t,e)=>{try{t==null||t(e)}catch(n){console.error("[base-site-channel][runtime] Chatbot callback failed")}},w=class extends Error{constructor(n,r){super(`Chatbot stream error: ${n}`);this.code=n;this.retryable=r;this.name="SiteChatbotStreamError"}},ce=class{constructor(e){this.options=e;this.init=e=>{this.destroy();let n=Qt(),r={lastSeq:0,subscriptionId:n,unsubscribeError:()=>{},unsubscribeMessage:()=>{}};r.unsubscribeMessage=this.channel.subscribeEvent(A.StreamMessage,i=>{i.subscriptionId!==n||i.seq<=r.lastSeq||(i.seq>r.lastSeq+1&&$(this.onErrorCallback,new w(d.StreamSeqGap,!0)),r.lastSeq=i.seq,$(this.onMessageCallback,i.data))}),r.unsubscribeError=this.channel.subscribeEvent(A.StreamError,i=>{i.subscriptionId===n&&$(this.onErrorCallback,new w(i.code,i.retryable))}),this.current=r,this.channel.invokeApi(S.StreamOpen,{chatbotId:this.options.chatbotId,subscriptionId:n,threadId:e}).catch(()=>{var i;((i=this.current)==null?void 0:i.subscriptionId)===n&&$(this.onErrorCallback,new w(d.StreamOpenFailed,!0))})};this.onMessage=e=>{this.onMessageCallback=e};this.onError=e=>{this.onErrorCallback=e};this.destroy=()=>{let e=this.current;e&&(e.unsubscribeMessage(),e.unsubscribeError(),this.current=void 0,this.channel.invokeApi(S.StreamClose,{subscriptionId:e.subscriptionId}).catch(()=>console.error("[base-site-channel][runtime] Chatbot stream close failed")))};var n;this.channel=(n=e.channel)!=null?n:M}};var de="prod",We=0,Ye=()=>typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(We+=1,`site-ai-fn-${We}`),y=(t,e)=>{try{t==null||t(e)}catch(n){console.error("[base-site-channel][runtime] AI function callback failed")}},h=(t,e)=>{let n=new Error(e||`AI function error: ${t}`);return n.name="SiteAIFunctionError",n.code=t,n},Je=()=>h(d.InvalidHttpUrl,"siteToken is required to invoke site AI function"),le=()=>typeof window!="undefined"&&window.parent!==window,pe=t=>{if(typeof queueMicrotask=="function"){queueMicrotask(t);return}Promise.resolve().then(t)},he=t=>{let e={data:[],event:"message"};for(let n of t.split(/\r?\n/))n.startsWith("event:")?e.event=n.slice(6).trim():n.startsWith("data:")&&e.data.push(n.slice(5).trimStart());return e},ue=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="string")return r}},Xe=t=>{let e=[t];if(t&&typeof t=="object"){let n=t;e.push(n.response,n.data)}for(let n of e){if(!n||typeof n!="object")continue;let r=ue(n,["request_id","requestId","RequestID","id"]);if(r)return r}},Qe=t=>{if(!t||typeof t!="object")return{};let e=t;return{content:ue(e,["content","text","answer"]),reasoningContent:ue(e,["reasoning_content","reasoningContent","reasoning"])}},Zt=t=>{if(!t||typeof t!="object")return{};let e=t.choices;if(!Array.isArray(e))return{};for(let n of e){let r=n.delta,{content:i,reasoningContent:o}=Qe(r);if(i!==void 0||o!==void 0)return{content:i,reasoningContent:o}}return{}},Ze=t=>{var n;let e=[t];if(t&&typeof t=="object"){let r=t;e.push(r.response,r.data)}for(let r of e){let i=Zt(r);if(i.content!==void 0||i.reasoningContent!==void 0)return i;let o=Qe(r&&typeof r=="object"&&(n=r.delta)!=null?n:r);if(o.content!==void 0||o.reasoningContent!==void 0)return o}return{}},Y=t=>{try{let e=JSON.parse(t),n=Ze(e),r=Xe(e);return g(s(s(s({},n.content!==void 0?{content:n.content}:{}),n.reasoningContent!==void 0?{reasoningContent:n.reasoningContent}:{}),r?{requestId:r}:{}),{raw:e})}catch(e){return{content:t,raw:t}}},et=t=>{if(typeof t=="string")return Y(t);let e=Ze(t),n=Xe(t),r=t&&typeof t=="object"&&"raw"in t?t.raw:t;return g(s(s(s({},e.content!==void 0?{content:e.content}:{}),e.reasoningContent!==void 0?{reasoningContent:e.reasoningContent}:{}),n?{requestId:n}:{}),{raw:r})},en=t=>{var e,n,r,i;try{let o=JSON.parse(t),a=(e=o.Code)!=null?e:o.code,u=(n=o.Message)!=null?n:o.message,c=typeof a=="string"||typeof a=="number"?String(a):"STREAM_FAILED";return Object.assign(h(c||"STREAM_FAILED",typeof u=="string"&&u?u:t),{issues:(r=o.Errors)!=null?r:o.errors,retryable:(i=o.Retryable)!=null?i:o.retryable})}catch(o){return h("STREAM_FAILED",t)}},me=()=>({text:""}),tn=t=>/(^|\n)(data|event|id|retry):/.test(t),Ge=t=>{if(!t||t==="[DONE]")return!!t;try{return JSON.parse(t),!0}catch(e){return!1}},nn=t=>{if(t){if(tn(t)){let n=he(t).data.join(`
|
|
2
|
+
`);return Ge(n)?n:void 0}return Ge(t)?t:void 0}},fe=(t,e)=>{var o;t.text+=e;let n=t.text.split(/\r?\n\r?\n/);t.text=(o=n.pop())!=null?o:"";let r=n.map(a=>he(a).data.join(`
|
|
3
|
+
`)).filter(Boolean),i=nn(t.text);return i!==void 0&&(r.push(i),t.text=""),r},rn=(t,e)=>t==="[DONE]"?(y(e.onDone,void 0),!0):(y(e.onMessage,Y(t)),!1),$e=(t,e,n)=>{let r=he(t);if(r.data.length===0)return!1;let i=r.data.join(`
|
|
4
|
+
`);try{let o=JSON.parse(i);o&&typeof o.Event=="string"&&typeof o.Data=="string"&&(r={event:o.Event,data:[o.Data]},i=o.Data)}catch(o){}if(r.event==="error")return y(n.onError,en(i)),!0;for(let o of fe(e,i))if(rn(o,n))return!0;return!1},tt=(t,e)=>m(void 0,null,function*(){var a;if(!t.body)throw h(d.StreamUnavailable,"SSE body missing");let n=t.body.getReader(),r=new TextDecoder,i=me(),o="";try{for(;;){let{done:u,value:c}=yield n.read();o+=r.decode(c,{stream:!u});let l=o.split(/\r?\n\r?\n/);o=(a=l.pop())!=null?a:"";for(let p of l)if($e(p,i,e))return;if(u){if(o&&$e(o,i,e))return;y(e.onError,h(d.StreamInterrupted,"SSE stream ended without [DONE]"));return}}}finally{yield n.cancel().catch(()=>{}),n.releaseLock()}}),ge=()=>{var n;let t=typeof globalThis.location=="undefined"?"":globalThis.location.pathname,e=/^\/?(preview\/)?app\/([^/]+)(\/|$)/.exec(t);return e?{env:e[1]?"preview":de,siteToken:decodeURIComponent((n=e[2])!=null?n:"")}:{}},nt=(t,e,n)=>{if(!t.startsWith("/")||t.startsWith("//"))throw h(d.InvalidHttpUrl,"AI function endpoint must be a same-origin relative path");let r=t.replace("{siteToken}",encodeURIComponent(e.siteToken)).replace(":token",encodeURIComponent(e.siteToken)).replace("{functionKey}","").replace(":function_key",""),i=new URL(r,"https://base.site");if(i.searchParams.set("env",e.env),n)for(let[o,a]of Object.entries(n))i.searchParams.set(o,a);return`${i.pathname}${i.search}`};var on="/space/api/bitable/streaming/site/v1/:token/functions/:function_key/invoke",sn="/space/api/bitable/site/v1/:token/functions/:function_key/invoke",an="/space/api/bitable/site/v1/:token/functions/:function_key/tasks",cn=6e4,un=/^([1-9][0-9]{1,4})x([1-9][0-9]{1,4})$/i,dn=3686400,ln=16777216,pn=14,J=t=>{if("params"in t&&"variables"in t)throw h("800004006","params and deprecated variables are mutually exclusive");let e="params"in t?t.params:t.variables;return e===void 0?{}:e},hn=t=>{let e=t.trim().replace("\xD7","x");if(/^[234]K$/i.test(e))return!0;let n=un.exec(e);if(!n)return!1;let r=Number(n[1]),i=Number(n[2]),o=r*i;return o>=dn&&o<=ln&&r<=i*16&&i<=r*16},mn=t=>{if(!t)return;let e=typeof t.image=="string"?[t.image]:t.image;if(e&&(e.length<1||e.length>pn||e.some(n=>!n.trim())))throw h(d.InvalidAIFunctionTask,"input.image must contain 1 to 14 non-empty strings");if(t.size!==void 0&&t.size.trim()&&!hn(t.size))throw h(d.InvalidAIFunctionTask,"input.size must follow the Seedream 5.0 lite size limits")},rt=t=>{var n;let e=(n=t.siteToken)==null?void 0:n.trim();return s(s(s({},t.env?{env:t.env}:{}),t.requestId?{requestId:t.requestId}:{}),e?{siteToken:e}:{})},Ie=t=>{var r,i,o;let e=ge(),n=((r=t.siteToken)==null?void 0:r.trim())||e.siteToken;if(!n)throw Je();return{env:(o=(i=t.env)!=null?i:e.env)!=null?o:de,requestId:t.requestId,siteToken:n}},Ee=(t,e,n)=>nt(t.replace(":function_key",encodeURIComponent(e)),n),it=t=>g(s({},t.requestId?{"X-Request-Id":t.requestId}:{}),{Accept:"application/json","Content-Type":"application/json"}),ot=t=>{var e;return!t.channel&&!le()?globalThis.fetch:G(W((e=t.channel)!=null?e:M),cn)},Se=class{constructor(e,n){this.params=e;this.context=n;this.callbacks={};this.controller=new AbortController;this.closed=!1;this.onMessage=e=>{this.callbacks.onMessage=e};this.onError=e=>{this.callbacks.onError=e};this.onDone=e=>{this.callbacks.onDone=e};this.destroy=()=>{this.closed||(this.closed=!0,this.controller.abort())};pe(()=>{this.start()})}start(){return m(this,null,function*(){if(!this.closed)try{let e=yield fetch(Ee(on,this.params.functionKey,this.context),{body:JSON.stringify({messages:this.params.messages,params:J(this.params)}),credentials:"include",headers:g(s({},this.context.requestId?{"X-Request-Id":this.context.requestId}:{}),{Accept:"text/event-stream","Content-Type":"application/json"}),method:"POST",signal:this.controller.signal});if(!e.ok)throw h("HTTP_ERROR",`${e.status} ${e.statusText}`);yield tt(e,{onMessage:n=>{this.closed||y(this.callbacks.onMessage,n)},onError:n=>{this.closed||y(this.callbacks.onError,n)},onDone:()=>{this.closed||y(this.callbacks.onDone,void 0)}})}catch(e){this.closed||y(this.callbacks.onError,e instanceof Error?e:h("STREAM_FAILED"))}})}},ye=class{constructor(e){this.options=e;this.closed=!1;this.onMessage=e=>{this.onMessageCallback=e};this.onError=e=>{this.onErrorCallback=e};this.onDone=e=>{this.onDoneCallback=e};this.destroy=()=>{this.closed=!0;let e=this.current;e&&(this.cleanup(),this.channel.invokeApi(S.AIFunctionStreamClose,{subscriptionId:e.subscriptionId}).catch(()=>console.error("[base-site-channel][runtime] AI function stream close failed")))};var n;this.channel=(n=e.channel)!=null?n:M,pe(()=>this.init())}init(){if(this.closed)return;this.cleanup();let e=Ye(),n={lastSeq:0,subscriptionId:e,unsubscribeDone:()=>{},unsubscribeError:()=>{},unsubscribeMessage:()=>{},upstream:me()};n.unsubscribeMessage=this.channel.subscribeEvent(A.AIFunctionStreamMessage,i=>this.handleMessage(i,n)),n.unsubscribeError=this.channel.subscribeEvent(A.AIFunctionStreamError,i=>this.handleError(i,e)),n.unsubscribeDone=this.channel.subscribeEvent(A.AIFunctionStreamDone,i=>this.handleDone(i,e)),this.current=n;let r=s(s(s({functionKey:this.options.params.functionKey,messages:this.options.params.messages,subscriptionId:e,params:J(this.options.params)},this.options.context.env?{env:this.options.context.env}:{}),this.options.context.requestId?{requestId:this.options.context.requestId}:{}),this.options.context.siteToken?{siteToken:this.options.context.siteToken}:{});this.channel.invokeApi(S.AIFunctionStreamOpen,r).catch(()=>{var i;((i=this.current)==null?void 0:i.subscriptionId)===e&&(y(this.onErrorCallback,h(d.StreamOpenFailed)),this.destroy())})}handleMessage(e,n){if(e.subscriptionId===n.subscriptionId&&!(e.seq<=n.lastSeq)){if(e.seq>n.lastSeq+1){y(this.onErrorCallback,h(d.StreamSeqGap)),this.destroy();return}if(n.lastSeq=e.seq,typeof e.data!="string"){y(this.onMessageCallback,et(e.data));return}fe(n.upstream,e.data).forEach(r=>{r!=="[DONE]"&&y(this.onMessageCallback,Y(r))})}}handleError(e,n){e.subscriptionId===n&&(y(this.onErrorCallback,Object.assign(h(e.code,e.message),{issues:e.issues,retryable:e.retryable})),this.cleanup())}handleDone(e,n){e.subscriptionId===n&&(y(this.onDoneCallback,void 0),this.cleanup())}cleanup(){let e=this.current;e&&(e.unsubscribeMessage(),e.unsubscribeError(),e.unsubscribeDone(),this.current=void 0)}},fn=(t,e={})=>{var r;if(!((r=t.functionKey)!=null&&r.trim()))throw h(d.InvalidFunctionName,"functionKey is required");J(t);let n=s(s({},ge()),rt(e));return e.channel||le()?new ye({channel:e.channel,context:n,params:t}):new Se(t,Ie(e))},st=t=>m(void 0,null,function*(){if(!t.ok){let e=yield t.text().catch(()=>"");throw h("HTTP_ERROR",`${t.status} ${t.statusText} ${e}`)}try{return yield t.json()}catch(e){throw h(d.InvalidAIFunctionTask,"AI function task response is invalid")}}),R=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gn=t=>t==="cancelled"||t==="failed"||t==="queued"||t==="running"||t==="succeeded",I=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="string"&&r.trim())return r}},Sn=(t,e)=>{for(let n of e){let r=t[n];if(typeof r=="number"&&Number.isFinite(r))return r}},yn=t=>{let e=I(t,["capabilityType","capability_type","CapabilityType"]);return e==="image"||e==="video"?e:void 0},In=t=>{if(Array.isArray(t))return t.filter(R).map(e=>{var o;let n=I(e,["size","Size"]),r=I(e,["token","Token"]),i=I(e,["url","URL"]);return s(s(s({safetyStatus:(o=I(e,["safetyStatus","safety_status","SafetyStatus"]))!=null?o:""},n?{size:n}:{}),r?{token:r}:{}),i?{url:i}:{})})},En=t=>{var i,o;if(!R(t))return;let e=(o=(i=t.durationSeconds)!=null?i:t.duration_seconds)!=null?o:t.DurationSeconds,n=I(t,["token","Token"]),r=I(t,["url","URL"]);return s(s(s({},typeof e=="number"?{durationSeconds:e}:{}),n?{token:n}:{}),r?{url:r}:{})},Ae=t=>{var f,k,T,L,H,N;if(!R(t))throw h(d.InvalidAIFunctionTask,"AI function task response is invalid");let e=I(t,["type","Type"]),n=I(t,["taskId","task_id","TaskID"]),r=(f=t.status)!=null?f:t.Status;if(e!=="image_task"&&e!=="video_task"||!n||!gn(r))throw h(d.InvalidAIFunctionTask,"AI function task response is invalid");let i=(k=I(t,["requestId","request_id","RequestID"]))!=null?k:"",o=Sn(t,["progress","Progress"]),a=yn(t),u=I(t,["errCode","err_code","ErrCode"]),c=I(t,["errMessage","err_message","ErrMessage"]),l=In((L=(T=t.imageAssets)!=null?T:t.image_assets)!=null?L:t.ImageAssets),p=En((N=(H=t.videoAsset)!=null?H:t.video_asset)!=null?N:t.VideoAsset);return g(s(s(s(s(s(s({},a?{capabilityType:a}:{}),u?{errCode:u}:{}),c?{errMessage:c}:{}),l?{imageAssets:l}:{}),o!==void 0?{progress:o}:{}),p?{videoAsset:p}:{}),{requestId:i,status:r,taskId:n,type:e})},An=t=>{var i,o,a,u,c,l,p;let e=(i=t.code)!=null?i:t.Code;if(typeof e=="number"&&e!==0||typeof e=="string"&&e&&e!=="0")return{code:String(e),message:(o=I(t,["msg","message","Message"]))!=null?o:"AI function task failed"};let n=(u=(a=t.BaseResp)!=null?a:t.base_resp)!=null?u:t.baseResp;if(!R(n))return;let r=(l=(c=n.StatusCode)!=null?c:n.status_code)!=null?l:n.statusCode;if(typeof r=="number"&&r!==0||typeof r=="string"&&r&&r!=="0")return{code:String(r),message:(p=I(n,["StatusMessage","status_message","statusMessage"]))!=null?p:"AI function task failed"}},at=t=>{var n,r;if(!R(t))return t;let e=An(t);if(e){let i=R(t.data)?(n=t.data.error)!=null?n:t.data:t,o=R(i)?(r=i.errors)!=null?r:i.issues:void 0;throw Object.assign(h(e.code,e.message),s({details:i},Array.isArray(o)?{issues:o}:{}))}return"data"in t&&t.data!==void 0?t.data:t},bn=t=>m(void 0,null,function*(){return Ae(at(yield st(t)))}),vn=(n,...r)=>m(void 0,[n,...r],function*(t,e={}){let i=yield ct(t,e,!0);return Ae(i)}),kn=(r,i,...o)=>m(void 0,[r,i,...o],function*(t,e,n={}){if(!(t!=null&&t.trim()))throw h(d.InvalidFunctionName,"functionKey is required");if(typeof e!="string"||!e.trim())throw h(d.InvalidAIFunctionTask,"taskId is required");let a=Ie(s(s({},n),rt(n))),u=Ee(an,t,a),c=u.includes("?")?`${u.replace("?",`/${encodeURIComponent(e)}?`)}`:`${u}/${encodeURIComponent(e)}`,l=yield ot(n)(c,{credentials:"include",headers:it(a),method:"GET",signal:n.signal});return bn(l)}),ct=(t,e,n=!1)=>m(void 0,null,function*(){var u;if(!((u=t.functionKey)!=null&&u.trim()))throw h(d.InvalidFunctionName,"functionKey is required");let r=J(t);t.capability==="image"&&mn(t.input);let i=g(s(s(s({},t.input!==void 0?{input:t.input}:{}),t.messages!==void 0?{messages:t.messages}:{}),(n||t.capability==="image"||t.capability==="video")&&t.input===void 0?{input:{}}:{}),{params:r}),o=Ie(e),a=yield ot(e)(Ee(sn,t.functionKey,o),{body:JSON.stringify(i),credentials:"include",headers:it(o),method:"POST",signal:e.signal});return at(yield st(a))}),Tn=(n,...r)=>m(void 0,[n,...r],function*(t,e={}){let i=yield ct(t,e);return R(i)&&i.type==="text"&&typeof i.content=="string"&&typeof i.requestId=="string"?s({type:"text",content:i.content,requestId:i.requestId},typeof i.firstTokenMs=="number"?{firstTokenMs:i.firstTokenMs}:{}):Ae(i)});var U,Cn=(t={})=>{if(U)return U;if(typeof window=="undefined"||typeof document=="undefined")return()=>{};let e=window.open,n=c=>{t.onError?t.onError(c):console.warn("[Site Runtime] Unable to open link")},r=c=>{ae(c).then(l=>{l.opened||n(new Error("Link was not opened"))},n)},i=c=>{try{return new URL(c,document.baseURI||window.location.href)}catch(l){return}},o=c=>{var L,H,N;if(c.defaultPrevented||(c.type==="auxclick"?c.button!==1:c.button!==0))return;let l=c.target instanceof Element?c.target:null,p=l==null?void 0:l.closest("a[href]");if(!p||p.hasAttribute("download"))return;let f=(H=(L=p.getAttribute("href"))==null?void 0:L.trim())!=null?H:"";if(!f||f.startsWith("#"))return;let k=i(f);!k||!["http:","https:"].includes(k.protocol)||((N=p.getAttribute("target"))==null?void 0:N.toLowerCase())!=="_blank"&&k.origin===window.location.origin&&!c.ctrlKey&&!c.metaKey&&!c.shiftKey&&c.button!==1||(c.preventDefault(),r(k.href))},a=(c,l,p)=>{if(c===void 0||!String(c).trim())return null;if(String(c).trim().startsWith("#"))return e.call(window,c,l,p);let f=i(String(c));return!f||!["http:","https:","mailto:","tel:"].includes(f.protocol)?null:f.origin===window.location.origin&&(l==null?void 0:l.toLowerCase())==="_self"?e.call(window,c,l,p):(r(f.href),null)};document.addEventListener("click",o,!0),document.addEventListener("auxclick",o,!0),window.open=a;let u=()=>{U===u&&(document.removeEventListener("click",o,!0),document.removeEventListener("auxclick",o,!0),window.open===a&&(window.open=e),U=void 0)};return U=u,u};export{Ue as SITE_RUNTIME_PROTOCOL_VERSION,ce as SiteChatbotStreamAdapter,w as SiteChatbotStreamError,S as SiteRuntimeApi,z as SiteRuntimeClient,d as SiteRuntimeErrorCode,A as SiteRuntimeEvent,K as SiteRuntimeFunction,E as SiteRuntimeInvocationError,Tn as callSiteAIFunction,vn as createSiteAIFunctionTask,W as createSiteRuntimeClient,G as createSiteRuntimeFetch,Xt as fetch,Bt as getCurrentUser,kn as getSiteAIFunctionTask,Cn as installLinkGuard,Dt as invokeApi,Ut as invokeHttp,fn as invokeSiteAIFunctionStream,De as isValidSiteFunctionName,qt as logout,ae as openLink,wr as readSiteAITextDelta,jt as requestEdit,v as siteRuntime,Kt as uploadAttachment};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-base-open/base-site-channel",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
"./runtime-contract": {
|
|
21
21
|
"types": "./dist/runtime-contract.d.ts",
|
|
22
22
|
"import": "./dist/runtime-contract.mjs"
|
|
23
|
+
},
|
|
24
|
+
"./capabilities": {
|
|
25
|
+
"types": "./dist/capabilities.d.ts",
|
|
26
|
+
"import": "./dist/capabilities.mjs",
|
|
27
|
+
"require": "./dist/capabilities.js"
|
|
23
28
|
}
|
|
24
29
|
},
|
|
25
30
|
"files": [
|