@zleap-ai/app-sdk 0.0.0-stage → 0.10.1

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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ zleapOS App SDK License
2
+
3
+ Copyright (c) 2026 Zleap. All rights reserved.
4
+
5
+ This package ("the SDK") is proprietary software provided by Zleap.
6
+
7
+ 1. Permitted use. You may install the SDK and include it, unmodified, in
8
+ applications that run on zleapOS (including applications you distribute to
9
+ others through zleapOS), solely to access zleapOS platform capabilities.
10
+
11
+ 2. Restrictions. Except as expressly permitted above, you may not copy, modify,
12
+ merge, publish, sublicense, sell or otherwise distribute the SDK on its own;
13
+ reverse engineer, decompile or attempt to derive its source code, except to
14
+ the extent applicable law expressly permits this despite this limitation; or
15
+ use the SDK to access services other than zleapOS.
16
+
17
+ 3. The TypeScript declaration files under dist/types may be read and used for
18
+ development tooling (editors, type checking, AI coding assistants).
19
+
20
+ 4. No warranty. THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21
+ EXPRESS OR IMPLIED. IN NO EVENT SHALL ZLEAP BE LIABLE FOR ANY CLAIM, DAMAGES
22
+ OR OTHER LIABILITY ARISING FROM THE USE OF THE SDK.
23
+
24
+ All rights not expressly granted are reserved by Zleap.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # @zleap-ai/app-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ zleapOS 云开发应用的前端 SDK。应用运行在 zleapOS 的 sandbox iframe 里,SDK 通过与宿主窗口的消息通道访问平台能力,不发网络请求。
4
+
5
+ ```bash
6
+ npm i @zleap-ai/app-sdk
7
+ ```
8
+
9
+ 用 `npm create zleap-app@latest` 生成的项目已经装好并封装在 `src/cloud/` 里。
10
+
11
+ ## 入口
12
+
13
+ | 导入路径 | 内容 |
14
+ | --- | --- |
15
+ | `@zleap-ai/app-sdk` | Cloud SDK:`zl.cloud.init` / `os.ready` / `database()`(查询、写入、watch)/ `uploadFile` / `downloadFile` / `callFunction`,以及 `CloudError` |
16
+ | `@zleap-ai/app-sdk/host` | 宿主能力:`connectHostedApp()`(剪贴板等,需在 manifest 声明权限) |
17
+ | `@zleap-ai/app-sdk/workspace` | 工作区:`connectWorkspace()`,在用户选定的文件夹内列出、整理文件(`workspace.files`),读取图片 `readImage()`(另需 `workspace.images.read`) |
18
+
19
+ ```ts
20
+ import { zl, CloudError } from '@zleap-ai/app-sdk';
21
+
22
+ zl.cloud.init({ env: zl.cloud.DYNAMIC_CURRENT_ENV });
23
+ const capabilities = await zl.cloud.os.ready();
24
+ const db = zl.cloud.database();
25
+ const { data } = await db.collection('todos').orderBy('created_at', 'desc').limit(20).get();
26
+ ```
27
+
28
+ 完整说明见 zleapOS 云开发文档;类型定义在 `dist/types/`。
29
+
30
+ ## 约束
31
+
32
+ - 只能在 zleapOS 桌面里运行;浏览器直接打开时握手会超时(`CALL_TIMEOUT`)。
33
+ - 环境永远用 `DYNAMIC_CURRENT_ENV`,由宿主决定 dev / prod。
34
+ - 产物不使用 `eval` / `new Function`,符合应用沙箱的 CSP。
35
+ - 出错时抛 `CloudError`:`errCode` 是错误码,`errMsg` 固定为 `App Cloud: <errCode>`。宿主不把服务端的中文说明和「下一步」传给应用,
36
+ 给用户看的提示请按 `errCode` 在应用里维护(脚手架模板 `src/cloud/client.ts` 的 `describeError` 可作参考)。完整错误码见文档「状态与错误码」。
37
+
38
+ ## 版本与许可
39
+
40
+ 与 `@zleap-ai/app-cli` 同版本发布。专有许可,仅限在 zleapOS 应用中使用,见 [LICENSE](./LICENSE)。
@@ -0,0 +1,20 @@
1
+ {
2
+ "package": "@zleap-ai/app-sdk",
3
+ "version": "0.10.1",
4
+ "source": "6d0ab79fb0aaa2df0163744d0e83efe3569235274040e464dc5b61ce7dee9e1e",
5
+ "files": 21,
6
+ "outputs": {
7
+ "index": {
8
+ "bytes": 38237,
9
+ "sha256": "d746f0ddba5c7949fa2b7980885624100314ca2f28b32de5ac3c062e98626d4c"
10
+ },
11
+ "host": {
12
+ "bytes": 11622,
13
+ "sha256": "c11013f994aa866b2160bebcb020dceb9030c399d3785e44115751fdaf801c94"
14
+ },
15
+ "workspace": {
16
+ "bytes": 2632,
17
+ "sha256": "956e9aef2d41661f3f50c02b40d8d9aa3b0591c9d48afdaa614244a2c4ad4f88"
18
+ }
19
+ }
20
+ }
package/dist/host.js ADDED
@@ -0,0 +1,2 @@
1
+ /*! @zleap-ai/app-sdk v0.10.1 | (c) 2026 Zleap | 专有许可,仅限在 zleapOS 应用中使用,见 LICENSE */
2
+ var U=Object.defineProperty;var F=(e,t,s)=>t in e?U(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var V=(e,t,s)=>F(e,typeof t!="symbol"?t+"":t,s);var o=class extends Error{constructor(s,n){super(s);V(this,"code");this.code=n,this.name="SDKError"}},I=1024*1024,D=64*1024,z=16,$=2**31-1,K=/^[a-z0-9][a-z0-9._-]{0,127}$/,J=128,q=/[/\\:%?#<>|"*]/,Z=/\p{C}/u,L=new Set(["con","prn","aux","nul",".packageroot",".","..",...Array.from({length:9},(e,t)=>`com${t+1}`),...Array.from({length:9},(e,t)=>`lpt${t+1}`)]),P=new WeakMap,S=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),k=e=>new TextEncoder().encode(e).byteLength,A=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function O(e){if(typeof e!="string"||!K.test(e))throw new o(`KV 键不合法:须匹配 ${K.source}(首字符小写字母/数字,仅含小写字母/数字/._-,长度 1-128),收到 ${JSON.stringify(e)}`,42200)}function C(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0||e>$)throw new o(`KV expectedVersion 不合法:须为 0..${$} 的整数(当前乐观锁版本,先 kv.get 取最新 version),收到 ${JSON.stringify(e)}`,42200)}function R(e){let t='文件名不合法:须为安全的根目录名称(非空、≤128 UTF-8 字节、无首尾空白、不以点结尾、不含 /\\:%?#<>|"* 与控制字符、非 con/com1-9 等系统保留名)',s=()=>{throw new o(t,42200)};if(typeof e!="string"||e.length===0)throw new o(t,42200);let n=e.normalize("NFC");Math.max(k(e),k(n))>J&&s(),(e!==e.trim()||e.endsWith("."))&&s(),(q.test(e)||Z.test(e))&&s();let a=n.toLowerCase(),f=a.split(".",1)[0]??a;(L.has(a)||L.has(f))&&s()}function X(e){let t=new Set,s=(n,a)=>{if(a>z)throw new o(`KV 值嵌套超过 ${z} 层上限`,42200);if(n===null)return"null";switch(typeof n){case"boolean":case"number":case"string":return JSON.stringify(n);case"bigint":throw new o("KV 值不支持 BigInt,请转换为 number 或 string",42200);case"undefined":case"function":case"symbol":return"";case"object":{if(t.has(n))throw new o("KV 值存在循环引用,无法序列化",42200);if(typeof n.toJSON=="function")throw new o("KV 值含带 toJSON 的对象(如 Date):请先显式转换(如 value.toISOString())后再写入",42200);t.add(n);try{return Array.isArray(n)?`[${n.map(f=>s(f,a+1)||"null").join(",")}]`:`{${Object.entries(n).filter(([,f])=>!["undefined","function","symbol"].includes(typeof f)).sort(([f],[d])=>f<d?-1:f>d?1:0).map(([f,d])=>`${JSON.stringify(f)}:${s(d,a+1)}`).join(",")}}`}finally{t.delete(n)}}default:throw new o(`KV 值含不支持的类型 ${typeof n}`,42200)}};return s(e,0)}function H(e){let t=X(e),s=new TextEncoder().encode(t).byteLength;if(s>D)throw new o(`KV 值过大:canonical JSON ${s} 字节,超过 64 KiB 上限`,42200)}function Q(e){switch(e){case 40400:return{code:e,retryable:!1,hint:"资源不存在:请确认 id / 路径正确后重试"};case 40900:return{code:e,retryable:!1,hint:"连接已关闭或请求 ID 冲突:请重新 connectHostedApp 后再试"};case 40901:return{code:e,retryable:!0,hint:"KV 版本冲突:请重新 kv.get 取最新 version 后以新的 expectedVersion 重试"};case 42200:return{code:e,retryable:!1,hint:"请求参数不合法:请检查键格式 / 值大小 / 文件上限后修正再提交"};case 42900:return{code:e,retryable:!0,hint:"并发请求过多:请降低并发(≤8)后重试"};case 40300:case 40301:case 40302:return{code:e,retryable:!1,hint:"宿主环境缺失或无权限:请确认从 Zleap OS 打开并已声明所需能力"};case 50200:return{code:e,retryable:!0,hint:"宿主响应异常:可重试;持续出现请向平台反馈"};case 50300:return{code:e,retryable:!0,hint:"连接不可用或超时:请检查宿主状态后重建连接重试"};default:return{code:e,retryable:!1,hint:"未识别的错误码:请结合 message 排查,必要时向平台反馈"}}}function j(e){if(!S(e)||typeof e.id!="string"||!/^[1-9]\d{0,19}$/.test(e.id)||typeof e.name!="string"||!e.name||e.name.length>512||e.mime_type!==null&&typeof e.mime_type!="string"||!A(e.size)||!A(e.version))throw new o("Invalid file response",50200);return{id:e.id,name:e.name,mime_type:e.mime_type,size:e.size,version:e.version}}function Y(e,t){if(!S(t))throw new o("Invalid runtime response",50200);if(e.startsWith("kv.")){if(typeof t.key!="string"||!A(t.version)||typeof t.exists!="boolean"||!Object.hasOwn(t,"value"))throw new o("Invalid KV response",50200);return{key:t.key,value:t.value,version:t.version,exists:t.exists}}if(e==="files.list"){if(!Array.isArray(t.list)||t.list.length>100||!A(t.total)||!A(t.page)||t.page<1||!A(t.page_size)||t.page_size<1||t.page_size>100)throw new o("Invalid file list response",50200);return{list:t.list.map(j),total:t.total,page:t.page,pageSize:t.page_size}}if(e==="files.read"){let s=j(t.file);if(typeof t.content_base64!="string"||t.content_base64.length>Math.ceil(I/3)*4||t.content_base64.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t.content_base64))throw new o("Invalid file content",50200);let n=atob(t.content_base64);if(n.length>I||n.length!==s.size)throw new o("Invalid file content",50200);return{file:s,data:Uint8Array.from(n,a=>a.charCodeAt(0))}}return j(t)}function ee(e={}){let t=P.get(window);if(t)return t;let s=new URL(window.location.href),n=s.pathname.match(/^\/api\/v1\/app-packages\/runtime\/([A-Za-z0-9_-]{43})\/.+/)?.[1];if(!n||window.parent===window||!["http:","https:"].includes(s.protocol))return Promise.reject(new o("Open this app from AgentOS",40300));let a=e.timeoutMs??3e4;if(!Number.isFinite(a)||a<1||a>12e4)return Promise.reject(new o("Invalid connection timeout",42200));let f,d,y=new Promise((i,p)=>{f=i,d=p});P.set(window,y);let m;try{m=new MessageChannel}catch{return P.delete(window),Promise.reject(new o("MessageChannel unavailable",50300))}let l=m.port1,g=!1,r=!1,c=new Map,h=(i=new o("App connection closed; reopen the app",40900),p=!0)=>{if(!g){g=!0,clearTimeout(M),p&&l.postMessage({type:"__zleap_hosted_close"}),l.onmessage=null,l.onmessageerror=null,l.close(),m.port2.close(),window.removeEventListener("pagehide",x),P.get(window)===y&&P.delete(window),d(i);for(let u of c.values())clearTimeout(u.timer),u.reject(i);c.clear()}},x=()=>h(),M=setTimeout(()=>h(new o("App connection timed out",50300)),a);function _(i,p,u=[]){if(g||!r)return Promise.reject(new o("App connection closed; reopen the app",40900));if(c.size>=8)return Promise.reject(new o("Too many concurrent app requests",42900));let w=crypto.randomUUID();try{let b={requestId:w,method:i,args:i==="files.write"&&S(p)?{...p,data:null}:p},v=JSON.stringify(b),E=i==="files.write"?4096:I;if(v.length>E||new TextEncoder().encode(v).byteLength>E)return Promise.reject(new o("App request too large",42200))}catch{return Promise.reject(new o("Invalid app request",42200))}return new Promise((b,v)=>{let E=setTimeout(()=>{c.delete(w),v(new o("App request timed out",50300))},a);c.set(w,{method:i,resolve:b,reject:v,timer:E});try{l.postMessage({requestId:w,method:i,args:p},u)}catch{clearTimeout(E),c.delete(w),v(new o("Invalid app request",42200))}})}let T=i=>{try{return i(),null}catch(p){return Promise.reject(p)}},B={kv:{get:i=>T(()=>O(i?.key))??_("kv.get",i),set:i=>T(()=>{O(i?.key),H(i?.value),C(i?.expectedVersion)})??_("kv.set",i),delete:i=>T(()=>{O(i?.key),C(i?.expectedVersion)})??_("kv.delete",i)},files:{list:(i={})=>_("files.list",i),read:i=>_("files.read",i),write:i=>{let p=T(()=>R(i?.name));if(p)return p;if(!(i.data instanceof ArrayBuffer)&&!(i.data instanceof Uint8Array))return Promise.reject(new o("File content must be binary",42200));if(i.data.byteLength>I)return Promise.reject(new o("Files must be at most 1 MiB",42200));let u=i.data instanceof ArrayBuffer?i.data.slice(0):new Uint8Array(i.data).buffer;return _("files.write",{...i,data:u},[u])}},close:()=>h()};l.onmessage=i=>{if(g||!S(i.data))return;let p=i.data;if(p.type==="__zleap_hosted_ready"&&p.protocol===1&&!r){r=!0,clearTimeout(M),f(B);return}if(p.type==="__zleap_hosted_closed"){h(new o("App connection closed; reopen the app",40900),!1);return}if(typeof p.requestId!="string")return;let u=c.get(p.requestId);if(u){c.delete(p.requestId),clearTimeout(u.timer);try{let w=u.method==="files.read"?I*1.5:I,b=JSON.stringify(p.result??null);if(b.length>w||k(b)>w)throw new o("App response too large",50200);S(p.error)&&Number.isSafeInteger(p.error.code)&&typeof p.error.message=="string"?u.reject(new o(p.error.message.slice(0,512),Number(p.error.code))):u.resolve(Y(u.method,p.result))}catch(w){u.reject(w instanceof o?w:new o("Invalid runtime response",50200))}}},l.onmessageerror=()=>h(new o("Invalid runtime message",50200)),l.start(),window.addEventListener("pagehide",x);try{window.parent.postMessage({type:"__zleap_hosted_connect",protocol:1,nonce:n},s.origin,[m.port2])}catch{h(new o("App connection unavailable",50300))}return y}var N=null;function te(){if(N)return N;let e=window.__ZLEAP_OS__;if(!e||typeof e!="object")throw new o("Zleap OS host bridge missing; open this app from Zleap OS",40301);let{auth:t,api:s,storage:n,notify:a,eventBus:f,app:d,invite:y,social:m}=e;if(!t||!s)throw new o("Zleap OS host bridge missing; open this app from Zleap OS",40301);let l=r=>()=>Promise.reject(new o(`宿主未提供 ${r} 能力域(宿主版本过旧),请升级 Zleap OS 后重试`,40302)),g={auth:{getToken:()=>t.getToken(),getUser:()=>t.getUser(),hasPermission:r=>t.hasPermission(r)},storage:{getItem:r=>n?n.getItem(r):l("storage")(),setItem:(r,c)=>n?n.setItem(r,c):l("storage")(),removeItem:r=>n?n.removeItem(r):l("storage")()},notify:{show:(r,c)=>a?a.show(r,c):l("notify")(),confirm:(r,c)=>a?a.confirm(r,c):l("notify")()},eventBus:{emit:(r,c)=>f?f.emit(r,c):l("eventBus")(),on:(r,c)=>f?f.on(r,c):l("eventBus")(),off:r=>f?f.off(r):l("eventBus")()},api:{get:(r,c)=>s.get(r,c),post:(r,c)=>s.post(r,c),put:(r,c)=>s.put(r,c),del:r=>s.del(r)},app:{getManifest:()=>d?d.getManifest():l("app")(),getAppId:()=>d?d.getAppId():l("app")()},invite:{send:r=>y?y.send(r):l("invite")()},social:{follow:(r,c)=>m?m.follow(r,c):l("social")(),unfollow:(r,c)=>m?m.unfollow(r,c):l("social")(),isFollowing:(r,c)=>m?m.isFollowing(r,c):l("social")(),pickUsers:r=>m?m.pickUsers(r):l("social")(),pickConversations:r=>m?m.pickConversations(r):l("social")(),shareToConversation:r=>m?m.shareToConversation(r):l("social")(),shareToDynamic:r=>m?m.shareToDynamic(r):l("social")(),createGroup:r=>m?m.createGroup(r):l("social")()}};return N=g,g}function G(e,t){if(!t)return e;let s=new URLSearchParams;for(let[a,f]of Object.entries(t))f!==void 0&&s.set(a,String(f));let n=s.toString();return n?`${e}${e.includes("?")?"&":"?"}${n}`:e}function ne(e,t={}){let s={auth:{getToken:()=>Promise.resolve(e.auth.getToken()),getUser:()=>Promise.resolve(e.auth.getUser())},storage:{getItem:n=>Promise.resolve(e.storage.getItem(n)),setItem:(n,a)=>Promise.resolve(e.storage.setItem(n,a)),removeItem:n=>Promise.resolve(e.storage.removeItem(n))},notify:{show:(n,a="info")=>Promise.resolve(e.notify(a,n)),confirm:(n,a)=>e.confirm({title:n,content:a})},api:{get:(n,a)=>e.apiProxy(G(n,a),{method:"GET"}),post:(n,a)=>e.apiProxy(n,{method:"POST",body:a}),put:(n,a)=>e.apiProxy(n,{method:"PUT",body:a}),del:n=>e.apiProxy(n,{method:"DELETE"})},app:{getAppId:()=>t.appId?Promise.resolve(t.appId):Promise.reject(new o("appId is unavailable in this host form",40302))}};return e.invite&&(s.invite=e.invite),e.social&&(s.social=e.social),s}export{o as SDKError,ne as connectHostCapabilities,ee as connectHostedApp,te as connectZleapOs,Q as describeError};
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ /*! @zleap-ai/app-sdk v0.10.1 | (c) 2026 Zleap | 专有许可,仅限在 zleapOS 应用中使用,见 LICENSE */
2
+ var Ue=Object.defineProperty;var Re=(t,e,n)=>e in t?Ue(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var O=(t,e,n)=>Re(t,typeof e!="symbol"?e+"":e,n);var re="__zleap_cloud_connect",oe="__zleap_cloud_ready",ie="__zleap_cloud_close",se="__zleap_cloud_closed",ae="__zleap_cloud_event",ce="__zleap_api_token",Pe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,L=/^op_\d{10}_[0-9a-f]{32}$/,De={BACKGROUND_CAPABILITY_UNAVAILABLE:"App Cloud: BACKGROUND_CAPABILITY_UNAVAILABLE(后台能力未开启:请在应用窗口顶部的「权限」里勾选并保存,应用会自动重新加载;如果应用没有声明后台能力,开发者要先在 Manifest 中声明)"},o=class extends Error{constructor(n,s,r,f){super(n);O(this,"errCode");O(this,"errMsg");O(this,"requestId");O(this,"operationId");O(this,"retryable");O(this,"jobId");O(this,"invocationId");this.name="CloudError",this.errCode=n,this.errMsg=De[n]??`App Cloud: ${n}`,this.requestId=s,this.operationId=r,this.jobId=f?.jobId,this.invocationId=f?.invocationId,this.retryable=["CALL_TIMEOUT","RUNTIME_UNAVAILABLE","COMMIT_UNKNOWN"].includes(n)}};function h(t){return!!(t&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))}function E(t,e){return Object.keys(t).every(n=>e.includes(n))}function T(t,e=256*1024){let n=new Set,s=0;function r(f,u){if(++s>1e4||u>24)return!1;if(f===null||typeof f=="boolean")return!0;if(typeof f=="number")return Number.isFinite(f);if(typeof f=="string")return f.length<=e;if(typeof f!="object"||!h(f)&&!Array.isArray(f)||n.has(f))return!1;n.add(f);let d=Object.entries(f).every(([i,l])=>!["__proto__","prototype","constructor"].includes(i)&&r(l,u+1));return n.delete(f),d}if(!r(t,0))return!1;try{return new TextEncoder().encode(JSON.stringify(t)).length<=e}catch{return!1}}function de(t){if(!h(t)||!E(t,["requestId","method","args"])||typeof t.requestId!="string"||!Pe.test(t.requestId)||!h(t.args)||!(t.method==="files.chunk"?k(t.args)&&T({...t,args:{...t.args,data:null}}):T(t)))return null;let{args:e,method:n,requestId:s}=t;if(typeof n=="string"&&n.startsWith("files.")){let r=typeof e.operation_id=="string"&&L.test(e.operation_id),f=typeof e.file_id=="string"&&e.file_id.length>=32&&e.file_id.length<=1024,u=w=>typeof w=="string"&&w.length>0&&w.length<=128,d=w=>typeof w=="string"&&/^[a-f0-9]{64}$/.test(w),i=(w,I,_)=>typeof w=="number"&&Number.isInteger(w)&&w>=I&&w<=_;return["files.operation","files.commit","files.cancel"].includes(n)&&r&&E(e,["operation_id"])||n==="files.stat"&&f&&E(e,["file_id"])||n==="files.read"&&f&&u(e.etag)&&i(e.offset,0,4194304)&&i(e.length,1,262144)&&E(e,["file_id","etag","offset","length"])||n==="files.delete"&&f&&r&&u(e.expected_etag)&&E(e,["file_id","expected_etag","operation_id"])||n==="files.chunk"&&r&&i(e.index,0,15)&&d(e.sha256)&&k(e)&&E(e,["operation_id","index","sha256","data"])||n==="files.begin"&&r&&typeof e.cloud_path=="string"&&e.cloud_path.length>0&&e.cloud_path.length<=512&&i(e.size_bytes,0,4194304)&&d(e.sha256)&&typeof e.mime_type=="string"&&e.mime_type.length<=128&&typeof e.overwrite=="boolean"&&e.overwrite===!!e.expected_etag&&(e.expected_etag===void 0||u(e.expected_etag))&&E(e,["cloud_path","size_bytes","mime_type","sha256","overwrite","expected_etag","operation_id"])?{requestId:s,method:n,args:e}:null}if(n==="execution.get"||n==="execution.cancel")return E(e,["job_id"])&&typeof e.job_id=="string"&&/^[1-9][0-9]{0,18}$/.test(e.job_id)?{requestId:s,method:n,args:e}:null;if(n==="execution.invoke"){let r=e.capability_key??e.function_name;return E(e,["capability_key","function_name","data","operation_id","wait_seconds"])&&e.capability_key!==void 0!=(e.function_name!==void 0)&&typeof r=="string"&&/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(r)&&h(e.data)&&T(e.data,65536)&&typeof e.operation_id=="string"&&L.test(e.operation_id)&&typeof e.wait_seconds=="number"&&Number.isInteger(e.wait_seconds)&&e.wait_seconds>=0&&e.wait_seconds<=25?{requestId:s,method:n,args:e}:null}return n==="operations.get"?E(e,["operation_id"])&&typeof e.operation_id=="string"&&L.test(e.operation_id)?{requestId:s,method:n,args:e}:null:typeof e.collection_key!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(e.collection_key)||/^(sys_|ac_|t_)/.test(e.collection_key)?null:n==="documents.query"&&E(e,["collection_key","operation","document_key","filter","order_by","projection","limit","skip"])&&["get","count"].includes(String(e.operation))?{requestId:s,method:n,args:e}:n==="documents.snapshot"&&E(e,["collection_key","query","cursor","max_docs"])&&h(e.query)&&E(e.query,["filter","order_by","projection","limit","skip"])&&(e.query.skip===void 0||e.query.skip===0)&&T(e.query,8192)&&typeof e.cursor=="number"&&Number.isSafeInteger(e.cursor)&&e.cursor>=0&&typeof e.max_docs=="number"&&Number.isSafeInteger(e.max_docs)&&e.max_docs>=1&&e.max_docs<=100?{requestId:s,method:n,args:e}:n==="documents.mutate"&&E(e,["collection_key","operation","document_key","data","value_types","field_operations","expected_version","operation_id"])&&["add","set","update","remove"].includes(String(e.operation))&&typeof e.operation_id=="string"&&L.test(e.operation_id)?{requestId:s,method:n,args:e}:null}function k(t){return h(t)&&t.data instanceof ArrayBuffer&&t.data.byteLength<=262144&&T({...t,data:null},16384)}function F(t){return["documents.mutate","execution.invoke","execution.cancel","files.begin","files.chunk","files.commit","files.cancel","files.delete"].includes(t)}var xe=60,ke=15e3;function qe(){if(typeof window>"u"||window.parent===window)return Promise.reject(new o("RUNTIME_UNAVAILABLE"));let t=window.location.pathname.match(/^\/api\/v1\/app-packages\/runtime\/([A-Za-z0-9_-]{43})\//)?.[1];return t?new Promise((e,n)=>{let s=new MessageChannel,r=u=>{clearTimeout(f),s.port1.onmessage=null,s.port1.close(),u()},f=setTimeout(()=>r(()=>n(new o("CALL_TIMEOUT"))),ke);s.port1.onmessage=u=>{let d=u.data,i=h(d)?d.result:void 0;if(h(i)&&typeof i.token=="string"&&typeof i.base_url=="string"&&typeof i.expires_at=="number"){let w={token:i.token,baseUrl:i.base_url,expiresAt:i.expires_at};r(()=>e(w));return}let l=h(d)&&h(d.error)&&typeof d.error.errCode=="string"?d.error.errCode:"RUNTIME_UNAVAILABLE";r(()=>n(new o(l)))},window.parent.postMessage({type:ce,nonce:t},"*",[s.port2])}):Promise.reject(new o("RUNTIME_UNAVAILABLE"))}function fe(t=qe){let e=null,n=null;function s(){return n??(n=t().then(i=>(e=i,i)).finally(()=>{n=null})),n}async function r(){return e&&e.expiresAt-Date.now()/1e3>xe?{...e}:{...await s()}}function f(i,l){if(typeof l!="string"||!l.startsWith("/")||l.startsWith("//"))throw new o("SCHEMA_INVALID");let w=new URL(i),I=new URL(i+l);if(I.origin!==w.origin||!I.pathname.startsWith(w.pathname+"/"))throw new o("SCHEMA_INVALID");return I}function u(i,l,w){let I=new Headers(w.headers);return I.set("Authorization","Bearer "+i.token),typeof w.body=="string"&&!I.has("Content-Type")&&I.set("Content-Type","application/json"),fetch(f(i.baseUrl,l),{...w,headers:I,credentials:"omit",redirect:"error"})}async function d(i,l={}){let w=await u(await r(),i,l),I=(l.method??"GET").toUpperCase();return w.status!==401||I!=="GET"&&I!=="HEAD"?w:(e=null,u(await r(),i,l))}return{token:r,fetch:d}}var He="__zleap_app_connect",Ve="__zleap_app_ready",je="__zleap_app_event";var M=class extends Error{constructor(n,s){super(s??n);O(this,"errCode");this.name="AppError",this.errCode=n}},j=t=>!!(t&&typeof t=="object"&&!Array.isArray(t)),V=null;function v(){return V||(V=new Promise((t,e)=>{if(typeof window>"u"||window.parent===window)return e(new M("OPEN_IN_ZLEAP_OS","请从 AgentOS 中打开应用"));let n=window.location.pathname.match(/^\/api\/v1\/app-packages\/runtime\/([A-Za-z0-9_-]{43})\//)?.[1];if(!n)return e(new M("OPEN_IN_ZLEAP_OS","请从 AgentOS 中打开应用"));let s=new MessageChannel,r=new Map,f=new Set,u=!1,d=setTimeout(()=>{u||(V=null,e(new M("HOST_UNAVAILABLE","宿主未响应,请升级 AgentOS 后重试")))},15e3);s.port1.onmessage=i=>{let l=i.data;if(!j(l))return;if(l.type===Ve&&l.protocol===1&&!u){u=!0,clearTimeout(d),t({call(I,_={},c=3e4){return new Promise((a,p)=>{if(r.size>=8)return p(new M("TOO_MANY_REQUESTS"));let y=crypto.randomUUID(),N=setTimeout(()=>{r.delete(y),p(new M("CALL_TIMEOUT"))},c);r.set(y,{resolve:a,reject:p,timer:N}),s.port1.postMessage({requestId:y,method:I,args:_})})},onEvent(I){return f.add(I),()=>f.delete(I)}});return}if(l.type===je&&typeof l.event=="string"){for(let I of f)try{I(l.event,l.data)}catch{}return}if(typeof l.requestId!="string")return;let w=r.get(l.requestId);w&&(r.delete(l.requestId),clearTimeout(w.timer),j(l.error)?w.reject(new M(typeof l.error.errCode=="string"?l.error.errCode:"RUNTIME_UNAVAILABLE",typeof l.error.message=="string"?l.error.message:void 0)):w.resolve(l.result))},s.port1.start(),window.parent.postMessage({type:He,protocol:1,nonce:n},"*",[s.port2])}),V.catch(()=>{}),V)}function Z(t){let e=j(t)?t:{};return{hasUpdate:e.hasUpdate===!0,currentVersion:typeof e.currentVersion=="string"?e.currentVersion:null,latestVersion:typeof e.latestVersion=="string"?e.latestVersion:null,notes:typeof e.notes=="string"?e.notes:null,deadline:typeof e.deadline=="number"?e.deadline:null}}var K=null;function ue(){if(K)return K;let t=new Set,e=new Set,n=new Set,s=null,r=!1,f=u=>{if(!(!u.hasUpdate||r)){r=!0;for(let d of e)d(u)}};return v().then(async u=>{u.onEvent((d,i)=>{d==="updateReady"&&(r=!1,f(Z(i)))}),s=Z(await u.call("app.checkUpdate"));for(let d of t)d(s);f(s)}).catch(u=>{let d=u instanceof M?u:new M("RUNTIME_UNAVAILABLE");for(let i of n)i(d)}),K={onCheckForUpdate(u){t.add(u),s&&u(s)},onUpdateReady(u){e.add(u),s?.hasUpdate&&r&&u(s)},onUpdateFailed(u){n.add(u)},async applyUpdate(){try{await(await v()).call("app.applyUpdate",{},6e4)}catch(u){let d=u instanceof M?u:new M("UPDATE_FAILED");for(let i of n)i(d);throw d}}},K}async function le(){return Z(await(await v()).call("app.checkUpdate"))}function pe(t){if(!j(t)||typeof t.openid!="string")throw new M("PROTOCOL_MISMATCH");let e={openid:t.openid,scopes:Array.isArray(t.scopes)?t.scopes.filter(n=>typeof n=="string"):[]};return j(t.profile)&&(e.profile={nickname:typeof t.profile.nickname=="string"?t.profile.nickname:"",avatarUrl:typeof t.profile.avatarUrl=="string"?t.profile.avatarUrl:null}),"phone"in t&&(e.phone=typeof t.phone=="string"?t.phone:null),"email"in t&&(e.email=typeof t.email=="string"?t.email:null),e}async function _e(t){if(!j(t)||!Array.isArray(t.scopes)||t.scopes.length===0||t.scopes.some(n=>!["profile","phone","email"].includes(n)))throw new M("SCHEMA_INVALID","scopes 只能是 profile、phone、email");if(t.reason!==void 0&&(typeof t.reason!="string"||t.reason.length>60))throw new M("SCHEMA_INVALID","reason 是不超过 60 字的用途说明");let e={scopes:t.scopes};return t.reason&&(e.reason=t.reason),pe(await(await v()).call("auth.authorize",e,3e5))}async function we(){return pe(await(await v()).call("auth.getIdentity"))}function he(t){if(typeof t.job_id!="string"||!/^\d+$/.test(t.job_id)||typeof t.invocation_id!="string"||!/^\d+$/.test(t.invocation_id)||typeof t.operation_id!="string"||!L.test(t.operation_id)||typeof t.status!="string"||!["accepted","queued","running","cancel_requested","cancelled","succeeded","failed","unknown"].includes(t.status)||!Array.isArray(t.committed_steps)||!t.committed_steps.every(e=>typeof e=="string"))throw new o("PROTOCOL_MISMATCH");return{jobId:t.job_id,invocationId:t.invocation_id,operationId:t.operation_id,status:t.status,result:t.result??null,errorCode:typeof t.error_code=="string"?t.error_code:null,committedSteps:t.committed_steps}}function ye(t){async function e(r,f,u,d=!1,i=0){if(typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(r)||!h(f)||!T(f,65536))throw new o("SCHEMA_INVALID");if(u!==void 0&&(typeof u!="string"||!L.test(u)))throw new o("SCHEMA_INVALID");let l=u??t.createId(),{value:w}=await t.request("execution.invoke",{[d?"function_name":"capability_key"]:r,data:f,operation_id:l,wait_seconds:i});return he(w)}async function n(r){if(!h(r)||!E(r,["jobId"])||typeof r.jobId!="string"||!/^[1-9][0-9]{0,18}$/.test(r.jobId))throw new o("SCHEMA_INVALID");return he((await t.request("execution.get",{job_id:r.jobId})).value)}async function s(r){if(!h(r)||!E(r,["jobId","timeoutSeconds","pollMilliseconds"])||typeof r.jobId!="string"||!/^[1-9][0-9]{0,18}$/.test(r.jobId)||r.timeoutSeconds!==void 0&&(!Number.isInteger(r.timeoutSeconds)||r.timeoutSeconds<0||r.timeoutSeconds>300)||r.pollMilliseconds!==void 0&&(!Number.isInteger(r.pollMilliseconds)||r.pollMilliseconds<100||r.pollMilliseconds>5e3))throw new o("SCHEMA_INVALID");let f=(r.timeoutSeconds??25)*1e3,u=r.pollMilliseconds??500,d=Date.now()+f,i=await n({jobId:r.jobId});for(;["accepted","queued","running","cancel_requested"].includes(i.status)&&Date.now()<d;)await new Promise(l=>setTimeout(l,Math.min(u,Math.max(0,d-Date.now())))),i=await n({jobId:r.jobId});if(["accepted","queued","running","cancel_requested"].includes(i.status))throw new o("CALL_TIMEOUT",void 0,i.operationId,{jobId:i.jobId,invocationId:i.invocationId});return i}return{capabilities:{invoke:async r=>{if(!h(r)||!E(r,["id","input","operationId","waitSeconds"]))throw new o("UNSUPPORTED_OPERATION");return e(r.id,r.input,r.operationId,!1,r.waitSeconds)}},jobs:{submit:async r=>{if(!h(r)||!E(r,["kind","capability","input","operationId","waitSeconds"])||r.kind!=="capability")throw new o("UNSUPPORTED_OPERATION");return e(r.capability,r.input,r.operationId,!1,r.waitSeconds)},get:n,result:n,wait:s,cancel:async r=>{if(!h(r)||!E(r,["jobId"])||typeof r.jobId!="string"||!/^[1-9][0-9]{0,18}$/.test(r.jobId))throw new o("SCHEMA_INVALID");let{value:f}=await t.request("execution.cancel",{job_id:r.jobId});if(f.cancel_requested!==!0)throw new o("PROTOCOL_MISMATCH");return{cancelRequested:!0}}},callFunction:async r=>{if(!h(r)||!E(r,["name","data","agentos","success","fail","complete"])||r.agentos!==void 0&&(!h(r.agentos)||!E(r.agentos,["operationId"])))throw new o("UNSUPPORTED_OPERATION");let f=await e(r.name,r.data??{},r.agentos?.operationId,!0,25);if(["accepted","queued","running","cancel_requested","unknown"].includes(f.status))throw new o(f.status==="unknown"?"COMMIT_UNKNOWN":"CALL_TIMEOUT",void 0,f.operationId,{jobId:f.jobId,invocationId:f.invocationId});if(f.status==="failed"||f.status==="cancelled")throw new o(f.errorCode??"EXECUTION_FAILED",void 0,f.operationId,{jobId:f.jobId,invocationId:f.invocationId});return f}}}var Ae=4*1024*1024,z=256*1024,me=16,ze=2,Be=new Set(["VERSION_CONFLICT","UPLOAD_INTEGRITY_FAILED"]);function $(t,e){let n=e??t.createId();if(!L.test(n))throw new o("SCHEMA_INVALID",void 0,n);return n}function Y(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return crypto.subtle.digest("SHA-256",e).then(n=>[...new Uint8Array(n)].map(s=>s.toString(16).padStart(2,"0")).join(""))}function Ie(t){if(!h(t))throw new o("PROTOCOL_MISMATCH");let e=t.size_bytes;if(typeof t.file_id!="string"||t.file_id.length<32||typeof t.etag!="string"||t.etag.length===0||typeof t.sha256!="string"||!/^[a-f0-9]{64}$/.test(t.sha256)||typeof e!="number"||!Number.isSafeInteger(e)||e<0||e>Ae)throw new o("PROTOCOL_MISMATCH");return{fileID:t.file_id,etag:t.etag,sha256:t.sha256,size:e,errMsg:"ok"}}function W(t){if(!h(t)||typeof t.operation_id!="string"||!L.test(t.operation_id)||!["pending","succeeded","cancelled"].includes(String(t.state)))throw new o("PROTOCOL_MISMATCH");let e=t.received;if(e!==void 0&&(!Array.isArray(e)||!e.every(n=>Number.isInteger(n)&&n>=0&&n<me)))throw new o("PROTOCOL_MISMATCH");return{operation_id:t.operation_id,state:t.state,...typeof t.chunk_size=="number"?{chunk_size:t.chunk_size}:{},...e===void 0?{}:{received:e},...t.file===null||t.file===void 0?{file:null}:{file:t.file}}}function Oe(t){async function e(d){let i=$(t,d),l=await t.request("files.operation",{operation_id:i}),w=W(l.value);if(w.operation_id!==i)throw new o("PROTOCOL_MISMATCH",l.requestId,i);return w}async function n(d){if(!h(d)||typeof d.cloudPath!="string"||typeof Blob>"u"||!(d.filePath instanceof Blob)||d.filePath.size>Ae)throw new o("SCHEMA_INVALID");let i=$(t,d.agentos?.operationId),l=new Uint8Array(await d.filePath.arrayBuffer()),w=await Y(l),I=A=>{let g=Ie(A);if(g.size!==l.byteLength||g.sha256!==w)throw new o("PROTOCOL_MISMATCH");return g},_=Math.ceil(l.byteLength/z);if(_>me)throw new o("RESOURCE_EXHAUSTED",void 0,i);let c;try{let A=await t.request("files.begin",{cloud_path:d.cloudPath,size_bytes:l.byteLength,mime_type:d.filePath.type||"application/octet-stream",sha256:w,overwrite:d.agentos?.overwrite===!0,...d.agentos?.expectedETag?{expected_etag:d.agentos.expectedETag}:{},operation_id:i});c=W(A.value)}catch(A){if(!(A instanceof o)||A.errCode!=="COMMIT_UNKNOWN")throw A;c=await e(i)}if(c.operation_id!==i)throw new o("PROTOCOL_MISMATCH");if(c.state==="succeeded"){if(!c.file)throw new o("PROTOCOL_MISMATCH");return I(c.file)}if(c.state==="cancelled")throw new o("OPERATION_EXPIRED",void 0,i);if(c.chunk_size!==void 0&&c.chunk_size!==z)throw new o("PROTOCOL_MISMATCH",void 0,i);let a=new Set(c.received??[]),p=Array.from({length:_},(A,g)=>g).filter(A=>!a.has(A)),y,N=0;async function m(A){let g=l.slice(A*z,Math.min(l.length,(A+1)*z)),P=await Y(g);try{let b=await t.request("files.chunk",{operation_id:i,index:A,sha256:P,data:g.slice().buffer});if(b.value.operation_id!==i||b.value.index!==A||b.value.received!==!0)throw new o("PROTOCOL_MISMATCH",b.requestId,i);a.add(A)}catch(b){if(!(b instanceof o)||b.errCode!=="COMMIT_UNKNOWN")throw b;let x=await e(i);if(x.state==="succeeded"&&x.file){y=I(x.file);return}if(x.state==="cancelled")throw new o("OPERATION_EXPIRED",void 0,i);if(x.received?.forEach(C=>a.add(C)),a.has(A))return;let H=await t.request("files.chunk",{operation_id:i,index:A,sha256:P,data:g.slice().buffer});if(H.value.operation_id!==i||H.value.index!==A||H.value.received!==!0)throw new o("PROTOCOL_MISMATCH",H.requestId,i);a.add(A)}}async function S(){for(;N<p.length&&!y;){let A=p[N++];A!==void 0&&await m(A)}}if(await Promise.all(Array.from({length:Math.min(ze,p.length)},S)),y)return y;try{let A=await t.request("files.commit",{operation_id:i}),g=W(A.value);if(g.state!=="succeeded"||!g.file)throw new o("PROTOCOL_MISMATCH",A.requestId,i);return I(g.file)}catch(A){if(A instanceof o&&Be.has(A.errCode))throw await u(i).catch(()=>{}),A;if(!(A instanceof o)||A.errCode!=="COMMIT_UNKNOWN")throw A;let g=await e(i);if(g.state==="succeeded"&&g.file)return I(g.file);throw g.state==="cancelled"?new o("OPERATION_EXPIRED",void 0,i):A}}async function s(d){if(typeof d!="string"||d.length<32||d.length>1024)throw new o("SCHEMA_INVALID");let i=await t.request("files.stat",{file_id:d});return Ie(i.value)}async function r(d){let i=await s(d),l=[];for(let _=0;_<i.size;_+=z){let c=Math.min(z,i.size-_),a=await t.request("files.read",{file_id:d,etag:i.etag,offset:_,length:c});if(!(a.value.data instanceof ArrayBuffer)||a.value.etag!==i.etag||a.value.offset!==_||a.value.data.byteLength!==c)throw new o("PROTOCOL_MISMATCH",a.requestId);l.push(a.value.data)}let w=new Uint8Array(i.size),I=0;for(let _ of l)w.set(new Uint8Array(_),I),I+=_.byteLength;if(await Y(w)!==i.sha256)throw new o("PROTOCOL_MISMATCH");return{fileContent:new Blob([w],{type:"application/octet-stream"}),errMsg:"ok"}}async function f(d){if(!h(d)||!Array.isArray(d.fileList)||d.fileList.length===0||d.fileList.length>100||!h(d.agentos?.expectedETags))throw new o("SCHEMA_INVALID");let i=[],l=[],w=new Set;for(let I=0;I<d.fileList.length;I++){let _=d.fileList[I],c=d.agentos?.expectedETags?.[_];if(typeof c!="string"||c.length===0)throw new o("SCHEMA_INVALID");let a=$(t,I===0?d.agentos?.operationId:void 0);for(;w.has(a);)a=$(t);w.add(a);try{let p=await t.request("files.delete",{file_id:_,expected_etag:c,operation_id:a}),y=W(p.value);if(y.operation_id!==a||y.state!=="succeeded")throw new o("PROTOCOL_MISMATCH",p.requestId,a);i.push(_)}catch(p){if(p instanceof o&&p.errCode==="COMMIT_UNKNOWN")try{if((await e(a)).state==="succeeded"){i.push(_);continue}}catch{}l.push({fileID:_,error:p instanceof o?p:new o("RUNTIME_UNAVAILABLE",void 0,a)})}}return{deleted:i,failed:l,errMsg:l.length?"partial failure":"ok"}}async function u(d){let i=$(t,d),l=await t.request("files.cancel",{operation_id:i});return W(l.value)}return{upload:n,download:r,remove:f,stat:s,getOperation:e,cancel:u}}function Fe(t){if(!h(t)||typeof t.event!="string"||!/^[a-z][a-z0-9_.]{0,63}$/.test(t.event))return null;let e={event:t.event};for(let n of["app_id","collection_key","collection_id","document_key","change_seq","operation_id"])typeof t[n]=="string"&&(e[n]=t[n]);return e}function ge(t){if(typeof window>"u"||window.parent===window)throw new o("RUNTIME_UNAVAILABLE");let e=window.location.pathname.match(/^\/api\/v1\/app-packages\/runtime\/([A-Za-z0-9_-]{43})\//)?.[1];if(!e)throw new o("RUNTIME_UNAVAILABLE");let n=new MessageChannel,s=!1,r=!1,f,u,d=new Promise((c,a)=>{f=c,u=a});d.catch(()=>{});let i=new Map,l=new Set,w=(c="RUNTIME_UNAVAILABLE")=>{if(!s){s=!0,clearTimeout(_),u(new o(c));for(let[a,p]of i)clearTimeout(p.timer),p.reject(new o(c,a,p.operationId));i.clear(),n.port1.postMessage({type:ie}),n.port1.onmessage=null,n.port1.close(),window.removeEventListener("pagehide",I)}},I=()=>w(),_=setTimeout(()=>w("CALL_TIMEOUT"),15e3);return n.port1.onmessageerror=()=>w("PROTOCOL_MISMATCH"),n.port1.onmessage=c=>{let a=c.data;if(!h(a)||!(T(a,1024*1024)||typeof a.requestId=="string"&&i.get(a.requestId)?.method==="files.read"&&k(a.result)&&T({...a,result:null},16384))){w("PROTOCOL_MISMATCH");return}if(a.type===se){w(typeof a.errCode=="string"?a.errCode:"RUNTIME_UNAVAILABLE");return}if(a.type===ae){let y=Fe(a.event);if(y)for(let N of l)N(y);return}if(a.type===oe&&!r){let y=a.capabilities;if(a.protocol!==2||!h(y)||!h(y.protocol)||y.protocol.major!==2||!Array.isArray(y.profiles)||!y.profiles.some(N=>["document-core/1","app-execution/1","storage-object/1"].includes(String(N)))||!Array.isArray(y.operators)||!h(y.limits)||typeof y.serverTime!="number"){w("PROTOCOL_MISMATCH");return}r=!0,clearTimeout(_),f(y);return}if(typeof a.requestId!="string"){w("PROTOCOL_MISMATCH");return}let p=i.get(a.requestId);p&&(clearTimeout(p.timer),i.delete(a.requestId),h(a.error)?p.reject(new o(typeof a.error.errCode=="string"?a.error.errCode:"RUNTIME_UNAVAILABLE",a.requestId,p.operationId)):p.resolve(a.result))},n.port1.start(),window.addEventListener("pagehide",I),window.parent.postMessage({type:re,protocol:2,nonce:e,environmentKey:t},"*",[n.port2]),{ready:()=>d,onEvent(c){return l.add(c),()=>l.delete(c)},request:async(c,a,p)=>{if(await d,s)throw new o("RUNTIME_UNAVAILABLE",p);if(i.size>=8)throw new o("RESOURCE_EXHAUSTED",p);return new Promise((y,N)=>{let m=typeof a.operation_id=="string"?a.operation_id:void 0,S=setTimeout(()=>{i.delete(p),N(new o(F(c)?"COMMIT_UNKNOWN":"CALL_TIMEOUT",p,m))},3e4);i.set(p,{resolve:y,reject:N,timer:S,operationId:m,method:c}),n.port1.postMessage({requestId:p,method:c,args:a},c==="files.chunk"&&a.data instanceof ArrayBuffer?[a.data]:[])})},close:()=>w()}}var q=class t{constructor(e){O(this,"filters");this.filters=e}and(e){return new t([{op:"and",filters:[...this.filters,...e.filters]}])}or(e){return new t([{op:"or",filters:[...this.filters,...e.filters]}])}},D=class{constructor(e,n,s=0){O(this,"op");O(this,"value");O(this,"offset");this.op=e,this.value=n,this.offset=s}};function U(t,e){let n=e instanceof Date;if(n&&!Number.isFinite(e.getTime()))throw new o("SCHEMA_INVALID");if(["in","nin"].includes(t)){if(!Array.isArray(e)||e.length>100||e.length===0)throw new o("SCHEMA_INVALID");let s=e.every(r=>r instanceof Date);if(e.some(r=>r instanceof Date)&&!s)throw new o("SCHEMA_INVALID");return new q([{op:t,value:s?e.map(r=>r.getTime()):e,...s?{value_type:"date"}:{}}])}if(!T(n?e.getTime():e))throw new o("SCHEMA_INVALID");return new q([{op:t,value:n?e.getTime():e,...n?{value_type:"date"}:{}}])}function Ce(t,e){if(e.length<1)throw new o("SCHEMA_INVALID");return new q([{op:t,filters:e.map(n=>X(n))}])}var Ne=Object.freeze({eq:t=>U("eq",t),neq:t=>U("neq",t),gt:t=>U("gt",t),gte:t=>U("gte",t),lt:t=>U("lt",t),lte:t=>U("lte",t),in:t=>U("in",t),nin:t=>U("nin",t),exists:t=>U("exists",t),and:(...t)=>Ce("and",t),or:(...t)=>Ce("or",t),inc:t=>{if(!Number.isFinite(t))throw new o("SCHEMA_INVALID");return new D("inc",t)},set:t=>new D("set",t),remove:()=>new D("remove")});function B(t,e=!1){let n=t.split(".");if(!t||n.length>16||n.some(s=>!/^[A-Za-z][A-Za-z0-9_]*$/.test(s)&&!(e&&n.length===1&&["_id","_openid","_version"].includes(s))||["__proto__","prototype","constructor"].includes(s)))throw new o("SCHEMA_INVALID")}function X(t,e){if(t instanceof q){let s=function(r){return r.filters?{...r,filters:r.filters.map(s)}:{...r,...e?{field:e}:{}}};return t.filters.length===1?s(t.filters[0]):{op:"and",filters:t.filters.map(s)}}if(!h(t)||!Object.keys(t).length)throw new o("SCHEMA_INVALID");let n=Object.entries(t).map(([s,r])=>(B(s,!0),X(r instanceof q?r:U("eq",r),s)));return n.length===1?n[0]:{op:"and",filters:n}}function J(t,e){if(!h(t))throw new o("SCHEMA_INVALID");let n={},s=[],r=new Set,f=0,u=[],d=_=>{if(u.some(c=>c===_||c.startsWith(`${_}.`)||_.startsWith(`${c}.`)))throw new o("SCHEMA_INVALID");u.push(_)};function i(_,c,a,p){if(++f>1e4||c.length>16)throw new o("SCHEMA_INVALID");let y=c.join(".");if(_ instanceof D){if(!p||e!=="update"&&_.op!=="serverDate")throw new o("UNSUPPORTED_OPERATION");if(d(y),_.op==="set"){let m={};s.push({op:"set",path:y,value:i(_.value,[],m,!1),value_types:m})}else s.push({op:_.op,path:y,..._.op==="inc"?{value:_.value}:{},..._.op==="serverDate"?{offset:_.offset}:{}});return}if(_ instanceof Date){if(!Number.isFinite(_.getTime()))throw new o("SCHEMA_INVALID");return a[c.length?`/${c.join("/")}`:""]="date",_.getTime()}if(_===null||typeof _=="boolean"||typeof _=="string"||typeof _=="number"&&Number.isFinite(_))return _;if(typeof _!="object"||_===null||!h(_)&&!Array.isArray(_)||r.has(_))throw new o("SCHEMA_INVALID");r.add(_);let N;if(Array.isArray(_))N=_.map((m,S)=>i(m,[...c,String(S)],a,!1));else{let m={};for(let[S,A]of Object.entries(_)){if(B(S),S.includes(".")&&e!=="update")throw new o("SCHEMA_INVALID");let g=[...c,...S.split(".")],P=i(A,g,a,p);P!==void 0&&(m[S]=P)}N=m}return r.delete(_),N}function l(_,c){for(let[a,p]of Object.entries(_)){B(a);let y=[...c,...a.split(".")];if(y.length>16)throw new o("SCHEMA_INVALID");if(h(p)&&Object.keys(p).length){if(r.has(p))throw new o("SCHEMA_INVALID");r.add(p),l(p,y),r.delete(p)}else if(p instanceof D)i(p,y,n,!0);else{d(y.join("."));let N={};s.push({op:"set",path:y.join("."),value:i(p,[],N,!1),value_types:N})}}}let w={};e==="update"?l(t,[]):w=i(t,[],n,!0);let I={data:w,value_types:n,field_operations:s};if(!T(I)||s.length>256)throw new o("SCHEMA_INVALID");return I}function Te(t,e){if(!T(t))throw new o("PROTOCOL_MISMATCH");function n(s,r){let f=e[`/${r.join("/")}`];if(f!==void 0){if(f!=="date"||typeof s!="number"||!Number.isSafeInteger(s)||Math.abs(s)>864e13)throw new o("PROTOCOL_MISMATCH");return new Date(s)}return Array.isArray(s)?s.map((u,d)=>n(u,[...r,String(d)])):h(s)?Object.fromEntries(Object.entries(s).map(([u,d])=>[u,n(d,[...r,u])])):s}return n(t,[])}function R(t,e){let n=Promise.resolve().then(e);if(!t||![t.success,t.fail,t.complete].some(s=>typeof s=="function"))return n;n.then(s=>{try{t.success?.(s)}finally{t.complete?.(s)}},s=>{let r=s instanceof o?s:new o("RUNTIME_UNAVAILABLE");try{t.fail?.(r)}finally{t.complete?.(r)}}).catch(()=>{})}function Me(t){if(!t||new TextEncoder().encode(t).length>128||[...t].some(e=>{let n=e.codePointAt(0)??0;return n<32||n===127||e==="/"||e==="\\"}))throw new o("SCHEMA_INVALID");return t}var Le="DYNAMIC_CURRENT_ENV";function ve(t){if(h(t)){let e=Object.values(t);if(!e.length||!e.every(n=>n===e[0]))throw new o("ENV_MISMATCH");t=e[0]}if(t===Le)return t;if(t!=="dev"&&t!=="prod")throw new o("ENV_MISMATCH");return t}function G(t,e){if(!h(t)||!h(e))throw new o("PROTOCOL_MISMATCH");let n=Te(t,e);if(n._version!==void 0){if(typeof n._version!="number"&&typeof n._version!="string")throw new o("PROTOCOL_MISMATCH");n._version=String(n._version)}return n}function ne(t,e,n){if(typeof t.operation_id!="string"||!L.test(t.operation_id)||n!==void 0&&t.operation_id!==n||!h(t.stats))throw new o("PROTOCOL_MISMATCH",e);let s=t.stats,r=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>=0,f=s.created===void 0?0:s.created,u=s.updated===void 0?0:s.updated,d=s.removed===void 0?0:s.removed;if(!r(f)||!r(u)||!r(d))throw new o("PROTOCOL_MISMATCH",e,t.operation_id);let i=h(t.document)?t.document:null;return{...typeof i?._id=="string"?{_id:i._id}:{},stats:{created:f,updated:u,removed:d},errMsg:"database:ok",_meta:{requestId:e,operationId:t.operation_id,...typeof i?._version=="number"||typeof i?._version=="string"?{version:String(i._version)}:{}}}}var Q=class t{constructor(e,n,s={}){O(this,"session");O(this,"key");O(this,"query");this.session=e,this.key=n,this.query=s}with(e){return new t(this.session,this.key,{...this.query,...e})}where(e){let n=X(e);return this.with({filter:this.query.filter?{op:"and",filters:[this.query.filter,n]}:n})}orderBy(e,n){if(B(e,!0),n!=="asc"&&n!=="desc")throw new o("SCHEMA_INVALID");let s=this.query.order_by??[];if(s.length>=4)throw new o("RESOURCE_EXHAUSTED");return this.with({order_by:[...s,{field:e,direction:n}]})}limit(e){if(!Number.isSafeInteger(e)||e<1||e>100)throw new o("RESOURCE_EXHAUSTED");return this.with({limit:e})}skip(e){if(!Number.isSafeInteger(e)||e<0||e>1e3)throw new o("RESOURCE_EXHAUSTED");return this.with({skip:e})}field(e){if(!h(e))throw new o("SCHEMA_INVALID");let n=new Set;for(let[s,r]of Object.entries(e)){if(B(s,!0),typeof r!="boolean")throw new o("SCHEMA_INVALID");s!=="_id"&&n.add(r)}if(n.size>1)throw new o("SCHEMA_INVALID");return this.with({projection:{...e}})}get(e){return R(e,async()=>{let{value:n,requestId:s}=await this.session.request("documents.query",{collection_key:this.key,operation:"get",limit:20,skip:0,...this.query});if(!Array.isArray(n.list)||!Array.isArray(n.value_types)||n.list.length!==n.value_types.length)throw new o("PROTOCOL_MISMATCH",s);let r=n.value_types;return{data:n.list.map((f,u)=>G(f,r[u])),errMsg:"collection.get:ok",_meta:{requestId:s}}})}count(e){return R(e,async()=>{let{value:n,requestId:s}=await this.session.request("documents.query",{collection_key:this.key,operation:"count",...this.query});if(!Number.isSafeInteger(n.total)||Number(n.total)<0)throw new o("PROTOCOL_MISMATCH",s);return{total:n.total,errMsg:"collection.count:ok",_meta:{requestId:s}}})}watch(e){return Promise.resolve().then(async()=>{let n=e?.cursor,s=n===void 0?0:Number(n);if(n!==void 0&&(typeof n!="string"||!/^(0|[1-9]\d*)$/.test(n)))throw new o("SCHEMA_INVALID");let r=e?.maxDocs??100;if(!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(r)||r<1||r>100)throw new o("SCHEMA_INVALID");if(e?.query!==void 0&&!h(e.query))throw new o("SCHEMA_INVALID");let f=e?.query===void 0?this.query:{...this.query,...e.query};if(!h(f)||!E(f,["filter","order_by","projection","limit","skip"]))throw new o("SCHEMA_INVALID");let{value:u,requestId:d}=await this.session.request("documents.snapshot",{collection_key:this.key,query:f,cursor:s,max_docs:r}),i=u;if(!Array.isArray(i.list)||!Array.isArray(i.value_types)||i.list.length!==i.value_types.length||typeof i.cursor!="string"||!/^(0|[1-9]\d*)$/.test(i.cursor)||!Number.isSafeInteger(Number(i.cursor))||typeof i.has_more!="boolean")throw new o("PROTOCOL_MISMATCH",d);return{data:i.list.map((l,w)=>G(l,i.value_types[w])),cursor:i.cursor,changed:i.cursor!==String(s),hasMore:i.has_more,errMsg:"collection.watch:ok",_meta:{requestId:d}}})}after(){throw new o("UNSUPPORTED_OPERATION")}onChange(e){if(typeof e!="function")throw new o("SCHEMA_INVALID");return this.session.onEvent?this.session.onEvent(n=>{n.collection_key!==void 0&&n.collection_key!==this.key||e(n)}):()=>{}}update(){throw new o("UNSUPPORTED_OPERATION")}remove(){throw new o("UNSUPPORTED_OPERATION")}},ee=class{constructor(e,n,s,r){O(this,"session");O(this,"collection");O(this,"id");O(this,"throwOnNotFound");this.session=e,this.collection=n,this.id=s,this.throwOnNotFound=r}get(e){return R(e,async()=>{try{let{value:n,requestId:s}=await this.session.request("documents.query",{collection_key:this.collection,document_key:this.id,operation:"get"});if(!Array.isArray(n.list)||n.list.length!==1||!Array.isArray(n.value_types))throw new o("PROTOCOL_MISMATCH",s);return{data:G(n.list[0],n.value_types[0]),errMsg:"document.get:ok",_meta:{requestId:s}}}catch(n){if(!this.throwOnNotFound&&n instanceof o&&n.errCode==="DOCUMENT_NOT_FOUND")return{data:null,errMsg:"document.get:ok",_meta:{requestId:n.requestId??""}};throw n}})}mutate(e,n,s){return R(s,async()=>{if(!h(n))throw new o("SCHEMA_INVALID");let r=n,f=r.agentos?.operationId??this.session.createId(),u=r.agentos?.expectedVersion;if(u!==void 0&&(!/^[1-9]\d*$/.test(u)||!Number.isSafeInteger(Number(u))))throw new o("SCHEMA_INVALID",void 0,f);let d={collection_key:this.collection,document_key:this.id,operation:e,operation_id:f,..."data"in r?J(r.data,e):{},...u===void 0?{}:{expected_version:u}},{value:i,requestId:l}=await this.session.request("documents.mutate",d);return ne(i,l,f)})}set(e){return this.mutate("set",e,e)}update(e){return this.mutate("update",e,e)}remove(e={}){return this.mutate("remove",e,e)}},te=class extends Q{constructor(n,s,r){super(n,s);O(this,"throwOnNotFound");this.throwOnNotFound=r}doc(n){return new ee(this.session,this.key,Me(n),this.throwOnNotFound)}add(n){return R(n,async()=>{if(!h(n)||!h(n.data))throw new o("SCHEMA_INVALID");let s=n.agentos?.operationId??this.session.createId(),{_id:r,...f}=n.data;if(r!==void 0&&typeof r!="string")throw new o("SCHEMA_INVALID",void 0,s);let{value:u,requestId:d}=await this.session.request("documents.mutate",{collection_key:this.key,operation:"add",operation_id:s,...J(f,"add"),...typeof r=="string"?{document_key:Me(r)}:{}});return ne(u,d,s)})}};function $e(t=ge){let e=null,n=null,s=0,r=null,f=0;function u(c,a,p){let y=c.limits[a];return typeof y=="number"&&Number.isSafeInteger(y)&&y>0?Math.min(p,y):p}function d(c){try{return new TextEncoder().encode(JSON.stringify(c)).byteLength}catch{return null}}let i={ready:()=>r??Promise.reject(new o("INIT_REQUIRED")),createId:()=>`op_${Math.floor((Date.now()+s)/1e3)}_${crypto.randomUUID().replaceAll("-","")}`,onEvent(c){return n?n.onEvent(c):()=>{}},request:async(c,a)=>{let p=await i.ready(),y=crypto.randomUUID(),N=c==="documents.snapshot"?"watch-snapshot/1":c.startsWith("execution.")?"app-execution/1":c.startsWith("files.")?"storage-object/1":"document-core/1";if(!p.profiles.includes(N))throw new o(c.startsWith("execution.")?"BACKGROUND_CAPABILITY_UNAVAILABLE":"UNSUPPORTED_OPERATION",y);let m=typeof a.operation_id=="string"?a.operation_id:void 0,S=u(p,"max_concurrent_requests",8);if(f>=S)throw new o("RESOURCE_EXHAUSTED",y,m);let A=u(p,"max_request_bytes",256*1024),g=d({method:c,args:a});if(g===null||g>A)throw new o("REQUEST_TOO_LARGE",y,m);if(!de({requestId:y,method:c,args:a})||m!==void 0&&!L.test(m))throw new o("SCHEMA_INVALID",y,m);function P(C){if(!p.operators.includes(C.op))throw new o("UNSUPPORTED_OPERATION",y,m);C.filters?.forEach(P)}if(h(a.filter)&&P(a.filter),c==="documents.snapshot"&&h(a.query)&&h(a.query.filter)&&P(a.query.filter),Array.isArray(a.field_operations)){for(let C of a.field_operations)if(!h(C)||!p.operators.includes(String(C.op)))throw new o("UNSUPPORTED_OPERATION",y,m)}let b=u(p,"max_query_limit",100),x=u(p,"max_query_skip",1e3),H=u(p,"max_watch_docs",100);if(typeof a.limit=="number"&&a.limit>b||typeof a.skip=="number"&&a.skip>x||c==="documents.snapshot"&&typeof a.max_docs=="number"&&a.max_docs>H)throw new o("RESOURCE_EXHAUSTED",y,m);f+=1;try{let C=await n.request(c,a,y);if(!h(C)||!(c==="files.read"?k(C):T(C,1024*1024)))throw new o("PROTOCOL_MISMATCH",y,m);return{value:C,requestId:y}}catch(C){let Se=C instanceof o?C.errCode:F(c)?"COMMIT_UNKNOWN":"RUNTIME_UNAVAILABLE",be=C instanceof o&&C.jobId&&C.invocationId?{jobId:C.jobId,invocationId:C.invocationId}:void 0;throw new o(Se,y,C instanceof o?C.operationId??m:m,be)}finally{f-=1}}},l=ye(i),w=fe(),I=Oe(i),_=c=>R(c,async()=>{throw await i.ready(),new o("UNSUPPORTED_OPERATION")});return{app:{getUpdateManager:ue,checkUpdate:le},auth:{authorize:_e,getIdentity:we},cloud:{DYNAMIC_CURRENT_ENV:Le,init(c){if(!h(c)||Object.keys(c).some(p=>!["env","traceUser"].includes(p)))throw new o("SCHEMA_INVALID");let a={env:ve(c.env),traceUser:c.traceUser??!1};if(e){if(JSON.stringify(e)!==JSON.stringify(a))throw new o("INIT_CONFLICT");return}e=a;try{n=t(a.env),r=n.ready().then(p=>{if(p.protocol.major!==2||!p.profiles.some(y=>["document-core/1","app-execution/1","storage-object/1","watch-snapshot/1"].includes(y)))throw new o("PROTOCOL_MISMATCH");return s=p.serverTime*1e3-Date.now(),p})}catch(p){r=Promise.reject(p instanceof o?p:new o("RUNTIME_UNAVAILABLE"))}r.catch(()=>{})},database(c={}){if(Object.keys(c).some(a=>a!=="throwOnNotFound"))throw new o("SCOPE_FORBIDDEN");return{command:Ne,collection:a=>{if(!/^[a-z][a-z0-9_]{0,63}$/.test(a)||/^(sys_|ac_|t_)/.test(a))throw new o("SCHEMA_INVALID");return new te(i,a,c.throwOnNotFound!==!1)},serverDate:(a={})=>{let p=a.offset??0;if(!Number.isSafeInteger(p)||Math.abs(p)>864e5)throw new o("SCHEMA_INVALID");return new D("serverDate",void 0,p)},runTransaction:_}},callFunction(c){return R(c,()=>l.callFunction(c))},uploadFile(c){return R(c,()=>I.upload(c))},downloadFile(c){return R(c,()=>I.download(c.fileID))},deleteFile(c){return R(c,()=>I.remove(c))},getTempFileURL:_,os:{files:{getOperation:I.getOperation,cancel:I.cancel,stat:I.stat},capabilities:l.capabilities,jobs:l.jobs,api:w,ready:()=>i.ready(),getCapabilities:async()=>structuredClone(await i.ready()),close:()=>n?.close(),operations:{createId:()=>i.createId(),get:async c=>{if(!L.test(c))throw new o("SCHEMA_INVALID");let{value:a,requestId:p}=await i.request("operations.get",{operation_id:c});if(a.operation_id!==c||a.state!=="succeeded"||!h(a.result))throw new o("PROTOCOL_MISMATCH",p,c);return{operationId:c,state:"succeeded",result:ne(a.result,p)}}}}}}}var wt=$e();export{M as AppError,o as CloudError,Le as DYNAMIC_CURRENT_ENV,k as boundedBinary,$e as createCloudClient,F as writesCloud,wt as zl};
@@ -0,0 +1,11 @@
1
+ export interface ApiToken {
2
+ token: string;
3
+ baseUrl: string;
4
+ expiresAt: number;
5
+ }
6
+ /** Independent of the Cloud session: an app that only calls OS APIs has no Cloud data. */
7
+ export declare function requestAppApiToken(): Promise<ApiToken>;
8
+ export declare function createApi(requestToken?: () => Promise<ApiToken>): {
9
+ token: () => Promise<ApiToken>;
10
+ fetch: (path: string, init?: RequestInit) => Promise<Response>;
11
+ };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 应用运行期能力(与云数据库无关,未开通云资源的应用也能用):
3
+ *
4
+ * - `zl.app.getUpdateManager()`:检查与应用线上版本更新(参照 wx.getUpdateManager)。
5
+ * 发布新线上版本后,正在使用的窗口继续跑旧版本;应用可以监听 `onUpdateReady` 提示用户,
6
+ * 调用 `applyUpdate()` 立即切换到新版本并重新加载。
7
+ * - `zl.auth.authorize({ scopes, reason })`:唤起系统授权框,用户同意后拿到头像昵称 / 手机号 / 邮箱;
8
+ * 要在用户点击时调用;manifest `host_api.requires` 须声明 `user.profile` / `user.phone` / `user.email`;
9
+ * `zl.auth.getIdentity()`:静默拿到本应用内的用户标识 openid(以及已同意范围的信息)。
10
+ *
11
+ * 通道:应用 iframe 用 MessagePort 连接宿主(`__zleap_app_connect`),宿主用当前用户会话调用平台接口,
12
+ * 应用永远拿不到用户令牌或平台用户 ID。
13
+ *
14
+ * 编码:utf8 | 语言:TypeScript | 作者:Claude | 日期:2026-11-01
15
+ */
16
+ export declare const APP_CONNECT = "__zleap_app_connect";
17
+ export declare const APP_READY = "__zleap_app_ready";
18
+ export declare const APP_EVENT = "__zleap_app_event";
19
+ export declare const APP_PROTOCOL = 1;
20
+ export declare class AppError extends Error {
21
+ readonly errCode: string;
22
+ constructor(errCode: string, message?: string);
23
+ }
24
+ export type AuthScope = 'profile' | 'phone' | 'email';
25
+ export interface AuthResult {
26
+ /** 本应用内的用户标识;同一用户在开发与线上一致,不同应用之间不同 */
27
+ openid: string;
28
+ /** 本次返回的范围 */
29
+ scopes: AuthScope[];
30
+ profile?: {
31
+ nickname: string;
32
+ avatarUrl: string | null;
33
+ };
34
+ phone?: string | null;
35
+ email?: string | null;
36
+ }
37
+ export interface UpdateCheckResult {
38
+ hasUpdate: boolean;
39
+ currentVersion: string | null;
40
+ latestVersion: string | null;
41
+ notes: string | null;
42
+ /**
43
+ * 旧版本可用到的时间(毫秒时间戳):新版本发布 24 小时后,宿主会自动把旧窗口切到新版本并重新加载。
44
+ * 没有更新或你是应用成员时为 null。
45
+ */
46
+ deadline: number | null;
47
+ }
48
+ export interface UpdateManager {
49
+ /** 检查结果回调(每次获取更新管理器后宿主检查一次) */
50
+ onCheckForUpdate(callback: (result: UpdateCheckResult) => void): void;
51
+ /** 有新的线上版本可用时回调(检查时发现,或使用过程中有成员发布了新版本) */
52
+ onUpdateReady(callback: (result: UpdateCheckResult) => void): void;
53
+ /** 切换失败回调(例如新版本的数据声明与当前不兼容,需要用户在应用中心手动更新) */
54
+ onUpdateFailed(callback: (error: AppError) => void): void;
55
+ /** 立即切换到新版本并重新加载应用 */
56
+ applyUpdate(): Promise<void>;
57
+ }
58
+ /** 获取全局唯一的更新管理器(多次调用返回同一个) */
59
+ export declare function getUpdateManager(): UpdateManager;
60
+ /** 立即检查一次是否有新的线上版本(不触发回调) */
61
+ export declare function checkUpdate(): Promise<UpdateCheckResult>;
62
+ /**
63
+ * 唤起系统授权框;已同意过的范围不再弹框。
64
+ *
65
+ * - 需要弹框时必须在用户点击(或按键)后立即调用,否则 `AUTH_GESTURE_REQUIRED`;
66
+ * - 用户可以只勾选一部分:结果的 `scopes` 只含实际同意的项,没同意 / 没绑定的项不在结果里;
67
+ * - 用户拒绝时 `AUTH_DENIED`;拒绝过的项 24 小时内再申请不弹框,直接 `AUTH_DENIED`;
68
+ * - manifest 没声明的项 `AUTH_SCOPE_UNDECLARED`。
69
+ *
70
+ * `reason` 是显示在授权框里的用途说明(最多 60 字),例如「用于预订成功后短信通知你」。
71
+ */
72
+ export declare function authorize(options: {
73
+ scopes: AuthScope[];
74
+ reason?: string;
75
+ }): Promise<AuthResult>;
76
+ /** 静默获取 openid(以及之前已同意范围的信息),不弹框 */
77
+ export declare function getIdentity(): Promise<AuthResult>;
@@ -0,0 +1,73 @@
1
+ import { type CloudMethod, type Capabilities } from './protocol.js';
2
+ interface Session {
3
+ ready(): Promise<Capabilities>;
4
+ request(method: CloudMethod, args: Record<string, unknown>): Promise<{
5
+ value: Record<string, unknown>;
6
+ requestId: string;
7
+ }>;
8
+ createId(): string;
9
+ }
10
+ export interface JobResult {
11
+ jobId: string;
12
+ invocationId: string;
13
+ operationId: string;
14
+ status: string;
15
+ result: unknown;
16
+ errorCode: string | null;
17
+ committedSteps: string[];
18
+ }
19
+ export interface CapabilityInput {
20
+ id: string;
21
+ input: Record<string, unknown>;
22
+ operationId?: string;
23
+ /**
24
+ * 提交后同步等待终态的秒数(0–25,默认 0 立即返回)。
25
+ *
26
+ * 服务端的等待本身就是 250 ms 粒度的轮询,所以让提交等在这里、而不是让每个
27
+ * 调用方自己写一个定时器去 `jobs.get`:后者既把延迟下限抬到调用方的间隔,
28
+ * 又让每次提交都多出若干次往返。窗口上限由平台定,超出会被拒。
29
+ */
30
+ waitSeconds?: number;
31
+ }
32
+ export interface JobInput {
33
+ kind: 'capability';
34
+ capability: string;
35
+ input: Record<string, unknown>;
36
+ operationId?: string;
37
+ waitSeconds?: number;
38
+ }
39
+ export interface JobWaitInput {
40
+ jobId: string;
41
+ timeoutSeconds?: number;
42
+ pollMilliseconds?: number;
43
+ }
44
+ export interface FunctionInput {
45
+ name: string;
46
+ data?: Record<string, unknown>;
47
+ agentos?: {
48
+ operationId?: string;
49
+ };
50
+ }
51
+ export declare function executionResult(raw: Record<string, unknown>): JobResult;
52
+ export declare function createExecution(session: Session): {
53
+ capabilities: {
54
+ invoke: (args: CapabilityInput) => Promise<JobResult>;
55
+ };
56
+ jobs: {
57
+ submit: (args: JobInput) => Promise<JobResult>;
58
+ get: (args: {
59
+ jobId: string;
60
+ }) => Promise<JobResult>;
61
+ result: (args: {
62
+ jobId: string;
63
+ }) => Promise<JobResult>;
64
+ wait: (args: JobWaitInput) => Promise<JobResult>;
65
+ cancel: (args: {
66
+ jobId: string;
67
+ }) => Promise<{
68
+ cancelRequested: boolean;
69
+ }>;
70
+ };
71
+ callFunction: (args: FunctionInput) => Promise<JobResult>;
72
+ };
73
+ export {};
@@ -0,0 +1,61 @@
1
+ import { CloudError, type Capabilities, type CloudMethod } from './protocol.js';
2
+ type Session = {
3
+ ready(): Promise<Capabilities>;
4
+ request(method: CloudMethod, args: Record<string, unknown>): Promise<{
5
+ value: Record<string, unknown>;
6
+ requestId: string;
7
+ }>;
8
+ createId(): string;
9
+ };
10
+ export interface UploadInput {
11
+ cloudPath: string;
12
+ filePath: Blob;
13
+ agentos?: {
14
+ operationId?: string;
15
+ overwrite?: boolean;
16
+ expectedETag?: string;
17
+ };
18
+ }
19
+ export interface UploadResult {
20
+ fileID: string;
21
+ etag: string;
22
+ sha256: string;
23
+ size: number;
24
+ errMsg: string;
25
+ }
26
+ export interface DownloadResult {
27
+ fileContent: Blob;
28
+ errMsg: string;
29
+ }
30
+ export interface DeleteInput {
31
+ fileList: string[];
32
+ /** expectedETags 必填:fileList 里每个 fileID 都要有当前 etag,缺了 SDK 抛 SCHEMA_INVALID(删除只做 CAS,不做无条件删除)。 */
33
+ agentos: {
34
+ operationId?: string;
35
+ expectedETags: Record<string, string>;
36
+ };
37
+ }
38
+ export interface DeleteResult {
39
+ deleted: string[];
40
+ failed: Array<{
41
+ fileID: string;
42
+ error: CloudError;
43
+ }>;
44
+ errMsg: string;
45
+ }
46
+ type Operation = {
47
+ operation_id: string;
48
+ state: 'pending' | 'succeeded' | 'cancelled';
49
+ chunk_size?: number;
50
+ received?: number[];
51
+ file?: Record<string, unknown> | null;
52
+ };
53
+ export declare function createFiles(session: Session): {
54
+ upload: (input: UploadInput) => Promise<UploadResult>;
55
+ download: (fileID: string) => Promise<DownloadResult>;
56
+ remove: (input: DeleteInput) => Promise<DeleteResult>;
57
+ stat: (fileID: string) => Promise<UploadResult>;
58
+ getOperation: (operationValue: string) => Promise<Operation>;
59
+ cancel: (operationValue: string) => Promise<Operation>;
60
+ };
61
+ export {};