@lark-base-open/base-database-app-sdk 0.0.0-stage → 0.0.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +6 -0
- package/README.md +42 -2
- package/capabilities.json +114 -0
- package/development-pairing.json +11 -0
- package/dist/capabilities-56e403e7.d.ts +22 -0
- package/dist/chunk-3JX3FIBG.js +1 -0
- package/dist/chunk-5XIFZ4AH.js +1 -0
- package/dist/chunk-OHPYKFCM.js +1 -0
- package/dist/chunk-ZKBZAK4L.js +1 -0
- package/dist/codegen.cjs +15 -0
- package/dist/codegen.d.cts +43 -0
- package/dist/codegen.d.ts +43 -0
- package/dist/codegen.js +15 -0
- package/dist/components.d.ts +6 -0
- package/dist/components.js +1 -0
- package/dist/index-64557073.d.ts +306 -0
- package/dist/page.d.ts +138 -0
- package/dist/page.js +1 -0
- package/dist/server.cjs +1 -0
- package/dist/server.d.cts +79 -0
- package/dist/server.d.ts +79 -0
- package/dist/server.js +1 -0
- package/dist/shared.cjs +1 -0
- package/dist/shared.d.cts +115 -0
- package/dist/shared.d.ts +115 -0
- package/dist/shared.js +1 -0
- package/dist/testing.d.ts +74 -0
- package/dist/testing.js +1 -0
- package/dist/theme.css +168 -0
- package/dist/vite.d.ts +15 -0
- package/dist/vite.js +3 -0
- package/docs/README.md +16 -0
- package/docs/capabilities.md +42 -0
- package/docs/codegen.md +28 -0
- package/docs/compat.md +36 -0
- package/docs/components.md +34 -0
- package/docs/exports.md +45 -0
- package/docs/page.md +101 -0
- package/docs/server.md +92 -0
- package/docs/shared.md +21 -0
- package/docs/start-base-app.md +47 -0
- package/docs/testing.md +57 -0
- package/docs/upgrade.md +44 -0
- package/examples/capabilities.ts +7 -0
- package/examples/codegen.ts +13 -0
- package/examples/compat.ts +21 -0
- package/examples/components.tsx +11 -0
- package/examples/contract-types.ts +41 -0
- package/examples/development-context.ts +17 -0
- package/examples/http.ts +12 -0
- package/examples/link.ts +10 -0
- package/examples/mock.ts +8 -0
- package/examples/msw.ts +5 -0
- package/examples/page.ts +6 -0
- package/examples/server.ts +57 -0
- package/examples/shared.ts +10 -0
- package/examples/start-base-app.tsx +8 -0
- package/examples/upgrade.ts +7 -0
- package/examples/upload.ts +18 -0
- package/examples/vite.ts +2 -0
- package/package.json +119 -4
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import React__default, { KeyboardEventHandler, MouseEventHandler, FocusEventHandler, ComponentType } from 'react';
|
|
3
|
+
import * as channelRuntime from '@lark-base-open/base-site-channel/runtime';
|
|
4
|
+
import { FunctionMap, RuntimeChannel, SiteProjectEnv } from '@lark-base-open/base-site-channel/runtime';
|
|
5
|
+
import { S as SiteRuntimeContext } from './capabilities-56e403e7.js';
|
|
6
|
+
import { RuntimeDiagnostic } from './shared.js';
|
|
7
|
+
|
|
8
|
+
declare class SiteRuntimeClient<Map = FunctionMap> extends channelRuntime.SiteRuntimeClient<Map> {
|
|
9
|
+
constructor(channel?: RuntimeChannel);
|
|
10
|
+
}
|
|
11
|
+
declare const createSiteRuntimeClient: <Map = FunctionMap>(channel?: RuntimeChannel) => SiteRuntimeClient<Map>;
|
|
12
|
+
declare const siteRuntime: {
|
|
13
|
+
getRuntimeContext(): Promise<SiteRuntimeContext>;
|
|
14
|
+
} & typeof channelRuntime.siteRuntime;
|
|
15
|
+
declare const invokeHttp: (request: channelRuntime.SiteHttpRequestOptions) => Promise<Response>;
|
|
16
|
+
declare const invokeApi: <Name extends never>(functionName: Name, params: channelRuntime.FunctionMap[Name] extends channelRuntime.SiteFunctionDefinition<infer Params, unknown> ? Params : never) => Promise<channelRuntime.FunctionMap[Name] extends channelRuntime.SiteFunctionDefinition<unknown, infer Result> ? Result : never>;
|
|
17
|
+
declare const getCurrentUser: () => Promise<channelRuntime.SiteRuntimeUserInfo>;
|
|
18
|
+
declare const logout: () => Promise<void>;
|
|
19
|
+
declare const requestEdit: () => Promise<void>;
|
|
20
|
+
declare const uploadAttachment: ({ onProgress, ...request }: channelRuntime.SiteAttachmentUploadOptions) => Promise<channelRuntime.SiteAttachmentUploadResult>;
|
|
21
|
+
declare const openLink: (url: string) => Promise<channelRuntime.SiteOpenLinkResult>;
|
|
22
|
+
declare const createSiteRuntimeFetch: typeof channelRuntime.createSiteRuntimeFetch;
|
|
23
|
+
declare const fetch: typeof globalThis.fetch;
|
|
24
|
+
|
|
25
|
+
/** 工程生成代码通过 page 模块扩充,未生成时拒绝任意函数名。 */
|
|
26
|
+
interface DatabaseFunctionInputMap extends FunctionInputMap {
|
|
27
|
+
}
|
|
28
|
+
interface FunctionInputMap {
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 应用产物在 BaseApp 页面 iframe 中的运行上下文。 */
|
|
32
|
+
interface DatabaseContext {
|
|
33
|
+
env: DatabaseEnv;
|
|
34
|
+
gatewayOrigin: string;
|
|
35
|
+
token: string;
|
|
36
|
+
}
|
|
37
|
+
/** 附件在底表里的位置。四个值都来自 catalog.json 与 Database Function 结果。 */
|
|
38
|
+
interface DatabaseAttachmentRef {
|
|
39
|
+
tableId: string;
|
|
40
|
+
fieldId: string;
|
|
41
|
+
recordId: string;
|
|
42
|
+
fileToken: string;
|
|
43
|
+
}
|
|
44
|
+
/** 产物环境沿用 site.v1 协议的规范类型,避免两侧各自声明后漂移。 */
|
|
45
|
+
type DatabaseEnv = SiteProjectEnv;
|
|
46
|
+
/** Function 调用的统一响应包裹结构,与运行态接口一致。 */
|
|
47
|
+
interface DatabaseFunctionResponse<Data = unknown> {
|
|
48
|
+
code: number;
|
|
49
|
+
data?: Data;
|
|
50
|
+
msg?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 从产物托管路径推断当前应用 token 与运行环境。
|
|
54
|
+
*
|
|
55
|
+
* 这是宿主未下发上下文时的兜底:BaseApp 形态下 site 与 BaseApp 共用同一个 token,
|
|
56
|
+
* 线上产物挂在 /app/{token}/、预览产物挂在 /preview/app/{token}/。
|
|
57
|
+
* 该推断依赖部署侧的 CDN 路径约定,优先级低于宿主下发值。
|
|
58
|
+
*
|
|
59
|
+
* @returns 应用 token、运行环境与业务网关 origin;无法推断的值为空字符串。
|
|
60
|
+
*/
|
|
61
|
+
declare function getDatabaseContext(): DatabaseContext;
|
|
62
|
+
/** 解析当前应用上下文,宿主下发值优先、产物路径推断兜底。
|
|
63
|
+
*
|
|
64
|
+
* 结果按会话缓存;解析失败时清空缓存,允许后续调用重试。
|
|
65
|
+
*
|
|
66
|
+
* @returns 应用 token、运行环境与业务网关 origin。
|
|
67
|
+
*/
|
|
68
|
+
declare function resolveDatabaseContext(): Promise<DatabaseContext>;
|
|
69
|
+
/** 宿主用当前访问者身份同源取图,返回可创建本地 URL 的图片字节。
|
|
70
|
+
* 调用方在替换或卸载时取消请求并释放自己创建的 Blob URL。
|
|
71
|
+
*/
|
|
72
|
+
declare function fetchAttachmentCover(ref: DatabaseAttachmentRef, size?: number, options?: {
|
|
73
|
+
signal?: AbortSignal;
|
|
74
|
+
}): Promise<Blob>;
|
|
75
|
+
/** 经父页面 bridge 取短时效自证链接;原文件由浏览器下载,不进入页面 JavaScript。
|
|
76
|
+
* 下载链接不代表附件增删已完成,也不提供并发或重试保证。
|
|
77
|
+
*
|
|
78
|
+
* @returns 短时效下载链接;用户下载请调用 openAttachmentDownload,由宿主打开。
|
|
79
|
+
*/
|
|
80
|
+
declare function fetchAttachmentDownloadUrl(context: DatabaseContext, ref: DatabaseAttachmentRef): Promise<string>;
|
|
81
|
+
/** 构造运行态读取应用信息的统一网关地址。
|
|
82
|
+
*
|
|
83
|
+
* @param context 当前应用上下文。
|
|
84
|
+
* @returns GetInvokeProject 的同源相对路径。
|
|
85
|
+
*/
|
|
86
|
+
declare function buildDatabaseInvokeGetPath(context: DatabaseContext): string;
|
|
87
|
+
/** 构造运行态调用函数的统一网关地址。
|
|
88
|
+
*
|
|
89
|
+
* token 与 function_id 是 path 参数,env 走 query(prod 为服务端缺省,不显式下传)。
|
|
90
|
+
*
|
|
91
|
+
* @param context 当前应用上下文。
|
|
92
|
+
* @param functionId Base Database Function ID。
|
|
93
|
+
* @returns InvokeFunction 的同源相对路径。
|
|
94
|
+
* @throws functionId 不满足命名约束时抛出 TypeError。
|
|
95
|
+
*/
|
|
96
|
+
declare function buildDatabaseInvokeFunctionPath(context: DatabaseContext, functionId: string): string;
|
|
97
|
+
/** 调用应用 Function。
|
|
98
|
+
*
|
|
99
|
+
* 请求经父页面同源代理发往统一网关;整个请求体即 payload,业务参数包在 params 下。
|
|
100
|
+
* 目标环境由 query 参数 env 指定,不重复添加环境 Header。
|
|
101
|
+
* 4xx/5xx 直接抛错,业务码由调用方按 operation 契约校验一次顶层 code。
|
|
102
|
+
*
|
|
103
|
+
* @param functionId Base Database Function ID。
|
|
104
|
+
* @param params 函数入参:Database Function、Mutation 与 FaaS 使用按声明名称构造的对象。
|
|
105
|
+
* @returns 统一包裹的函数响应。
|
|
106
|
+
*/
|
|
107
|
+
type DatabaseFunctionInvocation<Inputs extends object> = [
|
|
108
|
+
Extract<keyof Inputs, string>
|
|
109
|
+
] extends [never] ? [functionId: never, params: never] : {
|
|
110
|
+
[FunctionId in Extract<keyof Inputs, string>]: [
|
|
111
|
+
functionId: FunctionId,
|
|
112
|
+
params: Inputs[FunctionId]
|
|
113
|
+
];
|
|
114
|
+
}[Extract<keyof Inputs, string>];
|
|
115
|
+
declare function invokeDatabaseFunction<Data = unknown>(...[functionId, params]: DatabaseFunctionInvocation<DatabaseFunctionInputMap>): Promise<DatabaseFunctionResponse<Data>>;
|
|
116
|
+
/** 每组参数应用同一份已发布 Mutation 声明;总记录数最多 200。 */
|
|
117
|
+
declare function invokeDatabaseMutationBatch<Data = unknown>(functionId: string, parameterGroups: Record<string, unknown>[]): Promise<DatabaseFunctionResponse<Data>>;
|
|
118
|
+
/** 每次点击重新取短效 URL,经宿主打开;不代表浏览器已完成落盘。 */
|
|
119
|
+
declare function openAttachmentDownload(context: DatabaseContext, ref: DatabaseAttachmentRef): Promise<void>;
|
|
120
|
+
/** 旧模板的纯 URL 构造兼容接口:同步、无网络/宿主调用。
|
|
121
|
+
* 保留旧 extra.baseAppToken 与尺寸匹配语义;新业务取封面使用 fetchAttachmentCover,
|
|
122
|
+
* 其实际请求经统一调用边界。构造地址不能证明附件存在、权限或写入成功。
|
|
123
|
+
*/
|
|
124
|
+
declare function buildAttachmentCoverUrl(context: DatabaseContext, ref: DatabaseAttachmentRef, size?: number): string;
|
|
125
|
+
|
|
126
|
+
declare const UiLanguageContext: React.Context<"en" | "zh" | "ja" | undefined>;
|
|
127
|
+
declare const LANGUAGES: readonly [{
|
|
128
|
+
readonly id: "en";
|
|
129
|
+
readonly locale: "en-US";
|
|
130
|
+
readonly match: RegExp;
|
|
131
|
+
}, {
|
|
132
|
+
readonly id: "zh";
|
|
133
|
+
readonly locale: "zh-CN";
|
|
134
|
+
readonly match: RegExp;
|
|
135
|
+
}, {
|
|
136
|
+
readonly id: "ja";
|
|
137
|
+
readonly locale: "ja-JP";
|
|
138
|
+
readonly match: RegExp;
|
|
139
|
+
}];
|
|
140
|
+
type UiLanguage = (typeof LANGUAGES)[number]["id"];
|
|
141
|
+
/** Supported host locale wins; otherwise use the browser, then English. */
|
|
142
|
+
declare function selectUiLanguage(hostLocale: unknown, fallbackLocale: unknown): UiLanguage;
|
|
143
|
+
declare function getUiLanguage(): UiLanguage;
|
|
144
|
+
declare function getUiLocale(language?: "en" | "zh" | "ja"): string;
|
|
145
|
+
/** The Channel waits for the host handshake. All components share one request. */
|
|
146
|
+
declare function initializeUiLanguage(): Promise<UiLanguage>;
|
|
147
|
+
declare function useUiLanguage(): UiLanguage;
|
|
148
|
+
|
|
149
|
+
interface BaseAppContextValue {
|
|
150
|
+
runtime: typeof siteRuntime;
|
|
151
|
+
theme: "host" | "light" | "dark";
|
|
152
|
+
locale: UiLanguage;
|
|
153
|
+
mode?: string;
|
|
154
|
+
onDiagnostic?: (record: RuntimeDiagnostic) => void;
|
|
155
|
+
}
|
|
156
|
+
declare function BaseAppProvider({ children, ...value }: BaseAppContextValue & {
|
|
157
|
+
children?: React__default.ReactNode;
|
|
158
|
+
}): React__default.JSX.Element;
|
|
159
|
+
declare function useBaseApp(): BaseAppContextValue;
|
|
160
|
+
declare function useOptionalBaseApp(): BaseAppContextValue | null;
|
|
161
|
+
|
|
162
|
+
interface FloatingButtonProps {
|
|
163
|
+
position?: "bottom-right" | "bottom-left";
|
|
164
|
+
className?: string;
|
|
165
|
+
slots?: {
|
|
166
|
+
trigger?: React__default.ComponentType;
|
|
167
|
+
tooltip?: React__default.ComponentType<{
|
|
168
|
+
text: string;
|
|
169
|
+
}>;
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
declare function FloatingButton({ position, className, slots, }: FloatingButtonProps): React__default.JSX.Element | null;
|
|
173
|
+
|
|
174
|
+
/** 浮层菜单展示用的当前登录用户信息。 */
|
|
175
|
+
interface CurrentUser {
|
|
176
|
+
name: string;
|
|
177
|
+
avatarUrl: string;
|
|
178
|
+
/** 组织名。协议的 getCurrentUser 不含该字段,仅宿主用户接口回落路径提供。 */
|
|
179
|
+
tenantName: string;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
type DatabaseAudience = "enterprise" | "personal";
|
|
183
|
+
interface DatabaseUserMenuProps {
|
|
184
|
+
/** 默认 enterprise:拿不准时宁可多显示一个头像,也不要让用户找不到退出登录。 */
|
|
185
|
+
slots?: {
|
|
186
|
+
trigger?: React__default.ComponentType<{
|
|
187
|
+
user: CurrentUser;
|
|
188
|
+
}>;
|
|
189
|
+
organization?: React__default.ComponentType<{
|
|
190
|
+
name: string;
|
|
191
|
+
}>;
|
|
192
|
+
};
|
|
193
|
+
audience?: DatabaseAudience;
|
|
194
|
+
/** 弹层相对触发器的对齐方向,默认 right(触发器在右上角时用)。 */
|
|
195
|
+
align?: "left" | "right";
|
|
196
|
+
/** 弹层展开方向,默认 down(触发器在顶部时用);侧边栏底部的入口用 up。 */
|
|
197
|
+
side?: "up" | "down";
|
|
198
|
+
/** 是否在头像右侧显示姓名。窄侧栏或顶栏空间紧张时传 false。 */
|
|
199
|
+
showName?: boolean;
|
|
200
|
+
className?: string;
|
|
201
|
+
}
|
|
202
|
+
declare function DatabaseUserMenu({ audience, align, side, showName, className, slots, }: DatabaseUserMenuProps): React__default.JSX.Element | null;
|
|
203
|
+
|
|
204
|
+
interface UserAvatar {
|
|
205
|
+
avatar_72: string;
|
|
206
|
+
avatar_240: string;
|
|
207
|
+
avatar_640: string;
|
|
208
|
+
avatar_origin: string;
|
|
209
|
+
}
|
|
210
|
+
interface User {
|
|
211
|
+
avatar: UserAvatar;
|
|
212
|
+
department_ids: string[];
|
|
213
|
+
description?: string;
|
|
214
|
+
is_external?: boolean;
|
|
215
|
+
name: string;
|
|
216
|
+
user_id: string;
|
|
217
|
+
open_id?: string;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
type UserSelectorAction = "Select" | "Remove" | "Clear";
|
|
221
|
+
type UserSelectorMode = "multiple";
|
|
222
|
+
type UserSelectorSearchAction = "Input" | "AutoClear";
|
|
223
|
+
type UserSelectorValue = User | User[];
|
|
224
|
+
interface UserSelectorPanelProps {
|
|
225
|
+
className?: string;
|
|
226
|
+
slots?: {
|
|
227
|
+
empty?: React__default.ComponentType;
|
|
228
|
+
loading?: React__default.ComponentType;
|
|
229
|
+
option?: React__default.ComponentType<{
|
|
230
|
+
user: User;
|
|
231
|
+
selected: boolean;
|
|
232
|
+
}>;
|
|
233
|
+
footer?: React__default.ComponentType;
|
|
234
|
+
};
|
|
235
|
+
value?: UserSelectorValue | null;
|
|
236
|
+
defaultValue?: UserSelectorValue;
|
|
237
|
+
onChange?: (value: UserSelectorValue | undefined, meta: {
|
|
238
|
+
option: User | undefined;
|
|
239
|
+
action: UserSelectorAction;
|
|
240
|
+
}) => void;
|
|
241
|
+
onSelect?: (user: User, meta: {
|
|
242
|
+
option: User;
|
|
243
|
+
}) => void;
|
|
244
|
+
onClose?: () => void;
|
|
245
|
+
onSelectRecordCreator?: () => void;
|
|
246
|
+
getUserDescription?: (user: User) => string | undefined;
|
|
247
|
+
onSearch?: (value: string, meta: {
|
|
248
|
+
action: UserSelectorSearchAction;
|
|
249
|
+
}) => void;
|
|
250
|
+
loading?: boolean;
|
|
251
|
+
mode?: UserSelectorMode;
|
|
252
|
+
onKeyDown?: KeyboardEventHandler<HTMLInputElement>;
|
|
253
|
+
}
|
|
254
|
+
declare function UserSelectorPanel(props: UserSelectorPanelProps): React__default.JSX.Element;
|
|
255
|
+
|
|
256
|
+
type UserSelectorEditorValue = UserSelectorValue;
|
|
257
|
+
|
|
258
|
+
interface UserSelectorEditorProps {
|
|
259
|
+
className?: string;
|
|
260
|
+
portalContainer?: HTMLElement;
|
|
261
|
+
slots?: {
|
|
262
|
+
trigger?: React__default.ComponentType<{
|
|
263
|
+
value: UserSelectorEditorValue | null | undefined;
|
|
264
|
+
}>;
|
|
265
|
+
chip?: React__default.ComponentType<{
|
|
266
|
+
user: User;
|
|
267
|
+
}>;
|
|
268
|
+
};
|
|
269
|
+
value: UserSelectorEditorValue | null | undefined;
|
|
270
|
+
loading?: boolean;
|
|
271
|
+
mode?: UserSelectorMode;
|
|
272
|
+
onClick?: MouseEventHandler<HTMLDivElement>;
|
|
273
|
+
onChange?: (value: UserSelectorEditorValue | undefined) => void;
|
|
274
|
+
onSelect?: (user: User, meta: {
|
|
275
|
+
option: User;
|
|
276
|
+
}) => void;
|
|
277
|
+
onClear?: () => void;
|
|
278
|
+
onRemove?: (user: User) => void;
|
|
279
|
+
onSelectRecordCreator?: () => void;
|
|
280
|
+
getUserDescription?: (user: User) => string | undefined;
|
|
281
|
+
onDropdownVisibleChange?: (visible: boolean) => void;
|
|
282
|
+
onSearch?: (value: string, meta: {
|
|
283
|
+
action: UserSelectorSearchAction;
|
|
284
|
+
}) => void;
|
|
285
|
+
onKeyDown?: KeyboardEventHandler<HTMLInputElement>;
|
|
286
|
+
onFocus?: FocusEventHandler<HTMLButtonElement>;
|
|
287
|
+
onBlur?: FocusEventHandler<HTMLButtonElement>;
|
|
288
|
+
}
|
|
289
|
+
declare function UserSelectorEditor(props: UserSelectorEditorProps): React__default.JSX.Element;
|
|
290
|
+
|
|
291
|
+
/** 缩略图与大图共用;只在靠近可见区域时加载,组件持有并释放本地图片 URL。 */
|
|
292
|
+
declare function AttachmentImage({ attachment, size, alt, className, slots, }: {
|
|
293
|
+
slots?: {
|
|
294
|
+
loading?: ComponentType;
|
|
295
|
+
error?: ComponentType<{
|
|
296
|
+
code: string;
|
|
297
|
+
retry: () => void;
|
|
298
|
+
}>;
|
|
299
|
+
};
|
|
300
|
+
attachment: DatabaseAttachmentRef;
|
|
301
|
+
size?: number;
|
|
302
|
+
alt: string;
|
|
303
|
+
className?: string;
|
|
304
|
+
}): React.JSX.Element;
|
|
305
|
+
|
|
306
|
+
export { getUiLocale as $, UserSelectorPanel as A, UserSelectorPanelProps as B, User as C, DatabaseContext as D, UserSelectorValue as E, FunctionInputMap as F, UserSelectorMode as G, UserSelectorAction as H, UserSelectorSearchAction as I, UserSelectorEditor as J, UserSelectorEditorProps as K, UserSelectorEditorValue as L, BaseAppContextValue as M, BaseAppProvider as N, useBaseApp as O, useOptionalBaseApp as P, FloatingButtonProps as Q, FloatingButton as R, SiteRuntimeClient as S, DatabaseAudience as T, UiLanguage as U, DatabaseUserMenuProps as V, DatabaseUserMenu as W, AttachmentImage as X, UiLanguageContext as Y, selectUiLanguage as Z, getUiLanguage as _, getDatabaseContext as a, initializeUiLanguage as a0, useUiLanguage as a1, resolveDatabaseContext as b, fetchAttachmentCover as c, buildAttachmentCoverUrl as d, fetchAttachmentDownloadUrl as e, fetch as f, getCurrentUser as g, buildDatabaseInvokeGetPath as h, invokeHttp as i, buildDatabaseInvokeFunctionPath as j, invokeDatabaseFunction as k, logout as l, invokeDatabaseMutationBatch as m, DatabaseAttachmentRef as n, openAttachmentDownload as o, DatabaseEnv as p, DatabaseFunctionResponse as q, requestEdit as r, siteRuntime as s, DatabaseFunctionInvocation as t, DatabaseFunctionInputMap as u, createSiteRuntimeClient as v, createSiteRuntimeFetch as w, invokeApi as x, uploadAttachment as y, openLink as z };
|
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import * as channelRuntime from '@lark-base-open/base-site-channel/runtime';
|
|
2
|
+
import { LinkGuardOptions as LinkGuardOptions$1, CallSiteAIFunctionParams as CallSiteAIFunctionParams$1, InvokeSiteAIFunctionStreamParams as InvokeSiteAIFunctionStreamParams$1, SiteAIVideoTask, SiteAIImageAsset, SiteAIFunctionResult, SiteAIFunctionStreamHandle } from '@lark-base-open/base-site-channel/runtime';
|
|
3
|
+
export * from '@lark-base-open/base-site-channel/runtime';
|
|
4
|
+
export { SiteChatbotStreamError } from '@lark-base-open/base-site-channel/runtime';
|
|
5
|
+
import { RuntimeDiagnostic } from './shared.js';
|
|
6
|
+
export { CapabilityContext, CapabilityDescriptor, CapabilityMap, CapabilityName, CapabilityQueryResult, CapabilityUnavailableError, CapabilityUnavailableReason, DiagnosticCategory, DiagnosticCode, FunctionEnvelope, JsonValue, RuntimeCapabilities, SDKError, SDKErrorOptions, WriteResult, classifyRuntimeError } from './shared.js';
|
|
7
|
+
import { R as RuntimeContextReader } from './capabilities-56e403e7.js';
|
|
8
|
+
export { S as SiteRuntimeContext, g as getCapabilities, a as getRuntimeCapabilities, h as hasCapability, q as queryCapability, r as readCapabilities, b as requireCapability } from './capabilities-56e403e7.js';
|
|
9
|
+
export * from '@lark-base-open/base-site-channel/runtime-contract';
|
|
10
|
+
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteRuntimeApi, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, isValidSiteFunctionName, readSiteAITextDelta } from '@lark-base-open/base-site-channel/runtime-contract';
|
|
11
|
+
import { U as UiLanguage } from './index-64557073.js';
|
|
12
|
+
export { X as AttachmentImage, M as BaseAppContextValue, N as BaseAppProvider, n as DatabaseAttachmentRef, T as DatabaseAudience, D as DatabaseContext, p as DatabaseEnv, u as DatabaseFunctionInputMap, t as DatabaseFunctionInvocation, q as DatabaseFunctionResponse, W as DatabaseUserMenu, V as DatabaseUserMenuProps, R as FloatingButton, Q as FloatingButtonProps, F as FunctionInputMap, S as SiteRuntimeClient, Y as UiLanguageContext, C as User, H as UserSelectorAction, J as UserSelectorEditor, K as UserSelectorEditorProps, L as UserSelectorEditorValue, G as UserSelectorMode, A as UserSelectorPanel, B as UserSelectorPanelProps, I as UserSelectorSearchAction, E as UserSelectorValue, d as buildAttachmentCoverUrl, j as buildDatabaseInvokeFunctionPath, h as buildDatabaseInvokeGetPath, v as createSiteRuntimeClient, w as createSiteRuntimeFetch, f as fetch, c as fetchAttachmentCover, e as fetchAttachmentDownloadUrl, g as getCurrentUser, a as getDatabaseContext, _ as getUiLanguage, $ as getUiLocale, a0 as initializeUiLanguage, x as invokeApi, k as invokeDatabaseFunction, m as invokeDatabaseMutationBatch, i as invokeHttp, l as logout, o as openAttachmentDownload, z as openLink, r as requestEdit, b as resolveDatabaseContext, Z as selectUiLanguage, s as siteRuntime, y as uploadAttachment, O as useBaseApp, P as useOptionalBaseApp, a1 as useUiLanguage } from './index-64557073.js';
|
|
13
|
+
import React__default from 'react';
|
|
14
|
+
export { CAPABILITY_CATALOG } from '@lark-base-open/base-site-channel/capabilities';
|
|
15
|
+
|
|
16
|
+
interface LinkGuardOptions extends LinkGuardOptions$1 {
|
|
17
|
+
/** 测试时可注入上下文读取器;转发链接仍使用 channel 默认运行时。 */
|
|
18
|
+
runtime?: RuntimeContextReader;
|
|
19
|
+
onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;
|
|
20
|
+
}
|
|
21
|
+
/** 同步返回清理函数,异步查询期间维持原生行为;卸载后迟到的查询不会安装。 */
|
|
22
|
+
declare function installLinkGuard(options?: LinkGuardOptions): () => void;
|
|
23
|
+
|
|
24
|
+
type SiteAIMessageContentPart = {
|
|
25
|
+
text: string;
|
|
26
|
+
type: "text";
|
|
27
|
+
} | {
|
|
28
|
+
detail?: "high" | "low" | "xhigh";
|
|
29
|
+
type: "image";
|
|
30
|
+
url: string;
|
|
31
|
+
} | {
|
|
32
|
+
fps?: number;
|
|
33
|
+
type: "video";
|
|
34
|
+
url: string;
|
|
35
|
+
} | {
|
|
36
|
+
type: "audio";
|
|
37
|
+
url: string;
|
|
38
|
+
} | {
|
|
39
|
+
filename?: string;
|
|
40
|
+
type: "file";
|
|
41
|
+
url: string;
|
|
42
|
+
};
|
|
43
|
+
/** AI Function 对话消息。所有 content 都使用非空 parts 数组;System Prompt 由 Function 配置管理。
|
|
44
|
+
* 元组式 `[X, ...X[]]` 保证空数组无法通过 TS 编译,避免把空 content 推迟到运行态服务端校验。 */
|
|
45
|
+
type SiteAIMessage = {
|
|
46
|
+
content: [SiteAIMessageContentPart, ...SiteAIMessageContentPart[]];
|
|
47
|
+
role: "user";
|
|
48
|
+
} | {
|
|
49
|
+
content: [
|
|
50
|
+
Extract<SiteAIMessageContentPart, {
|
|
51
|
+
type: "text";
|
|
52
|
+
}>,
|
|
53
|
+
...Array<Extract<SiteAIMessageContentPart, {
|
|
54
|
+
type: "text";
|
|
55
|
+
}>>
|
|
56
|
+
];
|
|
57
|
+
role: "assistant";
|
|
58
|
+
};
|
|
59
|
+
type WithSiteAIMessages<T> = T extends unknown ? Omit<T, "messages"> & {
|
|
60
|
+
messages?: SiteAIMessage[];
|
|
61
|
+
} : never;
|
|
62
|
+
type CallSiteAIFunctionParams = WithSiteAIMessages<CallSiteAIFunctionParams$1>;
|
|
63
|
+
type InvokeSiteAIFunctionStreamParams = Omit<InvokeSiteAIFunctionStreamParams$1, "messages"> & {
|
|
64
|
+
messages: SiteAIMessage[];
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** AI Function 可判别联合返回与媒体任务态,供页面按 type 分支渲染。 */
|
|
68
|
+
type SiteAIMediaTask = SiteAIVideoTask | {
|
|
69
|
+
capabilityType?: "image";
|
|
70
|
+
errCode?: string;
|
|
71
|
+
errMessage?: string;
|
|
72
|
+
imageAssets?: SiteAIImageAsset[];
|
|
73
|
+
progress?: number;
|
|
74
|
+
requestId: string;
|
|
75
|
+
status: "cancelled" | "failed" | "queued" | "running" | "succeeded";
|
|
76
|
+
taskId: string;
|
|
77
|
+
type: "image_task";
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** 按 functionKey 调用 AI Function,返回可判别联合结果(text/image_task/video_task)。
|
|
81
|
+
*
|
|
82
|
+
* 页面用 switch(result.type) 分支渲染:text 为聚合文本,image_task/video_task
|
|
83
|
+
* 需再用 getSiteAIFunctionTask 轮询。传 messages 走文本/多模态理解,
|
|
84
|
+
* 传 input 创建媒体任务;随后用 getSiteAIFunctionTask 轮询。
|
|
85
|
+
*/
|
|
86
|
+
declare function callSiteAIFunction(params: CallSiteAIFunctionParams): Promise<SiteAIFunctionResult>;
|
|
87
|
+
/** 显式流式调用 AI Function(text/vision):逐帧消费增量,卸载或取消时 destroy。 */
|
|
88
|
+
declare function invokeSiteAIFunctionStream(params: InvokeSiteAIFunctionStreamParams): SiteAIFunctionStreamHandle;
|
|
89
|
+
/** 校验并归一化 AI Function 媒体任务响应。
|
|
90
|
+
*
|
|
91
|
+
* Channel SDK 新旧版本、OpenAPI 和父页面代理可能返回裸 task 或
|
|
92
|
+
* `{code,msg,data}` 包裹;页面只接受含合法 taskId/type/status 的任务。
|
|
93
|
+
*/
|
|
94
|
+
declare function normalizeSiteAIMediaTask(value: unknown): SiteAIMediaTask;
|
|
95
|
+
declare function hasRunnableMediaTask(task: SiteAIMediaTask): task is SiteAIMediaTask & {
|
|
96
|
+
taskId: string;
|
|
97
|
+
};
|
|
98
|
+
/** 提交文生图或文生视频任务,返回封装后的 taskId 与初始状态。 */
|
|
99
|
+
declare function createSiteAIFunctionTask(params: CallSiteAIFunctionParams): Promise<SiteAIMediaTask>;
|
|
100
|
+
/** 轮询文生图或文生视频任务进度与最终资源。 */
|
|
101
|
+
declare function getSiteAIFunctionTask(functionKey: string, taskId: string): Promise<SiteAIMediaTask>;
|
|
102
|
+
|
|
103
|
+
interface StartBaseAppOptions {
|
|
104
|
+
app: React__default.ComponentType;
|
|
105
|
+
root?: HTMLElement | string;
|
|
106
|
+
strictMode?: boolean;
|
|
107
|
+
linkGuard?: boolean;
|
|
108
|
+
reportLifecycle?: boolean;
|
|
109
|
+
platformUI?: boolean;
|
|
110
|
+
theme?: "host" | "light" | "dark";
|
|
111
|
+
locale?: "host" | UiLanguage;
|
|
112
|
+
providers?: (children: React__default.ReactNode) => React__default.ReactNode;
|
|
113
|
+
onDiagnostic?: (record: RuntimeDiagnostic) => void;
|
|
114
|
+
slots?: {
|
|
115
|
+
loading?: React__default.ComponentType;
|
|
116
|
+
error?: React__default.ComponentType<{
|
|
117
|
+
code: string;
|
|
118
|
+
}>;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
interface BaseAppHandle {
|
|
122
|
+
ready: Promise<void>;
|
|
123
|
+
dispose(): void;
|
|
124
|
+
}
|
|
125
|
+
declare function startBaseApp(options: StartBaseAppOptions): BaseAppHandle;
|
|
126
|
+
|
|
127
|
+
interface DevelopmentPairChallenge {
|
|
128
|
+
challenge: string;
|
|
129
|
+
}
|
|
130
|
+
interface DevelopmentPairProof {
|
|
131
|
+
proof: string;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
declare class SiteChatbotStreamAdapter extends channelRuntime.SiteChatbotStreamAdapter {
|
|
135
|
+
constructor(options: ConstructorParameters<typeof channelRuntime.SiteChatbotStreamAdapter>[0]);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export { BaseAppHandle, CallSiteAIFunctionParams, DevelopmentPairChallenge, DevelopmentPairProof, InvokeSiteAIFunctionStreamParams, LinkGuardOptions, RuntimeContextReader, RuntimeDiagnostic, SiteAIMediaTask, SiteAIMessage, SiteAIMessageContentPart, SiteChatbotStreamAdapter, StartBaseAppOptions, UiLanguage, callSiteAIFunction, createSiteAIFunctionTask, getSiteAIFunctionTask, hasRunnableMediaTask, installLinkGuard, invokeSiteAIFunctionStream, normalizeSiteAIMediaTask, startBaseApp };
|
package/dist/page.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as Qe,B as le,C as pe,D as fe,E as Se,F as Ae,G as ge,H as Ie,I as ke,J as ye,K as he,L as Ye,M as L,N as Je,O,P as Xe,Q as Ze,R as B,S as $e,T as et,U,V as G,W as tt,X as nt,Y as it,Z as rt,a as Q,b as Y,c as J,d as X,e as Z,f as $,g as ee,h as x,i as M,j as te,k as ne,l as m,m as ie,n as re,o as oe,p as ae,q as se,r as ce,s as ue,t as de,u as me,v as ze,w as _,x as Ke,y as We,z as je}from"./chunk-5XIFZ4AH.js";import{a as He,b as Ve,c as v,d as R}from"./chunk-ZKBZAK4L.js";import{a as qe}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as Re}from"@lark-base-open/base-site-channel/runtime";function D(e={}){let t=!0,n,i=s=>{let c=R(s);e.onDiagnostic?e.onDiagnostic(c):console.warn("[Base Database SDK]",c)},o=e.runtime??m;return Promise.resolve().then(()=>o.getRuntimeContext()).then(s=>{if(t){if(!_(s,"link.open")){i(new v("link.open",1));return}n=Re(e)}}).catch(s=>{t&&i(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as _t}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var P=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):M})}},F=e=>({...e,channel:e?.channel?x(e.channel):M}),N=(e,t)=>u.callSiteAIFunction(e,F(t)),q=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),H=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),V=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var Fe=new Set(["cancelled","failed","queued","running","succeeded"]);async function Te(e){let t=await N(e);return e.input&&!e.messages?k(t):t}function Ce(e){return q(e)}function a(e,t){for(let n of t){let i=e[n];if(typeof i=="string"&&i.trim())return i}}function be(e,t){for(let n of t){let i=e[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function xe(e){let t=a(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(C).map(t=>{let n=a(t,["size","Size"]),i=a(t,["token","Token"]),o=a(t,["url","URL"]);return{safetyStatus:a(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...i?{token:i}:{},...o?{url:o}:{}}})}function De(e){if(!C(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=a(e,["token","Token"]),i=a(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...i?{url:i}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function k(e){if(!C(e))throw T("AI Function task response has an invalid structure");let t=Pe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return k(e.data);let n=a(e,["type","Type"]),i=a(e,["taskId","task_id","TaskID"]),o=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!i||typeof o!="string"||!Fe.has(o))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=De(e.videoAsset??e.video_asset??e.VideoAsset),l=be(e,["progress","Progress"]),I=xe(e),p=a(e,["errCode","err_code","ErrCode"]),f=a(e,["errMessage","err_message","ErrMessage"]);return{...I?{capabilityType:I}:{},...p?{errCode:p}:{},...f?{errMessage:f}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:a(e,["requestId","request_id","RequestID"])??"",status:o,taskId:i,type:n}}function Pe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:a(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!C(n))return;let i=n.StatusCode??n.status_code??n.statusCode;if(typeof i=="number"&&i!==0||typeof i=="string"&&i&&i!=="0")return{code:String(i),message:a(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function Ee(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function we(e){return k(await H(e))}async function ve(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return k(await V(e,t))}function C(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as _e,StrictMode as Le,useEffect as Oe,useState as Be}from"react";import{createRoot as Ue}from"react-dom/client";import{Fragment as Ge,jsx as d,jsxs as Ne}from"react/jsx-runtime";var E=new WeakSet,b=class extends _e{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 Tt(e){let t,n,i=new Promise((r,g)=>{t=r,n=g});i.catch(()=>{});let o=!1,s=!1,c=!1,l,I=()=>{},p=()=>{},f=r=>{try{e.onDiagnostic?.(R(r))}catch{}},S=r=>{f(r),!(o||s||c)&&(c=!0,n(r),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED").catch(f))},A;try{A=typeof e.root=="string"?document.querySelector(e.root):e.root??document.querySelector("#root")}catch(r){return S(r),{ready:i,dispose(){o=!0}}}if(!A)return S(new Error("APP_ROOT_NOT_FOUND")),{ready:i,dispose(){o=!0}};if(E.has(A))throw new Error("APP_ALREADY_STARTED");E.add(A);let z=()=>{o||(o=!0,I(),p(),l?.unmount(),E.delete(A),U.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},K=()=>{queueMicrotask(()=>{o||c||s||(s=!0,e.reportLifecycle===!1?t():m.ready().then(t,r=>{f(r),n(r)}))})};function W({locale:r,theme:g}){let[y,h]=Be();Oe(()=>(p=m.subscribeModeChanged(h),K(),()=>p()),[]);let j=e.app,w=Ne(Ge,{children:[d(j,{}),e.platformUI===!1?null:d(G,{})]});return d(B,{runtime:m,theme:g,locale:r,mode:y,onDiagnostic:e.onDiagnostic,children:e.providers?e.providers(w):w})}try{l=Ue(A);let r=e.slots?.loading;r&&l.render(d(b,{failed:S,fallback:e.slots?.error,children:d(r,{})})),m.getRuntimeContext().then(g=>{if(o||c)return;let y=e.locale&&e.locale!=="host"?e.locale:L(g.locale,"en");document.documentElement.lang=O(y),e.linkGuard!==!1&&(I=D({onDiagnostic:e.onDiagnostic}));let h=d(b,{failed:S,fallback:e.slots?.error,children:d(W,{locale:y,theme:e.theme&&e.theme!=="host"?e.theme:g.colorScheme==="dark"?"dark":"light"})});l.render(e.strictMode===!1?h:d(Le,{children:h}))}).catch(S)}catch(r){S(r)}return{ready:i,dispose:z}}export{rt as AttachmentImage,B as BaseAppProvider,He as CAPABILITY_CATALOG,v as CapabilityUnavailableError,tt as DatabaseUserMenu,Ve as DiagnosticCode,G as FloatingButton,qe as SDKError,Q as SITE_RUNTIME_PROTOCOL_VERSION,P as SiteChatbotStreamAdapter,_t as SiteChatbotStreamError,Y as SiteRuntimeApi,te as SiteRuntimeClient,Z as SiteRuntimeErrorCode,J as SiteRuntimeEvent,X as SiteRuntimeFunction,Ye as UiLanguageContext,it as UserSelectorEditor,nt as UserSelectorPanel,he as buildAttachmentCoverUrl,ge as buildDatabaseInvokeFunctionPath,Ae as buildDatabaseInvokeGetPath,Te as callSiteAIFunction,R as classifyRuntimeError,we as createSiteAIFunctionTask,ne as createSiteRuntimeClient,de as createSiteRuntimeFetch,me as fetch,fe as fetchAttachmentCover,Se as fetchAttachmentDownloadUrl,Ke as getCapabilities,oe as getCurrentUser,le as getDatabaseContext,We as getRuntimeCapabilities,ve as getSiteAIFunctionTask,Je as getUiLanguage,O as getUiLocale,_ as hasCapability,Ee as hasRunnableMediaTask,Xe as initializeUiLanguage,D as installLinkGuard,re as invokeApi,Ie as invokeDatabaseFunction,ke as invokeDatabaseMutationBatch,ie as invokeHttp,Ce as invokeSiteAIFunctionStream,ee as isValidSiteFunctionName,ae as logout,k as normalizeSiteAIMediaTask,ye as openAttachmentDownload,ue as openLink,je as queryCapability,ze as readCapabilities,$ as readSiteAITextDelta,se as requestEdit,Qe as requireCapability,pe as resolveDatabaseContext,L as selectUiLanguage,m as siteRuntime,Tt as startBaseApp,ce as uploadAttachment,$e as useBaseApp,et as useOptionalBaseApp,Ze as useUiLanguage};
|
package/dist/server.cjs
ADDED
|
@@ -0,0 +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 n of L(s))!W.call(t,n)&&n!==o&&k(t,n,{get:()=>s[n],enumerable:!(e=U(s,n))||e.enumerable});return t};var z=t=>V(k({},"__esModule",{value:!0}),t);var M={};J(M,{SDKError:()=>f,bindFunctionRuntime:()=>j,createServerContext:()=>_,defineFunction:()=>K,normalizeRecordsResult:()=>x});module.exports=z(M);var F=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),f=class extends Error{constructor(o,e,n,r){super(e);this.code=o;this.name="SDKError",this.safeMessage=e;let c=typeof n=="object"?n:{};this.upstreamCode=typeof n=="string"?n: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??r??!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),b=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((n,r)=>n!==String(r))))throw 0;s.add(e);for(let n of Reflect.ownKeys(e)){if(Array.isArray(e)&&n==="length")continue;if(typeof n!="string")throw 0;let r=Object.getOwnPropertyDescriptor(e,n);if(!r.enumerable||!("value"in r))throw 0;o(r.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(b)&&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,n=e.ignored_fields??[];if(!Array.isArray(n)||!n.every(a=>d(a)&&["id","name","reason"].every(i=>typeof a[i]=="string")))return o();let r=e.record_not_found??[];if(!D(r))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(!b(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),r.some(a=>!c.includes(a)||u.includes(a))||!n.length&&c.some(a=>!u.includes(a)&&!r.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)||r.includes(i))||r.some(i=>!c.includes(i))||a.length+r.length!==c.length)return o();u=a}else{if(a.length!==c.length||a.some((i,p)=>i!==c[p])||r.some(i=>!c.includes(i)))return o();u=a.filter(i=>!r.includes(i))}}let l=y===void 0?{}:{attachments:y};return r.length||n.length?{status:"partial",appliedIds:u,notFoundIds:r,ignoredFields:n,...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,n,r,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(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(S(r),e==="create"){if(!Array.isArray(r)||!r.every(d))throw 0;a=r.length,y={create_records:r}}else if(e==="update"){if(!d(r)||!Object.values(r).every(d))throw 0;l=Object.keys(r),a=l.length,y={update_records:r}}else if(e==="delete"){if(!Array.isArray(r)||!r.every(b))throw 0;l=r,a=r.length,y={record_id_list:r}}else{if(!d(r))throw 0;let i=Object.create(null),p=0;for(let[m,g]of Object.entries(r)){if(!b(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(R=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(R)))throw 0;for(let R of["image_width","image_height"])if(h[R]!==void 0&&(typeof h[R]!="number"||!Number.isInteger(h[R])||h[R]<=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(b)||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(n.baseToken)}/tables/${encodeURIComponent(n.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,(n,r,c)=>o(e,n,r,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,n){let r=Object.defineProperty({...n},P,{value:o});return t.call(this,e,r)}}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 n=e.issues.map(r=>(r.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:n})}return e.value}function K(t){return async(s,o)=>{try{let e=await N(t.input,s,"INPUT"),n=await t.handler(e,_(o)),r=await N(t.output,n,"OUTPUT");return S(r),{code:0,msg:"success",data:r}}catch(e){let n=e instanceof f?e:new f("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");return console.error(JSON.stringify({source:"sdk",code:n.code,paths:n.paths,retryable:n.retryable,outcome:n.outcome})),{code:n.wireCode,msg:n.safeMessage}}}}0&&(module.exports={SDKError,bindFunctionRuntime,createServerContext,defineFunction,normalizeRecordsResult});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { JsonValue, WriteResult, FunctionEnvelope } from './shared.cjs';
|
|
3
|
+
export { DiagnosticCategory, RuntimeDiagnostic, SDKError, SDKErrorOptions } from './shared.cjs';
|
|
4
|
+
import '@lark-base-open/base-site-channel/capabilities';
|
|
5
|
+
|
|
6
|
+
type Fields = Record<string, JsonValue>;
|
|
7
|
+
type Target = {
|
|
8
|
+
baseToken: string;
|
|
9
|
+
tableId: string;
|
|
10
|
+
};
|
|
11
|
+
type AttachmentInput = {
|
|
12
|
+
file_token: string;
|
|
13
|
+
image_width?: number;
|
|
14
|
+
image_height?: number;
|
|
15
|
+
};
|
|
16
|
+
type Attachments = Record<string, Record<string, AttachmentInput[]>>;
|
|
17
|
+
interface RecordsClient {
|
|
18
|
+
create<T extends Fields>(target: Target, records: readonly T[], opts?: {
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}): Promise<WriteResult>;
|
|
21
|
+
update<T extends Fields>(target: Target, records: Readonly<Record<string, Partial<T>>>, opts?: {
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}): Promise<WriteResult>;
|
|
24
|
+
delete(target: Target, ids: readonly string[], opts?: {
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}): Promise<WriteResult>;
|
|
27
|
+
appendAttachments(target: Target, values: Attachments, opts?: {
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
}): Promise<WriteResult>;
|
|
30
|
+
removeAttachments(target: Target, values: Record<string, Record<string, {
|
|
31
|
+
file_token: string;
|
|
32
|
+
}[]>>, opts?: {
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}): Promise<WriteResult>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface RawFunctionContext {
|
|
38
|
+
fetch: typeof globalThis.fetch;
|
|
39
|
+
invokeFunction(p: {
|
|
40
|
+
projectId: string;
|
|
41
|
+
functionId: string;
|
|
42
|
+
params?: unknown;
|
|
43
|
+
}): Promise<unknown>;
|
|
44
|
+
}
|
|
45
|
+
interface RuntimeBuildProfile {
|
|
46
|
+
platformEnv: "online" | "pre" | "boe";
|
|
47
|
+
brand: "feishu" | "lark";
|
|
48
|
+
}
|
|
49
|
+
interface ServerContext extends RawFunctionContext {
|
|
50
|
+
records: RecordsClient;
|
|
51
|
+
}
|
|
52
|
+
declare function bindFunctionRuntime<F extends (raw: unknown, ctx: RawFunctionContext) => unknown>(fn: F, profile: RuntimeBuildProfile): F;
|
|
53
|
+
declare function createServerContext(raw: RawFunctionContext): ServerContext;
|
|
54
|
+
|
|
55
|
+
interface DefineFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
56
|
+
input: I;
|
|
57
|
+
output: O;
|
|
58
|
+
handler(input: StandardSchemaV1.InferOutput<I>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
59
|
+
}
|
|
60
|
+
interface DefinedFunction<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
61
|
+
(rawParams: unknown, context: RawFunctionContext): Promise<FunctionEnvelope<StandardSchemaV1.InferOutput<O>>>;
|
|
62
|
+
readonly __contractTypes?: {
|
|
63
|
+
input: StandardSchemaV1.InferInput<I>;
|
|
64
|
+
output: StandardSchemaV1.InferOutput<O>;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
declare function defineFunction<I extends StandardSchemaV1, O extends StandardSchemaV1>(definition: DefineFunctionOptions<I, O>): DefinedFunction<I, O>;
|
|
68
|
+
|
|
69
|
+
type RecordsOperation = "create" | "update" | "delete" | "appendAttachments" | "removeAttachments";
|
|
70
|
+
interface RecordsResultRequest {
|
|
71
|
+
operation: RecordsOperation;
|
|
72
|
+
requestedIds?: readonly string[];
|
|
73
|
+
count?: number;
|
|
74
|
+
}
|
|
75
|
+
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
76
|
+
|
|
77
|
+
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
78
|
+
|
|
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 };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { JsonValue, WriteResult, FunctionEnvelope } from './shared.js';
|
|
3
|
+
export { DiagnosticCategory, RuntimeDiagnostic, SDKError, SDKErrorOptions } from './shared.js';
|
|
4
|
+
import '@lark-base-open/base-site-channel/capabilities';
|
|
5
|
+
|
|
6
|
+
type Fields = Record<string, JsonValue>;
|
|
7
|
+
type Target = {
|
|
8
|
+
baseToken: string;
|
|
9
|
+
tableId: string;
|
|
10
|
+
};
|
|
11
|
+
type AttachmentInput = {
|
|
12
|
+
file_token: string;
|
|
13
|
+
image_width?: number;
|
|
14
|
+
image_height?: number;
|
|
15
|
+
};
|
|
16
|
+
type Attachments = Record<string, Record<string, AttachmentInput[]>>;
|
|
17
|
+
interface RecordsClient {
|
|
18
|
+
create<T extends Fields>(target: Target, records: readonly T[], opts?: {
|
|
19
|
+
signal?: AbortSignal;
|
|
20
|
+
}): Promise<WriteResult>;
|
|
21
|
+
update<T extends Fields>(target: Target, records: Readonly<Record<string, Partial<T>>>, opts?: {
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}): Promise<WriteResult>;
|
|
24
|
+
delete(target: Target, ids: readonly string[], opts?: {
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}): Promise<WriteResult>;
|
|
27
|
+
appendAttachments(target: Target, values: Attachments, opts?: {
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
}): Promise<WriteResult>;
|
|
30
|
+
removeAttachments(target: Target, values: Record<string, Record<string, {
|
|
31
|
+
file_token: string;
|
|
32
|
+
}[]>>, opts?: {
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}): Promise<WriteResult>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface RawFunctionContext {
|
|
38
|
+
fetch: typeof globalThis.fetch;
|
|
39
|
+
invokeFunction(p: {
|
|
40
|
+
projectId: string;
|
|
41
|
+
functionId: string;
|
|
42
|
+
params?: unknown;
|
|
43
|
+
}): Promise<unknown>;
|
|
44
|
+
}
|
|
45
|
+
interface RuntimeBuildProfile {
|
|
46
|
+
platformEnv: "online" | "pre" | "boe";
|
|
47
|
+
brand: "feishu" | "lark";
|
|
48
|
+
}
|
|
49
|
+
interface ServerContext extends RawFunctionContext {
|
|
50
|
+
records: RecordsClient;
|
|
51
|
+
}
|
|
52
|
+
declare function bindFunctionRuntime<F extends (raw: unknown, ctx: RawFunctionContext) => unknown>(fn: F, profile: RuntimeBuildProfile): F;
|
|
53
|
+
declare function createServerContext(raw: RawFunctionContext): ServerContext;
|
|
54
|
+
|
|
55
|
+
interface DefineFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
56
|
+
input: I;
|
|
57
|
+
output: O;
|
|
58
|
+
handler(input: StandardSchemaV1.InferOutput<I>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
59
|
+
}
|
|
60
|
+
interface DefinedFunction<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
61
|
+
(rawParams: unknown, context: RawFunctionContext): Promise<FunctionEnvelope<StandardSchemaV1.InferOutput<O>>>;
|
|
62
|
+
readonly __contractTypes?: {
|
|
63
|
+
input: StandardSchemaV1.InferInput<I>;
|
|
64
|
+
output: StandardSchemaV1.InferOutput<O>;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
declare function defineFunction<I extends StandardSchemaV1, O extends StandardSchemaV1>(definition: DefineFunctionOptions<I, O>): DefinedFunction<I, O>;
|
|
68
|
+
|
|
69
|
+
type RecordsOperation = "create" | "update" | "delete" | "appendAttachments" | "removeAttachments";
|
|
70
|
+
interface RecordsResultRequest {
|
|
71
|
+
operation: RecordsOperation;
|
|
72
|
+
requestedIds?: readonly string[];
|
|
73
|
+
count?: number;
|
|
74
|
+
}
|
|
75
|
+
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
76
|
+
|
|
77
|
+
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
78
|
+
|
|
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 };
|