@fireproof/core 0.20.0 → 0.20.1-dev-preview-02

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/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\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 useDocument = createUseDocument(database);\n const useLiveQuery = createUseLiveQuery(database);\n const useAllDocs = createUseAllDocs(database);\n const useChanges = createUseChanges(database);\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n const updateHappenedRef = useRef(false);\n\n return 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 try {\n if (e?.preventDefault) e.preventDefault();\n await save();\n reset();\n } catch (error) {\n console.error(\"Error in document submission:\", error);\n // We don't re-throw here since submit is often used in UI handlers\n // and we don't want unhandled rejections\n }\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","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n// Internal shadow type for array-like behavior (implementation detail)\ntype EnhancedQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> = LiveQueryResult<T, K, R> &\n DocWithId<T>[];\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return 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<EnhancedQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return Object.assign(docs, {\n docs,\n rows: initialRows,\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).filter((r): r is DocWithId<T> => !!r);\n setResult(\n Object.assign(docs, {\n docs,\n rows: res.rows,\n }),\n );\n }, [database, mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows();\n const unsubscribe = database.subscribe(refreshRows);\n return () => {\n unsubscribe();\n };\n }, [database, refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return 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","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return 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","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":";AACA,SAAS,iBAAiB;;;ACD1B,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;;;ACG3D,SAAS,UAAa,OAAa;AACxC,UAAQ,oBAAoB,CAAC,MAAS,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,IAAI,KAAK;AAC7E;;;ADGO,SAAS,kBAAkB,UAAoB;AACpD,QAAM,oBAAoB,OAAO,KAAK;AAEtC,SAAO,SAAS,YAAgC,gBAAqE;AACnH,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa,kBAAmB,CAAC;AAAA,IACnC;AAEA,UAAM,qBAAqB,QAAQ,MAAM,UAAU,EAAE,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;AAEzE,UAAM,CAAC,KAAK,MAAM,IAAI,SAAS,UAAU;AAEzC,UAAM,UAAU,YAAY,YAAY;AACtC,YAAM,SAAS,IAAI,MAAM,MAAM,SAAS,IAAO,IAAI,GAAG,EAAE,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ACtC;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":["useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useState","useEffect"]}
1
+ {"version":3,"sources":["../../../src/react/use-fireproof.ts","../../../src/react/use-document.ts","../../../src/react/utils.ts","../../../src/react/use-live-query.ts","../../../src/react/use-all-docs.ts","../../../src/react/use-changes.ts","../../../src/react/img-file.ts"],"sourcesContent":["import type { ConfigOpts, Database } from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useMemo } from \"react\";\nimport type { UseFireproof } from \"./types.js\";\nimport { createUseDocument } from \"./use-document.js\";\nimport { createUseLiveQuery } from \"./use-live-query.js\";\nimport { createUseAllDocs } from \"./use-all-docs.js\";\nimport { createUseChanges } from \"./use-changes.js\";\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\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 // Memoize the hook factory functions together to ensure they don't recreate on every render\n const hooks = useMemo(() => {\n return {\n useDocument: createUseDocument(database),\n useLiveQuery: createUseLiveQuery(database),\n useAllDocs: createUseAllDocs(database),\n useChanges: createUseChanges(database),\n };\n }, [database]);\n\n const { useDocument, useLiveQuery, useAllDocs, useChanges } = hooks;\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n\n// Export types\nexport type {\n LiveQueryResult,\n UseDocumentResult,\n AllDocsResult,\n ChangesResult,\n UseDocument,\n UseLiveQuery,\n UseAllDocs,\n UseChanges,\n UseFireproof,\n} from \"./types.js\";\n","import { useCallback, useEffect, useMemo, useState, useRef } from \"react\";\nimport type { DocSet, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport { deepClone } from \"./utils.js\";\nimport type { DeleteDocFn, StoreDocFn, UseDocumentInitialDocOrFn, UseDocumentResult } from \"./types.js\";\n\n/**\n * Implementation of the useDocument hook\n */\nexport function createUseDocument(database: Database) {\n return function useDocument<T extends DocTypes>(initialDocOrFn?: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n const updateHappenedRef = useRef(false);\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","/**\n * Deep clone a value\n */\nexport function deepClone<T>(value: T): T {\n return (structuredClone ?? ((v: T) => JSON.parse(JSON.stringify(v))))(value);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { DocFragment, DocTypes, DocWithId, IndexKeyType, IndexRow, MapFn, Database } from \"@fireproof/core\";\nimport type { LiveQueryResult } from \"./types.js\";\n\n// Internal shadow type for array-like behavior (implementation detail)\ntype EnhancedQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> = LiveQueryResult<T, K, R> &\n DocWithId<T>[];\n\n/**\n * Implementation of the useLiveQuery hook\n */\nexport function createUseLiveQuery(database: Database) {\n return 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<EnhancedQueryResult<T, K, R>>(() => {\n const docs = initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r);\n return Object.assign(docs, {\n docs,\n rows: initialRows,\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).filter((r): r is DocWithId<T> => !!r);\n setResult(\n Object.assign(docs, {\n docs,\n rows: res.rows,\n }),\n );\n }, [database, mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows();\n const unsubscribe = database.subscribe(refreshRows);\n return () => {\n unsubscribe();\n };\n }, [database, refreshRows]);\n\n return result;\n };\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { AllDocsResult } from \"./types.js\";\n\n/**\n * Implementation of the useAllDocs hook\n */\nexport function createUseAllDocs(database: Database) {\n return 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","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { ChangesOptions, ClockHead, DocTypes, DocWithId, Database } from \"@fireproof/core\";\nimport type { ChangesResult } from \"./types.js\";\n\n/**\n * Implementation of the useChanges hook\n */\nexport function createUseChanges(database: Database) {\n return 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","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":";AACA,SAAS,iBAAiB;AAC1B,SAAS,WAAAA,gBAAe;;;ACFxB,SAAS,aAAa,WAAW,SAAS,UAAU,cAAc;;;ACG3D,SAAS,UAAa,OAAa;AACxC,UAAQ,oBAAoB,CAAC,MAAS,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,IAAI,KAAK;AAC7E;;;ADGO,SAAS,kBAAkB,UAAoB;AACpD,SAAO,SAAS,YAAgC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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":["useMemo","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useMemo","useState","useMemo","useState","useEffect"]}
@@ -1 +1 @@
1
- {"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":4209,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":1760,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2247,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"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":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.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":19592},"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},{"path":"react","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":197},"src/react/use-fireproof.ts":{"bytesInOutput":502},"src/react/use-document.ts":{"bytesInOutput":3579},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1129},"src/react/use-all-docs.ts":{"bytesInOutput":657},"src/react/use-changes.ts":{"bytesInOutput":679},"src/react/img-file.ts":{"bytesInOutput":1499}},"bytes":10030}}}
1
+ {"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3959,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":1760,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2505,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"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":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.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":19682},"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},{"path":"react","kind":"require-call","external":true},{"path":"react","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":197},"src/react/use-fireproof.ts":{"bytesInOutput":687},"src/react/use-document.ts":{"bytesInOutput":3460},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1129},"src/react/use-all-docs.ts":{"bytesInOutput":657},"src/react/use-changes.ts":{"bytesInOutput":679},"src/react/img-file.ts":{"bytesInOutput":1499}},"bytes":10096}}}
@@ -1 +1 @@
1
- {"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":4209,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":1760,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2247,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"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":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.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":19622},"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},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","ImgFile","useFireproof"],"entryPoint":"src/react/index.ts","inputs":{"src/react/use-fireproof.ts":{"bytesInOutput":484},"src/react/use-document.ts":{"bytesInOutput":3383},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1123},"src/react/use-all-docs.ts":{"bytesInOutput":669},"src/react/use-changes.ts":{"bytesInOutput":691},"src/react/index.ts":{"bytesInOutput":0},"src/react/img-file.ts":{"bytesInOutput":1476}},"bytes":8248}}}
1
+ {"inputs":{"src/react/utils.ts":{"bytes":156,"imports":[],"format":"esm"},"src/react/use-document.ts":{"bytes":3959,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"src/react/utils.ts","kind":"import-statement","original":"./utils.js"}],"format":"esm"},"src/react/use-live-query.ts":{"bytes":1760,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-all-docs.ts":{"bytes":934,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-changes.ts":{"bytes":974,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/use-fireproof.ts":{"bytes":2505,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"src/react/use-document.ts","kind":"import-statement","original":"./use-document.js"},{"path":"src/react/use-live-query.ts","kind":"import-statement","original":"./use-live-query.js"},{"path":"src/react/use-all-docs.ts","kind":"import-statement","original":"./use-all-docs.js"},{"path":"src/react/use-changes.ts","kind":"import-statement","original":"./use-changes.js"}],"format":"esm"},"src/react/types.ts":{"bytes":2407,"imports":[],"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":124,"imports":[{"path":"src/react/use-fireproof.ts","kind":"import-statement","original":"./use-fireproof.js"},{"path":"src/react/types.ts","kind":"import-statement","original":"./types.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":19722},"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},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","ImgFile","useFireproof"],"entryPoint":"src/react/index.ts","inputs":{"src/react/use-fireproof.ts":{"bytesInOutput":658},"src/react/use-document.ts":{"bytesInOutput":3264},"src/react/utils.ts":{"bytesInOutput":107},"src/react/use-live-query.ts":{"bytesInOutput":1123},"src/react/use-all-docs.ts":{"bytesInOutput":669},"src/react/use-changes.ts":{"bytesInOutput":691},"src/react/index.ts":{"bytesInOutput":0},"src/react/img-file.ts":{"bytesInOutput":1476}},"bytes":8303}}}
@@ -0,0 +1,145 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { render, waitFor, fireEvent, act } from "@testing-library/react";
3
+ import { useState, useEffect, createElement } from "react";
4
+ import { useFireproof } from "../../src/react/use-fireproof.js";
5
+
6
+ // Extend HTMLElement for TypeScript compatibility
7
+ declare global {
8
+ interface HTMLElement {
9
+ querySelector(selectors: string): HTMLElement | null;
10
+ getAttribute(name: string): string | null;
11
+ textContent: string | null;
12
+ click(): void;
13
+ }
14
+ }
15
+
16
+ // Test component that triggers state updates and verifies database stability
17
+ function TestComponent() {
18
+ const { database } = useFireproof("test-stability-db");
19
+ const initialDatabaseRef = database;
20
+
21
+ const [counter, setCounter] = useState(0);
22
+
23
+ // Verify that the database reference remains stable across renders
24
+ if (counter > 0 && initialDatabaseRef !== database) {
25
+ throw new Error("Database reference changed between renders!");
26
+ }
27
+
28
+ return createElement("div", {}, [
29
+ createElement("div", { "data-testid": "db-name", key: "db-name" }, database.name),
30
+ createElement("div", { "data-testid": "counter", key: "counter" }, String(counter)),
31
+ createElement(
32
+ "button",
33
+ {
34
+ "data-testid": "increment",
35
+ key: "increment",
36
+ onClick: () => setCounter((c) => c + 1),
37
+ },
38
+ "Increment",
39
+ ),
40
+ ]);
41
+ }
42
+
43
+ // Test timeout value for CI
44
+ const TEST_TIMEOUT = 60000; // 1 minute per test
45
+
46
+ describe("HOOK: useFireproof stability", () => {
47
+ it(
48
+ "database instance remains stable across renders",
49
+ async () => {
50
+ // Mock console.error to catch any React errors
51
+ const consoleErrorMock = vi.spyOn(console, "error").mockImplementation(vi.fn());
52
+
53
+ const { findByTestId } = render(createElement(TestComponent, {}));
54
+
55
+ // Get initial state
56
+ const dbNameEl = await findByTestId("db-name" as const);
57
+ const counterEl = await findByTestId("counter" as const);
58
+
59
+ // Verify initial state
60
+ expect(dbNameEl.textContent).toBe("test-stability-db");
61
+ expect(counterEl.textContent).toBe("0");
62
+
63
+ // Trigger a re-render by updating state
64
+ const incrementButton = await findByTestId("increment" as const);
65
+ await act(async () => {
66
+ incrementButton.click();
67
+ });
68
+
69
+ // Verify state changed but no errors occurred
70
+ expect(counterEl.textContent).toBe("1");
71
+
72
+ // There should be no errors logged from React about database reference changing
73
+ expect(consoleErrorMock).not.toHaveBeenCalledWith(expect.stringContaining("Database reference changed between renders"));
74
+
75
+ // Perform multiple render cycles to ensure stability
76
+ for (let i = 0; i < 5; i++) {
77
+ await act(async () => {
78
+ incrementButton.click();
79
+ });
80
+ }
81
+
82
+ // Verify no errors occurred during multiple renders
83
+ expect(consoleErrorMock).not.toHaveBeenCalledWith(expect.stringContaining("Database reference changed between renders"));
84
+
85
+ // Restore console
86
+ consoleErrorMock.mockRestore();
87
+ },
88
+ TEST_TIMEOUT,
89
+ );
90
+
91
+ it(
92
+ "input events do not cause infinite render loops",
93
+ async () => {
94
+ // This test is specifically designed to catch the issue reported in v0.20.0
95
+
96
+ function InputTestComponent() {
97
+ // We still create the database to ensure no infinite render loops occur
98
+ // But we don't need to use any of its features directly in this test
99
+ useFireproof("test-input-db");
100
+ const [inputValue, setInputValue] = useState("");
101
+ const [renderCount, setRenderCount] = useState(0);
102
+
103
+ // Track render count
104
+ useEffect(() => {
105
+ setRenderCount((c) => c + 1);
106
+ }, []);
107
+
108
+ return createElement("div", {}, [
109
+ createElement("input", {
110
+ type: "text",
111
+ "data-testid": "input",
112
+ key: "input",
113
+ value: inputValue,
114
+ onChange: (e: { target: { value: string } }) => {
115
+ setInputValue(e.target.value);
116
+ },
117
+ }),
118
+ createElement("div", { "data-testid": "render-count", key: "render-count" }, String(renderCount)),
119
+ ]);
120
+ }
121
+
122
+ // Instead of using createRoot, use the standard render method
123
+ const { getByTestId } = render(createElement(InputTestComponent));
124
+
125
+ // Get the input element
126
+ const input = getByTestId("input");
127
+
128
+ // Simulate typing in the input field - this would trigger the bug in v0.20.0
129
+ await waitFor(() => {
130
+ fireEvent.change(input, { target: { value: "test" } });
131
+ });
132
+
133
+ // Wait a bit to ensure no infinite loop occurs
134
+ await new Promise((resolve) => setTimeout(resolve, 1000));
135
+
136
+ // Verify the render count hasn't exploded (if it were an infinite loop, the test would timeout)
137
+ const renderCount = getByTestId("render-count");
138
+
139
+ // The exact number isn't important, but it should be a small number
140
+ // If we're in an infinite loop, the test would have timed out before reaching here
141
+ expect(parseInt(renderCount.textContent || "0", 10)).toBeLessThan(10);
142
+ },
143
+ TEST_TIMEOUT,
144
+ );
145
+ });