@cloudbase/manager-node 5.10.4 → 5.10.6

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.
@@ -1,11 +1,44 @@
1
1
  "use strict";
2
2
  /* eslint-disable @typescript-eslint/member-ordering */
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
3
19
  var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
4
20
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5
21
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
6
22
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
7
23
  return c > 3 && r && Object.defineProperty(target, key, r), r;
8
24
  };
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
9
42
  var __importDefault = (this && this.__importDefault) || function (mod) {
10
43
  return (mod && mod.__esModule) ? mod : { "default": mod };
11
44
  };
@@ -13,6 +46,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
46
  exports.StorageService = exports.md5File = void 0;
14
47
  exports.collectBatchDeleteFailures = collectBatchDeleteFailures;
15
48
  const fs_1 = __importDefault(require("fs"));
49
+ const os_1 = __importDefault(require("os"));
50
+ const crypto_1 = __importDefault(require("crypto"));
16
51
  const util_1 = __importDefault(require("util"));
17
52
  const path_1 = __importDefault(require("path"));
18
53
  const make_dir_1 = __importDefault(require("make-dir"));
@@ -20,8 +55,11 @@ const walkdir_1 = __importDefault(require("walkdir"));
20
55
  const micromatch_1 = __importDefault(require("micromatch"));
21
56
  const mime_types_1 = __importDefault(require("mime-types"));
22
57
  const cos_nodejs_sdk_v5_1 = __importDefault(require("cos-nodejs-sdk-v5"));
58
+ const tus = __importStar(require("tus-js-client"));
59
+ const https_proxy_agent_1 = require("https-proxy-agent");
23
60
  const utils_1 = require("../utils");
24
61
  const error_1 = require("../error");
62
+ const error_types_1 = require("../error-types");
25
63
  const fs_2 = require("../utils/fs");
26
64
  const parallel_1 = require("../utils/parallel");
27
65
  const storage_config_1 = require("../utils/storage-config");
@@ -2018,10 +2056,10 @@ class StorageService {
2018
2056
  else if (Buffer.isBuffer(body) && fileSize === undefined) {
2019
2057
  fileSize = body.length;
2020
2058
  }
2021
- // 文档约束:> 100MB 拒绝
2022
- const LIMIT_100MB = 100 * 1024 * 1024;
2023
- if (fileSize !== undefined && fileSize > LIMIT_100MB) {
2024
- throw new error_1.CloudBaseError('文件大小超过 100MB', {
2059
+ // 文档约束:> 200MB 拒绝
2060
+ const LIMIT_200MB = 200 * 1024 * 1024;
2061
+ if (fileSize !== undefined && fileSize > LIMIT_200MB) {
2062
+ throw new error_1.CloudBaseError('文件大小超过 200MB', {
2025
2063
  code: 'FILE_SIZE_LIMIT_EXCEEDED'
2026
2064
  });
2027
2065
  }
@@ -2040,15 +2078,9 @@ class StorageService {
2040
2078
  if (fileSize !== undefined) {
2041
2079
  headers['Content-Length'] = String(fileSize);
2042
2080
  }
2043
- // 未显式传入(含空白字符串)时默认 max-age=3600;注意保留 0 的语义(max-age=0)
2044
- const normalizedCacheControl = typeof cacheControl === 'string' && cacheControl.trim() === ''
2045
- ? undefined
2046
- : cacheControl;
2047
- const finalCacheControl = normalizedCacheControl !== null && normalizedCacheControl !== void 0 ? normalizedCacheControl : 3600;
2048
- headers['Cache-Control'] =
2049
- typeof finalCacheControl === 'number'
2050
- ? `max-age=${finalCacheControl}`
2051
- : String(finalCacheControl);
2081
+ // 不传或空白时默认 3600;数字和纯数字字符串转成 max-age=N,其他字符串原样作为请求头
2082
+ const cacheControlText = String(cacheControl !== null && cacheControl !== void 0 ? cacheControl : '').trim() || '3600';
2083
+ headers['Cache-Control'] = /^\d+$/.test(cacheControlText) ? `max-age=${cacheControlText}` : cacheControlText;
2052
2084
  if (metadata) {
2053
2085
  // x-metadata 放在 Header 里,具体大小限制由服务端/网关决定
2054
2086
  headers['x-metadata'] = Buffer.from(JSON.stringify(metadata), 'utf8').toString('base64');
@@ -2095,6 +2127,352 @@ class StorageService {
2095
2127
  Key: payload.Key
2096
2128
  };
2097
2129
  }
2130
+ /**
2131
+ * 通过 CloudBase HTTP API 断点续传上传对象(TUS 协议)
2132
+ * POST / PATCH / HEAD /v1/storages/upload/resumable
2133
+ */
2134
+ async uploadObjectResumable(options) {
2135
+ var _a;
2136
+ if (!options || typeof options !== 'object') {
2137
+ (0, error_1.throwInvalidParam)('options 必须是非空对象');
2138
+ }
2139
+ const { bucketId, objectName, localPath } = options;
2140
+ if (!bucketId || typeof bucketId !== 'string') {
2141
+ (0, error_1.throwInvalidParam)('bucketId 必须是非空字符串');
2142
+ }
2143
+ if (!objectName || typeof objectName !== 'string') {
2144
+ (0, error_1.throwInvalidParam)('objectName 必须是非空字符串');
2145
+ }
2146
+ if (!localPath || typeof localPath !== 'string') {
2147
+ (0, error_1.throwInvalidParam)('localPath 必须是非空字符串');
2148
+ }
2149
+ if (options.accessToken !== undefined && (typeof options.accessToken !== 'string' || !options.accessToken)) {
2150
+ (0, error_1.throwInvalidParam)('accessToken 必须是非空字符串');
2151
+ }
2152
+ const resolvedPath = path_1.default.resolve(localPath);
2153
+ (0, utils_1.checkFullAccess)(resolvedPath, true);
2154
+ const stat = fs_1.default.statSync(resolvedPath);
2155
+ if (!stat.isFile()) {
2156
+ (0, error_1.throwInvalidParam)(`localPath 不是文件: ${localPath}`);
2157
+ }
2158
+ // 不支持空文件:服务端会返回 500(底层 COS 411 MissingContentLength),且 tus 客户端读取 0 字节源时会抛错
2159
+ if (stat.size === 0) {
2160
+ (0, error_1.throwInvalidParam)('断点续传不支持空文件,请使用 uploadObject 上传');
2161
+ }
2162
+ // 分片策略沿用 Supabase Studio 的分档规则:小于 30MB 固定 6MB,其余按所在档位的目标分片数均分。
2163
+ // 服务端约束:单分片 ≤ 60MB,分片数 ≤ 10000,单文件 ≤ 100GB
2164
+ const MB = 1024 * 1024;
2165
+ const MIN_CHUNK_SIZE = 6 * MB;
2166
+ const MAX_CHUNK_SIZE = 60 * MB;
2167
+ const MAX_CHUNK_COUNT = 10000;
2168
+ const MAX_FILE_SIZE = 100 * 1024 * MB;
2169
+ if (stat.size > MAX_FILE_SIZE) {
2170
+ (0, error_1.throwInvalidParam)(`文件过大(${stat.size} 字节),单文件上限 100GB,请自行分卷`);
2171
+ }
2172
+ // 各档位除数不同,分片大小在档位边界处不连续(99.9MB / 8 ≈ 12.49MB,100MB / 10 = 10MB)。
2173
+ // 每档以上一档边界值为下限,保证分片大小关于文件大小单调不减
2174
+ const sizeMB = stat.size / MB;
2175
+ let chunkSize = MIN_CHUNK_SIZE;
2176
+ if (sizeMB >= 10 * 1024) {
2177
+ chunkSize = Math.max(Math.floor(stat.size / 50), Math.floor((10 * 1024 * MB) / 30));
2178
+ }
2179
+ else if (sizeMB >= 1024) {
2180
+ chunkSize = Math.max(Math.floor(stat.size / 30), Math.floor((1024 * MB) / 20));
2181
+ }
2182
+ else if (sizeMB >= 500) {
2183
+ chunkSize = Math.max(Math.floor(stat.size / 20), Math.floor((500 * MB) / 10));
2184
+ }
2185
+ else if (sizeMB >= 100) {
2186
+ chunkSize = Math.max(Math.floor(stat.size / 10), Math.floor((100 * MB) / 8));
2187
+ }
2188
+ else if (sizeMB >= 30) {
2189
+ chunkSize = Math.floor(stat.size / 8);
2190
+ }
2191
+ // 30MB 边界同样不连续(30MB / 8 = 3.75MB < 6MB),统一钳制到 [MIN_CHUNK_SIZE, MAX_CHUNK_SIZE]
2192
+ chunkSize = Math.min(Math.max(chunkSize, MIN_CHUNK_SIZE), MAX_CHUNK_SIZE);
2193
+ // 现有常量下分片数上限约 1707(100GB / 60MB),该分支不可达;作为常量调整后的防御性校验保留
2194
+ if (Math.ceil(stat.size / chunkSize) > MAX_CHUNK_COUNT) {
2195
+ (0, error_1.throwInvalidParam)(`分片数超过服务端上限 ${MAX_CHUNK_COUNT}`);
2196
+ }
2197
+ const contentType = this.resolveUploadContentType({
2198
+ contentType: options.contentType,
2199
+ localPath: resolvedPath,
2200
+ objectName
2201
+ });
2202
+ // 默认 3600。服务端仅解析纯秒数并拼接为 max-age=N,其他取值均被存为 no-cache(预发环境验证)。
2203
+ // 因此仅接受秒数(可带 max-age= 前缀)与 no-cache,其余取值视为非法参数
2204
+ const cacheControlText = String((_a = options.cacheControl) !== null && _a !== void 0 ? _a : '').trim() || '3600';
2205
+ const maxAgeMatch = /^(?:max-age=)?(\d+)$/i.exec(cacheControlText);
2206
+ const noCacheMatch = /^no-cache$/i.test(cacheControlText);
2207
+ if (!maxAgeMatch && !noCacheMatch) {
2208
+ (0, error_1.throwInvalidParam)(`断点续传的 cacheControl 只支持秒数(如 3600 或 "max-age=3600")或 "no-cache",收到: ${cacheControlText}`);
2209
+ }
2210
+ // TUS Upload-Metadata,值由 tus-js-client 负责 base64 编码;服务端 bucketName 字段语义为 bucket id
2211
+ const tusMetadata = {
2212
+ bucketName: bucketId,
2213
+ objectName,
2214
+ cacheControl: maxAgeMatch ? maxAgeMatch[1] : 'no-cache'
2215
+ };
2216
+ if (contentType) {
2217
+ tusMetadata.contentType = contentType;
2218
+ }
2219
+ if (options.metadata) {
2220
+ tusMetadata.metadata = JSON.stringify(options.metadata);
2221
+ }
2222
+ const envId = options.envId || this.environment.getEnvId();
2223
+ // 存储网关仅支持 Bearer 鉴权,不支持 AK/SK 签名。未传 accessToken 时,使用初始化凭证换取目标环境的管理员 token
2224
+ // (EnvService 以 env + secretId 为键缓存,超过有效期一半后刷新)。
2225
+ // 上传前预取一次,使凭证缺失、换取失败等配置类错误在上传前快速失败,避免进入 tus 重试流程
2226
+ const getAccessToken = () => options.accessToken
2227
+ ? Promise.resolve(options.accessToken)
2228
+ : this.environment.getEnvService().getAdminAccessToken(undefined, envId);
2229
+ await getAccessToken();
2230
+ // 将 HTTP 响应解析为 CloudBaseError,兼容网关 JSON、存储服务 JSON 及 tus 协议层 "CODE: message" 纯文本三种格式
2231
+ const errorFromResponse = (res, original) => {
2232
+ const status = res.getStatus();
2233
+ const body = res.getBody() || '';
2234
+ let code = '';
2235
+ let message = '';
2236
+ let requestId = '';
2237
+ try {
2238
+ const payload = JSON.parse(body);
2239
+ code = (payload === null || payload === void 0 ? void 0 : payload.code) || (payload === null || payload === void 0 ? void 0 : payload.Code) || '';
2240
+ message = (payload === null || payload === void 0 ? void 0 : payload.message) || (payload === null || payload === void 0 ? void 0 : payload.Message) || '';
2241
+ requestId = (payload === null || payload === void 0 ? void 0 : payload.requestId) || (payload === null || payload === void 0 ? void 0 : payload.RequestId) || '';
2242
+ }
2243
+ catch (_a) {
2244
+ const match = /^([A-Z0-9_]+):\s*([\s\S]*)$/.exec(body.trim());
2245
+ if (match) {
2246
+ code = match[1];
2247
+ message = match[2];
2248
+ }
2249
+ }
2250
+ const source = code ? 'cloud-api' : 'manager-node';
2251
+ code = code || `HTTP_${status}`;
2252
+ // 无法按上述格式解析时(如网关返回的 "404 page not found"),以响应原文作为 message
2253
+ message = message || body.trim() || '断点续传上传失败';
2254
+ requestId = requestId || res.getHeader('x-cloudbase-request-id') || '';
2255
+ return new error_1.CloudBaseError(`${code}: ${message}`, { code, source, requestId, original });
2256
+ };
2257
+ // 公共请求头,tus 会附加到 POST/PATCH/HEAD/DELETE 所有请求;x-upsert 若仅在创建请求中携带,最后一个分片会返回 409。
2258
+ // Authorization 不在此设置,而是在 onBeforeRequest 中按请求注入,避免长时上传过程中 token 过期
2259
+ const tusHeaders = {};
2260
+ if (options.upsert) {
2261
+ tusHeaders['x-upsert'] = 'true';
2262
+ }
2263
+ // endpoint 不能以 "/" 结尾,否则网关返回 307 重定向
2264
+ const endpoint = `https://${envId}.api.tcloudbasegateway.com/v1/storages/upload/resumable`;
2265
+ // 代理解析规则与 fetchStream 保持一致:优先使用配置的 proxy,其次 process.env.http_proxy
2266
+ const { proxy } = this.environment.getAuthConfig();
2267
+ const proxyUrl = proxy || process.env.http_proxy;
2268
+ const httpStack = new tus.DefaultHttpStack(proxyUrl ? { agent: new https_proxy_agent_1.HttpsProxyAgent(proxyUrl) } : {});
2269
+ // 取消标志位,由 onAbort 置位,供 onBeforeRequest 拦截尚未发出的请求
2270
+ let cancelled = false;
2271
+ // 续传记录通过 tus FileUrlStorage 持久化至 ~/.cloudbase/tus-uploads.json。
2272
+ // 该记录仅用于跨调用续传,属于尽力而为:目录创建或读写失败(如只读文件系统)时降级为普通上传
2273
+ const recordFile = path_1.default.join(os_1.default.homedir(), '.cloudbase', 'tus-uploads.json');
2274
+ try {
2275
+ make_dir_1.default.sync(path_1.default.dirname(recordFile));
2276
+ }
2277
+ catch (e) {
2278
+ (0, utils_1.debugLog)(`[uploadObjectResumable] 续传记录目录不可用: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
2279
+ }
2280
+ const urlStorage = new tus.FileUrlStorage(recordFile);
2281
+ // tus 对 addUpload 的 rejection 没有任何 catch,失败一旦向上抛出上传流程会直接挂起,故在此兜底。
2282
+ // 失败时不能返回 null:tus 会把 resolve 值无条件赋给 _urlStorageKey,null 是其「尚未保存」的哨兵值,
2283
+ // 会让 tus 重新放行保存并为同一 fingerprint 累积多条记录。返回一个不会与真实 key
2284
+ // (形如 tus::<fingerprint>::<id>)冲突的哨兵值,借 tus 自身 `_urlStorageKey !== null` 守卫短路,不再重试
2285
+ const addUpload = urlStorage.addUpload.bind(urlStorage);
2286
+ urlStorage.addUpload = (fp, upload) => addUpload(fp, upload).catch((e) => {
2287
+ (0, utils_1.debugLog)(`[uploadObjectResumable] 保存续传记录失败: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
2288
+ return `disabled::${fp}`;
2289
+ });
2290
+ // 续传指纹由目标位置、本地文件特征与 upsert 组成:目标位置避免同一文件上传至不同位置时复用错误会话;
2291
+ // size 与 mtime 用于检测本地文件变更;upsert 用于隔离覆盖与非覆盖两类会话
2292
+ const fingerprint = crypto_1.default
2293
+ .createHash('sha256')
2294
+ .update([envId, bucketId, objectName, resolvedPath, stat.size, stat.mtimeMs, options.upsert ? 'upsert' : ''].join('\n'))
2295
+ .digest('hex');
2296
+ // 重试策略:无响应(网络错误、超时)、5xx 及协议异常(如响应缺少必需头)可重试;
2297
+ // 4xx 中仅 408、423(会话锁定)及 offset 冲突导致的 409 可重试,对象已存在的 409 与其余 4xx 属确定性失败
2298
+ const shouldRetry = (err) => {
2299
+ var _a, _b, _c, _d;
2300
+ const status = (_b = (_a = err.originalResponse) === null || _a === void 0 ? void 0 : _a.getStatus()) !== null && _b !== void 0 ? _b : 0;
2301
+ if (status < 400 || status >= 500) {
2302
+ return true;
2303
+ }
2304
+ if (status === 409) {
2305
+ const body = (_d = (_c = err.originalResponse) === null || _c === void 0 ? void 0 : _c.getBody()) !== null && _d !== void 0 ? _d : '';
2306
+ return !body.includes('STORAGE_KEY_ALREADY_EXISTS');
2307
+ }
2308
+ return status === 408 || status === 423;
2309
+ };
2310
+ // 进度上报:
2311
+ // - resumedFrom 取首次进度值:tus 在每次 POST / PATCH 前会以当前 offset 上报一次进度
2312
+ // (新建会话为 0,续传为断点 offset),HEAD 失败、423、响应头缺失时不上报,故首次进度即实际起始 offset
2313
+ // - tus 上报的是已写入 socket 的字节数,服务端确认前可能因重试回退;因此上传过程中进度单调不减且上限为 total - 1,
2314
+ // 仅在成功时(final)上报一次 100%,此后不再回调
2315
+ // - 速率仅统计本次调用实际传输的字节,即扣除 resumedFrom
2316
+ const startTime = Date.now();
2317
+ let resumedFrom;
2318
+ let maxLoaded = 0;
2319
+ let completed = false;
2320
+ const emitProgress = (loaded, total, final = false) => {
2321
+ resumedFrom = resumedFrom !== null && resumedFrom !== void 0 ? resumedFrom : loaded;
2322
+ if (!options.onProgress || completed) {
2323
+ return;
2324
+ }
2325
+ maxLoaded = Math.max(maxLoaded, final ? total : Math.min(loaded, total - 1));
2326
+ const elapsedSec = (Date.now() - startTime) / 1000;
2327
+ // 隔离用户回调异常,避免中断 tus 上传链路或阻断 onSuccess 中的 resolve
2328
+ try {
2329
+ options.onProgress({
2330
+ loaded: maxLoaded,
2331
+ total,
2332
+ speed: elapsedSec > 0 ? Math.max(0, maxLoaded - resumedFrom) / elapsedSec : 0,
2333
+ percent: final ? 1 : maxLoaded / total,
2334
+ resumedFrom
2335
+ });
2336
+ }
2337
+ catch (e) {
2338
+ (0, utils_1.debugLog)(`[uploadObjectResumable] onProgress 回调抛错: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
2339
+ }
2340
+ completed = final;
2341
+ };
2342
+ // 将 tus 错误归一化为 CloudBaseError:无响应时透传 SDK 自身抛出的 CloudBaseError(如 token 换取失败)以保留错误码,
2343
+ // 其余无响应归类为 NETWORK_ERROR;有响应时按响应解析
2344
+ const toCloudBaseError = (err) => {
2345
+ const res = err.originalResponse;
2346
+ if (!res) {
2347
+ const causingError = err.causingError;
2348
+ if (causingError instanceof error_1.CloudBaseError) {
2349
+ return causingError;
2350
+ }
2351
+ return new error_1.CloudBaseError(`${error_types_1.ERROR_TYPES.netError.code}: ${err.message}`, {
2352
+ type: error_types_1.ERROR_TYPES.netError,
2353
+ original: err
2354
+ });
2355
+ }
2356
+ return errorFromResponse(res, err);
2357
+ };
2358
+ // 文件流由 SDK 持有:tus 仅在成功时关闭源流,暂停、终止或失败时需在 abort 完成后显式销毁,避免文件描述符泄漏
2359
+ const source = fs_1.default.createReadStream(resolvedPath);
2360
+ const upload = new tus.Upload(source, {
2361
+ endpoint,
2362
+ chunkSize,
2363
+ uploadSize: stat.size,
2364
+ metadata: tusMetadata,
2365
+ headers: tusHeaders,
2366
+ // 每个请求(含终止时的 DELETE)发出前注入 token;换取失败时按无响应错误重试
2367
+ onBeforeRequest: async (req) => {
2368
+ const token = await getAccessToken();
2369
+ // 竞态处理:获取 token 期间发生暂停或终止时,请求尚未发出,不受 tus abort 控制,需在此拦截(终止所需的 DELETE 除外)。
2370
+ // abort 后 tus 不再上报错误,此处异常内容不会暴露给调用方
2371
+ if (cancelled && req.getMethod() !== 'DELETE') {
2372
+ throw new Error('上传已取消');
2373
+ }
2374
+ req.setHeader('Authorization', `Bearer ${token}`);
2375
+ },
2376
+ httpStack,
2377
+ urlStorage,
2378
+ fingerprint: () => Promise.resolve(fingerprint),
2379
+ // 以下两项配置与 Supabase Studio 保持一致
2380
+ uploadDataDuringCreation: stat.size <= chunkSize,
2381
+ retryDelays: [0, 200, 500, 1500, 3000, 5000],
2382
+ onShouldRetry: shouldRetry,
2383
+ onProgress: emitProgress
2384
+ });
2385
+ // 按指纹检索本地续传记录,命中则复用对应的服务端会话;记录文件损坏时视为无记录
2386
+ const previous = await upload.findPreviousUploads().catch((e) => {
2387
+ (0, utils_1.debugLog)(`[uploadObjectResumable] 读取续传记录失败(可删除 ${recordFile} 恢复): ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
2388
+ return [];
2389
+ });
2390
+ if (previous.length > 0) {
2391
+ upload.resumeFromPreviousUpload(previous[0]);
2392
+ }
2393
+ // 清理本地续传记录:成功与终止路径均等待清理完成后再返回。
2394
+ // 未采用 tus 的 removeFingerprintOnSuccess:其删除为异步且不被等待,紧随其后的同目标调用可能读取到过期记录。
2395
+ // 清理失败不影响本次调用结果
2396
+ const removeLocalRecords = async () => {
2397
+ try {
2398
+ const records = await urlStorage.findUploadsByFingerprint(fingerprint);
2399
+ await Promise.all(records.map(record => urlStorage.removeUpload(record.urlStorageKey)));
2400
+ }
2401
+ catch (e) {
2402
+ (0, utils_1.debugLog)(`[uploadObjectResumable] 删除续传记录失败: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
2403
+ }
2404
+ };
2405
+ // 终止上传:DELETE 请求超时上限 5 秒;无论成功与否均清理本地记录(tus 在 DELETE 失败时不会清理)
2406
+ const terminate = async () => {
2407
+ let timer;
2408
+ const timeout = new Promise(resolve => {
2409
+ timer = setTimeout(resolve, 5000);
2410
+ });
2411
+ await Promise.race([upload.abort(true).catch(() => undefined), timeout]);
2412
+ clearTimeout(timer);
2413
+ await removeLocalRecords();
2414
+ };
2415
+ return new Promise((resolve, reject) => {
2416
+ var _a, _b;
2417
+ // settled 保证 onAbort / onSuccess / onError 互斥且仅生效一次,并避免上传结束后 signal 触发对已完成会话发送 DELETE。
2418
+ // settled 在 abort 之前置位:signal 触发即确定本次结果为暂停/终止,后续 tus 的 onSuccess/onError 均被忽略;
2419
+ // reject 绑定在 abort 自身的 Promise 链上,不依赖 tus 回调,确保 Promise 必然落定
2420
+ let settled = false;
2421
+ // 结束时解绑监听:调用方常复用同一 signal 管理多次上传,不解绑会导致监听器累积并持有 upload 引用
2422
+ const settle = () => {
2423
+ var _a, _b;
2424
+ settled = true;
2425
+ (_b = (_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, 'abort', onAbort);
2426
+ };
2427
+ const onAbort = () => {
2428
+ if (settled) {
2429
+ return;
2430
+ }
2431
+ cancelled = true;
2432
+ settle();
2433
+ // 终止:发送 DELETE 并清理本地记录;暂停:仅中断当前请求并保留本地记录,以相同参数再次调用即可续传
2434
+ const [stop, type, message] = options.terminateOnAbort
2435
+ ? [terminate, error_types_1.ERROR_TYPES.uploadAborted, '上传已终止']
2436
+ : [() => upload.abort(false), error_types_1.ERROR_TYPES.uploadPaused, '上传已暂停,再次调用即可从断点继续'];
2437
+ // 经 Promise 链调用 stop,使 abort 的同步异常同样进入 reject 分支,避免 Promise 永不落定。
2438
+ // 源流须在 abort 完成后销毁:提前销毁会导致 tus 读流异常,进而触发重试或 onError
2439
+ Promise.resolve()
2440
+ .then(stop)
2441
+ .catch(() => undefined)
2442
+ .then(() => {
2443
+ source.destroy();
2444
+ reject(new error_1.CloudBaseError(message, { type }));
2445
+ });
2446
+ };
2447
+ // tus 在事件触发时才从 this.options 读取回调,构造后注入同样生效
2448
+ Object.assign(upload.options, {
2449
+ onSuccess: () => {
2450
+ if (settled) {
2451
+ return;
2452
+ }
2453
+ settle();
2454
+ source.destroy();
2455
+ // 唯一的 100% 上报点:上传过程中进度上限为 total - 1,且 tus 进度回调存在 100ms 节流
2456
+ emitProgress(stat.size, stat.size, true);
2457
+ removeLocalRecords().then(() => resolve({ bucketId, objectName, size: stat.size, resumedFrom: resumedFrom !== null && resumedFrom !== void 0 ? resumedFrom : 0 }));
2458
+ },
2459
+ onError: (err) => {
2460
+ if (settled) {
2461
+ return;
2462
+ }
2463
+ settle();
2464
+ source.destroy();
2465
+ reject(toCloudBaseError(err));
2466
+ }
2467
+ });
2468
+ if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
2469
+ onAbort();
2470
+ return;
2471
+ }
2472
+ (_b = options.abortSignal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', onAbort);
2473
+ upload.start();
2474
+ });
2475
+ }
2098
2476
  /**
2099
2477
  * 通过 CloudBase HTTP API 删除单个对象
2100
2478
  * DELETE /v1/storages/object/:bucketId/*objectName
@@ -3565,6 +3943,9 @@ __decorate([
3565
3943
  __decorate([
3566
3944
  (0, utils_1.preLazy)()
3567
3945
  ], StorageService.prototype, "uploadObject", null);
3946
+ __decorate([
3947
+ (0, utils_1.preLazy)()
3948
+ ], StorageService.prototype, "uploadObjectResumable", null);
3568
3949
  __decorate([
3569
3950
  (0, utils_1.preLazy)()
3570
3951
  ], StorageService.prototype, "deleteObject", null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudbase/manager-node",
3
- "version": "5.10.4",
3
+ "version": "5.10.6",
4
4
  "description": "The node manage service api for cloudbase.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
@@ -55,6 +55,7 @@
55
55
  "mime-types": "^3.0.2",
56
56
  "node-fetch": "^2.6.0",
57
57
  "query-string": "^6.8.3",
58
+ "tus-js-client": "^4.3.1",
58
59
  "unzipper": "^0.12.3",
59
60
  "uuid": "^9.0.0",
60
61
  "walkdir": "^0.4.1"
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 错误码表一致性核对
3
+ *
4
+ * 数据面码表(`src/error-docs.ts` 的 `RUNTIME_ERROR_CODES`)是**手工摘录**的,
5
+ * 官方清单会持续新增码;本脚本把本地码表与线上单码页做双向差集,防止静默漂移。
6
+ *
7
+ * 用法:
8
+ * node scripts/check-error-codes.cjs # 只报告
9
+ * node scripts/check-error-codes.cjs --strict # 有缺失时退出码 1(可用于定时任务)
10
+ *
11
+ * 为什么以「线上单码页」为准:每个错误码在 docs.cloudbase.net 都有独立页面,
12
+ * 侧边栏链接(`/error-code/{CODE}`)就是官方码表本身,无需解析表格。
13
+ */
14
+ 'use strict'
15
+
16
+ const fs = require('fs')
17
+ const path = require('path')
18
+
19
+ const SOURCE_URL = 'https://docs.cloudbase.net/error-code/basic'
20
+ /** 抓取超时(毫秒)。无超时会让脚本在网络异常时无限挂起 */
21
+ const FETCH_TIMEOUT_MS = 15000
22
+ const ERROR_DOCS = path.resolve(__dirname, '../src/error-docs.ts')
23
+ /** 侧边栏里混有小写分类页(basic / cli / toolbox),只取全大写码 */
24
+ const CODE_LINK_RE = /\/error-code\/([A-Z][A-Z0-9_]{3,})/g
25
+
26
+ async function fetchCodes() {
27
+ const fetch = require('node-fetch')
28
+ // 必须带超时:node-fetch 默认无限等待,文档站挂起时脚本会一直卡住,
29
+ // 挂定时任务时表现为「任务不结束」而不是失败
30
+ const response = await fetch(SOURCE_URL, { timeout: FETCH_TIMEOUT_MS })
31
+ if (!response.ok) {
32
+ throw new Error(`抓取失败 HTTP ${response.status} — ${SOURCE_URL}`)
33
+ }
34
+ const html = await response.text()
35
+ const codes = new Set()
36
+ let match
37
+ while ((match = CODE_LINK_RE.exec(html))) codes.add(match[1])
38
+ return codes
39
+ }
40
+
41
+ function readLocalCodes() {
42
+ const source = fs.readFileSync(ERROR_DOCS, 'utf8')
43
+ const block = source.match(/export const RUNTIME_ERROR_CODES[\s\S]*?\n\]\)/)
44
+ if (!block) throw new Error('未在 src/error-docs.ts 找到 RUNTIME_ERROR_CODES')
45
+ const codes = new Set()
46
+ const entryRe = /^ {4}'([^']+)'/gm
47
+ let match
48
+ while ((match = entryRe.exec(block[0]))) codes.add(match[1])
49
+ return codes
50
+ }
51
+
52
+ async function main() {
53
+ const strict = process.argv.includes('--strict')
54
+ const online = await fetchCodes()
55
+ const local = readLocalCodes()
56
+
57
+ const missing = [...online].filter(code => !local.has(code)).sort()
58
+ const extra = [...local].filter(code => !online.has(code)).sort()
59
+
60
+ console.log(`线上单码页 ${online.size} 个 | 本地码表 ${local.size} 条`)
61
+ console.log(`\n本地缺失(线上有、本地没有)${missing.length} 个:`)
62
+ console.log(missing.join(', ') || '(无)')
63
+ console.log(`\n本地多余(本地有、线上无单码页)${extra.length} 个:`)
64
+ console.log(extra.join(', ') || '(无)')
65
+
66
+ if (strict && missing.length > 0) {
67
+ process.exit(1)
68
+ }
69
+ }
70
+
71
+ // 顶部统一兜底:抓取失败 / 文件缺失都在这里转成可读信息并退出 1。
72
+ // 用 `.catch()` 而非 main 内部 try/catch —— 等价,且避免为错误处理再加一层缩进。
73
+ main().catch(err => {
74
+ console.error(`[check-error-codes] ${err.message}`)
75
+ console.error(
76
+ `提示:本脚本依赖公网文档站(${SOURCE_URL},超时 ${FETCH_TIMEOUT_MS}ms)。` +
77
+ '离网或文档站异常时跳过即可,不影响 lint / 单测等其他检查。'
78
+ )
79
+ process.exit(1)
80
+ })
@@ -1,13 +1,16 @@
1
1
  /**
2
- * PushPGUserMigrations 的单条 migration 输入
2
+ * PushPGUserMigrations / PreviewPGUserMigrations 的单条 migration 输入
3
3
  */
4
4
  export interface IPGUserMigrationInput {
5
5
  /** migration 版本,14 位数字时间串,如 20260526000000 */
6
6
  Version: string;
7
7
  /** migration 名称,仅允许小写字母和下划线 */
8
8
  Name: string;
9
- /** 要执行的 SQL */
10
- Query: string;
9
+ /**
10
+ * 要执行的 SQL,未应用的 migration 必须提供非空 SQL。
11
+ * 已应用的 migration 可省略,SDK 会在请求前移除其 SQL。
12
+ */
13
+ Query?: string;
11
14
  /** 回滚 SQL(可选) */
12
15
  Rollback?: string;
13
16
  }
@@ -17,7 +20,10 @@ export interface IPGUserMigrationInput {
17
20
  export interface IPushPGUserMigrationsOptions {
18
21
  /** 云开发环境 ID(可选,不传则自动使用当前环境 ID) */
19
22
  EnvId?: string;
20
- /** migration 列表(至少 1 条) */
23
+ /**
24
+ * 完整的本地 migration 列表(至少 1 条),不能仅传新增条目。
25
+ * SDK 查询远端已应用版本后裁剪历史 SQL,保留全量元数据用于漂移检测。
26
+ */
21
27
  Migrations: IPGUserMigrationInput[];
22
28
  /** 获取数据库锁最长等待时间(毫秒) */
23
29
  LockTimeoutMs?: number;
@@ -41,7 +47,10 @@ export interface IPushPGUserMigrationsResult {
41
47
  export interface IPreviewPGUserMigrationsOptions {
42
48
  /** 云开发环境 ID(可选,不传则自动使用当前环境 ID) */
43
49
  EnvId?: string;
44
- /** migration 列表(至少 1 条) */
50
+ /**
51
+ * 完整的本地 migration 列表(至少 1 条),不能仅传新增条目。
52
+ * SDK 查询远端已应用版本后裁剪历史 SQL,保留全量元数据用于漂移检测。
53
+ */
45
54
  Migrations: IPGUserMigrationInput[];
46
55
  /** 是否允许 out-of-order local migrations */
47
56
  IncludeAll?: boolean;
@@ -77,7 +86,7 @@ export interface IPGUserMigrationConflict {
77
86
  LocalChecksum?: string;
78
87
  /** 数据库中已应用 migration 的 checksum */
79
88
  RemoteChecksum?: string;
80
- /** 冲突原因(如 checksum_mismatch) */
89
+ /** 冲突原因,由服务端返回,可能涉及本地与远端历史漂移 */
81
90
  Reason?: string;
82
91
  /** 冲突详情信息 */
83
92
  Message?: string;
@@ -92,9 +101,9 @@ export interface IPreviewPGUserMigrationsResult {
92
101
  Pending: IPGUserMigrationPlanItem[] | null;
93
102
  /** 已经应用过的 migration 列表 */
94
103
  Applied: IPGUserMigrationPlanItem[] | null;
95
- /** checksum 冲突列表 */
104
+ /** migration 冲突列表,包括本地与远端历史漂移 */
96
105
  Conflicts: IPGUserMigrationConflict[] | null;
97
- /** 是否可直接执行(当前主要表示无 checksum 冲突) */
106
+ /** 是否可直接执行,以服务端计划校验结果为准 */
98
107
  Executable: boolean;
99
108
  /** 请求唯一 ID */
100
109
  RequestId: string;
@@ -25,6 +25,11 @@ export declare class DocsService {
25
25
  type: 'doc';
26
26
  data: string;
27
27
  }>;
28
+ /**
29
+ * 请求目标只由 DOCS_BASE_URL 决定:解析后丢弃入参带来的 scheme / host / userinfo / port,
30
+ * 只保留 pathname + search + hash 再拼回固定 origin。调用方无论如何都选不了主机。
31
+ */
32
+ resolveDocsRequestUrl(docPath: string): string;
28
33
  readDoc(docPath: string): Promise<string>;
29
34
  searchDocs(query: string): Promise<SearchResult[]>;
30
35
  private getCategory;