{"version":3,"file":"optimistic.mjs","sources":["../../../../../src/mutation/optimistic.ts"],"sourcesContent":["import { type Store, attach, sample } from \"effector\"\n\nimport type { ApolloClient, DocumentNode, Unmasked } from \"@apollo/client\"\nimport { Kind, OperationTypeNode } from \"graphql\"\n\nimport { storify } from \"../lib/storify\"\n\nimport type { Mutation } from \"./mutation\"\n\ninterface OptimisticOptions<Data, Variables> {\n  client?: ApolloClient<unknown> | Store<ApolloClient<unknown>>\n\n  fn: (variables: Variables) => Unmasked<Data>\n}\n\nexport function optimistic<Data, Variables>(\n  mutation: Mutation<Data, Variables>,\n  { client = mutation.meta.client, fn }: OptimisticOptions<Data, Variables>,\n) {\n  const name = `${mutation.meta.name}.optimistic`\n  const query = asQuery(mutation.meta.document)\n\n  const $client = storify(client, { name: `${name}.client`, sid: `apollo.${name}.$client` })\n\n  const updateFx = attach({\n    source: { client: $client, variables: mutation.__.$variables },\n    name: `${mutation.meta.name}.optimistic`,\n    effect({ variables, client: { cache } }, req: Promise<unknown>) {\n      const id = nextID()\n\n      cache.recordOptimisticTransaction(\n        () => cache.writeQuery({ data: fn(variables), query, variables }),\n        id,\n      )\n\n      return req.finally(() => cache.removeOptimistic(id))\n    },\n  })\n\n  sample({ clock: mutation.__.called, target: updateFx })\n}\n\nfunction asQuery(document: DocumentNode): DocumentNode {\n  return {\n    kind: Kind.DOCUMENT,\n    definitions: document.definitions.map((node) =>\n      node.kind === Kind.OPERATION_DEFINITION && node.operation !== OperationTypeNode.QUERY\n        ? { ...node, operation: OperationTypeNode.QUERY }\n        : node,\n    ),\n  }\n}\n\n// Apollo uses just a number under the hood\n// We add `effector` in front to prevent collisions\nlet optimisticID = 0\nconst nextID = () => `effector:${++optimisticID}`\n"],"names":[],"mappings":";;;AAegB,SAAA,WACd,UACA,EAAE,SAAS,SAAS,KAAK,QAAQ,MACjC;AACA,QAAM,OAAO,GAAG,SAAS,KAAK,IAAI;AAClC,QAAM,QAAQ,QAAQ,SAAS,KAAK,QAAQ;AAE5C,QAAM,UAAU,QAAQ,QAAQ,EAAE,MAAM,GAAG,IAAI,WAAW,KAAK,UAAU,IAAI,WAAA,CAAY;AAEzF,QAAM,WAAW,OAAO;AAAA,IACtB,QAAQ,EAAE,QAAQ,SAAS,WAAW,SAAS,GAAG,WAAW;AAAA,IAC7D,MAAM,GAAG,SAAS,KAAK,IAAI;AAAA,IAC3B,OAAO,EAAE,WAAW,QAAQ,EAAE,MAAM,KAAK,KAAuB;AAC9D,YAAM,KAAK,OAAO;AAEZ,YAAA;AAAA,QACJ,MAAM,MAAM,WAAW,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,WAAW;AAAA,QAChE;AAAA,MACF;AAEA,aAAO,IAAI,QAAQ,MAAM,MAAM,iBAAiB,EAAE,CAAC;AAAA,IAAA;AAAA,EACrD,CACD;AAED,SAAO,EAAE,OAAO,SAAS,GAAG,QAAQ,QAAQ,UAAU;AACxD;AAEA,SAAS,QAAQ,UAAsC;AAC9C,SAAA;AAAA,IACL,MAAM,KAAK;AAAA,IACX,aAAa,SAAS,YAAY;AAAA,MAAI,CAAC,SACrC,KAAK,SAAS,KAAK,wBAAwB,KAAK,cAAc,kBAAkB,QAC5E,EAAE,GAAG,MAAM,WAAW,kBAAkB,UACxC;AAAA,IAAA;AAAA,EAER;AACF;AAIA,IAAI,eAAe;AACnB,MAAM,SAAS,MAAM,YAAY,EAAE,YAAY;"}