@geektr.cloud/acrux-core 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 geektr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @geektr.cloud/acrux-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Acrux 的 Vue 集合、异步状态与 Standard Schema 校验抽象。
4
+
5
+ ```sh
6
+ pnpm add @geektr.cloud/acrux-core
7
+ ```
8
+
9
+ 这是 **source-only** 包:入口直接指向 TypeScript 源码,消费者需要能够编译 TypeScript 的 bundler。Vue 与 VueUse 等运行时依赖通过 peer dependencies 提供。
10
+
11
+ ```ts
12
+ import { useAsyncState, useCachedCollection, useValidation } from "@geektr.cloud/acrux-core";
13
+ ```
14
+
15
+ 完整说明见 [Acrux 文档](https://acrux.geektr.cloud/packages/core)与[仓库](https://github.com/geektr-cloud/acrux)。
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@geektr.cloud/acrux-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Vue 异步状态 / 排序集合 / 校验抽象层(tuple-based)。",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/geektr-cloud/acrux.git",
10
+ "directory": "packages/acrux"
11
+ },
12
+ "homepage": "https://acrux.geektr.cloud/packages/core",
13
+ "files": [
14
+ "src",
15
+ "!**/*.test.ts",
16
+ "!**/__fixtures__/",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "registry": "https://registry.npmjs.org"
23
+ },
24
+ "exports": {
25
+ ".": "./src/index.ts"
26
+ },
27
+ "devDependencies": {
28
+ "@standard-schema/spec": "^1.1.0",
29
+ "@vueuse/core": "^15.1.0",
30
+ "hono": "^4.13.23",
31
+ "typescript": "~5.9.3",
32
+ "vitest": "^5.1.2",
33
+ "vue": "^3.5.46"
34
+ },
35
+ "peerDependencies": {
36
+ "@standard-schema/spec": "^1.0.0",
37
+ "@vueuse/core": "^15.0.0",
38
+ "hono": "^4.0.0",
39
+ "vue": "^3.5.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "hono": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "scripts": {
47
+ "type-check": "tsc --noEmit -p tsconfig.json",
48
+ "test": "vitest",
49
+ "test:run": "vitest run"
50
+ }
6
51
  }
package/src/async.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { type MaybeRef, type Reactive, type Ref, reactive } from "vue";
2
+ import { type UseAsyncStateOptions, useAsyncState as _useAsyncState } from "@vueuse/core";
3
+
4
+ /**
5
+ * 异步状态,用于描述操作的加载与错误状态
6
+ */
7
+ export type AsyncStatus = Reactive<{
8
+ error: unknown;
9
+ loading: boolean;
10
+ }>;
11
+
12
+ /**
13
+ * 异步数据结构元组
14
+ * @template T
15
+ * @typedef {[Ref<T>, AsyncStatus, () => Promise<void>]}
16
+ * state: 数据引用
17
+ * status: 异步状态
18
+ * execute: 触发异步操作的函数
19
+ */
20
+ export type AsyncState<T> = [state: Ref<T>, status: AsyncStatus, execute: () => Promise<void>];
21
+
22
+ /**
23
+ * 自定义 useAsyncState 钩子,用于处理异步请求的数据、加载和错误状态。
24
+ * @template Data 异步请求返回的数据类型
25
+ * @param promise 执行异步请求的方法,返回 Promise<Data>
26
+ * @param initialState 初始数据状态
27
+ * @param options 可选配置项,继承自 @vueuse/core 的 UseAsyncStateOptions
28
+ * @returns {[Ref<Data>, AsyncStatus, () => Promise<void>]}
29
+ * - state: 响应式数据引用
30
+ * - status: { loading: boolean, error: unknown }
31
+ * - execute: 手动触发异步请求的方法
32
+ */
33
+ export const useAsyncState = <Data>(
34
+ promise: () => Promise<Data>,
35
+ initialState: MaybeRef<Data>,
36
+ options?: UseAsyncStateOptions<true, Data>,
37
+ ): AsyncState<Data> => {
38
+ options = Object.assign({ shallow: true, immediate: false }, options);
39
+ const { state, error, isLoading, execute } = _useAsyncState(promise, initialState, options);
40
+ const fn = async () => {
41
+ await execute();
42
+ };
43
+ return [state as Ref<Data>, reactive({ error, loading: isLoading }), fn];
44
+ };
package/src/base.ts ADDED
@@ -0,0 +1,74 @@
1
+ import { type Reactive, type Ref } from "vue";
2
+ import { type AsyncState, type AsyncStatus } from "./async";
3
+ import { type UseValidation } from "./issues";
4
+
5
+ /**
6
+ * 实体主键类型
7
+ */
8
+ export type BaseId = string;
9
+ export type BaseData = { id: BaseId };
10
+
11
+ /**
12
+ * 分页信息结构(offset 式)。
13
+ * 驱动状态是 page / limit / total;pages / hasPrev / hasNext 由这三者 compute。
14
+ * offset 不属于状态——仅在调接口时由 fetchFn 从 page/limit 计算。
15
+ */
16
+ export type Pagination = Reactive<{
17
+ page: number; // 当前页码(驱动状态,从 1 开始)
18
+ limit: number; // 每页大小(驱动状态)
19
+ total: number; // 总条目数(驱动状态)
20
+ pages: number; // 总页数 = ceil(total / limit)(compute)
21
+ hasPrev: boolean; // 是否有上一页(compute)
22
+ hasNext: boolean; // 是否有下一页(compute)
23
+ go(page: number): void; // 跳转到指定页码
24
+ }>;
25
+
26
+ /**
27
+ * 异步分页列表
28
+ * @template T
29
+ * @typedef {[...AsyncState<T>, Pagination]}
30
+ */
31
+ export type AsyncPaginatedList<T> = [...AsyncState<T>, page: Pagination];
32
+
33
+ /**
34
+ * 游标分页结构(cursor 式)。
35
+ * 核心状态是 cursor / limit / hasMore,贯穿 query 与状态。
36
+ */
37
+ export type Cursor = {
38
+ cursor: BaseId | null; // 下一页游标,null 表示从头(核心状态)
39
+ limit: number; // 单次获取数量限制(核心状态)
40
+ hasMore: boolean; // 是否还有更多数据(核心状态)
41
+ next(): Promise<void>; // 获取下一页(累积追加)
42
+ };
43
+
44
+ /**
45
+ * 基于游标的异步列表
46
+ * @template T
47
+ * @typedef {[...AsyncState<T>, Cursor]}
48
+ */
49
+ export type AsyncCursorList<T> = [...AsyncState<T>, cursor: Cursor];
50
+
51
+ /**
52
+ * 删除操作元组
53
+ * @template T
54
+ * @typedef {[AsyncStatus, () => Promise<void>, AsyncState<T | undefined>]}
55
+ * - status: 删除过程的异步状态 (AsyncStatus)
56
+ * - remove: 执行删除操作的函数 (() => Promise<void>)
57
+ * - source: 被删除实体的异步状态 (AsyncState<T | undefined>)
58
+ */
59
+ export type Removal<T> = [status: AsyncStatus, remove: () => Promise<void>, source: AsyncState<T | undefined>];
60
+
61
+ /**
62
+ * UseRemoval 类型,参数为实体主键 Ref,返回 Removal 元组
63
+ * @template T
64
+ */
65
+ export type UseRemoval<T> = (id: Ref<BaseId | undefined>) => Removal<T | undefined>;
66
+
67
+ export type Upsert<T> = [
68
+ form: Reactive<T>,
69
+ issues: UseValidation,
70
+ status: AsyncStatus,
71
+ execute: () => Promise<void>,
72
+ source: AsyncState<T | undefined>,
73
+ ];
74
+ export type UseUpsert<T> = (id: Ref<BaseId | undefined>) => Upsert<T | undefined>;
@@ -0,0 +1,352 @@
1
+ import { type Ref, computed, reactive, ref, watch } from "vue";
2
+ import { watchDebounced } from "@vueuse/core";
3
+ import { type AsyncState, useAsyncState } from "./async";
4
+ import { useValidation } from "./issues";
5
+ import { useClonedReactive } from "./utils";
6
+ import type {
7
+ AsyncCursorList,
8
+ AsyncPaginatedList,
9
+ BaseData,
10
+ BaseId,
11
+ Cursor,
12
+ Pagination,
13
+ Removal,
14
+ Upsert,
15
+ } from "./base";
16
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
17
+
18
+ // ── 缓存集合(字典表场景)────────────────────────────────────────────────────
19
+ // 一次拉取、内存内复用:适合在多个筛选组件间共享的字典数据。写操作就地增删改,不重拉。
20
+ export type CachedCollectionOptions<T extends BaseData, VariantT extends T = T> = {
21
+ newItem: () => T;
22
+ fetchFn: () => Promise<VariantT[]>;
23
+ /** 兜底过期时间(ms):每个 use* 被调用前都会按此时长做一次 refreshIfStale。 */
24
+ maxAge: number;
25
+ sortFn?: (a: VariantT, b: VariantT) => number;
26
+ resolveFn?: (item: T) => Promise<VariantT>;
27
+ removeFn: (id: BaseId) => Promise<T>;
28
+ upsertFn: (item: VariantT) => Promise<T>;
29
+ upsertSchema: StandardSchemaV1;
30
+ };
31
+
32
+ export const useCachedCollection = <T extends BaseData, VariantT extends T = T>(
33
+ opts: CachedCollectionOptions<T, VariantT>,
34
+ ) => {
35
+ const sortFn = opts.sortFn ?? ((a, b) => a.id.localeCompare(b.id));
36
+ const resolveFn = opts.resolveFn ?? ((item) => item as VariantT);
37
+
38
+ // 最近一次成功拉取的时间戳(首屏与每次 reload 成功后更新)。
39
+ const lastFetched = ref(0);
40
+ const [items, status, reload] = useAsyncState(opts.fetchFn, [], {
41
+ immediate: true,
42
+ onSuccess: () => (lastFetched.value = Date.now()),
43
+ });
44
+ const sorted = computed(() => items.value.sort(sortFn));
45
+
46
+ /**
47
+ * 按需刷新:数据距上次成功拉取超过 maxAge(毫秒) 时才重新 reload,否则跳过。
48
+ * 不传 maxAge 时用 opts.maxAge 兜底。已在加载中则跳过(避免同一 tick 内重复触发)。
49
+ * 走正常 reload 流程,status.loading 照常显示。
50
+ */
51
+ const refreshIfStale = (maxAge: number = opts.maxAge) => {
52
+ if (status.loading) return;
53
+ if (Date.now() - lastFetched.value > maxAge) void reload();
54
+ };
55
+
56
+ const _upsert = async (item: VariantT) => {
57
+ const index = items.value.findIndex((i) => i.id === item.id);
58
+ if (index !== -1) {
59
+ items.value[index] = item;
60
+ } else {
61
+ items.value.push(item);
62
+ }
63
+ items.value = items.value.slice();
64
+ };
65
+
66
+ const _remove = (id: BaseId) => {
67
+ const index = items.value.findIndex((i) => i.id === id);
68
+ if (index !== -1) {
69
+ items.value.splice(index, 1);
70
+ }
71
+ items.value = items.value.slice();
72
+ };
73
+
74
+ const useAll = (): AsyncState<VariantT[]> => {
75
+ refreshIfStale();
76
+ return [sorted, status, reload];
77
+ };
78
+
79
+ const useItem = (id: Ref<BaseId | undefined>): AsyncState<VariantT | undefined> => {
80
+ refreshIfStale();
81
+ return [computed(() => (id.value ? items.value.find((i) => i.id === id.value) : undefined)), status, reload];
82
+ };
83
+
84
+ const useRemoval = (id: Ref<BaseId | undefined>): Removal<T> => {
85
+ refreshIfStale();
86
+ const itemAs = useItem(id);
87
+ const fn = () => (id.value ? opts.removeFn(id.value) : Promise.reject(new Error("id is required")));
88
+ const [, rmStatus, rmExecute] = useAsyncState<T | undefined>(fn, undefined, {
89
+ onSuccess: (r) => r && _remove(r.id),
90
+ });
91
+
92
+ return [rmStatus, rmExecute, itemAs];
93
+ };
94
+
95
+ const useUpsert = (id: Ref<BaseId | undefined>): Upsert<T> => {
96
+ refreshIfStale();
97
+ const itemAs = useItem(id);
98
+ const form = useClonedReactive(itemAs[0], opts.newItem);
99
+ const issues = useValidation(form, opts.upsertSchema);
100
+ const [, upsertStatus, upsertExecute] = useAsyncState<T | undefined>(
101
+ () => opts.upsertFn(form as VariantT),
102
+ undefined,
103
+ {
104
+ onSuccess: async (r) => r && _upsert(await resolveFn(r)),
105
+ },
106
+ );
107
+ return [form, issues, upsertStatus, upsertExecute, itemAs];
108
+ };
109
+
110
+ return {
111
+ useAll,
112
+ useItem,
113
+ useRemoval,
114
+ useUpsert,
115
+ /** 距上次成功拉取超过 maxAge(ms) 则重新 reload(loading 照常显示)。 */
116
+ refreshIfStale,
117
+ };
118
+ };
119
+
120
+ // ── offset 分页 ──────────────────────────────────────────────────────────────
121
+ // 驱动源是 page / limit;offset 由 fetchFn 自行从 page/limit 计算(offset = (page-1)*limit)。
122
+ // filter 全程是一个字符串:序列化/反序列化由使用者完成。
123
+ export type PaginatedQuery = { page: number; limit: number; filter: string };
124
+ export type PaginatedPage<T> = { items: T[]; total: number };
125
+
126
+ export type PaginatedCollectionOptions<T extends BaseData, VariantT extends T = T> = {
127
+ newItem: () => T;
128
+ fetchFn: (query: PaginatedQuery) => Promise<PaginatedPage<VariantT>>;
129
+ removeFn: (id: BaseId) => Promise<T>;
130
+ upsertFn: (item: VariantT) => Promise<T>;
131
+ upsertSchema: StandardSchemaV1;
132
+ /** 外部页码 ref(如 useRouteQuery 返回值);不传则内部新建 ref(1)。 */
133
+ page?: Ref<number>;
134
+ /** 外部每页条数 ref;不传则内部新建 ref(20)。 */
135
+ limit?: Ref<number>;
136
+ /** 外部筛选字符串 ref;不传则内部新建 ref("")。 */
137
+ filter?: Ref<string>;
138
+ /** >0:filter 变化后防抖(ms)自动回到第一页重拉;0(默认):仅手动触发。 */
139
+ debounce?: number;
140
+ };
141
+
142
+ export const usePaginatedCollection = <T extends BaseData, VariantT extends T = T>(
143
+ opts: PaginatedCollectionOptions<T, VariantT>,
144
+ ) => {
145
+ // 驱动状态:page / limit / filter / total。offset 不是状态,由 fetchFn 从 page/limit 算。
146
+ // page / limit / filter 可由外部注入(路由同步等场景),否则内部自建。
147
+ const pageNo = opts.page ?? ref(1);
148
+ const limit = opts.limit ?? ref(20);
149
+ const filter = opts.filter ?? ref("");
150
+ const total = ref(0);
151
+
152
+ const query = (): PaginatedQuery => ({ page: pageNo.value, limit: limit.value, filter: filter.value });
153
+
154
+ // 防乱序:每次发起自增序列号,仅最新一次的响应允许落地 total(旧响应直接丢弃当前值)。
155
+ let seq = 0;
156
+ const [items, status, execute] = useAsyncState<VariantT[]>(
157
+ async (): Promise<VariantT[]> => {
158
+ const my = ++seq;
159
+ const res = await opts.fetchFn(query());
160
+ if (my !== seq) return items.value; // 已有更新的请求在飞,丢弃本次结果
161
+ total.value = res.total;
162
+ return res.items;
163
+ },
164
+ [],
165
+ { immediate: false },
166
+ );
167
+
168
+ // page / limit 是驱动源:变化即重拉(含外部 ref 触发的变更)。
169
+ watch([pageNo, limit], () => void execute(), { immediate: true });
170
+
171
+ // UI 对接层:pages / hasPrev / hasNext 由驱动状态 compute。limit 为 0 时兜底为 1,避免除零得 Infinity/NaN。
172
+ const pages = computed(() => Math.max(1, Math.ceil(total.value / (limit.value || 1))));
173
+ const go = (p: number) => {
174
+ const next = Math.min(Math.max(1, p), pages.value);
175
+ if (next === pageNo.value) return;
176
+ pageNo.value = next; // 触发上面的 watch 重拉
177
+ };
178
+
179
+ const page: Pagination = reactive({
180
+ page: pageNo,
181
+ limit,
182
+ total,
183
+ pages,
184
+ hasPrev: computed(() => pageNo.value > 1),
185
+ hasNext: computed(() => pageNo.value < pages.value),
186
+ go,
187
+ });
188
+
189
+ // filter 变化:debounce>0 时自动回到第一页重拉;为 0 则需手动 reload。
190
+ const resetAndReload = async () => {
191
+ if (pageNo.value !== 1)
192
+ pageNo.value = 1; // watch 会重拉
193
+ else await execute(); // 已在第一页:watch 不触发,直接重拉
194
+ };
195
+ if (opts.debounce) {
196
+ watchDebounced(filter, () => void resetAndReload(), { debounce: opts.debounce });
197
+ }
198
+
199
+ const reload = async () => {
200
+ await execute();
201
+ };
202
+
203
+ // 详情页等场景拿到的条目可能不在当前分页内:seed 注入本地副本,供 useItem / useUpsert 初始化表单。
204
+ // 只作为 items 的兜底,不写入当前页列表;列表中的同 id 条目始终优先。
205
+ const seeded = ref<Record<BaseId, VariantT>>({});
206
+ const seed = (item: VariantT) => {
207
+ seeded.value = { ...seeded.value, [item.id]: item };
208
+ };
209
+
210
+ const useAll = (): AsyncPaginatedList<VariantT[]> => [items, status, reload, page];
211
+
212
+ const useItem = (id: Ref<BaseId | undefined>): AsyncState<VariantT | undefined> => [
213
+ computed(() => {
214
+ if (!id.value) return undefined;
215
+ return items.value.find((i) => i.id === id.value) ?? seeded.value[id.value];
216
+ }),
217
+ status,
218
+ reload,
219
+ ];
220
+
221
+ const useRemoval = (id: Ref<BaseId | undefined>): Removal<T> => {
222
+ const itemAs = useItem(id);
223
+ const fn = () => (id.value ? opts.removeFn(id.value) : Promise.reject(new Error("id is required")));
224
+ const [, rmStatus, rmExecute] = useAsyncState<T | undefined>(fn, undefined, {
225
+ // 无缓存:写后重拉当前页;若当前页已超出新的总页数(删空了末页),回退到最后一页。
226
+ onSuccess: async () => {
227
+ await execute();
228
+ if (pageNo.value > pages.value) go(pages.value);
229
+ },
230
+ });
231
+ return [rmStatus, rmExecute, itemAs];
232
+ };
233
+
234
+ const useUpsert = (id: Ref<BaseId | undefined>): Upsert<T> => {
235
+ const itemAs = useItem(id);
236
+ const form = useClonedReactive(itemAs[0], opts.newItem);
237
+ const issues = useValidation(form, opts.upsertSchema);
238
+ const [, upsertStatus, upsertExecute] = useAsyncState<T | undefined>(
239
+ () => opts.upsertFn(form as VariantT),
240
+ undefined,
241
+ { onSuccess: () => void execute() }, // 无缓存:写后重拉当前页
242
+ );
243
+ return [form, issues, upsertStatus, upsertExecute, itemAs];
244
+ };
245
+
246
+ return { useAll, useItem, useRemoval, useUpsert, reload, page, filter, seed };
247
+ };
248
+
249
+ // ── cursor 分页 ──────────────────────────────────────────────────────────────
250
+ export type CursorQuery = { cursor: BaseId | null; limit: number; filter: string };
251
+ export type CursorPage<T> = { items: T[]; nextCursor: BaseId | null };
252
+
253
+ export type CursorCollectionOptions<T extends BaseData, VariantT extends T = T> = {
254
+ newItem: () => T;
255
+ fetchFn: (query: CursorQuery) => Promise<CursorPage<VariantT>>;
256
+ removeFn: (id: BaseId) => Promise<T>;
257
+ upsertFn: (item: VariantT) => Promise<T>;
258
+ upsertSchema: StandardSchemaV1;
259
+ /** 外部游标 ref(null 表示从头);不传则内部新建 ref(null)。 */
260
+ cursor?: Ref<BaseId | null>;
261
+ /** 外部每次拉取条数 ref;不传则内部新建 ref(20)。 */
262
+ limit?: Ref<number>;
263
+ /** 外部筛选字符串 ref;不传则内部新建 ref("")。 */
264
+ filter?: Ref<string>;
265
+ /** >0:filter 变化后防抖(ms)自动清空游标重拉;0(默认):仅手动触发。 */
266
+ debounce?: number;
267
+ };
268
+
269
+ export const useCursorCollection = <T extends BaseData, VariantT extends T = T>(
270
+ opts: CursorCollectionOptions<T, VariantT>,
271
+ ) => {
272
+ // 核心状态:cursor / limit / filter / hasMore。cursor / limit / filter 可由外部注入。
273
+ const limit = opts.limit ?? ref(20);
274
+ const cursorKey = opts.cursor ?? ref<BaseId | null>(null); // 下一页游标;null 表示从头
275
+ const filter = opts.filter ?? ref("");
276
+ const hasMore = ref(true);
277
+
278
+ // 累积式:next() 追加,refresh() 清空后重拉首屏。
279
+ // 通过 loadMode 切换重置/追加,统一走 execute(),使 status.loading 在两种场景都生效。
280
+ let loadMode: "reset" | "append" = "reset";
281
+ const loadFn = async (): Promise<VariantT[]> => {
282
+ const reset = loadMode === "reset";
283
+ const res = await opts.fetchFn({
284
+ cursor: reset ? null : cursorKey.value,
285
+ limit: limit.value,
286
+ filter: filter.value,
287
+ });
288
+ cursorKey.value = res.nextCursor;
289
+ hasMore.value = res.nextCursor != null;
290
+ return reset ? res.items : [...items.value, ...res.items];
291
+ };
292
+
293
+ // resetOnExecute 必须关闭:next() 依赖旧 items 做追加,不能由 useAsyncState 在请求前清空。
294
+ // refresh() 通过 loadMode="reset" 让 loadFn 返回替换数组,语义仍是整体替换。
295
+ const [items, status, execute] = useAsyncState<VariantT[]>(loadFn, [], { immediate: true, resetOnExecute: false });
296
+
297
+ // 清空游标,从头重新拉取首屏(语义上的「刷新」)。
298
+ const refresh = async () => {
299
+ cursorKey.value = null;
300
+ hasMore.value = true;
301
+ loadMode = "reset";
302
+ await execute();
303
+ };
304
+
305
+ const next = async () => {
306
+ if (!hasMore.value || status.loading) return;
307
+ loadMode = "append";
308
+ await execute();
309
+ };
310
+
311
+ // UI 对接层:直接暴露核心状态 + next()。
312
+ const cursor: Cursor = reactive({ cursor: cursorKey, limit, hasMore, next });
313
+
314
+ // limit 变化:清空游标从头重拉(与 offset 变体 watch limit 行为一致)。
315
+ watch(limit, () => void refresh());
316
+
317
+ // filter 变化:debounce>0 时自动清空游标重拉;为 0 则需手动 refresh。
318
+ if (opts.debounce) {
319
+ watchDebounced(filter, () => void refresh(), { debounce: opts.debounce });
320
+ }
321
+
322
+ const useAll = (): AsyncCursorList<VariantT[]> => [items, status, refresh, cursor];
323
+
324
+ const useItem = (id: Ref<BaseId | undefined>): AsyncState<VariantT | undefined> => [
325
+ computed(() => (id.value ? items.value.find((i) => i.id === id.value) : undefined)),
326
+ status,
327
+ refresh,
328
+ ];
329
+
330
+ const useRemoval = (id: Ref<BaseId | undefined>): Removal<T> => {
331
+ const itemAs = useItem(id);
332
+ const fn = () => (id.value ? opts.removeFn(id.value) : Promise.reject(new Error("id is required")));
333
+ const [, rmStatus, rmExecute] = useAsyncState<T | undefined>(fn, undefined, {
334
+ onSuccess: () => void refresh(), // 无缓存:写后从头重拉
335
+ });
336
+ return [rmStatus, rmExecute, itemAs];
337
+ };
338
+
339
+ const useUpsert = (id: Ref<BaseId | undefined>): Upsert<T> => {
340
+ const itemAs = useItem(id);
341
+ const form = useClonedReactive(itemAs[0], opts.newItem);
342
+ const issues = useValidation(form, opts.upsertSchema);
343
+ const [, upsertStatus, upsertExecute] = useAsyncState<T | undefined>(
344
+ () => opts.upsertFn(form as VariantT),
345
+ undefined,
346
+ { onSuccess: () => void refresh() },
347
+ );
348
+ return [form, issues, upsertStatus, upsertExecute, itemAs];
349
+ };
350
+
351
+ return { useAll, useItem, useRemoval, useUpsert, refresh, cursor, filter };
352
+ };
package/src/hono.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { ClientResponse } from "hono/client";
2
+ import type { ContentfulStatusCode } from "hono/utils/http-status";
3
+
4
+ /** 非 2xx 响应抛出的错误,携带 status 便于上层(如 401 重定向)分流。 */
5
+ export class HonoApiError extends Error {
6
+ constructor(
7
+ public status: number,
8
+ message: string,
9
+ ) {
10
+ super(message);
11
+ this.name = "HonoApiError";
12
+ }
13
+ }
14
+
15
+ /**
16
+ * 响应拦截器:在 res.ok 判定前介入(如 401 清登录态 + 跳转)。
17
+ * 返回 true 表示已处理(useResponse 会抛错中止),返回 false/undefined 则走默认 res.ok 流程。
18
+ * 由 app 层通过 setResponseInterceptor 注入,core 本身不耦合 router/store。
19
+ */
20
+ export type ResponseInterceptor = (res: { ok: boolean; status: number }) => boolean | void;
21
+
22
+ let interceptor: ResponseInterceptor | undefined;
23
+ export const setResponseInterceptor = (fn: ResponseInterceptor | undefined) => {
24
+ interceptor = fn;
25
+ };
26
+
27
+ export const useResponse = async <Dto, Out = Dto>(
28
+ response: Promise<ClientResponse<Dto, ContentfulStatusCode, "json">>,
29
+ transform: (dto: Dto) => Out = (dto: Dto) => dto as unknown as Out,
30
+ ): Promise<Out> => {
31
+ const r = await response;
32
+ if (interceptor?.({ ok: r.ok, status: r.status })) {
33
+ throw new HonoApiError(r.status, `HTTP ${r.status}`);
34
+ }
35
+ if (!r.ok) {
36
+ const data = (await r.json().catch(() => ({}))) as { error?: string };
37
+ throw new HonoApiError(r.status, data.error ?? `HTTP ${r.status}`);
38
+ }
39
+ return transform((await r.json()) as Dto);
40
+ };
41
+
42
+ type JsonResponse<Dto> = ClientResponse<Dto, ContentfulStatusCode, "json">;
43
+
44
+ /**
45
+ * 路由的返回类型现在会同时带上成功响应与 @hono/zod-validator 的 400 失败响应。
46
+ * 取非 400 分支作为数据 DTO,避免客户端推断落到 ZodSafeParseError。
47
+ */
48
+ type SuccessDto<T> =
49
+ T extends ClientResponse<infer Dto, infer Status, "json"> ? ([Status] extends [400] ? never : Dto) : never;
50
+
51
+ type AnyApi = (...args: never[]) => Promise<unknown>;
52
+ type ResultDto<F extends AnyApi> = SuccessDto<Awaited<ReturnType<F>>>;
53
+
54
+ export const useHonoApi = <F extends AnyApi, Out = ResultDto<F>>(
55
+ api: F,
56
+ transform: (dto: ResultDto<F>) => Out = (dto: ResultDto<F>) => dto as unknown as Out,
57
+ ) => {
58
+ return (...args: Parameters<F>) =>
59
+ useResponse<ResultDto<F>, Out>(api(...args) as unknown as Promise<JsonResponse<ResultDto<F>>>, transform);
60
+ };
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./async";
2
+ export * from "./hono";
3
+ export * from "./issues";
4
+ export * from "./base";
5
+ export * from "./utils";
6
+ export * from "./collection";
package/src/issues.ts ADDED
@@ -0,0 +1,71 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import { computed, ref, shallowRef } from "vue";
3
+
4
+ // Validation
5
+ export type Issues = readonly StandardSchemaV1.Issue[] | undefined;
6
+
7
+ const issuesToMap = (issues: Issues, ignored: PropertyKey[]) => {
8
+ const result: Record<PropertyKey, StandardSchemaV1.Issue[]> = {};
9
+ for (const issue of issues ?? []) {
10
+ for (const path of issue.path ?? []) {
11
+ if (ignored.includes(path as PropertyKey)) continue;
12
+
13
+ const key = (path as { key: PropertyKey })?.key || (path as PropertyKey);
14
+ result[key] = result[key] ?? [];
15
+ result[key]!.push(issue);
16
+ }
17
+ }
18
+ return result;
19
+ };
20
+
21
+ export const useValidation = <T extends object>(form: T, schema: StandardSchemaV1) => {
22
+ // 验证结果
23
+ const issues = ref<StandardSchemaV1.Issue[] | undefined>(undefined);
24
+
25
+ // 外部注入的错误(非 schema 来源,如输入控件内部的“文本→值”转换失败)。
26
+ // 校验的是 form,看不到这类错误,所以由字段组件通过 set(key, messages) 注入。
27
+ const external = ref<Record<PropertyKey, StandardSchemaV1.Issue[]>>({});
28
+ const set = (key: PropertyKey, messages: string[] | undefined) => {
29
+ if (!messages?.length) delete external.value[key];
30
+ else external.value[key] = messages.map((message) => ({ message }));
31
+ external.value = { ...external.value };
32
+ };
33
+
34
+ // 忽略的键,通常在一轮报错之后,临时解除正在编辑的键的报错
35
+ const ignored = shallowRef<PropertyKey[]>(Object.keys(form)); // todo: list deep keys
36
+ const ingore = (key: PropertyKey) => {
37
+ if (ignored.value.includes(key)) return;
38
+ ignored.value = [...ignored.value, key];
39
+ };
40
+
41
+ // 扁平化错误映射(schema issues + 外部注入,均受 ignored 约束)
42
+ const map = computed(() => {
43
+ const result = issuesToMap(issues.value, ignored.value);
44
+ for (const key of Reflect.ownKeys(external.value)) {
45
+ if (ignored.value.includes(key)) continue;
46
+ const list = external.value[key];
47
+ if (list?.length) result[key] = [...(result[key] ?? []), ...list];
48
+ }
49
+ return result;
50
+ });
51
+ const errors = (key: PropertyKey) => map.value[key] ?? [];
52
+ const useErrors = (key: PropertyKey) => computed(() => errors(key));
53
+ const valid = (key: PropertyKey) => errors(key).length === 0;
54
+
55
+ const validate = async () => {
56
+ try {
57
+ const r = await schema["~standard"].validate(form);
58
+ issues.value = r.issues as StandardSchemaV1.Issue[];
59
+ ignored.value = [];
60
+ const hasExternal = Reflect.ownKeys(external.value).some((k) => external.value[k]?.length);
61
+ return (issues.value?.length ?? 0) === 0 && !hasExternal;
62
+ } catch (error) {
63
+ console.error("validate failed", error);
64
+ return false;
65
+ }
66
+ };
67
+
68
+ return { ingore, errors, useErrors, valid, validate, set };
69
+ };
70
+
71
+ export type UseValidation = ReturnType<typeof useValidation>;
package/src/utils.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { type Ref, reactive, ref, watch } from "vue";
2
+
3
+ export const deepCopy = <T>(value: T) => {
4
+ try {
5
+ return JSON.parse(JSON.stringify(value));
6
+ } catch {
7
+ return structuredClone(value);
8
+ }
9
+ };
10
+
11
+ export const useClonedRef = <T>(v: Ref<T>) => {
12
+ const cloned = ref({}) as Ref<T>;
13
+ watch(v, (i) => (cloned.value = deepCopy(i)), { immediate: true });
14
+ return cloned;
15
+ };
16
+
17
+ export const useClonedReactive = <T extends object>(v: Ref<T | undefined>, newValue: () => T) => {
18
+ const cloned = reactive<T>(v.value ?? newValue());
19
+ watch(v, (i) => Object.assign(cloned, deepCopy(i)), { immediate: true });
20
+ return cloned;
21
+ };