@lark-base-open/base-database-app-sdk 0.0.1-alpha.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  用于开发以飞书多维表格为数据后端的 Base Database 应用,提供页面与服务端运行时、平台组件、版本化能力查询与测试工具。
4
4
 
5
- 安装:`npm install @lark-base-open/base-database-app-sdk@0.0.1-alpha.1`。
5
+ 安装:`npm install @lark-base-open/base-database-app-sdk@0.1.0`。
6
6
 
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.1.5。
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.1.6。
8
8
 
9
9
  server/shared 同时提供 ESM 和 CJS;page/components/testing/vite 仅 ESM。
10
10
 
@@ -34,10 +34,27 @@ SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务
34
34
 
35
35
  ## npm 发布
36
36
 
37
- SDK 0.0.1-alpha.1 依赖 channel 0.1.6,其 AI Function 调用需要后端与宿主支持 `functions/:key/invoke`。这两个版本均使用 `next` 标签。
37
+ SDK 0.1.0 依赖已发布的 channel 0.1.6,锁文件必须解析到 `registry.npmjs.org` 的制品。AI Function 调用需要后端与宿主支持 `functions/:key/invoke`。
38
38
 
39
- 先发布 channel 0.1.6,再将 SDK 的依赖锁解析到 registry 制品并运行构建、测试和打包检查。在 SDK 目录执行 `npm publish --tag next --registry=https://registry.npmjs.org/`。
39
+ 本版本为首个正式版,发布到 `latest`;channel 0.1.6 同步提升为 `latest`。CLI 已移除 codemod/自动迁移;契约生成使用工程安装的 SDK `./codegen` 入口,不要求 SDK 成为 `latest`。
40
40
 
41
- 后端与宿主上线并完成验收后,由用户执行 `npm dist-tag add @lark-base-open/base-site-channel@0.1.6 latest --registry=https://registry.npmjs.org/` 和 `npm dist-tag add @lark-base-open/base-database-app-sdk@0.0.1-alpha.1 latest --registry=https://registry.npmjs.org/`。使用 `npm view <pkg> dist-tags --json --registry=https://registry.npmjs.org/` 回读标签。
41
+ 在本 SDK 目录按顺序执行以下发布前检查(`npm test` 包含构建、公开文档与包边界检查、类型和组件测试):
42
42
 
43
- SDK 提升为 `latest` 之前,workspace 迁移命令不可用,会报 `SDK_CODEGEN_UNAVAILABLE`;迁移命令只读取 `latest`。
43
+ - `npm ci --registry=https://registry.npmjs.org/`
44
+ - `npm test`
45
+ - `node scripts/sync-contract-schema.mjs --check`
46
+ - `node scripts/sync-capabilities.mjs --check`
47
+ - `npm run docs:exports`
48
+ - `npm pack --dry-run --json`
49
+ - `npm publish --dry-run --tag latest --registry=https://registry.npmjs.org/`
50
+
51
+ 核对打包清单包含 dist、docs、examples、README、LICENSE、capabilities.json 与 development-pairing.json,以及所有 exports 指向的文件;不得包含测试、私有源码或本地配置。SDK 不提供根入口。
52
+
53
+ 检查通过后,由有发布权限的用户本人执行;先确认 `npm whoami` 返回预期账号:
54
+
55
+ - `npm whoami --registry=https://registry.npmjs.org/`
56
+ - `npm publish --tag latest --registry=https://registry.npmjs.org/`
57
+ - `npm view @lark-base-open/base-database-app-sdk@0.1.0 version dist --json --registry=https://registry.npmjs.org/`
58
+ - `npm view @lark-base-open/base-database-app-sdk dist-tags versions --json --registry=https://registry.npmjs.org/`
59
+
60
+ 回读应确认 `latest` 为 `0.1.0`。
package/capabilities.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "sdkVersion": "0.0.1-alpha.1",
3
+ "sdkVersion": "0.1.0",
4
4
  "capabilities": {
5
5
  "runtime.context": {
6
6
  "required": [
package/dist/codegen.cjs CHANGED
@@ -1,15 +1,15 @@
1
- "use strict";var A=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var R=(n,e)=>{for(var s in e)A(n,s,{get:e[s],enumerable:!0})},E=(n,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of F(e))!$.call(n,t)&&t!==s&&A(n,t,{get:()=>e[t],enumerable:!(i=k(e,t))||i.enumerable});return n};var x=n=>E(A({},"__esModule",{value:!0}),n);var J={};R(J,{CodegenError:()=>d,SUPPORTED_CONTRACT_FORMAT_VERSIONS:()=>M,generateFunctionClients:()=>G,validateContractData:()=>C});module.exports=x(J);var h=require("json-schema-to-typescript");function g(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let e=0,s=(i,t)=>{if(!(!i||typeof i!="object")){if(++e>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");if(Array.isArray(i))i.forEach(r=>s(r,t+1));else for(let[r,a]of Object.entries(i)){if(r==="$ref"&&(typeof a!="string"||!a.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].includes(r))throw new Error("CONTRACT_EXTERNAL_REF");s(a,t+1)}}};s(n,0)}var y="@lark-base-open/base-database-app-sdk/page",l=`/* Generated by base-database-cli. Do not edit. */
1
+ "use strict";var w=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var x=(n,e)=>{for(var o in e)w(n,o,{get:e[o],enumerable:!0})},E=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of F(e))!R.call(n,t)&&t!==o&&w(n,t,{get:()=>e[t],enumerable:!(r=$(e,t))||r.enumerable});return n};var _=n=>E(w({},"__esModule",{value:!0}),n);var U={};x(U,{CodegenError:()=>m,SUPPORTED_CONTRACT_FORMAT_VERSIONS:()=>G,generateFunctionClients:()=>J,validateContractData:()=>C});module.exports=_(U);var N=require("json-schema-to-typescript");function p(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let o=n;e(o);for(let t of["properties","patternProperties","$defs","definitions","dependentSchemas"]){let i=o[t];if(i&&typeof i=="object"&&!Array.isArray(i))for(let a of Object.values(i))p(a,e)}for(let t of["items","additionalItems","additionalProperties","unevaluatedProperties","unevaluatedItems","contains","propertyNames","not","if","then","else"]){let i=o[t];Array.isArray(i)?i.forEach(a=>p(a,e)):p(i,e)}for(let t of["allOf","anyOf","oneOf","prefixItems"])Array.isArray(o[t])&&o[t].forEach(i=>p(i,e));let r=o.dependencies;if(r&&typeof r=="object"&&!Array.isArray(r))for(let t of Object.values(r))Array.isArray(t)||p(t,e)}function g(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let e=0,o=(r,t)=>{if(!(!r||typeof r!="object")){if(++e>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");Object.values(r).forEach(i=>o(i,t+1))}};o(n,0),p(n,r=>{if(Object.hasOwn(r,"$ref")&&(typeof r.$ref!="string"||!r.$ref.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].some(t=>Object.hasOwn(r,t)))throw new Error("CONTRACT_EXTERNAL_REF")})}var l="@lark-base-open/base-database-app-sdk/page",b=`/* Generated by base-database-cli. Do not edit. */
2
2
  import type { DatabaseFunctionInputMap as GeneratedInputMap } from './database-function-inputs.generated';
3
- import '${y}';
4
- declare module '${y}' { interface FunctionInputMap extends GeneratedInputMap {} }
5
- `,w=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
3
+ import '${l}';
4
+ declare module '${l}' { interface FunctionInputMap extends GeneratedInputMap {} }
5
+ `,O=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
6
6
  export {};
7
- `;async function N(n,e,s="../lib/database-function-inputs.generated"){let i=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${y}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(s)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:e,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[r,a]of[...n].sort((o,c)=>o.functionId.localeCompare(c.functionId)).entries()){let o=`Function${r}Input`,c=`Function${r}Output`;i.push(`export type ${o} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`);let u=a.functionType===2?a.output:void 0;if(!u)i.push(`export type ${c} = unknown;`);else{g(u);try{i.push(await(0,h.compile)(_(u,c),c,{bannerComment:"",customName:(m,O)=>m.title===c?c:m.title||O?`${c}_${m.title||O}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}}))}catch{i.push(`// Schema could not be represented; no precision is claimed.
8
- export type ${c} = unknown;`)}}t.push(` [${JSON.stringify(a.functionId)}]: async (input: ${o}): Promise<${c}> => {
7
+ `;async function T(n,e,o="../lib/database-function-inputs.generated"){let r=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${l}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(o)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:e,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[i,a]of[...n].sort((s,c)=>s.functionId.localeCompare(c.functionId)).entries()){let s=`Function${i}Input`,c=`Function${i}Output`;r.push(`export type ${s} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`);let u=a.functionType===2?a.output:void 0;if(!u)r.push(`export type ${c} = unknown;`);else{g(u);try{r.push(await(0,N.compile)(P(u,c),c,{bannerComment:"",customName:(y,h)=>y.title===c?c:y.title||h?`${c}_${y.title||h}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}}))}catch{r.push(`// Schema could not be represented; no precision is claimed.
8
+ export type ${c} = unknown;`)}}t.push(` [${JSON.stringify(a.functionId)}]: async (input: ${s}): Promise<${c}> => {
9
9
  const response = await invokeDatabaseFunction<${c}>(${JSON.stringify(a.functionId)}, input);
10
10
  if (!response || !Number.isSafeInteger(response.code)) throw new SDKError('FUNCTION_RESPONSE_INVALID', 'Invalid Function response', {outcome:'unknown'});
11
11
  if (response.code !== 0) throw new SDKError('FUNCTION_INVOKE_FAILED', 'Function invocation failed', String(response.code));
12
12
  return response.data as ${c};
13
- },`)}return i.push(`declare module '${y}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),i.join(`
14
- `)}function _(n,e){let s=structuredClone(n),i=t=>{if(!t||typeof t!="object")return;if(Array.isArray(t)){t.forEach(i);return}let r=t;Object.values(r).forEach(i),Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)};return i(s),s.title=e,s}function p(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function b(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(b).join(", ")}]`:p(n)?`{ ${Object.entries(n).map(([e,s])=>`${JSON.stringify(e)}: ${b(s)}`).join("; ")} }`:"never"}function j(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 p(n);default:return!1}}function D(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(e=>typeof e=="string"):[]}function P(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 s=n.prefixItems,i=Array.isArray(s),t=i?s.filter(p):[];if(i&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(f).join(", ")}]`;let r=p(n.items)?f(n.items):"unknown";return t.length===0?`Array<${r}>`:`[${[...t.map(o=>`${f(o)}?`),`...Array<${r}>`].join(", ")}]`}case"object":{let s=p(n.properties)?n.properties:{},i=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(s).filter(u=>p(u[1])),r=new Set(t.map(([u])=>u)),a=[...i].filter(u=>!r.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let o=t.map(([u,m])=>`${JSON.stringify(u)}${i.has(u)?"":"?"}: ${f(m)}`);o.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${o.join("; ")} }`;return n.additionalProperties===!1?o.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function f(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let o of e)delete t[o];let r=e.map(o=>{let c=n[o].filter(p).map(f);return c.length?c.map(u=>`(${u})`).join(o==="allOf"?" & ":" | "):"never"}),a=f(t);return a!=="unknown"&&r.unshift(a),r.map(o=>`(${o})`).join(" & ")}if(Object.hasOwn(n,"const"))return b(n.const);let s=D(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(r=>s.length===0||s.some(a=>j(r,a)));return t.length===0?"never":t.map(b).join(" | ")}let i=[...new Set(s.map(t=>P(n,t)))];return i.length===0?"unknown":i.join(" | ")}function T(n){let e=[...n].sort((t,r)=>t.functionId<r.functionId?-1:t.functionId>r.functionId?1:0),s=e.map(t=>` ${JSON.stringify(t.functionId)}: ${f(t.inputSchema)}`),i=e.flatMap(t=>{let r=Object.entries(t.parameterOptions??{});return r.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...r.map(([a,o])=>` ${JSON.stringify(a)}: ${JSON.stringify(o)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...s,"}",...i.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 = {",...i,"} as const"]:[],""].join(`
15
- `)}var M=[1],d=class extends Error{constructor(s,i){super(i);this.code=s;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},S=l.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function C(n){if(!I(n)||n.contractFormatVersion!==1)throw new d("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let e=()=>{throw new d("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 s;try{s=JSON.stringify(n)}catch{return e()}Buffer.byteLength(s)>4*1024*1024&&e();for(let t of["functions","inputs"]){let r=n[t];if(!Array.isArray(r)||r.length>1e3)return e();let a=new Set;for(let o of r){if(!I(o)||typeof o.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(o.functionId)||a.has(o.functionId))return e();a.add(o.functionId),t==="functions"&&(typeof o.functionType!="number"||![1,2,5].includes(o.functionType))&&e(),t==="inputs"&&!I(o.inputSchema)&&e();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(o[c]!==void 0)try{g(o[c])}catch{e()}o.parameterOptions!==void 0&&(!I(o.parameterOptions)||!Object.values(o.parameterOptions).every(Array.isArray))&&e()}}let i=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!i.has(t.functionId))&&e()}async function G(n){if(C(n),n.previousAugmentation!==void 0&&![l,w,S].includes(n.previousAugmentation))throw new d("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:T(n.inputs)}];return n.client&&e.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"&&e.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?S:l:w}),e}0&&(module.exports={CodegenError,SUPPORTED_CONTRACT_FORMAT_VERSIONS,generateFunctionClients,validateContractData});
13
+ },`)}return r.push(`declare module '${l}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),r.join(`
14
+ `)}function P(n,e){let o=structuredClone(n);return p(o,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),o.title=e,o}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function A(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(A).join(", ")}]`:f(n)?`{ ${Object.entries(n).map(([e,o])=>`${JSON.stringify(e)}: ${A(o)}`).join("; ")} }`:"never"}function j(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 f(n);default:return!1}}function D(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(e=>typeof e=="string"):[]}function M(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 o=n.prefixItems,r=Array.isArray(o),t=r?o.filter(f):[];if(r&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(d).join(", ")}]`;let i=f(n.items)?d(n.items):"unknown";return t.length===0?`Array<${i}>`:`[${[...t.map(s=>`${d(s)}?`),`...Array<${i}>`].join(", ")}]`}case"object":{let o=f(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(o).filter(u=>f(u[1])),i=new Set(t.map(([u])=>u)),a=[...r].filter(u=>!i.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let s=t.map(([u,y])=>`${JSON.stringify(u)}${r.has(u)?"":"?"}: ${d(y)}`);s.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${s.join("; ")} }`;return n.additionalProperties===!1?s.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function d(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let s of e)delete t[s];let i=e.map(s=>{let c=n[s].filter(f).map(d);return c.length?c.map(u=>`(${u})`).join(s==="allOf"?" & ":" | "):"never"}),a=d(t);return a!=="unknown"&&i.unshift(a),i.map(s=>`(${s})`).join(" & ")}if(Object.hasOwn(n,"const"))return A(n.const);let o=D(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(i=>o.length===0||o.some(a=>j(i,a)));return t.length===0?"never":t.map(A).join(" | ")}let r=[...new Set(o.map(t=>M(n,t)))];return r.length===0?"unknown":r.join(" | ")}function S(n){let e=[...n].sort((t,i)=>t.functionId<i.functionId?-1:t.functionId>i.functionId?1:0),o=e.map(t=>` ${JSON.stringify(t.functionId)}: ${d(t.inputSchema)}`),r=e.flatMap(t=>{let i=Object.entries(t.parameterOptions??{});return i.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...i.map(([a,s])=>` ${JSON.stringify(a)}: ${JSON.stringify(s)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...o,"}",...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(`
15
+ `)}var G=[1],m=class extends Error{constructor(o,r){super(r);this.code=o;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 C(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 o;try{o=JSON.stringify(n)}catch{return e()}Buffer.byteLength(o)>4*1024*1024&&e();for(let t of["functions","inputs"]){let i=n[t];if(!Array.isArray(i)||i.length>1e3)return e();let a=new Set;for(let s of i){if(!I(s)||typeof s.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(s.functionId)||a.has(s.functionId))return e();a.add(s.functionId),t==="functions"&&(typeof s.functionType!="number"||![1,2,5].includes(s.functionType))&&e(),t==="inputs"&&!I(s.inputSchema)&&e();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(s[c]!==void 0)try{g(s[c])}catch{e()}s.parameterOptions!==void 0&&(!I(s.parameterOptions)||!Object.values(s.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!r.has(t.functionId))&&e()}async function J(n){if(C(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 e=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:S(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"?k:b:O}),e}0&&(module.exports={CodegenError,SUPPORTED_CONTRACT_FORMAT_VERSIONS,generateFunctionClients,validateContractData});
package/dist/codegen.js CHANGED
@@ -1,15 +1,15 @@
1
- import{compile as T}from"json-schema-to-typescript";function g(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let r=0,s=(o,t)=>{if(!(!o||typeof o!="object")){if(++r>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");if(Array.isArray(o))o.forEach(e=>s(e,t+1));else for(let[e,a]of Object.entries(o)){if(e==="$ref"&&(typeof a!="string"||!a.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].includes(e))throw new Error("CONTRACT_EXTERNAL_REF");s(a,t+1)}}};s(n,0)}var y="@lark-base-open/base-database-app-sdk/page",l=`/* Generated by base-database-cli. Do not edit. */
1
+ import{compile as S}from"json-schema-to-typescript";function p(n,r){if(!n||typeof n!="object"||Array.isArray(n))return;let s=n;r(s);for(let t of["properties","patternProperties","$defs","definitions","dependentSchemas"]){let o=s[t];if(o&&typeof o=="object"&&!Array.isArray(o))for(let a of Object.values(o))p(a,r)}for(let t of["items","additionalItems","additionalProperties","unevaluatedProperties","unevaluatedItems","contains","propertyNames","not","if","then","else"]){let o=s[t];Array.isArray(o)?o.forEach(a=>p(a,r)):p(o,r)}for(let t of["allOf","anyOf","oneOf","prefixItems"])Array.isArray(s[t])&&s[t].forEach(o=>p(o,r));let e=s.dependencies;if(e&&typeof e=="object"&&!Array.isArray(e))for(let t of Object.values(e))Array.isArray(t)||p(t,r)}function g(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let r=0,s=(e,t)=>{if(!(!e||typeof e!="object")){if(++r>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");Object.values(e).forEach(o=>s(o,t+1))}};s(n,0),p(n,e=>{if(Object.hasOwn(e,"$ref")&&(typeof e.$ref!="string"||!e.$ref.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].some(t=>Object.hasOwn(e,t)))throw new Error("CONTRACT_EXTERNAL_REF")})}var l="@lark-base-open/base-database-app-sdk/page",b=`/* Generated by base-database-cli. Do not edit. */
2
2
  import type { DatabaseFunctionInputMap as GeneratedInputMap } from './database-function-inputs.generated';
3
- import '${y}';
4
- declare module '${y}' { interface FunctionInputMap extends GeneratedInputMap {} }
5
- `,A=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
3
+ import '${l}';
4
+ declare module '${l}' { interface FunctionInputMap extends GeneratedInputMap {} }
5
+ `,w=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
6
6
  export {};
7
- `;async function O(n,r,s="../lib/database-function-inputs.generated"){let o=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${y}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(s)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:r,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[e,a]of[...n].sort((i,c)=>i.functionId.localeCompare(c.functionId)).entries()){let i=`Function${e}Input`,c=`Function${e}Output`;o.push(`export type ${i} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`);let u=a.functionType===2?a.output:void 0;if(!u)o.push(`export type ${c} = unknown;`);else{g(u);try{o.push(await T(S(u,c),c,{bannerComment:"",customName:(d,w)=>d.title===c?c:d.title||w?`${c}_${d.title||w}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}}))}catch{o.push(`// Schema could not be represented; no precision is claimed.
7
+ `;async function h(n,r,s="../lib/database-function-inputs.generated"){let e=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${l}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(s)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:r,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[o,a]of[...n].sort((i,c)=>i.functionId.localeCompare(c.functionId)).entries()){let i=`Function${o}Input`,c=`Function${o}Output`;e.push(`export type ${i} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`);let u=a.functionType===2?a.output:void 0;if(!u)e.push(`export type ${c} = unknown;`);else{g(u);try{e.push(await S(k(u,c),c,{bannerComment:"",customName:(m,O)=>m.title===c?c:m.title||O?`${c}_${m.title||O}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}}))}catch{e.push(`// Schema could not be represented; no precision is claimed.
8
8
  export type ${c} = unknown;`)}}t.push(` [${JSON.stringify(a.functionId)}]: async (input: ${i}): Promise<${c}> => {
9
9
  const response = await invokeDatabaseFunction<${c}>(${JSON.stringify(a.functionId)}, input);
10
10
  if (!response || !Number.isSafeInteger(response.code)) throw new SDKError('FUNCTION_RESPONSE_INVALID', 'Invalid Function response', {outcome:'unknown'});
11
11
  if (response.code !== 0) throw new SDKError('FUNCTION_INVOKE_FAILED', 'Function invocation failed', String(response.code));
12
12
  return response.data as ${c};
13
- },`)}return o.push(`declare module '${y}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),o.join(`
14
- `)}function S(n,r){let s=structuredClone(n),o=t=>{if(!t||typeof t!="object")return;if(Array.isArray(t)){t.forEach(o);return}let e=t;Object.values(e).forEach(o),Array.isArray(e.prefixItems)&&(e.additionalItems=e.items??e.maxItems!==e.prefixItems.length,e.items=e.prefixItems,delete e.prefixItems)};return o(s),s.title=r,s}function p(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function b(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(b).join(", ")}]`:p(n)?`{ ${Object.entries(n).map(([r,s])=>`${JSON.stringify(r)}: ${b(s)}`).join("; ")} }`:"never"}function C(n,r){switch(r){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 p(n);default:return!1}}function k(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(r=>typeof r=="string"):[]}function F(n,r){switch(r){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let s=n.prefixItems,o=Array.isArray(s),t=o?s.filter(p):[];if(o&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(f).join(", ")}]`;let e=p(n.items)?f(n.items):"unknown";return t.length===0?`Array<${e}>`:`[${[...t.map(i=>`${f(i)}?`),`...Array<${e}>`].join(", ")}]`}case"object":{let s=p(n.properties)?n.properties:{},o=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(s).filter(u=>p(u[1])),e=new Set(t.map(([u])=>u)),a=[...o].filter(u=>!e.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let i=t.map(([u,d])=>`${JSON.stringify(u)}${o.has(u)?"":"?"}: ${f(d)}`);i.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${i.join("; ")} }`;return n.additionalProperties===!1?i.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function f(n){let r=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(r.length){let t={...n};for(let i of r)delete t[i];let e=r.map(i=>{let c=n[i].filter(p).map(f);return c.length?c.map(u=>`(${u})`).join(i==="allOf"?" & ":" | "):"never"}),a=f(t);return a!=="unknown"&&e.unshift(a),e.map(i=>`(${i})`).join(" & ")}if(Object.hasOwn(n,"const"))return b(n.const);let s=k(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(e=>s.length===0||s.some(a=>C(e,a)));return t.length===0?"never":t.map(b).join(" | ")}let o=[...new Set(s.map(t=>F(n,t)))];return o.length===0?"unknown":o.join(" | ")}function h(n){let r=[...n].sort((t,e)=>t.functionId<e.functionId?-1:t.functionId>e.functionId?1:0),s=r.map(t=>` ${JSON.stringify(t.functionId)}: ${f(t.inputSchema)}`),o=r.flatMap(t=>{let e=Object.entries(t.parameterOptions??{});return e.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...e.map(([a,i])=>` ${JSON.stringify(a)}: ${JSON.stringify(i)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...s,"}",...o.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 = {",...o,"} as const"]:[],""].join(`
15
- `)}var G=[1],m=class extends Error{constructor(s,o){super(o);this.code=s;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},N=l.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function $(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let r=()=>{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")&&r();let s;try{s=JSON.stringify(n)}catch{return r()}Buffer.byteLength(s)>4*1024*1024&&r();for(let t of["functions","inputs"]){let e=n[t];if(!Array.isArray(e)||e.length>1e3)return r();let a=new Set;for(let i of e){if(!I(i)||typeof i.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(i.functionId)||a.has(i.functionId))return r();a.add(i.functionId),t==="functions"&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&r(),t==="inputs"&&!I(i.inputSchema)&&r();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(i[c]!==void 0)try{g(i[c])}catch{r()}i.parameterOptions!==void 0&&(!I(i.parameterOptions)||!Object.values(i.parameterOptions).every(Array.isArray))&&r()}}let o=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!o.has(t.functionId))&&r()}async function J(n){if($(n),n.previousAugmentation!==void 0&&![l,A,N].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let r=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:h(n.inputs)}];return n.client&&r.push({path:"page/src/generated/functions.ts",content:await O(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&r.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?N:l:A}),r}export{m as CodegenError,G as SUPPORTED_CONTRACT_FORMAT_VERSIONS,J as generateFunctionClients,$ as validateContractData};
13
+ },`)}return e.push(`declare module '${l}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),e.join(`
14
+ `)}function k(n,r){let s=structuredClone(n);return p(s,e=>{Array.isArray(e.prefixItems)&&(e.additionalItems=e.items??e.maxItems!==e.prefixItems.length,e.items=e.prefixItems,delete e.prefixItems)}),s.title=r,s}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function A(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(A).join(", ")}]`:f(n)?`{ ${Object.entries(n).map(([r,s])=>`${JSON.stringify(r)}: ${A(s)}`).join("; ")} }`:"never"}function C(n,r){switch(r){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 f(n);default:return!1}}function $(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(r=>typeof r=="string"):[]}function F(n,r){switch(r){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let s=n.prefixItems,e=Array.isArray(s),t=e?s.filter(f):[];if(e&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(d).join(", ")}]`;let o=f(n.items)?d(n.items):"unknown";return t.length===0?`Array<${o}>`:`[${[...t.map(i=>`${d(i)}?`),`...Array<${o}>`].join(", ")}]`}case"object":{let s=f(n.properties)?n.properties:{},e=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(s).filter(u=>f(u[1])),o=new Set(t.map(([u])=>u)),a=[...e].filter(u=>!o.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let i=t.map(([u,m])=>`${JSON.stringify(u)}${e.has(u)?"":"?"}: ${d(m)}`);i.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${i.join("; ")} }`;return n.additionalProperties===!1?i.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function d(n){let r=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(r.length){let t={...n};for(let i of r)delete t[i];let o=r.map(i=>{let c=n[i].filter(f).map(d);return c.length?c.map(u=>`(${u})`).join(i==="allOf"?" & ":" | "):"never"}),a=d(t);return a!=="unknown"&&o.unshift(a),o.map(i=>`(${i})`).join(" & ")}if(Object.hasOwn(n,"const"))return A(n.const);let s=$(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(o=>s.length===0||s.some(a=>C(o,a)));return t.length===0?"never":t.map(A).join(" | ")}let e=[...new Set(s.map(t=>F(n,t)))];return e.length===0?"unknown":e.join(" | ")}function N(n){let r=[...n].sort((t,o)=>t.functionId<o.functionId?-1:t.functionId>o.functionId?1:0),s=r.map(t=>` ${JSON.stringify(t.functionId)}: ${d(t.inputSchema)}`),e=r.flatMap(t=>{let o=Object.entries(t.parameterOptions??{});return o.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...o.map(([a,i])=>` ${JSON.stringify(a)}: ${JSON.stringify(i)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...s,"}",...e.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 = {",...e,"} as const"]:[],""].join(`
15
+ `)}var J=[1],y=class extends Error{constructor(s,e){super(e);this.code=s;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},T=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function R(n){if(!I(n)||n.contractFormatVersion!==1)throw new y("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let r=()=>{throw new y("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")&&r();let s;try{s=JSON.stringify(n)}catch{return r()}Buffer.byteLength(s)>4*1024*1024&&r();for(let t of["functions","inputs"]){let o=n[t];if(!Array.isArray(o)||o.length>1e3)return r();let a=new Set;for(let i of o){if(!I(i)||typeof i.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(i.functionId)||a.has(i.functionId))return r();a.add(i.functionId),t==="functions"&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&r(),t==="inputs"&&!I(i.inputSchema)&&r();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(i[c]!==void 0)try{g(i[c])}catch{r()}i.parameterOptions!==void 0&&(!I(i.parameterOptions)||!Object.values(i.parameterOptions).every(Array.isArray))&&r()}}let e=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!e.has(t.functionId))&&r()}async function U(n){if(R(n),n.previousAugmentation!==void 0&&![b,w,T].includes(n.previousAugmentation))throw new y("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let r=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:N(n.inputs)}];return n.client&&r.push({path:"page/src/generated/functions.ts",content:await h(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&r.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?T:b:w}),r}export{y as CodegenError,J as SUPPORTED_CONTRACT_FORMAT_VERSIONS,U as generateFunctionClients,R as validateContractData};
package/dist/testing.js CHANGED
@@ -1 +1 @@
1
- import{Host as me,ChannelCallbackError as P}from"@lark-base-open/base-site-channel";import{SiteRuntimeApi as s,SiteRuntimeEvent as C,SiteRuntimeFunction as D,isValidSiteFunctionName as he}from"@lark-base-open/base-site-channel/runtime-contract";import{ChannelCallbackError as K}from"@lark-base-open/base-site-channel";import{SiteRuntimeErrorCode as g}from"@lark-base-open/base-site-channel/runtime-contract";var X=3e4,Z=6e4,Y=4;var J=32,Q=127,ee=new Set(["DELETE","GET","PATCH","POST","PUT"]),te=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","transfer-encoding"]);var ne=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,E=(e,n)=>{throw new K(e,n)},oe=e=>{let n=e;for(let r=0;r<Y;r+=1){let a;try{a=decodeURIComponent(n)}catch{return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u7F16\u7801\u65E0\u6548")}if(a===n)return n;n=a}return n},B=(e,n)=>{if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//"))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u5FC5\u987B\u4EE5\u5355\u4E2A / \u5F00\u5934");if(e.includes("\\")||e.includes("#"))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u5305\u542B\u975E\u6CD5\u5B57\u7B26");let r=oe(e),a=r.split("?")[0]??"";if(r.startsWith("//")||r.includes("\\")||Array.from(r).some(f=>{let m=f.charCodeAt(0);return m<J||m===Q})||a.split("/").some(f=>f===".."))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u4E0D\u5141\u8BB8\u8DE8\u76EE\u5F55\u6216\u8DE8\u57DF");let c=new URL(e,n);return c.origin!==n?E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u4E0D\u5141\u8BB8\u8DE8\u57DF"):`${c.pathname}${c.search}`},ie=e=>{if(e===void 0)return{};if(e===null||typeof e!="object"||Array.isArray(e))return E(g.InvalidHttpHeader,"\u8BF7\u6C42\u5934\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u952E\u503C\u5BF9\u8C61");let n={};for(let[r,a]of Object.entries(e)){let c=r.toLowerCase();if(typeof a!="string"||!ne.test(r)||te.has(c)||c.startsWith("sec-")||c.startsWith("x-forwarded-")||c.startsWith("rpc-"))return E(g.InvalidHttpHeader,`\u8BF7\u6C42\u5934 ${r} \u4E0D\u5141\u8BB8\u900F\u4F20`);n[r]=a}return n},F=e=>{let n=e?.method?.toUpperCase()??"GET";if(!ee.has(n))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u65B9\u6CD5\u4E0D\u53D7\u652F\u6301");if(e?.body!==void 0&&typeof e.body!="string")return E(g.UnsupportedHttpBody,"\u8BF7\u6C42\u4F53\u4EC5\u652F\u6301\u5B57\u7B26\u4E32");if((n==="GET"||n==="HEAD")&&e?.body!==void 0)return E(g.UnsupportedHttpBody,"GET \u8BF7\u6C42\u4E0D\u652F\u6301\u8BF7\u6C42\u4F53");let r=e?.timeoutMs??X;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8D85\u65F6\u65F6\u95F4\u65E0\u6548");let a=Math.min(Math.max(r,1),Z);return{body:e?.body,credentials:"same-origin",headers:ie(e?.headers),method:n,timeoutMs:a}};var re=/^:[A-Za-z][A-Za-z0-9_]*$/;var v={routes:[{method:"GET",path:"/space/api/box/stream/download/v2/cover/:fileToken"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/invoke_get"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/functions/:key/invoke"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/functions/:key/tasks/:taskId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/invoke_function/:functionId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/ai_functions/:functionKey/tasks"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/ai_functions/:functionKey/tasks/:taskId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_create"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_update"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_delete"},{method:"POST",path:"/space/api/box/file/temporary_download_url"},{method:"POST",path:"/space/api/mention/recommend.v2"},{method:"GET",path:"/space/api/user"},{method:"POST",path:"/space/api/bitable/chatbot/chat"},{method:"GET",path:"/space/api/bitable/chatbot/poll"},{method:"POST",path:"/space/api/bitable/chatbot/:chatbotId/history/list"},{method:"POST",path:"/space/api/bitable/chatbot/chatbot_session/reset"},{method:"GET",path:"/space/api/bitable/chatbot/:chatbotId/run_log/session"},{method:"POST",path:"/space/api/bitable/chatbot/:chatbotId/run_log/stop"}]},q=e=>e.length>1&&e.endsWith("/")?e.slice(0,-1):e;var se=(e,n)=>{let r=q(e).split("/"),a=q(n).split("/");return r.length===a.length&&a.every((c,f)=>{let m=r[f];return re.test(c)?!!m:c===m})},z=(e,n,r)=>{let a=e.split("?")[0]??"";return r.some(c=>c.method===n&&se(a,c.path))};import{ChannelCallbackError as j}from"@lark-base-open/base-site-channel";import{SiteRuntimeErrorCode as ae}from"@lark-base-open/base-site-channel/runtime-contract";var G="/space/api/box/stream/download/v2/cover/",ce="/space/api/box/file/temporary_download_url",le=new Set(["120","360","720","1280"]),de=/^[A-Za-z0-9_-]{1,256}$/,w=e=>typeof e=="string"&&de.test(e),y=()=>{throw new j(ae.InvalidAttachmentTarget,"\u9644\u4EF6\u76EE\u6807\u4E0D\u5C5E\u4E8E\u5F53\u524D Site \u6216\u9644\u4EF6\u5750\u6807\u65E0\u6548")},$=(e,n,r)=>{let a=e.pathname.startsWith(G),c=e.pathname.replace(/\/+$/,"")===ce;if(!a&&!c)return()=>{};try{let f=c&&typeof r?.body=="string"?JSON.parse(r.body):void 0,m=a?e.pathname.slice(G.length):f?.file_token;if(a&&(e.searchParams.getAll("extra").length!==1||!["width","height"].every(o=>e.searchParams.getAll(o).length===1&&le.has(e.searchParams.get(o)??""))))return y();let R=JSON.parse(a?e.searchParams.get("extra")??"null":f?.extra??"null"),p=R?.bitablePerm;if(!n||!w(m)||!w(p?.tableId))return y();let _=Object.entries(p.attachments??{});if(_.length!==1||!w(_[0][0]))return y();let A=Object.entries(_[0][1]);if(A.length!==1||!w(A[0][0]))return y();let k=A[0][1];if(!Array.isArray(k)||k.length!==1||k[0]!==m)return y();let I=n.getSiteToken(),H=n.getSiteEnv?.()??"prod";if(!I||p.siteToken!==void 0&&p.baseAppToken!==void 0||(p.siteToken??p.baseAppToken)!==I||p.siteEnv!==void 0&&p.siteEnv!==H||c&&(r?.method!=="POST"||e.searchParams.has("extra"))||Object.keys(R).some(o=>o!=="bitablePerm"))return y();let O=JSON.stringify({bitablePerm:{tableId:p.tableId,attachments:p.attachments,siteToken:I,siteEnv:H}});a?e.searchParams.set("extra",O):r&&(r.body=JSON.stringify({file_token:m,extra:O}));let t=()=>{(I!==n.getSiteToken()||H!==(n.getSiteEnv?.()??"prod")||!n.isBoundTable(p.tableId))&&y()};return t(),t}catch(f){if(f instanceof j)throw f;return y()}};import{http as pe,HttpResponse as ue}from"msw";function fe(e){return e.map(n=>pe[n.method??"get"](n.url,()=>ue.json(n.body??null,{status:n.status??200,headers:n.headers})))}var u=(e,n=e)=>{throw new P(e,n)},Te=new Set(["cache-control","content-language","content-type","etag","last-modified","x-request-id","x-tt-logid","x-tt-trace-id"]);function Oe(e={}){let n={protocolVersion:"site.v1",colorScheme:"light",locale:"zh-CN",mode:"reading",env:"preview",siteToken:"mock-site",...e.context,...e.capabilities===void 0?{}:{capabilities:e.capabilities}},r=e.origin??"https://host.example",a=[],c=[],f=new Map,m=new Map,R=new Set,p=new Set,_=!1,A=0,k=async(t,o)=>{_||(c.push({event:t,payload:o}),await Promise.all([...[...f.get(t)??[]].map(l=>l(o)),...[...p].map(l=>l.emitEvent(t,o))]))},I=(t,o)=>(e.bindings??[]).some(l=>l.baseToken===t&&l.tableIds.includes(o)),H=async(t,o)=>{if(_&&u("CHANNEL_DESTROYED"),Object.values(s).includes(t)||u("10004"),a.push({api:t,params:o}),t!==s.RuntimeContext&&n.capabilities!==void 0){let h={[s.HttpRequestCancel]:"http.cancel",[s.AttachmentUploadCancel]:"attachment.cancel",[s.StreamOpen]:"chatbot.stream",[s.StreamClose]:"chatbot.stream",[s.AIFunctionStreamOpen]:"ai.function.stream",[s.AIFunctionStreamClose]:"ai.function.stream"}[t]??t.replace("site.v1.",""),d=Object.prototype.hasOwnProperty.call(n.capabilities,h)?n.capabilities[h]?.version:void 0;(!Number.isInteger(d)||(d??0)<1)&&u("10004")}let l,T=()=>{},b,S;if(t===s.RuntimeContext)l=structuredClone(n);else if(t===s.OpenLink){let i;try{if(typeof o?.url!="string"||!o.url.trim())throw 0;i=new URL(o.url)}catch{return u("INVALID_LINK_URL")}["http:","https:","mailto:","tel:"].includes(i.protocol)||u("INVALID_LINK_URL"),["http:","https:"].includes(i.protocol)&&e.secureLinkAvailable===!1&&u("LINK_CHECK_UNAVAILABLE"),l={opened:!0}}else if(t===s.HttpRequest){(!o||typeof o!="object")&&u("INVALID_HTTP_URL");let i=o,h=B(i.url,r);S=F(i.init),z(h,S.method??"GET",e.allowedRoutes??v.routes)||u("INVALID_HTTP_URL"),["text","arrayBuffer"].includes(i.init?.responseType??"text")||u("HTTP_RESPONSE_TYPE_UNSUPPORTED");let d=i.requestId??`legacy-${++A}`;(typeof d!="string"||!d||d.length>256||m.has(`http:${d}`))&&u("HTTP_REQUEST_FAILED"),b=`http:${d}`,T=$(new URL(h,r),{getSiteToken:()=>n.siteToken,getSiteEnv:()=>n.env??"prod",isBoundTable:U=>(e.bindings??[]).some(V=>V.tableIds.includes(U))},S),l={body:i.init?.responseType==="arrayBuffer"?new ArrayBuffer(0):"{}",...i.init?.responseType==="arrayBuffer"?{bodyType:"arrayBuffer"}:{},headers:{},status:200,statusText:"OK"}}else if(t===s.AttachmentUpload){let i=o,h=typeof i?.baseToken=="string"?i.baseToken.trim():"",d=typeof i?.tableId=="string"?i.tableId.trim():"";(!h||!d||typeof File>"u"||!(i.file instanceof File)||i.file.size<=0||i.file.size>2*1024*1024*1024||!I(h,d))&&u("INVALID_ATTACHMENT_TARGET"),n.siteToken?.trim()||u("ATTACHMENT_UPLOAD_FAILED"),b=`upload:${i.uploadId??++A}`,l={fileToken:"mock-file",name:i.file.name,size:i.file.size,mimeType:i.file.type}}else if(t===s.HttpRequestCancel||t===s.AttachmentUploadCancel){let i=t===s.HttpRequestCancel?`http:${o?.requestId}`:`upload:${o?.uploadId}`,h=m.get(i);h?.controller.abort(),h?.reject(new P(t===s.HttpRequestCancel?"HTTP_REQUEST_CANCELED":"ATTACHMENT_UPLOAD_CANCELED","\u6D4B\u8BD5\u8C03\u7528\u5DF2\u53D6\u6D88"))}else if(t===s.FunctionInvoke){let i=o?.functionName;(typeof i!="string"||!he(i))&&u("INVALID_FUNCTION_NAME"),i===D.GetCurrentUser?l={name:"\u6D4B\u8BD5\u7528\u6237",avatarUrl:""}:[D.Logout,D.RequestEdit].includes(i)||(!e.functions||!Object.prototype.hasOwnProperty.call(e.functions,i))&&u("FUNCTION_NOT_ALLOWED")}else t===s.AIFunctionStreamOpen||t===s.StreamOpen?(o?.subscriptionId||u("STREAM_UNAVAILABLE"),t===s.AIFunctionStreamOpen&&(!n.siteToken||!o.functionKey)&&u("STREAM_UNAVAILABLE")):(t===s.AIFunctionStreamClose||t===s.StreamClose)&&R.delete(o?.subscriptionId);let L=e.failures?.[t];L&&u(L.code,L.message);let x=new AbortController,M,N=()=>{},W=new Promise((i,h)=>{N=h});b??=`call:${++A}`,m.set(b,{controller:x,reject:N}),S&&(M=setTimeout(()=>{x.abort(),N(new P("REQUEST_TIMEOUT","HTTP \u8BF7\u6C42\u8D85\u65F6"))},S.timeoutMs));try{T();let i=e.handlers?.[t],h=t===s.FunctionInvoke?e.functions?.[o.functionName]:void 0,d=await Promise.race([Promise.resolve().then(()=>i?i(o,{signal:x.signal,emit:k}):h?h(o.params):l),W]);return T(),(t===s.AIFunctionStreamOpen||t===s.StreamOpen)&&R.add(o.subscriptionId),t===s.HttpRequest&&d&&typeof d=="object"&&"headers"in d?{...d,headers:Object.fromEntries(Object.entries(d.headers).filter(([U])=>Te.has(U.toLowerCase())))}:d}finally{clearTimeout(M),b&&m.delete(b)}};return{channel:{invokeApi:H,emitEvent:async(t,o)=>{c.push({event:t,payload:o})},subscribeEvent:(t,o)=>{let l=f.get(t)??new Set;return l.add(o),f.set(t,l),()=>{l.delete(o)}}},context:n,calls:a,events:c,emit:k,mount(t,o,l=new URL(o).origin){let T=new me(t,()=>{},`mock-${++A}`,[l],{sandbox:"allow-scripts allow-same-origin allow-downloads"},{enableBinaryFetch:!1});for(let b of Object.values(s))T.registerApi(b,S=>H(b,S));for(let b of[C.LifecycleReady,C.LifecycleLoadFailed])T.subscribeEvent(b,S=>{c.push({event:b,payload:S})});return p.add(T),T.setClientUrl(o),()=>{T.destroy(),p.delete(T)}},emitStreamMessage(t,o,l,T=!1){return R.has(t)?k(T?C.AIFunctionStreamMessage:C.StreamMessage,{subscriptionId:t,data:o,seq:l}):Promise.resolve()},dispose(){_=!0;for(let t of m.values())t.controller.abort(),t.reject(new P("CHANNEL_DESTROYED","\u6D4B\u8BD5\u5BBF\u4E3B\u5DF2\u9500\u6BC1"));m.clear(),f.clear(),R.clear();for(let t of p)t.destroy();p.clear()}}}export{v as DEFAULT_SITE_HTTP_BRIDGE_ALLOWLIST,fe as createHttpHandlers,Oe as createMockHost};
1
+ import{Host as me,ChannelCallbackError as P}from"@lark-base-open/base-site-channel";import{SiteRuntimeApi as s,SiteRuntimeEvent as C,SiteRuntimeFunction as M,isValidSiteFunctionName as he}from"@lark-base-open/base-site-channel/runtime-contract";import{ChannelCallbackError as K}from"@lark-base-open/base-site-channel";import{SiteRuntimeErrorCode as g}from"@lark-base-open/base-site-channel/runtime-contract";var Z=3e4,J=6e4,Y=4,Q=32,X=127,ee=new Set(["DELETE","GET","PATCH","POST","PUT"]),te=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","transfer-encoding"]),ne=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,E=(e,n)=>{throw new K(e,n)},oe=e=>{let n=e;for(let r=0;r<Y;r+=1){let a;try{a=decodeURIComponent(n)}catch{return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u7F16\u7801\u65E0\u6548")}if(a===n)return n;n=a}return n},B=(e,n)=>{if(typeof e!="string"||!e.startsWith("/")||e.startsWith("//"))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u5FC5\u987B\u4EE5\u5355\u4E2A / \u5F00\u5934");if(e.includes("\\")||e.includes("#"))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u5305\u542B\u975E\u6CD5\u5B57\u7B26");let r=oe(e),a=r.split("?")[0]??"";if(r.startsWith("//")||r.includes("\\")||Array.from(r).some(f=>{let m=f.charCodeAt(0);return m<Q||m===X})||a.split("/").some(f=>f===".."))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u4E0D\u5141\u8BB8\u8DE8\u76EE\u5F55\u6216\u8DE8\u57DF");let c=new URL(e,n);return c.origin!==n?E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8DEF\u5F84\u4E0D\u5141\u8BB8\u8DE8\u57DF"):`${c.pathname}${c.search}`},ie=e=>{if(e===void 0)return{};if(e===null||typeof e!="object"||Array.isArray(e))return E(g.InvalidHttpHeader,"\u8BF7\u6C42\u5934\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u952E\u503C\u5BF9\u8C61");let n={};for(let[r,a]of Object.entries(e)){let c=r.toLowerCase();if(typeof a!="string"||!ne.test(r)||te.has(c)||c.startsWith("sec-")||c.startsWith("x-forwarded-")||c.startsWith("rpc-"))return E(g.InvalidHttpHeader,`\u8BF7\u6C42\u5934 ${r} \u4E0D\u5141\u8BB8\u900F\u4F20`);n[r]=a}return n},F=e=>{let n=e?.method?.toUpperCase()??"GET";if(!ee.has(n))return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u65B9\u6CD5\u4E0D\u53D7\u652F\u6301");if(e?.body!==void 0&&typeof e.body!="string")return E(g.UnsupportedHttpBody,"\u8BF7\u6C42\u4F53\u4EC5\u652F\u6301\u5B57\u7B26\u4E32");if((n==="GET"||n==="HEAD")&&e?.body!==void 0)return E(g.UnsupportedHttpBody,"GET \u8BF7\u6C42\u4E0D\u652F\u6301\u8BF7\u6C42\u4F53");let r=e?.timeoutMs??Z;if(typeof r!="number"||!Number.isFinite(r)||r<=0)return E(g.InvalidHttpUrl,"\u8BF7\u6C42\u8D85\u65F6\u65F6\u95F4\u65E0\u6548");let a=Math.min(Math.max(r,1),J);return{body:e?.body,credentials:"same-origin",headers:ie(e?.headers),method:n,timeoutMs:a}};var re=/^:[A-Za-z][A-Za-z0-9_]*$/;var N={routes:[{method:"GET",path:"/space/api/box/stream/download/v2/cover/:fileToken"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/invoke_get"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/functions/:key/invoke"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/functions/:key/tasks/:taskId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/invoke_function/:functionId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/ai_functions/:functionKey/tasks"},{method:"GET",path:"/space/api/bitable/site/v1/:siteToken/ai_functions/:functionKey/tasks/:taskId"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_create"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_update"},{method:"POST",path:"/space/api/bitable/site/v1/:siteToken/bases/:baseToken/tables/:tableId/records/batch_delete"},{method:"POST",path:"/space/api/box/file/temporary_download_url"},{method:"POST",path:"/space/api/mention/recommend.v2"},{method:"GET",path:"/space/api/user"},{method:"POST",path:"/space/api/bitable/chatbot/chat"},{method:"GET",path:"/space/api/bitable/chatbot/poll"},{method:"POST",path:"/space/api/bitable/chatbot/:chatbotId/history/list"},{method:"POST",path:"/space/api/bitable/chatbot/chatbot_session/reset"},{method:"GET",path:"/space/api/bitable/chatbot/:chatbotId/run_log/session"},{method:"POST",path:"/space/api/bitable/chatbot/:chatbotId/run_log/stop"}]},z=e=>e.length>1&&e.endsWith("/")?e.slice(0,-1):e;var se=(e,n)=>{let r=z(e).split("/"),a=z(n).split("/");return r.length===a.length&&a.every((c,f)=>{let m=r[f];return re.test(c)?!!m:c===m})},G=(e,n,r)=>{let a=e.split("?")[0]??"";return r.some(c=>c.method===n&&se(a,c.path))};import{ChannelCallbackError as j}from"@lark-base-open/base-site-channel";import{SiteRuntimeErrorCode as ae}from"@lark-base-open/base-site-channel/runtime-contract";var q="/space/api/box/stream/download/v2/cover/",ce="/space/api/box/file/temporary_download_url",le=new Set(["120","360","720","1280"]),de=/^[A-Za-z0-9_-]{1,256}$/,w=e=>typeof e=="string"&&de.test(e),y=()=>{throw new j(ae.InvalidAttachmentTarget,"\u9644\u4EF6\u76EE\u6807\u4E0D\u5C5E\u4E8E\u5F53\u524D Site \u6216\u9644\u4EF6\u5750\u6807\u65E0\u6548")},$=(e,n,r)=>{let a=e.pathname.startsWith(q),c=e.pathname.replace(/\/+$/,"")===ce;if(!a&&!c)return()=>{};try{let f=c&&typeof r?.body=="string"?JSON.parse(r.body):void 0,m=a?e.pathname.slice(q.length):f?.file_token;if(a&&(e.searchParams.getAll("extra").length!==1||!["width","height"].every(o=>e.searchParams.getAll(o).length===1&&le.has(e.searchParams.get(o)??""))))return y();let k=JSON.parse(a?e.searchParams.get("extra")??"null":f?.extra??"null"),p=k?.bitablePerm;if(!n||!w(m)||!w(p?.tableId))return y();let R=Object.entries(p.attachments??{});if(R.length!==1||!w(R[0][0]))return y();let S=Object.entries(R[0][1]);if(S.length!==1||!w(S[0][0]))return y();let _=S[0][1];if(!Array.isArray(_)||_.length!==1||_[0]!==m)return y();let I=n.getSiteToken(),H=n.getSiteEnv?.()??"prod";if(!I||p.siteToken!==void 0&&p.baseAppToken!==void 0||(p.siteToken??p.baseAppToken)!==I||p.siteEnv!==void 0&&p.siteEnv!==H||c&&(r?.method!=="POST"||e.searchParams.has("extra"))||Object.keys(k).some(o=>o!=="bitablePerm"))return y();let O=JSON.stringify({bitablePerm:{tableId:p.tableId,attachments:p.attachments,siteToken:I,siteEnv:H}});a?e.searchParams.set("extra",O):r&&(r.body=JSON.stringify({file_token:m,extra:O}));let t=()=>{(I!==n.getSiteToken()||H!==(n.getSiteEnv?.()??"prod")||!n.isBoundTable(p.tableId))&&y()};return t(),t}catch(f){if(f instanceof j)throw f;return y()}};import{http as pe,HttpResponse as ue}from"msw";function fe(e){return e.map(n=>pe[n.method??"get"](n.url,()=>ue.json(n.body??null,{status:n.status??200,headers:n.headers})))}var u=(e,n=e)=>{throw new P(e,n)},Te=new Set(["cache-control","content-language","content-type","etag","last-modified","x-request-id","x-tt-logid","x-tt-trace-id"]);function Oe(e={}){let n={protocolVersion:"site.v1",colorScheme:"light",locale:"zh-CN",mode:"reading",env:"preview",siteToken:"mock-site",...e.context,...e.capabilities===void 0?{}:{capabilities:e.capabilities}},r=e.origin??"https://host.example",a=[],c=[],f=new Map,m=new Map,k=new Set,p=new Set,R=!1,S=0,_=async(t,o)=>{R||(c.push({event:t,payload:o}),await Promise.all([...[...f.get(t)??[]].map(l=>l(o)),...[...p].map(l=>l.emitEvent(t,o))]))},I=(t,o)=>(e.bindings??[]).some(l=>l.baseToken===t&&l.tableIds.includes(o)),H=async(t,o)=>{if(R&&u("CHANNEL_DESTROYED"),Object.values(s).includes(t)||u("10004"),a.push({api:t,params:o}),t!==s.RuntimeContext&&n.capabilities!==void 0){let h={[s.HttpRequestCancel]:"http.cancel",[s.AttachmentUploadCancel]:"attachment.cancel",[s.StreamOpen]:"chatbot.stream",[s.StreamClose]:"chatbot.stream",[s.AIFunctionStreamOpen]:"ai.function.stream",[s.AIFunctionStreamClose]:"ai.function.stream"}[t]??t.replace("site.v1.",""),d=Object.prototype.hasOwnProperty.call(n.capabilities,h)?n.capabilities[h]?.version:void 0;(!Number.isInteger(d)||(d??0)<1)&&u("10004")}let l,T=()=>{},b,A;if(t===s.RuntimeContext)l=structuredClone(n);else if(t===s.OpenLink){let i;try{if(typeof o?.url!="string"||!o.url.trim())throw 0;i=new URL(o.url)}catch{return u("INVALID_LINK_URL")}["http:","https:","mailto:","tel:"].includes(i.protocol)||u("INVALID_LINK_URL"),["http:","https:"].includes(i.protocol)&&e.secureLinkAvailable===!1&&u("LINK_CHECK_UNAVAILABLE"),l={opened:!0}}else if(t===s.HttpRequest){(!o||typeof o!="object")&&u("INVALID_HTTP_URL");let i=o,h=B(i.url,r);A=F(i.init),G(h,A.method??"GET",e.allowedRoutes??N.routes)||u("INVALID_HTTP_URL"),["text","arrayBuffer"].includes(i.init?.responseType??"text")||u("HTTP_RESPONSE_TYPE_UNSUPPORTED");let d=i.requestId??`legacy-${++S}`;(typeof d!="string"||!d||d.length>256||m.has(`http:${d}`))&&u("HTTP_REQUEST_FAILED"),b=`http:${d}`,T=$(new URL(h,r),{getSiteToken:()=>n.siteToken,getSiteEnv:()=>n.env??"prod",isBoundTable:U=>(e.bindings??[]).some(V=>V.tableIds.includes(U))},A),l={body:i.init?.responseType==="arrayBuffer"?new ArrayBuffer(0):"{}",...i.init?.responseType==="arrayBuffer"?{bodyType:"arrayBuffer"}:{},headers:{},status:200,statusText:"OK"}}else if(t===s.AttachmentUpload){let i=o,h=typeof i?.baseToken=="string"?i.baseToken.trim():"",d=typeof i?.tableId=="string"?i.tableId.trim():"";(!h||!d||typeof File>"u"||!(i.file instanceof File)||i.file.size<=0||i.file.size>2*1024*1024*1024||!I(h,d))&&u("INVALID_ATTACHMENT_TARGET"),n.siteToken?.trim()||u("ATTACHMENT_UPLOAD_FAILED"),b=`upload:${i.uploadId??++S}`,l={fileToken:"mock-file",name:i.file.name,size:i.file.size,mimeType:i.file.type}}else if(t===s.HttpRequestCancel||t===s.AttachmentUploadCancel){let i=t===s.HttpRequestCancel?`http:${o?.requestId}`:`upload:${o?.uploadId}`,h=m.get(i);h?.controller.abort(),h?.reject(new P(t===s.HttpRequestCancel?"HTTP_REQUEST_CANCELED":"ATTACHMENT_UPLOAD_CANCELED","\u6D4B\u8BD5\u8C03\u7528\u5DF2\u53D6\u6D88"))}else if(t===s.FunctionInvoke){let i=o?.functionName;(typeof i!="string"||!he(i))&&u("INVALID_FUNCTION_NAME"),i===M.GetCurrentUser?l={name:"\u6D4B\u8BD5\u7528\u6237",avatarUrl:""}:[M.Logout,M.RequestEdit].includes(i)||(!e.functions||!Object.prototype.hasOwnProperty.call(e.functions,i))&&u("FUNCTION_NOT_ALLOWED")}else t===s.AIFunctionStreamOpen||t===s.StreamOpen?(o?.subscriptionId||u("STREAM_UNAVAILABLE"),t===s.AIFunctionStreamOpen&&(!n.siteToken||!o.functionKey)&&u("STREAM_UNAVAILABLE")):(t===s.AIFunctionStreamClose||t===s.StreamClose)&&k.delete(o?.subscriptionId);let L=e.failures?.[t];L&&u(L.code,L.message);let x=new AbortController,D,v=()=>{},W=new Promise((i,h)=>{v=h});b??=`call:${++S}`,m.set(b,{controller:x,reject:v}),A&&(D=setTimeout(()=>{x.abort(),v(new P("REQUEST_TIMEOUT","HTTP \u8BF7\u6C42\u8D85\u65F6"))},A.timeoutMs));try{T();let i=e.handlers?.[t],h=t===s.FunctionInvoke?e.functions?.[o.functionName]:void 0,d=await Promise.race([Promise.resolve().then(()=>i?i(o,{signal:x.signal,emit:_}):h?h(o.params):l),W]);return T(),(t===s.AIFunctionStreamOpen||t===s.StreamOpen)&&k.add(o.subscriptionId),t===s.HttpRequest&&d&&typeof d=="object"&&"headers"in d?{...d,headers:Object.fromEntries(Object.entries(d.headers).filter(([U])=>Te.has(U.toLowerCase())))}:d}finally{clearTimeout(D),b&&m.delete(b)}};return{channel:{invokeApi:H,emitEvent:async(t,o)=>{c.push({event:t,payload:o})},subscribeEvent:(t,o)=>{let l=f.get(t)??new Set;return l.add(o),f.set(t,l),()=>{l.delete(o)}}},context:n,calls:a,events:c,emit:_,mount(t,o,l=new URL(o).origin){let T=new me(t,()=>{},`mock-${++S}`,[l],{sandbox:"allow-scripts allow-same-origin allow-downloads"},{enableBinaryFetch:!1});for(let b of Object.values(s))T.registerApi(b,A=>H(b,A));for(let b of[C.LifecycleReady,C.LifecycleLoadFailed])T.subscribeEvent(b,A=>{c.push({event:b,payload:A})});return p.add(T),T.setClientUrl(o),()=>{T.destroy(),p.delete(T)}},emitStreamMessage(t,o,l,T=!1){return k.has(t)?_(T?C.AIFunctionStreamMessage:C.StreamMessage,{subscriptionId:t,data:o,seq:l}):Promise.resolve()},dispose(){R=!0;for(let t of m.values())t.controller.abort(),t.reject(new P("CHANNEL_DESTROYED","\u6D4B\u8BD5\u5BBF\u4E3B\u5DF2\u9500\u6BC1"));m.clear(),f.clear(),k.clear();for(let t of p)t.destroy();p.clear()}}}export{N as DEFAULT_SITE_HTTP_BRIDGE_ALLOWLIST,fe as createHttpHandlers,Oe as createMockHost};
package/docs/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  - [start-base-app:启动、清理与 Vite 开发插件](start-base-app.md)
11
11
  - [capabilities:能力协商与诊断](capabilities.md)
12
12
  - [compat:老模板兼容](compat.md)
13
- - [upgrade:codemod 与模板 1→2 迁移](upgrade.md)
13
+ - [upgrade:工程迁移与 SDK 升级](upgrade.md)
14
14
  - [可编译示例](../examples)
15
15
 
16
16
  SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务规则、服务端契约、Mutation 结果、CLI 命令与发布流程,请查阅 [@lark-base-open/base-database-cli](https://www.npmjs.com/package/@lark-base-open/base-database-cli) 随包安装的 lark-base-database Skill 及其 references。升级 CLI 时以该版本随包 Skill 为准。
package/docs/codegen.md CHANGED
@@ -14,7 +14,7 @@ const data: FunctionContractData = {
14
14
  client: true,
15
15
  augmentation: 'none',
16
16
  };
17
- const files = await generateFunctionClients(data);
17
+ export const files = await generateFunctionClients(data);
18
18
  // [{path:'page/src/generated/function-inputs.ts',content:...},
19
19
  // {path:'page/src/generated/functions.ts',content:...}]
20
20
  ```
package/docs/upgrade.md CHANGED
@@ -1,44 +1,5 @@
1
- # 迁移到 SDK 0.0.1-alpha.1
1
+ # 工程迁移与 SDK 升级
2
2
 
3
- 先核对工程 AGENTS.md 中的模板版本、实际安装 SDK 和 CLI 随包 Skill。SDK 未发布期间仅在本地验收副本使用经审核 tarball;正式模板不写 file:/tarball 依赖,也不伪造 registry lock。老模板持续兼容并维护安全与事实更正,未设截止日期。
3
+ 存量 classic 的工程迁移由 coding agent 执行;步骤、输入声明与改前/改后示例统一以随 CLI 安装的建站 Skill `references/workspace-migration.md` 为准。CLI 只做配置、契约、类型和构建校验,不改写 helper 或自动搬迁工程。
4
4
 
5
- ## 老模板 database-runtime.ts → SDK(仍可保持模板 1)
6
-
7
- 1. 保存可回滚的源码和锁文件,核对 page/src/lib/database-runtime.ts 是否有业务定制。显式选择并安装 SDK 到 Page 工程,按其 peerDependencies 对齐 React/react-dom 与 TanStack Query;MSW 仅测试入口需要。codemod 不选择版本、不安装依赖。
8
- 2. 在项目根运行 `base-database-cli codemod database-runtime .` 查看默认 dry-run 的 changes/conflicts。仅受支持原模板指纹可自动迁移;定制 helper、未知引用或类型冲突须先人工审查,不覆盖定制逻辑。
9
- 3. 审查后运行 `base-database-cli codemod database-runtime . --apply`。存在冲突时不应用;检查输出 applied 和文件 diff。该操作迁移 helper 引用并适配输入类型声明,不搬目录、不升级模板版本、不迁移组件或启动入口。再次 dry-run 应无 changes。
10
- 4. 对使用 [`defineFunction`](exports.md#server) 的 FaaS,把 input/output 放独立 contract.ts,在项目根运行 `base-database-cli contracts generate .`,检查生成契约、输入扩充和页面客户端。生成失败或 runtime-only 警告须处理;Database Function 输出仍为 unknown。生成器属于 CLI,SDK 没有 createFunctionClient 导出,消费工程生成的客户端。
11
- 5. 手工检查其余 channel/runtime 导入与 [`FunctionMap`](exports.md#page) 扩充:channel 的 [`FunctionMap`](exports.md#page) 声明目标保持原样;[`DatabaseFunctionInputMap`](exports.md#page) 的新扩充目标为 SDK/page。兼容调用仍返回 envelope,HTTP 失败仍抛错,不二次解包。详见 [兼容说明](compat.md)。
12
- 6. 选择保留旧启动入口或采用 [startBaseApp](start-base-app.md)。采用后移除重复的 createRoot、guard、ready/load-failed 和默认悬浮按钮;保留业务 Provider、样式及路由。仅迁移 import 不要求更换布局。
13
- 7. 运行类型检查及 `base-database-cli check --json`;按 Skill 的验收和发布流程验证真实宿主中的链接、附件、成员选择与写入结果。验证失败时恢复源码与锁文件,不能把 mock 成功当作真实权限证明。
14
-
15
- guard 仍同步返回 cleanup,安装前异步查询能力。缺 capabilities 字段采用 host-baseline;显式空表或缺 link.open 时不拦截。只保留一处 guard;查询期间原生行为仍受 iframe sandbox 约束。测试替身只在测试中导入。
16
-
17
- ## 模板 1 → 2:手动迁移
18
-
19
- codemod 不做模板结构升级;应在独立副本逐项迁移。模板 2 当前非默认,公开 SDK 安装/根锁及远端流水线尚待发布和验收,本地构建通过不代表可远端交付。
20
-
21
- - 将 server-functions/functions 移到 server/functions;保留 Function ID、meta.json 和业务 handler,database-functions、mutations、Catalog 与应用绑定保持对应关系。移除旧布局前核对搬迁完整性,避免同时留下 server 与 server-functions。
22
- - 根 package.json 使用 private、type:module 和 workspaces:[page,server];两成员保留各自依赖声明,统一到唯一根 package-lock.json。合并依赖版本后重新生成根锁,不拼接两份旧锁,不保留成员锁或嵌套 workspace。正式锁须在依赖公开可安装后生成。
23
- - base-database.jsonc 标明 template:{name:"database-starter",version:2}。不能只改版本字段而保留旧目录;CLI 会拒绝混杂布局或锁冲突。
24
- - 根 base-app.config.ts 绑定业务 App、Provider 与启动选项;page/src/main.tsx 从 SDK/page 导入 [`startBaseApp`](exports.md#page) 并传入 options,同时加载 SDK/page/styles.css 和业务 CSS。生产入口直接导入,不依赖仅 serve 可用的 virtual:base-app。
25
- - 将复制的平台组件导入改为 SDK/page 或 SDK/components;核对 props、插槽、语言和样式覆盖,保留业务组件。平台权限仍由宿主判断。
26
- - server 源码采用 ESM,TypeScript 配置 noEmit;由 CLI build-server 做类型检查并输出兼容运行时的 CJS,不把 tsc emit 当作打包。不要手写 runtime profile 或凭据,绑定由 CLI 生成。
27
- - 再运行 contracts generate、Page 构建、build-server 和 check;依 Skill 做 Preview 与真实浏览器验收。遇到 REMOTE_TEMPLATE_2_BUILD_UNVERIFIED 保留未验收状态,不以本地成功消除警告。
28
-
29
- SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务规则、服务端契约、Mutation 结果、CLI 命令与发布流程,请查阅 [@lark-base-open/base-database-cli](https://www.npmjs.com/package/@lark-base-open/base-database-cli) 随包安装的 lark-base-database Skill 及其 references。升级 CLI 时以该版本随包 Skill 为准。
30
-
31
- 老工程参考:随 CLI 安装的 lark-base-database Skill 中的「页面」(references/legacy-development.md)、随 CLI 安装的 lark-base-database Skill 中的「AI」(references/legacy-ai-function.md)、随 CLI 安装的 lark-base-database Skill 中的「附件」(references/legacy-file-transfer.md)。命令选项与发布步骤以对应 CLI 随包 Skill 为准,此处仅标明迁移中需要调用的命令。
32
-
33
- 保留旧启动入口的最小示例(采用 [`startBaseApp`](exports.md#page) 时不要重复调用):
34
-
35
- <!-- example: upgrade.ts -->
36
- ```ts
37
- // 模板 1 可先迁移 helper 导入;切换启动入口与模板 2 是独立的手动步骤。
38
- import { installLinkGuard, siteRuntime, classifyRuntimeError } from '@lark-base-open/base-database-app-sdk/page';
39
- export function initializeRuntime() {
40
- const uninstall = installLinkGuard();
41
- void siteRuntime.ready().catch(error => console.warn(classifyRuntimeError(error)));
42
- return uninstall;
43
- }
44
- ```
5
+ 安装或升级本 SDK 前,核对已发布版本、Node 与 peerDependencies;保存源码和锁文件,保留业务扩展。按已安装版本的 [Page 启动说明](start-base-app.md) 接入应用生命周期,服务端契约按 [服务端说明](server.md) 编写。契约改变后显式运行 `base-database-cli contracts generate` 再 `base-database-cli check --json`;本地通过不代替 Preview 业务验收。
@@ -8,6 +8,6 @@ const data: FunctionContractData = {
8
8
  client: true,
9
9
  augmentation: 'none',
10
10
  };
11
- const files = await generateFunctionClients(data);
11
+ export const files = await generateFunctionClients(data);
12
12
  // [{path:'page/src/generated/function-inputs.ts',content:...},
13
13
  // {path:'page/src/generated/functions.ts',content:...}]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-app-sdk",
3
- "version": "0.0.1-alpha.1",
3
+ "version": "0.1.0",
4
4
  "description": "Base Database 页面与服务端 SDK、平台组件及测试工具",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -66,7 +66,7 @@
66
66
  "development-pairing.json"
67
67
  ],
68
68
  "scripts": {
69
- "build": "node scripts/sync-capabilities.mjs && tsup && tsup --config tsup.cjs.config.ts && cp src/page/theme.css dist/theme.css",
69
+ "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",
70
70
  "test": "node scripts/sync-capabilities.mjs --check && npm run build && node --import tsx --test test/*.test.ts && npm run test:types && npm run test:components",
71
71
  "test:types": "tsc -p tsconfig.examples.json && tsc -p tsconfig.server.json && tsc -p tsconfig.cjs.json",
72
72
  "test:browser": "node test/browser/verify.mjs && node test/browser/ui-verify.mjs",