@hachej/boring-files

中文文档
0.5.1发布于 2026/11/17MITTypeScriptES Module构建来源已验证近 30 天下载 8.6万

Versioned-resource contracts and the workspace provider over a Pi FileSystem (disk, virtual or SQLite).

原始使用文档
文档目录9 节
  1. Agent writes and the change feed
  2. Large files (blob pointers) and media sniffing
  3. Node hosts
  4. Optional authenticated resource transport
  5. Optional working Git
  6. Local publication preparation failures
  7. Migrating from the removed resource store
  8. Frontend revision provider
  9. Durable Object apps

@hachej/boring-files

Versioned resources over a workspace's files: the contracts, and the workspace provider over Pi's own FileSystem (no Boring file system). Reader, publisher and lookup capabilities are independently injectable; the aggregate ResourceProvider advertises actual support/grants/availability/qualified guarantees. ResourceClient carries browser intent, not trusted host ResourceAccess.

Publication requires nonempty changes and explicit atomicity. The trusted boundary computes the canonical digest and checks approval; those are not client-authored authority fields. Receipts identify valid create/replace/delete transitions; partial outcomes retain operation, input index and full target/view. Reconciliation is optional and required explicitly where claimed; not-found is not proof of no effect.

Opaque resource view IDs are provider-scoped and bound to the actual backing/incarnation by the provider. Import contracts with import type.

@hachej/boring-files/workspace exports createWorkspaceProvider({ identity, fs, journal }): the one provider of a workspace's files (One place for files). It takes a Pi FileSystem (a disk environment, the virtual workspace or the SQLite backend below), the host's workspace identity and a journal (createWorkspaceJournal(connection) from @hachej/boring-files/journal, receipts, intents and the last 20 versions of each file in SQLite). Revisions are Git blob ids of the bytes. A conditional write checks every expected revision and precondition inside the workspace's queue, records its intent first and its receipt last; an intent without a completion looks up as unknown and is never replayed. Its owner closes the connection; the provider borrows it. Node currently marks node:sqlite experimental.

The provider accepts all-or-nothing create, replace and conditional delete, plus conditional rename through renaming.rename. It refuses working views and folder mutations before any effect. Logical paths are relative to the workspace root; a path whose real location leaves the root is denied. A single file is replaced atomically by every backend; a multi-file batch only by the SQLite backend, together with its receipt when the journal shares the database. Access control is the host's, at the workspace boundary: there are no per-file permissions inside a workspace, and external revocation fencing is not implemented.

Agent writes and the change feed

Agent writes are observed, never receipted (owner ruling 2). provider.record({ path, before?, after, source: 'agent', conversationId? }, access) is what the file guard (@hachej/boring-agent/file-guard) calls after a Pi write or edit succeeded: the file's history gains the written revision with source: 'agent' (and the replaced revision, source: 'observed', when before carries its bytes), and the change feed an agent event. It never writes the publication journal and never mints a receipt. It does not enter the provider's queue (the guard already runs inside it), so calling it from queued work cannot deadlock. History entries (saves, catalog.history) carry source: publish, agent, observed (keep and replaced revisions), rename or delete (the affected retained version). History remains one row per content revision, not an operation log; receipts retain every conditional mutation. A rename retains the moved version at both paths; a delete retains its removed version without inventing a tombstone revision. savedAt remains the version's first recorded save time at that path, not a separate deletion timestamp.

provider.changes({ since?, signal }, access) is one change feed for every file view: an AsyncIterable of { kind: 'change', path, revision | null, source: 'publish' | 'agent' | 'poll' | 'watch', seq, at }, ordered by seq and replayable from since (the last seq seen; changeHead() is "now"). The provider retains the last changeBuffer events (default 1024); a cursor older than that, from another provider lifetime or ahead of this one, and a listener that falls behind get { kind: 'resnapshot', seq, at }: reload everything shown, then continue. Events are invalidation hints; bytes and the journal stay authoritative. Sources: conditional writes (publish), record (agent), poll and, while someone listens (and watchLingerMs after, default 30 s), the file system's own watch (watch; a reported directory is { revision: null, directory: true }). The SQLite file system reports writes through its own connection at once and polls every second for other connections. When the file system cannot watch (the virtual and remote environments report not_supported), the host calls provider.poll() at the end of each agent turn: without paths it hashes every file (not .git or node_modules); the first call takes the baseline, later ones report changed, new and removed files. A bash write gets change events only, never history. After the last listener leaves the watcher lingers and then closes; changes made while no watcher was open are unknown, so the first listener afterwards makes the feed append a resnapshot (a client that stays connected is never affected). changeIncarnation names the provider lifetime: a cursor sent with another incarnation is a resnapshot whatever its number. provider.close() ends every change stream, closes the watcher and drops the listeners.

Receipts are scoped by workspace identity, principal, scope and initiator. Identical committed retries return the original receipt; changed arguments conflict. Refused operations do not reserve an ID. A receipt from an earlier incarnation of the workspace reads unknown. A not-found lookup is not permission to replay an uncertain operation.

@hachej/boring-files/publication is browser-safe. It captures request bytes, computes a versioned canonical SHA-256 digest with WebCrypto, and parses result shapes. Digests carry boring-publication-v1:sha256: and bind that format identifier in the hashed payload. Consumers must also check operation, target, scope and index association against their own request. This module confers no authorization. The SQLite connection (openNodeConnection from @hachej/boring-files/sqlite) is a separate server entry point.

@hachej/boring-files/sqlite exports openNodeConnection(filename, settings?) (a node:sqlite file as a SqliteConnection) and openNodeDatabase(filename, settings?) (the configured DatabaseSync, for Pi's public adapter: SqliteStorage.open(new NodeSqliteDatabase(openNodeDatabase(file, settings)))). settings is SqliteSettings { journalMode?: 'wal' | 'delete' | 'truncate' | 'persist', lockingMode?: 'normal' | 'exclusive', busyTimeoutMs?, synchronous?: 'off' | 'normal' | 'full' | 'extra', tempStore?: 'default' | 'file' | 'memory' }; missing fields come from sqliteSettings.localDisk (WAL, normal locking, 5 s busy timeout, full sync: the behaviour before settings existed). sqliteSettings.networkFilesystem is for one process owning a file on NFS such as EFS: rollback journal, exclusive locking with the lock taken at open, 10 s busy timeout, full sync, temporary tables in memory; another connection to that file fails with SqliteLockedError (code: 'sqlite-locked') after its busy timeout. Names and values are allow-listed (TypeError otherwise, before the file is opened); there is no free-form pragma. The settings live in @hachej/boring-files/sqlite-settings (pure, browser-safe; sqlitePragmas(settings) is what the browser's SQLite Wasm uses), and npm run check refuses PRAGMA journal_mode/locking_mode assignments anywhere else. The journal, the metering ledger and the SQLite file system borrow a connection and never set pragmas.

@hachej/boring-files/sqlite-filesystem exports openSqliteFileSystem({ connection, workspace, cwd }): a Pi FileSystem whose regular files and directories are rows of one workspace in a SqliteConnection (openNodeConnection, durableObjectSqliteConnection, or openBrowserSqliteConnection from the private, unpublished @hachej/boring-browser/sqlite, available only inside this monorepo), with the incarnation of those rows. Like Pi's NodeExecutionEnv (which Pi's write tool relies on), writeFile creates missing parent directories; a parent that is a file still fails. Given to createWorkspaceProvider it is the SQLite workspace backend (One place for files): multi-file conditional batches commit in one transaction, together with the receipt when the journal uses the same connection. It implements Pi 1.2's full FileSystem (positional readers whose scanLines is Pi's own LineScanner, paged directory readers, and a polling watch) and answers with Pi's own FileErrors, so this entry loads @earendil-works/pi-durable/env (Pi's portable contracts, no engine): install @earendil-works/pi-durable with it. The other entries of this package do not need Pi.

See scaffold guide and resource design.

Large files (blob pointers) and media sniffing

A large or binary file (up to 100 MB) can live in the host's blob store as an immutable blob while the workspace holds a small pointer file in its place, <name>.blob.json with media type application/vnd.boring.blob+json: { "boring:blob": 1, "id", "sha256", "size", "type", "name" }. Where bytes live is the provider's business; the pointer is the provider's representation of a large immutable blob, written and read through the workspace's one provider like any file (no second place, no sync). The host serves the bytes at GET <blobBase><encodeURIComponent(id)> (default /_files/), same origin, checking access on every request and setting disposition, nosniff and a CSP. @hachej/boring-files/blob (pure, browser-safe) exports:

  • parseBlobPointer(bytes | text): strict (input under BLOB_POINTER_MAX_BYTES = 4 KB, UTF-8 JSON, every field with its type, 64 lower-case hex digits, a non-negative safe-integer size, a media type, a name without path separators). It returns the pointer, { kind: 'unsupported-version', version } for a higher boring:blob (show the file as JSON and say "newer format"), or undefined. Hosts validate with the same function.
  • checkBlobBase(base): a same-origin path starting with one /; a scheme, a host, //, a backslash or whitespace is a TypeError. blobItemOf(pointer, base) and resolveBlobPointer(bytes, base) give { name, size, type, url }, the only thing viewers see.
  • withBlobPointers(provider, base): the revision provider as a listing reads it: each pointer file of a list or search page carries blob (FileEntry.blob), read once through the same provider. Reads still return the pointer's bytes.
  • BLOB_POINTER_MEDIA_TYPE, BLOB_POINTER_SUFFIX, BLOB_POINTER_VERSION, DEFAULT_BLOB_BASE, isBlobPointerPath and the BlobPointer / BlobItem types.

@hachej/boring-files/file-types is the one table of what a file is. sniffMediaType(head) (pass up to SNIFF_BYTES = 8 KB) names PDF, PNG, JPEG, GIF, WebP, HEIC/HEIF (ISO-BMFF ftyp brands: heic, heix, hevc, … are HEIC; mif1/msf1 are HEIC with a HEVC compatible brand, HEIF otherwise, unclaimed with an AVIF brand), and zip documents from the head alone: OpenDocument and EPUB by their stored mimetype entry, docx/xlsx/pptx by a [Content_Types].xml entry and then its main part type when it is stored, else the folder of a later entry (word/, xl/, ppt/). The head is never inflated ([Content_Types].xml is almost always deflated, and inflating is asynchronous in a browser), so a zip whose sizes are in a data descriptor is not claimed. Otherwise bytes that are valid UTF-8 with no NUL are text/plain, a weak answer that never overrides a name. delimitedTextType(path, head) says CSV or TSV from the extension when the bytes are text. @hachej/boring-agent/file-types reads this table and head size; it keeps only its own routing kinds.

Node hosts

@hachej/boring-files/node-http bridges node:http to the Fetch handlers of these packages: webRequest(incoming, url, { signal, maxBytes }) reads the body first under a byte cap (never Readable.toWeb on a live request, whose cancellation kills the process) and sendWebResponse(response, outgoing, { signal }) flushes the headers at once, keeps each set-cookie, waits for drain when the socket is full and cancels the web body when the client disconnects. The example servers use it; npm run check refuses hand-written response copies under examples/.

Optional authenticated resource transport

@hachej/boring-files/remote exports createResourceClient and createResourceHandler. Both are Fetch adapters over the existing resource contracts. They import no Pi runtime, filesystem or database. The client implements ResourceClient; publication: true selects publish, rename and delete, and reconciliation: true selects lookup. The handler borrows a reader, optional publisher, renamer, deleter and lookup. It never closes them.

const handler = createResourceHandler({
  authenticate: request => host.authenticateResourceRequest(request),
  reader: provider,
  publisher: provider.publication,
  lookup: provider.reconciliation,
  renamer: provider.renaming,
  deleter: provider.deletion,
});
const client = createResourceClient({
  identity: { principalId, scopeId, initiatorId },
  endpoint: 'https://example.invalid/resources',
  fetch: authenticatedFetch,
  publication: true,
  reconciliation: true,
});

publication: true requires reconciliation: true (types and constructor): a mutation whose acknowledgement is lost is unknown, and only a lookup can resolve it. A read-only client sets neither. The handler answers 405 for an uninstalled capability; client opt-ins grant no server authority.

Authentication returns trusted ResourceAccess or null. Its optional signal represents host revocation; the handler combines it with request cancellation. Client identity is expected response metadata, never authority. The host owns credentials, origin/CSRF/CORS policy, endpoint routing and provider confinement. The injected Fetch must honor redirect: 'error', preserve cancellation and never retry effects. Bind a handler to the host's selected provider capabilities. Browser JSON cannot grant access or supply a trusted digest or approval.

The private versioned JSON envelope captures publication bytes before any asynchronous work. Protocol version 2 carries bytes as canonical base64 text (version 1 integer arrays are refused). Default limits are 4 MiB per serialized request and 8 MiB per serialized response, configurable up to 64 MiB. Incoming bodies use a bounded growing buffer. These are accepted-message limits, not limits on Fetch allocation, provider output, local request capture, JSON expansion or digest memory. Hosts must bound their trusted inputs and provider production separately.

All-or-nothing receipts must match the captured operation, canonical digest, actor and complete target transitions. Receipt order is preserved but does not determine association. Per-change requests are refused before dispatch; partial acknowledgements are unqualified and become unknown. A real partial provider must establish its receipt convention before that transport guarantee is added.

Transport errors, mismatched or oversized acknowledgements and aborted observation produce unknown publication/lookup outcomes. They never manufacture a known-no-commit denial or provider not-found, and never trigger replay. Read transport failures produce unavailable. Lookup checks operation and actor association; the caller still checks the digest and transitions against its captured original attempt. An operation ID alone cannot establish those arguments. Not-found does not authorize replay.

Revocation suppresses disclosure until the handler constructs its response; already delivered bytes cannot be retracted. Aborting observation does not prove provider termination, rollback or an atomic revocation fence. Provider exceptions and response serialization failures may follow a commit, so the client retains uncertainty. The workspace provider's declared guarantees remain unchanged.

Run node fixtures/resource-transport.mjs for a fictional exact-save and lookup journey through real Request/Response objects. Public-output tests also compose a native ToolTask and lost-acknowledgement Markdown reconciliation. The isolated document consumer exercises this adapter with strict types and a browser bundle without Pi, agent or React installed. These checks do not qualify deployed HTTP, browser identity policy or remote provider lifecycle.

@hachej/boring-files/text supplies the shared pure applyTextEdits transform and input parser. Edits run in order, require unique nonempty exact matches and preserve untouched whitespace. A failed edit refuses the whole transformation. It performs no I/O and grants no permission.

Optional working Git

@hachej/boring-files/git requires pinned [email protected]. createGitRepository borrows its public PromiseFsClient, an absolute normalized directory, a host author and a current authorize(operation) callback. The callback grants the bound caller access to the entire selected repository, including worktree and metadata. Only exact true grants access. It runs after queue acquisition and again before returning results. Share one repository instance across callers. Its queue serializes those calls only; other instances, raw filesystem writers and aliases require underlying host policy. Relative argument validation does not confine an unrestricted filesystem or symlink targets.

createEnvGitFs(fileSystem, context) is the PromiseFsClient over a Pi FileSystem (an ExecutionEnv's files): every Git read and write goes through that environment, so its confinement applies to Git too. Files read as mode 0o100644 (Pi's file contract has no modes) and symbolic links are refused (ENOSYS), never followed.

Methods are init, matrix status, add, index-only remove, commit, twenty-entry log, branches, branch, checkout and diff. Diff compares exact tree refs/object IDs, index and worktree. It returns changed blob paths, modes, object IDs and byte arrays, including untracked worktree files. It excludes .git, rejects unsupported entry types and reports limit errors without truncated success. Default returned-content limits are 100 files and 1 MiB. Traversal is serial, but upstream can allocate an entire blob before the byte limit is checked. These limits do not bound peak memory or repository traversal cost. Status and worktree diff disable native index refresh.

The host owns filesystem confinement, credentials and disposal. No network transport is installed. Cancellation is checked around native operations and during diff traversal; it cannot roll back Git mutations. GitOperationError.effects distinguishes pre-execution refusal from possible prior mutation. Git operations have no durable operation receipts, conditional publication or crash recovery guarantee.

Local publication preparation failures

PublicationNotDispatchedError from @hachej/boring-files/publication identifies a valid publication request that the remote client could not dispatch. Its operationId identifies that invocation. Local byte-limit, unsupported atomicity, digest, request-construction and pre-dispatch cancellation failures use this error. The error does not establish the outcome of earlier attempts with the same operation ID. Retain and reconcile any earlier uncertain attempt.

Once the fetch callback is called, transport exceptions, HTTP errors and invalid acknowledgements remain unknown, including a callback that throws the same error class after committing. A lookup not-found still does not prove that an interrupted request had no effect. The text controllers use the typed error only for their freshly generated operation, releasing that attempt so the user can save a corrected draft.

SQLite reads and receipt lookups of the SQLite workspace backend use deferred read transactions; a conditional write keeps its BEGIN IMMEDIATE transaction for its files and receipt. Tests hold an independent WAL writer transaction and read the previous committed file and receipt through the provider. This qualifies that WAL contention case; opening the database and arbitrary SQLite locking modes can still require write access or wait.

Migrating from the removed resource store

The SQLite resource store of @hachej/boring-files/sqlite (openSqliteResources, SqliteResourceProvider and its option types) is removed. Its documents become files of a workspace; SqliteConnection and openNodeConnection stay in @hachej/boring-files/sqlite. A host that kept one store with rows per scope (the current-hub fixture here) opens one SQLite-backed workspace per scope in the same database:

Old callNew call
openSqliteResources({ filename, providerId, authorize })connection = openNodeConnection(filename), journal = createWorkspaceJournal(connection), then per scope fs = openSqliteFileSystem({ connection, workspace: scopeId, cwd: '/workspace' }) and createWorkspaceProvider({ identity: { providerId, instanceId: scopeId, incarnation: fs.incarnation, viewId: 'published' }, fs, journal })
openSqliteResources({ connection, ... }) (a Durable Object)the same calls with durableObjectSqliteConnection(ctx.storage) from @hachej/boring-files/sqlite-durable-object
authorize(action, target, access) inside the storethe host checks its policy before calling the workspace's provider; shared/sqlite-workspaces.mjs shows one way (a refused write whose operation committed and a refused lookup read unknown)
provider.close()connection.close() by the connection's owner
a delete changeconditional publication with the observed revision, or provider.deletion.delete({ path: locator, expectedRevision, operationId }, access)
revisions were random ids; saving the same bytes made a new revisionrevisions are Git blob ids: the same bytes keep their revision, and before equal to after is a valid committed change
every revision retainedthe last 20 versions per file (createWorkspaceJournal(connection, { historyLimit })); older ones read unavailable

Existing store databases are not migrated: their boring_documents rows are not read by the workspace backend. Copy each current document into its workspace with a create, or start from the files.

Frontend revision provider

@hachej/boring-files/revision-handler serves an existing workspace provider. The host resolves its OAuth session and selected workspace on every request:

const handleFiles = createRevisionHandler({
  resolve: async request => {
    const session = await authenticate(request);
    if (!session) return null;
    return {
      provider: workspaces.workspace(session.workspaceId),
      access: {
        principalId: session.userId,
        scopeId: session.workspaceId,
        initiatorId: session.userId,
      },
    };
  },
});

authenticate and workspaces are host objects. Import createRevisionHandler from @hachej/boring-files/revision-handler. If acquisition returns a lease, include release; the handler retains it until underlying operations settle, including after request cancellation.

In the browser, import connectRevisionProvider from @hachej/boring-files/revision and connect once per selected workspace:

const revisionProvider = await connectRevisionProvider({
  endpoint: new URL('/api/workspace', location.origin),
  fetch: request => fetch(request),
});

The same route also answers createResourceClient of @hachej/boring-files/remote: a resource call (read, publish, lookup, rename, delete) sent without the binding header is served by createResourceHandler with the resolved access, so the envelope's identity must match it, and conditional writes refuse a stale revision with conflict. A binding header that is sent is checked (409 for another workspace); the listing and the change feed always need it. A host that serves only createResourceHandler (for example at /api/resource) keeps working with the same client; connectRevisionProvider there fails discovery (405), which means no listing.

The binding discovers identity and workspace incarnation from the authenticated server. Reconnect when the selected workspace changes. It exposes list, filename search, retained history, locate, read, publish, lookup, rename, delete and changes({ since?, signal }), the workspace's change feed.

const moved = await revisionProvider.rename?.({
  from: revisionProvider.locate('draft.md'),
  to: revisionProvider.locate('final.md'),
  expectedRevision: loaded.snapshot.ref.revision,
  operationId: 'move-draft-1',
});
const removed = await revisionProvider.delete?.({
  path: revisionProvider.locate('final.md'),
  expectedRevision: loaded.snapshot.ref.revision,
  operationId: 'remove-final-1',
});

These methods send rename and delete kinds on the same authenticated files endpoint. from, to and path are ResourceLocators, not strings. Both require the current source revision; rename also requires an absent target in the same provider/view and an existing parent directory. Direct workspace callers use provider.renaming.rename(request, access) and provider.deletion.delete(request, access). A rename receipt is a delete/create pair with the same content revision; its feed emits old-path revision: null then the new-path revision, both source: 'publish'. Delete emits revision: null. Stale revisions and existing file targets conflict. Identical operation-ID retries and lookup return the original receipt; changed arguments conflict. A lost reply stays unknown, never an automatic retry. createRevisionHandler installs these capabilities from its selected provider and holds the same workspace lease until they settle. Generic resource handlers install renamer/deleter explicitly. Folders, recursive deletion and file-tree Rename/Delete controls are not part of this endpoint increment.

Both operations use the workspace queue and Pi's native renameFile/remove. SQLite (including the Durable Object adapter) reuses those filesystem mutations inside the bytes/history/receipt transaction when the journal shares its connection. Disk/remote backends retain their existing crash window: an effect without a completed journal receipt is unknown. Shell writers remain outside the queue.

The feed is GET <endpoint>?op=changes[&since=<seq>&incarnation=<id>] with the binding header: server-sent events (event: ready with the current seq and the provider incarnation, then event: change or event: resnapshot with id: the seq and the JSON event as data:), and a comment line every heartbeatMs (createRevisionHandler({ resolve, heartbeatMs }), default 15 s). It is a plain streamed response with no queue (pull-based), so a slow client costs the provider's bounded replay buffer and a resnapshot, never memory in the handler; revocation discards anything unread. It runs on Node and Workers alike. The handler holds the workspace lease for the life of the stream and releases it when the client disconnects or its access signal aborts; a request the host refuses, or whose binding names another workspace or identity, gets no event (403 or 409). The client reconnects after the last seq it delivered, with backoff, until its signal aborts; a refusal ends it with a RevisionError. All writes use conditional publication; uploading a new file requires absence, and replacing one requires its exact resource revision. An unknown result must be reconciled by operation ID before another upload to that path.

Catalog defaults hide Git-ignored files, dependency/build folders and internal metadata. Configure createWorkspaceProvider({ ..., catalog: { defaults: false, filter: entry => ... } }) to override them. Filters govern presentation, not access control. The host authorizes the whole selected workspace. Listings do not follow symlinks. Pagination is a live, lexical view, not a frozen snapshot; refresh after concurrent changes. Traversal over the configured maxEntries (default 100,000) fails explicitly. History contains revisions retained by the workspace journal, not Git commits or an imported filesystem's prior history.

File search (the @ picker, the tree's filter) and uploads use this one route too: search is a catalog request, and an upload is a conditional create (expected: absent) with a receipt, like any other publication. There is no separate search or upload route to serve.

createRevisionHandler({ resolve, maxFileBytes }) names the largest file one write may carry, in bytes (default 3 MiB; at most about 48 MiB). Bytes travel as base64, so the handler sizes its resource requests and responses to that limit (at least 4 MiB and 8 MiB). A larger file gets the typed file_too_large result ({ path, size, limit, reason }) and nothing is written; a replay of an operation the journal already has keeps its recorded result. A request larger than the transport carries is answered 413, which the client reports as unavailable (a definite refusal). The binding (GET without op) names the limit as limits.maxFileBytes; connectRevisionProvider sizes its requests to it and exposes it as maxFileBytes, and the file tree refuses a larger upload before sending it. The provider's own file system may refuse a smaller file (SQLite: 1 900 000 bytes by default). This API does not provide streaming uploads.

Durable Object apps

A Cloudflare Durable Object keeps its workspace in its own SQLite storage, and the Library binds to it the same way as a Node host. Each piece is the one the Node example uses, with durableObjectSqliteConnection(ctx.storage) from @hachej/boring-files/sqlite-durable-object in place of openNodeConnection. The workspace and its journal share that one connection, so a multi-file save and its receipt commit in one transactionSync:

import { durableObjectSqliteConnection } from '@hachej/boring-files/sqlite-durable-object';
import { openSqliteFileSystem } from '@hachej/boring-files/sqlite-filesystem';
import { createWorkspaceJournal } from '@hachej/boring-files/journal';
import { createWorkspaceProvider } from '@hachej/boring-files/workspace';
import { createRevisionHandler } from '@hachej/boring-files/revision-handler';

// In the object's constructor: one connection and journal, one provider per workspace the object serves.
const connection = durableObjectSqliteConnection(this.ctx.storage);
const journal = createWorkspaceJournal(connection);
const fs = openSqliteFileSystem({ connection, workspace: workspaceId, cwd: '/workspace' });
const provider = createWorkspaceProvider({
  identity: { providerId: 'files', instanceId: workspaceId, incarnation: fs.incarnation, viewId: 'published' },
  fs,
  journal,
});

// The object's HTTP route: the host authenticates the request and picks the workspace it selected.
const handleFiles = createRevisionHandler({
  resolve: async request => {
    const session = await authenticate(request);
    if (!session) return null;
    return { provider: this.providerFor(session.workspaceId), access: { principalId: session.userId, scopeId: session.workspaceId, initiatorId: session.userId } };
  },
});

history is the journal's retained revisions for each file, newest first, with savedAt in milliseconds; a save made before this journal recorded times reports savedAt: 0. The browser connects as in the Node case: connectRevisionProvider({ endpoint, fetch }) from @hachej/boring-files/revision. Each scope is its own workspace (rows keyed by workspace), so a request is served only from the provider its resolve returns.

版本与发布记录

@hachej/boring-files 共发布 98 个版本,首次发布于 2026/10/12;过去 12 个月发布了 98 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.5.1latest2026/11/17今天
0.5.0next2026/11/133 天前
0.4.852026/11/125 天前
0.4.842026/11/125 天前
0.4.832026/11/125 天前
0.4.822026/11/116 天前

关于 @hachej/boring-files 的常见问题

@hachej/boring-files 是什么?

Versioned-resource contracts and the workspace provider over a Pi FileSystem (disk, virtual or SQLite).

如何安装 @hachej/boring-files?

在项目目录运行 npm install @hachej/boring-files,或使用 pnpm add / yarn add / bun add。

@hachej/boring-files 支持 TypeScript 吗?

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

@hachej/boring-files 支持 ESM 还是 CommonJS?

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

@hachej/boring-files 需要什么版本的 Node.js?

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

@hachej/boring-files 可以商用吗?

@hachej/boring-files 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@hachej/boring-files 的下载量有多少?

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

@hachej/boring-files 还在维护吗?

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