@ysgroup/core 0.1.22 → 0.1.23

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.22",
3
+ "version": "0.1.23",
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.3"
26
+ "@ysgroup/theme": "^0.2.5"
27
27
  }
28
28
  }
@@ -0,0 +1,246 @@
1
+ /* @ysgroup/core —— 业务 WS 分块文件传输(上传 begin → 按序发块 → finish 核对 sha256;读取逐块拼成 Blob)。 */
2
+
3
+ /** 每块原始字节数:1 MiB,与 Template `app/files.py` 的 CHUNK_SIZE 一致。服务端 begin 返回 chunk_size 时以服务端为准。 */
4
+ export const FILE_CHUNK_SIZE = 1024 * 1024;
5
+
6
+ /** 单块上传、读取、finish 的默认超时:一块 1 MiB 的 base64,慢网下也够。 */
7
+ export const FILE_CHUNK_TIMEOUT_MS = 60_000;
8
+
9
+ /**
10
+ * 业务调用函数:`store.call` 或业务仓自己的包装(如 `callWs`)都能直接传。
11
+ * 第三个参数只用到 `{ timeoutMs }`。
12
+ */
13
+ export type YsFileCall = (
14
+ event: string,
15
+ data: Record<string, unknown>,
16
+ options?: { timeoutMs?: number },
17
+ ) => Promise<unknown>;
18
+
19
+ /** 进度 0~1。 */
20
+ export type YsFileProgress = (ratio: number) => void;
21
+
22
+ /** 浏览器本地读文件出的错(不是服务端错误),调用方可单独提示「请重新选择文件」。 */
23
+ export class YsLocalFileError extends Error {
24
+ constructor(
25
+ message = "读取本地文件失败,请重新选择文件",
26
+ options?: ErrorOptions,
27
+ ) {
28
+ super(message, options);
29
+ this.name = "YsLocalFileError";
30
+ }
31
+ }
32
+
33
+ /** Blob 转 base64(不带 `data:` 前缀)。读失败抛 YsLocalFileError。 */
34
+ export function blobToBase64(blob: Blob): Promise<string> {
35
+ return new Promise((resolve, reject) => {
36
+ const reader = new FileReader();
37
+ reader.onerror = () =>
38
+ reject(new YsLocalFileError(undefined, { cause: reader.error }));
39
+ reader.onload = () =>
40
+ resolve(String(reader.result).replace(/^data:[^,]*,/, ""));
41
+ reader.readAsDataURL(blob);
42
+ });
43
+ }
44
+
45
+ /** base64 转字节。 */
46
+ export function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {
47
+ const binary = atob(value);
48
+ const bytes = new Uint8Array(binary.length);
49
+ for (let index = 0; index < binary.length; index += 1)
50
+ bytes[index] = binary.charCodeAt(index);
51
+ return bytes;
52
+ }
53
+
54
+ /**
55
+ * 整个 Blob 的 sha256(小写十六进制)。非 HTTPS 访问时浏览器不提供摘要接口,返回空串,
56
+ * 由服务端自己算(各系统 finish 都接受空 checksum)。
57
+ */
58
+ export async function sha256Hex(blob: Blob): Promise<string> {
59
+ if (!globalThis.crypto?.subtle) return "";
60
+ const digest = await crypto.subtle.digest(
61
+ "SHA-256",
62
+ await blob.arrayBuffer(),
63
+ );
64
+ return [...new Uint8Array(digest)]
65
+ .map((byte) => byte.toString(16).padStart(2, "0"))
66
+ .join("");
67
+ }
68
+
69
+ export interface YsUploadChunkedOptions {
70
+ /** 开始上传的事件与附加数据。实际发送 `{ name: file.name, size: file.size, ...data }`,data 里同名字段优先(如 content_type 自己传)。 */
71
+ begin: { event: string; data?: Record<string, unknown> };
72
+ /** 发块事件,如 `upload_file_chunk`。数据 `{ [idKey]: id, index, size, data }`,size 为这一块原始字节数。 */
73
+ chunkEvent: string;
74
+ /** 完成事件,如 `finish_file_upload`。数据 `{ [idKey]: id, checksum }`,返回值即 uploadChunked 的返回值。 */
75
+ finishEvent: string;
76
+ /** 取消事件,如 `cancel_file_upload`。出错或中止时发 `{ [idKey]: id }`,不等结果、不抛错。 */
77
+ cancelEvent: string;
78
+ /**
79
+ * 上传编号字段名:既用来从 begin 结果里读编号,也用作后续请求里的字段名。
80
+ * 不传时先看 `upload_id`,没有再看 `_id`,找到哪个就用哪个。
81
+ */
82
+ idKey?: string;
83
+ onProgress?: YsFileProgress;
84
+ /** 中止:立即发 cancel 并抛出 signal.reason(默认 AbortError),不等正在进行的请求。 */
85
+ signal?: AbortSignal;
86
+ /** 每块、finish 的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。begin、cancel 用调用方默认超时。 */
87
+ timeoutMs?: number;
88
+ }
89
+
90
+ /**
91
+ * 分块上传:begin → 按序发块 → finish(带整个文件 sha256),返回 finish 的结果。
92
+ * 块大小、块数以 begin 返回的 chunk_size、chunk_count 为准(没返回时按 FILE_CHUNK_SIZE 计算,空文件 0 块)。
93
+ * 任一步出错或中止:拿到上传编号后不等结果地发 cancel,再把原错误抛出。
94
+ */
95
+ export async function uploadChunked<T = unknown>(
96
+ call: YsFileCall,
97
+ file: Blob & { name?: string },
98
+ options: YsUploadChunkedOptions,
99
+ ): Promise<T> {
100
+ const { signal, onProgress } = options;
101
+ const timeoutMs = options.timeoutMs ?? FILE_CHUNK_TIMEOUT_MS;
102
+ signal?.throwIfAborted();
103
+ let idKey = options.idKey ?? "";
104
+ let id = "";
105
+ let cancelled = false;
106
+ const cancel = () => {
107
+ if (cancelled || !id) return;
108
+ cancelled = true;
109
+ // 不等结果:半截文件让服务端尽快清掉,取消失败也不影响抛出原错误。
110
+ void Promise.resolve()
111
+ .then(() => call(options.cancelEvent, { [idKey]: id }))
112
+ .catch(() => undefined);
113
+ };
114
+ const beginPromise = call(options.begin.event, {
115
+ name: file.name ?? "",
116
+ size: file.size,
117
+ ...options.begin.data,
118
+ }).then((result) => {
119
+ const begin = (result ?? {}) as Record<string, unknown>;
120
+ if (!idKey) idKey = "upload_id" in begin ? "upload_id" : "_id";
121
+ id = String(begin[idKey] ?? "");
122
+ // begin 回来前已经中止:补发 cancel,丢掉服务端刚建的上传。
123
+ if (signal?.aborted) cancel();
124
+ return begin;
125
+ });
126
+ try {
127
+ const begin = await abortable(beginPromise, signal);
128
+ if (!id)
129
+ throw new Error(`${options.begin.event} 没有返回上传编号 ${idKey}`);
130
+ const chunkSize = positive(begin.chunk_size) ?? FILE_CHUNK_SIZE;
131
+ const count =
132
+ nonNegative(begin.chunk_count) ?? Math.ceil(file.size / chunkSize);
133
+ onProgress?.(0);
134
+ for (let index = 0; index < count; index += 1) {
135
+ const piece = file.slice(index * chunkSize, (index + 1) * chunkSize);
136
+ const data = await abortable(blobToBase64(piece), signal);
137
+ await abortable(
138
+ call(
139
+ options.chunkEvent,
140
+ { [idKey]: id, index, size: piece.size, data },
141
+ { timeoutMs },
142
+ ),
143
+ signal,
144
+ );
145
+ onProgress?.((index + 1) / count);
146
+ }
147
+ const checksum = await abortable(sha256Hex(file), signal);
148
+ const result = (await abortable(
149
+ call(options.finishEvent, { [idKey]: id, checksum }, { timeoutMs }),
150
+ signal,
151
+ )) as T;
152
+ if (!count) onProgress?.(1);
153
+ return result;
154
+ } catch (error) {
155
+ cancel();
156
+ throw error;
157
+ }
158
+ }
159
+
160
+ export interface YsReadChunkedOptions {
161
+ onProgress?: YsFileProgress;
162
+ signal?: AbortSignal;
163
+ /** 每块的单次超时,默认 FILE_CHUNK_TIMEOUT_MS。 */
164
+ timeoutMs?: number;
165
+ /** Blob 类型:传了就用它;不传用块返回的 content_type;都没有为 application/octet-stream。 */
166
+ type?: string;
167
+ /**
168
+ * 文件编号字段名:第一块返回里这个字段非空时,后续请求把它设成返回值(覆盖请求里的原值)。
169
+ * 不传时依次看 `_id`、`id`。用于「第一块不带编号、由服务端返回」的读取(如员工本人照片)。
170
+ */
171
+ idKey?: string;
172
+ }
173
+
174
+ /**
175
+ * 分块读取:从第 0 块开始,每次请求 `{ ...data, index }`;以第一块返回的 chunk_count 为总块数,
176
+ * 逐块解 base64 拼成 Blob。chunk_count 缺失或为 0 时只读第 0 块。
177
+ */
178
+ export async function readChunked(
179
+ call: YsFileCall,
180
+ event: string,
181
+ data: Record<string, unknown>,
182
+ options: YsReadChunkedOptions = {},
183
+ ): Promise<Blob> {
184
+ const { signal, onProgress } = options;
185
+ const timeoutMs = options.timeoutMs ?? FILE_CHUNK_TIMEOUT_MS;
186
+ signal?.throwIfAborted();
187
+ const request = { ...data };
188
+ const parts: Uint8Array<ArrayBuffer>[] = [];
189
+ let count = 1;
190
+ let contentType = "";
191
+ for (let index = 0; index < count; index += 1) {
192
+ const result = ((await abortable(
193
+ call(event, { ...request, index }, { timeoutMs }),
194
+ signal,
195
+ )) ?? {}) as Record<string, unknown>;
196
+ if (index === 0) {
197
+ count = positive(result.chunk_count) ?? 1;
198
+ contentType =
199
+ typeof result.content_type === "string" ? result.content_type : "";
200
+ const key = options.idKey
201
+ ? options.idKey
202
+ : ["_id", "id"].find((name) => result[name]);
203
+ if (key && result[key]) request[key] = result[key];
204
+ }
205
+ parts.push(base64ToBytes(String(result.data ?? "")));
206
+ onProgress?.((index + 1) / count);
207
+ }
208
+ return new Blob(parts, {
209
+ type: options.type || contentType || "application/octet-stream",
210
+ });
211
+ }
212
+
213
+ function positive(value: unknown): number | undefined {
214
+ return typeof value === "number" && Number.isInteger(value) && value > 0
215
+ ? value
216
+ : undefined;
217
+ }
218
+
219
+ function nonNegative(value: unknown): number | undefined {
220
+ return typeof value === "number" && Number.isInteger(value) && value >= 0
221
+ ? value
222
+ : undefined;
223
+ }
224
+
225
+ /** 等 promise,但中止时立即抛出 signal.reason,不等它完成。 */
226
+ function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
227
+ if (!signal) return promise;
228
+ if (signal.aborted) {
229
+ promise.catch(() => undefined);
230
+ return Promise.reject(signal.reason);
231
+ }
232
+ return new Promise<T>((resolve, reject) => {
233
+ const onAbort = () => reject(signal.reason);
234
+ signal.addEventListener("abort", onAbort, { once: true });
235
+ promise.then(
236
+ (value) => {
237
+ signal.removeEventListener("abort", onAbort);
238
+ resolve(value);
239
+ },
240
+ (error) => {
241
+ signal.removeEventListener("abort", onAbort);
242
+ reject(error);
243
+ },
244
+ );
245
+ });
246
+ }
package/src/index.ts CHANGED
@@ -40,6 +40,20 @@ export {
40
40
  sealPassword,
41
41
  type PasswordWrap,
42
42
  } from "./password";
43
+ export {
44
+ FILE_CHUNK_SIZE,
45
+ FILE_CHUNK_TIMEOUT_MS,
46
+ YsLocalFileError,
47
+ base64ToBytes,
48
+ blobToBase64,
49
+ readChunked,
50
+ sha256Hex,
51
+ uploadChunked,
52
+ type YsFileCall,
53
+ type YsFileProgress,
54
+ type YsReadChunkedOptions,
55
+ type YsUploadChunkedOptions,
56
+ } from "./fileTransfer";
43
57
  export {
44
58
  normalizeSearchText,
45
59
  searchTokens,
package/src/rest.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /* @ysgroup/core —— 管理接口客户端(支持 HTTP 或统一 WS RPC 传输)。 */
2
2
 
3
+ import { base64ToBytes, blobToBase64 } from "./fileTransfer";
3
4
  import { sealLoginPassword } from "./password";
4
5
  import { YsRpcError } from "./ws";
5
6
 
@@ -135,7 +136,7 @@ export class YsRest {
135
136
  upload: {
136
137
  name: file.name,
137
138
  content_type: file.type || "application/octet-stream",
138
- base64: await fileToBase64(file),
139
+ base64: await blobToBase64(file),
139
140
  },
140
141
  user_agent: navigator.userAgent,
141
142
  })) as T;
@@ -443,22 +444,8 @@ function rpcError(error: unknown): YsRestError {
443
444
  return new YsRestError(Number(match[1]), detail);
444
445
  }
445
446
 
446
- function fileToBase64(file: File): Promise<string> {
447
- return new Promise((resolve, reject) => {
448
- const reader = new FileReader();
449
- reader.onerror = () =>
450
- reject(reader.error ?? new Error("读取上传文件失败"));
451
- reader.onload = () => resolve(String(reader.result).split(",", 2)[1] ?? "");
452
- reader.readAsDataURL(file);
453
- });
454
- }
455
-
456
447
  function base64ToBlob(value: string, contentType: string): Blob {
457
- const binary = atob(value);
458
- const bytes = new Uint8Array(binary.length);
459
- for (let index = 0; index < binary.length; index += 1)
460
- bytes[index] = binary.charCodeAt(index);
461
- return new Blob([bytes], { type: contentType });
448
+ return new Blob([base64ToBytes(value)], { type: contentType });
462
449
  }
463
450
 
464
451
  export interface TopologyNode {