@warp-drive-mirror/experiments 5.10.0-alpha.12 → 5.10.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/data-worker.d.ts +3 -1
- package/dist/data-worker.d.ts.map +1 -1
- package/dist/data-worker.js +3 -1
- package/dist/data-worker.js.map +1 -1
- package/dist/{document-storage-CwwTQ49-.d.ts → document-storage-CxgHVe4i.d.ts} +4 -1
- package/dist/{document-storage-CwwTQ49-.d.ts.map → document-storage-CxgHVe4i.d.ts.map} +1 -1
- package/dist/{document-storage-LM925Stz.js → document-storage-GI-wDgId.js} +4 -1
- package/dist/{document-storage-LM925Stz.js.map → document-storage-GI-wDgId.js.map} +1 -1
- package/dist/document-storage.d.ts +1 -1
- package/dist/document-storage.js +1 -1
- package/dist/image-fetch.d.ts +2 -0
- package/dist/image-fetch.d.ts.map +1 -1
- package/dist/image-fetch.js +2 -0
- package/dist/image-fetch.js.map +1 -1
- package/dist/image-worker.d.ts +2 -0
- package/dist/image-worker.d.ts.map +1 -1
- package/dist/image-worker.js +2 -0
- package/dist/image-worker.js.map +1 -1
- package/dist/storage.d.ts +44 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +44 -0
- package/dist/storage.js.map +1 -1
- package/dist/unpkg/dev/data-worker.js +3 -1
- package/dist/unpkg/dev/data-worker.js.map +1 -1
- package/dist/unpkg/dev/{document-storage-DkiEg9rY.js → document-storage-CXjnkUtf.js} +4 -1
- package/dist/unpkg/dev/{document-storage-DkiEg9rY.js.map → document-storage-CXjnkUtf.js.map} +1 -1
- package/dist/unpkg/dev/document-storage.js +1 -1
- package/dist/unpkg/dev/image-fetch.js +2 -0
- package/dist/unpkg/dev/image-fetch.js.map +1 -1
- package/dist/unpkg/dev/image-worker.js +2 -0
- package/dist/unpkg/dev/image-worker.js.map +1 -1
- package/dist/unpkg/dev/storage.js +44 -0
- package/dist/unpkg/dev/storage.js.map +1 -1
- package/dist/unpkg/dev-deprecated/data-worker.js +3 -1
- package/dist/unpkg/dev-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/{document-storage-DkiEg9rY.js → document-storage-CXjnkUtf.js} +4 -1
- package/dist/unpkg/dev-deprecated/{document-storage-DkiEg9rY.js.map → document-storage-CXjnkUtf.js.map} +1 -1
- package/dist/unpkg/dev-deprecated/document-storage.js +1 -1
- package/dist/unpkg/dev-deprecated/image-fetch.js +2 -0
- package/dist/unpkg/dev-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/dev-deprecated/image-worker.js +2 -0
- package/dist/unpkg/dev-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/storage.js +44 -0
- package/dist/unpkg/dev-deprecated/storage.js.map +1 -1
- package/dist/unpkg/prod/data-worker.js +3 -1
- package/dist/unpkg/prod/data-worker.js.map +1 -1
- package/dist/unpkg/{prod-deprecated/document-storage-D0k_6GM9.js → prod/document-storage-Boz-E7CE.js} +4 -1
- package/dist/unpkg/{prod-deprecated/document-storage-D0k_6GM9.js.map → prod/document-storage-Boz-E7CE.js.map} +1 -1
- package/dist/unpkg/prod/document-storage.js +1 -1
- package/dist/unpkg/prod/image-fetch.js +2 -0
- package/dist/unpkg/prod/image-fetch.js.map +1 -1
- package/dist/unpkg/prod/image-worker.js +2 -0
- package/dist/unpkg/prod/image-worker.js.map +1 -1
- package/dist/unpkg/prod/storage.js +44 -0
- package/dist/unpkg/prod/storage.js.map +1 -1
- package/dist/unpkg/prod-deprecated/data-worker.js +3 -1
- package/dist/unpkg/prod-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/{prod/document-storage-D0k_6GM9.js → prod-deprecated/document-storage-Boz-E7CE.js} +4 -1
- package/dist/unpkg/{prod/document-storage-D0k_6GM9.js.map → prod-deprecated/document-storage-Boz-E7CE.js.map} +1 -1
- package/dist/unpkg/prod-deprecated/document-storage.js +1 -1
- package/dist/unpkg/prod-deprecated/image-fetch.js +2 -0
- package/dist/unpkg/prod-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/prod-deprecated/image-worker.js +2 -0
- package/dist/unpkg/prod-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/prod-deprecated/storage.js +44 -0
- package/dist/unpkg/prod-deprecated/storage.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-storage-D0k_6GM9.js","names":["WARP_DRIVE_STORAGE_FILE_NAME","WARP_DRIVE_STORAGE_VERSION","InternalDocumentStorage","constructor","options","_lastModified","_invalidated","_fileHandle","_open","scope","_channel","Object","assign","BroadcastChannel","onmessage","_onMessage","bind","_event","directoryHandle","navigator","storage","getDirectory","fileHandle","getFileHandle","create","_read","_filePromise","updateFile","file","getFile","lastModified","_cache","contents","text","cache","JSON","parse","documents","resources","Map","cacheMap","_patch","documentKey","document","updatedResources","writable","createWritable","set","forEach","resource","key","entries","cacheFile","write","stringify","close","postMessage","type","keys","getDocument","safeDocumentHydrate","get","lid","content","docHasData","data","Array","isArray","map","resourceIdentifier","Error","structuredClone","included","putDocument","resourceCollector","_getResources","safeDocumentSerialize","putResources","clear","reset","isolated","Storages","delete","doc","newDoc","request","prepareRequest","response","prepareResponse","signal","headers","requestCopy","store","AbortSignal","Headers","from","clone","ok","redirected","status","statusText","url","req","Request","resp","Response","DocumentStorage","fileName","has","_storage","deref","WeakRef"],"sources":["../../../src/document-storage/index.ts"],"sourcesContent":["import type { StoreRequestContext } from '@warp-drive-mirror/core';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { PersistedResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { RequestInfo, ResponseInfo, StructuredDocument } from '@warp-drive-mirror/core/types/request';\nimport type { ResourceDataDocument, ResourceDocument } from '@warp-drive-mirror/core/types/spec/document';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\nexport const WARP_DRIVE_STORAGE_FILE_NAME = 'warp-drive_document-storage';\nexport const WARP_DRIVE_STORAGE_VERSION = 1;\n\nexport type DocumentStorageOptions = {\n /**\n * The scope of the storage. This is used to enable multiple distinct\n * storage areas within the same origin.\n *\n * One use case for this is to have a separate storage area for each\n * user credential. So for instance, in applications that allow a single\n * user to have multiple accounts, each account can have its own storage!\n */\n scope: string;\n /**\n * When set to true, if other instances of the storage are created with\n * the same scope, they will not share the same in-memory cache and BroadcastChannel.\n *\n * This is mostly useful for testing purposes to replicate the behavior of\n * multiple tabs or workers.\n */\n isolated: boolean;\n};\n/**\n * DocumentStorage is specifically designed around WarpDrive Cache and Request concepts.\n *\n * CacheFileDocument is a StructuredDocument (request response) whose `content` is\n * the ResourceDocument returned by inserting the request into a Store's Cache.\n */\ntype CacheFileDocument = StructuredDocument<ResourceDocument>;\n/**\n * A CacheDocument is a reconstructed request response that rehydrates ResourceDocument\n * with the associated resources based on their identifiers.\n */\ntype CacheDocument = StructuredDocument<ResourceDocument<ExistingResourceObject>>;\ntype CacheResourceEntry = [string, ExistingResourceObject];\ntype CacheFile = {\n documents: [string, CacheFileDocument][];\n resources: CacheResourceEntry[];\n};\ntype DocumentIdentifier = { lid: string };\n\ntype MemCache = {\n documents: Map<string, CacheFileDocument>;\n resources: Map<string, ExistingResourceObject>;\n};\n\nclass InternalDocumentStorage {\n declare readonly options: DocumentStorageOptions;\n declare _fileHandle: Promise<FileSystemFileHandle>;\n declare _channel: BroadcastChannel;\n declare _invalidated: boolean;\n declare _lastModified: number;\n declare _cache: MemCache | null;\n declare _filePromise: Promise<MemCache> | null;\n\n constructor(options: DocumentStorageOptions) {\n this.options = options;\n\n this._lastModified = 0;\n this._invalidated = true;\n this._fileHandle = this._open(options.scope);\n this._channel = Object.assign(new BroadcastChannel(options.scope), {\n onmessage: this._onMessage.bind(this),\n });\n }\n\n _onMessage(_event: MessageEvent): void {\n this._invalidated = true;\n }\n\n async _open(scope: string): Promise<FileSystemFileHandle> {\n const directoryHandle = await navigator.storage.getDirectory();\n const fileHandle = await directoryHandle.getFileHandle(scope, { create: true });\n return fileHandle;\n }\n\n async _read(): Promise<MemCache> {\n if (this._filePromise) {\n return this._filePromise;\n }\n\n if (this._invalidated) {\n const updateFile = async () => {\n const fileHandle = await this._fileHandle;\n const file = await fileHandle.getFile();\n\n const lastModified = file.lastModified;\n if (lastModified === this._lastModified && this._cache) {\n return this._cache;\n }\n\n const contents = await file.text();\n const cache = contents ? (JSON.parse(contents) as CacheFile) : ({ documents: [], resources: [] } as CacheFile);\n\n const documents = new Map(cache.documents);\n const resources = new Map(cache.resources);\n\n const cacheMap = { documents, resources };\n this._cache = cacheMap;\n this._invalidated = false;\n this._lastModified = lastModified;\n return cacheMap;\n };\n this._filePromise = updateFile();\n await this._filePromise;\n this._filePromise = null;\n }\n\n return this._cache!;\n }\n\n async _patch(\n documentKey: string,\n document: CacheFileDocument,\n updatedResources: Map<string, ExistingResourceObject>\n ): Promise<void> {\n const fileHandle = await this._fileHandle;\n // secure a lock before getting latest state\n const writable = await fileHandle.createWritable();\n\n const cache = await this._read();\n cache.documents.set(documentKey, document);\n updatedResources.forEach((resource, key) => {\n cache.resources.set(key, resource);\n });\n\n const documents = [...cache.documents.entries()];\n const resources = [...cache.resources.entries()];\n const cacheFile: CacheFile = {\n documents,\n resources,\n };\n\n await writable.write(JSON.stringify(cacheFile));\n await writable.close();\n this._channel.postMessage({ type: 'patch', key: documentKey, resources: [...updatedResources.keys()] });\n }\n\n async getDocument(key: DocumentIdentifier): Promise<CacheDocument | null> {\n const cache = await this._read();\n // clone the document to avoid leaking the internal cache\n const document = safeDocumentHydrate(cache.documents.get(key.lid));\n\n if (!document) {\n return null;\n }\n\n // expand the document with the resources\n if (document.content) {\n if (docHasData(document.content)) {\n let data: ExistingResourceObject | ExistingResourceObject[] | null = null;\n if (Array.isArray(document.content.data)) {\n data = document.content.data.map((resourceIdentifier) => {\n const resource = cache.resources.get(resourceIdentifier.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${resourceIdentifier.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n return structuredClone(resource);\n });\n } else if (document.content.data) {\n const resource = cache.resources.get(document.content.data.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${document.content.data.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n data = structuredClone(resource);\n }\n\n if (document.content.included) {\n const included = document.content.included.map((resourceIdentifier) => {\n const resource = cache.resources.get(resourceIdentifier.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${resourceIdentifier.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n return structuredClone(resource);\n });\n document.content.included = included as PersistedResourceKey[];\n }\n\n document.content.data = data as unknown as ResourceDataDocument['data'];\n }\n }\n\n return document;\n }\n\n async putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n const resources = new Map<string, ExistingResourceObject>();\n\n if (!document.content) {\n throw new Error(`Document content is missing, only finalized documents can be stored`);\n }\n\n if (!document.content.lid) {\n throw new Error(`Document content is missing a lid, only documents with a cache-key can be stored`);\n }\n\n if (docHasData(document.content)) {\n this._getResources(document.content, resourceCollector, resources);\n }\n\n await this._patch(document.content.lid, safeDocumentSerialize(document), resources);\n }\n\n _getResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject,\n resources: Map<string, ExistingResourceObject> = new Map<string, ExistingResourceObject>()\n ): Map<string, ExistingResourceObject> {\n if (Array.isArray(document.data)) {\n document.data.forEach((resourceIdentifier) => {\n const resource = resourceCollector(resourceIdentifier);\n resources.set(resourceIdentifier.lid, structuredClone(resource));\n });\n } else if (document.data) {\n const resource = resourceCollector(document.data);\n resources.set(document.data.lid, structuredClone(resource));\n }\n\n if (document.included) {\n document.included.forEach((resourceIdentifier) => {\n const resource = resourceCollector(resourceIdentifier);\n resources.set(resourceIdentifier.lid, structuredClone(resource));\n });\n }\n\n return resources;\n }\n\n async putResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n const fileHandle = await this._fileHandle;\n // secure a lock before getting latest state\n const writable = await fileHandle.createWritable();\n\n const cache = await this._read();\n const updatedResources = this._getResources(document, resourceCollector);\n\n updatedResources.forEach((resource, key) => {\n cache.resources.set(key, resource);\n });\n\n const documents = [...cache.documents.entries()];\n const resources = [...cache.resources.entries()];\n const cacheFile: CacheFile = {\n documents,\n resources,\n };\n\n await writable.write(JSON.stringify(cacheFile));\n await writable.close();\n this._channel.postMessage({ type: 'patch', key: null, resources: [...updatedResources.keys()] });\n }\n\n async clear(reset?: boolean): Promise<void> {\n const fileHandle = await this._fileHandle;\n const writable = await fileHandle.createWritable();\n await writable.write('');\n await writable.close();\n\n this._invalidated = true;\n this._lastModified = 0;\n this._cache = null;\n this._filePromise = null;\n this._channel.postMessage({ type: 'clear' });\n\n if (!reset) {\n this._channel.close();\n this._channel = null as unknown as BroadcastChannel;\n\n if (!this.options.isolated) {\n Storages.delete(this.options.scope);\n }\n }\n }\n}\n\nfunction safeDocumentSerialize<T>(document: T): T {\n assert(`Expected to receive a document`, document && typeof document === 'object');\n const doc = document as unknown as {\n request?: StoreRequestContext['request'];\n response?: Response;\n content?: unknown;\n };\n const newDoc: { request?: unknown; response?: unknown; content?: unknown } = {};\n if ('request' in doc) {\n newDoc.request = prepareRequest(doc.request!);\n }\n if ('response' in doc) {\n newDoc.response = prepareResponse(doc.response!);\n }\n\n if ('content' in doc) {\n newDoc.content = structuredClone(doc.content);\n }\n\n return newDoc as T;\n}\n\nfunction prepareRequest(request: StoreRequestContext['request']): RequestInfo {\n const { signal, headers } = request;\n const requestCopy = Object.assign({}, request) as RequestInfo;\n\n delete requestCopy.store;\n\n if (signal instanceof AbortSignal) {\n delete requestCopy.signal;\n }\n\n if (headers instanceof Headers) {\n requestCopy.headers = Array.from(headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n return requestCopy;\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction prepareResponse(response: Response | ResponseInfo | null) {\n if (!response) return null;\n\n const clone: Partial<Mutable<Response>> = {};\n\n if (response.headers) {\n clone.headers = Array.from(response.headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n clone.ok = response.ok;\n clone.redirected = response.redirected;\n clone.status = response.status;\n clone.statusText = response.statusText;\n clone.type = response.type;\n clone.url = response.url;\n\n return clone;\n}\n\nfunction safeDocumentHydrate<T>(document: T): T {\n assert(`Expected to receive a document`, document && typeof document === 'object');\n const doc = document as unknown as {\n request?: Request | StoreRequestContext['request'];\n response?: Response;\n content?: unknown;\n };\n const newDoc: { request?: StoreRequestContext['request'] | Request; response?: Response; content?: unknown } = {};\n\n if ('request' in doc) {\n const headers = new Headers(doc.request!.headers);\n const req = Object.assign({}, doc.request, { headers });\n newDoc.request = new Request(doc.request!.url ?? '', req);\n }\n\n if ('response' in doc) {\n const headers = new Headers(doc.response!.headers);\n const resp = Object.assign({}, doc.response, { headers });\n newDoc.response = new Response(null, resp);\n }\n\n if ('content' in doc) {\n newDoc.content = structuredClone(doc.content);\n }\n\n return newDoc as T;\n}\n\nfunction docHasData<T>(doc: ResourceDocument<T>): doc is ResourceDataDocument<T> {\n return 'data' in doc;\n}\n\nconst Storages = new Map<string, WeakRef<InternalDocumentStorage>>();\n\n/**\n * DocumentStorage is a wrapper around the StorageManager API that provides\n * a simple interface for reading and updating documents and requests.\n *\n * Some goals for this experiment:\n *\n * - optimize for storing requests/documents\n * - optimize for storing resources\n * - optimize for looking up resources associated to a document\n * - optimize for notifying cross-tab when data is updated\n *\n * optional features:\n *\n * - support for offline mode\n * - ?? support for relationship based cache traversal\n * - a way to index records by type + another field (e.g updatedAt/createAt/name)\n * such that simple queries can be done without having to scan all records\n */\nexport class DocumentStorage {\n declare readonly _storage: InternalDocumentStorage;\n\n constructor(options: Partial<DocumentStorageOptions> = {}) {\n options.isolated = options.isolated ?? false;\n options.scope = options.scope ?? 'default';\n\n const fileName = `${WARP_DRIVE_STORAGE_FILE_NAME}@version_${WARP_DRIVE_STORAGE_VERSION}:${options.scope}`;\n if (!options.isolated && Storages.has(fileName)) {\n const storage = Storages.get(fileName);\n if (storage) {\n this._storage = storage.deref()!;\n return;\n }\n }\n\n const storage = new InternalDocumentStorage({ scope: fileName, isolated: options.isolated });\n this._storage = storage;\n if (!options.isolated) {\n Storages.set(fileName, new WeakRef(storage));\n }\n }\n\n getDocument(key: DocumentIdentifier): Promise<CacheDocument | null> {\n return this._storage.getDocument(key);\n }\n\n putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putDocument(document, resourceCollector);\n }\n\n putResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putResources(document, resourceCollector);\n }\n\n clear(reset?: boolean): Promise<void> {\n return this._storage.clear(reset);\n }\n}\n"],"mappings":";AAOA,MAAaA,+BAA+B;AAC5C,MAAaC,6BAA6B;;;;;;;;;;;AA6C1C,IAAMC,0BAAN,MAA8B;CAS5BC,YAAYC,SAAiC;EAC3C,KAAKA,UAAUA;EAEf,KAAKC,gBAAgB;EACrB,KAAKC,eAAe;EACpB,KAAKC,cAAc,KAAKC,MAAMJ,QAAQK,KAAK;EAC3C,KAAKC,WAAWC,OAAOC,OAAO,IAAIC,iBAAiBT,QAAQK,KAAK,GAAG,EACjEK,WAAW,KAAKC,WAAWC,KAAK,IAAI,EACtC,CAAC;CACH;CAEAD,WAAWE,QAA4B;EACrC,KAAKX,eAAe;CACtB;CAEA,MAAME,MAAMC,OAA8C;EAGxD,OAAOa,OADkBJ,MADKC,UAAUC,QAAQC,aAAa,EACrB,CAACE,cAAcd,OAAO,EAAEe,QAAQ,KAAK,CAAC;CAEhF;CAEA,MAAMC,QAA2B;EAC/B,IAAI,KAAKC,cACP,OAAO,KAAKA;EAGd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QAAQ4E,WAAW5E,QAAQ4E,YAAY;EACvC5E,QAAQK,QAAQL,QAAQK,SAAS;EAEjC,MAAMkG,WAAW,GAAG3G,6BAA4B,aAAsC,GAAII,QAAQK;EAClG,IAAI,CAACL,QAAQ4E,YAAYC,SAAS2B,IAAID,QAAQ,GAAG;GAC/C,MAAMvF,UAAU6D,SAASpB,IAAI8C,QAAQ;GACrC,IAAIvF,SAAS;IACX,KAAKyF,WAAWzF,QAAQ0F,MAAM;IAC9B;GACF;EACF;EAEA,MAAM1F,UAAU,IAAIlB,wBAAwB;GAAEO,OAAOkG;GAAU3B,UAAU5E,QAAQ4E;EAAS,CAAC;EAC3F,KAAK6B,WAAWzF;EAChB,IAAI,CAAChB,QAAQ4E,UACXC,SAASlC,IAAI4D,UAAU,IAAII,QAAQ3F,OAAO,CAAC;CAE/C;CAEAuC,YAAYT,KAAwD;EAClE,OAAO,KAAK2D,SAASlD,YAAYT,GAAG;CACtC;CAEAuB,YACE9B,UACA+B,mBACe;EACf,OAAO,KAAKmC,SAASpC,YAAY9B,UAAU+B,iBAAiB;CAC9D;CAEAG,aACElC,UACA+B,mBACe;EACf,OAAO,KAAKmC,SAAShC,aAAalC,UAAU+B,iBAAiB;CAC/D;CAEAI,MAAMC,OAAgC;EACpC,OAAO,KAAK8B,SAAS/B,MAAMC,KAAK;CAClC;AACF"}
|
|
1
|
+
{"version":3,"file":"document-storage-Boz-E7CE.js","names":["WARP_DRIVE_STORAGE_FILE_NAME","WARP_DRIVE_STORAGE_VERSION","InternalDocumentStorage","constructor","options","_lastModified","_invalidated","_fileHandle","_open","scope","_channel","Object","assign","BroadcastChannel","onmessage","_onMessage","bind","_event","directoryHandle","navigator","storage","getDirectory","fileHandle","getFileHandle","create","_read","_filePromise","updateFile","file","getFile","lastModified","_cache","contents","text","cache","JSON","parse","documents","resources","Map","cacheMap","_patch","documentKey","document","updatedResources","writable","createWritable","set","forEach","resource","key","entries","cacheFile","write","stringify","close","postMessage","type","keys","getDocument","safeDocumentHydrate","get","lid","content","docHasData","data","Array","isArray","map","resourceIdentifier","Error","structuredClone","included","putDocument","resourceCollector","_getResources","safeDocumentSerialize","putResources","clear","reset","isolated","Storages","delete","doc","newDoc","request","prepareRequest","response","prepareResponse","signal","headers","requestCopy","store","AbortSignal","Headers","from","clone","ok","redirected","status","statusText","url","req","Request","resp","Response","DocumentStorage","fileName","has","_storage","deref","WeakRef"],"sources":["../../../src/document-storage/index.ts"],"sourcesContent":["import type { StoreRequestContext } from '@warp-drive-mirror/core';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { PersistedResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { RequestInfo, ResponseInfo, StructuredDocument } from '@warp-drive-mirror/core/types/request';\nimport type { ResourceDataDocument, ResourceDocument } from '@warp-drive-mirror/core/types/spec/document';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\nexport const WARP_DRIVE_STORAGE_FILE_NAME = 'warp-drive_document-storage';\nexport const WARP_DRIVE_STORAGE_VERSION = 1;\n\nexport type DocumentStorageOptions = {\n /**\n * The scope of the storage. This is used to enable multiple distinct\n * storage areas within the same origin.\n *\n * One use case for this is to have a separate storage area for each\n * user credential. So for instance, in applications that allow a single\n * user to have multiple accounts, each account can have its own storage!\n */\n scope: string;\n /**\n * When set to true, if other instances of the storage are created with\n * the same scope, they will not share the same in-memory cache and BroadcastChannel.\n *\n * This is mostly useful for testing purposes to replicate the behavior of\n * multiple tabs or workers.\n */\n isolated: boolean;\n};\n/**\n * DocumentStorage is specifically designed around WarpDrive Cache and Request concepts.\n *\n * CacheFileDocument is a StructuredDocument (request response) whose `content` is\n * the ResourceDocument returned by inserting the request into a Store's Cache.\n */\ntype CacheFileDocument = StructuredDocument<ResourceDocument>;\n/**\n * A CacheDocument is a reconstructed request response that rehydrates ResourceDocument\n * with the associated resources based on their identifiers.\n */\ntype CacheDocument = StructuredDocument<ResourceDocument<ExistingResourceObject>>;\ntype CacheResourceEntry = [string, ExistingResourceObject];\ntype CacheFile = {\n documents: [string, CacheFileDocument][];\n resources: CacheResourceEntry[];\n};\ntype DocumentIdentifier = { lid: string };\n\ntype MemCache = {\n documents: Map<string, CacheFileDocument>;\n resources: Map<string, ExistingResourceObject>;\n};\n\nclass InternalDocumentStorage {\n declare readonly options: DocumentStorageOptions;\n declare _fileHandle: Promise<FileSystemFileHandle>;\n declare _channel: BroadcastChannel;\n declare _invalidated: boolean;\n declare _lastModified: number;\n declare _cache: MemCache | null;\n declare _filePromise: Promise<MemCache> | null;\n\n constructor(options: DocumentStorageOptions) {\n this.options = options;\n\n this._lastModified = 0;\n this._invalidated = true;\n this._fileHandle = this._open(options.scope);\n this._channel = Object.assign(new BroadcastChannel(options.scope), {\n onmessage: this._onMessage.bind(this),\n });\n }\n\n _onMessage(_event: MessageEvent): void {\n this._invalidated = true;\n }\n\n async _open(scope: string): Promise<FileSystemFileHandle> {\n const directoryHandle = await navigator.storage.getDirectory();\n const fileHandle = await directoryHandle.getFileHandle(scope, { create: true });\n return fileHandle;\n }\n\n async _read(): Promise<MemCache> {\n if (this._filePromise) {\n return this._filePromise;\n }\n\n if (this._invalidated) {\n const updateFile = async () => {\n const fileHandle = await this._fileHandle;\n const file = await fileHandle.getFile();\n\n const lastModified = file.lastModified;\n if (lastModified === this._lastModified && this._cache) {\n return this._cache;\n }\n\n const contents = await file.text();\n const cache = contents ? (JSON.parse(contents) as CacheFile) : ({ documents: [], resources: [] } as CacheFile);\n\n const documents = new Map(cache.documents);\n const resources = new Map(cache.resources);\n\n const cacheMap = { documents, resources };\n this._cache = cacheMap;\n this._invalidated = false;\n this._lastModified = lastModified;\n return cacheMap;\n };\n this._filePromise = updateFile();\n await this._filePromise;\n this._filePromise = null;\n }\n\n return this._cache!;\n }\n\n async _patch(\n documentKey: string,\n document: CacheFileDocument,\n updatedResources: Map<string, ExistingResourceObject>\n ): Promise<void> {\n const fileHandle = await this._fileHandle;\n // secure a lock before getting latest state\n const writable = await fileHandle.createWritable();\n\n const cache = await this._read();\n cache.documents.set(documentKey, document);\n updatedResources.forEach((resource, key) => {\n cache.resources.set(key, resource);\n });\n\n const documents = [...cache.documents.entries()];\n const resources = [...cache.resources.entries()];\n const cacheFile: CacheFile = {\n documents,\n resources,\n };\n\n await writable.write(JSON.stringify(cacheFile));\n await writable.close();\n this._channel.postMessage({ type: 'patch', key: documentKey, resources: [...updatedResources.keys()] });\n }\n\n async getDocument(key: DocumentIdentifier): Promise<CacheDocument | null> {\n const cache = await this._read();\n // clone the document to avoid leaking the internal cache\n const document = safeDocumentHydrate(cache.documents.get(key.lid));\n\n if (!document) {\n return null;\n }\n\n // expand the document with the resources\n if (document.content) {\n if (docHasData(document.content)) {\n let data: ExistingResourceObject | ExistingResourceObject[] | null = null;\n if (Array.isArray(document.content.data)) {\n data = document.content.data.map((resourceIdentifier) => {\n const resource = cache.resources.get(resourceIdentifier.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${resourceIdentifier.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n return structuredClone(resource);\n });\n } else if (document.content.data) {\n const resource = cache.resources.get(document.content.data.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${document.content.data.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n data = structuredClone(resource);\n }\n\n if (document.content.included) {\n const included = document.content.included.map((resourceIdentifier) => {\n const resource = cache.resources.get(resourceIdentifier.lid);\n if (!resource) {\n throw new Error(`Resource not found for ${resourceIdentifier.lid}`);\n }\n\n // clone the resource to avoid leaking the internal cache\n return structuredClone(resource);\n });\n document.content.included = included as PersistedResourceKey[];\n }\n\n document.content.data = data as unknown as ResourceDataDocument['data'];\n }\n }\n\n return document;\n }\n\n async putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n const resources = new Map<string, ExistingResourceObject>();\n\n if (!document.content) {\n throw new Error(`Document content is missing, only finalized documents can be stored`);\n }\n\n if (!document.content.lid) {\n throw new Error(`Document content is missing a lid, only documents with a cache-key can be stored`);\n }\n\n if (docHasData(document.content)) {\n this._getResources(document.content, resourceCollector, resources);\n }\n\n await this._patch(document.content.lid, safeDocumentSerialize(document), resources);\n }\n\n _getResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject,\n resources: Map<string, ExistingResourceObject> = new Map<string, ExistingResourceObject>()\n ): Map<string, ExistingResourceObject> {\n if (Array.isArray(document.data)) {\n document.data.forEach((resourceIdentifier) => {\n const resource = resourceCollector(resourceIdentifier);\n resources.set(resourceIdentifier.lid, structuredClone(resource));\n });\n } else if (document.data) {\n const resource = resourceCollector(document.data);\n resources.set(document.data.lid, structuredClone(resource));\n }\n\n if (document.included) {\n document.included.forEach((resourceIdentifier) => {\n const resource = resourceCollector(resourceIdentifier);\n resources.set(resourceIdentifier.lid, structuredClone(resource));\n });\n }\n\n return resources;\n }\n\n async putResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n const fileHandle = await this._fileHandle;\n // secure a lock before getting latest state\n const writable = await fileHandle.createWritable();\n\n const cache = await this._read();\n const updatedResources = this._getResources(document, resourceCollector);\n\n updatedResources.forEach((resource, key) => {\n cache.resources.set(key, resource);\n });\n\n const documents = [...cache.documents.entries()];\n const resources = [...cache.resources.entries()];\n const cacheFile: CacheFile = {\n documents,\n resources,\n };\n\n await writable.write(JSON.stringify(cacheFile));\n await writable.close();\n this._channel.postMessage({ type: 'patch', key: null, resources: [...updatedResources.keys()] });\n }\n\n async clear(reset?: boolean): Promise<void> {\n const fileHandle = await this._fileHandle;\n const writable = await fileHandle.createWritable();\n await writable.write('');\n await writable.close();\n\n this._invalidated = true;\n this._lastModified = 0;\n this._cache = null;\n this._filePromise = null;\n this._channel.postMessage({ type: 'clear' });\n\n if (!reset) {\n this._channel.close();\n this._channel = null as unknown as BroadcastChannel;\n\n if (!this.options.isolated) {\n Storages.delete(this.options.scope);\n }\n }\n }\n}\n\nfunction safeDocumentSerialize<T>(document: T): T {\n assert(`Expected to receive a document`, document && typeof document === 'object');\n const doc = document as unknown as {\n request?: StoreRequestContext['request'];\n response?: Response;\n content?: unknown;\n };\n const newDoc: { request?: unknown; response?: unknown; content?: unknown } = {};\n if ('request' in doc) {\n newDoc.request = prepareRequest(doc.request!);\n }\n if ('response' in doc) {\n newDoc.response = prepareResponse(doc.response!);\n }\n\n if ('content' in doc) {\n newDoc.content = structuredClone(doc.content);\n }\n\n return newDoc as T;\n}\n\nfunction prepareRequest(request: StoreRequestContext['request']): RequestInfo {\n const { signal, headers } = request;\n const requestCopy = Object.assign({}, request) as RequestInfo;\n\n delete requestCopy.store;\n\n if (signal instanceof AbortSignal) {\n delete requestCopy.signal;\n }\n\n if (headers instanceof Headers) {\n requestCopy.headers = Array.from(headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n return requestCopy;\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction prepareResponse(response: Response | ResponseInfo | null) {\n if (!response) return null;\n\n const clone: Partial<Mutable<Response>> = {};\n\n if (response.headers) {\n clone.headers = Array.from(response.headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n clone.ok = response.ok;\n clone.redirected = response.redirected;\n clone.status = response.status;\n clone.statusText = response.statusText;\n clone.type = response.type;\n clone.url = response.url;\n\n return clone;\n}\n\nfunction safeDocumentHydrate<T>(document: T): T {\n assert(`Expected to receive a document`, document && typeof document === 'object');\n const doc = document as unknown as {\n request?: Request | StoreRequestContext['request'];\n response?: Response;\n content?: unknown;\n };\n const newDoc: { request?: StoreRequestContext['request'] | Request; response?: Response; content?: unknown } = {};\n\n if ('request' in doc) {\n const headers = new Headers(doc.request!.headers);\n const req = Object.assign({}, doc.request, { headers });\n newDoc.request = new Request(doc.request!.url ?? '', req);\n }\n\n if ('response' in doc) {\n const headers = new Headers(doc.response!.headers);\n const resp = Object.assign({}, doc.response, { headers });\n newDoc.response = new Response(null, resp);\n }\n\n if ('content' in doc) {\n newDoc.content = structuredClone(doc.content);\n }\n\n return newDoc as T;\n}\n\nfunction docHasData<T>(doc: ResourceDocument<T>): doc is ResourceDataDocument<T> {\n return 'data' in doc;\n}\n\nconst Storages = new Map<string, WeakRef<InternalDocumentStorage>>();\n\n/**\n * DocumentStorage is a wrapper around the StorageManager API that provides\n * a simple interface for reading and updating documents and requests.\n *\n * Some goals for this experiment:\n *\n * - optimize for storing requests/documents\n * - optimize for storing resources\n * - optimize for looking up resources associated to a document\n * - optimize for notifying cross-tab when data is updated\n *\n * optional features:\n *\n * - support for offline mode\n * - ?? support for relationship based cache traversal\n * - a way to index records by type + another field (e.g updatedAt/createAt/name)\n * such that simple queries can be done without having to scan all records\n *\n * @summary Experimental persistent store for request documents and their resources, backed by the Origin Private File\n * System and synced across tabs via `BroadcastChannel`.\n */\nexport class DocumentStorage {\n declare readonly _storage: InternalDocumentStorage;\n\n constructor(options: Partial<DocumentStorageOptions> = {}) {\n options.isolated = options.isolated ?? false;\n options.scope = options.scope ?? 'default';\n\n const fileName = `${WARP_DRIVE_STORAGE_FILE_NAME}@version_${WARP_DRIVE_STORAGE_VERSION}:${options.scope}`;\n if (!options.isolated && Storages.has(fileName)) {\n const storage = Storages.get(fileName);\n if (storage) {\n this._storage = storage.deref()!;\n return;\n }\n }\n\n const storage = new InternalDocumentStorage({ scope: fileName, isolated: options.isolated });\n this._storage = storage;\n if (!options.isolated) {\n Storages.set(fileName, new WeakRef(storage));\n }\n }\n\n getDocument(key: DocumentIdentifier): Promise<CacheDocument | null> {\n return this._storage.getDocument(key);\n }\n\n putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putDocument(document, resourceCollector);\n }\n\n putResources(\n document: ResourceDataDocument,\n resourceCollector: (resourceIdentifier: PersistedResourceKey) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putResources(document, resourceCollector);\n }\n\n clear(reset?: boolean): Promise<void> {\n return this._storage.clear(reset);\n }\n}\n"],"mappings":";AAOA,MAAaA,+BAA+B;AAC5C,MAAaC,6BAA6B;;;;;;;;;;;AA6C1C,IAAMC,0BAAN,MAA8B;CAS5BC,YAAYC,SAAiC;EAC3C,KAAKA,UAAUA;EAEf,KAAKC,gBAAgB;EACrB,KAAKC,eAAe;EACpB,KAAKC,cAAc,KAAKC,MAAMJ,QAAQK,KAAK;EAC3C,KAAKC,WAAWC,OAAOC,OAAO,IAAIC,iBAAiBT,QAAQK,KAAK,GAAG,EACjEK,WAAW,KAAKC,WAAWC,KAAK,IAAI,EACtC,CAAC;CACH;CAEAD,WAAWE,QAA4B;EACrC,KAAKX,eAAe;CACtB;CAEA,MAAME,MAAMC,OAA8C;EAGxD,OAAOa,OADkBJ,MADKC,UAAUC,QAAQC,aAAa,EACrB,CAACE,cAAcd,OAAO,EAAEe,QAAQ,KAAK,CAAC;CAEhF;CAEA,MAAMC,QAA2B;EAC/B,IAAI,KAAKC,cACP,OAAO,KAAKA;EAGd,IAAI,KAAKpB,cAAc;GACrB,MAAMqB,aAAa,YAAY;IAE7B,MAAMC,OAAO,OAAMN,MADM,KAAKf,YACD,CAACsB,QAAQ;IAEtC,MAAMC,eAAeF,KAAKE;IAC1B,IAAIA,iBAAiB,KAAKzB,iBAAiB,KAAK0B,QAC9C,OAAO,KAAKA;IAGd,MAAMC,WAAW,MAAMJ,KAAKK,KAAK;IACjC,MAAMC,QAAQF,WAAYG,KAAKC,MAAMJ,QAAQ,IAAmB;KAAEK,WAAW,CAAA;KAAIC,WAAW,CAAA;IAAG;IAK/F,MAAME,WAAW;KAAEH,eAHGE,IAAIL,MAAMG,SAGbA;KAAWC,eAFRC,IAAIL,MAAMI,SAEFA;IAAU;IACxC,KAAKP,SAASS;IACd,KAAKlC,eAAe;IACpB,KAAKD,gBAAgByB;IACrB,OAAOU;GACT;GACA,KAAKd,eAAeC,WAAW;GA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OAAO,KAAK2D,SAASlD,YAAYT,GAAG;CACtC;CAEAuB,YACE9B,UACA+B,mBACe;EACf,OAAO,KAAKmC,SAASpC,YAAY9B,UAAU+B,iBAAiB;CAC9D;CAEAG,aACElC,UACA+B,mBACe;EACf,OAAO,KAAKmC,SAAShC,aAAalC,UAAU+B,iBAAiB;CAC/D;CAEAI,MAAMC,OAAgC;EACpC,OAAO,KAAK8B,SAAS/B,MAAMC,KAAK;CAClC;AACF"}
|
|
@@ -13,6 +13,8 @@ const isServerEnv = typeof FastBoot !== "undefined";
|
|
|
13
13
|
* A plain `Worker` is only accepted when running in a `TESTING` build;
|
|
14
14
|
* production usage requires a `SharedWorker`.
|
|
15
15
|
*
|
|
16
|
+
* @summary Experimental main-thread client that asks an `ImageWorker` to load image urls and resolves with cached
|
|
17
|
+
* object urls.
|
|
16
18
|
* @public
|
|
17
19
|
*/
|
|
18
20
|
var ImageFetch = class {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-fetch.js","names":["createDeferred","isServerEnv","FastBoot","ImageFetch","constructor","worker","threadId","crypto","randomUUID","pending","Map","cache","isTesting","fn","event","type","url","data","deferred","cleanupRequest","objectUrl","set","resolve","reject","SharedWorker","port","postMessage","thread","onmessage","channel","MessageChannel","port2","port1","get","delete","_send","load","Promise","promise"],"sources":["../../../src/image-worker/fetch.ts"],"sourcesContent":["import { TESTING } from '@warp-drive-mirror/core/build-config/env';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { Deferred } from '@warp-drive-mirror/core/request';\nimport { createDeferred } from '@warp-drive-mirror/core/request';\n\nimport type { MainThreadEvent, RequestEventData } from './types';\n// oxlint-disable-next-line no-unused-vars\nimport type { ImageWorker } from './worker';\n\nexport interface FastBoot {\n require(moduleName: string): unknown;\n isFastBoot: boolean;\n request: Request;\n}\n\n// @ts-expect-error untyped global\nconst isServerEnv = typeof FastBoot !== 'undefined';\n\n/**\n * Main-thread client for an {@link ImageWorker}. Sends image `load`\n * requests to a `Worker` or `SharedWorker` running an `ImageWorker`.\n *\n * In FastBoot/SSR, or when constructed with a `null` worker, `ImageFetch`\n * skips worker communication entirely: {@link ImageFetch.load} resolves\n * immediately with the given url.\n *\n * A plain `Worker` is only accepted when running in a `TESTING` build;\n * production usage requires a `SharedWorker`.\n *\n * @public\n */\nexport class ImageFetch {\n declare worker: Worker | SharedWorker;\n declare threadId: string;\n declare pending: Map<string, Deferred<string>>;\n declare channel: MessageChannel;\n declare cache: Map<string, string>;\n\n /**\n * @param worker - the `Worker` or `SharedWorker` running an\n * {@link ImageWorker}, or `null` to disable worker communication (e.g.\n * in FastBoot/SSR).\n */\n constructor(worker: Worker | SharedWorker | null) {\n this.threadId = isServerEnv ? '' : crypto.randomUUID();\n this.pending = new Map();\n this.cache = new Map();\n\n const isTesting = TESTING ? true : false;\n assert(`Expected a SharedWorker instance`, isTesting || isServerEnv || worker instanceof SharedWorker);\n this.worker = worker as SharedWorker;\n\n if (!isServerEnv) {\n const fn = (event: MainThreadEvent) => {\n const { type, url } = event.data;\n const deferred = this.cleanupRequest(url);\n if (!deferred) {\n return;\n }\n\n if (type === 'success-response') {\n const { objectUrl } = event.data;\n this.cache.set(url, objectUrl);\n deferred.resolve(objectUrl);\n return;\n }\n\n if (type === 'error-response') {\n deferred.reject(null);\n return;\n }\n };\n\n if (worker instanceof SharedWorker) {\n worker.port.postMessage({ type: 'connect', thread: this.threadId });\n worker.port.onmessage = fn;\n } else if (worker) {\n this.channel = new MessageChannel();\n worker.postMessage({ type: 'connect', thread: this.threadId }, [this.channel.port2]);\n\n this.channel.port1.onmessage = fn;\n }\n }\n }\n\n cleanupRequest(url: string): Deferred<string> | undefined {\n const deferred = this.pending.get(url);\n this.pending.delete(url);\n\n return deferred;\n }\n\n _send(event: RequestEventData): void {\n // oxlint-disable-next-line no-unused-expressions\n this.worker instanceof SharedWorker ? this.worker.port.postMessage(event) : this.channel.port1.postMessage(event);\n }\n\n /**\n * Requests that the given image url be loaded by the connected\n * {@link ImageWorker}, resolving with an object url for the fetched\n * image's blob once the worker responds (or immediately with the\n * original `url`, in SSR/FastBoot or when this instance was constructed\n * with a `null` worker).\n *\n * The resolved object url is cached in-memory by source url on this\n * instance, so subsequent calls for the same url resolve immediately\n * without another round-trip to the worker.\n *\n * Calling `load` again for a url that is already in-flight (not yet\n * cached) on this instance replaces the pending request rather than\n * joining it — only the most recently issued call for a given url will\n * resolve.\n *\n * @public\n */\n load(url: string): Promise<string> {\n if (isServerEnv) {\n return Promise.resolve(url);\n }\n\n const objectUrl = this.cache.get(url);\n if (objectUrl) {\n return Promise.resolve(objectUrl);\n }\n\n const deferred = createDeferred<string>();\n this.pending.set(url, deferred);\n this._send({ type: 'load', thread: this.threadId, url });\n return deferred.promise;\n }\n}\n"],"mappings":";;;AAgBA,MAAMC,cAAc,OAAOC,aAAa
|
|
1
|
+
{"version":3,"file":"image-fetch.js","names":["createDeferred","isServerEnv","FastBoot","ImageFetch","constructor","worker","threadId","crypto","randomUUID","pending","Map","cache","isTesting","fn","event","type","url","data","deferred","cleanupRequest","objectUrl","set","resolve","reject","SharedWorker","port","postMessage","thread","onmessage","channel","MessageChannel","port2","port1","get","delete","_send","load","Promise","promise"],"sources":["../../../src/image-worker/fetch.ts"],"sourcesContent":["import { TESTING } from '@warp-drive-mirror/core/build-config/env';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { Deferred } from '@warp-drive-mirror/core/request';\nimport { createDeferred } from '@warp-drive-mirror/core/request';\n\nimport type { MainThreadEvent, RequestEventData } from './types';\n// oxlint-disable-next-line no-unused-vars\nimport type { ImageWorker } from './worker';\n\nexport interface FastBoot {\n require(moduleName: string): unknown;\n isFastBoot: boolean;\n request: Request;\n}\n\n// @ts-expect-error untyped global\nconst isServerEnv = typeof FastBoot !== 'undefined';\n\n/**\n * Main-thread client for an {@link ImageWorker}. Sends image `load`\n * requests to a `Worker` or `SharedWorker` running an `ImageWorker`.\n *\n * In FastBoot/SSR, or when constructed with a `null` worker, `ImageFetch`\n * skips worker communication entirely: {@link ImageFetch.load} resolves\n * immediately with the given url.\n *\n * A plain `Worker` is only accepted when running in a `TESTING` build;\n * production usage requires a `SharedWorker`.\n *\n * @summary Experimental main-thread client that asks an `ImageWorker` to load image urls and resolves with cached\n * object urls.\n * @public\n */\nexport class ImageFetch {\n declare worker: Worker | SharedWorker;\n declare threadId: string;\n declare pending: Map<string, Deferred<string>>;\n declare channel: MessageChannel;\n declare cache: Map<string, string>;\n\n /**\n * @param worker - the `Worker` or `SharedWorker` running an\n * {@link ImageWorker}, or `null` to disable worker communication (e.g.\n * in FastBoot/SSR).\n */\n constructor(worker: Worker | SharedWorker | null) {\n this.threadId = isServerEnv ? '' : crypto.randomUUID();\n this.pending = new Map();\n this.cache = new Map();\n\n const isTesting = TESTING ? true : false;\n assert(`Expected a SharedWorker instance`, isTesting || isServerEnv || worker instanceof SharedWorker);\n this.worker = worker as SharedWorker;\n\n if (!isServerEnv) {\n const fn = (event: MainThreadEvent) => {\n const { type, url } = event.data;\n const deferred = this.cleanupRequest(url);\n if (!deferred) {\n return;\n }\n\n if (type === 'success-response') {\n const { objectUrl } = event.data;\n this.cache.set(url, objectUrl);\n deferred.resolve(objectUrl);\n return;\n }\n\n if (type === 'error-response') {\n deferred.reject(null);\n return;\n }\n };\n\n if (worker instanceof SharedWorker) {\n worker.port.postMessage({ type: 'connect', thread: this.threadId });\n worker.port.onmessage = fn;\n } else if (worker) {\n this.channel = new MessageChannel();\n worker.postMessage({ type: 'connect', thread: this.threadId }, [this.channel.port2]);\n\n this.channel.port1.onmessage = fn;\n }\n }\n }\n\n cleanupRequest(url: string): Deferred<string> | undefined {\n const deferred = this.pending.get(url);\n this.pending.delete(url);\n\n return deferred;\n }\n\n _send(event: RequestEventData): void {\n // oxlint-disable-next-line no-unused-expressions\n this.worker instanceof SharedWorker ? this.worker.port.postMessage(event) : this.channel.port1.postMessage(event);\n }\n\n /**\n * Requests that the given image url be loaded by the connected\n * {@link ImageWorker}, resolving with an object url for the fetched\n * image's blob once the worker responds (or immediately with the\n * original `url`, in SSR/FastBoot or when this instance was constructed\n * with a `null` worker).\n *\n * The resolved object url is cached in-memory by source url on this\n * instance, so subsequent calls for the same url resolve immediately\n * without another round-trip to the worker.\n *\n * Calling `load` again for a url that is already in-flight (not yet\n * cached) on this instance replaces the pending request rather than\n * joining it — only the most recently issued call for a given url will\n * resolve.\n *\n * @public\n */\n load(url: string): Promise<string> {\n if (isServerEnv) {\n return Promise.resolve(url);\n }\n\n const objectUrl = this.cache.get(url);\n if (objectUrl) {\n return Promise.resolve(objectUrl);\n }\n\n const deferred = createDeferred<string>();\n this.pending.set(url, deferred);\n this._send({ type: 'load', thread: this.threadId, url });\n return deferred.promise;\n }\n}\n"],"mappings":";;;AAgBA,MAAMC,cAAc,OAAOC,aAAa;;;;;;;;;;;;;;;;AAiBxC,IAAaC,aAAb,MAAwB;;;;;;CAYtBC,YAAYC,QAAsC;EAChD,KAAKC,WAAWL,cAAc,KAAKM,OAAOC,WAAW;EACrD,KAAKC,0BAAU,IAAIC,IAAI;EACvB,KAAKC,wBAAQ,IAAID,IAAI;EAIrB,KAAKL,SAASA;EAEd,IAAI,CAACJ,aAAa;GAChB,MAAMY,MAAMC,UAA2B;IACrC,MAAM,EAAEC,MAAMC,QAAQF,MAAMG;IAC5B,MAAMC,WAAW,KAAKC,eAAeH,GAAG;IACxC,IAAI,CAACE,UACH;IAGF,IAAIH,SAAS,oBAAoB;KAC/B,MAAM,EAAEK,cAAcN,MAAMG;KAC5B,KAAKN,MAAMU,IAAIL,KAAKI,SAAS;KAC7BF,SAASI,QAAQF,SAAS;KAC1B;IACF;IAEA,IAAIL,SAAS,kBAAkB;KAC7BG,SAASK,OAAO,IAAI;KACpB;IACF;GACF;GAEA,IAAIlB,kBAAkBmB,cAAc;IAClCnB,OAAOoB,KAAKC,YAAY;KAAEX,MAAM;KAAWY,QAAQ,KAAKrB;IAAS,CAAC;IAClED,OAAOoB,KAAKG,YAAYf;GAC1B,OAAO,IAAIR,QAAQ;IACjB,KAAKwB,UAAU,IAAIC,eAAe;IAClCzB,OAAOqB,YAAY;KAAEX,MAAM;KAAWY,QAAQ,KAAKrB;IAAS,GAAG,CAAC,KAAKuB,QAAQE,KAAK,CAAC;IAEnF,KAAKF,QAAQG,MAAMJ,YAAYf;GACjC;EACF;CACF;CAEAM,eAAeH,KAA2C;EACxD,MAAME,WAAW,KAAKT,QAAQwB,IAAIjB,GAAG;EACrC,KAAKP,QAAQyB,OAAOlB,GAAG;EAEvB,OAAOE;CACT;CAEAiB,MAAMrB,OAA+B;EAEnC,KAAKT,kBAAkBmB,eAAe,KAAKnB,OAAOoB,KAAKC,YAAYZ,KAAK,IAAI,KAAKe,QAAQG,MAAMN,YAAYZ,KAAK;CAClH;;;;;;;;;;;;;;;;;;;CAoBAsB,KAAKpB,KAA8B;EACjC,IAAIf,aACF,OAAOoC,QAAQf,QAAQN,GAAG;EAG5B,MAAMI,YAAY,KAAKT,MAAMsB,IAAIjB,GAAG;EACpC,IAAII,WACF,OAAOiB,QAAQf,QAAQF,SAAS;EAGlC,MAAMF,WAAWlB,eAAuB;EACxC,KAAKS,QAAQY,IAAIL,KAAKE,QAAQ;EAC9B,KAAKiB,MAAM;GAAEpB,MAAM;GAAQY,QAAQ,KAAKrB;GAAUU;EAAI,CAAC;EACvD,OAAOE,SAASoB;CAClB;AACF"}
|
|
@@ -21,6 +21,8 @@ async function loadImage(url) {
|
|
|
21
21
|
* Only intended for use inside a Worker context: constructing an
|
|
22
22
|
* `ImageWorker` on the main thread is a no-op.
|
|
23
23
|
*
|
|
24
|
+
* @summary Experimental worker-side image loader that fetches images for connected `ImageFetch` clients and returns
|
|
25
|
+
* deduped, cached object urls.
|
|
24
26
|
* @public
|
|
25
27
|
*/
|
|
26
28
|
var ImageWorker = class {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-worker.js","names":["WorkerScope","globalThis","SharedWorkerGlobalScope","loadImage","url","response","fetch","fileBlob","blob","URL","createObjectURL","ImageWorker","constructor","options","window","threads","Map","pendingImages","cache","persisted","isSharedWorker","initialize","objectUrl","get","Promise","resolve","pending","promise","then","loadedObjectUrl","set","finally","delete","onconnect","e","port","ports","onmessage","event","type","data","setupThread","thread","start","request","postMessage"],"sources":["../../../src/image-worker/worker.ts"],"sourcesContent":["// oxlint-disable-next-line no-unused-vars\nimport type { ImageFetch } from './fetch';\nimport type { RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nasync function loadImage(url: string): Promise<string> {\n const response = await fetch(url);\n const fileBlob = await response.blob();\n return URL.createObjectURL(fileBlob);\n}\n\n/**\n * Runs inside a `Worker` or `SharedWorker` to fetch images on behalf of\n * one or more {@link ImageFetch} instances running on the main thread(s)\n * that connect to it.\n *\n * Each connecting thread registers itself by sending a `connect` message\n * along with a {@link MessagePort}. When a thread sends a `load` request\n * for a url, the worker fetches the image via `fetch`, converts the\n * response into a `Blob`, and creates an object url for it via\n * `URL.createObjectURL`. The fetch for a given url is deduped and cached\n * in-memory for the lifetime of the worker, so repeat `load` requests for\n * the same url — whether from the same or a different connected thread —\n * do not trigger another network request.\n *\n * Only intended for use inside a Worker context: constructing an\n * `ImageWorker` on the main thread is a no-op.\n *\n * @public\n */\nexport class ImageWorker {\n declare private threads: Map<string, MessagePort>;\n declare private pendingImages: Map<string, Promise<string>>;\n declare private options: { persisted: boolean };\n declare private isSharedWorker: boolean;\n declare private cache: Map<string, string>;\n\n /**\n * @param options.persisted - reserved for a future on-disk cache; currently unused.\n */\n constructor(options?: { persisted: boolean }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.threads = new Map();\n this.pendingImages = new Map();\n this.cache = new Map();\n this.options = options || { persisted: false };\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n private fetch(url: string): Promise<string> {\n const objectUrl = this.cache.get(url);\n\n if (objectUrl) {\n return Promise.resolve(objectUrl);\n }\n\n const pending = this.pendingImages.get(url);\n if (pending) {\n return pending;\n }\n\n const promise = loadImage(url).then((loadedObjectUrl) => {\n this.cache.set(url, loadedObjectUrl);\n return loadedObjectUrl;\n });\n this.pendingImages.set(url, promise);\n return promise.finally(() => {\n this.pendingImages.delete(url);\n });\n }\n\n private initialize(): void {\n if (this.isSharedWorker) {\n (globalThis as unknown as { onconnect: typeof globalThis.onmessage }).onconnect = (e) => {\n const port = e.ports[0];\n port.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, port);\n break;\n }\n };\n port.start();\n };\n } else {\n globalThis.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, event.ports[0]);\n break;\n }\n };\n }\n }\n\n private setupThread(thread: string, port: MessagePort): void {\n this.threads.set(thread, port);\n port.onmessage = (event: WorkerThreadEvent) => {\n if (event.type === 'close') {\n this.threads.delete(thread);\n return;\n }\n\n const { type } = event.data;\n switch (type) {\n case 'load':\n void this.request(event.data);\n break;\n }\n };\n }\n\n private async request(event: RequestEventData): Promise<void> {\n const { thread, url } = event;\n\n const objectUrl = await this.fetch(url);\n const port = this.threads.get(thread)!;\n port.postMessage({ type: 'success-response', thread, url, objectUrl });\n }\n}\n"],"mappings":";AAIA,MAAMA,cAAeC,WAA2EC;AAEhG,eAAeC,UAAUC,KAA8B;CAErD,MAAMG,WAAW,OAAMF,MADAC,MAAMF,GAAG,EACD,CAACI,KAAK;CACrC,OAAOC,IAAIC,gBAAgBH,QAAQ;AACrC
|
|
1
|
+
{"version":3,"file":"image-worker.js","names":["WorkerScope","globalThis","SharedWorkerGlobalScope","loadImage","url","response","fetch","fileBlob","blob","URL","createObjectURL","ImageWorker","constructor","options","window","threads","Map","pendingImages","cache","persisted","isSharedWorker","initialize","objectUrl","get","Promise","resolve","pending","promise","then","loadedObjectUrl","set","finally","delete","onconnect","e","port","ports","onmessage","event","type","data","setupThread","thread","start","request","postMessage"],"sources":["../../../src/image-worker/worker.ts"],"sourcesContent":["// oxlint-disable-next-line no-unused-vars\nimport type { ImageFetch } from './fetch';\nimport type { RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nasync function loadImage(url: string): Promise<string> {\n const response = await fetch(url);\n const fileBlob = await response.blob();\n return URL.createObjectURL(fileBlob);\n}\n\n/**\n * Runs inside a `Worker` or `SharedWorker` to fetch images on behalf of\n * one or more {@link ImageFetch} instances running on the main thread(s)\n * that connect to it.\n *\n * Each connecting thread registers itself by sending a `connect` message\n * along with a {@link MessagePort}. When a thread sends a `load` request\n * for a url, the worker fetches the image via `fetch`, converts the\n * response into a `Blob`, and creates an object url for it via\n * `URL.createObjectURL`. The fetch for a given url is deduped and cached\n * in-memory for the lifetime of the worker, so repeat `load` requests for\n * the same url — whether from the same or a different connected thread —\n * do not trigger another network request.\n *\n * Only intended for use inside a Worker context: constructing an\n * `ImageWorker` on the main thread is a no-op.\n *\n * @summary Experimental worker-side image loader that fetches images for connected `ImageFetch` clients and returns\n * deduped, cached object urls.\n * @public\n */\nexport class ImageWorker {\n declare private threads: Map<string, MessagePort>;\n declare private pendingImages: Map<string, Promise<string>>;\n declare private options: { persisted: boolean };\n declare private isSharedWorker: boolean;\n declare private cache: Map<string, string>;\n\n /**\n * @param options.persisted - reserved for a future on-disk cache; currently unused.\n */\n constructor(options?: { persisted: boolean }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.threads = new Map();\n this.pendingImages = new Map();\n this.cache = new Map();\n this.options = options || { persisted: false };\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n private fetch(url: string): Promise<string> {\n const objectUrl = this.cache.get(url);\n\n if (objectUrl) {\n return Promise.resolve(objectUrl);\n }\n\n const pending = this.pendingImages.get(url);\n if (pending) {\n return pending;\n }\n\n const promise = loadImage(url).then((loadedObjectUrl) => {\n this.cache.set(url, loadedObjectUrl);\n return loadedObjectUrl;\n });\n this.pendingImages.set(url, promise);\n return promise.finally(() => {\n this.pendingImages.delete(url);\n });\n }\n\n private initialize(): void {\n if (this.isSharedWorker) {\n (globalThis as unknown as { onconnect: typeof globalThis.onmessage }).onconnect = (e) => {\n const port = e.ports[0];\n port.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, port);\n break;\n }\n };\n port.start();\n };\n } else {\n globalThis.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, event.ports[0]);\n break;\n }\n };\n }\n }\n\n private setupThread(thread: string, port: MessagePort): void {\n this.threads.set(thread, port);\n port.onmessage = (event: WorkerThreadEvent) => {\n if (event.type === 'close') {\n this.threads.delete(thread);\n return;\n }\n\n const { type } = event.data;\n switch (type) {\n case 'load':\n void this.request(event.data);\n break;\n }\n };\n }\n\n private async request(event: RequestEventData): Promise<void> {\n const { thread, url } = event;\n\n const objectUrl = await this.fetch(url);\n const port = this.threads.get(thread)!;\n port.postMessage({ type: 'success-response', thread, url, objectUrl });\n }\n}\n"],"mappings":";AAIA,MAAMA,cAAeC,WAA2EC;AAEhG,eAAeC,UAAUC,KAA8B;CAErD,MAAMG,WAAW,OAAMF,MADAC,MAAMF,GAAG,EACD,CAACI,KAAK;CACrC,OAAOC,IAAIC,gBAAgBH,QAAQ;AACrC;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAaI,cAAb,MAAyB;;;;CAUvBC,YAAYC,SAAkC;EAE5C,IAAI,OAAOC,WAAW,aACpB;EAEF,KAAKC,0BAAU,IAAIC,IAAI;EACvB,KAAKC,gCAAgB,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AM;IAC1B;GACF;GAEA,MAAM,EAAEH,SAASD,MAAME;GACvB,QAAQD,MAAR;IACE,KAAK,QACH,AAAK,KAAKK,QAAQN,MAAME,IAAI;GAEhC;EACF;CACF;CAEA,MAAcI,QAAQN,OAAwC;EAC5D,MAAM,EAAEI,QAAQtC,QAAQkC;EAExB,MAAMhB,YAAY,MAAM,KAAKhB,MAAMF,GAAG;EAEtC+B,AADa,KAAKpB,QAAQQ,IAAImB,MAC9BP,CAAI,CAACU,YAAY;GAAEN,MAAM;GAAoBG;GAAQtC;GAAKkB;EAAU,CAAC;CACvE;AACF"}
|
|
@@ -74,6 +74,9 @@ StorageEvents.addEventListener("message", handleCacheEvent);
|
|
|
74
74
|
*
|
|
75
75
|
* This is a good option for larger data sets than can be efficiently stored in localStorage
|
|
76
76
|
* but should not be used as a permanent DB or storage solution.
|
|
77
|
+
*
|
|
78
|
+
* @summary Experimental `Storage`-compatible interface over the browser Cache API, suited to larger JSON data sets than
|
|
79
|
+
* localStorage.
|
|
77
80
|
*/
|
|
78
81
|
var CacheStorage = class CacheStorage {
|
|
79
82
|
#cache;
|
|
@@ -195,6 +198,9 @@ let sessionStorageOptions = {};
|
|
|
195
198
|
* Retrieves the singleton instance of the LocalStorage service.
|
|
196
199
|
*
|
|
197
200
|
* If the instance does not already exist, it is created.
|
|
201
|
+
*
|
|
202
|
+
* @summary Experimental function that returns the shared reactive wrapper around localStorage, creating it on first
|
|
203
|
+
* call.
|
|
198
204
|
*/
|
|
199
205
|
function getLocalStorage() {
|
|
200
206
|
if (!localStorageInstance) localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);
|
|
@@ -218,6 +224,9 @@ function getCacheStorage(namespace = null) {
|
|
|
218
224
|
/**
|
|
219
225
|
* Configure options for the localStorage singleton.
|
|
220
226
|
* Must be called before getLocalStorage() is first invoked.
|
|
227
|
+
*
|
|
228
|
+
* @summary Experimental function that sets fallback and quota-handling options for the reactive localStorage singleton
|
|
229
|
+
* before its first use.
|
|
221
230
|
*/
|
|
222
231
|
function configureLocalStorage(options) {
|
|
223
232
|
localStorageOptions = options;
|
|
@@ -225,6 +234,9 @@ function configureLocalStorage(options) {
|
|
|
225
234
|
/**
|
|
226
235
|
* Configure options for the sessionStorage singleton.
|
|
227
236
|
* Must be called before getSessionStorage() is first invoked.
|
|
237
|
+
*
|
|
238
|
+
* @summary Experimental function that sets fallback and quota-handling options for the reactive sessionStorage
|
|
239
|
+
* singleton before its first use.
|
|
228
240
|
*/
|
|
229
241
|
function configureSessionStorage(options) {
|
|
230
242
|
sessionStorageOptions = options;
|
|
@@ -266,6 +278,9 @@ function isStorageUnavailableError(error) {
|
|
|
266
278
|
*
|
|
267
279
|
* Route storage-event subscribers through this helper instead of calling
|
|
268
280
|
* `window.addEventListener('storage', ...)` directly.
|
|
281
|
+
*
|
|
282
|
+
* @summary Experimental helper that subscribes to storage changes from both native `StorageEvent`s and `CacheStorage`
|
|
283
|
+
* notifications, returning an unsubscribe function.
|
|
269
284
|
*/
|
|
270
285
|
function onStorageEvent(listener) {
|
|
271
286
|
const handler = (event) => {
|
|
@@ -279,6 +294,9 @@ function onStorageEvent(listener) {
|
|
|
279
294
|
* that provides signal-based access to storage items and length.
|
|
280
295
|
*
|
|
281
296
|
* Will automatically update when storage events occur in other tabs/windows.
|
|
297
|
+
*
|
|
298
|
+
* @summary Experimental signal-backed wrapper around a `Storage` area that makes reads reactive and updates on changes
|
|
299
|
+
* from other tabs.
|
|
282
300
|
*/
|
|
283
301
|
var ReactiveStorage = class {
|
|
284
302
|
_storage;
|
|
@@ -434,6 +452,9 @@ defineSignal(ReactiveStorage.prototype, "_signals", makeInitializer(() => new Si
|
|
|
434
452
|
* Use functions when you want to create more than
|
|
435
453
|
* one instance of a resource type, each with its own
|
|
436
454
|
* persisted data.
|
|
455
|
+
*
|
|
456
|
+
* @summary Experimental function type that derives a unique storage key from a storage resource instance, so each
|
|
457
|
+
* instance persists its own data.
|
|
437
458
|
*/
|
|
438
459
|
/**
|
|
439
460
|
* Symbol used to store persistence metadata on classes
|
|
@@ -708,6 +729,9 @@ function createParamField(companion, fieldName, config, controlFieldName, instan
|
|
|
708
729
|
*
|
|
709
730
|
* The function will be called once per instance during
|
|
710
731
|
* initialization to determine the unique ID for that instance.
|
|
732
|
+
*
|
|
733
|
+
* @summary Experimental class decorator that turns a class into a reactive resource whose fields persist in
|
|
734
|
+
* localStorage.
|
|
711
735
|
*/
|
|
712
736
|
function LocalResource(id) {
|
|
713
737
|
return _createStorageResource(id, "local-resource", null);
|
|
@@ -725,6 +749,9 @@ function LocalResource(id) {
|
|
|
725
749
|
*
|
|
726
750
|
* The function will be called once per instance during
|
|
727
751
|
* initialization to determine the unique ID for that instance.
|
|
752
|
+
*
|
|
753
|
+
* @summary Experimental class decorator that turns a class into a reactive resource whose fields persist in
|
|
754
|
+
* sessionStorage.
|
|
728
755
|
*/
|
|
729
756
|
function SessionResource(id) {
|
|
730
757
|
return _createStorageResource(id, "session-resource", null);
|
|
@@ -747,6 +774,9 @@ function SessionResource(id) {
|
|
|
747
774
|
* All object cached in the same `namespace` share the namespace's storage context,
|
|
748
775
|
* so partitioning can be achieved by using different namespaces for different groups
|
|
749
776
|
* of data.
|
|
777
|
+
*
|
|
778
|
+
* @summary Experimental class decorator that turns a class into a reactive resource whose fields persist via the Cache
|
|
779
|
+
* API and are shared across tabs.
|
|
750
780
|
*/
|
|
751
781
|
function CacheResource(id, namespace = null) {
|
|
752
782
|
return _createStorageResource(id, "cache-resource", namespace);
|
|
@@ -781,6 +811,8 @@ function CacheResource(id, namespace = null) {
|
|
|
781
811
|
* }
|
|
782
812
|
* ```
|
|
783
813
|
*
|
|
814
|
+
* @summary Experimental decorator that makes a storage resource property a reactive field persisted to local, session,
|
|
815
|
+
* or cache storage.
|
|
784
816
|
*/
|
|
785
817
|
function field(...args) {
|
|
786
818
|
if (args.length === 0) return setupField;
|
|
@@ -858,6 +890,9 @@ function input(type) {
|
|
|
858
890
|
* }
|
|
859
891
|
* }
|
|
860
892
|
* ```
|
|
893
|
+
*
|
|
894
|
+
* @summary Experimental field decorator for storage resources that runs a callback when the stored value changes in
|
|
895
|
+
* another tab or window.
|
|
861
896
|
*/
|
|
862
897
|
function effect(fn, type) {
|
|
863
898
|
const overrideType = type === "local" ? "local-storage" : type === "session" ? "session-storage" : null;
|
|
@@ -882,10 +917,15 @@ function effect(fn, type) {
|
|
|
882
917
|
//#region src/storage/query-params.ts
|
|
883
918
|
/**
|
|
884
919
|
* Configuration options for fields that are also query parameters
|
|
920
|
+
*
|
|
921
|
+
* @summary Experimental config passed to the `param` decorator that describes how a field is serialized to and parsed
|
|
922
|
+
* from a URL query parameter.
|
|
885
923
|
*/
|
|
886
924
|
/**
|
|
887
925
|
* Creates a {@link ParamConfig} for boolean fields that serialize to '1' or null.
|
|
888
926
|
*
|
|
927
|
+
* @summary Experimental helper that creates a query-param config serializing a boolean field as '1' when true and
|
|
928
|
+
* omitting it when false.
|
|
889
929
|
* @returns ParamConfig for boolean fields
|
|
890
930
|
*
|
|
891
931
|
* @example
|
|
@@ -904,6 +944,8 @@ function BooleanParam() {
|
|
|
904
944
|
/**
|
|
905
945
|
* Creates a {@link ParamConfig} for numeric fields with default value checking.
|
|
906
946
|
*
|
|
947
|
+
* @summary Experimental helper that creates a query-param config serializing numbers, optionally to a fixed precision,
|
|
948
|
+
* with an optional default value.
|
|
907
949
|
* @param precision - When given, the number of digits to serialize after the decimal point
|
|
908
950
|
* @param getDefault - Function to get the default value for comparison
|
|
909
951
|
* @returns ParamConfig for number fields
|
|
@@ -943,6 +985,8 @@ function NumberParam(precision, getDefault) {
|
|
|
943
985
|
* - Compare URL and local values
|
|
944
986
|
* - Determine when to include/exclude params from the URL
|
|
945
987
|
*
|
|
988
|
+
* @summary Experimental decorator that marks a storage resource field as a URL query parameter, recording how to
|
|
989
|
+
* serialize it for a router integration.
|
|
946
990
|
* @param config - Configuration for URL serialization/deserialization
|
|
947
991
|
*
|
|
948
992
|
* @example
|