solid-offline
Use when implementing or changing the solid-offline service-worker cache, proactive warmer, StorageClient reads, pod-notifications invalidation, app-shell precache, WebID-scoped storage, logout purge, status surface, or React offline hooks.
- License 许可
- MIT
- 所属仓库
- jeswr/solid-sdk
- 最近更新
- 2026-11-15
- Stars
- ★ 2
- Forks
- 0
01 前言 Front Matter
- name
- solid-offline
- description
- Use when implementing or changing the solid-offline service-worker cache, proactive warmer, StorageClient reads, pod-notifications invalidation, app-shell precache, WebID-scoped storage, logout purge, status surface, or React offline hooks.
02 资源文件 61
- 参考文档docs/MODEL-PROVENANCE.md28.9 KB
- 参考文档etc/solid-offline.api.md67.7 KB
- 参考文档package.json2.2 KB
- 参考文档README.md22.4 KB
- 脚本scripts/api-report.d.mts823 B
- 脚本scripts/api-report.mjs12.3 KB
- 脚本src/app-shell.ts27.8 KB
- 脚本src/cache-coherence.ts9.0 KB
- 脚本src/cache-policy.ts16.0 KB
- 脚本src/index.ts21.3 KB
- 脚本src/invalidation.ts16.6 KB
- 脚本src/listing-pages.ts1.0 KB
- 脚本src/logout.ts6.9 KB
- 脚本src/merge.ts1.1 KB
- 脚本src/metadata-store.ts9.0 KB
- 脚本src/outbox.ts48.9 KB
- 脚本src/page-cache.ts9.5 KB
- 脚本src/react.ts13.4 KB
- 脚本src/revalidation-events.ts1.0 KB
- 脚本src/scope.ts5.0 KB
- 脚本src/status.ts9.8 KB
- 脚本src/storage.ts1.7 KB
- 脚本src/swr.ts30.9 KB
- 脚本src/types.ts11.6 KB
- 脚本src/warm-transport.ts8.3 KB
- 脚本src/warmer-rdf.ts10.4 KB
- 脚本src/warmer.ts29.9 KB
- 脚本src/worker.ts28.7 KB
- 脚本test/api-report.test.ts3.6 KB
- 脚本test/app-shell.test.ts36.9 KB
- 脚本test/cache-coherence.test.ts4.6 KB
- 脚本test/cache-policy.test.ts8.8 KB
- 脚本test/cache-provenance-worker.test.ts4.1 KB
- 脚本test/cache-provenance.test.ts8.0 KB
- 脚本test/client-config.test.ts24.9 KB
- 脚本test/client-outbox.test.ts5.0 KB
- 脚本test/invalidation.test.ts16.4 KB
- 脚本test/listing-invalidation.test.ts16.2 KB
- 脚本test/logout.test.ts7.0 KB
- 脚本test/merge.test.ts2.4 KB
- 脚本test/metadata-store.test.ts4.1 KB
- 脚本test/mocks.ts3.2 KB
- 脚本test/outbox-destination.test.ts20.6 KB
- 脚本test/outbox-guard.test.ts45.5 KB
- 脚本test/outbox.test.ts28.3 KB
- 脚本test/page-cache.test.ts29.8 KB
- 脚本test/react.test.ts14.9 KB
- 脚本test/request-freshness.test.ts15.4 KB
- 脚本test/revalidation-events.test.ts15.1 KB
- 脚本test/scope.test.ts3.3 KB
- 脚本test/setup.ts271 B
- 脚本test/status-subscription.test.ts4.0 KB
- 脚本test/status.test.ts17.2 KB
- 脚本test/storage-plumbing.test.ts14.9 KB
- 脚本test/swr.test.ts21.4 KB
- 脚本test/warm-worker.test.ts25.6 KB
- 脚本test/warmer.test.ts42.9 KB
- 脚本test/worker-plumbing.test.ts10.1 KB
- 参考文档tsconfig.json732 B
- 脚本tsup.config.ts486 B
- 脚本vitest.config.ts581 B
03 SKILL.md 正文
<!-- AUTHORED-BY Codex GPT-5 --> <!-- AUTHORED-BY Codex GPT-6.1-Sol --> <!-- // AUTHORED-BY Codex GPT-6 -->
Work with @jeswr/solid-offline
Preserve the central invariant: cached pod data is never authoritative. Serve cached bytes quickly, mark offline hits stale, and revalidate online entries against the pod.
Page-client workflow
import { createOfflineClient } from "@jeswr/solid-offline";
import { createPodClient } from "@jeswr/storage-client";
const { storage } = await createPodClient({ storage: storageRoot, fetch: session.fetch });
const offline = createOfflineClient({
storage,
webId,
fetch: session.fetch,
warm: { seeds: "auto" },
notifications: true,
appShell: { precache: shellUrls, fallback: "/index.html", version: buildSha },
workerUrl: "/solid-offline-worker.js",
});
await offline.register();
// Mandatory when this identity signs out:
await offline.logout();
Import @jeswr/solid-offline/worker from an origin-served service-worker entry. Import React-only helpers from @jeswr/solid-offline/react; React is an optional peer and must not leak into the core entry point.
Native page adapter
createPageCache({ webId, storageRoot, fetch, usable, onEvent? }) wraps the bounded
session fetch without a worker. Use it only for native targets; keep the web worker.
It uses handleFetch with strategy: 'network-first', the shared IndexedDB body and
metadata stores, handleNotification, resyncSweep and purgeForWebId. Do not fork
those decisions in apps. The default worker delivery remains SWR for compatibility.
Create/start only after commit. usable() must include the live account and session
version, not just rendered state. Check around every await and never fallback from
session errors, aborts, HTTP failures or explicit freshness to cached success.
start() owns root and bounded hot-resource subscriptions; invoke again on reconnect
if setup failed. notify(frame)/resync() also accept externally owned notifications.
Relay updated events to session subscribers. close() fences permanently and retains
reads; logout() fences immediately then purges both bodies and metadata, preserving
outbox writes. On switches and all logout paths, call/await this purge; coordinate
replacement adapters with pending cleanup. Surface blocked/error purge outcomes.
Commit response bytes and metadata atomically after the live session/resource fence.
Notification revisions affect only the resource, membership targets and evicted cursor
pages; matching-ETag no-ops do not fence reads. Network-first/forced read completion uses
revalidated for initial fills, unchanged representations and repeated uncacheable reads.
Emit updated for a changed cached representation or eviction, and for real notifications,
so an updated subscriber can reread without feeding back into another invalidation.
Bound each persisted body to 25 MiB using declared size and a bounded reader; leave the caller stream available on overflow. Never await cancellation of its tee branch. Store bodies beside metadata in the same IndexedDB database for worker and page. Namespaces include full WebIDs to prevent hash collisions. Never persist Requests, credential-valued Vary keys or sensitive response headers. Purge legacy hash-only stores too; never serve their abandoned bytes. The new namespace starts empty.
Security and correctness rules
- Keep the service worker credential-free. Authenticated warming happens in the page through the injected StorageClient. The optional page fetch is used by pod-notifications.
- Scope Cache API and IndexedDB state by WebID. Anonymous and authenticated identities must never share a cache namespace.
- Purge both read-cache stores on logout. Preserve the separate write outbox; only its explicit
purge()discards unsent changes. A failure in one purge path must not prevent attempting the other. - Never cache auth, token, OIDC, notification-subscription, WebSocket-upgrade, opaque,
private, orno-storeresponses. - Cache response bytes only for GET. Treat HEAD as a network passthrough that may confirm existing
metadata freshness when its ETag matches; never pass a HEAD request to
Cache.put()and never let it replace or evict a cached GET body. Keep the bounded negative-cache behavior for 403/404 GETs. - Respect
Vary; normalize supported RDF reads to the canonical accept value without collapsing genuinely different variants. - On an online hit, serve immediately and conditionally revalidate. A
304refreshes metadata; a changed200replaces bytes and broadcasts an update. - Tag readable in-scope pod GET responses with
X-Solid-Offline-Cache, exported asCACHE_PROVENANCE_HEADER.cacheProvenance(response)returns'hit' | 'miss' | 'stale' | nullwithout reading the body. Network bytes aremiss, even when HTTP policy prevents storage; synchronous 304-confirmed bytes and negative entries within their bounded TTL arehit. Offline positive-cache reads and immediate SWR bytes arestale, including when background validation fails, is skipped, or later succeeds. Keep the legacy offlineX-Offlinemarker. Decorate cloned responses only, never cached entries. Leave out-of-scope requests, HEAD, app-shell responses, and opaque/opaque-redirect or status-zero responses unchanged. - Treat notification
state/ETag equality as a fast no-op, not a universal correctness assumption. Reconcile after disconnects. - Bound warming by resource count, bytes, depth, and concurrency. Acknowledge the worker budget session before intercepted StorageClient reads, retain HEAD size evidence, and validate streams before Cache.put; never retry guarded failures outside the budget. Prune unreadable subtrees and avoid eager caching of large binary bodies.
- Keep app-shell caches versioned and separate from pod-data caches. Cache only explicitly declared public shell URLs.
Status and React integration
Use offline.status or createStatusSurface() as a stable subscribe/getSnapshot store. useOfflineStatus and useOfflineResource should remain thin useSyncExternalStore adapters; caching policy stays in the shared engine, with worker and page drivers.
<!-- AUTHORED-BY Codex GPT-6.1-Sol -->
The worker broadcasts OfflineEvent messages containing only URL, event, and an opaque
random attemptId shared by an attempt's start and terminal messages: revalidating starts an attempt;
exactly one of updated (replacement/purge), revalidated (confirmed 304 or matching sweep HEAD), or
revalidate-failed (network/offline/storage/non-authoritative response) terminates it.
Keep UpdatedEvent source-compatible; do not put ETags, bytes, headers, credentials, or
errors on the channel. Direct delete purges use the same balanced lifecycle without
fetching; purge errors terminate with revalidate-failed.
Track URLs with the surface's mark methods. For tracked URLs, start → pending,
confirmed 304 → fresh, replacement/purge → updated, and failure → the prior state.
Parallel observed attempts remain pending until all settle. Correlate completions by ID,
so a missed start before subscription cannot settle newer work (including lazy offline.status).
Keep legacy ID-less messages source-compatible with separate URL-based counting; that
older protocol cannot guarantee correct accounting across missed starts.
Keep settled freshness separate from
active-attempt counts: manual marks update the settled state while pending, and failures
retain that state. An unread updated survives 304 confirmations until a consumer mark
acknowledges its read. Offline cache hits and no-op/skipped
validations emit no lifecycle events. An unsolicited 304 on an unconditional listing
refresh is a failed confirmation. markPending remains supported. useOfflineStatus
returns UseOfflineStatusResult, which adds syncing: boolean (pending > 0) to the
snapshot. useOfflineResource continues to reload only on updated events.
Test decision logic with fake storage clients/transports, Cache API, subscriptions, and real fake IndexedDB seams. A change to worker lifecycle wiring also needs browser-level verification because unit tests do not exercise real service-worker install/activate/fetch events.
Run the package and full workspace gates. For an intentional public API change, rebuild and update the API report before the final gate.
Storage and subscription plumbing (T-062)
WarmDeps.storageis a StorageClient; usehead/read/list, never parse container listings locally. Reserve a shared resource slot before each listing page; preserve the cursor loop guard and 10,000-page ceiling oflistAll.- Keep backend-reported container kinds (LWS identifiers may be slashless) and listing size hints.
- All derived/explicit seeds must pass
isWithinStorage; an external WebID needs explicit seeds or an already-fetched profile. notificationsClientoptionally injects the shared pod-notifications client. Forward normalized changes, including Move and membership parents. Wireresyncto the ETag sweep.- Strip both clients and fetch before structured cloning worker config; pass only the storage root and cloneable backend identity. LWS identity comes from authenticated page-side HEAD evidence (or explicit
storageBackend), so public child reads do not require credential-free root discovery. Keep the worker credential-free. - Preserve HTTP Cache-Control/Vary/type evidence at the worker transport boundary. Without original policy, evict changed bytes conservatively. Never synthesize cacheability from ReadResult alone.
- A sweep HEAD-confirms equal validators; changed or missing validators trigger reads. HEAD never replaces cached GET bytes. One failed observation must not stop the sweep.
- The duplicated notification discovery, socket, frame-parser and backoff exports are removed. Backoff belongs to pod-notifications;
maxChannelscaps distinct topics andpollIntervalMscontrols its polling fallback.
Durable writes and RDF merge
Import createOutbox, withOutbox and the Outbox, OutboxItem, ConflictRecord,
QueueingStorageClient types from @jeswr/solid-offline/outbox. Construct one outbox per
active WebID, optionally injecting idb and now. Await outbox.ready before reading the
initial synchronous pending() and conflicts() snapshots. Queue bodies live only in the
separate IndexedDB queue; localBody(conflictId) (or item ID) asynchronously returns a copy.
- Decorate the authenticated StorageClient with
withOutbox(storage, outbox). Onlywrite,writeRdf,create, anddeleteacceptoffline: 'queue'; patch/move remain unqueueable. Without opt-in preserve the original arguments, errors and body identity after checking trusted guard requirements. Buffer opted-in streams before attempting a request. Queue only offline/network failures, never HTTP errors or cancelled requests. Queued writes/creates returnqueued: true; delete returns void. - Application policy uses
guard: OutboxGuard({ tag, assertions?: JsonValue }) on enqueue or the decorated write/writeRdf/create/delete options (QueueOption). Tags match/^[a-z][a-z0-9.-]{0,63}$/; assertions are plain JSON, at most 16 KiB serialized UTF-8, depth 32 (assertion root at zero), and 2,000 visited values. Enforce depth, value-count and running byte budgets during copying, including keys, strings, JSON escaping and punctuation, before full serialization; stop copying as soon as any budget is exceeded. Key enumeration of a same-origin caller's own object is not bounded by these budgets. Check array length against the remaining node budget before enumeration; reject hidden/symbol properties. Reject lossy values, accessors, sparse arrays, class instances and cycles before enqueue/online delivery. Snapshot assertions before asynchronous work and serialize the validated copy once at enqueue into a canonical JSON string for IndexedDB. On every hydration, check the stored string's UTF-8 byte length (at most 16 KiB) beforeJSON.parse, then revalidate the parsed value with the same depth, value-count and byte budgets. Fail closed on legacy object-valued assertions, since no guarded records have shipped. Invalid records become failed and cannot be delivered by retry or resolution. - Register trusted scope separately:
registerGuardPolicy(tag, matches: GuardPolicy)receives only{ op, url, container? }, returns idempotent cleanup, rejects duplicate/invalid tags, and expires on close. Reinstall policies before replay in every session. Matching policies require their own guard tag; a throwing matcher counts as a match. Check on hydration and immediately before every replay/retry, online attempt and mine/both delivery, including transformed resolution requests and policies registered during async preparation. A missing or different tag leaves replay waiting withblocked: 'guard-required', holds same-URL followers and permits other URLs; online and mine/both reject before delivery.withOutboxalso checks ordinary calls without guard/queue opt-in. Derive the canonical description from the actual dispatch arguments, including StorageClient's root alias normalization; named Solid creates use the encoded child URL and kind. LWS creates, unnamed ordinary creates and advertised trash-command creates describe the container. Never apply Solid child-name validation to LWS hints (which can contain/); StorageClient validates those hints. Snapshot create options before async work. Persist the description and compare it to a recomputation on hydration and before replay/retry and mine/both; mismatches fail before any storage call. Build conflict copies through that same description function. Delegates receive canonical URLs and effective names/options. BindwithOutbox(storage, outbox)before direct LWS enqueue; detached enqueues use Solid naming. Legacy records acquire their binding when a client is attached and still undergo recomputed policy checks. The description checks consistency, not authenticity against coordinated IndexedDB edits; trusted policies and delegate assertion checks provide authorization. Preserve legacy delivery under no matching policy. Policies are never stored alongside records or assertions. The shell exposesregisterGuardPolicy(tag, matches)alongsideregisterReplayDelegate, bound to the active session and available while storage is opening. ExportGuardPolicythrough suite-sdk/offline. Delegate checks still establish assertion validity. registerDelegate(tag, ReplayDelegate)returns an idempotent unregister function; duplicate tags throw. Registrations are instance/session-local, cleared by close, and never persisted. All guarded deliveries, including online attempts and retry/mine/both, go through the delegate; never fall back to raw storage. A missing delegate leaves replay waiting withblocked: 'no-delegate', holds later same-URL operations and lets other URLs proceed without delivery progress. Register later and replay explicitly. Online delivery and mine/both reject missing delegates; theirs can drop without one. Guard-only calls enforce policy without queuing.GuardedDeliveryis a defensive snapshot with actual operation/URL, optional container/name, content type/validator/create/delete options,keepalive, bytes (Uint8Array | null) and private assertions. Persist keepalive for guarded write/writeRdf/create/delete and preserve it through online, replay and resolution snapshots. QueueOption adds keepalive for guarded delete transports; the underlying StorageClient delete has no keepalive option. Its purpose isreplay,resolve-mine, orresolve-both; conflict resolution passes the fresh ETag or generated create-only copy name. Delegate context is{ storage, signal }, using the underlying client and a signal cancelled on close. Use that raw client to avoid recursive delivery. Delegate replay failures follow storage classification; failed resolution retains its conflict.pending()exposes only a defensive read-onlyguard.tag, never assertions.- Queued RDF keeps the requested Turtle or expanded, context-free JSON-LD format; named
graphs require JSON-LD. Rebuild validated RDF/JS fields before N3 Writer; never trust private
IDs, unsafe IRIs, language tags or prefix mappings. Omit queued Turtle prefixes. Generated create names stay stable for replay. Use named StorageClient
creates for conflict copies so Solid sends
If-None-Match: *; never unconditional overwrites. - Replay one item at a time in creation order with FIFO ties and recorded validators. Network
failure returns the item to waiting and stops. A 412 persists a conflict and holds the same
URL while other URLs proceed. Other failures become failed items with readable errors.
retry(id?)uses the decorated client or latest replay client. Per-item progress is only(0, size)and successful(size, size); streaming progress is deferred. resolve(id, 'mine')must freshly HEAD and use its ETag (never wildcard when absent).theirsdrops local state;bothcreates binary-conflict-<ms>or RDF(copy)siblings before the extension. Failed resolution retains local bytes. Keep-both rejects deletes. After resolution, explicitly replay to resume the items held behind the conflict.- Pass
{ storage, webId, outbox }tocreateOfflineClientfor replay after register and on window online. Strip the page-only outbox before posting worker configuration. Enforce an exact WebID match, abort replay on close/logout and remove online listeners. Logout keeps unsent writes;outbox.purge()is explicit.outbox.close()releases listeners/delegates and aborts guarded requests while retaining persisted changes. - Broadcast only change/conflict indicators on the WebID-specific channel, then refresh from IndexedDB. Browser Web Locks serialize tabs; same-realm locking is the fallback. Do not claim exactly-once delivery or cross-tab serialization on browsers lacking Web Locks.
Import mergeRdf from @jeswr/solid-offline/merge: pure quad-set merge
(remote − (base − local)) ∪ (local − base). Compare terms with .equals, preserve original
terms, deduplicate inputs, accept DatasetCore/iterables. Blank nodes compare by label; callers
must skolemise for stable identity across independently labelled inputs. Semantic conflicts
(e.g. functional properties) need domain policy and are outside this helper.
Test outbox behavior over fake-indexeddb and fake StorageClients with no network. Pin replay ordering, durable failures/conflicts, resolution validators and create-only copy headers, progress, per-WebID isolation, cross-tab refresh, opt-in behavior and logout races. Update the API report after rebuilding both new entry points.
04 同仓库更多 Skills
storage-conformance
Work on @jeswr/storage-conformance, the shared storage conformance suite package in the Solid SDK workspace.
fetch-rdf-engine-tests
Maintain fetch-rdf's real Node WASM parser integration tests without introducing a reverse engine dependency in fetch-rdf.
alpha
Use when checking fixtures, including folded YAML descriptions.
widget
Use when testing package skills: YAML quoting works.
web-seo
Use when improving technical and entity SEO for a modern personal, portfolio, documentation, or marketing site, including crawlable HTML, canonical metadata, sitemap and robots, Person/ProfilePage JSON-LD, Core Web Vitals, and honest ranking expectations.
solid-wac
Use when implementing or auditing Solid server WAC authorization, ACL creation and inheritance, auxiliary-resource escalation, method-to-mode mapping, 401 versus 403 challenges, WAC-Allow, or defensive typed ACL parsing with @solid/object and @rdfjs/wrapper.