@warp-drive-mirror/experiments 0.0.1-alpha.106 → 0.0.1-alpha.108
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 +6 -2
- package/dist/data-worker.js.map +1 -1
- package/dist/document-storage.js +1 -1
- package/dist/image-worker.js +3 -1
- package/dist/image-worker.js.map +1 -1
- package/dist/{index-BhNHD6mY.js → index-Cn3o840t.js} +1 -4
- package/dist/index-Cn3o840t.js.map +1 -0
- package/package.json +12 -12
- package/unstable-preview-types/data-worker/cache-handler.d.ts.map +1 -1
- package/unstable-preview-types/image-worker/worker.d.ts.map +1 -1
- package/dist/index-BhNHD6mY.js.map +0 -1
package/dist/data-worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DocumentStorage } from "./index-
|
|
1
|
+
import { D as DocumentStorage } from "./index-Cn3o840t";
|
|
2
2
|
import { SkipCache } from '@warp-drive-mirror/core-types/request';
|
|
3
3
|
import { macroCondition, getGlobalConfig } from '@embroider/macros';
|
|
4
4
|
const WorkerScope = globalThis.SharedWorkerGlobalScope;
|
|
@@ -216,7 +216,11 @@ const CacheHandler = {
|
|
|
216
216
|
store.cache.put(document);
|
|
217
217
|
}
|
|
218
218
|
return completeRequest(identifier, store, context, next);
|
|
219
|
-
}).catch(
|
|
219
|
+
}).catch(e => {
|
|
220
|
+
if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
|
|
221
|
+
// eslint-disable-next-line no-console
|
|
222
|
+
console.log('Unable to retrieve document from persisted storage', e);
|
|
223
|
+
}
|
|
220
224
|
return completeRequest(identifier, store, context, next);
|
|
221
225
|
});
|
|
222
226
|
}
|
package/dist/data-worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-worker.js","sources":["../src/data-worker/worker.ts","../src/data-worker/utils.ts","../src/data-worker/cache-handler.ts"],"sourcesContent":["import type { Future, ResponseInfo, StructuredDataDocument } from '@ember-data-mirror/request';\nimport type Store from '@ember-data-mirror/store';\n\nimport { DocumentStorage } from '../document-storage';\nimport type { AbortEventData, RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nexport class DataWorker {\n declare store: Store;\n declare threads: Map<string, MessagePort>;\n declare pending: Map<string, Map<number, Future<unknown>>>;\n declare isSharedWorker: boolean;\n declare options: { persisted: boolean; scope?: string };\n declare storage: DocumentStorage;\n\n constructor(UserStore: typeof Store, options?: { persisted: boolean; scope?: string }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.store = new UserStore();\n this.threads = new Map();\n this.pending = new Map();\n this.options = Object.assign({ persisted: false, scope: '' }, options);\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n initialize() {\n // enable the CacheHandler to access the worker\n (this.store as unknown as { _worker: DataWorker })._worker = this;\n if (this.options.persisted) {\n // will be accessed by the worker's CacheHandler off of store\n this.storage = new DocumentStorage({ scope: this.options.scope });\n }\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 setupThread(thread: string, port: MessagePort) {\n this.threads.set(thread, port);\n this.pending.set(thread, new Map());\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 'abort':\n this.abortRequest(event.data);\n break;\n case 'request':\n void this.request(prepareRequest(event.data));\n break;\n }\n };\n }\n\n abortRequest(event: AbortEventData) {\n const { thread, id } = event;\n const future = this.pending.get(thread)!.get(id);\n\n if (future) {\n future.abort();\n this.pending.get(thread)!.delete(id);\n }\n }\n\n async request(event: RequestEventData) {\n const { thread, id, data } = event;\n\n try {\n const future = this.store.request(data);\n this.pending.get(thread)!.set(id, future);\n\n const result = await future;\n\n this.threads.get(thread)?.postMessage({ type: 'success-response', id, thread, data: prepareResponse(result) });\n } catch (error) {\n if (isAbortError(error)) return;\n\n this.threads.get(thread)?.postMessage({ type: 'error-response', id, thread, data: error });\n } finally {\n this.pending.get(thread)!.delete(id);\n }\n }\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction softCloneResponse(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.entries()) 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 isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n\nfunction prepareResponse<T>(result: StructuredDataDocument<T>) {\n const newResponse = {\n response: softCloneResponse(result.response),\n content: result.content,\n };\n\n return newResponse;\n}\n\nfunction prepareRequest(event: RequestEventData) {\n if (event.data.headers) {\n event.data.headers = new Headers(event.data.headers);\n }\n\n return event;\n}\n","import type Store from '@ember-data-mirror/store';\nimport type { StableDocumentIdentifier } from '@warp-drive-mirror/core-types/identifier';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '@warp-drive-mirror/core-types/request';\nimport type { ApiError } from '@warp-drive-mirror/core-types/spec/error';\n\nexport const MUTATION_OPS = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\n/**\n * In a Worker, any time we are asked to make a request, data needs to be returned.\n * background requests are ergo no different than foreground requests.\n * @internal\n */\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: StableDocumentIdentifier | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n cacheOptions?.backgroundReload ||\n !hasCachedValue ||\n (store.lifetimes && identifier\n ? store.lifetimes.isHardExpired(identifier, store) || store.lifetimes.isSoftExpired(identifier, store)\n : false)\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nfunction isAggregateError(error: Error & { errors?: ApiError[] }): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\ntype RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError) {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n","import type { CacheHandler as CacheHandlerType, Future, NextFn } from '@ember-data-mirror/request';\nimport type Store from '@ember-data-mirror/store';\nimport type { StoreRequestContext } from '@ember-data-mirror/store';\nimport { assert } from '@warp-drive-mirror/build-config/macros';\nimport type { ExistingRecordIdentifier, StableDocumentIdentifier } from '@warp-drive-mirror/core-types/identifier';\nimport type {\n StructuredDataDocument,\n StructuredDocument,\n StructuredErrorDocument,\n} from '@warp-drive-mirror/core-types/request';\nimport { SkipCache } from '@warp-drive-mirror/core-types/request';\nimport type {\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n} from '@warp-drive-mirror/core-types/spec/document';\nimport type { ApiError } from '@warp-drive-mirror/core-types/spec/error';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core-types/spec/json-api-raw';\n\nimport { calcShouldFetch, cloneError, isCacheAffecting, isMutation } from './utils';\nimport type { DataWorker } from './worker';\n\n/**\n * A simplified CacheHandler that hydrates ResourceDataDocuments from the cache\n * with their referenced resources.\n *\n * @typedoc\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(context: StoreRequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(context.request);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n if (identifier && !peeked) {\n // if we are using persisted cache, we should attempt to populate the in-memory cache now\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n if (worker?.storage) {\n return worker.storage\n .getDocument(identifier)\n .then((document) => {\n if (document) {\n store.cache.put(document);\n }\n return completeRequest(identifier, store, context, next);\n })\n .catch(() => {\n return completeRequest(identifier, store, context, next);\n });\n }\n }\n\n return completeRequest(identifier, store, context, next);\n },\n};\n\nfunction completeRequest<T>(\n identifier: StableDocumentIdentifier | null,\n store: Store,\n context: StoreRequestContext,\n next: NextFn<T>\n) {\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n // In a Worker, any time we are asked to make a request, data needs to be returned.\n // background requests are ergo no different than foreground requests.\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n return fetchContentAndHydrate(next, context, identifier);\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n throw peeked;\n }\n\n return maybeUpdateObjects<T>(store, peeked.content as ResourceDataDocument);\n}\n\nfunction maybeUpdateObjects<T>(store: Store, document: ResourceDataDocument | null): T {\n if (!document) {\n return document as T;\n }\n\n if (Array.isArray(document.data)) {\n const data = document.data.map((identifier) => {\n return store.cache.peek(identifier);\n });\n\n return Object.assign({}, document, { data }) as T;\n } else {\n const data = (document.data ? store.cache.peek(document.data) : null) as T;\n return Object.assign({}, document, { data }) as T;\n }\n}\n\nfunction maybeUpdatePersistedCache(\n store: Store,\n document: StructuredDocument<ResourceDocument<ExistingRecordIdentifier>> | null,\n resourceDocument?: ResourceDataDocument\n) {\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n\n if (!worker?.storage) {\n return;\n }\n\n if (!document && resourceDocument) {\n // we have resources to update but not a full request to cache\n void worker.storage.putResources(resourceDocument, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n } else if (document) {\n void worker.storage.putDocument(document, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n }\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n const record = request.data?.record || request.records?.[0];\n if (record) {\n response = store.cache.didCommit(record, document) as ResourceDataDocument;\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n maybeUpdatePersistedCache(store, null, response);\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n\n if (response.lid) {\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(request);\n const full = store.cache.peekRequest(identifier!);\n maybeUpdatePersistedCache(store, full);\n }\n }\n return maybeUpdateObjects(store, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: StableDocumentIdentifier | null,\n document: StructuredDataDocument<T>\n): T {\n let response: ResourceDataDocument;\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, document) as ResourceDataDocument;\n });\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, document.response, identifier, store);\n }\n\n return response! as T;\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n error: StructuredErrorDocument<T>\n) {\n if (isMutation(request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n const record = request.data?.record || request.records?.[0];\n\n store.cache.commitWasRejected(record, errors);\n } else {\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(request);\n if (identifier) {\n maybeUpdatePersistedCache(store, error as StructuredErrorDocument<ResourceErrorDocument>);\n }\n return store.cache.put(error) as ResourceErrorDocument;\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: StableDocumentIdentifier | null,\n error: StructuredErrorDocument<T>\n): never {\n if (request.signal?.aborted) {\n throw error;\n }\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, request, error);\n });\n\n if (identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, error.response, identifier, store);\n }\n\n if (isMutation(request)) {\n throw error;\n }\n\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: StableDocumentIdentifier | null\n): Promise<T> {\n const { request } = context;\n const { store } = context.request;\n\n if (isMutation(request)) {\n // TODO should we handle multiple records in request.records by iteratively calling willCommit for each\n const record = request.data?.record || request.records?.[0];\n assert(`Expected to receive a list of records included in the ${request.op} request`, record);\n if (record) {\n store.cache.willCommit(record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(request, identifier, store);\n }\n\n return next(request).then(\n (document) => handleFetchSuccess(store, request, identifier, document),\n (error: StructuredErrorDocument<T>) => handleFetchError(store, request, identifier, error)\n );\n}\n"],"names":["WorkerScope","globalThis","SharedWorkerGlobalScope","DataWorker","constructor","UserStore","options","window","store","threads","Map","pending","Object","assign","persisted","scope","isSharedWorker","initialize","_worker","storage","DocumentStorage","onconnect","e","port","ports","onmessage","event","type","data","setupThread","thread","start","set","delete","abortRequest","request","prepareRequest","id","future","get","abort","result","postMessage","prepareResponse","error","isAbortError","softCloneResponse","response","clone","headers","Array","from","entries","ok","redirected","status","statusText","url","Error","name","newResponse","content","Headers","MUTATION_OPS","Set","calcShouldFetch","hasCachedValue","identifier","cacheOptions","op","has","reload","backgroundReload","lifetimes","isHardExpired","isSoftExpired","isMutation","Boolean","isCacheAffecting","document","keys","length","isAggregateError","AggregateError","isArray","errors","cloneError","isAggregate","cloned","structuredClone","message","stack","CacheHandler","context","next","SkipCache","identifierCache","getOrCreateDocumentIdentifier","peeked","cache","peekRequest","worker","getDocument","then","put","completeRequest","catch","fetchContentAndHydrate","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","setResponse","maybeUpdateObjects","map","peek","maybeUpdatePersistedCache","resourceDocument","putResources","resourceIdentifier","putDocument","updateCacheForSuccess","record","records","didCommit","lid","full","handleFetchSuccess","_join","didRequest","updateCacheForError","undefined","commitWasRejected","handleFetchError","signal","aborted","newError","willCommit","willRequest"],"mappings":";;;;AAMA,MAAMA,WAAW,GAAIC,UAAU,CAAiEC,uBAAuB,CAAA;AAEhH,MAAMC,UAA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AKkD,kBAAkB,CAACzH,KAAK,EAAE2B,OAAO,EAAEgC,UAAU,EAAEY,QAAQ,CAAC,EACrEnC,KAAiC,IAAK2F,gBAAgB,CAAC/H,KAAK,EAAE2B,OAAO,EAAEgC,UAAU,EAAEvB,KAAK,CAC3F,CAAC,CAAA;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"data-worker.js","sources":["../src/data-worker/worker.ts","../src/data-worker/utils.ts","../src/data-worker/cache-handler.ts"],"sourcesContent":["import type { Future, ResponseInfo, StructuredDataDocument } from '@ember-data-mirror/request';\nimport type Store from '@ember-data-mirror/store';\n\nimport { DocumentStorage } from '../document-storage';\nimport type { AbortEventData, RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nexport class DataWorker {\n declare store: Store;\n declare threads: Map<string, MessagePort>;\n declare pending: Map<string, Map<number, Future<unknown>>>;\n declare isSharedWorker: boolean;\n declare options: { persisted: boolean; scope?: string };\n declare storage: DocumentStorage;\n\n constructor(UserStore: typeof Store, options?: { persisted: boolean; scope?: string }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.store = new UserStore();\n this.threads = new Map();\n this.pending = new Map();\n this.options = Object.assign({ persisted: false, scope: '' }, options);\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n initialize() {\n // enable the CacheHandler to access the worker\n (this.store as unknown as { _worker: DataWorker })._worker = this;\n if (this.options.persisted) {\n // will be accessed by the worker's CacheHandler off of store\n this.storage = new DocumentStorage({ scope: this.options.scope });\n }\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 setupThread(thread: string, port: MessagePort) {\n this.threads.set(thread, port);\n this.pending.set(thread, new Map());\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 'abort':\n this.abortRequest(event.data);\n break;\n case 'request':\n void this.request(prepareRequest(event.data));\n break;\n }\n };\n }\n\n abortRequest(event: AbortEventData) {\n const { thread, id } = event;\n const future = this.pending.get(thread)!.get(id);\n\n if (future) {\n future.abort();\n this.pending.get(thread)!.delete(id);\n }\n }\n\n async request(event: RequestEventData) {\n const { thread, id, data } = event;\n\n try {\n const future = this.store.request(data);\n this.pending.get(thread)!.set(id, future);\n\n const result = await future;\n\n this.threads.get(thread)?.postMessage({ type: 'success-response', id, thread, data: prepareResponse(result) });\n } catch (error) {\n if (isAbortError(error)) return;\n\n this.threads.get(thread)?.postMessage({ type: 'error-response', id, thread, data: error });\n } finally {\n this.pending.get(thread)!.delete(id);\n }\n }\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction softCloneResponse(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.entries()) 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 isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n\nfunction prepareResponse<T>(result: StructuredDataDocument<T>) {\n const newResponse = {\n response: softCloneResponse(result.response),\n content: result.content,\n };\n\n return newResponse;\n}\n\nfunction prepareRequest(event: RequestEventData) {\n if (event.data.headers) {\n event.data.headers = new Headers(event.data.headers);\n }\n\n return event;\n}\n","import type Store from '@ember-data-mirror/store';\nimport type { StableDocumentIdentifier } from '@warp-drive-mirror/core-types/identifier';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '@warp-drive-mirror/core-types/request';\nimport type { ApiError } from '@warp-drive-mirror/core-types/spec/error';\n\nexport const MUTATION_OPS = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\n/**\n * In a Worker, any time we are asked to make a request, data needs to be returned.\n * background requests are ergo no different than foreground requests.\n * @internal\n */\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: StableDocumentIdentifier | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n cacheOptions?.backgroundReload ||\n !hasCachedValue ||\n (store.lifetimes && identifier\n ? store.lifetimes.isHardExpired(identifier, store) || store.lifetimes.isSoftExpired(identifier, store)\n : false)\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nfunction isAggregateError(error: Error & { errors?: ApiError[] }): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\ntype RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError) {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n","import type { CacheHandler as CacheHandlerType, Future, NextFn } from '@ember-data-mirror/request';\nimport type Store from '@ember-data-mirror/store';\nimport type { StoreRequestContext } from '@ember-data-mirror/store';\nimport { DEBUG } from '@warp-drive-mirror/build-config/env';\nimport { assert } from '@warp-drive-mirror/build-config/macros';\nimport type { ExistingRecordIdentifier, StableDocumentIdentifier } from '@warp-drive-mirror/core-types/identifier';\nimport type {\n StructuredDataDocument,\n StructuredDocument,\n StructuredErrorDocument,\n} from '@warp-drive-mirror/core-types/request';\nimport { SkipCache } from '@warp-drive-mirror/core-types/request';\nimport type {\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n} from '@warp-drive-mirror/core-types/spec/document';\nimport type { ApiError } from '@warp-drive-mirror/core-types/spec/error';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core-types/spec/json-api-raw';\n\nimport { calcShouldFetch, cloneError, isCacheAffecting, isMutation } from './utils';\nimport type { DataWorker } from './worker';\n\n/**\n * A simplified CacheHandler that hydrates ResourceDataDocuments from the cache\n * with their referenced resources.\n *\n * @typedoc\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(context: StoreRequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(context.request);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n if (identifier && !peeked) {\n // if we are using persisted cache, we should attempt to populate the in-memory cache now\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n if (worker?.storage) {\n return worker.storage\n .getDocument(identifier)\n .then((document) => {\n if (document) {\n store.cache.put(document);\n }\n return completeRequest(identifier, store, context, next);\n })\n .catch((e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('Unable to retrieve document from persisted storage', e);\n }\n return completeRequest(identifier, store, context, next);\n });\n }\n }\n\n return completeRequest(identifier, store, context, next);\n },\n};\n\nfunction completeRequest<T>(\n identifier: StableDocumentIdentifier | null,\n store: Store,\n context: StoreRequestContext,\n next: NextFn<T>\n) {\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n // In a Worker, any time we are asked to make a request, data needs to be returned.\n // background requests are ergo no different than foreground requests.\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n return fetchContentAndHydrate(next, context, identifier);\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n throw peeked;\n }\n\n return maybeUpdateObjects<T>(store, peeked.content as ResourceDataDocument);\n}\n\nfunction maybeUpdateObjects<T>(store: Store, document: ResourceDataDocument | null): T {\n if (!document) {\n return document as T;\n }\n\n if (Array.isArray(document.data)) {\n const data = document.data.map((identifier) => {\n return store.cache.peek(identifier);\n });\n\n return Object.assign({}, document, { data }) as T;\n } else {\n const data = (document.data ? store.cache.peek(document.data) : null) as T;\n return Object.assign({}, document, { data }) as T;\n }\n}\n\nfunction maybeUpdatePersistedCache(\n store: Store,\n document: StructuredDocument<ResourceDocument<ExistingRecordIdentifier>> | null,\n resourceDocument?: ResourceDataDocument\n) {\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n\n if (!worker?.storage) {\n return;\n }\n\n if (!document && resourceDocument) {\n // we have resources to update but not a full request to cache\n void worker.storage.putResources(resourceDocument, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n } else if (document) {\n void worker.storage.putDocument(document, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n }\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n const record = request.data?.record || request.records?.[0];\n if (record) {\n response = store.cache.didCommit(record, document) as ResourceDataDocument;\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n maybeUpdatePersistedCache(store, null, response);\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n\n if (response.lid) {\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(request);\n const full = store.cache.peekRequest(identifier!);\n maybeUpdatePersistedCache(store, full);\n }\n }\n return maybeUpdateObjects(store, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: StableDocumentIdentifier | null,\n document: StructuredDataDocument<T>\n): T {\n let response: ResourceDataDocument;\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, document) as ResourceDataDocument;\n });\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, document.response, identifier, store);\n }\n\n return response! as T;\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n error: StructuredErrorDocument<T>\n) {\n if (isMutation(request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n const record = request.data?.record || request.records?.[0];\n\n store.cache.commitWasRejected(record, errors);\n } else {\n const identifier = store.identifierCache.getOrCreateDocumentIdentifier(request);\n if (identifier) {\n maybeUpdatePersistedCache(store, error as StructuredErrorDocument<ResourceErrorDocument>);\n }\n return store.cache.put(error) as ResourceErrorDocument;\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: StableDocumentIdentifier | null,\n error: StructuredErrorDocument<T>\n): never {\n if (request.signal?.aborted) {\n throw error;\n }\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, request, error);\n });\n\n if (identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, error.response, identifier, store);\n }\n\n if (isMutation(request)) {\n throw error;\n }\n\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: StableDocumentIdentifier | null\n): Promise<T> {\n const { request } = context;\n const { store } = context.request;\n\n if (isMutation(request)) {\n // TODO should we handle multiple records in request.records by iteratively calling willCommit for each\n const record = request.data?.record || request.records?.[0];\n assert(`Expected to receive a list of records included in the ${request.op} request`, record);\n if (record) {\n store.cache.willCommit(record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(request, identifier, store);\n }\n\n return next(request).then(\n (document) => handleFetchSuccess(store, request, identifier, document),\n (error: StructuredErrorDocument<T>) => handleFetchError(store, request, identifier, error)\n );\n}\n"],"names":["WorkerScope","globalThis","SharedWorkerGlobalScope","DataWorker","constructor","UserStore","options","window","store","threads","Map","pending","Object","assign","persisted","scope","isSharedWorker","initialize","_worker","storage","DocumentStorage","onconnect","e","port","ports","onmessage","event","type","data","setupThread","thread","start","set","delete","abortRequest","request","prepareRequest","id","future","get","abort","result","postMessage","prepareResponse","error","isAbortError","softCloneResponse","response","clone","headers","Array","from","entries","ok","redirected","status","statusText","url","Error","name","newResponse","content","Headers","MUTATION_OPS","Set","calcShouldFetch","hasCachedValue","identifier","cacheOptions","op","has","reload","backgroundReload","lifetimes","isHardExpired","isSoftExpired","isMutation","Boolean","isCacheAffecting","document","keys","length","isAggregateError","AggregateError","isArray","errors","cloneError","isAggregate","cloned","structuredClone","message","stack","CacheHandler","context","next","SkipCache","identifierCache","getOrCreateDocumentIdentifier","peeked","cache","peekRequest","worker","getDocument","then","put","completeRequest","catch","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","console","log","fetchContentAndHydrate","test","setResponse","maybeUpdateObjects","map","peek","maybeUpdatePersistedCache","resourceDocument","putResources","resourceIdentifier","putDocument","updateCacheForSuccess","record","records","didCommit","lid","full","handleFetchSuccess","_join","didRequest","updateCacheForError","undefined","commitWasRejected","handleFetchError","signal","aborted","newError","willCommit","willRequest"],"mappings":";;;;AAMA,MAAMA,WAAW,GAAIC,UAAU,CAAiEC,uBAAuB,CAAA;AAEhH,MAAMC,UAAU,CAAC;AAQtBC,EAAAA,WAAWA,CAACC,SAAuB,EAAEC,OAAgD,EAAE;AACrF;AACA,IAAA,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;AACjC,MAAA,OAAA;AACF,KAAA;AACA,IAAA,IAAI,CAACC,KAAK,GAAG,IAAIH,SAAS,EAAE,CAAA;AAC5B,IAAA,IAAI,CAACI,OAAO,GAAG,IAAIC,GAAG,EAAE,CAAA;AACxB,IAAA,IAAI,CAACC,OAAO,GAAG,IAAID,GAAG,EAAE,CAAA;AACxB,IAAA,IAAI,CAACJ,OAAO,GAAGM,MAAM,CAACC,MAAM,CAAC;AAAEC,MAAAA,SAAS,EAAE,KAAK;AAAEC,MAAAA,KAAK,EAAE,EAAA;KAAI,EAAET,OAAO,CAAC,CAAA;AACtE,IAAA,IAAI,CAACU,cAAc,GAAGhB,WAAW,IAAIC,UAAU,YAAYD,WAAW,CAAA;IACtE,IAAI,CAACiB,UAAU,EAAE,CAAA;AACnB,GAAA;AAEAA,EAAAA,UAAUA,GAAG;AACX;AACC,IAAA,IAAI,CAACT,KAAK,CAAwCU,OAAO,GAAG,IAAI,CAAA;AACjE,IAAA,IAAI,IAAI,CAACZ,OAAO,CAACQ,SAAS,EAAE;AAC1B;AACA,MAAA,IAAI,CAACK,OAAO,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A,GAAA,CAAAI,IAAA,IAAA;AAAA,MAAA,IAAA,CAAAA,IAAA,EAAA;AAAA,QAAA,MAAA,IAAAzD,KAAA,CAAQ,CAAA,sDAAA,EAAwDvB,OAAO,CAACkC,EAAG,CAAS,QAAA,CAAA,CAAA,CAAA;AAAA,OAAA;AAAA,KAAA,EAAEyD,MAAM,CAAA,GAAA,EAAA,CAAA;AAC5F,IAAA,IAAIA,MAAM,EAAE;MACVtH,KAAK,CAAC2F,KAAK,CAAC0C,UAAU,CAACf,MAAM,EAAEjC,OAAO,CAAC,CAAA;AACzC,KAAA;AACF,GAAA;AAEA,EAAA,IAAIrF,KAAK,CAACiE,SAAS,EAAEqE,WAAW,EAAE;IAChCtI,KAAK,CAACiE,SAAS,CAACqE,WAAW,CAAC3G,OAAO,EAAEgC,UAAU,EAAE3D,KAAK,CAAC,CAAA;AACzD,GAAA;AAEA,EAAA,OAAOsF,IAAI,CAAC3D,OAAO,CAAC,CAACoE,IAAI,CACtBxB,QAAQ,IAAKoD,kBAAkB,CAAC3H,KAAK,EAAE2B,OAAO,EAAEgC,UAAU,EAAEY,QAAQ,CAAC,EACrEnC,KAAiC,IAAK6F,gBAAgB,CAACjI,KAAK,EAAE2B,OAAO,EAAEgC,UAAU,EAAEvB,KAAK,CAC3F,CAAC,CAAA;AACH;;;;"}
|
package/dist/document-storage.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { D as DocumentStorage } from "./index-
|
|
1
|
+
export { D as DocumentStorage } from "./index-Cn3o840t";
|
package/dist/image-worker.js
CHANGED
|
@@ -12,6 +12,7 @@ class ImageWorker {
|
|
|
12
12
|
}
|
|
13
13
|
this.threads = new Map();
|
|
14
14
|
this.pendingImages = new Map();
|
|
15
|
+
this.cache = new Map();
|
|
15
16
|
this.options = options || {
|
|
16
17
|
persisted: false
|
|
17
18
|
};
|
|
@@ -89,7 +90,8 @@ class ImageWorker {
|
|
|
89
90
|
port.postMessage({
|
|
90
91
|
type: 'success-response',
|
|
91
92
|
thread,
|
|
92
|
-
url
|
|
93
|
+
url,
|
|
94
|
+
objectUrl
|
|
93
95
|
});
|
|
94
96
|
}
|
|
95
97
|
}
|
package/dist/image-worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-worker.js","sources":["../src/image-worker/worker.ts"],"sourcesContent":["import 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\nexport class ImageWorker {\n declare threads: Map<string, MessagePort>;\n declare pendingImages: Map<string, Promise<string>>;\n declare options: { persisted: boolean };\n declare isSharedWorker: boolean;\n declare cache: Map<string, string>;\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.options = options || { persisted: false };\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n 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);\n this.pendingImages.set(url, promise);\n return promise.finally(() => {\n this.pendingImages.delete(url);\n });\n }\n\n initialize() {\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 setupThread(thread: string, port: MessagePort) {\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 async request(event: RequestEventData) {\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
|
|
1
|
+
{"version":3,"file":"image-worker.js","sources":["../src/image-worker/worker.ts"],"sourcesContent":["import 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\nexport class ImageWorker {\n declare threads: Map<string, MessagePort>;\n declare pendingImages: Map<string, Promise<string>>;\n declare options: { persisted: boolean };\n declare isSharedWorker: boolean;\n declare cache: Map<string, string>;\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 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);\n this.pendingImages.set(url, promise);\n return promise.finally(() => {\n this.pendingImages.delete(url);\n });\n }\n\n initialize() {\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 setupThread(thread: string, port: MessagePort) {\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 async request(event: RequestEventData) {\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"],"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","set","finally","delete","onconnect","e","port","ports","onmessage","event","type","data","setupThread","thread","start","request","postMessage"],"mappings":"AAEA,MAAMA,WAAW,GAAIC,UAAU,CAAiEC,uBAAuB,CAAA;AAEvH,eAAeC,SAASA,CAACC,GAAW,EAAmB;AACrD,EAAA,MAAMC,QAAQ,GAAG,MAAMC,KAAK,CAACF,GAAG,CAAC,CAAA;AACjC,EAAA,MAAMG,QAAQ,GAAG,MAAMF,QAAQ,CAACG,IAAI,EAAE,CAAA;AACtC,EAAA,OAAOC,GAAG,CAACC,eAAe,CAACH,QAAQ,CAAC,CAAA;AACtC,CAAA;AAEO,MAAMI,WAAW,CAAC;EAOvBC,WAAWA,CAACC,OAAgC,EAAE;AAC5C;AACA,IAAA,IAAI,OAAOC,MAAM,KAAK,WAAW,EAAE;AACjC,MAAA,OAAA;AACF,KAAA;AACA,IAAA,IAAI,CAACC,OAAO,GAAG,IAAIC,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CAACE,IAAI,CAAC,CAAA;AAC7B,UAAA,MAAA;AACJ,OAAA;KACD,CAAA;AACH,GAAA;EAEA,MAAMI,OAAOA,CAACN,KAAuB,EAAE;IACrC,MAAM;MAAEI,MAAM;AAAEpC,MAAAA,GAAAA;AAAI,KAAC,GAAGgC,KAAK,CAAA;IAE7B,MAAMd,SAAS,GAAG,MAAM,IAAI,CAAChB,KAAK,CAACF,GAAG,CAAC,CAAA;IACvC,MAAM6B,IAAI,GAAG,IAAI,CAAClB,OAAO,CAACQ,GAAG,CAACiB,MAAM,CAAE,CAAA;IACtCP,IAAI,CAACU,WAAW,CAAC;AAAEN,MAAAA,IAAI,EAAE,kBAAkB;MAAEG,MAAM;MAAEpC,GAAG;AAAEkB,MAAAA,SAAAA;AAAU,KAAC,CAAC,CAAA;AACxE,GAAA;AACF;;;;"}
|
|
@@ -246,10 +246,7 @@ function prepareRequest(request) {
|
|
|
246
246
|
if (headers instanceof Headers) {
|
|
247
247
|
requestCopy.headers = Array.from(headers.entries());
|
|
248
248
|
}
|
|
249
|
-
return
|
|
250
|
-
signal: signal || null,
|
|
251
|
-
request: requestCopy
|
|
252
|
-
};
|
|
249
|
+
return requestCopy;
|
|
253
250
|
}
|
|
254
251
|
function prepareResponse(response) {
|
|
255
252
|
if (!response) return null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-Cn3o840t.js","sources":["../src/document-storage/index.ts"],"sourcesContent":["import type { RequestInfo, ResponseInfo, StructuredDocument } from '@ember-data-mirror/request';\nimport type { StoreRequestContext } from '@ember-data-mirror/store';\nimport { assert } from '@warp-drive-mirror/build-config/macros';\nimport type { ExistingRecordIdentifier } from '@warp-drive-mirror/core-types/identifier';\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<ExistingRecordIdentifier>>;\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) {\n this._invalidated = true;\n }\n\n async _open(scope: string) {\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 ) {\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 ExistingRecordIdentifier[];\n }\n\n document.content.data = data as unknown as ResourceDataDocument<ExistingRecordIdentifier>['data'];\n }\n }\n\n return document as CacheDocument;\n }\n\n async putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => 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<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject,\n resources: Map<string, ExistingResourceObject> = new Map<string, ExistingResourceObject>()\n ) {\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<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject\n ) {\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) {\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.entries()) 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.entries()) 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: ExistingRecordIdentifier) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putDocument(document, resourceCollector);\n }\n\n putResources(\n document: ResourceDataDocument<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putResources(document, resourceCollector);\n }\n\n clear(reset?: boolean) {\n return this._storage.clear(reset);\n }\n}\n"],"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","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","doc","newDoc","request","prepareRequest","response","prepareResponse","signal","headers","requestCopy","store","AbortSignal","Headers","from","clone","ok","redirected","status","statusText","url","req","Request","resp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CAAA;AAChE,GAAA;EAEAI,KAAKA,CAACC,KAAe,EAAE;AACrB,IAAA,OAAO,IAAI,CAACoC,QAAQ,CAACrC,KAAK,CAACC,KAAK,CAAC,CAAA;AACnC,GAAA;AACF;;;;"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@warp-drive-mirror/experiments",
|
|
3
3
|
"description": "Experimental features for EmberData/WarpDrive",
|
|
4
|
-
"version": "0.0.1-alpha.
|
|
4
|
+
"version": "0.0.1-alpha.108",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Chris Thoburn <runspired@users.noreply.github.com>",
|
|
7
7
|
"repository": {
|
|
@@ -47,10 +47,10 @@
|
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
49
|
"@sqlite.org/sqlite-wasm": "3.46.0-build2",
|
|
50
|
-
"@ember-data-mirror/request": "5.4.0-alpha.
|
|
51
|
-
"@ember-data-mirror/request-utils": "5.4.0-alpha.
|
|
52
|
-
"@ember-data-mirror/store": "5.4.0-alpha.
|
|
53
|
-
"@warp-drive-mirror/core-types": "0.0.0-alpha.
|
|
50
|
+
"@ember-data-mirror/request": "5.4.0-alpha.108",
|
|
51
|
+
"@ember-data-mirror/request-utils": "5.4.0-alpha.108",
|
|
52
|
+
"@ember-data-mirror/store": "5.4.0-alpha.108",
|
|
53
|
+
"@warp-drive-mirror/core-types": "0.0.0-alpha.94"
|
|
54
54
|
},
|
|
55
55
|
"peerDependenciesMeta": {
|
|
56
56
|
"@sqlite.org/sqlite-wasm": {
|
|
@@ -59,20 +59,20 @@
|
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"@embroider/macros": "^1.16.1",
|
|
62
|
-
"@warp-drive-mirror/build-config": "0.0.0-alpha.
|
|
62
|
+
"@warp-drive-mirror/build-config": "0.0.0-alpha.45"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@babel/core": "^7.24.5",
|
|
66
66
|
"@babel/plugin-transform-typescript": "^7.24.5",
|
|
67
67
|
"@babel/preset-env": "^7.24.5",
|
|
68
68
|
"@babel/preset-typescript": "^7.24.1",
|
|
69
|
-
"@ember-data-mirror/request": "5.4.0-alpha.
|
|
70
|
-
"@ember-data-mirror/request-utils": "5.4.0-alpha.
|
|
71
|
-
"@ember-data-mirror/store": "5.4.0-alpha.
|
|
72
|
-
"@ember-data-mirror/tracking": "5.4.0-alpha.
|
|
69
|
+
"@ember-data-mirror/request": "5.4.0-alpha.108",
|
|
70
|
+
"@ember-data-mirror/request-utils": "5.4.0-alpha.108",
|
|
71
|
+
"@ember-data-mirror/store": "5.4.0-alpha.108",
|
|
72
|
+
"@ember-data-mirror/tracking": "5.4.0-alpha.108",
|
|
73
73
|
"@glimmer/component": "^1.1.2",
|
|
74
|
-
"@warp-drive-mirror/core-types": "0.0.0-alpha.
|
|
75
|
-
"@warp-drive/internal-config": "5.4.0-alpha.
|
|
74
|
+
"@warp-drive-mirror/core-types": "0.0.0-alpha.94",
|
|
75
|
+
"@warp-drive/internal-config": "5.4.0-alpha.108",
|
|
76
76
|
"ember-source": "~5.8.0",
|
|
77
77
|
"pnpm-sync-dependencies-meta-injected": "0.0.14",
|
|
78
78
|
"@sqlite.org/sqlite-wasm": "3.46.0-build2",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache-handler.d.ts","sourceRoot":"","sources":["../../src/data-worker/cache-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,IAAI,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"cache-handler.d.ts","sourceRoot":"","sources":["../../src/data-worker/cache-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,IAAI,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAuB5F;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,gBAmC1B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../src/image-worker/worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAA0C,MAAM,SAAS,CAAC;AAUxF,qBAAa,WAAW;IACd,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAClC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,OAAO,EAAE;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC;IAChC,cAAc,EAAE,OAAO,CAAC;IACxB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;gBAEvB,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE;
|
|
1
|
+
{"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../src/image-worker/worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAA0C,MAAM,SAAS,CAAC;AAUxF,qBAAa,WAAW;IACd,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAClC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5C,OAAO,EAAE;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE,CAAC;IAChC,cAAc,EAAE,OAAO,CAAC;IACxB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;gBAEvB,OAAO,CAAC,EAAE;QAAE,SAAS,EAAE,OAAO,CAAA;KAAE;IAa5C,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAmBnC,UAAU;IA4BV,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW;IAiBvC,OAAO,CAAC,KAAK,EAAE,gBAAgB;CAOtC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-BhNHD6mY.js","sources":["../src/document-storage/index.ts"],"sourcesContent":["import type { RequestInfo, ResponseInfo, StructuredDocument } from '@ember-data-mirror/request';\nimport type { StoreRequestContext } from '@ember-data-mirror/store';\nimport { assert } from '@warp-drive-mirror/build-config/macros';\nimport type { ExistingRecordIdentifier } from '@warp-drive-mirror/core-types/identifier';\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<ExistingRecordIdentifier>>;\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) {\n this._invalidated = true;\n }\n\n async _open(scope: string) {\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 ) {\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 ExistingRecordIdentifier[];\n }\n\n document.content.data = data as unknown as ResourceDataDocument<ExistingRecordIdentifier>['data'];\n }\n }\n\n return document as CacheDocument;\n }\n\n async putDocument(\n document: CacheFileDocument,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => 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<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject,\n resources: Map<string, ExistingResourceObject> = new Map<string, ExistingResourceObject>()\n ) {\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<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject\n ) {\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) {\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']): { signal: AbortSignal | null; 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.entries()) as unknown as Headers;\n }\n\n return { signal: signal || null, request: 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.entries()) 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: ExistingRecordIdentifier) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putDocument(document, resourceCollector);\n }\n\n putResources(\n document: ResourceDataDocument<ExistingRecordIdentifier>,\n resourceCollector: (resourceIdentifier: ExistingRecordIdentifier) => ExistingResourceObject\n ): Promise<void> {\n return this._storage.putResources(document, resourceCollector);\n }\n\n clear(reset?: boolean) {\n return this._storage.clear(reset);\n }\n}\n"],"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","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","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"],"mappings":";;AAOO,MAAMA,4BAA4B,GAAG,6BAA6B,CAAA;AAClE,MAAMC,0BAA0B,GAAG,CAAC,CAAA;;AAqB3C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAcA,MAAMC,uBAAuB,CAAC;EAS5BC,WAAWA,CAACC,OAA+B,EAAE;IAC3C,IAAI,CAACA,OAAO,GAAGA,OAAO,CAAA;IAEtB,IAAI,CAACC,aAAa,GAAG,CAAC,CAAA;IACtB,IAAI,CAACC,YAAY,GAAG,IAAI,CAAA;IACxB,IAAI,CAACC,WAAW,GAAG,IAAI,CAACC,KAAK,CAACJ,OAAO,CAACK,KAAK,CAAC,CAAA;AAC5C,IAAA,IAAI,CAACC,QAAQ,GAAGC,MAAM,CAACC,MAAM,CAAC,IAAIC,gBAAgB,CAACT,OAAO,CAACK,KAAK,CAAC,EAAE;AACjEK,MAAAA,SAAS,EAAE,IAAI,CAACC,UAAU,CAACC,IAAI,CAAC,IAAI,CAAA;AACtC,KAAC,CAAC,CAAA;AACJ,GAAA;EAEAD,UAAUA,CAACE,MAAoB,EAAE;IAC/B,IAAI,CAACX,YAAY,GAAG,IAAI,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