@sisense/sdk-ai-core 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +35 -0
- package/README.md +1 -22
- package/dist/engines/chart-builder/chart-builder-engine.d.ts.map +1 -1
- package/dist/engines/chart-builder/create-chart/create-chart.d.ts.map +1 -1
- package/dist/engines/chart-builder/create-chart/generate-chart-recommendations.d.ts +2 -1
- package/dist/engines/chart-builder/create-chart/generate-chart-recommendations.d.ts.map +1 -1
- package/dist/engines/chart-builder/create-chart/generate-chart-table.d.ts +2 -1
- package/dist/engines/chart-builder/create-chart/generate-chart-table.d.ts.map +1 -1
- package/dist/engines/chart-builder/types.d.ts +4 -0
- package/dist/engines/chart-builder/types.d.ts.map +1 -1
- package/dist/engines/data-source-fields/data-source-fields-engine.d.ts.map +1 -1
- package/dist/engines/data-source-fields/types.d.ts +2 -0
- package/dist/engines/data-source-fields/types.d.ts.map +1 -1
- package/dist/engines/data-sources/types.d.ts +2 -0
- package/dist/engines/data-sources/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1524 -1360
- package/dist/index.js.map +1 -1
- package/dist/services/dashboards/dashboards-service.d.ts +3 -2
- package/dist/services/dashboards/dashboards-service.d.ts.map +1 -1
- package/dist/services/dashboards/fusion-dashboards-service.d.ts +15 -14
- package/dist/services/dashboards/fusion-dashboards-service.d.ts.map +1 -1
- package/dist/services/data-models/data-models-service.d.ts +2 -1
- package/dist/services/data-models/data-models-service.d.ts.map +1 -1
- package/dist/services/data-sources/data-sources-service.d.ts +6 -8
- package/dist/services/data-sources/data-sources-service.d.ts.map +1 -1
- package/dist/services/nlq/nlq-service.d.ts +6 -5
- package/dist/services/nlq/nlq-service.d.ts.map +1 -1
- package/dist/utils/http-client.d.ts.map +1 -1
- package/dist/utils/user-action-tracking.d.ts +33 -0
- package/dist/utils/user-action-tracking.d.ts.map +1 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../node_modules/zod-to-json-schema/dist/esm/Options.js","../node_modules/zod-to-json-schema/dist/esm/Refs.js","../node_modules/zod-to-json-schema/dist/esm/errorMessages.js","../node_modules/zod-to-json-schema/dist/esm/getRelativePath.js","../node_modules/zod/v3/types.js","../node_modules/zod-to-json-schema/dist/esm/parsers/any.js","../node_modules/zod-to-json-schema/dist/esm/parsers/array.js","../node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js","../node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js","../node_modules/zod-to-json-schema/dist/esm/parsers/branded.js","../node_modules/zod-to-json-schema/dist/esm/parsers/catch.js","../node_modules/zod-to-json-schema/dist/esm/parsers/date.js","../node_modules/zod-to-json-schema/dist/esm/parsers/default.js","../node_modules/zod-to-json-schema/dist/esm/parsers/effects.js","../node_modules/zod-to-json-schema/dist/esm/parsers/enum.js","../node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js","../node_modules/zod-to-json-schema/dist/esm/parsers/literal.js","../node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../node_modules/zod-to-json-schema/dist/esm/parsers/record.js","../node_modules/zod-to-json-schema/dist/esm/parsers/map.js","../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js","../node_modules/zod-to-json-schema/dist/esm/parsers/never.js","../node_modules/zod-to-json-schema/dist/esm/parsers/null.js","../node_modules/zod-to-json-schema/dist/esm/parsers/union.js","../node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js","../node_modules/zod-to-json-schema/dist/esm/parsers/number.js","../node_modules/zod-to-json-schema/dist/esm/parsers/object.js","../node_modules/zod-to-json-schema/dist/esm/parsers/optional.js","../node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js","../node_modules/zod-to-json-schema/dist/esm/parsers/promise.js","../node_modules/zod-to-json-schema/dist/esm/parsers/set.js","../node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js","../node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js","../node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js","../node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js","../node_modules/zod-to-json-schema/dist/esm/selectParser.js","../node_modules/zod-to-json-schema/dist/esm/parseDef.js","../node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js","../src/utils/zod-utils.ts","../src/engines/chart-builder/types.ts","../node_modules/nanoid/index.browser.js","../src/utils/id-utils.ts","../node_modules/openai/lib/parser.mjs","../node_modules/openai/_vendor/zod-to-json-schema/Options.mjs","../node_modules/openai/_vendor/zod-to-json-schema/util.mjs","../node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs","../node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs","../node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs","../node_modules/openai/helpers/zod.mjs","../src/utils/utils.ts","../src/utils/proxy-utils.ts","../src/utils/http-client.ts","../src/utils/openai-client.ts","../src/singleton-clients.ts","../src/utils/chat-completion-utils.ts","../src/engines/chart-builder/create-chart/generate-chart-recommendations.ts","../src/services/nlq/nlq-service.ts","../src/engines/chart-builder/create-chart/generate-chart-table.ts","../src/engines/chart-builder/create-chart/create-chart.ts","../src/engines/chart-builder/update-chart/update-chart-title.ts","../src/engines/chart-builder/update-chart/update-chart-type.ts","../src/engines/chart-builder/update-chart/chart-options-schemas.ts","../src/engines/chart-builder/update-chart/update-chart-data-options.ts","../node_modules/deepmerge/dist/cjs.js","../src/engines/chart-builder/update-chart/update-chart-style-options.ts","../src/constants.ts","../src/engines/chart-builder/chart-builder-service.ts","../src/engines/chart-builder/chart-builder-engine.ts","../src/services/data-models/data-models-service.ts","../src/services/data-sources/data-sources-service.ts","../src/engines/data-sources/data-sources-engine.ts","../src/engines/data-sources/types.ts","../src/engines/data-source-fields/data-source-fields-engine.ts","../src/engines/data-source-fields/types.ts","../src/services/dashboards/fusion-dashboards-service.ts","../node_modules/fast-deep-equal/index.js","../src/services/dashboards/dashboards-service.ts","../src/services/data-models/ecm-service.ts","../src/services/globals/globals-service.ts","../src/services/llm/llm-settings-service.ts"],"sourcesContent":["export const ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nexport const jsonDescription = (jsonSchema, def) => {\n if (def.description) {\n try {\n return {\n ...jsonSchema,\n ...JSON.parse(def.description),\n };\n }\n catch { }\n }\n return jsonSchema;\n};\nexport const defaultOptions = {\n name: undefined,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n target: \"jsonSchema7\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\",\n openAiAnyTypeName: \"OpenAiAnyType\"\n};\nexport const getDefaultOptions = (options) => (typeof options === \"string\"\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n });\n","import { getDefaultOptions } from \"./Options.js\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n flags: { hasReferencedOpenAiAnyType: false },\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n","export const getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]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(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { getRelativePath } from \"../getRelativePath.js\";\nexport function parseAnyDef(refs) {\n if (refs.target !== \"openAi\") {\n return {};\n }\n const anyDefinitionPath = [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ];\n refs.flags.hasReferencedOpenAiAnyType = true;\n return {\n $ref: refs.$refStrategy === \"relative\"\n ? getRelativePath(anyDefinitionPath, refs.currentPath)\n : anyDefinitionPath.join(\"/\"),\n };\n}\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: \"array\",\n };\n if (def.type?._def &&\n def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, \"minItems\", def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, \"maxItems\", def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, \"minItems\", def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, \"maxItems\", def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: \"integer\",\n format: \"int64\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","export function parseBooleanDef() {\n return {\n type: \"boolean\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\",\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\",\n };\n case \"integer\":\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\",\n };\n if (refs.target === \"openApi3\") {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minimum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maximum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\"\n ? parseDef(_def.schema._def, refs)\n : parseAnyDef(refs);\n}\n","export function parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nconst isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\")\n return false;\n return \"allOf\" in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === \"jsonSchema2019-09\"\n ? { unevaluatedProperties: false }\n : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema &&\n schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length\n ? {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" &&\n parsedType !== \"number\" &&\n parsedType !== \"boolean\" &&\n parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\",\n };\n }\n if (refs.target === \"openApi3\") {\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value,\n };\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n","import { ZodFirstPartyTypeKind, } from \"zod/v3\";\nimport { parseDef } from \"../parseDef.js\";\nimport { parseStringDef } from \"./string.js\";\nimport { parseBrandedDef } from \"./branded.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === \"openAi\") {\n console.warn(\"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.\");\n }\n if (refs.target === \"openApi3\" &&\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: \"object\",\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", key],\n }) ?? parseAnyDef(refs),\n }), {}),\n additionalProperties: refs.rejectedAdditionalProperties,\n };\n }\n const schema = {\n type: \"object\",\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n }) ?? refs.allowedAdditionalProperties,\n };\n if (refs.target === \"openApi3\") {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.type._def.checks?.length) {\n const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseRecordDef } from \"./record.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"],\n }) || parseAnyDef(refs);\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"],\n }) || parseAnyDef(refs);\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1\n ? parsedTypes[0] === \"string\"\n ? \"string\"\n : \"number\"\n : [\"string\", \"number\"],\n enum: actualValues,\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseNeverDef(refs) {\n return refs.target === \"openAi\"\n ? undefined\n : {\n not: parseAnyDef({\n ...refs,\n currentPath: [...refs.currentPath, \"not\"],\n }),\n };\n}\n","export function parseNullDef(refs) {\n return refs.target === \"openApi3\"\n ? {\n enum: [\"null\"],\n nullable: true,\n }\n : {\n type: \"null\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\",\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === \"openApi3\")\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null)\n return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce((acc, x) => [\n ...acc,\n ...x._def.values.filter((x) => !acc.includes(x)),\n ], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`],\n }))\n .filter((x) => !!x &&\n (!refs.strictUnions ||\n (typeof x === \"object\" && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n","import { parseDef } from \"../parseDef.js\";\nimport { primitiveMappings } from \"./union.js\";\nexport function parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === \"openApi3\") {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\",\n ],\n };\n }\n if (refs.target === \"openApi3\") {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && \"$ref\" in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"],\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n","import { addErrorMessage, setResponseValueAndErrors, } from \"../errorMessages.js\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: \"number\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n addErrorMessage(res, \"type\", check.message, refs);\n break;\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseObjectDef(def, refs) {\n const forceOptionalIntoNullable = refs.target === \"openAi\";\n const result = {\n type: \"object\",\n properties: {},\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === undefined || propDef._def === undefined) {\n continue;\n }\n let propOptional = safeIsOptional(propDef);\n if (propOptional && forceOptionalIntoNullable) {\n if (propDef._def.typeName === \"ZodOptional\") {\n propDef = propDef._def.innerType;\n }\n if (!propDef.isNullable()) {\n propDef = propDef.nullable();\n }\n propOptional = false;\n }\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName],\n });\n if (parsedDef === undefined) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== undefined) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\"\n ? refs.allowedAdditionalProperties\n : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n }\n catch {\n return true;\n }\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"],\n });\n return innerSchema\n ? {\n anyOf: [\n {\n not: parseAnyDef(refs),\n },\n innerSchema,\n ],\n }\n : parseAnyDef(refs);\n};\n","import { parseDef } from \"../parseDef.js\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, \"minItems\", def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, \"maxItems\", def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"],\n }),\n };\n }\n else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUndefinedDef(refs) {\n return {\n not: parseAnyDef(refs),\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUnknownDef(refs) {\n return parseAnyDef(refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseStringDef } from \"./parsers/string.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnionDef } from \"./parsers/union.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nexport const selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef(refs);\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef(refs);\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef(refs);\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef(refs);\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\n","import { ignoreOverride } from \"./Options.js\";\nimport { selectParser } from \"./selectParser.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n const jsonSchema = typeof jsonSchemaOrGetter === \"function\"\n ? parseDef(jsonSchemaOrGetter(), refs)\n : jsonSchemaOrGetter;\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n newItem.jsonSchema = jsonSchema;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n return parseAnyDef(refs);\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef(refs) : undefined;\n }\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n","import { parseDef } from \"./parseDef.js\";\nimport { getRefs } from \"./Refs.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions\n ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n ...acc,\n [name]: parseDef(schema._def, {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, true) ?? parseAnyDef(refs),\n }), {})\n : undefined;\n const name = typeof options === \"string\"\n ? options\n : options?.nameStrategy === \"title\"\n ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, false) ?? parseAnyDef(refs);\n const title = typeof options === \"object\" &&\n options.name !== undefined &&\n options.nameStrategy === \"title\"\n ? options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n if (refs.flags.hasReferencedOpenAiAnyType) {\n if (!definitions) {\n definitions = {};\n }\n if (!definitions[refs.openAiAnyTypeName]) {\n definitions[refs.openAiAnyTypeName] = {\n // Skipping \"object\" as no properties can be defined and additionalProperties must be \"false\"\n type: [\"string\", \"number\", \"integer\", \"boolean\", \"array\", \"null\"],\n items: {\n $ref: refs.$refStrategy === \"relative\"\n ? \"1\"\n : [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ].join(\"/\"),\n },\n };\n }\n }\n const combined = name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === \"relative\" ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === \"jsonSchema7\") {\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (refs.target === \"jsonSchema2019-09\" || refs.target === \"openAi\") {\n combined.$schema = \"https://json-schema.org/draft/2019-09/schema#\";\n }\n if (refs.target === \"openAi\" &&\n (\"anyOf\" in combined ||\n \"oneOf\" in combined ||\n \"allOf\" in combined ||\n (\"type\" in combined && Array.isArray(combined.type)))) {\n console.warn(\"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.\");\n }\n return combined;\n};\nexport { zodToJsonSchema };\n","import { z } from 'zod';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { RunnableToolFunctionWithParse } from 'openai/lib/RunnableFunction';\nimport { JSONSchema } from 'openai/lib/jsonschema';\n\nconst indent = (n: number) => ' '.repeat(n);\n\n/**\n * Parse error from various types\n */\nexport const parseError = (error: Error | string | object) => {\n\tif (error instanceof Error) {\n\t\ttry {\n\t\t\treturn JSON.parse(error.message);\n\t\t} catch (e) {\n\t\t\treturn error.message;\n\t\t}\n\t}\n\tif (typeof error === 'string') {\n\t\treturn error;\n\t}\n\treturn error;\n};\n\n/**\n * Check if a schema or its descendants contain any properties from the keep list.\n * Used to determine if a container (object/array) should be kept.\n */\nconst hasKeptProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToKeep: string[],\n): boolean => {\n\t// Unwrap optionals and nullables\n\tlet unwrapped = schema;\n\twhile (\n\t\tunwrapped instanceof z.ZodOptional ||\n\t\tunwrapped instanceof z.ZodNullable\n\t) {\n\t\tunwrapped = unwrapped.unwrap();\n\t}\n\n\t// Check arrays - recurse into element type\n\tif (unwrapped instanceof z.ZodArray) {\n\t\treturn hasKeptProperties(unwrapped.element, propertiesToKeep);\n\t}\n\n\t// Check unions - any option has kept properties\n\tif (unwrapped instanceof z.ZodUnion) {\n\t\treturn unwrapped.options.some((opt: z.ZodTypeAny) =>\n\t\t\thasKeptProperties(opt, propertiesToKeep),\n\t\t);\n\t}\n\n\t// Check objects - any property name matches or descendants match\n\tif (unwrapped instanceof z.ZodObject) {\n\t\tfor (const [key, value] of Object.entries(unwrapped.shape)) {\n\t\t\t// If property name is in keep list, we found one\n\t\t\tif (propertiesToKeep.includes(key)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t// Otherwise check if this property's descendants contain kept properties\n\t\t\tif (hasKeptProperties(value as z.ZodTypeAny, propertiesToKeep)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n};\n\n/**\n * Internal generic function to process schema properties with include or exclude mode.\n * This is the shared implementation for both filterSchemaProperties and excludeSchemaProperties.\n *\n * @param schema - The Zod schema to process\n * @param propertyNames - Array of property names to include or exclude\n * @param mode - 'include' to keep only specified properties, 'exclude' to remove them\n * @returns A new processed Zod schema\n */\nconst processSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertyNames: string[],\n\tmode: 'include' | 'exclude',\n): z.ZodTypeAny => {\n\t// Handle optionals - recurse and rewrap\n\tif (schema instanceof z.ZodOptional) {\n\t\treturn z.ZodOptional.create(\n\t\t\tprocessSchemaProperties(schema.unwrap(), propertyNames, mode),\n\t\t);\n\t}\n\n\t// Handle nullables - recurse and rewrap\n\tif (schema instanceof z.ZodNullable) {\n\t\treturn z.ZodNullable.create(\n\t\t\tprocessSchemaProperties(schema.unwrap(), propertyNames, mode),\n\t\t);\n\t}\n\n\t// Handle arrays - recurse into element type\n\tif (schema instanceof z.ZodArray) {\n\t\tconst processedElement = processSchemaProperties(\n\t\t\tschema.element,\n\t\t\tpropertyNames,\n\t\t\tmode,\n\t\t);\n\t\treturn z.ZodArray.create(processedElement, schema._def);\n\t}\n\n\t// Handle unions - recurse into each option\n\tif (schema instanceof z.ZodUnion) {\n\t\tconst processedOptions = schema.options.map((opt: z.ZodTypeAny) =>\n\t\t\tprocessSchemaProperties(opt, propertyNames, mode),\n\t\t);\n\t\treturn z.ZodUnion.create(processedOptions);\n\t}\n\n\t// Handle objects - mode-specific filtering\n\tif (schema instanceof z.ZodObject) {\n\t\tconst filteredEntries: [string, z.ZodTypeAny][] = [];\n\n\t\tfor (const [key, value] of Object.entries(schema.shape)) {\n\t\t\tif (mode === 'include') {\n\t\t\t\t// INCLUDE mode: keep property if in list OR if it leads to properties in list\n\t\t\t\tif (propertyNames.includes(key)) {\n\t\t\t\t\t// Keep property entirely with all descendants\n\t\t\t\t\tfilteredEntries.push([key, value as z.ZodTypeAny]);\n\t\t\t\t} else if (\n\t\t\t\t\thasKeptProperties(value as z.ZodTypeAny, propertyNames)\n\t\t\t\t) {\n\t\t\t\t\t// Property leads to kept properties - keep and recurse\n\t\t\t\t\tconst processedValue = processSchemaProperties(\n\t\t\t\t\t\tvalue as z.ZodTypeAny,\n\t\t\t\t\t\tpropertyNames,\n\t\t\t\t\t\tmode,\n\t\t\t\t\t);\n\t\t\t\t\tfilteredEntries.push([key, processedValue]);\n\t\t\t\t}\n\t\t\t\t// Otherwise, property is removed (not added to filteredEntries)\n\t\t\t} else {\n\t\t\t\t// EXCLUDE mode: remove property if in list, otherwise keep and recurse\n\t\t\t\tif (propertyNames.includes(key)) {\n\t\t\t\t\t// Property is in exclude list - remove entirely (don't add to filteredEntries)\n\t\t\t\t} else {\n\t\t\t\t\t// Property not in exclude list - keep and recurse to handle nested exclusions\n\t\t\t\t\tconst processedValue = processSchemaProperties(\n\t\t\t\t\t\tvalue as z.ZodTypeAny,\n\t\t\t\t\t\tpropertyNames,\n\t\t\t\t\t\tmode,\n\t\t\t\t\t);\n\t\t\t\t\tfilteredEntries.push([key, processedValue]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst filteredShape = Object.fromEntries(\n\t\t\tfilteredEntries,\n\t\t) as z.ZodRawShape;\n\t\treturn z.ZodObject.create(filteredShape, schema._def);\n\t}\n\n\t// For all other types (primitives, enums, literals, etc.), return as-is\n\treturn schema;\n};\n\n/**\n * Filter Zod schema properties using path-based filtering.\n * Keeps properties in the keep list, all their descendants, and the path to reach them.\n *\n * Algorithm:\n * - If property name is in keep list → keep it entirely (with all descendants)\n * - If property is a container → check if it contains kept properties\n * - If yes → keep container and recurse\n * - If no → remove it\n *\n * @param schema - The Zod schema to filter\n * @param propertiesToKeep - Array of property names to keep (with all their descendants)\n * @returns A new filtered Zod schema\n */\nexport const filterSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToKeep: string[],\n): z.ZodTypeAny => {\n\treturn processSchemaProperties(schema, propertiesToKeep, 'include');\n};\n\n/**\n * Exclude specified properties from a Zod schema.\n * Removes properties in the exclude list and all their descendants.\n *\n * Algorithm:\n * - If property name is in exclude list → remove entirely (with all descendants)\n * - Otherwise → keep and recurse to handle nested exclusions\n *\n * @param schema - The Zod schema to process\n * @param propertiesToExclude - Array of property names to remove (with all their descendants)\n * @returns A new filtered Zod schema\n */\nexport const excludeSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToExclude: string[],\n): z.ZodTypeAny => {\n\treturn processSchemaProperties(schema, propertiesToExclude, 'exclude');\n};\n\n/**\n * Convert a Zod schema to a readable type string representation\n */\nexport const zodToReadableType = (\n\tschema: z.ZodTypeAny,\n\tdepth = 0,\n\tpropName?: string,\n\tisOptional?: boolean,\n): string => {\n\t// Optionals\n\tif (schema instanceof z.ZodOptional) {\n\t\treturn zodToReadableType(schema.unwrap(), depth, propName, true);\n\t}\n\t// Nullables\n\tif (schema instanceof z.ZodNullable) {\n\t\treturn (\n\t\t\tzodToReadableType(schema.unwrap(), depth, propName, isOptional) +\n\t\t\t' | null'\n\t\t);\n\t}\n\t// Array\n\tif (schema instanceof z.ZodArray) {\n\t\tconst inner = zodToReadableType(schema.element, depth);\n\t\treturn `Array<${inner}>${\n\t\t\tschema.description ? ` - ${schema.description}` : ''\n\t\t}`;\n\t}\n\t// Object: print each property on its own line, with descriptions\n\tif (schema instanceof z.ZodObject) {\n\t\tconst props = Object.entries(schema.shape)\n\t\t\t.map(\n\t\t\t\t([k, v]: [string, any]) =>\n\t\t\t\t\t`${indent(depth + 1)}${k}${\n\t\t\t\t\t\tv.isOptional() ? '?' : ''\n\t\t\t\t\t}: ${zodToReadableType(v, depth + 1, k, v.isOptional())}${\n\t\t\t\t\t\tv.description ? ` - ${v.description}` : ''\n\t\t\t\t\t}`,\n\t\t\t)\n\t\t\t.join(',\\n');\n\t\treturn (\n\t\t\t`{\\n${props}\\n${indent(depth)}}` +\n\t\t\t(schema.description ? ` - ${schema.description}` : '')\n\t\t);\n\t}\n\t// Enum\n\tif (schema instanceof z.ZodEnum) {\n\t\tconst opts = schema.options.map((o: string) => `\"${o}\"`).join(' | ');\n\t\treturn opts + (schema.description ? ` - ${schema.description}` : '');\n\t}\n\t// Union\n\tif (schema instanceof z.ZodUnion) {\n\t\treturn schema.options\n\t\t\t.map((opt: z.ZodTypeAny) => zodToReadableType(opt, depth))\n\t\t\t.join(' | ');\n\t}\n\t// Literal\n\tif (schema instanceof z.ZodLiteral) return JSON.stringify(schema.value);\n\t// String, Number, Boolean\n\tif (schema instanceof z.ZodString) return 'string';\n\tif (schema instanceof z.ZodNumber) return 'number';\n\tif (schema instanceof z.ZodBoolean) return 'boolean';\n\t// Fallback\n\treturn 'any';\n};\n\n/**\n * Create a decoupled zodFunction that wraps Zod schemas for OpenAI tools.\n *\n * This is a pure function that does NOT depend on stores or session management.\n * It only wraps the schema and delegates to the provided function with a generic context.\n *\n * @param config - Configuration for the tool\n * @param config.schema - The Zod schema for parameters\n * @param config.name - The function name\n * @param config.description - The function description\n * @param config.function - The function to execute (receives args and generic context)\n * @param config.strict - Whether to use strict mode\n * @returns A runnable tool function for OpenAI\n */\nexport function zodFunction<T extends object, TContext = any>({\n\tfunction: fn,\n\tschema,\n\tdescription = '',\n\tname,\n\tstrict = false,\n}: {\n\tfunction: (args: T, context: TContext) => Promise<object>;\n\tschema: z.ZodSchema<T>;\n\tdescription?: string;\n\tname?: string;\n\tstrict?: boolean;\n}): RunnableToolFunctionWithParse<T> {\n\treturn {\n\t\ttype: 'function',\n\t\tfunction: {\n\t\t\tfunction: async (args: T, context: any) => {\n\t\t\t\treturn fn(args, context as TContext);\n\t\t\t},\n\t\t\tname: name ?? (fn as any).name,\n\t\t\tdescription: description,\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\tparameters: zodToJsonSchema(schema as any) as JSONSchema,\n\t\t\tstrict,\n\t\t\tparse(input: string): T {\n\t\t\t\tconst obj = JSON.parse(input);\n\t\t\t\treturn schema.parse(obj);\n\t\t\t},\n\t\t},\n\t};\n}\n","import { CalculatedMeasureColumn, MeasureColumn } from '@sisense/sdk-data';\nimport {\n\tChartType,\n\tChartWidgetProps,\n\tStyledColumn,\n\tStyledMeasureColumn,\n\tWithCommonWidgetProps,\n} from '@sisense/sdk-ui';\nimport { z } from 'zod';\nimport { NlqResponseData } from '@sisense/sdk-ui/ai';\n\n// Simple artifact reference type (no dependency on assistant types)\nexport type ArtifactReference = {\n\tartifactId?: string;\n};\n\n// temp solution until a new NLQ tool is implemented\nexport type ExtendedChartWidgetProps = WithCommonWidgetProps<\n\tChartWidgetProps,\n\t'chart'\n> &\n\tArtifactReference & {\n\t\t/**\n\t\t * data columns used to generate chart recommendations\n\t\t */\n\t\tdataColumns?: ColumnType[];\n\t\t/**\n\t\t * nlq result used to generate chart insights\n\t\t */\n\t\tnlqResponse?: NlqResponseData;\n\t};\n\nexport type NullableChartType = ChartType | null | undefined;\n\n/**\n * Base chart summary for LLM consumption and asset extraction\n */\nexport type BaseChartSummary = {\n\t/** Human-readable title of the chart */\n\ttitle?: string;\n\t/** Name of the data source used for the chart */\n\tdataSourceTitle: string;\n\t/** Type of chart (line, bar, pie, etc.) */\n\tchartType?: ChartType;\n\t/** Summary of applied filters */\n\tfilters: string;\n\t/** Summary of data configuration options */\n\tdataOptions: string;\n\t/** Summary of styling and visual options */\n\tstyleOptions: string;\n};\n\n/**\n * Summary of a chart for LLM consumption and asset extraction\n */\nexport interface ChartSummary {\n\t/** Status message indicating success or failure */\n\tmessage: string;\n\t/** Date and time ISO string of when the chart was created */\n\tcreatedAt: string;\n\t/** Unique identifier for the chart (typically the tool call ID) */\n\tchartId: string;\n\t/** Chart details, undefined if chart creation failed */\n\tchart?: BaseChartSummary;\n\t/** Whether this chart creation resulted in an error */\n\tisError?: boolean;\n}\n\nexport type ColumnType =\n\t| StyledColumn\n\t| StyledMeasureColumn\n\t| Column\n\t| MeasureColumn\n\t| CalculatedMeasureColumn;\n\nexport interface Column {\n\tid?: number;\n\tname: string;\n\ttype?: string;\n}\n\nconst cartesianChartType = z.enum(['bar', 'column', 'area', 'line', 'polar']);\n\nconst categoricalChartType = z.enum(['pie', 'funnel', 'treemap', 'sunburst']);\n\nconst otherChartType = z.enum([\n\t'scatter',\n\t'table',\n\t'indicator',\n\t'boxplot',\n\t'areamap',\n\t'scattermap',\n\t'arearange',\n]);\n\nexport const chartType = z.enum([\n\t...cartesianChartType.options,\n\t...categoricalChartType.options,\n\t...otherChartType.options,\n]);\n\nconst cartesianChartSchema = z\n\t.object({\n\t\ttype: cartesianChartType,\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tbreakBy: z.array(z.number()),\n\t})\n\t.strict();\n\nconst categoricalChartSchema = z\n\t.object({\n\t\ttype: categoricalChartType,\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t})\n\t.strict();\n\nconst scatterChartSchema = z\n\t.object({\n\t\ttype: z.literal('scatter'),\n\t\tx: z.array(z.number()),\n\t\ty: z.array(z.number()),\n\t\tbreakByPoint: z.array(z.number()),\n\t\tbreakByColor: z.array(z.number()),\n\t\tsize: z.array(z.number()),\n\t\t// showLegend: z.boolean(),\n\t})\n\t.strict();\n\nconst tableChartSchema = z\n\t.object({\n\t\ttype: z.literal('table'),\n\t\tcolumns: z.array(z.number()),\n\t\tpagination: z.boolean(),\n\t\trowsPerPage: z.number(),\n\t})\n\t.strict();\n\nconst rangeChartSchema = z\n\t.object({\n\t\ttype: z.literal('range'),\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tbreakBy: z.array(z.number()),\n\t})\n\t.strict();\n\nconst indicatorChartSchema = z\n\t.object({\n\t\ttype: z.literal('indicator'),\n\t\tvalue: z.array(z.number()),\n\t\tsecondary: z.array(z.number()),\n\t\tmin: z.array(z.number()),\n\t\tmax: z.array(z.number()),\n\t})\n\t.strict();\n\nconst boxplotChartSchema = z\n\t.object({\n\t\ttype: z.literal('boxplot'),\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tboxType: z.enum(['iqr', 'extremums', 'standardDeviation']),\n\t\toutliersEnabled: z.boolean(),\n\t})\n\t.strict();\n\nconst areamapChartSchema = z\n\t.object({\n\t\ttype: z.literal('areamap'),\n\t\tgeo: z.array(z.number()),\n\t\tcolor: z.array(z.number()),\n\t})\n\t.strict();\n\nconst scattermapChartSchema = z\n\t.object({\n\t\ttype: z.literal('scattermap'),\n\t\tgeo: z.array(z.number()),\n\t\tsize: z.array(z.number()),\n\t\tcolorBy: z.array(z.number()),\n\t\tdetails: z.array(z.number()),\n\t\tlocationLevel: z.enum(['auto', 'country', 'state', 'city']),\n\t})\n\t.strict();\n\nexport const axesMapping = z.discriminatedUnion('type', [\n\tcartesianChartSchema,\n\tcategoricalChartSchema,\n\tscatterChartSchema,\n\ttableChartSchema,\n\trangeChartSchema,\n\tindicatorChartSchema,\n\tboxplotChartSchema,\n\tareamapChartSchema,\n\tscattermapChartSchema,\n]);\n\nexport const nullableChartType = chartType\n\t.nullable()\n\t.describe(\n\t\t'If the user prompt does not specify a known chart type, pass null; otherwise, pass the specified chart type',\n\t);\n\nexport const chartIdSchema = z\n\t.string()\n\t.describe(\n\t\t'The ID of the chart to update. If not provided, use value \"chart_id_placeholder\"',\n\t)\n\t.default('chart_id_placeholder');\n\nexport const chartRecommendationsSchema = z.object({\n\tchartType: chartType,\n\taxesMapping: axesMapping,\n});\n\nexport const buildChartSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tuserPrompt: z.string().describe(\n\t\t`Combined natural language user prompt describing multiple actions on a chart. Do not split the user prompt into multiple requests.\nWhen responding to changes involving an existing chart:\n - If the prompt involves **adding or removing** chart's data structure such as dimensions, measures, or filters (e.g., \"add revenue\", \"remove date\", \"filter by region\"), do **not** modify the existing chart. Instead, **create a new chart** with the requested changes.\n - If the prompt involves **enhancing** how existing fields are displayed (e.g., \"show cost on the right axis\", \"add trend line\", \"change color\", \"adjust scale\"), apply the changes **to the existing chart**.\n`,\n\t),\n});\n\nconst baseChartSchema = z.object({\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Natural language user prompt describing a single action on a chart',\n\t\t),\n});\n\nexport const createChartSchema = baseChartSchema.extend({\n\tchartType: nullableChartType,\n\tchartTitle: z.string().describe('The new chart title'),\n});\n\nexport const updateChartSchema = baseChartSchema.extend({\n\tchartId: chartIdSchema,\n});\n\nexport const updateChartTitleSchema = updateChartSchema.extend({\n\tchartTitle: z.string().describe('The new chart title'),\n});\n\nexport const updateChartTypeSchema = updateChartSchema.extend({\n\tchartType: chartType,\n});\n\nexport const updateChartTypeOfMeasuresSchema = updateChartSchema;\n\nexport const updateChartSortingSchema = updateChartSchema;\n\nexport const updateTrendAndForecastSchema = updateChartSchema;\n\nexport const updateOtherChartDataOptionsSchema = updateChartSchema;\n\nexport const updateChartStyleOptionsSchema = updateChartSchema;\n\n/**\n * Build chart context interface\n */\nexport interface BuildChartContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\t/**\n\t * Data source title (optional)\n\t */\n\tdataSourceTitle?: string;\n\t/** Chart summaries to be used as context */\n\tchartSummaries?: ChartSummary[];\n\t/**\n\t * Retrieve a chart by its ID\n\t * @param chartId - The ID of the chart to retrieve\n\t * @returns The chart widget props\n\t */\n\tretrieveChart?: (chartId: string) => ExtendedChartWidgetProps | null;\n\t/**\n\t * Save a chart widget props\n\t * @param chartId - The ID of the chart to save\n\t * @param chartWidgetProps - The chart widget props to save\n\t */\n\tsaveChart?: (\n\t\tchartId: string,\n\t\tchartWidgetProps: ExtendedChartWidgetProps,\n\t) => void;\n\t/** Whether NLQ V3 is enabled */\n\tisNlqV3Enabled?: boolean;\n}\n","/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\n}\n","import { customAlphabet } from 'nanoid';\n\n/**\n * Generate a nanoid with a hex alphabet\n */\nexport const nanoidHex = customAlphabet('0123456789abcdef', 24);\n\n/**\n * Generate a nanoid with a hex alphabet that is a valid UUIDv4\n */\nexport function nanoidUUIDv4(): string {\n\tconst generateId = customAlphabet('0123456789abcdef', 32);\n\tconst id = generateId(); // Generate the actual string\n\n\t// Insert version (4) and variant (8-b)\n\treturn (\n\t\tid.substring(0, 8) +\n\t\t'-' +\n\t\tid.substring(8, 12) +\n\t\t'-' +\n\t\t'4' +\n\t\tid.substring(13, 16) +\n\t\t'-' +\n\t\t((parseInt(id[16], 16) & 0x3) | 0x8).toString(16) +\n\t\tid.substring(17, 20) +\n\t\t'-' +\n\t\tid.substring(20)\n\t);\n}\n","import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from \"../error.mjs\";\nexport function makeParseableResponseFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function makeParseableTextFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableResponseFormat(response_format) {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\nexport function makeParseableTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nexport function maybeParseChatCompletion(completion, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => ({\n ...choice,\n message: {\n ...choice.message,\n parsed: null,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls,\n }\n : undefined),\n },\n })),\n };\n }\n return parseChatCompletion(completion, params);\n}\nexport function parseChatCompletion(completion, params) {\n const choices = completion.choices.map((choice) => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n return {\n ...choice,\n message: {\n ...choice.message,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined,\n }\n : undefined),\n parsed: choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n return { ...completion, choices };\n}\nfunction parseResponseFormat(params, content) {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format;\n return response_format.$parseRaw(content);\n }\n return JSON.parse(content);\n }\n return null;\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params) {\n return false;\n }\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\n//# sourceMappingURL=parser.mjs.map","export const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use');\nconst defaultOptions = {\n name: undefined,\n $refStrategy: 'root',\n effectStrategy: 'input',\n pipeStrategy: 'all',\n dateStrategy: 'format:date-time',\n mapStrategy: 'entries',\n nullableStrategy: 'from-target',\n removeAdditionalStrategy: 'passthrough',\n definitionPath: 'definitions',\n target: 'jsonSchema7',\n strictUnions: false,\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: 'escape',\n applyRegexFlags: false,\n emailStrategy: 'format:email',\n base64Strategy: 'contentEncoding:base64',\n nameStrategy: 'ref',\n};\nexport const getDefaultOptions = (options) => {\n // We need to add `definitions` here as we may mutate it\n return (typeof options === 'string' ?\n {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n name: options,\n }\n : {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n ...options,\n });\n};\n//# sourceMappingURL=Options.mjs.map","export const zodDef = (zodSchema) => {\n return '_def' in zodSchema ? zodSchema._def : zodSchema;\n};\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n//# sourceMappingURL=util.mjs.map","import { getDefaultOptions } from \"./Options.mjs\";\nimport { zodDef } from \"./util.mjs\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined ?\n [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n currentPath: currentPath,\n propertyPath: undefined,\n seenRefs: new Set(),\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n zodDef(def),\n {\n def: zodDef(def),\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n//# sourceMappingURL=Refs.mjs.map","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n//# sourceMappingURL=errorMessages.mjs.map","export function parseAnyDef() {\n return {};\n}\n//# sourceMappingURL=any.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: 'array',\n };\n if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n//# sourceMappingURL=array.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: 'integer',\n format: 'int64',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=bigint.mjs.map","export function parseBooleanDef() {\n return {\n type: 'boolean',\n };\n}\n//# sourceMappingURL=boolean.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n//# sourceMappingURL=branded.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=catch.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case 'string':\n case 'format:date-time':\n return {\n type: 'string',\n format: 'date-time',\n };\n case 'format:date':\n return {\n type: 'string',\n format: 'date',\n };\n case 'integer':\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: 'integer',\n format: 'unix-time',\n };\n if (refs.target === 'openApi3') {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n//# sourceMappingURL=date.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n//# sourceMappingURL=default.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseEffectsDef(_def, refs, forceResolution) {\n return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {};\n}\n//# sourceMappingURL=effects.mjs.map","export function parseEnumDef(def) {\n return {\n type: 'string',\n enum: [...def.values],\n };\n}\n//# sourceMappingURL=enum.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nconst isJsonSchema7AllOfType = (type) => {\n if ('type' in type && type.type === 'string')\n return false;\n return 'allOf' in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '1'],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if ('additionalProperties' in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ?\n {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n//# sourceMappingURL=intersection.mjs.map","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== 'bigint' &&\n parsedType !== 'number' &&\n parsedType !== 'boolean' &&\n parsedType !== 'string') {\n return {\n type: Array.isArray(def.value) ? 'array' : 'object',\n };\n }\n if (refs.target === 'openApi3') {\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n const: def.value,\n };\n}\n//# sourceMappingURL=literal.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nlet emojiRegex;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp('^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$', 'u');\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: 'string',\n };\n function processPattern(value) {\n return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;\n }\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'email':\n switch (refs.emailStrategy) {\n case 'format:email':\n addFormat(res, 'email', check.message, refs);\n break;\n case 'format:idn-email':\n addFormat(res, 'idn-email', check.message, refs);\n break;\n case 'pattern:zod':\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case 'url':\n addFormat(res, 'uri', check.message, refs);\n break;\n case 'uuid':\n addFormat(res, 'uuid', check.message, refs);\n break;\n case 'regex':\n addPattern(res, check.regex, check.message, refs);\n break;\n case 'cuid':\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case 'cuid2':\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case 'startsWith':\n addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);\n break;\n case 'endsWith':\n addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);\n break;\n case 'datetime':\n addFormat(res, 'date-time', check.message, refs);\n break;\n case 'date':\n addFormat(res, 'date', check.message, refs);\n break;\n case 'time':\n addFormat(res, 'time', check.message, refs);\n break;\n case 'duration':\n addFormat(res, 'duration', check.message, refs);\n break;\n case 'length':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'includes': {\n addPattern(res, RegExp(processPattern(check.value)), check.message, refs);\n break;\n }\n case 'ip': {\n if (check.version !== 'v6') {\n addFormat(res, 'ipv4', check.message, refs);\n }\n if (check.version !== 'v4') {\n addFormat(res, 'ipv6', check.message, refs);\n }\n break;\n }\n case 'emoji':\n addPattern(res, zodPatterns.emoji, check.message, refs);\n break;\n case 'ulid': {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case 'base64': {\n switch (refs.base64Strategy) {\n case 'format:binary': {\n addFormat(res, 'binary', check.message, refs);\n break;\n }\n case 'contentEncoding:base64': {\n setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);\n break;\n }\n case 'pattern:zod': {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case 'nanoid': {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case 'toLowerCase':\n case 'toUpperCase':\n case 'trim':\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nconst escapeNonAlphaNumeric = (value) => Array.from(value)\n .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\\\${c}`))\n .join('');\nconst addFormat = (schema, value, message, refs) => {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message && refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'format', value, message, refs);\n }\n};\nconst addPattern = (schema, regex, message, refs) => {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: processRegExp(regex, refs),\n ...(message && refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);\n }\n};\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nconst processRegExp = (regexOrFunction, refs) => {\n const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;\n if (!refs.applyRegexFlags || !regex.flags)\n return regex.source;\n // Currently handled flags\n const flags = {\n i: regex.flags.includes('i'),\n m: regex.flags.includes('m'),\n s: regex.flags.includes('s'), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = '';\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === '^') {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === '$') {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === '.') {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === '\\\\') {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === ']') {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === '[') {\n inCharGroup = true;\n }\n }\n try {\n const regexTest = new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n};\n//# sourceMappingURL=string.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { parseDef } from \"../parseDef.mjs\";\nimport { parseStringDef } from \"./string.mjs\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: 'object',\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'properties', key],\n }) ?? {},\n }), {}),\n additionalProperties: false,\n };\n }\n const schema = {\n type: 'object',\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? {},\n };\n if (refs.target === 'openApi3') {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {\n const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {});\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n return schema;\n}\n//# sourceMappingURL=record.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { parseRecordDef } from \"./record.mjs\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === 'record') {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '0'],\n }) || {};\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '1'],\n }) || {};\n return {\n type: 'array',\n maxItems: 125,\n items: {\n type: 'array',\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n//# sourceMappingURL=map.mjs.map","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== 'number';\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1 ?\n parsedTypes[0] === 'string' ?\n 'string'\n : 'number'\n : ['string', 'number'],\n enum: actualValues,\n };\n}\n//# sourceMappingURL=nativeEnum.mjs.map","export function parseNeverDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=never.mjs.map","export function parseNullDef(refs) {\n return refs.target === 'openApi3' ?\n {\n enum: ['null'],\n nullable: true,\n }\n : {\n type: 'null',\n };\n}\n//# sourceMappingURL=null.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const primitiveMappings = {\n ZodString: 'string',\n ZodNumber: 'number',\n ZodBigInt: 'integer',\n ZodBoolean: 'boolean',\n ZodNull: 'null',\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === 'openApi3')\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case 'string':\n case 'number':\n case 'boolean':\n return [...acc, type];\n case 'bigint':\n return [...acc, 'integer'];\n case 'object':\n if (x._def.value === null)\n return [...acc, 'null'];\n case 'symbol':\n case 'undefined':\n case 'function':\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === 'ZodEnum')) {\n return {\n type: 'string',\n enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n }))\n .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n//# sourceMappingURL=union.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { primitiveMappings } from \"./union.mjs\";\nexport function parseNullableDef(def, refs) {\n if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [primitiveMappings[def.innerType._def.typeName], 'null'],\n };\n }\n if (refs.target === 'openApi3') {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && '$ref' in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '0'],\n });\n return base && { anyOf: [base, { type: 'null' }] };\n}\n//# sourceMappingURL=nullable.mjs.map","import { addErrorMessage, setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: 'number',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'int':\n res.type = 'integer';\n addErrorMessage(res, 'type', check.message, refs);\n break;\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=number.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nfunction decideAdditionalProperties(def, refs) {\n if (refs.removeAdditionalStrategy === 'strict') {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys !== 'strict'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n else {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys === 'passthrough'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n}\nexport function parseObjectDef(def, refs) {\n const result = {\n type: 'object',\n ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {\n if (propDef === undefined || propDef._def === undefined)\n return acc;\n const propertyPath = [...refs.currentPath, 'properties', propName];\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: propertyPath,\n propertyPath,\n });\n if (parsedDef === undefined)\n return acc;\n if (refs.openaiStrictMode && propDef.isOptional() && !propDef.isNullable()) {\n console.warn(`Zod field at \\`${propertyPath.join('/')}\\` uses \\`.optional()\\` without \\`.nullable()\\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required\\nThis will become an error in a future version of the SDK.`);\n }\n return {\n properties: {\n ...acc.properties,\n [propName]: parsedDef,\n },\n required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],\n };\n }, { properties: {}, required: [] }),\n additionalProperties: decideAdditionalProperties(def, refs),\n };\n if (!result.required.length)\n delete result.required;\n return result;\n}\n//# sourceMappingURL=object.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '1'],\n });\n return innerSchema ?\n {\n anyOf: [\n {\n not: {},\n },\n innerSchema,\n ],\n }\n : {};\n};\n//# sourceMappingURL=optional.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === 'input') {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === 'output') {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n//# sourceMappingURL=pipeline.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n//# sourceMappingURL=promise.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n const schema = {\n type: 'array',\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n//# sourceMappingURL=set.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: 'array',\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalItems'],\n }),\n };\n }\n else {\n return {\n type: 'array',\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n//# sourceMappingURL=tuple.mjs.map","export function parseUndefinedDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=undefined.mjs.map","export function parseUnknownDef() {\n return {};\n}\n//# sourceMappingURL=unknown.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=readonly.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { parseAnyDef } from \"./parsers/any.mjs\";\nimport { parseArrayDef } from \"./parsers/array.mjs\";\nimport { parseBigintDef } from \"./parsers/bigint.mjs\";\nimport { parseBooleanDef } from \"./parsers/boolean.mjs\";\nimport { parseBrandedDef } from \"./parsers/branded.mjs\";\nimport { parseCatchDef } from \"./parsers/catch.mjs\";\nimport { parseDateDef } from \"./parsers/date.mjs\";\nimport { parseDefaultDef } from \"./parsers/default.mjs\";\nimport { parseEffectsDef } from \"./parsers/effects.mjs\";\nimport { parseEnumDef } from \"./parsers/enum.mjs\";\nimport { parseIntersectionDef } from \"./parsers/intersection.mjs\";\nimport { parseLiteralDef } from \"./parsers/literal.mjs\";\nimport { parseMapDef } from \"./parsers/map.mjs\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.mjs\";\nimport { parseNeverDef } from \"./parsers/never.mjs\";\nimport { parseNullDef } from \"./parsers/null.mjs\";\nimport { parseNullableDef } from \"./parsers/nullable.mjs\";\nimport { parseNumberDef } from \"./parsers/number.mjs\";\nimport { parseObjectDef } from \"./parsers/object.mjs\";\nimport { parseOptionalDef } from \"./parsers/optional.mjs\";\nimport { parsePipelineDef } from \"./parsers/pipeline.mjs\";\nimport { parsePromiseDef } from \"./parsers/promise.mjs\";\nimport { parseRecordDef } from \"./parsers/record.mjs\";\nimport { parseSetDef } from \"./parsers/set.mjs\";\nimport { parseStringDef } from \"./parsers/string.mjs\";\nimport { parseTupleDef } from \"./parsers/tuple.mjs\";\nimport { parseUndefinedDef } from \"./parsers/undefined.mjs\";\nimport { parseUnionDef } from \"./parsers/union.mjs\";\nimport { parseUnknownDef } from \"./parsers/unknown.mjs\";\nimport { parseReadonlyDef } from \"./parsers/readonly.mjs\";\nimport { ignoreOverride } from \"./Options.mjs\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n if ('$ref' in seenSchema) {\n refs.seenRefs.add(seenSchema.$ref);\n }\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchema = selectParser(def, def.typeName, refs, forceResolution);\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case 'root':\n return { $ref: item.path.join('/') };\n // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e.\n // the top-level schema *must* be `{\"type\": \"object\", \"properties\": {...}}` but if we ever\n // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract\n // the schema to `#/definitions/` and reference that.\n //\n // e.g. if we need to reference a schema at\n // `[\"#\",\"definitions\",\"contactPerson\",\"properties\",\"person1\",\"properties\",\"name\"]`\n // then we'll extract it out to `contactPerson_properties_person1_properties_name`\n case 'extract-to-root':\n const name = item.path.slice(refs.basePath.length + 1).join('_');\n // we don't need to extract the root schema in this case, as it's already\n // been added to the definitions\n if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') {\n refs.definitions[name] = item.def;\n }\n return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') };\n case 'relative':\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case 'none':\n case 'seen': {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`);\n return {};\n }\n return refs.$refStrategy === 'seen' ? {} : undefined;\n }\n }\n};\nconst getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\nconst selectParser = (def, typeName, refs, forceResolution) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return parseDef(def.getter()._def, refs);\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs, forceResolution);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n//# sourceMappingURL=parseDef.mjs.map","import { parseDef } from \"./parseDef.mjs\";\nimport { getRefs } from \"./Refs.mjs\";\nimport { zodDef, isEmptyObj } from \"./util.mjs\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n const name = typeof options === 'string' ? options\n : options?.nameStrategy === 'title' ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined ? refs : ({\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }), false) ?? {};\n const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ?\n options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n const definitions = (() => {\n if (isEmptyObj(refs.definitions)) {\n return undefined;\n }\n const definitions = {};\n const processedDefinitions = new Set();\n // the call to `parseDef()` here might itself add more entries to `.definitions`\n // so we need to continually evaluate definitions until we've resolved all of them\n //\n // we have a generous iteration limit here to avoid blowing up the stack if there\n // are any bugs that would otherwise result in us iterating indefinitely\n for (let i = 0; i < 500; i++) {\n const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));\n if (newDefinitions.length === 0)\n break;\n for (const [key, schema] of newDefinitions) {\n definitions[key] =\n parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};\n processedDefinitions.add(key);\n }\n }\n return definitions;\n })();\n const combined = name === undefined ?\n definitions ?\n {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : refs.nameStrategy === 'duplicate-ref' ?\n {\n ...main,\n ...(definitions || refs.seenRefs.size ?\n {\n [refs.definitionPath]: {\n ...definitions,\n // only actually duplicate the schema definition if it was ever referenced\n // otherwise the duplication is completely pointless\n ...(refs.seenRefs.size ? { [name]: main } : undefined),\n },\n }\n : undefined),\n }\n : {\n $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === 'jsonSchema7') {\n combined.$schema = 'http://json-schema.org/draft-07/schema#';\n }\n else if (refs.target === 'jsonSchema2019-09') {\n combined.$schema = 'https://json-schema.org/draft/2019-09/schema#';\n }\n return combined;\n};\nexport { zodToJsonSchema };\n//# sourceMappingURL=zodToJsonSchema.mjs.map","import { makeParseableResponseFormat, makeParseableTextFormat, makeParseableTool, } from \"../lib/parser.mjs\";\nimport { zodToJsonSchema as _zodToJsonSchema } from \"../_vendor/zod-to-json-schema/index.mjs\";\nimport { makeParseableResponseTool } from \"../lib/ResponsesParser.mjs\";\nfunction zodToJsonSchema(schema, options) {\n return _zodToJsonSchema(schema, {\n openaiStrictMode: true,\n name: options.name,\n nameStrategy: 'duplicate-ref',\n $refStrategy: 'extract-to-root',\n nullableStrategy: 'property',\n });\n}\n/**\n * Creates a chat completion `JSONSchema` response format object from\n * the given Zod schema.\n *\n * If this is passed to the `.parse()`, `.stream()` or `.runTools()`\n * chat completion methods then the response message will contain a\n * `.parsed` property that is the result of parsing the content with\n * the given Zod object.\n *\n * ```ts\n * const completion = await client.beta.chat.completions.parse({\n * model: 'gpt-4o-2024-08-06',\n * messages: [\n * { role: 'system', content: 'You are a helpful math tutor.' },\n * { role: 'user', content: 'solve 8x + 31 = 2' },\n * ],\n * response_format: zodResponseFormat(\n * z.object({\n * steps: z.array(z.object({\n * explanation: z.string(),\n * answer: z.string(),\n * })),\n * final_answer: z.string(),\n * }),\n * 'math_answer',\n * ),\n * });\n * const message = completion.choices[0]?.message;\n * if (message?.parsed) {\n * console.log(message.parsed);\n * console.log(message.parsed.final_answer);\n * }\n * ```\n *\n * This can be passed directly to the `.create()` method but will not\n * result in any automatic parsing, you'll have to parse the response yourself.\n */\nexport function zodResponseFormat(zodObject, name, props) {\n return makeParseableResponseFormat({\n type: 'json_schema',\n json_schema: {\n ...props,\n name,\n strict: true,\n schema: zodToJsonSchema(zodObject, { name }),\n },\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\nexport function zodTextFormat(zodObject, name, props) {\n return makeParseableTextFormat({\n type: 'json_schema',\n ...props,\n name,\n strict: true,\n schema: zodToJsonSchema(zodObject, { name }),\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\n/**\n * Creates a chat completion `function` tool that can be invoked\n * automatically by the chat completion `.runTools()` method or automatically\n * parsed by `.parse()` / `.stream()`.\n */\nexport function zodFunction(options) {\n // @ts-expect-error TODO\n return makeParseableTool({\n type: 'function',\n function: {\n name: options.name,\n parameters: zodToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n },\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\nexport function zodResponsesFunction(options) {\n return makeParseableResponseTool({\n type: 'function',\n name: options.name,\n parameters: zodToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\n//# sourceMappingURL=zod.mjs.map","/**\n * Utilities for sdk-ai-services\n */\n\n/**\n * Normalize URL by ensuring it ends with a trailing slash\n */\nexport function normalizeUrl(url: string): string {\n\treturn url.endsWith('/') ? url : `${url}/`;\n}\n\n/**\n * Parse error to extract message\n */\nexport const parseError = (error: Error | string | object) => {\n\tif (error instanceof Error) {\n\t\ttry {\n\t\t\treturn JSON.parse(error.message);\n\t\t} catch (e) {\n\t\t\treturn error.message;\n\t\t}\n\t}\n\tif (typeof error === 'string') {\n\t\treturn error;\n\t}\n\treturn error;\n};\n","export function getUrlWithProxy(url: string): string {\n\treturn window.App && window.App.proxyurl\n\t\t? `${window.App.proxyurl}${url}`\n\t\t: url;\n}\n\nexport function getAbsoluteUrlWithProxy(url: string): string {\n\tconst baseUrl =\n\t\twindow.App && window.App.proxyurl\n\t\t\t? window.App.proxyurl\n\t\t\t: `${window.location.protocol}//${window.location.host}`;\n\n\treturn `${baseUrl}${url}`;\n}\n\nexport function getProxyPath(): string {\n\tif (!window.App || !window.App.proxyurl) {\n\t\treturn '';\n\t}\n\n\tconst parser = document.createElement('a');\n\tparser.href = window.App.proxyurl;\n\n\tconst resultPath = parser.pathname.replace(/\\/$/, '');\n\t// if (!isLoggedInUserBelongsToSystemTenant()) {\n\t// const tenantPath = `/${getLoggedInUserTenantName()}`;\n\t// const indexTenantName = resultPath.lastIndexOf(tenantPath);\n\t// if (indexTenantName !== -1) {\n\t// resultPath = `${resultPath.slice(0, indexTenantName)}${resultPath.slice(indexTenantName + tenantPath.length)}`;\n\t// }\n\t// }\n\n\treturn resultPath;\n}\n\nexport function getTenantPrefix() {\n\ttry {\n\t\tconst urlHost = window.location.host;\n\t\tconst {\n\t\t\ttenant: { tenantDomainNames, name: tenantName },\n\t\t} = window.App.user;\n\t\tconst isDNS =\n\t\t\turlHost &&\n\t\t\ttenantDomainNames &&\n\t\t\ttenantDomainNames.some((dnsUrl) => dnsUrl.includes(urlHost));\n\t\tconst tenantPrefix =\n\t\t\tisDNS || tenantName === 'system' ? '' : `/${tenantName}`;\n\n\t\treturn tenantPrefix;\n\t} catch (error) {\n\t\tconsole.debug('no tenant prefix', error);\n\t\treturn '';\n\t}\n}\n\n// function getSessionTimeoutPath(): string {\n// return getUrlWithProxy('/app/account#/timeout?src=');\n// }\n\n// function loadWithProxyURI(proxyURI: string, path: string): Promise<void> {\n// const fullPath = `${proxyURI}${path}`;\n// return core.utils.load(fullPath)\n// .catch((error) => {\n// console.error(`Error while loading ${fullPath}`, error);\n// throw error;\n// });\n// }\n","import {\n\tAuthenticator,\n\tgetAuthenticator,\n\tHttpClient,\n} from '@sisense/sdk-rest-client';\nimport { normalizeUrl } from '@/utils/utils';\nimport { getTenantPrefix } from './proxy-utils';\n\n// Re-export from CSDK for convenience\nexport type AuthenticatorConfig = {\n\turl: string;\n\tusername?: string;\n\tpassword?: string;\n\ttoken?: string | null;\n\twat?: string | null;\n\tssoEnabled?: boolean;\n\tenableSilentPreAuth?: boolean;\n\tuseFusionAuth?: boolean;\n\talternativeSsoHost?: string;\n};\n\n/**\n * Factory function to create an HTTP client from an authenticator\n * @param url - The URL to use for the HTTP client\n * @param authenticator - The authenticator to use for the HTTP client\n * @returns Configured HttpClient instance\n */\nexport function createHttpClientFromAuthenticator(\n\turl: string,\n\tauthenticator: Authenticator,\n): HttpClient {\n\tlet tenantPrefix = getTenantPrefix();\n\tif (tenantPrefix.startsWith('/')) {\n\t\ttenantPrefix = tenantPrefix.slice(1);\n\t}\n\tconst httpClientInstance = new HttpClient(\n\t\t`${normalizeUrl(url)}${tenantPrefix}`,\n\t\tauthenticator,\n\t\t'sdk-ai-core' + (__PACKAGE_VERSION__ ? `-${__PACKAGE_VERSION__}` : ''),\n\t);\n\thttpClientInstance.login();\n\treturn httpClientInstance;\n}\n\n/**\n * Factory function to create an HTTP client from an authenticator configuration\n * @param config - Authenticator configuration\n * @returns Configured HttpClient instance\n */\nexport function createHttpClientFromConfig(\n\tconfig: AuthenticatorConfig,\n): HttpClient {\n\tconst authenticator = getAuthenticator(config);\n\n\tif (!authenticator) {\n\t\tthrow new Error('Invalid authentication method');\n\t}\n\n\treturn createHttpClientFromAuthenticator(config.url, authenticator);\n}\n\n/**\n * Factory function to create a custom fetch function for OpenAI chat completions\n * This fetch function applies authentication headers from the provided httpClient\n * @param httpClient - The HTTP client instance to use for authentication\n * @returns Custom fetch function\n */\nexport function createCustomFetch(httpClient: HttpClient) {\n\treturn async (\n\t\turl: RequestInfo | URL,\n\t\tinit?: RequestInit,\n\t): Promise<Response> => {\n\t\tif (!url.toString().includes('chat/completions')) {\n\t\t\tthrow new Error('Use httpClient for non-completion requests');\n\t\t}\n\n\t\tconst headers = new Headers();\n\t\tconst isBearerAuth = httpClient.auth.type === 'bearer';\n\n\t\tif (init?.headers) {\n\t\t\tconst originalHeaders = new Headers(init.headers);\n\t\t\t// Sisense server doesn't allow `x-` headers\n\t\t\t// httpClient sets its own authorization header\n\t\t\toriginalHeaders.forEach((value, key) => {\n\t\t\t\tif (\n\t\t\t\t\t!key.toLowerCase().startsWith('x-') &&\n\t\t\t\t\t(isBearerAuth || key.toLowerCase() !== 'authorization')\n\t\t\t\t) {\n\t\t\t\t\theaders.set(key, value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\thttpClient.auth.applyHeaders(headers);\n\t\tconst newInit = { ...(init || {}), headers };\n\t\treturn fetch(url, newInit);\n\t};\n}\n","import { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport { createCustomFetch } from './http-client';\nimport { normalizeUrl } from './utils';\n\nconst OPENAI_API_URL_PATH = 'api/v2/ai';\n\n/**\n * Factory function to create an OpenAI client with custom configuration\n * @param baseURL - The base URL for the OpenAI API endpoint\n * @param fetchFn - Custom fetch function (e.g., with authentication headers)\n * @returns Configured OpenAI client instance\n */\nexport function createOpenAIClientHelper(\n\tbaseURL: string,\n\tfetchFn: typeof fetch,\n): OpenAI {\n\treturn new OpenAI({\n\t\t// @ts-expect-error - OpenAI client requires apiKey but we're using custom auth\n\t\tapiKey: null,\n\t\tdangerouslyAllowBrowser: true,\n\t\tbaseURL,\n\t\tfetch: fetchFn,\n\t});\n}\n\nexport function createOpenAIClient(httpClient: HttpClient): OpenAI {\n\tconst baseURL = normalizeUrl(httpClient.url) + OPENAI_API_URL_PATH;\n\treturn createOpenAIClientHelper(baseURL, createCustomFetch(httpClient));\n}\n","// ============================================================================\n// Lazy Initialization of HttpClient singleton\n// ============================================================================\n\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport {\n\tAuthenticatorConfig,\n\tcreateHttpClientFromAuthenticator,\n} from './utils/http-client';\nimport { createHttpClientFromConfig } from './utils/http-client';\nimport { createOpenAIClient } from './utils/openai-client';\n\nlet httpClientInstance: HttpClient | null = null;\n\n/**\n * Set a pre-created HttpClient instance (similar to initializeSisenseServices)\n * Useful when the consuming app already has an HttpClient instance\n *\n * @param httpClient - Pre-created HttpClient instance\n */\nexport function initializeHttpClient(httpClient: HttpClient): void {\n\thttpClientInstance = httpClient;\n}\n\n/**\n * Get the shared HttpClient instance (lazy initialization)\n *\n * @returns The HttpClient instance\n * @throws Error if client hasn't been initialized\n */\nexport function getHttpClient(): HttpClient {\n\tif (!httpClientInstance) {\n\t\tthrow new Error(\n\t\t\t'HttpClient not initialized. Create one using createHttpClient() and then initialize it using initializeHttpClient().',\n\t\t);\n\t}\n\treturn httpClientInstance;\n}\n\n/**\n * Reset the http client\n * This function is useful when the consuming app needs to switch tenant or login to another user\n */\nexport function resetHttpClient(): void {\n\tconst currentHttpClient = getHttpClient();\n\tconst url = currentHttpClient.url;\n\tconst authenticator = currentHttpClient.auth;\n\tconst httpClient = createHttpClientFromAuthenticator(url, authenticator);\n\tinitializeHttpClient(httpClient);\n}\n\n// ============================================================================\n// Lazy Initialization of OpenAI client singleton\n// ============================================================================\n\nlet openAIClientInstance: OpenAI | null = null;\n\n/**\n * Set a pre-created OpenAI client instance (similar to initializeSisenseServices)\n * Useful when the consuming app already has an OpenAI client instance\n *\n * @param openAIClient - Pre-created OpenAI client instance\n */\nexport function initializeOpenAIClient(openAIClient: OpenAI): void {\n\topenAIClientInstance = openAIClient;\n}\n\n/**\n * Get the shared OpenAI client instance (lazy initialization)\n *\n * @returns The OpenAI client instance\n * @throws Error if client hasn't been initialized\n */\nexport function getOpenAIClient(): OpenAI {\n\tif (!openAIClientInstance) {\n\t\tthrow new Error(\n\t\t\t'OpenAI client not initialized. Create one using createOpenAIClient() and then initialize it using initializeOpenAIClient().',\n\t\t);\n\t}\n\treturn openAIClientInstance;\n}\n\n/**\n * Reset the OpenAI client (useful for testing)\n *\n * Allows tests to clean up or reset the shared instance between test runs\n */\nexport function resetOpenAIClient(): void {\n\tconst openAIClient = createOpenAIClient(getHttpClient());\n\tinitializeOpenAIClient(openAIClient);\n}\n\n/**\n * Initialize the HttpClient and OpenAI client singletons\n * @param authConfig - Authenticator configuration\n */\nexport function initializeClients(authConfig: AuthenticatorConfig): void {\n\t// Create and initialize HttpClient singleton\n\tconst httpClient = createHttpClientFromConfig(authConfig);\n\tinitializeHttpClient(httpClient);\n\n\t// Create and initialize OpenAI client singleton\n\tconst openAIClient = createOpenAIClient(httpClient);\n\tinitializeOpenAIClient(openAIClient);\n}\n","import { zodResponseFormat } from 'openai/helpers/zod';\nimport { z } from 'zod';\nimport type { OpenAI } from 'openai';\nimport { ChatCompletionMessageParam } from 'openai/resources/chat/completions';\nimport { getOpenAIClient } from '@/singleton-clients';\n\ntype StructuredCompletionParams<T> = {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\tresponseFormat:\n\t\t| { type: 'json_schema'; schema: z.ZodSchema<T>; name: string }\n\t\t| { type: 'json_object' };\n\tmodel?: string;\n\ttemperature?: number;\n\tsessionId?: string | null;\n\topenAIClient?: OpenAI;\n};\n\n/**\n * Creates a structured completion using OpenAI with consistent configuration\n * across all tools.\n */\nexport async function createStructuredCompletion<T>(\n\tparams: StructuredCompletionParams<T>,\n): Promise<T> {\n\tconst {\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat,\n\t\tmodel = 'gpt-4o-mini',\n\t\ttemperature = 0,\n\t\tsessionId,\n\t\topenAIClient = getOpenAIClient(),\n\t} = params;\n\n\t// Determine response format for OpenAI\n\tconst openAiResponseFormat =\n\t\tresponseFormat.type === 'json_schema'\n\t\t\t? zodResponseFormat(responseFormat.schema, responseFormat.name)\n\t\t\t: { type: 'json_object' as const };\n\n\tconst response = await openAIClient.beta.chat.completions.parse({\n\t\tmodel,\n\t\tmessages: [\n\t\t\t{ role: 'system', content: systemPrompt },\n\t\t\t{ role: 'user', content: userPrompt },\n\t\t],\n\t\tresponse_format: openAiResponseFormat,\n\t\ttools: [],\n\t\ttool_choice: 'none',\n\t\ttemperature,\n\t\tmetadata: sessionId ? { refSessionId: sessionId } : undefined,\n\t});\n\n\t// Handle response based on format type\n\tconst message = response.choices[0].message;\n\n\tif (responseFormat.type === 'json_schema') {\n\t\t// Check if response comes as tool_calls (structured output sometimes returns this way)\n\t\tif (message.tool_calls && message.tool_calls.length > 0) {\n\t\t\tconst toolCall = message.tool_calls[0];\n\t\t\tif (toolCall.function && toolCall.function.arguments) {\n\t\t\t\tconst parsedArguments = JSON.parse(toolCall.function.arguments);\n\t\t\t\treturn parsedArguments as T;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to parsed content (standard structured output)\n\t\tconst parsedResponse = message.parsed as T;\n\t\tif (!parsedResponse) {\n\t\t\tthrow new Error('No valid response from AI');\n\t\t}\n\t\treturn parsedResponse;\n\t} else {\n\t\t// Handle JSON object responses\n\t\tconst content = message.content || '{}';\n\t\tconst parsedResponse = JSON.parse(content);\n\t\tif (!parsedResponse) {\n\t\t\tthrow new Error('No valid response from AI');\n\t\t}\n\t\treturn parsedResponse as T;\n\t}\n}\n\ntype ToolsCompletionParams = {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\ttools: any[];\n\tmodel?: string;\n\ttemperature?: number;\n\ttoolChoice?:\n\t\t| 'auto'\n\t\t| 'none'\n\t\t| { type: 'function'; function: { name: string } };\n\topenAIClient?: OpenAI;\n};\n\n// Generic message type to avoid dependency on assistant's Message type\ntype GenericMessage = {\n\trole: string;\n\tcontent?: string | any;\n\ttool_call_id?: string;\n\t[key: string]: any;\n};\n\ntype ToolsCompletionResult = {\n\ttoolMessages: GenericMessage[];\n\tassistantMessages: string[];\n\tcombinedMessage: string;\n\tisError: boolean;\n};\n\n/**\n * Creates a tools completion using OpenAI with streaming support.\n * Returns captured messages and a combined message string ready for use.\n */\nexport async function createToolsCompletion(\n\tparams: ToolsCompletionParams,\n): Promise<ToolsCompletionResult> {\n\tconst {\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\ttools,\n\t\tmodel = 'gpt-4o-mini',\n\t\ttemperature = 0,\n\t\ttoolChoice = 'auto',\n\t\topenAIClient = getOpenAIClient(),\n\t} = params;\n\n\treturn new Promise<ToolsCompletionResult>((resolve) => {\n\t\tconst toolMessages: GenericMessage[] = [];\n\t\tconst assistantMessages: string[] = [];\n\n\t\topenAIClient.beta.chat.completions\n\t\t\t.runTools({\n\t\t\t\tmessages: [\n\t\t\t\t\t{\n\t\t\t\t\t\trole: 'system',\n\t\t\t\t\t\tcontent: systemPrompt,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\trole: 'user',\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\t\t\ttext: userPrompt,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmodel,\n\t\t\t\tstream: true,\n\t\t\t\ttemperature,\n\t\t\t\ttools,\n\t\t\t\ttool_choice: toolChoice,\n\t\t\t})\n\t\t\t.on('message', (message: ChatCompletionMessageParam) => {\n\t\t\t\tif (message.role === 'tool') {\n\t\t\t\t\ttoolMessages.push(message as GenericMessage);\n\t\t\t\t} else if (message.role === 'assistant' && message.content) {\n\t\t\t\t\tassistantMessages.push(message.content as string);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tlet isError = false;\n\t\t\t\tlet combinedMessage = '';\n\n\t\t\t\ttry {\n\t\t\t\t\t// Extract tool messages\n\t\t\t\t\tconst toolMessagesText = toolMessages\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(message) =>\n\t\t\t\t\t\t\t\tJSON.parse(message.content as string).message,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\n\t\t\t\t\tconst assistantMessagesText = assistantMessages.join('\\n');\n\n\t\t\t\t\t// Error Detection Logic:\n\t\t\t\t\tif (\n\t\t\t\t\t\ttoolMessages.length === 0 &&\n\t\t\t\t\t\tassistantMessages.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\t// LLM didn't execute tools but provided explanation\n\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\tcombinedMessage = assistantMessagesText; // Use LLM's explanation as error message\n\t\t\t\t\t} else if (\n\t\t\t\t\t\ttoolMessages.length === 0 &&\n\t\t\t\t\t\tassistantMessages.length === 0\n\t\t\t\t\t) {\n\t\t\t\t\t\t// No tools and no explanation - something went wrong\n\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\tcombinedMessage =\n\t\t\t\t\t\t\t'No tools executed and no response from LLM';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Tools were executed - combine normally\n\t\t\t\t\t\tcombinedMessage = [\n\t\t\t\t\t\t\ttoolMessagesText,\n\t\t\t\t\t\t\tassistantMessagesText,\n\t\t\t\t\t\t]\n\t\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t\t.join('\\n');\n\n\t\t\t\t\t\t// Check if results are empty despite tool execution\n\t\t\t\t\t\tif (combinedMessage.trim() === '') {\n\t\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\t\tcombinedMessage =\n\t\t\t\t\t\t\t\t'Tools executed but returned empty results';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tisError = true;\n\t\t\t\t\tcombinedMessage = 'Malformed tool response detected';\n\t\t\t\t}\n\n\t\t\t\tresolve({\n\t\t\t\t\ttoolMessages,\n\t\t\t\t\tassistantMessages,\n\t\t\t\t\tcombinedMessage,\n\t\t\t\t\tisError,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on('error', (err: Error) => {\n\t\t\t\t// Handle Error objects properly - JSON.stringify on Error returns {}\n\t\t\t\tconst errorMessage =\n\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t? JSON.stringify(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: err.name,\n\t\t\t\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t\t\t\t\tstack: err.stack,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t )\n\t\t\t\t\t\t: JSON.stringify(err, null, 2);\n\t\t\t\tresolve({\n\t\t\t\t\ttoolMessages: [],\n\t\t\t\t\tassistantMessages: [],\n\t\t\t\t\tcombinedMessage: errorMessage,\n\t\t\t\t\tisError: true,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n","import { z } from 'zod';\nimport { ChartType } from '@sisense/sdk-ui';\nimport { chartRecommendationsSchema, Column, ColumnType } from '../types';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\n\nconst systemPrompt = `\nYou are an expert in chart visualization and data query structuring. Your task is to assist users in generating the optimal chart type and axes mapping based on their input, adhering to the provided schema (schema object with chartType and axesMapping). Your goal is to interpret the user's prompt, analyze the provided column data, select an appropriate chart type (unless specified by the user), and map column indices to the axes mapping arrays in a way that produces a valid, effective visualization.\n\nDO NOT use any tools.\n\n### Input Expectations\n- **User Prompt**: A natural language description of the desired visualization (e.g., \"Show sales over time by region\" or \"Compare product prices\").\n- **Column Data**: A list of columns adhering to the Column interface (e.g., { id: 0, name: \"Sales\", type: \"number\" } ), representing available data fields.\n- If the user provides only a prompt without column data, assume a reasonable set of columns based on the prompt and state your assumptions.\n\n### Chart Selection Process\n1. If the user specifies a chart type, use it and proceed to axes mapping.\n2. Otherwise, determine the best chart type by:\n - Analyzing the data types of columns (e.g., numeric, categorical, temporal, geographic).\n - Identifying relationships in the prompt (e.g., trends over time, comparisons, distributions).\n - Matching to a suitable chart type from chartTypes (e.g., bar for comparisons, line for trends, pie for proportions).\n - Default to bar for categorical-numeric pairs if no clear choice emerges.\n3. Ensure the selected chart type aligns with the corresponding axesMapping schema (e.g., cartesianChartSchema for bar).\n\n### Axes Mapping Guidelines\n- Map column indices (from id in Column) to the appropriate arrays in the axesMapping object (e.g., category, value, x, y).\n- Prioritize essential fields first:\n - For cartesian charts: Fill category (e.g., time, names) and value (e.g., numbers) before optional fields like breakBy.\n - For scatter charts: Fill x and y before breakByPoint or size.\n - For categorical charts: Fill category and value.\n- Columns can appear in multiple arrays only if logical (e.g., a category used in both category and breakBy for stacked bars).\n- Respect schema constraints (e.g., z.strict() means no extra fields; required arrays like value must be non-empty).\n\n### Edge Cases\n- If insufficient columns are provided, suggest additional columns needed (e.g., \"A time column is required for a line chart\").\n- If the user-specified chart type conflicts with data (e.g., pie with continuous data), recommend an alternative and explain why.\n- If a column's role is ambiguous, infer based on type (e.g., string → category, number → value) and prompt context.\n\n### Output Format\nReturn a JSON object matching the schema structure, with:\n- chartType: The selected or user-specified chart type.\n- axesMapping: The populated axes mapping object per the relevant schema.\nProvide a brief explanation of your chart type choice and axes mapping decisions, referencing the prompt and column data.\n`;\n\nfunction mapColumnIndicesToObjects(\n\tindices: number[] | undefined,\n\tcolumns: ColumnType[],\n): { column: ColumnType }[] {\n\tif (!indices) return [];\n\treturn indices\n\t\t.map((index) => ({\n\t\t\tcolumn: columns[index],\n\t\t}))\n\t\t.filter(({ column }) => Boolean(column));\n}\n\nfunction mapChartDataToColumns(\n\trecommendations: z.infer<typeof chartRecommendationsSchema>,\n\tcolumns: ColumnType[],\n): z.infer<typeof chartRecommendationsSchema> {\n\tif (!recommendations) return recommendations;\n\n\tconst mapping = recommendations.axesMapping;\n\tconst result = {\n\t\tchartType: recommendations.chartType,\n\t\taxesMapping: {} as any,\n\t};\n\n\tfor (const [key, value] of Object.entries(mapping)) {\n\t\tif (key === 'type') continue;\n\n\t\tif (Array.isArray(value)) {\n\t\t\tresult.axesMapping[key] = mapColumnIndicesToObjects(value, columns);\n\t\t} else {\n\t\t\tresult.axesMapping[key] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport const generateChartRecommendations = async (\n\tuserPrompt: string,\n\tcolumns: ColumnType[] = [],\n\tchartType: ChartType | undefined,\n): Promise<z.infer<typeof chartRecommendationsSchema>> => {\n\tconst cols: Column[] = [];\n\tlet i = 0;\n\tfor (const c of columns) {\n\t\tconst name = 'column' in c ? c.column?.name : c.name;\n\t\tconst type = (() => {\n\t\t\tif ('column' in c && c.column && 'type' in c.column) {\n\t\t\t\treturn c.column.type;\n\t\t\t}\n\t\t\tif ('type' in c && typeof c.type === 'string') {\n\t\t\t\treturn c.type;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\tcols.push({ id: i++, name, type });\n\t}\n\n\tlet prompt = userPrompt + `\\n\\n${JSON.stringify(cols)}`;\n\tif (chartType) {\n\t\tprompt += `\n\t\tUser selected the following chart type: ${chartType} \\n\n\t\t`;\n\t}\n\n\tconst recommendations = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt: prompt,\n\t\tresponseFormat: {\n\t\t\ttype: 'json_schema',\n\t\t\tschema: chartRecommendationsSchema,\n\t\t\tname: 'chartRecommendations',\n\t\t},\n\t});\n\n\tconst updatedRecommendations = mapChartDataToColumns(\n\t\trecommendations,\n\t\tcolumns,\n\t);\n\n\tswitch (updatedRecommendations.chartType) {\n\t\tcase 'scatter':\n\t\t\t(updatedRecommendations.axesMapping as any).x = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).x[0];\n\t\t\t(updatedRecommendations.axesMapping as any).y = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).y[0];\n\t\t\t(updatedRecommendations.axesMapping as any).breakByPoint = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).breakByPoint[0];\n\t\t\t(updatedRecommendations.axesMapping as any).breakByColor = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).breakByColor[0];\n\t\t\t(updatedRecommendations.axesMapping as any).size = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).size[0];\n\t\t\tbreak;\n\t\tcase 'indicator':\n\t\t\t(updatedRecommendations.axesMapping as any).secondary = [];\n\t\t\tbreak;\n\t}\n\n\treturn updatedRecommendations;\n};\n","import {\n\tNlqResult,\n\tNlqResultChartType,\n\tQueryRecommendationResponse,\n} from '@sisense/sdk-ui/ai';\nimport { getHttpClient } from '@/singleton-clients';\nimport {\n\tDataSchemaContext,\n\tNlqResponseJSON,\n} from '@sisense/sdk-ui/analytics-composer';\n\nexport interface GetNlqResultRequest {\n\ttext: string;\n\ttimezone?: string;\n\tchartTypes: NlqResultChartType[];\n}\n\nexport interface GetNlqResultLightRequest {\n\ttext: string;\n\ttimezone?: string;\n}\n\nexport interface GetNlqV3ResultRequest {\n\ttext: string;\n\ttimezone?: string;\n\tchartTypes?: NlqResultChartType[];\n\tforceGeneration: boolean;\n}\n\nexport interface NlqV3Result {\n\tchartState: NlqResponseJSON;\n\tdataSchema: DataSchemaContext;\n\tclarification?: string;\n\ttimestamp: string;\n}\n\nexport interface QueryRecommendationConfig {\n\tnumOfRecommendations: number;\n\tuserPrompt?: string;\n}\n\nexport async function getNlqResult(\n\tcontextTitle: string,\n\trequest: GetNlqResultRequest,\n): Promise<NlqResult | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.post<NlqResult>(\n\t\t`api/v2/ai/nlq/query/${contextTitle}`,\n\t\trequest,\n\t);\n\treturn result ?? null;\n}\n\nexport async function getNlqResultLight(\n\tcontextTitle: string,\n\trequest: GetNlqResultLightRequest,\n): Promise<NlqResult | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.post<NlqResult>(\n\t\t`api/v2/ai/nlq/query-light/${contextTitle}`,\n\t\trequest,\n\t);\n\treturn result ?? null;\n}\n\nexport async function getNlqV3Result(\n\tcontextTitle: string,\n\trequest: GetNlqV3ResultRequest,\n): Promise<NlqV3Result | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.post<NlqV3Result>(\n\t\t`api/v2/ai/nlq/smartQuery/${contextTitle}`,\n\t\trequest,\n\t);\n\treturn result ?? null;\n}\n\nexport async function getQueryRecommendations(\n\tcontextTitle: string,\n\tconfig: QueryRecommendationConfig,\n): Promise<QueryRecommendationResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.get<QueryRecommendationResponse>(\n\t\t`api/v2/ai/recommendations/query/${contextTitle}/${config.numOfRecommendations}`,\n\t);\n\treturn result ?? null;\n}\n\nexport async function getQueryRecommendationsLight(\n\tcontextTitle: string,\n\tconfig: QueryRecommendationConfig,\n): Promise<QueryRecommendationResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.get<QueryRecommendationResponse>(\n\t\t`api/v2/ai/recommendations/query-light/${contextTitle}/${\n\t\t\tconfig.numOfRecommendations\n\t\t}${config.userPrompt ? `?userPrompt=${config.userPrompt}` : ''}`,\n\t);\n\treturn result ?? null;\n}\n","// Store removed - config injected via params\nimport { ExtendedChartWidgetProps } from '../types';\nimport {\n\ttranslateQueryJSON,\n\ttranslateQueryToJaql,\n\twidgetComposer,\n} from '@sisense/sdk-ui/analytics-composer';\nimport { isChartWidgetProps } from '@sisense/sdk-ui';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { convertDataSource } from '@sisense/sdk-data';\nimport { getNlqResultLight, getNlqV3Result } from '@/services/nlq/nlq-service';\n\nconst generateChartTableFromNlqV2 = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst nlqResult = await getNlqResultLight(dataSourceTitle, {\n\t\ttext: userPrompt,\n\t\ttimezone: 'UTC',\n\t});\n\n\tif (!nlqResult) {\n\t\tthrow new Error(\n\t\t\t'Error: Failed to get NLQ result. Ask the user to specify the data source again.',\n\t\t);\n\t}\n\n\tconst widgetProps = widgetComposer.toWidgetProps(\n\t\t{ ...nlqResult, chartRecommendations: {} },\n\t\t{\n\t\t\tuseCustomizedStyleOptions: true,\n\t\t},\n\t) as ExtendedChartWidgetProps;\n\n\tif (!widgetProps) {\n\t\tthrow new Error('Error: Failed to generate widget props');\n\t}\n\twidgetProps.nlqResponse = nlqResult;\n\n\tif (!isChartWidgetProps(widgetProps)) {\n\t\tthrow new Error('Error: Non-chart widget props not supported yet');\n\t}\n\n\t// set widget title if it's not set\n\twidgetProps.title = widgetProps.title || nlqResult.nlqPrompt || userPrompt;\n\n\treturn widgetProps;\n};\n\nconst generateChartTableFromNlqV3 = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst nlqResult = await getNlqV3Result(dataSourceTitle, {\n\t\ttext: userPrompt,\n\t\tforceGeneration: true,\n\t});\n\tif (!nlqResult) {\n\t\tthrow new Error('Error: Failed to get NLQ result.');\n\t}\n\tconst dataSchema = nlqResult.dataSchema;\n\tif (!dataSchema) {\n\t\tthrow new Error('Error: Data schema not found');\n\t}\n\n\tconst translationResult = translateQueryJSON({\n\t\tdata: nlqResult.chartState,\n\t\tcontext: dataSchema,\n\t});\n\tif (!translationResult.success) {\n\t\tthrow new Error(\n\t\t\t'Error: Failed to translate query JSON: ' +\n\t\t\t\tJSON.stringify(translationResult.errors),\n\t\t);\n\t}\n\n\tconst translatedParams = translationResult.data;\n\tconst jaql = translateQueryToJaql(\n\t\ttranslatedParams,\n\t\tconvertDataSource(dataSchema.dataSource),\n\t);\n\n\tconst columns = [\n\t\t...(translatedParams.dimensions || []),\n\t\t...(translatedParams.measures || []),\n\t];\n\n\tconst widgetProps: ExtendedChartWidgetProps = {\n\t\ttitle: userPrompt,\n\t\tid: nanoidHex(),\n\t\twidgetType: 'chart',\n\t\tdataSource: translatedParams.dataSource,\n\t\tchartType: 'table',\n\t\tdataOptions: { columns },\n\t\tfilters: translatedParams.filters || [],\n\t\thighlights: translatedParams.highlights || [],\n\t\tnlqResponse: {\n\t\t\tchartRecommendations: {},\n\t\t\tdetailedDescription: userPrompt,\n\t\t\tnlqPrompt: userPrompt,\n\t\t\tuserMsg: userPrompt,\n\t\t\tqueryTitle: userPrompt,\n\t\t\tjaql,\n\t\t},\n\t};\n\n\treturn widgetProps;\n};\n\nexport const generateChartTable = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n\tisNlqV3Enabled?: boolean,\n) => {\n\tif (isNlqV3Enabled) {\n\t\tconsole.debug('Generating chart table from NLQ V3');\n\t\treturn generateChartTableFromNlqV3(dataSourceTitle, userPrompt);\n\t} else {\n\t\tconsole.debug('Generating chart table from NLQ V2');\n\t\treturn generateChartTableFromNlqV2(dataSourceTitle, userPrompt);\n\t}\n};\n","import { ChartDataOptions, TableDataOptions } from '@sisense/sdk-ui';\nimport {\n\tAxesMapping,\n\tgetChartStyleOptions,\n} from '@sisense/sdk-ui/analytics-composer';\nimport {\n\tBuildChartContext,\n\tcreateChartSchema,\n\tExtendedChartWidgetProps,\n\tNullableChartType,\n} from '../types';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { generateChartRecommendations } from './generate-chart-recommendations';\nimport { generateChartTable } from './generate-chart-table';\n\nimport z from 'zod';\n\ntype GenerateChartParams = {\n\tdataSourceTitle: string;\n\tuserPrompt: string;\n\tchartType: NullableChartType;\n\tchartTitle: string;\n};\n\nexport const generateChart = async (\n\t{ dataSourceTitle, userPrompt, chartType, chartTitle }: GenerateChartParams,\n\tcontext: BuildChartContext,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst widgetProps = await generateChartTable(\n\t\tdataSourceTitle,\n\t\tuserPrompt,\n\t\tcontext.isNlqV3Enabled ?? false,\n\t);\n\n\tconst dataColumns = (widgetProps.dataOptions as TableDataOptions).columns;\n\n\tconst chartRecommendations = await generateChartRecommendations(\n\t\tuserPrompt,\n\t\tdataColumns,\n\t\tchartType!,\n\t);\n\twidgetProps.nlqResponse!.chartRecommendations =\n\t\tchartRecommendations || widgetProps.nlqResponse!.chartRecommendations;\n\n\tconst { axesMapping, chartType: newChartType } = chartRecommendations;\n\n\twidgetProps.dataOptions = axesMapping as ChartDataOptions;\n\twidgetProps.chartType = newChartType;\n\twidgetProps.title = chartTitle;\n\n\tconst baseStyleOptions = getChartStyleOptions(\n\t\tnewChartType,\n\t\twidgetProps.dataOptions as AxesMapping,\n\t\t{},\n\t\ttrue,\n\t);\n\n\t// while dashboard assistant shows expanded chart with legend on the right, we want to show it on the bottom\n\twidgetProps.styleOptions = {\n\t\t...baseStyleOptions,\n\t\t...('legend' in baseStyleOptions\n\t\t\t? { legend: { enabled: true, position: 'bottom' } }\n\t\t\t: {}),\n\t};\n\n\t// generate artifact id for the chart\n\treturn {\n\t\t...widgetProps,\n\t\tartifactId: nanoidHex(),\n\t\tdataColumns,\n\t};\n};\n\nexport const createChart = async (\n\t{ userPrompt, chartType, chartTitle }: z.infer<typeof createChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'createChart', userPrompt, chartType, chartTitle);\n\tconst dataSourceTitle = context.dataSourceTitle;\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\tconst chartId = context.toolCallId;\n\tconst chartWidgetProps = await generateChart(\n\t\t{\n\t\t\tdataSourceTitle,\n\t\t\tuserPrompt,\n\t\t\tchartType,\n\t\t\tchartTitle,\n\t\t},\n\t\tcontext,\n\t);\n\n\tcontext.saveChart?.(chartId, chartWidgetProps);\n\n\treturn {\n\t\tmessage: `New chart (chartId: ${chartId}) created successfully`,\n\t};\n};\n","import z from 'zod';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartTitleSchema,\n} from '../types';\n\ntype UpdateChartTitleHelperParams = {\n\tchartTitle: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\nexport const updateChartTitleHelper = ({\n\tchartTitle,\n\tchartWidgetProps,\n}: UpdateChartTitleHelperParams): ExtendedChartWidgetProps => {\n\treturn {\n\t\t...chartWidgetProps,\n\t\ttitle: chartTitle,\n\t};\n};\n\nexport const updateChartTitle = async (\n\t{ chartId, chartTitle }: z.infer<typeof updateChartTitleSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartTitle', chartId, chartTitle);\n\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = updateChartTitleHelper({\n\t\tchartTitle,\n\t\tchartWidgetProps,\n\t});\n\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\n\treturn {\n\t\tmessage: 'Chart title updated successfully',\n\t};\n};\n","import { ChartDataOptions, ChartType } from '@sisense/sdk-ui';\nimport {\n\tAxesMapping,\n\tgetChartStyleOptions,\n} from '@sisense/sdk-ui/analytics-composer';\nimport {\n\tExtendedChartWidgetProps,\n\tBuildChartContext,\n\tupdateChartTypeSchema,\n} from '../types';\nimport { generateChartRecommendations } from '../create-chart/generate-chart-recommendations';\nimport z from 'zod';\n\ntype UpdateChartTypeHelperParams = {\n\tuserPrompt: string;\n\tchartType: ChartType;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\nexport const updateChartTypeHelper = async ({\n\tuserPrompt,\n\tchartType,\n\tchartWidgetProps,\n}: UpdateChartTypeHelperParams) => {\n\tconst { dataColumns, styleOptions: existingStyleOptions } =\n\t\tchartWidgetProps;\n\n\tconst chartRecommendations = await generateChartRecommendations(\n\t\tuserPrompt,\n\t\tdataColumns,\n\t\tchartType,\n\t);\n\n\tconst { axesMapping, chartType: newChartType } = chartRecommendations;\n\n\tchartWidgetProps.dataOptions = axesMapping as ChartDataOptions;\n\tchartWidgetProps.chartType = newChartType;\n\n\tconst baseStyleOptions = getChartStyleOptions(\n\t\tnewChartType,\n\t\tchartWidgetProps.dataOptions as AxesMapping,\n\t\t{},\n\t\ttrue,\n\t);\n\n\tconst styleOptions = existingStyleOptions\n\t\t? {\n\t\t\t\t...baseStyleOptions,\n\t\t\t\t// Preserve specific properties from existingStyleOptions\n\t\t\t\t...('legend' in existingStyleOptions &&\n\t\t\t\t'legend' in baseStyleOptions\n\t\t\t\t\t? { legend: existingStyleOptions.legend }\n\t\t\t\t\t: {}),\n\t\t\t\t...('labels' in existingStyleOptions &&\n\t\t\t\t'labels' in baseStyleOptions\n\t\t\t\t\t? { labels: existingStyleOptions.labels }\n\t\t\t\t\t: {}),\n\t\t\t\t...('xAxis' in existingStyleOptions &&\n\t\t\t\t'xAxis' in baseStyleOptions\n\t\t\t\t\t? { xAxis: existingStyleOptions.xAxis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('yAxis' in existingStyleOptions &&\n\t\t\t\t'yAxis' in baseStyleOptions\n\t\t\t\t\t? { yAxis: existingStyleOptions.yAxis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('y2Axis' in existingStyleOptions &&\n\t\t\t\t'y2Axis' in baseStyleOptions\n\t\t\t\t\t? { y2Axis: existingStyleOptions.y2Axis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('dataLimits' in existingStyleOptions &&\n\t\t\t\t'dataLimits' in baseStyleOptions\n\t\t\t\t\t? { dataLimits: existingStyleOptions.dataLimits }\n\t\t\t\t\t: {}),\n\t\t\t\t...('markerSize' in existingStyleOptions &&\n\t\t\t\t'markerSize' in baseStyleOptions\n\t\t\t\t\t? { markerSize: existingStyleOptions.markerSize }\n\t\t\t\t\t: {}),\n\t\t }\n\t\t: baseStyleOptions;\n\n\tchartWidgetProps.styleOptions = styleOptions;\n\n\treturn chartWidgetProps;\n};\n\nexport const updateChartType = async (\n\t{ chartId, userPrompt, chartType }: z.infer<typeof updateChartTypeSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'updateChartType',\n\t\tchartId,\n\t\tuserPrompt,\n\t\tchartType,\n\t);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartTypeHelper({\n\t\tuserPrompt,\n\t\tchartType,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart type updated successfully',\n\t};\n};\n","import { ChartType } from '@sisense/sdk-ui';\nimport { z } from 'zod';\nimport { chartType } from '../types';\n\nconst LineWidthSchema = z.object({\n\twidth: z.enum(['thin', 'bold', 'thick']),\n});\n\nconst LineSubtypeSchema = z.enum(['line/basic', 'line/spline']);\n\n// Common components schemas\nconst LegendSchema = z\n\t.object({\n\t\tenabled: z\n\n\t\t\t.boolean()\n\n\t\t\t.optional()\n\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if legend should be shown on the chart',\n\t\t\t),\n\t\tposition: z\n\n\t\t\t.enum(['top', 'left', 'right', 'bottom'])\n\n\t\t\t.optional()\n\n\t\t\t.describe('Position of the legend'),\n\t})\n\t.describe(\n\t\t'Options that define legend - a key that provides information about the data series or colors used in chart.',\n\t)\n\t.strict();\n\nconst SeriesLabelsSchema = z\n\t.object({\n\t\tenabled: z.boolean().optional(),\n\t\tshowValue: z.boolean().optional(),\n\t\tshowPercentage: z.boolean().optional(),\n\t\tfontSize: z.string().optional(),\n\t\t// color: z.string().optional(),\n\t})\n\t.strict();\n// Create separate axis schemas instead of reusing\nconst AxisLabel = z\n\t.object({\n\t\tenabled: z.boolean().optional(),\n\t\ttitle: z\n\t\t\t.object({\n\t\t\t\tenabled: z.boolean().default(true).optional(),\n\t\t\t\ttext: z.string().optional(),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('The title or name of the x-axis'),\n\t\tmin: z\n\t\t\t.number()\n\t\t\t.nullable()\n\t\t\t.optional()\n\t\t\t.describe('The minimum value of the x-axis'),\n\t\tmax: z\n\t\t\t.number()\n\t\t\t.nullable()\n\t\t\t.optional()\n\t\t\t.describe('The maximum value of the x-axis'),\n\t\tgridLines: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if grid lines should be shown on the chart',\n\t\t\t),\n\t\tintervalJumps: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Interval of the tick marks (jumps) in axis units.'),\n\t\tisIntervalEnabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if tick marks should be shown on the axis',\n\t\t\t),\n\t\tlabels: z\n\t\t\t.object({\n\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\tshowValue: z.boolean().optional(),\n\t\t\t\tshowPercentage: z.boolean().optional(),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('Configuration for labels on the axis'),\n\t\tlogarithmic: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if the axis should have logarithmic scale',\n\t\t\t),\n\t\ttemplateMainYHasGridLines: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if the Y axis should have grid lines extending the ticks across the plot area',\n\t\t\t),\n\t})\n\t.strict();\n\nconst XAxisSchema = AxisLabel.describe('X-axis configuration');\n\nconst YAxisSchema = AxisLabel.describe('Y-axis configuration');\n\nconst Y2AxisSchema = AxisLabel.describe('Y2-axis configuration');\n\nconst MarkersSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if markers should be shown on the chart',\n\t\t\t),\n\t\tfill: z\n\t\t\t.enum(['filled', 'hollow'])\n\t\t\t.optional()\n\t\t\t.describe('Marker fill style'),\n\t\tsize: z\n\t\t\t.enum(['small', 'medium', 'large'])\n\t\t\t.optional()\n\t\t\t.describe('Size of markers'),\n\t})\n\t.describe(\n\t\t'Options that define markers - symbols or data points that highlight specific values.',\n\t)\n\t.strict();\n\nconst NavigatorSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if navigator should be shown on the chart',\n\t\t\t),\n\t\tscrollerLocation: z\n\t\t\t.object({\n\t\t\t\tmax: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('The maximum value of the navigator scroller'),\n\t\t\t\tmin: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('The minimum value of the navigator scroller'),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'The scroll location of the navigator scroller / auto zoom feature',\n\t\t\t),\n\t})\n\t.describe(\n\t\t'Options that define navigator - zoom/pan tool for large datasets in a chart.',\n\t)\n\t.strict();\n\nconst DataLimitsSchema = z\n\t.object({\n\t\tcategoriesCapacity: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Maximum number of categories to chart'),\n\t\tseriesCapacity: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Maximum number of series to chart'),\n\t})\n\t.describe(\n\t\t'Configuration that limits the series or categories that are charted.',\n\t)\n\t.strict();\n\n// Chart-specific schemas\nexport const LineChartStyleSchema = z\n\t.object({\n\t\tlineWidth: LineWidthSchema.optional(),\n\t\tsubtype: LineSubtypeSchema.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const BarChartStyleSchema = z\n\t.object({\n\t\tsubtype: z\n\t\t\t.enum(['bar/classic', 'bar/stacked', 'bar/stacked100'])\n\t\t\t.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nconst ConvolutionSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if convolution ability should be enabled on chart',\n\t\t\t),\n\t\tindependentSlicesCount: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Number that defines of how many independent slices should be present in chart (other will be convolved)',\n\t\t\t),\n\t\tminimalIndependentSlicePercentage: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Value that defines what minimal size in percent should a slice take to fall under the convolution',\n\t\t\t),\n\t\tselectedConvolutionType: z\n\t\t\t.enum(['byPercentage', 'bySlicesCount'])\n\t\t\t.optional()\n\t\t\t.describe('Selected type of convolution behavior'),\n\t})\n\t.describe(\n\t\t'Configuration that defines the ability of the Pie chart to collapse (convolve) and hide part of the data under the single category \"Others\".',\n\t)\n\t.strict();\n\nexport const PieChartStyleSchema = z\n\t.object({\n\t\tsubtype: z.enum(['pie/basic', 'pie/donut', 'pie/ring']).optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\tconvolution: ConvolutionSchema.optional(),\n\t})\n\t.strict();\n\nexport const ScatterChartStyleSchema = z\n\t.object({\n\t\tmarkers: MarkersSchema.optional(),\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tmarkerSize: z\n\n\t\t\t.object({\n\t\t\t\tscatterBubbleMaxSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Maximum size of markers'),\n\t\t\t\tscatterBubbleMinSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Minimum size of markers'),\n\t\t\t\tscatterDefaultSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Default size of markers'),\n\t\t\t})\n\n\t\t\t.optional()\n\n\t\t\t.describe('Size of markers'),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const AreaChartStyleSchema = z\n\t.object({\n\t\tsubtype: z\n\t\t\t.enum([\n\t\t\t\t'area/basic',\n\t\t\t\t'area/spline',\n\t\t\t\t'area/stacked',\n\t\t\t\t'area/stacked100',\n\t\t\t\t'area/stackedspline',\n\t\t\t\t'area/stackedspline100',\n\t\t\t])\n\t\t\t.optional(),\n\t\topacity: z.number().optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const FunnelChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tfunnelDirection: z\n\t\t\t.enum(['inverted', 'regular'])\n\t\t\t.optional()\n\t\t\t.describe('Direction of FunnelChart narrowing'),\n\t\tfunnelSize: z\n\t\t\t.enum(['narrow', 'regular', 'wide'])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Visual size of the lowest slice (degree of funnel narrowing from highest to lowest slices)',\n\t\t\t),\n\t\tfunnelType: z\n\t\t\t.enum(['pinched', 'regular'])\n\t\t\t.optional()\n\t\t\t.describe('Visual type of the lowest slice of FunnelChar'),\n\t\tsubtype: z.enum(['funnel/basic', 'funnel/pyramid']).optional(),\n\t\tneckHeight: z.number().optional(),\n\t\tneckWidth: z.number().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t})\n\t.strict();\n\nexport const TreemapChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlayout: z\n\t\t\t.enum([\n\t\t\t\t'squarified',\n\t\t\t\t'stripes',\n\t\t\t\t'stripes-vertical',\n\t\t\t\t'stripes-horizontal',\n\t\t\t])\n\t\t\t.optional(),\n\t\tborderWidth: z.number().optional(),\n\t\tborderColor: z.string().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\ttooltip: z.object({\n\t\t\tmode: z\n\t\t\t\t.enum(['contribution', 'value'])\n\t\t\t\t.optional()\n\t\t\t\t.describe('Define mode of data showing'),\n\t\t}),\n\t})\n\t.strict();\n\nexport const SunburstChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlevels: z.number().optional(),\n\t\tborderWidth: z.number().optional(),\n\t\tborderColor: z.string().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t})\n\t.strict();\n\nexport const BoxplotChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tsubtype: z.enum(['boxplot/full', 'boxplot/hollow']).optional(),\n\t\tboxType: z.enum(['iqr', 'extremums', 'standardDeviation']).optional(),\n\t\toutliersEnabled: z.boolean().optional(),\n\t\twidth: z.number().optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const IndicatorChartStyleSchema = z\n\t.object({\n\t\tsubtype: z.enum(['indicator/numeric', 'indicator/gauge']).optional(),\n\t\tvalue: z.number().optional(),\n\t\tmin: z.number().optional(),\n\t\tmax: z.number().optional(),\n\t\tthresholds: z.array(z.number()).optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\tforceTickerView: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag to force render indicator in ticker mode regardless of display size',\n\t\t\t),\n\t\tskin: z.enum(['1', '2']).optional().describe('Skin gauge indicator'),\n\t})\n\t.strict();\n\nconst PolarChartStyleSchema = z.object({\n\tdataLimits: DataLimitsSchema.optional(),\n\theight: z.number().optional(),\n\twidth: z.number().optional(),\n\tlegend: LegendSchema.optional(),\n\tmarkers: MarkersSchema.optional(),\n\tnavigator: NavigatorSchema.optional(),\n\tsubtype: z.enum(['polar/area', 'polar/column', 'polar/line']).optional(),\n\txAxis: XAxisSchema.optional(),\n\tyAxis: YAxisSchema.optional(),\n\ty2Axis: Y2AxisSchema.optional(),\n\tseriesLabels: SeriesLabelsSchema.optional(),\n});\n\nconst TableChartStyleSchema = z.object({\n\tcolumns: z\n\t\t.object({\n\t\t\talternatingColor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Alternating color for columns'),\n\t\t\twidth: z\n\t\t\t\t.enum(['auto', 'content'])\n\t\t\t\t.optional()\n\t\t\t\t.describe('Width of columns'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for columns'),\n\theader: z\n\t\t.object({\n\t\t\tcolor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Color of header'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for header'),\n\trows: z\n\t\t.object({\n\t\t\talternatingColor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Alternating color for rows'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for rows'),\n\trowsPerPage: z.number().optional().describe('Number of rows per page'),\n\tpaddingHorizontal: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Horizontal padding around whole table'),\n\tpaddingVertical: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Vertical padding around whole table'),\n});\n\nexport const chartStyleSchemas: Record<ChartType, z.ZodObject<any>> = {\n\tline: LineChartStyleSchema,\n\tbar: BarChartStyleSchema,\n\tarea: AreaChartStyleSchema,\n\tcolumn: BarChartStyleSchema, // Assuming column is similar to bar; adjust as needed\n\tpie: PieChartStyleSchema,\n\tscatter: ScatterChartStyleSchema,\n\tfunnel: FunnelChartStyleSchema,\n\ttreemap: TreemapChartStyleSchema,\n\tsunburst: SunburstChartStyleSchema,\n\tboxplot: BoxplotChartStyleSchema,\n\tindicator: IndicatorChartStyleSchema,\n\tpolar: PolarChartStyleSchema,\n\ttable: TableChartStyleSchema,\n\tarearange: z.object({}),\n\tscattermap: z.object({}),\n\tareamap: z.object({}),\n\t'calendar-heatmap': z.object({}),\n\tstreamgraph: z.object({}),\n} as const;\n\nconst baseChartSchema = z.object({\n\tchartType,\n});\n\n// Function to get schema by chart type\nexport function getChartStyleOptionsSchema(chartType: ChartType) {\n\tconst styleSchema = chartStyleSchemas[chartType];\n\n\tif (!styleSchema) {\n\t\tthrow new Error(`Unsupported chart type: ${chartType}`);\n\t}\n\n\treturn baseChartSchema.extend({\n\t\tstyleOptions: styleSchema,\n\t});\n}\n\n// Type for all chart style options\nexport type ChartStyleOptions =\n\t| z.infer<typeof LineChartStyleSchema>\n\t| z.infer<typeof BarChartStyleSchema>\n\t| z.infer<typeof PieChartStyleSchema>\n\t| z.infer<typeof ScatterChartStyleSchema>\n\t| z.infer<typeof AreaChartStyleSchema>\n\t| z.infer<typeof FunnelChartStyleSchema>\n\t| z.infer<typeof TreemapChartStyleSchema>\n\t| z.infer<typeof SunburstChartStyleSchema>\n\t| z.infer<typeof BoxplotChartStyleSchema>\n\t| z.infer<typeof IndicatorChartStyleSchema>;\n\ntype DataOptionTypes =\n\t| 'cartesian'\n\t| 'categorical'\n\t| 'scatter'\n\t| 'table'\n\t| 'indicator'\n\t| 'areamap'\n\t| 'arearange';\n\nconst dataOptionsSchemas: Record<DataOptionTypes, z.ZodObject<any>> = {\n\tcartesian: z.object({\n\t\tcategory: z.array(\n\t\t\tz.object({\n\t\t\t\tcolumn: z.object({}),\n\t\t\t}),\n\t\t),\n\t\tvalue: z.array(\n\t\t\tz.object({\n\t\t\t\tcolumn: z.object({}),\n\t\t\t}),\n\t\t),\n\t}),\n\tcategorical: z.object({\n\t\tcategory: z.array(z.object({})),\n\t\tvalue: z.array(z.object({})),\n\t}),\n\tscatter: z.object({\n\t\tx: z.object({}),\n\t\ty: z.object({}),\n\t}),\n\ttable: z.object({}),\n\tindicator: z.object({}),\n\tareamap: z.object({}),\n\tarearange: z.object({}),\n} as const;\n\nexport const getChartDataOptionsSchema = (dataOptionType: DataOptionTypes) => {\n\treturn dataOptionsSchemas[dataOptionType];\n};\n\nexport const PartialColumnSchema = z.object({\n\tname: z.string(),\n\ttitle: z.string(),\n});\n\nexport const ColorStringSchema = z\n\t.string()\n\t.describe('hex color code for the measure.');\nexport const UniformColorSchema = z\n\t.object({\n\t\tcolor: ColorStringSchema,\n\t\ttype: z\n\t\t\t.enum(['uniform'])\n\t\t\t.describe('Type of color to be used for the measure.'),\n\t})\n\t.describe(\n\t\t'Uniform color options for data similar to the Single Color option in the Sisense UI.',\n\t);\n\nexport const ConditionalColorSchema = z\n\t.object({\n\t\tconditions: z\n\t\t\t.array(\n\t\t\t\tz.object({\n\t\t\t\t\tcolor: ColorStringSchema,\n\t\t\t\t\texpression: z.string(),\n\t\t\t\t\toperator: z.enum(['<', '>', '>=', '<=']),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.describe('Array of color conditions'),\n\t\tdefaultColor: ColorStringSchema.describe(\n\t\t\t'Default color when no condition is met',\n\t\t),\n\t\ttype: z.enum(['conditional']).describe('Color options type'),\n\t})\n\t.describe(\n\t\t'Conditional color options for data similar to the Conditional Color option in the Sisense UI.',\n\t);\n\nexport const ColorOptionsSchema = z.object({\n\tcolor: z.string().describe('hex color code for the measure.'),\n});\n\nexport const RangeColorSchema = z\n\t.object({\n\t\tmaxColor: ColorStringSchema.describe(\n\t\t\t'End color of the range',\n\t\t).optional(),\n\t\tmaxValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Maximum value explicitly set to override the maximum value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tmidValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Middle value explicitly set to override the middle value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tminColor: ColorStringSchema.describe(\n\t\t\t'Start color of the range',\n\t\t).optional(),\n\t\tminValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Minimum value explicitly set to override the minimum value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tsteps: z\n\t\t\t.number()\n\t\t\t.describe('Distinct number of colors in the range')\n\t\t\t.optional(),\n\t\ttype: z.enum(['range']).describe('Color options type'),\n\t})\n\t.describe('Color options for range color.');\n\nexport const NumberFormatConfigSchema = z.object({\n\tbilion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one billion - e.g. 1B',\n\t\t),\n\tdecimalScale: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('The number of decimal places'),\n\tkilo: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one thousand - e.g. 1K',\n\t\t),\n\tmillion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one million - e.g. 1M',\n\t\t),\n\tname: z\n\t\t.enum(['Currency', 'Numbers', 'Percent'])\n\t\t.optional()\n\t\t.describe('Supported formats'),\n\tprefix: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether symbol is shown in front of or after the number',\n\t\t),\n\tsymbol: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Symbol to show in front of or after the number depending on the value of prefix.',\n\t\t),\n\tthousandSeparator: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Boolean flag whether the thousand separator is shown'),\n\ttrillion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one trillion - e.g. 1T',\n\t\t),\n});\n\nexport const trendFormulaOptions = z\n\t.object({\n\t\tignoreAnomalies: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that enables the function to automatically identify and ignore anomalous values in the series. This can be particularly useful when you want to maintain the integrity of your analysis by avoiding potential outliers. default is false',\n\t\t\t),\n\t\tmodelType: z\n\t\t\t.enum([\n\t\t\t\t'advancedSmoothing',\n\t\t\t\t'linear',\n\t\t\t\t'localEstimates',\n\t\t\t\t'logarithmic',\n\t\t\t])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Trend analysis model type to be used for the operation. default is linear',\n\t\t\t),\n\t})\n\t.describe('Trend analysis options for the measure');\n\nexport const forecastFormulaOptions = z\n\t.object({\n\t\tconfidenceInterval: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Confidence interval showing the probabilistic upper and lower limits of the forecasted series according to the uncertainty level. The valid range is (0.8 <= X < 1). default is 0.8',\n\t\t\t),\n\t\tendDate: z\n\t\t\t.string()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'End date of the time series data that the forecasting model will be trained on. This parameter can be used to discard the end of the series. Specify a ISO 8601 date string or Date object.',\n\t\t\t),\n\t\tforecastHorizon: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Number of data points to be predicted. The accepted value range is between 1-1,000. default is 3',\n\t\t\t),\n\t\tlowerBound: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Expected lower limit to improve the forecast accuracy when reaching the limit. Note that values in the confidence interval can exceed this limit.',\n\t\t\t),\n\t\tmodelType: z\n\t\t\t.enum(['auto', 'autoArima', 'holtWinters', 'prophet'])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t\"Forecasting model type. The 'auto' option automatically fits the best combination of models. default is auto\",\n\t\t\t),\n\t\troundToInt: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag to round the predicted result to an integer if set to true. Otherwise, the predicted result is left as a float. default is false',\n\t\t\t),\n\t\tstartDate: z\n\t\t\t.string()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Start date of the time series data that the forecasting model will be trained on. This parameter can be used to discard the beginning of the series. Specify a ISO 8601 date string or Date object.',\n\t\t\t),\n\t\tupperBound: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Expected upper limit to improve the forecast accuracy when reaching the limit. Note that values in the confidence interval can exceed this limit.',\n\t\t\t),\n\t})\n\t.describe('Forecast analysis options for the measure');\n\nexport const dataOptionsEditingSchemas = {\n\tmeasures: z\n\t\t.object({\n\t\t\tcolumn: PartialColumnSchema,\n\t\t\tchartType: z\n\t\t\t\t.enum(['line', 'bar', 'column', 'area'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Series chart type, which is used with StyledMeasure to customize series in a mixed chart.',\n\t\t\t\t)\n\t\t\t\t.optional(),\n\t\t\tsortType: z\n\t\t\t\t.enum(['sortAsc', 'sortDesc', 'sortNone'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Sorting direction, either in Ascending order, Descending order, or None',\n\t\t\t\t),\n\t\t\tcolor: z.string().describe('hex color code for the measure.'),\n\t\t\tconnectNulls: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to connect a graph line across null points or render a gap',\n\t\t\t\t),\n\t\t\tdataBars: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'pivot table only -Boolean flag whether to display data bars for this measure in the pivot table.',\n\t\t\t\t),\n\t\t\tdataBarsColor: z\n\t\t\t\t.string()\n\t\t\t\t.describe(\n\t\t\t\t\t'pivot table only - Color options for data bars for this measure in the pivot table',\n\t\t\t\t),\n\t\t\tnumberFormatConfig: NumberFormatConfigSchema.describe(\n\t\t\t\t'Configuration for number formatting.',\n\t\t\t),\n\t\t\tseriesStyleOptions: z\n\t\t\t\t.object({})\n\t\t\t\t.describe(\n\t\t\t\t\t'Specific style options to be applied to specific series in Chart. Supported only for cartesian and polar charts.',\n\t\t\t\t),\n\t\t\tshowOnRightAxis: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to show this value/measure on the right axis (true) or on the left axis (false).',\n\t\t\t\t),\n\t\t\ttotalsCalculation: z\n\t\t\t\t.enum(['sum', 'avg', 'min', 'max', 'count'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Calculation for the totals of this measure in the pivot table.',\n\t\t\t\t),\n\t\t\ttreatNullDataAsZeros: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether null values are treated as zeros in the chart',\n\t\t\t\t),\n\t\t\ttrend: trendFormulaOptions\n\t\t\t\t.optional()\n\t\t\t\t.describe('Trend analysis options for the measure.'),\n\t\t\tforecast: forecastFormulaOptions\n\t\t\t\t.optional()\n\t\t\t\t.describe('Forecast analysis options for the measure.'),\n\t\t})\n\t\t.describe('Configuration for measures.StyledMeasure'),\n\tdimensions: z\n\t\t.object({\n\t\t\tcolumn: PartialColumnSchema,\n\t\t\tcontinuous: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag to toggle continuous timeline on this date column.',\n\t\t\t\t),\n\t\t\tdateFormat: z\n\t\t\t\t.string()\n\t\t\t\t.describe(\n\t\t\t\t\t'Date format. See ECMAScript Date Time String Format(opens new window) Note that \"YYYY\" and \"DD\" have been disabled since they often get confused with \"yyyy\" and \"dd\" and can produce unexpected results.',\n\t\t\t\t),\n\t\t\tgeoLevel: z\n\t\t\t\t.enum([\n\t\t\t\t\t'country',\n\t\t\t\t\t'state',\n\t\t\t\t\t'city',\n\t\t\t\t\t'zip',\n\t\t\t\t\t'latitude',\n\t\t\t\t\t'longitude',\n\t\t\t\t])\n\t\t\t\t.describe('Geographic location level for Scattermap chart.'),\n\t\t\tgranularity: z\n\t\t\t\t.enum(['day', 'week', 'month', 'year'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Date granularity that works with continuous timeline. Values from DateLevels.',\n\t\t\t\t),\n\t\t\tincludeSubTotals: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to include subtotals for this dimension in the pivot table.',\n\t\t\t\t),\n\t\t\tisColored: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe('Boolean flag whether to color the dimension.'),\n\t\t\tisHtml: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to render category/column value as HTML in the Table component.',\n\t\t\t\t),\n\t\t\tnumberFormatConfig: NumberFormatConfigSchema.describe(\n\t\t\t\t'Configuration for number formatting.',\n\t\t\t),\n\t\t\tsortType: z\n\t\t\t\t.enum(['sortAsc', 'sortDesc', 'sortNone'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Sorting configuration that represents either SortDirection or PivotRowsSort for the pivot table',\n\t\t\t\t),\n\t\t})\n\t\t.describe('Configuration for dimensions. StyledColumn'),\n};\n\n// export type DataOptionsEditingSchemas = z.infer<typeof dataOptionsEditingSchemas>;\n\nexport const cartesianDataOptionsEditingSchemas = z.object({\n\tvalues: z.array(dataOptionsEditingSchemas.measures),\n\tcategories: z.array(dataOptionsEditingSchemas.dimensions),\n\tbreakBy: z.array(dataOptionsEditingSchemas.dimensions),\n\tseriesToColorMap: z\n\t\t.object({})\n\t\t.describe(\n\t\t\t'Optional mapping of each of the series to colors. (key: color)',\n\t\t),\n});\n\nexport const categoricalDataOptionsEditingSchemas = z.object({\n\tvalues: z.array(dataOptionsEditingSchemas.measures),\n\tcategories: z.array(dataOptionsEditingSchemas.dimensions),\n\tseriesToColorMap: z\n\t\t.object({})\n\t\t.describe('Color mapping for series to color.'),\n});\nexport const scatterChartDataOptionsEditingSchemas = z.object({\n\ty: dataOptionsEditingSchemas.measures,\n\tx: dataOptionsEditingSchemas.dimensions,\n\tbreakByColor: dataOptionsEditingSchemas.measures,\n\tbreakBySize: dataOptionsEditingSchemas.measures,\n\tseriesToColorMap: dataOptionsEditingSchemas.measures,\n\tsize: dataOptionsEditingSchemas.measures,\n});\n\nexport const indicatorDataOptionsEditingSchemas = z.object({\n\tmin: z.array(dataOptionsEditingSchemas.measures),\n\tmax: z.array(dataOptionsEditingSchemas.measures),\n\tsecondary: z.array(dataOptionsEditingSchemas.measures),\n\tvalue: dataOptionsEditingSchemas.measures,\n});\n\nexport const boxplotDataOptionsEditingSchemas = z.object({\n\tboxType: z.enum(['extremums', 'iqr', 'standardDeviation']),\n\tcategory: z.array(dataOptionsEditingSchemas.dimensions),\n\toutliersEnabled: z.boolean().optional(),\n\tvalue: z.array(dataOptionsEditingSchemas.measures),\n});\n\nexport const scattermapDataOptionsEditingSchemas = z.object({\n\tcolorBy: dataOptionsEditingSchemas.measures,\n\t// todo: or statement dimensions or measures\n\tdetails: dataOptionsEditingSchemas.dimensions,\n\tgeo: z.array(dataOptionsEditingSchemas.dimensions),\n\tsize: dataOptionsEditingSchemas.measures,\n});\n\nexport const areamapDataOptionsEditingSchemas = z.object({\n\tcolor: z.array(dataOptionsEditingSchemas.measures),\n\tgeo: z.array(dataOptionsEditingSchemas.dimensions),\n});\n\nexport const calendarHeatmapDataOptionsEditingSchemas = z.object({\n\tdate: z.array(dataOptionsEditingSchemas.dimensions),\n\tvalue: z.array(dataOptionsEditingSchemas.measures),\n});\n\nexport const tableDataOptionsEditingSchemas = z.object({\n\tcolumns: z.array(dataOptionsEditingSchemas.dimensions),\n});\n\nexport const getChartDataOptionsEditingSchemas = (chartType: ChartType) => {\n\tswitch (chartType) {\n\t\tcase 'line':\n\t\tcase 'bar':\n\t\tcase 'column':\n\t\tcase 'area':\n\t\tcase 'polar':\n\t\t\treturn cartesianDataOptionsEditingSchemas;\n\t\tcase 'pie':\n\t\tcase 'funnel':\n\t\tcase 'treemap':\n\t\tcase 'sunburst':\n\t\t\treturn categoricalDataOptionsEditingSchemas;\n\t\tcase 'scatter':\n\t\t\treturn scatterChartDataOptionsEditingSchemas;\n\t\tcase 'indicator':\n\t\t\treturn indicatorDataOptionsEditingSchemas;\n\t\tcase 'table':\n\t\t\treturn tableDataOptionsEditingSchemas;\n\t\tcase 'boxplot':\n\t\t\treturn boxplotDataOptionsEditingSchemas;\n\t\tcase 'scattermap':\n\t\t\treturn scattermapDataOptionsEditingSchemas;\n\t\tcase 'areamap':\n\t\t\treturn areamapDataOptionsEditingSchemas;\n\t\tcase 'calendar-heatmap':\n\t\t\treturn calendarHeatmapDataOptionsEditingSchemas;\n\t\tdefault:\n\t\t\treturn z.object({});\n\t}\n};\n\nexport const chartDataOptionsSchemas: Record<ChartType, z.ZodObject<any>> = {\n\tline: cartesianDataOptionsEditingSchemas,\n\tbar: categoricalDataOptionsEditingSchemas,\n\tarea: cartesianDataOptionsEditingSchemas,\n\tcolumn: categoricalDataOptionsEditingSchemas, // Assuming column is similar to bar; adjust as needed\n\tpie: categoricalDataOptionsEditingSchemas,\n\tscatter: scatterChartDataOptionsEditingSchemas,\n\tfunnel: categoricalDataOptionsEditingSchemas,\n\ttreemap: categoricalDataOptionsEditingSchemas,\n\tsunburst: categoricalDataOptionsEditingSchemas,\n\tboxplot: boxplotDataOptionsEditingSchemas,\n\tindicator: indicatorDataOptionsEditingSchemas,\n\tpolar: cartesianDataOptionsEditingSchemas,\n\ttable: TableChartStyleSchema,\n\tarearange: z.object({}),\n\tscattermap: z.object({}),\n\tareamap: z.object({}),\n\t'calendar-heatmap': calendarHeatmapDataOptionsEditingSchemas,\n\tstreamgraph: z.object({}),\n} as const;\n","import { getChartDataOptionsEditingSchemas } from './chart-options-schemas';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartSchema,\n} from '../types';\nimport { zodToReadableType } from '@/utils/zod-utils';\nimport { ChartWidgetProps } from '@sisense/sdk-ui';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\nimport { z } from 'zod';\n\ntype UpdateChartDataOptionsHelperParams = {\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Updates chart data options based on the user's prompt.\n * @param userPrompt - The user's prompt to update the chart data options.\n * @param chartWidgetProps - The chart widget props to update the chart data options for.\n * @returns The updated chart.\n */\nexport const updateChartDataOptionsHelper = async ({\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartDataOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { dataOptions: currentDataOptions, chartType: currentChartType } =\n\t\tchartWidgetProps;\n\n\t// Get the schema for the current chart type\n\tconst baseSchema = getChartDataOptionsEditingSchemas(currentChartType);\n\tconst targetSchema = z.object({\n\t\tdataOptions: baseSchema,\n\t});\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart data options properties are as follows:\n\t\t\n\n\t\tdataOptions: {\n\t\t\t${Object.entries(baseSchema.shape)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`- ${key}: ${zodToReadableType(value as z.ZodTypeAny)}`,\n\t\t\t\t)\n\t\t\t\t.join('\\n')}\n\t\t}\n\n\t\tcurrent dataOptions: {\n\t\t\t${JSON.stringify(currentDataOptions, null, 2)}\n\t\t}\n\t\t`;\n\n\tconst systemPrompt = `\n\t\t\tYou are a chart data options assistant. You edit only the fields the user mentions.\n\n\t\t\tDO NOT use any tools.\n\t\t\t\n\t\t\tHere are the editable properties:\n\t\t\t${editableFieldsDoc}\n\t\t\t\n\t\t\tYour output must be a JSON object with only the requested changes.\n\n\t\t\tThe 'column' object, containing only the item's 'name', MUST be included for any change to an item within a list field ('values', 'categories', 'breakBy', etc.) \n\t\t\tto maintain identity.\n \n Do not include unchanged fields.\n \n Example:\n \n User: \"Sort revenue in descending order\"\n Output: { \"dataOptions\": { \"value\" : [\n {\n \"column\": {\n \"name\": \"Total Revenue\",\n },\n \"sortType\": \"sortDesc\"\n }\n ] } }\n\n\t\t\t`;\n\n\tconst parsedResponse = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat: { type: 'json_object' },\n\t});\n\n\tconsole.debug('LLM RESPONSE DATA OPTIONS', parsedResponse);\n\n\tconst { dataOptions: responseDataOptions = null } =\n\t\tparsedResponse as z.infer<typeof targetSchema>;\n\n\tconst mergedDataOptions = responseDataOptions\n\t\t? mergeDataOptions(chartWidgetProps.dataOptions, responseDataOptions)\n\t\t: chartWidgetProps.dataOptions;\n\n\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t...chartWidgetProps,\n\t\tdataOptions: mergedDataOptions,\n\t};\n\n\treturn updatedWidgetProps;\n};\n\nfunction mergeDataOptions(\n\toriginal: ChartWidgetProps['dataOptions'],\n\taiResponse: Partial<ChartWidgetProps['dataOptions']>,\n): ChartWidgetProps['dataOptions'] {\n\tconst merged = { ...original };\n\n\tfor (const key of Object.keys(aiResponse)) {\n\t\tconst dataOptionsKey = key as keyof ChartWidgetProps['dataOptions'];\n\t\tconst incomingList = aiResponse[dataOptionsKey];\n\t\tconst originalList = original[dataOptionsKey] || [];\n\n\t\t// @ts-expect-error - TODO: fix this\n\t\tmerged[dataOptionsKey] = originalList.map((originalItem: any) => {\n\t\t\tconst originalName = originalItem?.column?.name;\n\t\t\t// @ts-expect-error - TODO: fix this\n\t\t\tconst updatedItem = incomingList.find(\n\t\t\t\t(item: any) => item?.column?.name === originalName,\n\t\t\t);\n\n\t\t\tif (updatedItem) {\n\t\t\t\tconst result = { ...originalItem }; // Preserve all original properties\n\n\t\t\t\t// Update or remove properties based on updatedItem\n\t\t\t\tObject.keys(updatedItem).forEach((key) => {\n\t\t\t\t\tif (key !== 'column') {\n\t\t\t\t\t\tconst value = updatedItem[key];\n\t\t\t\t\t\tif (value === null || value === undefined) {\n\t\t\t\t\t\t\tdelete result[key]; // Remove property if null/undefined in update\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresult[key] = value; // Update property with new value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\treturn originalItem;\n\t\t});\n\t}\n\n\treturn merged;\n}\n\nexport const updateChartDataOptions = async (\n\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartDataOptions', chartId, userPrompt);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartDataOptionsHelper({\n\t\tuserPrompt,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart data options updated successfully',\n\t};\n};\n","'use strict';\n\nvar isMergeableObject = function isMergeableObject(value) {\n\treturn isNonNullObject(value)\n\t\t&& !isSpecial(value)\n};\n\nfunction isNonNullObject(value) {\n\treturn !!value && typeof value === 'object'\n}\n\nfunction isSpecial(value) {\n\tvar stringValue = Object.prototype.toString.call(value);\n\n\treturn stringValue === '[object RegExp]'\n\t\t|| stringValue === '[object Date]'\n\t\t|| isReactElement(value)\n}\n\n// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25\nvar canUseSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;\n\nfunction isReactElement(value) {\n\treturn value.$$typeof === REACT_ELEMENT_TYPE\n}\n\nfunction emptyTarget(val) {\n\treturn Array.isArray(val) ? [] : {}\n}\n\nfunction cloneUnlessOtherwiseSpecified(value, options) {\n\treturn (options.clone !== false && options.isMergeableObject(value))\n\t\t? deepmerge(emptyTarget(value), value, options)\n\t\t: value\n}\n\nfunction defaultArrayMerge(target, source, options) {\n\treturn target.concat(source).map(function(element) {\n\t\treturn cloneUnlessOtherwiseSpecified(element, options)\n\t})\n}\n\nfunction getMergeFunction(key, options) {\n\tif (!options.customMerge) {\n\t\treturn deepmerge\n\t}\n\tvar customMerge = options.customMerge(key);\n\treturn typeof customMerge === 'function' ? customMerge : deepmerge\n}\n\nfunction getEnumerableOwnPropertySymbols(target) {\n\treturn Object.getOwnPropertySymbols\n\t\t? Object.getOwnPropertySymbols(target).filter(function(symbol) {\n\t\t\treturn Object.propertyIsEnumerable.call(target, symbol)\n\t\t})\n\t\t: []\n}\n\nfunction getKeys(target) {\n\treturn Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))\n}\n\nfunction propertyIsOnObject(object, property) {\n\ttry {\n\t\treturn property in object\n\t} catch(_) {\n\t\treturn false\n\t}\n}\n\n// Protects from prototype poisoning and unexpected merging up the prototype chain.\nfunction propertyIsUnsafe(target, key) {\n\treturn propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,\n\t\t&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,\n\t\t\t&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.\n}\n\nfunction mergeObject(target, source, options) {\n\tvar destination = {};\n\tif (options.isMergeableObject(target)) {\n\t\tgetKeys(target).forEach(function(key) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(target[key], options);\n\t\t});\n\t}\n\tgetKeys(source).forEach(function(key) {\n\t\tif (propertyIsUnsafe(target, key)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {\n\t\t\tdestination[key] = getMergeFunction(key, options)(target[key], source[key], options);\n\t\t} else {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(source[key], options);\n\t\t}\n\t});\n\treturn destination\n}\n\nfunction deepmerge(target, source, options) {\n\toptions = options || {};\n\toptions.arrayMerge = options.arrayMerge || defaultArrayMerge;\n\toptions.isMergeableObject = options.isMergeableObject || isMergeableObject;\n\t// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()\n\t// implementations can use it. The caller may not replace it.\n\toptions.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;\n\n\tvar sourceIsArray = Array.isArray(source);\n\tvar targetIsArray = Array.isArray(target);\n\tvar sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;\n\n\tif (!sourceAndTargetTypesMatch) {\n\t\treturn cloneUnlessOtherwiseSpecified(source, options)\n\t} else if (sourceIsArray) {\n\t\treturn options.arrayMerge(target, source, options)\n\t} else {\n\t\treturn mergeObject(target, source, options)\n\t}\n}\n\ndeepmerge.all = function deepmergeAll(array, options) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new Error('first argument should be an array')\n\t}\n\n\treturn array.reduce(function(prev, next) {\n\t\treturn deepmerge(prev, next, options)\n\t}, {})\n};\n\nvar deepmerge_1 = deepmerge;\n\nmodule.exports = deepmerge_1;\n","import { z } from 'zod';\nimport { getChartStyleOptionsSchema } from './chart-options-schemas';\nimport deepmerge from 'deepmerge';\nimport { zodToReadableType } from '@/utils/zod-utils';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartSchema,\n} from '../types';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\n\ntype UpdateChartStyleOptionsHelperParams = {\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Updates chart style options based on the user's prompt.\n * @param userPrompt - The user's prompt to update the chart style options.\n * @param chartWidgetProps - The chart widget props to update the chart style options for.\n * @returns The updated chart.\n */\nexport const updateChartStyleOptionsHelper = async ({\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartStyleOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { styleOptions: currentStyleOptions, chartType: currentChartType } =\n\t\tchartWidgetProps;\n\n\t// Get the schema for the effective chart type\n\tconst targetSchema = getChartStyleOptionsSchema(currentChartType);\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart style properties are as follows:\n\t\t\n\t\tstyleOptions: {\n\t\t${Object.entries(targetSchema.shape)\n\t\t\t.map(([key, value]) => `- ${key}: ${zodToReadableType(value)}`)\n\t\t\t.join('\\n')}\n\t\t}\n\t\t`;\n\n\tconst systemPrompt = `\n\t\t\tYou are a chart style options assistant. You edit only the fields the user mentions.\n\n\t\t\tDO NOT use any tools.\n\t\t\t\n\t\t\tHere are the editable properties:\n\t\t\t${editableFieldsDoc}\n\t\t\t\n\t\t\tDO NOT return any field unless the user directly references it.\n\t\t\tYour output must be a JSON object with only the requested changes.\n\t\t\tDo not include unchanged fields.\n\t\t\t\n\t\t\tExample:\n\t\t\tUser \"name the y axis title to Awesome Revenue\"\n\t\t\tOutput: { \"styleOptions\": { \"yAxis\": { \"title\": \"Awesome Revenue\", enabled: true } } }\n\n\t\t\tUser: \"move legend to top\"\n\t\t\tOutput: { \"styleOptions\": { \"legend\": { \"position\": \"top\" } } }\n\n\t\t\t`;\n\n\tconst parsedResponse = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat: { type: 'json_object' },\n\t});\n\n\tconst { styleOptions: responseStyleOptions = currentStyleOptions } =\n\t\tparsedResponse as z.infer<typeof targetSchema>;\n\n\tconst mergedStyleOptions = deepmerge(\n\t\tcurrentStyleOptions || {},\n\t\tresponseStyleOptions || {},\n\t);\n\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t...chartWidgetProps,\n\t\tstyleOptions: mergedStyleOptions,\n\t};\n\n\treturn updatedWidgetProps;\n};\n\nexport const updateChartStyleOptions = async (\n\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartStyleOptions', chartId, userPrompt);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartStyleOptionsHelper({\n\t\tuserPrompt,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart style options updated successfully',\n\t};\n};\n","export const TOOL_NAME_CHART_BUILDER = 'buildChart';\nexport const TOOL_NAME_DASHBOARD_BUILDER = 'buildDashboard';\nexport const TOOL_NAME_DATA_MODEL_BUILDER = 'buildDataModel';\nexport const TOOL_NAME_RECOMMEND_QUERIES = 'recommendQueries';\nexport const TOOL_NAME_GET_DASHBOARDS = 'getDashboards';\nexport const TOOL_NAME_GET_DATA_SOURCES = 'getDataSources';\nexport const TOOL_NAME_GET_DATA_SOURCE_FIELDS = 'getDataSourceFields';\n\n// limit the number of assets to consider to keep the tool system prompt not too long\nexport const TOOL_CONTEXT_MAX_ASSETS = 10;\n","import { ExtendedChartWidgetProps, BaseChartSummary } from './types';\n\n/**\n * Get a base chart summary from chart props\n * Pure function with no store dependencies\n */\nexport const getBaseChartSummary = (\n\twidgetProps: ExtendedChartWidgetProps,\n\tdataSourceTitle: string,\n): BaseChartSummary => {\n\treturn {\n\t\ttitle: widgetProps.title,\n\t\tdataSourceTitle,\n\t\tchartType: widgetProps.chartType,\n\t\tfilters: 'Filters to be updated',\n\t\tdataOptions: 'Data options to be updated',\n\t\tstyleOptions: 'Style options to be updated',\n\t};\n};\n","import {\n\texcludeSchemaProperties,\n\tfilterSchemaProperties,\n\tzodFunction,\n\tzodToReadableType,\n} from '@/utils/zod-utils';\nimport {\n\tChartSummary,\n\tcreateChartSchema,\n\tupdateChartStyleOptionsSchema,\n\tupdateChartTitleSchema,\n\tupdateChartTypeSchema,\n\tExtendedChartWidgetProps,\n\tupdateChartTypeOfMeasuresSchema,\n\tupdateChartSortingSchema,\n\tupdateTrendAndForecastSchema,\n\tupdateOtherChartDataOptionsSchema,\n\tBuildChartContext,\n\tbuildChartSchema,\n} from './types';\nimport { createChart } from './create-chart/create-chart';\nimport { updateChartTitle } from './update-chart/update-chart-title';\nimport { updateChartType } from './update-chart/update-chart-type';\nimport { updateChartDataOptions } from './update-chart/update-chart-data-options';\nimport { updateChartStyleOptions } from './update-chart/update-chart-style-options';\nimport {\n\tchartDataOptionsSchemas,\n\tchartStyleSchemas,\n} from './update-chart/chart-options-schemas';\nimport { TOOL_CONTEXT_MAX_ASSETS, TOOL_NAME_CHART_BUILDER } from '@/constants';\nimport { getBaseChartSummary } from './chart-builder-service';\nimport z from 'zod';\nimport { createToolsCompletion } from '@/utils/chat-completion-utils';\n\n/**\n * Higher-order function to create a tool with bound context\n * @param originalSchema - The schema for the tool\n * @param name - The name of the tool\n * @param originalFunction - The function to call when the tool is used\n * @param boundContext - The context for the chart builder\n * @returns A zod function for the tool\n */\nconst createChartTool = (\n\toriginalSchema: any,\n\tname: string,\n\tdescription: string,\n\toriginalFunction: any,\n\tboundContext: BuildChartContext,\n) => {\n\treturn zodFunction({\n\t\tschema: originalSchema,\n\t\tname,\n\t\tdescription,\n\t\tfunction: async (params: any, context: any) => {\n\t\t\t// Merge LLM params with bound context params and dependencies\n\t\t\treturn originalFunction(\n\t\t\t\t{ ...params },\n\t\t\t\t{ ...boundContext, ...context },\n\t\t\t);\n\t\t},\n\t});\n};\n\n/**\n * Create a set of tools for the chart builder with injected dependencies\n * @param context - The bound context for the chart builder.\n * @returns A set of tools for the chart builder.\n */\nconst createChartTools = (context: BuildChartContext) => {\n\treturn [\n\t\tcreateChartTool(\n\t\t\tcreateChartSchema,\n\t\t\t'createChart',\n\t\t\t'Create a new chart from user prompt. Use this tool for initial creation OR when adding/removing/swapping data fields (e.g. changing Revenue to Profit). This tool also handles data limits (Top 10, Bottom 5).',\n\t\t\tcreateChart,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTitleSchema,\n\t\t\t'updateChartTitle',\n\t\t\t'Update the title of an existing chart',\n\t\t\tupdateChartTitle,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTypeSchema,\n\t\t\t'updateChartType',\n\t\t\t'Switch the chart type of an existing chart',\n\t\t\tupdateChartType,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTypeOfMeasuresSchema,\n\t\t\t'updateChartTypeOfMeasures',\n\t\t\t`Update the chart type of specific measures within a mixed/combo chart (e.g., make one measure a Bar and another a Line).\n\t\t\n\t\tSee the following options for editing the chart type of existing measures:\n\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, ['column', 'chartType']),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartSortingSchema,\n\t\t\t'updateChartSorting',\n\t\t\t`Update the sorting order (Ascending/Descending) of an existing chart. \n \n IMPORTANT: This tool ONLY handles the sorting order. It does NOT handle data limits or filtering (e.g., \"Top 10\", \"Bottom 5\"). Those constraints must be applied during chart creation or regeneration.\n\t\t\n\t\tSee the following sorting options for editing:\n\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, ['column', 'sortType']),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateTrendAndForecastSchema,\n\t\t\t'updateTrendAndForecast',\n\t\t\t`Update the trend and forecast analysis of existing measures in an existing chart\n\t\t\n\t\tSee the following trend and forecast analysis options for editing:\n\t\t\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, [\n\t\t\t\t\t\t\t'column',\n\t\t\t\t\t\t\t'trend',\n\t\t\t\t\t\t\t'forecast',\n\t\t\t\t\t\t]),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateOtherChartDataOptionsSchema,\n\t\t\t'updateOtherChartDataOptions',\n\t\t\t`Update other data options of an existing chart including visual encodings of axes (x-axis, y-axis, and right y-axis), dimensions, and measures\n\n\t\t\tFor a measure, for example, you can update its color and show it on the right axis.\n\n\t\t\tIMPORTANT: This tool cannot swap data columns (e.g. changing \"Revenue\" to \"Profit\"). Use createChart for that.\n\n\t\t\tSee the following data options for editing:\n\n\t\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\t\texcludeSchemaProperties(value, [\n\t\t\t\t\t\t\t\t'sortType', // Has dedicated sorting tool\n\t\t\t\t\t\t\t\t'trend', // Has dedicated trend/forecast tool\n\t\t\t\t\t\t\t\t'forecast', // Has dedicated trend/forecast tool\n\t\t\t\t\t\t\t\t'chartType', // Has dedicated chartType tool\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t)}`,\n\t\t\t\t)\n\t\t\t\t.join('\\n')}\n\t\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartStyleOptionsSchema,\n\t\t\t'updateChartStyleOptions',\n\t\t\t`Update cosmetic styling options: legend position, axis titles (text), axis label formatting.\n\n\t\t\tSee the following styling options for editing:\n\n\t\t\t${Object.entries(chartStyleSchemas)\n\t\t\t\t.map(([key, value]) => `- ${key}: ${zodToReadableType(value)}`)\n\t\t\t\t.join('\\n')}\n\t\t\t\n\t\t\t`,\n\t\t\tupdateChartStyleOptions,\n\t\t\tcontext,\n\t\t),\n\t];\n};\n\n/**\n * Build contextual system prompt for chart builder\n */\nexport function buildContextualSystemPrompt(chartSummaries: ChartSummary[]) {\n\treturn `You are an intelligent and proactive chart assistant. \nYour role is to create and update a chart based on natural language requests by using the available tools.\n\nIMPORTANT INSTRUCTIONS:\n1. Use the charts and their revisions in the following context to build the chart: ${JSON.stringify(\n\t\t{\n\t\t\tcharts: chartSummaries,\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\n2. Always reference the charts by their IDs instead of their titles.\n\n3. Use the last chart in the context as the current chart unless the user prompt specifies otherwise.\n\n4. If the user prompt involves multiple actions that require different available tools (e.g., sorting, trend and forecast, chart type of measures, and other data options), \nsplit it into multiple prompts. For example, if the user prompt is \"create a new chart showing total revenue by brand, and sort by revenue in descending order\", \nsplit it into two prompts: \"create a new chart showing total revenue by brand\" and \"sort by revenue in descending order\" in step by step.\nIf the prompt can be handled by a single tool, use that tool without splitting the prompt into multiple steps.\n\n5. When responding to changes involving an existing chart:\n - If the prompt involves **adding or removing** chart's data structure such as dimensions, measures, or filters (e.g., \"add revenue\", \"remove date\", \"filter by region\"), do **not** modify the existing chart. Instead, **redo a new chart** with the requested changes in step-by-step prompts.\n - If the prompt involves **enhancing** how existing fields are displayed (e.g., \"sort by revenue in descending order\", \"show cost on the right axis\", \"add trend line\", \"add forecast line\", \"remove trend line\", \"remove forecast line\"), apply the changes **to the existing chart** in step by step.\n\n6. When updating the chart type of existing measures, re-apply the data options and style options changes to the new chart.\n\n`;\n}\n\n/**\n * Standalone chart builder engine - completely decoupled from any UI or store\n * @param params - The parameters for the chart builder\n * @param context - All external dependencies injected\n * @returns The chart summary\n */\nexport async function buildChartEngine(\n\tparams: z.infer<typeof buildChartSchema>,\n\tcontext: BuildChartContext,\n): Promise<ChartSummary> {\n\tconst { dataSourceTitle, userPrompt } = params;\n\n\tconsole.debug(TOOL_NAME_CHART_BUILDER, dataSourceTitle, userPrompt);\n\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\n\tif (!userPrompt) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify textual user input',\n\t\t);\n\t}\n\n\t// use the tool call id as the new chart id\n\tconst newChartId = context.toolCallId;\n\n\tlet savedChartWidgetProps: ExtendedChartWidgetProps | null = null;\n\n\tlet message = '';\n\tlet isError = false;\n\n\tconst updatedContext: BuildChartContext = {\n\t\t...context,\n\t\tdataSourceTitle,\n\t\tretrieveChart: (chartId: string) => {\n\t\t\t// Prioritize savedChartWidgetProps in case of subsequent tool calls\n\t\t\tif (savedChartWidgetProps) {\n\t\t\t\treturn savedChartWidgetProps;\n\t\t\t}\n\t\t\tif (chartId && context.retrieveChart) {\n\t\t\t\treturn context.retrieveChart(chartId);\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsaveChart: (_, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\tcontext.saveChart?.(newChartId, chartWidgetProps);\n\t\t\tsavedChartWidgetProps = chartWidgetProps;\n\t\t},\n\t};\n\n\tconst systemPrompt = buildContextualSystemPrompt(\n\t\t(context.chartSummaries ?? []).slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t);\n\n\tconst internalTools = createChartTools(updatedContext);\n\n\t// Execute orchestration\n\tconst { combinedMessage, isError: isErrorInToolsCompletion } =\n\t\tawait createToolsCompletion({\n\t\t\tsystemPrompt,\n\t\t\tuserPrompt,\n\t\t\ttools: internalTools,\n\t\t});\n\n\tmessage = combinedMessage;\n\tisError = isErrorInToolsCompletion;\n\n\tif (isError) {\n\t\tthrow new Error(message);\n\t}\n\n\treturn {\n\t\tmessage,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tchartId: newChartId,\n\t\tchart: savedChartWidgetProps\n\t\t\t? getBaseChartSummary(savedChartWidgetProps, dataSourceTitle)\n\t\t\t: undefined,\n\t};\n}\n","import { DataSourceSchema } from '@sisense/sdk-data';\nimport { getHttpClient } from '@/singleton-clients';\n\nconst DATA_MODELS_API_URL_PATH = 'api/v2/datamodels';\n\n/**\n * Returns the schema of a data source by its name.\n */\nexport async function getDataSourceSchema(\n\tdataSourceName: string,\n): Promise<DataSourceSchema | null> {\n\tconst httpClient = getHttpClient();\n\tconst url = `${DATA_MODELS_API_URL_PATH}/schema?title=${encodeURIComponent(\n\t\tdataSourceName,\n\t)}`;\n\tconst result = await httpClient.get<DataSourceSchema>(url);\n\treturn result ?? null;\n}\n","import {\n\tDataSourceField,\n\tDateLevels,\n\tnormalizeName,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport { getDataSourceSchema } from '@/services/data-models/data-models-service';\nimport { getHttpClient } from '@/singleton-clients';\n\nexport const DATA_SOURCES_API_URL_PATH = 'api/datasources';\n\n/**\n * Data source schema table\n */\ntype DataSourceSchemaTable = {\n\tname: string;\n\tcolumns: {\n\t\tname: string;\n\t\tdescription: string | null;\n\t}[];\n};\n\n/**\n * Data source schema table\n */\ntype DataSourceSchemaDataset = {\n\tschema: {\n\t\ttables: DataSourceSchemaTable[];\n\t};\n};\n\nexport type DataSourceFieldWithDescription = DataSourceField & {\n\tdescription?: string;\n\ttableDescription?: string;\n};\n\nexport type NormalizedDataSourceField = {\n\ttable: string;\n\tcolumn: string;\n\ttype: string;\n\tlevel?: string;\n\texpression: string;\n\tdescription: string;\n};\n\n/**\n * Add 'description' property from datasource schema columns to datasource fields\n */\nfunction addDescriptionToFields(\n\tfields: DataSourceField[],\n\tdatasets: DataSourceSchemaDataset[],\n): DataSourceFieldWithDescription[] {\n\tconst schemaDataDescriptionsMap = datasets.reduce(\n\t\t(map: Record<string, Record<string, string | null>>, dataset) => {\n\t\t\tdataset.schema.tables.forEach((table) => {\n\t\t\t\tmap[table.name] = {};\n\t\t\t\ttable.columns.forEach((column) => {\n\t\t\t\t\tmap[table.name][column.name] = column.description;\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn map;\n\t\t},\n\t\t{},\n\t);\n\n\treturn fields.map((field) => ({\n\t\t...field,\n\t\tdescription:\n\t\t\tschemaDataDescriptionsMap[field.table]?.[field.column] || '',\n\t})) as DataSourceFieldWithDescription[];\n}\n\n/**\n * Get all data sources\n */\nexport async function getDataSources(): Promise<JaqlDataSourceForDto[]> {\n\tconst httpClient = getHttpClient();\n\tconst url = `${DATA_SOURCES_API_URL_PATH}/?sharedWith=r,w`;\n\tconst result = await httpClient.get<JaqlDataSourceForDto[]>(url);\n\treturn result || [];\n}\n\n/**\n * Get a data source by title\n */\nexport async function getDataSourceByTitle(\n\tdataSourceTitle: string,\n): Promise<JaqlDataSourceForDto | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.get<JaqlDataSourceForDto>(\n\t\t`${DATA_SOURCES_API_URL_PATH}/${encodeURIComponent(dataSourceTitle)}`,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Get data source fields\n */\nexport async function getDataSourceFields(\n\tdataSourceTitle: string,\n): Promise<DataSourceField[] | null> {\n\tconst httpClient = getHttpClient();\n\treturn httpClient\n\t\t.post<DataSourceField[]>(\n\t\t\t`${DATA_SOURCES_API_URL_PATH}/${encodeURIComponent(\n\t\t\t\tdataSourceTitle,\n\t\t\t)}/fields/search`,\n\t\t\t{\n\t\t\t\toffset: 0,\n\t\t\t\tcount: 9999,\n\t\t\t},\n\t\t)\n\t\t.then((result) => result ?? null);\n}\n\n/**\n * Get data source fields with descriptions from schema\n */\nexport async function getDataSourceFieldsWithDescriptions(\n\tdataSourceTitle: string,\n): Promise<DataSourceFieldWithDescription[] | DataSourceField[]> {\n\tconst fields = await getDataSourceFields(dataSourceTitle);\n\tif (!fields) return [];\n\n\ttry {\n\t\t// get the schema of the data source to add descriptions to the fields\n\t\tconst dataSourceSchema = await getDataSourceSchema(dataSourceTitle);\n\t\treturn dataSourceSchema?.datasets\n\t\t\t? addDescriptionToFields(\n\t\t\t\t\tfields,\n\t\t\t\t\tdataSourceSchema.datasets as DataSourceSchemaDataset[],\n\t\t\t )\n\t\t\t: fields;\n\t} catch (error) {\n\t\t// Normalize various error shapes (fetch, axios, custom)\n\t\tconst err: any = error as any;\n\t\tconst status = err?.status ?? err?.statusCode ?? err?.response?.status;\n\n\t\t// Not found: schema endpoint missing in some deployments or hidden by permissions.\n\t\tif ((status === 404 || status === '404') && fields.length) {\n\t\t\treturn fields;\n\t\t}\n\n\t\t// Unauthorized / Forbidden: user lacks permission to read schema. Fall back to fields without descriptions.\n\t\tif (\n\t\t\tstatus === 401 ||\n\t\t\tstatus === '401' ||\n\t\t\tstatus === 403 ||\n\t\t\tstatus === '403'\n\t\t) {\n\t\t\tconsole.log(\n\t\t\t\t`Note: Field descriptions are omitted from the data model due to restricted role of your account`,\n\t\t\t);\n\t\t\treturn fields;\n\t\t}\n\n\t\t// Unknown error shape — rethrow to surface real issues instead of masking them.\n\t\tthrow error;\n\t}\n}\n\n/**\n * Normalize data source fields (pure function - easily testable)\n */\nexport function normalizeFields(\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[],\n): NormalizedDataSourceField[] {\n\tconst normalizedFields: NormalizedDataSourceField[] = [];\n\n\tfields.forEach((field) => {\n\t\tconst normalizedName = normalizeName(field.column);\n\t\tconst baseField = {\n\t\t\ttable: normalizeName(field.table),\n\t\t\tcolumn: normalizedName,\n\t\t\ttype: field.dimtype,\n\t\t\texpression: field.id,\n\t\t\tdescription: field.description || `${field.table}.${field.column}`,\n\t\t};\n\n\t\tnormalizedFields.push(baseField);\n\n\t\tif (field.dimtype === 'datetime') {\n\t\t\t// Add fields for each date level\n\t\t\tDateLevels.all.forEach((level) => {\n\t\t\t\tnormalizedFields.push({\n\t\t\t\t\t...baseField,\n\t\t\t\t\tcolumn: `${normalizedName}.${level}`,\n\t\t\t\t\ttype: 'datetime',\n\t\t\t\t\tlevel: level,\n\t\t\t\t\texpression: field.id,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\tfield.description ||\n\t\t\t\t\t\t`${field.table}.${field.column}.${level}`,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n\n\treturn normalizedFields;\n}\n\n/**\n * Get normalized data source fields\n * @param dataSourceTitle - The title of the data source\n * @param getFieldsFn - Optional function to get fields (for testing)\n */\nexport async function getNormalizedDataSourceFields(\n\tdataSourceTitle: string,\n\tgetFieldsFn: (\n\t\ttitle: string,\n\t) => Promise<\n\t\tDataSourceFieldWithDescription[] | DataSourceField[]\n\t> = getDataSourceFieldsWithDescriptions,\n): Promise<NormalizedDataSourceField[]> {\n\tconst fields = await getFieldsFn(dataSourceTitle);\n\treturn normalizeFields(fields);\n}\n","import { z } from 'zod';\nimport { getDataSources } from '@/services/data-sources/data-sources-service';\nimport { TOOL_NAME_GET_DATA_SOURCES } from '@/constants';\nimport {\n\tgetDataSourcesSchema,\n\tGetDataSourcesContext,\n\tDataSourcesResult,\n} from './types';\n\n/**\n * Standalone data sources engine - completely decoupled from any UI or store\n * @param params - The parameters for getting data sources (currently empty)\n * @param context - Context with tool call ID for tracking\n * @returns The data sources summary with titles and full objects\n */\nexport async function getDataSourcesEngine(\n\tparams: z.infer<typeof getDataSourcesSchema>,\n\tcontext: GetDataSourcesContext,\n): Promise<DataSourcesResult> {\n\tconsole.debug(TOOL_NAME_GET_DATA_SOURCES, context.toolCallId);\n\n\tconst dataSources = await getDataSources();\n\n\treturn {\n\t\tdataSourceTitles: dataSources.map((ds) => ds.title),\n\t\tdataSources: dataSources,\n\t};\n}\n","import { z } from 'zod';\nimport { JaqlDataSourceForDto } from '@sisense/sdk-data';\n\n/**\n * Schema for getDataSources engine parameters\n */\nexport const getDataSourcesSchema = z.object({});\n\n/**\n * Context interface for getDataSourcesEngine\n */\nexport interface GetDataSourcesContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n}\n\n/**\n * Result from getDataSourcesEngine\n */\nexport interface DataSourcesResult {\n\t/**\n\t * List of data source titles\n\t */\n\tdataSourceTitles: string[];\n\t/**\n\t * Full data source objects\n\t */\n\tdataSources: JaqlDataSourceForDto[];\n}\n","import { z } from 'zod';\nimport { getDataSourceFieldsWithDescriptions } from '@/services/data-sources/data-sources-service';\nimport { TOOL_NAME_GET_DATA_SOURCE_FIELDS } from '@/constants';\nimport {\n\tgetDataSourceFieldsSchema,\n\tGetDataSourceFieldsContext,\n\tDataSourceFieldsResult,\n} from './types';\n\n/**\n * Standalone data source fields engine - completely decoupled from any UI or store\n * @param params - The parameters containing the data source title\n * @param context - Context with tool call ID for tracking\n * @returns The data source fields summary with title and fields\n */\nexport async function getDataSourceFieldsEngine(\n\tparams: z.infer<typeof getDataSourceFieldsSchema>,\n\tcontext: GetDataSourceFieldsContext,\n): Promise<DataSourceFieldsResult> {\n\tconst { dataSourceTitle } = params;\n\n\tconsole.debug(\n\t\tTOOL_NAME_GET_DATA_SOURCE_FIELDS,\n\t\tdataSourceTitle,\n\t\tcontext.toolCallId,\n\t);\n\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\n\tconst fields = await getDataSourceFieldsWithDescriptions(dataSourceTitle);\n\n\treturn {\n\t\tdataSourceTitle,\n\t\tfields: fields || [],\n\t};\n}\n","import { z } from 'zod';\nimport { DataSourceField } from '@sisense/sdk-data';\nimport { DataSourceFieldWithDescription } from '@/services/data-sources/data-sources-service';\n\n/**\n * Schema for getDataSourceFields engine parameters\n */\nexport const getDataSourceFieldsSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n});\n\n/**\n * Context interface for getDataSourceFieldsEngine\n */\nexport interface GetDataSourceFieldsContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n}\n\n/**\n * Result from getDataSourceFieldsEngine\n */\nexport interface DataSourceFieldsResult {\n\t/**\n\t * The title of the data source\n\t */\n\tdataSourceTitle: string;\n\t/**\n\t * List of fields (may or may not have descriptions depending on availability)\n\t */\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[];\n}\n","import {\n\tdashboardModelTranslator,\n\tDashboardProps,\n\tisChartWidgetProps,\n\ttranslateFiltersAndRelationsToDto,\n\tWidgetDto,\n\twidgetModelTranslator,\n\tWidgetProps,\n\tWidgetsPanelColumnLayout,\n\tDashboardDto,\n\tgetDashboardModel,\n} from '@sisense/sdk-ui';\nimport { getDataSourceByTitle } from '@/services/data-sources/data-sources-service';\nimport { getHttpClient } from '@/singleton-clients';\nimport { normalizeUrl } from '@/utils/utils';\nimport {\n\tconvertJaqlDataSourceForDto,\n\tFilter,\n\tFilterRelations,\n\tisDataSourceInfo,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\n\nconst FUSION_DASHBOARDS_API_URL_PATH = 'api/v1/dashboards';\n\ntype GetDashboardsOptions = {\n\tsearchByTitle?: string;\n\tfields?: string[];\n\texpand?: string[];\n};\n\nexport type Dashboard = {\n\tdashboardId: string;\n\tdashboardTitle: string;\n\tdataSourceTitle: string;\n};\n\nexport function getFusionDashboardUrl(dashboardOid: string): string {\n\tconst httpClient = getHttpClient();\n\treturn `${normalizeUrl(httpClient.url)}app/main/dashboards/${dashboardOid}`;\n}\n\n/**\n * Get all dashboards\n */\nexport async function getFusionDashboards(\n\toptions: GetDashboardsOptions = {},\n): Promise<DashboardDto[]> {\n\tconst httpClient = getHttpClient();\n\tconst { fields, expand, searchByTitle } = options;\n\tconst queryParams = new URLSearchParams({\n\t\t...(searchByTitle && { name: searchByTitle }),\n\t\t...(fields?.length && { fields: fields?.join(',') }),\n\t\t...(expand?.length && { expand: expand?.join(',') }),\n\t}).toString();\n\n\tconst dashboards = await httpClient.get<DashboardDto[]>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}?${queryParams}`,\n\t);\n\n\tif (!dashboards) return [];\n\n\treturn dashboards;\n}\n\n/**\n * Get all widgets of a specific dashboard\n */\nexport async function getFusionDashboardWidgets(\n\tdashboardOid: string,\n): Promise<WidgetDto[]> {\n\tconst httpClient = getHttpClient();\n\ttry {\n\t\tconst widgets = await httpClient.get<WidgetDto[]>(\n\t\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets`,\n\t\t);\n\t\treturn widgets ?? [];\n\t} catch {\n\t\t// when error is encountered, API may return only status code 422 without informative error message\n\t\t// to remedy, catch error and throw a more informative error message\n\t\tthrow new Error(\n\t\t\t'Failed to retrieve dashboard widgets. Please make sure the dashboard exists and is accessible.',\n\t\t);\n\t}\n}\n\n/**\n * Get dashboard model from Fusion\n */\nexport async function getFusionDashboardModel(dashboardOid: string) {\n\tconst httpClient = getHttpClient();\n\treturn await getDashboardModel(httpClient, dashboardOid, {\n\t\tincludeWidgets: true,\n\t\tincludeFilters: true,\n\t});\n}\n\n/**\n * Partially update a dashboard\n */\nexport async function patchFusionDashboard(\n\tdashboardOid: string,\n\tdashboard: Partial<DashboardDto>,\n): Promise<DashboardDto | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.patch<DashboardDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}`,\n\t\tdashboard,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Add widget to a dashboard\n */\nexport async function addWidgetToFusionDashboard(\n\tdashboardOid: string,\n\twidgetDto: WidgetDto,\n): Promise<WidgetDto | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.post<WidgetDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets`,\n\t\twidgetDto,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Create an empty dashboard\n */\nexport async function createEmptyFusionDashboard(\n\tdashboardTitle: string,\n\tdataSource: JaqlDataSourceForDto,\n): Promise<DashboardDto | null> {\n\tconst httpClient = getHttpClient();\n\tconst result = await httpClient.post<DashboardDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}`,\n\t\t{\n\t\t\ttitle: dashboardTitle,\n\t\t\tdatasource: dataSource,\n\t\t\tsettings: { managedByTool: 'studio-assistant' },\n\t\t},\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Delete a dashboard\n */\nexport function deleteFusionDashboard(dashboardOid: string): Promise<void> {\n\tconst httpClient = getHttpClient();\n\treturn httpClient.delete(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}`,\n\t);\n}\n\n/**\n * Delete a widget from a dashboard\n */\nfunction deleteWidgetFromFusionDashboard(\n\tdashboardOid: string,\n\twidgetOid: string,\n): Promise<void> {\n\tconst httpClient = getHttpClient();\n\treturn httpClient.delete(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets/${widgetOid}`,\n\t);\n}\n\n/**\n * Translate layout to DTO format\n */\nfunction translateToLayoutDto(layout: WidgetsPanelColumnLayout) {\n\treturn {\n\t\tcolumns: layout.columns.map((c) => ({\n\t\t\twidth: c.widthPercentage,\n\t\t\tcells: c.rows.map((r) => ({\n\t\t\t\tsubcells: r.cells.map((cell) => ({\n\t\t\t\t\twidth: cell.widthPercentage,\n\t\t\t\t\telements: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theight: cell.height ?? 384,\n\t\t\t\t\t\t\twidgetid: cell.widgetId,\n\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\tminWidth: 200,\n\t\t\t\t\t\t\tmaxWidth: 2000,\n\t\t\t\t\t\t\tminHeight: 200,\n\t\t\t\t\t\t\tmaxHeight: 2000,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t})),\n\t\t\t})),\n\t\t})),\n\t};\n}\n\n/**\n * Get available Fusion dashboards (filtered by studio-assistant)\n */\nexport async function getAvailableFusionDashboards(): Promise<Dashboard[]> {\n\tconst dashboardDtos = await getFusionDashboards({\n\t\tfields: ['title', 'oid', 'datasource', 'settings'],\n\t});\n\tconst dashboards: Dashboard[] = dashboardDtos\n\t\t// TEMP: For public preview, show only dashboards managed by the studio assistant\n\t\t.filter(\n\t\t\t(dashboard) =>\n\t\t\t\tdashboard.settings?.managedByTool === 'studio-assistant',\n\t\t)\n\t\t.map((dashboard) => ({\n\t\t\tdashboardTitle: dashboard.title,\n\t\t\tdashboardId: dashboard.oid,\n\t\t\tdataSourceTitle: dashboard.datasource.title,\n\t\t}));\n\n\treturn dashboards;\n}\n\n/**\n * Get Fusion dashboard props\n */\nexport async function getFusionDashboardProps(\n\tdashboardOid: string,\n): Promise<DashboardProps | undefined> {\n\tconst dashboardModel = await getFusionDashboardModel(dashboardOid);\n\t// TEMP: For public preview, show only dashboards created by the studio assistant\n\tif (\n\t\tdashboardModel &&\n\t\tdashboardModel.settings?.managedByTool !== 'studio-assistant'\n\t) {\n\t\treturn undefined;\n\t}\n\treturn dashboardModel\n\t\t? dashboardModelTranslator.toDashboardProps(dashboardModel)\n\t\t: undefined;\n}\n\n/**\n * Load existing dashboard from Fusion\n */\nexport async function loadExistingDashboardFromFusion(\n\tdashboardId: string,\n): Promise<DashboardProps> {\n\tconst fusionDashboardProps = await getFusionDashboardProps(dashboardId);\n\tif (!fusionDashboardProps) {\n\t\tthrow new Error(\n\t\t\t'Dashboard not available for editing. Please specify a different dashboard.',\n\t\t);\n\t}\n\treturn fusionDashboardProps;\n}\n\n/**\n * Add widgets to Fusion dashboard\n */\nexport async function addWidgetsToFusionDashboard(\n\tdashboardOid: string,\n\twidgetsToAdd: WidgetProps[],\n): Promise<WidgetDto[]> {\n\tif (widgetsToAdd.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst widgetDtos = widgetsToAdd.map((widgetProps) => {\n\t\tconst widgetModel = widgetModelTranslator.fromWidgetProps(widgetProps);\n\t\tconst dataSource =\n\t\t\tisChartWidgetProps(widgetProps) && widgetProps.dataSource\n\t\t\t\t? convertJaqlDataSourceForDto(widgetProps.dataSource)\n\t\t\t\t: undefined;\n\t\treturn widgetModelTranslator.toWidgetDto(widgetModel, dataSource);\n\t});\n\n\t// Create array of promises while preserving order\n\tconst widgetPromises = widgetDtos.map((widgetDto, index) =>\n\t\taddWidgetToFusionDashboard(dashboardOid, widgetDto).then((result) => ({\n\t\t\tindex,\n\t\t\tresult,\n\t\t})),\n\t);\n\t// await is needed so we can align widget OIDs with input widgets later\n\tconst results = await Promise.all(widgetPromises);\n\t// Sort results by original index to maintain order\n\tconst updatedWidgetDtos = results\n\t\t.sort((a, b) => a.index - b.index)\n\t\t.map((r) => r.result)\n\t\t.filter((dto): dto is WidgetDto => dto !== undefined);\n\n\treturn updatedWidgetDtos;\n}\n\n/**\n * Update Fusion dashboard filters\n */\nexport async function updateFusionDashboardFilters(\n\tdashboardOid: string,\n\tfiltersToUpdate: Filter[] | FilterRelations,\n) {\n\tconst filtersDto = translateFiltersAndRelationsToDto(filtersToUpdate);\n\tawait patchFusionDashboard(dashboardOid, filtersDto);\n}\n\n/**\n * Check if dashboard is saved\n */\nexport function isDashboardSaved(dashboardProps: DashboardProps): boolean {\n\treturn !!dashboardProps.id;\n}\n\n/**\n * Persist dashboard to Fusion\n */\nexport async function persistDashboardToFusion(\n\tdashboardProps: DashboardProps,\n): Promise<DashboardProps> {\n\tconst dataSource = dashboardProps.defaultDataSource;\n\n\tif (!dataSource) {\n\t\tthrow new Error('Dashboard must have a data source');\n\t}\n\n\tconst dataSourceTitle = isDataSourceInfo(dataSource)\n\t\t? dataSource.title\n\t\t: dataSource;\n\n\tconst jaqlDataSource = await getDataSourceByTitle(dataSourceTitle);\n\n\tif (!jaqlDataSource) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Please ask the user to specify a valid data source.',\n\t\t);\n\t}\n\n\tlet dashboardOid: string;\n\tlet dashboardTitle: string =\n\t\tdashboardProps.title || `Dashboard for ${dataSourceTitle}`;\n\n\tif (dashboardProps.id) {\n\t\tdashboardOid = dashboardProps.id;\n\t\ttry {\n\t\t\t// Dashboard already exists in Fusion - update it\n\t\t\tawait patchFusionDashboard(dashboardProps.id, {\n\t\t\t\ttitle: dashboardTitle,\n\t\t\t});\n\t\t\t// and delete all existing widgets in parallel to re-populate them later\n\t\t\tconst existingWidgetDtos = await getFusionDashboardWidgets(\n\t\t\t\tdashboardOid,\n\t\t\t);\n\t\t\tif (existingWidgetDtos) {\n\t\t\t\tawait Promise.all(\n\t\t\t\t\texistingWidgetDtos.map((widgetDto) =>\n\t\t\t\t\t\tdeleteWidgetFromFusionDashboard(\n\t\t\t\t\t\t\tdashboardOid,\n\t\t\t\t\t\t\twidgetDto.oid,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\t// If dashboard not found (404), create a new one instead\n\t\t\tif (error?.status === '404' || error?.status === 404) {\n\t\t\t\tconst fusionDashboardDto = await createEmptyFusionDashboard(\n\t\t\t\t\tdashboardTitle,\n\t\t\t\t\tjaqlDataSource,\n\t\t\t\t);\n\t\t\t\tif (!fusionDashboardDto) {\n\t\t\t\t\tthrow new Error('Error: Failed to create Fusion dashboard');\n\t\t\t\t}\n\t\t\t\tdashboardOid = fusionDashboardDto.oid;\n\t\t\t\tdashboardTitle = fusionDashboardDto.title;\n\t\t\t} else {\n\t\t\t\t// Re-throw other errors\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dashboard doesn't exist in Fusion yet - create it\n\t\tconst fusionDashboardDto = await createEmptyFusionDashboard(\n\t\t\tdashboardTitle,\n\t\t\tjaqlDataSource,\n\t\t);\n\t\tif (!fusionDashboardDto) {\n\t\t\tthrow new Error('Error: Failed to create Fusion dashboard');\n\t\t}\n\t\tdashboardOid = fusionDashboardDto.oid;\n\t\tdashboardTitle = fusionDashboardDto.title;\n\t}\n\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tid: dashboardOid,\n\t\ttitle: dashboardTitle,\n\t};\n\n\t// Add widgets to the Fusion dashboard\n\tconst updatedWidgetDtos = await addWidgetsToFusionDashboard(\n\t\tdashboardOid,\n\t\tdashboardProps.widgets,\n\t);\n\n\t// update IDs of updated widget Dtos to input widgets\n\tconst updatedWidgets = dashboardProps.widgets.map((widget, index) => ({\n\t\t...widget,\n\t\tid: updatedWidgetDtos[index]?.oid ?? widget.id,\n\t\toldId: widget.id,\n\t}));\n\n\t// iterate through columns and cells in dashboardProps.layoutOptions.widgetsPanel\n\t// and update the widgetId of each cell to the id of the widget in updatedWidgets\n\tconst updatedWidgetsLayout = dashboardProps.layoutOptions?.widgetsPanel\n\t\t? {\n\t\t\t\t...dashboardProps.layoutOptions.widgetsPanel,\n\t\t\t\tcolumns: dashboardProps.layoutOptions.widgetsPanel.columns.map(\n\t\t\t\t\t(column) => ({\n\t\t\t\t\t\t...column,\n\t\t\t\t\t\trows: column.rows.map((row) => ({\n\t\t\t\t\t\t\t...row,\n\t\t\t\t\t\t\tcells: row.cells.map((cell) => ({\n\t\t\t\t\t\t\t\t...cell,\n\t\t\t\t\t\t\t\twidgetId:\n\t\t\t\t\t\t\t\t\tupdatedWidgets.find(\n\t\t\t\t\t\t\t\t\t\t(w) => w.oldId === cell.widgetId,\n\t\t\t\t\t\t\t\t\t)?.id || cell.widgetId,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t})),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t }\n\t\t: dashboardProps.layoutOptions?.widgetsPanel;\n\n\t// Update layout\n\tif (updatedWidgetsLayout) {\n\t\tawait patchFusionDashboard(dashboardOid, {\n\t\t\tlayout: translateToLayoutDto(updatedWidgetsLayout),\n\t\t});\n\t}\n\n\t// Update filters\n\tawait updateFusionDashboardFilters(\n\t\tdashboardOid,\n\t\tdashboardProps.filters ?? [],\n\t);\n\n\treturn {\n\t\t...updatedDashboardProps,\n\t\twidgets: updatedWidgets,\n\t\tlayoutOptions: { widgetsPanel: updatedWidgetsLayout },\n\t};\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","import {\n\tDashboardChangeEvent,\n\tDashboardConfig,\n\tDashboardProps,\n\tWidgetProps,\n\tWidgetsPanelColumnLayout,\n\tWidgetsPanelLayout,\n} from '@sisense/sdk-ui';\nimport { getDataSourceByTitle } from '@/services/data-sources/data-sources-service';\nimport {\n\tconvertDataSource,\n\tconvertJaqlDataSourceForDto,\n\tFilter,\n\tFilterRelations,\n\tisDataSourceInfo,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport deepEq from 'fast-deep-equal';\nimport { nanoidHex } from '@/utils/id-utils';\n\n// Exported types and enums (remain outside the class)\nexport type DashboardChangeResult = {\n\tchanged: boolean;\n\tupdatedDashboardProps: DashboardProps;\n};\n\n// Core layout utilities (pure functions)\n\n/**\n * Extract widget IDs from layout structure\n */\nexport function extractWidgetIdsFromLayout(\n\tlayout: WidgetsPanelColumnLayout,\n): string[] {\n\treturn layout.columns.flatMap((column) =>\n\t\tcolumn.rows.flatMap((row) => row.cells.map((cell) => cell.widgetId)),\n\t);\n}\n\n/**\n * Remove cells that reference non-existent widgets, empty rows, and empty columns\n */\nexport function cleanupOrphanedCells(\n\tlayout: WidgetsPanelColumnLayout,\n\texistingWidgetIds: Set<string>,\n): WidgetsPanelColumnLayout {\n\tconst cleanedColumns = layout.columns\n\t\t.map((column) => ({\n\t\t\t...column,\n\t\t\trows: column.rows\n\t\t\t\t.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tcells: row.cells.filter((cell) =>\n\t\t\t\t\t\texistingWidgetIds.has(cell.widgetId),\n\t\t\t\t\t),\n\t\t\t\t}))\n\t\t\t\t.filter((row) => row.cells.length > 0), // Remove empty rows\n\t\t}))\n\t\t.filter((column) => column.rows.length > 0); // Remove empty columns\n\n\treturn cleanedColumns.length > 0\n\t\t? { columns: cleanedColumns }\n\t\t: { columns: [] };\n}\n\n/**\n * Set width to 100% if layout has only one column\n */\nexport function adjustSingleColumnWidth(\n\tlayout: WidgetsPanelColumnLayout,\n): WidgetsPanelColumnLayout {\n\tif (layout.columns.length === 1) {\n\t\treturn {\n\t\t\t...layout,\n\t\t\tcolumns: [\n\t\t\t\t{\n\t\t\t\t\t...layout.columns[0],\n\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn layout;\n}\n\n/**\n * Find widgets that exist in dashboard but not in layout\n */\nexport function findOutOfPlaceWidgets(\n\twidgets: WidgetProps[],\n\tlayout: WidgetsPanelColumnLayout | undefined,\n): string[] {\n\tif (!layout) {\n\t\treturn [];\n\t}\n\n\tconst widgetsInLayout = extractWidgetIdsFromLayout(layout);\n\treturn widgets\n\t\t.filter((widget) => !widgetsInLayout.includes(widget.id))\n\t\t.map((widget) => widget.id);\n}\n\n/**\n * Orchestrate all cleanup steps after any dashboard change\n */\nexport function cleanupDashboardAfterChange(\n\tdashboardProps: DashboardProps,\n): DashboardChangeResult {\n\tlet updatedProps = { ...dashboardProps };\n\n\t// Find and remove out-of-place widgets\n\tconst outOfPlaceWidgetIds = findOutOfPlaceWidgets(\n\t\tupdatedProps.widgets,\n\t\tupdatedProps.layoutOptions?.widgetsPanel,\n\t);\n\tif (outOfPlaceWidgetIds.length > 0) {\n\t\tupdatedProps = deleteWidgetsFromDashboard(\n\t\t\tupdatedProps,\n\t\t\toutOfPlaceWidgetIds,\n\t\t);\n\t}\n\n\t// Clean up orphaned cells in layout\n\tif (updatedProps.layoutOptions?.widgetsPanel) {\n\t\tconst existingWidgetIds = new Set(\n\t\t\tupdatedProps.widgets.map((widget) => widget.id),\n\t\t);\n\t\tlet cleanedLayout = cleanupOrphanedCells(\n\t\t\tupdatedProps.layoutOptions.widgetsPanel,\n\t\t\texistingWidgetIds,\n\t\t);\n\t\tcleanedLayout = adjustSingleColumnWidth(cleanedLayout);\n\n\t\tupdatedProps = {\n\t\t\t...updatedProps,\n\t\t\tlayoutOptions: {\n\t\t\t\t...updatedProps.layoutOptions,\n\t\t\t\twidgetsPanel: cleanedLayout,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { changed: true, updatedDashboardProps: updatedProps };\n}\n\n/**\n * Handle filters update\n */\nfunction handleFiltersUpdate(\n\tdashboardProps: DashboardProps,\n\tfilters: Filter[] | FilterRelations,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tfilters,\n\t\t},\n\t};\n}\n\n/**\n * Handle filters panel collapse state change\n */\nfunction handleFiltersPanelCollapse(\n\tdashboardProps: DashboardProps,\n\tcollapsed: boolean,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tconfig: {\n\t\t\t\t...dashboardProps.config,\n\t\t\t\tfiltersPanel: {\n\t\t\t\t\t...dashboardProps.config?.filtersPanel,\n\t\t\t\t\tcollapsedInitially: collapsed,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Handle widgets panel layout update\n */\nfunction handleWidgetsPanelLayoutUpdate(\n\tdashboardProps: DashboardProps,\n\tlayout: WidgetsPanelLayout,\n): DashboardChangeResult {\n\t// somehow CSDK triggers the layout action after the layout is applied\n\t// and causing infinite re-renders. This is a quick fix to avoid that.\n\tif (deepEq(layout, dashboardProps.layoutOptions?.widgetsPanel)) {\n\t\treturn { changed: false, updatedDashboardProps: dashboardProps };\n\t}\n\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tlayoutOptions: {\n\t\t\t\t...dashboardProps.layoutOptions,\n\t\t\t\twidgetsPanel: layout,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Handle widgets deletion\n */\nfunction handleWidgetsDelete(\n\tdashboardProps: DashboardProps,\n\twidgetIds: string[],\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: deleteWidgetsFromDashboard(\n\t\t\tdashboardProps,\n\t\t\twidgetIds,\n\t\t),\n\t};\n}\n\n/**\n * Handle widgets panel layout isEditing change\n */\nfunction handleWidgetsPanelLayoutIsEditingChange(\n\tdashboardProps: DashboardProps,\n\tisEditing: boolean,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tconfig: {\n\t\t\t\t...dashboardProps.config,\n\t\t\t\twidgetsPanel: {\n\t\t\t\t\t...dashboardProps.config?.widgetsPanel,\n\t\t\t\t\teditMode: {\n\t\t\t\t\t\t...dashboardProps.config?.widgetsPanel?.editMode,\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tisEditing,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport function getDashboardDataSourcesMap(\n\tdashboardProps: DashboardProps,\n): Map<string, JaqlDataSourceForDto> {\n\tconst dataSourcesMap = new Map<string, JaqlDataSourceForDto>();\n\tconst { widgets, defaultDataSource } = dashboardProps;\n\n\tif (defaultDataSource && isDataSourceInfo(defaultDataSource)) {\n\t\tdataSourcesMap.set(\n\t\t\tdefaultDataSource.title,\n\t\t\tconvertJaqlDataSourceForDto(defaultDataSource),\n\t\t);\n\t}\n\twidgets.forEach((widget) => {\n\t\tif (\n\t\t\t'dataSource' in widget &&\n\t\t\twidget.dataSource &&\n\t\t\tisDataSourceInfo(widget.dataSource)\n\t\t) {\n\t\t\tconst dataSourceTitle = widget.dataSource.title;\n\t\t\tif (!dataSourcesMap.has(dataSourceTitle)) {\n\t\t\t\tdataSourcesMap.set(\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tconvertJaqlDataSourceForDto(widget.dataSource),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn dataSourcesMap;\n}\n\nexport function layoutDashboardWidgets(\n\twidgetOids: string[],\n): WidgetsPanelColumnLayout {\n\tconst widgetsLayout: WidgetsPanelColumnLayout =\n\t\twidgetOids.length === 1\n\t\t\t? {\n\t\t\t\t\t// use a 1-column layout\n\t\t\t\t\tcolumns: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\trows: widgetOids.map((widgetOid) => ({\n\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\t// use a 2-column layout\n\t\t\t\t\tcolumns: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 50,\n\t\t\t\t\t\t\trows: widgetOids\n\t\t\t\t\t\t\t\t.filter((_, index) => index % 2 === 0)\n\t\t\t\t\t\t\t\t.map((widgetOid) => ({\n\t\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 50,\n\t\t\t\t\t\t\trows: widgetOids\n\t\t\t\t\t\t\t\t.filter((_, index) => index % 2 !== 0)\n\t\t\t\t\t\t\t\t.map((widgetOid) => ({\n\t\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t };\n\treturn widgetsLayout;\n}\n\n/**\n * Adds a widget to a new row in the column with the smallest number of rows and returns the updated layout.\n *\n * @param layout - The dashboard layout object to modify.\n * @param widgetId - The ID of the widget to add to the new row.\n * @returns The updated layout object with the new widget added.\n */\nexport function withWidgetAdded(\n\tlayout: WidgetsPanelColumnLayout,\n\twidgetId: string,\n): WidgetsPanelColumnLayout {\n\t// Create a new cell with the widgetId\n\tconst newCell = {\n\t\twidthPercentage: 100, // Assuming the new cell takes the full width of the row\n\t\theight: '400px',\n\t\twidgetId: widgetId,\n\t};\n\n\t// Create a new row and add the new cell to it\n\tconst newRow = {\n\t\tcells: [newCell],\n\t};\n\n\t// If there are no columns, create the first column\n\tif (!layout.columns || layout.columns.length === 0) {\n\t\treturn {\n\t\t\t...(layout || { columns: [] }),\n\t\t\tcolumns: [\n\t\t\t\t{\n\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\trows: [newRow],\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t// Find the index of the column with the smallest number of rows\n\tlet minRows = layout.columns[0].rows.length;\n\tlet minIndex = 0;\n\tfor (let i = 1; i < layout.columns.length; i++) {\n\t\tif (layout.columns[i].rows.length < minRows) {\n\t\t\tminRows = layout.columns[i].rows.length;\n\t\t\tminIndex = i;\n\t\t}\n\t}\n\n\t// Clone the layout to avoid mutating the original object\n\treturn {\n\t\t...(layout || { columns: [] }),\n\t\tcolumns: layout.columns.map((column, index) =>\n\t\t\tindex === minIndex\n\t\t\t\t? { ...column, rows: [...column.rows, newRow] }\n\t\t\t\t: column,\n\t\t),\n\t};\n}\n\nexport function getBaseDashboardConfig(): DashboardConfig {\n\treturn {\n\t\ttoolbar: { visible: true },\n\t\twidgetsPanel: {\n\t\t\tresponsive: true,\n\t\t\teditMode: {\n\t\t\t\tenabled: true,\n\t\t\t\tisEditing: true,\n\t\t\t\tapplyChangesAsBatch: {\n\t\t\t\t\tenabled: false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tfiltersPanel: {\n\t\t\tvisible: true,\n\t\t\tcollapsedInitially: false,\n\t\t\tactions: {\n\t\t\t\taddFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t\teditFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t\tdeleteFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction getBaseDashboardProps(): DashboardProps {\n\tconst dashboardProps: DashboardProps = {\n\t\ttitle: 'Dashboard Title',\n\t\twidgets: [],\n\t\tlayoutOptions: {},\n\t\tconfig: getBaseDashboardConfig(),\n\t\tfilters: [],\n\t};\n\n\treturn dashboardProps;\n}\n\nexport async function createEmptyDashboard(\n\tdataSourceTitle: string,\n\tdashboardTitle: string,\n): Promise<DashboardProps> {\n\tconst jaqlDataSource = await getDataSourceByTitle(dataSourceTitle);\n\tif (!jaqlDataSource) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Please ask the user to specify a valid data source.',\n\t\t);\n\t}\n\tconst dataSource = convertDataSource(jaqlDataSource);\n\n\treturn {\n\t\t...getBaseDashboardProps(),\n\t\ttitle: dashboardTitle,\n\t\tdefaultDataSource: dataSource,\n\t};\n}\n\nexport function resetWidgetForDashboard(widget: WidgetProps): WidgetProps {\n\t// regenerate Widget internal ID to make it unique for the dashboard\n\treturn {\n\t\t...widget,\n\t\tid: nanoidHex(),\n\t};\n}\n\nexport function addWidgetsToDashboard(\n\tdashboardProps: DashboardProps,\n\twidgetsToAdd: WidgetProps[],\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\twidgets: [...dashboardProps.widgets, ...widgetsToAdd],\n\t};\n}\n\nexport function updateDashboardWidgetsLayout(\n\tdashboardProps: DashboardProps,\n\tnewWidgetIds: string[] = [],\n): DashboardProps {\n\tconst currentWidgetsLayout = dashboardProps.layoutOptions?.widgetsPanel;\n\n\tlet widgetsLayout: WidgetsPanelColumnLayout = currentWidgetsLayout || {\n\t\tcolumns: [],\n\t};\n\t// for a dashboard without a layout, create a default layout\n\t// otherwise, update the layout with the new widget\n\tif (\n\t\t!currentWidgetsLayout ||\n\t\t!currentWidgetsLayout.columns ||\n\t\tcurrentWidgetsLayout.columns.length === 0\n\t) {\n\t\twidgetsLayout = layoutDashboardWidgets(\n\t\t\tdashboardProps.widgets.map((widget) => widget.id),\n\t\t);\n\t} else {\n\t\t// Ensure widgetsLayout is always defined\n\t\tif (!widgetsLayout) {\n\t\t\twidgetsLayout = layoutDashboardWidgets(\n\t\t\t\tdashboardProps.widgets.map((widget) => widget.id),\n\t\t\t);\n\t\t}\n\t\tnewWidgetIds.forEach((widgetId) => {\n\t\t\twidgetsLayout = withWidgetAdded(widgetsLayout, widgetId);\n\t\t});\n\t}\n\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tlayoutOptions: { widgetsPanel: widgetsLayout },\n\t};\n\n\treturn updatedDashboardProps;\n}\n\nexport function updateDashboardTitle(\n\tdashboardProps: DashboardProps,\n\tdashboardTitle: string,\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\ttitle: dashboardTitle,\n\t};\n}\n\nexport async function createNewDashboard(\n\tdataSourceTitle: string,\n\tdashboardTitle: string,\n\twidgets: WidgetProps[] = [],\n): Promise<DashboardProps> {\n\tconst dashboardProps = await createEmptyDashboard(\n\t\tdataSourceTitle,\n\t\tdashboardTitle,\n\t);\n\treturn addWidgetsToExistingDashboard(dashboardProps, widgets);\n}\n\nexport function addWidgetsToExistingDashboard(\n\tdashboardProps: DashboardProps,\n\twidgets: WidgetProps[],\n): DashboardProps {\n\tif (widgets.length === 0) {\n\t\treturn dashboardProps;\n\t}\n\n\tconst updatedDashboardProps = addWidgetsToDashboard(\n\t\tdashboardProps,\n\t\twidgets,\n\t);\n\n\tconst updatedDashboardPropsWithLayout = updateDashboardWidgetsLayout(\n\t\tupdatedDashboardProps,\n\t\twidgets.map((widget) => widget.id),\n\t);\n\n\treturn updatedDashboardPropsWithLayout;\n}\n\nexport function deleteWidgetsFromDashboard(\n\tdashboardProps: DashboardProps,\n\twidgetIds: string[],\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\twidgets: dashboardProps.widgets.filter(\n\t\t\t(widget) => !widgetIds.includes(widget.id),\n\t\t),\n\t};\n}\n\n// TODO: look into ways to do this in CSDK instead\nfunction handleChange(\n\tdashboardProps: DashboardProps,\n\tevent: DashboardChangeEvent,\n): DashboardChangeResult {\n\tswitch (event.type) {\n\t\tcase 'filters/updated':\n\t\t\treturn handleFiltersUpdate(dashboardProps, event.payload);\n\t\tcase 'filtersPanel/collapse/changed':\n\t\t\treturn handleFiltersPanelCollapse(dashboardProps, event.payload);\n\t\tcase 'widgetsPanel/layout/updated':\n\t\t\treturn handleWidgetsPanelLayoutUpdate(\n\t\t\t\tdashboardProps,\n\t\t\t\tevent.payload,\n\t\t\t);\n\t\tcase 'widgets/deleted':\n\t\t\treturn handleWidgetsDelete(dashboardProps, event.payload);\n\t\tcase 'widgetsPanel/editMode/isEditing/changed':\n\t\t\treturn handleWidgetsPanelLayoutIsEditingChange(\n\t\t\t\tdashboardProps,\n\t\t\t\tevent.payload,\n\t\t\t);\n\t\tdefault:\n\t\t\treturn { changed: false, updatedDashboardProps: dashboardProps };\n\t}\n}\n\nexport function changeDashboard(\n\tdashboardProps: DashboardProps,\n\tevent: DashboardChangeEvent,\n): DashboardChangeResult {\n\t// Delegate to specific handlers\n\tconst { changed, updatedDashboardProps } = handleChange(\n\t\tdashboardProps,\n\t\tevent,\n\t);\n\n\t// Apply cleanup if any changes were made\n\tif (changed) {\n\t\treturn cleanupDashboardAfterChange(updatedDashboardProps);\n\t}\n\n\treturn { changed, updatedDashboardProps };\n}\n","import { getHttpClient } from '@/singleton-clients';\nimport { nanoidUUIDv4 } from '@/utils/id-utils';\n\ntype CreateElasticubeProps = {\n\ttitle: string;\n};\n\ntype CreateElasticubeResponse = {\n\tdata: {\n\t\tnewCube: {\n\t\t\toid: string;\n\t\t};\n\t};\n\terrors: {\n\t\terror: {\n\t\t\tmessage: string;\n\t\t};\n\t}[];\n};\n\ntype GetCSVSchemaDetailsProps = {\n\tfilePath: string;\n\tfileName: string;\n};\n\ntype GetCSVSchemaDetailsResponse = {\n\tconnection: {\n\t\tApiVersion: number;\n\t\tfiles: string[];\n\t\tdelimiter: string;\n\t\thasHeader: boolean;\n\t\tignoreMissingColumns: boolean;\n\t\texcludeIfBegins: string;\n\t\texcludeIfContains: string;\n\t\tstringQuote: string;\n\t\tignoreFirstRows: string;\n\t\tculture: string;\n\t\tcolumnsDateTimePatterns: string;\n\t};\n\tschema: string;\n\ttable: string;\n};\n\ntype GetPerspectiveOidProps = {\n\telasticubeOid: string;\n};\n\ntype PerspectiveResponse = {\n\tlastUpdated: string;\n\ttitle: string;\n\tserver: string;\n\tdatasets: any[];\n\toid: string;\n\t'modeling-transformations': any[];\n\trelations: any[];\n\tshares: Array<{\n\t\tpartyId: string;\n\t\ttype: string;\n\t\tpermission: string;\n\t}>;\n\ttype: string;\n\trelationType: string;\n\texperiments: Record<string, any>;\n\tfiscal: string;\n\t_id: string;\n\tanalyticalEngine: Record<string, any>;\n\tbuildDestination: {\n\t\tdestination: string;\n\t};\n\tcreator: string;\n\thasDatasetsWithoutConnectionParameters: boolean | null;\n\tmodelStatistics: {\n\t\tenableModelStatistics: boolean;\n\t\tallTablesPerCollection: boolean;\n\t\tmaxTablesPerCollection: number;\n\t};\n\ttenantId: string;\n\trelationsTables: any[];\n\tdatamodelId: string;\n};\n\ntype GetPerspectiveOidResponse = {\n\tperspectives: PerspectiveResponse[];\n\trevisions: any[];\n};\n\ntype AddDataSetProps = {\n\telasticubeOid: string;\n\tfilePath: string;\n\tfileName: string;\n\ttable: any;\n\tperspectiveOid: string;\n};\n\ntype AddDataSetResponse = {\n\tdataSet: {\n\t\toid: string;\n\t};\n\tcolumns: any[];\n\ttableOid: string;\n};\n\ntype BuildElasticubeProps = {\n\telasticubeOid: string;\n};\n\ntype BuildElasticubeResponse = {\n\tbuildElasticube: {\n\t\toid: string;\n\t};\n};\n\nexport type BuildStatus =\n\t| 'building'\n\t| 'pending'\n\t| 'done'\n\t| 'failed'\n\t| 'cancelled';\n\nexport type BuildStatusResponse = {\n\toid: string;\n\tdatamodelId: string;\n\tbuildType: string;\n\tstatus: BuildStatus;\n\tdatamodelTitle: string;\n\tdatamodelType: string;\n\tindexSize: number;\n\tinstanceId: string;\n\tschemaLastUpdate: string;\n\tcreated: string;\n\tstarted: string;\n\tcompleted: string;\n\trowLimit: number;\n\tsource: string;\n};\n\ntype AddRelationProps = {\n\telasticubeOid: string;\n\tsource: any;\n\ttarget: any;\n};\n\ntype AddRelationResponse = {\n\trelation: {\n\t\toid: string;\n\t};\n};\n\nexport type GetElasticubesResponse = {\n\tdata: {\n\t\telasticubesMetadata: Array<{\n\t\t\toid: string;\n\t\t\ttitle: string;\n\t\t\tserver: string;\n\t\t\ttenant: {\n\t\t\t\t_id: string;\n\t\t\t\tname: string;\n\t\t\t\tsystemManagement: boolean;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tfiscal: string;\n\t\t\tserverId: string;\n\t\t\thasDatasets: boolean;\n\t\t\ttype: string;\n\t\t\trelationType: string;\n\t\t\tprovider: string;\n\t\t\timportTime: string;\n\t\t\thasDatasetsWithoutConnectionParameters: boolean;\n\t\t\tdatasets: Array<{\n\t\t\t\toid: string;\n\t\t\t\tdatabase: string;\n\t\t\t\tschemaName: string;\n\t\t\t\tconnection: {\n\t\t\t\t\tid: string;\n\t\t\t\t\t__typename: string;\n\t\t\t\t};\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tset: {\n\t\t\t\ttitle: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tstatus: string;\n\t\t\tlastBuildTime: string;\n\t\t\tlastBuildStatus: string;\n\t\t\tlastSuccessfulBuildStartTime: string;\n\t\t\tlastSuccessfulManualBuildStartTime: string;\n\t\t\tlastSuccessfulBuildTime: string;\n\t\t\tlastPublishTime: string;\n\t\t\tlastUpdated: string;\n\t\t\thasPendingChanges: boolean;\n\t\t\tnextBuildTime: string;\n\t\t\tcreator: {\n\t\t\t\tid: string;\n\t\t\t\tfirstName: string;\n\t\t\t\tlastName: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tsizeInMb: number;\n\t\t\tshares: Array<{\n\t\t\t\tpartyId: string;\n\t\t\t\ttype: string;\n\t\t\t\tpermission: string;\n\t\t\t\tfirstName?: string;\n\t\t\t\tlastName?: string;\n\t\t\t\temail?: string;\n\t\t\t\tname?: string;\n\t\t\t\tad?: boolean;\n\t\t\t\tobjectSid?: string;\n\t\t\t\teveryone?: boolean;\n\t\t\t\ttenantEveryone?: boolean;\n\t\t\t\tadmins?: boolean;\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tbuildDestination: {\n\t\t\t\tdestination: string;\n\t\t\t\tdatabase: string;\n\t\t\t\tschema: string;\n\t\t\t\tresultLimit: number;\n\t\t\t\tqueryTimeout: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tmodelStatistics: {\n\t\t\t\tenableModelStatistics: boolean;\n\t\t\t\tallTablesPerCollection: boolean;\n\t\t\t\tmaxTablesPerCollection: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\texperiments: Array<{\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tacceleration: {\n\t\t\t\tparentModelOid: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tanalyticalEngine: {\n\t\t\t\tqueryAeMode: string;\n\t\t\t\tcustomTranslationMode: string;\n\t\t\t\tgenerateDependenciesMode: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\t__typename: string;\n\t\t}>;\n\t};\n};\n\ntype GetElasticubeProps = {\n\tcubeOid: string;\n};\n\nexport type GetElasticubeResponse = {\n\telasticube: {\n\t\toid: string;\n\t\ttitle: string;\n\t\tserver: string;\n\t\ttenant: {\n\t\t\t_id: string;\n\t\t\tname: string;\n\t\t\tsystemManagement: boolean;\n\t\t};\n\t\tfiscal: string;\n\t\ttype: string;\n\t\trelationType: string;\n\t\tenableDimensionalModeling: boolean;\n\t\tlastSuccessfulManualBuildStartTime: string;\n\t\tlastBuildTime: string;\n\t\tlastPublishTime: string;\n\t\thasDatasetsWithoutConnectionParameters: boolean;\n\t\tdatasets: {\n\t\t\toid: string;\n\t\t\tname: string;\n\t\t\tdatabase: string;\n\t\t\tschemaName: string;\n\t\t\tlastUpdated: string;\n\t\t\ttype: string;\n\t\t\tliveQuerySettings: {\n\t\t\t\ttimeout: number;\n\t\t\t\tautoRefresh: boolean;\n\t\t\t\trefreshRate: number;\n\t\t\t\tresultLimit: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tconnection: {\n\t\t\t\tid: string;\n\t\t\t\toid: string;\n\t\t\t\tprovider: string;\n\t\t\t\tschema: string;\n\t\t\t\tfileName: string;\n\t\t\t\tparameters: string;\n\t\t\t\tprotectedParameters: string;\n\t\t\t\tglobalTableConfigOptions: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tschema: {\n\t\t\t\ttables: {\n\t\t\t\t\toid: string;\n\t\t\t\t\tid: string;\n\t\t\t\t\tname: string;\n\t\t\t\t\trole: string;\n\t\t\t\t\tisRoleBySystem: boolean;\n\t\t\t\t\tdescription: string;\n\t\t\t\t\ttype: string;\n\t\t\t\t\ttags: string[];\n\t\t\t\t\thidden: boolean;\n\t\t\t\t\tlastUpdated: string;\n\t\t\t\t\tconfigOptions: string;\n\t\t\t\t\tschemaName: string;\n\t\t\t\t\tisMaterialized: boolean;\n\t\t\t\t\tbuildBehavior: {\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\taccumulativeConfig: {\n\t\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\t\tcolumn: string;\n\t\t\t\t\t\t\tlastDays: number;\n\t\t\t\t\t\t\tkeepOnlyDays: number;\n\t\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\tcolumns: {\n\t\t\t\t\t\toid: string;\n\t\t\t\t\t\tid: string;\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\trole: string;\n\t\t\t\t\t\tisRoleBySystem: boolean;\n\t\t\t\t\t\tdescription: string;\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\tsize: number;\n\t\t\t\t\t\tprecision: number;\n\t\t\t\t\t\tscale: number;\n\t\t\t\t\t\thidden: boolean;\n\t\t\t\t\t\tindexed: boolean;\n\t\t\t\t\t\tisUpsertBy: boolean;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\texpression: {\n\t\t\t\t\t\toid: string;\n\t\t\t\t\t\tlastUpdated: string;\n\t\t\t\t\t\texpression: string;\n\t\t\t\t\t\tisDatabaseDialect: boolean;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\tcustomCode: {\n\t\t\t\t\t\tnoteBookId: string;\n\t\t\t\t\t\tdependsOn: string[];\n\t\t\t\t\t\tadditionalParameters: string;\n\t\t\t\t\t\tcodePath: string;\n\t\t\t\t\t\tcellsDisable: boolean;\n\t\t\t\t\t\tlanguage: string;\n\t\t\t\t\t\tmode: string;\n\t\t\t\t\t\tserverUrl: string;\n\t\t\t\t\t\ttimeout: number;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\ttupleTransformations: {\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\targuments: string[];\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\t__typename: string;\n\t\t\t\t};\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\t__typename: string;\n\t\t};\n\t\trelationsTables: {\n\t\t\tfirstTable: string;\n\t\t\tsecondTable: string;\n\t\t\tdirectionType: string;\n\t\t\tcondition: string;\n\t\t\t__typename: string;\n\t\t};\n\t\trelations: {\n\t\t\toid: string;\n\t\t\tcolumns: {\n\t\t\t\tdataset: string;\n\t\t\t\ttable: string;\n\t\t\t\tcolumn: string;\n\t\t\t\tisDropped: boolean;\n\t\t\t\t__typename: string;\n\t\t\t}[];\n\t\t\t__typename: string;\n\t\t};\n\t\texperiments: {\n\t\t\t__typename: string;\n\t\t}[];\n\t\tbuildDestination: {\n\t\t\tdestination: string;\n\t\t\tdatabase: string;\n\t\t\tschema: string;\n\t\t\t__typename: string;\n\t\t};\n\t\tmodelStatistics: {\n\t\t\tenableModelStatistics: boolean;\n\t\t\tallTablesPerCollection: boolean;\n\t\t\tmaxTablesPerCollection: number;\n\t\t\trecollectStatsInterval: number;\n\t\t\t__typename: string;\n\t\t};\n\t\t__typename: string;\n\t};\n};\n\ntype DeleteElasticubeProps = {\n\toid: string;\n\treplacementDataSource?: {\n\t\ttype: string;\n\t\toid: string;\n\t};\n};\n\ntype DeleteElasticubeResponse = {\n\tdata: {\n\t\tremoveElasticubeByOid: boolean;\n\t};\n};\n\ntype UploadCSVResponse = Array<{\n\tfilename: string;\n\textension: string;\n\tsize: number;\n\ttype: string;\n\tstorageInfo: {\n\t\tpath: string;\n\t};\n\tuploader: string;\n\tsource: string;\n\tcreatedAt: string;\n\ttenantId: string;\n\t_id: string;\n}>;\n\nexport async function createElasticube({ title }: CreateElasticubeProps) {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'createNewElasticube',\n\t\tvariables: {\n\t\t\ttitle,\n\t\t\ttype: 'extract',\n\t\t\trelationType: 'direct',\n\t\t\texperiments: {},\n\t\t\tbuildDestination: {\n\t\t\t\tdestination: 'elasticube',\n\t\t\t},\n\t\t},\n\t\tquery: 'mutation createNewElasticube($title: String!, $type: ElasticubeType, $relationType: RelationType, $experiments: ExperimentsInput, $buildDestination: BuildDestinationInput, $fiscal: String) {\\n newCube: createNewElasticube(\\n title: $title\\n type: $type\\n relationType: $relationType\\n experiments: $experiments\\n buildDestination: $buildDestination\\n fiscal: $fiscal\\n ) {\\n oid\\n title\\n server\\n type\\n relationType\\n lastBuildTime\\n lastUpdated\\n fiscal\\n creator {\\n id\\n firstName\\n lastName\\n __typename\\n }\\n shares {\\n partyId\\n type\\n ... on ShareUserInfo {\\n firstName\\n lastName\\n email\\n __typename\\n }\\n ... on ShareGroupInfo {\\n name\\n ad\\n objectSid\\n everyone\\n tenantEveryone\\n admins\\n __typename\\n }\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n buildDestination {\\n destination\\n __typename\\n }\\n __typename\\n }\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\tlet data: CreateElasticubeResponse | undefined;\n\ttry {\n\t\tdata = await httpClient.post<CreateElasticubeResponse>(\n\t\t\t`/api/v2/ecm/`,\n\t\t\tbody,\n\t\t);\n\t} catch (err: any) {\n\t\tconsole.error(err);\n\t\tthrow new Error(err.message);\n\t}\n\tif (data?.errors) {\n\t\tthrow new Error(data.errors[0].error.message);\n\t}\n\treturn data?.data?.newCube;\n}\n\nexport async function getCSVSchemaDetails({\n\tfilePath,\n\tfileName,\n}: GetCSVSchemaDetailsProps): Promise<GetCSVSchemaDetailsResponse | null> {\n\tconst body = {\n\t\tconnection: {\n\t\t\tApiVersion: 2,\n\t\t\tfiles: [filePath],\n\t\t\tdelimiter: ',',\n\t\t\thasHeader: true,\n\t\t\tignoreMissingColumns: false,\n\t\t\texcludeIfBegins: '',\n\t\t\texcludeIfContains: '',\n\t\t\tstringQuote: '\"',\n\t\t\tignoreFirstRows: '',\n\t\t\tculture: 'en-US',\n\t\t\tcolumnsDateTimePatterns: '{}',\n\t\t\tfileNames: [fileName],\n\t\t},\n\t\tschema: filePath,\n\t\ttable: filePath.split('/').pop(),\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<GetCSVSchemaDetailsResponse>(\n\t\t`/api/v1/live_connectors/CSV/table_schema_details`,\n\t\tbody,\n\t);\n\n\treturn response ?? null;\n}\n\nexport async function getPerspectiveOid({\n\telasticubeOid,\n}: GetPerspectiveOidProps): Promise<GetPerspectiveOidResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<GetPerspectiveOidResponse>(\n\t\t`/api/v2/perspectives/getPerspectiveElasticubesAndLatestRevisionsByOid?parentOid=${elasticubeOid}`,\n\t);\n\n\treturn response ?? null;\n}\n\nexport async function addDataSet({\n\telasticubeOid,\n\tfilePath,\n\tfileName,\n\ttable,\n\tperspectiveOid,\n}: AddDataSetProps) {\n\tconst tableId = filePath.split('/').pop();\n\tconst oid = tableId?.replace('.csv', '') || '';\n\tconst name = fileName.replace('.csv', '');\n\tconst { schemaName, columns } = table;\n\tconst dataColumns = columns.map((column: any) => ({\n\t\tname: column.columnName,\n\t\ttype: column.dbType,\n\t\toid: nanoidUUIDv4(),\n\t\tsize: column.size,\n\t\tprecision: column.precision,\n\t\tscale: column.scale,\n\t\thidden: false,\n\t\tindexed: true,\n\t\tid: column.columnName,\n\t}));\n\n\tconst body = {\n\t\toperationName: 'addDataset',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tconnection: {\n\t\t\t\tprovider: 'CSV',\n\t\t\t\tschema: filePath,\n\t\t\t\tparameters: {\n\t\t\t\t\tApiVersion: 2,\n\t\t\t\t\tfiles: [filePath],\n\t\t\t\t},\n\t\t\t\tuiParams: {},\n\t\t\t\tglobalTableConfigOptions: {\n\t\t\t\t\tdatesPicker: {},\n\t\t\t\t},\n\t\t\t\tfileName,\n\t\t\t},\n\t\t\ttables: [\n\t\t\t\t{\n\t\t\t\t\tid: tableId,\n\t\t\t\t\tname,\n\t\t\t\t\toid,\n\t\t\t\t\thidden: false,\n\t\t\t\t\tschemaName,\n\t\t\t\t\tbuildBehavior: {\n\t\t\t\t\t\ttype: 'sync',\n\t\t\t\t\t},\n\t\t\t\t\tcolumns: dataColumns,\n\t\t\t\t\tconfigOptions: {\n\t\t\t\t\t\tdelimiter: ',',\n\t\t\t\t\t\thasHeader: true,\n\t\t\t\t\t\tignoreMissingColumns: false,\n\t\t\t\t\t\texcludeIfBegins: '',\n\t\t\t\t\t\texcludeIfContains: '',\n\t\t\t\t\t\tstringQuote: '\"',\n\t\t\t\t\t\tignoreFirstRows: '',\n\t\t\t\t\t\tculture: 'en-US',\n\t\t\t\t\t\tcolumnsDateTimePatterns: '{}',\n\t\t\t\t\t},\n\t\t\t\t\ttupleTransformations: [],\n\t\t\t\t},\n\t\t\t],\n\t\t\tsuggestedOid: nanoidUUIDv4(),\n\t\t\tschemaName,\n\t\t\tperspectiveOid,\n\t\t\tupdatedPerspectiveData: {\n\t\t\t\trelationsTables: [],\n\t\t\t},\n\t\t},\n\t\tquery: `mutation addDataset($elasticubeOid: UUID!, $connection: ConnectionInput!, $tables: [TableInput!]!, $name: String, $suggestedOid: UUID!, $database: String, $schemaName: String, $perspectiveOid: UUID!, $updatedPerspectiveData: PerspectiveInput) {\n markTransactional(elasticubeOid: $elasticubeOid)\n dataset: addDatasetToElasticube(\n elasticubeOid: $elasticubeOid\n connection: $connection\n tables: $tables\n name: $name\n suggestedOid: $suggestedOid\n database: $database\n schemaName: $schemaName\n ) {\n oid\n connection {\n oid\n protectedParameters\n __typename\n }\n __typename\n }\n updatePerspective(\n perspectiveOid: $perspectiveOid\n updatedPerspectiveData: $updatedPerspectiveData\n )\n}`,\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst data = await httpClient.post<AddDataSetResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn { dataSet: data, columns: dataColumns, tableOid: oid };\n}\n\nexport async function buildElasticube({\n\telasticubeOid,\n}: BuildElasticubeProps): Promise<BuildElasticubeResponse | null> {\n\tconst body = {\n\t\toperationName: 'buildElasticube',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tbuildType: 'restart',\n\t\t},\n\t\tquery: 'mutation buildElasticube($elasticubeOid: UUID!, $buildType: ElasticubeBuildType, $buildRows: Int) {\\n buildElasticube(\\n elasticubeOid: $elasticubeOid\\n type: $buildType\\n rows: $buildRows\\n )\\n}\\n',\n\t};\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<BuildElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function buildStatus(): Promise<BuildStatusResponse[] | null> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<BuildStatusResponse[]>(\n\t\t`/api/v2/builds`,\n\t);\n\treturn response ?? null;\n}\n\nexport async function addRelation({\n\telasticubeOid,\n\tsource,\n\ttarget,\n}: AddRelationProps): Promise<AddRelationResponse | null> {\n\tconst body = {\n\t\toperationName: 'addRelation',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tsource,\n\t\t\ttarget,\n\t\t\tsuggestedOid: nanoidUUIDv4(),\n\t\t},\n\t\tquery: 'mutation addRelation($elasticubeOid: UUID!, $source: RelationReferenceInput!, $target: RelationReferenceInput!, $suggestedOid: UUID!) {\\n relation: addRelation(\\n elasticubeOid: $elasticubeOid\\n source: $source\\n target: $target\\n suggestedOid: $suggestedOid\\n ) {\\n oid\\n columns {\\n column\\n __typename\\n }\\n __typename\\n }\\n}\\n',\n\t};\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<AddRelationResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function getElasticubes() {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'elasticubesMetadata',\n\t\tvariables: { isViewMode: false },\n\t\tquery: 'query elasticubesMetadata($tenantFilter: String, $isViewMode: Boolean) {\\n elasticubesMetadata(tenantFilter: $tenantFilter, isViewMode: $isViewMode) {\\n ...ecMetaData\\n __typename\\n }\\n}\\n\\nfragment ecMetaData on ElasticubeMetadata {\\n oid\\n title\\n server\\n tenant {\\n _id\\n name\\n systemManagement\\n __typename\\n }\\n fiscal\\n serverId\\n hasDatasets\\n type\\n relationType\\n provider\\n importTime\\n hasDatasetsWithoutConnectionParameters\\n datasets {\\n oid\\n database\\n schemaName\\n connection {\\n id\\n __typename\\n }\\n __typename\\n }\\n set {\\n title\\n __typename\\n }\\n status\\n lastBuildTime\\n lastBuildStatus\\n lastSuccessfulBuildStartTime\\n lastSuccessfulManualBuildStartTime\\n lastSuccessfulBuildTime\\n lastPublishTime\\n lastUpdated\\n hasPendingChanges\\n nextBuildTime\\n creator {\\n id\\n firstName\\n lastName\\n __typename\\n }\\n sizeInMb\\n shares {\\n partyId\\n type\\n permission\\n ... on ShareUserInfo {\\n firstName\\n lastName\\n email\\n __typename\\n }\\n ... on ShareGroupInfo {\\n name\\n ad\\n objectSid\\n everyone\\n tenantEveryone\\n admins\\n __typename\\n }\\n __typename\\n }\\n buildDestination {\\n destination\\n database\\n schema\\n resultLimit\\n queryTimeout\\n __typename\\n }\\n modelStatistics {\\n enableModelStatistics\\n allTablesPerCollection\\n maxTablesPerCollection\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n acceleration {\\n parentModelOid\\n __typename\\n }\\n analyticalEngine {\\n queryAeMode\\n customTranslationMode\\n generateDependenciesMode\\n __typename\\n }\\n __typename\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\n\tconst response = await httpClient.post<GetElasticubesResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\tif (!response?.data?.elasticubesMetadata) {\n\t\tthrow new Error('Failed to get elasticubes list');\n\t}\n\treturn response.data.elasticubesMetadata;\n}\n\nexport async function getElasticube({\n\tcubeOid,\n}: GetElasticubeProps): Promise<GetElasticubeResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'elasticubeByOid',\n\t\tvariables: { cubeOid },\n\t\tquery: 'query elasticubeByOid($cubeOid: UUID!) {\\n elasticube: elasticubeByOid(oid: $cubeOid) {\\n ...ecData\\n __typename\\n }\\n}\\n\\nfragment ecData on Elasticube {\\n oid\\n title\\n server\\n tenant {\\n _id\\n name\\n systemManagement\\n __typename\\n }\\n fiscal\\n type\\n relationType\\n enableDimensionalModeling\\n lastSuccessfulManualBuildStartTime\\n lastBuildTime\\n lastPublishTime\\n hasDatasetsWithoutConnectionParameters\\n datasets {\\n oid\\n name\\n database\\n schemaName\\n lastUpdated\\n type\\n liveQuerySettings {\\n timeout\\n autoRefresh\\n refreshRate\\n resultLimit\\n __typename\\n }\\n connection {\\n id\\n oid\\n provider\\n schema\\n fileName\\n parameters\\n protectedParameters\\n globalTableConfigOptions\\n __typename\\n }\\n schema {\\n tables {\\n oid\\n id\\n name\\n role\\n isRoleBySystem\\n description\\n type\\n tags\\n hidden\\n lastUpdated\\n configOptions\\n schemaName\\n isMaterialized\\n buildBehavior {\\n type\\n accumulativeConfig {\\n type\\n column\\n lastDays\\n keepOnlyDays\\n __typename\\n }\\n __typename\\n }\\n columns {\\n oid\\n id\\n name\\n role\\n isRoleBySystem\\n description\\n type\\n size\\n precision\\n scale\\n hidden\\n indexed\\n isUpsertBy\\n __typename\\n }\\n expression {\\n oid\\n lastUpdated\\n expression\\n isDatabaseDialect\\n __typename\\n }\\n customCode {\\n noteBookId\\n dependsOn\\n additionalParameters\\n codePath\\n cellsDisable\\n language\\n mode\\n serverUrl\\n timeout\\n __typename\\n }\\n tupleTransformations {\\n type\\n arguments\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n relationsTables {\\n firstTable\\n secondTable\\n directionType\\n condition\\n __typename\\n }\\n relations {\\n oid\\n columns {\\n dataset\\n table\\n column\\n isDropped\\n __typename\\n }\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n buildDestination {\\n destination\\n database\\n schema\\n __typename\\n }\\n modelStatistics {\\n enableModelStatistics\\n allTablesPerCollection\\n maxTablesPerCollection\\n recollectStatsInterval\\n __typename\\n }\\n __typename\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\n\tconst response = await httpClient.post<GetElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function deleteElasticube({\n\toid,\n\treplacementDataSource,\n}: DeleteElasticubeProps): Promise<boolean> {\n\tconst body = {\n\t\toperationName: 'removeElasticubeByOid',\n\t\tvariables: {\n\t\t\toid,\n\t\t\treplacementDataSource,\n\t\t},\n\t\tquery: 'mutation removeElasticubeByOid($oid: UUID!, $replacementDataSource: DataSourceInput) {\\n removeElasticubeByOid(oid: $oid, replacementDataSource: $replacementDataSource)\\n}\\n',\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<DeleteElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\tif (!response?.data) {\n\t\tthrow new Error('Failed to delete elasticube');\n\t}\n\treturn response.data.removeElasticubeByOid;\n}\n\nasync function validateFile(\n\tfileName: string,\n\tcsv: string,\n): Promise<{ file: File; fileToken: string }> {\n\tconst httpClient = getHttpClient();\n\tconst file = new File([csv], fileName, { type: 'text/csv' });\n\tconst payload = {\n\t\tfilename: fileName,\n\t\tsize: file.size,\n\t};\n\n\tconst response = await httpClient.post<{ token: string }>(\n\t\t'/storage/fs/validate_file',\n\t\tpayload,\n\t);\n\n\tif (!response?.token) {\n\t\tthrow new Error('Failed to get file validation token');\n\t}\n\n\treturn { file, fileToken: response.token };\n}\n\nexport async function uploadCSVMultipart(\n\tfileName: string,\n\tcsvContent: string,\n): Promise<UploadCSVResponse> {\n\tconst httpClient = getHttpClient();\n\tconst { fileToken, file } = await validateFile(fileName, csvContent);\n\n\tconst formData = new FormData();\n\tformData.append('file', file);\n\n\tconst headers: Record<string, string> = {\n\t\tAccept: 'application/json',\n\t\tInternal: 'true',\n\t\t'x-upload-token': fileToken,\n\t};\n\thttpClient.auth.applyHeaders(headers);\n\n\tconst response = await fetch(`${httpClient.url}/storage/fs/upload`, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody: formData,\n\t\tcredentials: 'include',\n\t});\n\n\tif (!response.ok) {\n\t\tif (response.status === 403) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Sorry, file upload is not available for this instance as it's behind Cloudflare and we don't have a proper API for connection file upload\",\n\t\t\t);\n\t\t}\n\t\tthrow new Error('Failed to upload file');\n\t}\n\n\tconst data = await response.json();\n\treturn data;\n}\n","import { getHttpClient } from '@/singleton-clients';\n\nexport async function loadGlobals() {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get('api/globals');\n\treturn response;\n}\n","import { getHttpClient } from '@/singleton-clients';\n\nexport interface LlmSettings {\n\taiAssistant: {\n\t\tenabled: boolean;\n\t};\n\tllmServices: {\n\t\tenabled: boolean;\n\t};\n\tllmTerms: {\n\t\taccepted: boolean;\n\t};\n\tprovider: string;\n\tbaseUrl: string;\n\tmodel: string;\n\tapiKey?: string;\n}\n\nconst LLM_SETTINGS_API_URL_PATH = 'api/v2/settings/ai/llm';\n\nexport async function getLlmSettings(): Promise<LlmSettings> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<LlmSettings>(\n\t\tLLM_SETTINGS_API_URL_PATH,\n\t);\n\tif (!response) {\n\t\tthrow new Error('Failed to load LLM settings');\n\t}\n\treturn response;\n}\n\nexport async function updateLlmSettings(\n\tsettings: LlmSettings,\n): Promise<LlmSettings> {\n\tconst httpClient = getHttpClient();\n\t// Include all required fields for the API\n\tconst apiPayload = {\n\t\tprovider: settings.provider,\n\t\tmodel: settings.model,\n\t\tbaseUrl: settings.baseUrl,\n\t\tapiKey: settings.apiKey || 'dummy-api-key', // API requires this field\n\t\tllmTerms: settings.llmTerms,\n\t\tllmServices: settings.llmServices,\n\t\taiAssistant: settings.aiAssistant,\n\t};\n\n\ttry {\n\t\t// The API returns an empty array on success\n\t\tawait httpClient.post<any>(LLM_SETTINGS_API_URL_PATH, apiPayload);\n\n\t\t// Since the API doesn't return the settings object, return the original settings\n\t\t// This will likely need to be refreshed to get the actual state from the server\n\t\treturn settings;\n\t} catch (error) {\n\t\tconsole.error('Error updating LLM settings:', error);\n\t\tthrow error;\n\t}\n}\n"],"names":["ignoreOverride","defaultOptions","getDefaultOptions","options","getRefs","_options","currentPath","name","def","addErrorMessage","res","key","errorMessage","refs","setResponseValueAndErrors","value","getRelativePath","pathA","pathB","i","ZodFirstPartyTypeKind","parseAnyDef","anyDefinitionPath","parseArrayDef","_a","_c","_b","parseDef","parseBigintDef","check","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","overrideDateStrategy","strategy","item","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","type","parseIntersectionDef","allOf","x","unevaluatedProperties","mergedAllOf","schema","nestedSchema","additionalProperties","rest","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","addFormat","addPattern","escapeLiteralCheckValue","literal","escapeNonAlphaNumeric","ALPHA_NUMERIC","source","result","message","regex","stringifyRegExpWithFlags","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","acc","keyType","_d","_e","_f","parseMapDef","keys","values","parseNativeEnumDef","object","actualValues","parsedTypes","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","asAnyOf","types","uniqueTypes","a","anyOf","parseNullableDef","base","parseNumberDef","parseObjectDef","forceOptionalIntoNullable","required","shape","propName","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","b","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","_","forceResolution","seenItem","overrideResult","seenSchema","get$ref","newItem","jsonSchemaOrGetter","jsonSchema","addMeta","postProcessResult","index","zodToJsonSchema","definitions","main","combined","indent","n","hasKeptProperties","propertiesToKeep","unwrapped","z","opt","processSchemaProperties","propertyNames","mode","processedElement","processedOptions","filteredEntries","processedValue","filteredShape","filterSchemaProperties","excludeSchemaProperties","propertiesToExclude","zodToReadableType","depth","isOptional","k","v","o","zodFunction","fn","description","strict","args","context","input","obj","cartesianChartType","categoricalChartType","otherChartType","chartType","cartesianChartSchema","categoricalChartSchema","scatterChartSchema","tableChartSchema","rangeChartSchema","indicatorChartSchema","boxplotChartSchema","areamapChartSchema","scattermapChartSchema","axesMapping","nullableChartType","chartIdSchema","chartRecommendationsSchema","buildChartSchema","baseChartSchema","createChartSchema","updateChartSchema","updateChartTitleSchema","updateChartTypeSchema","updateChartTypeOfMeasuresSchema","updateChartSortingSchema","updateTrendAndForecastSchema","updateOtherChartDataOptionsSchema","updateChartStyleOptionsSchema","random","bytes","customRandom","alphabet","defaultSize","getRandom","mask","step","size","id","j","customAlphabet","nanoidHex","nanoidUUIDv4","makeParseableResponseFormat","response_format","parser","zodDef","zodSchema","isEmptyObj","_k","processPattern","c","processRegExp","regexOrFunction","regexTest","propertyPath","title","processedDefinitions","newDefinitions","_zodToJsonSchema","zodResponseFormat","zodObject","props","content","normalizeUrl","url","parseError","error","getTenantPrefix","urlHost","tenantDomainNames","tenantName","dnsUrl","createHttpClientFromAuthenticator","authenticator","tenantPrefix","httpClientInstance","HttpClient","createHttpClientFromConfig","config","getAuthenticator","createCustomFetch","httpClient","init","headers","isBearerAuth","newInit","OPENAI_API_URL_PATH","createOpenAIClientHelper","baseURL","fetchFn","OpenAI","createOpenAIClient","initializeHttpClient","getHttpClient","resetHttpClient","currentHttpClient","openAIClientInstance","initializeOpenAIClient","openAIClient","getOpenAIClient","resetOpenAIClient","initializeClients","authConfig","createStructuredCompletion","params","systemPrompt","userPrompt","responseFormat","model","temperature","sessionId","openAiResponseFormat","toolCall","parsedResponse","createToolsCompletion","tools","toolChoice","resolve","toolMessages","assistantMessages","isError","combinedMessage","toolMessagesText","assistantMessagesText","err","mapColumnIndicesToObjects","indices","columns","column","mapChartDataToColumns","recommendations","mapping","generateChartRecommendations","cols","prompt","updatedRecommendations","getNlqResult","contextTitle","request","getNlqResultLight","getNlqV3Result","getQueryRecommendations","getQueryRecommendationsLight","generateChartTableFromNlqV2","dataSourceTitle","nlqResult","widgetProps","widgetComposer","isChartWidgetProps","generateChartTableFromNlqV3","dataSchema","translationResult","translateQueryJSON","translatedParams","jaql","translateQueryToJaql","convertDataSource","generateChartTable","isNlqV3Enabled","generateChart","chartTitle","dataColumns","chartRecommendations","newChartType","baseStyleOptions","getChartStyleOptions","createChart","chartId","chartWidgetProps","updateChartTitleHelper","updateChartTitle","updatedChartWidgetProps","updateChartTypeHelper","existingStyleOptions","styleOptions","updateChartType","LineWidthSchema","LineSubtypeSchema","LegendSchema","SeriesLabelsSchema","AxisLabel","XAxisSchema","YAxisSchema","Y2AxisSchema","MarkersSchema","NavigatorSchema","DataLimitsSchema","LineChartStyleSchema","BarChartStyleSchema","ConvolutionSchema","PieChartStyleSchema","ScatterChartStyleSchema","AreaChartStyleSchema","FunnelChartStyleSchema","TreemapChartStyleSchema","SunburstChartStyleSchema","BoxplotChartStyleSchema","IndicatorChartStyleSchema","PolarChartStyleSchema","TableChartStyleSchema","chartStyleSchemas","getChartStyleOptionsSchema","styleSchema","PartialColumnSchema","ColorStringSchema","NumberFormatConfigSchema","trendFormulaOptions","forecastFormulaOptions","dataOptionsEditingSchemas","cartesianDataOptionsEditingSchemas","categoricalDataOptionsEditingSchemas","scatterChartDataOptionsEditingSchemas","indicatorDataOptionsEditingSchemas","boxplotDataOptionsEditingSchemas","scattermapDataOptionsEditingSchemas","areamapDataOptionsEditingSchemas","calendarHeatmapDataOptionsEditingSchemas","tableDataOptionsEditingSchemas","getChartDataOptionsEditingSchemas","chartDataOptionsSchemas","updateChartDataOptionsHelper","currentDataOptions","currentChartType","baseSchema","responseDataOptions","mergedDataOptions","mergeDataOptions","original","aiResponse","merged","dataOptionsKey","incomingList","originalList","originalItem","originalName","updatedItem","updateChartDataOptions","isMergeableObject","isNonNullObject","isSpecial","stringValue","isReactElement","canUseSymbol","REACT_ELEMENT_TYPE","emptyTarget","val","cloneUnlessOtherwiseSpecified","deepmerge","defaultArrayMerge","target","element","getMergeFunction","customMerge","getEnumerableOwnPropertySymbols","symbol","getKeys","propertyIsOnObject","property","propertyIsUnsafe","mergeObject","destination","sourceIsArray","targetIsArray","sourceAndTargetTypesMatch","array","prev","next","deepmerge_1","cjs","updateChartStyleOptionsHelper","currentStyleOptions","targetSchema","responseStyleOptions","mergedStyleOptions","updateChartStyleOptions","TOOL_NAME_CHART_BUILDER","TOOL_NAME_DASHBOARD_BUILDER","TOOL_NAME_DATA_MODEL_BUILDER","TOOL_NAME_RECOMMEND_QUERIES","TOOL_NAME_GET_DASHBOARDS","TOOL_NAME_GET_DATA_SOURCES","TOOL_NAME_GET_DATA_SOURCE_FIELDS","TOOL_CONTEXT_MAX_ASSETS","getBaseChartSummary","createChartTool","originalSchema","originalFunction","boundContext","createChartTools","buildContextualSystemPrompt","chartSummaries","buildChartEngine","newChartId","savedChartWidgetProps","updatedContext","internalTools","isErrorInToolsCompletion","DATA_MODELS_API_URL_PATH","getDataSourceSchema","dataSourceName","DATA_SOURCES_API_URL_PATH","addDescriptionToFields","fields","datasets","schemaDataDescriptionsMap","map","dataset","table","field","getDataSources","getDataSourceByTitle","getDataSourceFields","getDataSourceFieldsWithDescriptions","dataSourceSchema","status","normalizeFields","normalizedFields","normalizedName","normalizeName","baseField","DateLevels","level","getNormalizedDataSourceFields","getFieldsFn","getDataSourcesEngine","dataSources","ds","getDataSourcesSchema","getDataSourceFieldsEngine","getDataSourceFieldsSchema","FUSION_DASHBOARDS_API_URL_PATH","getFusionDashboardUrl","dashboardOid","getFusionDashboards","expand","searchByTitle","queryParams","dashboards","getFusionDashboardWidgets","getFusionDashboardModel","getDashboardModel","patchFusionDashboard","dashboard","addWidgetToFusionDashboard","widgetDto","createEmptyFusionDashboard","dashboardTitle","dataSource","deleteFusionDashboard","deleteWidgetFromFusionDashboard","widgetOid","translateToLayoutDto","layout","r","cell","getAvailableFusionDashboards","getFusionDashboardProps","dashboardModel","dashboardModelTranslator","loadExistingDashboardFromFusion","dashboardId","fusionDashboardProps","addWidgetsToFusionDashboard","widgetsToAdd","widgetPromises","widgetModel","widgetModelTranslator","convertJaqlDataSourceForDto","dto","updateFusionDashboardFilters","filtersToUpdate","filtersDto","translateFiltersAndRelationsToDto","isDashboardSaved","dashboardProps","persistDashboardToFusion","isDataSourceInfo","jaqlDataSource","existingWidgetDtos","fusionDashboardDto","updatedDashboardProps","updatedWidgetDtos","updatedWidgets","widget","updatedWidgetsLayout","row","w","fastDeepEqual","equal","length","extractWidgetIdsFromLayout","cleanupOrphanedCells","existingWidgetIds","cleanedColumns","adjustSingleColumnWidth","findOutOfPlaceWidgets","widgets","widgetsInLayout","cleanupDashboardAfterChange","updatedProps","outOfPlaceWidgetIds","deleteWidgetsFromDashboard","cleanedLayout","handleFiltersUpdate","filters","handleFiltersPanelCollapse","collapsed","handleWidgetsPanelLayoutUpdate","deepEq","handleWidgetsDelete","widgetIds","handleWidgetsPanelLayoutIsEditingChange","isEditing","getDashboardDataSourcesMap","dataSourcesMap","defaultDataSource","layoutDashboardWidgets","widgetOids","withWidgetAdded","widgetId","newRow","minRows","minIndex","getBaseDashboardConfig","getBaseDashboardProps","createEmptyDashboard","resetWidgetForDashboard","addWidgetsToDashboard","updateDashboardWidgetsLayout","newWidgetIds","currentWidgetsLayout","widgetsLayout","updateDashboardTitle","createNewDashboard","addWidgetsToExistingDashboard","handleChange","event","changeDashboard","changed","createElasticube","body","data","getCSVSchemaDetails","filePath","fileName","getPerspectiveOid","elasticubeOid","addDataSet","perspectiveOid","tableId","oid","schemaName","buildElasticube","buildStatus","addRelation","getElasticubes","response","getElasticube","cubeOid","deleteElasticube","replacementDataSource","validateFile","csv","file","payload","uploadCSVMultipart","csvContent","fileToken","formData","loadGlobals","LLM_SETTINGS_API_URL_PATH","getLlmSettings","updateLlmSettings","settings","apiPayload"],"mappings":";;;;;;AAAO,MAAMA,KAAiB,OAAO,mDAAmD,GAa3EC,KAAiB;AAAA,EAC1B,MAAM;AAAA,EACN,cAAc;AAAA,EACd,UAAU,CAAC,GAAG;AAAA,EACd,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,0BAA0B;AAAA,EAC1B,6BAA6B;AAAA,EAC7B,8BAA8B;AAAA,EAC9B,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,aAAa,CAAA;AAAA,EACb,eAAe;AAAA,EACf,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,mBAAmB;AACvB,GACaC,KAAoB,CAACC,OAK5B;AAAA,EACE,GAAGF;AAAAA,EACH,GAAGE;AACX,IC5CaC,KAAU,CAACD,MAAY;AAChC,QAAME,IAAWH,GAAkBC,CAAO,GACpCG,I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AAEpD;ACYA,MAAMyX,KAA4B;AAElC,eAAsBC,KAAuC;AAE5D,QAAMf,IAAW,MADE3W,EAAA,EACe;AAAA,IACjCyX;AAAA,EAAA;AAED,MAAI,CAACd;AACJ,UAAM,IAAI,MAAM,6BAA6B;AAE9C,SAAOA;AACR;AAEA,eAAsBgB,GACrBC,GACuB;AACvB,QAAMxY,IAAaY,EAAA,GAEb6X,IAAa;AAAA,IAClB,UAAUD,EAAS;AAAA,IACnB,OAAOA,EAAS;AAAA,IAChB,SAASA,EAAS;AAAA,IAClB,QAAQA,EAAS,UAAU;AAAA;AAAA,IAC3B,UAAUA,EAAS;AAAA,IACnB,aAAaA,EAAS;AAAA,IACtB,aAAaA,EAAS;AAAA,EAAA;AAGvB,MAAI;AAEH,iBAAMxY,EAAW,KAAUqY,IAA2BI,CAAU,GAIzDD;AAAA,EACR,SAASvZ,GAAO;AACf,kBAAQ,MAAM,gCAAgCA,CAAK,GAC7CA;AAAA,EACP;AACD;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,94,106]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../node_modules/zod-to-json-schema/dist/esm/Options.js","../node_modules/zod-to-json-schema/dist/esm/Refs.js","../node_modules/zod-to-json-schema/dist/esm/errorMessages.js","../node_modules/zod-to-json-schema/dist/esm/getRelativePath.js","../node_modules/zod/v3/types.js","../node_modules/zod-to-json-schema/dist/esm/parsers/any.js","../node_modules/zod-to-json-schema/dist/esm/parsers/array.js","../node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js","../node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js","../node_modules/zod-to-json-schema/dist/esm/parsers/branded.js","../node_modules/zod-to-json-schema/dist/esm/parsers/catch.js","../node_modules/zod-to-json-schema/dist/esm/parsers/date.js","../node_modules/zod-to-json-schema/dist/esm/parsers/default.js","../node_modules/zod-to-json-schema/dist/esm/parsers/effects.js","../node_modules/zod-to-json-schema/dist/esm/parsers/enum.js","../node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js","../node_modules/zod-to-json-schema/dist/esm/parsers/literal.js","../node_modules/zod-to-json-schema/dist/esm/parsers/string.js","../node_modules/zod-to-json-schema/dist/esm/parsers/record.js","../node_modules/zod-to-json-schema/dist/esm/parsers/map.js","../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js","../node_modules/zod-to-json-schema/dist/esm/parsers/never.js","../node_modules/zod-to-json-schema/dist/esm/parsers/null.js","../node_modules/zod-to-json-schema/dist/esm/parsers/union.js","../node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js","../node_modules/zod-to-json-schema/dist/esm/parsers/number.js","../node_modules/zod-to-json-schema/dist/esm/parsers/object.js","../node_modules/zod-to-json-schema/dist/esm/parsers/optional.js","../node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js","../node_modules/zod-to-json-schema/dist/esm/parsers/promise.js","../node_modules/zod-to-json-schema/dist/esm/parsers/set.js","../node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js","../node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js","../node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js","../node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js","../node_modules/zod-to-json-schema/dist/esm/selectParser.js","../node_modules/zod-to-json-schema/dist/esm/parseDef.js","../node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js","../src/utils/zod-utils.ts","../src/engines/chart-builder/types.ts","../node_modules/nanoid/index.browser.js","../src/utils/id-utils.ts","../node_modules/openai/lib/parser.mjs","../node_modules/openai/_vendor/zod-to-json-schema/Options.mjs","../node_modules/openai/_vendor/zod-to-json-schema/util.mjs","../node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs","../node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs","../node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs","../node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs","../node_modules/openai/helpers/zod.mjs","../src/utils/utils.ts","../src/utils/proxy-utils.ts","../src/utils/user-action-tracking.ts","../src/utils/http-client.ts","../src/utils/openai-client.ts","../src/singleton-clients.ts","../src/utils/chat-completion-utils.ts","../src/engines/chart-builder/create-chart/generate-chart-recommendations.ts","../src/services/nlq/nlq-service.ts","../src/engines/chart-builder/create-chart/generate-chart-table.ts","../src/engines/chart-builder/create-chart/create-chart.ts","../src/engines/chart-builder/update-chart/update-chart-title.ts","../src/engines/chart-builder/update-chart/update-chart-type.ts","../src/engines/chart-builder/update-chart/chart-options-schemas.ts","../src/engines/chart-builder/update-chart/update-chart-data-options.ts","../node_modules/deepmerge/dist/cjs.js","../src/engines/chart-builder/update-chart/update-chart-style-options.ts","../src/constants.ts","../src/engines/chart-builder/chart-builder-service.ts","../src/engines/chart-builder/chart-builder-engine.ts","../src/services/data-models/data-models-service.ts","../src/services/data-sources/data-sources-service.ts","../src/engines/data-sources/data-sources-engine.ts","../src/engines/data-sources/types.ts","../src/engines/data-source-fields/data-source-fields-engine.ts","../src/engines/data-source-fields/types.ts","../src/services/dashboards/fusion-dashboards-service.ts","../node_modules/fast-deep-equal/index.js","../src/services/dashboards/dashboards-service.ts","../src/services/data-models/ecm-service.ts","../src/services/globals/globals-service.ts","../src/services/llm/llm-settings-service.ts"],"sourcesContent":["export const ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nexport const jsonDescription = (jsonSchema, def) => {\n if (def.description) {\n try {\n return {\n ...jsonSchema,\n ...JSON.parse(def.description),\n };\n }\n catch { }\n }\n return jsonSchema;\n};\nexport const defaultOptions = {\n name: undefined,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n target: \"jsonSchema7\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\",\n openAiAnyTypeName: \"OpenAiAnyType\"\n};\nexport const getDefaultOptions = (options) => (typeof options === \"string\"\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n });\n","import { getDefaultOptions } from \"./Options.js\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n flags: { hasReferencedOpenAiAnyType: false },\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n","export const getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,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[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { getRelativePath } from \"../getRelativePath.js\";\nexport function parseAnyDef(refs) {\n if (refs.target !== \"openAi\") {\n return {};\n }\n const anyDefinitionPath = [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ];\n refs.flags.hasReferencedOpenAiAnyType = true;\n return {\n $ref: refs.$refStrategy === \"relative\"\n ? getRelativePath(anyDefinitionPath, refs.currentPath)\n : anyDefinitionPath.join(\"/\"),\n };\n}\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: \"array\",\n };\n if (def.type?._def &&\n def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, \"minItems\", def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, \"maxItems\", def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, \"minItems\", def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, \"maxItems\", def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: \"integer\",\n format: \"int64\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","export function parseBooleanDef() {\n return {\n type: \"boolean\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\",\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\",\n };\n case \"integer\":\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\",\n };\n if (refs.target === \"openApi3\") {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minimum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maximum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\"\n ? parseDef(_def.schema._def, refs)\n : parseAnyDef(refs);\n}\n","export function parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values),\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nconst isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\")\n return false;\n return \"allOf\" in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === \"jsonSchema2019-09\"\n ? { unevaluatedProperties: false }\n : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema &&\n schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length\n ? {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" &&\n parsedType !== \"number\" &&\n parsedType !== \"boolean\" &&\n parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\",\n };\n }\n if (refs.target === \"openApi3\") {\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value,\n };\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n","import { ZodFirstPartyTypeKind, } from \"zod/v3\";\nimport { parseDef } from \"../parseDef.js\";\nimport { parseStringDef } from \"./string.js\";\nimport { parseBrandedDef } from \"./branded.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === \"openAi\") {\n console.warn(\"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.\");\n }\n if (refs.target === \"openApi3\" &&\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: \"object\",\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", key],\n }) ?? parseAnyDef(refs),\n }), {}),\n additionalProperties: refs.rejectedAdditionalProperties,\n };\n }\n const schema = {\n type: \"object\",\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n }) ?? refs.allowedAdditionalProperties,\n };\n if (refs.target === \"openApi3\") {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.type._def.checks?.length) {\n const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseRecordDef } from \"./record.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"],\n }) || parseAnyDef(refs);\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"],\n }) || parseAnyDef(refs);\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1\n ? parsedTypes[0] === \"string\"\n ? \"string\"\n : \"number\"\n : [\"string\", \"number\"],\n enum: actualValues,\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseNeverDef(refs) {\n return refs.target === \"openAi\"\n ? undefined\n : {\n not: parseAnyDef({\n ...refs,\n currentPath: [...refs.currentPath, \"not\"],\n }),\n };\n}\n","export function parseNullDef(refs) {\n return refs.target === \"openApi3\"\n ? {\n enum: [\"null\"],\n nullable: true,\n }\n : {\n type: \"null\",\n };\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\",\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === \"openApi3\")\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null)\n return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce((acc, x) => [\n ...acc,\n ...x._def.values.filter((x) => !acc.includes(x)),\n ], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`],\n }))\n .filter((x) => !!x &&\n (!refs.strictUnions ||\n (typeof x === \"object\" && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n","import { parseDef } from \"../parseDef.js\";\nimport { primitiveMappings } from \"./union.js\";\nexport function parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === \"openApi3\") {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\",\n ],\n };\n }\n if (refs.target === \"openApi3\") {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && \"$ref\" in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"],\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n","import { addErrorMessage, setResponseValueAndErrors, } from \"../errorMessages.js\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: \"number\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n addErrorMessage(res, \"type\", check.message, refs);\n break;\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseObjectDef(def, refs) {\n const forceOptionalIntoNullable = refs.target === \"openAi\";\n const result = {\n type: \"object\",\n properties: {},\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === undefined || propDef._def === undefined) {\n continue;\n }\n let propOptional = safeIsOptional(propDef);\n if (propOptional && forceOptionalIntoNullable) {\n if (propDef._def.typeName === \"ZodOptional\") {\n propDef = propDef._def.innerType;\n }\n if (!propDef.isNullable()) {\n propDef = propDef.nullable();\n }\n propOptional = false;\n }\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName],\n });\n if (parsedDef === undefined) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== undefined) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\"\n ? refs.allowedAdditionalProperties\n : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n }\n catch {\n return true;\n }\n}\n","import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"],\n });\n return innerSchema\n ? {\n anyOf: [\n {\n not: parseAnyDef(refs),\n },\n innerSchema,\n ],\n }\n : parseAnyDef(refs);\n};\n","import { parseDef } from \"../parseDef.js\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n","import { parseDef } from \"../parseDef.js\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n","import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, \"minItems\", def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, \"maxItems\", def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n","import { parseDef } from \"../parseDef.js\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"],\n }),\n };\n }\n else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUndefinedDef(refs) {\n return {\n not: parseAnyDef(refs),\n };\n}\n","import { parseAnyDef } from \"./any.js\";\nexport function parseUnknownDef(refs) {\n return parseAnyDef(refs);\n}\n","import { parseDef } from \"../parseDef.js\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseStringDef } from \"./parsers/string.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnionDef } from \"./parsers/union.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nexport const selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef(refs);\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef(refs);\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef(refs);\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef(refs);\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\n","import { ignoreOverride } from \"./Options.js\";\nimport { selectParser } from \"./selectParser.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n const jsonSchema = typeof jsonSchemaOrGetter === \"function\"\n ? parseDef(jsonSchemaOrGetter(), refs)\n : jsonSchemaOrGetter;\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n newItem.jsonSchema = jsonSchema;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n return parseAnyDef(refs);\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef(refs) : undefined;\n }\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n","import { parseDef } from \"./parseDef.js\";\nimport { getRefs } from \"./Refs.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions\n ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n ...acc,\n [name]: parseDef(schema._def, {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, true) ?? parseAnyDef(refs),\n }), {})\n : undefined;\n const name = typeof options === \"string\"\n ? options\n : options?.nameStrategy === \"title\"\n ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, false) ?? parseAnyDef(refs);\n const title = typeof options === \"object\" &&\n options.name !== undefined &&\n options.nameStrategy === \"title\"\n ? options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n if (refs.flags.hasReferencedOpenAiAnyType) {\n if (!definitions) {\n definitions = {};\n }\n if (!definitions[refs.openAiAnyTypeName]) {\n definitions[refs.openAiAnyTypeName] = {\n // Skipping \"object\" as no properties can be defined and additionalProperties must be \"false\"\n type: [\"string\", \"number\", \"integer\", \"boolean\", \"array\", \"null\"],\n items: {\n $ref: refs.$refStrategy === \"relative\"\n ? \"1\"\n : [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ].join(\"/\"),\n },\n };\n }\n }\n const combined = name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === \"relative\" ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === \"jsonSchema7\") {\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (refs.target === \"jsonSchema2019-09\" || refs.target === \"openAi\") {\n combined.$schema = \"https://json-schema.org/draft/2019-09/schema#\";\n }\n if (refs.target === \"openAi\" &&\n (\"anyOf\" in combined ||\n \"oneOf\" in combined ||\n \"allOf\" in combined ||\n (\"type\" in combined && Array.isArray(combined.type)))) {\n console.warn(\"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.\");\n }\n return combined;\n};\nexport { zodToJsonSchema };\n","import { z } from 'zod';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { RunnableToolFunctionWithParse } from 'openai/lib/RunnableFunction';\nimport { JSONSchema } from 'openai/lib/jsonschema';\n\nconst indent = (n: number) => ' '.repeat(n);\n\n/**\n * Parse error from various types\n */\nexport const parseError = (error: Error | string | object) => {\n\tif (error instanceof Error) {\n\t\ttry {\n\t\t\treturn JSON.parse(error.message);\n\t\t} catch (e) {\n\t\t\treturn error.message;\n\t\t}\n\t}\n\tif (typeof error === 'string') {\n\t\treturn error;\n\t}\n\treturn error;\n};\n\n/**\n * Check if a schema or its descendants contain any properties from the keep list.\n * Used to determine if a container (object/array) should be kept.\n */\nconst hasKeptProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToKeep: string[],\n): boolean => {\n\t// Unwrap optionals and nullables\n\tlet unwrapped = schema;\n\twhile (\n\t\tunwrapped instanceof z.ZodOptional ||\n\t\tunwrapped instanceof z.ZodNullable\n\t) {\n\t\tunwrapped = unwrapped.unwrap();\n\t}\n\n\t// Check arrays - recurse into element type\n\tif (unwrapped instanceof z.ZodArray) {\n\t\treturn hasKeptProperties(unwrapped.element, propertiesToKeep);\n\t}\n\n\t// Check unions - any option has kept properties\n\tif (unwrapped instanceof z.ZodUnion) {\n\t\treturn unwrapped.options.some((opt: z.ZodTypeAny) =>\n\t\t\thasKeptProperties(opt, propertiesToKeep),\n\t\t);\n\t}\n\n\t// Check objects - any property name matches or descendants match\n\tif (unwrapped instanceof z.ZodObject) {\n\t\tfor (const [key, value] of Object.entries(unwrapped.shape)) {\n\t\t\t// If property name is in keep list, we found one\n\t\t\tif (propertiesToKeep.includes(key)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t// Otherwise check if this property's descendants contain kept properties\n\t\t\tif (hasKeptProperties(value as z.ZodTypeAny, propertiesToKeep)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n};\n\n/**\n * Internal generic function to process schema properties with include or exclude mode.\n * This is the shared implementation for both filterSchemaProperties and excludeSchemaProperties.\n *\n * @param schema - The Zod schema to process\n * @param propertyNames - Array of property names to include or exclude\n * @param mode - 'include' to keep only specified properties, 'exclude' to remove them\n * @returns A new processed Zod schema\n */\nconst processSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertyNames: string[],\n\tmode: 'include' | 'exclude',\n): z.ZodTypeAny => {\n\t// Handle optionals - recurse and rewrap\n\tif (schema instanceof z.ZodOptional) {\n\t\treturn z.ZodOptional.create(\n\t\t\tprocessSchemaProperties(schema.unwrap(), propertyNames, mode),\n\t\t);\n\t}\n\n\t// Handle nullables - recurse and rewrap\n\tif (schema instanceof z.ZodNullable) {\n\t\treturn z.ZodNullable.create(\n\t\t\tprocessSchemaProperties(schema.unwrap(), propertyNames, mode),\n\t\t);\n\t}\n\n\t// Handle arrays - recurse into element type\n\tif (schema instanceof z.ZodArray) {\n\t\tconst processedElement = processSchemaProperties(\n\t\t\tschema.element,\n\t\t\tpropertyNames,\n\t\t\tmode,\n\t\t);\n\t\treturn z.ZodArray.create(processedElement, schema._def);\n\t}\n\n\t// Handle unions - recurse into each option\n\tif (schema instanceof z.ZodUnion) {\n\t\tconst processedOptions = schema.options.map((opt: z.ZodTypeAny) =>\n\t\t\tprocessSchemaProperties(opt, propertyNames, mode),\n\t\t);\n\t\treturn z.ZodUnion.create(processedOptions);\n\t}\n\n\t// Handle objects - mode-specific filtering\n\tif (schema instanceof z.ZodObject) {\n\t\tconst filteredEntries: [string, z.ZodTypeAny][] = [];\n\n\t\tfor (const [key, value] of Object.entries(schema.shape)) {\n\t\t\tif (mode === 'include') {\n\t\t\t\t// INCLUDE mode: keep property if in list OR if it leads to properties in list\n\t\t\t\tif (propertyNames.includes(key)) {\n\t\t\t\t\t// Keep property entirely with all descendants\n\t\t\t\t\tfilteredEntries.push([key, value as z.ZodTypeAny]);\n\t\t\t\t} else if (\n\t\t\t\t\thasKeptProperties(value as z.ZodTypeAny, propertyNames)\n\t\t\t\t) {\n\t\t\t\t\t// Property leads to kept properties - keep and recurse\n\t\t\t\t\tconst processedValue = processSchemaProperties(\n\t\t\t\t\t\tvalue as z.ZodTypeAny,\n\t\t\t\t\t\tpropertyNames,\n\t\t\t\t\t\tmode,\n\t\t\t\t\t);\n\t\t\t\t\tfilteredEntries.push([key, processedValue]);\n\t\t\t\t}\n\t\t\t\t// Otherwise, property is removed (not added to filteredEntries)\n\t\t\t} else {\n\t\t\t\t// EXCLUDE mode: remove property if in list, otherwise keep and recurse\n\t\t\t\tif (propertyNames.includes(key)) {\n\t\t\t\t\t// Property is in exclude list - remove entirely (don't add to filteredEntries)\n\t\t\t\t} else {\n\t\t\t\t\t// Property not in exclude list - keep and recurse to handle nested exclusions\n\t\t\t\t\tconst processedValue = processSchemaProperties(\n\t\t\t\t\t\tvalue as z.ZodTypeAny,\n\t\t\t\t\t\tpropertyNames,\n\t\t\t\t\t\tmode,\n\t\t\t\t\t);\n\t\t\t\t\tfilteredEntries.push([key, processedValue]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst filteredShape = Object.fromEntries(\n\t\t\tfilteredEntries,\n\t\t) as z.ZodRawShape;\n\t\treturn z.ZodObject.create(filteredShape, schema._def);\n\t}\n\n\t// For all other types (primitives, enums, literals, etc.), return as-is\n\treturn schema;\n};\n\n/**\n * Filter Zod schema properties using path-based filtering.\n * Keeps properties in the keep list, all their descendants, and the path to reach them.\n *\n * Algorithm:\n * - If property name is in keep list → keep it entirely (with all descendants)\n * - If property is a container → check if it contains kept properties\n * - If yes → keep container and recurse\n * - If no → remove it\n *\n * @param schema - The Zod schema to filter\n * @param propertiesToKeep - Array of property names to keep (with all their descendants)\n * @returns A new filtered Zod schema\n */\nexport const filterSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToKeep: string[],\n): z.ZodTypeAny => {\n\treturn processSchemaProperties(schema, propertiesToKeep, 'include');\n};\n\n/**\n * Exclude specified properties from a Zod schema.\n * Removes properties in the exclude list and all their descendants.\n *\n * Algorithm:\n * - If property name is in exclude list → remove entirely (with all descendants)\n * - Otherwise → keep and recurse to handle nested exclusions\n *\n * @param schema - The Zod schema to process\n * @param propertiesToExclude - Array of property names to remove (with all their descendants)\n * @returns A new filtered Zod schema\n */\nexport const excludeSchemaProperties = (\n\tschema: z.ZodTypeAny,\n\tpropertiesToExclude: string[],\n): z.ZodTypeAny => {\n\treturn processSchemaProperties(schema, propertiesToExclude, 'exclude');\n};\n\n/**\n * Convert a Zod schema to a readable type string representation\n */\nexport const zodToReadableType = (\n\tschema: z.ZodTypeAny,\n\tdepth = 0,\n\tpropName?: string,\n\tisOptional?: boolean,\n): string => {\n\t// Optionals\n\tif (schema instanceof z.ZodOptional) {\n\t\treturn zodToReadableType(schema.unwrap(), depth, propName, true);\n\t}\n\t// Nullables\n\tif (schema instanceof z.ZodNullable) {\n\t\treturn (\n\t\t\tzodToReadableType(schema.unwrap(), depth, propName, isOptional) +\n\t\t\t' | null'\n\t\t);\n\t}\n\t// Array\n\tif (schema instanceof z.ZodArray) {\n\t\tconst inner = zodToReadableType(schema.element, depth);\n\t\treturn `Array<${inner}>${\n\t\t\tschema.description ? ` - ${schema.description}` : ''\n\t\t}`;\n\t}\n\t// Object: print each property on its own line, with descriptions\n\tif (schema instanceof z.ZodObject) {\n\t\tconst props = Object.entries(schema.shape)\n\t\t\t.map(\n\t\t\t\t([k, v]: [string, any]) =>\n\t\t\t\t\t`${indent(depth + 1)}${k}${\n\t\t\t\t\t\tv.isOptional() ? '?' : ''\n\t\t\t\t\t}: ${zodToReadableType(v, depth + 1, k, v.isOptional())}${\n\t\t\t\t\t\tv.description ? ` - ${v.description}` : ''\n\t\t\t\t\t}`,\n\t\t\t)\n\t\t\t.join(',\\n');\n\t\treturn (\n\t\t\t`{\\n${props}\\n${indent(depth)}}` +\n\t\t\t(schema.description ? ` - ${schema.description}` : '')\n\t\t);\n\t}\n\t// Enum\n\tif (schema instanceof z.ZodEnum) {\n\t\tconst opts = schema.options.map((o: string) => `\"${o}\"`).join(' | ');\n\t\treturn opts + (schema.description ? ` - ${schema.description}` : '');\n\t}\n\t// Union\n\tif (schema instanceof z.ZodUnion) {\n\t\treturn schema.options\n\t\t\t.map((opt: z.ZodTypeAny) => zodToReadableType(opt, depth))\n\t\t\t.join(' | ');\n\t}\n\t// Literal\n\tif (schema instanceof z.ZodLiteral) return JSON.stringify(schema.value);\n\t// String, Number, Boolean\n\tif (schema instanceof z.ZodString) return 'string';\n\tif (schema instanceof z.ZodNumber) return 'number';\n\tif (schema instanceof z.ZodBoolean) return 'boolean';\n\t// Fallback\n\treturn 'any';\n};\n\n/**\n * Create a decoupled zodFunction that wraps Zod schemas for OpenAI tools.\n *\n * This is a pure function that does NOT depend on stores or session management.\n * It only wraps the schema and delegates to the provided function with a generic context.\n *\n * @param config - Configuration for the tool\n * @param config.schema - The Zod schema for parameters\n * @param config.name - The function name\n * @param config.description - The function description\n * @param config.function - The function to execute (receives args and generic context)\n * @param config.strict - Whether to use strict mode\n * @returns A runnable tool function for OpenAI\n */\nexport function zodFunction<T extends object, TContext = any>({\n\tfunction: fn,\n\tschema,\n\tdescription = '',\n\tname,\n\tstrict = false,\n}: {\n\tfunction: (args: T, context: TContext) => Promise<object>;\n\tschema: z.ZodSchema<T>;\n\tdescription?: string;\n\tname?: string;\n\tstrict?: boolean;\n}): RunnableToolFunctionWithParse<T> {\n\treturn {\n\t\ttype: 'function',\n\t\tfunction: {\n\t\t\tfunction: async (args: T, context: any) => {\n\t\t\t\treturn fn(args, context as TContext);\n\t\t\t},\n\t\t\tname: name ?? (fn as any).name,\n\t\t\tdescription: description,\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\tparameters: zodToJsonSchema(schema as any) as JSONSchema,\n\t\t\tstrict,\n\t\t\tparse(input: string): T {\n\t\t\t\tconst obj = JSON.parse(input);\n\t\t\t\treturn schema.parse(obj);\n\t\t\t},\n\t\t},\n\t};\n}\n","import { CalculatedMeasureColumn, MeasureColumn } from '@sisense/sdk-data';\nimport {\n\tChartType,\n\tChartWidgetProps,\n\tStyledColumn,\n\tStyledMeasureColumn,\n\tWithCommonWidgetProps,\n} from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport { z } from 'zod';\nimport { NlqResponseData } from '@sisense/sdk-ui/ai';\n\n// Simple artifact reference type (no dependency on assistant types)\nexport type ArtifactReference = {\n\tartifactId?: string;\n};\n\n// temp solution until a new NLQ tool is implemented\nexport type ExtendedChartWidgetProps = WithCommonWidgetProps<\n\tChartWidgetProps,\n\t'chart'\n> &\n\tArtifactReference & {\n\t\t/**\n\t\t * data columns used to generate chart recommendations\n\t\t */\n\t\tdataColumns?: ColumnType[];\n\t\t/**\n\t\t * nlq result used to generate chart insights\n\t\t */\n\t\tnlqResponse?: NlqResponseData;\n\t};\n\nexport type NullableChartType = ChartType | null | undefined;\n\n/**\n * Base chart summary for LLM consumption and asset extraction\n */\nexport type BaseChartSummary = {\n\t/** Human-readable title of the chart */\n\ttitle?: string;\n\t/** Name of the data source used for the chart */\n\tdataSourceTitle: string;\n\t/** Type of chart (line, bar, pie, etc.) */\n\tchartType?: ChartType;\n\t/** Summary of applied filters */\n\tfilters: string;\n\t/** Summary of data configuration options */\n\tdataOptions: string;\n\t/** Summary of styling and visual options */\n\tstyleOptions: string;\n};\n\n/**\n * Summary of a chart for LLM consumption and asset extraction\n */\nexport interface ChartSummary {\n\t/** Status message indicating success or failure */\n\tmessage: string;\n\t/** Date and time ISO string of when the chart was created */\n\tcreatedAt: string;\n\t/** Unique identifier for the chart (typically the tool call ID) */\n\tchartId: string;\n\t/** Chart details, undefined if chart creation failed */\n\tchart?: BaseChartSummary;\n\t/** Whether this chart creation resulted in an error */\n\tisError?: boolean;\n}\n\nexport type ColumnType =\n\t| StyledColumn\n\t| StyledMeasureColumn\n\t| Column\n\t| MeasureColumn\n\t| CalculatedMeasureColumn;\n\nexport interface Column {\n\tid?: number;\n\tname: string;\n\ttype?: string;\n}\n\nconst cartesianChartType = z.enum(['bar', 'column', 'area', 'line', 'polar']);\n\nconst categoricalChartType = z.enum(['pie', 'funnel', 'treemap', 'sunburst']);\n\nconst otherChartType = z.enum([\n\t'scatter',\n\t'table',\n\t'indicator',\n\t'boxplot',\n\t'areamap',\n\t'scattermap',\n\t'arearange',\n]);\n\nexport const chartType = z.enum([\n\t...cartesianChartType.options,\n\t...categoricalChartType.options,\n\t...otherChartType.options,\n]);\n\nconst cartesianChartSchema = z\n\t.object({\n\t\ttype: cartesianChartType,\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tbreakBy: z.array(z.number()),\n\t})\n\t.strict();\n\nconst categoricalChartSchema = z\n\t.object({\n\t\ttype: categoricalChartType,\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t})\n\t.strict();\n\nconst scatterChartSchema = z\n\t.object({\n\t\ttype: z.literal('scatter'),\n\t\tx: z.array(z.number()),\n\t\ty: z.array(z.number()),\n\t\tbreakByPoint: z.array(z.number()),\n\t\tbreakByColor: z.array(z.number()),\n\t\tsize: z.array(z.number()),\n\t\t// showLegend: z.boolean(),\n\t})\n\t.strict();\n\nconst tableChartSchema = z\n\t.object({\n\t\ttype: z.literal('table'),\n\t\tcolumns: z.array(z.number()),\n\t\tpagination: z.boolean(),\n\t\trowsPerPage: z.number(),\n\t})\n\t.strict();\n\nconst rangeChartSchema = z\n\t.object({\n\t\ttype: z.literal('range'),\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tbreakBy: z.array(z.number()),\n\t})\n\t.strict();\n\nconst indicatorChartSchema = z\n\t.object({\n\t\ttype: z.literal('indicator'),\n\t\tvalue: z.array(z.number()),\n\t\tsecondary: z.array(z.number()),\n\t\tmin: z.array(z.number()),\n\t\tmax: z.array(z.number()),\n\t})\n\t.strict();\n\nconst boxplotChartSchema = z\n\t.object({\n\t\ttype: z.literal('boxplot'),\n\t\tcategory: z.array(z.number()),\n\t\tvalue: z.array(z.number()),\n\t\tboxType: z.enum(['iqr', 'extremums', 'standardDeviation']),\n\t\toutliersEnabled: z.boolean(),\n\t})\n\t.strict();\n\nconst areamapChartSchema = z\n\t.object({\n\t\ttype: z.literal('areamap'),\n\t\tgeo: z.array(z.number()),\n\t\tcolor: z.array(z.number()),\n\t})\n\t.strict();\n\nconst scattermapChartSchema = z\n\t.object({\n\t\ttype: z.literal('scattermap'),\n\t\tgeo: z.array(z.number()),\n\t\tsize: z.array(z.number()),\n\t\tcolorBy: z.array(z.number()),\n\t\tdetails: z.array(z.number()),\n\t\tlocationLevel: z.enum(['auto', 'country', 'state', 'city']),\n\t})\n\t.strict();\n\nexport const axesMapping = z.discriminatedUnion('type', [\n\tcartesianChartSchema,\n\tcategoricalChartSchema,\n\tscatterChartSchema,\n\ttableChartSchema,\n\trangeChartSchema,\n\tindicatorChartSchema,\n\tboxplotChartSchema,\n\tareamapChartSchema,\n\tscattermapChartSchema,\n]);\n\nexport const nullableChartType = chartType\n\t.nullable()\n\t.describe(\n\t\t'If the user prompt does not specify a known chart type, pass null; otherwise, pass the specified chart type',\n\t);\n\nexport const chartIdSchema = z\n\t.string()\n\t.describe(\n\t\t'The ID of the chart to update. If not provided, use value \"chart_id_placeholder\"',\n\t)\n\t.default('chart_id_placeholder');\n\nexport const chartRecommendationsSchema = z.object({\n\tchartType: chartType,\n\taxesMapping: axesMapping,\n});\n\nexport const buildChartSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tuserPrompt: z.string().describe(\n\t\t`Combined natural language user prompt describing multiple actions on a chart. Do not split the user prompt into multiple requests.\nWhen responding to changes involving an existing chart:\n - If the prompt involves **adding or removing** chart's data structure such as dimensions, measures, or filters (e.g., \"add revenue\", \"remove date\", \"filter by region\"), do **not** modify the existing chart. Instead, **create a new chart** with the requested changes.\n - If the prompt involves **enhancing** how existing fields are displayed (e.g., \"show cost on the right axis\", \"add trend line\", \"change color\", \"adjust scale\"), apply the changes **to the existing chart**.\n`,\n\t),\n});\n\nconst baseChartSchema = z.object({\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Natural language user prompt describing a single action on a chart',\n\t\t),\n});\n\nexport const createChartSchema = baseChartSchema.extend({\n\tchartType: nullableChartType,\n\tchartTitle: z.string().describe('The new chart title'),\n});\n\nexport const updateChartSchema = baseChartSchema.extend({\n\tchartId: chartIdSchema,\n});\n\nexport const updateChartTitleSchema = updateChartSchema.extend({\n\tchartTitle: z.string().describe('The new chart title'),\n});\n\nexport const updateChartTypeSchema = updateChartSchema.extend({\n\tchartType: chartType,\n});\n\nexport const updateChartTypeOfMeasuresSchema = updateChartSchema;\n\nexport const updateChartSortingSchema = updateChartSchema;\n\nexport const updateTrendAndForecastSchema = updateChartSchema;\n\nexport const updateOtherChartDataOptionsSchema = updateChartSchema;\n\nexport const updateChartStyleOptionsSchema = updateChartSchema;\n\n/**\n * Build chart context interface\n */\nexport interface BuildChartContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\t/**\n\t * Data source title (optional)\n\t */\n\tdataSourceTitle?: string;\n\t/** Chart summaries to be used as context */\n\tchartSummaries?: ChartSummary[];\n\t/**\n\t * Retrieve a chart by its ID\n\t * @param chartId - The ID of the chart to retrieve\n\t * @returns The chart widget props\n\t */\n\tretrieveChart?: (chartId: string) => ExtendedChartWidgetProps | null;\n\t/**\n\t * Save a chart widget props\n\t * @param chartId - The ID of the chart to save\n\t * @param chartWidgetProps - The chart widget props to save\n\t */\n\tsaveChart?: (\n\t\tchartId: string,\n\t\tchartWidgetProps: ExtendedChartWidgetProps,\n\t) => void;\n\t/** Whether NLQ V3 is enabled */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\n}\n","/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\n}\n","import { customAlphabet } from 'nanoid';\n\n/**\n * Generate a nanoid with a hex alphabet\n */\nexport const nanoidHex = customAlphabet('0123456789abcdef', 24);\n\n/**\n * Generate a nanoid with a hex alphabet that is a valid UUIDv4\n */\nexport function nanoidUUIDv4(): string {\n\tconst generateId = customAlphabet('0123456789abcdef', 32);\n\tconst id = generateId(); // Generate the actual string\n\n\t// Insert version (4) and variant (8-b)\n\treturn (\n\t\tid.substring(0, 8) +\n\t\t'-' +\n\t\tid.substring(8, 12) +\n\t\t'-' +\n\t\t'4' +\n\t\tid.substring(13, 16) +\n\t\t'-' +\n\t\t((parseInt(id[16], 16) & 0x3) | 0x8).toString(16) +\n\t\tid.substring(17, 20) +\n\t\t'-' +\n\t\tid.substring(20)\n\t);\n}\n","import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from \"../error.mjs\";\nexport function makeParseableResponseFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function makeParseableTextFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableResponseFormat(response_format) {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\nexport function makeParseableTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nexport function maybeParseChatCompletion(completion, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => ({\n ...choice,\n message: {\n ...choice.message,\n parsed: null,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls,\n }\n : undefined),\n },\n })),\n };\n }\n return parseChatCompletion(completion, params);\n}\nexport function parseChatCompletion(completion, params) {\n const choices = completion.choices.map((choice) => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n return {\n ...choice,\n message: {\n ...choice.message,\n ...(choice.message.tool_calls ?\n {\n tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined,\n }\n : undefined),\n parsed: choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n return { ...completion, choices };\n}\nfunction parseResponseFormat(params, content) {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format;\n return response_format.$parseRaw(content);\n }\n return JSON.parse(content);\n }\n return null;\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params) {\n return false;\n }\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\n//# sourceMappingURL=parser.mjs.map","export const ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use');\nconst defaultOptions = {\n name: undefined,\n $refStrategy: 'root',\n effectStrategy: 'input',\n pipeStrategy: 'all',\n dateStrategy: 'format:date-time',\n mapStrategy: 'entries',\n nullableStrategy: 'from-target',\n removeAdditionalStrategy: 'passthrough',\n definitionPath: 'definitions',\n target: 'jsonSchema7',\n strictUnions: false,\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: 'escape',\n applyRegexFlags: false,\n emailStrategy: 'format:email',\n base64Strategy: 'contentEncoding:base64',\n nameStrategy: 'ref',\n};\nexport const getDefaultOptions = (options) => {\n // We need to add `definitions` here as we may mutate it\n return (typeof options === 'string' ?\n {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n name: options,\n }\n : {\n ...defaultOptions,\n basePath: ['#'],\n definitions: {},\n ...options,\n });\n};\n//# sourceMappingURL=Options.mjs.map","export const zodDef = (zodSchema) => {\n return '_def' in zodSchema ? zodSchema._def : zodSchema;\n};\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n//# sourceMappingURL=util.mjs.map","import { getDefaultOptions } from \"./Options.mjs\";\nimport { zodDef } from \"./util.mjs\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined ?\n [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n currentPath: currentPath,\n propertyPath: undefined,\n seenRefs: new Set(),\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n zodDef(def),\n {\n def: zodDef(def),\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n//# sourceMappingURL=Refs.mjs.map","export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n//# sourceMappingURL=errorMessages.mjs.map","export function parseAnyDef() {\n return {};\n}\n//# sourceMappingURL=any.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: 'array',\n };\n if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n//# sourceMappingURL=array.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: 'integer',\n format: 'int64',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=bigint.mjs.map","export function parseBooleanDef() {\n return {\n type: 'boolean',\n };\n}\n//# sourceMappingURL=boolean.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n//# sourceMappingURL=branded.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=catch.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case 'string':\n case 'format:date-time':\n return {\n type: 'string',\n format: 'date-time',\n };\n case 'format:date':\n return {\n type: 'string',\n format: 'date',\n };\n case 'integer':\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: 'integer',\n format: 'unix-time',\n };\n if (refs.target === 'openApi3') {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n//# sourceMappingURL=date.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n//# sourceMappingURL=default.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseEffectsDef(_def, refs, forceResolution) {\n return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {};\n}\n//# sourceMappingURL=effects.mjs.map","export function parseEnumDef(def) {\n return {\n type: 'string',\n enum: [...def.values],\n };\n}\n//# sourceMappingURL=enum.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nconst isJsonSchema7AllOfType = (type) => {\n if ('type' in type && type.type === 'string')\n return false;\n return 'allOf' in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '1'],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if ('additionalProperties' in schema && schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ?\n {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n//# sourceMappingURL=intersection.mjs.map","export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== 'bigint' &&\n parsedType !== 'number' &&\n parsedType !== 'boolean' &&\n parsedType !== 'string') {\n return {\n type: Array.isArray(def.value) ? 'array' : 'object',\n };\n }\n if (refs.target === 'openApi3') {\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n const: def.value,\n };\n}\n//# sourceMappingURL=literal.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nlet emojiRegex;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp('^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$', 'u');\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: 'string',\n };\n function processPattern(value) {\n return refs.patternStrategy === 'escape' ? escapeNonAlphaNumeric(value) : value;\n }\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n break;\n case 'max':\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'email':\n switch (refs.emailStrategy) {\n case 'format:email':\n addFormat(res, 'email', check.message, refs);\n break;\n case 'format:idn-email':\n addFormat(res, 'idn-email', check.message, refs);\n break;\n case 'pattern:zod':\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case 'url':\n addFormat(res, 'uri', check.message, refs);\n break;\n case 'uuid':\n addFormat(res, 'uuid', check.message, refs);\n break;\n case 'regex':\n addPattern(res, check.regex, check.message, refs);\n break;\n case 'cuid':\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case 'cuid2':\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case 'startsWith':\n addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);\n break;\n case 'endsWith':\n addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);\n break;\n case 'datetime':\n addFormat(res, 'date-time', check.message, refs);\n break;\n case 'date':\n addFormat(res, 'date', check.message, refs);\n break;\n case 'time':\n addFormat(res, 'time', check.message, refs);\n break;\n case 'duration':\n addFormat(res, 'duration', check.message, refs);\n break;\n case 'length':\n setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs);\n setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);\n break;\n case 'includes': {\n addPattern(res, RegExp(processPattern(check.value)), check.message, refs);\n break;\n }\n case 'ip': {\n if (check.version !== 'v6') {\n addFormat(res, 'ipv4', check.message, refs);\n }\n if (check.version !== 'v4') {\n addFormat(res, 'ipv6', check.message, refs);\n }\n break;\n }\n case 'emoji':\n addPattern(res, zodPatterns.emoji, check.message, refs);\n break;\n case 'ulid': {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case 'base64': {\n switch (refs.base64Strategy) {\n case 'format:binary': {\n addFormat(res, 'binary', check.message, refs);\n break;\n }\n case 'contentEncoding:base64': {\n setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs);\n break;\n }\n case 'pattern:zod': {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case 'nanoid': {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case 'toLowerCase':\n case 'toUpperCase':\n case 'trim':\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nconst escapeNonAlphaNumeric = (value) => Array.from(value)\n .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\\\${c}`))\n .join('');\nconst addFormat = (schema, value, message, refs) => {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message && refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'format', value, message, refs);\n }\n};\nconst addPattern = (schema, regex, message, refs) => {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: processRegExp(regex, refs),\n ...(message && refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs);\n }\n};\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nconst processRegExp = (regexOrFunction, refs) => {\n const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction;\n if (!refs.applyRegexFlags || !regex.flags)\n return regex.source;\n // Currently handled flags\n const flags = {\n i: regex.flags.includes('i'),\n m: regex.flags.includes('m'),\n s: regex.flags.includes('s'), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = '';\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === '^') {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === '$') {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === '.') {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === '\\\\') {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === ']') {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === '[') {\n inCharGroup = true;\n }\n }\n try {\n const regexTest = new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n};\n//# sourceMappingURL=string.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { parseDef } from \"../parseDef.mjs\";\nimport { parseStringDef } from \"./string.mjs\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: 'object',\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'properties', key],\n }) ?? {},\n }), {}),\n additionalProperties: false,\n };\n }\n const schema = {\n type: 'object',\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? {},\n };\n if (refs.target === 'openApi3') {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {\n const keyType = Object.entries(parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {});\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n return schema;\n}\n//# sourceMappingURL=record.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { parseRecordDef } from \"./record.mjs\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === 'record') {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '0'],\n }) || {};\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '1'],\n }) || {};\n return {\n type: 'array',\n maxItems: 125,\n items: {\n type: 'array',\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n//# sourceMappingURL=map.mjs.map","export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== 'number';\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1 ?\n parsedTypes[0] === 'string' ?\n 'string'\n : 'number'\n : ['string', 'number'],\n enum: actualValues,\n };\n}\n//# sourceMappingURL=nativeEnum.mjs.map","export function parseNeverDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=never.mjs.map","export function parseNullDef(refs) {\n return refs.target === 'openApi3' ?\n {\n enum: ['null'],\n nullable: true,\n }\n : {\n type: 'null',\n };\n}\n//# sourceMappingURL=null.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const primitiveMappings = {\n ZodString: 'string',\n ZodNumber: 'number',\n ZodBigInt: 'integer',\n ZodBoolean: 'boolean',\n ZodNull: 'null',\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === 'openApi3')\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case 'string':\n case 'number':\n case 'boolean':\n return [...acc, type];\n case 'bigint':\n return [...acc, 'integer'];\n case 'object':\n if (x._def.value === null)\n return [...acc, 'null'];\n case 'symbol':\n case 'undefined':\n case 'function':\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === 'ZodEnum')) {\n return {\n type: 'string',\n enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n }))\n .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n//# sourceMappingURL=union.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nimport { primitiveMappings } from \"./union.mjs\";\nexport function parseNullableDef(def, refs) {\n if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [primitiveMappings[def.innerType._def.typeName], 'null'],\n };\n }\n if (refs.target === 'openApi3') {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && '$ref' in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '0'],\n });\n return base && { anyOf: [base, { type: 'null' }] };\n}\n//# sourceMappingURL=nullable.mjs.map","import { addErrorMessage, setResponseValueAndErrors } from \"../errorMessages.mjs\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: 'number',\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case 'int':\n res.type = 'integer';\n addErrorMessage(res, 'type', check.message, refs);\n break;\n case 'min':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs);\n }\n break;\n case 'max':\n if (refs.target === 'jsonSchema7') {\n if (check.inclusive) {\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs);\n }\n break;\n case 'multipleOf':\n setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n//# sourceMappingURL=number.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nfunction decideAdditionalProperties(def, refs) {\n if (refs.removeAdditionalStrategy === 'strict') {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys !== 'strict'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n else {\n return def.catchall._def.typeName === 'ZodNever' ?\n def.unknownKeys === 'passthrough'\n : parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? true;\n }\n}\nexport function parseObjectDef(def, refs) {\n const result = {\n type: 'object',\n ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {\n if (propDef === undefined || propDef._def === undefined)\n return acc;\n const propertyPath = [...refs.currentPath, 'properties', propName];\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: propertyPath,\n propertyPath,\n });\n if (parsedDef === undefined)\n return acc;\n if (refs.openaiStrictMode && propDef.isOptional() && !propDef.isNullable()) {\n console.warn(`Zod field at \\`${propertyPath.join('/')}\\` uses \\`.optional()\\` without \\`.nullable()\\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required\\nThis will become an error in a future version of the SDK.`);\n }\n return {\n properties: {\n ...acc.properties,\n [propName]: parsedDef,\n },\n required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName],\n };\n }, { properties: {}, required: [] }),\n additionalProperties: decideAdditionalProperties(def, refs),\n };\n if (!result.required.length)\n delete result.required;\n return result;\n}\n//# sourceMappingURL=object.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '1'],\n });\n return innerSchema ?\n {\n anyOf: [\n {\n not: {},\n },\n innerSchema,\n ],\n }\n : {};\n};\n//# sourceMappingURL=optional.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === 'input') {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === 'output') {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n//# sourceMappingURL=pipeline.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n//# sourceMappingURL=promise.mjs.map","import { setResponseValueAndErrors } from \"../errorMessages.mjs\";\nimport { parseDef } from \"../parseDef.mjs\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n const schema = {\n type: 'array',\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n//# sourceMappingURL=set.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: 'array',\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalItems'],\n }),\n };\n }\n else {\n return {\n type: 'array',\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n//# sourceMappingURL=tuple.mjs.map","export function parseUndefinedDef() {\n return {\n not: {},\n };\n}\n//# sourceMappingURL=undefined.mjs.map","export function parseUnknownDef() {\n return {};\n}\n//# sourceMappingURL=unknown.mjs.map","import { parseDef } from \"../parseDef.mjs\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n//# sourceMappingURL=readonly.mjs.map","import { ZodFirstPartyTypeKind } from 'zod';\nimport { parseAnyDef } from \"./parsers/any.mjs\";\nimport { parseArrayDef } from \"./parsers/array.mjs\";\nimport { parseBigintDef } from \"./parsers/bigint.mjs\";\nimport { parseBooleanDef } from \"./parsers/boolean.mjs\";\nimport { parseBrandedDef } from \"./parsers/branded.mjs\";\nimport { parseCatchDef } from \"./parsers/catch.mjs\";\nimport { parseDateDef } from \"./parsers/date.mjs\";\nimport { parseDefaultDef } from \"./parsers/default.mjs\";\nimport { parseEffectsDef } from \"./parsers/effects.mjs\";\nimport { parseEnumDef } from \"./parsers/enum.mjs\";\nimport { parseIntersectionDef } from \"./parsers/intersection.mjs\";\nimport { parseLiteralDef } from \"./parsers/literal.mjs\";\nimport { parseMapDef } from \"./parsers/map.mjs\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.mjs\";\nimport { parseNeverDef } from \"./parsers/never.mjs\";\nimport { parseNullDef } from \"./parsers/null.mjs\";\nimport { parseNullableDef } from \"./parsers/nullable.mjs\";\nimport { parseNumberDef } from \"./parsers/number.mjs\";\nimport { parseObjectDef } from \"./parsers/object.mjs\";\nimport { parseOptionalDef } from \"./parsers/optional.mjs\";\nimport { parsePipelineDef } from \"./parsers/pipeline.mjs\";\nimport { parsePromiseDef } from \"./parsers/promise.mjs\";\nimport { parseRecordDef } from \"./parsers/record.mjs\";\nimport { parseSetDef } from \"./parsers/set.mjs\";\nimport { parseStringDef } from \"./parsers/string.mjs\";\nimport { parseTupleDef } from \"./parsers/tuple.mjs\";\nimport { parseUndefinedDef } from \"./parsers/undefined.mjs\";\nimport { parseUnionDef } from \"./parsers/union.mjs\";\nimport { parseUnknownDef } from \"./parsers/unknown.mjs\";\nimport { parseReadonlyDef } from \"./parsers/readonly.mjs\";\nimport { ignoreOverride } from \"./Options.mjs\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n if ('$ref' in seenSchema) {\n refs.seenRefs.add(seenSchema.$ref);\n }\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchema = selectParser(def, def.typeName, refs, forceResolution);\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case 'root':\n return { $ref: item.path.join('/') };\n // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e.\n // the top-level schema *must* be `{\"type\": \"object\", \"properties\": {...}}` but if we ever\n // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract\n // the schema to `#/definitions/` and reference that.\n //\n // e.g. if we need to reference a schema at\n // `[\"#\",\"definitions\",\"contactPerson\",\"properties\",\"person1\",\"properties\",\"name\"]`\n // then we'll extract it out to `contactPerson_properties_person1_properties_name`\n case 'extract-to-root':\n const name = item.path.slice(refs.basePath.length + 1).join('_');\n // we don't need to extract the root schema in this case, as it's already\n // been added to the definitions\n if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') {\n refs.definitions[name] = item.def;\n }\n return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') };\n case 'relative':\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case 'none':\n case 'seen': {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`);\n return {};\n }\n return refs.$refStrategy === 'seen' ? {} : undefined;\n }\n }\n};\nconst getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\nconst selectParser = (def, typeName, refs, forceResolution) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return parseDef(def.getter()._def, refs);\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs, forceResolution);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n//# sourceMappingURL=parseDef.mjs.map","import { parseDef } from \"./parseDef.mjs\";\nimport { getRefs } from \"./Refs.mjs\";\nimport { zodDef, isEmptyObj } from \"./util.mjs\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n const name = typeof options === 'string' ? options\n : options?.nameStrategy === 'title' ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined ? refs : ({\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }), false) ?? {};\n const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ?\n options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n const definitions = (() => {\n if (isEmptyObj(refs.definitions)) {\n return undefined;\n }\n const definitions = {};\n const processedDefinitions = new Set();\n // the call to `parseDef()` here might itself add more entries to `.definitions`\n // so we need to continually evaluate definitions until we've resolved all of them\n //\n // we have a generous iteration limit here to avoid blowing up the stack if there\n // are any bugs that would otherwise result in us iterating indefinitely\n for (let i = 0; i < 500; i++) {\n const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key));\n if (newDefinitions.length === 0)\n break;\n for (const [key, schema] of newDefinitions) {\n definitions[key] =\n parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {};\n processedDefinitions.add(key);\n }\n }\n return definitions;\n })();\n const combined = name === undefined ?\n definitions ?\n {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : refs.nameStrategy === 'duplicate-ref' ?\n {\n ...main,\n ...(definitions || refs.seenRefs.size ?\n {\n [refs.definitionPath]: {\n ...definitions,\n // only actually duplicate the schema definition if it was ever referenced\n // otherwise the duplication is completely pointless\n ...(refs.seenRefs.size ? { [name]: main } : undefined),\n },\n }\n : undefined),\n }\n : {\n $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === 'jsonSchema7') {\n combined.$schema = 'http://json-schema.org/draft-07/schema#';\n }\n else if (refs.target === 'jsonSchema2019-09') {\n combined.$schema = 'https://json-schema.org/draft/2019-09/schema#';\n }\n return combined;\n};\nexport { zodToJsonSchema };\n//# sourceMappingURL=zodToJsonSchema.mjs.map","import { makeParseableResponseFormat, makeParseableTextFormat, makeParseableTool, } from \"../lib/parser.mjs\";\nimport { zodToJsonSchema as _zodToJsonSchema } from \"../_vendor/zod-to-json-schema/index.mjs\";\nimport { makeParseableResponseTool } from \"../lib/ResponsesParser.mjs\";\nfunction zodToJsonSchema(schema, options) {\n return _zodToJsonSchema(schema, {\n openaiStrictMode: true,\n name: options.name,\n nameStrategy: 'duplicate-ref',\n $refStrategy: 'extract-to-root',\n nullableStrategy: 'property',\n });\n}\n/**\n * Creates a chat completion `JSONSchema` response format object from\n * the given Zod schema.\n *\n * If this is passed to the `.parse()`, `.stream()` or `.runTools()`\n * chat completion methods then the response message will contain a\n * `.parsed` property that is the result of parsing the content with\n * the given Zod object.\n *\n * ```ts\n * const completion = await client.beta.chat.completions.parse({\n * model: 'gpt-4o-2024-08-06',\n * messages: [\n * { role: 'system', content: 'You are a helpful math tutor.' },\n * { role: 'user', content: 'solve 8x + 31 = 2' },\n * ],\n * response_format: zodResponseFormat(\n * z.object({\n * steps: z.array(z.object({\n * explanation: z.string(),\n * answer: z.string(),\n * })),\n * final_answer: z.string(),\n * }),\n * 'math_answer',\n * ),\n * });\n * const message = completion.choices[0]?.message;\n * if (message?.parsed) {\n * console.log(message.parsed);\n * console.log(message.parsed.final_answer);\n * }\n * ```\n *\n * This can be passed directly to the `.create()` method but will not\n * result in any automatic parsing, you'll have to parse the response yourself.\n */\nexport function zodResponseFormat(zodObject, name, props) {\n return makeParseableResponseFormat({\n type: 'json_schema',\n json_schema: {\n ...props,\n name,\n strict: true,\n schema: zodToJsonSchema(zodObject, { name }),\n },\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\nexport function zodTextFormat(zodObject, name, props) {\n return makeParseableTextFormat({\n type: 'json_schema',\n ...props,\n name,\n strict: true,\n schema: zodToJsonSchema(zodObject, { name }),\n }, (content) => zodObject.parse(JSON.parse(content)));\n}\n/**\n * Creates a chat completion `function` tool that can be invoked\n * automatically by the chat completion `.runTools()` method or automatically\n * parsed by `.parse()` / `.stream()`.\n */\nexport function zodFunction(options) {\n // @ts-expect-error TODO\n return makeParseableTool({\n type: 'function',\n function: {\n name: options.name,\n parameters: zodToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n },\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\nexport function zodResponsesFunction(options) {\n return makeParseableResponseTool({\n type: 'function',\n name: options.name,\n parameters: zodToJsonSchema(options.parameters, { name: options.name }),\n strict: true,\n ...(options.description ? { description: options.description } : undefined),\n }, {\n callback: options.function,\n parser: (args) => options.parameters.parse(JSON.parse(args)),\n });\n}\n//# sourceMappingURL=zod.mjs.map","/**\n * Utilities for sdk-ai-services\n */\n\n/**\n * Normalize URL by ensuring it ends with a trailing slash\n */\nexport function normalizeUrl(url: string): string {\n\treturn url.endsWith('/') ? url : `${url}/`;\n}\n\n/**\n * Parse error to extract message\n */\nexport const parseError = (error: Error | string | object) => {\n\tif (error instanceof Error) {\n\t\ttry {\n\t\t\treturn JSON.parse(error.message);\n\t\t} catch (e) {\n\t\t\treturn error.message;\n\t\t}\n\t}\n\tif (typeof error === 'string') {\n\t\treturn error;\n\t}\n\treturn error;\n};\n","export function getUrlWithProxy(url: string): string {\n\treturn window.App && window.App.proxyurl\n\t\t? `${window.App.proxyurl}${url}`\n\t\t: url;\n}\n\nexport function getAbsoluteUrlWithProxy(url: string): string {\n\tconst baseUrl =\n\t\twindow.App && window.App.proxyurl\n\t\t\t? window.App.proxyurl\n\t\t\t: `${window.location.protocol}//${window.location.host}`;\n\n\treturn `${baseUrl}${url}`;\n}\n\nexport function getProxyPath(): string {\n\tif (!window.App || !window.App.proxyurl) {\n\t\treturn '';\n\t}\n\n\tconst parser = document.createElement('a');\n\tparser.href = window.App.proxyurl;\n\n\tconst resultPath = parser.pathname.replace(/\\/$/, '');\n\t// if (!isLoggedInUserBelongsToSystemTenant()) {\n\t// const tenantPath = `/${getLoggedInUserTenantName()}`;\n\t// const indexTenantName = resultPath.lastIndexOf(tenantPath);\n\t// if (indexTenantName !== -1) {\n\t// resultPath = `${resultPath.slice(0, indexTenantName)}${resultPath.slice(indexTenantName + tenantPath.length)}`;\n\t// }\n\t// }\n\n\treturn resultPath;\n}\n\nexport function getTenantPrefix() {\n\ttry {\n\t\tconst urlHost = window.location.host;\n\t\tconst {\n\t\t\ttenant: { tenantDomainNames, name: tenantName },\n\t\t} = window.App.user;\n\t\tconst isDNS =\n\t\t\turlHost &&\n\t\t\ttenantDomainNames &&\n\t\t\ttenantDomainNames.some((dnsUrl) => dnsUrl.includes(urlHost));\n\t\tconst tenantPrefix =\n\t\t\tisDNS || tenantName === 'system' ? '' : `/${tenantName}`;\n\n\t\treturn tenantPrefix;\n\t} catch (error) {\n\t\tconsole.debug('no tenant prefix', error);\n\t\treturn '';\n\t}\n}\n\n// function getSessionTimeoutPath(): string {\n// return getUrlWithProxy('/app/account#/timeout?src=');\n// }\n\n// function loadWithProxyURI(proxyURI: string, path: string): Promise<void> {\n// const fullPath = `${proxyURI}${path}`;\n// return core.utils.load(fullPath)\n// .catch((error) => {\n// console.error(`Error while loading ${fullPath}`, error);\n// throw error;\n// });\n// }\n","/**\n * User Action Tracking Utility\n *\n * Provides functionality for generating user action IDs and W3C traceparent headers\n * to enable end-to-end trace visibility across the Assistant, ai-integration, and LLM services.\n *\n * The client generates valid W3C traceparent headers which ai-integration (server-side)\n * uses to create/continue traces in Langfuse. No Langfuse keys are needed on the client.\n */\n\nimport { nanoidHex, nanoidUUIDv4 } from './id-utils';\n\nexport const USER_ACTION_ID_HEADER = 'x-user-action-id';\nexport const TRACEPARENT_HEADER = 'traceparent';\n\nexport function generateUserActionId(): string {\n\treturn nanoidUUIDv4();\n}\n\nexport function generateTraceparent(): string {\n\tconst traceId = nanoidHex(32);\n\tconst spanId = nanoidHex(16);\n\tconst traceFlags = '01';\n\n\treturn `00-${traceId}-${spanId}-${traceFlags}`;\n}\n\nexport interface UserActionHeaders extends Record<string, string> {\n\t[USER_ACTION_ID_HEADER]: string;\n\t[TRACEPARENT_HEADER]: string;\n}\n\nclass UserActionContext {\n\tprivate currentActionId: string | null = null;\n\tprivate currentTraceparent: string | null = null;\n\n\tstartAction(): UserActionHeaders {\n\t\tthis.currentActionId = generateUserActionId();\n\t\tthis.currentTraceparent = generateTraceparent();\n\t\treturn this.getHeaders();\n\t}\n\n\tgetHeaders(): UserActionHeaders {\n\t\tif (!this.currentActionId || !this.currentTraceparent) {\n\t\t\treturn this.startAction();\n\t\t}\n\n\t\treturn {\n\t\t\t[USER_ACTION_ID_HEADER]: this.currentActionId,\n\t\t\t[TRACEPARENT_HEADER]: this.currentTraceparent,\n\t\t};\n\t}\n\n\tendAction(): void {\n\t\tthis.currentActionId = null;\n\t\tthis.currentTraceparent = null;\n\t}\n\n\thasActiveAction(): boolean {\n\t\treturn this.currentActionId !== null;\n\t}\n\n\tgetCurrentActionId(): string | null {\n\t\treturn this.currentActionId;\n\t}\n}\n\nexport const userActionContext = new UserActionContext();\n\nexport function startUserAction(): UserActionHeaders {\n\treturn userActionContext.startAction();\n}\n\nexport function getUserActionHeaders(): UserActionHeaders {\n\treturn userActionContext.getHeaders();\n}\n\nconst DEFAULT_HTTP_CLIENT_HEADERS: Record<string, string> = {\n\tAccept: 'application/json, text/plain, */*',\n\t'Content-Type': 'application/json;charset=UTF-8',\n};\n\nfunction normalizeHeaders(\n\theaders: HeadersInit | undefined,\n): Record<string, string> {\n\tif (!headers) {\n\t\treturn {};\n\t}\n\n\tif (headers instanceof Headers) {\n\t\tconst result: Record<string, string> = {};\n\t\theaders.forEach((value, key) => {\n\t\t\tresult[key] = value;\n\t\t});\n\t\treturn result;\n\t}\n\n\tif (Array.isArray(headers)) {\n\t\tconst result: Record<string, string> = {};\n\t\tfor (const [key, value] of headers) {\n\t\t\tresult[key] = String(value);\n\t\t}\n\t\treturn result;\n\t}\n\n\treturn { ...headers };\n}\n\nexport function withTrackingHeaders(options: RequestInit = {}): RequestInit {\n\tconst trackingHeaders = userActionContext.getHeaders();\n\tconst normalizedHeaders = normalizeHeaders(options.headers);\n\treturn {\n\t\t...options,\n\t\theaders: {\n\t\t\t...DEFAULT_HTTP_CLIENT_HEADERS,\n\t\t\t...normalizedHeaders,\n\t\t\t...trackingHeaders,\n\t\t},\n\t};\n}\n\nexport function endUserAction(): void {\n\tuserActionContext.endAction();\n}\n","import {\n\tAuthenticator,\n\tgetAuthenticator,\n\tHttpClient,\n} from '@sisense/sdk-rest-client';\nimport { normalizeUrl } from '@/utils/utils';\nimport { getTenantPrefix } from './proxy-utils';\nimport {\n\tgetUserActionHeaders,\n\tUSER_ACTION_ID_HEADER,\n\tTRACEPARENT_HEADER,\n} from './user-action-tracking';\n\n// Re-export from CSDK for convenience\nexport type AuthenticatorConfig = {\n\turl: string;\n\tusername?: string;\n\tpassword?: string;\n\ttoken?: string | null;\n\twat?: string | null;\n\tssoEnabled?: boolean;\n\tenableSilentPreAuth?: boolean;\n\tuseFusionAuth?: boolean;\n\talternativeSsoHost?: string;\n};\n\n/**\n * Factory function to create an HTTP client from an authenticator\n * @param url - The URL to use for the HTTP client\n * @param authenticator - The authenticator to use for the HTTP client\n * @returns Configured HttpClient instance\n */\nexport function createHttpClientFromAuthenticator(\n\turl: string,\n\tauthenticator: Authenticator,\n): HttpClient {\n\tlet tenantPrefix = getTenantPrefix();\n\tif (tenantPrefix.startsWith('/')) {\n\t\ttenantPrefix = tenantPrefix.slice(1);\n\t}\n\tconst httpClientInstance = new HttpClient(\n\t\t`${normalizeUrl(url)}${tenantPrefix}`,\n\t\tauthenticator,\n\t\t'sdk-ai-core' + (__PACKAGE_VERSION__ ? `-${__PACKAGE_VERSION__}` : ''),\n\t);\n\thttpClientInstance.login();\n\treturn httpClientInstance;\n}\n\n/**\n * Factory function to create an HTTP client from an authenticator configuration\n * @param config - Authenticator configuration\n * @returns Configured HttpClient instance\n */\nexport function createHttpClientFromConfig(\n\tconfig: AuthenticatorConfig,\n): HttpClient {\n\tconst authenticator = getAuthenticator(config);\n\n\tif (!authenticator) {\n\t\tthrow new Error('Invalid authentication method');\n\t}\n\n\treturn createHttpClientFromAuthenticator(config.url, authenticator);\n}\n\nconst ALLOWED_TRACKING_HEADERS = [\n\tUSER_ACTION_ID_HEADER.toLowerCase(),\n\tTRACEPARENT_HEADER.toLowerCase(),\n];\n\n/**\n * Factory function to create a custom fetch function for OpenAI chat completions\n * This fetch function applies authentication headers from the provided httpClient\n * @param httpClient - The HTTP client instance to use for authentication\n * @returns Custom fetch function\n */\nexport function createCustomFetch(httpClient: HttpClient) {\n\treturn async (\n\t\turl: RequestInfo | URL,\n\t\tinit?: RequestInit,\n\t): Promise<Response> => {\n\t\tif (!url.toString().includes('chat/completions')) {\n\t\t\tthrow new Error('Use httpClient for non-completion requests');\n\t\t}\n\n\t\tconst headers = new Headers();\n\t\tconst isBearerAuth = httpClient.auth.type === 'bearer';\n\n\t\tif (init?.headers) {\n\t\t\tconst originalHeaders = new Headers(init.headers);\n\t\t\t// Sisense server doesn't allow `x-` headers except for allowed tracking headers\n\t\t\t// httpClient sets its own authorization header\n\t\t\toriginalHeaders.forEach((value, key) => {\n\t\t\t\tconst lowerKey = key.toLowerCase();\n\t\t\t\tconst isAllowedTrackingHeader =\n\t\t\t\t\tALLOWED_TRACKING_HEADERS.includes(lowerKey);\n\t\t\t\tif (\n\t\t\t\t\tisAllowedTrackingHeader ||\n\t\t\t\t\t(!lowerKey.startsWith('x-') &&\n\t\t\t\t\t\t(isBearerAuth || lowerKey !== 'authorization'))\n\t\t\t\t) {\n\t\t\t\t\theaders.set(key, value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst trackingHeaders = getUserActionHeaders();\n\t\theaders.set(\n\t\t\tUSER_ACTION_ID_HEADER,\n\t\t\ttrackingHeaders[USER_ACTION_ID_HEADER],\n\t\t);\n\t\theaders.set(TRACEPARENT_HEADER, trackingHeaders[TRACEPARENT_HEADER]);\n\n\t\thttpClient.auth.applyHeaders(headers);\n\t\tconst newInit = { ...(init || {}), headers };\n\t\treturn fetch(url, newInit);\n\t};\n}\n","import { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport { createCustomFetch } from './http-client';\nimport { normalizeUrl } from './utils';\n\nconst OPENAI_API_URL_PATH = 'api/v2/ai';\n\n/**\n * Factory function to create an OpenAI client with custom configuration\n * @param baseURL - The base URL for the OpenAI API endpoint\n * @param fetchFn - Custom fetch function (e.g., with authentication headers)\n * @returns Configured OpenAI client instance\n */\nexport function createOpenAIClientHelper(\n\tbaseURL: string,\n\tfetchFn: typeof fetch,\n): OpenAI {\n\treturn new OpenAI({\n\t\t// @ts-expect-error - OpenAI client requires apiKey but we're using custom auth\n\t\tapiKey: null,\n\t\tdangerouslyAllowBrowser: true,\n\t\tbaseURL,\n\t\tfetch: fetchFn,\n\t});\n}\n\nexport function createOpenAIClient(httpClient: HttpClient): OpenAI {\n\tconst baseURL = normalizeUrl(httpClient.url) + OPENAI_API_URL_PATH;\n\treturn createOpenAIClientHelper(baseURL, createCustomFetch(httpClient));\n}\n","// ============================================================================\n// Lazy Initialization of HttpClient singleton\n// ============================================================================\n\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport {\n\tAuthenticatorConfig,\n\tcreateHttpClientFromAuthenticator,\n} from './utils/http-client';\nimport { createHttpClientFromConfig } from './utils/http-client';\nimport { createOpenAIClient } from './utils/openai-client';\n\nlet httpClientInstance: HttpClient | null = null;\n\n/**\n * Set a pre-created HttpClient instance (similar to initializeSisenseServices)\n * Useful when the consuming app already has an HttpClient instance\n *\n * @param httpClient - Pre-created HttpClient instance\n */\nexport function initializeHttpClient(httpClient: HttpClient): void {\n\thttpClientInstance = httpClient;\n}\n\n/**\n * Get the shared HttpClient instance (lazy initialization)\n *\n * @returns The HttpClient instance\n * @throws Error if client hasn't been initialized\n */\nexport function getHttpClient(): HttpClient {\n\tif (!httpClientInstance) {\n\t\tthrow new Error(\n\t\t\t'HttpClient not initialized. Create one using createHttpClient() and then initialize it using initializeHttpClient().',\n\t\t);\n\t}\n\treturn httpClientInstance;\n}\n\n/**\n * Reset the http client\n * This function is useful when the consuming app needs to switch tenant or login to another user\n */\nexport function resetHttpClient(): void {\n\tconst currentHttpClient = getHttpClient();\n\tconst url = currentHttpClient.url;\n\tconst authenticator = currentHttpClient.auth;\n\tconst httpClient = createHttpClientFromAuthenticator(url, authenticator);\n\tinitializeHttpClient(httpClient);\n}\n\n// ============================================================================\n// Lazy Initialization of OpenAI client singleton\n// ============================================================================\n\nlet openAIClientInstance: OpenAI | null = null;\n\n/**\n * Set a pre-created OpenAI client instance (similar to initializeSisenseServices)\n * Useful when the consuming app already has an OpenAI client instance\n *\n * @param openAIClient - Pre-created OpenAI client instance\n */\nexport function initializeOpenAIClient(openAIClient: OpenAI): void {\n\topenAIClientInstance = openAIClient;\n}\n\n/**\n * Get the shared OpenAI client instance (lazy initialization)\n *\n * @returns The OpenAI client instance\n * @throws Error if client hasn't been initialized\n */\nexport function getOpenAIClient(): OpenAI {\n\tif (!openAIClientInstance) {\n\t\tthrow new Error(\n\t\t\t'OpenAI client not initialized. Create one using createOpenAIClient() and then initialize it using initializeOpenAIClient().',\n\t\t);\n\t}\n\treturn openAIClientInstance;\n}\n\n/**\n * Reset the OpenAI client (useful for testing)\n *\n * Allows tests to clean up or reset the shared instance between test runs\n */\nexport function resetOpenAIClient(): void {\n\tconst openAIClient = createOpenAIClient(getHttpClient());\n\tinitializeOpenAIClient(openAIClient);\n}\n\n/**\n * Initialize the HttpClient and OpenAI client singletons\n * @param authConfig - Authenticator configuration\n */\nexport function initializeClients(authConfig: AuthenticatorConfig): void {\n\t// Create and initialize HttpClient singleton\n\tconst httpClient = createHttpClientFromConfig(authConfig);\n\tinitializeHttpClient(httpClient);\n\n\t// Create and initialize OpenAI client singleton\n\tconst openAIClient = createOpenAIClient(httpClient);\n\tinitializeOpenAIClient(openAIClient);\n}\n","import { zodResponseFormat } from 'openai/helpers/zod';\nimport { z } from 'zod';\nimport type { OpenAI } from 'openai';\nimport { ChatCompletionMessageParam } from 'openai/resources/chat/completions';\nimport { getOpenAIClient } from '@/singleton-clients';\n\ntype StructuredCompletionParams<T> = {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\tresponseFormat:\n\t\t| { type: 'json_schema'; schema: z.ZodSchema<T>; name: string }\n\t\t| { type: 'json_object' };\n\tmodel?: string;\n\ttemperature?: number;\n\tsessionId?: string | null;\n\topenAIClient?: OpenAI;\n};\n\n/**\n * Creates a structured completion using OpenAI with consistent configuration\n * across all tools.\n */\nexport async function createStructuredCompletion<T>(\n\tparams: StructuredCompletionParams<T>,\n): Promise<T> {\n\tconst {\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat,\n\t\tmodel = 'gpt-4o-mini',\n\t\ttemperature = 0,\n\t\tsessionId,\n\t\topenAIClient = getOpenAIClient(),\n\t} = params;\n\n\t// Determine response format for OpenAI\n\tconst openAiResponseFormat =\n\t\tresponseFormat.type === 'json_schema'\n\t\t\t? zodResponseFormat(responseFormat.schema, responseFormat.name)\n\t\t\t: { type: 'json_object' as const };\n\n\tconst response = await openAIClient.beta.chat.completions.parse({\n\t\tmodel,\n\t\tmessages: [\n\t\t\t{ role: 'system', content: systemPrompt },\n\t\t\t{ role: 'user', content: userPrompt },\n\t\t],\n\t\tresponse_format: openAiResponseFormat,\n\t\ttools: [],\n\t\ttool_choice: 'none',\n\t\ttemperature,\n\t\tmetadata: sessionId ? { refSessionId: sessionId } : undefined,\n\t});\n\n\t// Handle response based on format type\n\tconst message = response.choices[0].message;\n\n\tif (responseFormat.type === 'json_schema') {\n\t\t// Check if response comes as tool_calls (structured output sometimes returns this way)\n\t\tif (message.tool_calls && message.tool_calls.length > 0) {\n\t\t\tconst toolCall = message.tool_calls[0];\n\t\t\tif (toolCall.function && toolCall.function.arguments) {\n\t\t\t\tconst parsedArguments = JSON.parse(toolCall.function.arguments);\n\t\t\t\treturn parsedArguments as T;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to parsed content (standard structured output)\n\t\tconst parsedResponse = message.parsed as T;\n\t\tif (!parsedResponse) {\n\t\t\tthrow new Error('No valid response from AI');\n\t\t}\n\t\treturn parsedResponse;\n\t} else {\n\t\t// Handle JSON object responses\n\t\tconst content = message.content || '{}';\n\t\tconst parsedResponse = JSON.parse(content);\n\t\tif (!parsedResponse) {\n\t\t\tthrow new Error('No valid response from AI');\n\t\t}\n\t\treturn parsedResponse as T;\n\t}\n}\n\ntype ToolsCompletionParams = {\n\tsystemPrompt: string;\n\tuserPrompt: string;\n\ttools: any[];\n\tmodel?: string;\n\ttemperature?: number;\n\ttoolChoice?:\n\t\t| 'auto'\n\t\t| 'none'\n\t\t| { type: 'function'; function: { name: string } };\n\topenAIClient?: OpenAI;\n};\n\n// Generic message type to avoid dependency on assistant's Message type\ntype GenericMessage = {\n\trole: string;\n\tcontent?: string | any;\n\ttool_call_id?: string;\n\t[key: string]: any;\n};\n\ntype ToolsCompletionResult = {\n\ttoolMessages: GenericMessage[];\n\tassistantMessages: string[];\n\tcombinedMessage: string;\n\tisError: boolean;\n};\n\n/**\n * Creates a tools completion using OpenAI with streaming support.\n * Returns captured messages and a combined message string ready for use.\n */\nexport async function createToolsCompletion(\n\tparams: ToolsCompletionParams,\n): Promise<ToolsCompletionResult> {\n\tconst {\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\ttools,\n\t\tmodel = 'gpt-4o-mini',\n\t\ttemperature = 0,\n\t\ttoolChoice = 'auto',\n\t\topenAIClient = getOpenAIClient(),\n\t} = params;\n\n\treturn new Promise<ToolsCompletionResult>((resolve) => {\n\t\tconst toolMessages: GenericMessage[] = [];\n\t\tconst assistantMessages: string[] = [];\n\n\t\topenAIClient.beta.chat.completions\n\t\t\t.runTools({\n\t\t\t\tmessages: [\n\t\t\t\t\t{\n\t\t\t\t\t\trole: 'system',\n\t\t\t\t\t\tcontent: systemPrompt,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\trole: 'user',\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\t\t\ttext: userPrompt,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmodel,\n\t\t\t\tstream: true,\n\t\t\t\ttemperature,\n\t\t\t\ttools,\n\t\t\t\ttool_choice: toolChoice,\n\t\t\t})\n\t\t\t.on('message', (message: ChatCompletionMessageParam) => {\n\t\t\t\tif (message.role === 'tool') {\n\t\t\t\t\ttoolMessages.push(message as GenericMessage);\n\t\t\t\t} else if (message.role === 'assistant' && message.content) {\n\t\t\t\t\tassistantMessages.push(message.content as string);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tlet isError = false;\n\t\t\t\tlet combinedMessage = '';\n\n\t\t\t\ttry {\n\t\t\t\t\t// Extract tool messages\n\t\t\t\t\tconst toolMessagesText = toolMessages\n\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t(message) =>\n\t\t\t\t\t\t\t\tJSON.parse(message.content as string).message,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.join('\\n');\n\n\t\t\t\t\tconst assistantMessagesText = assistantMessages.join('\\n');\n\n\t\t\t\t\t// Error Detection Logic:\n\t\t\t\t\tif (\n\t\t\t\t\t\ttoolMessages.length === 0 &&\n\t\t\t\t\t\tassistantMessages.length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\t// LLM didn't execute tools but provided explanation\n\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\tcombinedMessage = assistantMessagesText; // Use LLM's explanation as error message\n\t\t\t\t\t} else if (\n\t\t\t\t\t\ttoolMessages.length === 0 &&\n\t\t\t\t\t\tassistantMessages.length === 0\n\t\t\t\t\t) {\n\t\t\t\t\t\t// No tools and no explanation - something went wrong\n\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\tcombinedMessage =\n\t\t\t\t\t\t\t'No tools executed and no response from LLM';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Tools were executed - combine normally\n\t\t\t\t\t\tcombinedMessage = [\n\t\t\t\t\t\t\ttoolMessagesText,\n\t\t\t\t\t\t\tassistantMessagesText,\n\t\t\t\t\t\t]\n\t\t\t\t\t\t\t.filter(Boolean)\n\t\t\t\t\t\t\t.join('\\n');\n\n\t\t\t\t\t\t// Check if results are empty despite tool execution\n\t\t\t\t\t\tif (combinedMessage.trim() === '') {\n\t\t\t\t\t\t\tisError = true;\n\t\t\t\t\t\t\tcombinedMessage =\n\t\t\t\t\t\t\t\t'Tools executed but returned empty results';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tisError = true;\n\t\t\t\t\tcombinedMessage = 'Malformed tool response detected';\n\t\t\t\t}\n\n\t\t\t\tresolve({\n\t\t\t\t\ttoolMessages,\n\t\t\t\t\tassistantMessages,\n\t\t\t\t\tcombinedMessage,\n\t\t\t\t\tisError,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on('error', (err: Error) => {\n\t\t\t\t// Handle Error objects properly - JSON.stringify on Error returns {}\n\t\t\t\tconst errorMessage =\n\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t? JSON.stringify(\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tname: err.name,\n\t\t\t\t\t\t\t\t\tmessage: err.message,\n\t\t\t\t\t\t\t\t\tstack: err.stack,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t )\n\t\t\t\t\t\t: JSON.stringify(err, null, 2);\n\t\t\t\tresolve({\n\t\t\t\t\ttoolMessages: [],\n\t\t\t\t\tassistantMessages: [],\n\t\t\t\t\tcombinedMessage: errorMessage,\n\t\t\t\t\tisError: true,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n","import { z } from 'zod';\nimport { ChartType } from '@sisense/sdk-ui';\nimport type { OpenAI } from 'openai';\nimport { chartRecommendationsSchema, Column, ColumnType } from '../types';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\n\nconst systemPrompt = `\nYou are an expert in chart visualization and data query structuring. Your task is to assist users in generating the optimal chart type and axes mapping based on their input, adhering to the provided schema (schema object with chartType and axesMapping). Your goal is to interpret the user's prompt, analyze the provided column data, select an appropriate chart type (unless specified by the user), and map column indices to the axes mapping arrays in a way that produces a valid, effective visualization.\n\nDO NOT use any tools.\n\n### Input Expectations\n- **User Prompt**: A natural language description of the desired visualization (e.g., \"Show sales over time by region\" or \"Compare product prices\").\n- **Column Data**: A list of columns adhering to the Column interface (e.g., { id: 0, name: \"Sales\", type: \"number\" } ), representing available data fields.\n- If the user provides only a prompt without column data, assume a reasonable set of columns based on the prompt and state your assumptions.\n\n### Chart Selection Process\n1. If the user specifies a chart type, use it and proceed to axes mapping.\n2. Otherwise, determine the best chart type by:\n - Analyzing the data types of columns (e.g., numeric, categorical, temporal, geographic).\n - Identifying relationships in the prompt (e.g., trends over time, comparisons, distributions).\n - Matching to a suitable chart type from chartTypes (e.g., bar for comparisons, line for trends, pie for proportions).\n - Default to bar for categorical-numeric pairs if no clear choice emerges.\n3. Ensure the selected chart type aligns with the corresponding axesMapping schema (e.g., cartesianChartSchema for bar).\n\n### Axes Mapping Guidelines\n- Map column indices (from id in Column) to the appropriate arrays in the axesMapping object (e.g., category, value, x, y).\n- Prioritize essential fields first:\n - For cartesian charts: Fill category (e.g., time, names) and value (e.g., numbers) before optional fields like breakBy.\n - For scatter charts: Fill x and y before breakByPoint or size.\n - For categorical charts: Fill category and value.\n- Columns can appear in multiple arrays only if logical (e.g., a category used in both category and breakBy for stacked bars).\n- Respect schema constraints (e.g., z.strict() means no extra fields; required arrays like value must be non-empty).\n\n### Edge Cases\n- If insufficient columns are provided, suggest additional columns needed (e.g., \"A time column is required for a line chart\").\n- If the user-specified chart type conflicts with data (e.g., pie with continuous data), recommend an alternative and explain why.\n- If a column's role is ambiguous, infer based on type (e.g., string → category, number → value) and prompt context.\n\n### Output Format\nReturn a JSON object matching the schema structure, with:\n- chartType: The selected or user-specified chart type.\n- axesMapping: The populated axes mapping object per the relevant schema.\nProvide a brief explanation of your chart type choice and axes mapping decisions, referencing the prompt and column data.\n`;\n\nfunction mapColumnIndicesToObjects(\n\tindices: number[] | undefined,\n\tcolumns: ColumnType[],\n): { column: ColumnType }[] {\n\tif (!indices) return [];\n\treturn indices\n\t\t.map((index) => ({\n\t\t\tcolumn: columns[index],\n\t\t}))\n\t\t.filter(({ column }) => Boolean(column));\n}\n\nfunction mapChartDataToColumns(\n\trecommendations: z.infer<typeof chartRecommendationsSchema>,\n\tcolumns: ColumnType[],\n): z.infer<typeof chartRecommendationsSchema> {\n\tif (!recommendations) return recommendations;\n\n\tconst mapping = recommendations.axesMapping;\n\tconst result = {\n\t\tchartType: recommendations.chartType,\n\t\taxesMapping: {} as any,\n\t};\n\n\tfor (const [key, value] of Object.entries(mapping)) {\n\t\tif (key === 'type') continue;\n\n\t\tif (Array.isArray(value)) {\n\t\t\tresult.axesMapping[key] = mapColumnIndicesToObjects(value, columns);\n\t\t} else {\n\t\t\tresult.axesMapping[key] = value;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport const generateChartRecommendations = async (\n\tuserPrompt: string,\n\tcolumns: ColumnType[] = [],\n\tchartType: ChartType | undefined,\n\topenAIClient?: OpenAI,\n): Promise<z.infer<typeof chartRecommendationsSchema>> => {\n\tconst cols: Column[] = [];\n\tlet i = 0;\n\tfor (const c of columns) {\n\t\tconst name = 'column' in c ? c.column?.name : c.name;\n\t\tconst type = (() => {\n\t\t\tif ('column' in c && c.column && 'type' in c.column) {\n\t\t\t\treturn c.column.type;\n\t\t\t}\n\t\t\tif ('type' in c && typeof c.type === 'string') {\n\t\t\t\treturn c.type;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\tcols.push({ id: i++, name, type });\n\t}\n\n\tlet prompt = userPrompt + `\\n\\n${JSON.stringify(cols)}`;\n\tif (chartType) {\n\t\tprompt += `\n\t\tUser selected the following chart type: ${chartType} \\n\n\t\t`;\n\t}\n\n\tconst recommendations = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt: prompt,\n\t\tresponseFormat: {\n\t\t\ttype: 'json_schema',\n\t\t\tschema: chartRecommendationsSchema,\n\t\t\tname: 'chartRecommendations',\n\t\t},\n\t\topenAIClient,\n\t});\n\n\tconst updatedRecommendations = mapChartDataToColumns(\n\t\trecommendations,\n\t\tcolumns,\n\t);\n\n\tswitch (updatedRecommendations.chartType) {\n\t\tcase 'scatter':\n\t\t\t(updatedRecommendations.axesMapping as any).x = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).x[0];\n\t\t\t(updatedRecommendations.axesMapping as any).y = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).y[0];\n\t\t\t(updatedRecommendations.axesMapping as any).breakByPoint = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).breakByPoint[0];\n\t\t\t(updatedRecommendations.axesMapping as any).breakByColor = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).breakByColor[0];\n\t\t\t(updatedRecommendations.axesMapping as any).size = (\n\t\t\t\tupdatedRecommendations.axesMapping as any\n\t\t\t).size[0];\n\t\t\tbreak;\n\t\tcase 'indicator':\n\t\t\t(updatedRecommendations.axesMapping as any).secondary = [];\n\t\t\tbreak;\n\t}\n\n\treturn updatedRecommendations;\n};\n","import {\n\tNlqResult,\n\tNlqResultChartType,\n\tQueryRecommendationResponse,\n} from '@sisense/sdk-ui/ai';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { getHttpClient } from '@/singleton-clients';\nimport {\n\tDataSchemaContext,\n\tNlqResponseJSON,\n} from '@sisense/sdk-ui/analytics-composer';\nimport { withTrackingHeaders } from '@/utils/user-action-tracking';\n\nexport interface GetNlqResultRequest {\n\ttext: string;\n\ttimezone?: string;\n\tchartTypes: NlqResultChartType[];\n}\n\nexport interface GetNlqResultLightRequest {\n\ttext: string;\n\ttimezone?: string;\n}\n\nexport interface GetNlqV3ResultRequest {\n\ttext: string;\n\ttimezone?: string;\n\tchartTypes?: NlqResultChartType[];\n\tforceGeneration: boolean;\n}\n\nexport interface NlqV3Result {\n\tchartState: NlqResponseJSON;\n\tdataSchema: DataSchemaContext;\n\tclarification?: string;\n\ttimestamp: string;\n}\n\nexport interface QueryRecommendationConfig {\n\tnumOfRecommendations: number;\n\tuserPrompt?: string;\n}\n\nexport async function getNlqResult(\n\tcontextTitle: string,\n\trequest: GetNlqResultRequest,\n\thttpClient?: HttpClient,\n): Promise<NlqResult | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.post<NlqResult>(\n\t\t`api/v2/ai/nlq/query/${contextTitle}`,\n\t\trequest,\n\t\twithTrackingHeaders(),\n\t);\n\treturn result ?? null;\n}\n\nexport async function getNlqResultLight(\n\tcontextTitle: string,\n\trequest: GetNlqResultLightRequest,\n\thttpClient?: HttpClient,\n): Promise<NlqResult | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.post<NlqResult>(\n\t\t`api/v2/ai/nlq/query-light/${contextTitle}`,\n\t\trequest,\n\t\twithTrackingHeaders(),\n\t);\n\treturn result ?? null;\n}\n\nexport async function getNlqV3Result(\n\tcontextTitle: string,\n\trequest: GetNlqV3ResultRequest,\n\thttpClient?: HttpClient,\n): Promise<NlqV3Result | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.post<NlqV3Result>(\n\t\t`api/v2/ai/nlq/smartQuery/${contextTitle}`,\n\t\trequest,\n\t\twithTrackingHeaders(),\n\t);\n\treturn result ?? null;\n}\n\nexport async function getQueryRecommendations(\n\tcontextTitle: string,\n\tconfig: QueryRecommendationConfig,\n\thttpClient?: HttpClient,\n): Promise<QueryRecommendationResponse | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.get<QueryRecommendationResponse>(\n\t\t`api/v2/ai/recommendations/query/${contextTitle}/${config.numOfRecommendations}`,\n\t\twithTrackingHeaders(),\n\t);\n\treturn result ?? null;\n}\n\nexport async function getQueryRecommendationsLight(\n\tcontextTitle: string,\n\tconfig: QueryRecommendationConfig,\n\thttpClient?: HttpClient,\n): Promise<QueryRecommendationResponse | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.get<QueryRecommendationResponse>(\n\t\t`api/v2/ai/recommendations/query-light/${contextTitle}/${\n\t\t\tconfig.numOfRecommendations\n\t\t}${config.userPrompt ? `?userPrompt=${config.userPrompt}` : ''}`,\n\t\twithTrackingHeaders(),\n\t);\n\treturn result ?? null;\n}\n","// Store removed - config injected via params\nimport { ExtendedChartWidgetProps } from '../types';\nimport {\n\ttranslateQueryJSON,\n\ttranslateQueryToJaql,\n\twidgetComposer,\n} from '@sisense/sdk-ui/analytics-composer';\nimport { isChartWidgetProps } from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { convertDataSource } from '@sisense/sdk-data';\nimport { getNlqResultLight, getNlqV3Result } from '@/services/nlq/nlq-service';\n\nconst generateChartTableFromNlqV2 = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n\thttpClient?: HttpClient,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst nlqResult = await getNlqResultLight(\n\t\tdataSourceTitle,\n\t\t{\n\t\t\ttext: userPrompt,\n\t\t\ttimezone: 'UTC',\n\t\t},\n\t\thttpClient,\n\t);\n\n\tif (!nlqResult) {\n\t\tthrow new Error(\n\t\t\t'Error: Failed to get NLQ result. Ask the user to specify the data source again.',\n\t\t);\n\t}\n\n\tconst widgetProps = widgetComposer.toWidgetProps(\n\t\t{ ...nlqResult, chartRecommendations: {} },\n\t\t{\n\t\t\tuseCustomizedStyleOptions: true,\n\t\t},\n\t) as ExtendedChartWidgetProps;\n\n\tif (!widgetProps) {\n\t\tthrow new Error('Error: Failed to generate widget props');\n\t}\n\twidgetProps.nlqResponse = nlqResult;\n\n\tif (!isChartWidgetProps(widgetProps)) {\n\t\tthrow new Error('Error: Non-chart widget props not supported yet');\n\t}\n\n\t// set widget title if it's not set\n\twidgetProps.title = widgetProps.title || nlqResult.nlqPrompt || userPrompt;\n\n\treturn widgetProps;\n};\n\nconst generateChartTableFromNlqV3 = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n\thttpClient?: HttpClient,\n): Promise<ExtendedChartWidgetProps> => {\n\ttry {\n\t\tconst nlqResult = await getNlqV3Result(\n\t\t\tdataSourceTitle,\n\t\t\t{\n\t\t\t\ttext: userPrompt,\n\t\t\t\tforceGeneration: true,\n\t\t\t},\n\t\t\thttpClient,\n\t\t);\n\t\tif (!nlqResult) {\n\t\t\tthrow new Error('Error: Failed to get NLQ result.');\n\t\t}\n\t\tconst dataSchema = nlqResult.dataSchema;\n\t\tif (!dataSchema) {\n\t\t\tthrow new Error('Error: Data schema not found');\n\t\t}\n\n\t\tconst translationResult = translateQueryJSON({\n\t\t\tdata: nlqResult.chartState,\n\t\t\tcontext: dataSchema,\n\t\t});\n\t\tif (!translationResult.success) {\n\t\t\tthrow new Error(\n\t\t\t\t'Error: Failed to translate query JSON: ' +\n\t\t\t\t\tJSON.stringify(translationResult.errors),\n\t\t\t);\n\t\t}\n\n\t\tconst translatedParams = translationResult.data;\n\t\tconst jaql = translateQueryToJaql(\n\t\t\ttranslatedParams,\n\t\t\tconvertDataSource(dataSchema.dataSource),\n\t\t);\n\n\t\tconst columns = [\n\t\t\t...(translatedParams.dimensions || []),\n\t\t\t...(translatedParams.measures || []),\n\t\t];\n\n\t\tconst widgetProps: ExtendedChartWidgetProps = {\n\t\t\ttitle: userPrompt,\n\t\t\tid: nanoidHex(),\n\t\t\twidgetType: 'chart',\n\t\t\tdataSource: translatedParams.dataSource,\n\t\t\tchartType: 'table',\n\t\t\tdataOptions: { columns },\n\t\t\tfilters: translatedParams.filters || [],\n\t\t\thighlights: translatedParams.highlights || [],\n\t\t\tnlqResponse: {\n\t\t\t\tchartRecommendations: {},\n\t\t\t\tdetailedDescription: userPrompt,\n\t\t\t\tnlqPrompt: userPrompt,\n\t\t\t\tuserMsg: userPrompt,\n\t\t\t\tqueryTitle: userPrompt,\n\t\t\t\tjaql,\n\t\t\t},\n\t\t};\n\n\t\treturn widgetProps;\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t'Error: Failed to generate chart table from NLQ V3. Falling back to NLQ V2.',\n\t\t\terror,\n\t\t);\n\t\treturn generateChartTableFromNlqV2(\n\t\t\tdataSourceTitle,\n\t\t\tuserPrompt,\n\t\t\thttpClient,\n\t\t);\n\t}\n};\n\nexport const generateChartTable = async (\n\tdataSourceTitle: string,\n\tuserPrompt: string,\n\tisNlqV3Enabled?: boolean,\n\thttpClient?: HttpClient,\n) => {\n\tif (isNlqV3Enabled) {\n\t\tconsole.debug('Generating chart table from NLQ V3');\n\t\treturn generateChartTableFromNlqV3(\n\t\t\tdataSourceTitle,\n\t\t\tuserPrompt,\n\t\t\thttpClient,\n\t\t);\n\t} else {\n\t\tconsole.debug('Generating chart table from NLQ V2');\n\t\treturn generateChartTableFromNlqV2(\n\t\t\tdataSourceTitle,\n\t\t\tuserPrompt,\n\t\t\thttpClient,\n\t\t);\n\t}\n};\n","import { ChartDataOptions, TableDataOptions } from '@sisense/sdk-ui';\nimport {\n\tAxesMapping,\n\tgetChartStyleOptions,\n} from '@sisense/sdk-ui/analytics-composer';\nimport {\n\tBuildChartContext,\n\tcreateChartSchema,\n\tExtendedChartWidgetProps,\n\tNullableChartType,\n} from '../types';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { generateChartRecommendations } from './generate-chart-recommendations';\nimport { generateChartTable } from './generate-chart-table';\n\nimport z from 'zod';\n\ntype GenerateChartParams = {\n\tdataSourceTitle: string;\n\tuserPrompt: string;\n\tchartType: NullableChartType;\n\tchartTitle: string;\n};\n\nexport const generateChart = async (\n\t{ dataSourceTitle, userPrompt, chartType, chartTitle }: GenerateChartParams,\n\tcontext: BuildChartContext,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst widgetProps = await generateChartTable(\n\t\tdataSourceTitle,\n\t\tuserPrompt,\n\t\tcontext.isNlqV3Enabled ?? false,\n\t\tcontext.httpClient,\n\t);\n\n\tconst dataColumns = (widgetProps.dataOptions as TableDataOptions).columns;\n\n\tconst chartRecommendations = await generateChartRecommendations(\n\t\tuserPrompt,\n\t\tdataColumns,\n\t\tchartType!,\n\t\tcontext.openAIClient,\n\t);\n\twidgetProps.nlqResponse!.chartRecommendations =\n\t\tchartRecommendations || widgetProps.nlqResponse!.chartRecommendations;\n\n\tconst { axesMapping, chartType: newChartType } = chartRecommendations;\n\n\twidgetProps.dataOptions = axesMapping as ChartDataOptions;\n\twidgetProps.chartType = newChartType;\n\twidgetProps.title = chartTitle;\n\n\tconst baseStyleOptions = getChartStyleOptions(\n\t\tnewChartType,\n\t\twidgetProps.dataOptions as AxesMapping,\n\t\t{},\n\t\ttrue,\n\t);\n\n\t// while dashboard assistant shows expanded chart with legend on the right, we want to show it on the bottom\n\twidgetProps.styleOptions = {\n\t\t...baseStyleOptions,\n\t\t...('legend' in baseStyleOptions\n\t\t\t? { legend: { enabled: true, position: 'bottom' } }\n\t\t\t: {}),\n\t};\n\n\t// generate artifact id for the chart\n\treturn {\n\t\t...widgetProps,\n\t\tartifactId: nanoidHex(),\n\t\tdataColumns,\n\t};\n};\n\nexport const createChart = async (\n\t{ userPrompt, chartType, chartTitle }: z.infer<typeof createChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'createChart', userPrompt, chartType, chartTitle);\n\tconst dataSourceTitle = context.dataSourceTitle;\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\tconst chartId = context.toolCallId;\n\tconst chartWidgetProps = await generateChart(\n\t\t{\n\t\t\tdataSourceTitle,\n\t\t\tuserPrompt,\n\t\t\tchartType,\n\t\t\tchartTitle,\n\t\t},\n\t\tcontext,\n\t);\n\n\tcontext.saveChart?.(chartId, chartWidgetProps);\n\n\treturn {\n\t\tmessage: `New chart (chartId: ${chartId}) created successfully`,\n\t};\n};\n","import z from 'zod';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartTitleSchema,\n} from '../types';\n\ntype UpdateChartTitleHelperParams = {\n\tchartTitle: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\nexport const updateChartTitleHelper = ({\n\tchartTitle,\n\tchartWidgetProps,\n}: UpdateChartTitleHelperParams): ExtendedChartWidgetProps => {\n\treturn {\n\t\t...chartWidgetProps,\n\t\ttitle: chartTitle,\n\t};\n};\n\nexport const updateChartTitle = async (\n\t{ chartId, chartTitle }: z.infer<typeof updateChartTitleSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartTitle', chartId, chartTitle);\n\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = updateChartTitleHelper({\n\t\tchartTitle,\n\t\tchartWidgetProps,\n\t});\n\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\n\treturn {\n\t\tmessage: 'Chart title updated successfully',\n\t};\n};\n","import { ChartDataOptions, ChartType } from '@sisense/sdk-ui';\nimport {\n\tAxesMapping,\n\tgetChartStyleOptions,\n} from '@sisense/sdk-ui/analytics-composer';\nimport {\n\tExtendedChartWidgetProps,\n\tBuildChartContext,\n\tupdateChartTypeSchema,\n} from '../types';\nimport { generateChartRecommendations } from '../create-chart/generate-chart-recommendations';\nimport z from 'zod';\n\ntype UpdateChartTypeHelperParams = {\n\tuserPrompt: string;\n\tchartType: ChartType;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\nexport const updateChartTypeHelper = async ({\n\tuserPrompt,\n\tchartType,\n\tchartWidgetProps,\n}: UpdateChartTypeHelperParams) => {\n\tconst { dataColumns, styleOptions: existingStyleOptions } =\n\t\tchartWidgetProps;\n\n\tconst chartRecommendations = await generateChartRecommendations(\n\t\tuserPrompt,\n\t\tdataColumns,\n\t\tchartType,\n\t);\n\n\tconst { axesMapping, chartType: newChartType } = chartRecommendations;\n\n\tchartWidgetProps.dataOptions = axesMapping as ChartDataOptions;\n\tchartWidgetProps.chartType = newChartType;\n\n\tconst baseStyleOptions = getChartStyleOptions(\n\t\tnewChartType,\n\t\tchartWidgetProps.dataOptions as AxesMapping,\n\t\t{},\n\t\ttrue,\n\t);\n\n\tconst styleOptions = existingStyleOptions\n\t\t? {\n\t\t\t\t...baseStyleOptions,\n\t\t\t\t// Preserve specific properties from existingStyleOptions\n\t\t\t\t...('legend' in existingStyleOptions &&\n\t\t\t\t'legend' in baseStyleOptions\n\t\t\t\t\t? { legend: existingStyleOptions.legend }\n\t\t\t\t\t: {}),\n\t\t\t\t...('labels' in existingStyleOptions &&\n\t\t\t\t'labels' in baseStyleOptions\n\t\t\t\t\t? { labels: existingStyleOptions.labels }\n\t\t\t\t\t: {}),\n\t\t\t\t...('xAxis' in existingStyleOptions &&\n\t\t\t\t'xAxis' in baseStyleOptions\n\t\t\t\t\t? { xAxis: existingStyleOptions.xAxis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('yAxis' in existingStyleOptions &&\n\t\t\t\t'yAxis' in baseStyleOptions\n\t\t\t\t\t? { yAxis: existingStyleOptions.yAxis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('y2Axis' in existingStyleOptions &&\n\t\t\t\t'y2Axis' in baseStyleOptions\n\t\t\t\t\t? { y2Axis: existingStyleOptions.y2Axis }\n\t\t\t\t\t: {}),\n\t\t\t\t...('dataLimits' in existingStyleOptions &&\n\t\t\t\t'dataLimits' in baseStyleOptions\n\t\t\t\t\t? { dataLimits: existingStyleOptions.dataLimits }\n\t\t\t\t\t: {}),\n\t\t\t\t...('markerSize' in existingStyleOptions &&\n\t\t\t\t'markerSize' in baseStyleOptions\n\t\t\t\t\t? { markerSize: existingStyleOptions.markerSize }\n\t\t\t\t\t: {}),\n\t\t }\n\t\t: baseStyleOptions;\n\n\tchartWidgetProps.styleOptions = styleOptions;\n\n\treturn chartWidgetProps;\n};\n\nexport const updateChartType = async (\n\t{ chartId, userPrompt, chartType }: z.infer<typeof updateChartTypeSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'updateChartType',\n\t\tchartId,\n\t\tuserPrompt,\n\t\tchartType,\n\t);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartTypeHelper({\n\t\tuserPrompt,\n\t\tchartType,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart type updated successfully',\n\t};\n};\n","import { ChartType } from '@sisense/sdk-ui';\nimport { z } from 'zod';\nimport { chartType } from '../types';\n\nconst LineWidthSchema = z.object({\n\twidth: z.enum(['thin', 'bold', 'thick']),\n});\n\nconst LineSubtypeSchema = z.enum(['line/basic', 'line/spline']);\n\n// Common components schemas\nconst LegendSchema = z\n\t.object({\n\t\tenabled: z\n\n\t\t\t.boolean()\n\n\t\t\t.optional()\n\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if legend should be shown on the chart',\n\t\t\t),\n\t\tposition: z\n\n\t\t\t.enum(['top', 'left', 'right', 'bottom'])\n\n\t\t\t.optional()\n\n\t\t\t.describe('Position of the legend'),\n\t})\n\t.describe(\n\t\t'Options that define legend - a key that provides information about the data series or colors used in chart.',\n\t)\n\t.strict();\n\nconst SeriesLabelsSchema = z\n\t.object({\n\t\tenabled: z.boolean().optional(),\n\t\tshowValue: z.boolean().optional(),\n\t\tshowPercentage: z.boolean().optional(),\n\t\tfontSize: z.string().optional(),\n\t\t// color: z.string().optional(),\n\t})\n\t.strict();\n// Create separate axis schemas instead of reusing\nconst AxisLabel = z\n\t.object({\n\t\tenabled: z.boolean().optional(),\n\t\ttitle: z\n\t\t\t.object({\n\t\t\t\tenabled: z.boolean().default(true).optional(),\n\t\t\t\ttext: z.string().optional(),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('The title or name of the x-axis'),\n\t\tmin: z\n\t\t\t.number()\n\t\t\t.nullable()\n\t\t\t.optional()\n\t\t\t.describe('The minimum value of the x-axis'),\n\t\tmax: z\n\t\t\t.number()\n\t\t\t.nullable()\n\t\t\t.optional()\n\t\t\t.describe('The maximum value of the x-axis'),\n\t\tgridLines: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if grid lines should be shown on the chart',\n\t\t\t),\n\t\tintervalJumps: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Interval of the tick marks (jumps) in axis units.'),\n\t\tisIntervalEnabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if tick marks should be shown on the axis',\n\t\t\t),\n\t\tlabels: z\n\t\t\t.object({\n\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\tshowValue: z.boolean().optional(),\n\t\t\t\tshowPercentage: z.boolean().optional(),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe('Configuration for labels on the axis'),\n\t\tlogarithmic: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if the axis should have logarithmic scale',\n\t\t\t),\n\t\ttemplateMainYHasGridLines: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if the Y axis should have grid lines extending the ticks across the plot area',\n\t\t\t),\n\t})\n\t.strict();\n\nconst XAxisSchema = AxisLabel.describe('X-axis configuration');\n\nconst YAxisSchema = AxisLabel.describe('Y-axis configuration');\n\nconst Y2AxisSchema = AxisLabel.describe('Y2-axis configuration');\n\nconst MarkersSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if markers should be shown on the chart',\n\t\t\t),\n\t\tfill: z\n\t\t\t.enum(['filled', 'hollow'])\n\t\t\t.optional()\n\t\t\t.describe('Marker fill style'),\n\t\tsize: z\n\t\t\t.enum(['small', 'medium', 'large'])\n\t\t\t.optional()\n\t\t\t.describe('Size of markers'),\n\t})\n\t.describe(\n\t\t'Options that define markers - symbols or data points that highlight specific values.',\n\t)\n\t.strict();\n\nconst NavigatorSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if navigator should be shown on the chart',\n\t\t\t),\n\t\tscrollerLocation: z\n\t\t\t.object({\n\t\t\t\tmax: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('The maximum value of the navigator scroller'),\n\t\t\t\tmin: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('The minimum value of the navigator scroller'),\n\t\t\t})\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'The scroll location of the navigator scroller / auto zoom feature',\n\t\t\t),\n\t})\n\t.describe(\n\t\t'Options that define navigator - zoom/pan tool for large datasets in a chart.',\n\t)\n\t.strict();\n\nconst DataLimitsSchema = z\n\t.object({\n\t\tcategoriesCapacity: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Maximum number of categories to chart'),\n\t\tseriesCapacity: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe('Maximum number of series to chart'),\n\t})\n\t.describe(\n\t\t'Configuration that limits the series or categories that are charted.',\n\t)\n\t.strict();\n\n// Chart-specific schemas\nexport const LineChartStyleSchema = z\n\t.object({\n\t\tlineWidth: LineWidthSchema.optional(),\n\t\tsubtype: LineSubtypeSchema.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const BarChartStyleSchema = z\n\t.object({\n\t\tsubtype: z\n\t\t\t.enum(['bar/classic', 'bar/stacked', 'bar/stacked100'])\n\t\t\t.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nconst ConvolutionSchema = z\n\t.object({\n\t\tenabled: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that defines if convolution ability should be enabled on chart',\n\t\t\t),\n\t\tindependentSlicesCount: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Number that defines of how many independent slices should be present in chart (other will be convolved)',\n\t\t\t),\n\t\tminimalIndependentSlicePercentage: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Value that defines what minimal size in percent should a slice take to fall under the convolution',\n\t\t\t),\n\t\tselectedConvolutionType: z\n\t\t\t.enum(['byPercentage', 'bySlicesCount'])\n\t\t\t.optional()\n\t\t\t.describe('Selected type of convolution behavior'),\n\t})\n\t.describe(\n\t\t'Configuration that defines the ability of the Pie chart to collapse (convolve) and hide part of the data under the single category \"Others\".',\n\t)\n\t.strict();\n\nexport const PieChartStyleSchema = z\n\t.object({\n\t\tsubtype: z.enum(['pie/basic', 'pie/donut', 'pie/ring']).optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\tconvolution: ConvolutionSchema.optional(),\n\t})\n\t.strict();\n\nexport const ScatterChartStyleSchema = z\n\t.object({\n\t\tmarkers: MarkersSchema.optional(),\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tmarkerSize: z\n\n\t\t\t.object({\n\t\t\t\tscatterBubbleMaxSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Maximum size of markers'),\n\t\t\t\tscatterBubbleMinSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Minimum size of markers'),\n\t\t\t\tscatterDefaultSize: z\n\t\t\t\t\t.number()\n\t\t\t\t\t.optional()\n\t\t\t\t\t.describe('Default size of markers'),\n\t\t\t})\n\n\t\t\t.optional()\n\n\t\t\t.describe('Size of markers'),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const AreaChartStyleSchema = z\n\t.object({\n\t\tsubtype: z\n\t\t\t.enum([\n\t\t\t\t'area/basic',\n\t\t\t\t'area/spline',\n\t\t\t\t'area/stacked',\n\t\t\t\t'area/stacked100',\n\t\t\t\t'area/stackedspline',\n\t\t\t\t'area/stackedspline100',\n\t\t\t])\n\t\t\t.optional(),\n\t\topacity: z.number().optional(),\n\t\tnavigator: NavigatorSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const FunnelChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tfunnelDirection: z\n\t\t\t.enum(['inverted', 'regular'])\n\t\t\t.optional()\n\t\t\t.describe('Direction of FunnelChart narrowing'),\n\t\tfunnelSize: z\n\t\t\t.enum(['narrow', 'regular', 'wide'])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Visual size of the lowest slice (degree of funnel narrowing from highest to lowest slices)',\n\t\t\t),\n\t\tfunnelType: z\n\t\t\t.enum(['pinched', 'regular'])\n\t\t\t.optional()\n\t\t\t.describe('Visual type of the lowest slice of FunnelChar'),\n\t\tsubtype: z.enum(['funnel/basic', 'funnel/pyramid']).optional(),\n\t\tneckHeight: z.number().optional(),\n\t\tneckWidth: z.number().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t})\n\t.strict();\n\nexport const TreemapChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlayout: z\n\t\t\t.enum([\n\t\t\t\t'squarified',\n\t\t\t\t'stripes',\n\t\t\t\t'stripes-vertical',\n\t\t\t\t'stripes-horizontal',\n\t\t\t])\n\t\t\t.optional(),\n\t\tborderWidth: z.number().optional(),\n\t\tborderColor: z.string().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\ttooltip: z.object({\n\t\t\tmode: z\n\t\t\t\t.enum(['contribution', 'value'])\n\t\t\t\t.optional()\n\t\t\t\t.describe('Define mode of data showing'),\n\t\t}),\n\t})\n\t.strict();\n\nexport const SunburstChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tlevels: z.number().optional(),\n\t\tborderWidth: z.number().optional(),\n\t\tborderColor: z.string().optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t})\n\t.strict();\n\nexport const BoxplotChartStyleSchema = z\n\t.object({\n\t\tdataLimits: DataLimitsSchema.optional(),\n\t\tsubtype: z.enum(['boxplot/full', 'boxplot/hollow']).optional(),\n\t\tboxType: z.enum(['iqr', 'extremums', 'standardDeviation']).optional(),\n\t\toutliersEnabled: z.boolean().optional(),\n\t\twidth: z.number().optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\txAxis: XAxisSchema.optional(),\n\t\tyAxis: YAxisSchema.optional(),\n\t\ty2Axis: Y2AxisSchema.optional(),\n\t\tmarkers: MarkersSchema.optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t})\n\t.strict();\n\nexport const IndicatorChartStyleSchema = z\n\t.object({\n\t\tsubtype: z.enum(['indicator/numeric', 'indicator/gauge']).optional(),\n\t\tvalue: z.number().optional(),\n\t\tmin: z.number().optional(),\n\t\tmax: z.number().optional(),\n\t\tthresholds: z.array(z.number()).optional(),\n\t\tseriesLabels: SeriesLabelsSchema.optional(),\n\t\tlegend: LegendSchema.optional(),\n\t\tforceTickerView: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag to force render indicator in ticker mode regardless of display size',\n\t\t\t),\n\t\tskin: z.enum(['1', '2']).optional().describe('Skin gauge indicator'),\n\t})\n\t.strict();\n\nconst PolarChartStyleSchema = z.object({\n\tdataLimits: DataLimitsSchema.optional(),\n\theight: z.number().optional(),\n\twidth: z.number().optional(),\n\tlegend: LegendSchema.optional(),\n\tmarkers: MarkersSchema.optional(),\n\tnavigator: NavigatorSchema.optional(),\n\tsubtype: z.enum(['polar/area', 'polar/column', 'polar/line']).optional(),\n\txAxis: XAxisSchema.optional(),\n\tyAxis: YAxisSchema.optional(),\n\ty2Axis: Y2AxisSchema.optional(),\n\tseriesLabels: SeriesLabelsSchema.optional(),\n});\n\nconst TableChartStyleSchema = z.object({\n\tcolumns: z\n\t\t.object({\n\t\t\talternatingColor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Alternating color for columns'),\n\t\t\twidth: z\n\t\t\t\t.enum(['auto', 'content'])\n\t\t\t\t.optional()\n\t\t\t\t.describe('Width of columns'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for columns'),\n\theader: z\n\t\t.object({\n\t\t\tcolor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Color of header'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for header'),\n\trows: z\n\t\t.object({\n\t\t\talternatingColor: z\n\t\t\t\t.object({\n\t\t\t\t\tenabled: z.boolean().optional(),\n\t\t\t\t\ttextColor: z.string().optional(),\n\t\t\t\t\tbackgroundColor: z.string().optional(),\n\t\t\t\t})\n\t\t\t\t.optional()\n\t\t\t\t.describe('Alternating color for rows'),\n\t\t})\n\t\t.optional()\n\t\t.describe('Configuration for rows'),\n\trowsPerPage: z.number().optional().describe('Number of rows per page'),\n\tpaddingHorizontal: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Horizontal padding around whole table'),\n\tpaddingVertical: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Vertical padding around whole table'),\n});\n\nexport const chartStyleSchemas: Record<ChartType, z.ZodObject<any>> = {\n\tline: LineChartStyleSchema,\n\tbar: BarChartStyleSchema,\n\tarea: AreaChartStyleSchema,\n\tcolumn: BarChartStyleSchema, // Assuming column is similar to bar; adjust as needed\n\tpie: PieChartStyleSchema,\n\tscatter: ScatterChartStyleSchema,\n\tfunnel: FunnelChartStyleSchema,\n\ttreemap: TreemapChartStyleSchema,\n\tsunburst: SunburstChartStyleSchema,\n\tboxplot: BoxplotChartStyleSchema,\n\tindicator: IndicatorChartStyleSchema,\n\tpolar: PolarChartStyleSchema,\n\ttable: TableChartStyleSchema,\n\tarearange: z.object({}),\n\tscattermap: z.object({}),\n\tareamap: z.object({}),\n\t'calendar-heatmap': z.object({}),\n\tstreamgraph: z.object({}),\n} as const;\n\nconst baseChartSchema = z.object({\n\tchartType,\n});\n\n// Function to get schema by chart type\nexport function getChartStyleOptionsSchema(chartType: ChartType) {\n\tconst styleSchema = chartStyleSchemas[chartType];\n\n\tif (!styleSchema) {\n\t\tthrow new Error(`Unsupported chart type: ${chartType}`);\n\t}\n\n\treturn baseChartSchema.extend({\n\t\tstyleOptions: styleSchema,\n\t});\n}\n\n// Type for all chart style options\nexport type ChartStyleOptions =\n\t| z.infer<typeof LineChartStyleSchema>\n\t| z.infer<typeof BarChartStyleSchema>\n\t| z.infer<typeof PieChartStyleSchema>\n\t| z.infer<typeof ScatterChartStyleSchema>\n\t| z.infer<typeof AreaChartStyleSchema>\n\t| z.infer<typeof FunnelChartStyleSchema>\n\t| z.infer<typeof TreemapChartStyleSchema>\n\t| z.infer<typeof SunburstChartStyleSchema>\n\t| z.infer<typeof BoxplotChartStyleSchema>\n\t| z.infer<typeof IndicatorChartStyleSchema>;\n\ntype DataOptionTypes =\n\t| 'cartesian'\n\t| 'categorical'\n\t| 'scatter'\n\t| 'table'\n\t| 'indicator'\n\t| 'areamap'\n\t| 'arearange';\n\nconst dataOptionsSchemas: Record<DataOptionTypes, z.ZodObject<any>> = {\n\tcartesian: z.object({\n\t\tcategory: z.array(\n\t\t\tz.object({\n\t\t\t\tcolumn: z.object({}),\n\t\t\t}),\n\t\t),\n\t\tvalue: z.array(\n\t\t\tz.object({\n\t\t\t\tcolumn: z.object({}),\n\t\t\t}),\n\t\t),\n\t}),\n\tcategorical: z.object({\n\t\tcategory: z.array(z.object({})),\n\t\tvalue: z.array(z.object({})),\n\t}),\n\tscatter: z.object({\n\t\tx: z.object({}),\n\t\ty: z.object({}),\n\t}),\n\ttable: z.object({}),\n\tindicator: z.object({}),\n\tareamap: z.object({}),\n\tarearange: z.object({}),\n} as const;\n\nexport const getChartDataOptionsSchema = (dataOptionType: DataOptionTypes) => {\n\treturn dataOptionsSchemas[dataOptionType];\n};\n\nexport const PartialColumnSchema = z.object({\n\tname: z.string(),\n\ttitle: z.string(),\n});\n\nexport const ColorStringSchema = z\n\t.string()\n\t.describe('hex color code for the measure.');\nexport const UniformColorSchema = z\n\t.object({\n\t\tcolor: ColorStringSchema,\n\t\ttype: z\n\t\t\t.enum(['uniform'])\n\t\t\t.describe('Type of color to be used for the measure.'),\n\t})\n\t.describe(\n\t\t'Uniform color options for data similar to the Single Color option in the Sisense UI.',\n\t);\n\nexport const ConditionalColorSchema = z\n\t.object({\n\t\tconditions: z\n\t\t\t.array(\n\t\t\t\tz.object({\n\t\t\t\t\tcolor: ColorStringSchema,\n\t\t\t\t\texpression: z.string(),\n\t\t\t\t\toperator: z.enum(['<', '>', '>=', '<=']),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.describe('Array of color conditions'),\n\t\tdefaultColor: ColorStringSchema.describe(\n\t\t\t'Default color when no condition is met',\n\t\t),\n\t\ttype: z.enum(['conditional']).describe('Color options type'),\n\t})\n\t.describe(\n\t\t'Conditional color options for data similar to the Conditional Color option in the Sisense UI.',\n\t);\n\nexport const ColorOptionsSchema = z.object({\n\tcolor: z.string().describe('hex color code for the measure.'),\n});\n\nexport const RangeColorSchema = z\n\t.object({\n\t\tmaxColor: ColorStringSchema.describe(\n\t\t\t'End color of the range',\n\t\t).optional(),\n\t\tmaxValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Maximum value explicitly set to override the maximum value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tmidValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Middle value explicitly set to override the middle value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tminColor: ColorStringSchema.describe(\n\t\t\t'Start color of the range',\n\t\t).optional(),\n\t\tminValue: z\n\t\t\t.number()\n\t\t\t.describe(\n\t\t\t\t'Minimum value explicitly set to override the minimum value of the data',\n\t\t\t)\n\t\t\t.optional(),\n\t\tsteps: z\n\t\t\t.number()\n\t\t\t.describe('Distinct number of colors in the range')\n\t\t\t.optional(),\n\t\ttype: z.enum(['range']).describe('Color options type'),\n\t})\n\t.describe('Color options for range color.');\n\nexport const NumberFormatConfigSchema = z.object({\n\tbilion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one billion - e.g. 1B',\n\t\t),\n\tdecimalScale: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('The number of decimal places'),\n\tkilo: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one thousand - e.g. 1K',\n\t\t),\n\tmillion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one million - e.g. 1M',\n\t\t),\n\tname: z\n\t\t.enum(['Currency', 'Numbers', 'Percent'])\n\t\t.optional()\n\t\t.describe('Supported formats'),\n\tprefix: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether symbol is shown in front of or after the number',\n\t\t),\n\tsymbol: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Symbol to show in front of or after the number depending on the value of prefix.',\n\t\t),\n\tthousandSeparator: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe('Boolean flag whether the thousand separator is shown'),\n\ttrillion: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Boolean flag whether to show an abbreviation for a number greater than or equal one trillion - e.g. 1T',\n\t\t),\n});\n\nexport const trendFormulaOptions = z\n\t.object({\n\t\tignoreAnomalies: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag that enables the function to automatically identify and ignore anomalous values in the series. This can be particularly useful when you want to maintain the integrity of your analysis by avoiding potential outliers. default is false',\n\t\t\t),\n\t\tmodelType: z\n\t\t\t.enum([\n\t\t\t\t'advancedSmoothing',\n\t\t\t\t'linear',\n\t\t\t\t'localEstimates',\n\t\t\t\t'logarithmic',\n\t\t\t])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Trend analysis model type to be used for the operation. default is linear',\n\t\t\t),\n\t})\n\t.describe('Trend analysis options for the measure');\n\nexport const forecastFormulaOptions = z\n\t.object({\n\t\tconfidenceInterval: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Confidence interval showing the probabilistic upper and lower limits of the forecasted series according to the uncertainty level. The valid range is (0.8 <= X < 1). default is 0.8',\n\t\t\t),\n\t\tendDate: z\n\t\t\t.string()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'End date of the time series data that the forecasting model will be trained on. This parameter can be used to discard the end of the series. Specify a ISO 8601 date string or Date object.',\n\t\t\t),\n\t\tforecastHorizon: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Number of data points to be predicted. The accepted value range is between 1-1,000. default is 3',\n\t\t\t),\n\t\tlowerBound: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Expected lower limit to improve the forecast accuracy when reaching the limit. Note that values in the confidence interval can exceed this limit.',\n\t\t\t),\n\t\tmodelType: z\n\t\t\t.enum(['auto', 'autoArima', 'holtWinters', 'prophet'])\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t\"Forecasting model type. The 'auto' option automatically fits the best combination of models. default is auto\",\n\t\t\t),\n\t\troundToInt: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Boolean flag to round the predicted result to an integer if set to true. Otherwise, the predicted result is left as a float. default is false',\n\t\t\t),\n\t\tstartDate: z\n\t\t\t.string()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Start date of the time series data that the forecasting model will be trained on. This parameter can be used to discard the beginning of the series. Specify a ISO 8601 date string or Date object.',\n\t\t\t),\n\t\tupperBound: z\n\t\t\t.number()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t'Expected upper limit to improve the forecast accuracy when reaching the limit. Note that values in the confidence interval can exceed this limit.',\n\t\t\t),\n\t})\n\t.describe('Forecast analysis options for the measure');\n\nexport const dataOptionsEditingSchemas = {\n\tmeasures: z\n\t\t.object({\n\t\t\tcolumn: PartialColumnSchema,\n\t\t\tchartType: z\n\t\t\t\t.enum(['line', 'bar', 'column', 'area'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Series chart type, which is used with StyledMeasure to customize series in a mixed chart.',\n\t\t\t\t)\n\t\t\t\t.optional(),\n\t\t\tsortType: z\n\t\t\t\t.enum(['sortAsc', 'sortDesc', 'sortNone'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Sorting direction, either in Ascending order, Descending order, or None',\n\t\t\t\t),\n\t\t\tcolor: z.string().describe('hex color code for the measure.'),\n\t\t\tconnectNulls: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to connect a graph line across null points or render a gap',\n\t\t\t\t),\n\t\t\tdataBars: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'pivot table only -Boolean flag whether to display data bars for this measure in the pivot table.',\n\t\t\t\t),\n\t\t\tdataBarsColor: z\n\t\t\t\t.string()\n\t\t\t\t.describe(\n\t\t\t\t\t'pivot table only - Color options for data bars for this measure in the pivot table',\n\t\t\t\t),\n\t\t\tnumberFormatConfig: NumberFormatConfigSchema.describe(\n\t\t\t\t'Configuration for number formatting.',\n\t\t\t),\n\t\t\tseriesStyleOptions: z\n\t\t\t\t.object({})\n\t\t\t\t.describe(\n\t\t\t\t\t'Specific style options to be applied to specific series in Chart. Supported only for cartesian and polar charts.',\n\t\t\t\t),\n\t\t\tshowOnRightAxis: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to show this value/measure on the right axis (true) or on the left axis (false).',\n\t\t\t\t),\n\t\t\ttotalsCalculation: z\n\t\t\t\t.enum(['sum', 'avg', 'min', 'max', 'count'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Calculation for the totals of this measure in the pivot table.',\n\t\t\t\t),\n\t\t\ttreatNullDataAsZeros: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether null values are treated as zeros in the chart',\n\t\t\t\t),\n\t\t\ttrend: trendFormulaOptions\n\t\t\t\t.optional()\n\t\t\t\t.describe('Trend analysis options for the measure.'),\n\t\t\tforecast: forecastFormulaOptions\n\t\t\t\t.optional()\n\t\t\t\t.describe('Forecast analysis options for the measure.'),\n\t\t})\n\t\t.describe('Configuration for measures.StyledMeasure'),\n\tdimensions: z\n\t\t.object({\n\t\t\tcolumn: PartialColumnSchema,\n\t\t\tcontinuous: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag to toggle continuous timeline on this date column.',\n\t\t\t\t),\n\t\t\tdateFormat: z\n\t\t\t\t.string()\n\t\t\t\t.describe(\n\t\t\t\t\t'Date format. See ECMAScript Date Time String Format(opens new window) Note that \"YYYY\" and \"DD\" have been disabled since they often get confused with \"yyyy\" and \"dd\" and can produce unexpected results.',\n\t\t\t\t),\n\t\t\tgeoLevel: z\n\t\t\t\t.enum([\n\t\t\t\t\t'country',\n\t\t\t\t\t'state',\n\t\t\t\t\t'city',\n\t\t\t\t\t'zip',\n\t\t\t\t\t'latitude',\n\t\t\t\t\t'longitude',\n\t\t\t\t])\n\t\t\t\t.describe('Geographic location level for Scattermap chart.'),\n\t\t\tgranularity: z\n\t\t\t\t.enum(['day', 'week', 'month', 'year'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Date granularity that works with continuous timeline. Values from DateLevels.',\n\t\t\t\t),\n\t\t\tincludeSubTotals: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to include subtotals for this dimension in the pivot table.',\n\t\t\t\t),\n\t\t\tisColored: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe('Boolean flag whether to color the dimension.'),\n\t\t\tisHtml: z\n\t\t\t\t.boolean()\n\t\t\t\t.describe(\n\t\t\t\t\t'Boolean flag whether to render category/column value as HTML in the Table component.',\n\t\t\t\t),\n\t\t\tnumberFormatConfig: NumberFormatConfigSchema.describe(\n\t\t\t\t'Configuration for number formatting.',\n\t\t\t),\n\t\t\tsortType: z\n\t\t\t\t.enum(['sortAsc', 'sortDesc', 'sortNone'])\n\t\t\t\t.describe(\n\t\t\t\t\t'Sorting configuration that represents either SortDirection or PivotRowsSort for the pivot table',\n\t\t\t\t),\n\t\t})\n\t\t.describe('Configuration for dimensions. StyledColumn'),\n};\n\n// export type DataOptionsEditingSchemas = z.infer<typeof dataOptionsEditingSchemas>;\n\nexport const cartesianDataOptionsEditingSchemas = z.object({\n\tvalues: z.array(dataOptionsEditingSchemas.measures),\n\tcategories: z.array(dataOptionsEditingSchemas.dimensions),\n\tbreakBy: z.array(dataOptionsEditingSchemas.dimensions),\n\tseriesToColorMap: z\n\t\t.object({})\n\t\t.describe(\n\t\t\t'Optional mapping of each of the series to colors. (key: color)',\n\t\t),\n});\n\nexport const categoricalDataOptionsEditingSchemas = z.object({\n\tvalues: z.array(dataOptionsEditingSchemas.measures),\n\tcategories: z.array(dataOptionsEditingSchemas.dimensions),\n\tseriesToColorMap: z\n\t\t.object({})\n\t\t.describe('Color mapping for series to color.'),\n});\nexport const scatterChartDataOptionsEditingSchemas = z.object({\n\ty: dataOptionsEditingSchemas.measures,\n\tx: dataOptionsEditingSchemas.dimensions,\n\tbreakByColor: dataOptionsEditingSchemas.measures,\n\tbreakBySize: dataOptionsEditingSchemas.measures,\n\tseriesToColorMap: dataOptionsEditingSchemas.measures,\n\tsize: dataOptionsEditingSchemas.measures,\n});\n\nexport const indicatorDataOptionsEditingSchemas = z.object({\n\tmin: z.array(dataOptionsEditingSchemas.measures),\n\tmax: z.array(dataOptionsEditingSchemas.measures),\n\tsecondary: z.array(dataOptionsEditingSchemas.measures),\n\tvalue: dataOptionsEditingSchemas.measures,\n});\n\nexport const boxplotDataOptionsEditingSchemas = z.object({\n\tboxType: z.enum(['extremums', 'iqr', 'standardDeviation']),\n\tcategory: z.array(dataOptionsEditingSchemas.dimensions),\n\toutliersEnabled: z.boolean().optional(),\n\tvalue: z.array(dataOptionsEditingSchemas.measures),\n});\n\nexport const scattermapDataOptionsEditingSchemas = z.object({\n\tcolorBy: dataOptionsEditingSchemas.measures,\n\t// todo: or statement dimensions or measures\n\tdetails: dataOptionsEditingSchemas.dimensions,\n\tgeo: z.array(dataOptionsEditingSchemas.dimensions),\n\tsize: dataOptionsEditingSchemas.measures,\n});\n\nexport const areamapDataOptionsEditingSchemas = z.object({\n\tcolor: z.array(dataOptionsEditingSchemas.measures),\n\tgeo: z.array(dataOptionsEditingSchemas.dimensions),\n});\n\nexport const calendarHeatmapDataOptionsEditingSchemas = z.object({\n\tdate: z.array(dataOptionsEditingSchemas.dimensions),\n\tvalue: z.array(dataOptionsEditingSchemas.measures),\n});\n\nexport const tableDataOptionsEditingSchemas = z.object({\n\tcolumns: z.array(dataOptionsEditingSchemas.dimensions),\n});\n\nexport const getChartDataOptionsEditingSchemas = (chartType: ChartType) => {\n\tswitch (chartType) {\n\t\tcase 'line':\n\t\tcase 'bar':\n\t\tcase 'column':\n\t\tcase 'area':\n\t\tcase 'polar':\n\t\t\treturn cartesianDataOptionsEditingSchemas;\n\t\tcase 'pie':\n\t\tcase 'funnel':\n\t\tcase 'treemap':\n\t\tcase 'sunburst':\n\t\t\treturn categoricalDataOptionsEditingSchemas;\n\t\tcase 'scatter':\n\t\t\treturn scatterChartDataOptionsEditingSchemas;\n\t\tcase 'indicator':\n\t\t\treturn indicatorDataOptionsEditingSchemas;\n\t\tcase 'table':\n\t\t\treturn tableDataOptionsEditingSchemas;\n\t\tcase 'boxplot':\n\t\t\treturn boxplotDataOptionsEditingSchemas;\n\t\tcase 'scattermap':\n\t\t\treturn scattermapDataOptionsEditingSchemas;\n\t\tcase 'areamap':\n\t\t\treturn areamapDataOptionsEditingSchemas;\n\t\tcase 'calendar-heatmap':\n\t\t\treturn calendarHeatmapDataOptionsEditingSchemas;\n\t\tdefault:\n\t\t\treturn z.object({});\n\t}\n};\n\nexport const chartDataOptionsSchemas: Record<ChartType, z.ZodObject<any>> = {\n\tline: cartesianDataOptionsEditingSchemas,\n\tbar: categoricalDataOptionsEditingSchemas,\n\tarea: cartesianDataOptionsEditingSchemas,\n\tcolumn: categoricalDataOptionsEditingSchemas, // Assuming column is similar to bar; adjust as needed\n\tpie: categoricalDataOptionsEditingSchemas,\n\tscatter: scatterChartDataOptionsEditingSchemas,\n\tfunnel: categoricalDataOptionsEditingSchemas,\n\ttreemap: categoricalDataOptionsEditingSchemas,\n\tsunburst: categoricalDataOptionsEditingSchemas,\n\tboxplot: boxplotDataOptionsEditingSchemas,\n\tindicator: indicatorDataOptionsEditingSchemas,\n\tpolar: cartesianDataOptionsEditingSchemas,\n\ttable: TableChartStyleSchema,\n\tarearange: z.object({}),\n\tscattermap: z.object({}),\n\tareamap: z.object({}),\n\t'calendar-heatmap': calendarHeatmapDataOptionsEditingSchemas,\n\tstreamgraph: z.object({}),\n} as const;\n","import { getChartDataOptionsEditingSchemas } from './chart-options-schemas';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartSchema,\n} from '../types';\nimport { zodToReadableType } from '@/utils/zod-utils';\nimport { ChartWidgetProps } from '@sisense/sdk-ui';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\nimport { z } from 'zod';\n\ntype UpdateChartDataOptionsHelperParams = {\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Updates chart data options based on the user's prompt.\n * @param userPrompt - The user's prompt to update the chart data options.\n * @param chartWidgetProps - The chart widget props to update the chart data options for.\n * @returns The updated chart.\n */\nexport const updateChartDataOptionsHelper = async ({\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartDataOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { dataOptions: currentDataOptions, chartType: currentChartType } =\n\t\tchartWidgetProps;\n\n\t// Get the schema for the current chart type\n\tconst baseSchema = getChartDataOptionsEditingSchemas(currentChartType);\n\tconst targetSchema = z.object({\n\t\tdataOptions: baseSchema,\n\t});\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart data options properties are as follows:\n\t\t\n\n\t\tdataOptions: {\n\t\t\t${Object.entries(baseSchema.shape)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`- ${key}: ${zodToReadableType(value as z.ZodTypeAny)}`,\n\t\t\t\t)\n\t\t\t\t.join('\\n')}\n\t\t}\n\n\t\tcurrent dataOptions: {\n\t\t\t${JSON.stringify(currentDataOptions, null, 2)}\n\t\t}\n\t\t`;\n\n\tconst systemPrompt = `\n\t\t\tYou are a chart data options assistant. You edit only the fields the user mentions.\n\n\t\t\tDO NOT use any tools.\n\t\t\t\n\t\t\tHere are the editable properties:\n\t\t\t${editableFieldsDoc}\n\t\t\t\n\t\t\tYour output must be a JSON object with only the requested changes.\n\n\t\t\tThe 'column' object, containing only the item's 'name', MUST be included for any change to an item within a list field ('values', 'categories', 'breakBy', etc.) \n\t\t\tto maintain identity.\n \n Do not include unchanged fields.\n \n Example:\n \n User: \"Sort revenue in descending order\"\n Output: { \"dataOptions\": { \"value\" : [\n {\n \"column\": {\n \"name\": \"Total Revenue\",\n },\n \"sortType\": \"sortDesc\"\n }\n ] } }\n\n\t\t\t`;\n\n\tconst parsedResponse = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat: { type: 'json_object' },\n\t});\n\n\tconsole.debug('LLM RESPONSE DATA OPTIONS', parsedResponse);\n\n\tconst { dataOptions: responseDataOptions = null } =\n\t\tparsedResponse as z.infer<typeof targetSchema>;\n\n\tconst mergedDataOptions = responseDataOptions\n\t\t? mergeDataOptions(chartWidgetProps.dataOptions, responseDataOptions)\n\t\t: chartWidgetProps.dataOptions;\n\n\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t...chartWidgetProps,\n\t\tdataOptions: mergedDataOptions,\n\t};\n\n\treturn updatedWidgetProps;\n};\n\nfunction mergeDataOptions(\n\toriginal: ChartWidgetProps['dataOptions'],\n\taiResponse: Partial<ChartWidgetProps['dataOptions']>,\n): ChartWidgetProps['dataOptions'] {\n\tconst merged = { ...original };\n\n\tfor (const key of Object.keys(aiResponse)) {\n\t\tconst dataOptionsKey = key as keyof ChartWidgetProps['dataOptions'];\n\t\tconst incomingList = aiResponse[dataOptionsKey];\n\t\tconst originalList = original[dataOptionsKey] || [];\n\n\t\t// @ts-expect-error - TODO: fix this\n\t\tmerged[dataOptionsKey] = originalList.map((originalItem: any) => {\n\t\t\tconst originalName = originalItem?.column?.name;\n\t\t\t// @ts-expect-error - TODO: fix this\n\t\t\tconst updatedItem = incomingList.find(\n\t\t\t\t(item: any) => item?.column?.name === originalName,\n\t\t\t);\n\n\t\t\tif (updatedItem) {\n\t\t\t\tconst result = { ...originalItem }; // Preserve all original properties\n\n\t\t\t\t// Update or remove properties based on updatedItem\n\t\t\t\tObject.keys(updatedItem).forEach((key) => {\n\t\t\t\t\tif (key !== 'column') {\n\t\t\t\t\t\tconst value = updatedItem[key];\n\t\t\t\t\t\tif (value === null || value === undefined) {\n\t\t\t\t\t\t\tdelete result[key]; // Remove property if null/undefined in update\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tresult[key] = value; // Update property with new value\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\treturn originalItem;\n\t\t});\n\t}\n\n\treturn merged;\n}\n\nexport const updateChartDataOptions = async (\n\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartDataOptions', chartId, userPrompt);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartDataOptionsHelper({\n\t\tuserPrompt,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart data options updated successfully',\n\t};\n};\n","'use strict';\n\nvar isMergeableObject = function isMergeableObject(value) {\n\treturn isNonNullObject(value)\n\t\t&& !isSpecial(value)\n};\n\nfunction isNonNullObject(value) {\n\treturn !!value && typeof value === 'object'\n}\n\nfunction isSpecial(value) {\n\tvar stringValue = Object.prototype.toString.call(value);\n\n\treturn stringValue === '[object RegExp]'\n\t\t|| stringValue === '[object Date]'\n\t\t|| isReactElement(value)\n}\n\n// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25\nvar canUseSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;\n\nfunction isReactElement(value) {\n\treturn value.$$typeof === REACT_ELEMENT_TYPE\n}\n\nfunction emptyTarget(val) {\n\treturn Array.isArray(val) ? [] : {}\n}\n\nfunction cloneUnlessOtherwiseSpecified(value, options) {\n\treturn (options.clone !== false && options.isMergeableObject(value))\n\t\t? deepmerge(emptyTarget(value), value, options)\n\t\t: value\n}\n\nfunction defaultArrayMerge(target, source, options) {\n\treturn target.concat(source).map(function(element) {\n\t\treturn cloneUnlessOtherwiseSpecified(element, options)\n\t})\n}\n\nfunction getMergeFunction(key, options) {\n\tif (!options.customMerge) {\n\t\treturn deepmerge\n\t}\n\tvar customMerge = options.customMerge(key);\n\treturn typeof customMerge === 'function' ? customMerge : deepmerge\n}\n\nfunction getEnumerableOwnPropertySymbols(target) {\n\treturn Object.getOwnPropertySymbols\n\t\t? Object.getOwnPropertySymbols(target).filter(function(symbol) {\n\t\t\treturn Object.propertyIsEnumerable.call(target, symbol)\n\t\t})\n\t\t: []\n}\n\nfunction getKeys(target) {\n\treturn Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))\n}\n\nfunction propertyIsOnObject(object, property) {\n\ttry {\n\t\treturn property in object\n\t} catch(_) {\n\t\treturn false\n\t}\n}\n\n// Protects from prototype poisoning and unexpected merging up the prototype chain.\nfunction propertyIsUnsafe(target, key) {\n\treturn propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,\n\t\t&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,\n\t\t\t&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.\n}\n\nfunction mergeObject(target, source, options) {\n\tvar destination = {};\n\tif (options.isMergeableObject(target)) {\n\t\tgetKeys(target).forEach(function(key) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(target[key], options);\n\t\t});\n\t}\n\tgetKeys(source).forEach(function(key) {\n\t\tif (propertyIsUnsafe(target, key)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {\n\t\t\tdestination[key] = getMergeFunction(key, options)(target[key], source[key], options);\n\t\t} else {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(source[key], options);\n\t\t}\n\t});\n\treturn destination\n}\n\nfunction deepmerge(target, source, options) {\n\toptions = options || {};\n\toptions.arrayMerge = options.arrayMerge || defaultArrayMerge;\n\toptions.isMergeableObject = options.isMergeableObject || isMergeableObject;\n\t// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()\n\t// implementations can use it. The caller may not replace it.\n\toptions.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;\n\n\tvar sourceIsArray = Array.isArray(source);\n\tvar targetIsArray = Array.isArray(target);\n\tvar sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;\n\n\tif (!sourceAndTargetTypesMatch) {\n\t\treturn cloneUnlessOtherwiseSpecified(source, options)\n\t} else if (sourceIsArray) {\n\t\treturn options.arrayMerge(target, source, options)\n\t} else {\n\t\treturn mergeObject(target, source, options)\n\t}\n}\n\ndeepmerge.all = function deepmergeAll(array, options) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new Error('first argument should be an array')\n\t}\n\n\treturn array.reduce(function(prev, next) {\n\t\treturn deepmerge(prev, next, options)\n\t}, {})\n};\n\nvar deepmerge_1 = deepmerge;\n\nmodule.exports = deepmerge_1;\n","import { z } from 'zod';\nimport { getChartStyleOptionsSchema } from './chart-options-schemas';\nimport deepmerge from 'deepmerge';\nimport { zodToReadableType } from '@/utils/zod-utils';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n\tupdateChartSchema,\n} from '../types';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\n\ntype UpdateChartStyleOptionsHelperParams = {\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Updates chart style options based on the user's prompt.\n * @param userPrompt - The user's prompt to update the chart style options.\n * @param chartWidgetProps - The chart widget props to update the chart style options for.\n * @returns The updated chart.\n */\nexport const updateChartStyleOptionsHelper = async ({\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartStyleOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { styleOptions: currentStyleOptions, chartType: currentChartType } =\n\t\tchartWidgetProps;\n\n\t// Get the schema for the effective chart type\n\tconst targetSchema = getChartStyleOptionsSchema(currentChartType);\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart style properties are as follows:\n\t\t\n\t\tstyleOptions: {\n\t\t${Object.entries(targetSchema.shape)\n\t\t\t.map(([key, value]) => `- ${key}: ${zodToReadableType(value)}`)\n\t\t\t.join('\\n')}\n\t\t}\n\t\t`;\n\n\tconst systemPrompt = `\n\t\t\tYou are a chart style options assistant. You edit only the fields the user mentions.\n\n\t\t\tDO NOT use any tools.\n\t\t\t\n\t\t\tHere are the editable properties:\n\t\t\t${editableFieldsDoc}\n\t\t\t\n\t\t\tDO NOT return any field unless the user directly references it.\n\t\t\tYour output must be a JSON object with only the requested changes.\n\t\t\tDo not include unchanged fields.\n\t\t\t\n\t\t\tExample:\n\t\t\tUser \"name the y axis title to Awesome Revenue\"\n\t\t\tOutput: { \"styleOptions\": { \"yAxis\": { \"title\": \"Awesome Revenue\", enabled: true } } }\n\n\t\t\tUser: \"move legend to top\"\n\t\t\tOutput: { \"styleOptions\": { \"legend\": { \"position\": \"top\" } } }\n\n\t\t\t`;\n\n\tconst parsedResponse = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt,\n\t\tresponseFormat: { type: 'json_object' },\n\t});\n\n\tconst { styleOptions: responseStyleOptions = currentStyleOptions } =\n\t\tparsedResponse as z.infer<typeof targetSchema>;\n\n\tconst mergedStyleOptions = deepmerge(\n\t\tcurrentStyleOptions || {},\n\t\tresponseStyleOptions || {},\n\t);\n\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t...chartWidgetProps,\n\t\tstyleOptions: mergedStyleOptions,\n\t};\n\n\treturn updatedWidgetProps;\n};\n\nexport const updateChartStyleOptions = async (\n\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug('toolCall', 'updateChartStyleOptions', chartId, userPrompt);\n\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\tif (!chartWidgetProps) {\n\t\tthrow new Error(`Chart not found`);\n\t}\n\n\tconst updatedChartWidgetProps = await updateChartStyleOptionsHelper({\n\t\tuserPrompt,\n\t\tchartWidgetProps,\n\t});\n\tcontext.saveChart?.(chartId, updatedChartWidgetProps);\n\treturn {\n\t\tmessage: 'Chart style options updated successfully',\n\t};\n};\n","export const TOOL_NAME_CHART_BUILDER = 'buildChart';\nexport const TOOL_NAME_DASHBOARD_BUILDER = 'buildDashboard';\nexport const TOOL_NAME_DATA_MODEL_BUILDER = 'buildDataModel';\nexport const TOOL_NAME_RECOMMEND_QUERIES = 'recommendQueries';\nexport const TOOL_NAME_GET_DASHBOARDS = 'getDashboards';\nexport const TOOL_NAME_GET_DATA_SOURCES = 'getDataSources';\nexport const TOOL_NAME_GET_DATA_SOURCE_FIELDS = 'getDataSourceFields';\n\n// limit the number of assets to consider to keep the tool system prompt not too long\nexport const TOOL_CONTEXT_MAX_ASSETS = 10;\n","import { ExtendedChartWidgetProps, BaseChartSummary } from './types';\n\n/**\n * Get a base chart summary from chart props\n * Pure function with no store dependencies\n */\nexport const getBaseChartSummary = (\n\twidgetProps: ExtendedChartWidgetProps,\n\tdataSourceTitle: string,\n): BaseChartSummary => {\n\treturn {\n\t\ttitle: widgetProps.title,\n\t\tdataSourceTitle,\n\t\tchartType: widgetProps.chartType,\n\t\tfilters: 'Filters to be updated',\n\t\tdataOptions: 'Data options to be updated',\n\t\tstyleOptions: 'Style options to be updated',\n\t};\n};\n","import {\n\texcludeSchemaProperties,\n\tfilterSchemaProperties,\n\tzodFunction,\n\tzodToReadableType,\n} from '@/utils/zod-utils';\nimport {\n\tChartSummary,\n\tcreateChartSchema,\n\tupdateChartStyleOptionsSchema,\n\tupdateChartTitleSchema,\n\tupdateChartTypeSchema,\n\tExtendedChartWidgetProps,\n\tupdateChartTypeOfMeasuresSchema,\n\tupdateChartSortingSchema,\n\tupdateTrendAndForecastSchema,\n\tupdateOtherChartDataOptionsSchema,\n\tBuildChartContext,\n\tbuildChartSchema,\n} from './types';\nimport { createChart } from './create-chart/create-chart';\nimport { updateChartTitle } from './update-chart/update-chart-title';\nimport { updateChartType } from './update-chart/update-chart-type';\nimport { updateChartDataOptions } from './update-chart/update-chart-data-options';\nimport { updateChartStyleOptions } from './update-chart/update-chart-style-options';\nimport {\n\tchartDataOptionsSchemas,\n\tchartStyleSchemas,\n} from './update-chart/chart-options-schemas';\nimport { TOOL_CONTEXT_MAX_ASSETS, TOOL_NAME_CHART_BUILDER } from '@/constants';\nimport { getBaseChartSummary } from './chart-builder-service';\nimport z from 'zod';\nimport { createToolsCompletion } from '@/utils/chat-completion-utils';\n\n/**\n * Higher-order function to create a tool with bound context\n * @param originalSchema - The schema for the tool\n * @param name - The name of the tool\n * @param originalFunction - The function to call when the tool is used\n * @param boundContext - The context for the chart builder\n * @returns A zod function for the tool\n */\nconst createChartTool = (\n\toriginalSchema: any,\n\tname: string,\n\tdescription: string,\n\toriginalFunction: any,\n\tboundContext: BuildChartContext,\n) => {\n\treturn zodFunction({\n\t\tschema: originalSchema,\n\t\tname,\n\t\tdescription,\n\t\tfunction: async (params: any, context: any) => {\n\t\t\t// Merge LLM params with bound context params and dependencies\n\t\t\treturn originalFunction(\n\t\t\t\t{ ...params },\n\t\t\t\t{ ...boundContext, ...context },\n\t\t\t);\n\t\t},\n\t});\n};\n\n/**\n * Create a set of tools for the chart builder with injected dependencies\n * @param context - The bound context for the chart builder.\n * @returns A set of tools for the chart builder.\n */\nconst createChartTools = (context: BuildChartContext) => {\n\treturn [\n\t\tcreateChartTool(\n\t\t\tcreateChartSchema,\n\t\t\t'createChart',\n\t\t\t'Create a new chart from user prompt. Use this tool for initial creation OR when adding/removing/swapping data fields (e.g. changing Revenue to Profit). This tool also handles data limits (Top 10, Bottom 5).',\n\t\t\tcreateChart,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTitleSchema,\n\t\t\t'updateChartTitle',\n\t\t\t'Update the title of an existing chart',\n\t\t\tupdateChartTitle,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTypeSchema,\n\t\t\t'updateChartType',\n\t\t\t'Switch the chart type of an existing chart',\n\t\t\tupdateChartType,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartTypeOfMeasuresSchema,\n\t\t\t'updateChartTypeOfMeasures',\n\t\t\t`Update the chart type of specific measures within a mixed/combo chart (e.g., make one measure a Bar and another a Line).\n\t\t\n\t\tSee the following options for editing the chart type of existing measures:\n\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, ['column', 'chartType']),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartSortingSchema,\n\t\t\t'updateChartSorting',\n\t\t\t`Update the sorting order (Ascending/Descending) of an existing chart. \n \n IMPORTANT: This tool ONLY handles the sorting order. It does NOT handle data limits or filtering (e.g., \"Top 10\", \"Bottom 5\"). Those constraints must be applied during chart creation or regeneration.\n\t\t\n\t\tSee the following sorting options for editing:\n\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, ['column', 'sortType']),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateTrendAndForecastSchema,\n\t\t\t'updateTrendAndForecast',\n\t\t\t`Update the trend and forecast analysis of existing measures in an existing chart\n\t\t\n\t\tSee the following trend and forecast analysis options for editing:\n\t\t\n\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t.map(\n\t\t\t\t([key, value]) =>\n\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\tfilterSchemaProperties(value, [\n\t\t\t\t\t\t\t'column',\n\t\t\t\t\t\t\t'trend',\n\t\t\t\t\t\t\t'forecast',\n\t\t\t\t\t\t]),\n\t\t\t\t\t)}`,\n\t\t\t)\n\t\t\t.join('\\n')}\n\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateOtherChartDataOptionsSchema,\n\t\t\t'updateOtherChartDataOptions',\n\t\t\t`Update other data options of an existing chart including visual encodings of axes (x-axis, y-axis, and right y-axis), dimensions, and measures\n\n\t\t\tFor a measure, for example, you can update its color and show it on the right axis.\n\n\t\t\tIMPORTANT: This tool cannot swap data columns (e.g. changing \"Revenue\" to \"Profit\"). Use createChart for that.\n\n\t\t\tSee the following data options for editing:\n\n\t\t\t${Object.entries(chartDataOptionsSchemas)\n\t\t\t\t.map(\n\t\t\t\t\t([key, value]) =>\n\t\t\t\t\t\t`- ${key}: ${zodToReadableType(\n\t\t\t\t\t\t\texcludeSchemaProperties(value, [\n\t\t\t\t\t\t\t\t'sortType', // Has dedicated sorting tool\n\t\t\t\t\t\t\t\t'trend', // Has dedicated trend/forecast tool\n\t\t\t\t\t\t\t\t'forecast', // Has dedicated trend/forecast tool\n\t\t\t\t\t\t\t\t'chartType', // Has dedicated chartType tool\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t)}`,\n\t\t\t\t)\n\t\t\t\t.join('\\n')}\n\t\t\t`,\n\t\t\tupdateChartDataOptions,\n\t\t\tcontext,\n\t\t),\n\n\t\tcreateChartTool(\n\t\t\tupdateChartStyleOptionsSchema,\n\t\t\t'updateChartStyleOptions',\n\t\t\t`Update cosmetic styling options: legend position, axis titles (text), axis label formatting.\n\n\t\t\tSee the following styling options for editing:\n\n\t\t\t${Object.entries(chartStyleSchemas)\n\t\t\t\t.map(([key, value]) => `- ${key}: ${zodToReadableType(value)}`)\n\t\t\t\t.join('\\n')}\n\t\t\t\n\t\t\t`,\n\t\t\tupdateChartStyleOptions,\n\t\t\tcontext,\n\t\t),\n\t];\n};\n\n/**\n * Build contextual system prompt for chart builder\n */\nexport function buildContextualSystemPrompt(chartSummaries: ChartSummary[]) {\n\treturn `You are an intelligent and proactive chart assistant. \nYour role is to create and update a chart based on natural language requests by using the available tools.\n\nIMPORTANT INSTRUCTIONS:\n1. Use the charts and their revisions in the following context to build the chart: ${JSON.stringify(\n\t\t{\n\t\t\tcharts: chartSummaries,\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\n2. Always reference the charts by their IDs instead of their titles.\n\n3. Use the last chart in the context as the current chart unless the user prompt specifies otherwise.\n\n4. If the user prompt involves multiple actions that require different available tools (e.g., sorting, trend and forecast, chart type of measures, and other data options), \nsplit it into multiple prompts. For example, if the user prompt is \"create a new chart showing total revenue by brand, and sort by revenue in descending order\", \nsplit it into two prompts: \"create a new chart showing total revenue by brand\" and \"sort by revenue in descending order\" in step by step.\nIf the prompt can be handled by a single tool, use that tool without splitting the prompt into multiple steps.\n\n5. When responding to changes involving an existing chart:\n - If the prompt involves **adding or removing** chart's data structure such as dimensions, measures, or filters (e.g., \"add revenue\", \"remove date\", \"filter by region\"), do **not** modify the existing chart. Instead, **redo a new chart** with the requested changes in step-by-step prompts.\n - If the prompt involves **enhancing** how existing fields are displayed (e.g., \"sort by revenue in descending order\", \"show cost on the right axis\", \"add trend line\", \"add forecast line\", \"remove trend line\", \"remove forecast line\"), apply the changes **to the existing chart** in step by step.\n\n6. When updating the chart type of existing measures, re-apply the data options and style options changes to the new chart.\n\n`;\n}\n\n/**\n * Standalone chart builder engine - completely decoupled from any UI or store\n * @param params - The parameters for the chart builder\n * @param context - All external dependencies injected\n * @returns The chart summary\n */\nexport async function buildChartEngine(\n\tparams: z.infer<typeof buildChartSchema>,\n\tcontext: BuildChartContext,\n): Promise<ChartSummary> {\n\tconst { dataSourceTitle, userPrompt } = params;\n\n\tconsole.debug(TOOL_NAME_CHART_BUILDER, dataSourceTitle, userPrompt);\n\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\n\tif (!userPrompt) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify textual user input',\n\t\t);\n\t}\n\n\t// use the tool call id as the new chart id\n\tconst newChartId = context.toolCallId;\n\n\tlet savedChartWidgetProps: ExtendedChartWidgetProps | null = null;\n\n\tlet message = '';\n\tlet isError = false;\n\n\tconst updatedContext: BuildChartContext = {\n\t\t...context,\n\t\tdataSourceTitle,\n\t\tretrieveChart: (chartId: string) => {\n\t\t\t// Prioritize savedChartWidgetProps in case of subsequent tool calls\n\t\t\tif (savedChartWidgetProps) {\n\t\t\t\treturn savedChartWidgetProps;\n\t\t\t}\n\t\t\tif (chartId && context.retrieveChart) {\n\t\t\t\treturn context.retrieveChart(chartId);\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsaveChart: (_, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\tcontext.saveChart?.(newChartId, chartWidgetProps);\n\t\t\tsavedChartWidgetProps = chartWidgetProps;\n\t\t},\n\t};\n\n\tconst systemPrompt = buildContextualSystemPrompt(\n\t\t(context.chartSummaries ?? []).slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t);\n\n\tconst internalTools = createChartTools(updatedContext);\n\n\t// Execute orchestration\n\tconst { combinedMessage, isError: isErrorInToolsCompletion } =\n\t\tawait createToolsCompletion({\n\t\t\tsystemPrompt,\n\t\t\tuserPrompt,\n\t\t\ttools: internalTools,\n\t\t\topenAIClient: context.openAIClient,\n\t\t});\n\n\tmessage = combinedMessage;\n\tisError = isErrorInToolsCompletion;\n\n\tif (isError) {\n\t\tthrow new Error(message);\n\t}\n\n\treturn {\n\t\tmessage,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tchartId: newChartId,\n\t\tchart: savedChartWidgetProps\n\t\t\t? getBaseChartSummary(savedChartWidgetProps, dataSourceTitle)\n\t\t\t: undefined,\n\t};\n}\n","import { DataSourceSchema } from '@sisense/sdk-data';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { getHttpClient } from '@/singleton-clients';\n\nconst DATA_MODELS_API_URL_PATH = 'api/v2/datamodels';\n\n/**\n * Returns the schema of a data source by its name.\n */\nexport async function getDataSourceSchema(\n\tdataSourceName: string,\n\thttpClient?: HttpClient,\n): Promise<DataSourceSchema | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst url = `${DATA_MODELS_API_URL_PATH}/schema?title=${encodeURIComponent(\n\t\tdataSourceName,\n\t)}`;\n\tconst result = await client.get<DataSourceSchema>(url);\n\treturn result ?? null;\n}\n","import {\n\tDataSourceField,\n\tDateLevels,\n\tnormalizeName,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { getDataSourceSchema } from '@/services/data-models/data-models-service';\nimport { getHttpClient } from '@/singleton-clients';\n\nexport const DATA_SOURCES_API_URL_PATH = 'api/datasources';\n\n/**\n * Data source schema table\n */\ntype DataSourceSchemaTable = {\n\tname: string;\n\tcolumns: {\n\t\tname: string;\n\t\tdescription: string | null;\n\t}[];\n};\n\n/**\n * Data source schema table\n */\ntype DataSourceSchemaDataset = {\n\tschema: {\n\t\ttables: DataSourceSchemaTable[];\n\t};\n};\n\nexport type DataSourceFieldWithDescription = DataSourceField & {\n\tdescription?: string;\n\ttableDescription?: string;\n};\n\nexport type NormalizedDataSourceField = {\n\ttable: string;\n\tcolumn: string;\n\ttype: string;\n\tlevel?: string;\n\texpression: string;\n\tdescription: string;\n};\n\n/**\n * Add 'description' property from datasource schema columns to datasource fields\n */\nfunction addDescriptionToFields(\n\tfields: DataSourceField[],\n\tdatasets: DataSourceSchemaDataset[],\n): DataSourceFieldWithDescription[] {\n\tconst schemaDataDescriptionsMap = datasets.reduce(\n\t\t(map: Record<string, Record<string, string | null>>, dataset) => {\n\t\t\tdataset.schema.tables.forEach((table) => {\n\t\t\t\tmap[table.name] = {};\n\t\t\t\ttable.columns.forEach((column) => {\n\t\t\t\t\tmap[table.name][column.name] = column.description;\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn map;\n\t\t},\n\t\t{},\n\t);\n\n\treturn fields.map((field) => ({\n\t\t...field,\n\t\tdescription:\n\t\t\tschemaDataDescriptionsMap[field.table]?.[field.column] || '',\n\t})) as DataSourceFieldWithDescription[];\n}\n\nexport async function getDataSources(\n\thttpClient?: HttpClient,\n): Promise<JaqlDataSourceForDto[]> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst url = `${DATA_SOURCES_API_URL_PATH}/?sharedWith=r,w`;\n\tconst result = await client.get<JaqlDataSourceForDto[]>(url);\n\treturn result || [];\n}\n\n/**\n * Get a data source by title\n */\nexport async function getDataSourceByTitle(\n\tdataSourceTitle: string,\n\thttpClient?: HttpClient,\n): Promise<JaqlDataSourceForDto | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.get<JaqlDataSourceForDto>(\n\t\t`${DATA_SOURCES_API_URL_PATH}/${encodeURIComponent(dataSourceTitle)}`,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Get data source fields\n */\nexport async function getDataSourceFields(\n\tdataSourceTitle: string,\n\thttpClient?: HttpClient,\n): Promise<DataSourceField[] | null> {\n\tconst client = httpClient ?? getHttpClient();\n\treturn client\n\t\t.post<DataSourceField[]>(\n\t\t\t`${DATA_SOURCES_API_URL_PATH}/${encodeURIComponent(\n\t\t\t\tdataSourceTitle,\n\t\t\t)}/fields/search`,\n\t\t\t{\n\t\t\t\toffset: 0,\n\t\t\t\tcount: 9999,\n\t\t\t},\n\t\t)\n\t\t.then((result) => result ?? null);\n}\n\n/**\n * Get data source fields with descriptions from schema\n */\nexport async function getDataSourceFieldsWithDescriptions(\n\tdataSourceTitle: string,\n\thttpClient?: HttpClient,\n): Promise<DataSourceFieldWithDescription[] | DataSourceField[]> {\n\tconst fields = await getDataSourceFields(dataSourceTitle, httpClient);\n\tif (!fields) return [];\n\n\ttry {\n\t\tconst dataSourceSchema = await getDataSourceSchema(\n\t\t\tdataSourceTitle,\n\t\t\thttpClient,\n\t\t);\n\t\treturn dataSourceSchema?.datasets\n\t\t\t? addDescriptionToFields(\n\t\t\t\t\tfields,\n\t\t\t\t\tdataSourceSchema.datasets as DataSourceSchemaDataset[],\n\t\t\t )\n\t\t\t: fields;\n\t} catch (error) {\n\t\t// Normalize various error shapes (fetch, axios, custom)\n\t\tconst err: any = error as any;\n\t\tconst status = err?.status ?? err?.statusCode ?? err?.response?.status;\n\n\t\t// Not found: schema endpoint missing in some deployments or hidden by permissions.\n\t\tif ((status === 404 || status === '404') && fields.length) {\n\t\t\treturn fields;\n\t\t}\n\n\t\t// Unauthorized / Forbidden: user lacks permission to read schema. Fall back to fields without descriptions.\n\t\tif (\n\t\t\tstatus === 401 ||\n\t\t\tstatus === '401' ||\n\t\t\tstatus === 403 ||\n\t\t\tstatus === '403'\n\t\t) {\n\t\t\tconsole.log(\n\t\t\t\t`Note: Field descriptions are omitted from the data model due to restricted role of your account`,\n\t\t\t);\n\t\t\treturn fields;\n\t\t}\n\n\t\t// Unknown error shape — rethrow to surface real issues instead of masking them.\n\t\tthrow error;\n\t}\n}\n\n/**\n * Normalize data source fields (pure function - easily testable)\n */\nexport function normalizeFields(\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[],\n): NormalizedDataSourceField[] {\n\tconst normalizedFields: NormalizedDataSourceField[] = [];\n\n\tfields.forEach((field) => {\n\t\tconst normalizedName = normalizeName(field.column);\n\t\tconst baseField = {\n\t\t\ttable: normalizeName(field.table),\n\t\t\tcolumn: normalizedName,\n\t\t\ttype: field.dimtype,\n\t\t\texpression: field.id,\n\t\t\tdescription: field.description || `${field.table}.${field.column}`,\n\t\t};\n\n\t\tnormalizedFields.push(baseField);\n\n\t\tif (field.dimtype === 'datetime') {\n\t\t\t// Add fields for each date level\n\t\t\tDateLevels.all.forEach((level) => {\n\t\t\t\tnormalizedFields.push({\n\t\t\t\t\t...baseField,\n\t\t\t\t\tcolumn: `${normalizedName}.${level}`,\n\t\t\t\t\ttype: 'datetime',\n\t\t\t\t\tlevel: level,\n\t\t\t\t\texpression: field.id,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\tfield.description ||\n\t\t\t\t\t\t`${field.table}.${field.column}.${level}`,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t});\n\n\treturn normalizedFields;\n}\n\n/**\n * Get normalized data source fields\n * @param dataSourceTitle - The title of the data source\n * @param getFieldsFn - Optional function to get fields (for testing)\n */\nexport async function getNormalizedDataSourceFields(\n\tdataSourceTitle: string,\n\tgetFieldsFn?: (\n\t\ttitle: string,\n\t\tclient?: HttpClient,\n\t) => Promise<DataSourceFieldWithDescription[] | DataSourceField[]>,\n\thttpClient?: HttpClient,\n): Promise<NormalizedDataSourceField[]> {\n\tconst fieldsFn = getFieldsFn ?? getDataSourceFieldsWithDescriptions;\n\tconst fields = await fieldsFn(dataSourceTitle, httpClient);\n\treturn normalizeFields(fields);\n}\n","import { z } from 'zod';\nimport { getDataSources } from '@/services/data-sources/data-sources-service';\nimport { TOOL_NAME_GET_DATA_SOURCES } from '@/constants';\nimport {\n\tgetDataSourcesSchema,\n\tGetDataSourcesContext,\n\tDataSourcesResult,\n} from './types';\n\n/**\n * Standalone data sources engine - completely decoupled from any UI or store\n * @param params - The parameters for getting data sources (currently empty)\n * @param context - Context with tool call ID for tracking\n * @returns The data sources summary with titles and full objects\n */\nexport async function getDataSourcesEngine(\n\tparams: z.infer<typeof getDataSourcesSchema>,\n\tcontext: GetDataSourcesContext,\n): Promise<DataSourcesResult> {\n\tconsole.debug(TOOL_NAME_GET_DATA_SOURCES, context.toolCallId);\n\n\tconst dataSources = await getDataSources(context.httpClient);\n\n\treturn {\n\t\tdataSourceTitles: dataSources.map((ds) => ds.title),\n\t\tdataSources: dataSources,\n\t};\n}\n","import { z } from 'zod';\nimport { JaqlDataSourceForDto } from '@sisense/sdk-data';\nimport { HttpClient } from '@sisense/sdk-rest-client';\n\n/**\n * Schema for getDataSources engine parameters\n */\nexport const getDataSourcesSchema = z.object({});\n\n/**\n * Context interface for getDataSourcesEngine\n */\nexport interface GetDataSourcesContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\thttpClient?: HttpClient;\n}\n\n/**\n * Result from getDataSourcesEngine\n */\nexport interface DataSourcesResult {\n\t/**\n\t * List of data source titles\n\t */\n\tdataSourceTitles: string[];\n\t/**\n\t * Full data source objects\n\t */\n\tdataSources: JaqlDataSourceForDto[];\n}\n","import { z } from 'zod';\nimport { getDataSourceFieldsWithDescriptions } from '@/services/data-sources/data-sources-service';\nimport { TOOL_NAME_GET_DATA_SOURCE_FIELDS } from '@/constants';\nimport {\n\tgetDataSourceFieldsSchema,\n\tGetDataSourceFieldsContext,\n\tDataSourceFieldsResult,\n} from './types';\n\n/**\n * Standalone data source fields engine - completely decoupled from any UI or store\n * @param params - The parameters containing the data source title\n * @param context - Context with tool call ID for tracking\n * @returns The data source fields summary with title and fields\n */\nexport async function getDataSourceFieldsEngine(\n\tparams: z.infer<typeof getDataSourceFieldsSchema>,\n\tcontext: GetDataSourceFieldsContext,\n): Promise<DataSourceFieldsResult> {\n\tconst { dataSourceTitle } = params;\n\n\tconsole.debug(\n\t\tTOOL_NAME_GET_DATA_SOURCE_FIELDS,\n\t\tdataSourceTitle,\n\t\tcontext.toolCallId,\n\t);\n\n\tif (!dataSourceTitle) {\n\t\tthrow new Error(\n\t\t\t'Error: Please ask the user to specify a data source title',\n\t\t);\n\t}\n\n\tconst fields = await getDataSourceFieldsWithDescriptions(\n\t\tdataSourceTitle,\n\t\tcontext.httpClient,\n\t);\n\n\treturn {\n\t\tdataSourceTitle,\n\t\tfields: fields || [],\n\t};\n}\n","import { z } from 'zod';\nimport { DataSourceField } from '@sisense/sdk-data';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { DataSourceFieldWithDescription } from '@/services/data-sources/data-sources-service';\n\n/**\n * Schema for getDataSourceFields engine parameters\n */\nexport const getDataSourceFieldsSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n});\n\n/**\n * Context interface for getDataSourceFieldsEngine\n */\nexport interface GetDataSourceFieldsContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\thttpClient?: HttpClient;\n}\n\n/**\n * Result from getDataSourceFieldsEngine\n */\nexport interface DataSourceFieldsResult {\n\t/**\n\t * The title of the data source\n\t */\n\tdataSourceTitle: string;\n\t/**\n\t * List of fields (may or may not have descriptions depending on availability)\n\t */\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[];\n}\n","import {\n\tdashboardModelTranslator,\n\tDashboardProps,\n\tisChartWidgetProps,\n\ttranslateFiltersAndRelationsToDto,\n\tWidgetDto,\n\twidgetModelTranslator,\n\tWidgetProps,\n\tWidgetsPanelColumnLayout,\n\tDashboardDto,\n\tgetDashboardModel,\n} from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { getDataSourceByTitle } from '@/services/data-sources/data-sources-service';\nimport { getHttpClient } from '@/singleton-clients';\nimport { normalizeUrl } from '@/utils/utils';\nimport {\n\tconvertJaqlDataSourceForDto,\n\tFilter,\n\tFilterRelations,\n\tisDataSourceInfo,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\n\nconst FUSION_DASHBOARDS_API_URL_PATH = 'api/v1/dashboards';\n\ntype GetDashboardsOptions = {\n\tsearchByTitle?: string;\n\tfields?: string[];\n\texpand?: string[];\n};\n\nexport type Dashboard = {\n\tdashboardId: string;\n\tdashboardTitle: string;\n\tdataSourceTitle: string;\n};\n\nexport function getFusionDashboardUrl(\n\tdashboardOid: string,\n\thttpClient?: HttpClient,\n): string {\n\tconst client = httpClient ?? getHttpClient();\n\treturn `${normalizeUrl(client.url)}app/main/dashboards/${dashboardOid}`;\n}\n\n/**\n * Get all dashboards\n */\nexport async function getFusionDashboards(\n\toptions: GetDashboardsOptions = {},\n\thttpClient?: HttpClient,\n): Promise<DashboardDto[]> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst { fields, expand, searchByTitle } = options;\n\tconst queryParams = new URLSearchParams({\n\t\t...(searchByTitle && { name: searchByTitle }),\n\t\t...(fields?.length && { fields: fields?.join(',') }),\n\t\t...(expand?.length && { expand: expand?.join(',') }),\n\t}).toString();\n\n\tconst dashboards = await client.get<DashboardDto[]>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}?${queryParams}`,\n\t);\n\n\tif (!dashboards) return [];\n\n\treturn dashboards;\n}\n\n/**\n * Get all widgets of a specific dashboard\n */\nexport async function getFusionDashboardWidgets(\n\tdashboardOid: string,\n\thttpClient?: HttpClient,\n): Promise<WidgetDto[]> {\n\tconst client = httpClient ?? getHttpClient();\n\ttry {\n\t\tconst widgets = await client.get<WidgetDto[]>(\n\t\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets`,\n\t\t);\n\t\treturn widgets ?? [];\n\t} catch {\n\t\t// when error is encountered, API may return only status code 422 without informative error message\n\t\t// to remedy, catch error and throw a more informative error message\n\t\tthrow new Error(\n\t\t\t'Failed to retrieve dashboard widgets. Please make sure the dashboard exists and is accessible.',\n\t\t);\n\t}\n}\n\n/**\n * Get dashboard model from Fusion\n */\nexport async function getFusionDashboardModel(\n\tdashboardOid: string,\n\thttpClient?: HttpClient,\n) {\n\tconst client = httpClient ?? getHttpClient();\n\treturn await getDashboardModel(client, dashboardOid, {\n\t\tincludeWidgets: true,\n\t\tincludeFilters: true,\n\t});\n}\n\n/**\n * Partially update a dashboard\n */\nexport async function patchFusionDashboard(\n\tdashboardOid: string,\n\tdashboard: Partial<DashboardDto>,\n\thttpClient?: HttpClient,\n): Promise<DashboardDto | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.patch<DashboardDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}`,\n\t\tdashboard,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Add widget to a dashboard\n */\nexport async function addWidgetToFusionDashboard(\n\tdashboardOid: string,\n\twidgetDto: WidgetDto,\n\thttpClient?: HttpClient,\n): Promise<WidgetDto | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.post<WidgetDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets`,\n\t\twidgetDto,\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Create an empty dashboard\n */\nexport async function createEmptyFusionDashboard(\n\tdashboardTitle: string,\n\tdataSource: JaqlDataSourceForDto,\n\thttpClient?: HttpClient,\n): Promise<DashboardDto | null> {\n\tconst client = httpClient ?? getHttpClient();\n\tconst result = await client.post<DashboardDto>(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}`,\n\t\t{\n\t\t\ttitle: dashboardTitle,\n\t\t\tdatasource: dataSource,\n\t\t\tsettings: { managedByTool: 'studio-assistant' },\n\t\t},\n\t);\n\treturn result ?? null;\n}\n\n/**\n * Delete a dashboard\n */\nexport function deleteFusionDashboard(\n\tdashboardOid: string,\n\thttpClient?: HttpClient,\n): Promise<void> {\n\tconst client = httpClient ?? getHttpClient();\n\treturn client.delete(`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}`);\n}\n\n/**\n * Delete a widget from a dashboard\n */\nfunction deleteWidgetFromFusionDashboard(\n\tdashboardOid: string,\n\twidgetOid: string,\n\thttpClient?: HttpClient,\n): Promise<void> {\n\tconst client = httpClient ?? getHttpClient();\n\treturn client.delete(\n\t\t`${FUSION_DASHBOARDS_API_URL_PATH}/${dashboardOid}/widgets/${widgetOid}`,\n\t);\n}\n\n/**\n * Translate layout to DTO format\n */\nfunction translateToLayoutDto(layout: WidgetsPanelColumnLayout) {\n\treturn {\n\t\tcolumns: layout.columns.map((c) => ({\n\t\t\twidth: c.widthPercentage,\n\t\t\tcells: c.rows.map((r) => ({\n\t\t\t\tsubcells: r.cells.map((cell) => ({\n\t\t\t\t\twidth: cell.widthPercentage,\n\t\t\t\t\telements: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\theight: cell.height ?? 384,\n\t\t\t\t\t\t\twidgetid: cell.widgetId,\n\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\tminWidth: 200,\n\t\t\t\t\t\t\tmaxWidth: 2000,\n\t\t\t\t\t\t\tminHeight: 200,\n\t\t\t\t\t\t\tmaxHeight: 2000,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t})),\n\t\t\t})),\n\t\t})),\n\t};\n}\n\n/**\n * Get available Fusion dashboards (filtered by studio-assistant)\n */\nexport async function getAvailableFusionDashboards(\n\thttpClient?: HttpClient,\n): Promise<Dashboard[]> {\n\tconst dashboardDtos = await getFusionDashboards(\n\t\t{\n\t\t\tfields: ['title', 'oid', 'datasource', 'settings'],\n\t\t},\n\t\thttpClient,\n\t);\n\tconst dashboards: Dashboard[] = dashboardDtos\n\t\t// TEMP: For public preview, show only dashboards managed by the studio assistant\n\t\t.filter(\n\t\t\t(dashboard) =>\n\t\t\t\tdashboard.settings?.managedByTool === 'studio-assistant',\n\t\t)\n\t\t.map((dashboard) => ({\n\t\t\tdashboardTitle: dashboard.title,\n\t\t\tdashboardId: dashboard.oid,\n\t\t\tdataSourceTitle: dashboard.datasource.title,\n\t\t}));\n\n\treturn dashboards;\n}\n\n/**\n * Get Fusion dashboard props\n */\nexport async function getFusionDashboardProps(\n\tdashboardOid: string,\n\thttpClient?: HttpClient,\n): Promise<DashboardProps | undefined> {\n\tconst dashboardModel = await getFusionDashboardModel(\n\t\tdashboardOid,\n\t\thttpClient,\n\t);\n\t// TEMP: For public preview, show only dashboards created by the studio assistant\n\tif (\n\t\tdashboardModel &&\n\t\tdashboardModel.settings?.managedByTool !== 'studio-assistant'\n\t) {\n\t\treturn undefined;\n\t}\n\treturn dashboardModel\n\t\t? dashboardModelTranslator.toDashboardProps(dashboardModel)\n\t\t: undefined;\n}\n\n/**\n * Load existing dashboard from Fusion\n */\nexport async function loadExistingDashboardFromFusion(\n\tdashboardId: string,\n\thttpClient?: HttpClient,\n): Promise<DashboardProps> {\n\tconst fusionDashboardProps = await getFusionDashboardProps(\n\t\tdashboardId,\n\t\thttpClient,\n\t);\n\tif (!fusionDashboardProps) {\n\t\tthrow new Error(\n\t\t\t'Dashboard not available for editing. Please specify a different dashboard.',\n\t\t);\n\t}\n\treturn fusionDashboardProps;\n}\n\n/**\n * Add widgets to Fusion dashboard\n */\nexport async function addWidgetsToFusionDashboard(\n\tdashboardOid: string,\n\twidgetsToAdd: WidgetProps[],\n\thttpClient?: HttpClient,\n): Promise<WidgetDto[]> {\n\tif (widgetsToAdd.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst widgetDtos = widgetsToAdd.map((widgetProps) => {\n\t\tconst widgetModel = widgetModelTranslator.fromWidgetProps(widgetProps);\n\t\tconst dataSource =\n\t\t\tisChartWidgetProps(widgetProps) && widgetProps.dataSource\n\t\t\t\t? convertJaqlDataSourceForDto(widgetProps.dataSource)\n\t\t\t\t: undefined;\n\t\treturn widgetModelTranslator.toWidgetDto(widgetModel, dataSource);\n\t});\n\n\t// Create array of promises while preserving order\n\tconst widgetPromises = widgetDtos.map((widgetDto, index) =>\n\t\taddWidgetToFusionDashboard(dashboardOid, widgetDto, httpClient).then(\n\t\t\t(result) => ({\n\t\t\t\tindex,\n\t\t\t\tresult,\n\t\t\t}),\n\t\t),\n\t);\n\t// await is needed so we can align widget OIDs with input widgets later\n\tconst results = await Promise.all(widgetPromises);\n\t// Sort results by original index to maintain order\n\tconst updatedWidgetDtos = results\n\t\t.sort((a, b) => a.index - b.index)\n\t\t.map((r) => r.result)\n\t\t.filter((dto): dto is WidgetDto => dto !== undefined);\n\n\treturn updatedWidgetDtos;\n}\n\n/**\n * Update Fusion dashboard filters\n */\nexport async function updateFusionDashboardFilters(\n\tdashboardOid: string,\n\tfiltersToUpdate: Filter[] | FilterRelations,\n\thttpClient?: HttpClient,\n) {\n\tconst filtersDto = translateFiltersAndRelationsToDto(filtersToUpdate);\n\tawait patchFusionDashboard(dashboardOid, filtersDto, httpClient);\n}\n\n/**\n * Check if dashboard is saved\n */\nexport function isDashboardSaved(dashboardProps: DashboardProps): boolean {\n\treturn !!dashboardProps.id;\n}\n\n/**\n * Persist dashboard to Fusion\n */\nexport async function persistDashboardToFusion(\n\tdashboardProps: DashboardProps,\n\thttpClient?: HttpClient,\n): Promise<DashboardProps> {\n\tconst dataSource = dashboardProps.defaultDataSource;\n\n\tif (!dataSource) {\n\t\tthrow new Error('Dashboard must have a data source');\n\t}\n\n\tconst dataSourceTitle = isDataSourceInfo(dataSource)\n\t\t? dataSource.title\n\t\t: dataSource;\n\n\tconst jaqlDataSource = await getDataSourceByTitle(\n\t\tdataSourceTitle,\n\t\thttpClient,\n\t);\n\n\tif (!jaqlDataSource) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Please ask the user to specify a valid data source.',\n\t\t);\n\t}\n\n\tlet dashboardOid: string;\n\tlet dashboardTitle: string =\n\t\tdashboardProps.title || `Dashboard for ${dataSourceTitle}`;\n\n\tif (dashboardProps.id) {\n\t\tdashboardOid = dashboardProps.id;\n\t\ttry {\n\t\t\t// Dashboard already exists in Fusion - update it\n\t\t\tawait patchFusionDashboard(\n\t\t\t\tdashboardProps.id,\n\t\t\t\t{\n\t\t\t\t\ttitle: dashboardTitle,\n\t\t\t\t},\n\t\t\t\thttpClient,\n\t\t\t);\n\t\t\t// and delete all existing widgets in parallel to re-populate them later\n\t\t\tconst existingWidgetDtos = await getFusionDashboardWidgets(\n\t\t\t\tdashboardOid,\n\t\t\t\thttpClient,\n\t\t\t);\n\t\t\tif (existingWidgetDtos) {\n\t\t\t\tawait Promise.all(\n\t\t\t\t\texistingWidgetDtos.map((widgetDto) =>\n\t\t\t\t\t\tdeleteWidgetFromFusionDashboard(\n\t\t\t\t\t\t\tdashboardOid,\n\t\t\t\t\t\t\twidgetDto.oid,\n\t\t\t\t\t\t\thttpClient,\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\t// If dashboard not found (404), create a new one instead\n\t\t\tif (error?.status === '404' || error?.status === 404) {\n\t\t\t\tconst fusionDashboardDto = await createEmptyFusionDashboard(\n\t\t\t\t\tdashboardTitle,\n\t\t\t\t\tjaqlDataSource,\n\t\t\t\t\thttpClient,\n\t\t\t\t);\n\t\t\t\tif (!fusionDashboardDto) {\n\t\t\t\t\tthrow new Error('Error: Failed to create Fusion dashboard');\n\t\t\t\t}\n\t\t\t\tdashboardOid = fusionDashboardDto.oid;\n\t\t\t\tdashboardTitle = fusionDashboardDto.title;\n\t\t\t} else {\n\t\t\t\t// Re-throw other errors\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Dashboard doesn't exist in Fusion yet - create it\n\t\tconst fusionDashboardDto = await createEmptyFusionDashboard(\n\t\t\tdashboardTitle,\n\t\t\tjaqlDataSource,\n\t\t\thttpClient,\n\t\t);\n\t\tif (!fusionDashboardDto) {\n\t\t\tthrow new Error('Error: Failed to create Fusion dashboard');\n\t\t}\n\t\tdashboardOid = fusionDashboardDto.oid;\n\t\tdashboardTitle = fusionDashboardDto.title;\n\t}\n\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tid: dashboardOid,\n\t\ttitle: dashboardTitle,\n\t};\n\n\t// Add widgets to the Fusion dashboard\n\tconst updatedWidgetDtos = await addWidgetsToFusionDashboard(\n\t\tdashboardOid,\n\t\tdashboardProps.widgets,\n\t\thttpClient,\n\t);\n\n\t// update IDs of updated widget Dtos to input widgets\n\tconst updatedWidgets = dashboardProps.widgets.map((widget, index) => ({\n\t\t...widget,\n\t\tid: updatedWidgetDtos[index]?.oid ?? widget.id,\n\t\toldId: widget.id,\n\t}));\n\n\t// iterate through columns and cells in dashboardProps.layoutOptions.widgetsPanel\n\t// and update the widgetId of each cell to the id of the widget in updatedWidgets\n\tconst updatedWidgetsLayout = dashboardProps.layoutOptions?.widgetsPanel\n\t\t? {\n\t\t\t\t...dashboardProps.layoutOptions.widgetsPanel,\n\t\t\t\tcolumns: dashboardProps.layoutOptions.widgetsPanel.columns.map(\n\t\t\t\t\t(column) => ({\n\t\t\t\t\t\t...column,\n\t\t\t\t\t\trows: column.rows.map((row) => ({\n\t\t\t\t\t\t\t...row,\n\t\t\t\t\t\t\tcells: row.cells.map((cell) => ({\n\t\t\t\t\t\t\t\t...cell,\n\t\t\t\t\t\t\t\twidgetId:\n\t\t\t\t\t\t\t\t\tupdatedWidgets.find(\n\t\t\t\t\t\t\t\t\t\t(w) => w.oldId === cell.widgetId,\n\t\t\t\t\t\t\t\t\t)?.id || cell.widgetId,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t})),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t }\n\t\t: dashboardProps.layoutOptions?.widgetsPanel;\n\n\t// Update layout\n\tif (updatedWidgetsLayout) {\n\t\tawait patchFusionDashboard(\n\t\t\tdashboardOid,\n\t\t\t{\n\t\t\t\tlayout: translateToLayoutDto(updatedWidgetsLayout),\n\t\t\t},\n\t\t\thttpClient,\n\t\t);\n\t}\n\n\t// Update filters\n\tawait updateFusionDashboardFilters(\n\t\tdashboardOid,\n\t\tdashboardProps.filters ?? [],\n\t\thttpClient,\n\t);\n\n\treturn {\n\t\t...updatedDashboardProps,\n\t\twidgets: updatedWidgets,\n\t\tlayoutOptions: { widgetsPanel: updatedWidgetsLayout },\n\t};\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","import {\n\tDashboardChangeEvent,\n\tDashboardConfig,\n\tDashboardProps,\n\tWidgetProps,\n\tWidgetsPanelColumnLayout,\n\tWidgetsPanelLayout,\n} from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { getDataSourceByTitle } from '@/services/data-sources/data-sources-service';\nimport {\n\tconvertDataSource,\n\tconvertJaqlDataSourceForDto,\n\tFilter,\n\tFilterRelations,\n\tisDataSourceInfo,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport deepEq from 'fast-deep-equal';\nimport { nanoidHex } from '@/utils/id-utils';\n\n// Exported types and enums (remain outside the class)\nexport type DashboardChangeResult = {\n\tchanged: boolean;\n\tupdatedDashboardProps: DashboardProps;\n};\n\n// Core layout utilities (pure functions)\n\n/**\n * Extract widget IDs from layout structure\n */\nexport function extractWidgetIdsFromLayout(\n\tlayout: WidgetsPanelColumnLayout,\n): string[] {\n\treturn layout.columns.flatMap((column) =>\n\t\tcolumn.rows.flatMap((row) => row.cells.map((cell) => cell.widgetId)),\n\t);\n}\n\n/**\n * Remove cells that reference non-existent widgets, empty rows, and empty columns\n */\nexport function cleanupOrphanedCells(\n\tlayout: WidgetsPanelColumnLayout,\n\texistingWidgetIds: Set<string>,\n): WidgetsPanelColumnLayout {\n\tconst cleanedColumns = layout.columns\n\t\t.map((column) => ({\n\t\t\t...column,\n\t\t\trows: column.rows\n\t\t\t\t.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tcells: row.cells.filter((cell) =>\n\t\t\t\t\t\texistingWidgetIds.has(cell.widgetId),\n\t\t\t\t\t),\n\t\t\t\t}))\n\t\t\t\t.filter((row) => row.cells.length > 0), // Remove empty rows\n\t\t}))\n\t\t.filter((column) => column.rows.length > 0); // Remove empty columns\n\n\treturn cleanedColumns.length > 0\n\t\t? { columns: cleanedColumns }\n\t\t: { columns: [] };\n}\n\n/**\n * Set width to 100% if layout has only one column\n */\nexport function adjustSingleColumnWidth(\n\tlayout: WidgetsPanelColumnLayout,\n): WidgetsPanelColumnLayout {\n\tif (layout.columns.length === 1) {\n\t\treturn {\n\t\t\t...layout,\n\t\t\tcolumns: [\n\t\t\t\t{\n\t\t\t\t\t...layout.columns[0],\n\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\treturn layout;\n}\n\n/**\n * Find widgets that exist in dashboard but not in layout\n */\nexport function findOutOfPlaceWidgets(\n\twidgets: WidgetProps[],\n\tlayout: WidgetsPanelColumnLayout | undefined,\n): string[] {\n\tif (!layout) {\n\t\treturn [];\n\t}\n\n\tconst widgetsInLayout = extractWidgetIdsFromLayout(layout);\n\treturn widgets\n\t\t.filter((widget) => !widgetsInLayout.includes(widget.id))\n\t\t.map((widget) => widget.id);\n}\n\n/**\n * Orchestrate all cleanup steps after any dashboard change\n */\nexport function cleanupDashboardAfterChange(\n\tdashboardProps: DashboardProps,\n): DashboardChangeResult {\n\tlet updatedProps = { ...dashboardProps };\n\n\t// Find and remove out-of-place widgets\n\tconst outOfPlaceWidgetIds = findOutOfPlaceWidgets(\n\t\tupdatedProps.widgets,\n\t\tupdatedProps.layoutOptions?.widgetsPanel,\n\t);\n\tif (outOfPlaceWidgetIds.length > 0) {\n\t\tupdatedProps = deleteWidgetsFromDashboard(\n\t\t\tupdatedProps,\n\t\t\toutOfPlaceWidgetIds,\n\t\t);\n\t}\n\n\t// Clean up orphaned cells in layout\n\tif (updatedProps.layoutOptions?.widgetsPanel) {\n\t\tconst existingWidgetIds = new Set(\n\t\t\tupdatedProps.widgets.map((widget) => widget.id),\n\t\t);\n\t\tlet cleanedLayout = cleanupOrphanedCells(\n\t\t\tupdatedProps.layoutOptions.widgetsPanel,\n\t\t\texistingWidgetIds,\n\t\t);\n\t\tcleanedLayout = adjustSingleColumnWidth(cleanedLayout);\n\n\t\tupdatedProps = {\n\t\t\t...updatedProps,\n\t\t\tlayoutOptions: {\n\t\t\t\t...updatedProps.layoutOptions,\n\t\t\t\twidgetsPanel: cleanedLayout,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { changed: true, updatedDashboardProps: updatedProps };\n}\n\n/**\n * Handle filters update\n */\nfunction handleFiltersUpdate(\n\tdashboardProps: DashboardProps,\n\tfilters: Filter[] | FilterRelations,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tfilters,\n\t\t},\n\t};\n}\n\n/**\n * Handle filters panel collapse state change\n */\nfunction handleFiltersPanelCollapse(\n\tdashboardProps: DashboardProps,\n\tcollapsed: boolean,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tconfig: {\n\t\t\t\t...dashboardProps.config,\n\t\t\t\tfiltersPanel: {\n\t\t\t\t\t...dashboardProps.config?.filtersPanel,\n\t\t\t\t\tcollapsedInitially: collapsed,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Handle widgets panel layout update\n */\nfunction handleWidgetsPanelLayoutUpdate(\n\tdashboardProps: DashboardProps,\n\tlayout: WidgetsPanelLayout,\n): DashboardChangeResult {\n\t// somehow CSDK triggers the layout action after the layout is applied\n\t// and causing infinite re-renders. This is a quick fix to avoid that.\n\tif (deepEq(layout, dashboardProps.layoutOptions?.widgetsPanel)) {\n\t\treturn { changed: false, updatedDashboardProps: dashboardProps };\n\t}\n\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tlayoutOptions: {\n\t\t\t\t...dashboardProps.layoutOptions,\n\t\t\t\twidgetsPanel: layout,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/**\n * Handle widgets deletion\n */\nfunction handleWidgetsDelete(\n\tdashboardProps: DashboardProps,\n\twidgetIds: string[],\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: deleteWidgetsFromDashboard(\n\t\t\tdashboardProps,\n\t\t\twidgetIds,\n\t\t),\n\t};\n}\n\n/**\n * Handle widgets panel layout isEditing change\n */\nfunction handleWidgetsPanelLayoutIsEditingChange(\n\tdashboardProps: DashboardProps,\n\tisEditing: boolean,\n): DashboardChangeResult {\n\treturn {\n\t\tchanged: true,\n\t\tupdatedDashboardProps: {\n\t\t\t...dashboardProps,\n\t\t\tconfig: {\n\t\t\t\t...dashboardProps.config,\n\t\t\t\twidgetsPanel: {\n\t\t\t\t\t...dashboardProps.config?.widgetsPanel,\n\t\t\t\t\teditMode: {\n\t\t\t\t\t\t...dashboardProps.config?.widgetsPanel?.editMode,\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tisEditing,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport function getDashboardDataSourcesMap(\n\tdashboardProps: DashboardProps,\n): Map<string, JaqlDataSourceForDto> {\n\tconst dataSourcesMap = new Map<string, JaqlDataSourceForDto>();\n\tconst { widgets, defaultDataSource } = dashboardProps;\n\n\tif (defaultDataSource && isDataSourceInfo(defaultDataSource)) {\n\t\tdataSourcesMap.set(\n\t\t\tdefaultDataSource.title,\n\t\t\tconvertJaqlDataSourceForDto(defaultDataSource),\n\t\t);\n\t}\n\twidgets.forEach((widget) => {\n\t\tif (\n\t\t\t'dataSource' in widget &&\n\t\t\twidget.dataSource &&\n\t\t\tisDataSourceInfo(widget.dataSource)\n\t\t) {\n\t\t\tconst dataSourceTitle = widget.dataSource.title;\n\t\t\tif (!dataSourcesMap.has(dataSourceTitle)) {\n\t\t\t\tdataSourcesMap.set(\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tconvertJaqlDataSourceForDto(widget.dataSource),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t});\n\n\treturn dataSourcesMap;\n}\n\nexport function layoutDashboardWidgets(\n\twidgetOids: string[],\n): WidgetsPanelColumnLayout {\n\tconst widgetsLayout: WidgetsPanelColumnLayout =\n\t\twidgetOids.length === 1\n\t\t\t? {\n\t\t\t\t\t// use a 1-column layout\n\t\t\t\t\tcolumns: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\trows: widgetOids.map((widgetOid) => ({\n\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\t// use a 2-column layout\n\t\t\t\t\tcolumns: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 50,\n\t\t\t\t\t\t\trows: widgetOids\n\t\t\t\t\t\t\t\t.filter((_, index) => index % 2 === 0)\n\t\t\t\t\t\t\t\t.map((widgetOid) => ({\n\t\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twidthPercentage: 50,\n\t\t\t\t\t\t\trows: widgetOids\n\t\t\t\t\t\t\t\t.filter((_, index) => index % 2 !== 0)\n\t\t\t\t\t\t\t\t.map((widgetOid) => ({\n\t\t\t\t\t\t\t\t\tcells: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\twidgetId: widgetOid,\n\t\t\t\t\t\t\t\t\t\t\theight: 384,\n\t\t\t\t\t\t\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t };\n\treturn widgetsLayout;\n}\n\n/**\n * Adds a widget to a new row in the column with the smallest number of rows and returns the updated layout.\n *\n * @param layout - The dashboard layout object to modify.\n * @param widgetId - The ID of the widget to add to the new row.\n * @returns The updated layout object with the new widget added.\n */\nexport function withWidgetAdded(\n\tlayout: WidgetsPanelColumnLayout,\n\twidgetId: string,\n): WidgetsPanelColumnLayout {\n\t// Create a new cell with the widgetId\n\tconst newCell = {\n\t\twidthPercentage: 100, // Assuming the new cell takes the full width of the row\n\t\theight: '400px',\n\t\twidgetId: widgetId,\n\t};\n\n\t// Create a new row and add the new cell to it\n\tconst newRow = {\n\t\tcells: [newCell],\n\t};\n\n\t// If there are no columns, create the first column\n\tif (!layout.columns || layout.columns.length === 0) {\n\t\treturn {\n\t\t\t...(layout || { columns: [] }),\n\t\t\tcolumns: [\n\t\t\t\t{\n\t\t\t\t\twidthPercentage: 100,\n\t\t\t\t\trows: [newRow],\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t// Find the index of the column with the smallest number of rows\n\tlet minRows = layout.columns[0].rows.length;\n\tlet minIndex = 0;\n\tfor (let i = 1; i < layout.columns.length; i++) {\n\t\tif (layout.columns[i].rows.length < minRows) {\n\t\t\tminRows = layout.columns[i].rows.length;\n\t\t\tminIndex = i;\n\t\t}\n\t}\n\n\t// Clone the layout to avoid mutating the original object\n\treturn {\n\t\t...(layout || { columns: [] }),\n\t\tcolumns: layout.columns.map((column, index) =>\n\t\t\tindex === minIndex\n\t\t\t\t? { ...column, rows: [...column.rows, newRow] }\n\t\t\t\t: column,\n\t\t),\n\t};\n}\n\nexport function getBaseDashboardConfig(): DashboardConfig {\n\treturn {\n\t\ttoolbar: { visible: true },\n\t\twidgetsPanel: {\n\t\t\tresponsive: true,\n\t\t\teditMode: {\n\t\t\t\tenabled: true,\n\t\t\t\tisEditing: true,\n\t\t\t\tapplyChangesAsBatch: {\n\t\t\t\t\tenabled: false,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tfiltersPanel: {\n\t\t\tvisible: true,\n\t\t\tcollapsedInitially: false,\n\t\t\tactions: {\n\t\t\t\taddFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t\teditFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t\tdeleteFilter: {\n\t\t\t\t\tenabled: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction getBaseDashboardProps(): DashboardProps {\n\tconst dashboardProps: DashboardProps = {\n\t\ttitle: 'Dashboard Title',\n\t\twidgets: [],\n\t\tlayoutOptions: {},\n\t\tconfig: getBaseDashboardConfig(),\n\t\tfilters: [],\n\t};\n\n\treturn dashboardProps;\n}\n\nexport async function createEmptyDashboard(\n\tdataSourceTitle: string,\n\tdashboardTitle: string,\n\thttpClient?: HttpClient,\n): Promise<DashboardProps> {\n\tconst jaqlDataSource = await getDataSourceByTitle(\n\t\tdataSourceTitle,\n\t\thttpClient,\n\t);\n\tif (!jaqlDataSource) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Please ask the user to specify a valid data source.',\n\t\t);\n\t}\n\tconst dataSource = convertDataSource(jaqlDataSource);\n\n\treturn {\n\t\t...getBaseDashboardProps(),\n\t\ttitle: dashboardTitle,\n\t\tdefaultDataSource: dataSource,\n\t};\n}\n\nexport function resetWidgetForDashboard(widget: WidgetProps): WidgetProps {\n\t// regenerate Widget internal ID to make it unique for the dashboard\n\treturn {\n\t\t...widget,\n\t\tid: nanoidHex(),\n\t};\n}\n\nexport function addWidgetsToDashboard(\n\tdashboardProps: DashboardProps,\n\twidgetsToAdd: WidgetProps[],\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\twidgets: [...dashboardProps.widgets, ...widgetsToAdd],\n\t};\n}\n\nexport function updateDashboardWidgetsLayout(\n\tdashboardProps: DashboardProps,\n\tnewWidgetIds: string[] = [],\n): DashboardProps {\n\tconst currentWidgetsLayout = dashboardProps.layoutOptions?.widgetsPanel;\n\n\tlet widgetsLayout: WidgetsPanelColumnLayout = currentWidgetsLayout || {\n\t\tcolumns: [],\n\t};\n\t// for a dashboard without a layout, create a default layout\n\t// otherwise, update the layout with the new widget\n\tif (\n\t\t!currentWidgetsLayout ||\n\t\t!currentWidgetsLayout.columns ||\n\t\tcurrentWidgetsLayout.columns.length === 0\n\t) {\n\t\twidgetsLayout = layoutDashboardWidgets(\n\t\t\tdashboardProps.widgets.map((widget) => widget.id),\n\t\t);\n\t} else {\n\t\t// Ensure widgetsLayout is always defined\n\t\tif (!widgetsLayout) {\n\t\t\twidgetsLayout = layoutDashboardWidgets(\n\t\t\t\tdashboardProps.widgets.map((widget) => widget.id),\n\t\t\t);\n\t\t}\n\t\tnewWidgetIds.forEach((widgetId) => {\n\t\t\twidgetsLayout = withWidgetAdded(widgetsLayout, widgetId);\n\t\t});\n\t}\n\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tlayoutOptions: { widgetsPanel: widgetsLayout },\n\t};\n\n\treturn updatedDashboardProps;\n}\n\nexport function updateDashboardTitle(\n\tdashboardProps: DashboardProps,\n\tdashboardTitle: string,\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\ttitle: dashboardTitle,\n\t};\n}\n\nexport async function createNewDashboard(\n\tdataSourceTitle: string,\n\tdashboardTitle: string,\n\twidgets: WidgetProps[] = [],\n\thttpClient?: HttpClient,\n): Promise<DashboardProps> {\n\tconst dashboardProps = await createEmptyDashboard(\n\t\tdataSourceTitle,\n\t\tdashboardTitle,\n\t\thttpClient,\n\t);\n\treturn addWidgetsToExistingDashboard(dashboardProps, widgets);\n}\n\nexport function addWidgetsToExistingDashboard(\n\tdashboardProps: DashboardProps,\n\twidgets: WidgetProps[],\n): DashboardProps {\n\tif (widgets.length === 0) {\n\t\treturn dashboardProps;\n\t}\n\n\tconst updatedDashboardProps = addWidgetsToDashboard(\n\t\tdashboardProps,\n\t\twidgets,\n\t);\n\n\tconst updatedDashboardPropsWithLayout = updateDashboardWidgetsLayout(\n\t\tupdatedDashboardProps,\n\t\twidgets.map((widget) => widget.id),\n\t);\n\n\treturn updatedDashboardPropsWithLayout;\n}\n\nexport function deleteWidgetsFromDashboard(\n\tdashboardProps: DashboardProps,\n\twidgetIds: string[],\n): DashboardProps {\n\treturn {\n\t\t...dashboardProps,\n\t\twidgets: dashboardProps.widgets.filter(\n\t\t\t(widget) => !widgetIds.includes(widget.id),\n\t\t),\n\t};\n}\n\n// TODO: look into ways to do this in CSDK instead\nfunction handleChange(\n\tdashboardProps: DashboardProps,\n\tevent: DashboardChangeEvent,\n): DashboardChangeResult {\n\tswitch (event.type) {\n\t\tcase 'filters/updated':\n\t\t\treturn handleFiltersUpdate(dashboardProps, event.payload);\n\t\tcase 'filtersPanel/collapse/changed':\n\t\t\treturn handleFiltersPanelCollapse(dashboardProps, event.payload);\n\t\tcase 'widgetsPanel/layout/updated':\n\t\t\treturn handleWidgetsPanelLayoutUpdate(\n\t\t\t\tdashboardProps,\n\t\t\t\tevent.payload,\n\t\t\t);\n\t\tcase 'widgets/deleted':\n\t\t\treturn handleWidgetsDelete(dashboardProps, event.payload);\n\t\tcase 'widgetsPanel/editMode/isEditing/changed':\n\t\t\treturn handleWidgetsPanelLayoutIsEditingChange(\n\t\t\t\tdashboardProps,\n\t\t\t\tevent.payload,\n\t\t\t);\n\t\tdefault:\n\t\t\treturn { changed: false, updatedDashboardProps: dashboardProps };\n\t}\n}\n\nexport function changeDashboard(\n\tdashboardProps: DashboardProps,\n\tevent: DashboardChangeEvent,\n): DashboardChangeResult {\n\t// Delegate to specific handlers\n\tconst { changed, updatedDashboardProps } = handleChange(\n\t\tdashboardProps,\n\t\tevent,\n\t);\n\n\t// Apply cleanup if any changes were made\n\tif (changed) {\n\t\treturn cleanupDashboardAfterChange(updatedDashboardProps);\n\t}\n\n\treturn { changed, updatedDashboardProps };\n}\n","import { getHttpClient } from '@/singleton-clients';\nimport { nanoidUUIDv4 } from '@/utils/id-utils';\n\ntype CreateElasticubeProps = {\n\ttitle: string;\n};\n\ntype CreateElasticubeResponse = {\n\tdata: {\n\t\tnewCube: {\n\t\t\toid: string;\n\t\t};\n\t};\n\terrors: {\n\t\terror: {\n\t\t\tmessage: string;\n\t\t};\n\t}[];\n};\n\ntype GetCSVSchemaDetailsProps = {\n\tfilePath: string;\n\tfileName: string;\n};\n\ntype GetCSVSchemaDetailsResponse = {\n\tconnection: {\n\t\tApiVersion: number;\n\t\tfiles: string[];\n\t\tdelimiter: string;\n\t\thasHeader: boolean;\n\t\tignoreMissingColumns: boolean;\n\t\texcludeIfBegins: string;\n\t\texcludeIfContains: string;\n\t\tstringQuote: string;\n\t\tignoreFirstRows: string;\n\t\tculture: string;\n\t\tcolumnsDateTimePatterns: string;\n\t};\n\tschema: string;\n\ttable: string;\n};\n\ntype GetPerspectiveOidProps = {\n\telasticubeOid: string;\n};\n\ntype PerspectiveResponse = {\n\tlastUpdated: string;\n\ttitle: string;\n\tserver: string;\n\tdatasets: any[];\n\toid: string;\n\t'modeling-transformations': any[];\n\trelations: any[];\n\tshares: Array<{\n\t\tpartyId: string;\n\t\ttype: string;\n\t\tpermission: string;\n\t}>;\n\ttype: string;\n\trelationType: string;\n\texperiments: Record<string, any>;\n\tfiscal: string;\n\t_id: string;\n\tanalyticalEngine: Record<string, any>;\n\tbuildDestination: {\n\t\tdestination: string;\n\t};\n\tcreator: string;\n\thasDatasetsWithoutConnectionParameters: boolean | null;\n\tmodelStatistics: {\n\t\tenableModelStatistics: boolean;\n\t\tallTablesPerCollection: boolean;\n\t\tmaxTablesPerCollection: number;\n\t};\n\ttenantId: string;\n\trelationsTables: any[];\n\tdatamodelId: string;\n};\n\ntype GetPerspectiveOidResponse = {\n\tperspectives: PerspectiveResponse[];\n\trevisions: any[];\n};\n\ntype AddDataSetProps = {\n\telasticubeOid: string;\n\tfilePath: string;\n\tfileName: string;\n\ttable: any;\n\tperspectiveOid: string;\n};\n\ntype AddDataSetResponse = {\n\tdataSet: {\n\t\toid: string;\n\t};\n\tcolumns: any[];\n\ttableOid: string;\n};\n\ntype BuildElasticubeProps = {\n\telasticubeOid: string;\n};\n\ntype BuildElasticubeResponse = {\n\tbuildElasticube: {\n\t\toid: string;\n\t};\n};\n\nexport type BuildStatus =\n\t| 'building'\n\t| 'pending'\n\t| 'done'\n\t| 'failed'\n\t| 'cancelled';\n\nexport type BuildStatusResponse = {\n\toid: string;\n\tdatamodelId: string;\n\tbuildType: string;\n\tstatus: BuildStatus;\n\tdatamodelTitle: string;\n\tdatamodelType: string;\n\tindexSize: number;\n\tinstanceId: string;\n\tschemaLastUpdate: string;\n\tcreated: string;\n\tstarted: string;\n\tcompleted: string;\n\trowLimit: number;\n\tsource: string;\n};\n\ntype AddRelationProps = {\n\telasticubeOid: string;\n\tsource: any;\n\ttarget: any;\n};\n\ntype AddRelationResponse = {\n\trelation: {\n\t\toid: string;\n\t};\n};\n\nexport type GetElasticubesResponse = {\n\tdata: {\n\t\telasticubesMetadata: Array<{\n\t\t\toid: string;\n\t\t\ttitle: string;\n\t\t\tserver: string;\n\t\t\ttenant: {\n\t\t\t\t_id: string;\n\t\t\t\tname: string;\n\t\t\t\tsystemManagement: boolean;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tfiscal: string;\n\t\t\tserverId: string;\n\t\t\thasDatasets: boolean;\n\t\t\ttype: string;\n\t\t\trelationType: string;\n\t\t\tprovider: string;\n\t\t\timportTime: string;\n\t\t\thasDatasetsWithoutConnectionParameters: boolean;\n\t\t\tdatasets: Array<{\n\t\t\t\toid: string;\n\t\t\t\tdatabase: string;\n\t\t\t\tschemaName: string;\n\t\t\t\tconnection: {\n\t\t\t\t\tid: string;\n\t\t\t\t\t__typename: string;\n\t\t\t\t};\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tset: {\n\t\t\t\ttitle: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tstatus: string;\n\t\t\tlastBuildTime: string;\n\t\t\tlastBuildStatus: string;\n\t\t\tlastSuccessfulBuildStartTime: string;\n\t\t\tlastSuccessfulManualBuildStartTime: string;\n\t\t\tlastSuccessfulBuildTime: string;\n\t\t\tlastPublishTime: string;\n\t\t\tlastUpdated: string;\n\t\t\thasPendingChanges: boolean;\n\t\t\tnextBuildTime: string;\n\t\t\tcreator: {\n\t\t\t\tid: string;\n\t\t\t\tfirstName: string;\n\t\t\t\tlastName: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tsizeInMb: number;\n\t\t\tshares: Array<{\n\t\t\t\tpartyId: string;\n\t\t\t\ttype: string;\n\t\t\t\tpermission: string;\n\t\t\t\tfirstName?: string;\n\t\t\t\tlastName?: string;\n\t\t\t\temail?: string;\n\t\t\t\tname?: string;\n\t\t\t\tad?: boolean;\n\t\t\t\tobjectSid?: string;\n\t\t\t\teveryone?: boolean;\n\t\t\t\ttenantEveryone?: boolean;\n\t\t\t\tadmins?: boolean;\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tbuildDestination: {\n\t\t\t\tdestination: string;\n\t\t\t\tdatabase: string;\n\t\t\t\tschema: string;\n\t\t\t\tresultLimit: number;\n\t\t\t\tqueryTimeout: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tmodelStatistics: {\n\t\t\t\tenableModelStatistics: boolean;\n\t\t\t\tallTablesPerCollection: boolean;\n\t\t\t\tmaxTablesPerCollection: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\texperiments: Array<{\n\t\t\t\t__typename: string;\n\t\t\t}>;\n\t\t\tacceleration: {\n\t\t\t\tparentModelOid: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tanalyticalEngine: {\n\t\t\t\tqueryAeMode: string;\n\t\t\t\tcustomTranslationMode: string;\n\t\t\t\tgenerateDependenciesMode: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\t__typename: string;\n\t\t}>;\n\t};\n};\n\ntype GetElasticubeProps = {\n\tcubeOid: string;\n};\n\nexport type GetElasticubeResponse = {\n\telasticube: {\n\t\toid: string;\n\t\ttitle: string;\n\t\tserver: string;\n\t\ttenant: {\n\t\t\t_id: string;\n\t\t\tname: string;\n\t\t\tsystemManagement: boolean;\n\t\t};\n\t\tfiscal: string;\n\t\ttype: string;\n\t\trelationType: string;\n\t\tenableDimensionalModeling: boolean;\n\t\tlastSuccessfulManualBuildStartTime: string;\n\t\tlastBuildTime: string;\n\t\tlastPublishTime: string;\n\t\thasDatasetsWithoutConnectionParameters: boolean;\n\t\tdatasets: {\n\t\t\toid: string;\n\t\t\tname: string;\n\t\t\tdatabase: string;\n\t\t\tschemaName: string;\n\t\t\tlastUpdated: string;\n\t\t\ttype: string;\n\t\t\tliveQuerySettings: {\n\t\t\t\ttimeout: number;\n\t\t\t\tautoRefresh: boolean;\n\t\t\t\trefreshRate: number;\n\t\t\t\tresultLimit: number;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tconnection: {\n\t\t\t\tid: string;\n\t\t\t\toid: string;\n\t\t\t\tprovider: string;\n\t\t\t\tschema: string;\n\t\t\t\tfileName: string;\n\t\t\t\tparameters: string;\n\t\t\t\tprotectedParameters: string;\n\t\t\t\tglobalTableConfigOptions: string;\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\tschema: {\n\t\t\t\ttables: {\n\t\t\t\t\toid: string;\n\t\t\t\t\tid: string;\n\t\t\t\t\tname: string;\n\t\t\t\t\trole: string;\n\t\t\t\t\tisRoleBySystem: boolean;\n\t\t\t\t\tdescription: string;\n\t\t\t\t\ttype: string;\n\t\t\t\t\ttags: string[];\n\t\t\t\t\thidden: boolean;\n\t\t\t\t\tlastUpdated: string;\n\t\t\t\t\tconfigOptions: string;\n\t\t\t\t\tschemaName: string;\n\t\t\t\t\tisMaterialized: boolean;\n\t\t\t\t\tbuildBehavior: {\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\taccumulativeConfig: {\n\t\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\t\tcolumn: string;\n\t\t\t\t\t\t\tlastDays: number;\n\t\t\t\t\t\t\tkeepOnlyDays: number;\n\t\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\tcolumns: {\n\t\t\t\t\t\toid: string;\n\t\t\t\t\t\tid: string;\n\t\t\t\t\t\tname: string;\n\t\t\t\t\t\trole: string;\n\t\t\t\t\t\tisRoleBySystem: boolean;\n\t\t\t\t\t\tdescription: string;\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\tsize: number;\n\t\t\t\t\t\tprecision: number;\n\t\t\t\t\t\tscale: number;\n\t\t\t\t\t\thidden: boolean;\n\t\t\t\t\t\tindexed: boolean;\n\t\t\t\t\t\tisUpsertBy: boolean;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\texpression: {\n\t\t\t\t\t\toid: string;\n\t\t\t\t\t\tlastUpdated: string;\n\t\t\t\t\t\texpression: string;\n\t\t\t\t\t\tisDatabaseDialect: boolean;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\tcustomCode: {\n\t\t\t\t\t\tnoteBookId: string;\n\t\t\t\t\t\tdependsOn: string[];\n\t\t\t\t\t\tadditionalParameters: string;\n\t\t\t\t\t\tcodePath: string;\n\t\t\t\t\t\tcellsDisable: boolean;\n\t\t\t\t\t\tlanguage: string;\n\t\t\t\t\t\tmode: string;\n\t\t\t\t\t\tserverUrl: string;\n\t\t\t\t\t\ttimeout: number;\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\ttupleTransformations: {\n\t\t\t\t\t\ttype: string;\n\t\t\t\t\t\targuments: string[];\n\t\t\t\t\t\t__typename: string;\n\t\t\t\t\t};\n\t\t\t\t\t__typename: string;\n\t\t\t\t};\n\t\t\t\t__typename: string;\n\t\t\t};\n\t\t\t__typename: string;\n\t\t};\n\t\trelationsTables: {\n\t\t\tfirstTable: string;\n\t\t\tsecondTable: string;\n\t\t\tdirectionType: string;\n\t\t\tcondition: string;\n\t\t\t__typename: string;\n\t\t};\n\t\trelations: {\n\t\t\toid: string;\n\t\t\tcolumns: {\n\t\t\t\tdataset: string;\n\t\t\t\ttable: string;\n\t\t\t\tcolumn: string;\n\t\t\t\tisDropped: boolean;\n\t\t\t\t__typename: string;\n\t\t\t}[];\n\t\t\t__typename: string;\n\t\t};\n\t\texperiments: {\n\t\t\t__typename: string;\n\t\t}[];\n\t\tbuildDestination: {\n\t\t\tdestination: string;\n\t\t\tdatabase: string;\n\t\t\tschema: string;\n\t\t\t__typename: string;\n\t\t};\n\t\tmodelStatistics: {\n\t\t\tenableModelStatistics: boolean;\n\t\t\tallTablesPerCollection: boolean;\n\t\t\tmaxTablesPerCollection: number;\n\t\t\trecollectStatsInterval: number;\n\t\t\t__typename: string;\n\t\t};\n\t\t__typename: string;\n\t};\n};\n\ntype DeleteElasticubeProps = {\n\toid: string;\n\treplacementDataSource?: {\n\t\ttype: string;\n\t\toid: string;\n\t};\n};\n\ntype DeleteElasticubeResponse = {\n\tdata: {\n\t\tremoveElasticubeByOid: boolean;\n\t};\n};\n\ntype UploadCSVResponse = Array<{\n\tfilename: string;\n\textension: string;\n\tsize: number;\n\ttype: string;\n\tstorageInfo: {\n\t\tpath: string;\n\t};\n\tuploader: string;\n\tsource: string;\n\tcreatedAt: string;\n\ttenantId: string;\n\t_id: string;\n}>;\n\nexport async function createElasticube({ title }: CreateElasticubeProps) {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'createNewElasticube',\n\t\tvariables: {\n\t\t\ttitle,\n\t\t\ttype: 'extract',\n\t\t\trelationType: 'direct',\n\t\t\texperiments: {},\n\t\t\tbuildDestination: {\n\t\t\t\tdestination: 'elasticube',\n\t\t\t},\n\t\t},\n\t\tquery: 'mutation createNewElasticube($title: String!, $type: ElasticubeType, $relationType: RelationType, $experiments: ExperimentsInput, $buildDestination: BuildDestinationInput, $fiscal: String) {\\n newCube: createNewElasticube(\\n title: $title\\n type: $type\\n relationType: $relationType\\n experiments: $experiments\\n buildDestination: $buildDestination\\n fiscal: $fiscal\\n ) {\\n oid\\n title\\n server\\n type\\n relationType\\n lastBuildTime\\n lastUpdated\\n fiscal\\n creator {\\n id\\n firstName\\n lastName\\n __typename\\n }\\n shares {\\n partyId\\n type\\n ... on ShareUserInfo {\\n firstName\\n lastName\\n email\\n __typename\\n }\\n ... on ShareGroupInfo {\\n name\\n ad\\n objectSid\\n everyone\\n tenantEveryone\\n admins\\n __typename\\n }\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n buildDestination {\\n destination\\n __typename\\n }\\n __typename\\n }\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\tlet data: CreateElasticubeResponse | undefined;\n\ttry {\n\t\tdata = await httpClient.post<CreateElasticubeResponse>(\n\t\t\t`/api/v2/ecm/`,\n\t\t\tbody,\n\t\t);\n\t} catch (err: any) {\n\t\tconsole.error(err);\n\t\tthrow new Error(err.message);\n\t}\n\tif (data?.errors) {\n\t\tthrow new Error(data.errors[0].error.message);\n\t}\n\treturn data?.data?.newCube;\n}\n\nexport async function getCSVSchemaDetails({\n\tfilePath,\n\tfileName,\n}: GetCSVSchemaDetailsProps): Promise<GetCSVSchemaDetailsResponse | null> {\n\tconst body = {\n\t\tconnection: {\n\t\t\tApiVersion: 2,\n\t\t\tfiles: [filePath],\n\t\t\tdelimiter: ',',\n\t\t\thasHeader: true,\n\t\t\tignoreMissingColumns: false,\n\t\t\texcludeIfBegins: '',\n\t\t\texcludeIfContains: '',\n\t\t\tstringQuote: '\"',\n\t\t\tignoreFirstRows: '',\n\t\t\tculture: 'en-US',\n\t\t\tcolumnsDateTimePatterns: '{}',\n\t\t\tfileNames: [fileName],\n\t\t},\n\t\tschema: filePath,\n\t\ttable: filePath.split('/').pop(),\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<GetCSVSchemaDetailsResponse>(\n\t\t`/api/v1/live_connectors/CSV/table_schema_details`,\n\t\tbody,\n\t);\n\n\treturn response ?? null;\n}\n\nexport async function getPerspectiveOid({\n\telasticubeOid,\n}: GetPerspectiveOidProps): Promise<GetPerspectiveOidResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<GetPerspectiveOidResponse>(\n\t\t`/api/v2/perspectives/getPerspectiveElasticubesAndLatestRevisionsByOid?parentOid=${elasticubeOid}`,\n\t);\n\n\treturn response ?? null;\n}\n\nexport async function addDataSet({\n\telasticubeOid,\n\tfilePath,\n\tfileName,\n\ttable,\n\tperspectiveOid,\n}: AddDataSetProps) {\n\tconst tableId = filePath.split('/').pop();\n\tconst oid = tableId?.replace('.csv', '') || '';\n\tconst name = fileName.replace('.csv', '');\n\tconst { schemaName, columns } = table;\n\tconst dataColumns = columns.map((column: any) => ({\n\t\tname: column.columnName,\n\t\ttype: column.dbType,\n\t\toid: nanoidUUIDv4(),\n\t\tsize: column.size,\n\t\tprecision: column.precision,\n\t\tscale: column.scale,\n\t\thidden: false,\n\t\tindexed: true,\n\t\tid: column.columnName,\n\t}));\n\n\tconst body = {\n\t\toperationName: 'addDataset',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tconnection: {\n\t\t\t\tprovider: 'CSV',\n\t\t\t\tschema: filePath,\n\t\t\t\tparameters: {\n\t\t\t\t\tApiVersion: 2,\n\t\t\t\t\tfiles: [filePath],\n\t\t\t\t},\n\t\t\t\tuiParams: {},\n\t\t\t\tglobalTableConfigOptions: {\n\t\t\t\t\tdatesPicker: {},\n\t\t\t\t},\n\t\t\t\tfileName,\n\t\t\t},\n\t\t\ttables: [\n\t\t\t\t{\n\t\t\t\t\tid: tableId,\n\t\t\t\t\tname,\n\t\t\t\t\toid,\n\t\t\t\t\thidden: false,\n\t\t\t\t\tschemaName,\n\t\t\t\t\tbuildBehavior: {\n\t\t\t\t\t\ttype: 'sync',\n\t\t\t\t\t},\n\t\t\t\t\tcolumns: dataColumns,\n\t\t\t\t\tconfigOptions: {\n\t\t\t\t\t\tdelimiter: ',',\n\t\t\t\t\t\thasHeader: true,\n\t\t\t\t\t\tignoreMissingColumns: false,\n\t\t\t\t\t\texcludeIfBegins: '',\n\t\t\t\t\t\texcludeIfContains: '',\n\t\t\t\t\t\tstringQuote: '\"',\n\t\t\t\t\t\tignoreFirstRows: '',\n\t\t\t\t\t\tculture: 'en-US',\n\t\t\t\t\t\tcolumnsDateTimePatterns: '{}',\n\t\t\t\t\t},\n\t\t\t\t\ttupleTransformations: [],\n\t\t\t\t},\n\t\t\t],\n\t\t\tsuggestedOid: nanoidUUIDv4(),\n\t\t\tschemaName,\n\t\t\tperspectiveOid,\n\t\t\tupdatedPerspectiveData: {\n\t\t\t\trelationsTables: [],\n\t\t\t},\n\t\t},\n\t\tquery: `mutation addDataset($elasticubeOid: UUID!, $connection: ConnectionInput!, $tables: [TableInput!]!, $name: String, $suggestedOid: UUID!, $database: String, $schemaName: String, $perspectiveOid: UUID!, $updatedPerspectiveData: PerspectiveInput) {\n markTransactional(elasticubeOid: $elasticubeOid)\n dataset: addDatasetToElasticube(\n elasticubeOid: $elasticubeOid\n connection: $connection\n tables: $tables\n name: $name\n suggestedOid: $suggestedOid\n database: $database\n schemaName: $schemaName\n ) {\n oid\n connection {\n oid\n protectedParameters\n __typename\n }\n __typename\n }\n updatePerspective(\n perspectiveOid: $perspectiveOid\n updatedPerspectiveData: $updatedPerspectiveData\n )\n}`,\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst data = await httpClient.post<AddDataSetResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn { dataSet: data, columns: dataColumns, tableOid: oid };\n}\n\nexport async function buildElasticube({\n\telasticubeOid,\n}: BuildElasticubeProps): Promise<BuildElasticubeResponse | null> {\n\tconst body = {\n\t\toperationName: 'buildElasticube',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tbuildType: 'restart',\n\t\t},\n\t\tquery: 'mutation buildElasticube($elasticubeOid: UUID!, $buildType: ElasticubeBuildType, $buildRows: Int) {\\n buildElasticube(\\n elasticubeOid: $elasticubeOid\\n type: $buildType\\n rows: $buildRows\\n )\\n}\\n',\n\t};\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<BuildElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function buildStatus(): Promise<BuildStatusResponse[] | null> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<BuildStatusResponse[]>(\n\t\t`/api/v2/builds`,\n\t);\n\treturn response ?? null;\n}\n\nexport async function addRelation({\n\telasticubeOid,\n\tsource,\n\ttarget,\n}: AddRelationProps): Promise<AddRelationResponse | null> {\n\tconst body = {\n\t\toperationName: 'addRelation',\n\t\tvariables: {\n\t\t\telasticubeOid,\n\t\t\tsource,\n\t\t\ttarget,\n\t\t\tsuggestedOid: nanoidUUIDv4(),\n\t\t},\n\t\tquery: 'mutation addRelation($elasticubeOid: UUID!, $source: RelationReferenceInput!, $target: RelationReferenceInput!, $suggestedOid: UUID!) {\\n relation: addRelation(\\n elasticubeOid: $elasticubeOid\\n source: $source\\n target: $target\\n suggestedOid: $suggestedOid\\n ) {\\n oid\\n columns {\\n column\\n __typename\\n }\\n __typename\\n }\\n}\\n',\n\t};\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<AddRelationResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function getElasticubes() {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'elasticubesMetadata',\n\t\tvariables: { isViewMode: false },\n\t\tquery: 'query elasticubesMetadata($tenantFilter: String, $isViewMode: Boolean) {\\n elasticubesMetadata(tenantFilter: $tenantFilter, isViewMode: $isViewMode) {\\n ...ecMetaData\\n __typename\\n }\\n}\\n\\nfragment ecMetaData on ElasticubeMetadata {\\n oid\\n title\\n server\\n tenant {\\n _id\\n name\\n systemManagement\\n __typename\\n }\\n fiscal\\n serverId\\n hasDatasets\\n type\\n relationType\\n provider\\n importTime\\n hasDatasetsWithoutConnectionParameters\\n datasets {\\n oid\\n database\\n schemaName\\n connection {\\n id\\n __typename\\n }\\n __typename\\n }\\n set {\\n title\\n __typename\\n }\\n status\\n lastBuildTime\\n lastBuildStatus\\n lastSuccessfulBuildStartTime\\n lastSuccessfulManualBuildStartTime\\n lastSuccessfulBuildTime\\n lastPublishTime\\n lastUpdated\\n hasPendingChanges\\n nextBuildTime\\n creator {\\n id\\n firstName\\n lastName\\n __typename\\n }\\n sizeInMb\\n shares {\\n partyId\\n type\\n permission\\n ... on ShareUserInfo {\\n firstName\\n lastName\\n email\\n __typename\\n }\\n ... on ShareGroupInfo {\\n name\\n ad\\n objectSid\\n everyone\\n tenantEveryone\\n admins\\n __typename\\n }\\n __typename\\n }\\n buildDestination {\\n destination\\n database\\n schema\\n resultLimit\\n queryTimeout\\n __typename\\n }\\n modelStatistics {\\n enableModelStatistics\\n allTablesPerCollection\\n maxTablesPerCollection\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n acceleration {\\n parentModelOid\\n __typename\\n }\\n analyticalEngine {\\n queryAeMode\\n customTranslationMode\\n generateDependenciesMode\\n __typename\\n }\\n __typename\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\n\tconst response = await httpClient.post<GetElasticubesResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\tif (!response?.data?.elasticubesMetadata) {\n\t\tthrow new Error('Failed to get elasticubes list');\n\t}\n\treturn response.data.elasticubesMetadata;\n}\n\nexport async function getElasticube({\n\tcubeOid,\n}: GetElasticubeProps): Promise<GetElasticubeResponse | null> {\n\tconst httpClient = getHttpClient();\n\tconst body = {\n\t\toperationName: 'elasticubeByOid',\n\t\tvariables: { cubeOid },\n\t\tquery: 'query elasticubeByOid($cubeOid: UUID!) {\\n elasticube: elasticubeByOid(oid: $cubeOid) {\\n ...ecData\\n __typename\\n }\\n}\\n\\nfragment ecData on Elasticube {\\n oid\\n title\\n server\\n tenant {\\n _id\\n name\\n systemManagement\\n __typename\\n }\\n fiscal\\n type\\n relationType\\n enableDimensionalModeling\\n lastSuccessfulManualBuildStartTime\\n lastBuildTime\\n lastPublishTime\\n hasDatasetsWithoutConnectionParameters\\n datasets {\\n oid\\n name\\n database\\n schemaName\\n lastUpdated\\n type\\n liveQuerySettings {\\n timeout\\n autoRefresh\\n refreshRate\\n resultLimit\\n __typename\\n }\\n connection {\\n id\\n oid\\n provider\\n schema\\n fileName\\n parameters\\n protectedParameters\\n globalTableConfigOptions\\n __typename\\n }\\n schema {\\n tables {\\n oid\\n id\\n name\\n role\\n isRoleBySystem\\n description\\n type\\n tags\\n hidden\\n lastUpdated\\n configOptions\\n schemaName\\n isMaterialized\\n buildBehavior {\\n type\\n accumulativeConfig {\\n type\\n column\\n lastDays\\n keepOnlyDays\\n __typename\\n }\\n __typename\\n }\\n columns {\\n oid\\n id\\n name\\n role\\n isRoleBySystem\\n description\\n type\\n size\\n precision\\n scale\\n hidden\\n indexed\\n isUpsertBy\\n __typename\\n }\\n expression {\\n oid\\n lastUpdated\\n expression\\n isDatabaseDialect\\n __typename\\n }\\n customCode {\\n noteBookId\\n dependsOn\\n additionalParameters\\n codePath\\n cellsDisable\\n language\\n mode\\n serverUrl\\n timeout\\n __typename\\n }\\n tupleTransformations {\\n type\\n arguments\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n __typename\\n }\\n relationsTables {\\n firstTable\\n secondTable\\n directionType\\n condition\\n __typename\\n }\\n relations {\\n oid\\n columns {\\n dataset\\n table\\n column\\n isDropped\\n __typename\\n }\\n __typename\\n }\\n experiments {\\n ...experiments\\n __typename\\n }\\n buildDestination {\\n destination\\n database\\n schema\\n __typename\\n }\\n modelStatistics {\\n enableModelStatistics\\n allTablesPerCollection\\n maxTablesPerCollection\\n recollectStatsInterval\\n __typename\\n }\\n __typename\\n}\\n\\nfragment experiments on Experiments {\\n __typename\\n}\\n',\n\t};\n\n\tconst response = await httpClient.post<GetElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\treturn response ?? null;\n}\n\nexport async function deleteElasticube({\n\toid,\n\treplacementDataSource,\n}: DeleteElasticubeProps): Promise<boolean> {\n\tconst body = {\n\t\toperationName: 'removeElasticubeByOid',\n\t\tvariables: {\n\t\t\toid,\n\t\t\treplacementDataSource,\n\t\t},\n\t\tquery: 'mutation removeElasticubeByOid($oid: UUID!, $replacementDataSource: DataSourceInput) {\\n removeElasticubeByOid(oid: $oid, replacementDataSource: $replacementDataSource)\\n}\\n',\n\t};\n\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.post<DeleteElasticubeResponse>(\n\t\t`/api/v2/ecm/`,\n\t\tbody,\n\t);\n\tif (!response?.data) {\n\t\tthrow new Error('Failed to delete elasticube');\n\t}\n\treturn response.data.removeElasticubeByOid;\n}\n\nasync function validateFile(\n\tfileName: string,\n\tcsv: string,\n): Promise<{ file: File; fileToken: string }> {\n\tconst httpClient = getHttpClient();\n\tconst file = new File([csv], fileName, { type: 'text/csv' });\n\tconst payload = {\n\t\tfilename: fileName,\n\t\tsize: file.size,\n\t};\n\n\tconst response = await httpClient.post<{ token: string }>(\n\t\t'/storage/fs/validate_file',\n\t\tpayload,\n\t);\n\n\tif (!response?.token) {\n\t\tthrow new Error('Failed to get file validation token');\n\t}\n\n\treturn { file, fileToken: response.token };\n}\n\nexport async function uploadCSVMultipart(\n\tfileName: string,\n\tcsvContent: string,\n): Promise<UploadCSVResponse> {\n\tconst httpClient = getHttpClient();\n\tconst { fileToken, file } = await validateFile(fileName, csvContent);\n\n\tconst formData = new FormData();\n\tformData.append('file', file);\n\n\tconst headers: Record<string, string> = {\n\t\tAccept: 'application/json',\n\t\tInternal: 'true',\n\t\t'x-upload-token': fileToken,\n\t};\n\thttpClient.auth.applyHeaders(headers);\n\n\tconst response = await fetch(`${httpClient.url}/storage/fs/upload`, {\n\t\tmethod: 'POST',\n\t\theaders,\n\t\tbody: formData,\n\t\tcredentials: 'include',\n\t});\n\n\tif (!response.ok) {\n\t\tif (response.status === 403) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Sorry, file upload is not available for this instance as it's behind Cloudflare and we don't have a proper API for connection file upload\",\n\t\t\t);\n\t\t}\n\t\tthrow new Error('Failed to upload file');\n\t}\n\n\tconst data = await response.json();\n\treturn data;\n}\n","import { getHttpClient } from '@/singleton-clients';\n\nexport async function loadGlobals() {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get('api/globals');\n\treturn response;\n}\n","import { getHttpClient } from '@/singleton-clients';\n\nexport interface LlmSettings {\n\taiAssistant: {\n\t\tenabled: boolean;\n\t};\n\tllmServices: {\n\t\tenabled: boolean;\n\t};\n\tllmTerms: {\n\t\taccepted: boolean;\n\t};\n\tprovider: string;\n\tbaseUrl: string;\n\tmodel: string;\n\tapiKey?: string;\n}\n\nconst LLM_SETTINGS_API_URL_PATH = 'api/v2/settings/ai/llm';\n\nexport async function getLlmSettings(): Promise<LlmSettings> {\n\tconst httpClient = getHttpClient();\n\tconst response = await httpClient.get<LlmSettings>(\n\t\tLLM_SETTINGS_API_URL_PATH,\n\t);\n\tif (!response) {\n\t\tthrow new Error('Failed to load LLM settings');\n\t}\n\treturn response;\n}\n\nexport async function updateLlmSettings(\n\tsettings: LlmSettings,\n): Promise<LlmSettings> {\n\tconst httpClient = getHttpClient();\n\t// Include all required fields for the API\n\tconst apiPayload = {\n\t\tprovider: settings.provider,\n\t\tmodel: settings.model,\n\t\tbaseUrl: settings.baseUrl,\n\t\tapiKey: settings.apiKey || 'dummy-api-key', // API requires this field\n\t\tllmTerms: settings.llmTerms,\n\t\tllmServices: settings.llmServices,\n\t\taiAssistant: settings.aiAssistant,\n\t};\n\n\ttry {\n\t\t// The API returns an empty array on success\n\t\tawait httpClient.post<any>(LLM_SETTINGS_API_URL_PATH, apiPayload);\n\n\t\t// Since the API doesn't return the settings object, return the original settings\n\t\t// This will likely need to be refreshed to get the actual state from the server\n\t\treturn settings;\n\t} catch (error) {\n\t\tconsole.error('Error updating LLM settings:', error);\n\t\tthrow error;\n\t}\n}\n"],"names":["ignoreOverride","defaultOptions","getDefaultOptions","options","getRefs","_options","currentPath","name","def","addErrorMessage","res","key","errorMessage","refs","setResponseValueAndErrors","value","getRelativePath","pathA","pathB","i","ZodFirstPartyTypeKind","parseAnyDef","anyDefinitionPath","parseArrayDef","_a","_c","_b","parseDef","parseBigintDef","check","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","overrideDateStrategy","strategy","item","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","type","parseIntersectionDef","allOf","x","unevaluatedProperties","mergedAllOf","schema","nestedSchema","additionalProperties","rest","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","addFormat","addPattern","escapeLiteralCheckValue","literal","escapeNonAlphaNumeric","ALPHA_NUMERIC","source","result","message","regex","stringifyRegExpWithFlags","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","acc","keyType","_d","_e","_f","parseMapDef","keys","values","parseNativeEnumDef","object","actualValues","parsedTypes","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","asAnyOf","types","uniqueTypes","a","anyOf","parseNullableDef","base","parseNumberDef","parseObjectDef","forceOptionalIntoNullable","required","shape","propName","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","b","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","_","forceResolution","seenItem","overrideResult","seenSchema","get$ref","newItem","jsonSchemaOrGetter","jsonSchema","addMeta","postProcessResult","index","zodToJsonSchema","definitions","main","combined","indent","n","hasKeptProperties","propertiesToKeep","unwrapped","z","opt","processSchemaProperties","propertyNames","mode","processedElement","processedOptions","filteredEntries","processedValue","filteredShape","filterSchemaProperties","excludeSchemaProperties","propertiesToExclude","zodToReadableType","depth","isOptional","k","v","o","zodFunction","fn","description","strict","args","context","input","obj","cartesianChartType","categoricalChartType","otherChartType","chartType","cartesianChartSchema","categoricalChartSchema","scatterChartSchema","tableChartSchema","rangeChartSchema","indicatorChartSchema","boxplotChartSchema","areamapChartSchema","scattermapChartSchema","axesMapping","nullableChartType","chartIdSchema","chartRecommendationsSchema","buildChartSchema","baseChartSchema","createChartSchema","updateChartSchema","updateChartTitleSchema","updateChartTypeSchema","updateChartTypeOfMeasuresSchema","updateChartSortingSchema","updateTrendAndForecastSchema","updateOtherChartDataOptionsSchema","updateChartStyleOptionsSchema","random","bytes","customRandom","alphabet","defaultSize","getRandom","mask","step","size","id","j","customAlphabet","nanoidHex","nanoidUUIDv4","makeParseableResponseFormat","response_format","parser","zodDef","zodSchema","isEmptyObj","_k","processPattern","c","processRegExp","regexOrFunction","regexTest","propertyPath","title","processedDefinitions","newDefinitions","_zodToJsonSchema","zodResponseFormat","zodObject","props","content","normalizeUrl","url","parseError","error","getTenantPrefix","urlHost","tenantDomainNames","tenantName","dnsUrl","USER_ACTION_ID_HEADER","TRACEPARENT_HEADER","generateUserActionId","generateTraceparent","traceId","spanId","UserActionContext","userActionContext","startUserAction","getUserActionHeaders","DEFAULT_HTTP_CLIENT_HEADERS","normalizeHeaders","headers","withTrackingHeaders","trackingHeaders","normalizedHeaders","endUserAction","createHttpClientFromAuthenticator","authenticator","tenantPrefix","httpClientInstance","HttpClient","createHttpClientFromConfig","config","getAuthenticator","ALLOWED_TRACKING_HEADERS","createCustomFetch","httpClient","init","isBearerAuth","lowerKey","newInit","OPENAI_API_URL_PATH","createOpenAIClientHelper","baseURL","fetchFn","OpenAI","createOpenAIClient","initializeHttpClient","getHttpClient","resetHttpClient","currentHttpClient","openAIClientInstance","initializeOpenAIClient","openAIClient","getOpenAIClient","resetOpenAIClient","initializeClients","authConfig","createStructuredCompletion","params","systemPrompt","userPrompt","responseFormat","model","temperature","sessionId","openAiResponseFormat","toolCall","parsedResponse","createToolsCompletion","tools","toolChoice","resolve","toolMessages","assistantMessages","isError","combinedMessage","toolMessagesText","assistantMessagesText","err","mapColumnIndicesToObjects","indices","columns","column","mapChartDataToColumns","recommendations","mapping","generateChartRecommendations","cols","prompt","updatedRecommendations","getNlqResult","contextTitle","request","getNlqResultLight","getNlqV3Result","getQueryRecommendations","getQueryRecommendationsLight","generateChartTableFromNlqV2","dataSourceTitle","nlqResult","widgetProps","widgetComposer","isChartWidgetProps","generateChartTableFromNlqV3","dataSchema","translationResult","translateQueryJSON","translatedParams","jaql","translateQueryToJaql","convertDataSource","generateChartTable","isNlqV3Enabled","generateChart","chartTitle","dataColumns","chartRecommendations","newChartType","baseStyleOptions","getChartStyleOptions","createChart","chartId","chartWidgetProps","updateChartTitleHelper","updateChartTitle","updatedChartWidgetProps","updateChartTypeHelper","existingStyleOptions","styleOptions","updateChartType","LineWidthSchema","LineSubtypeSchema","LegendSchema","SeriesLabelsSchema","AxisLabel","XAxisSchema","YAxisSchema","Y2AxisSchema","MarkersSchema","NavigatorSchema","DataLimitsSchema","LineChartStyleSchema","BarChartStyleSchema","ConvolutionSchema","PieChartStyleSchema","ScatterChartStyleSchema","AreaChartStyleSchema","FunnelChartStyleSchema","TreemapChartStyleSchema","SunburstChartStyleSchema","BoxplotChartStyleSchema","IndicatorChartStyleSchema","PolarChartStyleSchema","TableChartStyleSchema","chartStyleSchemas","getChartStyleOptionsSchema","styleSchema","PartialColumnSchema","ColorStringSchema","NumberFormatConfigSchema","trendFormulaOptions","forecastFormulaOptions","dataOptionsEditingSchemas","cartesianDataOptionsEditingSchemas","categoricalDataOptionsEditingSchemas","scatterChartDataOptionsEditingSchemas","indicatorDataOptionsEditingSchemas","boxplotDataOptionsEditingSchemas","scattermapDataOptionsEditingSchemas","areamapDataOptionsEditingSchemas","calendarHeatmapDataOptionsEditingSchemas","tableDataOptionsEditingSchemas","getChartDataOptionsEditingSchemas","chartDataOptionsSchemas","updateChartDataOptionsHelper","currentDataOptions","currentChartType","baseSchema","responseDataOptions","mergedDataOptions","mergeDataOptions","original","aiResponse","merged","dataOptionsKey","incomingList","originalList","originalItem","originalName","updatedItem","updateChartDataOptions","isMergeableObject","isNonNullObject","isSpecial","stringValue","isReactElement","canUseSymbol","REACT_ELEMENT_TYPE","emptyTarget","val","cloneUnlessOtherwiseSpecified","deepmerge","defaultArrayMerge","target","element","getMergeFunction","customMerge","getEnumerableOwnPropertySymbols","symbol","getKeys","propertyIsOnObject","property","propertyIsUnsafe","mergeObject","destination","sourceIsArray","targetIsArray","sourceAndTargetTypesMatch","array","prev","next","deepmerge_1","cjs","updateChartStyleOptionsHelper","currentStyleOptions","targetSchema","responseStyleOptions","mergedStyleOptions","updateChartStyleOptions","TOOL_NAME_CHART_BUILDER","TOOL_NAME_DASHBOARD_BUILDER","TOOL_NAME_DATA_MODEL_BUILDER","TOOL_NAME_RECOMMEND_QUERIES","TOOL_NAME_GET_DASHBOARDS","TOOL_NAME_GET_DATA_SOURCES","TOOL_NAME_GET_DATA_SOURCE_FIELDS","TOOL_CONTEXT_MAX_ASSETS","getBaseChartSummary","createChartTool","originalSchema","originalFunction","boundContext","createChartTools","buildContextualSystemPrompt","chartSummaries","buildChartEngine","newChartId","savedChartWidgetProps","updatedContext","internalTools","isErrorInToolsCompletion","DATA_MODELS_API_URL_PATH","getDataSourceSchema","dataSourceName","client","DATA_SOURCES_API_URL_PATH","addDescriptionToFields","fields","datasets","schemaDataDescriptionsMap","map","dataset","table","field","getDataSources","getDataSourceByTitle","getDataSourceFields","getDataSourceFieldsWithDescriptions","dataSourceSchema","status","normalizeFields","normalizedFields","normalizedName","normalizeName","baseField","DateLevels","level","getNormalizedDataSourceFields","getFieldsFn","getDataSourcesEngine","dataSources","ds","getDataSourcesSchema","getDataSourceFieldsEngine","getDataSourceFieldsSchema","FUSION_DASHBOARDS_API_URL_PATH","getFusionDashboardUrl","dashboardOid","getFusionDashboards","expand","searchByTitle","queryParams","dashboards","getFusionDashboardWidgets","getFusionDashboardModel","getDashboardModel","patchFusionDashboard","dashboard","addWidgetToFusionDashboard","widgetDto","createEmptyFusionDashboard","dashboardTitle","dataSource","deleteFusionDashboard","deleteWidgetFromFusionDashboard","widgetOid","translateToLayoutDto","layout","r","cell","getAvailableFusionDashboards","getFusionDashboardProps","dashboardModel","dashboardModelTranslator","loadExistingDashboardFromFusion","dashboardId","fusionDashboardProps","addWidgetsToFusionDashboard","widgetsToAdd","widgetPromises","widgetModel","widgetModelTranslator","convertJaqlDataSourceForDto","dto","updateFusionDashboardFilters","filtersToUpdate","filtersDto","translateFiltersAndRelationsToDto","isDashboardSaved","dashboardProps","persistDashboardToFusion","isDataSourceInfo","jaqlDataSource","existingWidgetDtos","fusionDashboardDto","updatedDashboardProps","updatedWidgetDtos","updatedWidgets","widget","updatedWidgetsLayout","row","w","fastDeepEqual","equal","length","extractWidgetIdsFromLayout","cleanupOrphanedCells","existingWidgetIds","cleanedColumns","adjustSingleColumnWidth","findOutOfPlaceWidgets","widgets","widgetsInLayout","cleanupDashboardAfterChange","updatedProps","outOfPlaceWidgetIds","deleteWidgetsFromDashboard","cleanedLayout","handleFiltersUpdate","filters","handleFiltersPanelCollapse","collapsed","handleWidgetsPanelLayoutUpdate","deepEq","handleWidgetsDelete","widgetIds","handleWidgetsPanelLayoutIsEditingChange","isEditing","getDashboardDataSourcesMap","dataSourcesMap","defaultDataSource","layoutDashboardWidgets","widgetOids","withWidgetAdded","widgetId","newRow","minRows","minIndex","getBaseDashboardConfig","getBaseDashboardProps","createEmptyDashboard","resetWidgetForDashboard","addWidgetsToDashboard","updateDashboardWidgetsLayout","newWidgetIds","currentWidgetsLayout","widgetsLayout","updateDashboardTitle","createNewDashboard","addWidgetsToExistingDashboard","handleChange","event","changeDashboard","changed","createElasticube","body","data","getCSVSchemaDetails","filePath","fileName","getPerspectiveOid","elasticubeOid","addDataSet","perspectiveOid","tableId","oid","schemaName","buildElasticube","buildStatus","addRelation","getElasticubes","response","getElasticube","cubeOid","deleteElasticube","replacementDataSource","validateFile","csv","file","payload","uploadCSVMultipart","csvContent","fileToken","formData","loadGlobals","LLM_SETTINGS_API_URL_PATH","getLlmSettings","updateLlmSettings","settings","apiPayload"],"mappings":";;;;;;AAAO,MAAMA,KAAiB,OAAO,mDAAmD,GAa3EC,KAAiB;AAAA,EAC1B,MAAM;AAAA,EACN,cAAc;AAAA,EACd,UAAU,CAAC,GAAG;AAAA,EACd,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,0BAA0B;AAAA,EAC1B,6BAA6B;AAAA,EAC7B,8BAA8B;AAAA,EAC9B,gBAAgB;AAAA,EAChB,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,aAAa,CAAA;AAAA,EACb,eAAe;AAAA,EACf,qBAAqB;AAAA,EACrB,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,mBAAmB;AACvB,GACaC,KAAoB,CAACC,OAK5B;AAAA,EACE,GAAGF;AAAAA,EACH,GAAGE;AACX,IC5CaC,KAAU,CAACD,MAAY;AAChC,QAAME,IAAWH,GAAkBC,CAAO,GACpCG,IAAcD,EAAS,SAAS,SAChC,CAAC,GAAGA,EAAS,UAAUA,EAAS,gBAAgBA,EAAS,IAAI,IAC7DA,EAAS;AACf,SAAO;AAAA,IACH,GAAGA;AAAA,IACH,OAAO,EAAE,4BAA4B,GAAK;AAAA,IAC1C,aAAaC;AAAA,IACb,cAAc;AAAA,IACd,MAAM,IAAI,IAAI,OAAO,QAAQD,EAAS,WAAW,EAAE,IAAI,CAAC,CAACE,GAAMC,CAAG,MAAM;AAAA,MACpEA,EAAI;AAAA,MACJ;AAAA,QACI,KAAKA,EAAI;AAAA,QACT,MAAM,CAAC,GAAGH,EAAS,UAAUA,EAAS,gBAAgBE,CAAI;AAAA;AAAA,QAE1D,YAAY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,CAAO;AAEpC,QAAMuY,IAAW,MAAM,MAAM,GAAGxX,EAAW,GAAG,sBAAsB;AAAA,IACnE,QAAQ;AAAA,IACR,SAAAf;AAAA,IACA,MAAMmZ;AAAA,IACN,aAAa;AAAA,EAAA,CACb;AAED,MAAI,CAACZ,EAAS;AACb,UAAIA,EAAS,WAAW,MACjB,IAAI;AAAA,MACT;AAAA,IAAA,IAGI,IAAI,MAAM,uBAAuB;AAIxC,SADa,MAAMA,EAAS,KAAA;AAE7B;ACzwBA,eAAsBa,KAAc;AAGnC,SADiB,MADEzX,EAAA,EACe,IAAI,aAAa;AAEpD;ACYA,MAAM0X,KAA4B;AAElC,eAAsBC,KAAuC;AAE5D,QAAMf,IAAW,MADE5W,EAAA,EACe;AAAA,IACjC0X;AAAA,EAAA;AAED,MAAI,CAACd;AACJ,UAAM,IAAI,MAAM,6BAA6B;AAE9C,SAAOA;AACR;AAEA,eAAsBgB,GACrBC,GACuB;AACvB,QAAMzY,IAAaY,EAAA,GAEb8X,IAAa;AAAA,IAClB,UAAUD,EAAS;AAAA,IACnB,OAAOA,EAAS;AAAA,IAChB,SAASA,EAAS;AAAA,IAClB,QAAQA,EAAS,UAAU;AAAA;AAAA,IAC3B,UAAUA,EAAS;AAAA,IACnB,aAAaA,EAAS;AAAA,IACtB,aAAaA,EAAS;AAAA,EAAA;AAGvB,MAAI;AAEH,iBAAMzY,EAAW,KAAUsY,IAA2BI,CAAU,GAIzDD;AAAA,EACR,SAAS1a,GAAO;AACf,kBAAQ,MAAM,gCAAgCA,CAAK,GAC7CA;AAAA,EACP;AACD;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,95,107]}
|