On this page
  1. Install
  2. Compose and store objects
  3. Put and URL properties
  4. Common method results
  5. Strict server-side writes
  6. Strict S3 direct uploads
  7. Error handling
  8. Advanced portable operations
  9. Provider bridge
  10. Provider-specific composition
  11. Filesystem capacity and ownership
  12. Boundary
  13. Bounded integrity verification
  14. API entry points and requirements
  15. Peer dependencies

This guide describes upcoming source contracts, not a publication receipt. Check release availability and keep your complete Playstack graph on one verified version.

@playstack/storage

Runtime-neutral object storage with streaming, conditional writes, listing, copy, ranges, multipart upload, and integrity checks.

Reference: @playstack/storage@0.1.0-beta.5 · TypeScript · MIT licence

Free. MIT licensed. Check preview availability before installing. See package access.

@playstack/storage provides one runtime-neutral object boundary across Cloudflare R2, S3-compatible services, local filesystem, and in-memory testing providers.

Install

After confirming preview access, install the package at your application's shared Playstack version:

sh
npm install --save-exact @playstack/storage@0.1.0-beta.5

Check the peer requirements below before choosing a runtime or provider.

Compose and store objects

For a complete example without cloud credentials, start with the storage quickstart.

Workers composition example: the snippet below assumes env.ASSETS is your configured R2 bucket binding, pdfBytes contains the document, and signer is your StorageUrlSigner. Omit signer if you do not need signed URLs. In Node, choose the S3 or filesystem entry point instead of a Workers binding.

ts
import { createStorage } from '@playstack/storage'
import { R2StorageProvider } from '@playstack/storage/r2'

const storage = createStorage({
  driver: new R2StorageProvider(env.ASSETS, {
    publicBaseUrl: 'https://assets.example.com',
    signer,
  }),
  prefix: 'billing',
})

const stored = await storage.put('invoices/invoice-1.pdf', pdfBytes, {
  contentType: 'application/pdf',
  cacheControl: 'private, max-age=0',
  metadata: { account_id: 'account-1' },
})

Bodies may be strings, bytes, ArrayBuffer, Blob, or Web readable streams. Reads always return a Web stream. Prefix and logical keys are canonical relative paths; dot/empty segments, backslashes, controls, and paths over 1,024 UTF-8 bytes are rejected.

Put and URL properties

Common method results

CallResultMissing object / important behavior
put(key, body, options?)Promise<StorageObjectMetadata>Creates or replaces an object; use write preconditions when replacement is not allowed.
putStrict(key, body, constraints)Promise<StorageUploadMetadata>Bounded server-side write with exact length, SHA-256 and encryption; requires provider support.
get(key, options?)Promise<StorageObject | null>Returns null when absent; consume or cancel the returned body stream.
head(key, options?)Promise<StorageObjectMetadata | null>Metadata only, without downloading the body.
exists(key, options?)Promise<boolean>Returns whether the object is present.
delete(key, options?)Promise<void>Deletes one key, not an application record or tenant.
list(options?)Promise<StorageListPage>A bounded page, not an unbounded list of the bucket.
verify(key, expected, options?)Promise<StorageObjectMetadata | null>Returns null when absent; throws on an integrity mismatch.
url(key)stringRequires public-URL capability; does not grant authorization.
signedUrl(key, options)Promise<string>Requires signing capability; treat the result as a secret capability.

For all overloads and option fields, open the StorageDriver and StoragePutOptions declarations through your editor. The entry-point table below identifies their installed files.

SurfaceProperties
CreateStorageOptionsRequired provider plus optional canonical prefix.
Put optionsContent type/encoding, cache control, disposition, length, and string metadata.
Signed URLget or put, expiry from 1 second through 7 days, optional disposition, and PUT content type.
CapabilitiesIndependent public URL, signed GET, and signed PUT booleans.

Calling an unsupported URL operation throws StorageCapabilityError. When a signed PUT includes content type or disposition, the uploader must send the exact signed header.

Strict server-side writes

Use putStrict for server-owned bytes that require the same explicit length, base64 SHA-256 and encryption constraints as a direct upload. The S3 provider submits those constraints and requires a matching checksum-enabled HEAD result. Unsupported providers refuse before consuming the body or writing an object.

The operation owns and checks the actual bytes before provider I/O, including Node Buffers and stream chunks. Its default byte ceiling is 16 MiB; a trusted host can set maxBytes explicitly. This is a bounded buffered profile, not streaming or multipart encryption support. Write conditions remain available. Ordinary put and multipart creation reject misplaced checksum/encryption fields instead of ignoring them.

HEAD observes the current object, not an immutable version receipt. A concurrent replacement or a failure after submission can leave a committed object without successful verification. StorageWriteUncertainError is non-retryable: reconcile before another write, and do not delete an object merely because verification failed. Playstack adds no retry loop; configure the supplied SDK's retry policy explicitly, including maxAttempts: 1 when automatic retries are prohibited. Live AWS/KMS enforcement remains a separate qualification gate.

Strict S3 direct uploads

Use signedUpload when direct upload admission requires an exact byte length, whole-body SHA-256 and server-side encryption. The result includes a PUT URL and all required signed headers. The checksum is canonical base64, unlike the hexadecimal checksum used by body-reading verify.

ts
const expected = {
  contentLength: uploadBytes.byteLength,
  checksumSha256: approvedBase64Sha256,
  encryption: { algorithm: 'AES256' as const },
  contentType: 'application/pdf',
}
const request = await storage.signedUpload('incoming/report.pdf', {
  ...expected,
  expiresInSeconds: 300,
})
// Send request.method, request.url, request.headers and the exact approved bytes.
// After the uploader completes, admit only a verified object:
const uploaded = await storage.verifyUpload('incoming/report.pdf', expected)

This partial example assumes an S3 provider, approved bytes and a trusted expected checksum. Use a client that transmits the exact required wire headers. Browser Fetch controls Content-Length itself; arbitrary browser streams are not covered. SSE-KMS uses { algorithm: 'aws:kms', keyId: fullKmsKeyArn }, with a full key ARN rather than an alias or implicit default. Optional type/disposition headers must also match exactly. Signed URLs and their headers are secret capabilities.

headUpload returns checksum and encryption metadata without downloading bytes. verifyUpload requires exact length, matching encryption/key and a full-object SHA-256. Missing, composite or unknown checksum metadata refuses verification; there is no ETag or download fallback. Both return null for an absent object. Providers without these optional operations throw StorageCapabilityError. Ordinary head, signedUrl and body-reading verify remain separate operations.

Presigned PUTs can be reused until expiry; credentials or policy can end them earlier. Verification observes the current object and does not bind a version or prevent replacement afterward. Your application owns upload authorization, key isolation, size policy and final admission. Checksum-enabled KMS HEAD can need additional KMS permissions. Local MinIO qualification is separate from live AWS/KMS, browser and multipart qualification. See AWS's presigned URL guidance and HEAD permission requirements.

Error handling

Errors are exported from @playstack/storage/errors. A missing read is null, not an exception. The main error codes are:

ErrorCodeWhat to do
StorageConfigurationErrorplaystack/storage/invalid_configurationCorrect the provider configuration.
StorageInputErrorplaystack/storage/invalid_inputCorrect the key, options or body.
StorageCapabilityErrorplaystack/storage/unsupported_capabilityChoose a provider that supports the operation.
StoragePreconditionErrorplaystack/storage/precondition_failedReconcile the object state; do not overwrite blindly.
StorageAbortedErrorplaystack/storage/operation_abortedTreat the operation as cancelled.
StorageIntegrityErrorplaystack/storage/integrity_failedReject the bytes and investigate the mismatch.
StorageWriteUncertainErrorplaystack/storage/write_outcome_unknownReconcile the possibly committed strict write before submitting another.
StorageUnavailableErrorplaystack/storage/unavailableConsider a bounded retry only when repeating the operation is safe.

All errors above except StorageUnavailableError are non-retryable. Its retryable flag does not establish whether a write took effect. Strict post-submission uncertainty uses StorageWriteUncertainError; an integrity mismatch can also follow a committed write. Your application owns write idempotency and recovery. Do not expose provider exception details or signed URLs to end users.

Advanced portable operations

ts
const page = await storage.list({ prefix: 'fonts', limit: 100 })
await storage.copy('fonts/source.woff2', 'fonts/archive/source.woff2')
await storage.deletePrefix({ prefix: 'temporary', maxObjects: 1_000 })

const chunk = await storage.getRange('packages/font.tgz', {
  start: 0,
  end: 1_048_575,
})

await storage.verify('packages/font.tgz', {
  size: expectedSize,
  etag: expectedEtag,
  sha256: expectedSha256,
})

Listing and prefix deletion are cursor-based and bounded. Range reads retain the complete object size. Verification can use size and ETag without downloading the body or SHA-256 when complete-body integrity is required. Operations accept an AbortSignal only when the selected provider declares that capability.

S3, R2, and memory providers support atomic create-only and compare-and-swap writes through ifNoneMatch and ifMatch. S3 also exposes portable multipart create, upload-part, complete, and abort operations. Unsupported capabilities fail explicitly before I/O.

Provider bridge

ts
interface StorageProvider<TClient> {
  client: TClient
  capabilities: StorageCapabilities
  put(key, body, options): Promise<StorageObjectMetadata>
  get(key): Promise<StorageObject | null>
  head(key): Promise<StorageObjectMetadata | null>
  delete(key): Promise<void>
  url(key): string
  signedUrl(key, options): Promise<string>
}

The driver wrapper adds logical prefixing, validation, normalized errors, exists, and stable metadata while exposing the exact native client.

Provider-specific composition

  • R2 accepts a structural bucket, optional public base URL, and optional external StorageUrlSigner for S3-compatible presigned URLs.
  • S3 accepts AWS client configuration plus bucket/public URL options and uses optional AWS SDK peers.
  • Filesystem is a Node development/test adapter for host-controlled, stable body and metadata trees. It accepts public URL/signing options, a byte ceiling, listing budgets, clock, and a separate metadata root.
  • Memory storage and the shared provider contract suite live under @playstack/storage/testing.
  • @playstack/nest-storage registers one or more named stores with stable injection tokens while preserving native clients and application lifecycle ownership.

Filesystem capacity and ownership

The filesystem adapter rejects observed symlinks in object paths, physically overlapping roots and changed root identities. It reads through the same verified regular-file handle rather than reopening a pathname. This requires supported no-follow/nonblocking file-open flags and host-protected roots and ancestors; it is not a sandbox against hostile concurrent parent replacement or hardlink injection.

maxBytes defaults to 16 MiB for PUT, complete GET and the returned range span. A bounded small range may read a larger source. Sidecar JSON is separately capped at 1 MiB. Growth or a short read fails instead of returning a silently truncated successful body. Consume or cancel each returned stream to release its handle.

Listing retains at most limit + 1 sorted candidates and rescans a bounded tree per page. maxListEntries defaults to 10,000 visited entries, including nonmatches and directories; maxListDepth defaults to 64 nested directories. Exhaustion throws without returning a partial page or cursor. This is a local development capacity guard, not indexed production pagination.

New directories/files use private permissions without changing existing modes. Body and metadata publication remain two separate renames, without atomic generation or equal-size metadata coherence. Conditional reads/writes and AbortSignal cancellation remain unsupported. Use a suitable production provider when those guarantees or an untrusted filesystem boundary are required.

Boundary

Storage does not decide tenant organization, media processing, access policy, lifecycle rules, or bucket administration. The application owns clients, credentials, shutdown, and domain-to-key mapping; use storage.client for provider-specific operations outside the portable surface.

Bounded integrity verification

SHA-256 verification now defaults to a 16 MiB actual-byte ceiling. Set verify(key, expected, { maxBytes, signal }) deliberately for larger objects. HEAD metadata permits early rejection but is not trusted instead of counting downloaded bytes; truncation, overflow and cancellation are checked. Changed/abandoned streams are cancelled. The portable hasher buffers up to the bound, so it is not constant-memory.

Node services can inject storageSha256Node from @playstack/storage/node through createStorage({ driver, sha256: storageSha256Node }) for incremental hashing under the same byte/abort contract. Use the S3 adapter for MinIO and R2's S3 endpoint in Node; the structural R2 binding is for Workers. Verification proves the downloaded snapshot, not immutability of future reads. Retain product key layouts, authorization and deployment-specific integrity tests.

API entry points and requirements

Reference snapshot: @playstack/storage@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.

Public entry pointDeclaration file
@playstack/storage./dist/index.d.ts
@playstack/storage/errors./dist/errors.d.ts
@playstack/storage/types./dist/types.d.ts
@playstack/storage/testing./dist/testing.d.ts
@playstack/storage/r2./dist/r2.d.ts
@playstack/storage/s3./dist/s3.d.ts
@playstack/storage/filesystem./dist/filesystem.d.ts
@playstack/storage/node./dist/node.d.ts
@playstack/storage/playstack.integration.jsonNo TypeScript declaration (asset or metadata export).
@playstack/storage/package.jsonNo TypeScript declaration (asset or metadata export).

Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.

Peer dependencies

Keep existing framework versions that satisfy these ranges. Install optional peers only when using the corresponding adapter. The package manager resolves ordinary dependencies separately.

PeerCompatible rangeWhen needed
@aws-sdk/client-s3^3.1116.0Optional; only for the entry points that use it.
@aws-sdk/s3-request-presigner^3.1116.0Optional; only for the entry points that use it.

For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.

Go

Playstack Pro tag
OriginsPricingBlogChangelogStatus

© 2026 Playstack. All rights reserved.

With OSS

By

Commune Software