@ gentleduck/ 上载
无头型,框架-不可知文件上载引擎,并配有打入的状态机,可插接策略和回放装订.
麻省理工学院 - 说吧 更改日志 - 说吧 捐款 - 说吧 文档
纯减量核心, 持久性意识和再现, 有限制上传
与特定的后端或 UI 库相通和零相接. 发动机留下
协议不可知: 您的后端返回一个意图, 其上的引擎调度 strategy 字段
到移动字节的已注册策略.
安装
bun add @gentleduck/upload
# peer deps for the React bindings
bun add react react-dom
快速启动
import { createUploadStore } from '@gentleduck/upload/core'
import { PutStrategy, createStrategyRegistry } from '@gentleduck/upload/strategies'
type Intents = { put: PutStrategy.Intent }
type Cursors = { put?: PutStrategy.Cursor }
type Purpose = 'attachment'
type Result = { fileId: string; key: string }
const strategies = createStrategyRegistry<Intents, Cursors, Purpose, Result>()
strategies.set(PutStrategy({ allowedHosts: ['uploads.example.com'] }))
const store = createUploadStore<Intents, Cursors, Purpose, Result>({
strategies,
api: {
// Ask your backend to presign the upload.
async createIntent({ filename, contentType, size }) {
const res = await fetch('/api/sign', {
method: 'POST',
body: JSON.stringify({ filename, contentType, size }),
})
return res.json() // -> { strategy: 'put', fileId, url, headers? }
},
// Finalize once the bytes are transferred.
async complete({ fileId }) {
return { fileId, key: `attachments/${fileId}` }
},
},
config: { maxConcurrentUploads: 3, autoStart: ['attachment'] },
})
store.dispatch({ type: 'addFiles', files, purpose: 'attachment' })
这个 createXHRTransport() 浏览器传输自动安装 。 过
transport: createFetchTransport() 用于在节点/SSR/边缘/工人中运行.
战略
策略是将意图转化为网络呼叫的薄层. 建造了四艘船;
登记您需要的,并让 createIntent 选择每个文件.
| 战略 | 工厂 | 使用大小写 | 可偿还 |
|---|---|---|---|
| 点 | PutStrategy(opts?) | 单个预签 PUT( S3) putObject,签名 PUT) | 没有 |
| 邮政 | PostStrategy(opts?) | 签名 multipart/form-data (S3 POST 政策) | 没有 |
| 多块 | multipartStrategy(opts?) | 大型文件,并行部分,每部分恢复 | 对 |
| s | TusStrategy(opts?) | 可恢复上传到 Tus 协议 | 对 |
import {
PutStrategy,
PostStrategy,
multipartStrategy,
TusStrategy,
createStrategyRegistry,
} from '@gentleduck/upload/strategies'
const strategies = createStrategyRegistry<Intents, Cursors, Purpose, Result>()
strategies.set(PutStrategy({ allowedHosts: ['uploads.example.com'] }))
strategies.set(PostStrategy())
strategies.set(multipartStrategy({ maxPartConcurrency: 4 }))
strategies.set(TusStrategy({ allowedHosts: ['tus.example.com'] }))
每个后端提供的 URL (PUT / POST /多部分 / tus) 运行于 validateUploadUrl
SSRF在任何字节离开客户端前进行守卫. 设定 allowedHosts 锁定主机; 保留
allowPrivateHosts 默认时 false 以阻断回转 / RFC1918 / 云-元数据目标.
PutStrategy, (中文(简体) ), PostStrategy,以及 TusStrategy 重试瞬态网络失败
(超时 / 5xx / ECONNRESET与指数后退.
反应
import {
UploadProvider,
useUploader,
useDropzone,
} from '@gentleduck/upload/react'
function Uploader() {
const { getRootProps, getInputProps, isDragging } = useDropzone({
purpose: 'attachment',
accept: 'image/*,.pdf',
})
const { items, dispatch } = useUploader<Intents, Cursors, Purpose, Result>()
return (
<div {...getRootProps()} data-active={isDragging}>
<input {...getInputProps()} />
{items.map((item) => (
<Row
key={item.localId}
item={item}
onCancel={() => dispatch({ type: 'cancel', localId: item.localId })}
/>
))}
</div>
)
}
// Wrap once so descendants can reach the store.
<UploadProvider store={store}>
<Uploader />
</UploadProvider>
反应导出 : UploadProvider, (中文(简体) ), useUploader, (中文(简体) ), useUploaderActions, (中文(简体) ), useDropzone, (中文(简体) ),
createUploadFactory, (中文(简体) ), useUploadStore, (中文(简体) ), isUploadStore (加上纯洁的助手)
fileMatchesAccept, (中文(简体) ), matchesAcceptToken, (中文(简体) ), selectFiles) (中文(简体) ).
子路径导出
import { createUploadStore, createFetchTransport } from '@gentleduck/upload/core'
import { UploadProvider, useUploader, useDropzone } from '@gentleduck/upload/react'
import { PutStrategy, TusStrategy, createStrategyRegistry } from '@gentleduck/upload/strategies'
特征
- 纯减排器 ——指挥/活动驱动的状态机器;效果被隔离.
- 输入端到端 - 意图、光标、目的和结果为四相线程
通过发动机(
M, (中文(简体) ),C, (中文(简体) ),P, (中文(简体) ),R) (中文(简体) ). - 四项内在战略 ——PUT,POST,多部分,tus——加上自己的注册.
- 两次运输 —— 说
createXHRTransport()(浏览器,真正的上传进度)和createFetchTransport()(节点/标准标准/边缘/工人),可选get()流线 下载和head()。 。 。 . - 刷新后继续 – 内存 / localStorage / 索引 DB 持久性适配器;光标意识
通过
rebind命令. - 重试策略 ——每相位尝试升级的指数回放(意图/上传/
完成),通过
config.retryPolicy。 。 。 . - 受约束货币 —— 说
config.maxConcurrentUploads封顶平行上传;已队列的项目 等待一个空位. - 内容去除线程 - SHA-256小文件的散列检查和
在大型的网络工人中
checksumMaxSize是边界,不是跳过.. 大文件在不冻结UI的情况下会被复制. - 无头反应 —— 说
useDropzone给拖放 + 文件拾取器 道具获取器为零 标记或造型. - SSRF 警卫队 ——许可列表+协议+IPv4/IPv6私人+云-元数据+NAT64+ 6to4 + IPv4 上传的每个 URL 上的检查 .
- 文件名 + MIME 硬化 ——NFKC常态化,控制带,Windows保留名称+
255-char + 路径- sep 拒绝; 魔法字节嗅取 交叉检查所声称的
file.type。 。 。 . - 纳恩安全配置 - 每个数字选项夹
NaN编号 :Infinity负于其 默认; 拒绝持续快照NaN字段. - 没有 DOM 组合 ——运行于Workers,Node 22+,或浏览器.
- 威胁模式+审计 - 坚固的
THREAT-MODEL.md可重运行AUDIT-RESULTS.md检查了包裹.
持久性
恒定让一个被暂停或飞行中的上传幸存的新鲜:快照是存储的,a
rebind 重新装入新鲜的 File (通过指纹验证) 所以一个可恢复的策略继续
从光标中.
import { createUploadStore, IndexedDBAdapter } from '@gentleduck/upload/core'
createUploadStore({
strategies,
api,
persistence: {
key: 'app:uploads',
version: 1,
adapter: IndexedDBAdapter, // or LocalStorageAdapter / createMemoryAdapter()
isPurpose,
isIntent,
},
})
适配器 : IndexedDBAdapter 财务报告和审定财务报表 LocalStorageAdapter (共享单吨), MemoryAdapter
(分摊)或 createMemoryAdapter() (每个店都隔离). 弹出 persistence.version 锁定
横跨标签/部署; 不同版本的快照被拒绝 deserializeSnapshot是因为
版本栅栏而不是加载.
写入自定义策略
战略实施 start() 反对: Contracts.Strategy.Me 合同. id 必须是平等的
意图 strategy 字段; resumable 是您 UI 的元数据。 荣誉 signal电话
reportProgress,并且——如果可以恢复的话—— persistCursor 在每一个安全边界.
import type { Contracts } from '@gentleduck/upload/core'
type Intents = { myput: { strategy: 'myput'; fileId: string; url: string } }
type Cursors = { myput?: Record<string, never> }
type Purpose = 'attachment'
type Result = { fileId: string; key: string }
const myPut: Contracts.Strategy.Me<Intents, Cursors, Purpose, Result, 'myput'> = {
id: 'myput',
resumable: false,
async start(ctx) {
await ctx.transport.put({
url: ctx.intent.url,
body: ctx.file,
signal: ctx.signal,
onProgress: (uploadedBytes, totalBytes) => ctx.reportProgress({ uploadedBytes, totalBytes }),
})
},
}
strategies.set(myPut)
start() 正在等待: 解决 ~ 引擎向 completing; 抛出 ~ 错误路径
结束 errorNormalizer + 键 retryPolicy编辑 ctx 还携带 intent, (中文(简体) ), api, (中文(简体) ), readCursor, (中文(简体) ),
persistCursor, (中文(简体) ), attempt,并注入 transport (单位:千美元)put 编号 : postForm 编号 : patch 编辑
选项 get 编号 : head) (中文(简体) ). 使用 api.multipart.signPart 编号 : completeMultipart 用于后端
绕道飞行需要中途飞行.
图标
通过 store.dispatch(cmd)。 。 。 .
| 命令 | 目的 |
|---|---|
addFiles | 验证 + 插入; 调度校验和 + 意图 |
start 编号 : startAll | 移动已准备好的项目到队列( 已选中) |
pause 编号 : pauseAll | 停止飞行, 持续光标( 有争议) |
resume | 重排已暂停的项目 |
cancel 编号 : cancelAll | 中止并标记已取消( 已辩论) |
retry | 重新尝试失败的阶段, 撞倒尝试计数器 |
rebind | 重新添加一个新鲜的 File 刷新后( 指纹验证) |
remove | 从状态丢弃项目 |
活动
通过 store.on(type, cb);有效载荷从发动机的事件地图上打出.
file.added, (中文(简体) ),file.rejectedvalidation.ok, (中文(简体) ),validation.failedintent.creating, (中文(简体) ),intent.created, (中文(简体) ),intent.failedupload.queued, (中文(简体) ),upload.started, (中文(简体) ),upload.progress, (中文(简体) ),upload.cursorupload.paused, (中文(简体) ),upload.resumed, (中文(简体) ),upload.canceledupload.completing, (中文(简体) ),upload.completed, (中文(简体) ),upload.error
Bundler 要求
引擎参考文献 process.env.NODE_ENV 以示警告。 虚拟/网络包装
Rspack / esbuild / rollup在建设时替换这个,并将一个分公司运到生产.
纯ESM 消费者必须在没有捆绑器的情况下装入源头
globalThis.process = { env: { NODE_ENV: 'production' } } 在导入软件包之前.
测试
bun run test
Vitest套房包括减速器状态机器、持久性、每个策略和运输、 递增的散列器,SSF/filename/MIME守护器,以及反应辅助器.
许可证
麻省理工学院