@gentleduck/upload

中文文档
0.3.0发布于 2026/10/29TypeScriptES Module零依赖近 30 天下载 3082

@gentleduck/upload

原始使用文档
文档目录13 节
  1. Install
  2. Quick Start
  3. Strategies
  4. React
  5. Subpath Exports
  6. Features
  7. Persistence
  8. Writing a custom strategy
  9. Commands
  10. Events
  11. Bundler requirement
  12. Tests
  13. License

@gentleduck/upload

@gentleduck/upload

Headless, framework-agnostic file-upload engine with a typed state machine, pluggable strategies, and React bindings.

MIT - Changelog - Contributing - Docs

npm downloads MIT


A pure-reducer core, persistence-aware and resume-after-refresh, with bounded upload concurrency and zero coupling to a specific backend or UI library. The engine stays protocol-agnostic: your backend returns an intent, the engine dispatches on its strategy field to a registered strategy that moves the bytes.

Install

bun add @gentleduck/upload
# peer deps for the React bindings
bun add react react-dom

Quick Start

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' })

The createXHRTransport() browser transport is installed automatically. Pass transport: createFetchTransport() to run in Node / SSR / edge / workers.

Strategies

A strategy is the thin layer that turns an intent into network calls. Four ship built in; register the ones you need and let createIntent pick per file.

StrategyFactoryUse caseResumable
PUTPutStrategy(opts?)Single presigned PUT (S3 putObject, signed PUT)No
POSTPostStrategy(opts?)Presigned multipart/form-data (S3 POST policy)No
MultipartmultipartStrategy(opts?)Large files, concurrent parts, per-part resumeYes
tusTusStrategy(opts?)Resumable uploads over the tus protocolYes
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'] }))

Every backend-supplied URL (PUT / POST / multipart part / tus) runs through the validateUploadUrl SSRF guard before any byte leaves the client. Set allowedHosts to lock the host; keep allowPrivateHosts at its default false to block loopback / RFC1918 / cloud-metadata targets. PutStrategy, PostStrategy, and TusStrategy retry transient network failures (timeouts / 5xx / ECONNRESET) with exponential backoff.

React

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>

React exports: UploadProvider, useUploader, useUploaderActions, useDropzone, createUploadFactory, useUploadStore, isUploadStore (plus the pure helpers fileMatchesAccept, matchesAcceptToken, selectFiles).

Subpath Exports

import { createUploadStore, createFetchTransport } from '@gentleduck/upload/core'
import { UploadProvider, useUploader, useDropzone } from '@gentleduck/upload/react'
import { PutStrategy, TusStrategy, createStrategyRegistry } from '@gentleduck/upload/strategies'

Features

  • Pure reducer — command/event-driven state machine; effects are isolated.
  • Typed end-to-end — intents, cursors, purposes, and results are quad-generics threaded through the engine (M, C, P, R).
  • Four built-in strategies — PUT, POST, multipart, tus — plus a registry for your own.
  • Two transports — createXHRTransport() (browser, real upload progress) and createFetchTransport() (Node / SSR / edge / workers), with optional get() streaming download and head().
  • Resume after refresh — Memory / LocalStorage / IndexedDB persistence adapters; cursor-aware re-binding via the rebind command.
  • Retry policy — exponential backoff with per-phase attempt escalation (intent / upload / complete), overridable via config.retryPolicy.
  • Bounded concurrency — config.maxConcurrentUploads caps parallel uploads; queued items wait for a free slot.
  • Content dedupe, off-thread — SHA-256 checksums hash inline for small files and incrementally in a Web Worker for large ones, so checksumMaxSize is a boundary, not a skip — big files stay deduplicated without freezing the UI.
  • Headless React — useDropzone gives drag-and-drop + file-picker prop getters with zero markup or styling.
  • SSRF guard built in — allowlist + protocol + IPv4/IPv6 private + cloud-metadata + NAT64 + 6to4 + IPv4-mapped checks on every upload URL.
  • Filename + MIME hardening — NFKC normalize, control-char strip, Windows reserved-name + 255-char + path-sep rejection; magic-byte sniff cross-checks the claimed file.type.
  • NaN-safe configs — every numeric option clamps NaN / Infinity / negative to its default; persisted snapshots reject NaN fields.
  • No DOM coupling — runs in Workers, Node 22+, or the browser.
  • Threat model + audit — STRIDE-mapped THREAT-MODEL.md and re-runnable AUDIT-RESULTS.md checked into the package.

Persistence

Persistence lets a paused or in-flight upload survive a refresh: the snapshot is stored, and a rebind re-attaches a fresh File (validated by fingerprint) so a resumable strategy continues from its cursor.

import { createUploadStore, IndexedDBAdapter } from '@gentleduck/upload/core'

createUploadStore({
  strategies,
  api,
  persistence: {
    key: 'app:uploads',
    version: 1,
    adapter: IndexedDBAdapter, // or LocalStorageAdapter / createMemoryAdapter()
    isPurpose,
    isIntent,
  },
})

Adapters: IndexedDBAdapter and LocalStorageAdapter (shared singletons), MemoryAdapter (shared) or createMemoryAdapter() (isolated per store). Bump persistence.version in lockstep across tabs/deployments; a snapshot at a different version is rejected by deserializeSnapshot's version fence rather than loaded.

Writing a custom strategy

A strategy implements one start() against the Contracts.Strategy.Me contract. id must equal the intent's strategy field; resumable is metadata for your UI. Honor signal, call reportProgress, and — if resumable — persistCursor at each safe boundary.

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() is awaited: resolve → the engine transitions to completing; throw → the error routes through errorNormalizer + retryPolicy. The ctx also carries intent, api, readCursor, persistCursor, attempt, and the injected transport (put / postForm / patch and the optional get / head). Use api.multipart.signPart / completeMultipart for backend round-trips a strategy needs mid-flight.

Commands

Dispatch via store.dispatch(cmd).

CommandPurpose
addFilesValidate + insert; schedules checksum + intent
start / startAllMove ready items to queued (batched)
pause / pauseAllAbort inflight, persist cursor (batched)
resumeRe-queue a paused item
cancel / cancelAllAbort and mark canceled (batched)
retryRe-attempt the failed phase, bumping the attempt counter
rebindRe-attach a fresh File after refresh (fingerprint-validated)
removeDrop the item from state

Events

Subscribe via store.on(type, cb); payloads are typed from the engine's event map.

  • file.added, file.rejected
  • validation.ok, validation.failed
  • intent.creating, intent.created, intent.failed
  • upload.queued, upload.started, upload.progress, upload.cursor
  • upload.paused, upload.resumed, upload.canceled
  • upload.completing, upload.completed, upload.error

Bundler requirement

The engine references process.env.NODE_ENV to gate dev-only invariant warnings. Vite / Webpack / Rspack / esbuild / Rollup replace this at build time and ship a single branch to production. Pure-ESM consumers loading the source without a bundler must set globalThis.process = { env: { NODE_ENV: 'production' } } before importing the package.

Tests

bun run test

The Vitest suite covers the reducer state machine, persistence, every strategy and transport, the incremental hasher, the SSRF/filename/MIME guards, and the React helpers.

License

MIT

版本与发布记录

@gentleduck/upload 共发布 6 个版本,首次发布于 2026/03/12;过去 12 个月发布了 6 个版本。

版本发布日期距今
0.3.0latest2026/10/2917 天前
0.2.62026/05/205 个月前
0.2.52026/05/066 个月前
0.2.42026/05/066 个月前
0.2.22026/03/128 个月前
0.2.12026/03/128 个月前

关于 @gentleduck/upload 的常见问题

如何安装 @gentleduck/upload?

在项目目录运行 npm install @gentleduck/upload,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^19.2.3)、react-dom(^19.2.3)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@gentleduck/upload 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gentleduck/upload 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gentleduck/upload 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gentleduck/upload 可以商用吗?

@gentleduck/upload 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@gentleduck/upload 的下载量有多少?

根据 npm 官方下载统计,@gentleduck/upload 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,082 次,日均约 103 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gentleduck/upload 还在维护吗?

最新版本 0.3.0 发布于 2026/10/29(17 天前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/03/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。