{"version":3,"sources":["../src/error.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Registry } from './registry.mjs';\nimport {\n  StatusNameSchema,\n  httpStatusCode,\n  type StatusName,\n} from './statusTypes.mjs';\n\nexport { StatusNameSchema };\nexport type { StatusName };\n\nexport interface HttpErrorWireFormat {\n  details?: unknown;\n  message: string;\n  status: StatusName;\n}\n\n/**\n * Metadata from the HTTP response that triggered this error.\n * This is not serialized into the wire format — it's only available\n * in-process for middleware (e.g. retry) to make informed decisions.\n */\nexport interface ErrorResponseMetadata {\n  /** Provider-suggested retry delay in milliseconds (parsed from Retry-After header). */\n  retryAfterMs?: number;\n  /** Raw HTTP response headers, if available. */\n  headers?: Record<string, string>;\n}\n\n/**\n * The markers tracing stamps on an error as it passes through spans:\n * `ignoreFailedSpan` once a span has claimed to be the failure's source, and\n * `traceId` once an action has recorded the trace it failed in.\n */\nexport interface SpanFailureMarks {\n  ignoreFailedSpan?: boolean;\n  traceId?: string;\n}\n\n/**\n * Copies the span markers `source` carries onto `target` where `target` has\n * none of its own. An error thrown in place of one that already passed\n * through spans (a wrapper, or the error a wrapper stood for) keeps the\n * span that first failed as the failure's source, so an enclosing span does\n * not claim it again.\n */\nexport function inheritSpanMarks(target: object, source: unknown): void {\n  if (typeof source !== 'object' || source === null) return;\n  const from = source as SpanFailureMarks;\n  const to = target as SpanFailureMarks;\n  if (\n    from.ignoreFailedSpan !== undefined &&\n    to.ignoreFailedSpan === undefined\n  ) {\n    to.ignoreFailedSpan = from.ignoreFailedSpan;\n  }\n  if (from.traceId !== undefined && to.traceId === undefined) {\n    to.traceId = from.traceId;\n  }\n}\n\n/**\n * Base error class for Genkit errors.\n */\nexport class GenkitError extends Error {\n  source?: string;\n  status: StatusName;\n  detail?: any;\n  code: number;\n\n  /**\n   * Metadata from the HTTP response that triggered this error.\n   * Not serialized into the wire format — only available in-process\n   * for middleware (e.g. retry) to make informed decisions.\n   */\n  responseMetadata?: ErrorResponseMetadata;\n\n  // For easy printing, we wrap the error with information like the source\n  // and status, but that's redundant with JSON.\n  originalMessage: string;\n\n  /**\n   * The message safe to send to a client when `originalMessage` is not.\n   * A `GenkitError` is treated as user-facing by the HTTP handlers (see\n   * {@link getCallableJSON}), so an error that wraps arbitrary text (a tool's\n   * own exception, a provider SDK error) sets this to keep that text\n   * in-process only. Unset means `originalMessage` is safe.\n   */\n  publicMessage?: string;\n\n  constructor({\n    status,\n    message,\n    detail,\n    source,\n    responseMetadata,\n    cause,\n    publicMessage,\n  }: {\n    status: StatusName;\n    message: string;\n    detail?: any;\n    source?: string;\n    responseMetadata?: ErrorResponseMetadata;\n    /** The underlying error, exposed as the standard `Error.cause`. */\n    cause?: unknown;\n    publicMessage?: string;\n  }) {\n    super(\n      `${source ? `${source}: ` : ''}${status}: ${message}`,\n      cause === undefined ? undefined : { cause }\n    );\n    this.originalMessage = message;\n    this.source = source;\n    this.code = httpStatusCode(status);\n    this.status = status;\n    this.detail = detail;\n    this.responseMetadata = responseMetadata;\n    this.publicMessage = publicMessage;\n    this.name = 'GenkitError';\n    // An error that wraps another keeps the span markers tracing stamped on\n    // the cause, so the span that first failed stays the failure source and\n    // the wrapper does not claim it again on the way up.\n    inheritSpanMarks(this, cause);\n  }\n\n  /**\n   * Returns a JSON-serializable representation of this object.\n   */\n  public toJSON(): HttpErrorWireFormat {\n    return {\n      // This error type is used by 3P authors with the field \"detail\",\n      // but the actual Callable protocol value is \"details\"\n      ...(this.detail === undefined ? {} : { details: this.detail }),\n      status: this.status,\n      message: this.publicMessage ?? this.originalMessage,\n    };\n  }\n}\n\nexport class UnstableApiError extends GenkitError {\n  constructor(level: 'beta', message?: string) {\n    super({\n      status: 'FAILED_PRECONDITION',\n      message: `${message ? message + ' ' : ''}This API requires '${level}' stability level.\\n\\nTo use this feature, initialize Genkit using \\`import {genkit} from \"genkit/${level}\"\\`.`,\n    });\n    this.name = 'UnstableApiError';\n  }\n}\n\n/**\n * assertUnstable allows features to raise exceptions when using Genkit from *more* stable initialized instances.\n *\n * @param level The maximum stability channel allowed.\n * @param message An optional message describing which feature is not allowed.\n */\nexport function assertUnstable(\n  registry: Registry,\n  level: 'beta',\n  message?: string\n) {\n  if (level === 'beta' && registry.apiStability === 'stable') {\n    throw new UnstableApiError(level, message);\n  }\n}\n\n/**\n * Creates a new class of Error for issues to be returned to users.\n * Using this error allows a web framework handler (e.g. express, next) to know it\n * is safe to return the message in a request. Other kinds of errors will\n * result in a generic 500 message to avoid the possibility of internal\n * exceptions being leaked to attackers.\n * In JSON requests, code will be an HTTP code and error will be a response body.\n * In streaming requests, { code, message } will be passed as the error message.\n */\nexport class UserFacingError extends GenkitError {\n  constructor(status: StatusName, message: string, details?: any) {\n    super({ status, detail: details, message });\n    super.name = 'UserFacingError';\n  }\n}\n\nexport function getHttpStatus(e: any): number {\n  if (e instanceof GenkitError) {\n    return e.code;\n  }\n  return 500;\n}\n\nexport function getCallableJSON(e: any): HttpErrorWireFormat {\n  if (e instanceof GenkitError) {\n    return e.toJSON();\n  }\n  return {\n    message: 'Internal Error',\n    status: 'INTERNAL',\n  };\n}\n\n/**\n * Extracts error message from the given error object, or if input is not an error then just turn the error into a string.\n */\nexport function getErrorMessage(e: any): string {\n  if (e instanceof Error) {\n    return e.message;\n  }\n  return `${e}`;\n}\n\n/**\n * Extracts stack trace from the given error object, or if input is not an error then returns undefined.\n */\nexport function getErrorStack(e: any): string | undefined {\n  if (e instanceof Error) {\n    return e.stack;\n  }\n  return undefined;\n}\n"],"mappings":"AAiBA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAwC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