@fireproof/core 0.20.0-dev-preview-06 → 0.20.0-dev-preview-11
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +9 -9
- package/index.cjs +3221 -3166
- package/index.cjs.map +1 -1
- package/index.d.cts +241 -189
- package/index.d.ts +241 -189
- package/index.js +3211 -3156
- package/index.js.map +1 -1
- package/metafile-cjs.json +1 -1
- package/metafile-esm.json +1 -1
- package/package.json +3 -3
- package/react/index.cjs.map +1 -1
- package/react/index.js.map +1 -1
- package/tests/blockstore/loader.test.ts +6 -6
- package/tests/blockstore/transaction.test.ts +8 -8
- package/tests/fireproof/all-gateway.test.ts +7 -7
- package/tests/fireproof/crdt.test.ts +35 -45
- package/tests/fireproof/database.test.ts +34 -33
- package/tests/fireproof/fireproof.test.ts +58 -60
- package/tests/fireproof/hello.test.ts +3 -3
- package/tests/fireproof/indexer.test.ts +37 -36
- package/tests/gateway/file/loader-config.test.ts +17 -17
- package/tests/gateway/indexdb/loader-config.test.ts +5 -5
- package/tests/www/gallery.html +2 -2
- package/tests/www/todo-aws.html +1 -1
- package/tests/www/todo-ipfs.html +1 -1
- package/tests/www/todo-local.html +1 -1
- package/tests/www/todo.html +1 -1
- /package/tests/fireproof/{multiple-database.test.ts → multiple-ledger.test.ts} +0 -0
package/react/index.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/react/index.ts","../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts"],"sourcesContent":["export {\n type TLUseDocument,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useDocument,\n} from \"./useDocument.js\";\nexport { FireproofCtx, type UseFireproof, useFireproof } from \"./useFireproof.js\";\nexport {\n type TLUseLiveQuery,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useLiveQuery,\n} from \"./useLiveQuery.js\";\nexport {\n type TLUseAllDocs,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useAllDocs,\n} from \"./useAllDocs.js\";\nexport {\n type TLUseChanges,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useChanges,\n} from \"./useChanges.js\";\n// why is this there is should be a package system\n// export * from \"@fireproof/core\";\n","import type {\n ConfigOpts,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n Database,\n MapFn,\n QueryOpts,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState } 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}\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\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<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, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\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 * 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 */\n readonly useChanges: UseChanges;\n}\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 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;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) 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 [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\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 rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\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 setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\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 new 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 This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.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 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 { Database, DocTypes } 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,kBAA0B;AAC1B,mBAA0D;AAoInD,IAAM,eAAe,CAAC;AA0BtB,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,eAAW,uBAAU,MAAM,MAAM,IAAI;AAEtE,WAASA,aAAgC,gBAAoE;AAC3G,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa;AAAA,IACf;AAGA,UAAM,QAAQ,WAAW,OAAO;AAKhC,UAAM,CAAC,KAAK,MAAM,QAAI,uBAAS,UAAU;AAEzC,UAAM,iBAAa,0BAAY,YAAY;AAEzC,YAAMC,OAAM,QAAQ,MAAM,SAAS,IAAO,KAAK,EAAE,MAAM,MAAM,UAAU,IAAI;AAC3E,aAAOA,IAAG;AAAA,IACZ,GAAG,CAAC,KAAK,CAAC;AAEV,UAAM,cAAyB;AAAA,MAC7B,OAAO,gBAAgB;AACrB,cAAM,MAAM,MAAM,SAAS,IAAI,eAAe,GAAG;AAEjD,YAAI,CAAC,eAAe,CAAC,IAAI,IAAK,QAAO,CAAC,OAAO,EAAE,GAAG,GAAG,KAAK,IAAI,GAAG,EAAE;AACnE,eAAO;AAAA,MACT;AAAA,MACA,CAAC,GAAG;AAAA,IACN;AAEA,UAAM,gBAA4B;AAAA,MAChC,OAAO,gBAAgB;AACrB,cAAM,KAAK,a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,IAAI,CAAC;AAE9D,UAAM,kBAAc,0BAAY,YAAY;AAC1C,YAAM,MAAM,MAAM,SAAS,QAAW,OAAO,IAAI;AACjD,gBAAU,EAAE,GAAG,KAAK,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,EAAE,KAAqB,EAAE,CAAC;AAAA,IAC1E,GAAG,CAAC,OAAO,WAAW,CAAC;AAEvB,gCAAU,MAAM;AACd,kBAAY;AACZ,aAAO,SAAS,UAAU,WAAW;AAAA,IACvC,GAAG,CAAC,WAAW,CAAC;AAEhB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,UAAU,cAAAF,eAAc,aAAAF,cAAa,YAAAG,aAAY,YAAAC,YAAW;AACvE;;;AC7SA,SAAS,uBAAuB,MAA+B;AAC7D,QAAM,EAAE,aAAAC,cAAa,SAAS,IAAI,aAAa;AAC/C,EAAC,oBAAsC,WAAW;AAClD,SAAOA,aAAY,GAAG,IAAI;AAC5B;AAkCO,IAAM,cAAc;;;ACpC3B,SAAS,wBAAwB,MAAgC;AAC/D,QAAM,EAAE,cAAAC,eAAc,SAAS,IAAI,aAAa;AAChD,EAAC,qBAAwC,WAAW;AACpD,SAAOA,cAAa,GAAG,IAAI;AAC7B;AAmBO,IAAM,eAAe;;;ACzB5B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;;;ACtB1B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
1
|
+
{"version":3,"sources":["../../../src/react/index.ts","../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts"],"sourcesContent":["export {\n type TLUseDocument,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useDocument,\n} from \"./useDocument.js\";\nexport { FireproofCtx, type UseFireproof, useFireproof } from \"./useFireproof.js\";\nexport {\n type TLUseLiveQuery,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useLiveQuery,\n} from \"./useLiveQuery.js\";\nexport {\n type TLUseAllDocs,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useAllDocs,\n} from \"./useAllDocs.js\";\nexport {\n type TLUseChanges,\n /** @deprecated Use return values from useFireproof('dbname') instead. Top level usage will be removed in future versions. */\n useChanges,\n} from \"./useChanges.js\";\n// why is this there is should be a package system\n// export * from \"@fireproof/core\";\n","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 } 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}\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\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<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, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\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 * 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 */\n readonly useChanges: UseChanges;\n}\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 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;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) 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 [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\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 rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\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 setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\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 new 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 This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.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 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,kBAA0B;AAC1B,mBAA0D;AAoInD,IAAM,eAAe,CAAC;AA0BtB,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,eAAW,uBAAU,MAAM,MAAM,IAAI;AAEtE,WAASA,aAAgC,gBAAoE;AAC3G,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa;AAAA,IACf;AAGA,UAAM,QAAQ,WAAW,OAAO;AAKhC,UAAM,CAAC,KAAK,MAAM,QAAI,uBAAS,UAAU;AAEzC,UAAM,iBAAa,0BAAY,YAAY;AAEzC,YAAMC,OAAM,QAAQ,MAAM,SAAS,IAAO,KAAK,EAAE,MAAM,MAAM,UAAU,IAAI;AAC3E,aA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AAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;;;ACtB1B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
package/react/index.js.map
CHANGED
@@ -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"],"sourcesContent":["import type {\n ConfigOpts,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n Database,\n MapFn,\n QueryOpts,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState } 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}\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\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<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, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\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 * 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 */\n readonly useChanges: UseChanges;\n}\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 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;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) 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 [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\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 rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\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 setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\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 new 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 This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.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 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 { Database, DocTypes } 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"],"mappings":";AAaA,SAAS,iBAAiB;AAC1B,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAoInD,IAAM,eAAe,CAAC;AA0BtB,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,WAAW,UAAU,MAAM,MAAM,IAAI;AAEtE,WAASA,aAAgC,gBAAoE;AAC3G,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa;AAAA,IACf;AAGA,UAAM,QAAQ,WAAW,OAAO;AAKhC,UAAM,CAAC,KAAK,MAAM,IAAI,SAAS,UAAU;AAEzC,UAAM,aAAa,YAAY,YAAY;AAEzC,YAAMC,OAAM,QAAQ,MAAM,SAAS,IAAO,KAAK,EAAE,MAAM,MAAM,UAAU,IAAI;AAC3E,aAAOA,IAAG;AAAA,IACZ,GAAG,CAAC,KAAK,CAAC;AAEV,UAAM,UAAyB;AAAA,MAC7B,OAAO,gBAAgB;AACrB,cAAM,MAAM,MAAM,SAAS,IAAI,eAAe,GAAG;AAEjD,YAAI,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AW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
1
|
+
{"version":3,"sources":["../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.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 } 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}\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\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<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, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\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 * 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 */\n readonly useChanges: UseChanges;\n}\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 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;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) 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 [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\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 rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\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 setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\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 new 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 This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.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 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"],"mappings":";AAaA,SAAS,iBAAiB;AAC1B,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAoInD,IAAM,eAAe,CAAC;AA0BtB,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,WAAW,UAAU,MAAM,MAAM,IAAI;AAEtE,WAASA,aAAgC,gBAAoE;AAC3G,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa;AAAA,IACf;AAGA,UAAM,QAAQ,WAAW,OAAO;AAKhC,UAAM,CAAC,KAAK,MAAM,IAAI,SAAS,UAAU;AAEzC,UAAM,aAAa,YAAY,YAAY;AAEzC,YAAMC,OAAM,QAAQ,MAAM,SAAS,IAAO,KAAK,EAAE,MAAM,MAAM,UAAU,IAAI;AAC3E,aAAOA,IAAG;AAAA,IACZ,GAAG,CAAC,KAAK,CAAC;AAEV,UAAM,UAAyB;AAAA,MAC7B,OAAO,gBAAgB;AACrB,cAAM,MAAM,MAAM,SAAS,IAAI,eAAe,GAAG;AAEjD,YAAI,CAAC,eAAe,CAAC,IAAI,IAAK,QAAO,CAAC,OAAO,EAAE,GAAG,GAAG,KAAK,IAAI,GAAG,EAAE;AACnE,eAAO;AAAA,MACT;AAAA,MACA,CAAC,GAAG;AAAA,IACN;AAEA,UAAM,YAA4B;AAAA,MAChC,OAAO,gBAAgB;AACrB,cAAM,KAAK,aAAa,OAAO;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AY,YAAY;AAC1C,YAAM,MAAM,MAAM,SAAS,QAAW,OAAO,IAAI;AACjD,gBAAU,EAAE,GAAG,KAAK,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,EAAE,KAAqB,EAAE,CAAC;AAAA,IAC1E,GAAG,CAAC,OAAO,WAAW,CAAC;AAEvB,cAAU,MAAM;AACd,kBAAY;AACZ,aAAO,SAAS,UAAU,WAAW;AAAA,IACvC,GAAG,CAAC,WAAW,CAAC;AAEhB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,UAAU,cAAAF,eAAc,aAAAF,cAAa,YAAAG,aAAY,YAAAC,YAAW;AACvE;;;AC7SA,SAAS,uBAAuB,MAA+B;AAC7D,QAAM,EAAE,aAAAC,cAAa,SAAS,IAAI,aAAa;AAC/C,EAAC,oBAAsC,WAAW;AAClD,SAAOA,aAAY,GAAG,IAAI;AAC5B;AAkCO,IAAM,cAAc;;;ACpC3B,SAAS,wBAAwB,MAAgC;AAC/D,QAAM,EAAE,cAAAC,eAAc,SAAS,IAAI,aAAa;AAChD,EAAC,qBAAwC,WAAW;AACpD,SAAOA,cAAa,GAAG,IAAI;AAC7B;AAmBO,IAAM,eAAe;;;ACzB5B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;;;ACtB1B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
@@ -3,7 +3,7 @@ import { sha256 as hasher } from "multiformats/hashes/sha2";
|
|
3
3
|
import { BlockView } from "multiformats";
|
4
4
|
import { CID } from "multiformats/cid";
|
5
5
|
import { MemoryBlockstore } from "@fireproof/vendor/@web3-storage/pail/block";
|
6
|
-
import { CRDTMeta, IndexTransactionMeta, SuperThis, bs, ensureSuperThis, rt } from "@fireproof/core";
|
6
|
+
import { CRDTMeta, CarTransaction, IndexTransactionMeta, SuperThis, bs, ensureSuperThis, rt } from "@fireproof/core";
|
7
7
|
import { simpleBlockOpts } from "../helpers.js";
|
8
8
|
|
9
9
|
class MyMemoryBlockStore extends bs.EncryptedBlockstore {
|
@@ -23,7 +23,7 @@ class MyMemoryBlockStore extends bs.EncryptedBlockstore {
|
|
23
23
|
close(): Promise<void> {
|
24
24
|
return this.loader.close();
|
25
25
|
}
|
26
|
-
readonly transactions = new Set<
|
26
|
+
readonly transactions = new Set<CarTransaction>();
|
27
27
|
// readonly lastTxMeta?: TransactionMeta;
|
28
28
|
readonly compacting: boolean = false;
|
29
29
|
|
@@ -51,7 +51,7 @@ class MyMemoryBlockStore extends bs.EncryptedBlockstore {
|
|
51
51
|
describe("basic Loader simple", function () {
|
52
52
|
let loader: bs.Loader;
|
53
53
|
let block: BlockView;
|
54
|
-
let t:
|
54
|
+
let t: CarTransaction;
|
55
55
|
const sthis = ensureSuperThis();
|
56
56
|
|
57
57
|
afterEach(async function () {
|
@@ -63,7 +63,7 @@ describe("basic Loader simple", function () {
|
|
63
63
|
const testDbName = "test-loader-commit";
|
64
64
|
await sthis.start();
|
65
65
|
const mockM = new MyMemoryBlockStore(sthis);
|
66
|
-
t = new bs.
|
66
|
+
t = new bs.CarTransactionImpl(mockM as bs.EncryptedBlockstore);
|
67
67
|
loader = new bs.Loader(sthis, {
|
68
68
|
...simpleBlockOpts(sthis, testDbName),
|
69
69
|
public: true,
|
@@ -99,7 +99,7 @@ describe("basic Loader with two commits", function () {
|
|
99
99
|
let block2: BlockView;
|
100
100
|
let block3: BlockView;
|
101
101
|
let block4: BlockView;
|
102
|
-
let t:
|
102
|
+
let t: CarTransaction;
|
103
103
|
let carCid: bs.CarGroup;
|
104
104
|
let carCid0: bs.CarGroup;
|
105
105
|
|
@@ -113,7 +113,7 @@ describe("basic Loader with two commits", function () {
|
|
113
113
|
beforeEach(async () => {
|
114
114
|
await sthis.start();
|
115
115
|
const mockM = new MyMemoryBlockStore(sthis);
|
116
|
-
t = new bs.
|
116
|
+
t = new bs.CarTransactionImpl(mockM);
|
117
117
|
loader = new bs.Loader(sthis, {
|
118
118
|
...simpleBlockOpts(sthis, "test-loader-two-commit"),
|
119
119
|
public: true,
|
@@ -1,12 +1,12 @@
|
|
1
1
|
import { CID } from "multiformats";
|
2
|
-
import { bs, ensureSuperThis, SuperThis } from "@fireproof/core";
|
2
|
+
import { BaseBlockstore, bs, CarTransaction, ensureSuperThis, SuperThis } from "@fireproof/core";
|
3
3
|
import { simpleBlockOpts } from "../helpers.js";
|
4
4
|
|
5
5
|
describe("Fresh TransactionBlockstore", function () {
|
6
|
-
let blocks:
|
6
|
+
let blocks: BaseBlockstore;
|
7
7
|
const sthis = ensureSuperThis();
|
8
8
|
beforeEach(function () {
|
9
|
-
blocks = new bs.
|
9
|
+
blocks = new bs.BaseBlockstoreImpl(simpleBlockOpts(sthis));
|
10
10
|
});
|
11
11
|
// it("should not have a name", function () {
|
12
12
|
// expect(blocks.name).toBeFalsy();
|
@@ -22,7 +22,7 @@ describe("Fresh TransactionBlockstore", function () {
|
|
22
22
|
it("should yield a transaction", async function () {
|
23
23
|
const txR = await blocks.transaction(async (tblocks) => {
|
24
24
|
expect(tblocks).toBeTruthy();
|
25
|
-
expect(tblocks instanceof bs.
|
25
|
+
expect(tblocks instanceof bs.CarTransactionImpl).toBeTruthy();
|
26
26
|
return { head: [] };
|
27
27
|
});
|
28
28
|
expect(txR).toBeTruthy();
|
@@ -55,12 +55,12 @@ describe("TransactionBlockstore with name", function () {
|
|
55
55
|
});
|
56
56
|
|
57
57
|
describe("A transaction", function () {
|
58
|
-
let tblocks:
|
58
|
+
let tblocks: CarTransaction;
|
59
59
|
let blocks: bs.EncryptedBlockstore;
|
60
60
|
const sthis = ensureSuperThis();
|
61
61
|
beforeEach(async function () {
|
62
62
|
blocks = new bs.EncryptedBlockstore(sthis, simpleBlockOpts(sthis, "test"));
|
63
|
-
tblocks = new bs.
|
63
|
+
tblocks = new bs.CarTransactionImpl(blocks);
|
64
64
|
blocks.transactions.add(tblocks);
|
65
65
|
});
|
66
66
|
it("should put and get", async function () {
|
@@ -80,7 +80,7 @@ function asUInt8Array(str: string, sthis: SuperThis) {
|
|
80
80
|
}
|
81
81
|
|
82
82
|
describe("TransactionBlockstore with a completed transaction", function () {
|
83
|
-
let blocks:
|
83
|
+
let blocks: BaseBlockstore;
|
84
84
|
let cid: CID;
|
85
85
|
let cid2: CID;
|
86
86
|
const sthis = ensureSuperThis();
|
@@ -89,7 +89,7 @@ describe("TransactionBlockstore with a completed transaction", function () {
|
|
89
89
|
cid = CID.parse("bafybeia4luuns6dgymy5kau5rm7r4qzrrzg6cglpzpogussprpy42cmcn4");
|
90
90
|
cid2 = CID.parse("bafybeibgouhn5ktecpjuovt52zamzvm4dlve5ak7x6d5smms3itkhplnhm");
|
91
91
|
|
92
|
-
blocks = new bs.
|
92
|
+
blocks = new bs.BaseBlockstoreImpl(simpleBlockOpts(sthis));
|
93
93
|
await blocks.transaction(async (tblocks) => {
|
94
94
|
await tblocks.put(cid, asUInt8Array("value", sthis));
|
95
95
|
await tblocks.put(cid, asUInt8Array("value", sthis));
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import { Database,
|
1
|
+
import { Database, Ledger, LedgerFactory, PARAM, bs, ensureSuperThis, fireproof } from "@fireproof/core";
|
2
2
|
|
3
3
|
import { fileContent } from "./cars/bafkreidxwt2nhvbl4fnqfw3ctlt6zbrir4kqwmjo5im6rf4q5si27kgo2i.js";
|
4
4
|
import { simpleCID } from "../helpers.js";
|
@@ -30,7 +30,7 @@ import { simpleCID } from "../helpers.js";
|
|
30
30
|
// }
|
31
31
|
|
32
32
|
describe("noop Gateway", function () {
|
33
|
-
let db:
|
33
|
+
let db: Ledger;
|
34
34
|
let carStore: bs.DataStore;
|
35
35
|
let metaStore: bs.MetaStore;
|
36
36
|
let fileStore: bs.DataStore;
|
@@ -46,7 +46,7 @@ describe("noop Gateway", function () {
|
|
46
46
|
await db.destroy();
|
47
47
|
});
|
48
48
|
beforeEach(async function () {
|
49
|
-
db =
|
49
|
+
db = LedgerFactory("test-gateway-" + sthis.nextId().str, {
|
50
50
|
logger: sthis.logger,
|
51
51
|
});
|
52
52
|
|
@@ -375,10 +375,10 @@ describe("noop Gateway subscribe", function () {
|
|
375
375
|
await db.destroy();
|
376
376
|
});
|
377
377
|
beforeEach(async function () {
|
378
|
-
db =
|
378
|
+
db = fireproof("test-gateway-" + sthis.nextId().str);
|
379
379
|
|
380
380
|
// Extract stores from the loader
|
381
|
-
metaStore = (await db.crdt.blockstore.loader?.metaStore()) as bs.MetaStore;
|
381
|
+
metaStore = (await db.ledger.crdt.blockstore.loader?.metaStore()) as bs.MetaStore;
|
382
382
|
|
383
383
|
metaGateway = metaStore.realGateway;
|
384
384
|
});
|
@@ -425,14 +425,14 @@ describe("Gateway", function () {
|
|
425
425
|
await db.destroy();
|
426
426
|
});
|
427
427
|
beforeEach(async function () {
|
428
|
-
db =
|
428
|
+
db = fireproof("test-gateway-" + sthis.nextId().str);
|
429
429
|
const ok = await db.put({ _id: "test", foo: "bar" });
|
430
430
|
expect(ok).toBeTruthy();
|
431
431
|
expect(ok.id).toBe("test");
|
432
432
|
|
433
433
|
// Extract stores from the loader
|
434
434
|
// carStore = (await db.blockstore.loader.carStore()) as unknown as ExtendedStore;
|
435
|
-
metaStore = (await db.crdt.blockstore.loader?.metaStore()) as bs.MetaStore;
|
435
|
+
metaStore = (await db.ledger.crdt.blockstore.loader?.metaStore()) as bs.MetaStore;
|
436
436
|
// fileStore = (await db.blockstore.loader.fileStore()) as unknown as ExtendedStore;
|
437
437
|
// walStore = (await db.blockstore.loader.WALStore()) as unknown as ExtendedStore;
|
438
438
|
|