{"version":3,"sources":["../src/client/CopilotRuntimeClient.ts","../package.json"],"sourcesContent":["import { Client, cacheExchange, fetchExchange } from \"@urql/core\";\nimport * as packageJson from \"../../package.json\";\nimport {\n  AvailableAgentsQuery,\n  GenerateCopilotResponseMutation,\n  GenerateCopilotResponseMutationVariables,\n  LoadAgentStateQuery,\n} from \"../graphql/@generated/graphql\";\nimport { generateCopilotResponseMutation } from \"../graphql/definitions/mutations\";\nimport { getAvailableAgentsQuery, loadAgentStateQuery } from \"../graphql/definitions/queries\";\nimport { OperationResultSource, OperationResult } from \"urql\";\nimport {\n  ResolvedCopilotKitError,\n  CopilotKitLowLevelError,\n  CopilotKitError,\n  CopilotKitVersionMismatchError,\n  getPossibleVersionMismatch,\n} from \"@copilotkit/shared\";\n\nconst createFetchFn =\n  (signal?: AbortSignal, handleGQLWarning?: (warning: string) => void) =>\n  async (...args: Parameters<typeof fetch>) => {\n    // @ts-expect-error -- since this is our own header, TS will not recognize\n    const publicApiKey = args[1]?.headers?.[\"x-copilotcloud-public-api-key\"];\n    try {\n      const result = await fetch(args[0], { ...(args[1] ?? {}), signal });\n\n      // No mismatch checking if cloud is being used\n      const mismatch = publicApiKey\n        ? null\n        : await getPossibleVersionMismatch({\n            runtimeVersion: result.headers.get(\"X-CopilotKit-Runtime-Version\")!,\n            runtimeClientGqlVersion: packageJson.version,\n          });\n      if (result.status !== 200) {\n        if (result.status >= 400 && result.status <= 500) {\n          if (mismatch) {\n            throw new CopilotKitVersionMismatchError(mismatch);\n          }\n\n          throw new ResolvedCopilotKitError({ status: result.status });\n        }\n      }\n\n      if (mismatch && handleGQLWarning) {\n        handleGQLWarning(mismatch.message);\n      }\n\n      return result;\n    } catch (error) {\n      // Let abort error pass through. It will be suppressed later\n      if (\n        (error as Error).message.includes(\"BodyStreamBuffer was aborted\") ||\n        (error as Error).message.includes(\"signal is aborted without reason\")\n      ) {\n        throw error;\n      }\n      if (error instanceof CopilotKitError) {\n        throw error;\n      }\n      throw new CopilotKitLowLevelError({ error: error as Error, url: args[0] as string });\n    }\n  };\n\nexport interface CopilotRuntimeClientOptions {\n  url: string;\n  publicApiKey?: string;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  handleGQLErrors?: (error: Error) => void;\n  handleGQLWarning?: (warning: string) => void;\n}\n\nexport class CopilotRuntimeClient {\n  client: Client;\n  public handleGQLErrors?: (error: Error) => void;\n  public handleGQLWarning?: (warning: string) => void;\n\n  constructor(options: CopilotRuntimeClientOptions) {\n    const headers: Record<string, string> = {};\n\n    this.handleGQLErrors = options.handleGQLErrors;\n    this.handleGQLWarning = options.handleGQLWarning;\n\n    if (options.headers) {\n      Object.assign(headers, options.headers);\n    }\n\n    if (options.publicApiKey) {\n      headers[\"x-copilotcloud-public-api-key\"] = options.publicApiKey;\n    }\n\n    this.client = new Client({\n      url: options.url,\n      exchanges: [cacheExchange, fetchExchange],\n      fetchOptions: {\n        headers: {\n          ...headers,\n          \"X-CopilotKit-Runtime-Client-GQL-Version\": packageJson.version,\n        },\n        ...(options.credentials ? { credentials: options.credentials } : {}),\n      },\n    });\n  }\n\n  generateCopilotResponse({\n    data,\n    properties,\n    signal,\n  }: {\n    data: GenerateCopilotResponseMutationVariables[\"data\"];\n    properties?: GenerateCopilotResponseMutationVariables[\"properties\"];\n    signal?: AbortSignal;\n  }) {\n    const fetchFn = createFetchFn(signal, this.handleGQLWarning);\n    const result = this.client.mutation<\n      GenerateCopilotResponseMutation,\n      GenerateCopilotResponseMutationVariables\n    >(generateCopilotResponseMutation, { data, properties }, { fetch: fetchFn });\n\n    return result;\n  }\n\n  public asStream<S, T>(source: OperationResultSource<OperationResult<S, { data: T }>>) {\n    const handleGQLErrors = this.handleGQLErrors;\n    return new ReadableStream<S>({\n      start(controller) {\n        source.subscribe(({ data, hasNext, error }) => {\n          if (error) {\n            if (\n              error.message.includes(\"BodyStreamBuffer was aborted\") ||\n              error.message.includes(\"signal is aborted without reason\")\n            ) {\n              // close the stream if there is no next item\n              if (!hasNext) controller.close();\n\n              //suppress this specific error\n              console.warn(\"Abort error suppressed\");\n              return;\n            }\n            controller.error(error);\n            if (handleGQLErrors) {\n              handleGQLErrors(error);\n            }\n          } else {\n            controller.enqueue(data);\n            if (!hasNext) {\n              controller.close();\n            }\n          }\n        });\n      },\n    });\n  }\n\n  availableAgents() {\n    const fetchFn = createFetchFn();\n    return this.client.query<AvailableAgentsQuery>(getAvailableAgentsQuery, {}, { fetch: fetchFn });\n  }\n\n  loadAgentState(data: { threadId: string; agentName: string }) {\n    const fetchFn = createFetchFn();\n    return this.client.query<LoadAgentStateQuery>(\n      loadAgentStateQuery,\n      { data },\n      { fetch: fetchFn },\n    );\n  }\n\n  static removeGraphQLTypename(data: any) {\n    if (Array.isArray(data)) {\n      data.forEach((item) => CopilotRuntimeClient.removeGraphQLTypename(item));\n    } else if (typeof data === \"object\" && data !== null) {\n      delete data.__typename;\n      Object.keys(data).forEach((key) => {\n        if (typeof data[key] === \"object\" && data[key] !== null) {\n          CopilotRuntimeClient.removeGraphQLTypename(data[key]);\n        }\n      });\n    }\n    return data;\n  }\n}\n","{\n  \"name\": \"@copilotkit/runtime-client-gql\",\n  \"private\": false,\n  \"homepage\": \"https://github.com/CopilotKit/CopilotKit\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/CopilotKit/CopilotKit.git\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"version\": \"1.8.4\",\n  \"sideEffects\": false,\n  \"main\": \"./dist/index.js\",\n  \"module\": \"./dist/index.mjs\",\n  \"exports\": {\n    \".\": {\n      \"import\": \"./dist/index.mjs\",\n      \"require\": \"./dist/index.js\",\n      \"types\": \"./dist/index.d.ts\"\n    }\n  },\n  \"types\": \"./dist/index.d.ts\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"build\": \"pnpm run graphql-codegen && tsup --clean\",\n    \"dev\": \"concurrently \\\"pnpm run graphql-codegen:watch\\\" \\\"tsup --watch --no-splitting\\\"\",\n    \"test\": \"jest --passWithNoTests\",\n    \"check-types\": \"tsc --noEmit\",\n    \"clean\": \"rm -rf .turbo && rm -rf node_modules && rm -rf ./src/graphql/@generated && rm -rf dist && rm -rf .next\",\n    \"graphql-codegen\": \"graphql-codegen -c codegen.ts\",\n    \"graphql-codegen:watch\": \"graphql-codegen -c codegen.ts --watch\",\n    \"link:global\": \"pnpm link --global\",\n    \"unlink:global\": \"pnpm unlink --global\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^18 || ^19 || ^19.0.0-rc\"\n  },\n  \"devDependencies\": {\n    \"@graphql-codegen/cli\": \"^5.0.2\",\n    \"@graphql-codegen/client-preset\": \"^4.2.6\",\n    \"@graphql-codegen/introspection\": \"^4.0.3\",\n    \"@graphql-codegen/typescript\": \"^4.0.7\",\n    \"@graphql-codegen/typescript-operations\": \"^4.2.1\",\n    \"@graphql-codegen/typescript-urql\": \"^4.0.0\",\n    \"@graphql-codegen/urql-introspection\": \"^3.0.0\",\n    \"@graphql-typed-document-node/core\": \"^3.2.0\",\n    \"@parcel/watcher\": \"^2.4.1\",\n    \"@types/node\": \"^20.12.12\",\n    \"concurrently\": \"^8.2.2\",\n    \"esbuild\": \"^0.23.0\",\n    \"jest\": \"^29.6.4\",\n    \"ts-jest\": \"^29.1.1\",\n    \"ts-node\": \"^10.9.2\",\n    \"tsup\": \"^6.7.0\",\n    \"typescript\": \"^5.4.5\",\n    \"@copilotkit/runtime\": \"workspace:*\",\n    \"graphql\": \"^16.8.1\"\n  },\n  \"dependencies\": {\n    \"@copilotkit/shared\": \"workspace:*\",\n    \"@urql/core\": \"^5.0.3\",\n    \"untruncate-json\": \"^0.0.1\",\n    \"urql\": \"^4.1.0\"\n  },\n  \"keywords\": [\n    \"copilotkit\",\n    \"copilot\",\n    \"react\",\n    \"nextjs\",\n    \"nodejs\",\n    \"ai\",\n    \"assistant\",\n    \"javascript\",\n    \"automation\",\n    \"textarea\"\n  ]\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,Q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