@e7w/easy-model 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,42 +1,533 @@
1
1
  # easy-model
2
2
 
3
- 一个简单的react状态管理库
3
+ 一个功能强大的 React 状态管理库,集成了状态管理、IoC 容器、观察者模式和加载器等功能。
4
4
 
5
- ## 示例
5
+ ## 特性
6
+
7
+ - 🚀 **简单易用** - 基于类的状态管理,直观的 API 设计
8
+ - 🔄 **响应式** - 自动观察状态变化,精确更新组件
9
+ - 💉 **IoC 容器** - 内置依赖注入容器,支持命名空间隔离
10
+ - 🎯 **类型安全** - 完整的 TypeScript 支持,基于 Zod 的运行时类型验证
11
+ - ⚡ **性能优化** - 智能缓存和垃圾回收机制
12
+ - 🔧 **加载状态管理** - 内置异步操作加载状态管理
13
+ - 🧩 **模块化** - 可按需使用各个功能模块
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ npm install @e7w/easy-model
19
+ # 或
20
+ yarn add @e7w/easy-model
21
+ # 或
22
+ pnpm add @e7w/easy-model
23
+ ```
24
+
25
+ ## 核心概念
26
+
27
+ ### 1. 状态管理
28
+
29
+ 基于类的状态管理,支持自动观察和响应式更新。
6
30
 
7
31
  ```tsx
8
32
  import { useModel } from "@e7w/easy-model";
9
33
 
10
- class MTest {
34
+ class CounterModel {
11
35
  constructor(public name: string) {}
12
36
 
13
- value = 0;
37
+ count = 0;
38
+
39
+ increment() {
40
+ this.count++;
41
+ }
42
+
43
+ decrement() {
44
+ this.count--;
45
+ }
46
+
47
+ reset() {
48
+ this.count = 0;
49
+ }
50
+ }
51
+
52
+ function Counter() {
53
+ const { count, increment, decrement, reset } = useModel(CounterModel, [
54
+ "main",
55
+ ]);
56
+
57
+ return (
58
+ <div>
59
+ <h2>计数器: {count}</h2>
60
+ <button onClick={increment}>+1</button>
61
+ <button onClick={decrement}>-1</button>
62
+ <button onClick={reset}>重置</button>
63
+ </div>
64
+ );
65
+ }
66
+ ```
67
+
68
+ ### 2. IoC 容器
69
+
70
+ 内置的依赖注入容器,支持值注入、构造函数注入和装饰器注入。
71
+
72
+ ```tsx
73
+ import { Container, VInjection, CInjection, inject } from "@e7w/easy-model";
74
+ import { z } from "zod";
75
+
76
+ // 定义配置 schema
77
+ const configSchema = z.object({
78
+ apiUrl: z.string(),
79
+ timeout: z.number(),
80
+ });
81
+
82
+ const loggerSchema = z.object({
83
+ log: z.function(),
84
+ });
85
+
86
+ // 定义服务类
87
+ class Logger {
88
+ log(message: string) {
89
+ console.log(`[LOG] ${message}`);
90
+ }
91
+ }
92
+
93
+ class ApiService {
94
+ @inject(configSchema)
95
+ config: z.infer<typeof configSchema> = { apiUrl: "", timeout: 0 };
96
+
97
+ @inject(loggerSchema)
98
+ logger: Logger | undefined;
99
+
100
+ async fetchData() {
101
+ this.logger?.log(`Fetching data from ${this.config.apiUrl}`);
102
+ // 实际的 API 调用逻辑
103
+ }
104
+ }
105
+
106
+ function App() {
107
+ return (
108
+ <Container namespace="app">
109
+ {/* 注入配置值 */}
110
+ <VInjection
111
+ schema={configSchema}
112
+ val={{ apiUrl: "https://api.example.com", timeout: 5000 }}
113
+ />
114
+
115
+ {/* 注入构造函数 */}
116
+ <CInjection schema={loggerSchema} ctor={Logger} />
117
+
118
+ <YourComponents />
119
+ </Container>
120
+ );
121
+ }
122
+ ```
123
+
124
+ ### 3. 观察者模式
125
+
126
+ 手动观察对象变化,适用于非 React 环境。注意:`observe` 函数是内部实现,不对外导出。
127
+
128
+ ```tsx
129
+ import { watch } from "@e7w/easy-model";
130
+
131
+ // 注意:observe 函数未导出,这里仅作为概念说明
132
+ // 实际使用中,观察功能已集成在 useModel 和 useInstance 中
133
+
134
+ // 监听对象变化的概念示例(实际需要通过 useModel 等方式)
135
+ const unwatch = watch(someObservableObject, (path, oldValue, newValue) => {
136
+ console.log(`属性 ${path.join(".")} 从 ${oldValue} 变为 ${newValue}`);
137
+ });
138
+
139
+ // 取消监听
140
+ unwatch();
141
+ ```
142
+
143
+ ### 4. 加载状态管理
144
+
145
+ 内置的异步操作加载状态管理,支持全局和局部加载状态。
146
+
147
+ ```tsx
148
+ import { loader } from "@e7w/easy-model";
149
+
150
+ class DataService {
151
+ data: any[] = [];
152
+
153
+ @loader.load(true) // true 表示全局加载状态
154
+ async fetchData() {
155
+ const response = await fetch("/api/data");
156
+ this.data = await response.json();
157
+ return this.data;
158
+ }
159
+
160
+ @loader.load() // 局部加载状态
161
+ async updateItem(id: string, updates: any) {
162
+ const response = await fetch(`/api/data/${id}`, {
163
+ method: "PUT",
164
+ body: JSON.stringify(updates),
165
+ });
166
+ return response.json();
167
+ }
168
+
169
+ @loader.once() // 只执行一次的异步操作
170
+ async initializeApp() {
171
+ // 初始化逻辑
172
+ }
173
+ }
174
+
175
+ function DataComponent() {
176
+ const service = useModel(DataService, []);
177
+ const { globalLoading } = useModel(loader, []);
178
+
179
+ return (
180
+ <div>
181
+ {globalLoading > 0 && <div>全局加载中...</div>}
182
+ <button onClick={() => service.fetchData()}>加载数据</button>
183
+ {service.data.map(item => (
184
+ <div key={item.id}>{item.name}</div>
185
+ ))}
186
+ </div>
187
+ );
188
+ }
189
+ ```
190
+
191
+ ## API 参考
192
+
193
+ ### 状态管理
194
+
195
+ #### `useModel<T>(Constructor: T, args: ConstructorParameters<T>): InstanceType<T>`
196
+
197
+ 创建或获取模型实例,自动观察状态变化并更新组件。
198
+
199
+ **参数:**
200
+
201
+ - `Constructor`: 模型类构造函数
202
+ - `args`: 构造函数参数数组
203
+
204
+ **返回值:** 模型实例,包含所有属性和方法
205
+
206
+ #### `useInstance<T>(instance: T): T`
207
+
208
+ 直接使用现有实例,自动观察状态变化。
209
+
210
+ **参数:**
211
+
212
+ - `instance`: 要观察的对象实例
213
+
214
+ **返回值:** 观察后的实例
215
+
216
+ #### `provide<T>(Constructor: T): T`
217
+
218
+ 为类提供实例缓存和观察功能。
219
+
220
+ **参数:**
221
+
222
+ - `Constructor`: 要包装的类构造函数
223
+
224
+ **返回值:** 包装后的构造函数,支持实例缓存
225
+
226
+ ### IoC 容器
227
+
228
+ #### `Container`
229
+
230
+ IoC 容器组件,提供依赖注入的上下文环境。
231
+
232
+ **Props:**
233
+
234
+ - `namespace?: string` - 命名空间,用于隔离不同的依赖注入环境
235
+ - `children: ReactNode` - 子组件
236
+
237
+ #### `VInjection<T>`
238
+
239
+ 值注入组件,将值注入到容器中。
240
+
241
+ **Props:**
242
+
243
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
244
+ - `val: T` - 要注入的值
245
+
246
+ #### `CInjection<T>`
247
+
248
+ 构造函数注入组件,将构造函数注入到容器中。
249
+
250
+ **Props:**
251
+
252
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
253
+ - `ctor: new () => T` - 要注入的构造函数
254
+
255
+ #### `inject<T>(schema: ZodType<T>, namespace?: string)`
256
+
257
+ 装饰器函数,用于从容器中注入依赖到类属性。
258
+
259
+ **参数:**
260
+
261
+ - `schema: ZodType<T>` - Zod schema,用于类型验证
262
+ - `namespace?: string` - 可选的命名空间
263
+
264
+ **返回值:** 装饰器函数
265
+
266
+ ### 观察者模式
267
+
268
+ #### `watch(target: object, callback: WatchCallback): () => void`
269
+
270
+ 监听对象的变化。
14
271
 
15
- random() {
16
- this.value = Math.random();
272
+ **参数:**
273
+
274
+ - `target: object` - 要监听的对象
275
+ - `callback: WatchCallback` - 变化时的回调函数
276
+
277
+ **返回值:** 取消监听的函数
278
+
279
+ **WatchCallback 类型:**
280
+
281
+ ```typescript
282
+ type WatchCallback = (
283
+ path: Array<string | symbol>,
284
+ oldValue: any,
285
+ newValue: any
286
+ ) => void;
287
+ ```
288
+
289
+ ### 加载器
290
+
291
+ #### `loader.load(isGlobal?: boolean)`
292
+
293
+ 异步方法装饰器,自动管理加载状态。
294
+
295
+ **参数:**
296
+
297
+ - `isGlobal?: boolean` - 是否影响全局加载状态,默认为 false
298
+
299
+ **返回值:** 方法装饰器
300
+
301
+ #### `loader.once()`
302
+
303
+ 确保异步方法只执行一次的装饰器。
304
+
305
+ **返回值:** 方法装饰器
306
+
307
+ #### `loader.isLoading(target: Function): boolean`
308
+
309
+ 检查指定方法是否正在加载中。
310
+
311
+ **参数:**
312
+
313
+ - `target: Function` - 要检查的方法
314
+
315
+ **返回值:** 是否正在加载
316
+
317
+ #### `loader.isGlobalLoading: boolean`
318
+
319
+ 获取全局加载状态。
320
+
321
+ **返回值:** 是否有全局加载正在进行
322
+
323
+ #### `loader.globalLoading: number`
324
+
325
+ 获取当前全局加载的数量。
326
+
327
+ **返回值:** 正在进行的全局加载数量
328
+
329
+ #### `finalizationRegistry(model: object)`
330
+
331
+ 为模型注册垃圾回收回调。
332
+
333
+ **参数:**
334
+
335
+ - `model: object` - 要监听垃圾回收的对象
336
+
337
+ **返回值:** 包含 `register` 和 `unregister` 方法的对象
338
+
339
+ ## 高级用法
340
+
341
+ ### 组件间通信
342
+
343
+ ```tsx
344
+ // 全局状态模型
345
+ class AppState {
346
+ user: User | null = null;
347
+ theme: "light" | "dark" = "light";
348
+
349
+ setUser(user: User) {
350
+ this.user = user;
351
+ }
352
+
353
+ toggleTheme() {
354
+ this.theme = this.theme === "light" ? "dark" : "light";
17
355
  }
18
356
  }
19
357
 
20
- function TestComA() {
21
- const { value, random } = useModel(MTest, ["test"]);
358
+ // 在任何组件中使用
359
+ function Header() {
360
+ const { user, theme, toggleTheme } = useModel(AppState, []);
361
+
362
+ return (
363
+ <header className={theme}>
364
+ <span>欢迎, {user?.name}</span>
365
+ <button onClick={toggleTheme}>切换主题</button>
366
+ </header>
367
+ );
368
+ }
369
+
370
+ function Sidebar() {
371
+ const { user } = useModel(AppState, []); // 同一个实例
372
+
373
+ return <aside>{user && <UserProfile user={user} />}</aside>;
374
+ }
375
+ ```
376
+
377
+ ### 嵌套模型
378
+
379
+ ```tsx
380
+ class UserModel {
381
+ constructor(public id: string) {}
382
+
383
+ name = "";
384
+ email = "";
385
+
386
+ updateProfile(data: Partial<UserModel>) {
387
+ Object.assign(this, data);
388
+ }
389
+ }
390
+
391
+ class TeamModel {
392
+ members: UserModel[] = [];
393
+
394
+ addMember(userId: string) {
395
+ const user = provide(UserModel)(userId);
396
+ this.members.push(user);
397
+ }
398
+
399
+ removeMember(userId: string) {
400
+ this.members = this.members.filter(m => m.id !== userId);
401
+ }
402
+ }
403
+
404
+ function TeamManagement() {
405
+ const team = useModel(TeamModel, ["team-1"]);
406
+
407
+ return (
408
+ <div>
409
+ <h2>团队成员</h2>
410
+ {team.members.map(member => (
411
+ <UserCard key={member.id} user={member} />
412
+ ))}
413
+ </div>
414
+ );
415
+ }
416
+
417
+ function UserCard({ user }: { user: UserModel }) {
418
+ const observedUser = useInstance(user);
419
+
22
420
  return (
23
421
  <div>
24
- <span>{value}</span>
25
- <button onClick={random}>changeValue</button>
422
+ <span>{observedUser.name}</span>
423
+ <span>{observedUser.email}</span>
26
424
  </div>
27
425
  );
28
426
  }
427
+ ```
428
+
429
+ ### 命名空间隔离
430
+
431
+ ```tsx
432
+ function App() {
433
+ return (
434
+ <div>
435
+ {/* 开发环境配置 */}
436
+ <Container namespace="dev">
437
+ <VInjection schema={configSchema} val={devConfig} />
438
+ <DevTools />
439
+ </Container>
440
+
441
+ {/* 生产环境配置 */}
442
+ <Container namespace="prod">
443
+ <VInjection schema={configSchema} val={prodConfig} />
444
+ <MainApp />
445
+ </Container>
446
+ </div>
447
+ );
448
+ }
449
+ ```
450
+
451
+ ## 最佳实践
452
+
453
+ ### 1. 模型设计
454
+
455
+ - **单一职责**: 每个模型类应该只负责一个特定的业务领域
456
+ - **不可变更新**: 尽量使用不可变的方式更新状态
457
+ - **类型安全**: 充分利用 TypeScript 的类型系统
458
+
459
+ ```tsx
460
+ // ✅ 好的实践
461
+ class UserModel {
462
+ constructor(public id: string) {}
463
+
464
+ private _profile: UserProfile | null = null;
465
+
466
+ get profile() {
467
+ return this._profile;
468
+ }
469
+
470
+ updateProfile(updates: Partial<UserProfile>) {
471
+ this._profile = { ...this._profile, ...updates };
472
+ }
473
+ }
29
474
 
30
- function TestComB() {
31
- const { value } = useModel(MTest, ["test"]);
32
- return <span>{value}</span>;
475
+ // 避免的实践
476
+ class BadModel {
477
+ // 避免在模型中直接操作 DOM
478
+ updateUI() {
479
+ document.getElementById("user-name")!.textContent = this.name;
480
+ }
33
481
  }
482
+ ```
483
+
484
+ ### 2. 依赖注入
485
+
486
+ - **明确依赖**: 使用 Zod schema 明确定义依赖的类型
487
+ - **命名空间**: 使用命名空间隔离不同环境的配置
488
+ - **懒加载**: 只在需要时注入依赖
489
+
490
+ ### 3. 性能优化
491
+
492
+ - **合理使用参数**: 相同参数会返回相同实例,利用这一点进行优化
493
+ - **避免过度观察**: 不要观察不必要的对象
494
+ - **及时清理**: 使用 `finalizationRegistry` 进行资源清理
495
+
496
+ ## 类型定义
34
497
 
35
- render(
36
- <div>
37
- <TestComA />
38
- <TestComB />
39
- </div>
40
- );
41
- // 当点击ComA的div时,两个组件都会更新
498
+ ```typescript
499
+ // 主要导出的类型
500
+ export interface WatchCallback {
501
+ (path: Array<string | symbol>, oldValue: any, newValue: any): void;
502
+ }
503
+
504
+ export interface FinalizationRegistry {
505
+ register(callback: () => void): void;
506
+ unregister(): void;
507
+ }
508
+
509
+ export interface LoaderInstance {
510
+ loading: Record<symbol, [Function, Promise<unknown>]>;
511
+ globalLoading: number;
512
+ load(isGlobal?: boolean): MethodDecorator;
513
+ once(): MethodDecorator;
514
+ }
42
515
  ```
516
+
517
+ ## 兼容性
518
+
519
+ - **React**: >= 17.0.0
520
+ - **TypeScript**: >= 4.5.0
521
+ - **Zod**: ^4.1.5
522
+
523
+ ## 许可证
524
+
525
+ MIT License - 详见 [LICENSE.md](./LICENSE.md)
526
+
527
+ ## 贡献
528
+
529
+ 欢迎提交 Issue 和 Pull Request!
530
+
531
+ ## 更新日志
532
+
533
+ 详见 [CHANGELOG.md](./CHANGELOG.md)
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ import { FC, PropsWithChildren, ReactNode } from 'react';
4
+ import { ZodType } from 'zod';
5
+
3
6
  export type WatchCallback = (path: Array<string | symbol>, oldValue: any, newValue: any) => void;
4
7
  export declare function watch(target: object, callback: WatchCallback): () => void;
5
8
  export declare function provide<T extends new (...args: any[]) => InstanceType<T>>(ctor: T): T & ((...args: ConstructorParameters<T>) => InstanceType<T>);
@@ -10,5 +13,35 @@ export declare function finalizationRegistry(model: object): {
10
13
  export declare function useModel<T extends new (...args: any[]) => InstanceType<T>>(Ctor: T, args: ConstructorParameters<T>): InstanceType<T>;
11
14
  export declare function useModel<T extends new (...args: any[]) => InstanceType<T>>(Ctor: T, args: ConstructorParameters<T> | null): InstanceType<T> | Partial<InstanceType<T>>;
12
15
  export declare function useInstance<T extends object>(model: T): T;
16
+ export type Fn = (...args: any[]) => unknown;
17
+ export type AsyncFn<T = unknown> = (...args: any[]) => Promise<T>;
18
+ declare class MLoader {
19
+ loading: Record<symbol, [
20
+ Fn,
21
+ Promise<unknown>
22
+ ]>;
23
+ globalLoading: number;
24
+ onceTokens: WeakMap<AsyncFn, symbol>;
25
+ oncePool: Record<symbol, Promise<unknown>>;
26
+ addGlobalLoading(): void;
27
+ subGlobalLoading(): void;
28
+ load(isGlobal?: boolean): <T extends AsyncFn>(target: T, { name }: ClassMethodDecoratorContext) => T;
29
+ once<T extends AsyncFn>(target: T, { name }: ClassMethodDecoratorContext): T;
30
+ isLoading<T extends AsyncFn>(target: T): boolean;
31
+ get isGlobalLoading(): boolean;
32
+ }
33
+ export declare const loader: MLoader;
34
+ export declare const Container: FC<PropsWithChildren<{
35
+ namespace?: string;
36
+ }>>;
37
+ export declare function CInjection<T extends ZodType, P extends new () => ReturnType<T["parse"]>>({ schema, ctor }: {
38
+ schema: T;
39
+ ctor: P;
40
+ }): ReactNode;
41
+ export declare function VInjection<T extends ZodType>({ schema, val, }: {
42
+ schema: T;
43
+ val: ReturnType<T["parse"]>;
44
+ }): ReactNode;
45
+ export declare function inject<T extends ZodType>(schema: T, namespace?: string): (_: unknown, { static: isStatic, kind }: ClassFieldDecoratorContext) => <P extends ReturnType<T["parse"]> | undefined>(initVal: P) => P;
13
46
 
14
47
  export {};
package/dist/index.es.js CHANGED
@@ -1,158 +1,531 @@
1
- import { useRef as C, useReducer as A, useEffect as L } from "react";
2
- const _ = /* @__PURE__ */ new WeakMap(), p = /* @__PURE__ */ new WeakMap(), O = Symbol("origin");
3
- let d = null;
4
- const v = ["includes", "indexOf", "lastIndexOf"], U = [Promise, RegExp, Date, WeakMap, WeakSet, Map, Set];
5
- function w(e) {
6
- if (e = l(e), !e || U.some((c) => e instanceof c)) return e;
7
- if (_.has(e)) return _.get(e);
8
- const n = {}, r = {}, i = new Proxy(e, {
9
- get(c, t, s) {
10
- if (t === O) return c;
11
- let o = j(c, t);
12
- return o || (o = Reflect.get(c, t, s), typeof o == "function" ? (r[t] || (r[t] = o.bind(w(c))), o = r[t]) : typeof o == "object" && o !== null && (n[t] || (n[t] = R(o, x(e, t))), o = w(o)), o);
1
+ var Te = Object.defineProperty;
2
+ var ge = (t, r, n) => r in t ? Te(t, r, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[r] = n;
3
+ var T = (t, r, n) => ge(t, typeof r != "symbol" ? r + "" : r, n);
4
+ import Pe, { useReducer as Oe, useEffect as Se, createContext as je, useContext as ce } from "react";
5
+ const U = /* @__PURE__ */ new WeakMap(), C = /* @__PURE__ */ new WeakMap(), ie = Symbol("origin");
6
+ let y = null;
7
+ const z = ["includes", "indexOf", "lastIndexOf"], xe = [Promise, RegExp, Date, WeakMap, WeakSet, Map, Set];
8
+ function x(t) {
9
+ if (t = _(t), !t || xe.some((a) => t instanceof a)) return t;
10
+ if (U.has(t)) return U.get(t);
11
+ const r = {}, n = {}, u = new Proxy(t, {
12
+ get(a, o, c) {
13
+ if (o === ie) return a;
14
+ let s = ue(a, o);
15
+ return s || (s = Reflect.get(a, o, c), typeof s == "function" ? (n[o] || (n[o] = s.bind(x(a))), s = n[o]) : typeof s == "object" && s !== null && (r[o] || (r[o] = q(s, re(t, o))), s = x(s)), s);
13
16
  },
14
- set(c, t, s, o) {
15
- let u = Reflect.get(c, t, o);
16
- if (u = l(u), s = l(s), u === s) return !0;
17
- const f = Reflect.set(c, t, s, o);
18
- if (f) {
19
- n[t] && (n[t](), delete n[t]), typeof s == "object" && s !== null && (n[t] = R(s, x(e, t))), r[t] && delete r[t];
20
- const y = d;
21
- d = /* @__PURE__ */ new WeakSet(), W(c, [t], u, s), d = y;
17
+ set(a, o, c, s) {
18
+ let f = Reflect.get(a, o, s);
19
+ if (f = _(f), c = _(c), f === c) return !0;
20
+ const l = Reflect.set(a, o, c, s);
21
+ if (l) {
22
+ r[o] && (r[o](), delete r[o]), typeof c == "object" && c !== null && (r[o] = q(c, re(t, o))), n[o] && delete n[o];
23
+ const p = y;
24
+ y = /* @__PURE__ */ new WeakSet(), J(a, [o], f, c), y = p;
22
25
  }
23
- return f;
26
+ return l;
24
27
  },
25
- deleteProperty(c, t) {
26
- let s = Reflect.get(c, t);
27
- s = l(s);
28
- const o = Reflect.deleteProperty(c, t);
29
- return o && (n[t] && (n[t](), delete n[t]), r[t] && delete r[t], W(c, [t], s, void 0)), o;
28
+ deleteProperty(a, o) {
29
+ let c = Reflect.get(a, o);
30
+ c = _(c);
31
+ const s = Reflect.deleteProperty(a, o);
32
+ return s && (r[o] && (r[o](), delete r[o]), n[o] && delete n[o], J(a, [o], c, void 0)), s;
30
33
  }
31
34
  });
32
- return _.set(e, i), i;
35
+ return U.set(t, u), u;
33
36
  }
34
- function R(e, n) {
35
- e = l(e), p.has(e) || p.set(e, /* @__PURE__ */ new Map());
36
- const r = p.get(e), i = Symbol();
37
- return r.set(i, n), function() {
38
- r.delete(i);
37
+ function q(t, r) {
38
+ t = _(t), C.has(t) || C.set(t, /* @__PURE__ */ new Map());
39
+ const n = C.get(t), u = Symbol();
40
+ return n.set(u, r), function() {
41
+ n.delete(u);
39
42
  };
40
43
  }
41
- function x(e, n) {
42
- return function(...r) {
43
- const [i, ...c] = r;
44
- W(e, [n, ...i], ...c);
44
+ function re(t, r) {
45
+ return function(...n) {
46
+ const [u, ...a] = n;
47
+ J(t, [r, ...u], ...a);
45
48
  };
46
49
  }
47
- function W(e, ...n) {
48
- if (e = l(e), d != null && d.has(e)) return;
49
- d == null || d.add(e);
50
- const r = p.get(e);
51
- if (!r) return;
52
- [...r.values()].forEach((c) => {
53
- const t = new EventTarget(), s = new Event("__trigger__");
54
- t.addEventListener(s.type, o), t.dispatchEvent(s);
55
- function o() {
56
- t.removeEventListener(s.type, o), c(...n);
50
+ function J(t, ...r) {
51
+ if (t = _(t), y != null && y.has(t)) return;
52
+ y == null || y.add(t);
53
+ const n = C.get(t);
54
+ if (!n) return;
55
+ [...n.values()].forEach((a) => {
56
+ const o = new EventTarget(), c = new Event("__trigger__");
57
+ o.addEventListener(c.type, s), o.dispatchEvent(c);
58
+ function s() {
59
+ o.removeEventListener(c.type, s), a(...r);
57
60
  }
58
61
  });
59
62
  }
60
- function l(e) {
61
- return typeof e != "object" || e === null ? e : e[O] ?? e;
63
+ function _(t) {
64
+ return typeof t != "object" || t === null ? t : t[ie] ?? t;
62
65
  }
63
- function j(e, n) {
64
- if (e = l(e), ["constructor", "__proto__"].includes(n))
65
- return Reflect.get(e, n);
66
- if (n === "hasOwnProperty")
67
- return function(r) {
68
- return Object.prototype.hasOwnProperty.call(l(this), r);
66
+ function ue(t, r) {
67
+ if (t = _(t), ["constructor", "__proto__"].includes(r))
68
+ return Reflect.get(t, r);
69
+ if (r === "hasOwnProperty")
70
+ return function(n) {
71
+ return Object.prototype.hasOwnProperty.call(_(this), n);
69
72
  };
70
- if (Array.isArray(e) && v.includes(n))
71
- return function(...r) {
72
- const i = v[n].apply(l(this), r);
73
- return i === -1 || i === !1 ? v[n].apply(l(this), r.map(l)) : i;
73
+ if (Array.isArray(t) && z.includes(r))
74
+ return function(...n) {
75
+ const u = z[r].apply(_(this), n);
76
+ return u === -1 || u === !1 ? z[r].apply(_(this), n.map(_)) : u;
74
77
  };
75
78
  }
76
- const h = Symbol("instance"), b = /* @__PURE__ */ new WeakMap(), E = /* @__PURE__ */ new WeakSet(), z = /* @__PURE__ */ new WeakMap(), m = /* @__PURE__ */ new WeakMap();
77
- function D(e) {
78
- if (E.has(e))
79
- return e;
80
- if (b.has(e))
81
- return b.get(e);
82
- const n = {};
83
- t.prototype = new Proxy(
79
+ const g = Symbol("instance"), A = /* @__PURE__ */ new WeakMap(), ne = /* @__PURE__ */ new WeakSet(), G = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakMap();
80
+ function W(t) {
81
+ if (ne.has(t))
82
+ return t;
83
+ if (A.has(t))
84
+ return A.get(t);
85
+ const r = {};
86
+ o.prototype = new Proxy(
84
87
  {
85
- constructor: e,
86
- __proto__: e.prototype
88
+ constructor: t,
89
+ __proto__: t.prototype
87
90
  },
88
91
  {
89
- get(s, o, u) {
90
- let f = j(s, o);
91
- return f || (f = Reflect.get(s, o, u), typeof o == "symbol" || ["constructor", "__proto__"].includes(o) || typeof f != "function") ? f : (n[o] || (n[o] = function(...y) {
92
- return f.apply(w(this), y);
93
- }), n[o]);
92
+ get(c, s, f) {
93
+ let l = ue(c, s);
94
+ return l || (l = Reflect.get(c, s, f), typeof s == "symbol" || ["constructor", "__proto__"].includes(s) || typeof l != "function") ? l : (r[s] || (r[s] = function(...p) {
95
+ return l.apply(x(this), p);
96
+ }), r[s]);
94
97
  }
95
98
  }
96
99
  );
97
- const r = /* @__PURE__ */ new Map(), i = new FinalizationRegistry(
98
- ({ args: s, token: o }) => {
99
- var u;
100
- F(r, s), (u = m.get(o)) == null || u(), i.unregister(o);
101
- }
102
- ), c = new Proxy(e, {
103
- apply(s, o, u) {
104
- var y, P, k, S;
105
- let f = r;
106
- for (let a = 0; a < u.length; a++)
107
- f.has(u[a]) || f.set(u[a], /* @__PURE__ */ new Map()), f = f.get(u[a]);
108
- if (!f.has(h) || f.get(h) !== void 0 && !((P = (y = f.get(h)) == null ? void 0 : y.deref) != null && P.call(y))) {
109
- f.set(h, void 0);
110
- const a = w(Reflect.construct(s, u, t));
111
- f.set(h, new WeakRef(a));
112
- const M = {};
113
- z.set(a, M), i.register(a, { args: u, token: M }, M);
100
+ const n = /* @__PURE__ */ new Map(), u = new FinalizationRegistry(
101
+ ({ args: c, token: s }) => {
102
+ var f;
103
+ le(n, c), (f = V.get(s)) == null || f(), u.unregister(s);
104
+ }
105
+ ), a = new Proxy(t, {
106
+ apply(c, s, f) {
107
+ var p, h, E, w;
108
+ let l = n;
109
+ for (let R = 0; R < f.length; R++)
110
+ l.has(f[R]) || l.set(f[R], /* @__PURE__ */ new Map()), l = l.get(f[R]);
111
+ if (!l.has(g) || l.get(g) !== void 0 && !((h = (p = l.get(g)) == null ? void 0 : p.deref) != null && h.call(p))) {
112
+ l.set(g, void 0);
113
+ const R = x(Reflect.construct(c, f, o));
114
+ l.set(g, new WeakRef(R));
115
+ const P = fe(R);
116
+ u.register(R, { args: f, token: P }, P);
114
117
  }
115
- return (S = (k = f.get(h)) == null ? void 0 : k.deref) == null ? void 0 : S.call(k);
118
+ return (w = (E = l.get(g)) == null ? void 0 : E.deref) == null ? void 0 : w.call(E);
116
119
  }
117
120
  });
118
- return b.set(e, c), E.add(c), b.get(e);
119
- function t() {
121
+ return A.set(t, a), ne.add(a), A.get(t);
122
+ function o() {
120
123
  }
121
124
  }
122
- function F(e, n) {
123
- if (n.length === 0) return e.delete(h);
124
- const [r, ...i] = n, c = e.get(r);
125
- if (!(c instanceof Map && (F(c, i), c.size > 0)))
126
- return e.delete(r);
125
+ function le(t, r) {
126
+ if (r.length === 0) return t.delete(g);
127
+ const [n, ...u] = r, a = t.get(n);
128
+ if (!(a instanceof Map && (le(a, u), a.size > 0)))
129
+ return t.delete(n);
127
130
  }
128
- function q(e) {
129
- const n = w(e), r = z.get(n);
131
+ function Ue(t) {
132
+ const r = x(t), n = fe(r);
130
133
  return {
131
- register(i) {
132
- r && m.set(r, i);
134
+ register(u) {
135
+ n && V.set(n, u);
133
136
  },
134
137
  unregister() {
135
- r && m.delete(r);
138
+ n && V.delete(n);
136
139
  }
137
140
  };
138
141
  }
139
- const G = /* @__PURE__ */ Object.create(null);
140
- function B(e, n) {
141
- const r = D(e), i = n ? r(...n) : G;
142
- return I(i);
142
+ function fe(t) {
143
+ return G.has(t) || G.set(t, {}), G.get(t);
144
+ }
145
+ const Ae = /* @__PURE__ */ Object.create(null);
146
+ function ze(t, r) {
147
+ const n = W(t), u = r ? n(...r) : Ae;
148
+ return Me(u);
149
+ }
150
+ function Me(t) {
151
+ const [, r] = Oe((n) => (n + 1) % 100, 0);
152
+ return Se(() => (r(), q(t, () => r())), [t]), t;
143
153
  }
144
- function I(e) {
145
- const n = C(null);
146
- n.current !== e && (n.current = e);
147
- const [, r] = A((i) => (i + 1) % 100, 0);
148
- return L(() => R(n.current, () => {
149
- r();
150
- }), [n.current]), n.current;
154
+ class Ce {
155
+ constructor(r, ...n) {
156
+ T(this, "symbol", Symbol());
157
+ T(this, "args");
158
+ this.target = r, this.args = n;
159
+ }
160
+ }
161
+ const Ne = W(Ce);
162
+ class Le {
163
+ constructor() {
164
+ T(this, "loading", {});
165
+ T(this, "globalLoading", 0);
166
+ T(this, "onceTokens", /* @__PURE__ */ new WeakMap());
167
+ T(this, "oncePool", {});
168
+ }
169
+ addGlobalLoading() {
170
+ this.globalLoading++;
171
+ }
172
+ subGlobalLoading() {
173
+ this.globalLoading--;
174
+ }
175
+ load(r = !1) {
176
+ return (n, { name: u }) => {
177
+ const { loading: a, addGlobalLoading: o, subGlobalLoading: c } = this;
178
+ return async function(...s) {
179
+ const f = Reflect.get(this, u), l = Ne(f, ...s);
180
+ if (!!a[l.symbol]) return a[l.symbol][1];
181
+ const { promise: h, resolve: E, reject: w } = Promise.withResolvers();
182
+ a[l.symbol] = [f, h], r && o();
183
+ try {
184
+ const R = await n.apply(this, s);
185
+ E(R);
186
+ } catch (R) {
187
+ w(R);
188
+ }
189
+ return Reflect.deleteProperty(a, l.symbol), r && c(), h;
190
+ };
191
+ };
192
+ }
193
+ once(r, { name: n }) {
194
+ const { oncePool: u, onceTokens: a } = this;
195
+ return function(...o) {
196
+ const c = Reflect.get(this, n);
197
+ a.has(c) || a.set(c, Symbol());
198
+ const s = a.get(c);
199
+ return !!u[s] || (u[s] = r.apply(this, o).catch((l) => (Reflect.deleteProperty(u, s), Promise.reject(l)))), u[s];
200
+ };
201
+ }
202
+ isLoading(r) {
203
+ return Object.getOwnPropertySymbols(this.loading).some(
204
+ (n) => this.loading[n][0] === r
205
+ );
206
+ }
207
+ get isGlobalLoading() {
208
+ return this.globalLoading > 0;
209
+ }
210
+ }
211
+ const Ge = W(Le)();
212
+ var M = { exports: {} }, S = {};
213
+ /**
214
+ * @license React
215
+ * react-jsx-runtime.production.js
216
+ *
217
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
218
+ *
219
+ * This source code is licensed under the MIT license found in the
220
+ * LICENSE file in the root directory of this source tree.
221
+ */
222
+ var oe;
223
+ function We() {
224
+ if (oe) return S;
225
+ oe = 1;
226
+ var t = Symbol.for("react.transitional.element"), r = Symbol.for("react.fragment");
227
+ function n(u, a, o) {
228
+ var c = null;
229
+ if (o !== void 0 && (c = "" + o), a.key !== void 0 && (c = "" + a.key), "key" in a) {
230
+ o = {};
231
+ for (var s in a)
232
+ s !== "key" && (o[s] = a[s]);
233
+ } else o = a;
234
+ return a = o.ref, {
235
+ $$typeof: t,
236
+ type: u,
237
+ key: c,
238
+ ref: a !== void 0 ? a : null,
239
+ props: o
240
+ };
241
+ }
242
+ return S.Fragment = r, S.jsx = n, S.jsxs = n, S;
243
+ }
244
+ var j = {};
245
+ /**
246
+ * @license React
247
+ * react-jsx-runtime.development.js
248
+ *
249
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
250
+ *
251
+ * This source code is licensed under the MIT license found in the
252
+ * LICENSE file in the root directory of this source tree.
253
+ */
254
+ var se;
255
+ function Ye() {
256
+ return se || (se = 1, process.env.NODE_ENV !== "production" && function() {
257
+ function t(e) {
258
+ if (e == null) return null;
259
+ if (typeof e == "function")
260
+ return e.$$typeof === he ? null : e.displayName || e.name || null;
261
+ if (typeof e == "string") return e;
262
+ switch (e) {
263
+ case P:
264
+ return "Fragment";
265
+ case be:
266
+ return "Profiler";
267
+ case de:
268
+ return "StrictMode";
269
+ case Ee:
270
+ return "Suspense";
271
+ case _e:
272
+ return "SuspenseList";
273
+ case ye:
274
+ return "Activity";
275
+ }
276
+ if (typeof e == "object")
277
+ switch (typeof e.tag == "number" && console.error(
278
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
279
+ ), e.$$typeof) {
280
+ case R:
281
+ return "Portal";
282
+ case Re:
283
+ return (e.displayName || "Context") + ".Provider";
284
+ case me:
285
+ return (e._context.displayName || "Context") + ".Consumer";
286
+ case pe:
287
+ var i = e.render;
288
+ return e = e.displayName, e || (e = i.displayName || i.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
289
+ case ve:
290
+ return i = e.displayName || null, i !== null ? i : t(e.type) || "Memo";
291
+ case B:
292
+ i = e._payload, e = e._init;
293
+ try {
294
+ return t(e(i));
295
+ } catch {
296
+ }
297
+ }
298
+ return null;
299
+ }
300
+ function r(e) {
301
+ return "" + e;
302
+ }
303
+ function n(e) {
304
+ try {
305
+ r(e);
306
+ var i = !1;
307
+ } catch {
308
+ i = !0;
309
+ }
310
+ if (i) {
311
+ i = console;
312
+ var d = i.error, b = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
313
+ return d.call(
314
+ i,
315
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
316
+ b
317
+ ), r(e);
318
+ }
319
+ }
320
+ function u(e) {
321
+ if (e === P) return "<>";
322
+ if (typeof e == "object" && e !== null && e.$$typeof === B)
323
+ return "<...>";
324
+ try {
325
+ var i = t(e);
326
+ return i ? "<" + i + ">" : "<...>";
327
+ } catch {
328
+ return "<...>";
329
+ }
330
+ }
331
+ function a() {
332
+ var e = Y.A;
333
+ return e === null ? null : e.getOwner();
334
+ }
335
+ function o() {
336
+ return Error("react-stack-top-frame");
337
+ }
338
+ function c(e) {
339
+ if (H.call(e, "key")) {
340
+ var i = Object.getOwnPropertyDescriptor(e, "key").get;
341
+ if (i && i.isReactWarning) return !1;
342
+ }
343
+ return e.key !== void 0;
344
+ }
345
+ function s(e, i) {
346
+ function d() {
347
+ Z || (Z = !0, console.error(
348
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
349
+ i
350
+ ));
351
+ }
352
+ d.isReactWarning = !0, Object.defineProperty(e, "key", {
353
+ get: d,
354
+ configurable: !0
355
+ });
356
+ }
357
+ function f() {
358
+ var e = t(this.type);
359
+ return Q[e] || (Q[e] = !0, console.error(
360
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
361
+ )), e = this.props.ref, e !== void 0 ? e : null;
362
+ }
363
+ function l(e, i, d, b, k, v, I, $) {
364
+ return d = v.ref, e = {
365
+ $$typeof: w,
366
+ type: e,
367
+ key: i,
368
+ props: v,
369
+ _owner: k
370
+ }, (d !== void 0 ? d : null) !== null ? Object.defineProperty(e, "ref", {
371
+ enumerable: !1,
372
+ get: f
373
+ }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
374
+ configurable: !1,
375
+ enumerable: !1,
376
+ writable: !0,
377
+ value: 0
378
+ }), Object.defineProperty(e, "_debugInfo", {
379
+ configurable: !1,
380
+ enumerable: !1,
381
+ writable: !0,
382
+ value: null
383
+ }), Object.defineProperty(e, "_debugStack", {
384
+ configurable: !1,
385
+ enumerable: !1,
386
+ writable: !0,
387
+ value: I
388
+ }), Object.defineProperty(e, "_debugTask", {
389
+ configurable: !1,
390
+ enumerable: !1,
391
+ writable: !0,
392
+ value: $
393
+ }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
394
+ }
395
+ function p(e, i, d, b, k, v, I, $) {
396
+ var m = i.children;
397
+ if (m !== void 0)
398
+ if (b)
399
+ if (ke(m)) {
400
+ for (b = 0; b < m.length; b++)
401
+ h(m[b]);
402
+ Object.freeze && Object.freeze(m);
403
+ } else
404
+ console.error(
405
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
406
+ );
407
+ else h(m);
408
+ if (H.call(i, "key")) {
409
+ m = t(e);
410
+ var O = Object.keys(i).filter(function(we) {
411
+ return we !== "key";
412
+ });
413
+ b = 0 < O.length ? "{key: someKey, " + O.join(": ..., ") + ": ...}" : "{key: someKey}", te[m + b] || (O = 0 < O.length ? "{" + O.join(": ..., ") + ": ...}" : "{}", console.error(
414
+ `A props object containing a "key" prop is being spread into JSX:
415
+ let props = %s;
416
+ <%s {...props} />
417
+ React keys must be passed directly to JSX without using spread:
418
+ let props = %s;
419
+ <%s key={someKey} {...props} />`,
420
+ b,
421
+ m,
422
+ O,
423
+ m
424
+ ), te[m + b] = !0);
425
+ }
426
+ if (m = null, d !== void 0 && (n(d), m = "" + d), c(i) && (n(i.key), m = "" + i.key), "key" in i) {
427
+ d = {};
428
+ for (var D in i)
429
+ D !== "key" && (d[D] = i[D]);
430
+ } else d = i;
431
+ return m && s(
432
+ d,
433
+ typeof e == "function" ? e.displayName || e.name || "Unknown" : e
434
+ ), l(
435
+ e,
436
+ m,
437
+ v,
438
+ k,
439
+ a(),
440
+ d,
441
+ I,
442
+ $
443
+ );
444
+ }
445
+ function h(e) {
446
+ typeof e == "object" && e !== null && e.$$typeof === w && e._store && (e._store.validated = 1);
447
+ }
448
+ var E = Pe, w = Symbol.for("react.transitional.element"), R = Symbol.for("react.portal"), P = Symbol.for("react.fragment"), de = Symbol.for("react.strict_mode"), be = Symbol.for("react.profiler"), me = Symbol.for("react.consumer"), Re = Symbol.for("react.context"), pe = Symbol.for("react.forward_ref"), Ee = Symbol.for("react.suspense"), _e = Symbol.for("react.suspense_list"), ve = Symbol.for("react.memo"), B = Symbol.for("react.lazy"), ye = Symbol.for("react.activity"), he = Symbol.for("react.client.reference"), Y = E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, H = Object.prototype.hasOwnProperty, ke = Array.isArray, F = console.createTask ? console.createTask : function() {
449
+ return null;
450
+ };
451
+ E = {
452
+ "react-stack-bottom-frame": function(e) {
453
+ return e();
454
+ }
455
+ };
456
+ var Z, Q = {}, K = E["react-stack-bottom-frame"].bind(
457
+ E,
458
+ o
459
+ )(), ee = F(u(o)), te = {};
460
+ j.Fragment = P, j.jsx = function(e, i, d, b, k) {
461
+ var v = 1e4 > Y.recentlyCreatedOwnerStacks++;
462
+ return p(
463
+ e,
464
+ i,
465
+ d,
466
+ !1,
467
+ b,
468
+ k,
469
+ v ? Error("react-stack-top-frame") : K,
470
+ v ? F(u(e)) : ee
471
+ );
472
+ }, j.jsxs = function(e, i, d, b, k) {
473
+ var v = 1e4 > Y.recentlyCreatedOwnerStacks++;
474
+ return p(
475
+ e,
476
+ i,
477
+ d,
478
+ !0,
479
+ b,
480
+ k,
481
+ v ? Error("react-stack-top-frame") : K,
482
+ v ? F(u(e)) : ee
483
+ );
484
+ };
485
+ }()), j;
486
+ }
487
+ var ae;
488
+ function Fe() {
489
+ return ae || (ae = 1, process.env.NODE_ENV === "production" ? M.exports = We() : M.exports = Ye()), M.exports;
490
+ }
491
+ var Ie = Fe();
492
+ const N = {}, L = {}, X = je({ namespace: "" }), qe = ({
493
+ children: t,
494
+ namespace: r = ""
495
+ }) => /* @__PURE__ */ Ie.jsx(X.Provider, { value: { namespace: r }, children: t });
496
+ function Je({ schema: t, ctor: r }) {
497
+ const { namespace: n } = ce(X);
498
+ return N[n] || (N[n] = /* @__PURE__ */ new Map()), N[n].set(t, r), null;
499
+ }
500
+ function Ve({
501
+ schema: t,
502
+ val: r
503
+ }) {
504
+ const { namespace: n } = ce(X);
505
+ return L[n] || (L[n] = /* @__PURE__ */ new Map()), L[n].set(t, r), null;
506
+ }
507
+ function Xe(t, r = "") {
508
+ return (n, { static: u, kind: a }) => {
509
+ if (a !== "field") throw "不能装饰非属性";
510
+ if (u) throw "不能装饰静态属性";
511
+ return function(o) {
512
+ let c = o;
513
+ const s = N[r].get(t);
514
+ s ? c = W(s)() : c = L[r].get(t) ?? c;
515
+ const { success: f, error: l } = t.safeParse(c);
516
+ return f ? c : (console.error("====注入属性失败====", l), o);
517
+ };
518
+ };
151
519
  }
152
520
  export {
153
- q as finalizationRegistry,
154
- D as provide,
155
- I as useInstance,
156
- B as useModel,
157
- R as watch
521
+ Je as CInjection,
522
+ qe as Container,
523
+ Ve as VInjection,
524
+ Ue as finalizationRegistry,
525
+ Xe as inject,
526
+ Ge as loader,
527
+ W as provide,
528
+ Me as useInstance,
529
+ ze as useModel,
530
+ q as watch
158
531
  };
package/dist/index.umd.js CHANGED
@@ -1 +1,22 @@
1
- (function(l,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],w):(l=typeof globalThis<"u"?globalThis:l||self,w(l["@e7w/easy-model"]={},l.React))})(this,function(l,w){"use strict";const R=new WeakMap,k=new WeakMap,O=Symbol("origin");let d=null;const m=["includes","indexOf","lastIndexOf"],L=[Promise,RegExp,Date,WeakMap,WeakSet,Map,Set];function p(e){if(e=a(e),!e||L.some(r=>e instanceof r))return e;if(R.has(e))return R.get(e);const n={},o={},s=new Proxy(e,{get(r,t,c){if(t===O)return r;let i=E(r,t);return i||(i=Reflect.get(r,t,c),typeof i=="function"?(o[t]||(o[t]=i.bind(p(r))),i=o[t]):typeof i=="object"&&i!==null&&(n[t]||(n[t]=M(i,j(e,t))),i=p(i)),i)},set(r,t,c,i){let u=Reflect.get(r,t,i);if(u=a(u),c=a(c),u===c)return!0;const f=Reflect.set(r,t,c,i);if(f){n[t]&&(n[t](),delete n[t]),typeof c=="object"&&c!==null&&(n[t]=M(c,j(e,t))),o[t]&&delete o[t];const h=d;d=new WeakSet,W(r,[t],u,c),d=h}return f},deleteProperty(r,t){let c=Reflect.get(r,t);c=a(c);const i=Reflect.deleteProperty(r,t);return i&&(n[t]&&(n[t](),delete n[t]),o[t]&&delete o[t],W(r,[t],c,void 0)),i}});return R.set(e,s),s}function M(e,n){e=a(e),k.has(e)||k.set(e,new Map);const o=k.get(e),s=Symbol();return o.set(s,n),function(){o.delete(s)}}function j(e,n){return function(...o){const[s,...r]=o;W(e,[n,...s],...r)}}function W(e,...n){if(e=a(e),d!=null&&d.has(e))return;d==null||d.add(e);const o=k.get(e);if(!o)return;[...o.values()].forEach(r=>{const t=new EventTarget,c=new Event("__trigger__");t.addEventListener(c.type,i),t.dispatchEvent(c);function i(){t.removeEventListener(c.type,i),r(...n)}})}function a(e){return typeof e!="object"||e===null?e:e[O]??e}function E(e,n){if(e=a(e),["constructor","__proto__"].includes(n))return Reflect.get(e,n);if(n==="hasOwnProperty")return function(o){return Object.prototype.hasOwnProperty.call(a(this),o)};if(Array.isArray(e)&&m.includes(n))return function(...o){const s=m[n].apply(a(this),o);return s===-1||s===!1?m[n].apply(a(this),o.map(a)):s}}const b=Symbol("instance"),_=new WeakMap,x=new WeakSet,z=new WeakMap,S=new WeakMap;function F(e){if(x.has(e))return e;if(_.has(e))return _.get(e);const n={};t.prototype=new Proxy({constructor:e,__proto__:e.prototype},{get(c,i,u){let f=E(c,i);return f||(f=Reflect.get(c,i,u),typeof i=="symbol"||["constructor","__proto__"].includes(i)||typeof f!="function")?f:(n[i]||(n[i]=function(...h){return f.apply(p(this),h)}),n[i])}});const o=new Map,s=new FinalizationRegistry(({args:c,token:i})=>{var u;T(o,c),(u=S.get(i))==null||u(),s.unregister(i)}),r=new Proxy(e,{apply(c,i,u){var h,A,v,I;let f=o;for(let y=0;y<u.length;y++)f.has(u[y])||f.set(u[y],new Map),f=f.get(u[y]);if(!f.has(b)||f.get(b)!==void 0&&!((A=(h=f.get(b))==null?void 0:h.deref)!=null&&A.call(h))){f.set(b,void 0);const y=p(Reflect.construct(c,u,t));f.set(b,new WeakRef(y));const P={};z.set(y,P),s.register(y,{args:u,token:P},P)}return(I=(v=f.get(b))==null?void 0:v.deref)==null?void 0:I.call(v)}});return _.set(e,r),x.add(r),_.get(e);function t(){}}function T(e,n){if(n.length===0)return e.delete(b);const[o,...s]=n,r=e.get(o);if(!(r instanceof Map&&(T(r,s),r.size>0)))return e.delete(o)}function U(e){const n=p(e),o=z.get(n);return{register(s){o&&S.set(o,s)},unregister(){o&&S.delete(o)}}}const g=Object.create(null);function q(e,n){const o=F(e),s=n?o(...n):g;return C(s)}function C(e){const n=w.useRef(null);n.current!==e&&(n.current=e);const[,o]=w.useReducer(s=>(s+1)%100,0);return w.useEffect(()=>M(n.current,()=>{o()}),[n.current]),n.current}l.finalizationRegistry=U,l.provide=F,l.useInstance=C,l.useModel=q,l.watch=M,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});
1
+ (function(b,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],m):(b=typeof globalThis<"u"?globalThis:b||self,m(b["@e7w/easy-model"]={},b.React))})(this,function(b,m){"use strict";var Ue=Object.defineProperty;var Ge=(b,m,w)=>m in b?Ue(b,m,{enumerable:!0,configurable:!0,writable:!0,value:w}):b[m]=w;var O=(b,m,w)=>Ge(b,typeof m!="symbol"?m+"":m,w);const w=new WeakMap,L=new WeakMap,Z=Symbol("origin");let k=null;const z=["includes","indexOf","lastIndexOf"],me=[Promise,RegExp,Date,WeakMap,WeakSet,Map,Set];function x(t){if(t=h(t),!t||me.some(a=>t instanceof a))return t;if(w.has(t))return w.get(t);const n={},r={},u=new Proxy(t,{get(a,o,c){if(o===Z)return a;let s=K(a,o);return s||(s=Reflect.get(a,o,c),typeof s=="function"?(r[o]||(r[o]=s.bind(x(a))),s=r[o]):typeof s=="object"&&s!==null&&(n[o]||(n[o]=W(s,Q(t,o))),s=x(s)),s)},set(a,o,c,s){let f=Reflect.get(a,o,s);if(f=h(f),c=h(c),f===c)return!0;const l=Reflect.set(a,o,c,s);if(l){n[o]&&(n[o](),delete n[o]),typeof c=="object"&&c!==null&&(n[o]=W(c,Q(t,o))),r[o]&&delete r[o];const v=k;k=new WeakSet,U(a,[o],f,c),k=v}return l},deleteProperty(a,o){let c=Reflect.get(a,o);c=h(c);const s=Reflect.deleteProperty(a,o);return s&&(n[o]&&(n[o](),delete n[o]),r[o]&&delete r[o],U(a,[o],c,void 0)),s}});return w.set(t,u),u}function W(t,n){t=h(t),L.has(t)||L.set(t,new Map);const r=L.get(t),u=Symbol();return r.set(u,n),function(){r.delete(u)}}function Q(t,n){return function(...r){const[u,...a]=r;U(t,[n,...u],...a)}}function U(t,...n){if(t=h(t),k!=null&&k.has(t))return;k==null||k.add(t);const r=L.get(t);if(!r)return;[...r.values()].forEach(a=>{const o=new EventTarget,c=new Event("__trigger__");o.addEventListener(c.type,s),o.dispatchEvent(c);function s(){o.removeEventListener(c.type,s),a(...n)}})}function h(t){return typeof t!="object"||t===null?t:t[Z]??t}function K(t,n){if(t=h(t),["constructor","__proto__"].includes(n))return Reflect.get(t,n);if(n==="hasOwnProperty")return function(r){return Object.prototype.hasOwnProperty.call(h(this),r)};if(Array.isArray(t)&&z.includes(n))return function(...r){const u=z[n].apply(h(this),r);return u===-1||u===!1?z[n].apply(h(this),r.map(h)):u}}const P=Symbol("instance"),I=new WeakMap,ee=new WeakSet,G=new WeakMap,J=new WeakMap;function C(t){if(ee.has(t))return t;if(I.has(t))return I.get(t);const n={};o.prototype=new Proxy({constructor:t,__proto__:t.prototype},{get(c,s,f){let l=K(c,s);return l||(l=Reflect.get(c,s,f),typeof s=="symbol"||["constructor","__proto__"].includes(s)||typeof l!="function")?l:(n[s]||(n[s]=function(...v){return l.apply(x(this),v)}),n[s])}});const r=new Map,u=new FinalizationRegistry(({args:c,token:s})=>{var f;te(r,c),(f=J.get(s))==null||f(),u.unregister(s)}),a=new Proxy(t,{apply(c,s,f){var v,T,p,j;let l=r;for(let E=0;E<f.length;E++)l.has(f[E])||l.set(f[E],new Map),l=l.get(f[E]);if(!l.has(P)||l.get(P)!==void 0&&!((T=(v=l.get(P))==null?void 0:v.deref)!=null&&T.call(v))){l.set(P,void 0);const E=x(Reflect.construct(c,f,o));l.set(P,new WeakRef(E));const S=ne(E);u.register(E,{args:f,token:S},S)}return(j=(p=l.get(P))==null?void 0:p.deref)==null?void 0:j.call(p)}});return I.set(t,a),ee.add(a),I.get(t);function o(){}}function te(t,n){if(n.length===0)return t.delete(P);const[r,...u]=n,a=t.get(r);if(!(a instanceof Map&&(te(a,u),a.size>0)))return t.delete(r)}function Re(t){const n=x(t),r=ne(n);return{register(u){r&&J.set(r,u)},unregister(){r&&J.delete(r)}}}function ne(t){return G.has(t)||G.set(t,{}),G.get(t)}const ye=Object.create(null);function Ee(t,n){const r=C(t),u=n?r(...n):ye;return re(u)}function re(t){const[,n]=m.useReducer(r=>(r+1)%100,0);return m.useEffect(()=>(n(),W(t,()=>n())),[t]),t}class ve{constructor(n,...r){O(this,"symbol",Symbol());O(this,"args");this.target=n,this.args=r}}const he=C(ve);class pe{constructor(){O(this,"loading",{});O(this,"globalLoading",0);O(this,"onceTokens",new WeakMap);O(this,"oncePool",{})}addGlobalLoading(){this.globalLoading++}subGlobalLoading(){this.globalLoading--}load(n=!1){return(r,{name:u})=>{const{loading:a,addGlobalLoading:o,subGlobalLoading:c}=this;return async function(...s){const f=Reflect.get(this,u),l=he(f,...s);if(!!a[l.symbol])return a[l.symbol][1];const{promise:T,resolve:p,reject:j}=Promise.withResolvers();a[l.symbol]=[f,T],n&&o();try{const E=await r.apply(this,s);p(E)}catch(E){j(E)}return Reflect.deleteProperty(a,l.symbol),n&&c(),T}}}once(n,{name:r}){const{oncePool:u,onceTokens:a}=this;return function(...o){const c=Reflect.get(this,r);a.has(c)||a.set(c,Symbol());const s=a.get(c);return!!u[s]||(u[s]=n.apply(this,o).catch(l=>(Reflect.deleteProperty(u,s),Promise.reject(l)))),u[s]}}isLoading(n){return Object.getOwnPropertySymbols(this.loading).some(r=>this.loading[r][0]===n)}get isGlobalLoading(){return this.globalLoading>0}}const _e=C(pe)();var Y={exports:{}},M={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var oe;function ke(){if(oe)return M;oe=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(u,a,o){var c=null;if(o!==void 0&&(c=""+o),a.key!==void 0&&(c=""+a.key),"key"in a){o={};for(var s in a)s!=="key"&&(o[s]=a[s])}else o=a;return a=o.ref,{$$typeof:t,type:u,key:c,ref:a!==void 0?a:null,props:o}}return M.Fragment=n,M.jsx=r,M.jsxs=r,M}var N={};/**
10
+ * @license React
11
+ * react-jsx-runtime.development.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var se;function we(){return se||(se=1,process.env.NODE_ENV!=="production"&&function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Fe?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case S:return"Fragment";case xe:return"Profiler";case Ae:return"StrictMode";case Le:return"Suspense";case We:return"SuspenseList";case Ye:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case E:return"Portal";case Me:return(e.displayName||"Context")+".Provider";case Ce:return(e._context.displayName||"Context")+".Consumer";case Ne:var i=e.render;return e=e.displayName,e||(e=i.displayName||i.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ie:return i=e.displayName||null,i!==null?i:t(e.type)||"Memo";case ce:i=e._payload,e=e._init;try{return t(e(i))}catch{}}return null}function n(e){return""+e}function r(e){try{n(e);var i=!1}catch{i=!0}if(i){i=console;var d=i.error,R=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return d.call(i,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",R),n(e)}}function u(e){if(e===S)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===ce)return"<...>";try{var i=t(e);return i?"<"+i+">":"<...>"}catch{return"<...>"}}function a(){var e=X.A;return e===null?null:e.getOwner()}function o(){return Error("react-stack-top-frame")}function c(e){if(ie.call(e,"key")){var i=Object.getOwnPropertyDescriptor(e,"key").get;if(i&&i.isReactWarning)return!1}return e.key!==void 0}function s(e,i){function d(){ue||(ue=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",i))}d.isReactWarning=!0,Object.defineProperty(e,"key",{get:d,configurable:!0})}function f(){var e=t(this.type);return le[e]||(le[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function l(e,i,d,R,g,_,q,$){return d=_.ref,e={$$typeof:j,type:e,key:i,props:_,_owner:g},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:f}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:q}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:$}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function v(e,i,d,R,g,_,q,$){var y=i.children;if(y!==void 0)if(R)if(De(y)){for(R=0;R<y.length;R++)T(y[R]);Object.freeze&&Object.freeze(y)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else T(y);if(ie.call(i,"key")){y=t(e);var A=Object.keys(i).filter(function(ze){return ze!=="key"});R=0<A.length?"{key: someKey, "+A.join(": ..., ")+": ...}":"{key: someKey}",be[y+R]||(A=0<A.length?"{"+A.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
+ let props = %s;
19
+ <%s {...props} />
20
+ React keys must be passed directly to JSX without using spread:
21
+ let props = %s;
22
+ <%s key={someKey} {...props} />`,R,y,A,y),be[y+R]=!0)}if(y=null,d!==void 0&&(r(d),y=""+d),c(i)&&(r(i.key),y=""+i.key),"key"in i){d={};for(var H in i)H!=="key"&&(d[H]=i[H])}else d=i;return y&&s(d,typeof e=="function"?e.displayName||e.name||"Unknown":e),l(e,y,_,g,a(),d,q,$)}function T(e){typeof e=="object"&&e!==null&&e.$$typeof===j&&e._store&&(e._store.validated=1)}var p=m,j=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),S=Symbol.for("react.fragment"),Ae=Symbol.for("react.strict_mode"),xe=Symbol.for("react.profiler"),Ce=Symbol.for("react.consumer"),Me=Symbol.for("react.context"),Ne=Symbol.for("react.forward_ref"),Le=Symbol.for("react.suspense"),We=Symbol.for("react.suspense_list"),Ie=Symbol.for("react.memo"),ce=Symbol.for("react.lazy"),Ye=Symbol.for("react.activity"),Fe=Symbol.for("react.client.reference"),X=p.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ie=Object.prototype.hasOwnProperty,De=Array.isArray,B=console.createTask?console.createTask:function(){return null};p={"react-stack-bottom-frame":function(e){return e()}};var ue,le={},fe=p["react-stack-bottom-frame"].bind(p,o)(),de=B(u(o)),be={};N.Fragment=S,N.jsx=function(e,i,d,R,g){var _=1e4>X.recentlyCreatedOwnerStacks++;return v(e,i,d,!1,R,g,_?Error("react-stack-top-frame"):fe,_?B(u(e)):de)},N.jsxs=function(e,i,d,R,g){var _=1e4>X.recentlyCreatedOwnerStacks++;return v(e,i,d,!0,R,g,_?Error("react-stack-top-frame"):fe,_?B(u(e)):de)}}()),N}var ae;function Te(){return ae||(ae=1,process.env.NODE_ENV==="production"?Y.exports=ke():Y.exports=we()),Y.exports}var ge=Te();const F={},D={},V=m.createContext({namespace:""}),Pe=({children:t,namespace:n=""})=>ge.jsx(V.Provider,{value:{namespace:n},children:t});function je({schema:t,ctor:n}){const{namespace:r}=m.useContext(V);return F[r]||(F[r]=new Map),F[r].set(t,n),null}function Oe({schema:t,val:n}){const{namespace:r}=m.useContext(V);return D[r]||(D[r]=new Map),D[r].set(t,n),null}function Se(t,n=""){return(r,{static:u,kind:a})=>{if(a!=="field")throw"不能装饰非属性";if(u)throw"不能装饰静态属性";return function(o){let c=o;const s=F[n].get(t);s?c=C(s)():c=D[n].get(t)??c;const{success:f,error:l}=t.safeParse(c);return f?c:(console.error("====注入属性失败====",l),o)}}}b.CInjection=je,b.Container=Pe,b.VInjection=Oe,b.finalizationRegistry=Re,b.inject=Se,b.loader=_e,b.provide=C,b.useInstance=re,b.useModel=Ee,b.watch=W,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e7w/easy-model",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "module": "./dist/index.es.js",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -16,7 +16,8 @@
16
16
  }
17
17
  },
18
18
  "peerDependencies": {
19
- "react": ">=17.0.0"
19
+ "react": ">=17.0.0",
20
+ "zod": "^4.1.5"
20
21
  },
21
22
  "devDependencies": {
22
23
  "@eslint/js": "^9.24.0",
@@ -70,7 +71,6 @@
70
71
  "lint:styles": "stylelint ./**/*.{css,scss}",
71
72
  "format:scripts": "prettier . --write",
72
73
  "format:styles": "stylelint ./**/*.{css,scss} --fix",
73
- "format": "npm run format:scripts && npm run format:styles",
74
- "uninstall-husky": "npm uninstall husky --no-save && git config --unset core.hooksPath && npx rimraf .husky"
74
+ "format": "npm run format:scripts && npm run format:styles"
75
75
  }
76
76
  }