ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

coze-studio 前端类型包详解:@coze-arch/bot-typings 的类型声明设计与使用

coze-studio 前端类型包详解:@coze-arch/bot-typings 的类型声明设计与使用 coze-studio 前端类型包详解coze-arch/bot-typings 的类型声明设计与使用【免费下载链接】coze-studioAn AI agent development platform with all-in-one visual tools, simplifying agent creation, debugging, and deployment like never before. Coze your way to AI Agent creation.项目地址: https://gitcode.com/GitHub_Trending/co/coze-studiocoze-studio 的 Coze bot 前端生态建立在 Rush.js monorepo 之上多个包之间共享同一套用户、鉴权、路由与平台集成类型。coze-arch/bot-typings位于 frontend/packages/arch/bot-typings就是从 bot 应用中抽取出来的纯 TypeScript 类型定义包它集中声明了文件模块图片/样式/SVG类型、通用工具类型、DataItem用户与鉴权命名空间、以及window/navigator全局扩展在零运行时依赖的前提下为整个 bot 生态提供类型安全。读完本篇你可以理解该包各入口的导出结构、每个核心类型的实现细节以及如何在一个 Rush 工作区项目中正确引用它。一、包定位与核心特性根据 README 与 package.json该包的元信息如下包名coze-arch/bot-typings版本0.0.1许可证 Apache-2.0描述bot typings that extract from bot/src/typings即从原 bot 应用的 typings 目录抽取而来运行时依赖dependencies为空对象纯类型声明无运行时开销。它提供的能力可分为五类全局模块声明Global Type Declarations为图片、样式表、SVG 等文件导入提供类型通用工具类型Common Utility TypesObj、Expand、PartialRequired等类型操纵工具平台相关类型Platform-Specific Types浏览器 API、window对象与navigator扩展用户与鉴权类型User Authentication Types用户数据、OAuth 登录流程、验证码等接口的数据结构Teamspace 与路由类型动态路由参数DynamicParams的声明。1.1 入口导出结构从 package.json 的exports字段可以看到包对外暴露的三个入口{ exports: { .: ./src/index.d.ts, ./common: ./src/common.ts, ./teamspace: ./src/teamspace.ts }, main: src/index.d.ts, types: src/index.d.ts, typesVersions: { .: { *: [./src/index.d.ts] }, *: { common: [./src/common.ts], teamspace: [./src/teamspace.ts] } } }这里有两点值得注意主入口.指向src/index.d.ts负责拉入全部全局声明模块声明 全局命名空间扩展子路径./common与./teamspace直接指向.ts源文件而非.d.ts并且额外配置了typesVersions映射保证旧版 TypeScript 或非标准解析路径下也能正确找到类型入口。新增子模块时必须同步更新exports字段README「Adding New Types」一节也强调了这一点。二、快速上手2.1 在 Rush.js monorepo 中安装README 给出的安装方式是在宿主包的package.json中声明 workspace 依赖然后执行rush update# Add to your package.json coze-arch/bot-typings: workspace:* # Run Rush update to install rush updateworkspace:*是 pnpm 的 workspace 协议表示始终解析到 monorepo 内的本地版本。coze-studio 仓库的 Rush 配置位于 common/config/rush子包通过workspace:*相互引用是该仓库的标准做法本包的devDependencies中coze-arch/bot-env、coze-arch/eslint-config、coze-arch/ts-config均为workspace:*。2.2 基本引用方式// 引入主类型定义拉入全部全局声明 import coze-arch/bot-typings; // 按需引入子模块 import { BotPageFromEnum, Obj, Expand, PartialRequired } from coze-arch/bot-typings/common; import { DynamicParams } from coze-arch/bot-typings/teamspace;需要说明的是coze-arch/bot-typings主入口是副作用式引入side-effect import它本身没有值导出作用是让index.d.ts中的declare module与全局interface扩展进入当前编译上下文。三、API 参考结合源码逐一解析3.1 Common 类型src/common.tscommon.ts 只有约 55 行包含一个枚举和三个工具类型。BotPageFromEnumBot 详情页来源export enum BotPageFromEnum { Bot bot, //bot list Explore explore, //Explore List Store store, Template template, }它标识 bot 详情页面是从哪个列表进入的bot 列表 / 探索列表 / 商店 / 模板。源码注释写明“currently only bot and explore list”即实际业务中目前主要使用前两个枚举值Store与Template属于预留扩展。注意它是运行时枚举而非declare enum因此会真正产出 JS 代码——这是该包中唯一具有运行时产出的导出也是它必须以.ts文件形式通过exports子路径暴露的原因。Obj通用对象类型export type Obj Recordstring, any;后续所有工具类型都以其作为约束基类如ExpandT extends Obj。ExpandT展开交叉类型README 中的示例解释了用途而源码给出了具体实现/** * Show the full type * * example * type Intersection { a: string } { b: number }; * type Result ExpandIntersection; * // Result: { a: string; b: number } */ export type ExpandT extends Obj T extends infer U ? { [K in keyof U]: U[K] } : never;从源码结构看它用T extends infer U捕获类型参数再通过一次映射类型mapped type把{ a: string } { b: number }这样的交叉类型“摊平”为对象字面量形态。这样做的好处是TypeScript 语言服务在悬停提示中会把交叉类型显示为A B的合并视图而Expand之后会显示完整、可直接阅读的对象结构对调试复杂类型非常有用。PartialRequiredT, K指定字段改为必填/** * Required only for specific fields, often used to correct server level type declaration errors * * example * interface Agent { * id?: string; * name?: string; * desc?: string * } * type Result PartialRequiredAgent, id | name; */ export type PartialRequiredT extends Obj, K extends keyof T Expand { [P in K]-?: T[P]; } PickT, Excludekeyof T, K ;实现上有三个关键点{ [P in K]-?: T[P] }对选中的键K做映射-?修饰符把原本的可选性移除使这些字段变为必填PickT, Excludekeyof T, K把其余字段原样保留可选性不变两者交叉后得到完整对象外层再套Expand让结果以摊平后的对象字面量呈现避免交叉类型在提示里显得臃肿。源码注释明确给出使用场景当服务端类型声明把所有字段都标成可选、而实际接口必填了其中一部分时用它“纠正”类型声明而不必复制一份 interface。3.2 Teamspace 类型src/teamspace.tsteamspace.ts 定义了动态路由参数类型export interface DynamicParams extends Recordstring, string | undefined { space_id?: string; bot_id?: string; plugin_id?: string; workflow_id?: string; dataset_id?: string; doc_id?: string; tool_id?: string; invite_key?: string; product_id?: string; mock_set_id?: string; conversation_id: string; commit_version?: string; /** social scene */ scene_id?: string; post_id?: string; project_id?: string; }几个使用上的要点接口继承Recordstring, string | undefined索引签名意味着除了枚举出的字段任意字符串键都能以string | undefined访问这与真实 URL query 参数的“不可穷举”特性相符字段覆盖了 teamspace 场景下的各类资源维度空间space_id、Botbot_id、插件plugin_id、工作流workflow_id、知识库dataset_id、文档doc_id、工具tool_id、市场商品product_id、Mock 集mock_set_id、社交场景scene_id/post_id源码注释标注为 social scene、项目project_id唯一必填字段是conversation_id没有?修饰符其余均为可选。使用时必须保证会话 ID 一定被提供否则类型检查不通过可选的invite_key用于团队空间邀请链接场景commit_version用于指定资源版本。3.3 用户与鉴权类型src/data_item.d.tsdata_item.d.ts 以全局declare namespace DataItem组织了一批账号体系数据结构。README 概括为UserInfo与四类鉴权类型源码中实际提供的接口更完整此处按功能分组说明。UserInfo完整用户信息interface UserInfo { app_id: number; /** * Deprecated will lose precision due to overflow, use user_id_str */ user_id: number; user_id_str: string; odin_user_type: number; name: string; screen_name: string; avatar_url: string; user_verified: boolean; email?: string; email_collected: boolean; // ... 其余约 70 个字段 bui_audit_info?: { audit_info: { user_unique_name?: string; avatar_url?: string; name?: string; [key: string]: unknown }; /** int value. 1 During the review, 2 passed the review, and 3 failed the review. */ audit_status: 1 | 2 | 3; details: Recordstring, unknown; is_auditing: boolean; last_update_time: number; unpass_reason: string; }; }值得注意的实现细节精度问题警示user_id: number被显式标注Deprecated注释说明大整数在 number 类型下会溢出丢精度应使用字符串形式的user_id_str。这是对接 64 位 ID 的经典坑类型注释直接把它固化在声明里布尔语义字段大量采用0/1 number表达如is_blocked、is_blocking、new_user、has_password与后端序列化习惯保持一致前端不能直接当真值判断嵌套的bui_audit_info.audit_status用了字面量联合1 | 2 | 3表示“审核中 / 通过 / 不通过”源码注释给出了每个取值的含义还有sec_user_id、old_user_id等历史迁移字段need_ttwid_migration说明该结构体长期跟随账号体系演进。鉴权与账号流程类型README 列举的四个核心接口在源码中的定义如下AuthLoginParams—— OAuth 登录入参platform_app_id必填、code/access_token/access_token_secret/openid/profile_key各 OAuth 平台回传凭证均可选、login_only、extra_paramsAuthorizeResponse—— 授权响应包含token与嵌套user_infouser_id、app_id、screen_name、mobile、email、avatar_url、create_time、is_new_user、is_new_connect、session_key、session_app_id、safe_mobile等SendCodeData—— 发送验证码响应mobile、mobile_ticket、retry_time重试冷却时间UserCheckResponse—— 用户校验响应value_ticket、authType、error_code、oauth_platformsstring[] | null、platform_user_names、userType等。除 README 提到的四个之外源码中还包含以下接口可视为同一命名空间的完整能力面接口用途关键字段UserConnectItem第三方平台账号绑定记录platform、access_token、open_id、expired_time、platform_uidbindWithEmailLoginParams邮箱第三方绑定登录入参platform_app_id必填、code、redirect_uribindWithMobileLoginParams手机号绑定登录入参platform_app_id必填、platform、need_mobile、change_bindValidateCodeResponse验证码校验结果ticketResetByEmailTicket邮箱重置票据ticketAuditItem单条审核项pass、title、text、reasonCancelCheckResponse账号注销前检查business_audit、punish_audit、user_permission_audit、cancel_ticketUploadAvatarResponse头像上传结果web_uri另外从源码结构看bindWithEmailLoginParams在文件内声明了两次第 130 行与第 186 行两次字段结构一致依赖 TypeScript 的 interface 声明合并declaration merging共存读取该文件时不必将其视为冲突。3.4 全局模块声明src/index.d.tsindex.d.ts 是这个包的“总装配点”开头通过 triple-slash 引用把其余声明文件与依赖包的类型串起来/// reference types./data_item / /// reference types./navigator / /// reference types./window / /// reference typescoze-arch/bot-env/typings /最后一行引向工作区包coze-arch/bot-env的 typings环境相关类型这也是 README「Dependencies」一节将coze-arch/bot-env列为开发依赖的原因——它只用于类型检查阶段不产生运行时依赖。其后的文件模块声明覆盖了前端资源导入的常见形态图片文件.jpeg/.jpg/.webp/.gif/.pngdeclare module *.png { const value: string; export default value; }导入后默认为字符串资源 URL例如import myImage from ./image.png; // string。样式文件.less/.cssdeclare module *.less { const resource: { [key: string]: string }; export resource; }注意这里用的是export 而非export default对应 CSS Modules 风格导入import styles from ./styles.less; // { [key: string]: string }。SVG 文件declare module *.svg { export const ReactComponent: React.FunctionComponent React.SVGPropsSVGSVGElement ; /** * The default export type depends on the svgDefaultExport config, * it can be a string or a ReactComponent * */ const content: any; export default content; }命名导出ReactComponent是固定可用的React.FunctionComponentReact.SVGPropsSVGSVGElementimport { ReactComponent } from ./icon.svg;默认导出类型刻意声明为any因为源码注释明确说明其真实类型取决于构建侧svgDefaultExport配置可能是字符串也可能是 ReactComponent声明层不做强断言。这里的React类型来自 devDependencies 中的 React 18.2 类型包。3.5 浏览器 API 扩展src/window.d.ts 与 src/navigator.d.tsWindow 扩展window.d.ts声明了 bot 平台在宿主环境中会注入/依赖的一组全局对象interface Window { /** IDE plugin iframe mount method for unmounting */ editorDispose?: any; MonacoEnvironment?: any; tt?: { miniProgram: { postMessage: (param: { data?: any; success?: (res) void; fail?: (err) void }) void; redirectTo: (param: { url?: string; success?: (res) void; fail?: (err) void }) void; navigateTo: (param: { url?: string; success?: (res) void; fail?: (err) void }) void; reLaunch: (param: { url?: string; success?: (res) void; fail?: (err) void }) void; navigateBack: (param?: { delta?: number; success?: (res) void; fail?: (err) void }) void; getEnv: (res) void; }; }; __cozeapp__?: { props: Recordstring, unknown; setLoading?: (loading: boolean) void; }; }对应 README 给出的三个典型调用场景// IDE 插件支持iframe 卸载回调 window.editorDispose?.(); // 小程序tt容器集成 window.tt?.miniProgram.postMessage({ data: { ... } }); // Coze 宿主 App 集成 window.__cozeapp__?.setLoading?.(true);从声明结构看这些扩展刻画了三类宿主环境IDE 插件宿主editorDispose、MonacoEnvironment后者用于 Monaco 编辑器的 worker 环境配置、字节小程序容器tt.miniProgram提供postMessage/redirectTo/navigateTo/reLaunch/navigateBack/getEnv六类页面与消息 API、Coze App 宿主__cozeapp__.props传参 setLoading控制全局 loading。由于全部声明为可选?在浏览器独立环境访问它们不会引发类型错误配合?.调用即可安全降级。另外该文件末尾还附加了一个process.env的全局命名空间声明declare namespace process { const env: { [key: string]: string } }README 未单独列出但源码中确实存在作用是让浏览器侧代码在引用process.env.XXX由构建工具 DefinePlugin 类机制注入时通过类型检查。Navigator 扩展navigator.d.ts非常简洁interface Navigator { standalone: boolean; }用于独立 Web AppPWA / 添加到主屏幕检测if (navigator.standalone) { // Running as standalone web app }standalone声明为非可选字段即该包假定运行环境总会提供此属性。四、工程化构建、检查与扩展4.1 项目结构src/ ├── index.d.ts # 主类型定义与文件模块声明总装配点 ├── common.ts # 通用工具类型与枚举唯一含运行时产出的文件 ├── teamspace.ts # Teamspace 动态路由参数 ├── data_item.d.ts # DataItem 命名空间用户与鉴权类型 ├── navigator.d.ts # Navigator 扩展 └── window.d.ts # Window 扩展与 process.env 声明六个文件与 README 描述一一对应职责划分清晰全局副作用声明放.d.ts需要值导出的放.ts。4.2 构建No-op 是设计使然package.json 中的脚本定义scripts: { build: exit 0, lint: eslint ./ }build就是exit 0——因为包内只有类型声明以及一个轻量枚举消费方直接编译其.ts源文件即可不需要产物步骤。类型层面的质量保障由 TypeScript 项目引用project references承担tsconfig.json 是一个 solution 文件composite: true并引用./tsconfig.build.json与 tsconfig.misc.json 两个子项目同时exclude: [**/*]保证 solution 层不重复包含源文件。Rush 侧则在 config/rush-project.json 中注册了ts-check操作输出目录./dist由仓库统一的rushx ts-check流程执行整仓类型检查。Lint 使用共享配置coze-arch/eslint-configdevDependency本地配置见 eslint.config.js源码中Obj定义处的// eslint-disable-next-line typescript-eslint/no-explicit-any -- had to any注释体现了该包对any的克制态度——只在确实无法避免如svgDefaultExport的不确定默认导出、tt小程序回调参数时才放行。4.3 新增类型的规范README「Adding New Types」给出四条规则对照包结构可以落地为文件模块声明新的资源后缀→ 加入 src/index.d.ts通用工具类型→ 加入 src/common.ts领域类型→ 新建文件如 teamspace 那样并在package.json的exports与typesVersions中登记子路径全局扩展window / navigator 等 DOM 全局对象→ 分别加入 src/window.d.ts 或 src/navigator.d.ts并通过index.d.ts的/// reference types... /保证被主入口拉起。最后一条更新exports字段是容易遗漏的一步exports字段存在时未登记的子路径会被 Node/TS 解析器直接拒绝typesVersions的兜底映射也要同步维护否则不同解析策略下会出现“本地能过、消费方报模块找不到”的不一致。五、依赖与版本前提运行时依赖无。该包不含可执行逻辑依赖dependencies为空。开发依赖类型检查阶段依赖版本用途coze-arch/bot-envworkspace:*提供环境相关 typings被index.d.ts以coze-arch/bot-env/typings引用coze-arch/eslint-configworkspace:*共享 ESLint 配置coze-arch/ts-configworkspace:*共享 TypeScript 基配置typescript~5.8.2类型编译器react/react-dom~18.2.0提供React.FunctionComponent等类型用于 SVG 声明types/node^18Node 侧类型webpack/rspack/core~5.91.0/0.6.0与构建工具相关的类型环境适用前提小结该包面向 coze-studio 的 Rush pnpm workspace 环境消费方 TypeScript 需能解析.ts源文件monorepo 内通过 workspace 链接天然满足svgDefaultExport等构建侧行为影响 SVG 默认导出的实际类型声明层已按any兼容处理。六、小结coze-arch/bot-typings用六个文件、零运行时依赖的方式把 coze-studio bot 前端的类型契约收敛到一个包内index.d.ts作为全局声明的装配入口common.ts提供Expand/PartialRequired这类可直接复用的类型工具teamspace.ts固化动态路由参数契约conversation_id必填data_item.d.ts覆盖账号与鉴权的完整数据面含 64 位 ID 精度、审核状态码等真实业务约束window.d.ts/navigator.d.ts则把 IDE 插件、小程序容器、Coze App 宿主三类运行环境的桥接 API 类型化。对于要在该 monorepo 中新增或修改 bot 相关前端的开发者正确的姿势是优先复用这些类型而非在业务包里重新声明并按「Adding New Types」的分工规则向对应文件补充新契约。【免费下载链接】coze-studioAn AI agent development platform with all-in-one visual tools, simplifying agent creation, debugging, and deployment like never before. Coze your way to AI Agent creation.项目地址: https://gitcode.com/GitHub_Trending/co/coze-studio创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表