@ysgroup/core 0.1.26 → 0.1.27

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/core",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -23,6 +23,6 @@
23
23
  "access": "public"
24
24
  },
25
25
  "devDependencies": {
26
- "@ysgroup/theme": "^0.2.6"
26
+ "@ysgroup/theme": "^0.3.0"
27
27
  }
28
28
  }
package/src/catalog.ts ADDED
@@ -0,0 +1,270 @@
1
+ /* @ysgroup/core —— 列表数据缓存骨架:把「查一次、缓存、收到推送再重拉」做成 Pinia store 工厂。
2
+ *
3
+ * 用法:
4
+ * export const useCatalogStore = createYsCatalog<{ schools: SchoolRow[]; roles: RoleRow[] }>({
5
+ * id: "template-catalog",
6
+ * tables: {
7
+ * schools: "query_schools",
8
+ * roles: { event: "query_user_roles", data: () => ({}) },
9
+ * },
10
+ * dirtyTables: (kind) => (kind === "users" ? ["roles"] : kind === "schools" ? ["schools"] : []),
11
+ * });
12
+ * const catalog = useCatalogStore();
13
+ * await catalog.ensure("schools", "roles"); // 页面进入时
14
+ * catalog.rows.schools; // 响应式行
15
+ * await catalog.refresh("schools"); // 保存后
16
+ * catalog.bind(); // 登录并连接后调用一次
17
+ * catalog.reset(); // 退出登录时
18
+ *
19
+ * 规则:
20
+ * - ensure 只在第一次(或上次失败、已知过期)时加载;同一张表的在途请求只发一次。
21
+ * - 收到 changeEvent 推送,只重拉已加载或在途的表;coalesceMs 内的多次推送合并成一轮。
22
+ * 推送到达时这张表正在请求,就等它回来再拉一次,不会堆出并发请求。
23
+ * - 重连(__connected)后把已加载、在途和上次加载失败的表补拉一次,同样合并。
24
+ * - 重拉期间旧行保留、loaded 不变,页面不闪;加载失败把文案写进 errors[表] 并向调用方抛出,行保持原样。
25
+ * - refresh 作废在途请求重新发;旧响应不会覆盖新状态,reset(退出登录)之后迟到的响应直接丢弃。
26
+ */
27
+ import { defineStore, type StoreDefinition } from "pinia";
28
+ import { reactive } from "vue";
29
+ import { formatError } from "./errors";
30
+ import { useYsStore } from "./store";
31
+
32
+ /** 一张表的查询:事件名,或事件名 + 每次查询时取的参数。 */
33
+ export type YsCatalogSource =
34
+ | string
35
+ | { event: string; data?: () => Record<string, unknown> };
36
+
37
+ type TableName<Tables> = Extract<keyof Tables, string>;
38
+
39
+ export interface YsCatalogOptions<Tables extends Record<string, unknown[]>> {
40
+ /** Pinia store id,全应用唯一。 */
41
+ id: string;
42
+ /** 每张表的查询事件;查询必须返回数组。 */
43
+ tables: { [K in keyof Tables]: YsCatalogSource };
44
+ /** 推送的 kind(和整条推送数据)→ 受影响的表。不传时重拉与 kind 同名的表。 */
45
+ dirtyTables?: (
46
+ kind: string,
47
+ payload: unknown,
48
+ ) => readonly TableName<Tables>[];
49
+ /** 数据变更推送的事件名,默认 business_changed;推送数据里的 kind 交给 dirtyTables。 */
50
+ changeEvent?: string;
51
+ /** 这段时间(毫秒)内的多次失效合并成一轮重拉,默认 150;0 表示立即重拉。 */
52
+ coalesceMs?: number;
53
+ }
54
+
55
+ export interface YsCatalogState<Tables> {
56
+ /** 每张表的行(响应式)。没加载或 reset 后是空数组,重拉期间保留旧行。 */
57
+ rows: Tables;
58
+ /** 这张表成功加载过(重拉期间保持 true,reset 后为 false)。 */
59
+ loaded: Record<TableName<Tables>, boolean>;
60
+ /** 这张表有请求在途。 */
61
+ loading: Record<TableName<Tables>, boolean>;
62
+ /** 最近一次加载失败的文案;成功后清空,空串表示没有错误。 */
63
+ errors: Record<TableName<Tables>, string>;
64
+ }
65
+
66
+ export interface YsCatalogActions<Tables> {
67
+ /** 需要这些表:没加载过(或上次失败、已知过期)才请求。失败时抛出,文案同时写进 errors。未登录时什么都不做。 */
68
+ ensure(...tables: TableName<Tables>[]): Promise<void>;
69
+ /** 立即重拉这些表(保存后调用):作废在途请求重新发。失败时抛出。不传表名什么都不做。 */
70
+ refresh(...tables: TableName<Tables>[]): Promise<void>;
71
+ /** 订阅数据变更推送和重连事件。登录并连接后调用;重复调用无影响。 */
72
+ bind(): void;
73
+ /** 退出登录时调用:清空数据和状态、取消订阅,在途请求的结果作废。 */
74
+ reset(): void;
75
+ }
76
+
77
+ export type YsCatalogStoreDefinition<Tables> = StoreDefinition<
78
+ string,
79
+ YsCatalogState<Tables>,
80
+ Record<never, never>,
81
+ YsCatalogActions<Tables>
82
+ >;
83
+
84
+ /** useCatalogStore() 的返回值类型。 */
85
+ export type YsCatalogStore<Tables> = ReturnType<
86
+ YsCatalogStoreDefinition<Tables>
87
+ >;
88
+
89
+ const DEFAULT_CHANGE_EVENT = "business_changed";
90
+ const DEFAULT_COALESCE_MS = 150;
91
+
92
+ export function createYsCatalog<Tables extends Record<string, unknown[]>>(
93
+ options: YsCatalogOptions<Tables>,
94
+ ): YsCatalogStoreDefinition<Tables> {
95
+ type Table = TableName<Tables>;
96
+ const names = Object.keys(options.tables) as Table[];
97
+ const changeEvent = options.changeEvent ?? DEFAULT_CHANGE_EVENT;
98
+ const coalesceMs = options.coalesceMs ?? DEFAULT_COALESCE_MS;
99
+
100
+ function perTable<T>(value: () => T): Record<Table, T> {
101
+ return Object.fromEntries(names.map((name) => [name, value()])) as Record<
102
+ Table,
103
+ T
104
+ >;
105
+ }
106
+
107
+ const useStore = defineStore(options.id, () => {
108
+ const ys = useYsStore();
109
+ const rows = reactive(perTable<unknown[]>(() => [])) as Tables;
110
+ const loaded = reactive(perTable(() => false)) as Record<Table, boolean>;
111
+ const loading = reactive(perTable(() => false)) as Record<Table, boolean>;
112
+ const errors = reactive(perTable(() => "")) as Record<Table, string>;
113
+
114
+ /** 每张表的请求代次:refresh、reset 时加一,回来的响应代次对不上就不写入。 */
115
+ const generation = perTable(() => 0);
116
+ const inflight = new Map<Table, Promise<void>>();
117
+ /** 已失效、等下一轮重拉的表。 */
118
+ const pending = new Set<Table>();
119
+ let timer: ReturnType<typeof setTimeout> | null = null;
120
+ let offChange: (() => void) | undefined;
121
+ let offConnected: (() => void) | undefined;
122
+
123
+ function known(table: string): table is Table {
124
+ return Object.prototype.hasOwnProperty.call(generation, table);
125
+ }
126
+
127
+ async function fetchRows(table: Table): Promise<unknown[]> {
128
+ if (!ys.connected) await ys.waitUntilConnected();
129
+ if (!ys.client() || !ys.accessToken) throw new Error("服务未连接");
130
+ const source = options.tables[table];
131
+ const event = typeof source === "string" ? source : source.event;
132
+ const data = typeof source === "string" ? {} : (source.data?.() ?? {});
133
+ const result = await ys.call<unknown>(event, data);
134
+ if (!Array.isArray(result)) throw new Error("返回的数据不是列表");
135
+ return result;
136
+ }
137
+
138
+ /** 这一代请求结束:清在途标记;期间又失效过就接着拉下一轮。 */
139
+ function settle(table: Table): void {
140
+ inflight.delete(table);
141
+ loading[table] = false;
142
+ if (pending.has(table) && !timer) flush();
143
+ }
144
+
145
+ async function run(table: Table, gen: number): Promise<void> {
146
+ let result: unknown[];
147
+ try {
148
+ result = await fetchRows(table);
149
+ } catch (error) {
150
+ // 已被 refresh 取代:跟着新请求走;已 reset:没有新请求,丢弃。
151
+ if (gen !== generation[table]) return inflight.get(table);
152
+ errors[table] = formatError(error, "加载失败");
153
+ settle(table);
154
+ throw error;
155
+ }
156
+ if (gen !== generation[table]) return inflight.get(table);
157
+ rows[table] = result as Tables[Table];
158
+ loaded[table] = true;
159
+ errors[table] = "";
160
+ settle(table);
161
+ }
162
+
163
+ function load(table: Table): Promise<void> {
164
+ const existing = inflight.get(table);
165
+ if (existing) return existing;
166
+ if (!ys.isLoggedIn) return Promise.resolve();
167
+ // 这次请求在失效之后才发出,拿到的就是新数据,不用再排下一轮。
168
+ pending.delete(table);
169
+ loading[table] = true;
170
+ const task = run(table, ++generation[table]);
171
+ inflight.set(table, task);
172
+ return task;
173
+ }
174
+
175
+ function unique(tables: readonly Table[]): Table[] {
176
+ const list = [...new Set(tables)];
177
+ for (const table of list)
178
+ if (!known(table)) throw new Error(`未登记的表:${String(table)}`);
179
+ return list;
180
+ }
181
+
182
+ async function ensure(...tables: Table[]): Promise<void> {
183
+ await Promise.all(
184
+ unique(tables).map((table) => {
185
+ const fresh =
186
+ loaded[table] &&
187
+ !errors[table] &&
188
+ !pending.has(table) &&
189
+ !inflight.has(table);
190
+ return fresh ? undefined : load(table);
191
+ }),
192
+ );
193
+ }
194
+
195
+ async function refresh(...tables: Table[]): Promise<void> {
196
+ const list = unique(tables);
197
+ for (const table of list) {
198
+ // 在途请求可能早于这次修改,作废它;它的调用方会跟着新请求走。
199
+ generation[table] += 1;
200
+ inflight.delete(table);
201
+ loading[table] = false;
202
+ }
203
+ await Promise.all(list.map((table) => load(table)));
204
+ }
205
+
206
+ function flush(): void {
207
+ if (timer) clearTimeout(timer);
208
+ timer = null;
209
+ for (const table of [...pending]) {
210
+ // 正在请求的等它回来(settle)再拉,同一张表不并发。
211
+ if (inflight.has(table)) continue;
212
+ pending.delete(table);
213
+ // 后台重拉:失败已写进 errors,这里没有调用方可抛。
214
+ void load(table).catch(() => undefined);
215
+ }
216
+ }
217
+
218
+ function invalidate(tables: readonly string[], retryFailed = false): void {
219
+ for (const table of tables) {
220
+ if (!known(table)) continue;
221
+ if (
222
+ loaded[table] ||
223
+ inflight.has(table) ||
224
+ (retryFailed && errors[table])
225
+ )
226
+ pending.add(table);
227
+ }
228
+ if (!pending.size || timer) return;
229
+ if (coalesceMs > 0) timer = setTimeout(flush, coalesceMs);
230
+ else flush();
231
+ }
232
+
233
+ function onChange(data: unknown): void {
234
+ const kind = String((data as { kind?: unknown } | null)?.kind ?? "");
235
+ invalidate(
236
+ options.dirtyTables ? options.dirtyTables(kind, data) : [kind],
237
+ );
238
+ }
239
+
240
+ function bind(): void {
241
+ const client = ys.client();
242
+ if (!client || offChange) return;
243
+ offChange = client.on(changeEvent, onChange);
244
+ // 断线期间的推送收不到:重连后补拉一次,上次加载失败的表也顺带重试。
245
+ offConnected = client.on("__connected", () => invalidate(names, true));
246
+ }
247
+
248
+ function reset(): void {
249
+ offChange?.();
250
+ offConnected?.();
251
+ offChange = undefined;
252
+ offConnected = undefined;
253
+ if (timer) clearTimeout(timer);
254
+ timer = null;
255
+ pending.clear();
256
+ inflight.clear();
257
+ for (const table of names) {
258
+ generation[table] += 1;
259
+ rows[table] = [] as unknown as Tables[Table];
260
+ loaded[table] = false;
261
+ loading[table] = false;
262
+ errors[table] = "";
263
+ }
264
+ }
265
+
266
+ return { rows, loaded, loading, errors, ensure, refresh, bind, reset };
267
+ });
268
+
269
+ return useStore as unknown as YsCatalogStoreDefinition<Tables>;
270
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,57 @@
1
+ /* @ysgroup/core —— 给用户看的错误文案,以及「结果未知」的判断。
2
+ *
3
+ * 用法:
4
+ * try { await store.call("save_school", data); }
5
+ * catch (error) {
6
+ * ElMessage.error(formatError(error, "保存失败"));
7
+ * if (isResultUnknown(error)) await catalog.refresh("schools"); // 先核对,不要自动重发
8
+ * }
9
+ */
10
+ import { YsConnectionLostError, YsRpcError, YsTimeoutError } from "./ws";
11
+
12
+ /** 「Error: 」「TypeError: 」「YsRpcError: 」这类类名前缀。 */
13
+ const NAME_PREFIX = /^(?:[A-Za-z_$][\w$]*)?Error:\s*/;
14
+ /** 开头的「[500] 」这类回执码。 */
15
+ const CODE_PREFIX = /^\[\d+\]\s*/;
16
+
17
+ function cleanText(text: string): string {
18
+ let out = text.trim();
19
+ let previous = "";
20
+ // 「Error: [500] YsRpcError: 文案」这种多层前缀逐层去掉。
21
+ while (previous !== out) {
22
+ previous = out;
23
+ out = out.replace(NAME_PREFIX, "").replace(CODE_PREFIX, "").trim();
24
+ }
25
+ return out;
26
+ }
27
+
28
+ function rawText(error: unknown): string {
29
+ if (error === null || error === undefined) return "";
30
+ if (typeof error === "string") return error;
31
+ // YsRpcError.message 就是展示文案(500 时已带编号)。
32
+ if (error instanceof YsRpcError || error instanceof Error)
33
+ return error.message;
34
+ if (typeof error === "object") {
35
+ const message = (error as { message?: unknown }).message;
36
+ return typeof message === "string" ? message : "";
37
+ }
38
+ return String(error);
39
+ }
40
+
41
+ /**
42
+ * 把任意错误变成给用户看的一句话:去掉「XxxError: 」「Error: 」前缀和开头的「[数字] 」,
43
+ * 得到空文案时用 fallback。YsRpcError 取它的展示文案(500 时带编号,便于对照日志)。
44
+ */
45
+ export function formatError(error: unknown, fallback = "操作失败"): string {
46
+ return cleanText(rawText(error)) || fallback;
47
+ }
48
+
49
+ /**
50
+ * 请求已经发出但不知道服务端有没有执行:连接中断(YsConnectionLostError)或等回复超时(YsTimeoutError)。
51
+ * 写操作遇到它不要自动重试,先刷新数据核对。请求没发出(YsOfflineError)和服务端明确拒绝(YsRpcError)都不算。
52
+ */
53
+ export function isResultUnknown(error: unknown): boolean {
54
+ return (
55
+ error instanceof YsConnectionLostError || error instanceof YsTimeoutError
56
+ );
57
+ }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export {
8
8
  YsRpcError,
9
9
  YsOfflineError,
10
10
  YsConnectionLostError,
11
+ YsTimeoutError,
11
12
  DEFAULT_CALL_TIMEOUT_MS,
12
13
  DEFAULT_OFFLINE_WAIT_MS,
13
14
  MIN_CALL_TIMEOUT_MS,
@@ -77,3 +78,14 @@ export {
77
78
  ysMatch,
78
79
  ysSearchText,
79
80
  } from "./search";
81
+ export { formatError, isResultUnknown } from "./errors";
82
+ export { compareNatural, sortByNatural } from "./naturalSort";
83
+ export {
84
+ createYsCatalog,
85
+ type YsCatalogOptions,
86
+ type YsCatalogSource,
87
+ type YsCatalogState,
88
+ type YsCatalogActions,
89
+ type YsCatalogStore,
90
+ type YsCatalogStoreDefinition,
91
+ } from "./catalog";
@@ -0,0 +1,21 @@
1
+ /* @ysgroup/core —— 中文 + 数字自然序:同一串里的数字按数值比,避免「10号」排在「1号」前面。 */
2
+
3
+ const collator = new Intl.Collator("zh-CN", {
4
+ numeric: true,
5
+ sensitivity: "base",
6
+ });
7
+
8
+ /** 比较两个值(转成字符串,null / undefined 当空串),可直接给 Array.sort 或 el-table 的 sort-method。 */
9
+ export function compareNatural(left: unknown, right: unknown): number {
10
+ return collator.compare(String(left ?? ""), String(right ?? ""));
11
+ }
12
+
13
+ /** 按 key(item) 自然序排出新数组,不改原数组。 */
14
+ export function sortByNatural<T>(
15
+ items: readonly T[],
16
+ key: (item: T) => unknown,
17
+ ): T[] {
18
+ return [...items].sort((left, right) =>
19
+ compareNatural(key(left), key(right)),
20
+ );
21
+ }
package/src/ws.ts CHANGED
@@ -46,6 +46,19 @@ export class YsConnectionLostError extends Error {
46
46
  }
47
47
  }
48
48
 
49
+ /**
50
+ * 请求已经发出,等到超时也没有回复:服务端可能已经执行,结果未知,不要自动重试写操作。
51
+ * 不改 name(仍是 Error):String(error) 还是「Error: 请求超时:…」,旧代码照常显示。
52
+ */
53
+ export class YsTimeoutError extends Error {
54
+ constructor(
55
+ public readonly event: string,
56
+ public readonly timeoutMs: number,
57
+ ) {
58
+ super(`请求超时:${event} 超过 ${timeoutMs / 1000} 秒没有返回`);
59
+ }
60
+ }
61
+
49
62
  /** 断开事件附带的信息。restarting 表示服务端主动重启(关闭码 1012 / 1001),多半是在部署新版本。 */
50
63
  export interface YsDisconnectInfo {
51
64
  code: number;
@@ -238,7 +251,7 @@ export class YsWsClient {
238
251
  return new Promise((resolve, reject) => {
239
252
  const timer = setTimeout(() => {
240
253
  this.pending.delete(id);
241
- reject(new Error(`请求超时:${event} 超过 ${limit / 1000} 秒没有返回`));
254
+ reject(new YsTimeoutError(event, limit));
242
255
  }, limit);
243
256
  this.pending.set(id, {
244
257
  resolve: (v) => {