@lark-base-open/base-database-app-sdk 0.6.0-durable.1 → 0.6.0-durable.3

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/CHANGELOG.md CHANGED
@@ -1,21 +1,19 @@
1
1
  # Changelog
2
2
 
3
- ## [0.6.0-durable.1] - 2026-11-03
3
+ ## [0.6.0-durable.3] - 2026-11-08
4
4
 
5
- ### Fixed
5
+ ### Changed
6
6
 
7
- - 修复 Durable Function 契约生成失败,codegen 直接接受 `functionType: 6` 并保留控制命令参数与输出类型。
7
+ - DurableError 改为 code、message、logId,保留服务端错误说明与网络原因。
8
+ - Durable events 可省略;schema 错误附前三条字段路径,脱敏保留长记录 ID。
9
+ - 导出可增强的 DurableFunctions,start 推断 input,get/signal 支持显式泛型;StepView 增加 lastError。
10
+ - 更新声明式 Trigger、环境边界与 CLI 类型生成文档。
8
11
 
9
- ## [0.6.0-durable.0] - 2026-11-03
12
+ ## [0.6.0-durable.2] - 2026-11-05
10
13
 
11
14
  ### Added
12
15
 
13
- - 在 0.5.2 功能基线上提供 `/durable/workflow` 与 `/durable/activity`,支持持久化步骤、等待、进度、事件及站点 Function 调用。
14
- - 提供 Durable 使用文档和可编译的 Workflow/Activity 示例。
15
-
16
- ### Compatibility
17
-
18
- - Durable 入口需要平台提供匹配的托管运行时;Temporal 1.24.0 作为可选 peer 依赖提供。
16
+ - 支持 Durable Function。
19
17
 
20
18
  ## 0.5.2 - 2026-10-30
21
19
 
@@ -45,12 +43,6 @@
45
43
  - 页面启动时向平台报告所用的 SDK 版本,便于排查问题。
46
44
  - 页面出现未处理的错误时,错误信息会上报给平台;内容会截断,并去掉链接里的参数。
47
45
 
48
- ## [0.5.0-durable.0] - 2026-10-26
49
-
50
- ### Added
51
-
52
- - 新增 Durable Workflow 与 Activity 入口,支持持久化步骤、等待、进度和站点 Function 调用。
53
-
54
46
  ## 0.4.2 - 2026-10-26
55
47
 
56
48
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  用于开发以飞书多维表格为数据后端的 Base Database 应用,提供页面与服务端运行时、平台组件、版本化能力查询与测试工具。
4
4
 
5
- 安装:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.1`。从旧版本升级前请阅读 [变更记录](CHANGELOG.md)。
5
+ 安装:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.3`。从旧版本升级前请阅读 [变更记录](CHANGELOG.md)。
6
6
 
7
7
  运行环境需支持 ES2022;页面 API 需要 Base Database 页面宿主,服务端 API 用于 Node.js / FaaS。组件需要 React 与 React DOM 19.2,页面查询能力使用 @tanstack/react-query 5.104.1;npm 会安装声明的依赖与必需 peer。底层通信依赖 base-site-channel 0.2.1。
8
8
 
@@ -34,8 +34,6 @@ SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务
34
34
 
35
35
  新建工程可显式开启 `styleScope: 'components'` 隔离业务样式;主题和迁移契约见 [启动说明](docs/start-base-app.md)。
36
36
 
37
- ## Durable Function
37
+ ## Durable Function(开发分支)
38
38
 
39
- 本预发布版本通过 npm 的 `durable` 标签提供 `/durable/workflow` 和 `/durable/activity` 持久化函数 API,见 [Durable 文档](docs/durable.md)。
40
-
41
- 使用前需确认平台部署了匹配的 Durable 运行时;Temporal 为可选 peer,仅 Durable 开发和执行环境安装匹配版本,普通页面和普通 Function 不依赖它。ESM import 与 CJS require 共享 Durable 模块。
39
+ `/server` 提供 `defineDurableFunction`、`durable` 和错误类型,见 [Durable 文档](docs/durable.md)。本分支接口尚未发布,本地联调使用构建后的 tarball。长时任务在站点 Function 内执行,由平台逐步推进,不需要安装额外执行引擎依赖。
package/capabilities.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "sdkVersion": "0.6.0-durable.1",
3
+ "sdkVersion": "0.6.0-durable.3",
4
4
  "capabilities": {
5
5
  "runtime.diagnostic": {
6
6
  "required": [
package/dist/codegen.cjs CHANGED
@@ -13,5 +13,5 @@ export type ${t} = unknown;`}}function _(n){if(!n||n.type!=="object")return;let
13
13
  return response.data as ${a};
14
14
  },`)}return r.push(`declare module '${p}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...e,"};",""),r.join(`
15
15
  `)}function j(n,t){let i=structuredClone(n);return f(i,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),i.title=t,i}function d(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function w(n){return n===null?"null":typeof n=="string"||typeof n=="boolean"?JSON.stringify(n):typeof n=="number"&&Number.isFinite(n)?Object.is(n,-0)?"-0":String(n):Array.isArray(n)?`[${n.map(w).join(", ")}]`:d(n)?`{ ${Object.entries(n).map(([t,i])=>`${JSON.stringify(t)}: ${w(i)}`).join("; ")} }`:"never"}function P(n,t){switch(t){case"string":return typeof n=="string";case"integer":return typeof n=="number"&&Number.isInteger(n);case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"null":return n===null;case"array":return Array.isArray(n);case"object":return d(n);default:return!1}}function G(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(t=>typeof t=="string"):[]}function J(n,t){switch(t){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let i=n.prefixItems,r=Array.isArray(i),e=r?i.filter(d):[];if(r&&n.minItems===e.length&&n.maxItems===e.length)return`[${e.map(y).join(", ")}]`;let o=d(n.items)?y(n.items):"unknown";return e.length===0?`Array<${o}>`:`[${[...e.map(u=>`${y(u)}?`),`...Array<${o}>`].join(", ")}]`}case"object":{let i=d(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(c=>typeof c=="string"):[]),e=Object.entries(i).filter(c=>d(c[1])),o=new Set(e.map(([c])=>c)),s=[...r].filter(c=>!o.has(c));if(s.length>0&&n.additionalProperties===!1)return"never";let u=e.map(([c,g])=>`${JSON.stringify(c)}${r.has(c)?"":"?"}: ${y(g)}`);u.push(...s.map(c=>`${JSON.stringify(c)}: unknown`));let a=`{ ${u.join("; ")} }`;return n.additionalProperties===!1?u.length===0?"Record<string, never>":a:`${a} & Record<string, unknown>`}default:return"unknown"}}function y(n){let t=["anyOf","oneOf","allOf"].filter(e=>Array.isArray(n[e]));if(t.length){let e={...n};for(let u of t)delete e[u];let o=t.map(u=>{let a=n[u].filter(d).map(y);return a.length?a.map(c=>`(${c})`).join(u==="allOf"?" & ":" | "):"never"}),s=y(e);return s!=="unknown"&&o.unshift(s),o.map(u=>`(${u})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let i=G(n);if(Array.isArray(n.enum)&&n.enum.length>0){let e=n.enum.filter(o=>i.length===0||i.some(s=>P(o,s)));return e.length===0?"never":e.map(w).join(" | ")}let r=[...new Set(i.map(e=>J(n,e)))];return r.length===0?"unknown":r.join(" | ")}function F(n){let t=[...n].sort((e,o)=>e.functionId<o.functionId?-1:e.functionId>o.functionId?1:0),i=t.map(e=>` ${JSON.stringify(e.functionId)}: ${y(e.inputSchema)}`),r=t.flatMap(e=>{let o=Object.entries(e.parameterOptions??{});return o.length===0?[]:[` ${JSON.stringify(e.functionId)}: {`,...o.map(([s,u])=>` ${JSON.stringify(s)}: ${JSON.stringify(u)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...i,"}",...r.length?["","/** Fixed options declared as enum, keyed by Function ID and parameter name; the Agent-facing schema uses the same values. */","// prettier-ignore","export const DatabaseFunctionParameterOptions = {",...r,"} as const"]:[],""].join(`
16
- `)}var U=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},k=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function S(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let t=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&t();let i;try{i=JSON.stringify(n)}catch{return t()}Buffer.byteLength(i)>4*1024*1024&&t();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return t();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return t();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&t(),o==="inputs"&&!I(a.inputSchema)&&t(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&t();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{t()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&t()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&t();let e=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&e.has(o.functionId)&&e.get(o.functionId)!==o.functionType)&&t()}async function L(n){if(S(n),n.previousAugmentation!==void 0&&![b,O,k].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let t=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await $(n.functions,n.inputs)}
16
+ `)}var U=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},k=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function S(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let t=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&t();let i;try{i=JSON.stringify(n)}catch{return t()}Buffer.byteLength(i)>4*1024*1024&&t();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return t();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return t();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&t(),o==="inputs"&&!I(a.inputSchema)&&t(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&t();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{t()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&t()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&t();let e=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&e.has(o.functionId)&&e.get(o.functionId)!==o.functionType)&&t()}async function L(n){if(S(n),n.previousAugmentation!==void 0&&![b,O,k].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let t=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await $(n.functions,n.inputs)}
17
17
  ${F(n.inputs)}`}];return n.client&&t.push({path:"page/src/generated/functions.ts",content:await N(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&t.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?k:b:O}),t}0&&(module.exports={CodegenError,SUPPORTED_CONTRACT_FORMAT_VERSIONS,generateFunctionClients,validateContractData});
@@ -9,7 +9,7 @@ declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
9
9
  interface FunctionInputContract {
10
10
  functionId: string;
11
11
  /** CLI also supplies the type when regenerating a legacy helper without client contracts. */
12
- functionType?: 1 | 2 | 5 | 6;
12
+ functionType?: 1 | 2 | 5;
13
13
  inputSchema: Record<string, unknown>;
14
14
  parameterOptions?: Record<string, unknown[]>;
15
15
  }
package/dist/codegen.d.ts CHANGED
@@ -9,7 +9,7 @@ declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
9
9
  interface FunctionInputContract {
10
10
  functionId: string;
11
11
  /** CLI also supplies the type when regenerating a legacy helper without client contracts. */
12
- functionType?: 1 | 2 | 5 | 6;
12
+ functionType?: 1 | 2 | 5;
13
13
  inputSchema: Record<string, unknown>;
14
14
  parameterOptions?: Record<string, unknown[]>;
15
15
  }
package/dist/codegen.js CHANGED
@@ -13,5 +13,5 @@ export type ${e} = unknown;`}}function k(n){if(!n||n.type!=="object")return;let
13
13
  return response.data as ${a};
14
14
  },`)}return r.push(`declare module '${p}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),r.join(`
15
15
  `)}function S(n,e){let i=structuredClone(n);return f(i,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),i.title=e,i}function d(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function w(n){return n===null?"null":typeof n=="string"||typeof n=="boolean"?JSON.stringify(n):typeof n=="number"&&Number.isFinite(n)?Object.is(n,-0)?"-0":String(n):Array.isArray(n)?`[${n.map(w).join(", ")}]`:d(n)?`{ ${Object.entries(n).map(([e,i])=>`${JSON.stringify(e)}: ${w(i)}`).join("; ")} }`:"never"}function C(n,e){switch(e){case"string":return typeof n=="string";case"integer":return typeof n=="number"&&Number.isInteger(n);case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"null":return n===null;case"array":return Array.isArray(n);case"object":return d(n);default:return!1}}function R(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(e=>typeof e=="string"):[]}function x(n,e){switch(e){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let i=n.prefixItems,r=Array.isArray(i),t=r?i.filter(d):[];if(r&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(y).join(", ")}]`;let o=d(n.items)?y(n.items):"unknown";return t.length===0?`Array<${o}>`:`[${[...t.map(u=>`${y(u)}?`),`...Array<${o}>`].join(", ")}]`}case"object":{let i=d(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(c=>typeof c=="string"):[]),t=Object.entries(i).filter(c=>d(c[1])),o=new Set(t.map(([c])=>c)),s=[...r].filter(c=>!o.has(c));if(s.length>0&&n.additionalProperties===!1)return"never";let u=t.map(([c,g])=>`${JSON.stringify(c)}${r.has(c)?"":"?"}: ${y(g)}`);u.push(...s.map(c=>`${JSON.stringify(c)}: unknown`));let a=`{ ${u.join("; ")} }`;return n.additionalProperties===!1?u.length===0?"Record<string, never>":a:`${a} & Record<string, unknown>`}default:return"unknown"}}function y(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let u of e)delete t[u];let o=e.map(u=>{let a=n[u].filter(d).map(y);return a.length?a.map(c=>`(${c})`).join(u==="allOf"?" & ":" | "):"never"}),s=y(t);return s!=="unknown"&&o.unshift(s),o.map(u=>`(${u})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let i=R(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(o=>i.length===0||i.some(s=>C(o,s)));return t.length===0?"never":t.map(w).join(" | ")}let r=[...new Set(i.map(t=>x(n,t)))];return r.length===0?"unknown":r.join(" | ")}function $(n){let e=[...n].sort((t,o)=>t.functionId<o.functionId?-1:t.functionId>o.functionId?1:0),i=e.map(t=>` ${JSON.stringify(t.functionId)}: ${y(t.inputSchema)}`),r=e.flatMap(t=>{let o=Object.entries(t.parameterOptions??{});return o.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...o.map(([s,u])=>` ${JSON.stringify(s)}: ${JSON.stringify(u)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...i,"}",...r.length?["","/** Fixed options declared as enum, keyed by Function ID and parameter name; the Agent-facing schema uses the same values. */","// prettier-ignore","export const DatabaseFunctionParameterOptions = {",...r,"} as const"]:[],""].join(`
16
- `)}var L=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},N=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function D(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let e=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&e();let i;try{i=JSON.stringify(n)}catch{return e()}Buffer.byteLength(i)>4*1024*1024&&e();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return e();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return e();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&e(),o==="inputs"&&!I(a.inputSchema)&&e(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&e();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{e()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&e();let t=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&t.has(o.functionId)&&t.get(o.functionId)!==o.functionType)&&e()}async function V(n){if(D(n),n.previousAugmentation!==void 0&&![b,A,N].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let e=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await h(n.functions,n.inputs)}
16
+ `)}var L=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},N=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function D(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let e=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&e();let i;try{i=JSON.stringify(n)}catch{return e()}Buffer.byteLength(i)>4*1024*1024&&e();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return e();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return e();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&e(),o==="inputs"&&!I(a.inputSchema)&&e(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&e();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{e()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&e();let t=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&t.has(o.functionId)&&t.get(o.functionId)!==o.functionType)&&e()}async function V(n){if(D(n),n.previousAugmentation!==void 0&&![b,A,N].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let e=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await h(n.functions,n.inputs)}
17
17
  ${$(n.inputs)}`}];return n.client&&e.push({path:"page/src/generated/functions.ts",content:await T(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&e.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?N:b:A}),e}export{m as CodegenError,L as SUPPORTED_CONTRACT_FORMAT_VERSIONS,V as generateFunctionClients,D as validateContractData};
package/dist/page.js CHANGED
@@ -1 +1 @@
1
- import{A as Ze,B as Se,C as fe,D as ge,E as Ae,F as Ie,G as ye,H as ke,I as Re,J as he,K as Fe,L as Te,M as $e,N as B,O as et,P as U,Q as tt,R as nt,S as N,T as ot,U as it,V as G,W as V,X as at,Y as rt,Z as st,_ as ct,a as J,b as X,c as Z,d as $,e as ee,f as te,g as ne,h as x,i as _,j as oe,k as ie,l as m,m as ae,n as re,o as se,p as ce,q as ue,r as de,s as me,t as le,u as pe,v as Ye,w as L,x as je,y as Je,z as Xe}from"./chunk-EG6R7YAD.js";import{a as We,b as Qe,c as v,d as h}from"./chunk-ZKBZAK4L.js";import{a as Ke}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as De}from"@lark-base-open/base-site-channel/runtime";function P(e={}){let t=!0,n,o=s=>{let c=h(s);e.onDiagnostic?e.onDiagnostic(c):console.warn("[Base Database SDK]",c)},a=e.runtime??m;return Promise.resolve().then(()=>a.getRuntimeContext()).then(s=>{if(t){if(!L(s,"link.open")){o(new v("link.open",1));return}n=De(e)}}).catch(s=>{t&&o(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as Vt}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var M=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):_})}},F=e=>({...e,channel:e?.channel?x(e.channel):_}),q=(e,t)=>u.callSiteAIFunction(e,F(t)),H=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),z=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),K=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var be=new Set(["cancelled","failed","queued","running","succeeded"]);async function Ce(e){let t=await q(e);return e.input&&!e.messages?y(t):t}function xe(e){return H(e)}function r(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.trim())return o}}function _e(e,t){for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return o}}function Pe(e){let t=r(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(D).map(t=>{let n=r(t,["size","Size"]),o=r(t,["token","Token"]),a=r(t,["url","URL"]);return{safetyStatus:r(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...o?{token:o}:{},...a?{url:a}:{}}})}function Ee(e){if(!D(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=r(e,["token","Token"]),o=r(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...o?{url:o}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function y(e){if(!D(e))throw T("AI Function task response has an invalid structure");let t=Oe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return y(e.data);let n=r(e,["type","Type"]),o=r(e,["taskId","task_id","TaskID"]),a=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!o||typeof a!="string"||!be.has(a))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=Ee(e.videoAsset??e.video_asset??e.VideoAsset),l=_e(e,["progress","Progress"]),A=Pe(e),I=r(e,["errCode","err_code","ErrCode"]),S=r(e,["errMessage","err_message","ErrMessage"]);return{...A?{capabilityType:A}:{},...I?{errCode:I}:{},...S?{errMessage:S}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:r(e,["requestId","request_id","RequestID"])??"",status:a,taskId:o,type:n}}function Oe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:r(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!D(n))return;let o=n.StatusCode??n.status_code??n.statusCode;if(typeof o=="number"&&o!==0||typeof o=="string"&&o&&o!=="0")return{code:String(o),message:r(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function we(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function ve(e){return y(await z(e))}async function Le(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return y(await K(e,t))}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as Ue,StrictMode as Ne,useEffect as Ge,useState as Ve}from"react";import{createRoot as qe}from"react-dom/client";import{installRouteSync as Be}from"@lark-base-open/base-site-channel/runtime";function E(e={}){return Be({...e,onDiagnostic:t=>{let n={source:"sdk",code:t.code,category:t.code==="PATH_ROUTING_UNSUPPORTED"?"protocol":"unknown",retryable:t.code==="ROUTE_SYNC_UNAVAILABLE",message:t.message,redaction:"\u539F\u59CB\u9519\u8BEF\u6D88\u606F\u548C\u4E1A\u52A1\u53C2\u6570\u5DF2\u7701\u7565"};e.onDiagnostic?e.onDiagnostic(n):console.warn("[Base Database SDK]",n.message)}})}import{Fragment as He,jsx as d,jsxs as ze}from"react/jsx-runtime";var O=new WeakSet,b=class extends Ue{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.failed(t)}render(){let t=this.props.fallback;return this.state.failed?t?d(t,{code:"APP_BOOT_FAILED"}):d("div",{role:"alert",children:"APP_BOOT_FAILED"}):this.props.children}};function Mt(e){let t,n,o=new Promise((i,p)=>{t=i,n=p});o.catch(()=>{});let a=!1,s=!1,c=!1,l,A=()=>{},I=()=>{},S=()=>{},C=i=>{try{e.onDiagnostic?.(h(i))}catch{}},f=i=>{C(i),!(a||s||c)&&(c=!0,n(i),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED",{appSdk:"0.6.0-durable.1"}).catch(C))},g;try{g=typeof e.root=="string"?document.querySelector(e.root):e.root??document.querySelector("#root")}catch(i){return f(i),{ready:o,dispose(){a=!0}}}if(!g)return f(new Error("APP_ROOT_NOT_FOUND")),{ready:o,dispose(){a=!0}};if(O.has(g))throw new Error("APP_ALREADY_STARTED");O.add(g);let W=()=>{a||(a=!0,A(),I(),S(),l?.unmount(),O.delete(g),G.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},Q=()=>{queueMicrotask(()=>{a||c||s||(s=!0,e.reportLifecycle===!1?t():m.ready({appSdk:"0.6.0-durable.1"}).then(t,i=>{C(i),n(i)}))})};function Y({locale:i,theme:p}){let[k,R]=Ve();Ge(()=>(S=m.subscribeModeChanged(R),Q(),()=>S()),[]);let j=e.app,w=ze(He,{children:[d(j,{}),e.platformUI===!1?null:d(V,{})]});return d(N,{runtime:m,theme:p,styleScope:e.styleScope,locale:i,mode:k,onDiagnostic:e.onDiagnostic,children:e.providers?e.providers(w):w})}try{l=qe(g);let i=e.slots?.loading;i&&l.render(d(b,{failed:f,fallback:e.slots?.error,children:d(i,{})})),m.getRuntimeContext().then(p=>{if(a||c)return;let k=e.locale&&e.locale!=="host"?e.locale:B(p.locale,"en");document.documentElement.lang=U(k),e.linkGuard!==!1&&(A=P({onDiagnostic:e.onDiagnostic})),e.routeSync!==!1&&(I=E({context:p,onDiagnostic:e.onDiagnostic}));let R=d(b,{failed:f,fallback:e.slots?.error,children:d(Y,{locale:k,theme:e.theme&&e.theme!=="host"?e.theme:p.colorScheme==="dark"?"dark":"light"})});l.render(e.strictMode===!1?R:d(Ne,{children:R}))}).catch(f)}catch(i){f(i)}return{ready:o,dispose:W}}export{ct as AttachmentImage,N as BaseAppProvider,We as CAPABILITY_CATALOG,v as CapabilityUnavailableError,ke as DataNotReadyError,at as DatabaseUserMenu,Qe as DiagnosticCode,V as FloatingButton,Ke as SDKError,J as SITE_RUNTIME_PROTOCOL_VERSION,M as SiteChatbotStreamAdapter,Vt as SiteChatbotStreamError,X as SiteRuntimeApi,oe as SiteRuntimeClient,ee as SiteRuntimeErrorCode,Z as SiteRuntimeEvent,$ as SiteRuntimeFunction,$e as UiLanguageContext,st as UserSelectorEditor,rt as UserSelectorPanel,Te as buildAttachmentCoverUrl,ye as buildDatabaseInvokeFunctionPath,Ie as buildDatabaseInvokeGetPath,Ce as callSiteAIFunction,h as classifyRuntimeError,ve as createSiteAIFunctionTask,ie as createSiteRuntimeClient,le as createSiteRuntimeFetch,pe as fetch,ge as fetchAttachmentCover,Ae as fetchAttachmentDownloadUrl,je as getCapabilities,se as getCurrentUser,Se as getDatabaseContext,Je as getRuntimeCapabilities,Le as getSiteAIFunctionTask,et as getUiLanguage,U as getUiLocale,L as hasCapability,we as hasRunnableMediaTask,tt as initializeUiLanguage,P as installLinkGuard,E as installRouteSync,re as invokeApi,Re as invokeDatabaseFunction,he as invokeDatabaseMutationBatch,ae as invokeHttp,xe as invokeSiteAIFunctionStream,ne as isValidSiteFunctionName,ce as logout,y as normalizeSiteAIMediaTask,Fe as openAttachmentDownload,me as openLink,Xe as queryCapability,Ye as readCapabilities,te as readSiteAITextDelta,ue as requestEdit,Ze as requireCapability,fe as resolveDatabaseContext,B as selectUiLanguage,m as siteRuntime,Mt as startBaseApp,de as uploadAttachment,ot as useBaseApp,it as useOptionalBaseApp,nt as useUiLanguage};
1
+ import{A as Ze,B as Se,C as fe,D as ge,E as Ae,F as Ie,G as ye,H as ke,I as Re,J as he,K as Fe,L as Te,M as $e,N as B,O as et,P as U,Q as tt,R as nt,S as N,T as ot,U as it,V as G,W as V,X as at,Y as rt,Z as st,_ as ct,a as J,b as X,c as Z,d as $,e as ee,f as te,g as ne,h as x,i as _,j as oe,k as ie,l as m,m as ae,n as re,o as se,p as ce,q as ue,r as de,s as me,t as le,u as pe,v as Ye,w as L,x as je,y as Je,z as Xe}from"./chunk-EG6R7YAD.js";import{a as We,b as Qe,c as v,d as h}from"./chunk-ZKBZAK4L.js";import{a as Ke}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as De}from"@lark-base-open/base-site-channel/runtime";function P(e={}){let t=!0,n,o=s=>{let c=h(s);e.onDiagnostic?e.onDiagnostic(c):console.warn("[Base Database SDK]",c)},a=e.runtime??m;return Promise.resolve().then(()=>a.getRuntimeContext()).then(s=>{if(t){if(!L(s,"link.open")){o(new v("link.open",1));return}n=De(e)}}).catch(s=>{t&&o(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as Vt}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var M=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):_})}},F=e=>({...e,channel:e?.channel?x(e.channel):_}),q=(e,t)=>u.callSiteAIFunction(e,F(t)),H=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),z=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),K=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var be=new Set(["cancelled","failed","queued","running","succeeded"]);async function Ce(e){let t=await q(e);return e.input&&!e.messages?y(t):t}function xe(e){return H(e)}function r(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.trim())return o}}function _e(e,t){for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return o}}function Pe(e){let t=r(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(D).map(t=>{let n=r(t,["size","Size"]),o=r(t,["token","Token"]),a=r(t,["url","URL"]);return{safetyStatus:r(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...o?{token:o}:{},...a?{url:a}:{}}})}function Ee(e){if(!D(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=r(e,["token","Token"]),o=r(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...o?{url:o}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function y(e){if(!D(e))throw T("AI Function task response has an invalid structure");let t=Oe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return y(e.data);let n=r(e,["type","Type"]),o=r(e,["taskId","task_id","TaskID"]),a=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!o||typeof a!="string"||!be.has(a))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=Ee(e.videoAsset??e.video_asset??e.VideoAsset),l=_e(e,["progress","Progress"]),A=Pe(e),I=r(e,["errCode","err_code","ErrCode"]),S=r(e,["errMessage","err_message","ErrMessage"]);return{...A?{capabilityType:A}:{},...I?{errCode:I}:{},...S?{errMessage:S}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:r(e,["requestId","request_id","RequestID"])??"",status:a,taskId:o,type:n}}function Oe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:r(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!D(n))return;let o=n.StatusCode??n.status_code??n.statusCode;if(typeof o=="number"&&o!==0||typeof o=="string"&&o&&o!=="0")return{code:String(o),message:r(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function we(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function ve(e){return y(await z(e))}async function Le(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return y(await K(e,t))}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as Ue,StrictMode as Ne,useEffect as Ge,useState as Ve}from"react";import{createRoot as qe}from"react-dom/client";import{installRouteSync as Be}from"@lark-base-open/base-site-channel/runtime";function E(e={}){return Be({...e,onDiagnostic:t=>{let n={source:"sdk",code:t.code,category:t.code==="PATH_ROUTING_UNSUPPORTED"?"protocol":"unknown",retryable:t.code==="ROUTE_SYNC_UNAVAILABLE",message:t.message,redaction:"\u539F\u59CB\u9519\u8BEF\u6D88\u606F\u548C\u4E1A\u52A1\u53C2\u6570\u5DF2\u7701\u7565"};e.onDiagnostic?e.onDiagnostic(n):console.warn("[Base Database SDK]",n.message)}})}import{Fragment as He,jsx as d,jsxs as ze}from"react/jsx-runtime";var O=new WeakSet,b=class extends Ue{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.failed(t)}render(){let t=this.props.fallback;return this.state.failed?t?d(t,{code:"APP_BOOT_FAILED"}):d("div",{role:"alert",children:"APP_BOOT_FAILED"}):this.props.children}};function Mt(e){let t,n,o=new Promise((i,p)=>{t=i,n=p});o.catch(()=>{});let a=!1,s=!1,c=!1,l,A=()=>{},I=()=>{},S=()=>{},C=i=>{try{e.onDiagnostic?.(h(i))}catch{}},f=i=>{C(i),!(a||s||c)&&(c=!0,n(i),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED",{appSdk:"0.6.0-durable.3"}).catch(C))},g;try{g=typeof e.root=="string"?document.querySelector(e.root):e.root??document.querySelector("#root")}catch(i){return f(i),{ready:o,dispose(){a=!0}}}if(!g)return f(new Error("APP_ROOT_NOT_FOUND")),{ready:o,dispose(){a=!0}};if(O.has(g))throw new Error("APP_ALREADY_STARTED");O.add(g);let W=()=>{a||(a=!0,A(),I(),S(),l?.unmount(),O.delete(g),G.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},Q=()=>{queueMicrotask(()=>{a||c||s||(s=!0,e.reportLifecycle===!1?t():m.ready({appSdk:"0.6.0-durable.3"}).then(t,i=>{C(i),n(i)}))})};function Y({locale:i,theme:p}){let[k,R]=Ve();Ge(()=>(S=m.subscribeModeChanged(R),Q(),()=>S()),[]);let j=e.app,w=ze(He,{children:[d(j,{}),e.platformUI===!1?null:d(V,{})]});return d(N,{runtime:m,theme:p,styleScope:e.styleScope,locale:i,mode:k,onDiagnostic:e.onDiagnostic,children:e.providers?e.providers(w):w})}try{l=qe(g);let i=e.slots?.loading;i&&l.render(d(b,{failed:f,fallback:e.slots?.error,children:d(i,{})})),m.getRuntimeContext().then(p=>{if(a||c)return;let k=e.locale&&e.locale!=="host"?e.locale:B(p.locale,"en");document.documentElement.lang=U(k),e.linkGuard!==!1&&(A=P({onDiagnostic:e.onDiagnostic})),e.routeSync!==!1&&(I=E({context:p,onDiagnostic:e.onDiagnostic}));let R=d(b,{failed:f,fallback:e.slots?.error,children:d(Y,{locale:k,theme:e.theme&&e.theme!=="host"?e.theme:p.colorScheme==="dark"?"dark":"light"})});l.render(e.strictMode===!1?R:d(Ne,{children:R}))}).catch(f)}catch(i){f(i)}return{ready:o,dispose:W}}export{ct as AttachmentImage,N as BaseAppProvider,We as CAPABILITY_CATALOG,v as CapabilityUnavailableError,ke as DataNotReadyError,at as DatabaseUserMenu,Qe as DiagnosticCode,V as FloatingButton,Ke as SDKError,J as SITE_RUNTIME_PROTOCOL_VERSION,M as SiteChatbotStreamAdapter,Vt as SiteChatbotStreamError,X as SiteRuntimeApi,oe as SiteRuntimeClient,ee as SiteRuntimeErrorCode,Z as SiteRuntimeEvent,$ as SiteRuntimeFunction,$e as UiLanguageContext,st as UserSelectorEditor,rt as UserSelectorPanel,Te as buildAttachmentCoverUrl,ye as buildDatabaseInvokeFunctionPath,Ie as buildDatabaseInvokeGetPath,Ce as callSiteAIFunction,h as classifyRuntimeError,ve as createSiteAIFunctionTask,ie as createSiteRuntimeClient,le as createSiteRuntimeFetch,pe as fetch,ge as fetchAttachmentCover,Ae as fetchAttachmentDownloadUrl,je as getCapabilities,se as getCurrentUser,Se as getDatabaseContext,Je as getRuntimeCapabilities,Le as getSiteAIFunctionTask,et as getUiLanguage,U as getUiLocale,L as hasCapability,we as hasRunnableMediaTask,tt as initializeUiLanguage,P as installLinkGuard,E as installRouteSync,re as invokeApi,Re as invokeDatabaseFunction,he as invokeDatabaseMutationBatch,ae as invokeHttp,xe as invokeSiteAIFunctionStream,ne as isValidSiteFunctionName,ce as logout,y as normalizeSiteAIMediaTask,Fe as openAttachmentDownload,me as openLink,Xe as queryCapability,Ye as readCapabilities,te as readSiteAITextDelta,ue as requestEdit,Ze as requireCapability,fe as resolveDatabaseContext,B as selectUiLanguage,m as siteRuntime,Mt as startBaseApp,de as uploadAttachment,ot as useBaseApp,it as useOptionalBaseApp,nt as useUiLanguage};
package/dist/server.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var k=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var J=(t,s)=>{for(var o in s)k(t,o,{get:s[o],enumerable:!0})},V=(t,s,o,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of L(s))!W.call(t,r)&&r!==o&&k(t,r,{get:()=>s[r],enumerable:!(e=U(s,r))||e.enumerable});return t};var z=t=>V(k({},"__esModule",{value:!0}),t);var v={};J(v,{SDKError:()=>f,bindFunctionRuntime:()=>j,createServerContext:()=>_,defineFunction:()=>K,normalizeRecordsResult:()=>x});module.exports=z(v);var F=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),f=class extends Error{constructor(o,e,r,n){super(e);this.code=o;this.name="SDKError",this.safeMessage=e;let c=typeof r=="object"?r:{};this.upstreamCode=typeof r=="string"?r:void 0,this.wireCode=Number.isSafeInteger(c.wireCode)&&c.wireCode!==0?c.wireCode:o==="SDK_TIMEOUT"?504:o==="SDK_CANCELLED"?499:o==="SDK_INPUT_INVALID"?400:500,this.retryable=c.retryable??n??!1,this.outcome=c.outcome??"failed",this.paths=c.paths??[]}[F]=!0;static[Symbol.hasInstance](o){return this!==f?Function.prototype[Symbol.hasInstance].call(this,o):o!==null&&typeof o=="object"&&o[F]===!0}wireCode;safeMessage;retryable;outcome;paths;upstreamCode};var d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),R=t=>typeof t=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(t);function S(t){let s=new Set,o=e=>{if(!(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))){if(typeof e!="object"||!e||s.has(e)||Array.isArray(e)&&Object.getPrototypeOf(e)!==Array.prototype||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Array.isArray(e)&&(Object.keys(e).length!==e.length||Object.keys(e).some((r,n)=>r!==String(n))))throw 0;s.add(e);for(let r of Reflect.ownKeys(e)){if(Array.isArray(e)&&r==="length")continue;if(typeof r!="string")throw 0;let n=Object.getOwnPropertyDescriptor(e,r);if(!n.enumerable||!("value"in n))throw 0;o(n.value)}s.delete(e)}};try{o(t)}catch{throw new f("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function O(t,s,o){return{status:"unknown",code:t,retryable:!1,...s?{requestedIds:[...s]}:{},...o?{logid:o}:{}}}var B=t=>typeof t=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(t),A=t=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:t,retryable:!1,appliedIds:[]}),D=t=>Array.isArray(t)&&t.every(R)&&new Set(t).size===t.length;function x(t,s){let o=()=>O("SDK_RECORDS_RESULT_UNKNOWN",s.requestedIds);if(d(t)&&B(t.code))return A(t.code);if(!d(t)||t.code!==0||!d(t.data))return o();let e=t.data,r=e.ignored_fields??[];if(!Array.isArray(r)||!r.every(a=>d(a)&&["id","name","reason"].every(i=>typeof a[i]=="string")))return o();let n=e.record_not_found??[];if(!D(n))return o();let c=s.requestedIds??[],u,y;if(s.operation==="appendAttachments"||s.operation==="removeAttachments"){if(!d(e.attachments))return o();try{S(e.attachments)}catch{return o()}for(let[a,i]of Object.entries(e.attachments)){if(!R(a)||!c.includes(a)||!d(i)||!Object.keys(i).length)return o();for(let[p,m]of Object.entries(i))if(!/^fld[A-Za-z0-9]+$/.test(p)||!Array.isArray(m)||!m.every(g=>d(g)&&typeof g.file_token=="string"&&g.file_token.length>0))return o()}if(u=Object.keys(e.attachments),n.some(a=>!c.includes(a)||u.includes(a))||!r.length&&c.some(a=>!u.includes(a)&&!n.includes(a)))return o();y=e.attachments}else{if(!D(e.record_id_list))return o();let a=e.record_id_list;if(s.operation==="create"){if(a.length!==s.count||Object.hasOwn(e,"record_not_found"))return o();u=a}else if(s.operation==="update"){if(a.some(i=>!c.includes(i)||n.includes(i))||n.some(i=>!c.includes(i))||a.length+n.length!==c.length)return o();u=a}else{if(a.length!==c.length||a.some((i,p)=>i!==c[p])||n.some(i=>!c.includes(i)))return o();u=a.filter(i=>!n.includes(i))}}let l=y===void 0?{}:{attachments:y};return n.length||r.length?{status:"partial",appliedIds:u,notFoundIds:n,ignoredFields:r,...l}:{status:"success",appliedIds:u,notFoundIds:[],ignoredFields:[],...l}}var E={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},I=t=>({status:"failed",code:t,retryable:!1,appliedIds:[]});function $(t){if(t?.platformEnv==="online")return t.brand==="feishu"?"https://open.feishu.cn":t.brand==="lark"?"https://open.larksuite.com":void 0;if(t?.brand==="feishu"){if(t.platformEnv==="pre")return"https://open.feishu-pre.cn";if(t.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function T(t,s){let o=async(e,r,n,c)=>{if(!s)return I("SDK_RUNTIME_PROFILE_MISSING");let u=$(s);if(!u)return I("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return I("SDK_CANCELLED");let y,l,a;try{if(!d(r)||typeof r.baseToken!="string"||typeof r.tableId!="string"||!/^[A-Za-z0-9]+$/.test(r.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(r.tableId))throw 0;if(S(n),e==="create"){if(!Array.isArray(n)||!n.every(d))throw 0;a=n.length,y={create_records:n}}else if(e==="update"){if(!d(n)||!Object.values(n).every(d))throw 0;l=Object.keys(n),a=l.length,y={update_records:n}}else if(e==="delete"){if(!Array.isArray(n)||!n.every(R))throw 0;l=n,a=n.length,y={record_id_list:n}}else{if(!d(n))throw 0;let i=Object.create(null),p=0;for(let[m,g]of Object.entries(n)){if(!R(m)||!d(g))throw 0;for(let[C,w]of Object.entries(g)){if(!C.trim()||!Array.isArray(w))throw 0;for(let h of w){if(!d(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(b=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(b)))throw 0;for(let b of["image_width","image_height"])if(h[b]!==void 0&&(typeof h[b]!="number"||!Number.isInteger(h[b])||h[b]<=0))throw 0}p+=w.length,w.length&&(i[m]??=Object.create(null),i[m][C]=w)}}if(p>50)throw 0;if(!p)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};l=Object.keys(i),y={attachments:i}}if(a!==void 0&&(a<1||a>200)||l&&(!l.every(R)||new Set(l).size!==l.length))throw 0}catch{return I("SDK_RECORDS_INPUT_INVALID")}try{let i=await t.fetch(`${u}/open-apis/bitable/v1/apps/${encodeURIComponent(r.baseToken)}/tables/${encodeURIComponent(r.tableId)}/${E[e]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y),signal:c?.signal}),p=i.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(i.status))return A(i.status);if(!i.ok)return O("SDK_RECORDS_HTTP_ERROR",l,p);let m=x(await i.json(),{operation:e,requestedIds:l,count:a});return m.status==="unknown"&&p?{...m,logid:p}:m}catch(i){let p=i instanceof Error?i.name:"";return O(p==="AbortError"?"SDK_CANCELLED":p==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",l)}};return Object.fromEntries(Object.keys(E).map(e=>[e,(r,n,c)=>o(e,r,n,c)]))}var P=Symbol("base-database-runtime-profile");function j(t,s){let o=Object.freeze({platformEnv:s.platformEnv,brand:s.brand});return function(e,r){let n=Object.defineProperty({...r},P,{value:o});return t.call(this,e,n)}}function _(t){return{...t,records:T(t,t[P])}}async function N(t,s,o){let e;try{e=await t["~standard"].validate(s)}catch{throw new f("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(e.issues){let r=e.issues.map(n=>(n.path??[]).map(c=>{let u=typeof c=="object"?c.key:c;return typeof u=="number"||typeof u=="string"?u:"[symbol]"}));throw new f(`SDK_${o}_INVALID`,o==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:r})}return e.value}function K(t){return async(s,o)=>{try{let e=await N(t.input,s,"INPUT"),r=await t.handler(e,_(o)),n=await N(t.output,r,"OUTPUT");return S(n),{code:0,msg:"success",data:n}}catch(e){let r=e instanceof f?e:new f("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome}));let n={code:r.wireCode,msg:r.safeMessage};return e instanceof f||Object.defineProperty(n,Symbol.for("base-site.function-error"),{value:e}),n}}}0&&(module.exports={SDKError,bindFunctionRuntime,createServerContext,defineFunction,normalizeRecordsResult});
1
+ "use strict";var W=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var me=Object.prototype.hasOwnProperty;var ge=(e,o)=>{for(var n in o)W(e,n,{get:o[n],enumerable:!0})},ye=(e,o,n,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of fe(o))!me.call(e,r)&&r!==n&&W(e,r,{get:()=>o[r],enumerable:!(t=pe(o,r))||t.enumerable});return e};var be=e=>ye(W({},"__esModule",{value:!0}),e);var Fe={};ge(Fe,{DurableError:()=>E,NonRetryableError:()=>k,SDKError:()=>R,StepFailedError:()=>N,bindFunctionRuntime:()=>ee,createServerContext:()=>_,defineDurableFunction:()=>ue,defineFunction:()=>ne,durable:()=>ce,normalizeRecordsResult:()=>M});module.exports=be(Fe);var G=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),R=class extends Error{constructor(n,t,r,s){super(t);this.code=n;this.name="SDKError",this.safeMessage=t;let c=typeof r=="object"?r:{};this.upstreamCode=typeof r=="string"?r:void 0,this.wireCode=Number.isSafeInteger(c.wireCode)&&c.wireCode!==0?c.wireCode:n==="SDK_TIMEOUT"?504:n==="SDK_CANCELLED"?499:n==="SDK_INPUT_INVALID"?400:500,this.retryable=c.retryable??s??!1,this.outcome=c.outcome??"failed",this.paths=c.paths??[]}[G]=!0;static[Symbol.hasInstance](n){return this!==R?Function.prototype[Symbol.hasInstance].call(this,n):n!==null&&typeof n=="object"&&n[G]===!0}wireCode;safeMessage;retryable;outcome;paths;upstreamCode};var x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),P=e=>typeof e=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(e);function T(e){let o=new Set,n=t=>{if(!(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))){if(typeof t!="object"||!t||o.has(t)||Array.isArray(t)&&Object.getPrototypeOf(t)!==Array.prototype||!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null||Array.isArray(t)&&(Object.keys(t).length!==t.length||Object.keys(t).some((r,s)=>r!==String(s))))throw 0;o.add(t);for(let r of Reflect.ownKeys(t)){if(Array.isArray(t)&&r==="length")continue;if(typeof r!="string")throw 0;let s=Object.getOwnPropertyDescriptor(t,r);if(!s.enumerable||!("value"in s))throw 0;n(s.value)}o.delete(t)}};try{n(e)}catch{throw new R("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function V(e,o,n){return{status:"unknown",code:e,retryable:!1,...o?{requestedIds:[...o]}:{},...n?{logid:n}:{}}}var xe=e=>typeof e=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(e),$=e=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:e,retryable:!1,appliedIds:[]}),Y=e=>Array.isArray(e)&&e.every(P)&&new Set(e).size===e.length;function M(e,o){let n=()=>V("SDK_RECORDS_RESULT_UNKNOWN",o.requestedIds);if(x(e)&&xe(e.code))return $(e.code);if(!x(e)||e.code!==0||!x(e.data))return n();let t=e.data,r=t.ignored_fields??[];if(!Array.isArray(r)||!r.every(a=>x(a)&&["id","name","reason"].every(u=>typeof a[u]=="string")))return n();let s=t.record_not_found??[];if(!Y(s))return n();let c=o.requestedIds??[],d,I;if(o.operation==="appendAttachments"||o.operation==="removeAttachments"){if(!x(t.attachments))return n();try{T(t.attachments)}catch{return n()}for(let[a,u]of Object.entries(t.attachments)){if(!P(a)||!c.includes(a)||!x(u)||!Object.keys(u).length)return n();for(let[m,g]of Object.entries(u))if(!/^fld[A-Za-z0-9]+$/.test(m)||!Array.isArray(g)||!g.every(S=>x(S)&&typeof S.file_token=="string"&&S.file_token.length>0))return n()}if(d=Object.keys(t.attachments),s.some(a=>!c.includes(a)||d.includes(a))||!r.length&&c.some(a=>!d.includes(a)&&!s.includes(a)))return n();I=t.attachments}else{if(!Y(t.record_id_list))return n();let a=t.record_id_list;if(o.operation==="create"){if(a.length!==o.count||Object.hasOwn(t,"record_not_found"))return n();d=a}else if(o.operation==="update"){if(a.some(u=>!c.includes(u)||s.includes(u))||s.some(u=>!c.includes(u))||a.length+s.length!==c.length)return n();d=a}else{if(a.length!==c.length||a.some((u,m)=>u!==c[m])||s.some(u=>!c.includes(u)))return n();d=a.filter(u=>!s.includes(u))}}let p=I===void 0?{}:{attachments:I};return s.length||r.length?{status:"partial",appliedIds:d,notFoundIds:s,ignoredFields:r,...p}:{status:"success",appliedIds:d,notFoundIds:[],ignoredFields:[],...p}}var Z={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},j=e=>({status:"failed",code:e,retryable:!1,appliedIds:[]});function Se(e){if(e?.platformEnv==="online")return e.brand==="feishu"?"https://open.feishu.cn":e.brand==="lark"?"https://open.larksuite.com":void 0;if(e?.brand==="feishu"){if(e.platformEnv==="pre")return"https://open.feishu-pre.cn";if(e.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function X(e,o){let n=async(t,r,s,c)=>{if(!o)return j("SDK_RUNTIME_PROFILE_MISSING");let d=Se(o);if(!d)return j("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return j("SDK_CANCELLED");let I,p,a;try{if(!x(r)||typeof r.baseToken!="string"||typeof r.tableId!="string"||!/^[A-Za-z0-9]+$/.test(r.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(r.tableId))throw 0;if(T(s),t==="create"){if(!Array.isArray(s)||!s.every(x))throw 0;a=s.length,I={create_records:s}}else if(t==="update"){if(!x(s)||!Object.values(s).every(x))throw 0;p=Object.keys(s),a=p.length,I={update_records:s}}else if(t==="delete"){if(!Array.isArray(s)||!s.every(P))throw 0;p=s,a=s.length,I={record_id_list:s}}else{if(!x(s))throw 0;let u=Object.create(null),m=0;for(let[g,S]of Object.entries(s)){if(!P(g)||!x(S))throw 0;for(let[w,f]of Object.entries(S)){if(!w.trim()||!Array.isArray(f))throw 0;for(let h of f){if(!x(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(D=>!["file_token",...t==="appendAttachments"?["image_width","image_height"]:[]].includes(D)))throw 0;for(let D of["image_width","image_height"])if(h[D]!==void 0&&(typeof h[D]!="number"||!Number.isInteger(h[D])||h[D]<=0))throw 0}m+=f.length,f.length&&(u[g]??=Object.create(null),u[g][w]=f)}}if(m>50)throw 0;if(!m)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};p=Object.keys(u),I={attachments:u}}if(a!==void 0&&(a<1||a>200)||p&&(!p.every(P)||new Set(p).size!==p.length))throw 0}catch{return j("SDK_RECORDS_INPUT_INVALID")}try{let u=await e.fetch(`${d}/open-apis/bitable/v1/apps/${encodeURIComponent(r.baseToken)}/tables/${encodeURIComponent(r.tableId)}/${Z[t]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(I),signal:c?.signal}),m=u.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(u.status))return $(u.status);if(!u.ok)return V("SDK_RECORDS_HTTP_ERROR",p,m);let g=M(await u.json(),{operation:t,requestedIds:p,count:a});return g.status==="unknown"&&m?{...g,logid:m}:g}catch(u){let m=u instanceof Error?u.name:"";return V(m==="AbortError"?"SDK_CANCELLED":m==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",p)}};return Object.fromEntries(Object.keys(Z).map(t=>[t,(r,s,c)=>n(t,r,s,c)]))}var Q=Symbol("base-database-runtime-profile");function ee(e,o){let n=Object.freeze({platformEnv:o.platformEnv,brand:o.brand});return function(t,r){let s=Object.defineProperty({...r},Q,{value:n});return e.call(this,t,s)}}function _(e){return{...e,records:X(e,e[Q])}}async function te(e,o,n){let t;try{t=await e["~standard"].validate(o)}catch{throw new R("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(t.issues){let r=t.issues.map(s=>(s.path??[]).map(c=>{let d=typeof c=="object"?c.key:c;return typeof d=="number"||typeof d=="string"?d:"[symbol]"}));throw new R(`SDK_${n}_INVALID`,n==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:r})}return t.value}function ne(e){return async(o,n)=>{try{let t=await te(e.input,o,"INPUT"),r=await e.handler(t,_(n)),s=await te(e.output,r,"OUTPUT");return T(s),{code:0,msg:"success",data:s}}catch(t){let r=t instanceof R?t:new R("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome}));let s={code:r.wireCode,msg:r.safeMessage};return t instanceof R||Object.defineProperty(s,Symbol.for("base-site.function-error"),{value:t}),s}}}var re="base-site.durable",oe="base-site.runtime";var E=class extends Error{constructor(n,t=n,r,s){super(t,s);this.code=n;this.logId=r;this.name="DurableError"}},k=class extends Error{constructor(o){super(o),this.name="NonRetryableError"}},N=class extends Error{constructor(n,t){super(t.message);this.key=n;this.error=t;this.name="StepFailedError"}};function J(e,o,n){let t="Unknown error",r="Error";try{e instanceof Error?(typeof e.message=="string"&&(t=e.message),typeof e.name=="string"&&(r=e.name)):typeof e=="string"&&(t=e)}catch{}t=t.slice(0,1024*4).replace(/([?&][^=&#\s]*?(?:token|ticket|code|secret|key|password|authorization)[^=&#\s]*=)[^&#\s]*/gi,"$1[REDACTED]").replace(/\bBearer\s+[^\s"'<>]+/gi,"Bearer [REDACTED]");let s="",c=0;for(let d of t){if(c+=new TextEncoder().encode(d).length,c>1024)break;s+=d}return{name:r,message:s,...o?{code:o}:{},...n?{key:n}:{},...e instanceof k?{retryable:!1}:{}}}function ae(e,o){return`${e} schema validation failed: `+o.slice(0,3).map(n=>`${n.path?.map(r=>String(typeof r=="object"?r.key:r)).join(".")||"$"}: ${n.message}`).join("; ")}function z(e){let o={ms:1,s:1e3,m:6e4,h:36e5,d:864e5},n=typeof e=="string"&&/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(e),t=typeof e=="number"?e:n?Number(n[1])*o[n[2]]:NaN;if(!Number.isSafeInteger(t)||t<0)throw new Error("Invalid duration");return t}function q(e){return T(e),e}function H(e){return new TextEncoder().encode(JSON.stringify(e)).length}var A=()=>new Promise(()=>{});function ue(e){let o={v:1,async execute(n,t){try{return await De(e,n,t)}catch(r){return{v:1,seq:n?.invocation?.seq??0,op:"fail",error:J(r,"HANDLER_ERROR")}}}};return{[Symbol.for(re)]:o}}function De(e,o,n){return new Promise(t=>{let r={v:1,seq:o.invocation.seq},s=new Set,c=new Map(o.steps.map(i=>[i.key,i])),d,I=!1,p=!1,a,u,m,g,S=Math.min(n.deadline,o.invocation.deadline),w=i=>{p||((!a||i.op==="fail")&&(a=i),queueMicrotask(()=>{p||!a||(p=!0,clearTimeout(D),clearTimeout(m),n.signal.removeEventListener("abort",h),u?.abort(),t({...a,...d!==void 0?{progress:d}:{}}))}))},f=(i,y,l=new Error(i))=>w({...r,op:"fail",error:J(l,i,y)}),h=()=>g?g():f("REPLAY_TIMEOUT"),D=setTimeout(h,Math.max(0,S-Date.now())),K=(i,y)=>{if(p||a?.op==="fail")return;if(Date.now()>=S){h();return}if(typeof i!="string"||i.length<1||i.length>128||/[\x00-\x1f\x7f-\x9f]/.test(i)){f("DEFINITION_INVALID",void 0,new Error("Invalid step key"));return}if(s.has(i)){f("DUPLICATE_STEP_KEY",i);return}s.add(i);let l=c.get(i);if(l){if(l.kind!==y){f("DEFINITION_KIND_MISMATCH",i);return}if(!l.ok)throw new N(i,l.error);return{fresh:!1,value:y==="sleep"?void 0:l.timedOut?null:l.value}}if(I){f("PARALLEL_STEPS",i);return}if(c.size>=100){f("STEP_LIMIT",i);return}return I=!0,{fresh:!0}},le={async run(i,y,l={}){let b=K(i,"run");if(!b)return A();if(!b.fresh)return b.value;let O,U=l.retries??3;try{if(O=l.timeout===void 0?S-Date.now():Math.min(z(l.timeout),S-Date.now()),!Number.isSafeInteger(U)||U<0||O<=0)throw new Error("Invalid step options")}catch(F){return f("DEFINITION_INVALID",i,F),A()}u=new AbortController;let de=u.signal,v=Date.now(),B=(F,L)=>w({...r,op:"step",key:i,ok:!1,error:J(F,L,i),policy:{retries:U},durationMs:Math.max(0,Date.now()-v)});return g=()=>{B(new Error("Step exceeded its deadline"),"STEP_TIMEOUT"),u?.abort()},m=setTimeout(g,O),Promise.resolve().then(async()=>{if(!(a||p))try{let F=await y({signal:de,attempt:o.invocation.attempt});if(Date.now()>=v+O){g?.();return}let L=q(F===void 0?null:F);if(H(L)>262144){B(new k("Step result exceeds 256KB"),"STEP_RESULT_TOO_LARGE");return}w({...r,op:"step",key:i,ok:!0,value:L,durationMs:Math.max(0,Date.now()-v)})}catch(F){Date.now()>=v+O?g?.():B(F)}}),A()},async sleep(i,y){let l=K(i,"sleep");if(!l)return A();if(l.fresh){try{let b=z(y);if(b<1e3||b>2592e6)throw new Error("Sleep duration must be between 1s and 30d");w({...r,op:"sleep",key:i,durationMs:b})}catch(b){f("DEFINITION_INVALID",i,b)}return A()}},async waitForEvent(i,y,l){if(!Object.hasOwn(e.events??{},y))return f("EVENT_UNDECLARED",i),A();let b=K(i,"wait");if(!b)return A();if(!b.fresh)return b.value;try{let O=z(l.timeout);if(O<1e3||O>2592e6)throw new Error("Event timeout must be between 1s and 30d");w({...r,op:"wait",key:i,event:y,timeoutMs:O})}catch(O){f("DEFINITION_INVALID",i,O)}return A()},progress(i){if(!p)try{let y=q(i);H(y)<=4096?d=JSON.parse(JSON.stringify(y)):console.warn("Durable progress exceeds 4KB; discarded")}catch{f("DEFINITION_INVALID",void 0,new Error("Progress must be JSON"))}}};if(n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted||S<=Date.now()){h();return}Promise.resolve().then(async()=>{try{let i;try{let l=await e.input["~standard"].validate(o.input);if(l.issues)throw new Error(ae("Input",l.issues));i=l.value}catch(l){f("INPUT_INVALID",void 0,l);return}if(p||a)return;if(Date.now()>=S){f("REPLAY_TIMEOUT");return}let y=await e.handler(i,le,_(n.ctx));if(I||p||a)return;try{let l=await e.output["~standard"].validate(y);if(l.issues)throw new Error(ae("Output",l.issues));if(Date.now()>=S){f("REPLAY_TIMEOUT");return}let b=q(l.value);if(H(b)>262144)throw new Error("Output exceeds 256KB");w({...r,op:"done",output:b})}catch(l){f("OUTPUT_INVALID",void 0,l)}}catch(i){f("HANDLER_ERROR",i instanceof N?i.key:void 0,i)}})})}async function C(e){let o=globalThis[Symbol.for(oe)],n=o?.v===1?o.context.getStore()?.ctx:void 0;if(!n?.faasInvoke)throw new E("DURABLE_NO_CONTEXT");try{let t=await n.faasInvoke({method:"durable",params:JSON.stringify(e)});if(!t||t.code!==0)throw new E(t?.data?.reason??"INFRA_UNAVAILABLE",t?.msg,t?.data?.logId);return t.data}catch(t){if(t instanceof E)throw t;let r=t,c=[r?.code??r?.cause?.code,r?.message,r?.cause?.message].filter(d=>d!=null&&d!=="").join(": ")||(typeof t=="string"?t:"INFRA_UNAVAILABLE");throw new E("INFRA_UNAVAILABLE",c,r?.logId,{cause:t})}}var ce={start(e,o,n){return C({...n,action:"start",functionId:e,input:o})},get(e,o){return C({...o,action:"get",runId:e})},list(e){return C({...e,action:"list"})},cancel(e,o){return C({...o,action:"cancel",runId:e})},signal(e,o,n,t){return C({...t,action:"signal",runId:e,event:o,data:n})}};0&&(module.exports={DurableError,NonRetryableError,SDKError,StepFailedError,bindFunctionRuntime,createServerContext,defineDurableFunction,defineFunction,durable,normalizeRecordsResult});
package/dist/server.d.cts CHANGED
@@ -35,6 +35,10 @@ interface RecordsClient {
35
35
  }
36
36
 
37
37
  interface RawFunctionContext {
38
+ faasInvoke?(request: {
39
+ method: "durable";
40
+ params: string;
41
+ }): Promise<unknown>;
38
42
  fetch: typeof globalThis.fetch;
39
43
  invokeFunction(p: {
40
44
  projectId: string;
@@ -74,6 +78,161 @@ interface RecordsResultRequest {
74
78
  }
75
79
  declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
76
80
 
81
+ type JSONValue = null | boolean | number | string | JSONValue[] | {
82
+ [key: string]: JSONValue;
83
+ };
84
+ type RunStatus = "queued" | "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled" | (string & {});
85
+ type StepKind = "run" | "sleep" | "wait";
86
+ type Trigger = {
87
+ kind: "server";
88
+ } | {
89
+ kind: "timer";
90
+ fireId: string;
91
+ };
92
+ interface OpError {
93
+ name?: string;
94
+ message: string;
95
+ code?: string;
96
+ key?: string;
97
+ retryable?: boolean;
98
+ }
99
+ interface Waiting {
100
+ event: string;
101
+ until: number;
102
+ }
103
+ interface StepView {
104
+ key: string;
105
+ kind: StepKind;
106
+ status: string;
107
+ attempts: number;
108
+ startedAt: number;
109
+ endedAt?: number;
110
+ lastError?: OpError;
111
+ }
112
+ interface RunSummary {
113
+ runId: string;
114
+ functionId: string;
115
+ status: RunStatus;
116
+ trigger: Trigger;
117
+ output: JSONValue;
118
+ error: OpError | null;
119
+ progress: JSONValue;
120
+ waiting: Waiting | null;
121
+ sleepingUntil: number | null;
122
+ createdAt: number;
123
+ updatedAt: number;
124
+ closedAt: number | null;
125
+ }
126
+ interface Run extends RunSummary {
127
+ input?: JSONValue;
128
+ steps: StepView[];
129
+ }
130
+ interface GetParams {
131
+ action: "get";
132
+ runId: string;
133
+ scope?: string;
134
+ }
135
+ interface ListParams {
136
+ action: "list";
137
+ functionId?: string;
138
+ status?: RunStatus;
139
+ scope?: string;
140
+ pageToken?: string;
141
+ pageSize?: number;
142
+ }
143
+ interface StartResponse {
144
+ runId: string;
145
+ status: RunStatus;
146
+ deduplicated: boolean;
147
+ }
148
+ interface ListResponse {
149
+ runs: RunSummary[];
150
+ nextPageToken: string;
151
+ }
152
+ interface CancelResponse {
153
+ status: RunStatus;
154
+ }
155
+ interface SignalResponse {
156
+ accepted: true;
157
+ }
158
+
159
+ type Duration = number | string;
160
+ interface StepRunOptions {
161
+ timeout?: Duration;
162
+ retries?: number;
163
+ }
164
+ interface StepExecutionContext {
165
+ signal: AbortSignal;
166
+ attempt: number;
167
+ }
168
+ interface DurableStep<E extends Record<string, StandardSchemaV1>> {
169
+ run<T>(key: string, callback: (context: StepExecutionContext) => T | Promise<T>, options?: StepRunOptions): Promise<T>;
170
+ sleep(key: string, duration: Duration): Promise<void>;
171
+ waitForEvent<K extends keyof E & string>(key: string, event: K, options: {
172
+ timeout: Duration;
173
+ }): Promise<StandardSchemaV1.InferOutput<E[K]> | null>;
174
+ progress(value: JSONValue): void;
175
+ }
176
+ interface DefineDurableFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1> = {}> {
177
+ input: I;
178
+ output: O;
179
+ events?: E;
180
+ handler(input: StandardSchemaV1.InferOutput<I>, step: DurableStep<E>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
181
+ }
182
+ interface DefinedDurableFunction {
183
+ readonly [key: symbol]: unknown;
184
+ }
185
+ declare function defineDurableFunction<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1> = {}>(definition: DefineDurableFunctionOptions<I, O, E>): DefinedDurableFunction;
186
+
187
+ type FunctionId = keyof DurableFunctions extends never ? string : keyof DurableFunctions & string;
188
+ type Contract<F extends FunctionId> = F extends keyof DurableFunctions ? DurableFunctions[F] : {
189
+ input: JSONValue;
190
+ output: JSONValue;
191
+ events: Record<string, JSONValue>;
192
+ };
193
+ type Input<F extends FunctionId> = Contract<F> extends {
194
+ input: infer I;
195
+ } ? I : never;
196
+ type Output<F extends FunctionId> = Contract<F> extends {
197
+ output: infer O;
198
+ } ? O : never;
199
+ type Events<F extends FunctionId> = Contract<F> extends {
200
+ events: infer E;
201
+ } ? E : never;
202
+ type TypedRun<F extends FunctionId> = Omit<Run, 'input' | 'output'> & {
203
+ input?: Input<F>;
204
+ output: Output<F> | null;
205
+ };
206
+ declare const durable: {
207
+ start<F extends FunctionId>(functionId: F, input: Input<F>, options?: {
208
+ idempotencyKey?: string;
209
+ }): Promise<StartResponse>;
210
+ get<F extends FunctionId>(runId: string, options?: Pick<GetParams, "scope">): Promise<TypedRun<F>>;
211
+ list(options?: Omit<ListParams, "action">): Promise<ListResponse>;
212
+ cancel(runId: string, options?: Pick<GetParams, "scope">): Promise<CancelResponse>;
213
+ signal<F extends FunctionId, E extends keyof Events<F> & string>(runId: string, event: E, data: Events<F>[E], options: {
214
+ eventId: string;
215
+ }): Promise<SignalResponse>;
216
+ };
217
+
218
+ declare class DurableError extends Error {
219
+ readonly code: string;
220
+ readonly logId?: string | undefined;
221
+ constructor(code: string, message?: string, logId?: string | undefined, options?: ErrorOptions);
222
+ }
223
+ declare class NonRetryableError extends Error {
224
+ constructor(message: string);
225
+ }
226
+ declare class StepFailedError extends Error {
227
+ readonly key: string;
228
+ readonly error: OpError;
229
+ constructor(key: string, error: OpError);
230
+ }
231
+
77
232
  type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
78
233
 
79
- export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
234
+ /** CLI contracts generate augments this registry with { input; output; events } per function. */
235
+ interface DurableFunctions {
236
+ }
237
+
238
+ export { AttachmentInput, Attachments, DefineDurableFunctionOptions, DefineFunctionOptions, DefinedDurableFunction, DefinedFunction, DurableError, DurableFunctions, DurableStep, Duration, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, NonRetryableError, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, StepExecutionContext, StepFailedError, StepRunOptions, Target, WriteResult, bindFunctionRuntime, createServerContext, defineDurableFunction, defineFunction, durable, normalizeRecordsResult };
package/dist/server.d.ts CHANGED
@@ -35,6 +35,10 @@ interface RecordsClient {
35
35
  }
36
36
 
37
37
  interface RawFunctionContext {
38
+ faasInvoke?(request: {
39
+ method: "durable";
40
+ params: string;
41
+ }): Promise<unknown>;
38
42
  fetch: typeof globalThis.fetch;
39
43
  invokeFunction(p: {
40
44
  projectId: string;
@@ -74,6 +78,161 @@ interface RecordsResultRequest {
74
78
  }
75
79
  declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
76
80
 
81
+ type JSONValue = null | boolean | number | string | JSONValue[] | {
82
+ [key: string]: JSONValue;
83
+ };
84
+ type RunStatus = "queued" | "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled" | (string & {});
85
+ type StepKind = "run" | "sleep" | "wait";
86
+ type Trigger = {
87
+ kind: "server";
88
+ } | {
89
+ kind: "timer";
90
+ fireId: string;
91
+ };
92
+ interface OpError {
93
+ name?: string;
94
+ message: string;
95
+ code?: string;
96
+ key?: string;
97
+ retryable?: boolean;
98
+ }
99
+ interface Waiting {
100
+ event: string;
101
+ until: number;
102
+ }
103
+ interface StepView {
104
+ key: string;
105
+ kind: StepKind;
106
+ status: string;
107
+ attempts: number;
108
+ startedAt: number;
109
+ endedAt?: number;
110
+ lastError?: OpError;
111
+ }
112
+ interface RunSummary {
113
+ runId: string;
114
+ functionId: string;
115
+ status: RunStatus;
116
+ trigger: Trigger;
117
+ output: JSONValue;
118
+ error: OpError | null;
119
+ progress: JSONValue;
120
+ waiting: Waiting | null;
121
+ sleepingUntil: number | null;
122
+ createdAt: number;
123
+ updatedAt: number;
124
+ closedAt: number | null;
125
+ }
126
+ interface Run extends RunSummary {
127
+ input?: JSONValue;
128
+ steps: StepView[];
129
+ }
130
+ interface GetParams {
131
+ action: "get";
132
+ runId: string;
133
+ scope?: string;
134
+ }
135
+ interface ListParams {
136
+ action: "list";
137
+ functionId?: string;
138
+ status?: RunStatus;
139
+ scope?: string;
140
+ pageToken?: string;
141
+ pageSize?: number;
142
+ }
143
+ interface StartResponse {
144
+ runId: string;
145
+ status: RunStatus;
146
+ deduplicated: boolean;
147
+ }
148
+ interface ListResponse {
149
+ runs: RunSummary[];
150
+ nextPageToken: string;
151
+ }
152
+ interface CancelResponse {
153
+ status: RunStatus;
154
+ }
155
+ interface SignalResponse {
156
+ accepted: true;
157
+ }
158
+
159
+ type Duration = number | string;
160
+ interface StepRunOptions {
161
+ timeout?: Duration;
162
+ retries?: number;
163
+ }
164
+ interface StepExecutionContext {
165
+ signal: AbortSignal;
166
+ attempt: number;
167
+ }
168
+ interface DurableStep<E extends Record<string, StandardSchemaV1>> {
169
+ run<T>(key: string, callback: (context: StepExecutionContext) => T | Promise<T>, options?: StepRunOptions): Promise<T>;
170
+ sleep(key: string, duration: Duration): Promise<void>;
171
+ waitForEvent<K extends keyof E & string>(key: string, event: K, options: {
172
+ timeout: Duration;
173
+ }): Promise<StandardSchemaV1.InferOutput<E[K]> | null>;
174
+ progress(value: JSONValue): void;
175
+ }
176
+ interface DefineDurableFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1> = {}> {
177
+ input: I;
178
+ output: O;
179
+ events?: E;
180
+ handler(input: StandardSchemaV1.InferOutput<I>, step: DurableStep<E>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
181
+ }
182
+ interface DefinedDurableFunction {
183
+ readonly [key: symbol]: unknown;
184
+ }
185
+ declare function defineDurableFunction<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1> = {}>(definition: DefineDurableFunctionOptions<I, O, E>): DefinedDurableFunction;
186
+
187
+ type FunctionId = keyof DurableFunctions extends never ? string : keyof DurableFunctions & string;
188
+ type Contract<F extends FunctionId> = F extends keyof DurableFunctions ? DurableFunctions[F] : {
189
+ input: JSONValue;
190
+ output: JSONValue;
191
+ events: Record<string, JSONValue>;
192
+ };
193
+ type Input<F extends FunctionId> = Contract<F> extends {
194
+ input: infer I;
195
+ } ? I : never;
196
+ type Output<F extends FunctionId> = Contract<F> extends {
197
+ output: infer O;
198
+ } ? O : never;
199
+ type Events<F extends FunctionId> = Contract<F> extends {
200
+ events: infer E;
201
+ } ? E : never;
202
+ type TypedRun<F extends FunctionId> = Omit<Run, 'input' | 'output'> & {
203
+ input?: Input<F>;
204
+ output: Output<F> | null;
205
+ };
206
+ declare const durable: {
207
+ start<F extends FunctionId>(functionId: F, input: Input<F>, options?: {
208
+ idempotencyKey?: string;
209
+ }): Promise<StartResponse>;
210
+ get<F extends FunctionId>(runId: string, options?: Pick<GetParams, "scope">): Promise<TypedRun<F>>;
211
+ list(options?: Omit<ListParams, "action">): Promise<ListResponse>;
212
+ cancel(runId: string, options?: Pick<GetParams, "scope">): Promise<CancelResponse>;
213
+ signal<F extends FunctionId, E extends keyof Events<F> & string>(runId: string, event: E, data: Events<F>[E], options: {
214
+ eventId: string;
215
+ }): Promise<SignalResponse>;
216
+ };
217
+
218
+ declare class DurableError extends Error {
219
+ readonly code: string;
220
+ readonly logId?: string | undefined;
221
+ constructor(code: string, message?: string, logId?: string | undefined, options?: ErrorOptions);
222
+ }
223
+ declare class NonRetryableError extends Error {
224
+ constructor(message: string);
225
+ }
226
+ declare class StepFailedError extends Error {
227
+ readonly key: string;
228
+ readonly error: OpError;
229
+ constructor(key: string, error: OpError);
230
+ }
231
+
77
232
  type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
78
233
 
79
- export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
234
+ /** CLI contracts generate augments this registry with { input; output; events } per function. */
235
+ interface DurableFunctions {
236
+ }
237
+
238
+ export { AttachmentInput, Attachments, DefineDurableFunctionOptions, DefineFunctionOptions, DefinedDurableFunction, DefinedFunction, DurableError, DurableFunctions, DurableStep, Duration, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, NonRetryableError, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, StepExecutionContext, StepFailedError, StepRunOptions, Target, WriteResult, bindFunctionRuntime, createServerContext, defineDurableFunction, defineFunction, durable, normalizeRecordsResult };
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as h}from"./chunk-3JX3FIBG.js";var d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),b=t=>typeof t=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(t);function O(t){let a=new Set,i=e=>{if(!(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))){if(typeof e!="object"||!e||a.has(e)||Array.isArray(e)&&Object.getPrototypeOf(e)!==Array.prototype||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Array.isArray(e)&&(Object.keys(e).length!==e.length||Object.keys(e).some((r,n)=>r!==String(n))))throw 0;a.add(e);for(let r of Reflect.ownKeys(e)){if(Array.isArray(e)&&r==="length")continue;if(typeof r!="string")throw 0;let n=Object.getOwnPropertyDescriptor(e,r);if(!n.enumerable||!("value"in n))throw 0;i(n.value)}a.delete(e)}};try{i(t)}catch{throw new h("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function x(t,a,i){return{status:"unknown",code:t,retryable:!1,...a?{requestedIds:[...a]}:{},...i?{logid:i}:{}}}var P=t=>typeof t=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(t),I=t=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:t,retryable:!1,appliedIds:[]}),F=t=>Array.isArray(t)&&t.every(b)&&new Set(t).size===t.length;function _(t,a){let i=()=>x("SDK_RECORDS_RESULT_UNKNOWN",a.requestedIds);if(d(t)&&P(t.code))return I(t.code);if(!d(t)||t.code!==0||!d(t.data))return i();let e=t.data,r=e.ignored_fields??[];if(!Array.isArray(r)||!r.every(s=>d(s)&&["id","name","reason"].every(o=>typeof s[o]=="string")))return i();let n=e.record_not_found??[];if(!F(n))return i();let c=a.requestedIds??[],u,m;if(a.operation==="appendAttachments"||a.operation==="removeAttachments"){if(!d(e.attachments))return i();try{O(e.attachments)}catch{return i()}for(let[s,o]of Object.entries(e.attachments)){if(!b(s)||!c.includes(s)||!d(o)||!Object.keys(o).length)return i();for(let[p,f]of Object.entries(o))if(!/^fld[A-Za-z0-9]+$/.test(p)||!Array.isArray(f)||!f.every(g=>d(g)&&typeof g.file_token=="string"&&g.file_token.length>0))return i()}if(u=Object.keys(e.attachments),n.some(s=>!c.includes(s)||u.includes(s))||!r.length&&c.some(s=>!u.includes(s)&&!n.includes(s)))return i();m=e.attachments}else{if(!F(e.record_id_list))return i();let s=e.record_id_list;if(a.operation==="create"){if(s.length!==a.count||Object.hasOwn(e,"record_not_found"))return i();u=s}else if(a.operation==="update"){if(s.some(o=>!c.includes(o)||n.includes(o))||n.some(o=>!c.includes(o))||s.length+n.length!==c.length)return i();u=s}else{if(s.length!==c.length||s.some((o,p)=>o!==c[p])||n.some(o=>!c.includes(o)))return i();u=s.filter(o=>!n.includes(o))}}let l=m===void 0?{}:{attachments:m};return n.length||r.length?{status:"partial",appliedIds:u,notFoundIds:n,ignoredFields:r,...l}:{status:"success",appliedIds:u,notFoundIds:[],ignoredFields:[],...l}}var C={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},S=t=>({status:"failed",code:t,retryable:!1,appliedIds:[]});function j(t){if(t?.platformEnv==="online")return t.brand==="feishu"?"https://open.feishu.cn":t.brand==="lark"?"https://open.larksuite.com":void 0;if(t?.brand==="feishu"){if(t.platformEnv==="pre")return"https://open.feishu-pre.cn";if(t.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function E(t,a){let i=async(e,r,n,c)=>{if(!a)return S("SDK_RUNTIME_PROFILE_MISSING");let u=j(a);if(!u)return S("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return S("SDK_CANCELLED");let m,l,s;try{if(!d(r)||typeof r.baseToken!="string"||typeof r.tableId!="string"||!/^[A-Za-z0-9]+$/.test(r.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(r.tableId))throw 0;if(O(n),e==="create"){if(!Array.isArray(n)||!n.every(d))throw 0;s=n.length,m={create_records:n}}else if(e==="update"){if(!d(n)||!Object.values(n).every(d))throw 0;l=Object.keys(n),s=l.length,m={update_records:n}}else if(e==="delete"){if(!Array.isArray(n)||!n.every(b))throw 0;l=n,s=n.length,m={record_id_list:n}}else{if(!d(n))throw 0;let o=Object.create(null),p=0;for(let[f,g]of Object.entries(n)){if(!b(f)||!d(g))throw 0;for(let[A,w]of Object.entries(g)){if(!A.trim()||!Array.isArray(w))throw 0;for(let y of w){if(!d(y)||typeof y.file_token!="string"||!y.file_token.trim()||Object.keys(y).some(R=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(R)))throw 0;for(let R of["image_width","image_height"])if(y[R]!==void 0&&(typeof y[R]!="number"||!Number.isInteger(y[R])||y[R]<=0))throw 0}p+=w.length,w.length&&(o[f]??=Object.create(null),o[f][A]=w)}}if(p>50)throw 0;if(!p)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};l=Object.keys(o),m={attachments:o}}if(s!==void 0&&(s<1||s>200)||l&&(!l.every(b)||new Set(l).size!==l.length))throw 0}catch{return S("SDK_RECORDS_INPUT_INVALID")}try{let o=await t.fetch(`${u}/open-apis/bitable/v1/apps/${encodeURIComponent(r.baseToken)}/tables/${encodeURIComponent(r.tableId)}/${C[e]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(m),signal:c?.signal}),p=o.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(o.status))return I(o.status);if(!o.ok)return x("SDK_RECORDS_HTTP_ERROR",l,p);let f=_(await o.json(),{operation:e,requestedIds:l,count:s});return f.status==="unknown"&&p?{...f,logid:p}:f}catch(o){let p=o instanceof Error?o.name:"";return x(p==="AbortError"?"SDK_CANCELLED":p==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",l)}};return Object.fromEntries(Object.keys(C).map(e=>[e,(r,n,c)=>i(e,r,n,c)]))}var T=Symbol("base-database-runtime-profile");function N(t,a){let i=Object.freeze({platformEnv:a.platformEnv,brand:a.brand});return function(e,r){let n=Object.defineProperty({...r},T,{value:i});return t.call(this,e,n)}}function k(t){return{...t,records:E(t,t[T])}}async function D(t,a,i){let e;try{e=await t["~standard"].validate(a)}catch{throw new h("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(e.issues){let r=e.issues.map(n=>(n.path??[]).map(c=>{let u=typeof c=="object"?c.key:c;return typeof u=="number"||typeof u=="string"?u:"[symbol]"}));throw new h(`SDK_${i}_INVALID`,i==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:r})}return e.value}function K(t){return async(a,i)=>{try{let e=await D(t.input,a,"INPUT"),r=await t.handler(e,k(i)),n=await D(t.output,r,"OUTPUT");return O(n),{code:0,msg:"success",data:n}}catch(e){let r=e instanceof h?e:new h("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome}));let n={code:r.wireCode,msg:r.safeMessage};return e instanceof h||Object.defineProperty(n,Symbol.for("base-site.function-error"),{value:e}),n}}}export{h as SDKError,N as bindFunctionRuntime,k as createServerContext,K as defineFunction,_ as normalizeRecordsResult};
1
+ import{a as w}from"./chunk-3JX3FIBG.js";var S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),N=e=>typeof e=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(e);function T(e){let o=new Set,r=t=>{if(!(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))){if(typeof t!="object"||!t||o.has(t)||Array.isArray(t)&&Object.getPrototypeOf(t)!==Array.prototype||!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null||Array.isArray(t)&&(Object.keys(t).length!==t.length||Object.keys(t).some((n,s)=>n!==String(s))))throw 0;o.add(t);for(let n of Reflect.ownKeys(t)){if(Array.isArray(t)&&n==="length")continue;if(typeof n!="string")throw 0;let s=Object.getOwnPropertyDescriptor(t,n);if(!s.enumerable||!("value"in s))throw 0;r(s.value)}o.delete(t)}};try{r(e)}catch{throw new w("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function V(e,o,r){return{status:"unknown",code:e,retryable:!1,...o?{requestedIds:[...o]}:{},...r?{logid:r}:{}}}var ie=e=>typeof e=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(e),B=e=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:e,retryable:!1,appliedIds:[]}),H=e=>Array.isArray(e)&&e.every(N)&&new Set(e).size===e.length;function W(e,o){let r=()=>V("SDK_RECORDS_RESULT_UNKNOWN",o.requestedIds);if(S(e)&&ie(e.code))return B(e.code);if(!S(e)||e.code!==0||!S(e.data))return r();let t=e.data,n=t.ignored_fields??[];if(!Array.isArray(n)||!n.every(a=>S(a)&&["id","name","reason"].every(u=>typeof a[u]=="string")))return r();let s=t.record_not_found??[];if(!H(s))return r();let p=o.requestedIds??[],l,R;if(o.operation==="appendAttachments"||o.operation==="removeAttachments"){if(!S(t.attachments))return r();try{T(t.attachments)}catch{return r()}for(let[a,u]of Object.entries(t.attachments)){if(!N(a)||!p.includes(a)||!S(u)||!Object.keys(u).length)return r();for(let[m,g]of Object.entries(u))if(!/^fld[A-Za-z0-9]+$/.test(m)||!Array.isArray(g)||!g.every(b=>S(b)&&typeof b.file_token=="string"&&b.file_token.length>0))return r()}if(l=Object.keys(t.attachments),s.some(a=>!p.includes(a)||l.includes(a))||!n.length&&p.some(a=>!l.includes(a)&&!s.includes(a)))return r();R=t.attachments}else{if(!H(t.record_id_list))return r();let a=t.record_id_list;if(o.operation==="create"){if(a.length!==o.count||Object.hasOwn(t,"record_not_found"))return r();l=a}else if(o.operation==="update"){if(a.some(u=>!p.includes(u)||s.includes(u))||s.some(u=>!p.includes(u))||a.length+s.length!==p.length)return r();l=a}else{if(a.length!==p.length||a.some((u,m)=>u!==p[m])||s.some(u=>!p.includes(u)))return r();l=a.filter(u=>!s.includes(u))}}let d=R===void 0?{}:{attachments:R};return s.length||n.length?{status:"partial",appliedIds:l,notFoundIds:s,ignoredFields:n,...d}:{status:"success",appliedIds:l,notFoundIds:[],ignoredFields:[],...d}}var G={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},M=e=>({status:"failed",code:e,retryable:!1,appliedIds:[]});function ae(e){if(e?.platformEnv==="online")return e.brand==="feishu"?"https://open.feishu.cn":e.brand==="lark"?"https://open.larksuite.com":void 0;if(e?.brand==="feishu"){if(e.platformEnv==="pre")return"https://open.feishu-pre.cn";if(e.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function Y(e,o){let r=async(t,n,s,p)=>{if(!o)return M("SDK_RUNTIME_PROFILE_MISSING");let l=ae(o);if(!l)return M("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(p?.signal?.aborted)return M("SDK_CANCELLED");let R,d,a;try{if(!S(n)||typeof n.baseToken!="string"||typeof n.tableId!="string"||!/^[A-Za-z0-9]+$/.test(n.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(n.tableId))throw 0;if(T(s),t==="create"){if(!Array.isArray(s)||!s.every(S))throw 0;a=s.length,R={create_records:s}}else if(t==="update"){if(!S(s)||!Object.values(s).every(S))throw 0;d=Object.keys(s),a=d.length,R={update_records:s}}else if(t==="delete"){if(!Array.isArray(s)||!s.every(N))throw 0;d=s,a=s.length,R={record_id_list:s}}else{if(!S(s))throw 0;let u=Object.create(null),m=0;for(let[g,b]of Object.entries(s)){if(!N(g)||!S(b))throw 0;for(let[O,f]of Object.entries(b)){if(!O.trim()||!Array.isArray(f))throw 0;for(let h of f){if(!S(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(E=>!["file_token",...t==="appendAttachments"?["image_width","image_height"]:[]].includes(E)))throw 0;for(let E of["image_width","image_height"])if(h[E]!==void 0&&(typeof h[E]!="number"||!Number.isInteger(h[E])||h[E]<=0))throw 0}m+=f.length,f.length&&(u[g]??=Object.create(null),u[g][O]=f)}}if(m>50)throw 0;if(!m)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};d=Object.keys(u),R={attachments:u}}if(a!==void 0&&(a<1||a>200)||d&&(!d.every(N)||new Set(d).size!==d.length))throw 0}catch{return M("SDK_RECORDS_INPUT_INVALID")}try{let u=await e.fetch(`${l}/open-apis/bitable/v1/apps/${encodeURIComponent(n.baseToken)}/tables/${encodeURIComponent(n.tableId)}/${G[t]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R),signal:p?.signal}),m=u.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(u.status))return B(u.status);if(!u.ok)return V("SDK_RECORDS_HTTP_ERROR",d,m);let g=W(await u.json(),{operation:t,requestedIds:d,count:a});return g.status==="unknown"&&m?{...g,logid:m}:g}catch(u){let m=u instanceof Error?u.name:"";return V(m==="AbortError"?"SDK_CANCELLED":m==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",d)}};return Object.fromEntries(Object.keys(G).map(t=>[t,(n,s,p)=>r(t,n,s,p)]))}var Z=Symbol("base-database-runtime-profile");function ue(e,o){let r=Object.freeze({platformEnv:o.platformEnv,brand:o.brand});return function(t,n){let s=Object.defineProperty({...n},Z,{value:r});return e.call(this,t,s)}}function _(e){return{...e,records:Y(e,e[Z])}}async function X(e,o,r){let t;try{t=await e["~standard"].validate(o)}catch{throw new w("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(t.issues){let n=t.issues.map(s=>(s.path??[]).map(p=>{let l=typeof p=="object"?p.key:p;return typeof l=="number"||typeof l=="string"?l:"[symbol]"}));throw new w(`SDK_${r}_INVALID`,r==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:n})}return t.value}function ce(e){return async(o,r)=>{try{let t=await X(e.input,o,"INPUT"),n=await e.handler(t,_(r)),s=await X(e.output,n,"OUTPUT");return T(s),{code:0,msg:"success",data:s}}catch(t){let n=t instanceof w?t:new w("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:n.code,paths:n.paths,retryable:n.retryable,outcome:n.outcome}));let s={code:n.wireCode,msg:n.safeMessage};return t instanceof w||Object.defineProperty(s,Symbol.for("base-site.function-error"),{value:t}),s}}}var Q="base-site.durable",ee="base-site.runtime";var F=class extends Error{constructor(r,t=r,n,s){super(t,s);this.code=r;this.logId=n;this.name="DurableError"}},k=class extends Error{constructor(o){super(o),this.name="NonRetryableError"}},P=class extends Error{constructor(r,t){super(t.message);this.key=r;this.error=t;this.name="StepFailedError"}};function J(e,o,r){let t="Unknown error",n="Error";try{e instanceof Error?(typeof e.message=="string"&&(t=e.message),typeof e.name=="string"&&(n=e.name)):typeof e=="string"&&(t=e)}catch{}t=t.slice(0,1024*4).replace(/([?&][^=&#\s]*?(?:token|ticket|code|secret|key|password|authorization)[^=&#\s]*=)[^&#\s]*/gi,"$1[REDACTED]").replace(/\bBearer\s+[^\s"'<>]+/gi,"Bearer [REDACTED]");let s="",p=0;for(let l of t){if(p+=new TextEncoder().encode(l).length,p>1024)break;s+=l}return{name:n,message:s,...o?{code:o}:{},...r?{key:r}:{},...e instanceof k?{retryable:!1}:{}}}function re(e,o){return`${e} schema validation failed: `+o.slice(0,3).map(r=>`${r.path?.map(n=>String(typeof n=="object"?n.key:n)).join(".")||"$"}: ${r.message}`).join("; ")}function $(e){let o={ms:1,s:1e3,m:6e4,h:36e5,d:864e5},r=typeof e=="string"&&/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(e),t=typeof e=="number"?e:r?Number(r[1])*o[r[2]]:NaN;if(!Number.isSafeInteger(t)||t<0)throw new Error("Invalid duration");return t}function z(e){return T(e),e}function q(e){return new TextEncoder().encode(JSON.stringify(e)).length}var A=()=>new Promise(()=>{});function ye(e){let o={v:1,async execute(r,t){try{return await xe(e,r,t)}catch(n){return{v:1,seq:r?.invocation?.seq??0,op:"fail",error:J(n,"HANDLER_ERROR")}}}};return{[Symbol.for(Q)]:o}}function xe(e,o,r){return new Promise(t=>{let n={v:1,seq:o.invocation.seq},s=new Set,p=new Map(o.steps.map(i=>[i.key,i])),l,R=!1,d=!1,a,u,m,g,b=Math.min(r.deadline,o.invocation.deadline),O=i=>{d||((!a||i.op==="fail")&&(a=i),queueMicrotask(()=>{d||!a||(d=!0,clearTimeout(E),clearTimeout(m),r.signal.removeEventListener("abort",h),u?.abort(),t({...a,...l!==void 0?{progress:l}:{}}))}))},f=(i,y,c=new Error(i))=>O({...n,op:"fail",error:J(c,i,y)}),h=()=>g?g():f("REPLAY_TIMEOUT"),E=setTimeout(h,Math.max(0,b-Date.now())),j=(i,y)=>{if(d||a?.op==="fail")return;if(Date.now()>=b){h();return}if(typeof i!="string"||i.length<1||i.length>128||/[\x00-\x1f\x7f-\x9f]/.test(i)){f("DEFINITION_INVALID",void 0,new Error("Invalid step key"));return}if(s.has(i)){f("DUPLICATE_STEP_KEY",i);return}s.add(i);let c=p.get(i);if(c){if(c.kind!==y){f("DEFINITION_KIND_MISMATCH",i);return}if(!c.ok)throw new P(i,c.error);return{fresh:!1,value:y==="sleep"?void 0:c.timedOut?null:c.value}}if(R){f("PARALLEL_STEPS",i);return}if(p.size>=100){f("STEP_LIMIT",i);return}return R=!0,{fresh:!0}},oe={async run(i,y,c={}){let x=j(i,"run");if(!x)return A();if(!x.fresh)return x.value;let I,K=c.retries??3;try{if(I=c.timeout===void 0?b-Date.now():Math.min($(c.timeout),b-Date.now()),!Number.isSafeInteger(K)||K<0||I<=0)throw new Error("Invalid step options")}catch(D){return f("DEFINITION_INVALID",i,D),A()}u=new AbortController;let se=u.signal,C=Date.now(),U=(D,L)=>O({...n,op:"step",key:i,ok:!1,error:J(D,L,i),policy:{retries:K},durationMs:Math.max(0,Date.now()-C)});return g=()=>{U(new Error("Step exceeded its deadline"),"STEP_TIMEOUT"),u?.abort()},m=setTimeout(g,I),Promise.resolve().then(async()=>{if(!(a||d))try{let D=await y({signal:se,attempt:o.invocation.attempt});if(Date.now()>=C+I){g?.();return}let L=z(D===void 0?null:D);if(q(L)>262144){U(new k("Step result exceeds 256KB"),"STEP_RESULT_TOO_LARGE");return}O({...n,op:"step",key:i,ok:!0,value:L,durationMs:Math.max(0,Date.now()-C)})}catch(D){Date.now()>=C+I?g?.():U(D)}}),A()},async sleep(i,y){let c=j(i,"sleep");if(!c)return A();if(c.fresh){try{let x=$(y);if(x<1e3||x>2592e6)throw new Error("Sleep duration must be between 1s and 30d");O({...n,op:"sleep",key:i,durationMs:x})}catch(x){f("DEFINITION_INVALID",i,x)}return A()}},async waitForEvent(i,y,c){if(!Object.hasOwn(e.events??{},y))return f("EVENT_UNDECLARED",i),A();let x=j(i,"wait");if(!x)return A();if(!x.fresh)return x.value;try{let I=$(c.timeout);if(I<1e3||I>2592e6)throw new Error("Event timeout must be between 1s and 30d");O({...n,op:"wait",key:i,event:y,timeoutMs:I})}catch(I){f("DEFINITION_INVALID",i,I)}return A()},progress(i){if(!d)try{let y=z(i);q(y)<=4096?l=JSON.parse(JSON.stringify(y)):console.warn("Durable progress exceeds 4KB; discarded")}catch{f("DEFINITION_INVALID",void 0,new Error("Progress must be JSON"))}}};if(r.signal.addEventListener("abort",h,{once:!0}),r.signal.aborted||b<=Date.now()){h();return}Promise.resolve().then(async()=>{try{let i;try{let c=await e.input["~standard"].validate(o.input);if(c.issues)throw new Error(re("Input",c.issues));i=c.value}catch(c){f("INPUT_INVALID",void 0,c);return}if(d||a)return;if(Date.now()>=b){f("REPLAY_TIMEOUT");return}let y=await e.handler(i,oe,_(r.ctx));if(R||d||a)return;try{let c=await e.output["~standard"].validate(y);if(c.issues)throw new Error(re("Output",c.issues));if(Date.now()>=b){f("REPLAY_TIMEOUT");return}let x=z(c.value);if(q(x)>262144)throw new Error("Output exceeds 256KB");O({...n,op:"done",output:x})}catch(c){f("OUTPUT_INVALID",void 0,c)}}catch(i){f("HANDLER_ERROR",i instanceof P?i.key:void 0,i)}})})}async function v(e){let o=globalThis[Symbol.for(ee)],r=o?.v===1?o.context.getStore()?.ctx:void 0;if(!r?.faasInvoke)throw new F("DURABLE_NO_CONTEXT");try{let t=await r.faasInvoke({method:"durable",params:JSON.stringify(e)});if(!t||t.code!==0)throw new F(t?.data?.reason??"INFRA_UNAVAILABLE",t?.msg,t?.data?.logId);return t.data}catch(t){if(t instanceof F)throw t;let n=t,p=[n?.code??n?.cause?.code,n?.message,n?.cause?.message].filter(l=>l!=null&&l!=="").join(": ")||(typeof t=="string"?t:"INFRA_UNAVAILABLE");throw new F("INFRA_UNAVAILABLE",p,n?.logId,{cause:t})}}var Se={start(e,o,r){return v({...r,action:"start",functionId:e,input:o})},get(e,o){return v({...o,action:"get",runId:e})},list(e){return v({...e,action:"list"})},cancel(e,o){return v({...o,action:"cancel",runId:e})},signal(e,o,r,t){return v({...t,action:"signal",runId:e,event:o,data:r})}};export{F as DurableError,k as NonRetryableError,w as SDKError,P as StepFailedError,ue as bindFunctionRuntime,_ as createServerContext,ye as defineDurableFunction,ce as defineFunction,Se as durable,W as normalizeRecordsResult};
package/docs/codegen.md CHANGED
@@ -29,4 +29,4 @@ export const files = await generateFunctionClients(data);
29
29
 
30
30
  生成完成后运行 `base-database-cli check --json` 检查契约与生成文件是否一致。
31
31
 
32
- Durable Function 使用 `functionType=6`,`functions` 和 `inputs` 均可保留该类型。`inputSchema` 是任务控制命令的 Schema(例如 `action: start`、`input` 和 `idempotencyKey`),不直接用 Workflow 的业务输入替代。生成的客户端沿用 Function 调用入口;有输出 Schema 时保留其类型,没有时为 `unknown`。Durable 不生成 Mutation 标记,也不能通过 Mutation 批量接口调用。
32
+ Page 客户端只接受 SQL、FaaS 与 Mutation(`functionType=1|2|5`)。Durable Function 不生成页面调用入口;在 server 代码中通过 `/server` 的 `durable` 客户端控制任务。
package/docs/durable.md CHANGED
@@ -1,54 +1,117 @@
1
- # Base Site Durable SDK
1
+ # 长时任务 SDK
2
2
 
3
- 供 Base Site 的 Durable Function 源码使用。Workflow 定义执行顺序和等待,Activity 执行网络请求、站点 Function 调用等业务操作。执行由 DevCenter 管理的 Worker 承载。
3
+ 从 `/server` 导入 `defineDurableFunction`、`durable`、`NonRetryableError`、`StepFailedError` 与 `DurableError`。长时任务放在 `server/durable/<id>`,与普通 Function 共用依赖与构建。
4
4
 
5
- Durable 是 App SDK 的两个子入口。预发布版本 0.6.0-durable.0 使用 npm 的 durable 标签。使用前需确认目标平台已部署匹配的 Durable 运行时。
5
+ `defineDurableFunction({ input, output, events, handler })` 返回默认导出对象。handler 参数为 `(input, step, ctx)`;契约使用 Standard Schema(如 zod)。`events` 可省略,默认 `{}`;未声明的事件不能等待或发送。每轮推进按当前契约解析 input,default、transform 均生效;不合规时以 INPUT_INVALID 失败。handler 返回后校验 output。INPUT_INVALID / OUTPUT_INVALID 的 message 附前 3 条 schema issues(字段路径与原因),UTF-8 总长不超过 1KB。
6
6
 
7
- ## 构建与安装
7
+ - `step.run(key, callback, { timeout?, retries? })`:回调接收 `{ signal, attempt }`。默认重试 3 次(最多 4 次尝试),按 1 秒起、倍增至最多 60 秒的间隔退避;抛出 `NonRetryableError` 禁止重试。失败耗尽后重放抛出 `StepFailedError`,业务可捕获补偿。错误仅包含 key、error;重试次数见 durable.get 返回的 step 列表。
8
+ - `step.sleep(key, duration)`:持久化等待。时长支持毫秒数以及 `ms`、`s`、`m`、`h`、`d` 后缀。
9
+ - `step.waitForEvent(key, event, { timeout })`:等待声明的事件,超时返回 null。sleep/wait 时长范围为 1 秒至 30 天。
10
+ - `step.progress(value)`:记录本轮最后一个有效 JSON 进度,超过 4KB 丢弃。
8
11
 
9
- 安装此预发布版本:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.0`。
12
+ 每个 key 在流程中唯一;循环使用动态 key。只支持顺序 await,不支持 Promise.all。每轮只执行第一个未记录步骤;该 await 不恢复,平台记录结果后重新调用整个 handler。步骤外代码每轮重放,随机值、时间与外部副作用放进 step.run。步骤至少执行一次,写入仍需业务幂等。step.run 结果与最终输出各最大 256KB;step.run 的 void 结果转为 null。最多记录 100 个步骤。
10
13
 
11
- 本地开发 SDK 时,在 SDK 根目录执行 `npm ci`、`npm run build`、`npm pack`。构建完成类型检查、JS 编译和公开声明生成。在使用项目中通过 `npm install <tarball-path>` 安装。Temporal 是可选 peer。开发时若直接加载 Durable 模块,需要安装 `@temporalio/workflow@1.24.0` 与 `@temporalio/activity@1.24.0`;只做公开类型检查不需要加载它们。托管 Worker 负责提供匹配版本,当前固定为 1.24.0。
14
+ ## 报销审批
12
15
 
13
- Durable 使用 `/durable/workflow` 和 `/durable/activity` 两个入口。Workflow API 在 Temporal Workflow 执行上下文内使用,Activity API 在托管 Worker 的 Activity 上下文内使用;普通 Node 进程中的 import 成功不代表任务可以执行。
16
+ <!-- example: durable.ts -->
17
+ ```ts
18
+ import { z } from 'zod';
19
+ import { defineDurableFunction } from '@lark-base-open/base-database-app-sdk/server';
20
+
21
+ export const input = z.object({ title: z.string(), amount: z.number().positive(), approverId: z.string() });
22
+ export const output = z.object({ expenseId: z.string(), status: z.enum(['paid', 'rejected', 'expired']) });
23
+ export const events = { approval: z.object({ approved: z.boolean() }) };
24
+
25
+ // 业务模块由应用提供;写入需以业务单号去重。
26
+ export function expenseApproval(service: {
27
+ createExpense(value: z.infer<typeof input>): Promise<{ id: string }>;
28
+ notifyApprover(id: string, approver: string): Promise<void>;
29
+ setStatus(id: string, status: 'paid' | 'rejected' | 'expired'): Promise<void>;
30
+ }) {
31
+ return defineDurableFunction({ input, output, events, handler: async (input, step) => {
32
+ const expense = await step.run('create', () => service.createExpense(input), { timeout: '30s', retries: 3 });
33
+ await step.run('notify', () => service.notifyApprover(expense.id, input.approverId));
34
+ step.progress({ stage: 'waiting_approval' });
35
+ const decision = await step.waitForEvent('wait-approval', 'approval', { timeout: '3d' });
36
+ const status = decision === null ? 'expired' : decision.approved ? 'paid' : 'rejected';
37
+ await step.run(status === 'paid' ? 'pay' : status === 'expired' ? 'expire' : 'reject', () => service.setStatus(expense.id, status));
38
+ return { expenseId: expense.id, status } as const;
39
+ } });
40
+ }
41
+ ```
14
42
 
15
- ## 编排与步骤
43
+ ## server 控制接口
16
44
 
17
- `workflow.ts`:
45
+ `durable.start(functionId, input, { idempotencyKey? })`、`get(runId, { scope? })`、`list({ functionId?, status?, scope?, pageToken?, pageSize? })`、`cancel(runId, { scope? })`、`signal(runId, event, data, { eventId })` 只能在请求上下文中调用。默认只查询或取消当前调用人启动的任务,全站点可见性需显式 scope: 'site'。审批业务需自行鉴权。
18
46
 
19
- <!-- example: durable-workflow.ts -->
20
- ```ts
21
- import { callStep, reportProgress, sleep } from '@lark-base-open/base-database-app-sdk/durable/workflow';
47
+ 调用失败抛出 `DurableError`,包含 `code`、`message` 和 `logId`。业务失败的 `code` 取自响应 `data.reason`,`logId` 取自 `data.logId`,`message` 保留响应 `msg`,不从 msg 猜错误码。缺少请求上下文时 code 为 DURABLE_NO_CONTEXT;网络异常的 code 固定为 INFRA_UNAVAILABLE,message 保留底层错误码(如 ECONNREFUSED)和原因,cause 保留原始异常,没有请求 LogID 时 logId 为 undefined。业务身份不会缓存在模块变量中。
22
48
 
23
- export default async function task(input: { value: number }) {
24
- const result = await callStep<number>('double', input, { key: 'double-input' });
25
- reportProgress({ processed: 1, total: 1 });
26
- await sleep(1000);
27
- return result;
28
- }
29
- ```
49
+ `get` 的 `steps` 包含 `attempts` 和可选 `lastError`(最近一次失败的 name、message、code、key、retryable),重试过程中也可查看;step 不带 logId。run 在运行期间及结束后 7 天内可查询。运行错误仅遮盖 URL 中 token、ticket、code、secret、key、password、authorization 等参数值以及 Bearer 凭证,保留长记录 ID。
50
+
51
+ ## 契约类型生成
30
52
 
31
- `activities.ts`:
53
+ CLI `contracts generate` 从契约渲染 `server/src/generated/durable.d.ts`,增强 `/server` 导出的 `DurableFunctions` 接口;每个函数项为 `{ input; output; events }`,events 省略时生成为 `{}`。SDK 不提供这份文件的 codegen。确保 tsconfig 包含生成文件:
32
54
 
33
- <!-- example: durable-activities.ts -->
55
+ <!-- example: durable-control.ts -->
34
56
  ```ts
35
- export async function double(input: { value: number }): Promise<number> {
36
- return input.value * 2;
57
+ import { durable, DurableError } from '@lark-base-open/base-database-app-sdk/server';
58
+ import type { z } from 'zod';
59
+ import type { input, output, events } from './durable';
60
+
61
+ // 应用中由 CLI contracts generate 写入 server/src/generated/durable.d.ts。
62
+ declare module '@lark-base-open/base-database-app-sdk/server' {
63
+ interface DurableFunctions {
64
+ expenseApproval: {
65
+ input: z.input<typeof input>;
66
+ output: z.output<typeof output>;
67
+ events: { approval: z.input<typeof events.approval> };
68
+ };
69
+ }
37
70
  }
38
- ```
39
71
 
40
- 在对应 Function 的 `meta.json` 中声明 `double` Activity 的 timeout 和 retry.maximumAttempts。输入 Schema、发布方式和任务调用接口由 Site/DevCenter 契约管理。
72
+ // 在普通 server Function 的请求上下文中调用;业务需自行鉴权。
73
+ export async function startExpense(value: z.input<typeof input>) {
74
+ try {
75
+ const { runId } = await durable.start('expenseApproval', value);
76
+ const run = await durable.get<'expenseApproval'>(runId);
77
+ return { runId, status: run.status, expenseId: run.output?.expenseId };
78
+ } catch (error) {
79
+ if (error instanceof DurableError) {
80
+ console.error({ code: error.code, message: error.message, logId: error.logId });
81
+ }
82
+ throw error;
83
+ }
84
+ }
41
85
 
42
- `callStep` 的 key 在同一次 Workflow 中必须唯一;等待使用 SDK 的 `sleep` 或 `waitForEvent`,外部 I/O 放入 Activity。暂停在 SDK 边界生效,不中断已经开始执行的 Activity。
86
+ export async function approveExpense(runId: string, eventId: string) {
87
+ return durable.signal<'expenseApproval', 'approval'>(runId, 'approval', { approved: true }, { eventId });
88
+ }
89
+ ```
43
90
 
44
- ## 站点能力
91
+ `start` 根据 functionId 推断 input;`get<'expenseApproval'>(runId)` 显式指定函数来推断 output(未完成时可为 null);`signal<'expenseApproval', 'approval'>(runId, 'approval', { approved: true }, { eventId: 'decision-1' })` 显式指定函数与事件。runId 始终是 string,类型增强不改变运行时行为。未增强接口时,函数名和事件名接受 string,数据回退 JSONValue。
45
92
 
46
- Activity 通过 `invokeFunction(functionId, input, { key })` 调用同一站点的普通 Function,input 与普通调用请求体一致,例如 `{ params: { city: '北京' } }`。key 表示同一个业务调用,Activity 重试时保持不变。平台注入调用通道和执行凭证,业务源码不传 token。
93
+ 完整调用示例见 [durable-control.ts](../examples/durable-control.ts)。
47
94
 
48
- 请求结果未知时 Activity 可能重试。稳定 key 不等于业务端已经去重,写操作仍须由 Function 实现幂等处理。
95
+ ## 声明 Timer Trigger
49
96
 
50
- ## 类型维护
97
+ 在所属函数 `server/durable/<functionId>/meta.json` 声明 `triggers`:
51
98
 
52
- 公开声明由 TypeScript 源码生成,内部启动器接口不出现在公开声明中。修改源码后执行 `npm run build`。平台私有传输实现不进入 SDK tarball。
99
+ <!-- example: durable-trigger.ts -->
100
+ ```ts
101
+ // 将此对象保存为 server/durable/dailyReport/meta.json 的 JSON 内容。
102
+ export const meta = {
103
+ "triggers": [{
104
+ "id": "daily-report",
105
+ "type": "timer",
106
+ "timer": {
107
+ "startAt": "2026-11-10T09:00:00+08:00",
108
+ "timezone": "Asia/Shanghai",
109
+ "repeat": { "unit": "DAY", "interval": 1 }
110
+ },
111
+ "input": { "scope": "yesterday" },
112
+ "enabled": true
113
+ }]
114
+ };
115
+ ```
53
116
 
54
- SDK 的构建、声明与打包测试由本目录独立维护。执行端消费本包的 tarball;平台凭证传输和 Worker 管理不进入此包。
117
+ id 在站点内唯一,为 1–64 位字母、数字、下划线或连字符。声明随部署、发布与版本恢复生效;input 必须符合所属函数契约。Preview 不自动触发,可用 CLI `durable trigger fire <triggerId>` 按声明 input 以站点 Owner 身份手动验证,需要站点管理权限。Prod 自动触发,CLI 只提供 `trigger enable/disable` 开关,已有 id 的线上开关在发布时保留。删除声明或停用 Trigger 不取消在途 run。SDK 仅提供 server 代码的 run 控制,不提供线上规则 CRUD;CLI 的 run.start/cancel/signal 限 Preview,Prod 仅可 get/list 查询。
package/docs/exports.md CHANGED
@@ -10,9 +10,9 @@
10
10
 
11
11
  ## server
12
12
 
13
- 值:`SDKError`、`bindFunctionRuntime`、`createServerContext`、`defineFunction`、`normalizeRecordsResult`。
13
+ 值:`DurableError`、`NonRetryableError`、`SDKError`、`StepFailedError`、`bindFunctionRuntime`、`createServerContext`、`defineDurableFunction`、`defineFunction`、`durable`、`normalizeRecordsResult`。
14
14
 
15
- 类型与值完整清单:`AttachmentInput`、`Attachments`、`DefineFunctionOptions`、`DefinedFunction`、`DiagnosticCategory`、`Fields`、`FunctionEnvelope`、`FunctionResult`、`JsonValue`、`LegacyFunctionHandler`、`RawFunctionContext`、`RecordsClient`、`RecordsOperation`、`RecordsResultRequest`、`RuntimeBuildProfile`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`ServerContext`、`Target`、`WriteResult`、`bindFunctionRuntime`、`createServerContext`、`defineFunction`、`normalizeRecordsResult`。
15
+ 类型与值完整清单:`AttachmentInput`、`Attachments`、`DefineDurableFunctionOptions`、`DefineFunctionOptions`、`DefinedDurableFunction`、`DefinedFunction`、`DiagnosticCategory`、`DurableError`、`DurableFunctions`、`DurableStep`、`Duration`、`Fields`、`FunctionEnvelope`、`FunctionResult`、`JsonValue`、`LegacyFunctionHandler`、`NonRetryableError`、`RawFunctionContext`、`RecordsClient`、`RecordsOperation`、`RecordsResultRequest`、`RuntimeBuildProfile`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`ServerContext`、`StepExecutionContext`、`StepFailedError`、`StepRunOptions`、`Target`、`WriteResult`、`bindFunctionRuntime`、`createServerContext`、`defineDurableFunction`、`defineFunction`、`durable`、`normalizeRecordsResult`。
16
16
 
17
17
  ## shared
18
18
 
@@ -43,15 +43,3 @@
43
43
  值:`CodegenError`、`SUPPORTED_CONTRACT_FORMAT_VERSIONS`、`generateFunctionClients`、`validateContractData`。
44
44
 
45
45
  类型与值完整清单:`ClientContract`、`CodegenError`、`FunctionContractData`、`FunctionInputContract`、`GeneratedFile`、`SUPPORTED_CONTRACT_FORMAT_VERSIONS`、`generateFunctionClients`、`validateContractData`。
46
-
47
- ## durable/workflow
48
-
49
- 值:`callStep`、`reportProgress`、`sleep`、`waitForEvent`。
50
-
51
- 类型与值完整清单:`callStep`、`reportProgress`、`sleep`、`waitForEvent`。
52
-
53
- ## durable/activity
54
-
55
- 值:`cancellationSignal`、`getAttempt`、`invokeFunction`。
56
-
57
- 类型与值完整清单:`cancellationSignal`、`getAttempt`、`invokeFunction`。
@@ -0,0 +1,32 @@
1
+ import { durable, DurableError } from '@lark-base-open/base-database-app-sdk/server';
2
+ import type { z } from 'zod';
3
+ import type { input, output, events } from './durable';
4
+
5
+ // 应用中由 CLI contracts generate 写入 server/src/generated/durable.d.ts。
6
+ declare module '@lark-base-open/base-database-app-sdk/server' {
7
+ interface DurableFunctions {
8
+ expenseApproval: {
9
+ input: z.input<typeof input>;
10
+ output: z.output<typeof output>;
11
+ events: { approval: z.input<typeof events.approval> };
12
+ };
13
+ }
14
+ }
15
+
16
+ // 在普通 server Function 的请求上下文中调用;业务需自行鉴权。
17
+ export async function startExpense(value: z.input<typeof input>) {
18
+ try {
19
+ const { runId } = await durable.start('expenseApproval', value);
20
+ const run = await durable.get<'expenseApproval'>(runId);
21
+ return { runId, status: run.status, expenseId: run.output?.expenseId };
22
+ } catch (error) {
23
+ if (error instanceof DurableError) {
24
+ console.error({ code: error.code, message: error.message, logId: error.logId });
25
+ }
26
+ throw error;
27
+ }
28
+ }
29
+
30
+ export async function approveExpense(runId: string, eventId: string) {
31
+ return durable.signal<'expenseApproval', 'approval'>(runId, 'approval', { approved: true }, { eventId });
32
+ }
@@ -0,0 +1,14 @@
1
+ // 将此对象保存为 server/durable/dailyReport/meta.json 的 JSON 内容。
2
+ export const meta = {
3
+ "triggers": [{
4
+ "id": "daily-report",
5
+ "type": "timer",
6
+ "timer": {
7
+ "startAt": "2026-11-10T09:00:00+08:00",
8
+ "timezone": "Asia/Shanghai",
9
+ "repeat": { "unit": "DAY", "interval": 1 }
10
+ },
11
+ "input": { "scope": "yesterday" },
12
+ "enabled": true
13
+ }]
14
+ };
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ import { defineDurableFunction } from '@lark-base-open/base-database-app-sdk/server';
3
+
4
+ export const input = z.object({ title: z.string(), amount: z.number().positive(), approverId: z.string() });
5
+ export const output = z.object({ expenseId: z.string(), status: z.enum(['paid', 'rejected', 'expired']) });
6
+ export const events = { approval: z.object({ approved: z.boolean() }) };
7
+
8
+ // 业务模块由应用提供;写入需以业务单号去重。
9
+ export function expenseApproval(service: {
10
+ createExpense(value: z.infer<typeof input>): Promise<{ id: string }>;
11
+ notifyApprover(id: string, approver: string): Promise<void>;
12
+ setStatus(id: string, status: 'paid' | 'rejected' | 'expired'): Promise<void>;
13
+ }) {
14
+ return defineDurableFunction({ input, output, events, handler: async (input, step) => {
15
+ const expense = await step.run('create', () => service.createExpense(input), { timeout: '30s', retries: 3 });
16
+ await step.run('notify', () => service.notifyApprover(expense.id, input.approverId));
17
+ step.progress({ stage: 'waiting_approval' });
18
+ const decision = await step.waitForEvent('wait-approval', 'approval', { timeout: '3d' });
19
+ const status = decision === null ? 'expired' : decision.approved ? 'paid' : 'rejected';
20
+ await step.run(status === 'paid' ? 'pay' : status === 'expired' ? 'expire' : 'reject', () => service.setStatus(expense.id, status));
21
+ return { expenseId: expense.id, status } as const;
22
+ } });
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-app-sdk",
3
- "version": "0.6.0-durable.1",
3
+ "version": "0.6.0-durable.3",
4
4
  "description": "Base Database 页面与服务端 SDK、平台组件及测试工具",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -54,26 +54,6 @@
54
54
  "types": "./dist/codegen.d.cts",
55
55
  "default": "./dist/codegen.cjs"
56
56
  }
57
- },
58
- "./durable/workflow": {
59
- "import": {
60
- "types": "./dist/durable/workflow.d.cts",
61
- "default": "./dist/durable/workflow.cjs"
62
- },
63
- "require": {
64
- "types": "./dist/durable/workflow.d.cts",
65
- "default": "./dist/durable/workflow.cjs"
66
- }
67
- },
68
- "./durable/activity": {
69
- "import": {
70
- "types": "./dist/durable/activity.d.cts",
71
- "default": "./dist/durable/activity.cjs"
72
- },
73
- "require": {
74
- "types": "./dist/durable/activity.d.cts",
75
- "default": "./dist/durable/activity.cjs"
76
- }
77
57
  }
78
58
  },
79
59
  "files": [
@@ -86,6 +66,16 @@
86
66
  "capabilities.json",
87
67
  "development-pairing.json"
88
68
  ],
69
+ "scripts": {
70
+ "build": "node scripts/sync-contract-schema.mjs --check && node scripts/sync-capabilities.mjs && tsup && tsup --config tsup.cjs.config.ts && cp src/page/theme.css dist/theme.css",
71
+ "test": "npm run check:migrations && node scripts/sync-capabilities.mjs --check && npm run build && node --import tsx --test test/*.test.ts && npm run test:types && npm run test:components",
72
+ "check:migrations": "node scripts/check-migrations.mjs",
73
+ "prepublishOnly": "npm run check:migrations",
74
+ "test:types": "tsc -p tsconfig.examples.json && tsc -p tsconfig.server.json && tsc -p tsconfig.cjs.json",
75
+ "test:browser": "node test/browser/verify.mjs && node test/browser/ui-verify.mjs",
76
+ "test:components": "vitest run",
77
+ "docs:exports": "node scripts/doc-exports.mjs"
78
+ },
89
79
  "dependencies": {
90
80
  "@lark-base-open/base-site-channel": "0.2.1",
91
81
  "@radix-ui/react-popover": "1.2.0",
@@ -97,21 +87,28 @@
97
87
  "@tanstack/react-query": "5.104.1",
98
88
  "msw": "2.11.6",
99
89
  "react": "^19.2.0",
100
- "react-dom": "^19.2.0",
101
- "@temporalio/activity": "1.24.0",
102
- "@temporalio/workflow": "1.24.0"
90
+ "react-dom": "^19.2.0"
103
91
  },
104
92
  "peerDependenciesMeta": {
105
93
  "msw": {
106
94
  "optional": true
107
- },
108
- "@temporalio/activity": {
109
- "optional": true
110
- },
111
- "@temporalio/workflow": {
112
- "optional": true
113
95
  }
114
96
  },
97
+ "devDependencies": {
98
+ "@testing-library/react": "16.3.0",
99
+ "@types/node": "22.15.0",
100
+ "@types/react": "19.2.17",
101
+ "@types/react-dom": "19.2.3",
102
+ "clean-publish": "7.1.0",
103
+ "jsdom": "26.1.0",
104
+ "msw": "2.11.6",
105
+ "pngjs": "7.0.0",
106
+ "tsup": "6.7.0",
107
+ "tsx": "4.20.3",
108
+ "typescript": "5.8.3",
109
+ "vitest": "3.2.4",
110
+ "zod": "4.2.1"
111
+ },
115
112
  "typesVersions": {
116
113
  "*": {
117
114
  "server": [
@@ -122,13 +119,13 @@
122
119
  ],
123
120
  "codegen": [
124
121
  "dist/codegen.d.cts"
125
- ],
126
- "durable/workflow": [
127
- "dist/durable/workflow.d.ts"
128
- ],
129
- "durable/activity": [
130
- "dist/durable/activity.d.ts"
131
122
  ]
132
123
  }
124
+ },
125
+ "clean-publish": {
126
+ "fields": [
127
+ "scripts"
128
+ ],
129
+ "beforeScript": "./scripts/prepare-publish.mjs"
133
130
  }
134
131
  }
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAttempt = getAttempt;
4
- exports.cancellationSignal = cancellationSignal;
5
- exports.__installCapabilityTransport = __installCapabilityTransport;
6
- exports.invokeFunction = invokeFunction;
7
- const activity_1 = require("@temporalio/activity");
8
- function getAttempt() { return (0, activity_1.activityInfo)().attempt; }
9
- function cancellationSignal() { return activity_1.Context.current().cancellationSignal; }
10
- let capabilityTransport;
11
- // 只由通用 Worker 启动器装配;公开 SDK 类型不暴露凭证或配置入口。
12
- /** @internal */
13
- function __installCapabilityTransport(transport) {
14
- if (capabilityTransport)
15
- throw new Error('Site capability transport is already configured');
16
- capabilityTransport = transport;
17
- }
18
- /** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
19
- async function invokeFunction(functionId, input, options) {
20
- if (!functionId || !options?.key || options.key.length > 256)
21
- throw new Error('Function and a stable call key are required');
22
- if (!capabilityTransport)
23
- throw new Error('Site capability transport is unavailable');
24
- return capabilityTransport((0, activity_1.activityInfo)().taskToken, { function_id: functionId, call_key: options.key, payload: input }, cancellationSignal());
25
- }
@@ -1,6 +0,0 @@
1
- export declare function getAttempt(): number;
2
- export declare function cancellationSignal(): AbortSignal;
3
- /** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
4
- export declare function invokeFunction<T = unknown>(functionId: string, input: Record<string, unknown>, options: {
5
- key: string;
6
- }): Promise<T>;
@@ -1,6 +0,0 @@
1
- export declare function getAttempt(): number;
2
- export declare function cancellationSignal(): AbortSignal;
3
- /** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
4
- export declare function invokeFunction<T = unknown>(functionId: string, input: Record<string, unknown>, options: {
5
- key: string;
6
- }): Promise<T>;
@@ -1,107 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runDefinition = runDefinition;
4
- exports.callStep = callStep;
5
- exports.sleep = sleep;
6
- exports.reportProgress = reportProgress;
7
- exports.waitForEvent = waitForEvent;
8
- const workflow_1 = require("@temporalio/workflow");
9
- let state;
10
- let definition;
11
- let keys;
12
- let events;
13
- let receivedEvents;
14
- let eventOverflow;
15
- function receiveEvent(name, data, id) {
16
- if (!(definition.events ?? ['approval']).includes(name))
17
- return;
18
- const key = id === undefined ? undefined : name + ':' + id;
19
- if (key && receivedEvents.has(key))
20
- return;
21
- if (receivedEvents.size >= 1000 || [...events.values()].reduce((n, items) => n + items.length, 0) >= 1000) {
22
- eventOverflow = true;
23
- return;
24
- }
25
- if (key)
26
- receivedEvents.add(key);
27
- const pending = events.get(name) ?? [];
28
- pending.push(data);
29
- events.set(name, pending);
30
- }
31
- /** @internal */
32
- async function runDefinition(meta, fn, input) {
33
- definition = meta;
34
- keys = new Set();
35
- events = new Map();
36
- receivedEvents = new Set();
37
- eventOverflow = false;
38
- state = { stage: 'starting', processed: 0, total: 0, paused: false, approved: false, results: [] };
39
- (0, workflow_1.setHandler)((0, workflow_1.defineQuery)('progress'), () => ({ ...state, results: [...state.results] }));
40
- (0, workflow_1.setHandler)((0, workflow_1.defineSignal)('pause'), () => { state.paused = true; });
41
- (0, workflow_1.setHandler)((0, workflow_1.defineSignal)('resume'), () => { state.paused = false; });
42
- (0, workflow_1.setHandler)((0, workflow_1.defineSignal)('approve'), () => { state.approved = true; receiveEvent('approval', { approved: true }); });
43
- (0, workflow_1.setHandler)((0, workflow_1.defineSignal)('event'), (event) => {
44
- if (!event || typeof event.name !== 'string' || typeof event.id !== 'string' || event.id.length < 8 || event.id.length > 128)
45
- return;
46
- receiveEvent(event.name, event.data, event.id);
47
- });
48
- try {
49
- const result = await fn(input);
50
- await boundary();
51
- state.stage = 'completed';
52
- return result;
53
- }
54
- catch (e) {
55
- if (e instanceof TypeError || e instanceof RangeError)
56
- throw workflow_1.ApplicationFailure.nonRetryable('Durable Function definition error', 'DefinitionError');
57
- throw e;
58
- }
59
- }
60
- async function boundary() {
61
- if (eventOverflow)
62
- throw workflow_1.ApplicationFailure.nonRetryable('Durable event limit exceeded', 'EventLimitExceeded');
63
- if (state.paused) {
64
- state.stage = 'paused';
65
- await (0, workflow_1.condition)(() => !state.paused || eventOverflow);
66
- }
67
- if (eventOverflow)
68
- throw workflow_1.ApplicationFailure.nonRetryable('Durable event limit exceeded', 'EventLimitExceeded');
69
- }
70
- async function callStep(name, args, options) {
71
- await boundary();
72
- if (!definition.activities[name] || !options.key || keys.has(options.key) || keys.size >= 100)
73
- throw workflow_1.ApplicationFailure.nonRetryable('Invalid or repeated step key', 'DefinitionError');
74
- keys.add(options.key);
75
- const policy = definition.activities[name];
76
- state.stage = 'processing';
77
- const activity = definition.id + '__' + name;
78
- const proxy = (0, workflow_1.proxyActivities)({
79
- activityId: options.key, startToCloseTimeout: policy.timeout, scheduleToCloseTimeout: '2 minutes',
80
- retry: { initialInterval: '1 second', maximumInterval: '5 seconds', maximumAttempts: policy.retry.maximumAttempts },
81
- });
82
- return proxy[activity](args);
83
- }
84
- async function sleep(milliseconds) {
85
- await boundary();
86
- state.stage = 'durable_wait';
87
- await (0, workflow_1.sleep)(milliseconds);
88
- await boundary();
89
- }
90
- function reportProgress(progress) {
91
- Object.assign(state, progress);
92
- }
93
- async function waitForEvent(name, options) {
94
- if (!(definition.events ?? ['approval']).includes(name))
95
- throw workflow_1.ApplicationFailure.nonRetryable('Undeclared event', 'DefinitionError');
96
- if (!Number.isFinite(options.timeout) || options.timeout <= 0)
97
- throw workflow_1.ApplicationFailure.nonRetryable('Invalid event timeout', 'DefinitionError');
98
- await boundary();
99
- state.stage = 'waiting_' + name;
100
- if (!await (0, workflow_1.condition)(() => (events.get(name)?.length ?? 0) > 0 || eventOverflow, options.timeout))
101
- throw workflow_1.ApplicationFailure.nonRetryable('Event wait timed out', 'EventTimeout');
102
- await boundary();
103
- const result = events.get(name).shift();
104
- if (name === 'approval')
105
- state.approved = false;
106
- return result;
107
- }
@@ -1,15 +0,0 @@
1
- type Json = any;
2
- export declare function callStep<T>(name: string, args: Json, options: {
3
- key: string;
4
- }): Promise<T>;
5
- export declare function sleep(milliseconds: number): Promise<void>;
6
- export declare function reportProgress(progress: {
7
- stage?: string;
8
- processed: number;
9
- total: number;
10
- results?: Json[];
11
- }): void;
12
- export declare function waitForEvent<T = Json>(name: string, options: {
13
- timeout: number;
14
- }): Promise<T>;
15
- export {};
@@ -1,15 +0,0 @@
1
- type Json = any;
2
- export declare function callStep<T>(name: string, args: Json, options: {
3
- key: string;
4
- }): Promise<T>;
5
- export declare function sleep(milliseconds: number): Promise<void>;
6
- export declare function reportProgress(progress: {
7
- stage?: string;
8
- processed: number;
9
- total: number;
10
- results?: Json[];
11
- }): void;
12
- export declare function waitForEvent<T = Json>(name: string, options: {
13
- timeout: number;
14
- }): Promise<T>;
15
- export {};
@@ -1,3 +0,0 @@
1
- export async function double(input: { value: number }): Promise<number> {
2
- return input.value * 2;
3
- }
@@ -1,8 +0,0 @@
1
- import { callStep, reportProgress, sleep } from '@lark-base-open/base-database-app-sdk/durable/workflow';
2
-
3
- export default async function task(input: { value: number }) {
4
- const result = await callStep<number>('double', input, { key: 'double-input' });
5
- reportProgress({ processed: 1, total: 1 });
6
- await sleep(1000);
7
- return result;
8
- }