@warp-drive-mirror/experiments 0.2.7-beta.1 → 0.2.7-beta.2
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/dist/data-worker.js.map +1 -1
- package/dist/document-storage-LM925Stz.js.map +1 -1
- package/dist/image-fetch.js.map +1 -1
- package/dist/image-worker.js.map +1 -1
- package/dist/pagination.d.ts +2 -0
- package/dist/pagination.js +3 -0
- package/{declarations → dist}/storage.d.ts +0 -5
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js.map +1 -1
- package/dist/unpkg/dev/data-worker.js.map +1 -1
- package/dist/unpkg/dev/document-storage-DkiEg9rY.js.map +1 -1
- package/dist/unpkg/dev/image-fetch.js.map +1 -1
- package/dist/unpkg/dev/image-worker.js.map +1 -1
- package/dist/unpkg/dev/pagination.js +3 -0
- package/dist/unpkg/dev/storage.js.map +1 -1
- package/dist/unpkg/dev/worker-fetch.js.map +1 -1
- package/dist/unpkg/dev-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js.map +1 -1
- package/dist/unpkg/dev-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/dev-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/pagination.js +3 -0
- package/dist/unpkg/dev-deprecated/storage.js.map +1 -1
- package/dist/unpkg/dev-deprecated/worker-fetch.js.map +1 -1
- package/dist/unpkg/prod/data-worker.js.map +1 -1
- package/dist/unpkg/prod/document-storage-D0k_6GM9.js.map +1 -1
- package/dist/unpkg/prod/image-fetch.js.map +1 -1
- package/dist/unpkg/prod/image-worker.js.map +1 -1
- package/dist/unpkg/prod/pagination.js +3 -0
- package/dist/unpkg/prod/storage.js.map +1 -1
- package/dist/unpkg/prod/worker-fetch.js.map +1 -1
- package/dist/unpkg/prod-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js.map +1 -1
- package/dist/unpkg/prod-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/prod-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/prod-deprecated/pagination.js +3 -0
- package/dist/unpkg/prod-deprecated/storage.js.map +1 -1
- package/dist/unpkg/prod-deprecated/worker-fetch.js.map +1 -1
- package/dist/worker-fetch.js.map +1 -1
- package/package.json +25 -21
- package/declarations/storage.d.ts.map +0 -1
- /package/{declarations → dist}/data-worker.d.ts +0 -0
- /package/{declarations → dist}/data-worker.d.ts.map +0 -0
- /package/{declarations → dist}/document-storage-CwwTQ49-.d.ts +0 -0
- /package/{declarations → dist}/document-storage-CwwTQ49-.d.ts.map +0 -0
- /package/{declarations → dist}/document-storage.d.ts +0 -0
- /package/{declarations → dist}/image-fetch.d.ts +0 -0
- /package/{declarations → dist}/image-fetch.d.ts.map +0 -0
- /package/{declarations → dist}/image-worker.d.ts +0 -0
- /package/{declarations → dist}/image-worker.d.ts.map +0 -0
- /package/{declarations → dist}/types-CRs-Qww6.d.ts +0 -0
- /package/{declarations → dist}/types-CRs-Qww6.d.ts.map +0 -0
- /package/{declarations → dist}/worker-fetch.d.ts +0 -0
- /package/{declarations → dist}/worker-fetch.d.ts.map +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-storage-DkiEg9rY.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","test","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 as CacheDocument;\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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CAAChB,QAAQ4E,UACXC,SAASlC,IAAI6D,UAAU,IAAII,QAAQ5F,OAAO,CAAC;CAE/C;CAEAuC,YAAYT,KAAwD;EAClE,OAAO,KAAK4D,SAASnD,YAAYT,GAAG;CACtC;CAEAuB,YACE9B,UACA+B,mBACe;EACf,OAAO,KAAKoC,SAASrC,YAAY9B,UAAU+B,iBAAiB;CAC9D;CAEAG,aACElC,UACA+B,mBACe;EACf,OAAO,KAAKoC,SAASjC,aAAalC,UAAU+B,iBAAiB;CAC/D;CAEAI,MAAMC,OAAgC;EACpC,OAAO,KAAK+B,SAAShC,MAAMC,KAAK;CAClC;AACF"}
|
|
1
|
+
{"version":3,"file":"document-storage-DkiEg9rY.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","test","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;EA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AK;CAClC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-fetch.js","names":["createDeferred","isServerEnv","FastBoot","ImageFetch","constructor","worker","threadId","crypto","randomUUID","pending","Map","cache","isTesting","test","Error","SharedWorker","fn","event","type","url","data","deferred","cleanupRequest","objectUrl","set","resolve","reject","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//
|
|
1
|
+
{"version":3,"file":"image-fetch.js","names":["createDeferred","isServerEnv","FastBoot","ImageFetch","constructor","worker","threadId","crypto","randomUUID","pending","Map","cache","isTesting","test","Error","SharedWorker","fn","event","type","url","data","deferred","cleanupRequest","objectUrl","set","resolve","reject","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;;;;;;;;;;;;;;AAexC,IAAaC,aAAb,MAAwB;;;;;;CAYtBC,YAAYC,QAAsC;EAChD,KAAKC,WAAWL,cAAc,KAAKM,OAAOC,WAAW;EACrD,KAAKC,0BAAU,IAAIC,IAAI;EACvB,KAAKC,wBAAQ,IAAID,IAAI;EAGrB,EAAAG,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,kCAAkC;EAAA,EAAA,CAAEF,IAA0D;EACrG,KAAKP,SAASA;EAEd,IAAI,CAACJ,aAAa;GAChB,MAAMe,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,KAAKT,MAAMa,IAAIL,KAAKI,SAAS;KAC7BF,SAASI,QAAQF,SAAS;KAC1B;IACF;IAEA,IAAIL,SAAS,kBAAkB;KAC7BG,SAASK,OAAO,IAAI;KACpB;IACF;GACF;GAEA,IAAIrB,kBAAkBU,cAAc;IAClCV,OAAOsB,KAAKC,YAAY;KAAEV,MAAM;KAAWW,QAAQ,KAAKvB;IAAS,CAAC;IAClED,OAAOsB,KAAKG,YAAYd;GAC1B,OAAO,IAAIX,QAAQ;IACjB,KAAK0B,UAAU,IAAIC,eAAe;IAClC3B,OAAOuB,YAAY;KAAEV,MAAM;KAAWW,QAAQ,KAAKvB;IAAS,GAAG,CAAC,KAAKyB,QAAQE,KAAK,CAAC;IAEnF,KAAKF,QAAQG,MAAMJ,YAAYd;GACjC;EACF;CACF;CAEAM,eAAeH,KAA2C;EACxD,MAAME,WAAW,KAAKZ,QAAQ0B,IAAIhB,GAAG;EACrC,KAAKV,QAAQ2B,OAAOjB,GAAG;EAEvB,OAAOE;CACT;CAEAgB,MAAMpB,OAA+B;EAEnC,KAAKZ,kBAAkBU,eAAe,KAAKV,OAAOsB,KAAKC,YAAYX,KAAK,IAAI,KAAKc,QAAQG,MAAMN,YAAYX,KAAK;CAClH;;;;;;;;;;;;;;;;;;;CAoBAqB,KAAKnB,KAA8B;EACjC,IAAIlB,aACF,OAAOsC,QAAQd,QAAQN,GAAG;EAG5B,MAAMI,YAAY,KAAKZ,MAAMwB,IAAIhB,GAAG;EACpC,IAAII,WACF,OAAOgB,QAAQd,QAAQF,SAAS;EAGlC,MAAMF,WAAWrB,eAAuB;EACxC,KAAKS,QAAQe,IAAIL,KAAKE,QAAQ;EAC9B,KAAKgB,MAAM;GAAEnB,MAAM;GAAQW,QAAQ,KAAKvB;GAAUa;EAAI,CAAC;EACvD,OAAOE,SAASmB;CAClB;AACF"}
|
|
@@ -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":["//
|
|
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;;;;;;;;;;;;;;;;;;;;AAqBA,IAAaI,cAAb,MAAyB;;;;CAUvBC,YAAYC,SAAkC;EAE5C,IAAI,OAAOC,WAAW,aACpB;EAEF,KAAK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AAS,SAAS;IAC1B,KAAKxB,QAAQiB,OAAOU,MAAM;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"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { clearPaginationCache, createPaginationLinksSubscription, createPaginationSubscription, defaultPageHints, getPaginationCache, getPaginationLinks, getPaginationState } from "@warp-drive-mirror/core/signals/-leaked";
|
|
2
|
+
|
|
3
|
+
export { clearPaginationCache, createPaginationLinksSubscription, createPaginationSubscription, defaultPageHints, getPaginationCache, getPaginationLinks, getPaginationState };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":["defineSignal","entangleSignal","getOrCreateInternalSignal","notifyInternalSignal","withSignalStore","SignalMap","_map","_signals","subscribe","key","test","Error","existing","has","undefined","size","_size","notify","signal","clear","value","values","prototype","DEFAULT_CACHE_ID","CACHES","Map","StorageEvents","BroadcastChannel","CACHE_URL","location","origin","emitStorageEvent","event","window","dispatchEvent","CustomEvent","detail","handleCacheEvent","data","cache","get","storageArea","key","_data","oldValue","newValue","delete","set","addEventListener","CacheStorage","cacheId","inititalization","_nextUpdate","_bufferedEvents","initialize","#initialize","caches","open","deserializeFromCache","constructor","length","size","update","#update","Error","push","setTimeout","events","serializeToCache","postMessage","clear","getItem","index","test","Number","isInteger","i","value","keys","removeItem","has","setItem","expectCache","getAllCacheIds","Array","from","entries","blob","JSON","stringify","version","response","Response","put","match","then","json","defineSignal","makeInitializer","SignalMap","CacheStorage","DEFAULT_CACHE_ID","localStorageInstance","sessionStorageInstance","localStorageOptions","sessionStorageOptions","getLocalStorage","ReactiveStorage","localStorage","getSessionStorage","sessionStorage","CacheStorages","Map","getCacheStorage","namespace","key","cache","get","storage","expectCache","set","configureLocalStorage","options","configureSessionStorage","isQuotaExceededError","error","DOMException","name","isStorageUnavailableError","_storage","_options","_memoryOnly","_values","_effects","setEffect","fn","test","Error","has","constructor","testKey","setItem","removeItem","_length","length","fallbackToMemory","window","addEventListener","event","data","detail","storageArea","newValue","_signals","notify","effect","peekItem","keyStr","String","value","undefined","item","getItem","subscribe","valueStr","current","currentValue","updateOnQuotaExceeded","onQuotaExceeded","result","retry","Promise","clear","index","keys","Object","filter","k","prototype","memoized","getCacheStorage","getLocalStorage","getSessionStorage","PERSISTED_RESOURCE_META","Symbol","initMeta","target","meta","id","namespace","pkFn","type","fields","Map","initializers","paramConfigs","paramCompanion","instances","typeOverrides","useMeta","instance","WeakMap","instanceMeta","get","pk","test","Error","length","set","getField","key","overrideType","storage","getStorage","stored","getItem","keyFor","JSON","parse","initializer","value","call","undefined","peekField","peekItem","initializeFields","source","baseMeta","getResourceMeta","entries","newValue","defaultValue","currentValue","localStorage","sessionStorage","setItem","stringify","setField","_createStorageResource","prototype","originalConstructor","constructor","DynamicStorageInitializer","args","installEffectsForDynamicInstance","toJSON","isLocalResource","Set","keys","add","delete","idKey","has","data","Promise","resolve","installEffect","setupField","orgDesc","desc","configurable","enumerable","effect","setEffect","event","oldValue","from","to","getParamCompanion","groupControlMap","companion","size","fieldName","config","controlFieldName","createParamField","isActiveGroupParam","controlValue","getParamFieldDefaultValue","getDefault","initValue","initialized","rawValue","serialized","serialize","urlValue","rawValueSerialized","newRawValue","deserialize","Object","defineProperty","_createStorageResource","getField","initMeta","installEffect","setField","setupField","useMeta","LocalResource","id","SessionResource","CacheResource","namespace","field","args","length","test","Error","type","target","key","desc","descriptor","input","includes","originalSet","set","value","Number","undefined","call","effect","fn","overrideType","effectField","_descriptor","meta","fields","pkFn","configurable","enumerable","get"],"sources":["../../../src/storage/-private/reactive-map.ts","../../../src/storage/cache.ts","../../../src/storage/storage.ts","../../../src/storage/-private/storage-infra.ts","../../../src/storage/storage-resource.ts"],"sourcesContent":["import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { SignalStore } from '@warp-drive-mirror/core/signals/-leaked';\nimport {\n defineSignal,\n entangleSignal,\n getOrCreateInternalSignal,\n notifyInternalSignal,\n withSignalStore,\n} from '@warp-drive-mirror/core/signals/-leaked';\n\n/**\n * A reactive wrapper around the browser's Map API that provides\n * granular per-key reactivity via WarpDrive's signal system.\n */\nexport class SignalMap<K extends string> {\n private _map: Record<K, number> = {} as Record<K, number>;\n // _size is signal-backed via defineSignal below\n declare private _size: number;\n private _signals: SignalStore = withSignalStore(this._map);\n\n subscribe(key: K): boolean {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const existing = this._signals.has(key);\n entangleSignal(this._signals, this._map, key, undefined);\n const size = this._size;\n this._size = existing ? size : size + 1;\n return existing;\n }\n\n notify(key: K): void {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const signal = getOrCreateInternalSignal(this._signals, this._map, key, 0);\n notifyInternalSignal(signal);\n }\n\n clear(): void {\n for (const value of this._signals.values()) {\n notifyInternalSignal(value);\n }\n this._size = 0;\n }\n\n get size(): number {\n return this._size;\n }\n}\ndefineSignal(SignalMap.prototype, '_size', 0);\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nexport const DEFAULT_CACHE_ID = 'reactive-cache';\nconst CACHES = new Map<string, CacheStorage>();\nconst StorageEvents = new BroadcastChannel('reactive-cache-events');\nconst CACHE_URL = `${location.origin}/api/reactive-cache.json`;\n\nexport interface InternalCacheStorageEvent {\n storageArea: string;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\nexport interface CacheStorageEvent {\n storageArea: CacheStorage;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\n\n/**\n * Emits a {@link StorageEvent} on the local context to\n * match the broadcast event.\n */\nfunction emitStorageEvent(event: CacheStorageEvent): void {\n window.dispatchEvent(new CustomEvent('storage', { detail: event }));\n}\n\n/**\n * Updates the cache and re-emits the event on the local context as a StorageEvent\n * This is necessary to trigger the reactive updates in the current tab.\n */\nfunction handleCacheEvent(event: MessageEvent<InternalCacheStorageEvent>): void {\n const { data } = event;\n\n const cache = CACHES.get(data.storageArea);\n // if we don't have an instance of the cache in this context\n // then we don't need to do anything since there are no reactive\n // subscribers to update\n if (!cache) {\n return;\n }\n\n // a StorageEvent with a key of null\n // is a signal that the entire cache should be cleared.\n if (data.key === null) {\n cache._data = new Map();\n emitStorageEvent({\n storageArea: cache,\n key: null,\n oldValue: null,\n newValue: null,\n });\n return;\n }\n\n if (data.newValue === null) {\n // remove the key from the cache\n cache._data.delete(data.key);\n } else {\n // update the cache with the new value\n cache._data.set(data.key, data.newValue);\n }\n\n // emit a StorageEvent to trigger reactive updates in this context\n emitStorageEvent({\n storageArea: cache,\n key: data.key,\n oldValue: data.oldValue,\n newValue: data.newValue,\n });\n}\n\n// subscribe to all storage events from other contexts to\n// keep caches in sync\nStorageEvents.addEventListener('message', handleCacheEvent);\n\n/**\n * A reactive interface for json stored in the browser [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API.\n *\n * This is a good option for larger data sets than can be efficiently stored in localStorage\n * but should not be used as a permanent DB or storage solution.\n */\nexport class CacheStorage implements Storage {\n #cache: Cache | null;\n #cacheId: string;\n #inititalization: Promise<CacheStorage>;\n _data: Map<string, string | null> = new Map();\n _nextUpdate: number | null = null;\n _bufferedEvents: InternalCacheStorageEvent[] = [];\n\n async #initialize() {\n const cache = await caches.open(this.#cacheId);\n this.#cache = cache;\n\n // Load all existing entries into memory\n this._data = await deserializeFromCache(cache);\n\n return this;\n }\n\n constructor(cacheId: string) {\n this.#cacheId = cacheId;\n this.#cache = null;\n this.#inititalization = this.#initialize();\n }\n\n get length(): number {\n return this._data.size;\n }\n\n #update(key: string | null, oldValue: string | null, newValue: string | null) {\n const cache = this.#cache;\n if (!cache) {\n throw new Error('Cache not initialized');\n }\n this._bufferedEvents.push({\n storageArea: this.#cacheId,\n key: key,\n oldValue: oldValue,\n newValue: newValue,\n });\n if (!this._nextUpdate) {\n this._nextUpdate = window.setTimeout(() => {\n const events = this._bufferedEvents;\n this._bufferedEvents = [];\n this._nextUpdate = null;\n void serializeToCache(cache, this._data);\n for (const event of events) {\n StorageEvents.postMessage(event);\n }\n }, 0);\n }\n }\n\n clear(): void {\n this._data = new Map();\n this.#update(null, null, null);\n }\n\n getItem(key: string): string | null {\n return this._data.get(key) ?? null;\n }\n\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n assert('ReactiveStorage.key: index must be a non-negative integer', index >= 0 && Number.isInteger(index));\n assert('ReactiveStorage.key: index must be less than the number of items in storage', index < this.length);\n\n let i = 0;\n for (const value of this._data.keys()) {\n if (i === index) {\n return value;\n }\n i++;\n }\n\n return null;\n }\n\n removeItem(key: string): void {\n if (this._data.has(key)) {\n const oldValue = this._data.get(key) ?? null;\n this._data.delete(key);\n this.#update(key, oldValue, null);\n }\n }\n\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n const oldValue = this._data.get(key) ?? null;\n if (oldValue === value) {\n return;\n }\n this._data.set(key, value);\n this.#update(key, oldValue, value);\n }\n\n /**\n * Get the singleton CacheStorage instance.\n *\n */\n static get(cacheId: string = DEFAULT_CACHE_ID): Promise<CacheStorage> {\n let cache = CACHES.get(cacheId);\n if (!cache) {\n cache = new CacheStorage(cacheId);\n CACHES.set(cacheId, cache);\n }\n return cache.#inititalization;\n }\n\n static expectCache(cacheId: string = DEFAULT_CACHE_ID): CacheStorage {\n const cache = CACHES.get(cacheId);\n if (!cache) {\n throw new Error(`Cache with id ${cacheId} not found. Make sure to call CacheStorage.get(${cacheId}) first.`);\n }\n return cache;\n }\n\n /**\n * Returns the IDs of all {@link CacheStorage} instances that have been\n * opened in this context via {@link CacheStorage.get}.\n */\n static getAllCacheIds(): string[] {\n return Array.from(CACHES.keys());\n }\n}\n\ninterface CacheFile {\n version: 1;\n data: Array<[string, string]>;\n}\n\nfunction serializeToCache(cache: Cache, data: Map<string, string | null>): Promise<void> {\n const entries = Array.from(data.entries());\n const blob = JSON.stringify({\n version: 1,\n data: entries,\n });\n const response = new Response(blob);\n return cache.put(CACHE_URL, response);\n}\n\nfunction deserializeFromCache(cache: Cache): Promise<Map<string, string | null>> {\n return cache.match(CACHE_URL).then((response) => {\n if (!response) {\n return new Map();\n }\n return response.json().then((json: CacheFile) => {\n if (json.version !== 1) {\n throw new Error(`Unsupported cache version: ${json.version as string}`);\n }\n return new Map(json.data);\n });\n });\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { defineSignal, makeInitializer } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { SignalMap } from './-private/reactive-map.ts';\nimport { CacheStorage, type CacheStorageEvent, DEFAULT_CACHE_ID } from './cache.ts';\n\nexport interface ReactiveStorageOptions {\n /**\n * If true, falls back to in-memory storage when the underlying\n * storage is unavailable (e.g., private browsing mode).\n */\n fallbackToMemory?: boolean;\n\n /**\n * If true, updates signal state even when writes fail due to quota.\n * The onQuotaExceeded callback will be invoked before retrying.\n */\n updateOnQuotaExceeded?: boolean;\n\n /**\n * Called when a write fails due to quota exceeded.\n * Return true to retry the write after freeing space.\n */\n onQuotaExceeded?: (key: string, value: string) => boolean | Promise<boolean>;\n}\n\nlet localStorageInstance: ReactiveStorage | null = null;\nlet sessionStorageInstance: ReactiveStorage | null = null;\nlet localStorageOptions: ReactiveStorageOptions = {};\nlet sessionStorageOptions: ReactiveStorageOptions = {};\n\n// This pattern enables us to have a singleton service-like\n// instance that also functions as a global singleton that\n// can be imported and used outside of Ember's DI system.\n/**\n * Retrieves the singleton instance of the LocalStorage service.\n *\n * If the instance does not already exist, it is created.\n */\nexport function getLocalStorage(): ReactiveStorage {\n if (!localStorageInstance) {\n localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);\n }\n return localStorageInstance;\n}\n\nexport function getSessionStorage(): ReactiveStorage {\n if (!sessionStorageInstance) {\n sessionStorageInstance = new ReactiveStorage(sessionStorage, sessionStorageOptions);\n }\n return sessionStorageInstance;\n}\n\nconst CacheStorages = new Map<string, ReactiveStorage>();\nexport function getCacheStorage(namespace: string | null = null): ReactiveStorage {\n const key = namespace ?? DEFAULT_CACHE_ID;\n let cache = CacheStorages.get(key);\n if (!cache) {\n const storage = CacheStorage.expectCache(key);\n cache = new ReactiveStorage(storage);\n CacheStorages.set(key, cache);\n }\n return cache;\n}\n\n/**\n * Configure options for the localStorage singleton.\n * Must be called before getLocalStorage() is first invoked.\n */\nexport function configureLocalStorage(options: ReactiveStorageOptions): void {\n localStorageOptions = options;\n}\n\n/**\n * Configure options for the sessionStorage singleton.\n * Must be called before getSessionStorage() is first invoked.\n */\nexport function configureSessionStorage(options: ReactiveStorageOptions): void {\n sessionStorageOptions = options;\n}\n\n/**\n * Check if an error is a quota exceeded error\n */\nfunction isQuotaExceededError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Most browsers\n if (error.name === 'QuotaExceededError') return true;\n // Firefox\n if (error.name === 'NS_ERROR_DOM_QUOTA_REACHED') return true;\n }\n return false;\n}\n\n/**\n * Check if an error indicates storage is unavailable (private browsing, etc.)\n */\nfunction isStorageUnavailableError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Safari private browsing, some security restrictions\n if (error.name === 'SecurityError') return true;\n // Some browsers throw this in private mode\n if (error.name === 'InvalidStateError') return true;\n }\n return false;\n}\n\nexport type EffectStorageEvent = CacheStorageEvent | StorageEvent;\n\ndeclare global {\n interface WindowEventMap {\n storage: CustomEvent<CacheStorageEvent> | StorageEvent;\n }\n}\n\n/**\n * A reactive wrapper around the Web Storage API (localStorage/sessionStorage)\n * that provides signal-based access to storage items and length.\n *\n * Will automatically update when storage events occur in other tabs/windows.\n */\nclass ReactiveStorage implements Storage {\n private _storage: Storage;\n private _options: ReactiveStorageOptions;\n private _memoryOnly = false;\n private _values: Record<string, string | null> = {};\n\n declare private _signals: SignalMap<string>;\n declare private _length: number;\n\n private _effects = new Map<string, (value: EffectStorageEvent) => void>();\n setEffect(key: string, fn: (value: EffectStorageEvent) => void): void {\n assert(`Can only set effect once for key: ${key}`, !this._effects.has(key));\n this._effects.set(key, fn);\n }\n\n constructor(storage: Storage, options: ReactiveStorageOptions = {}) {\n this._storage = storage;\n this._options = options;\n\n if (!(storage instanceof CacheStorage)) {\n // Test if storage is accessible\n try {\n const testKey = '__storage_test__';\n storage.setItem(testKey, testKey);\n storage.removeItem(testKey);\n this._length = storage.length;\n } catch (error) {\n if (options.fallbackToMemory && isStorageUnavailableError(error)) {\n this._memoryOnly = true;\n this._length = 0;\n } else {\n throw error;\n }\n }\n }\n\n // bind to localStorage events to trigger reactivity\n if (!this._memoryOnly) {\n window.addEventListener('storage', (event: StorageEvent | CustomEvent<CacheStorageEvent>) => {\n const data = 'detail' in event ? event.detail : event;\n\n // Only react to changes in the same storage area\n if (data.storageArea === storage) {\n this._values[data.key as string] = data.newValue;\n this._signals.notify(data.key as string);\n this._length = this._storage.length;\n const effect = this._effects.get(data.key as string);\n if (effect) {\n effect(data);\n }\n }\n });\n }\n }\n\n /**\n * Reactive access to the number of keys in Storage\n */\n get length(): number {\n return this._length;\n }\n\n /**\n * Non-reactive way to peek the current value of a key in Storage\n */\n peekItem(key: string): string | null {\n assert('ReactiveStorage.peekItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n return value;\n }\n\n // Not yet loaded, fetch from storage, but don't track access\n const item = this._storage.getItem(keyStr);\n // this._values[keyStr] = item;\n return item;\n }\n\n /**\n * Reactive access to Storage contents\n */\n getItem(key: string): string | null {\n assert('ReactiveStorage.getItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n this._signals.subscribe(keyStr);\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n this._signals.subscribe(keyStr);\n return value;\n }\n\n // Not yet loaded, fetch from storage\n const item = this._storage.getItem(keyStr);\n this._values[keyStr] = item;\n this._signals.subscribe(keyStr);\n return item;\n }\n\n /**\n * Set a value in Storage, triggering reactivity\n */\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n\n // Coerce to strings to match Storage API behavior\n const keyStr = String(key);\n const valueStr = String(value);\n const current = this._values[keyStr];\n if (current === valueStr) {\n // No change\n return;\n }\n\n // console.trace(`set field ${key} => ${String(value)}`);\n\n if (this._memoryOnly) {\n const currentValue = this._values[keyStr];\n if (currentValue === null || currentValue === undefined) {\n this._length += 1;\n }\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n return;\n }\n\n try {\n this._storage.setItem(keyStr, valueStr);\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n } catch (error) {\n if (isQuotaExceededError(error)) {\n if (this._options.updateOnQuotaExceeded) {\n // Update signal state even though write failed\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n }\n\n if (this._options.onQuotaExceeded) {\n const result = this._options.onQuotaExceeded(keyStr, valueStr);\n const retry = result instanceof Promise ? false : result;\n\n if (retry) {\n // Retry the write after callback freed space\n this._storage.setItem(keyStr, valueStr);\n this._length = this._storage.length;\n }\n } else {\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Remove a value from Storage, triggering reactivity\n */\n removeItem(key: string): void {\n assert('ReactiveStorage.removeItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n const value = this._values[keyStr];\n if (value !== null && value !== undefined) {\n this._length -= 1;\n }\n this._values[keyStr] = null;\n return;\n }\n\n this._storage.removeItem(keyStr);\n this._values[keyStr] = null;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n }\n\n /**\n * Clears all keys from Storage, triggering reactivity\n */\n clear(): void {\n this._values = {};\n this._signals.clear();\n this._length = 0;\n\n if (this._memoryOnly) {\n return;\n }\n\n this._storage.clear();\n }\n\n /**\n * Reactive access to the key at the given index\n */\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n this._length; // track length access\n\n if (this._memoryOnly) {\n const keys = Object.keys(this._values).filter((k) => this._values[k] !== null);\n return keys[index] ?? null;\n }\n\n return this._storage.key(index);\n }\n}\ndefineSignal(ReactiveStorage.prototype, '_length', 0);\ndefineSignal(\n ReactiveStorage.prototype,\n '_signals',\n makeInitializer(() => new SignalMap<string>())\n);\n\nexport type { ReactiveStorage };\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { memoized } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { type EffectStorageEvent, getCacheStorage, getLocalStorage, getSessionStorage } from '../storage.ts';\n\n/**\n * Configuration options for fields that are also query parameters\n */\nexport interface ParamConfig {\n /**\n * Convert a value into a string for storage in the URL.\n * `null` indicates the value should be omitted from the URL.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialize: (value: unknown, instance: any) => string | null;\n /**\n * Convert a string value from the URL back into\n * its original type\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n deserialize: (urlValue: string, instance: any) => unknown;\n /**\n * Get the default value for this param from the given instance.\n *\n * If not present, the value passed to the field initializer\n * will be used as the default.\n *\n * This should return the value in the field's native type,\n * not the serialized URL form.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getDefault?: (instance: any) => unknown;\n}\n\ninterface InternalParamConfig extends ParamConfig {\n initialized?: boolean;\n}\n\nexport interface ValueTransition<T = unknown> {\n key: string;\n from: T;\n to: T;\n}\n\n/**\n * Metadata attached to persisted resource classes\n */\nexport interface StorageResourceMeta {\n id: string;\n namespace: string | null;\n pkFn: KeyFn | null;\n type: 'local-resource' | 'session-resource' | 'cache-resource';\n typeOverrides: Map<string, 'local-storage' | 'session-storage' | 'cache-storage'> | null;\n fields: Map<string, null | ((update: ValueTransition<string>) => void)>;\n initializers: Map<string, (() => unknown) | null>;\n paramConfigs: Map<string, InternalParamConfig> | null;\n paramCompanion: object | null;\n instances: WeakMap<object, StorageResourceMeta> | null;\n}\n\n/**\n * A function which generates a unique primary-key\n * string for a given LocalResource or SessionResource\n * instance.\n *\n * Use functions when you want to create more than\n * one instance of a resource type, each with its own\n * persisted data.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type KeyFn = (obj: any) => string;\n\n/**\n * Symbol used to store persistence metadata on classes\n */\nconst PERSISTED_RESOURCE_META = Symbol('StorageResourceMeta');\n\n/**\n * Setup persisted resource metadata on target\n * if not already present\n *\n * @private\n */\nexport function initMeta(target: object): StorageResourceMeta {\n let meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n if (!meta) {\n meta = {\n id: '',\n namespace: null,\n pkFn: null,\n type: '' as 'local-resource' | 'session-resource',\n fields: new Map(),\n initializers: new Map(),\n paramConfigs: null,\n paramCompanion: null,\n instances: null,\n typeOverrides: null,\n };\n (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META] = meta;\n }\n return meta;\n}\n\nexport function useMeta(meta: StorageResourceMeta, instance: object): StorageResourceMeta {\n // If a primary key function is defined, use it to generate\n // a unique ID for this instance\n if (meta.id === '' && meta.pkFn) {\n // we are in an instance context\n meta.instances = meta.instances ?? new WeakMap();\n let instanceMeta = meta.instances.get(instance);\n if (!instanceMeta) {\n instanceMeta = { ...meta };\n const pk = meta.pkFn(instance);\n assert('Primary key function must return a non-empty string.', typeof pk === 'string' && pk.length > 0);\n instanceMeta.id = pk;\n meta.instances.set(instance, instanceMeta);\n }\n return instanceMeta;\n }\n\n assert('StorageResourceMeta must have a valid id.', typeof meta.id === 'string' && meta.id.length > 0);\n return meta;\n}\n\n/**\n * Load storage field\n */\nexport function getField(\n instance: object,\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): Record<string, unknown> | null {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.getItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n } else {\n // No stored value, check for initializer\n const initializer = meta.initializers.get(key);\n if (initializer) {\n const value = initializer.call(instance);\n if (value !== undefined) {\n return value as Record<string, unknown>;\n }\n }\n }\n return null;\n}\n\nfunction keyFor(meta: StorageResourceMeta, key: string): string {\n return `persisted:${meta.id}:${key}`;\n}\n\nfunction getStorage(type: string, namespace: string | null) {\n if (type === 'local-resource') {\n return getLocalStorage();\n } else if (type === 'session-resource') {\n return getSessionStorage();\n } else {\n return getCacheStorage(namespace);\n }\n}\n\nexport function peekField(\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): unknown {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.peekItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n }\n return null;\n}\n\nexport function initializeFields(instance: object, source: object): void {\n // we need to initialize the fields without reading from their reactive state\n // we also only want to initialize the field if it is still at its default value\n // as otherwise we are likely overwriting a persisted value or url value\n const baseMeta = getResourceMeta(instance);\n const meta = useMeta(baseMeta, instance);\n\n for (const [key] of meta.fields.entries()) {\n if (key in source) {\n // get the new value from source\n const newValue = (source as Record<string, unknown>)[key];\n\n // get the current default value from the field initializer\n const initializer = meta.initializers.get(key);\n let defaultValue: unknown = null;\n if (initializer) {\n defaultValue = initializer.call(instance);\n }\n\n // get the overrideType\n const overrideType = meta.typeOverrides?.get(key) ?? null;\n const type = overrideType || meta.type;\n\n // get the current stored value, without triggering reactivity\n const currentValue = peekField(meta, keyFor(meta, key), overrideType);\n\n // if there is no current value, silently update the field\n const storage = type === 'local-resource' ? localStorage : sessionStorage;\n storage.setItem(keyFor(meta, key), JSON.stringify(newValue));\n // only initialize if current value matches default value\n // or we have no persisted value yet.\n if (currentValue === defaultValue) {\n setField(meta, keyFor(meta, key), newValue as string, overrideType);\n }\n }\n }\n}\n\n/**\n * Update storage field\n */\nexport function setField(\n meta: StorageResourceMeta,\n key: string,\n value: string | boolean | null | number | Record<string, unknown> | unknown[],\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): void {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n storage.setItem(keyFor(meta, key), JSON.stringify(value));\n}\n\nfunction getResourceMeta(target: object): StorageResourceMeta {\n const meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n assert(\n 'StorageResourceMeta not found on target. Did you forget to use the @LocalResource() or @SessionResource() decorator?',\n meta !== undefined\n );\n return meta;\n}\n\nexport function _createStorageResource(\n id: string | KeyFn,\n type: 'local-resource' | 'session-resource' | 'cache-resource',\n namespace: string | null\n): ClassDecorator {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n return function (target: Function) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const meta = getResourceMeta(target.prototype);\n meta.id = typeof id === 'string' ? id : '';\n meta.pkFn = typeof id === 'function' ? id : null;\n meta.type = type;\n meta.namespace = namespace;\n if (meta.pkFn !== null) {\n // for dynamic instances, we install effects only once\n // fields have been defined and a key created for the\n // instance.\n // for this, we defer effect installation until\n // until object instantiation by wrapping the constructor\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n const originalConstructor = target.prototype.constructor;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n target.prototype.constructor = function DynamicStorageInitializer(...args: unknown[]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, new-cap\n const instance = new originalConstructor(...args) as object;\n void installEffectsForDynamicInstance(meta, instance);\n return instance;\n };\n }\n\n if (!('toJSON' in target.prototype)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n target.prototype.toJSON = function (this: object) {\n const instanceMeta = useMeta(meta, this);\n // we only serialize the id and any localStorage fields, not sessionStorage fields.\n const isLocalResource = meta.type === 'local-resource' || meta.type === 'cache-resource';\n const fields = isLocalResource ? new Set(meta.fields.keys()) : new Set<string>();\n for (const [key, overrideType] of meta.typeOverrides?.entries() ?? []) {\n if (overrideType === 'local-storage') {\n fields.add(key);\n } else if (overrideType === 'session-storage' && isLocalResource) {\n fields.delete(key);\n }\n }\n let idKey = '$key';\n while (fields.has(idKey)) {\n idKey = `_${idKey}`;\n }\n const data: Record<string, unknown> = {\n [idKey]: instanceMeta.id,\n };\n\n for (const key of fields) {\n const value = getField(this, instanceMeta, key, meta.typeOverrides?.get(key) ?? null);\n if (value !== null) {\n data[key] = value;\n }\n }\n\n return data;\n };\n }\n };\n}\n\nasync function installEffectsForDynamicInstance(meta: StorageResourceMeta, instance: object): Promise<void> {\n await Promise.resolve();\n for (const [key, value] of meta.fields.entries()) {\n if (typeof value === 'function') {\n void installEffect(useMeta(meta, instance), key);\n }\n }\n}\n\n/**\n * Returns the descriptor but is cast\n * to void to satisfy Typescript's incorrect\n * typing for legacy decorators.\n */\nexport function setupField(\n target: object,\n key: string,\n orgDesc?: PropertyDescriptor,\n type?: 'local' | 'session' | 'cache'\n): void {\n const meta = initMeta(target);\n meta.fields.set(key, null);\n const overrideType =\n type === 'local'\n ? 'local-storage'\n : type === 'session'\n ? 'session-storage'\n : type === 'cache'\n ? 'cache-storage'\n : null;\n if (overrideType) {\n meta.typeOverrides = meta.typeOverrides || new Map<string, 'local-storage' | 'session-storage' | 'cache-storage'>();\n meta.typeOverrides.set(key, overrideType);\n }\n // @ts-expect-error initializer does exist\n const initializer = (orgDesc?.initializer || null) as (() => unknown) | null;\n meta.initializers.set(key, initializer);\n\n const desc = {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n };\n\n return memoized(target as Record<string, unknown>, key, desc) as unknown as void;\n}\n\nexport async function installEffect(meta: StorageResourceMeta, key: string): Promise<void> {\n await Promise.resolve();\n const effect = meta.fields.get(key) as <K>(v: ValueTransition<K>) => void;\n const storage = getStorage(meta.type, meta.namespace);\n storage.setEffect(keyFor(meta, key), (event: EffectStorageEvent) => {\n const oldValue = event.oldValue ? (JSON.parse(event.oldValue) as unknown) : null;\n const newValue = event.newValue ? (JSON.parse(event.newValue) as unknown) : null;\n effect({ key, from: oldValue, to: newValue });\n });\n}\n\n/**\n * Get or create the param companion object for a StorageResource instance.\n *\n * The companion object contains URL-serialized versions of all @param decorated fields.\n * Each param field gets a corresponding property on the companion that:\n * - Reads: Serializes the storage value to a URL string (returns null if not active)\n * - Writes: Deserializes the URL string and updates the storage value\n *\n * The companion object is reactive using trackedObject, ensuring that changes\n * to the underlying storage fields trigger updates in the query param system.\n *\n * This companion object is what QPRoute will bind to for URL query params.\n *\n * @private\n * @param instance - The StorageResource instance\n * @param groupControlMap - Optional map of fieldName -> controlFieldName for grouped params\n * @returns The companion object with serialized param properties\n */\nexport function getParamCompanion(instance: object, groupControlMap?: Record<string, string>): object {\n const meta = getResourceMeta(instance);\n const instanceMeta = useMeta(meta, instance);\n\n // Return existing companion if already created\n if (instanceMeta.paramCompanion) {\n return instanceMeta.paramCompanion;\n }\n\n // Create new companion object\n const companion = {};\n instanceMeta.paramCompanion = companion;\n\n // Install a property for each param\n const paramConfigs = instanceMeta.paramConfigs;\n if (!paramConfigs || paramConfigs.size === 0) {\n return companion;\n }\n\n for (const [fieldName, config] of paramConfigs.entries()) {\n const controlFieldName = groupControlMap?.[fieldName];\n\n createParamField(companion, fieldName, config, controlFieldName, instance, meta);\n }\n\n return companion;\n}\n\nfunction isActiveGroupParam(companion: object, controlFieldName: string): boolean {\n // if the url value for the control param is `null` we are inactive\n const controlValue = (companion as Record<string, unknown>)[controlFieldName];\n return controlValue !== null;\n}\n\n/**\n * The default value of a param is determined by:\n * - the getDefault() function if provided, and its return is not undefined\n * - the initializer value provided to the field, if not undefined\n * - null otherwise\n *\n * The value is the deserialized form (i.e., the local storage value type)\n */\nfunction getParamFieldDefaultValue(\n meta: StorageResourceMeta,\n config: ParamConfig,\n fieldName: string,\n instance: object\n) {\n const defaultValue = config.getDefault?.(instance);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n const initializer = meta.initializers.get(fieldName);\n if (initializer) {\n const initValue = initializer.call(instance);\n\n if (initValue !== undefined) {\n return initValue;\n }\n }\n\n return null;\n}\n\nfunction createParamField(\n companion: object,\n fieldName: string,\n config: InternalParamConfig,\n controlFieldName: string | undefined,\n instance: object,\n meta: StorageResourceMeta\n): void {\n const desc = {\n configurable: true,\n enumerable: true,\n get(): string | null {\n // Mark as initialized on first access, but continue with normal logic\n if (!config.initialized) {\n config.initialized = true;\n return null;\n }\n\n // Next, check if this param is part of a group and if its control param is active\n // If not active, return null to indicate inactive state\n if (controlFieldName && !isActiveGroupParam(companion, controlFieldName)) {\n return null;\n }\n\n // Next, check if the currently stored value is the default\n // value. If so, return null to indicate inactive state\n const defaultValue = getParamFieldDefaultValue(meta, config, fieldName, instance);\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n if (rawValue === defaultValue) {\n return null;\n }\n\n // Serialize to URL format\n const serialized = config.serialize(rawValue, instance);\n\n // Return null if serialization returns empty, indicating no URL representation\n if (!serialized) {\n return null;\n }\n\n return serialized;\n },\n set(urlValue: string | null) {\n /**\n * set will never come from anything except URL deserialization.\n * which is managed by Ember.\n *\n * Our job is to not unnecessarily update the storage resource\n * so we need to run the compare function to see if the\n * incoming URL value is different from the existing local value.\n */\n\n // If null or empty, skip deserialization\n if (!urlValue) {\n return;\n }\n\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n // Compare incoming URL value with existing local value\n const rawValueSerialized = config.serialize(rawValue, instance);\n if (rawValueSerialized === urlValue) {\n // No change\n return;\n }\n\n // Deserialize from URL format\n const newRawValue = config.deserialize(urlValue, instance);\n\n // Update the storage resource\n (instance as Record<string, unknown>)[fieldName] = newRawValue;\n },\n };\n\n memoized(companion as Record<string, unknown>, fieldName, desc);\n Object.defineProperty(companion, fieldName, desc);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nimport {\n _createStorageResource,\n getField,\n initMeta,\n installEffect,\n type KeyFn,\n setField,\n setupField,\n useMeta,\n type ValueTransition,\n} from './-private/storage-infra.ts';\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in localStorage.\n *\n * LocalResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function LocalResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'local-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in sessionStorage.\n *\n * SessionResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function SessionResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'session-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted via the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n * api and shared across all tabs/windows under the same origin.\n *\n * CacheResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n *\n * All object cached in the same `namespace` share the namespace's storage context,\n * so partitioning can be achieved by using different namespaces for different groups\n * of data.\n */\nexport function CacheResource(id: string | KeyFn, namespace: string | null = null): ClassDecorator {\n return _createStorageResource(id, 'cache-resource', namespace);\n}\n\n/**\n * Decorator which marks a property as a field on\n * a LocalResource or SessionResource\n *\n * The field's value will be initialized from the persisted resource data\n * if available, falling back to the property's default value otherwise.\n *\n * Fields can be of any type that is serializable to and restorable from JSON,\n * but complex types (like objects or arrays) should be handled with care to avoid\n * unintended mutations or reactivity issues.\n *\n * By default, fields are persisted in the storage type defined by the resource decorator\n * (@LocalResource or @SessionResource). However, you can override this behavior\n * by passing 'local' or 'session' as an argument to the decorator.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-settings')\n * class UserSettings {\n * @field\n * theme: 'light' | 'dark' = 'light';\n *\n * @field('session')\n * sessionToken: string | null = null;\n * }\n * ```\n *\n */\nexport function field(type: 'local' | 'session' | 'cache'): PropertyDecorator;\nexport function field(target: object, key: string, descriptor?: PropertyDescriptor): void;\nexport function field(...args: unknown[]): PropertyDecorator | void {\n if (args.length === 0) {\n assert('field decorator requires at least 1 argument or should be used without parens', true);\n return setupField as PropertyDecorator;\n }\n if (args.length === 1) {\n const type = args[0] as 'local' | 'session' | 'cache';\n return ((target: object, key: string, desc?: PropertyDescriptor) =>\n setupField(target, key, desc, type)) as PropertyDecorator;\n }\n if (args.length === 2 || args.length === 3) {\n const [target, key, descriptor] = args as [object, string, PropertyDescriptor | undefined];\n return setupField(target, key, descriptor);\n }\n}\nexport function input(type: 'number' | 'boolean' | 'float'): PropertyDecorator {\n assert('input decorator requires a valid type argument', ['number', 'boolean', 'float'].includes(type));\n return function (target: object, key: string, desc: PropertyDescriptor): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalSet = desc.set!;\n desc.set = function (this: object, value: unknown) {\n switch (type) {\n case 'number':\n value = Number(value);\n break;\n case 'boolean':\n value =\n value === 'false' ||\n value === '' ||\n value === '0' ||\n value === 'undefined' ||\n value === 'null' ||\n value === false ||\n value === 0 ||\n value === null ||\n value === undefined\n ? 0\n : 1;\n break;\n default:\n assert(`Unsupported input type: ${type}`);\n }\n originalSet.call(this, value);\n };\n return desc as unknown as void;\n } as PropertyDecorator;\n}\n\n/**\n * Effects are fields that run a side-effecting function.\n *\n * Effects are intended to enable synchronizing get states between\n * tabs or windows that result in needing to synchronize other\n * non-reactive state.\n *\n * For example, when a user selects a light/dark mode theme preference\n * that differs from the system preference, effects can be used to trigger\n * DOM updates on the documentElement necessary to ensure its state is\n * consistent with the persisted resource state and reactive application state.\n *\n * To do this without an effect would require either setting up your own\n * storage event listeners or consuming the reactive state of the property\n * in another effect-like API such as an Ember modifier or React useEffect,\n *\n * Effects *only* run when the stored value changes due to storage events\n * emitted from other tabs or windows. They do not run when the property\n * is updated in the same context.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-preferences')\n * class UserPreferences {\n * @effect(syncThemeToDOM)\n * explicitThemePreference: 'light' | 'dark' | null = null;\n *\n * @matchMedia('(prefers-color-scheme: dark)')\n * systemPrefersDarkMode: boolean = false;\n * }\n *\n * function syncThemeToDOM(update: ValueTransition<'light' | 'dark' | null>): void {\n * const newTheme = update.to;\n * document.documentElement.style.colorScheme = newTheme ?? 'light dark';\n *\n * if (newTheme === 'dark') {\n * document.documentElement.classList.add('dark-theme');\n * document.documentElement.classList.remove('light-theme');\n * } else if (newTheme === 'light') {\n * document.documentElement.classList.add('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * } else {\n * document.documentElement.classList.remove('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * }\n * }\n * ```\n */\nexport function effect(fn: <K>(update: ValueTransition<K>) => void, type?: 'local' | 'session'): PropertyDecorator {\n const overrideType = type === 'local' ? 'local-storage' : type === 'session' ? 'session-storage' : null;\n return function effectField(\n target: object,\n key: string,\n\n _descriptor?: PropertyDescriptor\n ): void {\n const meta = initMeta(target);\n meta.fields.set(key, fn);\n\n // only install the effect if we are not in a primary-keyed instance context\n if (meta.pkFn === null) void installEffect(meta, key);\n\n return {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n } as unknown as void;\n } as unknown as PropertyDecorator;\n}\n"],"mappings":";;;;;;;AAcA,IAAaK,YAAb,MAAyC;CAC/BC,OAA0B,CAAC;CAG3BC,WAAwBH,gBAAgB,KAAKE,IAAI;CAEzDE,UAAUC,KAAiB;EACzB,EAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOF,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMG,WAAW,KAAKL,SAASM,IAAIJ,GAAG;EACtCR,eAAe,KAAKM,UAAU,KAAKD,MAAMG,KAAKK,MAAS;EACvD,MAAMC,OAAO,KAAKC;EAClB,KAAKA,QAAQJ,WAAWG,OAAOA,OAAO;EACtC,OAAOH;CACT;CAEAK,OAAOR,KAAc;EACnB,EAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOF,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMS,SAAShB,0BAA0B,KAAKK,UAAU,KAAKD,MAAMG,KAAK,CAAC;EACzEN,qBAAqBe,MAAM;CAC7B;CAEAC,QAAc;EACZ,KAAK,MAAMC,SAAS,KAAKb,SAASc,OAAO,GACvClB,qBAAqBiB,KAAK;EAE5B,KAAKJ,QAAQ;CACf;CAEA,IAAID,OAAe;EACjB,OAAO,KAAKC;CACd;AACF;AACAhB,aAAaK,UAAUiB,WAAW,SAAS,CAAC;;;;AC5C5C,MAAaC,mBAAmB;AAChC,MAAMC,yBAAS,IAAIC,IAA0B;AAC7C,MAAMC,gBAAgB,IAAIC,iBAAiB,uBAAuB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AC,MAAO,2BAA2BC,MAAM;IAAA,EAAA,CAAA,KAAA;GAC5C;GACAO,YAAYK,KAAK,MAAMH,KAAK;EAC9B;EACA,OAAON;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgBU,OAAOC,IAA6Cd,MAA+C;CACjH,MAAMe,eAAef,SAAS,UAAU,kBAAkBA,SAAS,YAAY,oBAAoB;CACnG,OAAO,SAASgB,YACdf,QACAC,KAEAe,aACM;EACN,MAAMC,OAAOjC,SAASgB,MAAM;EAC5BiB,KAAKC,OAAOX,IAAIN,KAAKY,EAAE;EAGvB,IAAII,KAAKE,SAAS,MAAM,AAAKlC,cAAcgC,MAAMhB,GAAG;EAEpD,OAAO;GACLmB,cAAc;GACdC,YAAY;GACZC,MAA2B;IACzB,OAAOvC,SAAS,MAAMK,QAAQ6B,MAAM,IAAI,GAAGhB,KAAKa,YAAY;GAC9D;GACAP,IAAkBC,OAAgB;IAChCtB,SAASE,QAAQ6B,MAAM,IAAI,GAAGhB,KAAKO,OAAiBM,YAAY;GAClE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"storage.js","names":["defineSignal","entangleSignal","getOrCreateInternalSignal","notifyInternalSignal","withSignalStore","SignalMap","_map","_signals","subscribe","key","test","Error","existing","has","undefined","size","_size","notify","signal","clear","value","values","prototype","DEFAULT_CACHE_ID","CACHES","Map","StorageEvents","BroadcastChannel","CACHE_URL","location","origin","emitStorageEvent","event","window","dispatchEvent","CustomEvent","detail","handleCacheEvent","data","cache","get","storageArea","key","_data","oldValue","newValue","delete","set","addEventListener","CacheStorage","cacheId","inititalization","_nextUpdate","_bufferedEvents","initialize","#initialize","caches","open","deserializeFromCache","constructor","length","size","update","#update","Error","push","setTimeout","events","serializeToCache","postMessage","clear","getItem","index","test","Number","isInteger","i","value","keys","removeItem","has","setItem","expectCache","getAllCacheIds","Array","from","entries","blob","JSON","stringify","version","response","Response","put","match","then","json","defineSignal","makeInitializer","SignalMap","CacheStorage","DEFAULT_CACHE_ID","localStorageInstance","sessionStorageInstance","localStorageOptions","sessionStorageOptions","getLocalStorage","ReactiveStorage","localStorage","getSessionStorage","sessionStorage","CacheStorages","Map","getCacheStorage","namespace","key","cache","get","storage","expectCache","set","configureLocalStorage","options","configureSessionStorage","isQuotaExceededError","error","DOMException","name","isStorageUnavailableError","_storage","_options","_memoryOnly","_values","_effects","setEffect","fn","test","Error","has","constructor","testKey","setItem","removeItem","_length","length","fallbackToMemory","window","addEventListener","event","data","detail","storageArea","newValue","_signals","notify","effect","peekItem","keyStr","String","value","undefined","item","getItem","subscribe","valueStr","current","currentValue","updateOnQuotaExceeded","onQuotaExceeded","result","retry","Promise","clear","index","keys","Object","filter","k","prototype","memoized","getCacheStorage","getLocalStorage","getSessionStorage","PERSISTED_RESOURCE_META","Symbol","initMeta","target","meta","id","namespace","pkFn","type","fields","Map","initializers","paramConfigs","paramCompanion","instances","typeOverrides","useMeta","instance","WeakMap","instanceMeta","get","pk","test","Error","length","set","getField","key","overrideType","storage","getStorage","stored","getItem","keyFor","JSON","parse","initializer","value","call","undefined","peekField","peekItem","initializeFields","source","baseMeta","getResourceMeta","entries","newValue","defaultValue","currentValue","localStorage","sessionStorage","setItem","stringify","setField","_createStorageResource","prototype","originalConstructor","constructor","DynamicStorageInitializer","args","installEffectsForDynamicInstance","toJSON","isLocalResource","Set","keys","add","delete","idKey","has","data","Promise","resolve","installEffect","setupField","orgDesc","desc","configurable","enumerable","effect","setEffect","event","oldValue","from","to","getParamCompanion","groupControlMap","companion","size","fieldName","config","controlFieldName","createParamField","isActiveGroupParam","controlValue","getParamFieldDefaultValue","getDefault","initValue","initialized","rawValue","serialized","serialize","urlValue","rawValueSerialized","newRawValue","deserialize","Object","defineProperty","_createStorageResource","getField","initMeta","installEffect","setField","setupField","useMeta","LocalResource","id","SessionResource","CacheResource","namespace","field","args","length","test","Error","type","target","key","desc","descriptor","input","includes","originalSet","set","value","Number","undefined","call","effect","fn","overrideType","effectField","_descriptor","meta","fields","pkFn","configurable","enumerable","get"],"sources":["../../../src/storage/-private/reactive-map.ts","../../../src/storage/cache.ts","../../../src/storage/storage.ts","../../../src/storage/-private/storage-infra.ts","../../../src/storage/storage-resource.ts"],"sourcesContent":["import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { SignalStore } from '@warp-drive-mirror/core/signals/-leaked';\nimport {\n defineSignal,\n entangleSignal,\n getOrCreateInternalSignal,\n notifyInternalSignal,\n withSignalStore,\n} from '@warp-drive-mirror/core/signals/-leaked';\n\n/**\n * A reactive wrapper around the browser's Map API that provides\n * granular per-key reactivity via WarpDrive's signal system.\n */\nexport class SignalMap<K extends string> {\n private _map: Record<K, number> = {} as Record<K, number>;\n // _size is signal-backed via defineSignal below\n declare private _size: number;\n private _signals: SignalStore = withSignalStore(this._map);\n\n subscribe(key: K): boolean {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const existing = this._signals.has(key);\n entangleSignal(this._signals, this._map, key, undefined);\n const size = this._size;\n this._size = existing ? size : size + 1;\n return existing;\n }\n\n notify(key: K): void {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const signal = getOrCreateInternalSignal(this._signals, this._map, key, 0);\n notifyInternalSignal(signal);\n }\n\n clear(): void {\n for (const value of this._signals.values()) {\n notifyInternalSignal(value);\n }\n this._size = 0;\n }\n\n get size(): number {\n return this._size;\n }\n}\ndefineSignal(SignalMap.prototype, '_size', 0);\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nexport const DEFAULT_CACHE_ID = 'reactive-cache';\nconst CACHES = new Map<string, CacheStorage>();\nconst StorageEvents = new BroadcastChannel('reactive-cache-events');\nconst CACHE_URL = `${location.origin}/api/reactive-cache.json`;\n\nexport interface InternalCacheStorageEvent {\n storageArea: string;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\nexport interface CacheStorageEvent {\n storageArea: CacheStorage;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\n\n/**\n * Emits a {@link StorageEvent} on the local context to\n * match the broadcast event.\n */\nfunction emitStorageEvent(event: CacheStorageEvent): void {\n window.dispatchEvent(new CustomEvent('storage', { detail: event }));\n}\n\n/**\n * Updates the cache and re-emits the event on the local context as a StorageEvent\n * This is necessary to trigger the reactive updates in the current tab.\n */\nfunction handleCacheEvent(event: MessageEvent<InternalCacheStorageEvent>): void {\n const { data } = event;\n\n const cache = CACHES.get(data.storageArea);\n // if we don't have an instance of the cache in this context\n // then we don't need to do anything since there are no reactive\n // subscribers to update\n if (!cache) {\n return;\n }\n\n // a StorageEvent with a key of null\n // is a signal that the entire cache should be cleared.\n if (data.key === null) {\n cache._data = new Map();\n emitStorageEvent({\n storageArea: cache,\n key: null,\n oldValue: null,\n newValue: null,\n });\n return;\n }\n\n if (data.newValue === null) {\n // remove the key from the cache\n cache._data.delete(data.key);\n } else {\n // update the cache with the new value\n cache._data.set(data.key, data.newValue);\n }\n\n // emit a StorageEvent to trigger reactive updates in this context\n emitStorageEvent({\n storageArea: cache,\n key: data.key,\n oldValue: data.oldValue,\n newValue: data.newValue,\n });\n}\n\n// subscribe to all storage events from other contexts to\n// keep caches in sync\nStorageEvents.addEventListener('message', handleCacheEvent);\n\n/**\n * A reactive interface for json stored in the browser [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API.\n *\n * This is a good option for larger data sets than can be efficiently stored in localStorage\n * but should not be used as a permanent DB or storage solution.\n */\nexport class CacheStorage implements Storage {\n #cache: Cache | null;\n #cacheId: string;\n #inititalization: Promise<CacheStorage>;\n _data: Map<string, string | null> = new Map();\n _nextUpdate: number | null = null;\n _bufferedEvents: InternalCacheStorageEvent[] = [];\n\n async #initialize() {\n const cache = await caches.open(this.#cacheId);\n this.#cache = cache;\n\n // Load all existing entries into memory\n this._data = await deserializeFromCache(cache);\n\n return this;\n }\n\n constructor(cacheId: string) {\n this.#cacheId = cacheId;\n this.#cache = null;\n this.#inititalization = this.#initialize();\n }\n\n get length(): number {\n return this._data.size;\n }\n\n #update(key: string | null, oldValue: string | null, newValue: string | null) {\n const cache = this.#cache;\n if (!cache) {\n throw new Error('Cache not initialized');\n }\n this._bufferedEvents.push({\n storageArea: this.#cacheId,\n key: key,\n oldValue: oldValue,\n newValue: newValue,\n });\n if (!this._nextUpdate) {\n this._nextUpdate = window.setTimeout(() => {\n const events = this._bufferedEvents;\n this._bufferedEvents = [];\n this._nextUpdate = null;\n void serializeToCache(cache, this._data);\n for (const event of events) {\n StorageEvents.postMessage(event);\n }\n }, 0);\n }\n }\n\n clear(): void {\n this._data = new Map();\n this.#update(null, null, null);\n }\n\n getItem(key: string): string | null {\n return this._data.get(key) ?? null;\n }\n\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n assert('ReactiveStorage.key: index must be a non-negative integer', index >= 0 && Number.isInteger(index));\n assert('ReactiveStorage.key: index must be less than the number of items in storage', index < this.length);\n\n let i = 0;\n for (const value of this._data.keys()) {\n if (i === index) {\n return value;\n }\n i++;\n }\n\n return null;\n }\n\n removeItem(key: string): void {\n if (this._data.has(key)) {\n const oldValue = this._data.get(key) ?? null;\n this._data.delete(key);\n this.#update(key, oldValue, null);\n }\n }\n\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n const oldValue = this._data.get(key) ?? null;\n if (oldValue === value) {\n return;\n }\n this._data.set(key, value);\n this.#update(key, oldValue, value);\n }\n\n /**\n * Get the singleton CacheStorage instance.\n *\n */\n static get(cacheId: string = DEFAULT_CACHE_ID): Promise<CacheStorage> {\n let cache = CACHES.get(cacheId);\n if (!cache) {\n cache = new CacheStorage(cacheId);\n CACHES.set(cacheId, cache);\n }\n return cache.#inititalization;\n }\n\n static expectCache(cacheId: string = DEFAULT_CACHE_ID): CacheStorage {\n const cache = CACHES.get(cacheId);\n if (!cache) {\n throw new Error(`Cache with id ${cacheId} not found. Make sure to call CacheStorage.get(${cacheId}) first.`);\n }\n return cache;\n }\n\n /**\n * Returns the IDs of all {@link CacheStorage} instances that have been\n * opened in this context via {@link CacheStorage.get}.\n */\n static getAllCacheIds(): string[] {\n return Array.from(CACHES.keys());\n }\n}\n\ninterface CacheFile {\n version: 1;\n data: Array<[string, string]>;\n}\n\nfunction serializeToCache(cache: Cache, data: Map<string, string | null>): Promise<void> {\n const entries = Array.from(data.entries());\n const blob = JSON.stringify({\n version: 1,\n data: entries,\n });\n const response = new Response(blob);\n return cache.put(CACHE_URL, response);\n}\n\nfunction deserializeFromCache(cache: Cache): Promise<Map<string, string | null>> {\n return cache.match(CACHE_URL).then((response) => {\n if (!response) {\n return new Map();\n }\n return response.json().then((json: CacheFile) => {\n if (json.version !== 1) {\n throw new Error(`Unsupported cache version: ${json.version as string}`);\n }\n return new Map(json.data);\n });\n });\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { defineSignal, makeInitializer } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { SignalMap } from './-private/reactive-map.ts';\nimport { CacheStorage, type CacheStorageEvent, DEFAULT_CACHE_ID } from './cache.ts';\n\nexport interface ReactiveStorageOptions {\n /**\n * If true, falls back to in-memory storage when the underlying\n * storage is unavailable (e.g., private browsing mode).\n */\n fallbackToMemory?: boolean;\n\n /**\n * If true, updates signal state even when writes fail due to quota.\n * The onQuotaExceeded callback will be invoked before retrying.\n */\n updateOnQuotaExceeded?: boolean;\n\n /**\n * Called when a write fails due to quota exceeded.\n * Return true to retry the write after freeing space.\n */\n onQuotaExceeded?: (key: string, value: string) => boolean | Promise<boolean>;\n}\n\nlet localStorageInstance: ReactiveStorage | null = null;\nlet sessionStorageInstance: ReactiveStorage | null = null;\nlet localStorageOptions: ReactiveStorageOptions = {};\nlet sessionStorageOptions: ReactiveStorageOptions = {};\n\n// This pattern enables us to have a singleton service-like\n// instance that also functions as a global singleton that\n// can be imported and used outside of Ember's DI system.\n/**\n * Retrieves the singleton instance of the LocalStorage service.\n *\n * If the instance does not already exist, it is created.\n */\nexport function getLocalStorage(): ReactiveStorage {\n if (!localStorageInstance) {\n localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);\n }\n return localStorageInstance;\n}\n\nexport function getSessionStorage(): ReactiveStorage {\n if (!sessionStorageInstance) {\n sessionStorageInstance = new ReactiveStorage(sessionStorage, sessionStorageOptions);\n }\n return sessionStorageInstance;\n}\n\nconst CacheStorages = new Map<string, ReactiveStorage>();\nexport function getCacheStorage(namespace: string | null = null): ReactiveStorage {\n const key = namespace ?? DEFAULT_CACHE_ID;\n let cache = CacheStorages.get(key);\n if (!cache) {\n const storage = CacheStorage.expectCache(key);\n cache = new ReactiveStorage(storage);\n CacheStorages.set(key, cache);\n }\n return cache;\n}\n\n/**\n * Configure options for the localStorage singleton.\n * Must be called before getLocalStorage() is first invoked.\n */\nexport function configureLocalStorage(options: ReactiveStorageOptions): void {\n localStorageOptions = options;\n}\n\n/**\n * Configure options for the sessionStorage singleton.\n * Must be called before getSessionStorage() is first invoked.\n */\nexport function configureSessionStorage(options: ReactiveStorageOptions): void {\n sessionStorageOptions = options;\n}\n\n/**\n * Check if an error is a quota exceeded error\n */\nfunction isQuotaExceededError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Most browsers\n if (error.name === 'QuotaExceededError') return true;\n // Firefox\n if (error.name === 'NS_ERROR_DOM_QUOTA_REACHED') return true;\n }\n return false;\n}\n\n/**\n * Check if an error indicates storage is unavailable (private browsing, etc.)\n */\nfunction isStorageUnavailableError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Safari private browsing, some security restrictions\n if (error.name === 'SecurityError') return true;\n // Some browsers throw this in private mode\n if (error.name === 'InvalidStateError') return true;\n }\n return false;\n}\n\nexport type EffectStorageEvent = CacheStorageEvent | StorageEvent;\n\n/**\n * A reactive wrapper around the Web Storage API (localStorage/sessionStorage)\n * that provides signal-based access to storage items and length.\n *\n * Will automatically update when storage events occur in other tabs/windows.\n */\nclass ReactiveStorage implements Storage {\n private _storage: Storage;\n private _options: ReactiveStorageOptions;\n private _memoryOnly = false;\n private _values: Record<string, string | null> = {};\n\n declare private _signals: SignalMap<string>;\n declare private _length: number;\n\n private _effects = new Map<string, (value: EffectStorageEvent) => void>();\n setEffect(key: string, fn: (value: EffectStorageEvent) => void): void {\n assert(`Can only set effect once for key: ${key}`, !this._effects.has(key));\n this._effects.set(key, fn);\n }\n\n constructor(storage: Storage, options: ReactiveStorageOptions = {}) {\n this._storage = storage;\n this._options = options;\n\n if (!(storage instanceof CacheStorage)) {\n // Test if storage is accessible\n try {\n const testKey = '__storage_test__';\n storage.setItem(testKey, testKey);\n storage.removeItem(testKey);\n this._length = storage.length;\n } catch (error) {\n if (options.fallbackToMemory && isStorageUnavailableError(error)) {\n this._memoryOnly = true;\n this._length = 0;\n } else {\n throw error;\n }\n }\n }\n\n // bind to localStorage events to trigger reactivity\n if (!this._memoryOnly) {\n window.addEventListener('storage', ((event: StorageEvent | CustomEvent<CacheStorageEvent>) => {\n const data = 'detail' in event ? event.detail : event;\n\n // Only react to changes in the same storage area\n if (data.storageArea === storage) {\n this._values[data.key as string] = data.newValue;\n this._signals.notify(data.key as string);\n this._length = this._storage.length;\n const effect = this._effects.get(data.key as string);\n if (effect) {\n effect(data);\n }\n }\n }) as EventListener);\n }\n }\n\n /**\n * Reactive access to the number of keys in Storage\n */\n get length(): number {\n return this._length;\n }\n\n /**\n * Non-reactive way to peek the current value of a key in Storage\n */\n peekItem(key: string): string | null {\n assert('ReactiveStorage.peekItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n return value;\n }\n\n // Not yet loaded, fetch from storage, but don't track access\n const item = this._storage.getItem(keyStr);\n // this._values[keyStr] = item;\n return item;\n }\n\n /**\n * Reactive access to Storage contents\n */\n getItem(key: string): string | null {\n assert('ReactiveStorage.getItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n this._signals.subscribe(keyStr);\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n this._signals.subscribe(keyStr);\n return value;\n }\n\n // Not yet loaded, fetch from storage\n const item = this._storage.getItem(keyStr);\n this._values[keyStr] = item;\n this._signals.subscribe(keyStr);\n return item;\n }\n\n /**\n * Set a value in Storage, triggering reactivity\n */\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n\n // Coerce to strings to match Storage API behavior\n const keyStr = String(key);\n const valueStr = String(value);\n const current = this._values[keyStr];\n if (current === valueStr) {\n // No change\n return;\n }\n\n // console.trace(`set field ${key} => ${String(value)}`);\n\n if (this._memoryOnly) {\n const currentValue = this._values[keyStr];\n if (currentValue === null || currentValue === undefined) {\n this._length += 1;\n }\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n return;\n }\n\n try {\n this._storage.setItem(keyStr, valueStr);\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n } catch (error) {\n if (isQuotaExceededError(error)) {\n if (this._options.updateOnQuotaExceeded) {\n // Update signal state even though write failed\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n }\n\n if (this._options.onQuotaExceeded) {\n const result = this._options.onQuotaExceeded(keyStr, valueStr);\n const retry = result instanceof Promise ? false : result;\n\n if (retry) {\n // Retry the write after callback freed space\n this._storage.setItem(keyStr, valueStr);\n this._length = this._storage.length;\n }\n } else {\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Remove a value from Storage, triggering reactivity\n */\n removeItem(key: string): void {\n assert('ReactiveStorage.removeItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n const value = this._values[keyStr];\n if (value !== null && value !== undefined) {\n this._length -= 1;\n }\n this._values[keyStr] = null;\n return;\n }\n\n this._storage.removeItem(keyStr);\n this._values[keyStr] = null;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n }\n\n /**\n * Clears all keys from Storage, triggering reactivity\n */\n clear(): void {\n this._values = {};\n this._signals.clear();\n this._length = 0;\n\n if (this._memoryOnly) {\n return;\n }\n\n this._storage.clear();\n }\n\n /**\n * Reactive access to the key at the given index\n */\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n // oxlint-disable-next-line no-unused-expressions\n this._length; // track length access\n\n if (this._memoryOnly) {\n const keys = Object.keys(this._values).filter((k) => this._values[k] !== null);\n return keys[index] ?? null;\n }\n\n return this._storage.key(index);\n }\n}\ndefineSignal(ReactiveStorage.prototype, '_length', 0);\ndefineSignal(\n ReactiveStorage.prototype,\n '_signals',\n makeInitializer(() => new SignalMap<string>())\n);\n\nexport type { ReactiveStorage };\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { memoized } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { type EffectStorageEvent, getCacheStorage, getLocalStorage, getSessionStorage } from '../storage.ts';\n\n/**\n * Configuration options for fields that are also query parameters\n */\nexport interface ParamConfig {\n /**\n * Convert a value into a string for storage in the URL.\n * `null` indicates the value should be omitted from the URL.\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n serialize: (value: unknown, instance: any) => string | null;\n /**\n * Convert a string value from the URL back into\n * its original type\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n deserialize: (urlValue: string, instance: any) => unknown;\n /**\n * Get the default value for this param from the given instance.\n *\n * If not present, the value passed to the field initializer\n * will be used as the default.\n *\n * This should return the value in the field's native type,\n * not the serialized URL form.\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n getDefault?: (instance: any) => unknown;\n}\n\ninterface InternalParamConfig extends ParamConfig {\n initialized?: boolean;\n}\n\nexport interface ValueTransition<T = unknown> {\n key: string;\n from: T;\n to: T;\n}\n\n/**\n * Metadata attached to persisted resource classes\n */\nexport interface StorageResourceMeta {\n id: string;\n namespace: string | null;\n pkFn: KeyFn | null;\n type: 'local-resource' | 'session-resource' | 'cache-resource';\n typeOverrides: Map<string, 'local-storage' | 'session-storage' | 'cache-storage'> | null;\n fields: Map<string, null | ((update: ValueTransition<string>) => void)>;\n initializers: Map<string, (() => unknown) | null>;\n paramConfigs: Map<string, InternalParamConfig> | null;\n paramCompanion: object | null;\n instances: WeakMap<object, StorageResourceMeta> | null;\n}\n\n/**\n * A function which generates a unique primary-key\n * string for a given LocalResource or SessionResource\n * instance.\n *\n * Use functions when you want to create more than\n * one instance of a resource type, each with its own\n * persisted data.\n */\n// oxlint-disable-next-line typescript/no-explicit-any\nexport type KeyFn = (obj: any) => string;\n\n/**\n * Symbol used to store persistence metadata on classes\n */\nconst PERSISTED_RESOURCE_META = Symbol('StorageResourceMeta');\n\n/**\n * Setup persisted resource metadata on target\n * if not already present\n *\n * @private\n */\nexport function initMeta(target: object): StorageResourceMeta {\n let meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n if (!meta) {\n meta = {\n id: '',\n namespace: null,\n pkFn: null,\n type: '' as 'local-resource' | 'session-resource',\n fields: new Map(),\n initializers: new Map(),\n paramConfigs: null,\n paramCompanion: null,\n instances: null,\n typeOverrides: null,\n };\n (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META] = meta;\n }\n return meta;\n}\n\nexport function useMeta(meta: StorageResourceMeta, instance: object): StorageResourceMeta {\n // If a primary key function is defined, use it to generate\n // a unique ID for this instance\n if (meta.id === '' && meta.pkFn) {\n // we are in an instance context\n meta.instances = meta.instances ?? new WeakMap();\n let instanceMeta = meta.instances.get(instance);\n if (!instanceMeta) {\n instanceMeta = { ...meta };\n const pk = meta.pkFn(instance);\n assert('Primary key function must return a non-empty string.', typeof pk === 'string' && pk.length > 0);\n instanceMeta.id = pk;\n meta.instances.set(instance, instanceMeta);\n }\n return instanceMeta;\n }\n\n assert('StorageResourceMeta must have a valid id.', typeof meta.id === 'string' && meta.id.length > 0);\n return meta;\n}\n\n/**\n * Load storage field\n */\nexport function getField(\n instance: object,\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): Record<string, unknown> | null {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.getItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n } else {\n // No stored value, check for initializer\n const initializer = meta.initializers.get(key);\n if (initializer) {\n const value = initializer.call(instance);\n if (value !== undefined) {\n return value as Record<string, unknown>;\n }\n }\n }\n return null;\n}\n\nfunction keyFor(meta: StorageResourceMeta, key: string): string {\n return `persisted:${meta.id}:${key}`;\n}\n\nfunction getStorage(type: string, namespace: string | null) {\n if (type === 'local-resource') {\n return getLocalStorage();\n } else if (type === 'session-resource') {\n return getSessionStorage();\n } else {\n return getCacheStorage(namespace);\n }\n}\n\nexport function peekField(\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): unknown {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.peekItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n }\n return null;\n}\n\nexport function initializeFields(instance: object, source: object): void {\n // we need to initialize the fields without reading from their reactive state\n // we also only want to initialize the field if it is still at its default value\n // as otherwise we are likely overwriting a persisted value or url value\n const baseMeta = getResourceMeta(instance);\n const meta = useMeta(baseMeta, instance);\n\n for (const [key] of meta.fields.entries()) {\n if (key in source) {\n // get the new value from source\n const newValue = (source as Record<string, unknown>)[key];\n\n // get the current default value from the field initializer\n const initializer = meta.initializers.get(key);\n let defaultValue: unknown = null;\n if (initializer) {\n defaultValue = initializer.call(instance);\n }\n\n // get the overrideType\n const overrideType = meta.typeOverrides?.get(key) ?? null;\n const type = overrideType || meta.type;\n\n // get the current stored value, without triggering reactivity\n const currentValue = peekField(meta, keyFor(meta, key), overrideType);\n\n // if there is no current value, silently update the field\n const storage = type === 'local-resource' ? localStorage : sessionStorage;\n storage.setItem(keyFor(meta, key), JSON.stringify(newValue));\n // only initialize if current value matches default value\n // or we have no persisted value yet.\n if (currentValue === defaultValue) {\n setField(meta, keyFor(meta, key), newValue as string, overrideType);\n }\n }\n }\n}\n\n/**\n * Update storage field\n */\nexport function setField(\n meta: StorageResourceMeta,\n key: string,\n value: string | boolean | null | number | Record<string, unknown> | unknown[],\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): void {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n storage.setItem(keyFor(meta, key), JSON.stringify(value));\n}\n\nfunction getResourceMeta(target: object): StorageResourceMeta {\n const meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n assert(\n 'StorageResourceMeta not found on target. Did you forget to use the @LocalResource() or @SessionResource() decorator?',\n meta !== undefined\n );\n return meta;\n}\n\nexport function _createStorageResource(\n id: string | KeyFn,\n type: 'local-resource' | 'session-resource' | 'cache-resource',\n namespace: string | null\n): ClassDecorator {\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n return function (target: Function) {\n // oxlint-disable-next-line typescript/no-unsafe-argument\n const meta = getResourceMeta(target.prototype);\n meta.id = typeof id === 'string' ? id : '';\n meta.pkFn = typeof id === 'function' ? id : null;\n meta.type = type;\n meta.namespace = namespace;\n if (meta.pkFn !== null) {\n // for dynamic instances, we install effects only once\n // fields have been defined and a key created for the\n // instance.\n // for this, we defer effect installation until\n // until object instantiation by wrapping the constructor\n // oxlint-disable-next-line typescript/no-unsafe-assignment, typescript/no-unsafe-member-access\n const originalConstructor = target.prototype.constructor;\n // oxlint-disable-next-line typescript/no-unsafe-member-access\n target.prototype.constructor = function DynamicStorageInitializer(...args: unknown[]) {\n /* oxlint-disable new-cap, typescript/no-unsafe-call */\n const instance = new originalConstructor(...args) as object;\n /* oxlint-enable new-cap, typescript/no-unsafe-call */\n void installEffectsForDynamicInstance(meta, instance);\n return instance;\n };\n }\n\n if (!('toJSON' in target.prototype)) {\n // oxlint-disable-next-line typescript/no-unsafe-member-access\n target.prototype.toJSON = function (this: object) {\n const instanceMeta = useMeta(meta, this);\n // we only serialize the id and any localStorage fields, not sessionStorage fields.\n const isLocalResource = meta.type === 'local-resource' || meta.type === 'cache-resource';\n const fields = isLocalResource ? new Set(meta.fields.keys()) : new Set<string>();\n for (const [key, overrideType] of meta.typeOverrides?.entries() ?? []) {\n if (overrideType === 'local-storage') {\n fields.add(key);\n } else if (overrideType === 'session-storage' && isLocalResource) {\n fields.delete(key);\n }\n }\n let idKey = '$key';\n while (fields.has(idKey)) {\n idKey = `_${idKey}`;\n }\n const data: Record<string, unknown> = {\n [idKey]: instanceMeta.id,\n };\n\n for (const key of fields) {\n const value = getField(this, instanceMeta, key, meta.typeOverrides?.get(key) ?? null);\n if (value !== null) {\n data[key] = value;\n }\n }\n\n return data;\n };\n }\n };\n}\n\nasync function installEffectsForDynamicInstance(meta: StorageResourceMeta, instance: object): Promise<void> {\n await Promise.resolve();\n for (const [key, value] of meta.fields.entries()) {\n if (typeof value === 'function') {\n void installEffect(useMeta(meta, instance), key);\n }\n }\n}\n\n/**\n * Returns the descriptor but is cast\n * to void to satisfy Typescript's incorrect\n * typing for legacy decorators.\n */\nexport function setupField(\n target: object,\n key: string,\n orgDesc?: PropertyDescriptor,\n type?: 'local' | 'session' | 'cache'\n): void {\n const meta = initMeta(target);\n meta.fields.set(key, null);\n const overrideType =\n type === 'local'\n ? 'local-storage'\n : type === 'session'\n ? 'session-storage'\n : type === 'cache'\n ? 'cache-storage'\n : null;\n if (overrideType) {\n meta.typeOverrides = meta.typeOverrides || new Map<string, 'local-storage' | 'session-storage' | 'cache-storage'>();\n meta.typeOverrides.set(key, overrideType);\n }\n // @ts-expect-error initializer does exist\n const initializer = (orgDesc?.initializer || null) as (() => unknown) | null;\n meta.initializers.set(key, initializer);\n\n const desc = {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n };\n\n return memoized(target as Record<string, unknown>, key, desc) as unknown as void;\n}\n\nexport async function installEffect(meta: StorageResourceMeta, key: string): Promise<void> {\n await Promise.resolve();\n const effect = meta.fields.get(key) as <K>(v: ValueTransition<K>) => void;\n const storage = getStorage(meta.type, meta.namespace);\n storage.setEffect(keyFor(meta, key), (event: EffectStorageEvent) => {\n const oldValue = event.oldValue ? (JSON.parse(event.oldValue) as unknown) : null;\n const newValue = event.newValue ? (JSON.parse(event.newValue) as unknown) : null;\n effect({ key, from: oldValue, to: newValue });\n });\n}\n\n/**\n * Get or create the param companion object for a StorageResource instance.\n *\n * The companion object contains URL-serialized versions of all @param decorated fields.\n * Each param field gets a corresponding property on the companion that:\n * - Reads: Serializes the storage value to a URL string (returns null if not active)\n * - Writes: Deserializes the URL string and updates the storage value\n *\n * The companion object is reactive using trackedObject, ensuring that changes\n * to the underlying storage fields trigger updates in the query param system.\n *\n * This companion object is what QPRoute will bind to for URL query params.\n *\n * @private\n * @param instance - The StorageResource instance\n * @param groupControlMap - Optional map of fieldName -> controlFieldName for grouped params\n * @returns The companion object with serialized param properties\n */\nexport function getParamCompanion(instance: object, groupControlMap?: Record<string, string>): object {\n const meta = getResourceMeta(instance);\n const instanceMeta = useMeta(meta, instance);\n\n // Return existing companion if already created\n if (instanceMeta.paramCompanion) {\n return instanceMeta.paramCompanion;\n }\n\n // Create new companion object\n const companion = {};\n instanceMeta.paramCompanion = companion;\n\n // Install a property for each param\n const paramConfigs = instanceMeta.paramConfigs;\n if (!paramConfigs || paramConfigs.size === 0) {\n return companion;\n }\n\n for (const [fieldName, config] of paramConfigs.entries()) {\n const controlFieldName = groupControlMap?.[fieldName];\n\n createParamField(companion, fieldName, config, controlFieldName, instance, meta);\n }\n\n return companion;\n}\n\nfunction isActiveGroupParam(companion: object, controlFieldName: string): boolean {\n // if the url value for the control param is `null` we are inactive\n const controlValue = (companion as Record<string, unknown>)[controlFieldName];\n return controlValue !== null;\n}\n\n/**\n * The default value of a param is determined by:\n * - the getDefault() function if provided, and its return is not undefined\n * - the initializer value provided to the field, if not undefined\n * - null otherwise\n *\n * The value is the deserialized form (i.e., the local storage value type)\n */\nfunction getParamFieldDefaultValue(\n meta: StorageResourceMeta,\n config: ParamConfig,\n fieldName: string,\n instance: object\n) {\n const defaultValue = config.getDefault?.(instance);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n const initializer = meta.initializers.get(fieldName);\n if (initializer) {\n const initValue = initializer.call(instance);\n\n if (initValue !== undefined) {\n return initValue;\n }\n }\n\n return null;\n}\n\nfunction createParamField(\n companion: object,\n fieldName: string,\n config: InternalParamConfig,\n controlFieldName: string | undefined,\n instance: object,\n meta: StorageResourceMeta\n): void {\n const desc = {\n configurable: true,\n enumerable: true,\n get(): string | null {\n // Mark as initialized on first access, but continue with normal logic\n if (!config.initialized) {\n config.initialized = true;\n return null;\n }\n\n // Next, check if this param is part of a group and if its control param is active\n // If not active, return null to indicate inactive state\n if (controlFieldName && !isActiveGroupParam(companion, controlFieldName)) {\n return null;\n }\n\n // Next, check if the currently stored value is the default\n // value. If so, return null to indicate inactive state\n const defaultValue = getParamFieldDefaultValue(meta, config, fieldName, instance);\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n if (rawValue === defaultValue) {\n return null;\n }\n\n // Serialize to URL format\n const serialized = config.serialize(rawValue, instance);\n\n // Return null if serialization returns empty, indicating no URL representation\n if (!serialized) {\n return null;\n }\n\n return serialized;\n },\n set(urlValue: string | null) {\n /**\n * set will never come from anything except URL deserialization.\n * which is managed by Ember.\n *\n * Our job is to not unnecessarily update the storage resource\n * so we need to run the compare function to see if the\n * incoming URL value is different from the existing local value.\n */\n\n // If null or empty, skip deserialization\n if (!urlValue) {\n return;\n }\n\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n // Compare incoming URL value with existing local value\n const rawValueSerialized = config.serialize(rawValue, instance);\n if (rawValueSerialized === urlValue) {\n // No change\n return;\n }\n\n // Deserialize from URL format\n const newRawValue = config.deserialize(urlValue, instance);\n\n // Update the storage resource\n (instance as Record<string, unknown>)[fieldName] = newRawValue;\n },\n };\n\n memoized(companion as Record<string, unknown>, fieldName, desc);\n Object.defineProperty(companion, fieldName, desc);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nimport {\n _createStorageResource,\n getField,\n initMeta,\n installEffect,\n type KeyFn,\n setField,\n setupField,\n useMeta,\n type ValueTransition,\n} from './-private/storage-infra.ts';\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in localStorage.\n *\n * LocalResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function LocalResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'local-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in sessionStorage.\n *\n * SessionResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function SessionResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'session-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted via the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n * api and shared across all tabs/windows under the same origin.\n *\n * CacheResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n *\n * All object cached in the same `namespace` share the namespace's storage context,\n * so partitioning can be achieved by using different namespaces for different groups\n * of data.\n */\nexport function CacheResource(id: string | KeyFn, namespace: string | null = null): ClassDecorator {\n return _createStorageResource(id, 'cache-resource', namespace);\n}\n\n/**\n * Decorator which marks a property as a field on\n * a LocalResource or SessionResource\n *\n * The field's value will be initialized from the persisted resource data\n * if available, falling back to the property's default value otherwise.\n *\n * Fields can be of any type that is serializable to and restorable from JSON,\n * but complex types (like objects or arrays) should be handled with care to avoid\n * unintended mutations or reactivity issues.\n *\n * By default, fields are persisted in the storage type defined by the resource decorator\n * (@LocalResource or @SessionResource). However, you can override this behavior\n * by passing 'local' or 'session' as an argument to the decorator.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-settings')\n * class UserSettings {\n * @field\n * theme: 'light' | 'dark' = 'light';\n *\n * @field('session')\n * sessionToken: string | null = null;\n * }\n * ```\n *\n */\nexport function field(type: 'local' | 'session' | 'cache'): PropertyDecorator;\nexport function field(target: object, key: string, descriptor?: PropertyDescriptor): void;\nexport function field(...args: unknown[]): PropertyDecorator | void {\n if (args.length === 0) {\n assert('field decorator requires at least 1 argument or should be used without parens', true);\n return setupField as PropertyDecorator;\n }\n if (args.length === 1) {\n const type = args[0] as 'local' | 'session' | 'cache';\n return ((target: object, key: string, desc?: PropertyDescriptor) =>\n setupField(target, key, desc, type)) as PropertyDecorator;\n }\n if (args.length === 2 || args.length === 3) {\n const [target, key, descriptor] = args as [object, string, PropertyDescriptor | undefined];\n return setupField(target, key, descriptor);\n }\n}\nexport function input(type: 'number' | 'boolean' | 'float'): PropertyDecorator {\n assert('input decorator requires a valid type argument', ['number', 'boolean', 'float'].includes(type));\n return function (target: object, key: string, desc: PropertyDescriptor): void {\n // oxlint-disable-next-line typescript/unbound-method\n const originalSet = desc.set!;\n desc.set = function (this: object, value: unknown) {\n switch (type) {\n case 'number':\n value = Number(value);\n break;\n case 'boolean':\n value =\n value === 'false' ||\n value === '' ||\n value === '0' ||\n value === 'undefined' ||\n value === 'null' ||\n value === false ||\n value === 0 ||\n value === null ||\n value === undefined\n ? 0\n : 1;\n break;\n default:\n assert(`Unsupported input type: ${type}`);\n }\n originalSet.call(this, value);\n };\n return desc as unknown as void;\n } as PropertyDecorator;\n}\n\n/**\n * Effects are fields that run a side-effecting function.\n *\n * Effects are intended to enable synchronizing get states between\n * tabs or windows that result in needing to synchronize other\n * non-reactive state.\n *\n * For example, when a user selects a light/dark mode theme preference\n * that differs from the system preference, effects can be used to trigger\n * DOM updates on the documentElement necessary to ensure its state is\n * consistent with the persisted resource state and reactive application state.\n *\n * To do this without an effect would require either setting up your own\n * storage event listeners or consuming the reactive state of the property\n * in another effect-like API such as an Ember modifier or React useEffect,\n *\n * Effects *only* run when the stored value changes due to storage events\n * emitted from other tabs or windows. They do not run when the property\n * is updated in the same context.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-preferences')\n * class UserPreferences {\n * @effect(syncThemeToDOM)\n * explicitThemePreference: 'light' | 'dark' | null = null;\n *\n * @matchMedia('(prefers-color-scheme: dark)')\n * systemPrefersDarkMode: boolean = false;\n * }\n *\n * function syncThemeToDOM(update: ValueTransition<'light' | 'dark' | null>): void {\n * const newTheme = update.to;\n * document.documentElement.style.colorScheme = newTheme ?? 'light dark';\n *\n * if (newTheme === 'dark') {\n * document.documentElement.classList.add('dark-theme');\n * document.documentElement.classList.remove('light-theme');\n * } else if (newTheme === 'light') {\n * document.documentElement.classList.add('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * } else {\n * document.documentElement.classList.remove('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * }\n * }\n * ```\n */\nexport function effect(fn: <K>(update: ValueTransition<K>) => void, type?: 'local' | 'session'): PropertyDecorator {\n const overrideType = type === 'local' ? 'local-storage' : type === 'session' ? 'session-storage' : null;\n return function effectField(\n target: object,\n key: string,\n\n _descriptor?: PropertyDescriptor\n ): void {\n const meta = initMeta(target);\n meta.fields.set(key, fn);\n\n // only install the effect if we are not in a primary-keyed instance context\n if (meta.pkFn === null) void installEffect(meta, key);\n\n return {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n } as unknown as void;\n } as unknown as PropertyDecorator;\n}\n"],"mappings":";;;;;;;AAcA,IAAaK,YAAb,MAAyC;CAC/BC,OAA0B,CAAC;CAG3BC,WAAwBH,gBAAgB,KAAKE,IAAI;CAEzDE,UAAUC,KAAiB;EACzB,EAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOF,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMG,WAAW,KAAKL,SAASM,IAAIJ,GAAG;EACtCR,eAAe,KAAKM,UAAU,KAAKD,MAAMG,KAAKK,MAAS;EACvD,MAAMC,OAAO,KAAKC;EAClB,KAAKA,QAAQJ,WAAWG,OAAOA,OAAO;EACtC,OAAOH;CACT;CAEAK,OAAOR,KAAc;EACnB,EAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOF,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMS,SAAShB,0BAA0B,KAAKK,UAAU,KAAKD,MAAMG,KAAK,CAAC;EACzEN,qBAAqBe,MAAM;CAC7B;CAEAC,QAAc;EACZ,KAAK,MAAMC,SAAS,KAAKb,SAASc,OAAO,GACvClB,qBAAqBiB,KAAK;EAE5B,KAAKJ,QAAQ;CACf;CAEA,IAAID,OAAe;EACjB,OAAO,KAAKC;CACd;AACF;AACAhB,aAAaK,UAAUiB,WAAW,SAAS,CAAC;;;;AC5C5C,MAAaC,mBAAmB;AAChC,MAAMC,yBAAS,IAAIC,IAA0B;AAC7C,MAAMC,gBAAgB,IAAIC,iBAAiB,uBAAuB;AAClE,MAAMC,YAAY,GAAGC,SAASC,OAAM;;;;;AAmBpC,SAASC,iBAAiBC,OAAgC;CACxDC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