@h-ai/storage 0.1.0-alpha8 → 1.0.0-beta.1
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.en.md +287 -0
- package/README.ja.md +287 -0
- package/README.md +235 -59
- package/dist/browser.d.ts +490 -102
- package/dist/browser.js +3 -2
- package/dist/chunk-KVFEQHRX.js +360 -0
- package/dist/chunk-KVFEQHRX.js.map +1 -0
- package/dist/{chunk-KHZOR6CR.js → chunk-P4NA6BCH.js} +37 -12
- package/dist/chunk-P4NA6BCH.js.map +1 -0
- package/dist/chunk-P65WYXJG.js +33 -0
- package/dist/chunk-P65WYXJG.js.map +1 -0
- package/dist/client/index.d.ts +57 -48
- package/dist/client/index.js +1 -1
- package/dist/node.d.ts +15 -11
- package/dist/node.js +582 -178
- package/dist/node.js.map +1 -1
- package/dist/schemas.d.ts +103 -0
- package/dist/schemas.js +3 -0
- package/dist/schemas.js.map +1 -0
- package/package.json +22 -16
- package/dist/api/index.d.ts +0 -167
- package/dist/api/index.js +0 -105
- package/dist/api/index.js.map +0 -1
- package/dist/chunk-KHZOR6CR.js.map +0 -1
- package/dist/chunk-U427BQIQ.js +0 -266
- package/dist/chunk-U427BQIQ.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage-config.ts","../src/storage-types.ts"],"names":[],"mappings":";;;;;AAyBO,IAAM,oBAAoB,CAAA,CAAE,IAAA,CAAK,CAAC,IAAA,EAAM,OAAO,CAAC;AAwBhD,IAAM,+BAAA,GAAkC,EAAE,MAAA,CAAO;AAAA,EACtD,IAAA,EAAM,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA,EAC/B,KAAA,EAAO,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAQ,KAAK,CAAA;AAAA,EAChC,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,GAAA,CAAI,CAAC,CAAA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zC,0BAAA,EAA4B,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AACzC,CAAC;AA0BM,IAAM,0BAAA,GAA6B,qBAAqB,MAAA,CAAO;AAAA;AAAA,EAEpE,WAAA,EAAa,CAAA,CAAE,MAAA,EAAO,CAAE,QAAQ,0BAA0B;AAC5D,CAAC;AC/PD,IAAM,gBAAA,GAAmB;AAAA,EACvB,iBAAA,EAAmB,SAAA;AAAA,EACnB,gBAAA,EAAkB,SAAA;AAAA,EAClB,SAAA,EAAW,SAAA;AAAA,EACX,cAAA,EAAgB,SAAA;AAAA,EAChB,iBAAA,EAAmB,SAAA;AAAA,EACnB,cAAA,EAAgB,SAAA;AAAA,EAChB,YAAA,EAAc,SAAA;AAAA,EACd,QAAA,EAAU,SAAA;AAAA,EACV,aAAA,EAAe,SAAA;AAAA,EACf,eAAA,EAAiB,SAAA;AAAA,EACjB,gBAAA,EAAkB,SAAA;AAAA,EAClB,YAAA,EAAc,SAAA;AAAA,EACd,cAAA,EAAgB,SAAA;AAAA,EAChB,aAAA,EAAe,SAAA;AAAA,EACf,eAAA,EAAiB,SAAA;AAAA,EACjB,eAAA,EAAiB,SAAA;AAAA,EACjB,gBAAA,EAAkB,SAAA;AAAA,EAClB,qBAAA,EAAuB,SAAA;AAAA,EACvB,oBAAA,EAAsB;AACxB,CAAA;AAaO,IAAM,eAAA,GAAkB,IAAA,CAAK,KAAA,CAAM,iBAAA,CAAkB,WAAW,gBAAgB","file":"chunk-P4NA6BCH.js","sourcesContent":["/**\n * @h-ai/storage — 存储配置 Schema\n * @module storage-config\n */\n\nimport { z } from 'zod'\nimport { storageM } from './storage-i18n.js'\nimport { StoragePresignExpiresInSchema } from './storage-schemas.js'\n\n// ─── 配置 Schema ───\n\n/**\n * 存储类型枚举\n *\n * 支持的存储类型:\n * - `s3` - S3 协议对象存储(兼容 AWS S3、MinIO、RustFS、阿里云 OSS 等)\n * - `local` - 本地文件存储(仅后端)\n * @example\n * ```ts\n * import { StorageTypeSchema } from '@h-ai/storage'\n *\n * const value = StorageTypeSchema.parse('local')\n * void value\n * ```\n */\nexport const StorageTypeSchema = z.enum(['s3', 'local'])\n\n/**\n * 存储类型\n * @example\n * ```ts\n * import type { StorageType } from '@h-ai/storage'\n *\n * const value: StorageType = 's3'\n * void value\n * ```\n */\nexport type StorageType = z.infer<typeof StorageTypeSchema>\n\n/**\n * StorageOperationLogConfigSchema 的数据约束与操作契约。\n * @example\n * ```ts\n * import { StorageOperationLogConfigSchema } from '@h-ai/storage'\n *\n * const value = StorageOperationLogConfigSchema.parse({ read: false, write: true, maxLength: 500, level: 'debug' })\n * void value\n * ```\n */\nexport const StorageOperationLogConfigSchema = z.object({\n read: z.boolean().default(false),\n write: z.boolean().default(false),\n maxLength: z.number().int().min(0).default(1000),\n level: z.enum(['info', 'debug', 'trace']).default('debug'),\n})\n\n/**\n * StorageOperationLogConfig 的数据约束与操作契约。\n * @example\n * ```ts\n * import { StorageOperationLogConfigSchema, type StorageOperationLogConfig } from '@h-ai/storage'\n *\n * const value: StorageOperationLogConfig = StorageOperationLogConfigSchema.parse({ read: false, write: true, maxLength: 500, level: 'debug' })\n * void value\n * ```\n */\nexport type StorageOperationLogConfig = z.infer<typeof StorageOperationLogConfigSchema>\n\nconst OperationLogConfigFieldSchema = {\n operationLog: StorageOperationLogConfigSchema.optional(),\n}\n\n/**\n * S3 存储配置 Schema\n *\n * 支持标准 AWS S3 以及兼容 S3 协议的存储服务(MinIO、RustFS、阿里云 OSS 等)。\n * 必填字段:bucket、region、accessKeyId、secretAccessKey。\n * @example\n * ```ts\n * import { S3ConfigSchema } from '@h-ai/storage'\n *\n * const value = S3ConfigSchema.parse({ type: 's3', bucket: 'uploads', region: 'us-east-1', accessKeyId: process.env.HAI_STORAGE_ACCESS_KEY_ID, secretAccessKey: process.env.HAI_STORAGE_SECRET_ACCESS_KEY })\n * void value\n * ```\n */\nexport const S3ConfigSchema = z.object({\n /** 存储类型 */\n type: z.literal('s3'),\n\n /** 存储桶名称 */\n bucket: z.string().min(1, storageM('storage_config_bucketRequired')),\n\n /** 初始化时检查并创建缺失的桶;默认关闭,启用后凭据须有建桶权限。 */\n createBucket: z.boolean().default(false),\n\n /** 区域 */\n region: z.string().min(1, storageM('storage_config_regionRequired')),\n\n /** Access Key ID */\n accessKeyId: z.string().min(1, storageM('storage_config_accessKeyIdRequired')),\n\n /** Secret Access Key */\n secretAccessKey: z.string().min(1, storageM('storage_config_secretAccessKeyRequired')),\n\n /** 自定义端点(用于 MinIO、RustFS、阿里云 OSS 等) */\n endpoint: z.string().url().optional(),\n\n /** 浏览器预签名访问端点;仅 HTTP(S) 源地址,不含桶名、路径、凭据或查询。未配置时使用 endpoint。 */\n publicEndpoint: z.string().url().refine((value) => {\n try {\n const url = new URL(value)\n return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password\n && url.pathname === '/' && !url.search && !url.hash\n }\n catch {\n return false\n }\n }, storageM('storage_config_publicEndpointInvalid')).optional(),\n\n /** 强制使用路径风格 URL(某些 S3 兼容服务需要) */\n forcePathStyle: z.boolean().default(false),\n\n /** 路径前缀(所有操作都会加上此前缀) */\n prefix: z.string().default(''),\n\n /** 公开访问基础 URL(用于生成公开 URL) */\n publicUrl: z.string().url().optional(),\n\n ...OperationLogConfigFieldSchema,\n})\n\n/**\n * S3 配置类型(parse 后,带默认值的字段已填充,optional 字段仍可缺省)\n * @example\n * ```ts\n * import { S3ConfigSchema, type S3Config } from '@h-ai/storage'\n *\n * const value: S3Config = S3ConfigSchema.parse({ type: 's3', bucket: 'uploads', region: 'us-east-1', accessKeyId: process.env.HAI_STORAGE_ACCESS_KEY_ID, secretAccessKey: process.env.HAI_STORAGE_SECRET_ACCESS_KEY })\n * void value\n * ```\n */\nexport type S3Config = z.infer<typeof S3ConfigSchema>\n\n/**\n * 本地存储配置 Schema\n *\n * 基于本地文件系统,仅后端可用。必填字段:root。\n * @example\n * ```ts\n * import { LocalConfigSchema } from '@h-ai/storage'\n *\n * const value = LocalConfigSchema.parse({ type: 'local', root: './data/uploads' })\n * void value\n * ```\n */\nexport const LocalConfigSchema = z.object({\n /** 存储类型 */\n type: z.literal('local'),\n\n /** 根目录路径 */\n root: z.string().min(1, storageM('storage_config_rootRequired')),\n\n /** 目录创建权限 */\n directoryMode: z.number().default(0o755),\n\n /** 文件创建权限 */\n fileMode: z.number().default(0o644),\n\n ...OperationLogConfigFieldSchema,\n})\n\n/**\n * 本地配置类型(parse 后,带默认值的字段已填充,optional 字段仍可缺省)\n * @example\n * ```ts\n * import { LocalConfigSchema, type LocalConfig } from '@h-ai/storage'\n *\n * const value: LocalConfig = LocalConfigSchema.parse({ type: 'local', root: './data/uploads' })\n * void value\n * ```\n */\nexport type LocalConfig = z.infer<typeof LocalConfigSchema>\n\n/**\n * 统一存储配置 Schema\n *\n * 支持 S3 和本地文件两种类型的配置验证。\n * @example\n * ```ts\n * import { StorageConfigSchema } from '@h-ai/storage'\n *\n * const value = StorageConfigSchema.parse({ type: 'local', root: './data/uploads' })\n * void value\n * ```\n */\nexport const StorageConfigSchema = z.discriminatedUnion('type', [\n S3ConfigSchema,\n LocalConfigSchema,\n])\n\n/**\n * 存储配置类型(parse 后的完整配置)\n * @example\n * ```ts\n * import { StorageConfigSchema, type StorageConfig } from '@h-ai/storage'\n *\n * const value: StorageConfig = StorageConfigSchema.parse({ type: 'local', root: './data/uploads' })\n * void value\n * ```\n */\nexport type StorageConfig = z.infer<typeof StorageConfigSchema>\n\n/**\n * 存储配置输入类型(parse 前,允许省略带默认值的字段)\n * @example\n * ```ts\n * import type { StorageConfigInput } from '@h-ai/storage'\n *\n * const value: StorageConfigInput = { type: 'local', root: './data/uploads' }\n * void value\n * ```\n */\nexport type StorageConfigInput = z.input<typeof StorageConfigSchema>\n\n// ─── 签名 URL 配置 ───\n\n/**\n * 签名 URL 配置 Schema\n *\n * 用于控制 `storage.presign.getUrl()` 生成的下载签名 URL 参数。\n * @example\n * ```ts\n * import { PresignOptionsSchema } from '@h-ai/storage'\n *\n * const value = PresignOptionsSchema.parse({ expiresIn: 60 })\n * void value\n * ```\n */\nexport const PresignOptionsSchema = z.object({\n /** 过期时间(秒),范围 1~604800(7 天),默认 3600(1 小时) */\n expiresIn: StoragePresignExpiresInSchema.default(3600), // 最长 7 天\n\n /** 响应内容类型(用于下载时设置 Content-Type) */\n responseContentType: z.string().optional(),\n\n /** 响应内容处置(用于设置下载文件名) */\n responseContentDisposition: z.string().optional(),\n})\n\n/**\n * 签名 URL 输入选项,允许省略带默认值的字段。\n * @example\n * ```ts\n * import type { PresignOptions } from '@h-ai/storage'\n *\n * const value: PresignOptions = { expiresIn: 60, responseContentType: 'text/plain' }\n * void value\n * ```\n */\nexport type PresignOptions = z.input<typeof PresignOptionsSchema>\n\n/**\n * 上传签名 URL 配置 Schema\n *\n * 继承 PresignOptionsSchema 并扩展上传专属参数,用于 `storage.presign.putUrl()`。\n * @example\n * ```ts\n * import { PresignUploadOptionsSchema } from '@h-ai/storage'\n *\n * const value = PresignUploadOptionsSchema.parse({ contentType: 'text/plain' })\n * void value\n * ```\n */\nexport const PresignUploadOptionsSchema = PresignOptionsSchema.extend({\n /** 上传内容类型(必须与实际上传匹配) */\n contentType: z.string().default('application/octet-stream'),\n})\n\n/**\n * 上传签名 URL 输入选项,省略 contentType 时使用 application/octet-stream。\n * @example\n * ```ts\n * import type { PresignUploadOptions } from '@h-ai/storage'\n *\n * const value: PresignUploadOptions = { expiresIn: 60, contentType: 'text/plain' }\n * void value\n * ```\n */\nexport type PresignUploadOptions = z.input<typeof PresignUploadOptionsSchema>\n","/**\n * @h-ai/storage — 公共类型定义\n *\n * 包含:\n * - 错误定义(HaiStorageError)\n * - 文件元数据(FileMetadata)\n * - 列表结果(ListResult)\n * - 文件操作接口(FileOperations)\n * - 目录操作接口(DirOperations)\n * - 签名 URL 操作接口(PresignOperations)\n * - 函数接口(StorageFunctions)\n * @module storage-types\n */\n\nimport type { ErrorInfo, HaiError, HaiResult } from '@h-ai/core'\nimport type { Buffer } from 'node:buffer'\nimport type { PresignOptions, PresignUploadOptions, StorageConfig, StorageConfigInput } from './storage-config.js'\nimport { core } from '@h-ai/core'\n\n// ─── 错误定义(照 @h-ai/core 范式) ───\n\nconst StorageErrorInfo = {\n CONNECTION_FAILED: '001:500',\n OPERATION_FAILED: '002:500',\n NOT_FOUND: '003:404',\n ALREADY_EXISTS: '004:409',\n PERMISSION_DENIED: '005:403',\n QUOTA_EXCEEDED: '006:413',\n INVALID_PATH: '007:400',\n IO_ERROR: '008:500',\n NETWORK_ERROR: '009:502',\n NOT_INITIALIZED: '010:500',\n UNSUPPORTED_TYPE: '011:400',\n CONFIG_ERROR: '012:500',\n PRESIGN_FAILED: '013:500',\n UPLOAD_FAILED: '014:500',\n DOWNLOAD_FAILED: '015:500',\n CHECKSUM_FAILED: '016:500',\n INVALID_CHECKSUM: '017:400',\n UNSUPPORTED_OPERATION: '018:400',\n INVALID_LIST_OPTIONS: '019:400',\n} as const satisfies ErrorInfo\n\n/**\n * HaiStorageError 的数据约束与操作契约。\n * @example\n * ```ts\n * import { HaiStorageError } from '@h-ai/storage'\n * import { err } from '@h-ai/core'\n *\n * const result = err(HaiStorageError.NOT_FOUND, 'File missing')\n * if (!result.success) void result.error.code\n * ```\n */\nexport const HaiStorageError = core.error.buildHaiErrorsDef('storage', StorageErrorInfo)\n\n/**\n * 批量删除中未确认完成的一项;key 始终使用调用方视角,不含 Provider prefix。\n * @example\n * ```ts\n * import type { StorageDeleteFailure } from '@h-ai/storage'\n *\n * const value: StorageDeleteFailure = { key: 'private.txt', code: 'AccessDenied', retryable: false, outcome: 'failed' }\n * void value\n * ```\n */\nexport interface StorageDeleteFailure {\n /** 调用方提交的文件键。 */\n key: string\n /** 渠道/框架错误标识,不包含渠道原始 Message。 */\n code: string\n /** 是否属于可重试的瞬时故障;未知结果重试前仍需考虑并发上传/版本语义。 */\n retryable: boolean\n /** failed 为已知失败,unknown 为已发送但结果未知,notAttempted 为尚未发送。 */\n outcome: 'failed' | 'unknown' | 'notAttempted'\n}\n\n/**\n * 批量删除进度;任一失败不能宣称全部删除完成。\n * @example\n * ```ts\n * import type { StorageDeleteSummary } from '@h-ai/storage'\n *\n * const value: StorageDeleteSummary = { deletedKeys: ['a.txt'], failures: [] }\n * void value\n * ```\n */\nexport interface StorageDeleteSummary {\n /** 已确认删除或本来就不存在的唯一文件键。 */\n deletedKeys: string[]\n /** 失败、未知及尚未尝试的唯一文件键。 */\n failures: StorageDeleteFailure[]\n}\n\n/**\n * 批量删除结果;失败仍遵守 HaiResult,部分进度置于 error.ext.deleteMany。\n * @example\n * ```ts\n * import { storage, type StorageDeleteResult } from '@h-ai/storage'\n *\n * async function remove() {\n * const result: StorageDeleteResult = await storage.file.deleteMany(['a.txt', 'b.txt'])\n * return result.success ? result.data : result.error.ext?.deleteMany\n * }\n * ```\n */\nexport type StorageDeleteResult\n = | { success: true, data: StorageDeleteSummary }\n | { success: false, error: HaiError & { ext?: Record<string, unknown> & { deleteMany?: StorageDeleteSummary } } }\n\n// ─── 文件元数据 ───\n\n/**\n * 文件元数据接口\n *\n * 表示存储中单个文件的元信息,由 put/head/copy/list 等操作返回。\n * @example\n * ```ts\n * import type { FileMetadata } from '@h-ai/storage'\n *\n * const value: FileMetadata = { key: 'a.txt', size: 5, contentType: 'text/plain', lastModified: new Date() }\n * void value\n * ```\n */\nexport interface FileMetadata {\n /** 文件键/路径(不含配置 prefix,对用户透明) */\n key: string\n /** 文件大小(字节) */\n size: number\n /** 内容类型(MIME),未指定时根据扩展名自动推断 */\n contentType: string\n /** 最后修改时间 */\n lastModified: Date\n /** ETag(缓存验证标记;本地为 size-mtime,S3 由服务端生成,不等同于内容 checksum) */\n etag?: string\n /** 自定义元数据键值对 */\n metadata?: Record<string, string>\n}\n\n/**\n * 列表选项\n *\n * 用于控制 `storage.dir.list()` 的过滤、分页和目录模拟行为。\n * @example\n * ```ts\n * import type { ListOptions } from '@h-ai/storage'\n *\n * const value: ListOptions = { prefix: 'reports/', delimiter: '/', maxKeys: 100 }\n * void value\n * ```\n */\nexport interface ListOptions {\n /** 前缀过滤(只返回以此前缀开头的文件) */\n prefix?: string\n /**\n * 分页标记(从上次 ListResult.nextContinuationToken 获取)\n *\n * Local 游标绑定根目录、prefix 和 delimiter,可跨实例使用;不得跨查询或 provider 混用。\n */\n continuationToken?: string\n /** 每页逻辑条目上限(1–1000,默认 1000);files 和 commonPrefixes 合计计数。 */\n maxKeys?: number\n /** 分隔符,通常为 '/';从 prefix 之后首次出现的位置折叠 commonPrefixes,空字符串表示不折叠。 */\n delimiter?: string\n}\n\n/**\n * 列表结果\n *\n * 包含当前页的文件列表、目录前缀、分页信息。\n * @example\n * ```ts\n * import type { ListResult } from '@h-ai/storage'\n *\n * const value: ListResult = { files: [], commonPrefixes: ['reports/'], isTruncated: false }\n * void value\n * ```\n */\nexport interface ListResult {\n /** 当前页文件元数据列表 */\n files: FileMetadata[]\n /** 公共前缀:由实际匹配文件按 delimiter 折叠,不包含 Local 空物理目录。 */\n commonPrefixes: string[]\n /** 下一页标记;无后续页时为 undefined */\n nextContinuationToken?: string\n /** 是否被截断(true 表示还有更多数据,可用 nextContinuationToken 继续拉取) */\n isTruncated: boolean\n}\n\n// ─── 上传下载选项 ───\n\n/**\n * 上传选项\n *\n * 用于控制 `storage.file.put()` 的元数据与缓存行为。\n * @example\n * ```ts\n * import type { UploadOptions } from '@h-ai/storage'\n *\n * const value: UploadOptions = { ifNoneMatch: '*', contentType: 'text/plain', signal: new AbortController().signal }\n * void value\n * ```\n */\nexport interface UploadOptions {\n /** 仅当 key 不存在时原子写入;S3 使用标准 If-None-Match,后端不支持时返回错误。 */\n ifNoneMatch?: '*'\n /** 取消上传;失败或取消时清理未完成的临时文件/分片。 */\n signal?: AbortSignal\n /** 内容类型(不指定时根据文件扩展名自动推断) */\n contentType?: string\n /** 自定义元数据键值对(存储后可通过 head 获取) */\n metadata?: Record<string, string>\n /** Cache-Control 响应头(例如 'max-age=3600') */\n cacheControl?: string\n /** Content-Disposition 响应头(例如 'attachment; filename=\"a.txt\"') */\n contentDisposition?: string\n}\n\n/**\n * 下载选项\n *\n * 用于控制 `storage.file.get()` 的范围读取。\n * 两个字段均为字节偏移(含),与 HTTP Range 语义一致。\n * @example\n * ```ts\n * import type { DownloadOptions } from '@h-ai/storage'\n *\n * const value: DownloadOptions = { rangeStart: 0, rangeEnd: 99 }\n * void value\n * ```\n */\nexport interface DownloadOptions {\n /** 取消读取。 */\n signal?: AbortSignal\n /** 范围起始位置(字节,含);不指定时从文件开头读取 */\n rangeStart?: number\n /** 范围结束位置(字节,含);不指定时读取到文件末尾 */\n rangeEnd?: number\n}\n\n/**\n * 复制选项\n *\n * 用于控制 `storage.file.copy()` 的目标文件元数据。\n * 提供任意字段时,S3 Provider 会使用 MetadataDirective='REPLACE' 覆盖源文件元数据。\n * @example\n * ```ts\n * import type { CopyOptions } from '@h-ai/storage'\n *\n * const value: CopyOptions = { contentType: 'text/plain', metadata: { category: 'reports' } }\n * void value\n * ```\n */\nexport interface CopyOptions {\n /** 目标文件的内容类型(不指定时继承源文件) */\n contentType?: string\n /** 目标文件的自定义元数据(不指定时继承源文件) */\n metadata?: Record<string, string>\n}\n\n// ─── 操作接口 ───\n\n/**\n * 文件内容;异步字节流支持 Node Readable 等,不将整个文件载入内存。\n * @example\n * ```ts\n * import type { StorageData } from '@h-ai/storage'\n *\n * const value: StorageData = new TextEncoder().encode('hello')\n * void value\n * ```\n */\nexport type StorageData = Buffer | Uint8Array | string | AsyncIterable<Uint8Array>\n\n/**\n * 常见 checksum 算法;MD5/SHA-1 仅用于兼容性完整性校验,不用于安全认证。\n * @example\n * ```ts\n * import type { ChecksumAlgorithm } from '@h-ai/storage'\n *\n * const value: ChecksumAlgorithm = 'sha256'\n * void value\n * ```\n */\nexport type ChecksumAlgorithm = 'sha256' | 'sha384' | 'sha512' | 'sha1' | 'md5'\n\n/**\n * checksum 计算选项;默认 SHA-256、小写 hex。\n * @example\n * ```ts\n * import type { ChecksumOptions } from '@h-ai/storage'\n *\n * const value: ChecksumOptions = { algorithm: 'sha256', encoding: 'hex' }\n * void value\n * ```\n */\nexport interface ChecksumOptions {\n algorithm?: ChecksumAlgorithm\n encoding?: 'hex' | 'base64'\n signal?: AbortSignal\n}\n\n/**\n * Node 端无状态 checksum 工具,不依赖 storage.init;流输入仅消费一次。\n * @example\n * ```ts\n * import type { ChecksumOperations } from '@h-ai/storage'\n *\n * async function inspect(operations: ChecksumOperations) {\n * const result = await operations.generate('hello')\n * if (!result.success) return result.error.message\n * return result.data\n * }\n * ```\n */\nexport interface ChecksumOperations {\n generate: (data: StorageData, options?: ChecksumOptions) => Promise<HaiResult<string>>\n verify: (data: StorageData, expected: string, options?: ChecksumOptions) => Promise<HaiResult<boolean>>\n}\n\n/**\n * 文件操作接口\n *\n * 提供文件的读写操作。\n * @example\n * ```ts\n * import type { FileOperations } from '@h-ai/storage'\n *\n * async function inspect(operations: FileOperations) {\n * const result = await operations.getStream('reports/a.txt')\n * if (!result.success) return result.error.message\n * for await (const chunk of result.data) void chunk.byteLength\n * }\n * ```\n */\nexport interface FileOperations {\n /**\n * 上传文件\n *\n * @param key - 文件键/路径\n * @param data - 文件内容(Buffer、Uint8Array、字符串或异步字节流)\n * @param options - 上传选项\n * @returns 上传结果包含文件元数据\n * @example\n * ```ts\n * const result = await storage.file.put('uploads/a.txt', 'hello')\n * if (result.success) {\n * result.data.key\n * }\n * ```\n */\n put: (key: string, data: StorageData, options?: UploadOptions) => Promise<HaiResult<FileMetadata>>\n\n /**\n * 下载文件\n *\n * @param key - 文件键/路径\n * @param options - 下载选项\n * @returns 文件内容\n * @example\n * ```ts\n * const result = await storage.file.get('uploads/a.txt')\n * if (result.success) {\n * const buffer = result.data\n * void buffer\n * }\n * ```\n */\n get: (key: string, options?: DownloadOptions) => Promise<HaiResult<Buffer>>\n\n /**\n * 读取字节流,支持 Range 与取消;消费方负责及时迭代或关闭流。\n * @throws 迭代期间的 I/O/取消错误;初始请求失败通过 HaiResult 返回。\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const result = await storage.file.getStream('reports/a.txt')\n * if (!result.success) throw new Error(result.error.message)\n * try {\n * for await (const chunk of result.data) void chunk.byteLength\n * } catch (error) {\n * // 初始请求成功后,迭代仍可能因 I/O/取消失败。\n * throw error\n * }\n * ```\n */\n getStream: (key: string, options?: DownloadOptions) => Promise<HaiResult<AsyncIterable<Uint8Array>>>\n\n /**\n * 获取文件元数据\n *\n * @param key - 文件键/路径\n * @returns 文件元数据\n * @example\n * ```ts\n * const result = await storage.file.head('uploads/a.txt')\n * if (result.success) {\n * result.data.size\n * }\n * ```\n */\n head: (key: string) => Promise<HaiResult<FileMetadata>>\n\n /**\n * 检查文件是否存在\n *\n * @param key - 文件键/路径\n * @returns 是否存在\n * @example\n * ```ts\n * const result = await storage.file.exists('uploads/a.txt')\n * if (result.success) {\n * result.data\n * }\n * ```\n */\n exists: (key: string) => Promise<HaiResult<boolean>>\n\n /**\n * 删除文件\n *\n * @param key - 文件键/路径\n * @returns 删除结果\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const result = await storage.file.delete('uploads/a.txt')\n * if (!result.success) throw new Error(result.error.message)\n * ```\n */\n delete: (key: string) => Promise<HaiResult<void>>\n\n /**\n * 批量删除文件\n *\n * @param keys - 文件键/路径列表\n * @returns 全部成功时返回进度;任一失败时 success=false,进度在 error.ext.deleteMany\n * @example\n * ```ts\n * const result = await storage.file.deleteMany(['a.txt', 'b.txt'])\n * const progress = result.success ? result.data : result.error.ext?.deleteMany\n * void progress\n * ```\n */\n deleteMany: (keys: string[]) => Promise<StorageDeleteResult>\n\n /**\n * 复制文件\n *\n * @param sourceKey - 源文件键\n * @param destKey - 目标文件键\n * @param options - 复制选项\n * @returns 目标文件元数据\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const result = await storage.file.copy('a.txt', 'b.txt')\n * if (!result.success) throw new Error(result.error.message)\n * void result.data.key\n * ```\n */\n copy: (sourceKey: string, destKey: string, options?: CopyOptions) => Promise<HaiResult<FileMetadata>>\n}\n\n/**\n * 目录操作接口\n *\n * 提供目录(前缀)的列表操作。\n * @example\n * ```ts\n * import type { DirOperations } from '@h-ai/storage'\n *\n * async function inspect(operations: DirOperations) {\n * const page = await operations.list({ prefix: 'reports/', maxKeys: 100 })\n * if (!page.success) return page.error.message\n * return page.data.files\n * }\n * ```\n */\nexport interface DirOperations {\n /**\n * 列出目录内容\n *\n * @param options - 列表选项\n * @returns 文件和目录列表\n * @example\n * ```ts\n * const result = await storage.dir.list({ prefix: 'uploads/' })\n * if (result.success) {\n * result.data.files\n * }\n * ```\n */\n list: (options?: ListOptions) => Promise<HaiResult<ListResult>>\n\n /**\n * 删除目录(删除指定前缀下的所有文件)\n *\n * @param prefix - 目录前缀\n * @returns 删除结果\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const result = await storage.dir.delete('uploads/tmp/')\n * if (!result.success) throw new Error(result.error.message)\n * ```\n */\n delete: (prefix: string) => Promise<HaiResult<void>>\n}\n\n/**\n * 签名 URL 操作接口\n *\n * S3 provider 提供临时授权 URL,支持前端直接上传下载。\n * local 的 getUrl/putUrl 返回 UNSUPPORTED_OPERATION,publicUrl 返回 null。\n * @example\n * ```ts\n * import type { PresignOperations } from '@h-ai/storage'\n *\n * async function inspect(operations: PresignOperations) {\n * const signed = await operations.putUrl('reports/a.txt', { contentType: 'text/plain', expiresIn: 300 })\n * if (!signed.success) return signed.error.message\n * return signed.data\n * }\n * ```\n */\nexport interface PresignOperations {\n /**\n * 生成 GET 下载签名 URL;使用 publicEndpoint,缺省回退 endpoint/AWS 端点,签名后不能改写地址。\n *\n * @param key - 文件键/路径\n * @param options - 签名选项\n * @returns 成功时为可访问的 S3 签名 URL;local 返回 UNSUPPORTED_OPERATION。\n * @example\n * ```ts\n * const result = await storage.presign.getUrl('a.txt', { expiresIn: 60 })\n * if (!result.success) throw new Error(result.error.message)\n * const downloadUrl = result.data\n * void downloadUrl\n * ```\n */\n getUrl: (key: string, options?: PresignOptions) => Promise<HaiResult<string>>\n\n /**\n * 生成 PUT 上传签名 URL;使用 publicEndpoint,服务端 CRUD 仍使用内部 endpoint。\n *\n * @param key - 文件键/路径\n * @param options - 上传签名选项\n * @returns 成功时为可访问的 S3 签名 URL;local 返回 UNSUPPORTED_OPERATION。\n * @example\n * ```ts\n * const result = await storage.presign.putUrl('a.txt', { contentType: 'text/plain' })\n * if (!result.success) throw new Error(result.error.message)\n * const uploadUrl = result.data\n * void uploadUrl\n * ```\n */\n putUrl: (key: string, options?: PresignUploadOptions) => Promise<HaiResult<string>>\n\n /**\n * 获取公开访问 URL(如果配置了 publicUrl)\n *\n * @param key - 文件键/路径\n * @returns 公开 URL;S3 未配置 publicUrl 或 local provider 均返回 null。\n * @example\n * ```ts\n * const url = storage.presign.publicUrl('a.txt')\n * void url\n * ```\n */\n publicUrl: (key: string) => string | null\n}\n\n// ─── 函数接口 ───\n\n/**\n * 存储函数接口\n *\n * 统一的存储访问入口:\n * - `storage.init()` — 初始化存储连接\n * - `storage.close()` — 关闭连接并释放资源\n * - `storage.file` — 文件操作(上传/下载/删除/复制等)\n * - `storage.dir` — 目录操作(列表/删除)\n * - `storage.presign` — 签名 URL 操作\n * - `storage.config` — 当前脱敏配置快照(未初始化时为 null)\n * - `storage.isInitialized` — 初始化状态\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const initialized = await storage.init({ type: 'local', root: './data/uploads' })\n * if (!initialized.success) throw new Error(initialized.error.message)\n * try {\n * const uploaded = await storage.file.put('reports/a.txt', 'hello', { ifNoneMatch: '*' })\n * if (!uploaded.success) throw new Error(uploaded.error.message)\n * const downloaded = await storage.file.get('reports/a.txt')\n * if (!downloaded.success) throw new Error(downloaded.error.message)\n * void downloaded.data\n * } finally {\n * const closed = await storage.close()\n * if (!closed.success) throw new Error(closed.error.message)\n * }\n * ```\n */\nexport interface StorageFunctions {\n /** 无状态 checksum 生成与校验,Node 专用,无需初始化。 */\n readonly checksum: ChecksumOperations\n /**\n * 初始化存储连接\n *\n * 已有连接时会先 close 再重新初始化。\n *\n * @param config - 存储配置(支持省略带默认值的字段)\n * @returns 成功 ok(undefined);失败返回 err(含 HaiStorageError 定义的错误信息)\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const initialized = await storage.init({ type: 'local', root: './data/uploads' })\n * if (!initialized.success) throw new Error(initialized.error.message)\n * const closed = await storage.close()\n * if (!closed.success) throw new Error(closed.error.message)\n * ```\n */\n init: (config: StorageConfigInput) => Promise<HaiResult<void>>\n\n /**\n * 关闭存储连接并释放资源\n *\n * 等待初始化并合并并发关闭;失败时操作不可用,资源保留供 close/init 重试。\n * @returns 所有资源释放成功才返回成功;未初始化时同样成功。\n * @example\n * ```ts\n * import { storage } from '@h-ai/storage'\n *\n * const closed = await storage.close()\n * if (!closed.success) throw new Error(closed.error.message)\n * ```\n */\n close: () => Promise<HaiResult<void>>\n\n /** 当前脱敏后的存储配置快照;未初始化或已关闭时为 null */\n readonly config: StorageConfig | null\n\n /** 是否已完成初始化 */\n readonly isInitialized: boolean\n\n /** 文件操作接口(put / get / head / exists / delete / deleteMany / copy) */\n readonly file: FileOperations\n\n /** 目录操作接口(list / delete) */\n readonly dir: DirOperations\n\n /** 签名 URL 操作接口(getUrl / putUrl / publicUrl) */\n readonly presign: PresignOperations\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
// src/storage-schemas.ts
|
|
4
|
+
var STORAGE_KEY_MAX_BYTES = 1024;
|
|
5
|
+
var STORAGE_DELETE_MAX_KEYS = 1e3;
|
|
6
|
+
function getStorageKeyIssue(key, allowEmpty = false) {
|
|
7
|
+
if (allowEmpty && key === "")
|
|
8
|
+
return void 0;
|
|
9
|
+
if (key.trim() === "")
|
|
10
|
+
return "empty";
|
|
11
|
+
if (new TextEncoder().encode(key).byteLength > STORAGE_KEY_MAX_BYTES)
|
|
12
|
+
return "tooLong";
|
|
13
|
+
if (key.startsWith("/") || key.includes("\\") || [...key].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
|
|
14
|
+
return "characters";
|
|
15
|
+
if (key.split("/").some((segment) => segment === "." || segment === ".."))
|
|
16
|
+
return "segments";
|
|
17
|
+
return void 0;
|
|
18
|
+
}
|
|
19
|
+
function keySchema(allowEmpty) {
|
|
20
|
+
return z.string().superRefine((key, context) => {
|
|
21
|
+
const issue = getStorageKeyIssue(key, allowEmpty);
|
|
22
|
+
if (issue)
|
|
23
|
+
context.addIssue({ code: "custom", params: { storageKeyIssue: issue } });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
var StorageKeySchema = keySchema(false);
|
|
27
|
+
var StoragePrefixSchema = keySchema(true);
|
|
28
|
+
var StorageDeleteKeysSchema = z.array(StorageKeySchema).min(1).max(STORAGE_DELETE_MAX_KEYS);
|
|
29
|
+
var StoragePresignExpiresInSchema = z.number().int().min(1).max(604800);
|
|
30
|
+
|
|
31
|
+
export { STORAGE_DELETE_MAX_KEYS, STORAGE_KEY_MAX_BYTES, StorageDeleteKeysSchema, StorageKeySchema, StoragePrefixSchema, StoragePresignExpiresInSchema, getStorageKeyIssue };
|
|
32
|
+
//# sourceMappingURL=chunk-P65WYXJG.js.map
|
|
33
|
+
//# sourceMappingURL=chunk-P65WYXJG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage-schemas.ts"],"names":[],"mappings":";;;AAgBO,IAAM,qBAAA,GAAwB;AAa9B,IAAM,uBAAA,GAA0B;AA6BhC,SAAS,kBAAA,CAAmB,GAAA,EAAa,UAAA,GAAa,KAAA,EAAoC;AAC/F,EAAA,IAAI,cAAc,GAAA,KAAQ,EAAA;AACxB,IAAA,OAAO,MAAA;AACT,EAAA,IAAI,GAAA,CAAI,MAAK,KAAM,EAAA;AACjB,IAAA,OAAO,OAAA;AACT,EAAA,IAAI,IAAI,WAAA,EAAY,CAAE,MA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依赖 Zod,不加载 Provider、配置或 Node 模块。\n * @module storage-schemas\n */\nimport { z } from 'zod'\n\n/**\n * 对象键的 UTF-8 字节上限;不是 JavaScript 字符串长度。\n * @example\n * ```ts\n * import { STORAGE_KEY_MAX_BYTES } from '@h-ai/storage/schemas'\n *\n * const fits = new TextEncoder().encode('uploads/报告.pdf').length <= STORAGE_KEY_MAX_BYTES\n * void fits\n * ```\n */\nexport const STORAGE_KEY_MAX_BYTES = 1024\n\n/**\n * 单次公开 HTTP 删除请求的原始键数量上限;Node deleteMany 仍按 Provider 上限分批。\n * @example\n * ```ts\n * import { STORAGE_DELETE_MAX_KEYS } from '@h-ai/storage/schemas'\n *\n * const keys = ['a.txt', 'b.txt']\n * const page = keys.slice(0, STORAGE_DELETE_MAX_KEYS)\n * void page\n * ```\n */\nexport const STORAGE_DELETE_MAX_KEYS = 1000\n\n/**\n * 键校验失败类别;调用层据此生成本地化消息,不解析错误文本。\n * @example\n * ```ts\n * import type { StorageKeyIssue } from '@h-ai/storage'\n *\n * const value: StorageKeyIssue = 'tooLong'\n * void value\n * ```\n */\nexport type StorageKeyIssue = 'empty' | 'tooLong' | 'characters' | 'segments'\n\n/**\n * 检查跨端键边界,不归一化输入,不替代文件系统防逃逸或资源授权。\n *\n * @param key - 调用方视角的对象键,不含 Provider 配置前缀。\n * @param allowEmpty - 是否允许空字符串(用于列表前缀);纯空白仍无效。\n * @returns 首个失败类别;合法时为 undefined。\n * @example\n * ```ts\n * import { getStorageKeyIssue } from '@h-ai/storage/schemas'\n *\n * const unsafe = getStorageKeyIssue('../private.txt') // segments\n * const emptyPrefix = getStorageKeyIssue('', true) // undefined\n * void [unsafe, emptyPrefix]\n * ```\n */\nexport function getStorageKeyIssue(key: string, allowEmpty = false): StorageKeyIssue | undefined {\n if (allowEmpty && key === '')\n return undefined\n if (key.trim() === '')\n return 'empty'\n if (new TextEncoder().encode(key).byteLength > STORAGE_KEY_MAX_BYTES)\n return 'tooLong'\n if (key.startsWith('/') || key.includes('\\\\') || [...key].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))\n return 'characters'\n if (key.split('/').some(segment => segment === '.' || segment === '..'))\n return 'segments'\n return undefined\n}\n\n/** 通过稳定 params 保留失败类别;默认 Zod 消息交由请求层按 locale 映射。 */\nfunction keySchema(allowEmpty: boolean) {\n return z.string().superRefine((key, context) => {\n const issue = getStorageKeyIssue(key, allowEmpty)\n if (issue)\n context.addIssue({ code: 'custom', params: { storageKeyIssue: issue } })\n })\n}\n\n/**\n * 文件键 Schema:非空、UTF-8 最多 1024 字节,无绝对路径、反斜线、控制符或点路径段。\n * @example\n * ```ts\n * import { StorageKeySchema } from '@h-ai/storage'\n *\n * const value = StorageKeySchema.parse('users/u1/report.pdf')\n * void value\n * ```\n */\nexport const StorageKeySchema = keySchema(false)\n\n/**\n * 列表前缀 Schema;允许空字符串与部分文件名,不把前缀当物理目录。\n * @example\n * ```ts\n * import { StoragePrefixSchema } from '@h-ai/storage'\n *\n * const value = StoragePrefixSchema.parse('users/u1/rep')\n * void value\n * ```\n */\nexport const StoragePrefixSchema = keySchema(true)\n\n/**\n * HTTP 批量删除键 Schema;按输入数量计数,重复键不能绕过上限。\n * @example\n * ```ts\n * import { StorageDeleteKeysSchema } from '@h-ai/storage'\n *\n * const value = StorageDeleteKeysSchema.parse(['users/u1/a.txt', 'users/u1/b.txt'])\n * void value\n * ```\n */\nexport const StorageDeleteKeysSchema = z.array(StorageKeySchema).min(1).max(STORAGE_DELETE_MAX_KEYS)\n\n/**\n * 预签名有效期,单位秒;整数 1–604800,不在此处填充 Node/HTTP 各自默认值。\n * @example\n * ```ts\n * import { StoragePresignExpiresInSchema } from '@h-ai/storage'\n *\n * const value = StoragePresignExpiresInSchema.parse(900)\n * void value\n * ```\n */\nexport const StoragePresignExpiresInSchema = z.number().int().min(1).max(604800)\n"]}
|
package/dist/client/index.d.ts
CHANGED
|
@@ -8,6 +8,13 @@
|
|
|
8
8
|
* 上传进度回调数据
|
|
9
9
|
*
|
|
10
10
|
* 由 `uploadWithPresignedUrl` 在上传过程中通过 `onProgress` 回调返回。
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import type { UploadProgress } from '@h-ai/storage'
|
|
14
|
+
*
|
|
15
|
+
* const value: UploadProgress = { loaded: 50, total: 100, percent: 50 }
|
|
16
|
+
* void value
|
|
17
|
+
* ```
|
|
11
18
|
*/
|
|
12
19
|
interface UploadProgress {
|
|
13
20
|
/** 已上传字节数 */
|
|
@@ -21,19 +28,33 @@ interface UploadProgress {
|
|
|
21
28
|
* 前端上传选项
|
|
22
29
|
*
|
|
23
30
|
* 控制 `uploadWithPresignedUrl` 的行为,包括内容类型、进度监听和取消。
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import type { ClientUploadOptions } from '@h-ai/storage'
|
|
34
|
+
*
|
|
35
|
+
* const value: ClientUploadOptions = { contentType: 'text/plain', onProgress: progress => { document.title = `${progress.percent}%` } }
|
|
36
|
+
* void value
|
|
37
|
+
* ```
|
|
24
38
|
*/
|
|
25
39
|
interface ClientUploadOptions {
|
|
26
40
|
/** 内容类型(设置后会加到请求 Content-Type 头) */
|
|
27
41
|
contentType?: string;
|
|
28
42
|
/** 进度回调(设置后会使用 XMLHttpRequest;仅 lengthComputable=true 时回调) */
|
|
29
43
|
onProgress?: (progress: UploadProgress) => void;
|
|
30
|
-
/**
|
|
44
|
+
/** 取消上传;预取消不发送请求,进行中取消返回失败,完成后移除本次监听。取消不能撤销远端已写入对象。 */
|
|
31
45
|
abortController?: AbortController;
|
|
32
46
|
}
|
|
33
47
|
/**
|
|
34
48
|
* 前端下载选项
|
|
35
49
|
*
|
|
36
50
|
* 控制 `downloadWithPresignedUrl` / `downloadAndSave` 的行为。
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* import type { ClientDownloadOptions } from '@h-ai/storage'
|
|
54
|
+
*
|
|
55
|
+
* const value: ClientDownloadOptions = { filename: 'report.pdf', abortController: new AbortController() }
|
|
56
|
+
* void value
|
|
57
|
+
* ```
|
|
37
58
|
*/
|
|
38
59
|
interface ClientDownloadOptions {
|
|
39
60
|
/** 保存的文件名(仅 downloadAndSave 使用,默认为 'download') */
|
|
@@ -44,31 +65,19 @@ interface ClientDownloadOptions {
|
|
|
44
65
|
/**
|
|
45
66
|
* 使用签名 URL 上传文件
|
|
46
67
|
*
|
|
47
|
-
* @param url -
|
|
68
|
+
* @param url - 已成功获取的 S3 HTTP(S) 上传签名 URL;本地存储须使用应用的鉴权文件接口。
|
|
48
69
|
* @param data - 要上传的数据(File、Blob、ArrayBuffer 或字符串)
|
|
49
70
|
* @param options - 上传选项
|
|
50
|
-
* @returns
|
|
51
|
-
*
|
|
71
|
+
* @returns 上传结果;预取消不发送,进行中取消/网络失败/初始化异常结算为失败,终态移除本次监听。
|
|
72
|
+
* 取消不代表远端对象已回滚;上传完成后的撤销由应用另行授权删除。
|
|
52
73
|
* @example
|
|
53
74
|
* ```ts
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* })
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* // 使用签名 URL 上传
|
|
62
|
-
* const file = document.getElementById('fileInput').files[0]
|
|
63
|
-
* const result = await uploadWithPresignedUrl(uploadUrl, file, {
|
|
64
|
-
* contentType: 'image/png',
|
|
65
|
-
* onProgress: (p) => {
|
|
66
|
-
* // 在此更新进度条:p.percent
|
|
67
|
-
* }
|
|
68
|
-
* })
|
|
69
|
-
*
|
|
70
|
-
* if (result.success) {
|
|
71
|
-
* // 上传成功
|
|
75
|
+
* import { uploadWithPresignedUrl } from '@h-ai/storage/client'
|
|
76
|
+
*
|
|
77
|
+
* // url 由应用鉴权接口返回,且 S3 签名包含相同 Content-Type。
|
|
78
|
+
* async function upload(url: string, file: File) {
|
|
79
|
+
* const result = await uploadWithPresignedUrl(url, file, { contentType: file.type })
|
|
80
|
+
* if (!result.success) throw new Error(result.error)
|
|
72
81
|
* }
|
|
73
82
|
* ```
|
|
74
83
|
*/
|
|
@@ -82,18 +91,15 @@ declare function uploadWithPresignedUrl(url: string, data: File | Blob | ArrayBu
|
|
|
82
91
|
* @param url - 后端生成的下载签名 URL
|
|
83
92
|
* @param options - 下载选项
|
|
84
93
|
* @returns 下载结果(成功时 data 为 Blob)
|
|
85
|
-
*
|
|
86
94
|
* @example
|
|
87
95
|
* ```ts
|
|
88
|
-
*
|
|
89
|
-
* const result = await downloadWithPresignedUrl(downloadUrl)
|
|
90
|
-
* if (result.success) {
|
|
91
|
-
* const blob = result.data
|
|
92
|
-
* // 处理 blob...
|
|
93
|
-
* }
|
|
96
|
+
* import { downloadWithPresignedUrl } from '@h-ai/storage/client'
|
|
94
97
|
*
|
|
95
|
-
*
|
|
96
|
-
* await
|
|
98
|
+
* async function download(url: string) {
|
|
99
|
+
* const result = await downloadWithPresignedUrl(url)
|
|
100
|
+
* if (!result.success || !result.data) throw new Error(result.error ?? 'Empty download')
|
|
101
|
+
* return result.data
|
|
102
|
+
* }
|
|
97
103
|
* ```
|
|
98
104
|
*/
|
|
99
105
|
declare function downloadWithPresignedUrl(url: string, options?: ClientDownloadOptions): Promise<{
|
|
@@ -106,12 +112,15 @@ declare function downloadWithPresignedUrl(url: string, options?: ClientDownloadO
|
|
|
106
112
|
*
|
|
107
113
|
* @param url - 下载 URL
|
|
108
114
|
* @param options - 下载选项
|
|
109
|
-
*
|
|
115
|
+
* @returns 声明返回类型对应的操作结果。
|
|
110
116
|
* @example
|
|
111
117
|
* ```ts
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
118
|
+
* import { downloadAndSave } from '@h-ai/storage/client'
|
|
119
|
+
*
|
|
120
|
+
* async function save(url: string) {
|
|
121
|
+
* const result = await downloadAndSave(url, { filename: 'report.pdf' })
|
|
122
|
+
* if (!result.success) throw new Error(result.error)
|
|
123
|
+
* }
|
|
115
124
|
* ```
|
|
116
125
|
*/
|
|
117
126
|
declare function downloadAndSave(url: string, options?: ClientDownloadOptions): Promise<{
|
|
@@ -122,16 +131,16 @@ declare function downloadAndSave(url: string, options?: ClientDownloadOptions):
|
|
|
122
131
|
* 从 File 对象获取文件扩展名
|
|
123
132
|
*
|
|
124
133
|
* 取文件名中最后一个 '.' 之后的部分,转为小写。
|
|
125
|
-
*
|
|
134
|
+
* 没有点号或以点号结尾时返回空字符串;仅前导点号的文件名按其后文本返回扩展名。
|
|
126
135
|
*
|
|
127
136
|
* @param file - 浏览器 File 对象
|
|
128
137
|
* @returns 扩展名(不含点),如 'png'、'tar.gz' 返回 'gz'
|
|
129
|
-
*
|
|
130
138
|
* @example
|
|
131
139
|
* ```ts
|
|
132
|
-
* getFileExtension
|
|
133
|
-
*
|
|
134
|
-
* getFileExtension(new File([], '
|
|
140
|
+
* import { getFileExtension } from '@h-ai/storage/client'
|
|
141
|
+
*
|
|
142
|
+
* const extension = getFileExtension(new File(['hello'], 'report.txt'))
|
|
143
|
+
* void extension
|
|
135
144
|
* ```
|
|
136
145
|
*/
|
|
137
146
|
declare function getFileExtension(file: File): string;
|
|
@@ -143,11 +152,12 @@ declare function getFileExtension(file: File): string;
|
|
|
143
152
|
*
|
|
144
153
|
* @param extension - 文件扩展名(不含点,大小写不敏感)
|
|
145
154
|
* @returns MIME 类型字符串
|
|
146
|
-
*
|
|
147
155
|
* @example
|
|
148
156
|
* ```ts
|
|
149
|
-
* getMimeType
|
|
150
|
-
*
|
|
157
|
+
* import { getMimeType } from '@h-ai/storage/client'
|
|
158
|
+
*
|
|
159
|
+
* const mime = getMimeType('pdf')
|
|
160
|
+
* void mime
|
|
151
161
|
* ```
|
|
152
162
|
*/
|
|
153
163
|
declare function getMimeType(extension: string): string;
|
|
@@ -155,16 +165,15 @@ declare function getMimeType(extension: string): string;
|
|
|
155
165
|
* 格式化文件大小为人类可读字符串
|
|
156
166
|
*
|
|
157
167
|
* 使用 1024 进制,输出单位为 B/KB/MB/GB/TB。
|
|
158
|
-
*
|
|
168
|
+
* 非零值使用对应单位并保留 2 位小数。
|
|
159
169
|
*
|
|
160
170
|
* @param bytes - 字节数(非负整数)
|
|
161
171
|
* @returns 格式化后的字符串,如 '0 B'、'1.50 KB'、'2.30 MB'
|
|
162
|
-
*
|
|
163
172
|
* @example
|
|
164
173
|
* ```ts
|
|
165
|
-
* formatFileSize
|
|
166
|
-
*
|
|
167
|
-
* formatFileSize(
|
|
174
|
+
* import { formatFileSize } from '@h-ai/storage/client'
|
|
175
|
+
*
|
|
176
|
+
* void formatFileSize(1536)
|
|
168
177
|
* ```
|
|
169
178
|
*/
|
|
170
179
|
declare function formatFileSize(bytes: number): string;
|
package/dist/client/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { downloadAndSave, downloadWithPresignedUrl, formatFileSize, getFileExtension, getMimeType, uploadWithPresignedUrl } from '../chunk-
|
|
1
|
+
export { downloadAndSave, downloadWithPresignedUrl, formatFileSize, getFileExtension, getMimeType, uploadWithPresignedUrl } from '../chunk-KVFEQHRX.js';
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/node.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { ClientDownloadOptions, ClientUploadOptions, UploadProgress, downloadAndSave, downloadWithPresignedUrl, formatFileSize, getFileExtension, getMimeType, uploadWithPresignedUrl } from './client/index.js';
|
|
2
2
|
import { StorageFunctions } from './browser.js';
|
|
3
|
-
export { CopyOptions, DirOperations, DownloadOptions, FileMetadata, FileOperations, HaiStorageError, ListOptions, ListResult, LocalConfig, LocalConfigSchema, PresignOperations, PresignOptions, PresignOptionsSchema, PresignUploadOptions, PresignUploadOptionsSchema, S3Config, S3ConfigSchema, StorageConfig, StorageConfigInput, StorageConfigSchema,
|
|
3
|
+
export { ChecksumAlgorithm, ChecksumOperations, ChecksumOptions, CopyOptions, DirOperations, DownloadOptions, FileMetadata, FileOperations, HaiStorageError, ListOptions, ListResult, LocalConfig, LocalConfigSchema, PresignOperations, PresignOptions, PresignOptionsSchema, PresignUploadOptions, PresignUploadOptionsSchema, S3Config, S3ConfigSchema, StorageConfig, StorageConfigInput, StorageConfigSchema, StorageData, StorageDeleteFailure, StorageDeleteResult, StorageDeleteSummary, StorageOperationLogConfig, StorageOperationLogConfigSchema, StorageType, StorageTypeSchema, UploadOptions } from './browser.js';
|
|
4
|
+
export { STORAGE_DELETE_MAX_KEYS, STORAGE_KEY_MAX_BYTES, StorageDeleteKeysSchema, StorageKeyIssue, StorageKeySchema, StoragePrefixSchema, StoragePresignExpiresInSchema, getStorageKeyIssue } from './schemas.js';
|
|
4
5
|
import 'zod';
|
|
5
6
|
import '@h-ai/core';
|
|
6
7
|
import 'node:buffer';
|
|
@@ -15,21 +16,24 @@ import 'node:buffer';
|
|
|
15
16
|
/**
|
|
16
17
|
* 存储服务单例
|
|
17
18
|
*
|
|
18
|
-
*
|
|
19
|
+
* 文件、目录及签名操作前须调用 `storage.init()`;checksum 为无状态工具,无需初始化。
|
|
19
20
|
* 初始化后通过 `storage.file`、`storage.dir`、`storage.presign` 访问各操作接口。
|
|
20
|
-
*
|
|
21
21
|
* @example
|
|
22
22
|
* ```ts
|
|
23
23
|
* import { storage } from '@h-ai/storage'
|
|
24
24
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
25
|
+
* const initialized = await storage.init({ type: 'local', root: './data/uploads' })
|
|
26
|
+
* if (!initialized.success) throw new Error(initialized.error.message)
|
|
27
|
+
* try {
|
|
28
|
+
* const uploaded = await storage.file.put('reports/a.txt', 'hello', { ifNoneMatch: '*' })
|
|
29
|
+
* if (!uploaded.success) throw new Error(uploaded.error.message)
|
|
30
|
+
* const downloaded = await storage.file.get('reports/a.txt')
|
|
31
|
+
* if (!downloaded.success) throw new Error(downloaded.error.message)
|
|
32
|
+
* void downloaded.data
|
|
33
|
+
* } finally {
|
|
34
|
+
* const closed = await storage.close()
|
|
35
|
+
* if (!closed.success) throw new Error(closed.error.message)
|
|
36
|
+
* }
|
|
33
37
|
* ```
|
|
34
38
|
*/
|
|
35
39
|
declare const storage: StorageFunctions;
|