@fireproof/core 0.20.0-dev-preview-54 → 0.20.0-dev-preview-57

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type {\n ConfigOpts,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n MapFn,\n QueryOpts,\n Database,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { AllDocsQueryOpts, ChangesOptions, ClockHead } from \"@fireproof/core\";\n\nexport interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> {\n readonly docs: DocWithId<T>[];\n readonly rows: IndexRow<K, T, R>[];\n /** @internal */\n readonly length: number;\n /** @internal */\n map<U>(callbackfn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U): U[];\n /** @internal */\n filter(predicate: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean): DocWithId<T>[];\n /** @internal */\n forEach(callbackfn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void): void;\n /** @internal */\n [Symbol.iterator](): Iterator<DocWithId<T>>;\n}\n\nexport type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: string | MapFn<T>,\n query?: QueryOpts<K>,\n initialRows?: IndexRow<K, T, R>[],\n) => LiveQueryResult<T, K, R>;\n\nexport interface AllDocsResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport interface ChangesResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport type UseAllDocs = <T extends DocTypes>(query?: AllDocsQueryOpts) => AllDocsResult<T>;\n\nexport type UseChanges = <T extends DocTypes>(since: ClockHead, opts: ChangesOptions) => ChangesResult<T>;\n\ninterface UpdateDocFnOptions {\n readonly replace?: boolean;\n readonly reset?: boolean;\n}\n\ntype UpdateDocFn<T extends DocTypes> = (newDoc?: DocSet<T>, options?: UpdateDocFnOptions) => void;\n\ntype StoreDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype DeleteDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype UseDocumentResultTuple<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<T>];\n\ninterface UseDocumentResultObject<T extends DocTypes> {\n doc: DocWithId<T>;\n merge: (newDoc: Partial<T>) => void;\n replace: (newDoc: T) => void;\n reset: () => void;\n refresh: () => Promise<void>;\n save: StoreDocFn<T>;\n remove: DeleteDocFn<T>;\n submit: (e?: Event) => Promise<void>;\n}\n\nexport type UseDocumentResult<T extends DocTypes> = UseDocumentResultObject<T> & UseDocumentResultTuple<T>;\n\nexport type UseDocumentInitialDocOrFn<T extends DocTypes> = DocSet<T> | (() => DocSet<T>);\nexport type UseDocument = <T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>) => UseDocumentResult<T>;\n\nexport interface UseFireproof {\n readonly database: Database;\n /**\n * ## Summary\n *\n * React hook that provides the ability to create/update/save new Fireproof documents into your custom Fireproof database.\n * The creation occurs when you do not pass in an `_id` as part of your initial document -- the database will assign a new\n * one when you call the provided `save` handler. The hook also provides generics support so you can inline your custom type into\n * the invocation to receive type-safety and auto-complete support in your IDE.\n *\n * ## Usage\n *\n * ```tsx\n * const todo = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n * // Access via object properties\n * todo.doc // The current document\n * todo.merge({ completed: true }) // Update specific fields\n * todo.replace({ text: 'new', date: Date.now(), completed: false }) // Replace entire doc\n * todo.save() // Save changes\n * todo.remove() // Delete document\n * todo.reset() // Reset to initial state\n * todo.refresh() // Refresh from database\n *\n * // Or use tuple destructuring for legacy compatibility\n * const [doc, updateDoc, saveDoc, removeDoc] = todo\n * ```\n *\n * ## Overview\n *\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useDocument: UseDocument;\n /**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app.\n *\n * ## Usage\n * ```tsx\n * const result = useLiveQuery(\"date\"); // using string key\n * const result = useLiveQuery('date', { limit: 10, descending: true }) // key + options\n * const result = useLiveQuery<CustomType>(\"date\"); // using generics\n * const result = useLiveQuery((doc) => doc.date)); // using map function\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useLiveQuery: UseLiveQuery;\n /**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useAllDocs: UseAllDocs;\n /**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useChanges: UseChanges;\n}\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\nfunction deepClone<T>(value: T): T {\n if (typeof structuredClone !== \"undefined\") {\n return structuredClone(value);\n } else {\n // Fallback if structuredClone is not available (older browsers, older Node versions, etc.)\n return JSON.parse(JSON.stringify(value));\n }\n}\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const updateHappenedRef = useRef(false);\n\n function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n }\n\n function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return {\n rows: initialRows,\n docs,\n length: docs.length,\n map: (fn) => docs.map(fn),\n filter: (fn) => docs.filter(fn),\n forEach: (fn) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n };\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc as DocWithId<T>).filter((r): r is DocWithId<T> => !!r);\n setResult({\n ...res,\n docs,\n length: docs.length,\n map: (fn) => docs.map(fn),\n filter: (fn) => docs.filter(fn),\n forEach: (fn) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n });\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n","import { Database, DocTypes, DocWithId } from \"@fireproof/core\";\n\nimport { UseDocument, UseDocumentResult, useFireproof } from \"./useFireproof.js\";\n\nexport interface TLUseDocument {\n <T extends DocTypes>(initialDoc: DocWithId<T>): UseDocumentResult<T>;\n database: Database;\n}\n\nfunction topLevelUseDocument(...args: Parameters<UseDocument>) {\n const { useDocument, database } = useFireproof();\n (topLevelUseDocument as TLUseDocument).database = database;\n return useDocument(...args);\n}\n\n/**\n * ## Summary\n *\n * React hook that provides the ability to create and manage Fireproof documents. The creation occurs when\n * you do not pass in an `_id` as part of your initial document -- the database will assign a new one when\n * you call the provided `save` handler.\n *\n * ## Usage\n *\n * ```tsx\n * const todo = useDocument({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n * // Access via object properties\n * todo.doc // The current document\n * todo.merge({ completed: true }) // Update specific fields\n * todo.replace({ text: 'new', date: Date.now(), completed: false }) // Replace entire doc\n * todo.save() // Save changes\n * todo.remove() // Delete document\n * todo.reset() // Reset to initial state\n * todo.refresh() // Refresh from database\n * ```\n *\n * ### Create document with custom ID\n * Custom IDs let you create predictable document identifiers for data that has\n * a natural unique key, like userIds or email addresses. This makes it easy to\n * look up and update specific documents without having to query for them first.\n * For example, storing user profiles by customerId:\n *\n * ```tsx\n * const profile = useDocument({\n * _id: `${props.customerId}-profile`, // Predictable ID based on customerId\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\n * ```\n *\n * ## API\n *\n * - `doc`: The current document state\n * - `merge(newDoc)`: Merge new properties into the document\n * - `replace(newDoc)`: Replace the entire document\n * - `reset()`: Reset to initial state\n * - `refresh()`: Refresh from database\n * - `save()`: Save changes to the document\n * - `remove()`: Delete the document\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useDocument = topLevelUseDocument as TLUseDocument;\n","import { Database, DocFragment, DocTypes, IndexKeyType } from \"@fireproof/core\";\n\nimport { LiveQueryResult, useFireproof, UseLiveQuery } from \"./useFireproof.js\";\n\nexport interface TLUseLiveQuery {\n <T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T>(\n ...args: Parameters<UseLiveQuery>\n ): LiveQueryResult<T, K, R>;\n database: Database;\n}\n\nfunction topLevelUseLiveQuery(...args: Parameters<UseLiveQuery>) {\n const { useLiveQuery, database } = useFireproof();\n (topLevelUseLiveQuery as TLUseLiveQuery).database = database;\n return useLiveQuery(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app. This uses\n * the default database named \"useFireproof\" under the hood which you can also access via the `database` accessor.\n *\n * ## Usage\n * ```tsx\n * const results = useLiveQuery(\"date\"); // using string\n * const results = useLiveQuery((doc) => doc.date)); // using map function\n * const database = useLiveQuery.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useLiveQuery = topLevelUseLiveQuery as TLUseLiveQuery;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { AllDocsResult, useFireproof, UseAllDocs } from \"./useFireproof.js\";\n\nexport interface TLUseAllDocs {\n <T extends DocTypes>(...args: Parameters<UseAllDocs>): AllDocsResult<T>;\n database: Database;\n}\n\nfunction topLevelUseAllDocs(...args: Parameters<UseAllDocs>) {\n const { useAllDocs, database } = useFireproof();\n (topLevelUseAllDocs as TLUseAllDocs).database = database;\n return useAllDocs(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * const database = useAllDocs.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useAllDocs = topLevelUseAllDocs as TLUseAllDocs;\n","import { DocTypes, Database } from \"@fireproof/core\";\n\nimport { ChangesResult, useFireproof, UseChanges } from \"./useFireproof.js\";\n\nexport interface TLUseChanges {\n <T extends DocTypes>(...args: Parameters<UseChanges>): ChangesResult<T>;\n database: Database;\n}\n\nfunction topLevelUseChanges(...args: Parameters<UseChanges>) {\n const { useChanges, database } = useFireproof();\n (topLevelUseChanges as TLUseChanges).database = database;\n return useChanges(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useChanges = topLevelUseChanges as TLUseChanges;\n","import React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\nimport { DocFileMeta } from \"use-fireproof\";\n\nconst { URL } = window;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,\n })\n : null;\n}\n\nexport default ImgFile;\n"],"mappings":";AAaA,SAAS,iBAAiB;AAC1B,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;AA8J3D,IAAM,eAAe,CAAC;AAE7B,SAAS,UAAa,OAAa;AACjC,MAAI,OAAO,oBAAoB,aAAa;AAC1C,WAAO,gBAAgB,KAAK;AAAA,EAC9B,OAAO;AAEL,WAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA,EACzC;AACF;AA0BO,SAAS,aAAa,OAA0B,gBAAgB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Document","useLiveQuery","useAllDocs","useChanges","useState","useEffect"]}
1
+ {"version":3,"sources":["../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type {\n ConfigOpts,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n MapFn,\n QueryOpts,\n Database,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { AllDocsQueryOpts, ChangesOptions, ClockHead } from \"@fireproof/core\";\n\nexport interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> {\n readonly docs: DocWithId<T>[];\n readonly rows: IndexRow<K, T, R>[];\n /** @internal */\n readonly length: number;\n /** @internal */\n map<U>(callbackfn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => U): U[];\n /** @internal */\n filter(predicate: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => boolean): DocWithId<T>[];\n /** @internal */\n forEach(callbackfn: (value: DocWithId<T>, index: number, array: DocWithId<T>[]) => void): void;\n /** @internal */\n [Symbol.iterator](): Iterator<DocWithId<T>>;\n}\n\nexport type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: string | MapFn<T>,\n query?: QueryOpts<K>,\n initialRows?: IndexRow<K, T, R>[],\n) => LiveQueryResult<T, K, R>;\n\nexport interface AllDocsResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport interface ChangesResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport type UseAllDocs = <T extends DocTypes>(query?: AllDocsQueryOpts) => AllDocsResult<T>;\n\nexport type UseChanges = <T extends DocTypes>(since: ClockHead, opts: ChangesOptions) => ChangesResult<T>;\n\ninterface UpdateDocFnOptions {\n readonly replace?: boolean;\n readonly reset?: boolean;\n}\n\ntype UpdateDocFn<T extends DocTypes> = (newDoc?: DocSet<T>, options?: UpdateDocFnOptions) => void;\n\ntype StoreDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype DeleteDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype UseDocumentResultTuple<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<T>];\n\ninterface UseDocumentResultObject<T extends DocTypes> {\n doc: DocWithId<T>;\n merge: (newDoc: Partial<T>) => void;\n replace: (newDoc: T) => void;\n reset: () => void;\n refresh: () => Promise<void>;\n save: StoreDocFn<T>;\n remove: DeleteDocFn<T>;\n submit: (e?: Event) => Promise<void>;\n}\n\nexport type UseDocumentResult<T extends DocTypes> = UseDocumentResultObject<T> & UseDocumentResultTuple<T>;\n\nexport type UseDocumentInitialDocOrFn<T extends DocTypes> = DocSet<T> | (() => DocSet<T>);\nexport type UseDocument = <T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>) => UseDocumentResult<T>;\n\nexport interface UseFireproof {\n readonly database: Database;\n /**\n * ## Summary\n *\n * React hook that provides the ability to create/update/save new Fireproof documents into your custom Fireproof database.\n * The creation occurs when you do not pass in an `_id` as part of your initial document -- the database will assign a new\n * one when you call the provided `save` handler. The hook also provides generics support so you can inline your custom type into\n * the invocation to receive type-safety and auto-complete support in your IDE.\n *\n * ## Usage\n *\n * ```tsx\n * const todo = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n * // Access via object properties\n * todo.doc // The current document\n * todo.merge({ completed: true }) // Update specific fields\n * todo.replace({ text: 'new', date: Date.now(), completed: false }) // Replace entire doc\n * todo.save() // Save changes\n * todo.remove() // Delete document\n * todo.reset() // Reset to initial state\n * todo.refresh() // Refresh from database\n *\n * // Or use tuple destructuring for legacy compatibility\n * const [doc, updateDoc, saveDoc, removeDoc] = todo\n * ```\n *\n * ## Overview\n *\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useDocument: UseDocument;\n /**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app.\n *\n * ## Usage\n * ```tsx\n * const result = useLiveQuery(\"date\"); // using string key\n * const result = useLiveQuery('date', { limit: 10, descending: true }) // key + options\n * const result = useLiveQuery<CustomType>(\"date\"); // using generics\n * const result = useLiveQuery((doc) => doc.date)); // using map function\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useLiveQuery: UseLiveQuery;\n /**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useAllDocs: UseAllDocs;\n /**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useChanges: UseChanges;\n}\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\nfunction deepClone<T>(value: T): T {\n if (typeof structuredClone !== \"undefined\") {\n return structuredClone(value);\n } else {\n // Fallback if structuredClone is not available (older browsers, older Node versions, etc.)\n return JSON.parse(JSON.stringify(value));\n }\n}\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n const updateHappenedRef = useRef(false);\n\n function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn ?? ({} as T);\n }\n\n const originalInitialDoc = useMemo(() => deepClone({ ...initialDoc }), []);\n\n const [doc, setDoc] = useState(initialDoc);\n\n const refresh = useCallback(async () => {\n const gotDoc = doc._id ? await database.get<T>(doc._id).catch(() => initialDoc) : initialDoc;\n setDoc(gotDoc);\n }, [doc._id]);\n\n const save: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n updateHappenedRef.current = false;\n const toSave = existingDoc ?? doc;\n const res = await database.put(toSave);\n\n if (!updateHappenedRef.current && !doc._id && !existingDoc) {\n setDoc((d) => ({ ...d, _id: res.id }));\n }\n\n return res;\n },\n [doc],\n );\n\n const remove: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? doc._id;\n if (!id) throw database.logger.Error().Msg(`Document must have an _id to be removed`).AsError();\n const gotDoc = await database.get<T>(id).catch(() => undefined);\n if (!gotDoc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [doc, initialDoc],\n );\n\n // New granular update methods\n const merge = useCallback((newDoc: Partial<T>) => {\n updateHappenedRef.current = true;\n setDoc((prev) => ({ ...prev, ...newDoc }));\n }, []);\n\n const replace = useCallback((newDoc: T) => {\n updateHappenedRef.current = true;\n setDoc(newDoc);\n }, []);\n\n const reset = useCallback(() => {\n updateHappenedRef.current = true;\n setDoc({ ...originalInitialDoc });\n }, [originalInitialDoc]);\n\n // Legacy-compatible updateDoc\n const updateDoc = useCallback(\n (newDoc?: DocSet<T>, opts = { replace: false, reset: false }) => {\n if (!newDoc) {\n return opts.reset ? reset() : refresh();\n }\n return opts.replace ? replace(newDoc as T) : merge(newDoc);\n },\n [refresh, reset, replace, merge],\n );\n\n useEffect(() => {\n if (!doc._id) return;\n return database.subscribe((changes) => {\n if (updateHappenedRef.current) {\n return;\n }\n if (changes.find((c) => c._id === doc._id)) {\n void refresh();\n }\n }, true);\n }, [doc._id, refresh]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const submit = useCallback(\n async (e?: Event) => {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n },\n [save, reset],\n );\n\n // Primary Object API with both new and legacy methods\n const apiObject = {\n doc: { ...doc } as DocWithId<T>,\n merge,\n replace,\n reset,\n refresh,\n save,\n remove,\n submit,\n };\n\n // Make the object properly iterable\n const tuple = [{ ...doc }, updateDoc, save, remove, reset, refresh];\n Object.assign(apiObject, tuple);\n Object.defineProperty(apiObject, Symbol.iterator, {\n enumerable: false,\n value: function* () {\n yield* tuple;\n },\n });\n\n return apiObject as UseDocumentResult<T>;\n }\n\n function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return {\n rows: initialRows,\n docs,\n length: docs.length,\n map: (fn) => docs.map(fn),\n filter: (fn) => docs.filter(fn),\n forEach: (fn) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n };\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n const docs = res.rows.map((r) => r.doc as DocWithId<T>).filter((r): r is DocWithId<T> => !!r);\n setResult({\n ...res,\n docs,\n length: docs.length,\n map: (fn) => docs.map(fn),\n filter: (fn) => docs.filter(fn),\n forEach: (fn) => docs.forEach(fn),\n [Symbol.iterator]: () => docs[Symbol.iterator](),\n });\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n","import { Database, DocTypes, DocWithId } from \"@fireproof/core\";\n\nimport { UseDocument, UseDocumentResult, useFireproof } from \"./useFireproof.js\";\n\nexport interface TLUseDocument {\n <T extends DocTypes>(initialDoc: DocWithId<T>): UseDocumentResult<T>;\n database: Database;\n}\n\nfunction topLevelUseDocument(...args: Parameters<UseDocument>) {\n const { useDocument, database } = useFireproof();\n (topLevelUseDocument as TLUseDocument).database = database;\n return useDocument(...args);\n}\n\n/**\n * ## Summary\n *\n * React hook that provides the ability to create and manage Fireproof documents. The creation occurs when\n * you do not pass in an `_id` as part of your initial document -- the database will assign a new one when\n * you call the provided `save` handler.\n *\n * ## Usage\n *\n * ```tsx\n * const todo = useDocument({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n * // Access via object properties\n * todo.doc // The current document\n * todo.merge({ completed: true }) // Update specific fields\n * todo.replace({ text: 'new', date: Date.now(), completed: false }) // Replace entire doc\n * todo.save() // Save changes\n * todo.remove() // Delete document\n * todo.reset() // Reset to initial state\n * todo.refresh() // Refresh from database\n * ```\n *\n * ### Create document with custom ID\n * Custom IDs let you create predictable document identifiers for data that has\n * a natural unique key, like userIds or email addresses. This makes it easy to\n * look up and update specific documents without having to query for them first.\n * For example, storing user profiles by customerId:\n *\n * ```tsx\n * const profile = useDocument({\n * _id: `${props.customerId}-profile`, // Predictable ID based on customerId\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\n * ```\n *\n * ## API\n *\n * - `doc`: The current document state\n * - `merge(newDoc)`: Merge new properties into the document\n * - `replace(newDoc)`: Replace the entire document\n * - `reset()`: Reset to initial state\n * - `refresh()`: Refresh from database\n * - `save()`: Save changes to the document\n * - `remove()`: Delete the document\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useDocument = topLevelUseDocument as TLUseDocument;\n","import { Database, DocFragment, DocTypes, IndexKeyType } from \"@fireproof/core\";\n\nimport { LiveQueryResult, useFireproof, UseLiveQuery } from \"./useFireproof.js\";\n\nexport interface TLUseLiveQuery {\n <T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T>(\n ...args: Parameters<UseLiveQuery>\n ): LiveQueryResult<T, K, R>;\n database: Database;\n}\n\nfunction topLevelUseLiveQuery(...args: Parameters<UseLiveQuery>) {\n const { useLiveQuery, database } = useFireproof();\n (topLevelUseLiveQuery as TLUseLiveQuery).database = database;\n return useLiveQuery(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app. This uses\n * the default database named \"useFireproof\" under the hood which you can also access via the `database` accessor.\n *\n * ## Usage\n * ```tsx\n * const results = useLiveQuery(\"date\"); // using string\n * const results = useLiveQuery((doc) => doc.date)); // using map function\n * const database = useLiveQuery.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useLiveQuery = topLevelUseLiveQuery as TLUseLiveQuery;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { AllDocsResult, useFireproof, UseAllDocs } from \"./useFireproof.js\";\n\nexport interface TLUseAllDocs {\n <T extends DocTypes>(...args: Parameters<UseAllDocs>): AllDocsResult<T>;\n database: Database;\n}\n\nfunction topLevelUseAllDocs(...args: Parameters<UseAllDocs>) {\n const { useAllDocs, database } = useFireproof();\n (topLevelUseAllDocs as TLUseAllDocs).database = database;\n return useAllDocs(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * const database = useAllDocs.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useAllDocs = topLevelUseAllDocs as TLUseAllDocs;\n","import { DocTypes, Database } from \"@fireproof/core\";\n\nimport { ChangesResult, useFireproof, UseChanges } from \"./useFireproof.js\";\n\nexport interface TLUseChanges {\n <T extends DocTypes>(...args: Parameters<UseChanges>): ChangesResult<T>;\n database: Database;\n}\n\nfunction topLevelUseChanges(...args: Parameters<UseChanges>) {\n const { useChanges, database } = useFireproof();\n (topLevelUseChanges as TLUseChanges).database = database;\n return useChanges(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useChanges = topLevelUseChanges as TLUseChanges;\n","import { DocFileMeta } from \"@fireproof/core\";\nimport React, { useState, useEffect, ImgHTMLAttributes } from \"react\";\n\nconst { URL } = globalThis;\n\n// Union type to support both direct File objects and metadata objects\ntype FileType = File | DocFileMeta;\n\ninterface ImgFileProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, \"src\"> {\n file?: FileType;\n /**\n * @deprecated Use 'file' instead. This is for internal use only to support legacy code.\n * @internal\n */\n meta?: FileType;\n}\n\n// Helper function to determine if the object is a File-like object\nfunction isFile(obj: FileType): obj is File {\n return \"type\" in obj && \"size\" in obj && \"stream\" in obj && typeof obj.stream === \"function\";\n}\n\n// Helper function to determine if the object is a DocFileMeta\nfunction isFileMeta(obj: FileType): obj is DocFileMeta {\n return \"type\" in obj && \"size\" in obj && \"file\" in obj && typeof obj.file === \"function\";\n}\n\nexport function ImgFile({ file, meta, ...imgProps }: ImgFileProps) {\n const [imgDataUrl, setImgDataUrl] = useState(\"\");\n\n // Use meta as fallback if file is not provided (for backward compatibility)\n const fileData = file || meta;\n\n useEffect(() => {\n if (!fileData) return;\n\n const loadFile = async () => {\n let fileObj: File | null = null;\n let fileType = \"\";\n\n switch (true) {\n case isFile(fileData):\n fileObj = fileData;\n fileType = fileData.type;\n break;\n case isFileMeta(fileData):\n fileType = fileData.type;\n fileObj = (await fileData.file?.()) || null;\n break;\n }\n\n if (fileObj && /image/.test(fileType)) {\n const src = URL.createObjectURL(fileObj);\n setImgDataUrl(src);\n return () => URL.revokeObjectURL(src);\n }\n };\n\n let isMounted = true;\n let cleanup: (() => void) | undefined;\n\n loadFile().then((result) => {\n if (isMounted) {\n cleanup = result;\n } else if (result) {\n result();\n }\n });\n\n return () => {\n isMounted = false;\n if (cleanup) cleanup();\n };\n }, [fileData]);\n\n return imgDataUrl\n ? React.createElement(\"img\", {\n src: imgDataUrl,\n ...imgProps,\n })\n : null;\n}\n\nexport default ImgFile;\n"],"mappings":";AAaA,SAAS,iBAAiB;AAC1B,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;AA8J3D,IAAM,eAAe,CAAC;AAE7B,SAAS,UAAa,OAAa;AACjC,MAAI,OAAO,oBAAoB,aAAa;AAC1C,WAAO,gBAAgB,KAAK;AAAA,EAC9B,OAAO;AAEL,WAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA,EACzC;AACF;AA0BO,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,WAAW,UAAU,MAAM,MAAM,IAAI;AAEtE,QAAM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AAO,YAAY,OAAO,OAAO,IAAI,WAAW;AACpF;AAGA,SAAS,WAAW,KAAmC;AACrD,SAAO,UAAU,OAAO,UAAU,OAAO,UAAU,OAAO,OAAO,IAAI,SAAS;AAChF;AAEO,SAAS,QAAQ,EAAE,MAAM,MAAM,GAAG,SAAS,GAAiB;AACjE,QAAM,CAAC,YAAY,aAAa,IAAID,UAAS,EAAE;AAG/C,QAAM,WAAW,QAAQ;AAEzB,EAAAC,WAAU,MAAM;AACd,QAAI,CAAC,SAAU;AAEf,UAAM,WAAW,YAAY;AAC3B,UAAI,UAAuB;AAC3B,UAAI,WAAW;AAEf,cAAQ,MAAM;AAAA,QACZ,KAAK,OAAO,QAAQ;AAClB,oBAAU;AACV,qBAAW,SAAS;AACpB;AAAA,QACF,KAAK,WAAW,QAAQ;AACtB,qBAAW,SAAS;AACpB,oBAAW,MAAM,SAAS,OAAO,KAAM;AACvC;AAAA,MACJ;AAEA,UAAI,WAAW,QAAQ,KAAK,QAAQ,GAAG;AACrC,cAAM,MAAM,IAAI,gBAAgB,OAAO;AACvC,sBAAc,GAAG;AACjB,eAAO,MAAM,IAAI,gBAAgB,GAAG;AAAA,MACtC;AAAA,IACF;AAEA,QAAI,YAAY;AAChB,QAAI;AAEJ,aAAS,EAAE,KAAK,CAAC,WAAW;AAC1B,UAAI,WAAW;AACb,kBAAU;AAAA,MACZ,WAAW,QAAQ;AACjB,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,kBAAY;AACZ,UAAI,QAAS,SAAQ;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO,aACH,MAAM,cAAc,OAAO;AAAA,IACzB,KAAK;AAAA,IACL,GAAG;AAAA,EACL,CAAC,IACD;AACN;","names":["useDocument","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges","useState","useEffect"]}
@@ -1 +1 @@
1
- {"inputs":{"src/react/useFireproof.ts":{"bytes":14322,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":2460,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/img-file.ts":{"bytes":2242,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"use-fireproof","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":972,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":31574},"dist/fireproof-core/react/index.cjs":{"imports":[{"path":"@fireproof/core","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/react/index.ts","inputs":{"src/react/index.ts":{"bytesInOutput":331},"src/react/useFireproof.ts":{"bytesInOutput":6388},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215},"src/react/img-file.ts":{"bytesInOutput":1495}},"bytes":10685}}}
1
+ {"inputs":{"src/react/useFireproof.ts":{"bytes":14322,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":2460,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/img-file.ts":{"bytes":2248,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":962,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":31570},"dist/fireproof-core/react/index.cjs":{"imports":[{"path":"@fireproof/core","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/react/index.ts","inputs":{"src/react/index.ts":{"bytesInOutput":331},"src/react/useFireproof.ts":{"bytesInOutput":6388},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215},"src/react/img-file.ts":{"bytesInOutput":1499}},"bytes":10689}}}
@@ -1 +1 @@
1
- {"inputs":{"src/react/useFireproof.ts":{"bytes":14322,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":2460,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/img-file.ts":{"bytes":2242,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"use-fireproof","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":972,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":30463},"dist/fireproof-core/react/index.js":{"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","ImgFile","useAllDocs","useChanges","useDocument","useFireproof","useLiveQuery"],"entryPoint":"src/react/index.ts","inputs":{"src/react/useFireproof.ts":{"bytesInOutput":5940},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/index.ts":{"bytesInOutput":0},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215},"src/react/img-file.ts":{"bytesInOutput":1472}},"bytes":8576}}}
1
+ {"inputs":{"src/react/useFireproof.ts":{"bytes":14322,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":2460,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/img-file.ts":{"bytes":2248,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/index.ts":{"bytes":962,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"},{"path":"src/react/img-file.ts","kind":"import-statement","original":"./img-file.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":30469},"dist/fireproof-core/react/index.js":{"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","ImgFile","useAllDocs","useChanges","useDocument","useFireproof","useLiveQuery"],"entryPoint":"src/react/index.ts","inputs":{"src/react/useFireproof.ts":{"bytesInOutput":5940},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/index.ts":{"bytesInOutput":0},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215},"src/react/img-file.ts":{"bytesInOutput":1476}},"bytes":8580}}}
@@ -1,5 +1,5 @@
1
- import { Result, URI } from "@adviser/cement";
2
- import { bs, fireproof } from "@fireproof/core";
1
+ import { BuildURI, Result, URI } from "@adviser/cement";
2
+ import { bs, rt, fireproof, SuperThis } from "@fireproof/core";
3
3
 
4
4
  class TestInterceptor extends bs.PassThroughGateway {
5
5
  readonly fn = vitest.fn();
@@ -51,6 +51,72 @@ class TestInterceptor extends bs.PassThroughGateway {
51
51
  }
52
52
  }
53
53
 
54
+ export class URITrackGateway implements bs.Gateway {
55
+ readonly uris: Set<string>;
56
+ readonly memgw: rt.gw.memory.MemoryGateway;
57
+
58
+ constructor(sthis: SuperThis, memorys: Map<string, Uint8Array>, uris: Set<string>) {
59
+ this.memgw = new rt.gw.memory.MemoryGateway(sthis, memorys);
60
+ this.uris = uris;
61
+ }
62
+
63
+ uriAdd(uri: URI) {
64
+ if (!uri.getParam("itis")) {
65
+ throw new Error("itis not set");
66
+ }
67
+ if (this.uris.has(uri.toString())) {
68
+ throw new Error(`uri already added:${uri.toString()}`);
69
+ }
70
+ this.uris.add(uri.toString());
71
+ }
72
+
73
+ buildUrl(baseUrl: URI, key: string): Promise<Result<URI>> {
74
+ this.uriAdd(baseUrl);
75
+ return this.memgw.buildUrl(baseUrl, key);
76
+ }
77
+ start(baseUrl: URI): Promise<Result<URI>> {
78
+ this.uriAdd(baseUrl);
79
+ return this.memgw.start(baseUrl);
80
+ }
81
+ close(uri: URI): Promise<bs.VoidResult> {
82
+ this.uriAdd(uri);
83
+ return this.memgw.close(uri);
84
+ }
85
+ destroy(baseUrl: URI): Promise<bs.VoidResult> {
86
+ this.uriAdd(baseUrl);
87
+ return this.memgw.destroy(baseUrl);
88
+ }
89
+
90
+ put(url: URI, bytes: Uint8Array): Promise<bs.VoidResult> {
91
+ this.uriAdd(url);
92
+ return this.memgw.put(url, bytes);
93
+ }
94
+
95
+ get(url: URI): Promise<bs.GetResult> {
96
+ this.uriAdd(url);
97
+ return this.memgw.get(url);
98
+ }
99
+ delete(url: URI): Promise<bs.VoidResult> {
100
+ this.uriAdd(url);
101
+ return this.memgw.delete(url);
102
+ }
103
+
104
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
105
+ subscribe(url: URI, callback: (meta: Uint8Array) => void, sthis: SuperThis): Promise<bs.UnsubscribeResult> {
106
+ this.uriAdd(url);
107
+ return Promise.resolve(
108
+ Result.Ok(() => {
109
+ /* noop */
110
+ }),
111
+ );
112
+ }
113
+
114
+ async getPlain(url: URI, key: string): Promise<Result<Uint8Array>> {
115
+ this.uriAdd(url);
116
+ return this.memgw.getPlain(url, key);
117
+ }
118
+ }
119
+
54
120
  describe("InterceptorGateway", () => {
55
121
  it("passthrough", async () => {
56
122
  const gwi = new TestInterceptor();
@@ -70,7 +136,7 @@ describe("InterceptorGateway", () => {
70
136
  await db.close();
71
137
  await db.destroy();
72
138
  // await sleep(1000);
73
- expect(gwi.fn.mock.calls.length).toBe(56);
139
+ expect(gwi.fn.mock.calls.length).toBe(58);
74
140
  // might be a stupid test
75
141
  expect(gwi.fn.mock.calls.map((i) => i[0]).sort() /* not ok there are some operation */).toEqual(
76
142
  [
@@ -130,7 +196,58 @@ describe("InterceptorGateway", () => {
130
196
  "destroy",
131
197
  "destroy",
132
198
  "destroy",
199
+ "subscribe",
200
+ "subscribe",
133
201
  ].sort() /* not ok there are some operation */,
134
202
  );
135
203
  });
204
+
205
+ it("use the uri-interceptor", async () => {
206
+ let callCount = 0;
207
+ const gwUris = new Set<string>();
208
+ const unreg = bs.registerStoreProtocol({
209
+ protocol: "uriTest:",
210
+ isDefault: false,
211
+ defaultURI: () => {
212
+ return BuildURI.from("uriTest://").pathname("ram").URI();
213
+ },
214
+ gateway: async (sthis) => {
215
+ return new URITrackGateway(sthis, new Map<string, Uint8Array>(), gwUris);
216
+ },
217
+ });
218
+ const db = fireproof("interceptor-gateway", {
219
+ storeUrls: {
220
+ base: "uriTest://inspector-gateway",
221
+ },
222
+ gatewayInterceptor: bs.URIInterceptor.withMapper(async (uri: URI) =>
223
+ uri
224
+ .build()
225
+ .setParam("itis", "" + ++callCount)
226
+ .URI(),
227
+ ),
228
+ });
229
+ await Promise.all(
230
+ Array(5)
231
+ .fill(0)
232
+ .map((_, i) => db.put({ _id: "foo" + i, foo: i })),
233
+ );
234
+ expect((await db.allDocs<{ foo: number }>()).rows.map((i) => i.value.foo)).toEqual(
235
+ Array(5)
236
+ .fill(0)
237
+ .map((_, i) => i),
238
+ );
239
+ await db.close();
240
+ expect(callCount).toBe(gwUris.size);
241
+ expect(
242
+ Array.from(gwUris)
243
+ .map((i) => URI.from(i).getParam("itis"))
244
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
245
+ .sort((a, b) => +a! - +b!),
246
+ ).toEqual(
247
+ Array(gwUris.size)
248
+ .fill(1)
249
+ .map((_, i) => "" + (i + 1)),
250
+ );
251
+ unreg();
252
+ });
136
253
  });
@@ -86,6 +86,13 @@ describe("basic Ledger with record", function () {
86
86
  const e = await db.get("hello").catch((e) => e);
87
87
  expect(e.message).toMatch(/Not found/);
88
88
  });
89
+ it("should remove as an alias for del", async () => {
90
+ const ok = await db.remove("hello");
91
+ expect(ok.id).toBe("hello");
92
+
93
+ const e = await db.get("hello").catch((e) => e);
94
+ expect(e.message).toMatch(/Not found/);
95
+ });
89
96
  it("has changes", async () => {
90
97
  const { rows } = await db.changes([]);
91
98
  expect(rows.length).toBe(1);
@@ -197,6 +204,13 @@ describe("named Ledger with record", function () {
197
204
  const e = await db.get("hello").catch((e) => e);
198
205
  expect(e.message).toMatch(/Not found/);
199
206
  });
207
+ it("should remove as an alias for del", async () => {
208
+ const ok = await db.remove("hello");
209
+ expect(ok.id).toBe("hello");
210
+
211
+ const e = await db.get("hello").catch((e) => e);
212
+ expect(e.message).toMatch(/Not found/);
213
+ });
200
214
  it("has changes", async () => {
201
215
  const { rows } = await db.changes([]);
202
216
  expect(rows.length).toBe(1);
@@ -1,7 +1,7 @@
1
1
  import { renderHook, waitFor } from "@testing-library/react";
2
2
  import { describe, expect, it } from "vitest";
3
3
  import { fireproof, useFireproof } from "use-fireproof";
4
- import type { Database, LiveQueryResult, UseDocumentResult } from "use-fireproof";
4
+ import type { Database, DocResponse, LiveQueryResult, UseDocumentResult } from "use-fireproof";
5
5
 
6
6
  // Test timeout value for CI
7
7
  const TEST_TIMEOUT = 45000;
@@ -306,11 +306,13 @@ describe("HOOK: useFireproof useDocument has results reset sync", () => {
306
306
  docResult.merge({ input: "fresh" });
307
307
  });
308
308
 
309
+ let waitForSave: Promise<DocResponse>;
309
310
  renderHook(() => {
310
- docResult.save();
311
+ waitForSave = docResult.save();
311
312
  });
312
313
 
313
- await waitFor(() => {
314
+ await waitFor(async () => {
315
+ await waitForSave;
314
316
  expect(docResult.doc.input).toBe("fresh");
315
317
  expect(docResult.doc._id).toBeDefined();
316
318
  });
@@ -527,11 +529,13 @@ describe("HOOK: useFireproof bug fix: once the ID is set, it can reset", () => {
527
529
  docResult.merge({ input: "new temp data" });
528
530
  });
529
531
 
532
+ let waitForSave: Promise<DocResponse>;
530
533
  renderHook(() => {
531
- docResult.save();
534
+ waitForSave = docResult.save();
532
535
  });
533
536
 
534
- await waitFor(() => {
537
+ await waitFor(async () => {
538
+ await waitForSave;
535
539
  expect(docResult.doc._id).toBeDefined();
536
540
  expect(docResult.doc.input).toBe("new temp data");
537
541
  });
@@ -0,0 +1,94 @@
1
+ import { URI } from "@adviser/cement";
2
+ import { rt, bs, fireproof, PARAM, ensureSuperThis, Database } from "@fireproof/core";
3
+
4
+ describe("MetaKeyHack", () => {
5
+ const storageMap = new Map();
6
+
7
+ const sthis = ensureSuperThis();
8
+ const memGw = new rt.gw.memory.MemoryGateway(sthis, storageMap);
9
+ bs.registerStoreProtocol({
10
+ protocol: "hack:",
11
+ defaultURI: () => URI.from(`hack://localhost?version=hack`),
12
+ serdegateway: async () => {
13
+ return new rt.AddKeyToDbMetaGateway(memGw, "v2");
14
+ },
15
+ });
16
+
17
+ let db: Database;
18
+ let ctx: { loader: bs.Loadable };
19
+ beforeAll(async () => {
20
+ db = fireproof("test", {
21
+ storeUrls: {
22
+ base: "hack://localhost",
23
+ },
24
+ keyBag: {
25
+ url: "memory://./dist/kb-dir-partykit?extractKey=_deprecated_internal_api",
26
+ },
27
+ });
28
+ await db.ready();
29
+ ctx = { loader: db.ledger.crdt.blockstore.loader };
30
+ });
31
+
32
+ it("inject key into meta", async () => {
33
+ const loader = db.ledger.crdt.blockstore.loader;
34
+ const metaStore = loader.attachedStores.local().active.meta;
35
+ const subscribeFn = vitest.fn();
36
+ const unreg = await metaStore.realGateway.subscribe(
37
+ ctx,
38
+ metaStore.url().build().setParam(PARAM.SELF_REFLECT, "x").URI(),
39
+ subscribeFn,
40
+ );
41
+ expect(unreg.isOk()).toBeTruthy();
42
+ await db.put({ val: "test" });
43
+
44
+ const dataStore = loader.attachedStores.local().active.car;
45
+ const kb = new rt.KeyBag(db.ledger.opts.keyBag);
46
+ const rDataStoreKeyItem = await kb.getNamedKey(dataStore.url().getParam(PARAM.STORE_KEY) ?? "");
47
+
48
+ await rDataStoreKeyItem.Ok().upsert("zBUFMmu5c3VdCa4r2DZTzhR", false);
49
+ await rDataStoreKeyItem.Ok().upsert("zH1fyizirAiYVxoaQ2XZ3Xj", false);
50
+
51
+ expect(rDataStoreKeyItem.isOk()).toBeTruthy();
52
+ const rUrl = await memGw.buildUrl(metaStore.url(), "main");
53
+ // console.log(">>>>", rUrl.Ok().toString())
54
+ const rGet = await memGw.get(rUrl.Ok());
55
+ const metas = JSON.parse(ctx.loader.sthis.txt.decode(rGet.Ok())) as rt.V2SerializedMetaKey;
56
+ const keyMaterials = metas.keys;
57
+ const dataStoreKeyMaterial = await rDataStoreKeyItem.Ok().asKeysItem();
58
+ expect(keyMaterials.length).toBeGreaterThan(0);
59
+ expect(dataStoreKeyMaterial).toEqual({
60
+ keys: {
61
+ ...(await rDataStoreKeyItem
62
+ .Ok()
63
+ .get()
64
+ .then(async (r) => ({
65
+ [r?.fingerPrint as string]: {
66
+ default: true,
67
+ fingerPrint: r?.fingerPrint,
68
+ key: await r?.extract().then((i) => i.keyStr),
69
+ },
70
+ }))),
71
+ z3boMcLEQxjZAMrVo2j3k9bZJzmSqXkQmh6q7bLZ2nRuo: {
72
+ default: false,
73
+ fingerPrint: "z3boMcLEQxjZAMrVo2j3k9bZJzmSqXkQmh6q7bLZ2nRuo",
74
+ key: "zH1fyizirAiYVxoaQ2XZ3Xj",
75
+ },
76
+ zG5F2VWVAs3uAFyLE5rty5WWo7zJ1oBmYTdnraxfhaHG5: {
77
+ default: false,
78
+ fingerPrint: "zG5F2VWVAs3uAFyLE5rty5WWo7zJ1oBmYTdnraxfhaHG5",
79
+ key: "zBUFMmu5c3VdCa4r2DZTzhR",
80
+ },
81
+ },
82
+ name: "@test-data@",
83
+ });
84
+
85
+ // expect(keyMaterials.every((k) => k === dataStoreKeyMaterial.keyStr)).toBeTruthy()
86
+ // expect(subscribeFn.mock.calls).toEqual([]);
87
+ expect(subscribeFn).toHaveBeenCalledTimes(2);
88
+ const addKeyToDbMetaGateway = metaStore.realGateway as rt.AddKeyToDbMetaGateway;
89
+ expect(
90
+ subscribeFn.mock.calls.map((i) => i.map((i) => i.payload.map((i: bs.DbMetaEvent) => i.eventCid.toString()))).flat(),
91
+ ).toEqual(addKeyToDbMetaGateway.lastDecodedMetas.map((i) => i.metas.map((i) => i.cid)));
92
+ unreg.Ok()();
93
+ });
94
+ });