{"version":3,"file":"optimistic.cjs","names":[],"sources":["../../src/query/optimistic.ts"],"sourcesContent":["/**\n * Ready-made `applyOptimistic` builders for {@link useOfflineMutation} over a\n * list-shaped query cache (`TData = T[]`). They cover the two most common\n * optimistic edits — insert-or-update and remove — so callers stop hand-writing\n * the array spread. Both compare records by an id field (`\"id\"` by default) and\n * treat the mutation variables as the record itself.\n */\n\n/**\n * Build an `applyOptimistic` that inserts the item when absent or shallow-merges\n * it into the existing entry (matched by `idField`). New items append to the end.\n *\n * @typeParam T - The list item shape.\n * @param idField - The identity field. Default `\"id\"`.\n * @returns An `(current, item) => T[]` patcher for a list cache.\n *\n * @example\n * useOfflineMutation<Note, Note[], Note>({\n *     sync, queryKey: [\"notes\"],\n *     toEntry: (n) => ({ op: \"update\", recordId: n.id, payload: n }),\n *     applyOptimistic: upsertById(),\n * });\n */\nexport function upsertById<T>(\n    idField: keyof T = \"id\" as keyof T,\n): (current: T[] | undefined, item: T) => T[] {\n    return (current = [], item) => {\n        const index = current.findIndex((entry) => entry[idField] === item[idField]);\n        if (index === -1) return [...current, item];\n        const next = current.slice();\n        next[index] = { ...current[index], ...item };\n        return next;\n    };\n}\n\n/**\n * Build an `applyOptimistic` that removes the entry matching the item's id\n * (by `idField`) from the list. For `delete` mutations, pass variables carrying\n * at least the id field.\n *\n * @typeParam T - The list item shape.\n * @param idField - The identity field. Default `\"id\"`.\n * @returns An `(current, item) => T[]` patcher for a list cache.\n *\n * @example\n * useOfflineMutation<{ id: string }, Note[], Note>({\n *     sync, queryKey: [\"notes\"],\n *     toEntry: ({ id }) => ({ op: \"delete\", recordId: id }),\n *     applyOptimistic: removeById(),\n * });\n */\nexport function removeById<T, V extends Partial<Record<keyof T, unknown>> = T>(\n    idField: keyof T = \"id\" as keyof T,\n): (current: T[] | undefined, item: V) => T[] {\n    return (current = [], item) => {\n        const targetId = (item as Record<keyof T, unknown>)[idField];\n        return current.filter((entry) => entry[idField] !== targetId);\n    };\n}\n"],"mappings":"AAuBA,SAAgB,EACZ,EAAmB,KACuB,CAC1C,OAAQ,EAAU,CAAC,EAAG,IAAS,CAC3B,IAAM,EAAQ,EAAQ,UAAW,GAAU,EAAM,KAAa,EAAK,EAAQ,EAC3E,GAAI,IAAU,GAAI,MAAO,CAAC,GAAG,EAAS,CAAI,EAC1C,IAAM,EAAO,EAAQ,MAAM,EAE3B,MADA,GAAK,GAAS,CAAE,GAAG,EAAQ,GAAQ,GAAG,CAAK,EACpC,CACX,CACJ,CAkBA,SAAgB,EACZ,EAAmB,KACuB,CAC1C,OAAQ,EAAU,CAAC,EAAG,IAAS,CAC3B,IAAM,EAAY,EAAkC,GACpD,OAAO,EAAQ,OAAQ,GAAU,EAAM,KAAa,CAAQ,CAChE,CACJ"}