transone 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as $e,A as ue,Aa as dr,B as pe,C as ce,D as fe,E as ge,F as me,G as Re,H as xe,I as Te,J as Ve,K as ye,L as be,M as ke,N as Fe,O as Me,P as he,Q as je,R as ve,S as Ce,T as we,U as Ae,V as Ee,W as Oe,X as Pe,Y as Se,Z as qe,_ as Le,a as z,aa as ze,b as B,ba as Be,c as D,ca as De,d as G,da as Ge,e as H,ea as He,f as I,fa as Ie,g as J,ga as Je,h as K,ha as Ke,i as N,ia as Ne,j as Q,ja as Qe,k as U,ka as d,l as W,la as Ue,m as X,ma as We,n as Y,na as Xe,o as Z,oa as Ye,p as _,pa as Ze,q as ee,qa as _e,r as re,ra as er,s as te,sa as rr,t as oe,ta as tr,u as ne,ua as nr,v as ie,va as u,w as le,wa as ir,x as se,xa as lr,y as ae,ya as sr,z as de,za as ar}from"./index-3t506ckz.js";import{Ca as or}from"./index-mbmajrpr.js";function p(e){return e instanceof Error?e.message:String(e)}function c(e,r,t){try{let n=e(r,t);if(n===!0)return;return n===!1?"Validation failed":n}catch(n){return p(n)}}function g(e="This field is required"){return(r)=>{if(r===null||r===void 0)return e;if(typeof r==="string"&&r.trim().length===0)return e;if(Array.isArray(r)&&r.length===0)return e;return!0}}function m(e,r=`Must be at least ${e} characters`){return(t)=>typeof t==="string"&&t.length>=e?!0:r}function R(e){return e}function x(e,r){let t={},n=(o)=>{let i=r[o]??[],l=d(e,o),s=i.map((a)=>c(a,l,e)).filter((a)=>a!==void 0);if(s.length===0)delete t[o];else t[o]=s;return{valid:s.length===0,errors:s}};return{model:e,errors:t,validate(){let o={};return Object.keys(r).forEach((i)=>{let l=n(i);if(!l.valid)o[i]=l.errors}),{valid:Object.keys(o).length===0,errors:o}},validateField:n,resetErrors(){Object.keys(t).forEach((o)=>delete t[o])}}}function E(e={}){return new u(e)}var O="0.1.0",P="@geektech/transone";export{Ee as A,ge as Article,me as Aside,ve as Blockquote,se as Button,je as Code,tr as Component,_e as ComponentRenderStrategy,ne as Div,Xe as ElementRenderStrategy,Fe as Em,ce as Footer,Pe as Form,Re as H1,xe as H2,Te as H3,Ve as H4,ye as H5,be as H6,pe as Header,Oe as Img,ae as Input,Se as Label,Ae as Li,ue as Main,We as ModelBindingController,fe as Nav,we as Ol,u as OneApp,$e as Option,le as P,he as Pre,G as ReactiveSystem,Ye as RendererContext,lr as Router,sr as RouterLink,ar as RouterView,de as Section,Le as Select,er as SlotRenderStrategy,Me as Small,ie as Span,ke as Strong,ze as Table,oe as Tag,De as Tbody,Ie as Td,rr as TemplateEngine,Ze as TextRenderStrategy,qe as Textarea,He as Th,Be as Thead,Ge as Tr,Ce as Ul,K as computed,E as createApp,Je as createComponent,x as createForm,dr as createRouter,Ne as each,J as effect,D as flushSync,d as getModelValue,te as h,_ as isComponentNode,ee as isHTMLNode,Y as isReactive,Z as isReadonly,Q as isRef,re as isSlotProvider,m as minLength,Qe as modelPath,P as name,B as nextTick,H as reactive,z as reactiveScheduler,I as readonly,N as ref,nr as renderHtmlDocument,or as renderStyleSheet,g as required,Ue as setModelValue,Ke as slot,W as stop,U as unref,ir as useRouter,R as validate,O as version,X as watch};
1
+ import{$ as ze,A as pe,Aa as pr,B as fe,Ba as u,C as ce,D as ge,E as me,F as xe,G as Re,H as Te,I as Ve,J as ye,K as be,L as Fe,M as Me,N as je,O as ke,P as he,Q as ve,R as Ce,S as we,T as Ae,U as Ee,V as Oe,W as Pe,X as Se,Y as qe,Z as Le,_ as $e,a as B,aa as Be,b as D,ba as De,c as G,ca as Ge,d as H,da as He,e as I,ea as Ie,f as J,fa as Je,g as K,ga as Ke,h as N,ha as Ne,i as Q,ia as Qe,j as U,ja as Ue,k as W,ka as We,l as X,la as d,m as Y,ma as Xe,n as Z,na as Ye,o as _,oa as Ze,p as ee,pa as _e,q as re,qa as er,r as te,ra as rr,s as oe,sa as tr,t as ne,ta as or,u as ie,ua as nr,v as le,va as ir,w as se,wa as lr,x as ae,xa as sr,y as de,ya as ar,z as ue,za as dr}from"./index-sf0hkgh3.js";import{Ea as ur}from"./index-d5wsetxf.js";import{Fa as fr,Ga as cr,Ha as gr,Ia as mr,Ja as xr,Ka as Rr,La as Tr,Ma as Vr,Na as yr,Oa as br}from"./index-xp7y2crt.js";function p(e){return e instanceof Error?e.message:String(e)}function f(e,r,t){try{let n=e(r,t);if(n===!0)return;return n===!1?"Validation failed":n}catch(n){return p(n)}}function g(e="This field is required"){return(r)=>{if(r===null||r===void 0)return e;if(typeof r==="string"&&r.trim().length===0)return e;if(Array.isArray(r)&&r.length===0)return e;return!0}}function m(e,r=`Must be at least ${e} characters`){return(t)=>typeof t==="string"&&t.length>=e?!0:r}function x(e){return e}function R(e,r){let t={},n=(o)=>{let i=r[o]??[],l=d(e,o),s=i.map((a)=>f(a,l,e)).filter((a)=>a!==void 0);if(s.length===0)delete t[o];else t[o]=s;return{valid:s.length===0,errors:s}};return{model:e,errors:t,validate(){let o={};return Object.keys(r).forEach((i)=>{let l=n(i);if(!l.valid)o[i]=l.errors}),{valid:Object.keys(o).length===0,errors:o}},validateField:n,resetErrors(){Object.keys(t).forEach((o)=>delete t[o])}}}function E(e={}){return new u(e)}var O="0.2.0",P="transone";export{Pe as A,xe as Article,Re as Aside,we as Blockquote,de as Button,Ce as Code,dr as Component,lr as ComponentRenderStrategy,le as Div,or as ElementRenderStrategy,ke as Em,ge as Footer,qe as Form,Te as H1,Ve as H2,ye as H3,be as H4,Fe as H5,Me as H6,ce as Header,Se as Img,ue as Input,Tr as InterceptorManager,Le as Label,Oe as Li,fe as Main,Ye as ModelBindingController,me as Nav,Ee as Ol,u as OneApp,Be as Option,ae as P,ve as Pre,H as ReactiveSystem,nr as RendererContext,Vr as Request,fr as RequestError,Ze as Router,_e as RouterLink,er as RouterView,pe as Section,ze as Select,sr as SlotRenderStrategy,he as Small,se as Span,je as Strong,De as Table,ie as Tag,He as Tbody,Ke as Td,ar as TemplateEngine,ir as TextRenderStrategy,$e as Textarea,Je as Th,Ge as Thead,Ie as Tr,Ae as Ul,mr as adapters,N as computed,xr as createAdapter,E as createApp,Ne as createComponent,R as createForm,yr as createRequest,rr as createRouter,gr as detectPlatform,Ue as each,K as effect,G as flushSync,d as getModelValue,ne as h,re as isComponentNode,te as isHTMLNode,Z as isReactive,_ as isReadonly,U as isRef,cr as isRequestError,oe as isSlotProvider,m as minLength,We as modelPath,P as name,D as nextTick,I as reactive,B as reactiveScheduler,J as readonly,Q as ref,pr as renderHtmlDocument,ur as renderStyleSheet,br as request,g as required,Rr as resolveAdapter,Xe as setModelValue,Qe as slot,X as stop,ee as toChildren,W as unref,tr as useRouter,x as validate,O as version,Y as watch};
2
2
 
3
- //# debugId=4FA5C6C6C6CCA20664756E2164756E21
3
+ //# debugId=67A3AA10CDAABA5564756E2164756E21
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -3,9 +3,9 @@
3
3
  "sources": ["../lib/core/form.ts", "../lib/index.ts"],
4
4
  "sourcesContent": [
5
5
  "import { getModelValue } from './model';\n\nexport type ValidationResult = boolean | string;\n\nexport type ValidationRule<T = unknown> = (\n value: T,\n model: object\n) => ValidationResult;\n\nexport type ValidationRules<TModel extends object> = {\n [TPath in keyof TModel & string]?: readonly ValidationRule[];\n} & Record<string, readonly ValidationRule[] | undefined>;\n\nexport interface FieldValidationResult {\n valid: boolean;\n errors: string[];\n}\n\nexport interface FormValidationResult {\n valid: boolean;\n errors: Record<string, string[]>;\n}\n\nexport interface FormController<TModel extends object> {\n readonly model: TModel;\n readonly errors: Record<string, string[]>;\n validate(): FormValidationResult;\n validateField(path: string): FieldValidationResult;\n resetErrors(): void;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction runRule(\n rule: ValidationRule,\n value: unknown,\n model: object\n): string | undefined {\n try {\n const result = rule(value, model);\n if (result === true) {\n return undefined;\n }\n return result === false ? 'Validation failed' : result;\n } catch (error) {\n return errorMessage(error);\n }\n}\n\nexport function required(message = 'This field is required'): ValidationRule {\n return (value) => {\n if (value === null || value === undefined) {\n return message;\n }\n if (typeof value === 'string' && value.trim().length === 0) {\n return message;\n }\n if (Array.isArray(value) && value.length === 0) {\n return message;\n }\n return true;\n };\n}\n\nexport function minLength(\n length: number,\n message = `Must be at least ${length} characters`\n): ValidationRule {\n return (value) =>\n typeof value === 'string' && value.length >= length ? true : message;\n}\n\nexport function validate(rule: ValidationRule): ValidationRule {\n return rule;\n}\n\nexport function createForm<TModel extends object>(\n model: TModel,\n rules: ValidationRules<TModel>\n): FormController<TModel> {\n const errors: Record<string, string[]> = {};\n\n const validateField = (path: string): FieldValidationResult => {\n const fieldRules = rules[path] ?? [];\n const value = getModelValue(model as Record<string, unknown>, path);\n const fieldErrors = fieldRules\n .map((rule) => runRule(rule, value, model))\n .filter((message): message is string => message !== undefined);\n\n if (fieldErrors.length === 0) {\n delete errors[path];\n } else {\n errors[path] = fieldErrors;\n }\n\n return { valid: fieldErrors.length === 0, errors: fieldErrors };\n };\n\n return {\n model,\n errors,\n validate(): FormValidationResult {\n const allErrors: Record<string, string[]> = {};\n Object.keys(rules).forEach((path) => {\n const result = validateField(path);\n if (!result.valid) {\n allErrors[path] = result.errors;\n }\n });\n return { valid: Object.keys(allErrors).length === 0, errors: allErrors };\n },\n validateField,\n resetErrors(): void {\n Object.keys(errors).forEach((path) => delete errors[path]);\n },\n };\n}\n",
6
- "import { OneApp, AppOptions } from './core/app';\nimport type { ComponentProps } from './core/component';\n\n// 导出核心功能\nexport * from './core';\n\n// 导出路由功能\nexport * from './router';\n\n// 创建应用实例的主函数\nexport function createApp<\n TState extends object = Record<string, unknown>,\n TConfig extends object = Record<string, unknown>,\n TRootProps extends ComponentProps = ComponentProps,\n>(\n options: AppOptions<TState, TConfig, TRootProps> = {}\n): OneApp<TState, TConfig, TRootProps> {\n return new OneApp(options);\n}\n\n// 导出框架名称和版本\nexport const version = '0.1.0';\nexport const name = '@geektech/transone';\n"
6
+ "import { OneApp, AppOptions } from './core/app';\nimport type { ComponentProps } from './core/component';\n\n// 导出核心功能\nexport * from './core';\n\n// 导出路由功能\nexport * from './router';\n\n// 导出跨端请求模块\nexport * from './request';\n\n// 创建应用实例的主函数\nexport function createApp<\n TState extends object = Record<string, unknown>,\n TConfig extends object = Record<string, unknown>,\n TRootProps extends ComponentProps = ComponentProps,\n>(\n options: AppOptions<TState, TConfig, TRootProps> = {}\n): OneApp<TState, TConfig, TRootProps> {\n return new OneApp(options);\n}\n\n// 导出框架名称和版本\nexport const version = '0.2.0';\nexport const name = 'transone';\n"
7
7
  ],
8
- "mappings": "4tBA+BA,SAAS,CAAY,CAAC,EAAwB,CAC5C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAG9D,SAAS,CAAO,CACd,EACA,EACA,EACoB,CACpB,GAAI,CACF,IAAM,EAAS,EAAK,EAAO,CAAK,EAChC,GAAI,IAAW,GACb,OAEF,OAAO,IAAW,GAAQ,oBAAsB,EAChD,MAAO,EAAO,CACd,OAAO,EAAa,CAAK,GAItB,SAAS,CAAQ,CAAC,EAAU,yBAA0C,CAC3E,MAAO,CAAC,IAAU,CAChB,GAAI,IAAU,MAAQ,IAAU,OAC9B,OAAO,EAET,GAAI,OAAO,IAAU,UAAY,EAAM,KAAK,EAAE,SAAW,EACvD,OAAO,EAET,GAAI,MAAM,QAAQ,CAAK,GAAK,EAAM,SAAW,EAC3C,OAAO,EAET,MAAO,IAIJ,SAAS,CAAS,CACvB,EACA,EAAU,oBAAoB,eACd,CAChB,MAAO,CAAC,IACN,OAAO,IAAU,UAAY,EAAM,QAAU,EAAS,GAAO,EAG1D,SAAS,CAAQ,CAAC,EAAsC,CAC7D,OAAO,EAGF,SAAS,CAAiC,CAC/C,EACA,EACwB,CACxB,IAAM,EAAmC,CAAC,EAEpC,EAAgB,CAAC,IAAwC,CAC7D,IAAM,EAAa,EAAM,IAAS,CAAC,EAC7B,EAAQ,EAAc,EAAkC,CAAI,EAC5D,EAAc,EACjB,IAAI,CAAC,IAAS,EAAQ,EAAM,EAAO,CAAK,CAAC,EACzC,OAAO,CAAC,IAA+B,IAAY,MAAS,EAE/D,GAAI,EAAY,SAAW,EACzB,OAAO,EAAO,GAEd,OAAO,GAAQ,EAGjB,MAAO,CAAE,MAAO,EAAY,SAAW,EAAG,OAAQ,CAAY,GAGhE,MAAO,CACL,QACA,SACA,QAAQ,EAAyB,CAC/B,IAAM,EAAsC,CAAC,EAO7C,OANA,OAAO,KAAK,CAAK,EAAE,QAAQ,CAAC,IAAS,CACnC,IAAM,EAAS,EAAc,CAAI,EACjC,GAAI,CAAC,EAAO,MACV,EAAU,GAAQ,EAAO,OAE5B,EACM,CAAE,MAAO,OAAO,KAAK,CAAS,EAAE,SAAW,EAAG,OAAQ,CAAU,GAEzE,gBACA,WAAW,EAAS,CAClB,OAAO,KAAK,CAAM,EAAE,QAAQ,CAAC,IAAS,OAAO,EAAO,EAAK,EAE7D,EC3GK,SAAS,CAIf,CACC,EAAmD,CAAC,EACf,CACrC,OAAO,IAAI,EAAO,CAAO,EAIpB,IAAM,EAAU,QACV,EAAO",
9
- "debugId": "4FA5C6C6C6CCA20664756E2164756E21",
8
+ "mappings": "i2BA+BA,SAAS,CAAY,CAAC,EAAwB,CAC5C,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EAG9D,SAAS,CAAO,CACd,EACA,EACA,EACoB,CACpB,GAAI,CACF,IAAM,EAAS,EAAK,EAAO,CAAK,EAChC,GAAI,IAAW,GACb,OAEF,OAAO,IAAW,GAAQ,oBAAsB,EAChD,MAAO,EAAO,CACd,OAAO,EAAa,CAAK,GAItB,SAAS,CAAQ,CAAC,EAAU,yBAA0C,CAC3E,MAAO,CAAC,IAAU,CAChB,GAAI,IAAU,MAAQ,IAAU,OAC9B,OAAO,EAET,GAAI,OAAO,IAAU,UAAY,EAAM,KAAK,EAAE,SAAW,EACvD,OAAO,EAET,GAAI,MAAM,QAAQ,CAAK,GAAK,EAAM,SAAW,EAC3C,OAAO,EAET,MAAO,IAIJ,SAAS,CAAS,CACvB,EACA,EAAU,oBAAoB,eACd,CAChB,MAAO,CAAC,IACN,OAAO,IAAU,UAAY,EAAM,QAAU,EAAS,GAAO,EAG1D,SAAS,CAAQ,CAAC,EAAsC,CAC7D,OAAO,EAGF,SAAS,CAAiC,CAC/C,EACA,EACwB,CACxB,IAAM,EAAmC,CAAC,EAEpC,EAAgB,CAAC,IAAwC,CAC7D,IAAM,EAAa,EAAM,IAAS,CAAC,EAC7B,EAAQ,EAAc,EAAkC,CAAI,EAC5D,EAAc,EACjB,IAAI,CAAC,IAAS,EAAQ,EAAM,EAAO,CAAK,CAAC,EACzC,OAAO,CAAC,IAA+B,IAAY,MAAS,EAE/D,GAAI,EAAY,SAAW,EACzB,OAAO,EAAO,GAEd,OAAO,GAAQ,EAGjB,MAAO,CAAE,MAAO,EAAY,SAAW,EAAG,OAAQ,CAAY,GAGhE,MAAO,CACL,QACA,SACA,QAAQ,EAAyB,CAC/B,IAAM,EAAsC,CAAC,EAO7C,OANA,OAAO,KAAK,CAAK,EAAE,QAAQ,CAAC,IAAS,CACnC,IAAM,EAAS,EAAc,CAAI,EACjC,GAAI,CAAC,EAAO,MACV,EAAU,GAAQ,EAAO,OAE5B,EACM,CAAE,MAAO,OAAO,KAAK,CAAS,EAAE,SAAW,EAAG,OAAQ,CAAU,GAEzE,gBACA,WAAW,EAAS,CAClB,OAAO,KAAK,CAAM,EAAE,QAAQ,CAAC,IAAS,OAAO,EAAO,EAAK,EAE7D,ECxGK,SAAS,CAIf,CACC,EAAmD,CAAC,EACf,CACrC,OAAO,IAAI,EAAO,CAAO,EAIpB,IAAM,EAAU,QACV,EAAO",
9
+ "debugId": "67A3AA10CDAABA5564756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -0,0 +1,12 @@
1
+ import type { RequestAdapter, RequestConfig, RequestResponse } from '../types';
2
+ /**
3
+ * Web 端适配器(策略):基于 fetch。
4
+ *
5
+ * - 超时:AbortController + timer,超时归类 TIMEOUT
6
+ * - 取消:config.signal 与超时共用同一个 AbortController,外部取消归类 ABORTED
7
+ * - 响应体:arraybuffer 返回 ArrayBuffer;json(默认)尝试解析、失败回退原文;text 返回原文
8
+ */
9
+ export declare class FetchAdapter implements RequestAdapter {
10
+ readonly platform: "web";
11
+ request<T>(config: RequestConfig<T>): Promise<RequestResponse<T>>;
12
+ }
@@ -0,0 +1,15 @@
1
+ import type { RequestAdapter, RequestAdapterResolver, RequestConfig, RequestPlatform } from '../types';
2
+ export { detectPlatform } from './platform';
3
+ export type { MiniProgramRequestApi } from './platform';
4
+ export type { MiniProgramDialect } from './mp';
5
+ /** 各端适配器注册表:'auto' 不在此列,由运行时探测决定 */
6
+ export declare const adapters: Record<Exclude<RequestPlatform, 'auto'>, RequestAdapter>;
7
+ /** 按目标端创建适配器;不支持的端抛 UNSUPPORTED_PLATFORM */
8
+ export declare function createAdapter(platform: Exclude<RequestPlatform, 'auto'>): RequestAdapter;
9
+ /**
10
+ * 解析请求应使用的适配器(优先级从高到低):
11
+ * 1. 请求级 config.platform(显式指定非 auto 时)
12
+ * 2. 实例级自定义 adapter(对象或解析函数)
13
+ * 3. 实例级默认 platform;仍为 auto 时运行时探测
14
+ */
15
+ export declare function resolveAdapter(config: RequestConfig, instanceAdapter?: RequestAdapter | RequestAdapterResolver, instancePlatform?: RequestPlatform): Promise<RequestAdapter>;
@@ -0,0 +1,34 @@
1
+ import type { RequestAdapter, RequestConfig, RequestResponse } from '../types';
2
+ /**
3
+ * 小程序差异层:微信 / 阿里 / 字节的请求 API 语义一致(wx.request /
4
+ * my.request / tt.request),仅字段名与回调形状不同。与 CLI 的 MpDialect
5
+ * 同思路,把差异收敛为参数化方言,避免三个适配器重复实现。
6
+ */
7
+ export interface MiniProgramDialect {
8
+ /** 目标端标识 */
9
+ platform: 'weixin' | 'alipay' | 'bytedance';
10
+ /** 全局对象名:wx / my / tt */
11
+ globalName: 'wx' | 'my' | 'tt';
12
+ /** 请求参数中请求头字段名:微信/字节 header,阿里 headers */
13
+ headerField: 'header' | 'headers';
14
+ /** 成功回调中状态码字段:微信/字节 statusCode,阿里 status */
15
+ statusField: 'statusCode' | 'status';
16
+ /** 成功回调中响应头字段名:微信/字节 header,阿里 headers */
17
+ responseHeaderField: 'header' | 'headers';
18
+ }
19
+ export declare const WEIXIN_DIALECT: MiniProgramDialect;
20
+ export declare const ALIPAY_DIALECT: MiniProgramDialect;
21
+ export declare const BYTEDANCE_DIALECT: MiniProgramDialect;
22
+ /**
23
+ * 小程序端适配器(策略):wx.request / my.request / tt.request 的统一封装。
24
+ *
25
+ * - 超时:手动 timer + 底层任务 abort,三端行为一致;成功/失败回调都会清理 timer
26
+ * - 取消:config.signal 触发时 abort 底层任务
27
+ * - 失败归一化:按平台 errMsg 关键字归类 TIMEOUT / ABORTED / NETWORK_ERROR
28
+ */
29
+ export declare class MiniProgramAdapter implements RequestAdapter {
30
+ private readonly dialect;
31
+ readonly platform: 'weixin' | 'alipay' | 'bytedance';
32
+ constructor(dialect: MiniProgramDialect);
33
+ request<T>(config: RequestConfig<T>): Promise<RequestResponse<T>>;
34
+ }
@@ -0,0 +1,18 @@
1
+ import type { DetectedPlatform } from '../types';
2
+ /** 小程序请求全局的公共形状(wx.request / my.request / tt.request) */
3
+ export interface MiniProgramRequestApi {
4
+ request?: (options: Record<string, unknown>) => {
5
+ abort?: () => void;
6
+ };
7
+ }
8
+ /**
9
+ * 读取小程序请求全局(wx / my / tt)。
10
+ * 通过全局对象属性访问而非直接引用全局名,避免污染全局声明、
11
+ * 也避免与用户安装的小程序官方类型(如 miniprogram-api-typings)冲突。
12
+ */
13
+ export declare function getMiniProgramApi(name: 'wx' | 'my' | 'tt'): MiniProgramRequestApi | null;
14
+ /**
15
+ * 运行时探测目标端:
16
+ * 小程序全局优先(wx → my → tt),其次 Web fetch;均不可用返回 'unknown'。
17
+ */
18
+ export declare function detectPlatform(): DetectedPlatform;
@@ -0,0 +1,33 @@
1
+ import type { RequestConfig, RequestResponse } from './types';
2
+ /**
3
+ * 统一请求错误码:
4
+ * - NETWORK_ERROR:网络层失败(断网、DNS、连接被拒等)
5
+ * - TIMEOUT:超时
6
+ * - ABORTED:被 AbortSignal 取消
7
+ * - BAD_REQUEST:配置非法(缺少 url、方法不支持等)
8
+ * - UNSUPPORTED_PLATFORM:当前环境没有可用的请求 API,或指定了不支持的端
9
+ * - UNKNOWN:无法归类的失败
10
+ */
11
+ export type RequestErrorCode = 'NETWORK_ERROR' | 'TIMEOUT' | 'ABORTED' | 'BAD_REQUEST' | 'UNSUPPORTED_PLATFORM' | 'UNKNOWN';
12
+ export interface RequestErrorOptions {
13
+ code: RequestErrorCode;
14
+ message: string;
15
+ /** 出错的请求配置 */
16
+ config: RequestConfig;
17
+ /** 出错时已拿到的响应(如响应处理阶段失败) */
18
+ response?: RequestResponse;
19
+ /** 底层原因(原生异常 / 平台 fail 对象等) */
20
+ cause?: unknown;
21
+ }
22
+ /**
23
+ * 统一请求错误:适配器与拦截器抛出的错误全部归一化为该类型,
24
+ * 便于调用方按 code 分支处理(超时重试、取消忽略、网络提示等)。
25
+ */
26
+ export declare class RequestError extends Error {
27
+ readonly code: RequestErrorCode;
28
+ readonly config: RequestConfig;
29
+ readonly response?: RequestResponse;
30
+ readonly cause?: unknown;
31
+ constructor(options: RequestErrorOptions);
32
+ }
33
+ export declare function isRequestError(error: unknown): error is RequestError;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * request 模块纯函数工具:URL 拼接、query 序列化、请求头合并、请求体序列化。
3
+ * 不依赖任何平台全局,便于单测。
4
+ */
5
+ import type { HeaderValue, HttpMethod } from './types';
6
+ /** 归一化 HTTP 方法为大写;缺省为 GET,非法方法抛错 */
7
+ export declare function normalizeMethod(method: string | undefined): HttpMethod;
8
+ /** 是否为带协议的绝对地址(http:// / https:// 等) */
9
+ export declare function isAbsoluteURL(url: string): boolean;
10
+ /** 拼接 baseURL 与相对地址,去除重复斜杠;绝对地址直接返回 */
11
+ export declare function combineURLs(baseURL: string | undefined, url: string): string;
12
+ /**
13
+ * 序列化 query 参数:null / undefined 跳过,数组展开为重复键,
14
+ * Date 转 ISO 字符串,对象 JSON 序列化。
15
+ */
16
+ export declare function serializeParams(params: Record<string, unknown> | undefined): string;
17
+ /** 拼接完整请求地址:baseURL + url + query 参数 */
18
+ export declare function buildURL(baseURL: string | undefined, url: string, params: Record<string, unknown> | undefined): string;
19
+ /**
20
+ * 大小写不敏感合并请求头:多个来源按顺序合并,后出现的同名头(忽略大小写)
21
+ * 覆盖先前的,键名保留后出现来源的原始写法。
22
+ */
23
+ export declare function mergeHeaders(...sources: Array<Record<string, HeaderValue> | undefined>): Record<string, string>;
24
+ /**
25
+ * 序列化请求体(Web 端):
26
+ * - GET / HEAD 无请求体
27
+ * - 字符串、FormData、Blob、ArrayBuffer / TypedArray 原样透传
28
+ * - 普通对象 / 数组 JSON 序列化,并自动设置 Content-Type: application/json
29
+ */
30
+ export declare function serializeBody(data: unknown, headers: Record<string, string>, method: HttpMethod): BodyInit | undefined;
@@ -0,0 +1,19 @@
1
+ import { Request } from './request';
2
+ import type { RequestOptions } from './types';
3
+ /** 创建独立请求实例;不传配置时等价于使用默认实例 */
4
+ export declare function createRequest(options?: RequestOptions): Request;
5
+ /**
6
+ * 全局默认请求实例:直接使用无需创建。
7
+ * ```ts
8
+ * import { request } from 'transone/request';
9
+ * const res = await request.get('/api/items');
10
+ * ```
11
+ */
12
+ export declare const request: Request;
13
+ export { Request } from './request';
14
+ export { InterceptorManager } from './interceptors';
15
+ export { RequestError, isRequestError } from './errors';
16
+ export type { RequestErrorCode, RequestErrorOptions } from './errors';
17
+ export { adapters, createAdapter, detectPlatform, resolveAdapter, } from './adapters';
18
+ export type { MiniProgramDialect, MiniProgramRequestApi } from './adapters';
19
+ export type { DetectedPlatform, HeaderValue, HttpMethod, InterceptorFulfilled, InterceptorHandler, InterceptorRejected, RequestAdapter, RequestAdapterResolver, RequestConfig, RequestDataType, RequestOptions, RequestPlatform, RequestResponse, RequestResponseType, } from './types';
@@ -0,0 +1,4 @@
1
+ import{Fa as a,Ga as b,Ha as c,Ia as d,Ja as e,Ka as f,La as g,Ma as h,Na as i,Oa as j}from"../index-xp7y2crt.js";export{g as InterceptorManager,h as Request,a as RequestError,d as adapters,e as createAdapter,i as createRequest,c as detectPlatform,b as isRequestError,j as request,f as resolveAdapter};
2
+
3
+ //# debugId=3E481CB7C031442F64756E2164756E21
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [
5
+ ],
6
+ "mappings": "",
7
+ "debugId": "3E481CB7C031442F64756E2164756E21",
8
+ "names": []
9
+ }
@@ -0,0 +1,13 @@
1
+ import type { InterceptorFulfilled, InterceptorHandler, InterceptorRejected } from './types';
2
+ /**
3
+ * 拦截器管理器:维护同类型(请求 / 响应)拦截器列表。
4
+ * - use 注册并返回 id,eject 按 id 移除(软删除,保留占位)
5
+ * - forEach 跳过已移除的项
6
+ */
7
+ export declare class InterceptorManager<T> {
8
+ private readonly handlers;
9
+ use(onFulfilled?: InterceptorFulfilled<T>, onRejected?: InterceptorRejected): number;
10
+ eject(id: number): void;
11
+ clear(): void;
12
+ forEach(fn: (handler: InterceptorHandler<T>, id: number) => void): void;
13
+ }
@@ -0,0 +1,43 @@
1
+ import { InterceptorManager } from './interceptors';
2
+ import type { RequestConfig, RequestOptions, RequestResponse } from './types';
3
+ /**
4
+ * 统一请求客户端:跨端请求入口。
5
+ *
6
+ * 职责:
7
+ * - 实例级默认值(baseURL / headers / timeout / platform 等)与单次配置合并
8
+ * - 请求拦截器(注册顺序)→ 平台适配器 → 响应拦截器(后注册先执行)的链路编排
9
+ * - 目标端解析:config.platform > 实例 adapter > 实例 platform > 运行时探测
10
+ *
11
+ * 用法:
12
+ * ```ts
13
+ * const http = createRequest({ baseURL: '/api', timeout: 10000 });
14
+ * http.interceptors.request.use((config) => {
15
+ * config.headers.Authorization = `Bearer ${token}`;
16
+ * return config;
17
+ * });
18
+ * const res = await http.get<{ list: Item[] }>('/items');
19
+ * ```
20
+ */
21
+ export declare class Request {
22
+ /** 请求 / 响应拦截器管理器 */
23
+ readonly interceptors: {
24
+ request: InterceptorManager<RequestConfig>;
25
+ response: InterceptorManager<RequestResponse>;
26
+ };
27
+ private readonly instanceDefaults;
28
+ private readonly instanceAdapter?;
29
+ private readonly instancePlatform?;
30
+ constructor(options?: RequestOptions);
31
+ /** 发起请求:合并配置 → 请求拦截器 → 适配器 → 响应拦截器 */
32
+ request<T = unknown>(config: RequestConfig<T>): Promise<RequestResponse<T>>;
33
+ get<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<RequestResponse<T>>;
34
+ delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<RequestResponse<T>>;
35
+ head<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<RequestResponse<T>>;
36
+ options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<RequestResponse<T>>;
37
+ post<T = unknown>(url: string, data?: T, config?: Omit<RequestConfig<T>, 'url' | 'method' | 'data'>): Promise<RequestResponse<T>>;
38
+ put<T = unknown>(url: string, data?: T, config?: Omit<RequestConfig<T>, 'url' | 'method' | 'data'>): Promise<RequestResponse<T>>;
39
+ patch<T = unknown>(url: string, data?: T, config?: Omit<RequestConfig<T>, 'url' | 'method' | 'data'>): Promise<RequestResponse<T>>;
40
+ private dispatch;
41
+ /** 合并实例级默认值与单次配置,并校验 url / method */
42
+ private mergeConfig;
43
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * request 模块公共类型:跨端(Web / 微信 / 阿里 / 字节小程序)统一请求模型。
3
+ */
4
+ /** 支持的 HTTP 方法 */
5
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
6
+ /**
7
+ * 目标端。'auto' 表示运行时按环境自动探测(默认)。
8
+ * 各端对应请求 API:Web fetch / 微信 wx.request / 阿里 my.request / 字节 tt.request。
9
+ */
10
+ export type RequestPlatform = 'auto' | 'web' | 'weixin' | 'alipay' | 'bytedance';
11
+ /** 运行时探测结果;探测不到任何受支持环境时为 'unknown' */
12
+ export type DetectedPlatform = Exclude<RequestPlatform, 'auto'> | 'unknown';
13
+ /** 响应数据解析方式:json 自动解析(失败回退原文),text 返回原始字符串 */
14
+ export type RequestDataType = 'json' | 'text';
15
+ /** 响应数据类型(小程序端 responseType 语义) */
16
+ export type RequestResponseType = 'text' | 'arraybuffer';
17
+ export type HeaderValue = string | number | boolean | undefined;
18
+ /**
19
+ * 单次请求配置。
20
+ * 未填写的字段回退到实例级默认值(RequestOptions);实例级也没有的字段使用平台默认。
21
+ */
22
+ export interface RequestConfig<T = unknown> {
23
+ /** 请求地址;以协议(http:// / https:// 等)开头时忽略 baseURL */
24
+ url: string;
25
+ /** HTTP 方法,默认 GET */
26
+ method?: HttpMethod | Lowercase<HttpMethod>;
27
+ /** 基础地址,与 url 拼接;仅对相对地址生效 */
28
+ baseURL?: string;
29
+ /** 请求头,合并到实例级默认请求头之上(大小写不敏感,后者覆盖前者) */
30
+ headers?: Record<string, HeaderValue>;
31
+ /** URL query 参数,序列化追加到地址后 */
32
+ params?: Record<string, unknown>;
33
+ /** 请求体:普通对象 / 数组自动 JSON 序列化并设置 Content-Type */
34
+ data?: T;
35
+ /** 超时(毫秒);0 / 缺省表示不超时 */
36
+ timeout?: number;
37
+ /** 响应解析方式,默认 json */
38
+ dataType?: RequestDataType;
39
+ /** 响应数据类型,默认 text */
40
+ responseType?: RequestResponseType;
41
+ /** 取消信号(AbortSignal);小程序端通过 abort 底层请求任务实现 */
42
+ signal?: AbortSignal;
43
+ /** 本次请求的目标端覆盖;缺省继承实例级配置,默认 auto 自动探测 */
44
+ platform?: RequestPlatform;
45
+ /** Web 端:跨域请求携带凭证(等价 credentials: 'include') */
46
+ withCredentials?: boolean;
47
+ /** Web 端:fetch credentials,显式设置时优先于 withCredentials */
48
+ credentials?: RequestCredentials;
49
+ /** 透传平台特有选项(如 wx.request 的 enableHttp2 / enableChunked 等) */
50
+ [key: string]: unknown;
51
+ }
52
+ /**
53
+ * 统一响应:各端原始响应(fetch Response / wx success 等)归一化后的形状。
54
+ * HTTP 4xx/5xx 不视为异常(与小程序端 success 语义一致),由调用方按 statusCode 处理。
55
+ */
56
+ export interface RequestResponse<T = unknown> {
57
+ /** 响应体:dataType json 时已尝试 JSON.parse */
58
+ data: T;
59
+ /** HTTP 状态码 */
60
+ statusCode: number;
61
+ /** 状态文本(Web 端有,小程序端为空) */
62
+ statusText?: string;
63
+ /** 响应头(键名保持平台原始大小写) */
64
+ headers: Record<string, string>;
65
+ /** 请求最终使用的配置(含实例级默认值合并结果) */
66
+ config: RequestConfig;
67
+ /** 小程序端返回的 cookie(微信 / 字节) */
68
+ cookies?: string[];
69
+ /** 平台原始 errMsg(如有) */
70
+ errMsg?: string;
71
+ }
72
+ /** 拦截器成功回调:可返回原值 / 新值 / Promise */
73
+ export type InterceptorFulfilled<T> = (value: T) => T | Promise<T>;
74
+ /** 拦截器失败回调:处理后可返回一个值恢复流程,或再次抛出 */
75
+ export type InterceptorRejected = (error: unknown) => unknown;
76
+ export interface InterceptorHandler<T> {
77
+ onFulfilled?: InterceptorFulfilled<T>;
78
+ onRejected?: InterceptorRejected;
79
+ }
80
+ /**
81
+ * 平台适配器(策略):每种目标端一个实现。
82
+ * 统一输入 RequestConfig,输出归一化 RequestResponse;失败抛出 RequestError。
83
+ */
84
+ export interface RequestAdapter {
85
+ readonly platform: Exclude<RequestPlatform, 'auto'>;
86
+ request<T>(config: RequestConfig<T>): Promise<RequestResponse<T>>;
87
+ }
88
+ /** 自定义适配器解析函数:根据请求配置返回适配器 */
89
+ export type RequestAdapterResolver = (config: RequestConfig) => RequestAdapter | Promise<RequestAdapter>;
90
+ /**
91
+ * 实例级默认配置:字段语义与 RequestConfig 一致,作为默认值合并到每次请求。
92
+ */
93
+ export interface RequestOptions {
94
+ baseURL?: string;
95
+ headers?: Record<string, HeaderValue>;
96
+ params?: Record<string, unknown>;
97
+ timeout?: number;
98
+ dataType?: RequestDataType;
99
+ responseType?: RequestResponseType;
100
+ /** 默认目标端,默认 auto(运行时探测) */
101
+ platform?: RequestPlatform;
102
+ /** 自定义适配器(对象或解析函数),优先级高于 platform */
103
+ adapter?: RequestAdapter | RequestAdapterResolver;
104
+ }
@@ -1,4 +1,4 @@
1
- import{Aa as e,wa as a,xa as b,ya as c,za as d}from"../index-3t506ckz.js";import"../index-mbmajrpr.js";export{b as Router,c as RouterLink,d as RouterView,e as createRouter,a as useRouter};
1
+ import{oa as a,pa as b,qa as c,ra as d,sa as e}from"../index-sf0hkgh3.js";import"../index-d5wsetxf.js";export{a as Router,b as RouterLink,c as RouterView,d as createRouter,e as useRouter};
2
2
 
3
- //# debugId=8DC4B118E770CA5A64756E2164756E21
3
+ //# debugId=C414913A2B2EE6FA64756E2164756E21
4
4
  //# sourceMappingURL=index.js.map
@@ -4,6 +4,6 @@
4
4
  "sourcesContent": [
5
5
  ],
6
6
  "mappings": "",
7
- "debugId": "8DC4B118E770CA5A64756E2164756E21",
7
+ "debugId": "C414913A2B2EE6FA64756E2164756E21",
8
8
  "names": []
9
9
  }
@@ -1,4 +1,4 @@
1
- import{Ba as f,Ca as m}from"../index-mbmajrpr.js";export{f as StyleManager,m as renderStyleSheet};
1
+ import{Da as f,Ea as m}from"../index-d5wsetxf.js";export{f as StyleManager,m as renderStyleSheet};
2
2
 
3
- //# debugId=93EF7DFA6C00C6E764756E2164756E21
3
+ //# debugId=17CBBF4901184E9464756E2164756E21
4
4
  //# sourceMappingURL=index.js.map
@@ -4,6 +4,6 @@
4
4
  "sourcesContent": [
5
5
  ],
6
6
  "mappings": "",
7
- "debugId": "93EF7DFA6C00C6E764756E2164756E21",
7
+ "debugId": "17CBBF4901184E9464756E2164756E21",
8
8
  "names": []
9
9
  }
@@ -0,0 +1,9 @@
1
+ /** 跨端尺寸单位换算:rpx(微信 750 设计宽)在 H5 端转换为视口相对值。
2
+ *
3
+ * 1rpx = 视口宽度 / 750,且视口宽度上限 750px(桌面端不再放大,页面按
4
+ * 750px 基准居中显示,与小程序设计宽一致)。
5
+ */
6
+ /** 根 CSS 变量:--cyy-rpx 为 1rpx 的等效长度 */
7
+ export declare const ROOT_RPX_RULE = ":root{--cyy-rpx:calc(min(100vw, 750px) / 750);}";
8
+ /** 把字符串/数值中的 `N rpx` 替换为 `calc(N * var(--cyy-rpx))` */
9
+ export declare function convertRpx(value: string | number): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "transone",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "TransOne 是跨端前端框架:一份 TypeScript 源码,编译期静态转换为 Web 与多端小程序原生产物,产物不携带框架运行时",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,6 +22,10 @@
22
22
  "./dom": {
23
23
  "import": "./dist/dom/index.js",
24
24
  "types": "./dist/dom/index.d.ts"
25
+ },
26
+ "./request": {
27
+ "import": "./dist/request/index.js",
28
+ "types": "./dist/request/index.d.ts"
25
29
  }
26
30
  },
27
31
  "scripts": {
@@ -42,6 +46,7 @@
42
46
  "miniprogram",
43
47
  "transpile"
44
48
  ],
49
+ "homepage": "https://github.com/geektech-team/transone/tree/main/packages/transone",
45
50
  "author": "Jimmie Max(Qianyu)",
46
51
  "license": "MIT",
47
52
  "engines": {
@@ -1,12 +0,0 @@
1
- import{Ba as ae,Ca as K}from"./index-mbmajrpr.js";var y=Symbol("is_reactive"),l=Symbol("is_readonly"),H=Symbol("is_ref"),F=["push","pop","shift","unshift","splice","sort","reverse"];function d(e,t){return Boolean(Reflect.get(e,t))}function h(e){return e!==null&&typeof e==="object"}class k{pending=new Set;flushing=!1;flushPromise=null;flushResolve=null;enqueue(e){if(this.pending.has(e))return;if(this.pending.add(e),!this.flushing)queueMicrotask(()=>this.flush())}flush(){if(this.flushing)return;this.flushing=!0;try{while(this.pending.size>0){let e=Array.from(this.pending);this.pending.clear();for(let t of e)if(t.active)t()}}finally{this.flushing=!1;let e=this.flushResolve;this.flushResolve=null,this.flushPromise=null,e?.()}}nextTick(){if(!this.flushing&&this.pending.size===0)return Promise.resolve();if(this.flushPromise)return this.flushPromise;return this.flushPromise=new Promise((e)=>{this.flushResolve=e}),this.flushPromise}}var fe=0,b=new k;function Ue(){return b.nextTick()}function Ke(){b.flush()}class f{static instance;activeEffect=null;effectStack=[];targetMap=new WeakMap;reactiveMap=new WeakMap;readonlyMap=new WeakMap;proxyMap=new WeakMap;constructor(){}static getInstance(){if(!f.instance)f.instance=new f;return f.instance}reactive(e){if(!h(e))return console.warn("reactive: target must be an object"),e;if(me(e))return e;if(this.reactiveMap.has(e))return this.reactiveMap.get(e);if(Array.isArray(e))return this.createReactiveArray(e);let t=new Proxy(e,{get:(n,r)=>{if(r===y)return!0;if(r===l)return!1;this.track(n,r);let o=Reflect.get(n,r);if(h(o)&&!d(o,l))return this.reactive(o);return o},set:(n,r,o)=>{if(d(n,l))return console.warn(`Cannot set property ${String(r)} on readonly object`),!1;let i=Reflect.get(n,r);if(h(o)&&!d(o,y)&&!d(o,l))o=this.reactive(o);let s=Reflect.set(n,r,o);if(i!==o)this.trigger(n,r);return s},deleteProperty:(n,r)=>{if(d(n,l))return console.warn(`Cannot delete property ${String(r)} on readonly object`),!1;let o=r in n,i=Reflect.deleteProperty(n,r);if(o)this.trigger(n,r);return i}});return this.reactiveMap.set(e,t),this.proxyMap.set(t,e),t}toRawValue(e){if(h(e)&&this.proxyMap.has(e))return this.proxyMap.get(e);return e}createReactiveArray(e){if(this.reactiveMap.has(e))return this.reactiveMap.get(e);let t=new Proxy(e,{get:(n,r)=>{if(r===y)return!0;if(r===l)return!1;this.track(n,r);let o=Reflect.get(n,r);if(typeof r==="string"&&(r==="includes"||r==="indexOf"||r==="lastIndexOf")){this.track(n,"length");for(let s=0;s<n.length;s++)this.track(n,String(s));let i=o;return(...s)=>{let a=i.apply(n,s);if(a===!1||a===-1){let c=n.map((u)=>this.toRawValue(u));return c[r].apply(c,s.map((u)=>this.toRawValue(u)))}return a}}if(typeof r==="string"&&F.includes(r))return(...i)=>{let a=o.apply(n,i);return this.trigger(n,"length"),this.trigger(n,r),a};if(h(o)&&!d(o,l))return this.reactive(o);return o},set:(n,r,o)=>{if(d(n,l))return console.warn(`Cannot set property ${String(r)} on readonly object`),!1;let i=Reflect.get(n,r);if(h(o)&&!d(o,y)&&!d(o,l))o=this.reactive(o);let s=Reflect.set(n,r,o);if(i!==o){if(this.trigger(n,r),typeof r==="string"&&!isNaN(Number(r)))this.trigger(n,"length")}return s},deleteProperty:(n,r)=>{if(d(n,l))return console.warn(`Cannot delete property ${String(r)} on readonly object`),!1;let o=r in n,i=Reflect.deleteProperty(n,r);if(o)this.trigger(n,r),this.trigger(n,"length");return i}});return this.reactiveMap.set(e,t),this.proxyMap.set(t,e),t}readonly(e){if(!h(e))return console.warn("readonly: target must be an object"),e;if(d(e,l))return e;if(this.readonlyMap.has(e))return this.readonlyMap.get(e);let t=new Proxy(e,{get:(n,r)=>{if(r===y)return!1;if(r===l)return!0;let o=Reflect.get(n,r);if(h(o))return this.readonly(o);return o},set:()=>(console.warn("Cannot set property on readonly object"),!1),deleteProperty:()=>(console.warn("Cannot delete property on readonly object"),!1)});return this.readonlyMap.set(e,t),t}effect(e,t){let{lazy:n=!1,scheduler:r,throwOnError:o=!1}=t||{},i=()=>{if(!i.active)return e();try{return this.cleanup(i),this.effectStack.push(i),this.activeEffect=i,e()}catch(s){if(o)throw s;console.error("Effect error:",s);return}finally{this.effectStack.pop(),this.activeEffect=this.effectStack[this.effectStack.length-1]??null}};if(i.id=fe++,i.deps=[],i.active=!0,i.scheduler=r,!n)i();return i}runWithEffect(e,t){this.effectStack.push(e),this.activeEffect=e;try{return t()}finally{this.effectStack.pop(),this.activeEffect=this.effectStack[this.effectStack.length-1]??null}}computed(e){let t=!0,n,r={},o=()=>{this.track(r,"value")},i=this.effect(()=>{n=e(),t=!1},{lazy:!0,scheduler:()=>{if(!t)t=!0,this.trigger(r,"value")}});return{get value(){if(t)i();return o(),n}}}cleanup(e){e.deps.forEach((t)=>{t.delete(e)}),e.deps.length=0}track(e,t){if(!this.activeEffect||!this.activeEffect.active)return;let n=this.targetMap.get(e);if(!n)n=new Map,this.targetMap.set(e,n);let r=n.get(t);if(!r)r=new Set,n.set(t,r);if(!r.has(this.activeEffect))r.add(this.activeEffect),this.activeEffect.deps.push(r)}trigger(e,t){let n=this.targetMap.get(e);if(!n)return;let r=n.get(t);if(!r)return;new Set(r).forEach((i)=>{if(i.active)if(i.scheduler)i.scheduler(i);else i()})}stop(e){if(e.active)this.cleanup(e),e.active=!1}}function O(e){return f.getInstance().reactive(e)}function We(e){return f.getInstance().readonly(e)}function g(e,t){return f.getInstance().effect(e,t)}function Fe(e){return f.getInstance().computed(e)}function Ge(e){let t={value:e};return Object.defineProperty(t,H,{configurable:!1,enumerable:!1,value:!0}),O(t)}function G(e){return h(e)&&Boolean(Reflect.get(e,H))}function qe(e){return G(e)?e.value:e}function v(e){f.getInstance().stop(e)}function j(e,t){if(!h(e)||t.has(e))return;if(t.add(e),Array.isArray(e)){e.forEach((n)=>j(n,t));return}Object.keys(e).forEach((n)=>{j(e[n],t)})}function ze(e,t,n={}){let r=f.getInstance(),o=G(e)?()=>e.value:e,i,s=null,a=()=>{if(!m.active)return;s?.(),s=null;let u=c();t(u,i,(C)=>{s=C}),i=u},c=g(()=>{let u=o();if(n.deep&&h(u))j(u,new Set);return u},{lazy:!0,scheduler:()=>{if(n.sync)a();else b.enqueue(m)}}),m=g(()=>{a()},{lazy:!0});if(n.immediate)a();else i=c();return()=>{r.stop(c),r.stop(m)}}function me(e){return h(e)&&d(e,y)}function Ye(e){return h(e)&&d(e,l)}function q(e){return typeof e==="object"&&e!==null&&"component"in e}function z(e){return typeof e==="object"&&e!==null&&"tag"in e&&e.tag!=="slot"}function Y(e){return typeof e==="object"&&e!==null&&"tag"in e&&e.tag==="slot"}function Ze(e,t,n,r,o,i){return{tag:e,props:t,children:n,listeners:r,key:o,directions:i}}function ge(e,t={}){return{tag:e,...t}}function p(e){return(t={})=>ge(e,t)}var T=p("div"),Je=p("span"),Xe=p("p"),et=p("button"),tt=p("input"),nt=p("section"),rt=p("main"),ot=p("header"),it=p("footer"),st=p("nav"),at=p("article"),pt=p("aside"),ct=p("h1"),ut=p("h2"),lt=p("h3"),dt=p("h4"),ht=p("h5"),ft=p("h6"),mt=p("strong"),gt=p("em"),vt=p("small"),yt=p("pre"),Rt=p("code"),Ct=p("blockquote"),bt=p("ul"),Et=p("ol"),xt=p("li"),Tt=p("a"),wt=p("img"),St=p("form"),Mt=p("label"),Lt=p("textarea"),Nt=p("select"),Pt=p("option"),At=p("table"),It=p("thead"),Ht=p("tbody"),kt=p("tr"),jt=p("th"),Ot=p("td");function Vt(e,t,n,r,o){return{component:e,props:t,children:n,key:r,directions:o}}function Bt(e,t,n){return{tag:"slot",props:{name:e},key:t,directions:n}}function _t(e,t,n){return e.map((r,o)=>{let i=t(r,o);if(typeof i==="string")throw Error("each render callback must return a VNode");return{...i,key:n(r,o)}})}function Z(e){let t=e.split(".");if(e.length===0||t.some((n)=>n.length===0||n==="__proto__"||n==="prototype"||n==="constructor"))throw Error(`Invalid model path "${e}"`);return t}function B(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function J(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ve(e){return typeof e==="string"?e:e.path}function Q(e,t){let n=e;for(let r of Z(t)){if(!B(n))throw Error(`Invalid model path "${t}"`);if(!J(n,r)){if(r in n)throw Error(`Invalid model path "${t}"`);return}n=n[r]}return n}function ye(e,t,n){let r=Z(t),o=e;for(let s of r.slice(0,-1)){if(!J(o,s)){if(s in o)throw Error(`Invalid model path "${t}"`);o[s]={}}else if(!B(o[s]))throw Error(`Invalid model path "${t}"`);let a=o[s];if(!B(a))throw Error(`Invalid model path "${t}"`);o=a}let i=r[r.length-1];o[i]=n}function V(e,t){if(typeof e!=="string"&&e.format)return e.format(t);return t===void 0||t===null?"":String(t)}function Re(e,t){if(typeof e!=="string"&&e.parse)return e.parse(t);return t}function Ce(e,t,n){if(e instanceof HTMLInputElement){if(e.type==="checkbox"){e.checked=Array.isArray(n)?n.some((r)=>String(r)===e.value):Boolean(n);return}if(e.type==="radio"){e.checked=n===e.value;return}e.value=V(t,n);return}if(e instanceof HTMLTextAreaElement){e.value=V(t,n);return}if(e instanceof HTMLSelectElement){if(e.multiple){let r=Array.isArray(n)?new Set(n.map(String)):new Set;for(let o=0;o<e.options.length;o+=1){let i=e.options.item(o);if(!i)continue;i.selected=r.has(i.value)}return}e.value=V(t,n)}}function be(e,t){if(e instanceof HTMLInputElement){if(e.type==="checkbox"){if(Array.isArray(t)){let n=t.filter((r)=>String(r)!==e.value);return e.checked?[...n,e.value]:n}return e.checked}if(e.type==="radio")return e.checked?e.value:t;return e.value}if(e instanceof HTMLTextAreaElement)return e.value;if(e instanceof HTMLSelectElement){if(!e.multiple)return e.value;let n=[];for(let r=0;r<e.selectedOptions.length;r+=1){let o=e.selectedOptions.item(r);if(o)n.push(o.value)}return n}return}class _{bindings=new WeakMap;bind(e,t,n){if(!this.isSupportedControl(e))return;let r=this.bindings.get(e);if(r&&this.sameBinding(r,t))return;this.cleanup(e);let o=ve(t),i=()=>Ce(e,t,Q(n,o)),s=e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement&&!["checkbox","radio"].includes(e.type)?"input":"change",a=()=>{let m=Q(n,o);ye(n,o,Re(t,be(e,m)))};e.addEventListener(s,a);let c=g(i);this.bindings.set(e,{binding:t,path:o,parse:typeof t==="string"?void 0:t.parse,format:typeof t==="string"?void 0:t.format,eventName:s,listener:a,effect:c})}cleanup(e){let t=this.bindings.get(e);if(!t)return;e.removeEventListener(t.eventName,t.listener),v(t.effect),this.bindings.delete(e)}isSupportedControl(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}sameBinding(e,t){if(typeof e.binding==="string"||typeof t==="string")return e.binding===t;return e.path===t.path&&e.parse===t.parse&&e.format===t.format}}function M(e){return/^on[A-Z]/.test(e)||/^on[a-z]/.test(e)}function X(e){return e.slice(2).toLowerCase()}function ee(e){let[t,...n]=e.split(".");return{eventName:t,modifiers:new Set(n)}}function te(e,t){let n=(r)=>{if(t.has("stop"))r.stopPropagation();if(t.has("prevent"))r.preventDefault();if(t.has("self")&&r.currentTarget!==r.target)return;if(t.has("once"))r.currentTarget.removeEventListener(r.type,n);e(r)};return n}function ne(e,t,n){let r=t.includes("-")?t:t.replace(/[A-Z]/g,(o)=>`-${o.toLowerCase()}`);e.setProperty(r,String(n))}var re="http://www.w3.org/2000/svg",Ee=new Set(["svg","g","defs","rect","circle","ellipse","line","polyline","polygon","path","text","tspan","textPath","use","symbol","marker","linearGradient","radialGradient","stop","pattern","mask","clipPath","foreignObject"]);class N{listeners=new WeakMap;effects=new WeakMap;modelBindings=new _;matches(e){return typeof e==="object"&&e!==null&&z(e)}mount(e,t){if(e.directions?.if===!1)return document.createComment("if");let n=Ee.has(e.tag)?document.createElementNS(re,e.tag):document.createElement(e.tag);return this.applyProps(n,{},e.props??{},t),this.updateListeners(n,{},this.collectListeners(e)),this.mountChildren(n,e,t),this.applyDirections(n,void 0,e.directions,t),n}patch(e,t,n,r){if(e.tag!==t.tag||n.nodeType===Node.COMMENT_NODE){let o=this.mount(t,r);return n.parentNode?.replaceChild(o,n),this.unmount(e,n,r),o}if(!(n instanceof Element))return n;if(t.directions?.if===!1){let o=document.createComment("if");return n.parentNode?.replaceChild(o,n),this.unmount(e,n,r),o}return this.applyProps(n,e.props??{},t.props??{},r),this.updateListeners(n,this.collectListeners(e),this.collectListeners(t)),this.updateChildren(n,e,t,r),this.applyDirections(n,e.directions,t.directions,r),n}unmount(e,t,n){if(!(t instanceof Element))return;this.effects.get(t)?.forEach((r)=>v(r)),this.effects.delete(t),this.listeners.get(t)?.forEach(({eventName:r,listener:o})=>{t.removeEventListener(r,o)}),this.listeners.delete(t),this.modelBindings.cleanup(t),this.unmountChildren(t,e,n)}mountChildren(e,t,n){(t.children??[]).forEach((r)=>{e.appendChild(n.renderer.mount(r,n))})}updateChildren(e,t,n,r){this.updateOrdinaryChildren(e,t.children??[],n.children??[],r)}unmountChildren(e,t,n){(t.children??[]).forEach((r,o)=>{let i=e.childNodes[o];if(i)n.renderer.unmount(r,i,n)})}applyProps(e,t,n,r){Object.keys(t).forEach((o)=>{if(M(o)||o in n)return;if(o==="className"||o==="class")e.removeAttribute("class");else if(o==="style")e.removeAttribute("style");else if(o==="value"&&typeof e==="object"&&e!==null&&"value"in e)e.value="";else e.removeAttribute(L(o))}),Object.entries(n).forEach(([o,i])=>{if(M(o))return;if(t[o]===i)return;if(o==="className"||o==="class"){if(e.namespaceURI===re)e.setAttribute("class",String(i??""));else e.className=String(i??"");return}if(o==="value"&&typeof e==="object"&&e!==null&&"value"in e){e.value=String(i??"");return}if(o==="style"&&typeof i==="object"&&i!==null){e.removeAttribute("style");let s=e.style;Object.entries(i).forEach(([a,c])=>{ne(s,a,c)});return}if(i===!1||i===void 0||i===null){e.removeAttribute(L(o));return}if(i===!0){e.setAttribute(L(o),"");return}if(typeof i==="string"&&r.templateEngine.hasExpressions(i)){this.setupReactiveAttribute(e,o,i,r);return}e.setAttribute(L(o),String(i))})}applyDirections(e,t,n,r){if(n&&"show"in n)e.style.display=n.show?"":"none";else if(t&&"show"in t)e.style.display="";if(!n?.model){this.modelBindings.cleanup(e);return}this.modelBindings.bind(e,n.model,r.templateEngine.state)}updateOrdinaryChildren(e,t,n,r){if(this.assertNoDuplicateKeys(t),this.assertNoDuplicateKeys(n),this.hasOnlyKeyedChildren(t,n)){this.updateKeyedChildren(e,t,n,r);return}let o=Math.min(t.length,n.length);for(let i=0;i<o;i+=1){let s=e.childNodes[i];if(!s){e.appendChild(r.renderer.mount(n[i],r));continue}r.renderer.patch(t[i],n[i],s,r)}for(let i=o;i<n.length;i+=1)e.appendChild(r.renderer.mount(n[i],r));for(let i=t.length-1;i>=n.length;i-=1){let s=e.childNodes[i];if(s){if(r.renderer.unmount(t[i],s,r),s.parentNode===e)e.removeChild(s)}}}updateKeyedChildren(e,t,n,r){let o=t.map((a,c)=>({vnode:a,node:e.childNodes[c],index:c})),i=new Map,s=new Set;o.forEach((a)=>{let c=this.getVNodeKey(a.vnode);if(c!==void 0&&a.node)i.set(c,{vnode:a.vnode,node:a.node,index:a.index})}),n.forEach((a,c)=>{let m=this.getVNodeKey(a),u=m===void 0?void 0:i.get(m),C;if(u)C=r.renderer.patch(u.vnode,a,u.node,r),s.add(u.index);else C=r.renderer.mount(a,r);let W=e.childNodes[c]??null;if(C!==W)e.insertBefore(C,W)}),o.forEach((a)=>{if(!a.node||s.has(a.index))return;if(r.renderer.unmount(a.vnode,a.node,r),a.node.parentNode===e)e.removeChild(a.node)})}hasOnlyKeyedChildren(e,t){return[...e,...t].every((n)=>this.getVNodeKey(n)!==void 0)}assertNoDuplicateKeys(e){let t=new Set;e.forEach((n)=>{let r=this.getVNodeKey(n);if(r===void 0)return;if(t.has(r))throw Error(`Duplicate key "${r}"`);t.add(r)})}getVNodeKey(e){if(typeof e==="string")return;return e.key}collectListeners(e){let t={};return Object.entries(e.props??{}).forEach(([n,r])=>{if(M(n)&&typeof r==="function")t[X(n)]=r}),{...t,...e.listeners??{}}}updateListeners(e,t,n){let r=this.listeners.get(e)??new Map,o=new Set(Object.keys(t)),i=new Set(Object.keys(n));o.forEach((s)=>{if(!i.has(s)||t[s]!==n[s]){let a=r.get(s);if(a)e.removeEventListener(a.eventName,a.listener),r.delete(s)}}),i.forEach((s)=>{if(!o.has(s)||t[s]!==n[s]){let{eventName:a,modifiers:c}=ee(s),m=te(n[s],c);e.addEventListener(a,m),r.set(s,{eventName:a,listener:m})}}),this.listeners.set(e,r)}setupReactiveAttribute(e,t,n,r){let o=g(()=>{e.setAttribute(t,r.templateEngine.evaluateTemplateValue(n))});this.trackEffect(e,o)}trackEffect(e,t){let n=this.effects.get(e)??new Set;n.add(t),this.effects.set(e,n)}}function L(e){if(e.startsWith("data")&&e.length>4)return`data${e.slice(4).replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`;if(e==="tabIndex"||e==="colSpan"||e==="htmlFor")return e.toLowerCase();return e}class w{strategies;constructor(){this.strategies=[new oe,new ie,new se,new N]}mount(e,t){return this.findStrategy(e).mount(e,t)}patch(e,t,n,r){let o=this.findStrategy(e),i=this.findStrategy(t);if(o!==i){let s=i.mount(t,r);return n.parentNode?.replaceChild(s,n),o.unmount(e,n,r),s}return o.patch(e,t,n,r)}unmount(e,t,n){this.findStrategy(e).unmount(e,t,n)}findStrategy(e){let t=this.strategies.find((n)=>n.matches(e));if(!t)throw Error("No render strategy found for vnode");return t}}class oe{matches(e){return typeof e==="string"}mount(e,t){return t.templateEngine.parseTemplate(e)}patch(e,t,n,r){if(e===t)return n;let o=this.mount(t,r);return n.parentNode?.replaceChild(o,n),o}unmount(){}}class ie{instances=new WeakMap;instanceNodes=new Map;emitterUnsubscribers=new WeakMap;matches(e){return typeof e==="object"&&e!==null&&q(e)}mount(e,t){if(e.directions?.if===!1)return document.createComment("if");let r=new e.component(this.createProps(e));if(t.appContext&&r.setAppContext)r.setAppContext(t.appContext);this.syncEmitters(r,e.emitters??{}),t.registerChild(r);let o=r.mountToNode();return this.trackInstanceNode(r,o),r.setElementChangeListener?.((i,s)=>{this.trackInstanceNode(r,i),this.trackInstanceNode(r,s)}),o}patch(e,t,n,r){if(n.nodeType===Node.COMMENT_NODE){let s=this.mount(t,r);return n.parentNode?.replaceChild(s,n),s}if(t.directions?.if===!1){let s=document.createComment("if");return n.parentNode?.replaceChild(s,n),this.unmount(e,n,r),s}let o=this.instances.get(n);if(o&&e.component===t.component){this.syncEmitters(o,t.emitters??{}),o.setProps(this.createProps(t));let s=o.getElement()??n;return this.trackInstanceNode(o,s),s}let i=this.mount(t,r);return n.parentNode?.replaceChild(i,n),this.unmount(e,n,r),i}unmount(e,t,n){let r=this.instances.get(t);if(r)this.clearEmitters(r),r.unmount(),this.clearInstanceNodes(r),n.unregisterChild(r)}createProps(e){return{...e.props??{},children:e.children??[]}}syncEmitters(e,t){let n=this.emitterUnsubscribers.get(e)??new Map;n.forEach(({listener:r,unsubscribe:o},i)=>{let s=t[i];if(!s||s!==r)o(),n.delete(i)}),Object.entries(t).forEach(([r,o])=>{if(n.get(r)?.listener===o)return;n.set(r,{listener:o,unsubscribe:e.on(r,o)})}),this.emitterUnsubscribers.set(e,n)}clearEmitters(e){this.emitterUnsubscribers.get(e)?.forEach(({unsubscribe:t})=>{t()}),this.emitterUnsubscribers.delete(e)}trackInstanceNode(e,t){this.instances.set(t,e);let n=this.instanceNodes.get(e)??new Set;n.add(t),this.instanceNodes.set(e,n)}clearInstanceNodes(e){this.instanceNodes.get(e)?.forEach((t)=>{this.instances.delete(t)}),this.instanceNodes.delete(e)}}class se{renderedChildren=new WeakMap;matches(e){return typeof e==="object"&&e!==null&&Y(e)}mount(e,t){if(e.directions?.if===!1)return document.createComment("if");let n=document.createElement("div");return n.setAttribute("data-slot",e.props.name),this.mountSlotChildren(n,this.resolveChildren(e,t),t),n}patch(e,t,n,r){if(n.nodeType===Node.COMMENT_NODE){let o=this.mount(t,r);return n.parentNode?.replaceChild(o,n),o}if(t.directions?.if===!1){let o=document.createComment("if");return n.parentNode?.replaceChild(o,n),this.unmount(e,n,r),o}if(n instanceof HTMLElement)n.setAttribute("data-slot",t.props.name),this.replaceSlotChildren(n,e,t,r);return n}unmount(e,t,n){if(!(t instanceof HTMLElement))return;this.unmountSlotChildren(t,n),this.renderedChildren.delete(t)}resolveChildren(e,t){return t.slots[e.props.name]??e.children??[]}replaceSlotChildren(e,t,n,r){let o=this.renderedChildren.get(e)??[],i=this.resolveChildren(n,r),s=Math.min(o.length,i.length);for(let a=0;a<s;a+=1){let c=e.childNodes[a];if(!c){e.appendChild(r.renderer.mount(i[a],r));continue}r.renderer.patch(o[a],i[a],c,r)}for(let a=s;a<i.length;a+=1)e.appendChild(r.renderer.mount(i[a],r));for(let a=o.length-1;a>=i.length;a-=1){let c=e.childNodes[a];if(c){if(r.renderer.unmount(o[a],c,r),c.parentNode===e)e.removeChild(c)}}this.renderedChildren.set(e,i)}mountSlotChildren(e,t,n){t.forEach((r)=>{e.appendChild(n.renderer.mount(r,n))}),this.renderedChildren.set(e,t)}unmountSlotChildren(e,t){(this.renderedChildren.get(e)??[]).forEach((r,o)=>{let i=e.childNodes[o];if(i)t.renderer.unmount(r,i,t)})}}class R{state;bindings=[];templateRegex=/{{(.*?)}}/g;constructor(e){this.state=e;if(!e||typeof e!=="object")throw Error("TemplateEngine requires a valid state object")}parseTemplate(e){if(typeof e!=="string")e=String(e);let t=document.createTextNode("");this.templateRegex.lastIndex=0;let n=Array.from(e.matchAll(this.templateRegex));if(n&&n.length>0)this.setupReactiveBindings(t,e,n);else t.textContent=e;return t}setupReactiveBindings(e,t,n){let r=new Set,o=this.evaluateTemplate(t,n,r);e.textContent=o;let i=g(()=>{try{let s=this.evaluateTemplate(t,n,r);if(e.textContent!==s)e.textContent=s}catch(s){console.error("Template update error:",s),e.textContent=`Error: ${s instanceof Error?s.message:"Unknown error"}`}});this.bindings.push({node:e,originalText:t,effect:i})}evaluateTemplate(e,t,n){let r=e;return t.forEach((o)=>{let i=o[1]?.trim();if(i){n.add(i);let s=this.getValueFromState(i),a=s===void 0||s===null?"":String(s);r=r.replace(o[0],a)}}),r}getValueFromState(e){if(!e)return;let t=e.split("."),n=this.state;for(let r of t){if(!n||typeof n!=="object")return;n=n[r]}return n}clearBindings(){this.bindings.forEach((e)=>{v(e.effect)}),this.bindings=[]}getBindingCount(){return this.bindings.length}hasExpressions(e){return this.templateRegex.lastIndex=0,this.templateRegex.test(e)}extractKeys(e){let t=[],n,r=new RegExp(this.templateRegex,"g");while((n=r.exec(e))!==null){let o=n[1]?.trim();if(o)t.push(o)}return t}evaluateTemplateValue(e){this.templateRegex.lastIndex=0;let t=Array.from(e.matchAll(this.templateRegex));if(!t||t.length===0)return e;let n=new Set;return this.evaluateTemplate(e,t,n)}}class S{props;vnode=null;el=null;renderer=new w;templateEngine;childComponents=new Set;eventListeners={};providers=new Map;updateEffect;appContext=null;parentComponent=null;elementChangeListener=null;styleManager;state;mounted=!1;constructor(e={}){this.props=e;this.styleManager=new ae,this.state=O(this.initState()??{}),this.templateEngine=new R(this.state),this.initStyles(),this.updateEffect=g(()=>{if(this.mounted)try{this.update()}catch(t){if(!this.dispatchError(t))throw t}},{throwOnError:!0,scheduler:(t)=>{b.enqueue(t)}})}mount(e){if(!e||!(e instanceof HTMLElement))throw Error("Invalid container element");try{e.appendChild(this.mountToNode())}catch(t){throw console.error("组件渲染错误:",t),t}}mountToNode(){if(this.mounted&&this.el)return this.el;return this.beforeMount(),this.el=f.getInstance().runWithEffect(this.updateEffect,()=>{try{return this.vnode=this.render(),this.renderer.mount(this.vnode,this.createRenderContext())}catch(e){if(this.dispatchError(e))return document.createComment("error-boundary");throw e}}),this.mounted=!0,this.onMounted(),this.el}update(){if(!this.el||!this.vnode)return;this.beforeUpdate();let e=this.vnode,t=this.el;if(this.el=f.getInstance().runWithEffect(this.updateEffect,()=>{let n=this.render(),r=this.renderer.patch(e,n,t,this.createRenderContext());return this.vnode=n,r}),t!==this.el)this.elementChangeListener?.(t,this.el);this.onUpdated()}unmount(){if(!this.mounted)return;if(this.beforeUnmount(),this.vnode&&this.el)this.renderer.unmount(this.vnode,this.el,this.createRenderContext());if(this.childComponents.clear(),Object.keys(this.eventListeners).forEach((e)=>{this.eventListeners[e].clear(),delete this.eventListeners[e]}),this.providers.clear(),this.parentComponent=null,this.elementChangeListener=null,this.templateEngine.clearBindings(),this.styleManager.destroy(),v(this.updateEffect),this.el?.parentNode)this.el.parentNode.removeChild(this.el);this.el=null,this.vnode=null,this.mounted=!1,this.onUnmounted()}setProps(e){if(this.props={...this.props,...e},this.mounted)b.enqueue(this.updateEffect)}setState(e){Object.assign(this.state,e)}setAppContext(e){this.appContext=e,this.childComponents.forEach((t)=>{t.setAppContext?.(e)})}setParentComponent(e){this.parentComponent=e}getParentComponent(){return this.parentComponent}setElementChangeListener(e){this.elementChangeListener=e}provide(e,t){this.providers.set(e,t)}inject(e,t){let n=this.resolveInjection(e);return n.found?n.value:t}resolveInjection(e){if(this.providers.has(e))return{found:!0,value:this.providers.get(e)};if(this.parentComponent?.resolveInjection)return this.parentComponent.resolveInjection(e);return this.resolveAppInjection(e)}getElement(){return this.el}beforeMount(){}onMounted(){}beforeUpdate(){}onUpdated(){}beforeUnmount(){}onUnmounted(){}dispatchError(e){let t=this.getParentComponent();while(t){let n=t;if(typeof n.onErrorCaptured==="function"){if(n.onErrorCaptured(e,this)===!1)return!0}t=t.getParentComponent?.()??null}return!1}getContext(){return this.appContext}get router(){return this.getRouterFrom(this.appContext)??this.getRouterFromGlobalApp()}emit(e,...t){this.eventListeners[e]?.forEach((n)=>{n(...t)})}on(e,t){if(!this.eventListeners[e])this.eventListeners[e]=new Set;return this.eventListeners[e].add(t),()=>this.off(e,t)}off(e,t){this.eventListeners[e]?.delete(t)}createRenderContext(){return{appContext:this.appContext,templateEngine:this.templateEngine,renderer:this.renderer,slots:this.collectSlots(),registerChild:(e)=>{this.childComponents.add(e),e.setParentComponent?.(this),e.setAppContext?.(this.appContext)},unregisterChild:(e)=>{this.childComponents.delete(e),e.setParentComponent?.(null)}}}collectSlots(){let e={default:[]};return(this.props.children??[]).forEach((n)=>{let r=this.getSlotName(n);if(!e[r])e[r]=[];e[r].push(this.normalizeSlotChild(n))}),e}getSlotName(e){if(typeof e==="string")return"default";return"slot"in e&&typeof e.slot==="string"?e.slot:"default"}normalizeSlotChild(e){if(typeof e==="string"||!("slot"in e))return e;let t={...e};return delete t.slot,t}getRouterFrom(e){if(!e||typeof e!=="object"||!("router"in e))return;return e.router}getRouterFromGlobalApp(){let e=globalThis.__APP__;return this.getRouterFrom(e)}resolveAppInjection(e){if(!this.appContext||typeof this.appContext!=="object")return{found:!1,value:void 0};return this.appContext.app?.resolveInjection?.(e)??{found:!1,value:void 0}}}var D=null;function pe(e){if(!e||!(e instanceof P))throw Error("Invalid router instance");D=e}function xe(){if(!D)throw Error("Router is not initialized. Please make sure you have installed the router plugin.");return D}function E(e){if(!e.startsWith("/"))return`/${e}`;return e||"/"}function A(e,t){let n=E(t.split("?")[0]);for(let i of e){if(i.path==="*")continue;let s=Te(i.path,n);if(s)return{route:i,params:s}}let r=e.find((i)=>i.path==="*");if(r)return{route:r,params:{pathMatch:n}};let o=e.find((i)=>i.path==="/");return o?{route:o,params:{}}:null}function Te(e,t){let n=ce(e),r=ce(t);if(n.length!==r.length)return null;let o={};for(let i=0;i<n.length;i+=1){let s=n[i],a=r[i];if(s.startsWith(":")){let c=s.slice(1);if(!c)return null;o[decodeURIComponent(c)]=decodeURIComponent(a);continue}if(s!==a)return null}return o}function ce(e){let t=E(e);if(t==="/")return[];return t.split("/").filter(Boolean)}function ue(e,t,n){let r=E(e),o=n==="/"?r:n+r;return t==="hash"?`#${o}`:o}function le(e,t){let n,r,o;if(e==="history")r=window.location.pathname+window.location.search,n=window.location.pathname,o=window.location.search;else{r=window.location.hash||"#/",n=r.startsWith("#")?r.slice(1):r;let s=n.indexOf("?");o=s>=0?n.slice(s+1):"",n=s>=0?n.slice(0,s):n}if(n.startsWith(t)&&t!=="/"&&n!=="/")n=n.slice(t.length);return n=E(n),{path:n,fullPath:r,query:we(o),params:{}}}function U(e,t,n,r){let o=E(e),i=r==="/"?o:r+o;if(n==="history"){if(t)window.history.replaceState({},"",i);else window.history.pushState({},"",i);return}if(t){let s=window.location.href.split("#")[0];window.location.replace(`${s}#${i}`);return}window.location.hash=i}function we(e){let t={},n=e.startsWith("?")?e.slice(1):e;if(!n)return t;return n.split("&").forEach((r)=>{let[o,i]=r.split("=");if(o)t[decodeURIComponent(o)]=i?decodeURIComponent(i):""}),t}function Se(e){let t=e.indexOf("?");if(t<0)return{};let n=e.slice(t+1),r={};if(!n)return r;return n.split("&").forEach((o)=>{let[i,s]=o.split("=");if(i)r[decodeURIComponent(i)]=s?decodeURIComponent(s):""}),r}class P{currentRoute=null;currentLocation=null;routes=[];app=null;mode;base;routeChangeListeners=[];beforeGuards=[];afterHooks=[];removeWindowListener;constructor(e){let t=Array.isArray(e)?{routes:e}:e;this.routes=t.routes||[],this.mode=t.mode||"history",this.base=t.base||"/",this.validateRoutes(),this.initEvents(),this.resolveCurrentRoute()}install(e){this.app=e,e.router=this,pe(this);let t=e.getContext();t.router=this,this.resolveCurrentRoute()}push(e){this.navigate(e,!1)}replace(e){this.navigate(e,!0)}forward(){window.history.forward()}back(){window.history.back()}go(e){window.history.go(e)}getCurrentRoute(){if(!this.currentLocation)this.resolveCurrentRoute();return this.currentLocation}getCurrentRouteRecord(){if(!this.currentRoute)this.resolveCurrentRoute();return this.currentRoute}onRouteChange(e){return this.routeChangeListeners.push(e),()=>{let t=this.routeChangeListeners.indexOf(e);if(t>-1)this.routeChangeListeners.splice(t,1)}}beforeEach(e){return this.beforeGuards.push(e),()=>{let t=this.beforeGuards.indexOf(e);if(t>-1)this.beforeGuards.splice(t,1)}}afterEach(e){return this.afterHooks.push(e),()=>{let t=this.afterHooks.indexOf(e);if(t>-1)this.afterHooks.splice(t,1)}}getRoutes(){return[...this.routes]}addRoute(e){if(this.routes.some((n)=>n.path===e.path))throw Error(`Route already exists: ${e.path}`);if(this.routes.push(e),this.getCurrentLocation().path===e.path)this.handleRouteChange()}createHref(e){return ue(e,this.mode,this.base)}destroy(){if(this.removeWindowListener?.(),this.removeWindowListener=void 0,this.app?.router===this)this.app.router=void 0;this.app=null}navigate(e,t){if(!e||typeof e!=="string")throw Error("Path must be a non-empty string");let n=this.currentLocation,r=this.resolveTarget(e);if(!r)return;let o=r.location;for(let i of this.beforeGuards){let s=i(o,n);if(s===!1)return;if(typeof s==="string"&&s!==e){this.navigate(s,t);return}}if(n&&this.isSameLocation(n,o))return;U(r.path,t,this.mode,this.base),this.currentRoute=r.route,this.currentLocation=o,this.triggerRouteChangeListeners(o,n),this.afterHooks.forEach((i)=>{try{i(o,n)}catch(s){console.error("Route afterEach error:",s)}})}resolveTarget(e){let t=A(this.routes,e.split("?")[0]);if(!t)return null;let n=this.applyRedirect(t),r=n?.path??e,o=n?.route??t.route;return{path:r,route:o,location:{path:r.split("?")[0],query:Se(r),params:n?.params??t.params,fullPath:r,name:o?.name,meta:o?.meta}}}applyRedirect(e){let t=new Set,n=e,r="";while(n.route.redirect){if(t.has(n.route.path))throw Error(`Redirect loop detected for route: ${n.route.path}`);t.add(n.route.path),r=n.route.redirect;let o=A(this.routes,r.split("?")[0]);if(!o)return null;n=o}return r?{route:n.route,params:n.params,path:r}:null}validateRoutes(){if(!Array.isArray(this.routes))throw Error("Router routes must be an array");let e=new Set;this.routes.forEach((t)=>{if(!t.component&&!t.redirect)throw Error(`Route ${t.path} must define a component or redirect`);if(e.has(t.path))throw Error(`Duplicate route path: ${t.path}`);e.add(t.path)})}initEvents(){if(typeof window>"u")return;let e=this.mode==="history"?"popstate":"hashchange",t=()=>{this.handleRouteChange()};window.addEventListener(e,t),this.removeWindowListener=()=>{window.removeEventListener(e,t)}}handleRouteChange(){let e=this.currentLocation,t=this.resolveCurrentRoute();if(!this.isSameLocation(e,t))this.triggerRouteChangeListeners(t,e)}resolveCurrentRoute(){let e=this.getCurrentLocation(),t=A(this.routes,e.path),n=t?this.applyRedirect(t):null,r=n?.route??t?.route??null;if(n&&n.path!==e.path)U(n.path,!0,this.mode,this.base);return this.currentRoute=r,this.currentLocation={...e,params:n?.params??t?.params??{},name:r?.name,meta:r?.meta},this.currentLocation}getCurrentLocation(){return le(this.mode,this.base)}isSameLocation(e,t){return e?.fullPath===t?.fullPath&&e?.name===t?.name}triggerRouteChangeListeners(e,t){this.routeChangeListeners.forEach((n)=>{try{n(e,t)}catch(r){console.error("Route change listener error:",r)}})}}class Me extends S{unsubscribe;initState(){return{currentPath:this.router?.getCurrentRoute()?.path??window.location.pathname}}initStyles(){}onMounted(){let e=this.router;this.unsubscribe=e?.onRouteChange((t)=>{this.state.currentPath=t.path})}onUnmounted(){this.unsubscribe?.()}render(){let e=this.router,t=this.props.activeClass??"active",n=this.state.currentPath===this.props.to,r=[this.props.className,n?t:void 0].filter(Boolean).join(" ");return{tag:"a",props:{href:e?.createHref(this.props.to)??this.props.to,className:r},listeners:{click:(o)=>{if(o.preventDefault(),this.props.replace)e?.replace(this.props.to);else e?.push(this.props.to)}},children:this.props.children&&this.props.children.length>0?this.props.children:[this.props.to]}}}class Le extends S{unsubscribe;initState(){let e=this.router;return{route:e?.getCurrentRoute()??null,record:e?.getCurrentRouteRecord()??null}}initStyles(){}onMounted(){let e=this.router;this.unsubscribe=e?.onRouteChange((t)=>{this.state.route=t,this.state.record=e.getCurrentRouteRecord()})}onUnmounted(){this.unsubscribe?.()}render(){let e=this.state.record??this.router?.getCurrentRouteRecord();return{tag:"div",props:{"data-router-view":""},children:e?.component?[{component:e.component}]:[]}}}function kn(e){return new P(e)}var Ne=new Set(["base","link","meta"]);function de(e){let t=e.lang??"en",n=e.charset??"utf-8",r=e.viewport??"width=device-width, initial-scale=1",o=I({lang:t,...e.htmlAttributes??{}}),i=I(e.bodyAttributes),s=Pe(e.body);return["<!doctype html>",`<html${o}>`,"<head>",` <meta charset="${x(n)}">`,` <meta name="viewport" content="${x(r)}">`,` <title>${x(e.title)}</title>`,e.description?` <meta name="description" content="${x(e.description)}">`:"",...(e.head??[]).map((a)=>` ${Ae(a)}`),e.styles&&e.styles.length>0?` <style>${K(e.styles)}</style>`:"","</head>",`<body${i}>`,s,...(e.scripts??[]).map((a)=>` ${Ie(a)}`),"</body>","</html>"].filter((a)=>a!=="").join(`
2
- `)}function Pe(e){if(typeof document>"u")throw Error("renderHtmlDocument requires a DOM-like document");let t=document.createElement("div"),n=new w,r=new Set,o=Array.isArray(e)?e:[e],i={templateEngine:new R({}),renderer:n,slots:{default:[]},registerChild:(a)=>{r.add(a)},unregisterChild:(a)=>{r.delete(a)}};o.forEach((a)=>{t.appendChild(n.mount(a,i))});let s=t.innerHTML;return r.forEach((a)=>{a.unmount()}),s}function Ae(e){let t=I(e.attributes);if(Ne.has(e.tag)&&!e.text)return`<${e.tag}${t}>`;return`<${e.tag}${t}>${x(e.text??"")}</${e.tag}>`}function Ie(e){return`<script${I({type:e.type,src:e.src,async:e.async,defer:e.defer,...e.attributes??{}})}></script>`}function I(e={}){let t=Object.entries(e).flatMap(([n,r])=>{if(r===!1||r===null||r===void 0)return[];return r===!0?[n]:[`${n}="${x(String(r))}"`]}).join(" ");return t?` ${t}`:""}function x(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var he="#app";class He{options;container=null;rootInstance=null;mounted=!1;templateEngine=null;appContext;providers=new Map;plugins=[];unmountedCallback;router;constructor(e={}){this.options=e;this.appContext={app:this,version:"0.1.0",config:e.config||{}}}handleError(e){console.error("应用错误:",e),this.renderErrorUI(e)}renderErrorUI(e){if(!this.container)return;this.container.innerHTML=`
3
- <div style="padding: 20px; background-color: #ffebee; color: #c62828; font-family: Arial, sans-serif;">
4
- <h3>应用错误</h3>
5
- <p>${e.message}</p>
6
- <pre style="background-color: #fff; padding: 10px; border-radius: 4px; overflow: auto;">${e.stack}</pre>
7
- </div>
8
- `}use(e,...t){if(typeof e.install!=="function")throw Error("插件必须提供 install 方法");return e.install(this,...t),this.plugins.push({plugin:e,args:t}),this}mount(){if(this.mounted){console.warn("应用已经处于运行状态");return}let e=this.resolveMountContainer();if(!e)return;try{if(this.container=e,globalThis.__APP__=this,this.options.root){if(this.rootInstance=new this.options.root(this.options.rootProps),"setAppContext"in this.rootInstance)this.rootInstance.setAppContext(this.appContext);if(this.options.state&&"setState"in this.rootInstance)this.rootInstance.setState(this.options.state);this.rootInstance.mount(this.container),this.templateEngine=new R(this.options.state||{})}this.mounted=!0,this.onMounted()}catch(t){this.handleError(t)}}unmount(){if(!this.mounted){console.warn("应用未处于运行状态");return}try{if(this.onBeforeUnmount(),this.rootInstance){if("unmount"in this.rootInstance)this.rootInstance.unmount();this.rootInstance=null,this.mounted=!1,delete globalThis.__APP__}if(this.templateEngine)this.templateEngine.clearBindings(),this.templateEngine=null;if(this.container)this.container.innerHTML="";if(this.unmountedCallback)this.unmountedCallback()}catch(e){console.error("Failed to unmount app:",e)}}isRunning(){return this.mounted}updateRootComponent(e){if(this.mounted)this.unmount();this.options.root=e,this.mount()}update(e){if(!this.mounted)return console.warn("Cannot update unmounted app"),this;try{if(e&&this.options.state){if(this.options.state={...this.options.state,...e},this.rootInstance&&"setState"in this.rootInstance)this.rootInstance.setState(e);if(this.templateEngine)this.templateEngine.state=this.options.state}this.onUpdated()}catch(t){console.error("Failed to update app:",t)}return this}getContext(){return this.appContext}provide(e,t){return this.providers.set(e,t),this}inject(e,t){let n=this.resolveInjection(e);return n.found?n.value:t}resolveInjection(e){if(!this.providers.has(e))return{found:!1,value:void 0};return{found:!0,value:this.providers.get(e)}}getState(){return this.options.state}setState(e){if(this.options.state=e,this.mounted)this.update();return this}onUnmounted(e){return this.unmountedCallback=e,this}renderHtmlDocument(e={}){let t=this.options.document??{},n=this.mergeDocumentScripts(t.scripts,e.scripts);return de({...t,...e,title:e.title??t.title??"TransOne App",body:e.body??t.body??this.createMountDocumentBody(),scripts:n})}resolveRootElement(e){if(!e)return null;if(typeof e==="string"){if(typeof document>"u")return null;return document.querySelector(e)}return typeof Element<"u"&&e instanceof Element?e:null}resolveMountContainer(){if(typeof document>"u")return null;let e=this.resolveRootElement(this.options.rootElement??he);return e instanceof HTMLElement?e:null}createMountDocumentBody(){let e=this.options.rootElement??he;if(typeof e==="string")return this.createMountElementFromSelector(e);if(typeof Element<"u"&&e instanceof Element){let t={};if(e.id)t.id=e.id;if(e.className)t.className=e.className;return{tag:e.tagName.toLowerCase(),props:t}}return T({props:{id:"app"}})}createMountElementFromSelector(e){if(e.startsWith("#")&&e.length>1)return T({props:{id:e.slice(1)}});if(e.startsWith(".")&&e.length>1)return T({props:{className:e.slice(1)}});return T({props:{"data-transone-root":e}})}mergeDocumentScripts(e,t){if(!e&&!t)return;return[...e??[],...t??[]]}onMounted(){this.plugins.forEach(({plugin:e})=>{if(e&&typeof e.onMounted==="function")e.onMounted(this)})}onUpdated(){this.plugins.forEach(({plugin:e})=>{if(e&&typeof e.onUpdated==="function")e.onUpdated(this)})}onBeforeUnmount(){this.plugins.forEach(({plugin:e})=>{if(e&&typeof e.onBeforeUnmount==="function")e.onBeforeUnmount(this)})}}
9
- export{b as a,Ue as b,Ke as c,f as d,O as e,We as f,g,Fe as h,Ge as i,G as j,qe as k,v as l,ze as m,me as n,Ye as o,q as p,z as q,Y as r,Ze as s,ge as t,T as u,Je as v,Xe as w,et as x,tt as y,nt as z,rt as A,ot as B,it as C,st as D,at as E,pt as F,ct as G,ut as H,lt as I,dt as J,ht as K,ft as L,mt as M,gt as N,vt as O,yt as P,Rt as Q,Ct as R,bt as S,Et as T,xt as U,Tt as V,wt as W,St as X,Mt as Y,Lt as Z,Nt as _,Pt as $,At as aa,It as ba,Ht as ca,kt as da,jt as ea,Ot as fa,Vt as ga,Bt as ha,_t as ia,ve as ja,Q as ka,ye as la,_ as ma,N as na,w as oa,oe as pa,ie as qa,se as ra,R as sa,S as ta,de as ua,He as va,xe as wa,P as xa,Me as ya,Le as za,kn as Aa};
10
-
11
- //# debugId=8A550B29FEBC7E8B64756E2164756E21
12
- //# sourceMappingURL=index-3t506ckz.js.map