@sisense/sdk-ai-core 0.5.0 → 0.6.0

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.
Files changed (37) hide show
  1. package/dist/constants.d.ts +7 -0
  2. package/dist/constants.d.ts.map +1 -1
  3. package/dist/engines/build-query/build-query-engine.d.ts +11 -0
  4. package/dist/engines/build-query/build-query-engine.d.ts.map +1 -0
  5. package/dist/engines/build-query/index.d.ts +3 -0
  6. package/dist/engines/build-query/index.d.ts.map +1 -0
  7. package/dist/engines/build-query/types.d.ts +34 -0
  8. package/dist/engines/build-query/types.d.ts.map +1 -0
  9. package/dist/engines/chart-builder/chart-builder-engine.d.ts +4 -3
  10. package/dist/engines/chart-builder/chart-builder-engine.d.ts.map +1 -1
  11. package/dist/engines/chart-builder/create-chart/create-chart.d.ts +3 -2
  12. package/dist/engines/chart-builder/create-chart/create-chart.d.ts.map +1 -1
  13. package/dist/engines/chart-builder/create-chart/generate-chart-table.d.ts +2 -1
  14. package/dist/engines/chart-builder/create-chart/generate-chart-table.d.ts.map +1 -1
  15. package/dist/engines/chart-builder/types.d.ts +46 -18
  16. package/dist/engines/chart-builder/types.d.ts.map +1 -1
  17. package/dist/engines/chart-builder/update-chart/chart-options-schemas.d.ts +218 -218
  18. package/dist/engines/chart-builder/update-chart/schemas.d.ts +24 -24
  19. package/dist/engines/data-source-fields/data-source-fields-engine.d.ts +7 -6
  20. package/dist/engines/data-source-fields/data-source-fields-engine.d.ts.map +1 -1
  21. package/dist/engines/data-source-fields/types.d.ts +1 -43
  22. package/dist/engines/data-source-fields/types.d.ts.map +1 -1
  23. package/dist/engines/index.d.ts +1 -0
  24. package/dist/engines/index.d.ts.map +1 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4606 -2136
  28. package/dist/index.js.map +1 -1
  29. package/dist/services/llm/llm-consumption-service.d.ts +17 -0
  30. package/dist/services/llm/llm-consumption-service.d.ts.map +1 -0
  31. package/dist/utils/create-custom-fetch.d.ts +10 -0
  32. package/dist/utils/create-custom-fetch.d.ts.map +1 -0
  33. package/dist/utils/http-client.d.ts +2 -5
  34. package/dist/utils/http-client.d.ts.map +1 -1
  35. package/dist/utils/user-action-tracking.d.ts +17 -26
  36. package/dist/utils/user-action-tracking.d.ts.map +1 -1
  37. package/package.json +2 -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/user-action-tracking.ts","../src/utils/http-client.ts","../src/utils/openai-client.ts","../src/singleton-clients.ts","../src/constants.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/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","../src/engines/dashboards/dashboards-engine.ts","../src/engines/dashboards/types.ts","../src/engines/dashboard-builder/types.ts","../node_modules/fast-deep-equal/index.js","../src/services/dashboards/dashboards-service.ts","../src/engines/dashboard-builder/create-dashboard.ts","../src/engines/dashboard-builder/load-existing-fusion-dashboard.ts","../src/engines/dashboard-builder/update-dashboard.ts","../src/engines/dashboard-builder/add-dashboard-widgets.ts","../src/engines/dashboard-builder/dashboard-filters/filter-factory-types.ts","../src/engines/dashboard-builder/dashboard-filters/measure-factory-types.ts","../src/engines/dashboard-builder/dashboard-filters/dashboard-filters-system-prompt.ts","../src/engines/dashboard-builder/dashboard-filters/translate-filters.ts","../src/engines/dashboard-builder/dashboard-filters/manipulate-dashboard-filters.ts","../src/engines/dashboard-builder/add-dashboard-filters.ts","../src/engines/dashboard-builder/create-chart-widget.ts","../src/engines/dashboard-builder/update-chart-widget.ts","../src/engines/dashboard-builder/dashboard-builder-service.ts","../src/engines/dashboard-builder/dashboard-builder-engine.ts","../src/engines/recommend-queries/types.ts","../src/engines/recommend-queries/recommend-queries-engine.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-9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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\tlet typeName = unwrapped?._def?.typeName;\n\twhile (typeName === 'ZodOptional' || typeName === 'ZodNullable') {\n\t\tunwrapped = (\n\t\t\tunwrapped as z.ZodOptional<any> | z.ZodNullable<any>\n\t\t).unwrap();\n\t\ttypeName = unwrapped?._def?.typeName;\n\t}\n\n\t// Check arrays - recurse into element type\n\tif (typeName === 'ZodArray') {\n\t\treturn hasKeptProperties(\n\t\t\t(unwrapped as z.ZodArray<any>).element,\n\t\t\tpropertiesToKeep,\n\t\t);\n\t}\n\n\t// Check unions - any option has kept properties\n\tif (typeName === 'ZodUnion') {\n\t\treturn (unwrapped as z.ZodUnion<any>).options.some(\n\t\t\t(opt: z.ZodTypeAny) => hasKeptProperties(opt, propertiesToKeep),\n\t\t);\n\t}\n\n\t// Check objects - any property name matches or descendants match\n\tif (typeName === 'ZodObject') {\n\t\tfor (const [key, value] of Object.entries(\n\t\t\t(unwrapped as z.ZodObject<any>).shape,\n\t\t)) {\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\tconst typeName = schema?._def?.typeName;\n\n\t// Handle optionals - recurse and rewrap\n\tif (typeName === 'ZodOptional') {\n\t\treturn z.ZodOptional.create(\n\t\t\tprocessSchemaProperties(\n\t\t\t\t(schema as z.ZodOptional<any>).unwrap(),\n\t\t\t\tpropertyNames,\n\t\t\t\tmode,\n\t\t\t),\n\t\t);\n\t}\n\n\t// Handle nullables - recurse and rewrap\n\tif (typeName === 'ZodNullable') {\n\t\treturn z.ZodNullable.create(\n\t\t\tprocessSchemaProperties(\n\t\t\t\t(schema as z.ZodNullable<any>).unwrap(),\n\t\t\t\tpropertyNames,\n\t\t\t\tmode,\n\t\t\t),\n\t\t);\n\t}\n\n\t// Handle arrays - recurse into element type\n\tif (typeName === 'ZodArray') {\n\t\tconst processedElement = processSchemaProperties(\n\t\t\t(schema as z.ZodArray<any>).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 (typeName === 'ZodUnion') {\n\t\tconst processedOptions = (schema as z.ZodUnion<any>).options.map(\n\t\t\t(opt: z.ZodTypeAny) =>\n\t\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 (typeName === 'ZodObject') {\n\t\tconst filteredEntries: [string, z.ZodTypeAny][] = [];\n\n\t\tfor (const [key, value] of Object.entries(\n\t\t\t(schema as z.ZodObject<any>).shape,\n\t\t)) {\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 * Uses _def.typeName instead of instanceof because instanceof is unreliable\n * for classes extending built-ins (like Error, Array) when code is downleveled to ES5.\n * See: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n */\nexport const zodToReadableType = (\n\tschema: z.ZodTypeAny,\n\tdepth = 0,\n\tpropName?: string,\n\tisOptional?: boolean,\n): string => {\n\tconst typeName = schema?._def?.typeName;\n\n\t// Optionals\n\tif (typeName === 'ZodOptional') {\n\t\treturn zodToReadableType(\n\t\t\t(schema as z.ZodOptional<any>).unwrap(),\n\t\t\tdepth,\n\t\t\tpropName,\n\t\t\ttrue,\n\t\t);\n\t}\n\t// Nullables\n\tif (typeName === 'ZodNullable') {\n\t\treturn (\n\t\t\tzodToReadableType(\n\t\t\t\t(schema as z.ZodNullable<any>).unwrap(),\n\t\t\t\tdepth,\n\t\t\t\tpropName,\n\t\t\t\tisOptional,\n\t\t\t) + ' | null'\n\t\t);\n\t}\n\t// Array\n\tif (typeName === 'ZodArray') {\n\t\tconst inner = zodToReadableType(\n\t\t\t(schema as z.ZodArray<any>).element,\n\t\t\tdepth,\n\t\t);\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 (typeName === 'ZodObject') {\n\t\tconst props = Object.entries((schema as z.ZodObject<any>).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 (typeName === 'ZodEnum') {\n\t\tconst opts = (schema as z.ZodEnum<any>).options\n\t\t\t.map((o: string) => `\"${o}\"`)\n\t\t\t.join(' | ');\n\t\treturn opts + (schema.description ? ` - ${schema.description}` : '');\n\t}\n\t// Union\n\tif (typeName === 'ZodUnion') {\n\t\treturn (schema as z.ZodUnion<any>).options\n\t\t\t.map((opt: z.ZodTypeAny) => zodToReadableType(opt, depth))\n\t\t\t.join(' | ');\n\t}\n\t// Literal\n\tif (typeName === 'ZodLiteral') {\n\t\treturn JSON.stringify((schema as z.ZodLiteral<any>).value);\n\t}\n\t// String, Number, Boolean\n\tif (typeName === 'ZodString') return 'string';\n\tif (typeName === 'ZodNumber') return 'number';\n\tif (typeName === '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. Pass the user prompt exactly as received - do NOT transform or modify it. The chart builder logic will handle prompt splitting internally.\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 = z.object({\n\tqueryPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Data-focused query prompt for retrieving data. Be faithful to the original user prompt but remove chart-specific instructions (e.g., \"bar chart\", \"use X as dimension\"). Focus on the data intent - the system will extract specific dimensions, measures, and filters automatically.',\n\t\t),\n\tchartPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Visualization-focused prompt for chart recommendations. Be faithful to the original user prompt and keep chart-specific instructions. Do not infer the chart type from the user prompt.',\n\t\t),\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 (required)\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","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\n// Limit the number of fields in data source fields summary to prevent token overflow\nexport const MAX_DATA_SOURCE_FIELDS_SUMMARY = 200;\n\n// This is a placeholder for the backend to override with the actual model to use\nexport const DEFAULT_LLM = 'LLM_PLACEHOLDER';\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';\nimport { DEFAULT_LLM } from '@/constants';\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 = DEFAULT_LLM,\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 = DEFAULT_LLM,\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\tconst mapping = updatedRecommendations.axesMapping as any;\n\t\t\tif (mapping.value && mapping.value.length > 1) {\n\t\t\t\tmapping.value = [mapping.value[0]];\n\t\t\t}\n\t\t\tif (mapping.secondary && mapping.secondary.length > 1) {\n\t\t\t\tmapping.secondary = [mapping.secondary[0]];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\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\tqueryPrompt: string,\n\thttpClient?: HttpClient,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst nlqResult = await getNlqResultLight(\n\t\tdataSourceTitle,\n\t\t{\n\t\t\ttext: queryPrompt,\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 || queryPrompt;\n\n\treturn widgetProps;\n};\n\nconst generateChartTableFromNlqV3 = async (\n\tdataSourceTitle: string,\n\tqueryPrompt: 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: queryPrompt,\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: queryPrompt,\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: queryPrompt,\n\t\t\t\tnlqPrompt: queryPrompt,\n\t\t\t\tuserMsg: queryPrompt,\n\t\t\t\tqueryTitle: queryPrompt,\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\tqueryPrompt,\n\t\t\thttpClient,\n\t\t);\n\t}\n};\n\nexport const generateChartTable = async (\n\tdataSourceTitle: string,\n\tqueryPrompt: string,\n\tisNlqV3Enabled?: boolean,\n\thttpClient?: HttpClient,\n) => {\n\tif (isNlqV3Enabled) {\n\t\tconsole.debug(\n\t\t\t'Generating chart table from NLQ V3',\n\t\t\tqueryPrompt,\n\t\t\tdataSourceTitle,\n\t\t);\n\t\treturn generateChartTableFromNlqV3(\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\n\t\t\thttpClient,\n\t\t);\n\t} else {\n\t\tconsole.debug(\n\t\t\t'Generating chart table from NLQ V2',\n\t\t\tqueryPrompt,\n\t\t\tdataSourceTitle,\n\t\t);\n\t\treturn generateChartTableFromNlqV2(\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\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\tqueryPrompt: string;\n\tchartPrompt: string;\n\tchartType: NullableChartType;\n\tchartTitle: string;\n};\n\nexport const generateChart = async (\n\t{\n\t\tdataSourceTitle,\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t}: GenerateChartParams,\n\tcontext: BuildChartContext,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst widgetProps = await generateChartTable(\n\t\tdataSourceTitle,\n\t\tqueryPrompt,\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\tchartPrompt,\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{\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t}: z.infer<typeof createChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createChart',\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t);\n\tconst dataSourceTitle = context.dataSourceTitle;\n\tconst chartId = context.toolCallId;\n\tconst chartWidgetProps = await generateChart(\n\t\t{\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\n\t\t\tchartPrompt,\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\tvalue: z.array(dataOptionsEditingSchemas.measures),\n\tcategory: 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\tvalue: z.array(dataOptionsEditingSchemas.measures),\n\tcategory: 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});\nexport const scatterChartDataOptionsEditingSchemas = z.object({\n\ty: dataOptionsEditingSchemas.measures,\n\tx: dataOptionsEditingSchemas.measures,\n\tbreakByColor: dataOptionsEditingSchemas.measures,\n\tbreakByPoint: dataOptionsEditingSchemas.dimensions,\n\tsize: dataOptionsEditingSchemas.measures,\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 indicatorDataOptionsEditingSchemas = z.object({\n\tmin: z.array(dataOptionsEditingSchemas.measures),\n\tmax: z.array(dataOptionsEditingSchemas.measures),\n\tsecondary: z.array(dataOptionsEditingSchemas.measures),\n\tvalue: z.array(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: cartesianDataOptionsEditingSchemas,\n\tarea: cartesianDataOptionsEditingSchemas,\n\tcolumn: cartesianDataOptionsEditingSchemas, // 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 {\n\tzodToReadableType,\n\tfilterSchemaProperties,\n\texcludeSchemaProperties,\n} 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\tsystemPrompt: string;\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Builds a system prompt for chart data options editing.\n * @param chartWidgetProps - The chart widget props containing current data options\n * @param filteredSchema - The filtered schema for the specific subtool\n * @param additionalInstructions - Optional additional instructions to append to the prompt\n * @returns The complete system prompt string\n */\nexport const buildSystemPromptForDataOptions = (\n\tchartWidgetProps: ExtendedChartWidgetProps,\n\tfilteredSchema: z.ZodTypeAny,\n\tadditionalInstructions?: string,\n): string => {\n\tconst { dataOptions: currentDataOptions } = chartWidgetProps;\n\n\t// Ensure we have a ZodObject to access shape property\n\tif (filteredSchema?._def?.typeName !== 'ZodObject') {\n\t\tthrow new Error(\n\t\t\t'Expected filteredSchema to be a ZodObject, but got a different type',\n\t\t);\n\t}\n\tconst schema = filteredSchema as z.ZodObject<any>;\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart data options properties are as follows:\n\n\t\tdataOptions: {\n\t\t\t${Object.entries(schema.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 ('value', 'category', 'breakBy', etc.) to maintain identity.\n \n Do not include unchanged fields.\n ${\n\t\t\t\tadditionalInstructions\n\t\t\t\t\t? `\\n ${additionalInstructions}`\n\t\t\t\t\t: ''\n\t\t\t}\n \n Example:\n \n User: \"Sort brands by total 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\treturn systemPrompt;\n};\n\n/**\n * Updates chart data options based on the user's prompt.\n * @param systemPrompt - The system prompt to use for the LLM completion.\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\tsystemPrompt,\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartDataOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { chartType: currentChartType } = chartWidgetProps;\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 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\tsystemPrompt: string,\n\tcontext: BuildChartContext,\n) => {\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\tsystemPrompt,\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\n/**\n * Configuration for data options update tools.\n */\ntype DataOptionsToolConfig = {\n\ttoolName: string;\n\tbuildSystemPrompt: (chartWidgetProps: ExtendedChartWidgetProps) => string;\n};\n\n/**\n * Factory function to create update chart data options tools.\n * Encapsulates common logic (chart retrieval, validation, calling updateChartDataOptions)\n * while allowing each tool to customize its system prompt generation.\n */\nconst createUpdateChartDataOptionsTool = (config: DataOptionsToolConfig) => {\n\treturn async (\n\t\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\t\tcontext: BuildChartContext,\n\t) => {\n\t\tconsole.debug('toolCall', config.toolName, chartId, userPrompt);\n\t\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\t\tif (!chartWidgetProps) {\n\t\t\tthrow new Error(`Chart not found`);\n\t\t}\n\n\t\tconst systemPrompt = config.buildSystemPrompt(chartWidgetProps);\n\t\treturn updateChartDataOptions(\n\t\t\t{ chartId, userPrompt },\n\t\t\tsystemPrompt,\n\t\t\tcontext,\n\t\t);\n\t};\n};\n\n// Tool configurations\nconst updateChartTypeOfMeasuresConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateChartTypeOfMeasures',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'chartType',\n\t\t]);\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t);\n\t},\n};\n\nconst updateChartSortingConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateChartSorting',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'sortType',\n\t\t]);\n\t\tconst additionalInstructions = `IMPORTANT: When setting sortType on a column within dataOptions, if sortType exists on any other column, set it to null to ensure only one is active.`;\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t\tadditionalInstructions,\n\t\t);\n\t},\n};\n\nconst updateTrendAndForecastConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateTrendAndForecast',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'trend',\n\t\t\t'forecast',\n\t\t]);\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t);\n\t},\n};\n\nconst updateOtherChartDataOptionsConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateOtherChartDataOptions',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = excludeSchemaProperties(baseSchema, [\n\t\t\t'sortType', // Has dedicated sorting tool\n\t\t\t'trend', // Has dedicated trend/forecast tool\n\t\t\t'forecast', // Has dedicated trend/forecast tool\n\t\t\t'chartType', // Has dedicated chartType tool\n\t\t]);\n\t\tconst additionalInstructions = `IMPORTANT: This tool cannot swap data columns (e.g. changing \"Revenue\" to \"Profit\"). Use createChart for that.`;\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t\tadditionalInstructions,\n\t\t);\n\t},\n};\n\n// Generate and export wrapper functions\nexport const updateChartTypeOfMeasures = createUpdateChartDataOptionsTool(\n\tupdateChartTypeOfMeasuresConfig,\n);\n\nexport const updateChartSorting = createUpdateChartDataOptionsTool(\n\tupdateChartSortingConfig,\n);\n\nexport const updateTrendAndForecast = createUpdateChartDataOptionsTool(\n\tupdateTrendAndForecastConfig,\n);\n\nexport const updateOtherChartDataOptions = createUpdateChartDataOptionsTool(\n\tupdateOtherChartDataOptionsConfig,\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","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 { zodFunction } 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 {\n\tupdateChartTypeOfMeasures,\n\tupdateChartSorting,\n\tupdateTrendAndForecast,\n\tupdateOtherChartDataOptions,\n} from './update-chart/update-chart-data-options';\nimport { updateChartStyleOptions } from './update-chart/update-chart-style-options';\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. \n\nIMPORTANT: Split the user prompt into two parts:\n1. queryPrompt: Be as faithful to the original user prompt as possible, but remove chart-specific instructions (e.g., \"bar chart\", \"use X as dimension\"). Focus on what data to retrieve - the tool will extract specific dimensions, measures, and filters automatically.\n2. chartPrompt: Be as faithful to the original user prompt as possible and keep chart-specific instructions. Do not infer the chart type from the user prompt.\n\nUse 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\tupdateChartTypeOfMeasures,\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\tupdateChartSorting,\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\tupdateTrendAndForecast,\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\t\t\tupdateOtherChartDataOptions,\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\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 (!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 {\n\tgetDataSourceFieldsWithDescriptions,\n\tDataSourceFieldWithDescription,\n} from '@/services/data-sources/data-sources-service';\nimport { DataSourceField } from '@sisense/sdk-data';\nimport {\n\tTOOL_NAME_GET_DATA_SOURCE_FIELDS,\n\tMAX_DATA_SOURCE_FIELDS_SUMMARY,\n} from '@/constants';\nimport {\n\tgetDataSourceFieldsSchema,\n\tGetDataSourceFieldsContext,\n\tDataSourceFieldsResult,\n\tDataSourceFieldsSummary,\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\n/**\n * Create a lightweight summary of data source fields for LLM consumption\n * @param dataSourceTitle - The title of the data source\n * @param fields - The full list of fields from the data source\n * @returns A summary object with only table and column names (truncated if needed)\n */\nexport function getDataSourceFieldsSummary(\n\tdataSourceTitle: string,\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[],\n): DataSourceFieldsSummary {\n\tconst totalFields = fields.length;\n\tconst tableCount = new Set(fields.map((f) => f.table)).size;\n\tconst truncatedFields = fields.slice(0, MAX_DATA_SOURCE_FIELDS_SUMMARY);\n\tconst isTruncated = totalFields > MAX_DATA_SOURCE_FIELDS_SUMMARY;\n\n\treturn {\n\t\tmessage: isTruncated\n\t\t\t? `Retrieved ${totalFields} fields from ${tableCount} tables (showing first ${MAX_DATA_SOURCE_FIELDS_SUMMARY} in summary)`\n\t\t\t: `Retrieved ${totalFields} fields from ${tableCount} tables`,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tdataSourceTitle,\n\t\tfields: truncatedFields.map((field) => ({\n\t\t\ttable: field.table,\n\t\t\tcolumn: field.column,\n\t\t})),\n\t\ttotalFields,\n\t\ttableCount,\n\t\tisTruncated,\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\n/**\n * Summary of data source fields for LLM consumption (lightweight version)\n */\nexport interface DataSourceFieldsSummary {\n\t/**\n\t * Status message indicating success and field count\n\t */\n\tmessage: string;\n\t/**\n\t * Date and time ISO string of when the fields were retrieved\n\t */\n\tcreatedAt: string;\n\t/**\n\t * The title of the data source\n\t */\n\tdataSourceTitle: string;\n\t/**\n\t * List of fields with only table and column names (truncated if needed)\n\t */\n\tfields: Array<{ table: string; column: string }>;\n\t/**\n\t * Total number of fields in the data source\n\t */\n\ttotalFields: number;\n\t/**\n\t * Number of unique tables in the data source\n\t */\n\ttableCount: number;\n\t/**\n\t * Whether the fields array was truncated due to limit\n\t */\n\tisTruncated: boolean;\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","import { z } from 'zod';\nimport { getAvailableFusionDashboards } from '@/services/dashboards/fusion-dashboards-service';\nimport { TOOL_NAME_GET_DASHBOARDS } from '@/constants';\nimport {\n\tgetDashboardsSchema,\n\tGetDashboardsContext,\n\tDashboardsResult,\n} from './types';\n\n/**\n * Standalone dashboards engine - completely decoupled from any UI or store\n * @param params - The parameters for getting dashboards (currently empty)\n * @param context - Context with tool call ID for tracking\n * @returns The dashboards result with list of dashboards\n */\nexport async function getDashboardsEngine(\n\tparams: z.infer<typeof getDashboardsSchema>,\n\tcontext: GetDashboardsContext,\n): Promise<DashboardsResult> {\n\tconsole.debug(TOOL_NAME_GET_DASHBOARDS, context.toolCallId);\n\n\tconst dashboards = await getAvailableFusionDashboards(context.httpClient);\n\n\treturn {\n\t\tdashboards,\n\t};\n}\n","import { z } from 'zod';\nimport { Dashboard } from '@/services/dashboards/fusion-dashboards-service';\nimport { HttpClient } from '@sisense/sdk-rest-client';\n\n/**\n * Schema for getDashboards engine parameters\n */\nexport const getDashboardsSchema = z.object({});\n\n/**\n * Context interface for getDashboardsEngine\n */\nexport interface GetDashboardsContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\thttpClient?: HttpClient;\n}\n\n/**\n * Result from getDashboardsEngine\n */\nexport interface DashboardsResult {\n\t/**\n\t * List of dashboards\n\t */\n\tdashboards: Dashboard[];\n}\n","import {\n\tDashboardProps,\n\tWidgetProps,\n\tChartType,\n\tWidgetType,\n} from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport { z } from 'zod';\nimport { ChartSummary, ArtifactReference } from '../chart-builder/types';\n\nexport type ExtendedDashboardProps = DashboardProps & ArtifactReference;\n\n/**\n * Chart list summary for LLM context\n */\nexport type ChartListSummary = {\n\tmessage: string;\n\tcreatedAt: string;\n\tchartListId: string;\n};\n\n/**\n * Base dashboard summary for LLM consumption and asset extraction\n */\nexport type BaseDashboardSummary = {\n\t/** Fusion dashboard ID */\n\tfusionDashboardId?: string;\n\t/** Human-readable title of the dashboard */\n\tdashboardTitle?: string;\n\t/** Default data source title for the dashboard */\n\tdefaultDataSourceTitle: string;\n\t/** Array of widget summaries */\n\twidgets: Array<{\n\t\t/** Widget ID */\n\t\twidgetId?: string;\n\t\t/** Widget title (for chart and pivot table widgets) */\n\t\twidgetTitle?: string;\n\t\t/** Widget type (for chart and pivot table widgets) */\n\t\twidgetType?: WidgetType;\n\t\t/** Chart type (for chart widgets only) */\n\t\tchartType?: ChartType;\n\t}>;\n};\n\n/**\n * Summary of a dashboard for LLM consumption and asset extraction\n */\nexport interface DashboardSummary {\n\t/** Status message indicating success or failure */\n\tmessage: string;\n\t/** Date and time ISO string of when the dashboard was created */\n\tcreatedAt: string;\n\t/** Unique identifier for the dashboard (typically the tool call ID) */\n\tdashboardId: string;\n\t/** Dashboard details, undefined if dashboard creation failed */\n\tdashboard?: BaseDashboardSummary;\n}\n\n/**\n * Schema for the main buildDashboard smart tool\n */\nexport const buildDashboardSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tuserPrompt: z.string().describe(\n\t\t`Combined natural language user prompt describing actions on a dashboard.\n\t\t\nExamples:\n- \"Create a dashboard with sales charts\"\n- \"Load dashboard ABC123\"\n- \"Add revenue chart to the current dashboard\"\n- \"Rename the dashboard to 'Q4 Sales Report'\"\n- \"Add filters for region and date to the dashboard\"\n`,\n\t),\n});\n\nexport type BuildDashboardParams = z.infer<typeof buildDashboardSchema>;\n\n/**\n * Schema for createDashboard tool\n */\nexport const createDashboardSchema = z.object({\n\tdashboardTitle: z.string().optional().describe('Optional dashboard title'),\n\twidgetIdsToAdd: z\n\t\t.array(z.string())\n\t\t.describe(\n\t\t\t'Chart Widget IDs or Chart Widget List ID to add to the dashboard. Use empty array if no charts are found',\n\t\t),\n});\n\nexport type CreateDashboardParams = z.infer<typeof createDashboardSchema>;\n\n/**\n * Schema for loadExistingDashboard tool\n */\nexport const loadExistingFusionDashboardSchema = z.object({\n\tdashboardTitle: z.string().describe('Fusion dashboard title to load'),\n});\n\nexport type LoadExistingFusionDashboardParams = z.infer<\n\ttypeof loadExistingFusionDashboardSchema\n>;\n\n/**\n * Schema for updateDashboard tool\n */\nexport const updateDashboardSchema = z.object({\n\tdashboardId: z.string().describe('Dashboard ID to update'),\n\tdashboardTitle: z.string().describe('New dashboard title'),\n});\n\nexport type UpdateDashboardParams = z.infer<typeof updateDashboardSchema>;\n\n/**\n * Schema for addDashboardWidgets tool\n */\nexport const addDashboardWidgetsSchema = z.object({\n\tdashboardId: z.string().describe('Existing dashboard ID to add widgets to'),\n\twidgetIdsToAdd: z\n\t\t.array(z.string())\n\t\t.describe('Chart IDs or Chart List ID to add to the dashboard'),\n});\n\nexport type AddDashboardWidgetsParams = z.infer<\n\ttypeof addDashboardWidgetsSchema\n>;\n\n/**\n * Schema for createChartForDashboard tool\n */\nexport const createChartWidgetForDashboardSchema = z.object({\n\tdashboardId: z.string().describe('Existing dashboard ID to add a chart to'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('User prompt to describe a chart widget for the dashboard'),\n});\n\nexport type CreateChartWidgetForDashboardParams = z.infer<\n\ttypeof createChartWidgetForDashboardSchema\n>;\n\n/**\n * Schema for updateChartWidgetForDashboard tool\n */\nexport const updateChartWidgetForDashboardSchema = z.object({\n\tdashboardId: z\n\t\t.string()\n\t\t.describe('Existing dashboard ID to update a chart widget in'),\n\twidgetId: z.string().describe('Widget ID to update'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('User prompt to describe the update to the chart widget'),\n});\n\nexport type UpdateChartWidgetForDashboardParams = z.infer<\n\ttypeof updateChartWidgetForDashboardSchema\n>;\n\n/**\n * Schema for addDashboardFilters tool\n */\nexport const addDashboardFiltersSchema = z.object({\n\tdashboardId: z.string().describe('Dashboard ID to add filters to'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('Combined user prompt to add filters to the dashboard.'),\n});\n\nexport type AddDashboardFiltersParams = z.infer<\n\ttypeof addDashboardFiltersSchema\n>;\n\n/**\n * Build dashboard context interface\n */\nexport interface BuildDashboardContext {\n\t/**\n\t * Tool call ID - REQUIRED\n\t */\n\ttoolCallId: string;\n\t/**\n\t * Data source title (required)\n\t */\n\tdataSourceTitle: string;\n\t/**\n\t * Chart summaries for context\n\t */\n\tchartSummaries?: ChartSummary[];\n\t/**\n\t * Chart list summaries for context\n\t */\n\tchartListSummaries?: ChartListSummary[];\n\t/**\n\t * Dashboard summaries for context\n\t */\n\tdashboardSummaries?: DashboardSummary[];\n\t/**\n\t * Retrieve a dashboard by ID (optional)\n\t * @param dashboardId - The ID of the dashboard to retrieve\n\t * @returns The dashboard props or null\n\t */\n\tretrieveDashboard?: (dashboardId: string) => ExtendedDashboardProps | null;\n\t/**\n\t * Save dashboard props (optional)\n\t * @param dashboardProps - The dashboard props to save\n\t */\n\tsaveDashboard?: (dashboardProps: ExtendedDashboardProps) => void;\n\t/**\n\t * Get widget list by IDs (optional)\n\t * @param widgetIds - The IDs of widgets to retrieve\n\t * @returns Array of widget props\n\t */\n\tgetWidgetList?: (widgetIds: string[]) => WidgetProps[];\n\t/**\n\t * Whether NLQ V3 is enabled\n\t */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\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 {\n\tCreateDashboardParams,\n\tExtendedDashboardProps,\n\tBuildDashboardContext,\n} from './types';\nimport { createNewDashboard } from '@/services/dashboards/dashboards-service';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const createDashboard = async (\n\t{ dashboardTitle, widgetIdsToAdd }: CreateDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { dataSourceTitle, getWidgetList, saveDashboard, httpClient } =\n\t\tcontext;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createDashboard',\n\t\tdashboardTitle,\n\t\twidgetIdsToAdd,\n\t);\n\n\tlet newWidgetList: WidgetProps[] = [];\n\ttry {\n\t\tnewWidgetList =\n\t\t\t(widgetIdsToAdd && widgetIdsToAdd.length > 0\n\t\t\t\t? getWidgetList?.(widgetIdsToAdd)\n\t\t\t\t: []) || [];\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t'Error: Failed to locate input chart widgets. Empty widget list will be used.',\n\t\t\terror,\n\t\t);\n\t}\n\n\tconst dashboardProps: ExtendedDashboardProps = await createNewDashboard(\n\t\tdataSourceTitle,\n\t\tdashboardTitle || `Dashboard for ${dataSourceTitle}`,\n\t\tnewWidgetList,\n\t\thttpClient,\n\t);\n\n\t// generate a new artifact id for the dashboard\n\tdashboardProps.artifactId = nanoidHex();\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tnewWidgetList.length > 0\n\t\t\t\t? 'Dashboard created successfully. Click \"Save\" to persist to My Dashboards.'\n\t\t\t\t: 'Dashboard created with no chart widgets. Run the createChartWidgetForDashboard tool to create one.',\n\t};\n};\n","import {\n\tExtendedDashboardProps,\n\tLoadExistingFusionDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport { getAvailableFusionDashboards } from '@/services/dashboards/fusion-dashboards-service';\nimport { loadExistingDashboardFromFusion } from '@/services/dashboards/fusion-dashboards-service';\nimport { getBaseDashboardConfig } from '@/services/dashboards/dashboards-service';\nimport { nanoidHex } from '@/utils/id-utils';\n\nexport const loadExistingFusionDashboard = async (\n\t{ dashboardTitle }: LoadExistingFusionDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { saveDashboard, httpClient } = context;\n\tconsole.debug('toolCall', 'loadExistingFusionDashboard', dashboardTitle);\n\n\tconst availableDashboards = await getAvailableFusionDashboards(httpClient);\n\n\tconst fusionDashboard = availableDashboards.find(\n\t\t(dashboard) => dashboard.dashboardTitle === dashboardTitle,\n\t);\n\n\tif (!fusionDashboard) {\n\t\tthrow new Error(\n\t\t\t`Fusion dashboard with title ${dashboardTitle} not found`,\n\t\t);\n\t}\n\n\tconst dashboardProps: ExtendedDashboardProps =\n\t\tawait loadExistingDashboardFromFusion(\n\t\t\tfusionDashboard.dashboardId,\n\t\t\thttpClient,\n\t\t);\n\n\tconst updatedDashboardProps: ExtendedDashboardProps = {\n\t\t...dashboardProps,\n\t\t// Use the base dashboard config to ensure the dashboard is created with the correct default settings\n\t\tconfig: {\n\t\t\t...dashboardProps.config,\n\t\t\t...getBaseDashboardConfig(),\n\t\t},\n\t\t// Generate a new artifact id for the dashboard\n\t\tartifactId: dashboardProps.artifactId || nanoidHex(),\n\t};\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage: 'Dashboard loaded successfully from Fusion.',\n\t};\n};\n","import { UpdateDashboardParams, BuildDashboardContext } from './types';\nimport { updateDashboardTitle } from '@/services/dashboards/dashboards-service';\n\nexport const updateDashboard = async (\n\t{ dashboardId, dashboardTitle }: UpdateDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { retrieveDashboard, saveDashboard } = context;\n\tconsole.debug('toolCall', 'updateDashboard', dashboardId, dashboardTitle);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tlet dashboardProps = currentDashboard;\n\tif (dashboardTitle && dashboardTitle !== dashboardProps.title) {\n\t\tdashboardProps = updateDashboardTitle(dashboardProps, dashboardTitle);\n\t}\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\t'Dashboard updated successfully. Click \"Save\" to persist changes to My Dashboards.',\n\t};\n};\n","import { AddDashboardWidgetsParams, BuildDashboardContext } from './types';\nimport { addWidgetsToExistingDashboard } from '@/services/dashboards/dashboards-service';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const addDashboardWidgets = async (\n\t{ dashboardId, widgetIdsToAdd }: AddDashboardWidgetsParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { retrieveDashboard, saveDashboard, getWidgetList } = context;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'addDashboardWidgets',\n\t\tdashboardId,\n\t\twidgetIdsToAdd,\n\t);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tlet newWidgetList: WidgetProps[] = [];\n\ttry {\n\t\tnewWidgetList = getWidgetList?.(widgetIdsToAdd) || [];\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t'Error: Failed to locate input chart widgets. Empty widget list will be used.',\n\t\t\terror,\n\t\t);\n\t}\n\tconst dashboardProps = addWidgetsToExistingDashboard(\n\t\tcurrentDashboard,\n\t\tnewWidgetList,\n\t);\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tnewWidgetList.length > 0\n\t\t\t\t? 'Widgets added successfully. Click \"Save\" to persist changes to My Dashboards.'\n\t\t\t\t: widgetIdsToAdd.length > 0\n\t\t\t\t? 'Widgets cannot be located. Try to create chart widgets one by one and add them to the dashboard.'\n\t\t\t\t: 'Widgets cannot be located. Run the recommend queries tool and add them all as widgets to the dashboard.',\n\t};\n};\n","export const FILTER_FACTORY_TYPES = `import {\n\tDateDimension,\n\tLevelAttribute,\n\tAttribute,\n\tMeasure,\n\tFilter,\n\tBaseMeasure,\n\tFilterRelationsNode,\n\tFilterRelations,\n\tMembersFilterConfig,\n\tBaseFilterConfig,\n} from '../interfaces.js';\n/**\n * Creates a filter representing the union of multiple filters on the same attribute. The resulting\n * union filter filters on items that match any of the given filters.\n *\n * To create 'or' filters using different attributes, use the {@link logic.and | \\`or()\\`} function.\n *\n * @example\n * Filter for countries that start with the letter 'A' **or** end with the letter 'A'\n * in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.union([\n * filterFactory.startsWith(DM.Country.Country, 'A'),\n * filterFactory.endsWith(DM.Country.Country, 'A'),\n * ])\n * \\`\\`\\`\n * @param filters - Filters to union. The filters must all be on the same attribute.\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function union(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter representing the intersection of multiple filters on the same attribute. The resulting\n * intersection filter filters on items that match all of the given filters.\n *\n * To create 'and' filters using different attributes, use the {@link logic.and | \\`and()\\`} function.\n *\n * @example\n * Filter for countries that start with the letter 'A' **and** end with the letter 'A'\n * in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.intersection([\n * filterFactory.startsWith(DM.Country.Country, 'A'),\n * filterFactory.endsWith(DM.Country.Country, 'A'),\n * ])\n * \\`\\`\\`\n * @param filters - Filters to intersect. The filters must all be on the same attribute.\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function intersection(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter that excludes items matching the given filter\n * from all items or from items matching the optional input filter.\n *\n * @example\n * Filter for items where the country name does not contain the letter 'A'\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.exclude(filterFactory.contains(DM.Country.Country, 'A'))\n * \\`\\`\\`\n *\n * Filter for items where the country name starts with the letter 'B' but does not contain the letter 'A'\n * from the Sample ECommerce data model. This filter will match countries like 'Belgium', but will not\n * match countries like 'Bermuda'.\n * \\`\\`\\`ts\n * filterFactory.exclude(\n * filterFactory.contains(DM.Country.Country, 'A'),\n * filterFactory.startsWith(DM.Country.Country, 'B')\n * )\n * \\`\\`\\`\n * @param filter - Filter to exclude\n * @param input - Input filter to exclude from, on the same attribute. If not provided, the filter excludes from all items.\n * @param config - Optional configuration for the filter\n * @returns A filter representing an exclusion of the given filter\n * from all attribute members or from the optional input filter\n */\nexport declare function exclude(filter: Filter, input?: Filter, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate attribute values that do not contain a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for categories in the Sample ECommerce data model where the category name doesn't contain\n * 'digital'. This filter matches categories not like 'Digital Cameras' and 'MP3 & Digital Media Players'.\n * \\`\\`\\`ts\n * filterFactory.contains(DM.Category.Category, 'digital')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntContain(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not end with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name doesn't end with\n * 'land'. This filter matches countries not like 'Iceland' and 'Ireland'.\n * \\`\\`\\`ts\n * filterFactory.doesntEndWith(DM.Country.Country, 'land')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntEndWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not start with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name doesn't start with\n * 'United'. This filter matches countries not like 'United States' and 'United Kingdom'.\n * \\`\\`\\`ts\n * filterFactory.doesntStartWith(DM.Country.Country, 'United')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntStartWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that contain a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for categories in the Sample ECommerce data model where the category name contains\n * 'digital'. This filter matches categories like 'Digital Cameras' and 'MP3 & Digital Media Players'.\n * \\`\\`\\`ts\n * filterFactory.contains(DM.Category.Category, 'digital')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function contains(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that end with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name ends with\n * 'land'. This filter matches countries like 'Ireland' and 'Iceland'.\n * \\`\\`\\`ts\n * filterFactory.endsWith(DM.Country.Country, 'land')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function endsWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that start with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name starts with\n * 'United'. This filter matches countries like 'United States' and 'United Kingdom'.\n * \\`\\`\\`ts\n * filterFactory.startsWith(DM.Country.Country, 'United')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function startsWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that match a specified string pattern.\n *\n * The pattern can include the following wildcard characters:\n *\n * + \\`_\\`: Matches a single character\n * + \\`%\\`: Matches multiple characters\n *\n * To search for a literal underscore (\\`_\\`) or percent symbol (\\`%\\`), use the backslash (\\`\\\\\\`) escape\n * character.\n *\n * Matching is case insensitive.\n *\n * @example\n * Filter for countries from the Sample ECommerce data model where the country name starts with an\n * 'A' and ends with an 'a'. This filter matches countries like 'Argentina' and 'Australia'.\n * \\`\\`\\`ts\n * filterFactory.like(DM.Country.Country, 'A%a')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function like(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not equal a specified string or number.\n *\n * When filtering against a string:\n *\n * + Matching is case insensitive.\n * + You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for items not in new condition from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.doesntEqual(DM.Commerce.Condition, 'New')\n * \\`\\`\\`\n * @param attribute - Text or numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntEqual(\n\tattribute: Attribute,\n\tvalue: string | number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that equal a specified string or number.\n *\n * When filtering against a string:\n *\n * + Matching is case insensitive.\n * + You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for items in new condition from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.equals(DM.Commerce.Condition, 'New')\n * \\`\\`\\`\n * @param attribute - Text or numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function equals(\n\tattribute: Attribute,\n\tvalue: string | number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values strictly greater than a specified number.\n *\n * @example\n * Filter for items where the cost is greater than 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.greaterThan(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function greaterThan(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values greater than or equal to a specified number.\n *\n * @example\n * Filter for items where the cost is greater than or equal to 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.greaterThanOrEqual(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function greaterThanOrEqual(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values strictly less than a specified number.\n *\n * @example\n * Filter for items where the cost is less than 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.lessThan(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function lessThan(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values less than or equal to a specified number.\n *\n * @example\n * Filter for items where the cost is less than or equal to 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.lessThanOrEqual(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function lessThanOrEqual(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values within or exactly matching two specified numerical boundaries.\n *\n * @example\n * Filter for items from the Sample ECommerce data model where the cost is greater than or equal to 100 and less than or equal to 200.\n * \\`\\`\\`ts\n * filterFactory.between(DM.Commerce.Cost, 100, 200)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param valueA - Value to filter from\n * @param valueB - Value to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function between(\n\tattribute: Attribute,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter that isolates attribute values strictly within two specified numerical boundaries.\n *\n * @example\n * Filter for items from the Sample ECommerce data model where the cost is greater than 100 and less than 200.\n * \\`\\`\\`ts\n * filterFactory.betweenNotEqual(DM.Commerce.Cost, 100, 200)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param valueA - Value to filter from\n * @param valueB - Value to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function betweenNotEqual(\n\tattribute: Attribute,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a custom numeric filter that filters for given attribute values.\n *\n * @example\n * Filter for items where the cost is greater than 100 and less than 200\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.numeric(\n * DM.Commerce.Cost,\n * NumericOperators.From,\n * 100,\n * NumericOperators.To,\n * 200\n * )\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter\n * @param operatorA - First operator\n * @param valueA - First value\n * @param operatorB - Second operator\n * @param valueB - Second value\n * @param config - Optional configuration for the filter\n * @returns A custom numeric filter of the given attribute\n */\nexport declare function numeric(\n\tattribute: Attribute,\n\toperatorA?: string,\n\tvalueA?: number,\n\toperatorB?: string,\n\tvalueB?: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that match any of the specified strings.\n *\n * Matching is case sensitive.\n *\n * @example\n * Filter for items where the condition is 'Used' or 'Refurbished'\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.members(DM.Commerce.Condition, ['Used', 'Refurbished'])\n * \\`\\`\\`\n * @param attribute - Attribute to filter on\n * @param members - Array of member values to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n * @shortDescription Creates filter on attribute to match certain string values\n */\nexport declare function members(\n\tattribute: Attribute,\n\tmembers: string[],\n\tconfig?: MembersFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate date values starting from and including the given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is not before the year 2010.\n * \\`\\`\\`ts\n * filterFactory.dateFrom(DM.Commerce.Date.Years, '2010-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param from - Date or string representing the value to filter from\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateFrom(\n\tlevel: LevelAttribute,\n\tfrom: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items up until and including the given date and level.\n *\n * @example\n * Filter for items where the date is from the year 2010 or earlier in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.dateTo(DM.Commerce.Date.Years, '2010-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param to - Date or string representing the last member to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateTo(\n\tlevel: LevelAttribute,\n\tto: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items between and including the given dates and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is from the years 2009, 2010, or 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRange(DM.Commerce.Date.Years, '2009-01', '2011-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param from - Date or string representing the start member to filter from\n * @param to - Date or string representing the end member to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRange(\n\tlevel: LevelAttribute,\n\tfrom?: Date | string,\n\tto?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range after a\n * given date and level.\n *\n * Although the \\`offset\\` can be used to set a beginning date prior to the \\`anchor\\`, the filter range always\n * continues forward after the offset beginning date. So, using an \\`offset\\` of \\`-6\\` and a \\`count\\` of \\`18\\` when \\`level\\`\n * is a month level creates a range that begins 6 month before the \\`anchor\\` date and extends to 12 months after\n * the \\`anchor\\` date.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in 2011 or the first half of 2012.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, 0, 18, '2011-01'),\n * \\`\\`\\`\n *\n * Filter for items in the Sample ECommerce data model where the date is in the second half of 2010 or in 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, -6, 18, '2011-01'),\n * \\`\\`\\`\n *\n * Filter for items in the Sample ECommerce data model where the date is in the past 6 months.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, -6, 6),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day.\n * Positive numbers skip forwards and negative numbers skip backwards (e.g. \\`-6\\` is 6 months backwards when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter from, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelative(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range after a\n * given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in 2011 or the first half of 2012.\n * \\`\\`\\`ts\n * filterFactory.dateRelativeFrom(DM.Commerce.Date.Months, 0, 18, '2011-01'),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter from, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelativeFrom(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range before a\n * given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in the first half of 2010 or in 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRelativeTo(DM.Commerce.Date.Months, 0, 18, '2011-12'),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter to, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelativeTo(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current calendar year.\n *\n * @example\n * Filter for items where the date is in the current calendar year in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisYear(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisYear(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current calendar month.\n *\n * @example\n * Filter for items where the date is in the current calendar month in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisMonth(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisMonth(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current quarter.\n *\n * @example\n * Filter for items where the date is in the current quarter in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisQuarter(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisQuarter(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value of the current date.\n *\n * @example\n * Filter for items where the date is today in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.today(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function today(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter on all measure values matching the provided criteria.\n *\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param operatorA - Operator to apply on \\`valueA\\` ({@link NumericOperators})\n * @param valueA - First value\n * @param operatorB - Operator to apply on \\`valueB\\` ({@link NumericOperators})\n * @param valueB - Second value\n * @param config - Optional configuration for the filter\n * @returns A filter representing the provided logic\n * @internal\n */\nexport declare function measureBase(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\toperatorA?: string,\n\tvalueA?: number,\n\toperatorB?: string,\n\tvalueB?: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue equal 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureEquals(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureEquals(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value greater than to a given number.\n *\n * @example\n * Filter for categories that have an average revenue greater than\n * to 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureGreaterThan(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Min value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureGreaterThan(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value greater than or equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue greater than\n * or equal to 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureGreaterThanOrEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Min value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureGreaterThanOrEqual(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value less than or equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue less than\n * or equal to 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureLessThanOrEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureLessThanOrEqual(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value less than a given number.\n *\n * @example\n * Filter for categories that have an average revenue less than 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureLessThan(\n * measureFactory.average(DM.Commerce.Revenue),\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureLessThan(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value between or equal to two given numbers.\n *\n * @example\n * Filter for categories that have an average revenue greater than or equal to 50 and less than\n * or equal to 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureBetween(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50,\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param valueA - Min value\n * @param valueB - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureBetween(\n\tmeasure: BaseMeasure,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value between but not equal to two given numbers.\n *\n * @example\n * Filter for categories that have an average revenue greater than 50 and less than\n * 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureBetweenNotEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50,\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param valueA - Min value\n * @param valueB - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureBetweenNotEqual(\n\tmeasure: BaseMeasure,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items that rank towards the top for a given measure.\n *\n * @example\n * Filter for age ranges with the top 3 highest total revenue in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.topRanking(\n * DM.Commerce.AgeRange,\n * measureFactory.sum(DM.Commerce.Revenue),\n * 3\n * )\n * \\`\\`\\`\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param count - Number of members to return\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function topRanking(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\tcount: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items that rank towards the bottom for a given measure.\n *\n * @example\n * Filter for age ranges with the bottom 3 lowest total revenue in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.bottomRanking(\n * DM.Commerce.AgeRange,\n * measureFactory.sum(DM.Commerce.Revenue),\n * 3\n * )\n * \\`\\`\\`\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param count - Number of members to return\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function bottomRanking(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\tcount: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter that contains a list of dependent/cascading filters,\n * where each filter depends on the results or state of the previous ones in the array.\n *\n * Each filter in the array operates in the context of its predecessors, and the\n * cascading behavior ensures that all filters are applied sequentially.\n *\n * @example\n * \\`\\`\\`ts\n * // Create a cascading filter for gender and age range\n * const cascadingFilter = filterFactory.cascading(\n * [\n * filterFactory.members(DM.Commerce.Gender, ['Male', 'Female']),\n * filterFactory.members(DM.Commerce.AgeRange, ['0-18']),\n * ],\n * { disabled: true }, // Optional configuration to disable the cascading filter\n * );\n * \\`\\`\\`\n * @param filters - Array of dependent filters\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function cascading(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Set of logic operators for filter relations construction\n *\n * These operators are still in beta.\n *\n * @example\n * \\`\\`\\`ts\n * import { filters } from '@sisense/sdk-data';\n *\n * // define filters\n * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 1000);\n * const countryFilter = filterFactory.members(DM.Commerce.Country, ['USA', 'Canada']);\n * const genderFilter = filterFactory.doesntContain(DM.Commerce.Gender, 'Unspecified');\n * const costFilter = filterFactory.between(DM.Commerce.Cost, 1000, 2000);\n *\n * // create filter relations of two filters\n * const orFilerRelations = filterFactory.logic.or(revenueFilter, countryFilter);\n * // revenueFilter OR countryFilter\n *\n * // filter relations can have nested filter relations\n * const mixedFilterRelations = filterFactory.logic.and(genderFilter, orFilerRelations);\n * // genderFilter AND (revenueFilter OR countryFilter)\n *\n * // array, specified in filter relations, will be converted to an intersection of filters automatically\n * const arrayFilterRelations = filterFactory.logic.or([genderFilter, costFilter], mixedFilterRelations);\n * // (genderFilter AND costFilter) OR (genderFilter AND (revenueFilter OR countryFilter))\n * \\`\\`\\`\n * @beta\n */\nexport declare namespace logic {\n\t/**\n\t * Creates an 'AND' filter relations\n\t *\n\t * @example\n\t * Create filter relations for items that have a revenue greater than 100 and are in new condition\n\t * in the Sample ECommerce data model.\n\t * \\`\\`\\`ts\n\t * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 100);\n\t * const conditionFilter = filterFactory.equals(DM.Commerce.Condition, 'New');\n\t *\n\t * const andFilerRelation = filterFactory.logic.and(revenueFilter, conditionFilter);\n\t * \\`\\`\\`\n\t * @param left First filter or filter relations\n\t * @param right Second filter or filter relations\n\t * @returns Filter relations\n\t * @beta\n\t */\n\tconst and: (left: FilterRelationsNode, right: FilterRelationsNode) => FilterRelations;\n\t/**\n\t * Creates an 'OR' filter relations\n\t *\n\t * @example\n\t * Create filter relations for items that have a revenue greater than 100 or are in new condition\n\t * in the Sample ECommerce data model.\n\t * \\`\\`\\`ts\n\t * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 100);\n\t * const conditionFilter = filterFactory.equals(DM.Commerce.Condition, 'New');\n\t *\n\t * const orFilerRelation = filterFactory.logic.or(revenueFilter, conditionFilter);\n\t * \\`\\`\\`\n\t * @param left First filter or filter relations\n\t * @param right Second filter or filter relations\n\t * @returns Filter relations\n\t * @beta\n\t */\n\tconst or: (left: FilterRelationsNode, right: FilterRelationsNode) => FilterRelations;\n}\n/**\n * Creates a filter from JAQL\n *\n * @param attribute - Attribute to filter\n * @param jaql - Filter Jaql\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n * @internal\n */\nexport declare function customFilter(\n\tattribute: Attribute,\n\tjaql: any,\n\tconfig?: BaseFilterConfig,\n): Filter;` as const;\n","export const MEASURE_FACTORY_TYPES = `import {\n\tAttribute,\n\tMeasure,\n\tFilter,\n\tCalculatedMeasure,\n\tBaseMeasure,\n\tCustomFormulaContext,\n} from '../interfaces.js';\nimport { ForecastFormulaOptions, TrendFormulaOptions } from '../../interfaces.js';\nimport { CustomFormulaJaql } from '../filters/utils/types.js';\n/**\n * Defines the different numeric operators that can be used with numeric filters\n *\n * @internal\n */\nexport declare const RankingTypes: {\n\t/**\n\t * In competition ranking, items that rank equally receive the same ranking number, and then a gap is left after the equally ranked items in the ranking numbers.\n\t */\n\tStandardCompetition: string;\n\t/**\n\t * In modified competition ranking, items that rank equally receive the same ranking number, and a gap is left before the equally ranked items in the ranking numbers.\n\t */\n\tModifiedCompetition: string;\n\t/**\n\t * In dense ranking, items that rank equally receive the same ranking number, and the next items receive the immediately following ranking number.\n\t */\n\tDense: string;\n\t/**\n\t * In ordinal ranking, all items receive distinct ordinal numbers, including items that rank equally. The assignment of distinct ordinal numbers for equal-ranking items is arbitrary.\n\t */\n\tOrdinal: string;\n};\n/**\n * Defines the different ranking sorting types supported by rank measure\n *\n * @internal\n */\nexport declare const RankingSortTypes: {\n\tAscending: string;\n\tDescending: string;\n};\n/**\n * Transforms a custom formula jaql into a calculated measure instance.\n *\n * As custom formulas can be nested, the function performs a recursive transformation via a helper function.\n *\n * @param jaql - Custom formula jaql\n * @returns Calculated measure instance\n * @internal\n */\nexport declare function transformCustomFormulaJaql(jaql: CustomFormulaJaql): CalculatedMeasure;\n/**\n * Creates a calculated measure for a valid custom formula built from [base functions](/guides/sdk/reference/functions.html#measured-value-functions).\n *\n * Use square brackets (\\`[]\\`) within the \\`formula\\` property to include dimensions, measures, or filters.\n * Each unique dimension, measure, or filter included in the \\`formula\\` must be defined using a property:value pair in the \\`context\\` parameter.\n *\n * You can nest custom formulas by placing one inside the \\`formula\\` parameter of another.\n *\n * Note: To use [shared formulas](https://docs.sisense.com/main/SisenseLinux/shared-formulas.htm)\n * from a Fusion instance, you must fetch them first using {@link @sisense/sdk-ui!useGetSharedFormula | useGetSharedFormula}.\n *\n * @example\n * An example of constructing a custom formulas using dimensions, measures, and nested custom formulas\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * // Custom formula\n * const profitabilityRatio = measureFactory.customFormula(\n * 'Profitability Ratio',\n * '([totalRevenue] - SUM([cost])) / [totalRevenue]',\n * {\n * totalRevenue: measureFactory.sum(DM.Commerce.Revenue),\n * cost: DM.Commerce.Cost,\n * },\n * );\n *\n * // Nested custom formula\n * const profitabilityRatioRank = measureFactory.customFormula(\n * 'Profitability Ratio Rank',\n * 'RANK([profRatio], \"ASC\", \"1224\")',\n * {\n * profRatio: profitabilityRatio,\n * },\n * );\n * \\`\\`\\`\n *\n * Another example of constructing a custom formula using measures and filters\n * \\`\\`\\`ts\n * const totalCostWithFilter = measureFactory.customFormula(\n * 'Total Cost with Filter',\n * '(SUM([cost]), [categoryFilter])',\n * {\n * cost: DM.Commerce.Cost,\n * categoryFilter: filterFactory.members(DM.Category.Category, ['Apple Mac Desktops']),\n * },\n * );\n * \\`\\`\\`\n * @param title - Title of the measure to be displayed in legend\n * @param formula - Formula to be used for the measure\n * @param context - Formula context as a map of strings to attributes, measures, or filters\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function customFormula(\n\ttitle: string,\n\tformula: string,\n\tcontext: CustomFormulaContext,\n): CalculatedMeasure;\n/**\n * Creates an aggregated measure.\n *\n * This is a base function to build other aggregation functions (e.g., \\`sum\\`, \\`average\\`, etc.)\n * as listed in {@link AggregationTypes}.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.aggregate(DM.Commerce.Cost, 'sum'),\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param aggregationType - Aggregation type. See {@link AggregationTypes}\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function aggregate(\n\tattribute: Attribute,\n\taggregationType: string,\n\tname?: string,\n\tformat?: string,\n): BaseMeasure;\n/**\n * Creates a calculated measure from a numeric value.\n *\n * @example\n * Creates a calculated measure from a numeric value.\n * \\`\\`\\`ts\n * measureFactory.constant(42)\n * \\`\\`\\`\n * @param value - Value to be returned as a measure\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function constant(value: number): CalculatedMeasure;\n/**\n * Creates a sum aggregation measure over the given attribute.\n *\n * To create a running sum, use {@link runningSum}.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.sum(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function sum(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates an average aggregation measure over the given attribute.\n *\n * Both \\`average()\\` and \\`avg()\\` can be used interchangeably.\n *\n * @example\n * Calculate the average cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.average(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function average(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * {@inheritDoc average}\n *\n * @example\n * Calculate the average cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.avg(DM.Commerce.Cost)\n * \\`\\`\\`\n * @group Aggregation\n */\nexport declare function avg(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a min aggregation measure over the given attribute.\n *\n * @example\n * Calculate the minimum cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.min(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function min(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a max aggregation measure over the given attribute.\n *\n * @example\n * Calculate the maximum cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.max(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function max(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a median aggregation measure over the given attribute.\n *\n * @example\n * Calculate the median cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.median(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function median(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a count aggregation measure over the given attribute.\n *\n * To count distinct values in the given attribute, use {@link countDistinct}.\n *\n * @example\n * Counts the number of Commerce items from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.count(DM.Commerce.BrandID)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function count(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a count distinct aggregation measure over the given attribute.\n *\n * To count all values in the given attribute, use {@link count}.\n *\n * @example\n * Calculate the number of distinct brands from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.countDistinct(DM.Brand.BrandID)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function countDistinct(\n\tattribute: Attribute,\n\tname?: string,\n\tformat?: string,\n): BaseMeasure;\n/**\n * Creates a measured value with the given measure and set of filters.\n *\n * A measured value only includes values from items that match the provided filters.\n *\n * For example you can use a measured value to get a total cost for all items where the cost is greater than 100.\n *\n * Note that the filters on the measured value override the filters on the query, chart, or table the\n * measured value is used in.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model,\n * where the cost is greater than 100. Additional filtering on the cost will not affect this measure.\n * \\`\\`\\`ts\n * measureFactory.measuredValue(\n * measureFactory.sum(DM.Commerce.Cost),\n * [filterFactory.greaterThan(DM.Commerce.Cost, 100)],\n * 'Cost Greater Than 100'\n * ),\n * \\`\\`\\`\n * @param measure - Measure to filter\n * @param filters - Filters to apply to the measure\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function measuredValue(\n\tmeasure: Measure,\n\tfilters: Filter[],\n\tname?: string,\n\tformat?: string,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by adding two given numbers or measures.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureSum = measureFactory.add(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function add(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by subtracting two given numbers or measures. Subtracts \\`value2\\` from \\`value1\\`.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureDifference = measureFactory.subtract(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function subtract(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by multiplying two given numbers or measures.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureProduct = measureFactory.multiply(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function multiply(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by dividing two given numbers or measures. Divides \\`value1\\` by \\`value2\\`.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureQuotient = measureFactory.divide(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function divide(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the year up to the current day, week, month, or quarter.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the year up to the current day, week, month, or quarter.\n * \\`\\`\\`ts\n * measureFactory.yearToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the YTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function yearToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the quarter up to the current day, week, or month.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the quarter up to the current day, week, or month.\n * \\`\\`\\`ts\n * measureFactory.quarterToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the QTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function quarterToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the month up to the current day or week.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the month up to the current day or week.\n * \\`\\`\\`ts\n * measureFactory.monthToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the MTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function monthToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the week up to the current day.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the week up to the current day.\n * \\`\\`\\`ts\n * measureFactory.weekToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the WTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function weekToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total of a given measure.\n *\n * The running sum is calculated using the current sort order of the query it's used in.\n *\n * @example\n * Calculate the running sum of the total cost from the Sample Ecommerce data model across all categories.\n * \\`\\`\\`ts\n * measureFactory.runningSum(measureFactory.sum(DM.Commerce.Cost)),\n * \\`\\`\\`\n *\n * Running sum values from the Sample Ecommerce data model when categorizing by age range.\n * | AgeRange | Cost | Running Cost |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 4.32M |\n * | 19-24 | 8.66M | 12.98M |\n * | 25-34 | 21.19M | 34.16M |\n * | 35-44 | 23.64M | 57.8M |\n * | 45-54 | 20.39M | 78.19M |\n * | 55-64 | 11.82M | 90.01M |\n * | 65+ | 17.26M | 107.27M |\n * @param measure - Measure to apply the running sum to\n * @param _continuous - Boolean flag whether to accumulate the sum continuously\n * when there are two or more dimensions. The default value is false.\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function runningSum(\n\tmeasure: Measure,\n\t_continuous?: boolean,\n\tname?: string,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates growth over a period of time.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentPeriod – previousPeriod) / previousPeriod\\`.\n *\n * For example, if this period the value is 12 and the previous period's value was 10, the growth for\n * this period is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous period's value is greater than the current period, the growth will be negative.\n *\n * For example, if this period the value is 80, and the previous period's was 100, the growth for\n * this period is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this period in comparison to the previous period from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates growth rate over a period of time.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * Growth rate is calculated using the following formula: \\`currentPeriod / previousPeriod\\`.\n *\n * For example, if this period the value is 12 and the previous period's value was 10, the growth rate for\n * this period is 120%, returned as '1.2' (calculation: \\`12 / 10 = 1.2\\`).\n *\n * If the previous period's value is greater than the current period, the growth rate will be less than one.\n *\n * For example, if this period the value is 80, and the previous period's was 100, the growth for\n * this period is 80%, returned as \\`0.8\\` (calculation: \\`80 / 100 = .8\\`).\n *\n * @example\n * Calculate the growth rate in total cost this period in comparison to the previous period from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthRate(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the Growth rate\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthRate(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous week to the current week.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentWeek – previousWeek) / previousWeek\\`.\n *\n * For example, if this week the value is 12 and the previous week's value was 10, the growth for\n * this week is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous week's value is greater than the current week, the growth will be negative.\n *\n * For example, if this week the value is 80, and the previous week's was 100, the growth for\n * this week is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this week in comparison to the previous week from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous month to the current month.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentMonth – previousMonth) / previousMonth\\`.\n *\n * For example, if this month the value is 12 and the previous month's value was 10, the growth for\n * this month is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous month's value is greater than the current month, the growth will be negative.\n *\n * For example, if this month the value is 80, and the previous month's was 100, the growth for\n * this month is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this month in comparison to the previous month from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous quarter to the current quarter.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentQuarter – previousQuarter) / previousQuarter\\`.\n *\n * For example, if this quarter the value is 12 and the previous quarter's value was 10, the growth for\n * this quarter is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous quarter's value is greater than the current quarter, the growth will be negative.\n *\n * For example, if this quarter the value is 80, and the previous quarter's was 100, the growth for\n * this quarter is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this quarter in comparison to the previous quarter from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous year to the current year.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentYear – previousYear) / previousYear\\`.\n *\n * For example, if this year the value is 12 and the previous year's value was 10, the growth for\n * this year is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous year's value is greater than the current year, the growth will be negative.\n *\n * For example, if this year the value is 80, and the previous year's was 100, the growth for\n * this year is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this year in comparison to the previous year from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this period's data\n * and the data from the previous period for the given measure.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the difference between this period's total cost and the previous period's total cost\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.difference(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function difference(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this week's data\n * and the data from the previous week for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this week's total cost and the previous week's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this month's data\n * and the data from the previous month for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this month's total cost and the previous month's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this quarter's data\n * and the data from the previous quarter for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this quarter's total cost and the previous quarter's total cost\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this year's data\n * and the data from the previous year for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this year's total cost and the previous year's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the previous day.\n *\n * @example\n * Calculate total cost for the previous day from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastDay(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastDay(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day in the previous week.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day one week ago from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day or week in the previous month.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day or week one month ago from the Sample Ecommerce\n * data model.\n * \\`\\`\\`ts\n * measureFactory.pastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day, week, or month in the previous quarter.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day, week, or month one quarter ago from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day, week, month, or quarter in the previous year.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day, week, month, or quarter one year ago from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated contribution measure.\n *\n * A contribution measure calculates the contribution, in percentage, of a measure towards the total.\n * Percentages are expressed as a number between 0 and 1 (e.g. 42% is \\`0.42\\`).\n *\n * For example, using the Sample Ecommerce data model you can retrieve the total cost of products\n * categorized by age range. Using a contribution measure you can calculate how much each age range's\n * total cost contributes to the total cost across all age ranges. So, the total cost for the 35-44\n * age range is 23.64M, which is 22% of the 107.27M of all age ranges together. Therefore, the\n * contribution of the 35-44 age range is \\`.22\\`.\n *\n * @example\n * Calculates the percentage of the total cost across all categories for items in a category from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.contribution(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n *\n * Contribution values from the Sample Ecommerce data model when categorizing by age range.\n * | AgeRange | Cost | Contribution |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 0.04 |\n * | 19-24 | 8.66M | 0.08 |\n * | 25-34 | 21.19M | 0.2 |\n * | 35-44 | 23.64M | 0.22 |\n * | 45-54 | 20.39M | 0.19 |\n * | 55-64 | 11.82M | 0.11 |\n * | 65+ | 17.26M | 0.16 |\n * @param measure - Measure to apply the Contribution logic to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function contribution(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that computes a specified trend type for a given measure.\n *\n * The trend types include linear (the default), logarithmic, advanced smoothing, and local estimates.\n * You can also opt to automatically identify and ignore anomalous values in the series.\n *\n * Trend requires a Sisense instance version of L2023.6.0 or greater.\n *\n * @example\n * Calculate the trend in total cost from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.trend(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Total Cost Trend',\n * {\n * modelType: 'advancedSmoothing',\n * ignoreAnomalies: true,\n * }\n * )\n * \\`\\`\\`\n * @param measure - Measure to apply the trend logic to\n * @param name - Name for the new measure\n * @param options - Trend options\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function trend(\n\tmeasure: Measure,\n\tname?: string,\n\toptions?: TrendFormulaOptions,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that generates a forecast based on a specified measure employing\n * advanced autoML techniques.\n *\n * This function offers flexible options allowing you to:\n * + Let the function auto-select the best statistical model or explicitly choose a preferred model\n * + Control the time period used for training the model\n * + Set additional options to improve forecast accuracy by supplying expected lower and upper limits.\n *\n * In addition to the forecast, upper and lower confidence intervals are returned\n * with the name of the new measure and a suffix of _upper and _lower\n * respectively.\n *\n * Forecast requires a Sisense instance version of L2023.6.0 or greater.\n *\n * @example\n * Calculate a forecast for total cost from the Sample Ecommerce data model from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.forecast(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Total Cost Forecast',\n * {\n * modelType: 'prophet',\n * roundToInt: true,\n * }\n * )\n * \\`\\`\\`\n * @param measure - Measure to apply the forecast logic to\n * @param name - Name for the new measure\n * @param options - Forecast options\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function forecast(\n\tmeasure: Measure,\n\tname?: string,\n\toptions?: ForecastFormulaOptions,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the rank of a value in a list of values.\n *\n * This function includes options that allow you do customize the ranking order and how to handle\n * equally ranked items.\n *\n * The order options are:\n * + \\`'DESC'\\` (default): Descending, meaning the largest number is ranked first.\n * + \\`'ASC'\\`: Ascending, meaning the smallest number is ranked first.\n *\n * The rank type options are:\n * + \\`'1224'\\`: Standard competition, meaning items that rank equally receive the same ranking number,\n * and then a gap is left after the equally ranked items in the ranking numbers.\n * + \\`'1334'\\`: Modified competition ranking, meaning items that rank equally receive the same ranking number,\n * and a gap is left before the equally ranked items in the ranking numbers.\n * + \\`'1223'\\`: Dense ranking, meaning items that rank equally receive the same ranking number,\n * and the next items receive the immediately following ranking number.\n * + \\`'1234'\\`: Ordinal ranking, meaning all items receive distinct ordinal numbers,\n * including items that rank equally. The assignment of distinct ordinal numbers for equal-ranking items is arbitrary.\n *\n * @example\n * Calculate the rank of the total cost per category, sorted with the smallest cost ranked first,\n * and ranking ties are handled using the ordinal ranking type from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.rank(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Cost Rank',\n * measureFactory.RankingSortTypes.Ascending,\n * measureFactory.RankingTypes.Ordinal\n * )\n * \\`\\`\\`\n *\n * Ranking values from the Sample Ecommerce data model when categorizing by age range using the above ranking.\n * | AgeRange | Cost | Cost Rank |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 1 |\n * | 19-24 | 8.66M | 2 |\n * | 25-34 | 21.19M | 6 |\n * | 35-44 | 23.64M | 7 |\n * | 45-54 | 20.39M | 5 |\n * | 55-64 | 11.82M | 3 |\n * | 65+ | 17.26M | 4 |\n * @param measure - Measure to apply the ranking logic to\n * @param name - Name for the new measure\n * @param sort - Sorting for ranking. By default sort order is descending, where the largest number is ranked first.\n * @param rankType - How to handle equally ranked items. By default the type is standard competition ranking.\n * @param groupBy - Rank partition attributes\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function rank(\n\tmeasure: Measure,\n\tname?: string,\n\tsort?: string,\n\trankType?: string,\n\tgroupBy?: Attribute[],\n): CalculatedMeasure;` as const;\n","import { FILTER_FACTORY_TYPES } from './filter-factory-types';\nimport { MEASURE_FACTORY_TYPES } from './measure-factory-types';\n\nexport function generateFilterSystemPrompt() {\n\treturn `You are an expert in translating natural language into JSON filter expressions for data filtering.\n\n**Task:** Convert user prompts into JSON filter objects using the provided resources. DO NOT use any tools.\n\n**Available Resources:**\n1. **Measure Factory Types:**\n${MEASURE_FACTORY_TYPES}\n\n2. **Filter Factory Types:**\n${FILTER_FACTORY_TYPES}\n\n**Data Model Structure:**\n- DM.TableName.ColumnName (e.g., DM.Commerce.Revenue) - Use exact names.\n\n**Instructions:**\n1. **Default Filtering:**\n - Measures (without specified values): Filter for values > 0.\n - Categorical Attributes (without specified values): Use \\`members\\` filter with \\`[]\\` to filter for all members.\n - Date Level Attributes (without specified values): Use \\`members\\` filter with \\`[]\\` to filter for all members.\n - Explain any default behavior assumptions in plain English.\n\n2. **Filter Logic:**\n - Match user requirements to exact data fields.\n - Combine filters with \\`filterFactory.logic.or\\`/\\`and\\`.\n - Adhere to factory function names and argument order.\n - Output JSON with \\`\"function\"\\` and \\`\"args\"\\` properties (including nested).\n - Use exact function names from factory types.\n - Create measures with \\`measureFactory\\` for measure-based filters (unless no aggregation is specified).\n - Use corresponding date level fields for specified granularities (Years, Quarters, Months, Weeks, Days).\n - Always use \\`members\\` filter for concrete date level values in an array. Do not use \\`equals\\` filter for date level values.\n\n3. **Field Matching:**\n - Use exact field names.\n - Use closest match if exact name not found.\n - Refer to the data fields list for verification.\n\n**Output Format:**\n\\`\\`\\`json\n{\n \"function\": \"<factoryFunctionName>\",\n \"args\": [...]\n}\n\\`\\`\\`\n\n**Example Input/Output:**\n\\`\\`\\`\nInput: \"Filter for countries that start with 'A'\"\nOutput:\n{\n \"function\": \"filterFactory.startsWith\",\n \"args\": [\"DM.Country.Country\", \"A\"]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Filter for total revenue between 1000 and 2000\"\nOutput:\n{\n \"function\": \"filterFactory.measureBetween\",\n \"args\": [\n {\n \"function\": \"measureFactory.sum\",\n \"args\": [\"DM.Commerce.Revenue\", \"Total Revenue\"]\n },\n 1000,\n 2000\n ]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Filter for countries that start with 'A' OR have revenue > 1000\"\nOutput:\n{\n \"function\": \"filterFactory.logic.or\",\n \"args\": [\n {\n \"function\": \"filterFactory.startsWith\",\n \"args\": [\"DM.Country.Country\", \"A\"]\n },\n {\n \"function\": \"filterFactory.greaterThan\",\n \"args\": [\n \"DM.Commerce.Revenue\",\n 1000\n ]\n }\n ]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Show all years\"\nOutput:\n{\n \"function\": \"filterFactory.members\",\n \"args\": [\"DM.Date.Years\", []]\n}\n\\`\\`\\`\n`;\n}\n","import {\n\tBaseMeasure,\n\tCalculatedMeasure,\n\tcreateAttributeHelper,\n\tFilter,\n\tFilterRelations,\n\tisFilterRelations,\n\tisMembersFilter,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport { filterFactory, measureFactory } from '@sisense/sdk-data';\nimport { NormalizedDataSourceField } from '@/services/data-sources/data-sources-service';\n\n// Type to represent a function arg\ntype ParsedArg = string | number | ParsedFunctionCall;\n\n// Type to represent the structure parsed from the JSON\ntype ParsedFunctionCall = {\n\tfunction: string;\n\targs: ParsedArg[];\n};\n\nexport function getFactoryFunctionsMap(\n\tfactoryName: string,\n\tfactoryObject: Record<string, any>,\n): Record<string, (...args: any[]) => any> {\n\tconst functionsMap: Record<string, (...args: any[]) => any> = {};\n\tconst prefix = factoryName !== '' ? factoryName + '.' : '';\n\tfor (const key in factoryObject) {\n\t\tif (typeof factoryObject[key] === 'function') {\n\t\t\tfunctionsMap[`${prefix}${key}`] = factoryObject[key];\n\t\t} else if (typeof factoryObject[key] === 'object') {\n\t\t\tconst nestedFunctionsMap = getFactoryFunctionsMap(\n\t\t\t\t'',\n\t\t\t\tfactoryObject[key],\n\t\t\t);\n\t\t\tfor (const nestedKey in nestedFunctionsMap) {\n\t\t\t\tfunctionsMap[`${prefix}${key}.${nestedKey}`] =\n\t\t\t\t\tnestedFunctionsMap[nestedKey];\n\t\t\t}\n\t\t}\n\t}\n\treturn functionsMap;\n}\n\nexport const measureFactoryFunctionsMap = getFactoryFunctionsMap(\n\t'measureFactory',\n\tmeasureFactory,\n);\nexport const filterFactoryFunctionsMap = getFactoryFunctionsMap(\n\t'filterFactory',\n\tfilterFactory,\n);\n\nfunction executeFunction(\n\tfunctionPath: string,\n\targs: any[],\n): Filter | FilterRelations | BaseMeasure | CalculatedMeasure {\n\tconst parts = functionPath.split('.');\n\tconst factoryName = parts[0];\n\n\tif (factoryName === 'filterFactory') {\n\t\tif (filterFactoryFunctionsMap[functionPath]) {\n\t\t\treturn (\n\t\t\t\tfilterFactoryFunctionsMap[functionPath] as (\n\t\t\t\t\t...params: any[]\n\t\t\t\t) => Filter | FilterRelations\n\t\t\t)(...args);\n\t\t}\n\t} else if (factoryName === 'measureFactory') {\n\t\tif (measureFactoryFunctionsMap[functionPath]) {\n\t\t\treturn (\n\t\t\t\tmeasureFactoryFunctionsMap[functionPath] as (\n\t\t\t\t\t...params: any[]\n\t\t\t\t) => BaseMeasure | CalculatedMeasure\n\t\t\t)(...args);\n\t\t}\n\t}\n\n\tthrow new Error(\n\t\t`Function \"${functionPath}\" not found in filterFactory or measureFactory.`,\n\t);\n}\n\nfunction createAttribute(\n\tattributeName: string,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n) {\n\tconst dataField = dataFields.find(\n\t\t(field) => `DM.${field.table}.${field.column}` === attributeName,\n\t);\n\tif (!dataField) {\n\t\tthrow new Error(\n\t\t\t`Data field \"${attributeName}\" not found in data fields.`,\n\t\t);\n\t}\n\treturn createAttributeHelper({\n\t\texpression: dataField.expression,\n\t\tdataType: dataField.type,\n\t\tgranularity: dataField.level,\n\t\tformat: undefined,\n\t\tsort: undefined,\n\t\tdataSource,\n\t});\n}\n\nfunction processArg(\n\targ: ParsedArg,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n) {\n\tif (typeof arg === 'object' && arg !== null && arg.function && arg.args) {\n\t\treturn processNode(arg, dataSource, dataFields);\n\t}\n\tif (typeof arg === 'string' && arg.startsWith('DM.')) {\n\t\treturn createAttribute(arg, dataSource, dataFields);\n\t}\n\treturn arg;\n}\n\n/**\n * Recursively processes a parsed JSON object to execute filterFactory and measureFactory functions.\n *\n * @param parsedObject - The parsed JSON object representing a function call or a nested structure.\n * @returns The result of the executed function or the processed nested structure.\n */\nfunction processNode(\n\tparsedObject: ParsedFunctionCall,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n): Filter | FilterRelations | BaseMeasure | CalculatedMeasure {\n\tconst { function: functionPath, args } = parsedObject;\n\t// Recursively process arguments that are also function calls\n\tconst processedArgs = args.map((arg) =>\n\t\tprocessArg(arg, dataSource, dataFields),\n\t);\n\treturn executeFunction(functionPath, processedArgs);\n}\n\nfunction postProcessFilter(filter: Filter) {\n\tconst { attribute, config } = filter;\n\tif (isMembersFilter(filter) && 'granularity' in attribute) {\n\t\tconst granularity = attribute.granularity;\n\t\t// Convert values to ISO 8601 string -- e.g., 2011 to \"2011-01-01\"\n\t\treturn filterFactory.members(\n\t\t\tattribute,\n\t\t\tfilter.members.map((member) => {\n\t\t\t\tif (granularity === 'Years' && !isNaN(Number(member))) {\n\t\t\t\t\treturn `${member}-01-01T00:00:00`;\n\t\t\t\t}\n\t\t\t\treturn member;\n\t\t\t}),\n\t\t\tconfig,\n\t\t);\n\t}\n\treturn filter;\n}\n\nfunction postProcessFilters(\n\tfilters: Filter | FilterRelations,\n): Filter[] | FilterRelations {\n\tif (isFilterRelations(filters as FilterRelations | Filter[])) {\n\t\treturn filters as FilterRelations;\n\t}\n\treturn [filters as Filter].map(postProcessFilter);\n}\n\n/**\n * Translate JSON string to filters\n *\n * @example\n *\n * {\n * \"function\": \"filterFactory.logic.or\",\n * \"args\": [\n * {\n * \"function\": \"filterFactory.startsWith\",\n * \"args\": [\"DM.Country.Country\", \"A\"]\n * },\n * {\n * \"function\": \"filterFactory.measureGreaterThan\",\n * \"args\": [\n * {\n * \"function\": \"measureFactory.sum\",\n * \"args\": [\"DM.Commerce.Revenue\", \"Total Revenue\"]\n * },\n * 1000\n * ]\n * }\n * ]\n * }\n *\n * is translated to the following Filter[] or FilterRelations object:\n * filterFactory.logic.or([\n * filterFactory.startsWith(\"DM.Country.Country\", \"A\"),\n * filterFactory.measureGreaterThan(\n * measureFactory.sum(\"DM.Commerce.Revenue\", \"Total Revenue\"),\n * 1000\n * )\n * ])\n *\n * @param filtersJson - A JSON string representing the filters\n * @returns A Filter[] or FilterRelations object\n */\nexport const translateFiltersFromJsonFunctionCall = (\n\tfiltersJson: string,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n): Filter[] | FilterRelations => {\n\tconst parsedJson = JSON.parse(filtersJson);\n\tconst result = processNode(parsedJson, dataSource, dataFields) as\n\t\t| Filter\n\t\t| FilterRelations;\n\n\tconst postProcessedFilters = postProcessFilters(result);\n\treturn postProcessedFilters;\n};\n","import { z } from 'zod';\nimport { getNormalizedDataSourceFields } from '@/services/data-sources/data-sources-service';\nimport { generateFilterSystemPrompt } from './dashboard-filters-system-prompt';\nimport { translateFiltersFromJsonFunctionCall } from './translate-filters';\nimport { DashboardProps } from '@sisense/sdk-ui';\nimport { getDashboardDataSourcesMap } from '@/services/dashboards/dashboards-service';\nimport { mergeFiltersOrFilterRelations } from '@sisense/sdk-data';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\nimport { OpenAI } from 'openai';\n\nconst schema = z.object({\n\tfiltersJson: z.string().describe('A JSON string representing the filters'),\n\texplanation: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'A non-technical explanation of how the filters were manipulated',\n\t\t),\n});\n\nexport const manipulateDashboardFilters = async (\n\tuserPrompt: string,\n\tdataSourceTitle: string,\n\tdashboardProps: DashboardProps,\n\topenAIClient?: OpenAI,\n): Promise<{ dashboardProps: DashboardProps; explanation: string }> => {\n\tconst dataSourcesMap = getDashboardDataSourcesMap(dashboardProps);\n\tconst dataSource = dataSourcesMap.get(dataSourceTitle);\n\tif (!dataSource) {\n\t\tthrow new Error(\n\t\t\t`Data source \"${dataSourceTitle}\" not found in dashboard. Please ask the user to specify a valid data source.`,\n\t\t);\n\t}\n\n\tconst systemPrompt = generateFilterSystemPrompt();\n\n\tconst dataFields = await getNormalizedDataSourceFields(dataSourceTitle);\n\n\tconst fullUserPrompt = `${userPrompt}\\n\\nAvailable Data Fields:\\n${JSON.stringify(\n\t\tdataFields,\n\t\tnull,\n\t\t2,\n\t)}`;\n\n\tconst response = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt: fullUserPrompt,\n\t\topenAIClient,\n\t\tresponseFormat: {\n\t\t\ttype: 'json_schema',\n\t\t\tschema,\n\t\t\tname: 'filters',\n\t\t},\n\t});\n\n\tconst { filtersJson, explanation } = response;\n\tif (!filtersJson) {\n\t\tthrow new Error('Failed to manipulate filters');\n\t}\n\n\tconst filters = translateFiltersFromJsonFunctionCall(\n\t\tfiltersJson,\n\t\tdataSource,\n\t\tdataFields,\n\t);\n\n\t// Always return local dashboard props with merged filters\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tfilters: mergeFiltersOrFilterRelations(dashboardProps.filters, filters),\n\t};\n\n\treturn {\n\t\tdashboardProps: updatedDashboardProps,\n\t\texplanation,\n\t};\n};\n","import { AddDashboardFiltersParams, BuildDashboardContext } from './types';\nimport { manipulateDashboardFilters } from './dashboard-filters/manipulate-dashboard-filters';\n\nexport const addDashboardFilters = async (\n\t{ dashboardId, userPrompt }: AddDashboardFiltersParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { dataSourceTitle, retrieveDashboard, saveDashboard, openAIClient } =\n\t\tcontext;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'addDashboardFilters',\n\t\tdashboardId,\n\t\tuserPrompt,\n\t\tdataSourceTitle,\n\t);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tconst { dashboardProps: updatedDashboardProps, explanation } =\n\t\tawait manipulateDashboardFilters(\n\t\t\tuserPrompt,\n\t\t\tdataSourceTitle,\n\t\t\tcurrentDashboard,\n\t\t\topenAIClient,\n\t\t);\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage: `${explanation} Click \"Save\" to persist changes to My Dashboards.`,\n\t};\n};\n","import {\n\tCreateChartWidgetForDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport {\n\taddWidgetsToExistingDashboard,\n\tcreateEmptyDashboard,\n\tresetWidgetForDashboard,\n} from '@/services/dashboards/dashboards-service';\nimport { buildChartEngine } from '../chart-builder/chart-builder-engine';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n} from '../chart-builder/types';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const createChartWidgetForDashboard = async (\n\t{ dashboardId, userPrompt }: CreateChartWidgetForDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createChartWidgetForDashboard',\n\t\tdashboardId,\n\t\tuserPrompt,\n\t);\n\n\tconst {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard,\n\t\tsaveDashboard,\n\t\thttpClient,\n\t\topenAIClient,\n\t\tisNlqV3Enabled,\n\t} = context;\n\tif (!toolCallId) {\n\t\tthrow new Error('Error: Invalid tool call ID. Please try again.');\n\t}\n\n\tlet isNewDashboard = false;\n\tlet currentDashboard;\n\ttry {\n\t\tcurrentDashboard = retrieveDashboard?.(dashboardId);\n\t\tif (!currentDashboard) {\n\t\t\tthrow new Error('Dashboard not found. Creating a new dashboard.');\n\t\t}\n\t} catch (error) {\n\t\tcurrentDashboard = await createEmptyDashboard(\n\t\t\tdataSourceTitle,\n\t\t\t`Dashboard for ${dataSourceTitle}`,\n\t\t\thttpClient,\n\t\t);\n\t\tisNewDashboard = true;\n\t}\n\n\t// reuse chart builder engine to create a new chart widget\n\tlet newChartWidgetProps: ExtendedChartWidgetProps | null = null;\n\tconst buildChartContext: BuildChartContext = {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tretrieveChart: (_: string) => newChartWidgetProps,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tsaveChart: (_: string, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\tnewChartWidgetProps = chartWidgetProps;\n\t\t},\n\t\tisNlqV3Enabled,\n\t\thttpClient,\n\t\topenAIClient,\n\t};\n\n\tconst chartSummary = await buildChartEngine(\n\t\t{ dataSourceTitle, userPrompt },\n\t\tbuildChartContext,\n\t);\n\n\tif (chartSummary.isError) {\n\t\tthrow new Error(chartSummary.message);\n\t}\n\n\tif (!newChartWidgetProps) {\n\t\tthrow new Error('Error: Failed to create chart widget');\n\t}\n\n\tconst resetChartWidgetProps: WidgetProps =\n\t\tresetWidgetForDashboard(newChartWidgetProps);\n\n\tconst updatedDashboardProps = addWidgetsToExistingDashboard(\n\t\tcurrentDashboard,\n\t\t[resetChartWidgetProps],\n\t);\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tisNewDashboard && newChartWidgetProps\n\t\t\t\t? 'Dashboard created and chart widget added successfully. Click \"Save\" to persist changes to My Dashboards.'\n\t\t\t\t: `Chart widget (widgetId: ${resetChartWidgetProps.id}) added to the dashboard successfully. Click \"Save\" to persist changes to My Dashboards.`,\n\t};\n};\n","import {\n\tUpdateChartWidgetForDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport { buildChartEngine } from '../chart-builder/chart-builder-engine';\nimport { getBaseChartSummary } from '../chart-builder/chart-builder-service';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n} from '../chart-builder/types';\nimport { isChartWidgetProps } from '@sisense/sdk-ui';\n\nexport const updateChartWidgetForDashboard = async (\n\t{ dashboardId, widgetId, userPrompt }: UpdateChartWidgetForDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'updateChartWidgetForDashboard',\n\t\tdashboardId,\n\t\twidgetId,\n\t\tuserPrompt,\n\t);\n\n\tconst {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard,\n\t\tsaveDashboard,\n\t\thttpClient,\n\t\topenAIClient,\n\t\tisNlqV3Enabled,\n\t} = context;\n\tif (!toolCallId) {\n\t\tthrow new Error('Error: Invalid tool call ID. Please try again.');\n\t}\n\n\tconst dashboardProps = retrieveDashboard?.(dashboardId);\n\tif (!dashboardProps) {\n\t\tthrow new Error('Dashboard not found.');\n\t}\n\n\tlet widgetIndex = dashboardProps.widgets.findIndex(\n\t\t(widget) => widget.id === widgetId,\n\t);\n\tif (widgetIndex === -1) {\n\t\tconsole.debug(\n\t\t\t'Widget not found. Retrieving the last chart widget from dashboard.',\n\t\t);\n\t\twidgetIndex = dashboardProps.widgets.length - 1;\n\t}\n\n\tconst widgetProps = dashboardProps.widgets[widgetIndex];\n\n\tif (!isChartWidgetProps(widgetProps)) {\n\t\tthrow new Error('Widget is not a chart widget.');\n\t}\n\n\tlet savedChartWidgetProps = widgetProps;\n\n\tconst chartSummaries = [\n\t\t{\n\t\t\tmessage: 'This is the current chart widget',\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tchartId: widgetId,\n\t\t\tchart: getBaseChartSummary(savedChartWidgetProps, dataSourceTitle),\n\t\t},\n\t];\n\n\tconst buildChartContext: BuildChartContext = {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tchartSummaries,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tretrieveChart: (_: string) => savedChartWidgetProps,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tsaveChart: (_: string, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\t// Preserve the original widget ID to maintain dashboard layout references\n\t\t\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t\t\t...chartWidgetProps,\n\t\t\t\tid: widgetId,\n\t\t\t};\n\t\t\tdashboardProps.widgets[widgetIndex] = updatedWidgetProps;\n\t\t\tsavedChartWidgetProps = updatedWidgetProps;\n\t\t},\n\t\tisNlqV3Enabled,\n\t\thttpClient,\n\t\topenAIClient,\n\t};\n\n\tconst chartSummary = await buildChartEngine(\n\t\t{ dataSourceTitle, userPrompt },\n\t\tbuildChartContext,\n\t);\n\n\tif (chartSummary.isError) {\n\t\tthrow new Error(chartSummary.message);\n\t}\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\t'Chart widget updated successfully. Click \"Save\" to persist changes to My Dashboards.',\n\t};\n};\n","import { isChartWidgetProps, isPivotTableWidgetProps } from '@sisense/sdk-ui';\nimport { BaseDashboardSummary, ExtendedDashboardProps } from './types';\n\n/**\n * Get a base dashboard summary from dashboard props\n * This is used by the engine to create a summary for LLM consumption\n */\nexport const getBaseDashboardSummary = (\n\tdashboardProps: ExtendedDashboardProps,\n\tdataSourceTitle: string,\n): BaseDashboardSummary => {\n\treturn {\n\t\tfusionDashboardId: dashboardProps.id,\n\t\tdashboardTitle: dashboardProps.title,\n\t\tdefaultDataSourceTitle: dataSourceTitle,\n\t\twidgets: dashboardProps.widgets.map((widgetProps) => ({\n\t\t\twidgetId: widgetProps.id,\n\t\t\t...(isChartWidgetProps(widgetProps)\n\t\t\t\t? {\n\t\t\t\t\t\twidgetTitle: widgetProps.title,\n\t\t\t\t\t\twidgetType: widgetProps.widgetType,\n\t\t\t\t\t\tchartType: widgetProps.chartType,\n\t\t\t\t }\n\t\t\t\t: {}),\n\t\t\t...(isPivotTableWidgetProps(widgetProps)\n\t\t\t\t? {\n\t\t\t\t\t\twidgetTitle: widgetProps.title,\n\t\t\t\t\t\twidgetType: widgetProps.widgetType,\n\t\t\t\t }\n\t\t\t\t: {}),\n\t\t})),\n\t};\n};\n","import { zodFunction } from '@/utils/zod-utils';\nimport {\n\tBuildDashboardContext,\n\tChartListSummary,\n\tDashboardSummary,\n\tExtendedDashboardProps,\n\tbuildDashboardSchema,\n\tcreateDashboardSchema,\n\tloadExistingFusionDashboardSchema,\n\tupdateDashboardSchema,\n\taddDashboardWidgetsSchema,\n\taddDashboardFiltersSchema,\n\tcreateChartWidgetForDashboardSchema,\n\tupdateChartWidgetForDashboardSchema,\n} from './types';\nimport { ChartSummary } from '../chart-builder/types';\nimport { createDashboard } from './create-dashboard';\nimport { loadExistingFusionDashboard } from './load-existing-fusion-dashboard';\nimport { updateDashboard } from './update-dashboard';\nimport { addDashboardWidgets } from './add-dashboard-widgets';\nimport { addDashboardFilters } from './add-dashboard-filters';\nimport { createChartWidgetForDashboard } from './create-chart-widget';\nimport { updateChartWidgetForDashboard } from './update-chart-widget';\nimport { getBaseDashboardSummary } from './dashboard-builder-service';\nimport {\n\tTOOL_CONTEXT_MAX_ASSETS,\n\tTOOL_NAME_DASHBOARD_BUILDER,\n} from '@/constants';\nimport { createToolsCompletion } from '@/utils/chat-completion-utils';\nimport { resetWidgetForDashboard } from '@/services/dashboards/dashboards-service';\nimport z from 'zod';\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 description - The description of the tool\n * @param originalFunction - The function to call when the tool is used\n * @param boundContext - The context for the dashboard builder\n * @returns A zod function for the tool\n */\nconst createDashboardTool = (\n\toriginalSchema: any,\n\tname: string,\n\tdescription: string,\n\toriginalFunction: any,\n\tboundContext: BuildDashboardContext,\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 dashboard builder with injected dependencies\n * @param context - The bound context for the dashboard builder.\n * @returns A set of tools for the dashboard builder.\n */\nconst createDashboardTools = (context: BuildDashboardContext) => {\n\treturn [\n\t\tcreateDashboardTool(\n\t\t\tloadExistingFusionDashboardSchema,\n\t\t\t'loadExistingFusionDashboard',\n\t\t\t'Load an existing Fusion dashboard by title',\n\t\t\tloadExistingFusionDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tcreateDashboardSchema,\n\t\t\t'createDashboard',\n\t\t\t'Create a new dashboard with optional widgets',\n\t\t\tcreateDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tupdateDashboardSchema,\n\t\t\t'updateDashboard',\n\t\t\t'Update the title of an existing dashboard',\n\t\t\tupdateDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\taddDashboardWidgetsSchema,\n\t\t\t'addDashboardWidgets',\n\t\t\t'Add existing chart or chart list to an existing dashboard',\n\t\t\taddDashboardWidgets,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tcreateChartWidgetForDashboardSchema,\n\t\t\t'createChartWidgetForDashboard',\n\t\t\t'Create a new chart widget and add it to the dashboard',\n\t\t\tcreateChartWidgetForDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tupdateChartWidgetForDashboardSchema,\n\t\t\t'updateChartWidgetForDashboard',\n\t\t\t'Update an existing chart widget in the dashboard.',\n\t\t\tupdateChartWidgetForDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\taddDashboardFiltersSchema,\n\t\t\t'addDashboardFilters',\n\t\t\t'Add combined filters to an existing dashboard. Do not split the prompt into multiple filters.',\n\t\t\taddDashboardFilters,\n\t\t\tcontext,\n\t\t),\n\t];\n};\n\n/**\n * Build contextual system prompt for dashboard builder\n */\nexport function buildContextualSystemPrompt(\n\tchartSummaries: ChartSummary[],\n\tchartListSummaries: ChartListSummary[],\n\tdashboardSummaries: DashboardSummary[],\n) {\n\treturn `You are an intelligent and proactive dashboard assistant. \n\tYour role is to create, load, and update a dashboard, its widgets, and its filters based on natural language requests by using the available tools.\n\t\n\t \n\tIMPORTANT INSTRUCTIONS:\n\t1. Use the available tools to build the dashboard. Politely decline if asked to do something not related to the available tools.\n\t2. If the user prompt can be handled by a single tool, use that tool without splitting the prompt into multiple steps. \n\t3. Use the assets in the following context to build the dashboard: ${JSON.stringify(\n\t\t{\n\t\t\tcharts: chartSummaries,\n\t\t\tchartLists: chartListSummaries,\n\t\t\tdashboards: dashboardSummaries,\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\n\t4. Always reference the assets by their IDs instead of their titles.\n 5. Always use the last dashboard in the context as the current dashboard unless the user prompt specifies otherwise.\n\t6. To add a widget to the dashboard, use the last chart or chart list in the context.\n\t7. If no charts or chart lists exist in the context, run the \\`createChartWidgetForDashboard\\` tool to build a chart and add it to the dashboard.\n\t8. To update a chart widget, make sure the widget exists within the dashboard.\n\t`;\n}\n\n/**\n * Standalone dashboard builder engine - completely decoupled from any UI or store\n * @param params - The parameters for the dashboard builder\n * @param context - All external dependencies injected\n * @returns The dashboard summary\n */\nexport async function buildDashboardEngine(\n\tparams: z.infer<typeof buildDashboardSchema>,\n\tcontext: BuildDashboardContext,\n): Promise<DashboardSummary> {\n\tconst { dataSourceTitle, userPrompt } = params;\n\n\tconsole.debug(TOOL_NAME_DASHBOARD_BUILDER, dataSourceTitle, userPrompt);\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 dashboard id\n\tconst newDashboardId = context.toolCallId;\n\n\tlet savedDashboardProps: ExtendedDashboardProps | null = null;\n\n\tlet message = '';\n\tlet isError = false;\n\n\tconst updatedContext: BuildDashboardContext = {\n\t\t...context,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard: (dashboardId: string) => {\n\t\t\t// Prioritize savedDashboardProps in case of subsequent tool calls\n\t\t\tif (savedDashboardProps) {\n\t\t\t\treturn savedDashboardProps;\n\t\t\t}\n\t\t\tif (dashboardId && context.retrieveDashboard) {\n\t\t\t\treturn context.retrieveDashboard(dashboardId);\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsaveDashboard: (dashboardProps: ExtendedDashboardProps) => {\n\t\t\tcontext.saveDashboard?.(dashboardProps);\n\t\t\tsavedDashboardProps = dashboardProps;\n\t\t},\n\t\tgetWidgetList: (widgetIds: string[]) => {\n\t\t\tif (context.getWidgetList) {\n\t\t\t\treturn context\n\t\t\t\t\t.getWidgetList(widgetIds)\n\t\t\t\t\t.map(resetWidgetForDashboard);\n\t\t\t}\n\t\t\treturn [];\n\t\t},\n\t};\n\n\t// Update dashboard summaries with latest changes from context\n\t// (dashboard tool call results may be manually updated by the user using the UI)\n\tconst updatedDashboardSummaries: DashboardSummary[] = (\n\t\tcontext.dashboardSummaries ?? []\n\t).map((dashboardSummary) => {\n\t\tif (!dashboardSummary.dashboard) {\n\t\t\treturn dashboardSummary;\n\t\t}\n\n\t\tif (context.retrieveDashboard) {\n\t\t\ttry {\n\t\t\t\tconst dashboardProps = context.retrieveDashboard(\n\t\t\t\t\tdashboardSummary.dashboardId,\n\t\t\t\t);\n\t\t\t\tif (dashboardProps) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...dashboardSummary,\n\t\t\t\t\t\tdashboard: getBaseDashboardSummary(\n\t\t\t\t\t\t\tdashboardProps,\n\t\t\t\t\t\t\tdashboardSummary.dashboard\n\t\t\t\t\t\t\t\t?.defaultDataSourceTitle || dataSourceTitle,\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// If loading fails, return original summary\n\t\t\t}\n\t\t}\n\t\treturn dashboardSummary;\n\t});\n\n\tconst systemPrompt = buildContextualSystemPrompt(\n\t\t(context.chartSummaries ?? []).slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t\t// only use the latest chart list summary so that the LLM can focus on the latest recommendations\n\t\t(context.chartListSummaries ?? []).slice(-1),\n\t\tupdatedDashboardSummaries.slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t);\n\n\tconst internalTools = createDashboardTools(updatedContext);\n\n\t// Use createToolsCompletion to let LLM choose and execute the appropriate sub-tool\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\tconst resultForLLM: DashboardSummary = {\n\t\tmessage,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tdashboardId: newDashboardId,\n\t\tdashboard: savedDashboardProps\n\t\t\t? getBaseDashboardSummary(savedDashboardProps, dataSourceTitle)\n\t\t\t: undefined,\n\t};\n\n\treturn resultForLLM;\n}\n","import { z } from 'zod';\nimport { WidgetProps, ChartType } from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport type { OpenAI } from 'openai';\n\n/**\n * Default number of query recommendations to return\n */\nexport const DEFAULT_QUERY_COUNT = 4;\n\n/**\n * Schema for recommendQueries engine parameters\n */\nexport const recommendQueriesSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tqueryCount: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Number of recommended queries to return.'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'User prompt or context to guide recommendations. Used to filter and prioritize relevant queries.',\n\t\t),\n\texistingWidgets: z\n\t\t.array(z.string())\n\t\t.optional()\n\t\t.describe(\n\t\t\t'List of existing widget titles/descriptions to avoid duplicates when adding to existing dashboard.',\n\t\t),\n});\n\n/**\n * Context interface for recommendQueriesEngine\n */\nexport interface RecommendQueriesContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\t/** Whether NLQ V3 is enabled */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\n}\n\n/**\n * Query and chart recommendation type\n */\nexport type QueryAndChartRecommendation = {\n\tdetailedDescription: string;\n\tnlqPrompt: string;\n} & WidgetProps;\n\n/**\n * Result from recommendQueriesEngine\n */\nexport interface RecommendQueriesResult {\n\t/**\n\t * List of query and chart recommendations\n\t */\n\trecommendations: QueryAndChartRecommendation[];\n}\n\n/**\n * Callback for receiving intermediate recommendations (before chart generation)\n */\nexport type OnIntermediateResultsCallback = (\n\trecommendations: QueryAndChartRecommendation[],\n) => void;\n\n/**\n * Chart type keywords mapping for extraction from user prompts\n */\nexport const CHART_TYPE_KEYWORDS: Record<string, ChartType> = {\n\tbar: 'bar',\n\tcolumn: 'column',\n\tline: 'line',\n\tpie: 'pie',\n\tscatter: 'scatter',\n\tarea: 'area',\n\tfunnel: 'funnel',\n\tpolar: 'polar',\n\ttreemap: 'treemap',\n\tsunburst: 'sunburst',\n\tboxplot: 'boxplot',\n};\n","import { z } from 'zod';\nimport { ChartType } from '@sisense/sdk-ui';\nimport { getQueryRecommendationsLight } from '@/services/nlq/nlq-service';\nimport { getDataSourceSchema } from '@/services/data-models/data-models-service';\nimport { generateChart } from '@/engines/chart-builder/create-chart/create-chart';\nimport { TOOL_NAME_RECOMMEND_QUERIES } from '@/constants';\nimport {\n\trecommendQueriesSchema,\n\tRecommendQueriesContext,\n\tRecommendQueriesResult,\n\tQueryAndChartRecommendation,\n\tOnIntermediateResultsCallback,\n\tDEFAULT_QUERY_COUNT,\n\tCHART_TYPE_KEYWORDS,\n} from './types';\n\n/**\n * Helper function to extract chart type preference from user prompt\n */\nexport function extractChartTypeFromPrompt(\n\tuserPrompt: string,\n): ChartType | undefined {\n\tconst lowerPrompt = userPrompt.toLowerCase();\n\tfor (const [keyword, chartType] of Object.entries(CHART_TYPE_KEYWORDS)) {\n\t\tif (lowerPrompt.includes(keyword)) {\n\t\t\treturn chartType;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Helper function to build context-aware user prompt\n */\nexport function buildContextualPrompt(\n\tuserPrompt?: string,\n\texistingWidgets?: string[],\n): string | undefined {\n\tif (!userPrompt && !existingWidgets?.length) {\n\t\treturn undefined;\n\t}\n\n\tlet contextualPrompt = '';\n\n\t// Add the user's original prompt\n\tif (userPrompt) {\n\t\tcontextualPrompt = userPrompt;\n\t}\n\n\t// Add context about existing widgets to avoid duplicates\n\tif (existingWidgets?.length) {\n\t\t// also unique the existing widgets\n\t\tconst uniqueExistingWidgets = [...new Set(existingWidgets)];\n\t\tconst widgetContext = `DO NOT recommend queries that are similar to these:\\n${uniqueExistingWidgets\n\t\t\t.map((widget) => `- ${widget}`)\n\t\t\t.join('\\n')}`;\n\t\tcontextualPrompt = contextualPrompt\n\t\t\t? `<INSTRUCTIONS>${widgetContext}</INSTRUCTIONS>\\n\\n<USER-PROMPT> ${contextualPrompt}</USER-PROMPT>`\n\t\t\t: widgetContext;\n\t}\n\n\treturn contextualPrompt;\n}\n\n/**\n * Standalone recommend queries engine - completely decoupled from any UI or store\n * @param params - The parameters for getting query recommendations\n * @param context - Context with tool call ID for tracking\n * @param onIntermediateResults - Optional callback for intermediate results (before chart generation)\n * @returns The recommendations result with query and chart recommendations\n */\nexport async function recommendQueriesEngine(\n\tparams: z.infer<typeof recommendQueriesSchema>,\n\tcontext: RecommendQueriesContext,\n\tonIntermediateResults?: OnIntermediateResultsCallback,\n): Promise<RecommendQueriesResult> {\n\tconst {\n\t\tdataSourceTitle,\n\t\tqueryCount = DEFAULT_QUERY_COUNT,\n\t\tuserPrompt,\n\t\texistingWidgets,\n\t} = params;\n\n\tconst defaultErrorMessage = 'Error: Failed to get recommended queries';\n\n\tconsole.debug(\n\t\tTOOL_NAME_RECOMMEND_QUERIES,\n\t\tdataSourceTitle,\n\t\tcontext.toolCallId,\n\t);\n\n\t// Validate required parameters\n\tif (!dataSourceTitle) {\n\t\tthrow new Error('Error: Please specify data source title');\n\t}\n\n\t// Verify data source exists\n\tconst dataSources = await getDataSourceSchema(\n\t\tdataSourceTitle,\n\t\tcontext.httpClient,\n\t);\n\tif (!dataSources) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Make sure to create a model first',\n\t\t);\n\t}\n\n\t// Build contextual prompt that includes user intent and existing widgets\n\tconst contextualPrompt = buildContextualPrompt(userPrompt, existingWidgets);\n\n\tconst recommendedQueries = await getQueryRecommendationsLight(\n\t\tdataSourceTitle,\n\t\t{\n\t\t\tnumOfRecommendations: queryCount,\n\t\t\tuserPrompt: contextualPrompt,\n\t\t},\n\t\tcontext.httpClient,\n\t);\n\n\tif (!recommendedQueries) {\n\t\tthrow new Error(defaultErrorMessage);\n\t}\n\n\t// Notify intermediate results (queries without charts) if callback provided\n\tif (onIntermediateResults && recommendedQueries.length > 0) {\n\t\tconst intermediateResults = recommendedQueries.map((query) => ({\n\t\t\tnlqPrompt: query.nlqPrompt,\n\t\t\tdetailedDescription: query.detailedDescription,\n\t\t})) as QueryAndChartRecommendation[];\n\t\tonIntermediateResults(intermediateResults);\n\t}\n\n\t// Extract chart type preference from user prompt\n\tconst preferredChartType = userPrompt\n\t\t? extractChartTypeFromPrompt(userPrompt)\n\t\t: undefined;\n\n\t// Generate chart for each recommended query\n\tconst recommendedCharts = await Promise.all(\n\t\trecommendedQueries.map(async (query) => {\n\t\t\t// query.nlqPrompt is already data-focused, use it as queryPrompt\n\t\t\t// Create a simple chartPrompt based on preferred chart type or generic\n\t\t\tconst chartPrompt = preferredChartType\n\t\t\t\t? `Create a ${preferredChartType} chart visualization`\n\t\t\t\t: 'Create a chart visualization';\n\n\t\t\tconst chartWidgetProps = await generateChart(\n\t\t\t\t{\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tqueryPrompt: query.nlqPrompt,\n\t\t\t\t\tchartPrompt,\n\t\t\t\t\tchartType: preferredChartType,\n\t\t\t\t\tchartTitle: query.nlqPrompt,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttoolCallId: context.toolCallId,\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tisNlqV3Enabled: context.isNlqV3Enabled,\n\t\t\t\t\thttpClient: context.httpClient,\n\t\t\t\t\topenAIClient: context.openAIClient,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\t...chartWidgetProps,\n\t\t\t\tnlqPrompt: query.nlqPrompt,\n\t\t\t\tdetailedDescription: query.detailedDescription,\n\t\t\t};\n\t\t}),\n\t);\n\n\treturn {\n\t\trecommendations: recommendedCharts,\n\t};\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","opt","processSchemaProperties","propertyNames","mode","z","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","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","MAX_DATA_SOURCE_FIELDS_SUMMARY","DEFAULT_LLM","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","queryPrompt","nlqResult","widgetProps","widgetComposer","isChartWidgetProps","generateChartTableFromNlqV3","dataSchema","translationResult","translateQueryJSON","translatedParams","jaql","translateQueryToJaql","convertDataSource","generateChartTable","isNlqV3Enabled","generateChart","chartPrompt","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","buildSystemPromptForDataOptions","filteredSchema","additionalInstructions","currentDataOptions","updateChartDataOptionsHelper","currentChartType","baseSchema","responseDataOptions","mergedDataOptions","mergeDataOptions","original","aiResponse","merged","dataOptionsKey","incomingList","originalList","originalItem","originalName","updatedItem","updateChartDataOptions","createUpdateChartDataOptionsTool","updateChartTypeOfMeasuresConfig","updateChartSortingConfig","updateTrendAndForecastConfig","updateOtherChartDataOptionsConfig","updateChartTypeOfMeasures","updateChartSorting","updateTrendAndForecast","updateOtherChartDataOptions","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","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","getDataSourceFieldsSummary","totalFields","tableCount","f","truncatedFields","isTruncated","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","getDashboardsEngine","getDashboardsSchema","buildDashboardSchema","createDashboardSchema","loadExistingFusionDashboardSchema","updateDashboardSchema","addDashboardWidgetsSchema","createChartWidgetForDashboardSchema","updateChartWidgetForDashboardSchema","addDashboardFiltersSchema","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","createDashboard","widgetIdsToAdd","getWidgetList","saveDashboard","newWidgetList","loadExistingFusionDashboard","fusionDashboard","updateDashboard","retrieveDashboard","currentDashboard","addDashboardWidgets","FILTER_FACTORY_TYPES","MEASURE_FACTORY_TYPES","generateFilterSystemPrompt","getFactoryFunctionsMap","factoryName","factoryObject","functionsMap","prefix","nestedFunctionsMap","nestedKey","measureFactoryFunctionsMap","measureFactory","filterFactoryFunctionsMap","filterFactory","executeFunction","functionPath","createAttribute","attributeName","dataFields","dataField","createAttributeHelper","processArg","arg","processNode","parsedObject","processedArgs","postProcessFilter","filter","attribute","isMembersFilter","granularity","member","postProcessFilters","isFilterRelations","translateFiltersFromJsonFunctionCall","filtersJson","parsedJson","manipulateDashboardFilters","fullUserPrompt","response","explanation","mergeFiltersOrFilterRelations","addDashboardFilters","createChartWidgetForDashboard","toolCallId","isNewDashboard","newChartWidgetProps","chartSummary","resetChartWidgetProps","updateChartWidgetForDashboard","widgetIndex","updatedWidgetProps","getBaseDashboardSummary","isPivotTableWidgetProps","createDashboardTool","createDashboardTools","chartListSummaries","dashboardSummaries","buildDashboardEngine","newDashboardId","savedDashboardProps","updatedDashboardSummaries","dashboardSummary","DEFAULT_QUERY_COUNT","recommendQueriesSchema","CHART_TYPE_KEYWORDS","extractChartTypeFromPrompt","lowerPrompt","keyword","buildContextualPrompt","existingWidgets","contextualPrompt","widgetContext","recommendQueriesEngine","onIntermediateResults","queryCount","defaultErrorMessage","recommendedQueries","intermediateResults","query","preferredChartType","createElasticube","body","data","getCSVSchemaDetails","filePath","fileName","getPerspectiveOid","elasticubeOid","addDataSet","perspectiveOid","tableId","oid","schemaName","buildElasticube","buildStatus","addRelation","getElasticubes","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,QAA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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,96,110]}
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/constants.ts","../src/services/llm/llm-consumption-service.ts","../src/utils/user-action-tracking.ts","../src/utils/create-custom-fetch.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/build-query/build-query-engine.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/engines/chart-builder/chart-builder-service.ts","../src/engines/chart-builder/chart-builder-engine.ts","../src/engines/build-query/types.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","../node_modules/yaml/browser/dist/nodes/identity.js","../node_modules/yaml/browser/dist/visit.js","../node_modules/yaml/browser/dist/doc/directives.js","../node_modules/yaml/browser/dist/doc/anchors.js","../node_modules/yaml/browser/dist/doc/applyReviver.js","../node_modules/yaml/browser/dist/nodes/toJS.js","../node_modules/yaml/browser/dist/nodes/Node.js","../node_modules/yaml/browser/dist/nodes/Alias.js","../node_modules/yaml/browser/dist/nodes/Scalar.js","../node_modules/yaml/browser/dist/doc/createNode.js","../node_modules/yaml/browser/dist/nodes/Collection.js","../node_modules/yaml/browser/dist/stringify/stringifyComment.js","../node_modules/yaml/browser/dist/stringify/foldFlowLines.js","../node_modules/yaml/browser/dist/stringify/stringifyString.js","../node_modules/yaml/browser/dist/stringify/stringify.js","../node_modules/yaml/browser/dist/stringify/stringifyPair.js","../node_modules/yaml/browser/dist/log.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js","../node_modules/yaml/browser/dist/nodes/addPairToJSMap.js","../node_modules/yaml/browser/dist/nodes/Pair.js","../node_modules/yaml/browser/dist/stringify/stringifyCollection.js","../node_modules/yaml/browser/dist/nodes/YAMLMap.js","../node_modules/yaml/browser/dist/schema/common/map.js","../node_modules/yaml/browser/dist/nodes/YAMLSeq.js","../node_modules/yaml/browser/dist/schema/common/seq.js","../node_modules/yaml/browser/dist/schema/common/string.js","../node_modules/yaml/browser/dist/schema/common/null.js","../node_modules/yaml/browser/dist/schema/core/bool.js","../node_modules/yaml/browser/dist/stringify/stringifyNumber.js","../node_modules/yaml/browser/dist/schema/core/float.js","../node_modules/yaml/browser/dist/schema/core/int.js","../node_modules/yaml/browser/dist/schema/core/schema.js","../node_modules/yaml/browser/dist/schema/json/schema.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/float.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/int.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/set.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js","../node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js","../node_modules/yaml/browser/dist/schema/tags.js","../node_modules/yaml/browser/dist/schema/Schema.js","../node_modules/yaml/browser/dist/stringify/stringifyDocument.js","../node_modules/yaml/browser/dist/doc/Document.js","../node_modules/yaml/browser/dist/parse/lexer.js","../node_modules/yaml/browser/dist/public-api.js","../src/engines/data-source-fields/data-source-fields-engine.ts","../src/engines/data-source-fields/types.ts","../src/services/dashboards/fusion-dashboards-service.ts","../src/engines/dashboards/dashboards-engine.ts","../src/engines/dashboards/types.ts","../src/engines/dashboard-builder/types.ts","../node_modules/fast-deep-equal/index.js","../src/services/dashboards/dashboards-service.ts","../src/engines/dashboard-builder/create-dashboard.ts","../src/engines/dashboard-builder/load-existing-fusion-dashboard.ts","../src/engines/dashboard-builder/update-dashboard.ts","../src/engines/dashboard-builder/add-dashboard-widgets.ts","../src/engines/dashboard-builder/dashboard-filters/filter-factory-types.ts","../src/engines/dashboard-builder/dashboard-filters/measure-factory-types.ts","../src/engines/dashboard-builder/dashboard-filters/dashboard-filters-system-prompt.ts","../src/engines/dashboard-builder/dashboard-filters/translate-filters.ts","../src/engines/dashboard-builder/dashboard-filters/manipulate-dashboard-filters.ts","../src/engines/dashboard-builder/add-dashboard-filters.ts","../src/engines/dashboard-builder/create-chart-widget.ts","../src/engines/dashboard-builder/update-chart-widget.ts","../src/engines/dashboard-builder/dashboard-builder-service.ts","../src/engines/dashboard-builder/dashboard-builder-engine.ts","../src/engines/recommend-queries/types.ts","../src/engines/recommend-queries/recommend-queries-engine.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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,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\tlet typeName = unwrapped?._def?.typeName;\n\twhile (typeName === 'ZodOptional' || typeName === 'ZodNullable') {\n\t\tunwrapped = (\n\t\t\tunwrapped as z.ZodOptional<any> | z.ZodNullable<any>\n\t\t).unwrap();\n\t\ttypeName = unwrapped?._def?.typeName;\n\t}\n\n\t// Check arrays - recurse into element type\n\tif (typeName === 'ZodArray') {\n\t\treturn hasKeptProperties(\n\t\t\t(unwrapped as z.ZodArray<any>).element,\n\t\t\tpropertiesToKeep,\n\t\t);\n\t}\n\n\t// Check unions - any option has kept properties\n\tif (typeName === 'ZodUnion') {\n\t\treturn (unwrapped as z.ZodUnion<any>).options.some(\n\t\t\t(opt: z.ZodTypeAny) => hasKeptProperties(opt, propertiesToKeep),\n\t\t);\n\t}\n\n\t// Check objects - any property name matches or descendants match\n\tif (typeName === 'ZodObject') {\n\t\tfor (const [key, value] of Object.entries(\n\t\t\t(unwrapped as z.ZodObject<any>).shape,\n\t\t)) {\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\tconst typeName = schema?._def?.typeName;\n\n\t// Handle optionals - recurse and rewrap\n\tif (typeName === 'ZodOptional') {\n\t\treturn z.ZodOptional.create(\n\t\t\tprocessSchemaProperties(\n\t\t\t\t(schema as z.ZodOptional<any>).unwrap(),\n\t\t\t\tpropertyNames,\n\t\t\t\tmode,\n\t\t\t),\n\t\t);\n\t}\n\n\t// Handle nullables - recurse and rewrap\n\tif (typeName === 'ZodNullable') {\n\t\treturn z.ZodNullable.create(\n\t\t\tprocessSchemaProperties(\n\t\t\t\t(schema as z.ZodNullable<any>).unwrap(),\n\t\t\t\tpropertyNames,\n\t\t\t\tmode,\n\t\t\t),\n\t\t);\n\t}\n\n\t// Handle arrays - recurse into element type\n\tif (typeName === 'ZodArray') {\n\t\tconst processedElement = processSchemaProperties(\n\t\t\t(schema as z.ZodArray<any>).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 (typeName === 'ZodUnion') {\n\t\tconst processedOptions = (schema as z.ZodUnion<any>).options.map(\n\t\t\t(opt: z.ZodTypeAny) =>\n\t\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 (typeName === 'ZodObject') {\n\t\tconst filteredEntries: [string, z.ZodTypeAny][] = [];\n\n\t\tfor (const [key, value] of Object.entries(\n\t\t\t(schema as z.ZodObject<any>).shape,\n\t\t)) {\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 * Uses _def.typeName instead of instanceof because instanceof is unreliable\n * for classes extending built-ins (like Error, Array) when code is downleveled to ES5.\n * See: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n */\nexport const zodToReadableType = (\n\tschema: z.ZodTypeAny,\n\tdepth = 0,\n\tpropName?: string,\n\tisOptional?: boolean,\n): string => {\n\tconst typeName = schema?._def?.typeName;\n\n\t// Optionals\n\tif (typeName === 'ZodOptional') {\n\t\treturn zodToReadableType(\n\t\t\t(schema as z.ZodOptional<any>).unwrap(),\n\t\t\tdepth,\n\t\t\tpropName,\n\t\t\ttrue,\n\t\t);\n\t}\n\t// Nullables\n\tif (typeName === 'ZodNullable') {\n\t\treturn (\n\t\t\tzodToReadableType(\n\t\t\t\t(schema as z.ZodNullable<any>).unwrap(),\n\t\t\t\tdepth,\n\t\t\t\tpropName,\n\t\t\t\tisOptional,\n\t\t\t) + ' | null'\n\t\t);\n\t}\n\t// Array\n\tif (typeName === 'ZodArray') {\n\t\tconst inner = zodToReadableType(\n\t\t\t(schema as z.ZodArray<any>).element,\n\t\t\tdepth,\n\t\t);\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 (typeName === 'ZodObject') {\n\t\tconst props = Object.entries((schema as z.ZodObject<any>).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 (typeName === 'ZodEnum') {\n\t\tconst opts = (schema as z.ZodEnum<any>).options\n\t\t\t.map((o: string) => `\"${o}\"`)\n\t\t\t.join(' | ');\n\t\treturn opts + (schema.description ? ` - ${schema.description}` : '');\n\t}\n\t// Union\n\tif (typeName === 'ZodUnion') {\n\t\treturn (schema as z.ZodUnion<any>).options\n\t\t\t.map((opt: z.ZodTypeAny) => zodToReadableType(opt, depth))\n\t\t\t.join(' | ');\n\t}\n\t// Literal\n\tif (typeName === 'ZodLiteral') {\n\t\treturn JSON.stringify((schema as z.ZodLiteral<any>).value);\n\t}\n\t// String, Number, Boolean\n\tif (typeName === 'ZodString') return 'string';\n\tif (typeName === 'ZodNumber') return 'number';\n\tif (typeName === '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';\nimport { QueryResult } from '../build-query/types';\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 queryIdSchema = z\n\t.string()\n\t.nullable()\n\t.default(null)\n\t.describe(\n\t\t'The ID of the build query to use. This ID is created by the build query tool.',\n\t);\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. Pass the user prompt exactly as received - do NOT transform or modify it. The chart builder logic will handle prompt splitting internally.\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\nexport const buildChartSchemaNaturalConversation = 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. Pass the user prompt exactly as received - do NOT transform or modify it. The chart builder logic will handle prompt splitting internally.\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\tqueryId: z\n\t\t.string()\n\t\t.nullable()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'When the chart is based on a prior query result, pass its queryId; otherwise omit or pass null.',\n\t\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 = z.object({\n\tqueryPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Data-focused query prompt for retrieving data. Be faithful to the original user prompt but remove chart-specific instructions (e.g., \"bar chart\", \"use X as dimension\"). Focus on the data intent - the system will extract specific dimensions, measures, and filters automatically.',\n\t\t),\n\tchartPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'Visualization-focused prompt for chart recommendations. Be faithful to the original user prompt and keep chart-specific instructions. Do not infer the chart type from the user prompt.',\n\t\t),\n\tchartType: nullableChartType,\n\tchartTitle: z.string().describe('The new chart title'),\n\tqueryId: queryIdSchema,\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 (required)\n\t */\n\tdataSourceTitle: string;\n\t/** Chart summaries to be used as context */\n\tchartSummaries?: ChartSummary[];\n\t/** query results to be used as context */\n\tquerySummaries?: QueryResult[];\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/**\n\t * Retrieve a query result by its ID\n\t * @param queryId - The ID of the query to retrieve\n\t * @returns The query result, or null if not found\n\t */\n\tretrieveQuery?: (queryId: string) => QueryResult | null;\n\t/** Whether NLQ V3 is enabled */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\n\t/** ID of a prior query result when this chart uses that query; otherwise null/undefined */\n\tqueryId?: string | null;\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';\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 * Extracts HTTP status code from various error shapes (Axios, fetch, custom).\n */\nexport function getHttpErrorStatus(error: unknown): number | undefined {\n\tconst err = error as Record<string, unknown>;\n\tconst raw =\n\t\terr?.status ??\n\t\terr?.statusCode ??\n\t\t(err?.response as Record<string, unknown>)?.status;\n\treturn raw !== undefined ? Number(raw) : undefined;\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';\nexport const TOOL_NAME_BUILD_QUERY = 'buildQuery';\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\n// Limit the number of fields in data source fields summary to prevent token overflow\nexport const MAX_DATA_SOURCE_FIELDS_SUMMARY = 200;\n\n// This is a placeholder for the backend to override with the actual model to use\nexport const DEFAULT_LLM = 'LLM_PLACEHOLDER';\n\n// User action tracking headers (W3C traceparent, quota, etc.)\nexport const HEADER_USER_ACTION_ID = 'x-user-action-id';\nexport const HEADER_TRACEPARENT = 'traceparent';\nexport const HEADER_INTERFACE_NAME = 'x-interface-name';\nexport const HEADER_FEATURE_NAME = 'x-feature-name';\nexport const HEADER_QUOTA_ID = 'x-quota-id';\n\nexport const ALLOWED_HEADERS = [\n\tHEADER_USER_ACTION_ID,\n\tHEADER_TRACEPARENT,\n\tHEADER_INTERFACE_NAME,\n\tHEADER_FEATURE_NAME,\n\tHEADER_QUOTA_ID,\n];\n","import { getHttpClient } from '@/singleton-clients';\nimport { getHttpErrorStatus } from '@/utils/http-client';\n\nconst CONSUMPTION_CAPTURE_PATH = 'api/v2/ai/llm/consumption/capture';\nconst CONSUMPTION_REPORT_PATH = 'api/v2/ai/llm/consumption/report';\n\nexport class QuotaExceededError extends Error {\n\tconstructor(message = 'Quota exceeded') {\n\t\tsuper(message);\n\t\tthis.name = 'QuotaExceededError';\n\t}\n}\n\n/**\n * Captures consumption of LLM tokens.\n * @param requestOptions - Optional request options (e.g. from withTrackingHeaders()) for user-action tracking headers.\n * @returns The capture UUID if successful, undefined otherwise.\n */\nexport async function captureConsumption(\n\trequestOptions?: RequestInit,\n): Promise<string | undefined> {\n\tconst client = getHttpClient();\n\n\ttry {\n\t\tconst response = await client.post<{ captureUuid?: string }>(\n\t\t\tCONSUMPTION_CAPTURE_PATH,\n\t\t\t{},\n\t\t\trequestOptions ?? {},\n\t\t);\n\n\t\treturn response?.captureUuid;\n\t} catch (error: unknown) {\n\t\tconst status = getHttpErrorStatus(error);\n\n\t\tif (status === 429) {\n\t\t\tthrow new QuotaExceededError();\n\t\t}\n\n\t\tif (status === 400 || status === 422) {\n\t\t\tconst message =\n\t\t\t\t(error as Error)?.message ??\n\t\t\t\t(status === 422\n\t\t\t\t\t? 'Request validation failed (e.g. missing x-feature-name or x-interface-name). Ensure tracking headers are passed.'\n\t\t\t\t\t: 'The LLM configuration is missing. Reach out to your Admin to configure your LLM provider.');\n\t\t\tconsole.debug(`LLM consumption capture skipped: ${message}`);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconsole.error('Error capturing consumption:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Reports consumption of LLM tokens to the backend.\n * Fire-and-forget: failures are non-critical and are silently ignored.\n * @param quotaId - The capture UUID from captureConsumption.\n * @param requestOptions - Optional request options (e.g. from withTrackingHeaders()) for user-action tracking headers.\n */\nexport function reportConsumption(\n\tquotaId: string,\n\trequestOptions?: RequestInit,\n): void {\n\tconst client = getHttpClient();\n\tconst url = `${CONSUMPTION_REPORT_PATH}?consumptionId=${encodeURIComponent(\n\t\tquotaId,\n\t)}`;\n\tclient.post(url, {}, requestOptions ?? {}).catch(() => {\n\t\t/* Fire-and-forget: consumption report failures are non-critical */\n\t});\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 {\n\tHEADER_FEATURE_NAME,\n\tHEADER_INTERFACE_NAME,\n\tHEADER_QUOTA_ID,\n\tHEADER_TRACEPARENT,\n\tHEADER_USER_ACTION_ID,\n} from '@/constants';\nimport {\n\tcaptureConsumption,\n\treportConsumption,\n} from '@/services/llm/llm-consumption-service';\nimport { nanoidHex, nanoidUUIDv4 } from './id-utils';\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[HEADER_USER_ACTION_ID]: string;\n\t[HEADER_TRACEPARENT]: string;\n\t[HEADER_INTERFACE_NAME]: string;\n\t[HEADER_FEATURE_NAME]: string;\n\t[HEADER_QUOTA_ID]: string;\n}\n\nclass UserActionContext {\n\tprivate currentActionId: string | null = null;\n\tprivate currentTraceparent: string | null = null;\n\tprivate interfaceName: string | null = null;\n\tprivate featureName: string | null = null;\n\tprivate quotaId: string | null = null;\n\n\tprivate _ensureContext(\n\t\tinterfaceName?: string,\n\t\tfeatureName?: string,\n\t): UserActionHeaders {\n\t\tthis.currentActionId = generateUserActionId();\n\t\tthis.currentTraceparent = generateTraceparent();\n\t\tthis.interfaceName = interfaceName ?? null;\n\t\tthis.featureName = featureName ?? null;\n\t\treturn this._buildHeaders();\n\t}\n\n\tprivate _buildHeaders(): UserActionHeaders {\n\t\treturn {\n\t\t\t[HEADER_USER_ACTION_ID]: this.currentActionId ?? '',\n\t\t\t[HEADER_TRACEPARENT]: this.currentTraceparent ?? '',\n\t\t\t[HEADER_INTERFACE_NAME]: this.interfaceName ?? '',\n\t\t\t[HEADER_FEATURE_NAME]: this.featureName ?? '',\n\t\t\t[HEADER_QUOTA_ID]: this.quotaId ?? '',\n\t\t};\n\t}\n\n\tgetHeaders(): UserActionHeaders {\n\t\tif (!this.currentActionId || !this.currentTraceparent) {\n\t\t\treturn this._ensureContext();\n\t\t}\n\t\treturn this._buildHeaders();\n\t}\n\n\tasync startAction(\n\t\tinterfaceName?: string,\n\t\tfeatureName?: string,\n\t): Promise<UserActionHeaders> {\n\t\tthis._ensureContext(interfaceName, featureName);\n\t\ttry {\n\t\t\tconst captureUuid = await captureConsumption(withTrackingHeaders());\n\t\t\tif (captureUuid) {\n\t\t\t\tthis.quotaId = captureUuid;\n\t\t\t}\n\t\t\treturn this._buildHeaders();\n\t\t} catch (e) {\n\t\t\tthis.currentActionId = null;\n\t\t\tthis.currentTraceparent = null;\n\t\t\tthis.interfaceName = null;\n\t\t\tthis.featureName = null;\n\t\t\tthis.quotaId = null;\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tendAction(): void {\n\t\tif (this.quotaId) {\n\t\t\treportConsumption(this.quotaId, withTrackingHeaders());\n\t\t}\n\t\tthis.currentActionId = null;\n\t\tthis.currentTraceparent = null;\n\t\tthis.interfaceName = null;\n\t\tthis.featureName = null;\n\t\tthis.quotaId = null;\n\t}\n}\n\nconst userActionContext = new UserActionContext();\n\nexport const startUserAction = (interfaceName?: string, featureName?: string) =>\n\tuserActionContext.startAction(interfaceName, featureName);\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 = getUserActionHeaders();\n\tconst normalizedHeaders = normalizeHeaders(options.headers);\n\tconst headers: Record<string, string> = {\n\t\t...DEFAULT_HTTP_CLIENT_HEADERS,\n\t\t...normalizedHeaders,\n\t\t...trackingHeaders,\n\t};\n\treturn {\n\t\t...options,\n\t\theaders,\n\t};\n}\n\nexport const endUserAction = () => userActionContext.endAction();\n\n/**\n * Wraps an async function with user-action tracking (capture at start, report at end).\n * Use for standalone engine calls (e.g., from MCP Server) when tracing and consumption tracking are required.\n * @param interfaceName - e.g. 'MCP'\n * @param featureName - e.g. 'BUILD-CHART'\n * @param fn - The async function to execute\n * @returns The result of fn\n */\nexport async function runWithUserAction<T>(\n\tinterfaceName: string,\n\tfeatureName: string,\n\tfn: () => Promise<T>,\n): Promise<T> {\n\tlet started = false;\n\ttry {\n\t\tawait startUserAction(interfaceName, featureName);\n\t\tstarted = true;\n\t\treturn await fn();\n\t} finally {\n\t\tif (started) {\n\t\t\tendUserAction();\n\t\t}\n\t}\n}\n","import { HttpClient } from '@sisense/sdk-rest-client';\nimport { ALLOWED_HEADERS } from '@/constants';\nimport { getUserActionHeaders } from './user-action-tracking';\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 * and sets the user action tracking headers.\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\toriginalHeaders.forEach((value, key) => {\n\t\t\t\tconst lowerKey = key.toLowerCase();\n\t\t\t\t// Skip tracking headers - we set them from getUserActionHeaders()\n\t\t\t\tif (ALLOWED_HEADERS.includes(lowerKey)) return;\n\t\t\t\t// Sisense server doesn't allow x- headers except tracking\n\t\t\t\tif (lowerKey.startsWith('x-')) return;\n\t\t\t\t// httpClient sets its own authorization header (unless bearer auth)\n\t\t\t\tif (!isBearerAuth && lowerKey === 'authorization') return;\n\t\t\t\theaders.set(key, value);\n\t\t\t});\n\t\t}\n\n\t\tconst trackingHeaders = getUserActionHeaders();\n\t\tALLOWED_HEADERS.forEach((header) => {\n\t\t\theaders.set(header, trackingHeaders[header]);\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 './create-custom-fetch';\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';\nimport { DEFAULT_LLM } from '@/constants';\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 = DEFAULT_LLM,\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 = DEFAULT_LLM,\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\tconst mapping = updatedRecommendations.axesMapping as any;\n\t\t\tif (mapping.value && mapping.value.length > 1) {\n\t\t\t\tmapping.value = [mapping.value[0]];\n\t\t\t}\n\t\t\tif (mapping.secondary && mapping.secondary.length > 1) {\n\t\t\t\tmapping.secondary = [mapping.secondary[0]];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\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","import { z } from 'zod';\nimport { getNlqV3Result } from '@/services/nlq/nlq-service';\nimport { getHttpClient } from '@/singleton-clients';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { TOOL_NAME_BUILD_QUERY } from '@/constants';\nimport { buildQuerySchema, BuildQueryContext, QueryResult } from './types';\n\n/**\n * Standalone build query engine - completely decoupled from any UI or store\n * Converts a natural language query into an NLQ result and dataset\n * @param params - The parameters containing data source title and query prompt\n * @param context - Context with tool call ID and optional httpClient\n * @returns The query result with queryId, nlqResult, and dataset\n */\nexport async function buildQueryEngine(\n\tparams: z.infer<typeof buildQuerySchema>,\n\tcontext: BuildQueryContext,\n): Promise<QueryResult> {\n\tconst { dataSourceTitle, queryPrompt } = params;\n\n\tconsole.debug(\n\t\tTOOL_NAME_BUILD_QUERY,\n\t\tdataSourceTitle,\n\t\tqueryPrompt,\n\t\tcontext.toolCallId,\n\t);\n\n\tconst httpClient = context.httpClient ?? getHttpClient();\n\n\tconst nlqResult = await getNlqV3Result(\n\t\tdataSourceTitle,\n\t\t{ text: queryPrompt, forceGeneration: true },\n\t\thttpClient,\n\t);\n\n\tif (!nlqResult?.chartState) {\n\t\tthrow new Error(\n\t\t\t`Error: Failed to build query for \"${queryPrompt}\". Chart state not found. Try rephrasing or check data source \"${dataSourceTitle}\".`,\n\t\t);\n\t}\n\n\tconst dataSchema = nlqResult.dataSchema;\n\tconst dataset =\n\t\t(nlqResult as { dataset?: unknown }).dataset ??\n\t\t(dataSchema as { dataset?: unknown } | undefined)?.dataset ??\n\t\t'There was an error executing the query, please rephrase it or simplify it into multiple queries';\n\n\tconst queryId = context.generateQueryId?.() ?? nanoidHex(12);\n\tconst title = (nlqResult.chartState as { title?: string }).title ?? '';\n\n\treturn {\n\t\tqueryId,\n\t\ttitle,\n\t\tnlqResult,\n\t\tdataset,\n\t};\n}\n","// Store removed - config injected via params\nimport { ExtendedChartWidgetProps } from '../types';\nimport {\n\ttranslateQueryFromJSON,\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 {\n\tgetNlqResultLight,\n\ttype NlqV3Result,\n} from '@/services/nlq/nlq-service';\nimport { buildQueryEngine } from '../../build-query/build-query-engine';\nimport { QueryResult } from '../../build-query/types';\nconst generateChartTableFromNlqV2 = async (\n\tdataSourceTitle: string,\n\tqueryPrompt: string,\n\thttpClient?: HttpClient,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst nlqResult = await getNlqResultLight(\n\t\tdataSourceTitle,\n\t\t{\n\t\t\ttext: queryPrompt,\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 || queryPrompt;\n\n\treturn widgetProps;\n};\n\nconst generateChartTableFromNlqV3 = async (\n\tdataSourceTitle: string,\n\tqueryPrompt: string,\n\thttpClient?: HttpClient,\n\tqueryId?: string | null,\n\tretrieveQuery?: (queryId: string) => QueryResult | null,\n): Promise<ExtendedChartWidgetProps> => {\n\ttry {\n\t\tlet nlqResult: NlqV3Result | null;\n\t\tlet chartTitle: string = queryPrompt;\n\t\tif (queryId && retrieveQuery) {\n\t\t\t// use the query id to get the nlq result from context (Zustand store)\n\t\t\tconst queryResult = retrieveQuery(queryId);\n\t\t\tif (!queryResult) {\n\t\t\t\tthrow new Error('Error: Failed to get query result.');\n\t\t\t}\n\t\t\tnlqResult = queryResult.nlqResult;\n\t\t\tchartTitle = queryResult.title || queryPrompt;\n\t\t} else {\n\t\t\t// use buildQueryEngine for single source of truth (no duplication with buildQuery tool)\n\t\t\tconst queryResult = await buildQueryEngine(\n\t\t\t\t{ dataSourceTitle, queryPrompt },\n\t\t\t\t{\n\t\t\t\t\ttoolCallId: 'chart-builder-internal',\n\t\t\t\t\thttpClient,\n\t\t\t\t},\n\t\t\t);\n\t\t\tnlqResult = queryResult.nlqResult;\n\t\t\tchartTitle = queryResult.title || queryPrompt;\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 = translateQueryFromJSON({\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: chartTitle,\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: chartTitle,\n\t\t\t\tnlqPrompt: chartTitle,\n\t\t\t\tuserMsg: chartTitle,\n\t\t\t\tqueryTitle: chartTitle,\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\tqueryPrompt,\n\t\t\thttpClient,\n\t\t);\n\t}\n};\n\nexport const generateChartTable = async (\n\tdataSourceTitle: string,\n\tqueryPrompt: string,\n\tisNlqV3Enabled?: boolean,\n\thttpClient?: HttpClient,\n\tqueryId?: string | null,\n\tretrieveQuery?: (queryId: string) => QueryResult | null,\n) => {\n\tif (isNlqV3Enabled) {\n\t\tconsole.debug(\n\t\t\t'Generating chart table from NLQ V3',\n\t\t\tqueryPrompt,\n\t\t\tdataSourceTitle,\n\t\t);\n\t\treturn generateChartTableFromNlqV3(\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\n\t\t\thttpClient,\n\t\t\tqueryId,\n\t\t\tretrieveQuery,\n\t\t);\n\t} else {\n\t\tconsole.debug(\n\t\t\t'Generating chart table from NLQ V2',\n\t\t\tqueryPrompt,\n\t\t\tdataSourceTitle,\n\t\t);\n\t\treturn generateChartTableFromNlqV2(\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\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\tqueryPrompt: string;\n\tchartPrompt: string;\n\tchartType: NullableChartType;\n\tchartTitle: string;\n\tqueryId?: string | null;\n};\n\nexport const generateChart = async (\n\t{\n\t\tdataSourceTitle,\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t\tqueryId,\n\t}: GenerateChartParams,\n\tcontext: BuildChartContext,\n): Promise<ExtendedChartWidgetProps> => {\n\tconst widgetProps = await generateChartTable(\n\t\tdataSourceTitle,\n\t\tqueryPrompt,\n\t\tcontext.isNlqV3Enabled ?? false,\n\t\tcontext.httpClient,\n\t\tqueryId,\n\t\tcontext.retrieveQuery,\n\t);\n\n\tconst dataColumns = (widgetProps.dataOptions as TableDataOptions).columns;\n\n\tconst chartRecommendations = await generateChartRecommendations(\n\t\tchartPrompt,\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 = widgetProps.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{\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t\tqueryId: paramsQueryId,\n\t}: z.infer<typeof createChartSchema>,\n\tcontext: BuildChartContext,\n) => {\n\t// Use queryId from LLM params, or fall back to context (from buildChartSchemaNaturalConversation)\n\t// This determines whether we load chart state from prior query or call NLQ v3\n\tconst queryId = paramsQueryId ?? context.queryId ?? null;\n\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createChart',\n\t\tqueryPrompt,\n\t\tchartPrompt,\n\t\tchartType,\n\t\tchartTitle,\n\t);\n\tconst dataSourceTitle = context.dataSourceTitle;\n\tconst chartId = context.toolCallId;\n\tconst chartWidgetProps = await generateChart(\n\t\t{\n\t\t\tdataSourceTitle,\n\t\t\tqueryPrompt,\n\t\t\tchartPrompt,\n\t\t\tchartType,\n\t\t\tchartTitle,\n\t\t\tqueryId,\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\tvalue: z.array(dataOptionsEditingSchemas.measures),\n\tcategory: 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\tvalue: z.array(dataOptionsEditingSchemas.measures),\n\tcategory: 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});\nexport const scatterChartDataOptionsEditingSchemas = z.object({\n\ty: dataOptionsEditingSchemas.measures,\n\tx: dataOptionsEditingSchemas.measures,\n\tbreakByColor: dataOptionsEditingSchemas.measures,\n\tbreakByPoint: dataOptionsEditingSchemas.dimensions,\n\tsize: dataOptionsEditingSchemas.measures,\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 indicatorDataOptionsEditingSchemas = z.object({\n\tmin: z.array(dataOptionsEditingSchemas.measures),\n\tmax: z.array(dataOptionsEditingSchemas.measures),\n\tsecondary: z.array(dataOptionsEditingSchemas.measures),\n\tvalue: z.array(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: cartesianDataOptionsEditingSchemas,\n\tarea: cartesianDataOptionsEditingSchemas,\n\tcolumn: cartesianDataOptionsEditingSchemas, // 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 {\n\tzodToReadableType,\n\tfilterSchemaProperties,\n\texcludeSchemaProperties,\n} 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\tsystemPrompt: string;\n\tuserPrompt: string;\n\tchartWidgetProps: ExtendedChartWidgetProps;\n};\n\n/**\n * Builds a system prompt for chart data options editing.\n * @param chartWidgetProps - The chart widget props containing current data options\n * @param filteredSchema - The filtered schema for the specific subtool\n * @param additionalInstructions - Optional additional instructions to append to the prompt\n * @returns The complete system prompt string\n */\nexport const buildSystemPromptForDataOptions = (\n\tchartWidgetProps: ExtendedChartWidgetProps,\n\tfilteredSchema: z.ZodTypeAny,\n\tadditionalInstructions?: string,\n): string => {\n\tconst { dataOptions: currentDataOptions } = chartWidgetProps;\n\n\t// Ensure we have a ZodObject to access shape property\n\tif (filteredSchema?._def?.typeName !== 'ZodObject') {\n\t\tthrow new Error(\n\t\t\t'Expected filteredSchema to be a ZodObject, but got a different type',\n\t\t);\n\t}\n\tconst schema = filteredSchema as z.ZodObject<any>;\n\n\tconst editableFieldsDoc = `\n\t\tEditable chart data options properties are as follows:\n\n\t\tdataOptions: {\n\t\t\t${Object.entries(schema.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 ('value', 'category', 'breakBy', etc.) to maintain identity.\n \n Do not include unchanged fields.\n ${\n\t\t\t\tadditionalInstructions\n\t\t\t\t\t? `\\n ${additionalInstructions}`\n\t\t\t\t\t: ''\n\t\t\t}\n \n Example:\n \n User: \"Sort brands by total 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\treturn systemPrompt;\n};\n\n/**\n * Updates chart data options based on the user's prompt.\n * @param systemPrompt - The system prompt to use for the LLM completion.\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\tsystemPrompt,\n\tuserPrompt,\n\tchartWidgetProps,\n}: UpdateChartDataOptionsHelperParams): Promise<ExtendedChartWidgetProps> => {\n\tconst { chartType: currentChartType } = chartWidgetProps;\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 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\tsystemPrompt: string,\n\tcontext: BuildChartContext,\n) => {\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\tsystemPrompt,\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\n/**\n * Configuration for data options update tools.\n */\ntype DataOptionsToolConfig = {\n\ttoolName: string;\n\tbuildSystemPrompt: (chartWidgetProps: ExtendedChartWidgetProps) => string;\n};\n\n/**\n * Factory function to create update chart data options tools.\n * Encapsulates common logic (chart retrieval, validation, calling updateChartDataOptions)\n * while allowing each tool to customize its system prompt generation.\n */\nconst createUpdateChartDataOptionsTool = (config: DataOptionsToolConfig) => {\n\treturn async (\n\t\t{ chartId, userPrompt }: z.infer<typeof updateChartSchema>,\n\t\tcontext: BuildChartContext,\n\t) => {\n\t\tconsole.debug('toolCall', config.toolName, chartId, userPrompt);\n\t\tconst chartWidgetProps = context.retrieveChart?.(chartId);\n\t\tif (!chartWidgetProps) {\n\t\t\tthrow new Error(`Chart not found`);\n\t\t}\n\n\t\tconst systemPrompt = config.buildSystemPrompt(chartWidgetProps);\n\t\treturn updateChartDataOptions(\n\t\t\t{ chartId, userPrompt },\n\t\t\tsystemPrompt,\n\t\t\tcontext,\n\t\t);\n\t};\n};\n\n// Tool configurations\nconst updateChartTypeOfMeasuresConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateChartTypeOfMeasures',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'chartType',\n\t\t]);\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t);\n\t},\n};\n\nconst updateChartSortingConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateChartSorting',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'sortType',\n\t\t]);\n\t\tconst additionalInstructions = `IMPORTANT: When setting sortType on a column within dataOptions, if sortType exists on any other column, set it to null to ensure only one is active.`;\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t\tadditionalInstructions,\n\t\t);\n\t},\n};\n\nconst updateTrendAndForecastConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateTrendAndForecast',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = filterSchemaProperties(baseSchema, [\n\t\t\t'column',\n\t\t\t'trend',\n\t\t\t'forecast',\n\t\t]);\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t);\n\t},\n};\n\nconst updateOtherChartDataOptionsConfig: DataOptionsToolConfig = {\n\ttoolName: 'updateOtherChartDataOptions',\n\tbuildSystemPrompt: (chartWidgetProps) => {\n\t\tconst baseSchema = getChartDataOptionsEditingSchemas(\n\t\t\tchartWidgetProps.chartType,\n\t\t);\n\t\tconst filteredSchema = excludeSchemaProperties(baseSchema, [\n\t\t\t'sortType', // Has dedicated sorting tool\n\t\t\t'trend', // Has dedicated trend/forecast tool\n\t\t\t'forecast', // Has dedicated trend/forecast tool\n\t\t\t'chartType', // Has dedicated chartType tool\n\t\t]);\n\t\tconst additionalInstructions = `IMPORTANT: This tool cannot swap data columns (e.g. changing \"Revenue\" to \"Profit\"). Use createChart for that.`;\n\t\treturn buildSystemPromptForDataOptions(\n\t\t\tchartWidgetProps,\n\t\t\tfilteredSchema,\n\t\t\tadditionalInstructions,\n\t\t);\n\t},\n};\n\n// Generate and export wrapper functions\nexport const updateChartTypeOfMeasures = createUpdateChartDataOptionsTool(\n\tupdateChartTypeOfMeasuresConfig,\n);\n\nexport const updateChartSorting = createUpdateChartDataOptionsTool(\n\tupdateChartSortingConfig,\n);\n\nexport const updateTrendAndForecast = createUpdateChartDataOptionsTool(\n\tupdateTrendAndForecastConfig,\n);\n\nexport const updateOtherChartDataOptions = createUpdateChartDataOptionsTool(\n\tupdateOtherChartDataOptionsConfig,\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","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 { zodFunction } 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\tbuildChartSchemaNaturalConversation,\n} from './types';\nimport { QueryResult } from '../build-query/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 {\n\tupdateChartTypeOfMeasures,\n\tupdateChartSorting,\n\tupdateTrendAndForecast,\n\tupdateOtherChartDataOptions,\n} from './update-chart/update-chart-data-options';\nimport { updateChartStyleOptions } from './update-chart/update-chart-style-options';\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. \n\nIMPORTANT: Split the user prompt into two parts:\n1. queryPrompt: Be as faithful to the original user prompt as possible, but remove chart-specific instructions (e.g., \"bar chart\", \"use X as dimension\"). Focus on what data to retrieve - the tool will extract specific dimensions, measures, and filters automatically.\n2. chartPrompt: Be as faithful to the original user prompt as possible and keep chart-specific instructions. Do not infer the chart type from the user prompt.\n\nUse 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\tupdateChartTypeOfMeasures,\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\tupdateChartSorting,\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\tupdateTrendAndForecast,\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\t\t\tupdateOtherChartDataOptions,\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\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(\n\tchartSummaries: ChartSummary[],\n\tquerySummaries?: QueryResult[],\n) {\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\tqueries: querySummaries ?? [],\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. When creating a chart that should use data from a prior query result, pass the query's queryId (from queries context) as the queryId parameter. If the user's request relates to a query that exists in the context, use its queryId when calling createChart.\n\n5. 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\n6. 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\n7. When updating the chart type of existing measures, re-apply the data options and style options changes to the new chart.\n\n8. Chart title: The chart title is automatically set from the data API during chart creation — do NOT call 'updateChartTitle' as part of initial chart creation or data modifications. Only call 'updateChartTitle' when the user explicitly asks to rename or change the title (e.g., \"rename the chart to X\", \"change the title to Y\").\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:\n\t\t| z.infer<typeof buildChartSchema>\n\t\t| z.infer<typeof buildChartSchemaNaturalConversation>,\n\tcontext: BuildChartContext,\n): Promise<ChartSummary> {\n\tconst { dataSourceTitle, userPrompt } = params;\n\tconst queryId = 'queryId' in params ? params.queryId : undefined;\n\n\tconsole.debug(TOOL_NAME_CHART_BUILDER, dataSourceTitle, userPrompt);\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\tqueryId,\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\tconst systemPrompt = buildContextualSystemPrompt(\n\t\t(context.chartSummaries ?? []).slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t\t(context.querySummaries ?? []).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 { z } from 'zod';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport { NlqV3Result } from '../../services/nlq/nlq-service';\n\n/**\n * Schema for buildQuery engine parameters\n */\nexport const buildQuerySchema = z.object({\n\tdataSourceTitle: z\n\t\t.string()\n\t\t.describe('The title of the data source to query'),\n\tqueryPrompt: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'The natural language query describing what data to retrieve',\n\t\t),\n});\n\n/**\n * Context interface for buildQueryEngine\n */\nexport interface BuildQueryContext {\n\t/** Tool call ID for tracking */\n\ttoolCallId: string;\n\t/** HTTP client for API calls (optional, uses singleton if not provided) */\n\thttpClient?: HttpClient;\n\t/** Optional ID generator for testability (defaults to nanoidHex(12)) */\n\tgenerateQueryId?: () => string;\n}\n\nexport interface QueryResult {\n\tqueryId: string;\n\ttitle: string;\n\tnlqResult: NlqV3Result;\n\tdataset: {} | string | null;\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","const ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case MAP:\n case SEQ:\n return true;\n }\n return false;\n}\nfunction isNode(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case ALIAS:\n case MAP:\n case SCALAR:\n case SEQ:\n return true;\n }\n return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexport { ALIAS, DOC, MAP, NODE_TYPE, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq };\n","import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (isDocument(node)) {\n const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n const ctrl = callVisitor(key, node, visitor, path);\n if (isNode(ctrl) || isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visit_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = visit_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = visit_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = visit_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `Promise`: Must resolve to one of the following values\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (isDocument(node)) {\n const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n const ctrl = await callVisitor(key, node, visitor, path);\n if (isNode(ctrl) || isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visitAsync_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = await visitAsync_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = await visitAsync_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = await visitAsync_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\nfunction initVisitor(visitor) {\n if (typeof visitor === 'object' &&\n (visitor.Collection || visitor.Node || visitor.Value)) {\n return Object.assign({\n Alias: visitor.Node,\n Map: visitor.Node,\n Scalar: visitor.Node,\n Seq: visitor.Node\n }, visitor.Value && {\n Map: visitor.Value,\n Scalar: visitor.Value,\n Seq: visitor.Value\n }, visitor.Collection && {\n Map: visitor.Collection,\n Seq: visitor.Collection\n }, visitor);\n }\n return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n if (typeof visitor === 'function')\n return visitor(key, node, path);\n if (isMap(node))\n return visitor.Map?.(key, node, path);\n if (isSeq(node))\n return visitor.Seq?.(key, node, path);\n if (isPair(node))\n return visitor.Pair?.(key, node, path);\n if (isScalar(node))\n return visitor.Scalar?.(key, node, path);\n if (isAlias(node))\n return visitor.Alias?.(key, node, path);\n return undefined;\n}\nfunction replaceNode(key, path, node) {\n const parent = path[path.length - 1];\n if (isCollection(parent)) {\n parent.items[key] = node;\n }\n else if (isPair(parent)) {\n if (key === 'key')\n parent.key = node;\n else\n parent.value = node;\n }\n else if (isDocument(parent)) {\n parent.contents = node;\n }\n else {\n const pt = isAlias(parent) ? 'alias' : 'scalar';\n throw new Error(`Cannot replace node with ${pt} parent`);\n }\n}\n\nexport { visit, visitAsync };\n","import { isNode } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\nconst escapeChars = {\n '!': '%21',\n ',': '%2C',\n '[': '%5B',\n ']': '%5D',\n '{': '%7B',\n '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n constructor(yaml, tags) {\n /**\n * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n * included in the document's stringified representation.\n */\n this.docStart = null;\n /** The doc-end marker `...`. */\n this.docEnd = false;\n this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n this.tags = Object.assign({}, Directives.defaultTags, tags);\n }\n clone() {\n const copy = new Directives(this.yaml, this.tags);\n copy.docStart = this.docStart;\n return copy;\n }\n /**\n * During parsing, get a Directives instance for the current document and\n * update the stream state according to the current version's spec.\n */\n atDocument() {\n const res = new Directives(this.yaml, this.tags);\n switch (this.yaml.version) {\n case '1.1':\n this.atNextDocument = true;\n break;\n case '1.2':\n this.atNextDocument = false;\n this.yaml = {\n explicit: Directives.defaultYaml.explicit,\n version: '1.2'\n };\n this.tags = Object.assign({}, Directives.defaultTags);\n break;\n }\n return res;\n }\n /**\n * @param onError - May be called even if the action was successful\n * @returns `true` on success\n */\n add(line, onError) {\n if (this.atNextDocument) {\n this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n this.tags = Object.assign({}, Directives.defaultTags);\n this.atNextDocument = false;\n }\n const parts = line.trim().split(/[ \\t]+/);\n const name = parts.shift();\n switch (name) {\n case '%TAG': {\n if (parts.length !== 2) {\n onError(0, '%TAG directive should contain exactly two parts');\n if (parts.length < 2)\n return false;\n }\n const [handle, prefix] = parts;\n this.tags[handle] = prefix;\n return true;\n }\n case '%YAML': {\n this.yaml.explicit = true;\n if (parts.length !== 1) {\n onError(0, '%YAML directive should contain exactly one part');\n return false;\n }\n const [version] = parts;\n if (version === '1.1' || version === '1.2') {\n this.yaml.version = version;\n return true;\n }\n else {\n const isValid = /^\\d+\\.\\d+$/.test(version);\n onError(6, `Unsupported YAML version ${version}`, isValid);\n return false;\n }\n }\n default:\n onError(0, `Unknown directive ${name}`, true);\n return false;\n }\n }\n /**\n * Resolves a tag, matching handles to those defined in %TAG directives.\n *\n * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n * `'!local'` tag, or `null` if unresolvable.\n */\n tagName(source, onError) {\n if (source === '!')\n return '!'; // non-specific tag\n if (source[0] !== '!') {\n onError(`Not a valid tag: ${source}`);\n return null;\n }\n if (source[1] === '<') {\n const verbatim = source.slice(2, -1);\n if (verbatim === '!' || verbatim === '!!') {\n onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n return null;\n }\n if (source[source.length - 1] !== '>')\n onError('Verbatim tags must end with a >');\n return verbatim;\n }\n const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n if (!suffix)\n onError(`The ${source} tag has no suffix`);\n const prefix = this.tags[handle];\n if (prefix) {\n try {\n return prefix + decodeURIComponent(suffix);\n }\n catch (error) {\n onError(String(error));\n return null;\n }\n }\n if (handle === '!')\n return source; // local tag\n onError(`Could not resolve tag: ${source}`);\n return null;\n }\n /**\n * Given a fully resolved tag, returns its printable string form,\n * taking into account current tag prefixes and defaults.\n */\n tagString(tag) {\n for (const [handle, prefix] of Object.entries(this.tags)) {\n if (tag.startsWith(prefix))\n return handle + escapeTagName(tag.substring(prefix.length));\n }\n return tag[0] === '!' ? tag : `!<${tag}>`;\n }\n toString(doc) {\n const lines = this.yaml.explicit\n ? [`%YAML ${this.yaml.version || '1.2'}`]\n : [];\n const tagEntries = Object.entries(this.tags);\n let tagNames;\n if (doc && tagEntries.length > 0 && isNode(doc.contents)) {\n const tags = {};\n visit(doc.contents, (_key, node) => {\n if (isNode(node) && node.tag)\n tags[node.tag] = true;\n });\n tagNames = Object.keys(tags);\n }\n else\n tagNames = [];\n for (const [handle, prefix] of tagEntries) {\n if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n continue;\n if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n lines.push(`%TAG ${handle} ${prefix}`);\n }\n return lines.join('\\n');\n }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexport { Directives };\n","import { isScalar, isCollection } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n const sa = JSON.stringify(anchor);\n const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n throw new Error(msg);\n }\n return true;\n}\nfunction anchorNames(root) {\n const anchors = new Set();\n visit(root, {\n Value(_key, node) {\n if (node.anchor)\n anchors.add(node.anchor);\n }\n });\n return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n for (let i = 1; true; ++i) {\n const name = `${prefix}${i}`;\n if (!exclude.has(name))\n return name;\n }\n}\nfunction createNodeAnchors(doc, prefix) {\n const aliasObjects = [];\n const sourceObjects = new Map();\n let prevAnchors = null;\n return {\n onAnchor: (source) => {\n aliasObjects.push(source);\n prevAnchors ?? (prevAnchors = anchorNames(doc));\n const anchor = findNewAnchor(prefix, prevAnchors);\n prevAnchors.add(anchor);\n return anchor;\n },\n /**\n * With circular references, the source node is only resolved after all\n * of its child nodes are. This is why anchors are set only after all of\n * the nodes have been created.\n */\n setAnchors: () => {\n for (const source of aliasObjects) {\n const ref = sourceObjects.get(source);\n if (typeof ref === 'object' &&\n ref.anchor &&\n (isScalar(ref.node) || isCollection(ref.node))) {\n ref.node.anchor = ref.anchor;\n }\n else {\n const error = new Error('Failed to resolve repeated object (this should not happen)');\n error.source = source;\n throw error;\n }\n }\n },\n sourceObjects\n };\n}\n\nexport { anchorIsValid, anchorNames, createNodeAnchors, findNewAnchor };\n","/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n if (val && typeof val === 'object') {\n if (Array.isArray(val)) {\n for (let i = 0, len = val.length; i < len; ++i) {\n const v0 = val[i];\n const v1 = applyReviver(reviver, val, String(i), v0);\n // eslint-disable-next-line @typescript-eslint/no-array-delete\n if (v1 === undefined)\n delete val[i];\n else if (v1 !== v0)\n val[i] = v1;\n }\n }\n else if (val instanceof Map) {\n for (const k of Array.from(val.keys())) {\n const v0 = val.get(k);\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n val.delete(k);\n else if (v1 !== v0)\n val.set(k, v1);\n }\n }\n else if (val instanceof Set) {\n for (const v0 of Array.from(val)) {\n const v1 = applyReviver(reviver, val, v0, v0);\n if (v1 === undefined)\n val.delete(v0);\n else if (v1 !== v0) {\n val.delete(v0);\n val.add(v1);\n }\n }\n }\n else {\n for (const [k, v0] of Object.entries(val)) {\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n delete val[k];\n else if (v1 !== v0)\n val[k] = v1;\n }\n }\n }\n return reviver.call(obj, key, val);\n}\n\nexport { applyReviver };\n","import { hasAnchor } from './identity.js';\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n * as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n * `{ keep: true }` is not set, output should be suitable for JSON\n * stringification.\n */\nfunction toJS(value, arg, ctx) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n if (Array.isArray(value))\n return value.map((v, i) => toJS(v, String(i), ctx));\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (!ctx || !hasAnchor(value))\n return value.toJSON(arg, ctx);\n const data = { aliasCount: 0, count: 1, res: undefined };\n ctx.anchors.set(value, data);\n ctx.onCreate = res => {\n data.res = res;\n delete ctx.onCreate;\n };\n const res = value.toJSON(arg, ctx);\n if (ctx.onCreate)\n ctx.onCreate(res);\n return res;\n }\n if (typeof value === 'bigint' && !ctx?.keep)\n return Number(value);\n return value;\n}\n\nexport { toJS };\n","import { applyReviver } from '../doc/applyReviver.js';\nimport { NODE_TYPE, isDocument } from './identity.js';\nimport { toJS } from './toJS.js';\n\nclass NodeBase {\n constructor(type) {\n Object.defineProperty(this, NODE_TYPE, { value: type });\n }\n /** Create a copy of this node. */\n clone() {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** A plain JavaScript representation of this node. */\n toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n if (!isDocument(doc))\n throw new TypeError('A document argument is required');\n const ctx = {\n anchors: new Map(),\n doc,\n keep: true,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS(this, '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n}\n\nexport { NodeBase };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { visit } from '../visit.js';\nimport { ALIAS, isAlias, isCollection, isPair, hasAnchor } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nclass Alias extends NodeBase {\n constructor(source) {\n super(ALIAS);\n this.source = source;\n Object.defineProperty(this, 'tag', {\n set() {\n throw new Error('Alias nodes cannot have tags');\n }\n });\n }\n /**\n * Resolve the value of this alias within `doc`, finding the last\n * instance of the `source` anchor before this node.\n */\n resolve(doc, ctx) {\n let nodes;\n if (ctx?.aliasResolveCache) {\n nodes = ctx.aliasResolveCache;\n }\n else {\n nodes = [];\n visit(doc, {\n Node: (_key, node) => {\n if (isAlias(node) || hasAnchor(node))\n nodes.push(node);\n }\n });\n if (ctx)\n ctx.aliasResolveCache = nodes;\n }\n let found = undefined;\n for (const node of nodes) {\n if (node === this)\n break;\n if (node.anchor === this.source)\n found = node;\n }\n return found;\n }\n toJSON(_arg, ctx) {\n if (!ctx)\n return { source: this.source };\n const { anchors, doc, maxAliasCount } = ctx;\n const source = this.resolve(doc, ctx);\n if (!source) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new ReferenceError(msg);\n }\n let data = anchors.get(source);\n if (!data) {\n // Resolve anchors for Node.prototype.toJS()\n toJS(source, null, ctx);\n data = anchors.get(source);\n }\n /* istanbul ignore if */\n if (data?.res === undefined) {\n const msg = 'This should not happen: Alias anchor was not resolved?';\n throw new ReferenceError(msg);\n }\n if (maxAliasCount >= 0) {\n data.count += 1;\n if (data.aliasCount === 0)\n data.aliasCount = getAliasCount(doc, source, anchors);\n if (data.count * data.aliasCount > maxAliasCount) {\n const msg = 'Excessive alias count indicates a resource exhaustion attack';\n throw new ReferenceError(msg);\n }\n }\n return data.res;\n }\n toString(ctx, _onComment, _onChompKeep) {\n const src = `*${this.source}`;\n if (ctx) {\n anchorIsValid(this.source);\n if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new Error(msg);\n }\n if (ctx.implicitKey)\n return `${src} `;\n }\n return src;\n }\n}\nfunction getAliasCount(doc, node, anchors) {\n if (isAlias(node)) {\n const source = node.resolve(doc);\n const anchor = anchors && source && anchors.get(source);\n return anchor ? anchor.count * anchor.aliasCount : 0;\n }\n else if (isCollection(node)) {\n let count = 0;\n for (const item of node.items) {\n const c = getAliasCount(doc, item, anchors);\n if (c > count)\n count = c;\n }\n return count;\n }\n else if (isPair(node)) {\n const kc = getAliasCount(doc, node.key, anchors);\n const vc = getAliasCount(doc, node.value, anchors);\n return Math.max(kc, vc);\n }\n return 1;\n}\n\nexport { Alias };\n","import { SCALAR } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends NodeBase {\n constructor(value) {\n super(SCALAR);\n this.value = value;\n }\n toJSON(arg, ctx) {\n return ctx?.keep ? this.value : toJS(this.value, arg, ctx);\n }\n toString() {\n return String(this.value);\n }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexport { Scalar, isScalarValue };\n","import { Alias } from '../nodes/Alias.js';\nimport { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n if (tagName) {\n const match = tags.filter(t => t.tag === tagName);\n const tagObj = match.find(t => !t.format) ?? match[0];\n if (!tagObj)\n throw new Error(`Tag ${tagName} not found`);\n return tagObj;\n }\n return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n if (isDocument(value))\n value = value.contents;\n if (isNode(value))\n return value;\n if (isPair(value)) {\n const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);\n map.items.push(value);\n return map;\n }\n if (value instanceof String ||\n value instanceof Number ||\n value instanceof Boolean ||\n (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n ) {\n // https://tc39.es/ecma262/#sec-serializejsonproperty\n value = value.valueOf();\n }\n const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n // Detect duplicate references to the same object & use Alias nodes for all\n // after first. The `ref` wrapper allows for circular references to resolve.\n let ref = undefined;\n if (aliasDuplicateObjects && value && typeof value === 'object') {\n ref = sourceObjects.get(value);\n if (ref) {\n ref.anchor ?? (ref.anchor = onAnchor(value));\n return new Alias(ref.anchor);\n }\n else {\n ref = { anchor: null, node: null };\n sourceObjects.set(value, ref);\n }\n }\n if (tagName?.startsWith('!!'))\n tagName = defaultTagPrefix + tagName.slice(2);\n let tagObj = findTagObject(value, tagName, schema.tags);\n if (!tagObj) {\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n value = value.toJSON();\n }\n if (!value || typeof value !== 'object') {\n const node = new Scalar(value);\n if (ref)\n ref.node = node;\n return node;\n }\n tagObj =\n value instanceof Map\n ? schema[MAP]\n : Symbol.iterator in Object(value)\n ? schema[SEQ]\n : schema[MAP];\n }\n if (onTagObj) {\n onTagObj(tagObj);\n delete ctx.onTagObj;\n }\n const node = tagObj?.createNode\n ? tagObj.createNode(ctx.schema, value, ctx)\n : typeof tagObj?.nodeClass?.from === 'function'\n ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n : new Scalar(value);\n if (tagName)\n node.tag = tagName;\n else if (!tagObj.default)\n node.tag = tagObj.tag;\n if (ref)\n ref.node = node;\n return node;\n}\n\nexport { createNode };\n","import { createNode } from '../doc/createNode.js';\nimport { isNode, isPair, isCollection, isScalar } from './identity.js';\nimport { NodeBase } from './Node.js';\n\nfunction collectionFromPath(schema, path, value) {\n let v = value;\n for (let i = path.length - 1; i >= 0; --i) {\n const k = path[i];\n if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n const a = [];\n a[k] = v;\n v = a;\n }\n else {\n v = new Map([[k, v]]);\n }\n }\n return createNode(v, undefined, {\n aliasDuplicateObjects: false,\n keepUndefined: false,\n onAnchor: () => {\n throw new Error('This should not happen, please report a bug.');\n },\n schema,\n sourceObjects: new Map()\n });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends NodeBase {\n constructor(type, schema) {\n super(type);\n Object.defineProperty(this, 'schema', {\n value: schema,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n /**\n * Create a copy of this collection.\n *\n * @param schema - If defined, overwrites the original's schema\n */\n clone(schema) {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (schema)\n copy.schema = schema;\n copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it);\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /**\n * Adds a value to the collection. For `!!map` and `!!omap` the value must\n * be a Pair instance or a `{ key, value }` object, which may not have a key\n * that already exists in the map.\n */\n addIn(path, value) {\n if (isEmptyPath(path))\n this.add(value);\n else {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (isCollection(node))\n node.addIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n /**\n * Removes a value from the collection.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.delete(key);\n const node = this.get(key, true);\n if (isCollection(node))\n return node.deleteIn(rest);\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (rest.length === 0)\n return !keepScalar && isScalar(node) ? node.value : node;\n else\n return isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n }\n hasAllNullValues(allowScalar) {\n return this.items.every(node => {\n if (!isPair(node))\n return false;\n const n = node.value;\n return (n == null ||\n (allowScalar &&\n isScalar(n) &&\n n.value == null &&\n !n.commentBefore &&\n !n.comment &&\n !n.tag));\n });\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n */\n hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return isCollection(node) ? node.hasIn(rest) : false;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n const [key, ...rest] = path;\n if (rest.length === 0) {\n this.set(key, value);\n }\n else {\n const node = this.get(key, true);\n if (isCollection(node))\n node.setIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n}\n\nexport { Collection, collectionFromPath, isEmptyPath };\n","/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n if (/^\\n+$/.test(comment))\n return comment.substring(1);\n return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n ? indentComment(comment, indent)\n : comment.includes('\\n')\n ? '\\n' + indentComment(comment, indent)\n : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexport { indentComment, lineComment, stringifyComment };\n","const FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n if (!lineWidth || lineWidth < 0)\n return text;\n if (lineWidth < minContentWidth)\n minContentWidth = 0;\n const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n if (text.length <= endStep)\n return text;\n const folds = [];\n const escapedFolds = {};\n let end = lineWidth - indent.length;\n if (typeof indentAtStart === 'number') {\n if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n folds.push(0);\n else\n end = lineWidth - indentAtStart;\n }\n let split = undefined;\n let prev = undefined;\n let overflow = false;\n let i = -1;\n let escStart = -1;\n let escEnd = -1;\n if (mode === FOLD_BLOCK) {\n i = consumeMoreIndentedLines(text, i, indent.length);\n if (i !== -1)\n end = i + endStep;\n }\n for (let ch; (ch = text[(i += 1)]);) {\n if (mode === FOLD_QUOTED && ch === '\\\\') {\n escStart = i;\n switch (text[i + 1]) {\n case 'x':\n i += 3;\n break;\n case 'u':\n i += 5;\n break;\n case 'U':\n i += 9;\n break;\n default:\n i += 1;\n }\n escEnd = i;\n }\n if (ch === '\\n') {\n if (mode === FOLD_BLOCK)\n i = consumeMoreIndentedLines(text, i, indent.length);\n end = i + indent.length + endStep;\n split = undefined;\n }\n else {\n if (ch === ' ' &&\n prev &&\n prev !== ' ' &&\n prev !== '\\n' &&\n prev !== '\\t') {\n // space surrounded by non-space can be replaced with newline + indent\n const next = text[i + 1];\n if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n split = i;\n }\n if (i >= end) {\n if (split) {\n folds.push(split);\n end = split + endStep;\n split = undefined;\n }\n else if (mode === FOLD_QUOTED) {\n // white-space collected at end may stretch past lineWidth\n while (prev === ' ' || prev === '\\t') {\n prev = ch;\n ch = text[(i += 1)];\n overflow = true;\n }\n // Account for newline escape, but don't break preceding escape\n const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n // Bail out if lineWidth & minContentWidth are shorter than an escape string\n if (escapedFolds[j])\n return text;\n folds.push(j);\n escapedFolds[j] = true;\n end = j + endStep;\n split = undefined;\n }\n else {\n overflow = true;\n }\n }\n }\n prev = ch;\n }\n if (overflow && onOverflow)\n onOverflow();\n if (folds.length === 0)\n return text;\n if (onFold)\n onFold();\n let res = text.slice(0, folds[0]);\n for (let i = 0; i < folds.length; ++i) {\n const fold = folds[i];\n const end = folds[i + 1] || text.length;\n if (fold === 0)\n res = `\\n${indent}${text.slice(0, end)}`;\n else {\n if (mode === FOLD_QUOTED && escapedFolds[fold])\n res += `${text[fold]}\\\\`;\n res += `\\n${indent}${text.slice(fold + 1, end)}`;\n }\n }\n return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n let end = i;\n let start = i + 1;\n let ch = text[start];\n while (ch === ' ' || ch === '\\t') {\n if (i < start + indent) {\n ch = text[++i];\n }\n else {\n do {\n ch = text[++i];\n } while (ch && ch !== '\\n');\n end = i;\n start = i + 1;\n ch = text[start];\n }\n }\n return end;\n}\n\nexport { FOLD_BLOCK, FOLD_FLOW, FOLD_QUOTED, foldFlowLines };\n","import { Scalar } from '../nodes/Scalar.js';\nimport { foldFlowLines, FOLD_FLOW, FOLD_QUOTED, FOLD_BLOCK } from './foldFlowLines.js';\n\nconst getFoldOptions = (ctx, isBlock) => ({\n indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n lineWidth: ctx.options.lineWidth,\n minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n if (!lineWidth || lineWidth < 0)\n return false;\n const limit = lineWidth - indentLength;\n const strLen = str.length;\n if (strLen <= limit)\n return false;\n for (let i = 0, start = 0; i < strLen; ++i) {\n if (str[i] === '\\n') {\n if (i - start > limit)\n return true;\n start = i + 1;\n if (strLen - start <= limit)\n return false;\n }\n }\n return true;\n}\nfunction doubleQuotedString(value, ctx) {\n const json = JSON.stringify(value);\n if (ctx.options.doubleQuotedAsJSON)\n return json;\n const { implicitKey } = ctx;\n const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n let str = '';\n let start = 0;\n for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n // space before newline needs to be escaped to not be folded\n str += json.slice(start, i) + '\\\\ ';\n i += 1;\n start = i;\n ch = '\\\\';\n }\n if (ch === '\\\\')\n switch (json[i + 1]) {\n case 'u':\n {\n str += json.slice(start, i);\n const code = json.substr(i + 2, 4);\n switch (code) {\n case '0000':\n str += '\\\\0';\n break;\n case '0007':\n str += '\\\\a';\n break;\n case '000b':\n str += '\\\\v';\n break;\n case '001b':\n str += '\\\\e';\n break;\n case '0085':\n str += '\\\\N';\n break;\n case '00a0':\n str += '\\\\_';\n break;\n case '2028':\n str += '\\\\L';\n break;\n case '2029':\n str += '\\\\P';\n break;\n default:\n if (code.substr(0, 2) === '00')\n str += '\\\\x' + code.substr(2);\n else\n str += json.substr(i, 6);\n }\n i += 5;\n start = i + 1;\n }\n break;\n case 'n':\n if (implicitKey ||\n json[i + 2] === '\"' ||\n json.length < minMultiLineLength) {\n i += 1;\n }\n else {\n // folding will eat first newline\n str += json.slice(start, i) + '\\n\\n';\n while (json[i + 2] === '\\\\' &&\n json[i + 3] === 'n' &&\n json[i + 4] !== '\"') {\n str += '\\n';\n i += 2;\n }\n str += indent;\n // space after newline needs to be escaped to not be folded\n if (json[i + 2] === ' ')\n str += '\\\\';\n i += 1;\n start = i + 1;\n }\n break;\n default:\n i += 1;\n }\n }\n str = start ? str + json.slice(start) : json;\n return implicitKey\n ? str\n : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n if (ctx.options.singleQuote === false ||\n (ctx.implicitKey && value.includes('\\n')) ||\n /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n )\n return doubleQuotedString(value, ctx);\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n return ctx.implicitKey\n ? res\n : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n const { singleQuote } = ctx.options;\n let qs;\n if (singleQuote === false)\n qs = doubleQuotedString;\n else {\n const hasDouble = value.includes('\"');\n const hasSingle = value.includes(\"'\");\n if (hasDouble && !hasSingle)\n qs = singleQuotedString;\n else if (hasSingle && !hasDouble)\n qs = doubleQuotedString;\n else\n qs = singleQuote ? singleQuotedString : doubleQuotedString;\n }\n return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n const { blockQuote, commentString, lineWidth } = ctx.options;\n // 1. Block can't end in whitespace unless the last line is non-empty.\n // 2. Strings consisting of only whitespace are best rendered explicitly.\n if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n return quotedString(value, ctx);\n }\n const indent = ctx.indent ||\n (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');\n const literal = blockQuote === 'literal'\n ? true\n : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED\n ? false\n : type === Scalar.BLOCK_LITERAL\n ? true\n : !lineLengthOverLimit(value, lineWidth, indent.length);\n if (!value)\n return literal ? '|\\n' : '>\\n';\n // determine chomping from whitespace at value end\n let chomp;\n let endStart;\n for (endStart = value.length; endStart > 0; --endStart) {\n const ch = value[endStart - 1];\n if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n break;\n }\n let end = value.substring(endStart);\n const endNlPos = end.indexOf('\\n');\n if (endNlPos === -1) {\n chomp = '-'; // strip\n }\n else if (value === end || endNlPos !== end.length - 1) {\n chomp = '+'; // keep\n if (onChompKeep)\n onChompKeep();\n }\n else {\n chomp = ''; // clip\n }\n if (end) {\n value = value.slice(0, -end.length);\n if (end[end.length - 1] === '\\n')\n end = end.slice(0, -1);\n end = end.replace(blockEndNewlines, `$&${indent}`);\n }\n // determine indent indicator from whitespace at value start\n let startWithSpace = false;\n let startEnd;\n let startNlPos = -1;\n for (startEnd = 0; startEnd < value.length; ++startEnd) {\n const ch = value[startEnd];\n if (ch === ' ')\n startWithSpace = true;\n else if (ch === '\\n')\n startNlPos = startEnd;\n else\n break;\n }\n let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n if (start) {\n value = value.substring(start.length);\n start = start.replace(/\\n+/g, `$&${indent}`);\n }\n const indentSize = indent ? '2' : '1'; // root is at -1\n // Leading | or > is added later\n let header = (startWithSpace ? indentSize : '') + chomp;\n if (comment) {\n header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n if (onComment)\n onComment();\n }\n if (!literal) {\n const foldedValue = value\n .replace(/\\n+/g, '\\n$&')\n .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent\n .replace(/\\n+/g, `$&${indent}`);\n let literalFallback = false;\n const foldOptions = getFoldOptions(ctx, true);\n if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) {\n foldOptions.onOverflow = () => {\n literalFallback = true;\n };\n }\n const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);\n if (!literalFallback)\n return `>${header}\\n${indent}${body}`;\n }\n value = value.replace(/\\n+/g, `$&${indent}`);\n return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n const { type, value } = item;\n const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n if ((implicitKey && value.includes('\\n')) ||\n (inFlow && /[[\\]{},]/.test(value))) {\n return quotedString(value, ctx);\n }\n if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n // not allowed:\n // - '-' or '?'\n // - start with an indicator character (except [?:-]) or /[?-] /\n // - '\\n ', ': ' or ' \\n' anywhere\n // - '#' not preceded by a non-space char\n // - end with ' ' or ':'\n return implicitKey || inFlow || !value.includes('\\n')\n ? quotedString(value, ctx)\n : blockString(item, ctx, onComment, onChompKeep);\n }\n if (!implicitKey &&\n !inFlow &&\n type !== Scalar.PLAIN &&\n value.includes('\\n')) {\n // Where allowed & type not set explicitly, prefer block style for multiline strings\n return blockString(item, ctx, onComment, onChompKeep);\n }\n if (containsDocumentMarker(value)) {\n if (indent === '') {\n ctx.forceBlockIndent = true;\n return blockString(item, ctx, onComment, onChompKeep);\n }\n else if (implicitKey && indent === indentStep) {\n return quotedString(value, ctx);\n }\n }\n const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n // Verify that output will be parsed as a string, as e.g. plain numbers and\n // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n // and others in v1.1.\n if (actualString) {\n const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n const { compat, tags } = ctx.doc.schema;\n if (tags.some(test) || compat?.some(test))\n return quotedString(value, ctx);\n }\n return implicitKey\n ? str\n : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n const { implicitKey, inFlow } = ctx;\n const ss = typeof item.value === 'string'\n ? item\n : Object.assign({}, item, { value: String(item.value) });\n let { type } = item;\n if (type !== Scalar.QUOTE_DOUBLE) {\n // force double quotes on control characters & unpaired surrogates\n if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n type = Scalar.QUOTE_DOUBLE;\n }\n const _stringify = (_type) => {\n switch (_type) {\n case Scalar.BLOCK_FOLDED:\n case Scalar.BLOCK_LITERAL:\n return implicitKey || inFlow\n ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n : blockString(ss, ctx, onComment, onChompKeep);\n case Scalar.QUOTE_DOUBLE:\n return doubleQuotedString(ss.value, ctx);\n case Scalar.QUOTE_SINGLE:\n return singleQuotedString(ss.value, ctx);\n case Scalar.PLAIN:\n return plainString(ss, ctx, onComment, onChompKeep);\n default:\n return null;\n }\n };\n let res = _stringify(type);\n if (res === null) {\n const { defaultKeyType, defaultStringType } = ctx.options;\n const t = (implicitKey && defaultKeyType) || defaultStringType;\n res = _stringify(t);\n if (res === null)\n throw new Error(`Unsupported default string type ${t}`);\n }\n return res;\n}\n\nexport { stringifyString };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/identity.js';\nimport { stringifyComment } from './stringifyComment.js';\nimport { stringifyString } from './stringifyString.js';\n\nfunction createStringifyContext(doc, options) {\n const opt = Object.assign({\n blockQuote: true,\n commentString: stringifyComment,\n defaultKeyType: null,\n defaultStringType: 'PLAIN',\n directives: null,\n doubleQuotedAsJSON: false,\n doubleQuotedMinMultiLineLength: 40,\n falseStr: 'false',\n flowCollectionPadding: true,\n indentSeq: true,\n lineWidth: 80,\n minContentWidth: 20,\n nullStr: 'null',\n simpleKeys: false,\n singleQuote: null,\n trueStr: 'true',\n verifyAliasOrder: true\n }, doc.schema.toStringOptions, options);\n let inFlow;\n switch (opt.collectionStyle) {\n case 'block':\n inFlow = false;\n break;\n case 'flow':\n inFlow = true;\n break;\n default:\n inFlow = null;\n }\n return {\n anchors: new Set(),\n doc,\n flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n indent: '',\n indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',\n inFlow,\n options: opt\n };\n}\nfunction getTagObject(tags, item) {\n if (item.tag) {\n const match = tags.filter(t => t.tag === item.tag);\n if (match.length > 0)\n return match.find(t => t.format === item.format) ?? match[0];\n }\n let tagObj = undefined;\n let obj;\n if (isScalar(item)) {\n obj = item.value;\n let match = tags.filter(t => t.identify?.(obj));\n if (match.length > 1) {\n const testMatch = match.filter(t => t.test);\n if (testMatch.length > 0)\n match = testMatch;\n }\n tagObj =\n match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n }\n else {\n obj = item;\n tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n }\n if (!tagObj) {\n const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n throw new Error(`Tag not resolved for ${name} value`);\n }\n return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors, doc }) {\n if (!doc.directives)\n return '';\n const props = [];\n const anchor = (isScalar(node) || isCollection(node)) && node.anchor;\n if (anchor && anchorIsValid(anchor)) {\n anchors.add(anchor);\n props.push(`&${anchor}`);\n }\n const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n if (tag)\n props.push(doc.directives.tagString(tag));\n return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n if (isPair(item))\n return item.toString(ctx, onComment, onChompKeep);\n if (isAlias(item)) {\n if (ctx.doc.directives)\n return item.toString(ctx);\n if (ctx.resolvedAliases?.has(item)) {\n throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n }\n else {\n if (ctx.resolvedAliases)\n ctx.resolvedAliases.add(item);\n else\n ctx.resolvedAliases = new Set([item]);\n item = item.resolve(ctx.doc);\n }\n }\n let tagObj = undefined;\n const node = isNode(item)\n ? item\n : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n const props = stringifyProps(node, tagObj, ctx);\n if (props.length > 0)\n ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n const str = typeof tagObj.stringify === 'function'\n ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n : isScalar(node)\n ? stringifyString(node, ctx, onComment, onChompKeep)\n : node.toString(ctx, onComment, onChompKeep);\n if (!props)\n return str;\n return isScalar(node) || str[0] === '{' || str[0] === '['\n ? `${props} ${str}`\n : `${props}\\n${ctx.indent}${str}`;\n}\n\nexport { createStringifyContext, stringify };\n","import { isCollection, isNode, isScalar, isSeq } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n let keyComment = (isNode(key) && key.comment) || null;\n if (simpleKeys) {\n if (keyComment) {\n throw new Error('With simple keys, key nodes cannot have comments');\n }\n if (isCollection(key) || (!isNode(key) && typeof key === 'object')) {\n const msg = 'With simple keys, collection cannot be used as a key value';\n throw new Error(msg);\n }\n }\n let explicitKey = !simpleKeys &&\n (!key ||\n (keyComment && value == null && !ctx.inFlow) ||\n isCollection(key) ||\n (isScalar(key)\n ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL\n : typeof key === 'object'));\n ctx = Object.assign({}, ctx, {\n allNullValues: false,\n implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n indent: indent + indentStep\n });\n let keyCommentDone = false;\n let chompKeep = false;\n let str = stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n if (simpleKeys)\n throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n explicitKey = true;\n }\n if (ctx.inFlow) {\n if (allNullValues || value == null) {\n if (keyCommentDone && onComment)\n onComment();\n return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n }\n }\n else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n str = `? ${str}`;\n if (keyComment && !keyCommentDone) {\n str += lineComment(str, ctx.indent, commentString(keyComment));\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n }\n if (keyCommentDone)\n keyComment = null;\n if (explicitKey) {\n if (keyComment)\n str += lineComment(str, ctx.indent, commentString(keyComment));\n str = `? ${str}\\n${indent}:`;\n }\n else {\n str = `${str}:`;\n if (keyComment)\n str += lineComment(str, ctx.indent, commentString(keyComment));\n }\n let vsb, vcb, valueComment;\n if (isNode(value)) {\n vsb = !!value.spaceBefore;\n vcb = value.commentBefore;\n valueComment = value.comment;\n }\n else {\n vsb = false;\n vcb = null;\n valueComment = null;\n if (value && typeof value === 'object')\n value = doc.createNode(value);\n }\n ctx.implicitKey = false;\n if (!explicitKey && !keyComment && isScalar(value))\n ctx.indentAtStart = str.length + 1;\n chompKeep = false;\n if (!indentSeq &&\n indentStep.length >= 2 &&\n !ctx.inFlow &&\n !explicitKey &&\n isSeq(value) &&\n !value.flow &&\n !value.tag &&\n !value.anchor) {\n // If indentSeq === false, consider '- ' as part of indentation where possible\n ctx.indent = ctx.indent.substring(2);\n }\n let valueCommentDone = false;\n const valueStr = stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n let ws = ' ';\n if (keyComment || vsb || vcb) {\n ws = vsb ? '\\n' : '';\n if (vcb) {\n const cs = commentString(vcb);\n ws += `\\n${indentComment(cs, ctx.indent)}`;\n }\n if (valueStr === '' && !ctx.inFlow) {\n if (ws === '\\n' && valueComment)\n ws = '\\n\\n';\n }\n else {\n ws += `\\n${ctx.indent}`;\n }\n }\n else if (!explicitKey && isCollection(value)) {\n const vs0 = valueStr[0];\n const nl0 = valueStr.indexOf('\\n');\n const hasNewline = nl0 !== -1;\n const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n if (hasNewline || !flow) {\n let hasPropsLine = false;\n if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n let sp0 = valueStr.indexOf(' ');\n if (vs0 === '&' &&\n sp0 !== -1 &&\n sp0 < nl0 &&\n valueStr[sp0 + 1] === '!') {\n sp0 = valueStr.indexOf(' ', sp0 + 1);\n }\n if (sp0 === -1 || nl0 < sp0)\n hasPropsLine = true;\n }\n if (!hasPropsLine)\n ws = `\\n${ctx.indent}`;\n }\n }\n else if (valueStr === '' || valueStr[0] === '\\n') {\n ws = '';\n }\n str += ws + valueStr;\n if (ctx.inFlow) {\n if (valueCommentDone && onComment)\n onComment();\n }\n else if (valueComment && !valueCommentDone) {\n str += lineComment(str, ctx.indent, commentString(valueComment));\n }\n else if (chompKeep && onChompKeep) {\n onChompKeep();\n }\n return str;\n}\n\nexport { stringifyPair };\n","function debug(logLevel, ...messages) {\n if (logLevel === 'debug')\n console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n if (logLevel === 'debug' || logLevel === 'warn') {\n console.warn(warning);\n }\n}\n\nexport { debug, warn };\n","import { isScalar, isAlias, isSeq, isMap } from '../../nodes/identity.js';\nimport { Scalar } from '../../nodes/Scalar.js';\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n identify: value => value === MERGE_KEY ||\n (typeof value === 'symbol' && value.description === MERGE_KEY),\n default: 'key',\n tag: 'tag:yaml.org,2002:merge',\n test: /^<<$/,\n resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {\n addToJSMap: addMergeToJSMap\n }),\n stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n (isScalar(key) &&\n (!key.type || key.type === Scalar.PLAIN) &&\n merge.identify(key.value))) &&\n ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;\n if (isSeq(value))\n for (const it of value.items)\n mergeValue(ctx, map, it);\n else if (Array.isArray(value))\n for (const it of value)\n mergeValue(ctx, map, it);\n else\n mergeValue(ctx, map, value);\n}\nfunction mergeValue(ctx, map, value) {\n const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;\n if (!isMap(source))\n throw new Error('Merge sources must be maps or map aliases');\n const srcMap = source.toJSON(null, ctx, Map);\n for (const [key, value] of srcMap) {\n if (map instanceof Map) {\n if (!map.has(key))\n map.set(key, value);\n }\n else if (map instanceof Set) {\n map.add(key);\n }\n else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n Object.defineProperty(map, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return map;\n}\n\nexport { addMergeToJSMap, isMergeKey, merge };\n","import { warn } from '../log.js';\nimport { isMergeKey, addMergeToJSMap } from '../schema/yaml-1.1/merge.js';\nimport { createStringifyContext } from '../stringify/stringify.js';\nimport { isNode } from './identity.js';\nimport { toJS } from './toJS.js';\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n if (isNode(key) && key.addToJSMap)\n key.addToJSMap(ctx, map, value);\n // TODO: Should drop this special case for bare << handling\n else if (isMergeKey(ctx, key))\n addMergeToJSMap(ctx, map, value);\n else {\n const jsKey = toJS(key, '', ctx);\n if (map instanceof Map) {\n map.set(jsKey, toJS(value, jsKey, ctx));\n }\n else if (map instanceof Set) {\n map.add(jsKey);\n }\n else {\n const stringKey = stringifyKey(key, jsKey, ctx);\n const jsValue = toJS(value, stringKey, ctx);\n if (stringKey in map)\n Object.defineProperty(map, stringKey, {\n value: jsValue,\n writable: true,\n enumerable: true,\n configurable: true\n });\n else\n map[stringKey] = jsValue;\n }\n }\n return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n if (jsKey === null)\n return '';\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n if (typeof jsKey !== 'object')\n return String(jsKey);\n if (isNode(key) && ctx?.doc) {\n const strCtx = createStringifyContext(ctx.doc, {});\n strCtx.anchors = new Set();\n for (const node of ctx.anchors.keys())\n strCtx.anchors.add(node.anchor);\n strCtx.inFlow = true;\n strCtx.inStringifyKey = true;\n const strKey = key.toString(strCtx);\n if (!ctx.mapKeyWarned) {\n let jsonStr = JSON.stringify(strKey);\n if (jsonStr.length > 40)\n jsonStr = jsonStr.substring(0, 36) + '...\"';\n warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n ctx.mapKeyWarned = true;\n }\n return strKey;\n }\n return JSON.stringify(jsKey);\n}\n\nexport { addPairToJSMap };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyPair } from '../stringify/stringifyPair.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { NODE_TYPE, PAIR, isNode } from './identity.js';\n\nfunction createPair(key, value, ctx) {\n const k = createNode(key, undefined, ctx);\n const v = createNode(value, undefined, ctx);\n return new Pair(k, v);\n}\nclass Pair {\n constructor(key, value = null) {\n Object.defineProperty(this, NODE_TYPE, { value: PAIR });\n this.key = key;\n this.value = value;\n }\n clone(schema) {\n let { key, value } = this;\n if (isNode(key))\n key = key.clone(schema);\n if (isNode(value))\n value = value.clone(schema);\n return new Pair(key, value);\n }\n toJSON(_, ctx) {\n const pair = ctx?.mapAsMap ? new Map() : {};\n return addPairToJSMap(ctx, pair, this);\n }\n toString(ctx, onComment, onChompKeep) {\n return ctx?.doc\n ? stringifyPair(this, ctx, onComment, onChompKeep)\n : JSON.stringify(this);\n }\n}\n\nexport { Pair, createPair };\n","import { isNode, isPair } from '../nodes/identity.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyCollection(collection, ctx, options) {\n const flow = ctx.inFlow ?? collection.flow;\n const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n const { indent, options: { commentString } } = ctx;\n const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n let chompKeep = false; // flag for the preceding node's status\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (isNode(item)) {\n if (!chompKeep && item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n if (item.comment)\n comment = item.comment;\n }\n else if (isPair(item)) {\n const ik = isNode(item.key) ? item.key : null;\n if (ik) {\n if (!chompKeep && ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n }\n }\n chompKeep = false;\n let str = stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n if (comment)\n str += lineComment(str, itemIndent, commentString(comment));\n if (chompKeep && comment)\n chompKeep = false;\n lines.push(blockItemPrefix + str);\n }\n let str;\n if (lines.length === 0) {\n str = flowChars.start + flowChars.end;\n }\n else {\n str = lines[0];\n for (let i = 1; i < lines.length; ++i) {\n const line = lines[i];\n str += line ? `\\n${indent}${line}` : '\\n';\n }\n }\n if (comment) {\n str += '\\n' + indentComment(commentString(comment), indent);\n if (onComment)\n onComment();\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n itemIndent += indentStep;\n const itemCtx = Object.assign({}, ctx, {\n indent: itemIndent,\n inFlow: true,\n type: null\n });\n let reqNewline = false;\n let linesAtValue = 0;\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (isNode(item)) {\n if (item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, false);\n if (item.comment)\n comment = item.comment;\n }\n else if (isPair(item)) {\n const ik = isNode(item.key) ? item.key : null;\n if (ik) {\n if (ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, false);\n if (ik.comment)\n reqNewline = true;\n }\n const iv = isNode(item.value) ? item.value : null;\n if (iv) {\n if (iv.comment)\n comment = iv.comment;\n if (iv.commentBefore)\n reqNewline = true;\n }\n else if (item.value == null && ik?.comment) {\n comment = ik.comment;\n }\n }\n if (comment)\n reqNewline = true;\n let str = stringify(item, itemCtx, () => (comment = null));\n if (i < items.length - 1)\n str += ',';\n if (comment)\n str += lineComment(str, itemIndent, commentString(comment));\n if (!reqNewline && (lines.length > linesAtValue || str.includes('\\n')))\n reqNewline = true;\n lines.push(str);\n linesAtValue = lines.length;\n }\n const { start, end } = flowChars;\n if (lines.length === 0) {\n return start + end;\n }\n else {\n if (!reqNewline) {\n const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n }\n if (reqNewline) {\n let str = start;\n for (const line of lines)\n str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n return `${str}\\n${indent}${end}`;\n }\n else {\n return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n }\n }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n if (comment && chompKeep)\n comment = comment.replace(/^\\n+/, '');\n if (comment) {\n const ic = indentComment(commentString(comment), indent);\n lines.push(ic.trimStart()); // Avoid double indent on first line\n }\n}\n\nexport { stringifyCollection };\n","import { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { Collection } from './Collection.js';\nimport { MAP, isPair, isScalar } from './identity.js';\nimport { Pair, createPair } from './Pair.js';\nimport { isScalarValue } from './Scalar.js';\n\nfunction findPair(items, key) {\n const k = isScalar(key) ? key.value : key;\n for (const it of items) {\n if (isPair(it)) {\n if (it.key === key || it.key === k)\n return it;\n if (isScalar(it.key) && it.key.value === k)\n return it;\n }\n }\n return undefined;\n}\nclass YAMLMap extends Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:map';\n }\n constructor(schema) {\n super(MAP, schema);\n this.items = [];\n }\n /**\n * A generic collection parsing method that can be extended\n * to other node classes that inherit from YAMLMap\n */\n static from(schema, obj, ctx) {\n const { keepUndefined, replacer } = ctx;\n const map = new this(schema);\n const add = (key, value) => {\n if (typeof replacer === 'function')\n value = replacer.call(obj, key, value);\n else if (Array.isArray(replacer) && !replacer.includes(key))\n return;\n if (value !== undefined || keepUndefined)\n map.items.push(createPair(key, value, ctx));\n };\n if (obj instanceof Map) {\n for (const [key, value] of obj)\n add(key, value);\n }\n else if (obj && typeof obj === 'object') {\n for (const key of Object.keys(obj))\n add(key, obj[key]);\n }\n if (typeof schema.sortMapEntries === 'function') {\n map.items.sort(schema.sortMapEntries);\n }\n return map;\n }\n /**\n * Adds a value to the collection.\n *\n * @param overwrite - If not set `true`, using a key that is already in the\n * collection will throw. Otherwise, overwrites the previous value.\n */\n add(pair, overwrite) {\n let _pair;\n if (isPair(pair))\n _pair = pair;\n else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n // In TypeScript, this never happens.\n _pair = new Pair(pair, pair?.value);\n }\n else\n _pair = new Pair(pair.key, pair.value);\n const prev = findPair(this.items, _pair.key);\n const sortEntries = this.schema?.sortMapEntries;\n if (prev) {\n if (!overwrite)\n throw new Error(`Key ${_pair.key} already set`);\n // For scalars, keep the old node & its comments and anchors\n if (isScalar(prev.value) && isScalarValue(_pair.value))\n prev.value.value = _pair.value;\n else\n prev.value = _pair.value;\n }\n else if (sortEntries) {\n const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n if (i === -1)\n this.items.push(_pair);\n else\n this.items.splice(i, 0, _pair);\n }\n else {\n this.items.push(_pair);\n }\n }\n delete(key) {\n const it = findPair(this.items, key);\n if (!it)\n return false;\n const del = this.items.splice(this.items.indexOf(it), 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const it = findPair(this.items, key);\n const node = it?.value;\n return (!keepScalar && isScalar(node) ? node.value : node) ?? undefined;\n }\n has(key) {\n return !!findPair(this.items, key);\n }\n set(key, value) {\n this.add(new Pair(key, value), true);\n }\n /**\n * @param ctx - Conversion context, originally set in Document#toJS()\n * @param {Class} Type - If set, forces the returned collection type\n * @returns Instance of Type, Map, or Object\n */\n toJSON(_, ctx, Type) {\n const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const item of this.items)\n addPairToJSMap(ctx, map, item);\n return map;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n for (const item of this.items) {\n if (!isPair(item))\n throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n }\n if (!ctx.allNullValues && this.hasAllNullValues(false))\n ctx = Object.assign({}, ctx, { allNullValues: true });\n return stringifyCollection(this, ctx, {\n blockItemPrefix: '',\n flowChars: { start: '{', end: '}' },\n itemIndent: ctx.indent || '',\n onChompKeep,\n onComment\n });\n }\n}\n\nexport { YAMLMap, findPair };\n","import { isMap } from '../../nodes/identity.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\n\nconst map = {\n collection: 'map',\n default: true,\n nodeClass: YAMLMap,\n tag: 'tag:yaml.org,2002:map',\n resolve(map, onError) {\n if (!isMap(map))\n onError('Expected a mapping for this tag');\n return map;\n },\n createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)\n};\n\nexport { map };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { Collection } from './Collection.js';\nimport { SEQ, isScalar } from './identity.js';\nimport { isScalarValue } from './Scalar.js';\nimport { toJS } from './toJS.js';\n\nclass YAMLSeq extends Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:seq';\n }\n constructor(schema) {\n super(SEQ, schema);\n this.items = [];\n }\n add(value) {\n this.items.push(value);\n }\n /**\n * Removes a value from the collection.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n *\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return false;\n const del = this.items.splice(idx, 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return undefined;\n const it = this.items[idx];\n return !keepScalar && isScalar(it) ? it.value : it;\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n */\n has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n *\n * If `key` does not contain a representation of an integer, this will throw.\n * It may be wrapped in a `Scalar`.\n */\n set(key, value) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n throw new Error(`Expected a valid index, not ${key}.`);\n const prev = this.items[idx];\n if (isScalar(prev) && isScalarValue(value))\n prev.value = value;\n else\n this.items[idx] = value;\n }\n toJSON(_, ctx) {\n const seq = [];\n if (ctx?.onCreate)\n ctx.onCreate(seq);\n let i = 0;\n for (const item of this.items)\n seq.push(toJS(item, String(i++), ctx));\n return seq;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n return stringifyCollection(this, ctx, {\n blockItemPrefix: '- ',\n flowChars: { start: '[', end: ']' },\n itemIndent: (ctx.indent || '') + ' ',\n onChompKeep,\n onComment\n });\n }\n static from(schema, obj, ctx) {\n const { replacer } = ctx;\n const seq = new this(schema);\n if (obj && Symbol.iterator in Object(obj)) {\n let i = 0;\n for (let it of obj) {\n if (typeof replacer === 'function') {\n const key = obj instanceof Set ? it : String(i++);\n it = replacer.call(obj, key, it);\n }\n seq.items.push(createNode(it, undefined, ctx));\n }\n }\n return seq;\n }\n}\nfunction asItemIndex(key) {\n let idx = isScalar(key) ? key.value : key;\n if (idx && typeof idx === 'string')\n idx = Number(idx);\n return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n ? idx\n : null;\n}\n\nexport { YAMLSeq };\n","import { isSeq } from '../../nodes/identity.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nconst seq = {\n collection: 'seq',\n default: true,\n nodeClass: YAMLSeq,\n tag: 'tag:yaml.org,2002:seq',\n resolve(seq, onError) {\n if (!isSeq(seq))\n onError('Expected a sequence for this tag');\n return seq;\n },\n createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)\n};\n\nexport { seq };\n","import { stringifyString } from '../../stringify/stringifyString.js';\n\nconst string = {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify(item, ctx, onComment, onChompKeep) {\n ctx = Object.assign({ actualString: true }, ctx);\n return stringifyString(item, ctx, onComment, onChompKeep);\n }\n};\n\nexport { string };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst nullTag = {\n identify: value => value == null,\n createNode: () => new Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^(?:~|[Nn]ull|NULL)?$/,\n resolve: () => new Scalar(null),\n stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n ? source\n : ctx.options.nullStr\n};\n\nexport { nullTag };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst boolTag = {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),\n stringify({ source, value }, ctx) {\n if (source && boolTag.test.test(source)) {\n const sv = source[0] === 't' || source[0] === 'T';\n if (value === sv)\n return source;\n }\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n }\n};\n\nexport { boolTag };\n","function stringifyNumber({ format, minFractionDigits, tag, value }) {\n if (typeof value === 'bigint')\n return String(value);\n const num = typeof value === 'number' ? value : Number(value);\n if (!isFinite(num))\n return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n if (!format &&\n minFractionDigits &&\n (!tag || tag === 'tag:yaml.org,2002:float') &&\n /^\\d/.test(n)) {\n let i = n.indexOf('.');\n if (i < 0) {\n i = n.length;\n n += '.';\n }\n let d = minFractionDigits - (n.length - i - 1);\n while (d-- > 0)\n n += '0';\n }\n return n;\n}\n\nexport { stringifyNumber };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: str => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n resolve: str => parseFloat(str),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n resolve(str) {\n const node = new Scalar(parseFloat(str));\n const dot = str.indexOf('.');\n if (dot !== -1 && str[str.length - 1] === '0')\n node.minFractionDigits = str.length - dot - 1;\n return node;\n },\n stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value) && value >= 0)\n return prefix + value.toString(radix);\n return stringifyNumber(node);\n}\nconst intOct = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^0o[0-7]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber\n};\nconst intHex = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^0x[0-9a-fA-F]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intHex, intOct };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { boolTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intOct, int, intHex } from './int.js';\n\nconst schema = [\n map,\n seq,\n string,\n nullTag,\n boolTag,\n intOct,\n int,\n intHex,\n floatNaN,\n floatExp,\n float\n];\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { map } from '../common/map.js';\nimport { seq } from '../common/seq.js';\n\nfunction intIdentify(value) {\n return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify: stringifyJSON\n },\n {\n identify: value => value == null,\n createNode: () => new Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^null$/,\n resolve: () => null,\n stringify: stringifyJSON\n },\n {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^true$|^false$/,\n resolve: str => str === 'true',\n stringify: stringifyJSON\n },\n {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^-?(?:0|[1-9][0-9]*)$/,\n resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n },\n {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n resolve: str => parseFloat(str),\n stringify: stringifyJSON\n }\n];\nconst jsonError = {\n default: true,\n tag: '',\n test: /^/,\n resolve(str, onError) {\n onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n return str;\n }\n};\nconst schema = [map, seq].concat(jsonScalars, jsonError);\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyString } from '../../stringify/stringifyString.js';\n\nconst binary = {\n identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n default: false,\n tag: 'tag:yaml.org,2002:binary',\n /**\n * Returns a Buffer in node and an Uint8Array in browsers\n *\n * To use the resulting buffer as an image, you'll want to do something like:\n *\n * const blob = new Blob([buffer], { type: 'image/jpeg' })\n * document.querySelector('#photo').src = URL.createObjectURL(blob)\n */\n resolve(src, onError) {\n if (typeof atob === 'function') {\n // On IE 11, atob() can't handle newlines\n const str = atob(src.replace(/[\\n\\r]/g, ''));\n const buffer = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i)\n buffer[i] = str.charCodeAt(i);\n return buffer;\n }\n else {\n onError('This environment does not support reading binary tags; either Buffer or atob is required');\n return src;\n }\n },\n stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n if (!value)\n return '';\n const buf = value; // checked earlier by binary.identify()\n let str;\n if (typeof btoa === 'function') {\n let s = '';\n for (let i = 0; i < buf.length; ++i)\n s += String.fromCharCode(buf[i]);\n str = btoa(s);\n }\n else {\n throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n }\n type ?? (type = Scalar.BLOCK_LITERAL);\n if (type !== Scalar.QUOTE_DOUBLE) {\n const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n const n = Math.ceil(str.length / lineWidth);\n const lines = new Array(n);\n for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n lines[i] = str.substr(o, lineWidth);\n }\n str = lines.join(type === Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n }\n return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n }\n};\n\nexport { binary };\n","import { isSeq, isPair, isMap } from '../../nodes/identity.js';\nimport { createPair, Pair } from '../../nodes/Pair.js';\nimport { Scalar } from '../../nodes/Scalar.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nfunction resolvePairs(seq, onError) {\n if (isSeq(seq)) {\n for (let i = 0; i < seq.items.length; ++i) {\n let item = seq.items[i];\n if (isPair(item))\n continue;\n else if (isMap(item)) {\n if (item.items.length > 1)\n onError('Each pair must have its own sequence indicator');\n const pair = item.items[0] || new Pair(new Scalar(null));\n if (item.commentBefore)\n pair.key.commentBefore = pair.key.commentBefore\n ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n : item.commentBefore;\n if (item.comment) {\n const cn = pair.value ?? pair.key;\n cn.comment = cn.comment\n ? `${item.comment}\\n${cn.comment}`\n : item.comment;\n }\n item = pair;\n }\n seq.items[i] = isPair(item) ? item : new Pair(item);\n }\n }\n else\n onError('Expected a sequence for this tag');\n return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n const { replacer } = ctx;\n const pairs = new YAMLSeq(schema);\n pairs.tag = 'tag:yaml.org,2002:pairs';\n let i = 0;\n if (iterable && Symbol.iterator in Object(iterable))\n for (let it of iterable) {\n if (typeof replacer === 'function')\n it = replacer.call(iterable, String(i++), it);\n let key, value;\n if (Array.isArray(it)) {\n if (it.length === 2) {\n key = it[0];\n value = it[1];\n }\n else\n throw new TypeError(`Expected [key, value] tuple: ${it}`);\n }\n else if (it && it instanceof Object) {\n const keys = Object.keys(it);\n if (keys.length === 1) {\n key = keys[0];\n value = it[key];\n }\n else {\n throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n }\n }\n else {\n key = it;\n }\n pairs.items.push(createPair(key, value, ctx));\n }\n return pairs;\n}\nconst pairs = {\n collection: 'seq',\n default: false,\n tag: 'tag:yaml.org,2002:pairs',\n resolve: resolvePairs,\n createNode: createPairs\n};\n\nexport { createPairs, pairs, resolvePairs };\n","import { isScalar, isPair } from '../../nodes/identity.js';\nimport { toJS } from '../../nodes/toJS.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\nimport { resolvePairs, createPairs } from './pairs.js';\n\nclass YAMLOMap extends YAMLSeq {\n constructor() {\n super();\n this.add = YAMLMap.prototype.add.bind(this);\n this.delete = YAMLMap.prototype.delete.bind(this);\n this.get = YAMLMap.prototype.get.bind(this);\n this.has = YAMLMap.prototype.has.bind(this);\n this.set = YAMLMap.prototype.set.bind(this);\n this.tag = YAMLOMap.tag;\n }\n /**\n * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n * but TypeScript won't allow widening the signature of a child method.\n */\n toJSON(_, ctx) {\n if (!ctx)\n return super.toJSON(_);\n const map = new Map();\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const pair of this.items) {\n let key, value;\n if (isPair(pair)) {\n key = toJS(pair.key, '', ctx);\n value = toJS(pair.value, key, ctx);\n }\n else {\n key = toJS(pair, '', ctx);\n }\n if (map.has(key))\n throw new Error('Ordered maps must not include duplicate keys');\n map.set(key, value);\n }\n return map;\n }\n static from(schema, iterable, ctx) {\n const pairs = createPairs(schema, iterable, ctx);\n const omap = new this();\n omap.items = pairs.items;\n return omap;\n }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n collection: 'seq',\n identify: value => value instanceof Map,\n nodeClass: YAMLOMap,\n default: false,\n tag: 'tag:yaml.org,2002:omap',\n resolve(seq, onError) {\n const pairs = resolvePairs(seq, onError);\n const seenKeys = [];\n for (const { key } of pairs.items) {\n if (isScalar(key)) {\n if (seenKeys.includes(key.value)) {\n onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n }\n else {\n seenKeys.push(key.value);\n }\n }\n }\n return Object.assign(new YAMLOMap(), pairs);\n },\n createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexport { YAMLOMap, omap };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nfunction boolStringify({ value, source }, ctx) {\n const boolObj = value ? trueTag : falseTag;\n if (source && boolObj.test.test(source))\n return source;\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n identify: value => value === true,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n resolve: () => new Scalar(true),\n stringify: boolStringify\n};\nconst falseTag = {\n identify: value => value === false,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n resolve: () => new Scalar(false),\n stringify: boolStringify\n};\n\nexport { falseTag, trueTag };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n resolve: (str) => parseFloat(str.replace(/_/g, '')),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n resolve(str) {\n const node = new Scalar(parseFloat(str.replace(/_/g, '')));\n const dot = str.indexOf('.');\n if (dot !== -1) {\n const f = str.substring(dot + 1).replace(/_/g, '');\n if (f[f.length - 1] === '0')\n node.minFractionDigits = f.length;\n }\n return node;\n },\n stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n const sign = str[0];\n if (sign === '-' || sign === '+')\n offset += 1;\n str = str.substring(offset).replace(/_/g, '');\n if (intAsBigInt) {\n switch (radix) {\n case 2:\n str = `0b${str}`;\n break;\n case 8:\n str = `0o${str}`;\n break;\n case 16:\n str = `0x${str}`;\n break;\n }\n const n = BigInt(str);\n return sign === '-' ? BigInt(-1) * n : n;\n }\n const n = parseInt(str, radix);\n return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value)) {\n const str = value.toString(radix);\n return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n }\n return stringifyNumber(node);\n}\nconst intBin = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'BIN',\n test: /^[-+]?0b[0-1_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^[-+]?0[0-7_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9][0-9_]*$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber\n};\nconst intHex = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^[-+]?0x[0-9a-fA-F_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intBin, intHex, intOct };\n","import { isMap, isPair, isScalar } from '../../nodes/identity.js';\nimport { Pair, createPair } from '../../nodes/Pair.js';\nimport { YAMLMap, findPair } from '../../nodes/YAMLMap.js';\n\nclass YAMLSet extends YAMLMap {\n constructor(schema) {\n super(schema);\n this.tag = YAMLSet.tag;\n }\n add(key) {\n let pair;\n if (isPair(key))\n pair = key;\n else if (key &&\n typeof key === 'object' &&\n 'key' in key &&\n 'value' in key &&\n key.value === null)\n pair = new Pair(key.key, null);\n else\n pair = new Pair(key, null);\n const prev = findPair(this.items, pair.key);\n if (!prev)\n this.items.push(pair);\n }\n /**\n * If `keepPair` is `true`, returns the Pair matching `key`.\n * Otherwise, returns the value of that Pair's key.\n */\n get(key, keepPair) {\n const pair = findPair(this.items, key);\n return !keepPair && isPair(pair)\n ? isScalar(pair.key)\n ? pair.key.value\n : pair.key\n : pair;\n }\n set(key, value) {\n if (typeof value !== 'boolean')\n throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n const prev = findPair(this.items, key);\n if (prev && !value) {\n this.items.splice(this.items.indexOf(prev), 1);\n }\n else if (!prev && value) {\n this.items.push(new Pair(key));\n }\n }\n toJSON(_, ctx) {\n return super.toJSON(_, ctx, Set);\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n if (this.hasAllNullValues(true))\n return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n else\n throw new Error('Set items must all have null values');\n }\n static from(schema, iterable, ctx) {\n const { replacer } = ctx;\n const set = new this(schema);\n if (iterable && Symbol.iterator in Object(iterable))\n for (let value of iterable) {\n if (typeof replacer === 'function')\n value = replacer.call(iterable, value, value);\n set.items.push(createPair(value, null, ctx));\n }\n return set;\n }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n collection: 'map',\n identify: value => value instanceof Set,\n nodeClass: YAMLSet,\n default: false,\n tag: 'tag:yaml.org,2002:set',\n createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n resolve(map, onError) {\n if (isMap(map)) {\n if (map.hasAllNullValues(true))\n return Object.assign(new YAMLSet(), map);\n else\n onError('Set items must all have null values');\n }\n else\n onError('Expected a mapping for this tag');\n return map;\n }\n};\n\nexport { YAMLSet, set };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n const sign = str[0];\n const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n const num = (n) => asBigInt ? BigInt(n) : Number(n);\n const res = parts\n .replace(/_/g, '')\n .split(':')\n .reduce((res, p) => res * num(60) + num(p), num(0));\n return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n let { value } = node;\n let num = (n) => n;\n if (typeof value === 'bigint')\n num = n => BigInt(n);\n else if (isNaN(value) || !isFinite(value))\n return stringifyNumber(node);\n let sign = '';\n if (value < 0) {\n sign = '-';\n value *= num(-1);\n }\n const _60 = num(60);\n const parts = [value % _60]; // seconds, including ms\n if (value < 60) {\n parts.unshift(0); // at least one : is required\n }\n else {\n value = (value - parts[0]) / _60;\n parts.unshift(value % _60); // minutes\n if (value >= 60) {\n value = (value - parts[0]) / _60;\n parts.unshift(value); // hours\n }\n }\n return (sign +\n parts\n .map(n => String(n).padStart(2, '0'))\n .join(':')\n .replace(/000000\\d*$/, '') // % 60 may introduce error\n );\n}\nconst intTime = {\n identify: value => typeof value === 'bigint' || Number.isInteger(value),\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n stringify: stringifySexagesimal\n};\nconst floatTime = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n resolve: str => parseSexagesimal(str, false),\n stringify: stringifySexagesimal\n};\nconst timestamp = {\n identify: value => value instanceof Date,\n default: true,\n tag: 'tag:yaml.org,2002:timestamp',\n // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n // may be omitted altogether, resulting in a date format. In such a case, the time part is\n // assumed to be 00:00:00Z (start of day, UTC).\n test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n '(?:' + // time is optional\n '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n ')?$'),\n resolve(str) {\n const match = str.match(timestamp.test);\n if (!match)\n throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n const [, year, month, day, hour, minute, second] = match.map(Number);\n const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n const tz = match[8];\n if (tz && tz !== 'Z') {\n let d = parseSexagesimal(tz, false);\n if (Math.abs(d) < 30)\n d *= 60;\n date -= 60000 * d;\n }\n return new Date(date);\n },\n stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexport { floatTime, intTime, timestamp };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { binary } from './binary.js';\nimport { trueTag, falseTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intBin, intOct, int, intHex } from './int.js';\nimport { merge } from './merge.js';\nimport { omap } from './omap.js';\nimport { pairs } from './pairs.js';\nimport { set } from './set.js';\nimport { intTime, floatTime, timestamp } from './timestamp.js';\n\nconst schema = [\n map,\n seq,\n string,\n nullTag,\n trueTag,\n falseTag,\n intBin,\n intOct,\n int,\n intHex,\n floatNaN,\n floatExp,\n float,\n binary,\n merge,\n omap,\n pairs,\n set,\n intTime,\n floatTime,\n timestamp\n];\n\nexport { schema };\n","import { map } from './common/map.js';\nimport { nullTag } from './common/null.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { boolTag } from './core/bool.js';\nimport { floatNaN, floatExp, float } from './core/float.js';\nimport { intOct, intHex, int } from './core/int.js';\nimport { schema } from './core/schema.js';\nimport { schema as schema$1 } from './json/schema.js';\nimport { binary } from './yaml-1.1/binary.js';\nimport { merge } from './yaml-1.1/merge.js';\nimport { omap } from './yaml-1.1/omap.js';\nimport { pairs } from './yaml-1.1/pairs.js';\nimport { schema as schema$2 } from './yaml-1.1/schema.js';\nimport { set } from './yaml-1.1/set.js';\nimport { timestamp, intTime, floatTime } from './yaml-1.1/timestamp.js';\n\nconst schemas = new Map([\n ['core', schema],\n ['failsafe', [map, seq, string]],\n ['json', schema$1],\n ['yaml11', schema$2],\n ['yaml-1.1', schema$2]\n]);\nconst tagsByName = {\n binary,\n bool: boolTag,\n float,\n floatExp,\n floatNaN,\n floatTime,\n int,\n intHex,\n intOct,\n intTime,\n map,\n merge,\n null: nullTag,\n omap,\n pairs,\n seq,\n set,\n timestamp\n};\nconst coreKnownTags = {\n 'tag:yaml.org,2002:binary': binary,\n 'tag:yaml.org,2002:merge': merge,\n 'tag:yaml.org,2002:omap': omap,\n 'tag:yaml.org,2002:pairs': pairs,\n 'tag:yaml.org,2002:set': set,\n 'tag:yaml.org,2002:timestamp': timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n const schemaTags = schemas.get(schemaName);\n if (schemaTags && !customTags) {\n return addMergeTag && !schemaTags.includes(merge)\n ? schemaTags.concat(merge)\n : schemaTags.slice();\n }\n let tags = schemaTags;\n if (!tags) {\n if (Array.isArray(customTags))\n tags = [];\n else {\n const keys = Array.from(schemas.keys())\n .filter(key => key !== 'yaml11')\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n }\n }\n if (Array.isArray(customTags)) {\n for (const tag of customTags)\n tags = tags.concat(tag);\n }\n else if (typeof customTags === 'function') {\n tags = customTags(tags.slice());\n }\n if (addMergeTag)\n tags = tags.concat(merge);\n return tags.reduce((tags, tag) => {\n const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n if (!tagObj) {\n const tagName = JSON.stringify(tag);\n const keys = Object.keys(tagsByName)\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n }\n if (!tags.includes(tagObj))\n tags.push(tagObj);\n return tags;\n }, []);\n}\n\nexport { coreKnownTags, getTags };\n","import { MAP, SCALAR, SEQ } from '../nodes/identity.js';\nimport { map } from './common/map.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { getTags, coreKnownTags } from './tags.js';\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n this.compat = Array.isArray(compat)\n ? getTags(compat, 'compat')\n : compat\n ? getTags(null, compat)\n : null;\n this.name = (typeof schema === 'string' && schema) || 'core';\n this.knownTags = resolveKnownTags ? coreKnownTags : {};\n this.tags = getTags(customTags, this.name, merge);\n this.toStringOptions = toStringDefaults ?? null;\n Object.defineProperty(this, MAP, { value: map });\n Object.defineProperty(this, SCALAR, { value: string });\n Object.defineProperty(this, SEQ, { value: seq });\n // Used by createMap()\n this.sortMapEntries =\n typeof sortMapEntries === 'function'\n ? sortMapEntries\n : sortMapEntries === true\n ? sortMapEntriesByKey\n : null;\n }\n clone() {\n const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n copy.tags = this.tags.slice();\n return copy;\n }\n}\n\nexport { Schema };\n","import { isNode } from '../nodes/identity.js';\nimport { createStringifyContext, stringify } from './stringify.js';\nimport { indentComment, lineComment } from './stringifyComment.js';\n\nfunction stringifyDocument(doc, options) {\n const lines = [];\n let hasDirectives = options.directives === true;\n if (options.directives !== false && doc.directives) {\n const dir = doc.directives.toString(doc);\n if (dir) {\n lines.push(dir);\n hasDirectives = true;\n }\n else if (doc.directives.docStart)\n hasDirectives = true;\n }\n if (hasDirectives)\n lines.push('---');\n const ctx = createStringifyContext(doc, options);\n const { commentString } = ctx.options;\n if (doc.commentBefore) {\n if (lines.length !== 1)\n lines.unshift('');\n const cs = commentString(doc.commentBefore);\n lines.unshift(indentComment(cs, ''));\n }\n let chompKeep = false;\n let contentComment = null;\n if (doc.contents) {\n if (isNode(doc.contents)) {\n if (doc.contents.spaceBefore && hasDirectives)\n lines.push('');\n if (doc.contents.commentBefore) {\n const cs = commentString(doc.contents.commentBefore);\n lines.push(indentComment(cs, ''));\n }\n // top-level block scalars need to be indented if followed by a comment\n ctx.forceBlockIndent = !!doc.comment;\n contentComment = doc.contents.comment;\n }\n const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n let body = stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n if (contentComment)\n body += lineComment(body, '', commentString(contentComment));\n if ((body[0] === '|' || body[0] === '>') &&\n lines[lines.length - 1] === '---') {\n // Top-level block scalars with a preceding doc marker ought to use the\n // same line for their header.\n lines[lines.length - 1] = `--- ${body}`;\n }\n else\n lines.push(body);\n }\n else {\n lines.push(stringify(doc.contents, ctx));\n }\n if (doc.directives?.docEnd) {\n if (doc.comment) {\n const cs = commentString(doc.comment);\n if (cs.includes('\\n')) {\n lines.push('...');\n lines.push(indentComment(cs, ''));\n }\n else {\n lines.push(`... ${cs}`);\n }\n }\n else {\n lines.push('...');\n }\n }\n else {\n let dc = doc.comment;\n if (dc && chompKeep)\n dc = dc.replace(/^\\n+/, '');\n if (dc) {\n if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n lines.push('');\n lines.push(indentComment(commentString(dc), ''));\n }\n }\n return lines.join('\\n') + '\\n';\n}\n\nexport { stringifyDocument };\n","import { Alias } from '../nodes/Alias.js';\nimport { isEmptyPath, collectionFromPath } from '../nodes/Collection.js';\nimport { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js';\nimport { Pair } from '../nodes/Pair.js';\nimport { toJS } from '../nodes/toJS.js';\nimport { Schema } from '../schema/Schema.js';\nimport { stringifyDocument } from '../stringify/stringifyDocument.js';\nimport { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';\nimport { applyReviver } from './applyReviver.js';\nimport { createNode } from './createNode.js';\nimport { Directives } from './directives.js';\n\nclass Document {\n constructor(value, replacer, options) {\n /** A comment before this Document */\n this.commentBefore = null;\n /** A comment immediately after this Document */\n this.comment = null;\n /** Errors encountered during parsing. */\n this.errors = [];\n /** Warnings encountered during parsing. */\n this.warnings = [];\n Object.defineProperty(this, NODE_TYPE, { value: DOC });\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const opt = Object.assign({\n intAsBigInt: false,\n keepSourceTokens: false,\n logLevel: 'warn',\n prettyErrors: true,\n strict: true,\n stringKeys: false,\n uniqueKeys: true,\n version: '1.2'\n }, options);\n this.options = opt;\n let { version } = opt;\n if (options?._directives) {\n this.directives = options._directives.atDocument();\n if (this.directives.yaml.explicit)\n version = this.directives.yaml.version;\n }\n else\n this.directives = new Directives({ version });\n this.setSchema(version, options);\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents =\n value === undefined ? null : this.createNode(value, _replacer, options);\n }\n /**\n * Create a deep copy of this Document and its contents.\n *\n * Custom Node values that inherit from `Object` still refer to their original instances.\n */\n clone() {\n const copy = Object.create(Document.prototype, {\n [NODE_TYPE]: { value: DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n // @ts-expect-error We can't really know that this matches Contents.\n copy.contents = isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** Adds a value to the document. */\n add(value) {\n if (assertCollection(this.contents))\n this.contents.add(value);\n }\n /** Adds a value to the document. */\n addIn(path, value) {\n if (assertCollection(this.contents))\n this.contents.addIn(path, value);\n }\n /**\n * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n *\n * If `node` already has an anchor, `name` is ignored.\n * Otherwise, the `node.anchor` value will be set to `name`,\n * or if an anchor with that name is already present in the document,\n * `name` will be used as a prefix for a new unique anchor.\n * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n */\n createAlias(node, name) {\n if (!node.anchor) {\n const prev = anchorNames(this);\n node.anchor =\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;\n }\n return new Alias(node.anchor);\n }\n createNode(value, replacer, options) {\n let _replacer = undefined;\n if (typeof replacer === 'function') {\n value = replacer.call({ '': value }, '', value);\n _replacer = replacer;\n }\n else if (Array.isArray(replacer)) {\n const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n const asStr = replacer.filter(keyToStr).map(String);\n if (asStr.length > 0)\n replacer = replacer.concat(asStr);\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, \n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n anchorPrefix || 'a');\n const ctx = {\n aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n keepUndefined: keepUndefined ?? false,\n onAnchor,\n onTagObj,\n replacer: _replacer,\n schema: this.schema,\n sourceObjects\n };\n const node = createNode(value, tag, ctx);\n if (flow && isCollection(node))\n node.flow = true;\n setAnchors();\n return node;\n }\n /**\n * Convert a key and a value into a `Pair` using the current schema,\n * recursively wrapping all values as `Scalar` or `Collection` nodes.\n */\n createPair(key, value, options = {}) {\n const k = this.createNode(key, null, options);\n const v = this.createNode(value, null, options);\n return new Pair(k, v);\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n return assertCollection(this.contents) ? this.contents.delete(key) : false;\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n if (isEmptyPath(path)) {\n if (this.contents == null)\n return false;\n // @ts-expect-error Presumed impossible if Strict extends false\n this.contents = null;\n return true;\n }\n return assertCollection(this.contents)\n ? this.contents.deleteIn(path)\n : false;\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n get(key, keepScalar) {\n return isCollection(this.contents)\n ? this.contents.get(key, keepScalar)\n : undefined;\n }\n /**\n * Returns item at `path`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n if (isEmptyPath(path))\n return !keepScalar && isScalar(this.contents)\n ? this.contents.value\n : this.contents;\n return isCollection(this.contents)\n ? this.contents.getIn(path, keepScalar)\n : undefined;\n }\n /**\n * Checks if the document includes a value with the key `key`.\n */\n has(key) {\n return isCollection(this.contents) ? this.contents.has(key) : false;\n }\n /**\n * Checks if the document includes a value at `path`.\n */\n hasIn(path) {\n if (isEmptyPath(path))\n return this.contents !== undefined;\n return isCollection(this.contents) ? this.contents.hasIn(path) : false;\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n set(key, value) {\n if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = collectionFromPath(this.schema, [key], value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.set(key, value);\n }\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n if (isEmptyPath(path)) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = value;\n }\n else if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = collectionFromPath(this.schema, Array.from(path), value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.setIn(path, value);\n }\n }\n /**\n * Change the YAML version and schema used by the document.\n * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n * It also requires the `schema` option to be given as a `Schema` instance value.\n *\n * Overrides all previously set schema options.\n */\n setSchema(version, options = {}) {\n if (typeof version === 'number')\n version = String(version);\n let opt;\n switch (version) {\n case '1.1':\n if (this.directives)\n this.directives.yaml.version = '1.1';\n else\n this.directives = new Directives({ version: '1.1' });\n opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n break;\n case '1.2':\n case 'next':\n if (this.directives)\n this.directives.yaml.version = version;\n else\n this.directives = new Directives({ version });\n opt = { resolveKnownTags: true, schema: 'core' };\n break;\n case null:\n if (this.directives)\n delete this.directives;\n opt = null;\n break;\n default: {\n const sv = JSON.stringify(version);\n throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n }\n }\n // Not using `instanceof Schema` to allow for duck typing\n if (options.schema instanceof Object)\n this.schema = options.schema;\n else if (opt)\n this.schema = new Schema(Object.assign(opt, options));\n else\n throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n }\n // json & jsonArg are only used from toJSON()\n toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n const ctx = {\n anchors: new Map(),\n doc: this,\n keep: !json,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS(this.contents, jsonArg ?? '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n /**\n * A JSON representation of the document `contents`.\n *\n * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n * property name.\n */\n toJSON(jsonArg, onAnchor) {\n return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n }\n /** A YAML representation of the document. */\n toString(options = {}) {\n if (this.errors.length > 0)\n throw new Error('Document with errors cannot be stringified');\n if ('indent' in options &&\n (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n const s = JSON.stringify(options.indent);\n throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n }\n return stringifyDocument(this, options);\n }\n}\nfunction assertCollection(contents) {\n if (isCollection(contents))\n return true;\n throw new Error('Expected a YAML collection as document contents');\n}\n\nexport { Document };\n","import { BOM, DOCUMENT, FLOW_END, SCALAR } from './cst.js';\n\n/*\nSTART -> stream\n\nstream\n directive -> line-end -> stream\n indent + line-end -> stream\n [else] -> line-start\n\nline-end\n comment -> line-end\n newline -> .\n input-end -> END\n\nline-start\n doc-start -> doc\n doc-end -> stream\n [else] -> indent -> block-start\n\nblock-start\n seq-item-start -> block-start\n explicit-key-start -> block-start\n map-value-start -> block-start\n [else] -> doc\n\ndoc\n line-end -> line-start\n spaces -> doc\n anchor -> doc\n tag -> doc\n flow-start -> flow -> doc\n flow-end -> error -> doc\n seq-item-start -> error -> doc\n explicit-key-start -> error -> doc\n map-value-start -> doc\n alias -> doc\n quote-start -> quoted-scalar -> doc\n block-scalar-header -> line-end -> block-scalar(min) -> line-start\n [else] -> plain-scalar(false, min) -> doc\n\nflow\n line-end -> flow\n spaces -> flow\n anchor -> flow\n tag -> flow\n flow-start -> flow -> flow\n flow-end -> .\n seq-item-start -> error -> flow\n explicit-key-start -> flow\n map-value-start -> flow\n alias -> flow\n quote-start -> quoted-scalar -> flow\n comma -> flow\n [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n quote-end -> .\n [else] -> quoted-scalar\n\nblock-scalar(min)\n newline + peek(indent < min) -> .\n [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n scalar-end(is-flow) -> .\n peek(newline + (indent < min)) -> .\n [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n switch (ch) {\n case undefined:\n case ' ':\n case '\\n':\n case '\\r':\n case '\\t':\n return true;\n default:\n return false;\n }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n constructor() {\n /**\n * Flag indicating whether the end of the current buffer marks the end of\n * all input\n */\n this.atEnd = false;\n /**\n * Explicit indent set in block scalar header, as an offset from the current\n * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n * explicitly set.\n */\n this.blockScalarIndent = -1;\n /**\n * Block scalars that include a + (keep) chomping indicator in their header\n * include trailing empty lines, which are otherwise excluded from the\n * scalar's contents.\n */\n this.blockScalarKeep = false;\n /** Current input */\n this.buffer = '';\n /**\n * Flag noting whether the map value indicator : can immediately follow this\n * node within a flow context.\n */\n this.flowKey = false;\n /** Count of surrounding flow collection levels. */\n this.flowLevel = 0;\n /**\n * Minimum level of indentation required for next lines to be parsed as a\n * part of the current scalar value.\n */\n this.indentNext = 0;\n /** Indentation level of the current line. */\n this.indentValue = 0;\n /** Position of the next \\n character. */\n this.lineEndPos = null;\n /** Stores the state of the lexer if reaching the end of incpomplete input */\n this.next = null;\n /** A pointer to `buffer`; the current position of the lexer. */\n this.pos = 0;\n }\n /**\n * Generate YAML tokens from the `source` string. If `incomplete`,\n * a part of the last line may be left as a buffer for the next call.\n *\n * @returns A generator of lexical tokens\n */\n *lex(source, incomplete = false) {\n if (source) {\n if (typeof source !== 'string')\n throw TypeError('source is not a string');\n this.buffer = this.buffer ? this.buffer + source : source;\n this.lineEndPos = null;\n }\n this.atEnd = !incomplete;\n let next = this.next ?? 'stream';\n while (next && (incomplete || this.hasChars(1)))\n next = yield* this.parseNext(next);\n }\n atLineEnd() {\n let i = this.pos;\n let ch = this.buffer[i];\n while (ch === ' ' || ch === '\\t')\n ch = this.buffer[++i];\n if (!ch || ch === '#' || ch === '\\n')\n return true;\n if (ch === '\\r')\n return this.buffer[i + 1] === '\\n';\n return false;\n }\n charAt(n) {\n return this.buffer[this.pos + n];\n }\n continueScalar(offset) {\n let ch = this.buffer[offset];\n if (this.indentNext > 0) {\n let indent = 0;\n while (ch === ' ')\n ch = this.buffer[++indent + offset];\n if (ch === '\\r') {\n const next = this.buffer[indent + offset + 1];\n if (next === '\\n' || (!next && !this.atEnd))\n return offset + indent + 1;\n }\n return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n ? offset + indent\n : -1;\n }\n if (ch === '-' || ch === '.') {\n const dt = this.buffer.substr(offset, 3);\n if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n return -1;\n }\n return offset;\n }\n getLine() {\n let end = this.lineEndPos;\n if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n end = this.buffer.indexOf('\\n', this.pos);\n this.lineEndPos = end;\n }\n if (end === -1)\n return this.atEnd ? this.buffer.substring(this.pos) : null;\n if (this.buffer[end - 1] === '\\r')\n end -= 1;\n return this.buffer.substring(this.pos, end);\n }\n hasChars(n) {\n return this.pos + n <= this.buffer.length;\n }\n setNext(state) {\n this.buffer = this.buffer.substring(this.pos);\n this.pos = 0;\n this.lineEndPos = null;\n this.next = state;\n return null;\n }\n peek(n) {\n return this.buffer.substr(this.pos, n);\n }\n *parseNext(next) {\n switch (next) {\n case 'stream':\n return yield* this.parseStream();\n case 'line-start':\n return yield* this.parseLineStart();\n case 'block-start':\n return yield* this.parseBlockStart();\n case 'doc':\n return yield* this.parseDocument();\n case 'flow':\n return yield* this.parseFlowCollection();\n case 'quoted-scalar':\n return yield* this.parseQuotedScalar();\n case 'block-scalar':\n return yield* this.parseBlockScalar();\n case 'plain-scalar':\n return yield* this.parsePlainScalar();\n }\n }\n *parseStream() {\n let line = this.getLine();\n if (line === null)\n return this.setNext('stream');\n if (line[0] === BOM) {\n yield* this.pushCount(1);\n line = line.substring(1);\n }\n if (line[0] === '%') {\n let dirEnd = line.length;\n let cs = line.indexOf('#');\n while (cs !== -1) {\n const ch = line[cs - 1];\n if (ch === ' ' || ch === '\\t') {\n dirEnd = cs - 1;\n break;\n }\n else {\n cs = line.indexOf('#', cs + 1);\n }\n }\n while (true) {\n const ch = line[dirEnd - 1];\n if (ch === ' ' || ch === '\\t')\n dirEnd -= 1;\n else\n break;\n }\n const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n yield* this.pushCount(line.length - n); // possible comment\n this.pushNewline();\n return 'stream';\n }\n if (this.atLineEnd()) {\n const sp = yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - sp);\n yield* this.pushNewline();\n return 'stream';\n }\n yield DOCUMENT;\n return yield* this.parseLineStart();\n }\n *parseLineStart() {\n const ch = this.charAt(0);\n if (!ch && !this.atEnd)\n return this.setNext('line-start');\n if (ch === '-' || ch === '.') {\n if (!this.atEnd && !this.hasChars(4))\n return this.setNext('line-start');\n const s = this.peek(3);\n if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n yield* this.pushCount(3);\n this.indentValue = 0;\n this.indentNext = 0;\n return s === '---' ? 'doc' : 'stream';\n }\n }\n this.indentValue = yield* this.pushSpaces(false);\n if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n this.indentNext = this.indentValue;\n return yield* this.parseBlockStart();\n }\n *parseBlockStart() {\n const [ch0, ch1] = this.peek(2);\n if (!ch1 && !this.atEnd)\n return this.setNext('block-start');\n if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n this.indentNext = this.indentValue + 1;\n this.indentValue += n;\n return yield* this.parseBlockStart();\n }\n return 'doc';\n }\n *parseDocument() {\n yield* this.pushSpaces(true);\n const line = this.getLine();\n if (line === null)\n return this.setNext('doc');\n let n = yield* this.pushIndicators();\n switch (line[n]) {\n case '#':\n yield* this.pushCount(line.length - n);\n // fallthrough\n case undefined:\n yield* this.pushNewline();\n return yield* this.parseLineStart();\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel = 1;\n return 'flow';\n case '}':\n case ']':\n // this is an error\n yield* this.pushCount(1);\n return 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'doc';\n case '\"':\n case \"'\":\n return yield* this.parseQuotedScalar();\n case '|':\n case '>':\n n += yield* this.parseBlockScalarHeader();\n n += yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - n);\n yield* this.pushNewline();\n return yield* this.parseBlockScalar();\n default:\n return yield* this.parsePlainScalar();\n }\n }\n *parseFlowCollection() {\n let nl, sp;\n let indent = -1;\n do {\n nl = yield* this.pushNewline();\n if (nl > 0) {\n sp = yield* this.pushSpaces(false);\n this.indentValue = indent = sp;\n }\n else {\n sp = 0;\n }\n sp += yield* this.pushSpaces(true);\n } while (nl + sp > 0);\n const line = this.getLine();\n if (line === null)\n return this.setNext('flow');\n if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n (indent === 0 &&\n (line.startsWith('---') || line.startsWith('...')) &&\n isEmpty(line[3]))) {\n // Allowing for the terminal ] or } at the same (rather than greater)\n // indent level as the initial [ or { is technically invalid, but\n // failing here would be surprising to users.\n const atFlowEndMarker = indent === this.indentNext - 1 &&\n this.flowLevel === 1 &&\n (line[0] === ']' || line[0] === '}');\n if (!atFlowEndMarker) {\n // this is an error\n this.flowLevel = 0;\n yield FLOW_END;\n return yield* this.parseLineStart();\n }\n }\n let n = 0;\n while (line[n] === ',') {\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n this.flowKey = false;\n }\n n += yield* this.pushIndicators();\n switch (line[n]) {\n case undefined:\n return 'flow';\n case '#':\n yield* this.pushCount(line.length - n);\n return 'flow';\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel += 1;\n return 'flow';\n case '}':\n case ']':\n yield* this.pushCount(1);\n this.flowKey = true;\n this.flowLevel -= 1;\n return this.flowLevel ? 'flow' : 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'flow';\n case '\"':\n case \"'\":\n this.flowKey = true;\n return yield* this.parseQuotedScalar();\n case ':': {\n const next = this.charAt(1);\n if (this.flowKey || isEmpty(next) || next === ',') {\n this.flowKey = false;\n yield* this.pushCount(1);\n yield* this.pushSpaces(true);\n return 'flow';\n }\n }\n // fallthrough\n default:\n this.flowKey = false;\n return yield* this.parsePlainScalar();\n }\n }\n *parseQuotedScalar() {\n const quote = this.charAt(0);\n let end = this.buffer.indexOf(quote, this.pos + 1);\n if (quote === \"'\") {\n while (end !== -1 && this.buffer[end + 1] === \"'\")\n end = this.buffer.indexOf(\"'\", end + 2);\n }\n else {\n // double-quote\n while (end !== -1) {\n let n = 0;\n while (this.buffer[end - 1 - n] === '\\\\')\n n += 1;\n if (n % 2 === 0)\n break;\n end = this.buffer.indexOf('\"', end + 1);\n }\n }\n // Only looking for newlines within the quotes\n const qb = this.buffer.substring(0, end);\n let nl = qb.indexOf('\\n', this.pos);\n if (nl !== -1) {\n while (nl !== -1) {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = qb.indexOf('\\n', cs);\n }\n if (nl !== -1) {\n // this is an error caused by an unexpected unindent\n end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n }\n }\n if (end === -1) {\n if (!this.atEnd)\n return this.setNext('quoted-scalar');\n end = this.buffer.length;\n }\n yield* this.pushToIndex(end + 1, false);\n return this.flowLevel ? 'flow' : 'doc';\n }\n *parseBlockScalarHeader() {\n this.blockScalarIndent = -1;\n this.blockScalarKeep = false;\n let i = this.pos;\n while (true) {\n const ch = this.buffer[++i];\n if (ch === '+')\n this.blockScalarKeep = true;\n else if (ch > '0' && ch <= '9')\n this.blockScalarIndent = Number(ch) - 1;\n else if (ch !== '-')\n break;\n }\n return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n }\n *parseBlockScalar() {\n let nl = this.pos - 1; // may be -1 if this.pos === 0\n let indent = 0;\n let ch;\n loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n switch (ch) {\n case ' ':\n indent += 1;\n break;\n case '\\n':\n nl = i;\n indent = 0;\n break;\n case '\\r': {\n const next = this.buffer[i + 1];\n if (!next && !this.atEnd)\n return this.setNext('block-scalar');\n if (next === '\\n')\n break;\n } // fallthrough\n default:\n break loop;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('block-scalar');\n if (indent >= this.indentNext) {\n if (this.blockScalarIndent === -1)\n this.indentNext = indent;\n else {\n this.indentNext =\n this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n }\n do {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = this.buffer.indexOf('\\n', cs);\n } while (nl !== -1);\n if (nl === -1) {\n if (!this.atEnd)\n return this.setNext('block-scalar');\n nl = this.buffer.length;\n }\n }\n // Trailing insufficiently indented tabs are invalid.\n // To catch that during parsing, we include them in the block scalar value.\n let i = nl + 1;\n ch = this.buffer[i];\n while (ch === ' ')\n ch = this.buffer[++i];\n if (ch === '\\t') {\n while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n ch = this.buffer[++i];\n nl = i - 1;\n }\n else if (!this.blockScalarKeep) {\n do {\n let i = nl - 1;\n let ch = this.buffer[i];\n if (ch === '\\r')\n ch = this.buffer[--i];\n const lastChar = i; // Drop the line if last char not more indented\n while (ch === ' ')\n ch = this.buffer[--i];\n if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n nl = i;\n else\n break;\n } while (true);\n }\n yield SCALAR;\n yield* this.pushToIndex(nl + 1, true);\n return yield* this.parseLineStart();\n }\n *parsePlainScalar() {\n const inFlow = this.flowLevel > 0;\n let end = this.pos - 1;\n let i = this.pos - 1;\n let ch;\n while ((ch = this.buffer[++i])) {\n if (ch === ':') {\n const next = this.buffer[i + 1];\n if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n break;\n end = i;\n }\n else if (isEmpty(ch)) {\n let next = this.buffer[i + 1];\n if (ch === '\\r') {\n if (next === '\\n') {\n i += 1;\n ch = '\\n';\n next = this.buffer[i + 1];\n }\n else\n end = i;\n }\n if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n break;\n if (ch === '\\n') {\n const cs = this.continueScalar(i + 1);\n if (cs === -1)\n break;\n i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n }\n }\n else {\n if (inFlow && flowIndicatorChars.has(ch))\n break;\n end = i;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('plain-scalar');\n yield SCALAR;\n yield* this.pushToIndex(end + 1, true);\n return inFlow ? 'flow' : 'doc';\n }\n *pushCount(n) {\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos += n;\n return n;\n }\n return 0;\n }\n *pushToIndex(i, allowEmpty) {\n const s = this.buffer.slice(this.pos, i);\n if (s) {\n yield s;\n this.pos += s.length;\n return s.length;\n }\n else if (allowEmpty)\n yield '';\n return 0;\n }\n *pushIndicators() {\n switch (this.charAt(0)) {\n case '!':\n return ((yield* this.pushTag()) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n case '&':\n return ((yield* this.pushUntil(isNotAnchorChar)) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n case '-': // this is an error\n case '?': // this is an error outside flow collections\n case ':': {\n const inFlow = this.flowLevel > 0;\n const ch1 = this.charAt(1);\n if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n if (!inFlow)\n this.indentNext = this.indentValue + 1;\n else if (this.flowKey)\n this.flowKey = false;\n return ((yield* this.pushCount(1)) +\n (yield* this.pushSpaces(true)) +\n (yield* this.pushIndicators()));\n }\n }\n }\n return 0;\n }\n *pushTag() {\n if (this.charAt(1) === '<') {\n let i = this.pos + 2;\n let ch = this.buffer[i];\n while (!isEmpty(ch) && ch !== '>')\n ch = this.buffer[++i];\n return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n }\n else {\n let i = this.pos + 1;\n let ch = this.buffer[i];\n while (ch) {\n if (tagChars.has(ch))\n ch = this.buffer[++i];\n else if (ch === '%' &&\n hexDigits.has(this.buffer[i + 1]) &&\n hexDigits.has(this.buffer[i + 2])) {\n ch = this.buffer[(i += 3)];\n }\n else\n break;\n }\n return yield* this.pushToIndex(i, false);\n }\n }\n *pushNewline() {\n const ch = this.buffer[this.pos];\n if (ch === '\\n')\n return yield* this.pushCount(1);\n else if (ch === '\\r' && this.charAt(1) === '\\n')\n return yield* this.pushCount(2);\n else\n return 0;\n }\n *pushSpaces(allowTabs) {\n let i = this.pos - 1;\n let ch;\n do {\n ch = this.buffer[++i];\n } while (ch === ' ' || (allowTabs && ch === '\\t'));\n const n = i - this.pos;\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos = i;\n }\n return n;\n }\n *pushUntil(test) {\n let i = this.pos;\n let ch = this.buffer[i];\n while (!test(ch))\n ch = this.buffer[++i];\n return yield* this.pushToIndex(i, false);\n }\n}\n\nexport { Lexer };\n","import { Composer } from './compose/composer.js';\nimport { Document } from './doc/Document.js';\nimport { prettifyError, YAMLParseError } from './errors.js';\nimport { warn } from './log.js';\nimport { isDocument } from './nodes/identity.js';\nimport { LineCounter } from './parse/line-counter.js';\nimport { Parser } from './parse/parser.js';\n\nfunction parseOptions(options) {\n const prettyErrors = options.prettyErrors !== false;\n const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;\n return { lineCounter, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n * EmptyStream and contain additional stream information. In\n * TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser = new Parser(lineCounter?.addNewLine);\n const composer = new Composer(options);\n const docs = Array.from(composer.compose(parser.parse(source)));\n if (prettyErrors && lineCounter)\n for (const doc of docs) {\n doc.errors.forEach(prettifyError(source, lineCounter));\n doc.warnings.forEach(prettifyError(source, lineCounter));\n }\n if (docs.length > 0)\n return docs;\n return Object.assign([], { empty: true }, composer.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser = new Parser(lineCounter?.addNewLine);\n const composer = new Composer(options);\n // `doc` is always set by compose.end(true) at the very latest\n let doc = null;\n for (const _doc of composer.compose(parser.parse(source), true, source.length)) {\n if (!doc)\n doc = _doc;\n else if (doc.options.logLevel !== 'silent') {\n doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n break;\n }\n }\n if (prettyErrors && lineCounter) {\n doc.errors.forEach(prettifyError(source, lineCounter));\n doc.warnings.forEach(prettifyError(source, lineCounter));\n }\n return doc;\n}\nfunction parse(src, reviver, options) {\n let _reviver = undefined;\n if (typeof reviver === 'function') {\n _reviver = reviver;\n }\n else if (options === undefined && reviver && typeof reviver === 'object') {\n options = reviver;\n }\n const doc = parseDocument(src, options);\n if (!doc)\n return null;\n doc.warnings.forEach(warning => warn(doc.options.logLevel, warning));\n if (doc.errors.length > 0) {\n if (doc.options.logLevel !== 'silent')\n throw doc.errors[0];\n else\n doc.errors = [];\n }\n return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n }\n if (typeof options === 'string')\n options = options.length;\n if (typeof options === 'number') {\n const indent = Math.round(options);\n options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n }\n if (value === undefined) {\n const { keepUndefined } = options ?? replacer ?? {};\n if (!keepUndefined)\n return undefined;\n }\n if (isDocument(value) && !_replacer)\n return value.toString(options);\n return new Document(value, _replacer, options).toString(options);\n}\n\nexport { parse, parseAllDocuments, parseDocument, stringify };\n","import { z } from 'zod';\nimport { stringify } from 'yaml';\nimport {\n\tgetDataSourceFieldsWithDescriptions,\n\tDataSourceFieldWithDescription,\n} from '@/services/data-sources/data-sources-service';\nimport { DataSourceField } from '@sisense/sdk-data';\nimport {\n\tTOOL_NAME_GET_DATA_SOURCE_FIELDS,\n\tMAX_DATA_SOURCE_FIELDS_SUMMARY,\n} from '@/constants';\nimport {\n\tgetDataSourceFieldsSchema,\n\tGetDataSourceFieldsContext,\n\tDataSourceFieldsResult,\n} from './types';\n\n/**\n * Fetches fields for a data source (decoupled from UI/store).\n * @param params - The parameters containing the data source title\n * @param context - Context with tool call ID for tracking\n * @returns Raw result: dataSourceTitle and fields array for UI and for building the LLM summary.\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\nfunction buildCompactSchema(\n\tdataSourceTitle: string,\n\tmessage: string,\n\tisTruncated: boolean,\n\ttables: Record<string, string[]>,\n): string {\n\tconst truncationNote = isTruncated\n\t\t? ' (truncated summary from the data source)'\n\t\t: '';\n\tconst intro = `${dataSourceTitle}: ${message}${truncationNote}.`;\n\tconst tableEntries = Object.keys(tables);\n\tif (tableEntries.length === 0) {\n\t\treturn intro;\n\t}\n\tconst tablesYaml = stringify(tables, {\n\t\tdefaultStringType: 'PLAIN',\n\t}).trimEnd();\n\treturn `${intro}\\n\\n${tablesYaml}`;\n}\n\n/**\n * Builds the compact schema string returned to the LLM (intro + tables/columns).\n * Reduces token use by returning a single string instead of a JSON object.\n * @param dataSourceTitle - The title of the data source\n * @param fields - The full list of fields from the data source\n * @returns A compact schema string with table and column names (truncated if needed)\n */\nexport function getDataSourceFieldsSummary(\n\tdataSourceTitle: string,\n\tfields: DataSourceFieldWithDescription[] | DataSourceField[],\n): string {\n\tconst totalFields = fields.length;\n\tconst tableCount = new Set(fields.map((f) => f.table)).size;\n\tconst truncatedFields = fields.slice(0, MAX_DATA_SOURCE_FIELDS_SUMMARY);\n\tconst isTruncated = totalFields > MAX_DATA_SOURCE_FIELDS_SUMMARY;\n\n\tconst tables: Record<string, string[]> = {};\n\tfor (const field of truncatedFields) {\n\t\tconst tableName = field.table;\n\t\tif (!tables[tableName]) tables[tableName] = [];\n\t\ttables[tableName].push(field.column);\n\t}\n\n\tconst fieldsLabel = totalFields === 1 ? 'field' : 'fields';\n\tconst tablesLabel = tableCount === 1 ? 'table' : 'tables';\n\tconst message = isTruncated\n\t\t? `Retrieved ${totalFields} ${fieldsLabel} from ${tableCount} ${tablesLabel} (showing first ${MAX_DATA_SOURCE_FIELDS_SUMMARY} in summary)`\n\t\t: `Retrieved ${totalFields} ${fieldsLabel} from ${tableCount} ${tablesLabel}`;\n\n\treturn buildCompactSchema(dataSourceTitle, message, isTruncated, tables);\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 (raw data for UI and for building the LLM summary).\n */\nexport interface DataSourceFieldsResult {\n\tdataSourceTitle: string;\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","import { z } from 'zod';\nimport { getAvailableFusionDashboards } from '@/services/dashboards/fusion-dashboards-service';\nimport { TOOL_NAME_GET_DASHBOARDS } from '@/constants';\nimport {\n\tgetDashboardsSchema,\n\tGetDashboardsContext,\n\tDashboardsResult,\n} from './types';\n\n/**\n * Standalone dashboards engine - completely decoupled from any UI or store\n * @param params - The parameters for getting dashboards (currently empty)\n * @param context - Context with tool call ID for tracking\n * @returns The dashboards result with list of dashboards\n */\nexport async function getDashboardsEngine(\n\tparams: z.infer<typeof getDashboardsSchema>,\n\tcontext: GetDashboardsContext,\n): Promise<DashboardsResult> {\n\tconsole.debug(TOOL_NAME_GET_DASHBOARDS, context.toolCallId);\n\n\tconst dashboards = await getAvailableFusionDashboards(context.httpClient);\n\n\treturn {\n\t\tdashboards,\n\t};\n}\n","import { z } from 'zod';\nimport { Dashboard } from '@/services/dashboards/fusion-dashboards-service';\nimport { HttpClient } from '@sisense/sdk-rest-client';\n\n/**\n * Schema for getDashboards engine parameters\n */\nexport const getDashboardsSchema = z.object({});\n\n/**\n * Context interface for getDashboardsEngine\n */\nexport interface GetDashboardsContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\thttpClient?: HttpClient;\n}\n\n/**\n * Result from getDashboardsEngine\n */\nexport interface DashboardsResult {\n\t/**\n\t * List of dashboards\n\t */\n\tdashboards: Dashboard[];\n}\n","import {\n\tDashboardProps,\n\tWidgetProps,\n\tChartType,\n\tWidgetType,\n} from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport OpenAI from 'openai';\nimport { z } from 'zod';\nimport { ChartSummary, ArtifactReference } from '../chart-builder/types';\n\nexport type ExtendedDashboardProps = DashboardProps & ArtifactReference;\n\n/**\n * Chart list summary for LLM context\n */\nexport type ChartListSummary = {\n\tmessage: string;\n\tcreatedAt: string;\n\tchartListId: string;\n};\n\n/**\n * Base dashboard summary for LLM consumption and asset extraction\n */\nexport type BaseDashboardSummary = {\n\t/** Fusion dashboard ID */\n\tfusionDashboardId?: string;\n\t/** Human-readable title of the dashboard */\n\tdashboardTitle?: string;\n\t/** Default data source title for the dashboard */\n\tdefaultDataSourceTitle: string;\n\t/** Array of widget summaries */\n\twidgets: Array<{\n\t\t/** Widget ID */\n\t\twidgetId?: string;\n\t\t/** Widget title (for chart and pivot table widgets) */\n\t\twidgetTitle?: string;\n\t\t/** Widget type (for chart and pivot table widgets) */\n\t\twidgetType?: WidgetType;\n\t\t/** Chart type (for chart widgets only) */\n\t\tchartType?: ChartType;\n\t}>;\n};\n\n/**\n * Summary of a dashboard for LLM consumption and asset extraction\n */\nexport interface DashboardSummary {\n\t/** Status message indicating success or failure */\n\tmessage: string;\n\t/** Date and time ISO string of when the dashboard was created */\n\tcreatedAt: string;\n\t/** Unique identifier for the dashboard (typically the tool call ID) */\n\tdashboardId: string;\n\t/** Dashboard details, undefined if dashboard creation failed */\n\tdashboard?: BaseDashboardSummary;\n}\n\n/**\n * Schema for the main buildDashboard smart tool\n */\nexport const buildDashboardSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tuserPrompt: z.string().describe(\n\t\t`Combined natural language user prompt describing actions on a dashboard.\n\t\t\nExamples:\n- \"Create a dashboard with sales charts\"\n- \"Load dashboard ABC123\"\n- \"Add revenue chart to the current dashboard\"\n- \"Rename the dashboard to 'Q4 Sales Report'\"\n- \"Add filters for region and date to the dashboard\"\n`,\n\t),\n});\n\nexport type BuildDashboardParams = z.infer<typeof buildDashboardSchema>;\n\n/**\n * Schema for createDashboard tool\n */\nexport const createDashboardSchema = z.object({\n\tdashboardTitle: z.string().optional().describe('Optional dashboard title'),\n\twidgetIdsToAdd: z\n\t\t.array(z.string())\n\t\t.describe(\n\t\t\t'Chart Widget IDs or Chart Widget List ID to add to the dashboard. Use empty array if no charts are found',\n\t\t),\n});\n\nexport type CreateDashboardParams = z.infer<typeof createDashboardSchema>;\n\n/**\n * Schema for loadExistingDashboard tool\n */\nexport const loadExistingFusionDashboardSchema = z.object({\n\tdashboardTitle: z.string().describe('Fusion dashboard title to load'),\n});\n\nexport type LoadExistingFusionDashboardParams = z.infer<\n\ttypeof loadExistingFusionDashboardSchema\n>;\n\n/**\n * Schema for updateDashboard tool\n */\nexport const updateDashboardSchema = z.object({\n\tdashboardId: z.string().describe('Dashboard ID to update'),\n\tdashboardTitle: z.string().describe('New dashboard title'),\n});\n\nexport type UpdateDashboardParams = z.infer<typeof updateDashboardSchema>;\n\n/**\n * Schema for addDashboardWidgets tool\n */\nexport const addDashboardWidgetsSchema = z.object({\n\tdashboardId: z.string().describe('Existing dashboard ID to add widgets to'),\n\twidgetIdsToAdd: z\n\t\t.array(z.string())\n\t\t.describe('Chart IDs or Chart List ID to add to the dashboard'),\n});\n\nexport type AddDashboardWidgetsParams = z.infer<\n\ttypeof addDashboardWidgetsSchema\n>;\n\n/**\n * Schema for createChartForDashboard tool\n */\nexport const createChartWidgetForDashboardSchema = z.object({\n\tdashboardId: z.string().describe('Existing dashboard ID to add a chart to'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('User prompt to describe a chart widget for the dashboard'),\n});\n\nexport type CreateChartWidgetForDashboardParams = z.infer<\n\ttypeof createChartWidgetForDashboardSchema\n>;\n\n/**\n * Schema for updateChartWidgetForDashboard tool\n */\nexport const updateChartWidgetForDashboardSchema = z.object({\n\tdashboardId: z\n\t\t.string()\n\t\t.describe('Existing dashboard ID to update a chart widget in'),\n\twidgetId: z.string().describe('Widget ID to update'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('User prompt to describe the update to the chart widget'),\n});\n\nexport type UpdateChartWidgetForDashboardParams = z.infer<\n\ttypeof updateChartWidgetForDashboardSchema\n>;\n\n/**\n * Schema for addDashboardFilters tool\n */\nexport const addDashboardFiltersSchema = z.object({\n\tdashboardId: z.string().describe('Dashboard ID to add filters to'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.describe('Combined user prompt to add filters to the dashboard.'),\n});\n\nexport type AddDashboardFiltersParams = z.infer<\n\ttypeof addDashboardFiltersSchema\n>;\n\n/**\n * Build dashboard context interface\n */\nexport interface BuildDashboardContext {\n\t/**\n\t * Tool call ID - REQUIRED\n\t */\n\ttoolCallId: string;\n\t/**\n\t * Data source title (required)\n\t */\n\tdataSourceTitle: string;\n\t/**\n\t * Chart summaries for context\n\t */\n\tchartSummaries?: ChartSummary[];\n\t/**\n\t * Chart list summaries for context\n\t */\n\tchartListSummaries?: ChartListSummary[];\n\t/**\n\t * Dashboard summaries for context\n\t */\n\tdashboardSummaries?: DashboardSummary[];\n\t/**\n\t * Retrieve a dashboard by ID (optional)\n\t * @param dashboardId - The ID of the dashboard to retrieve\n\t * @returns The dashboard props or null\n\t */\n\tretrieveDashboard?: (dashboardId: string) => ExtendedDashboardProps | null;\n\t/**\n\t * Save dashboard props (optional)\n\t * @param dashboardProps - The dashboard props to save\n\t */\n\tsaveDashboard?: (dashboardProps: ExtendedDashboardProps) => void;\n\t/**\n\t * Get widget list by IDs (optional)\n\t * @param widgetIds - The IDs of widgets to retrieve\n\t * @returns Array of widget props\n\t */\n\tgetWidgetList?: (widgetIds: string[]) => WidgetProps[];\n\t/**\n\t * Whether NLQ V3 is enabled\n\t */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\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 {\n\tCreateDashboardParams,\n\tExtendedDashboardProps,\n\tBuildDashboardContext,\n} from './types';\nimport { createNewDashboard } from '@/services/dashboards/dashboards-service';\nimport { nanoidHex } from '@/utils/id-utils';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const createDashboard = async (\n\t{ dashboardTitle, widgetIdsToAdd }: CreateDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { dataSourceTitle, getWidgetList, saveDashboard, httpClient } =\n\t\tcontext;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createDashboard',\n\t\tdashboardTitle,\n\t\twidgetIdsToAdd,\n\t);\n\n\tlet newWidgetList: WidgetProps[] = [];\n\ttry {\n\t\tnewWidgetList =\n\t\t\t(widgetIdsToAdd && widgetIdsToAdd.length > 0\n\t\t\t\t? getWidgetList?.(widgetIdsToAdd)\n\t\t\t\t: []) || [];\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t'Error: Failed to locate input chart widgets. Empty widget list will be used.',\n\t\t\terror,\n\t\t);\n\t}\n\n\tconst dashboardProps: ExtendedDashboardProps = await createNewDashboard(\n\t\tdataSourceTitle,\n\t\tdashboardTitle || `Dashboard for ${dataSourceTitle}`,\n\t\tnewWidgetList,\n\t\thttpClient,\n\t);\n\n\t// generate a new artifact id for the dashboard\n\tdashboardProps.artifactId = nanoidHex();\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tnewWidgetList.length > 0\n\t\t\t\t? 'Dashboard created successfully. Click \"Save\" to persist to My Dashboards.'\n\t\t\t\t: 'Dashboard created with no chart widgets. Run the createChartWidgetForDashboard tool to create one.',\n\t};\n};\n","import {\n\tExtendedDashboardProps,\n\tLoadExistingFusionDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport { getAvailableFusionDashboards } from '@/services/dashboards/fusion-dashboards-service';\nimport { loadExistingDashboardFromFusion } from '@/services/dashboards/fusion-dashboards-service';\nimport { getBaseDashboardConfig } from '@/services/dashboards/dashboards-service';\nimport { nanoidHex } from '@/utils/id-utils';\n\nexport const loadExistingFusionDashboard = async (\n\t{ dashboardTitle }: LoadExistingFusionDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { saveDashboard, httpClient } = context;\n\tconsole.debug('toolCall', 'loadExistingFusionDashboard', dashboardTitle);\n\n\tconst availableDashboards = await getAvailableFusionDashboards(httpClient);\n\n\tconst fusionDashboard = availableDashboards.find(\n\t\t(dashboard) => dashboard.dashboardTitle === dashboardTitle,\n\t);\n\n\tif (!fusionDashboard) {\n\t\tthrow new Error(\n\t\t\t`Fusion dashboard with title ${dashboardTitle} not found`,\n\t\t);\n\t}\n\n\tconst dashboardProps: ExtendedDashboardProps =\n\t\tawait loadExistingDashboardFromFusion(\n\t\t\tfusionDashboard.dashboardId,\n\t\t\thttpClient,\n\t\t);\n\n\tconst updatedDashboardProps: ExtendedDashboardProps = {\n\t\t...dashboardProps,\n\t\t// Use the base dashboard config to ensure the dashboard is created with the correct default settings\n\t\tconfig: {\n\t\t\t...dashboardProps.config,\n\t\t\t...getBaseDashboardConfig(),\n\t\t},\n\t\t// Generate a new artifact id for the dashboard\n\t\tartifactId: dashboardProps.artifactId || nanoidHex(),\n\t};\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage: 'Dashboard loaded successfully from Fusion.',\n\t};\n};\n","import { UpdateDashboardParams, BuildDashboardContext } from './types';\nimport { updateDashboardTitle } from '@/services/dashboards/dashboards-service';\n\nexport const updateDashboard = async (\n\t{ dashboardId, dashboardTitle }: UpdateDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { retrieveDashboard, saveDashboard } = context;\n\tconsole.debug('toolCall', 'updateDashboard', dashboardId, dashboardTitle);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tlet dashboardProps = currentDashboard;\n\tif (dashboardTitle && dashboardTitle !== dashboardProps.title) {\n\t\tdashboardProps = updateDashboardTitle(dashboardProps, dashboardTitle);\n\t}\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\t'Dashboard updated successfully. Click \"Save\" to persist changes to My Dashboards.',\n\t};\n};\n","import { AddDashboardWidgetsParams, BuildDashboardContext } from './types';\nimport { addWidgetsToExistingDashboard } from '@/services/dashboards/dashboards-service';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const addDashboardWidgets = async (\n\t{ dashboardId, widgetIdsToAdd }: AddDashboardWidgetsParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { retrieveDashboard, saveDashboard, getWidgetList } = context;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'addDashboardWidgets',\n\t\tdashboardId,\n\t\twidgetIdsToAdd,\n\t);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tlet newWidgetList: WidgetProps[] = [];\n\ttry {\n\t\tnewWidgetList = getWidgetList?.(widgetIdsToAdd) || [];\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t'Error: Failed to locate input chart widgets. Empty widget list will be used.',\n\t\t\terror,\n\t\t);\n\t}\n\tconst dashboardProps = addWidgetsToExistingDashboard(\n\t\tcurrentDashboard,\n\t\tnewWidgetList,\n\t);\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tnewWidgetList.length > 0\n\t\t\t\t? 'Widgets added successfully. Click \"Save\" to persist changes to My Dashboards.'\n\t\t\t\t: widgetIdsToAdd.length > 0\n\t\t\t\t? 'Widgets cannot be located. Try to create chart widgets one by one and add them to the dashboard.'\n\t\t\t\t: 'Widgets cannot be located. Run the recommend queries tool and add them all as widgets to the dashboard.',\n\t};\n};\n","export const FILTER_FACTORY_TYPES = `import {\n\tDateDimension,\n\tLevelAttribute,\n\tAttribute,\n\tMeasure,\n\tFilter,\n\tBaseMeasure,\n\tFilterRelationsNode,\n\tFilterRelations,\n\tMembersFilterConfig,\n\tBaseFilterConfig,\n} from '../interfaces.js';\n/**\n * Creates a filter representing the union of multiple filters on the same attribute. The resulting\n * union filter filters on items that match any of the given filters.\n *\n * To create 'or' filters using different attributes, use the {@link logic.and | \\`or()\\`} function.\n *\n * @example\n * Filter for countries that start with the letter 'A' **or** end with the letter 'A'\n * in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.union([\n * filterFactory.startsWith(DM.Country.Country, 'A'),\n * filterFactory.endsWith(DM.Country.Country, 'A'),\n * ])\n * \\`\\`\\`\n * @param filters - Filters to union. The filters must all be on the same attribute.\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function union(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter representing the intersection of multiple filters on the same attribute. The resulting\n * intersection filter filters on items that match all of the given filters.\n *\n * To create 'and' filters using different attributes, use the {@link logic.and | \\`and()\\`} function.\n *\n * @example\n * Filter for countries that start with the letter 'A' **and** end with the letter 'A'\n * in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.intersection([\n * filterFactory.startsWith(DM.Country.Country, 'A'),\n * filterFactory.endsWith(DM.Country.Country, 'A'),\n * ])\n * \\`\\`\\`\n * @param filters - Filters to intersect. The filters must all be on the same attribute.\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function intersection(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter that excludes items matching the given filter\n * from all items or from items matching the optional input filter.\n *\n * @example\n * Filter for items where the country name does not contain the letter 'A'\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.exclude(filterFactory.contains(DM.Country.Country, 'A'))\n * \\`\\`\\`\n *\n * Filter for items where the country name starts with the letter 'B' but does not contain the letter 'A'\n * from the Sample ECommerce data model. This filter will match countries like 'Belgium', but will not\n * match countries like 'Bermuda'.\n * \\`\\`\\`ts\n * filterFactory.exclude(\n * filterFactory.contains(DM.Country.Country, 'A'),\n * filterFactory.startsWith(DM.Country.Country, 'B')\n * )\n * \\`\\`\\`\n * @param filter - Filter to exclude\n * @param input - Input filter to exclude from, on the same attribute. If not provided, the filter excludes from all items.\n * @param config - Optional configuration for the filter\n * @returns A filter representing an exclusion of the given filter\n * from all attribute members or from the optional input filter\n */\nexport declare function exclude(filter: Filter, input?: Filter, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate attribute values that do not contain a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for categories in the Sample ECommerce data model where the category name doesn't contain\n * 'digital'. This filter matches categories not like 'Digital Cameras' and 'MP3 & Digital Media Players'.\n * \\`\\`\\`ts\n * filterFactory.contains(DM.Category.Category, 'digital')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntContain(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not end with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name doesn't end with\n * 'land'. This filter matches countries not like 'Iceland' and 'Ireland'.\n * \\`\\`\\`ts\n * filterFactory.doesntEndWith(DM.Country.Country, 'land')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntEndWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not start with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name doesn't start with\n * 'United'. This filter matches countries not like 'United States' and 'United Kingdom'.\n * \\`\\`\\`ts\n * filterFactory.doesntStartWith(DM.Country.Country, 'United')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntStartWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that contain a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for categories in the Sample ECommerce data model where the category name contains\n * 'digital'. This filter matches categories like 'Digital Cameras' and 'MP3 & Digital Media Players'.\n * \\`\\`\\`ts\n * filterFactory.contains(DM.Category.Category, 'digital')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function contains(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that end with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name ends with\n * 'land'. This filter matches countries like 'Ireland' and 'Iceland'.\n * \\`\\`\\`ts\n * filterFactory.endsWith(DM.Country.Country, 'land')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function endsWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that start with a specified string.\n *\n * Matching is case insensitive.\n *\n * You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for countries in the Sample ECommerce data model where the country name starts with\n * 'United'. This filter matches countries like 'United States' and 'United Kingdom'.\n * \\`\\`\\`ts\n * filterFactory.startsWith(DM.Country.Country, 'United')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function startsWith(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that match a specified string pattern.\n *\n * The pattern can include the following wildcard characters:\n *\n * + \\`_\\`: Matches a single character\n * + \\`%\\`: Matches multiple characters\n *\n * To search for a literal underscore (\\`_\\`) or percent symbol (\\`%\\`), use the backslash (\\`\\\\\\`) escape\n * character.\n *\n * Matching is case insensitive.\n *\n * @example\n * Filter for countries from the Sample ECommerce data model where the country name starts with an\n * 'A' and ends with an 'a'. This filter matches countries like 'Argentina' and 'Australia'.\n * \\`\\`\\`ts\n * filterFactory.like(DM.Country.Country, 'A%a')\n * \\`\\`\\`\n * @param attribute - Text attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function like(\n\tattribute: Attribute,\n\tvalue: string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that do not equal a specified string or number.\n *\n * When filtering against a string:\n *\n * + Matching is case insensitive.\n * + You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for items not in new condition from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.doesntEqual(DM.Commerce.Condition, 'New')\n * \\`\\`\\`\n * @param attribute - Text or numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function doesntEqual(\n\tattribute: Attribute,\n\tvalue: string | number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that equal a specified string or number.\n *\n * When filtering against a string:\n *\n * + Matching is case insensitive.\n * + You can optionally use wildcard characters for pattern matching, as described in the\n * {@link like | \\`like()\\`} function.\n *\n * @example\n * Filter for items in new condition from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.equals(DM.Commerce.Condition, 'New')\n * \\`\\`\\`\n * @param attribute - Text or numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function equals(\n\tattribute: Attribute,\n\tvalue: string | number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values strictly greater than a specified number.\n *\n * @example\n * Filter for items where the cost is greater than 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.greaterThan(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function greaterThan(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values greater than or equal to a specified number.\n *\n * @example\n * Filter for items where the cost is greater than or equal to 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.greaterThanOrEqual(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function greaterThanOrEqual(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values strictly less than a specified number.\n *\n * @example\n * Filter for items where the cost is less than 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.lessThan(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function lessThan(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values less than or equal to a specified number.\n *\n * @example\n * Filter for items where the cost is less than or equal to 100 from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.lessThanOrEqual(DM.Commerce.Cost, 100)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param value - Value to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function lessThanOrEqual(\n\tattribute: Attribute,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values within or exactly matching two specified numerical boundaries.\n *\n * @example\n * Filter for items from the Sample ECommerce data model where the cost is greater than or equal to 100 and less than or equal to 200.\n * \\`\\`\\`ts\n * filterFactory.between(DM.Commerce.Cost, 100, 200)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param valueA - Value to filter from\n * @param valueB - Value to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function between(\n\tattribute: Attribute,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter that isolates attribute values strictly within two specified numerical boundaries.\n *\n * @example\n * Filter for items from the Sample ECommerce data model where the cost is greater than 100 and less than 200.\n * \\`\\`\\`ts\n * filterFactory.betweenNotEqual(DM.Commerce.Cost, 100, 200)\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter on\n * @param valueA - Value to filter from\n * @param valueB - Value to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function betweenNotEqual(\n\tattribute: Attribute,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a custom numeric filter that filters for given attribute values.\n *\n * @example\n * Filter for items where the cost is greater than 100 and less than 200\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.numeric(\n * DM.Commerce.Cost,\n * NumericOperators.From,\n * 100,\n * NumericOperators.To,\n * 200\n * )\n * \\`\\`\\`\n * @param attribute - Numeric attribute to filter\n * @param operatorA - First operator\n * @param valueA - First value\n * @param operatorB - Second operator\n * @param valueB - Second value\n * @param config - Optional configuration for the filter\n * @returns A custom numeric filter of the given attribute\n */\nexport declare function numeric(\n\tattribute: Attribute,\n\toperatorA?: string,\n\tvalueA?: number,\n\toperatorB?: string,\n\tvalueB?: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate attribute values that match any of the specified strings.\n *\n * Matching is case sensitive.\n *\n * @example\n * Filter for items where the condition is 'Used' or 'Refurbished'\n * from the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.members(DM.Commerce.Condition, ['Used', 'Refurbished'])\n * \\`\\`\\`\n * @param attribute - Attribute to filter on\n * @param members - Array of member values to filter by\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n * @shortDescription Creates filter on attribute to match certain string values\n */\nexport declare function members(\n\tattribute: Attribute,\n\tmembers: string[],\n\tconfig?: MembersFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate date values starting from and including the given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is not before the year 2010.\n * \\`\\`\\`ts\n * filterFactory.dateFrom(DM.Commerce.Date.Years, '2010-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param from - Date or string representing the value to filter from\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateFrom(\n\tlevel: LevelAttribute,\n\tfrom: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items up until and including the given date and level.\n *\n * @example\n * Filter for items where the date is from the year 2010 or earlier in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.dateTo(DM.Commerce.Date.Years, '2010-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param to - Date or string representing the last member to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateTo(\n\tlevel: LevelAttribute,\n\tto: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items between and including the given dates and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is from the years 2009, 2010, or 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRange(DM.Commerce.Date.Years, '2009-01', '2011-01')\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param from - Date or string representing the start member to filter from\n * @param to - Date or string representing the end member to filter to\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRange(\n\tlevel: LevelAttribute,\n\tfrom?: Date | string,\n\tto?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range after a\n * given date and level.\n *\n * Although the \\`offset\\` can be used to set a beginning date prior to the \\`anchor\\`, the filter range always\n * continues forward after the offset beginning date. So, using an \\`offset\\` of \\`-6\\` and a \\`count\\` of \\`18\\` when \\`level\\`\n * is a month level creates a range that begins 6 month before the \\`anchor\\` date and extends to 12 months after\n * the \\`anchor\\` date.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in 2011 or the first half of 2012.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, 0, 18, '2011-01'),\n * \\`\\`\\`\n *\n * Filter for items in the Sample ECommerce data model where the date is in the second half of 2010 or in 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, -6, 18, '2011-01'),\n * \\`\\`\\`\n *\n * Filter for items in the Sample ECommerce data model where the date is in the past 6 months.\n * \\`\\`\\`ts\n * filterFactory.dateRelative(DM.Commerce.Date.Months, -6, 6),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day.\n * Positive numbers skip forwards and negative numbers skip backwards (e.g. \\`-6\\` is 6 months backwards when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter from, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelative(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range after a\n * given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in 2011 or the first half of 2012.\n * \\`\\`\\`ts\n * filterFactory.dateRelativeFrom(DM.Commerce.Date.Months, 0, 18, '2011-01'),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter from, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelativeFrom(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value within a specified range before a\n * given date and level.\n *\n * @example\n * Filter for items in the Sample ECommerce data model where the date is in the first half of 2010 or in 2011.\n * \\`\\`\\`ts\n * filterFactory.dateRelativeTo(DM.Commerce.Date.Months, 0, 18, '2011-12'),\n * \\`\\`\\`\n * @param level - Date {@link LevelAttribute} to filter on\n * @param offset - Number of levels to skip from the given \\`anchor\\` or the default of the current day (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param count - Number of levels to include in the filter (e.g. \\`6\\` is 6 months when \\`level\\` is a months level attribute)\n * @param anchor - Date to filter to, defaults to the current day\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function dateRelativeTo(\n\tlevel: LevelAttribute,\n\toffset: number,\n\tcount: number,\n\tanchor?: Date | string,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current calendar year.\n *\n * @example\n * Filter for items where the date is in the current calendar year in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisYear(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisYear(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current calendar month.\n *\n * @example\n * Filter for items where the date is in the current calendar month in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisMonth(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisMonth(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value in the current quarter.\n *\n * @example\n * Filter for items where the date is in the current quarter in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.thisQuarter(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - Date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function thisQuarter(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter to isolate items with a date dimension value of the current date.\n *\n * @example\n * Filter for items where the date is today in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.today(DM.Commerce.Date)\n * \\`\\`\\`\n * @param dimension - date dimension to filter\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function today(dimension: DateDimension, config?: BaseFilterConfig): Filter;\n/**\n * Creates a filter on all measure values matching the provided criteria.\n *\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param operatorA - Operator to apply on \\`valueA\\` ({@link NumericOperators})\n * @param valueA - First value\n * @param operatorB - Operator to apply on \\`valueB\\` ({@link NumericOperators})\n * @param valueB - Second value\n * @param config - Optional configuration for the filter\n * @returns A filter representing the provided logic\n * @internal\n */\nexport declare function measureBase(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\toperatorA?: string,\n\tvalueA?: number,\n\toperatorB?: string,\n\tvalueB?: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue equal 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureEquals(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureEquals(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value greater than to a given number.\n *\n * @example\n * Filter for categories that have an average revenue greater than\n * to 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureGreaterThan(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Min value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureGreaterThan(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value greater than or equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue greater than\n * or equal to 50 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureGreaterThanOrEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Min value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureGreaterThanOrEqual(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value less than or equal to a given number.\n *\n * @example\n * Filter for categories that have an average revenue less than\n * or equal to 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureLessThanOrEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureLessThanOrEqual(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value less than a given number.\n *\n * @example\n * Filter for categories that have an average revenue less than 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureLessThan(\n * measureFactory.average(DM.Commerce.Revenue),\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param value - Value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureLessThan(\n\tmeasure: BaseMeasure,\n\tvalue: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value between or equal to two given numbers.\n *\n * @example\n * Filter for categories that have an average revenue greater than or equal to 50 and less than\n * or equal to 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureBetween(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50,\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param valueA - Min value\n * @param valueB - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureBetween(\n\tmeasure: BaseMeasure,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate a measure value between but not equal to two given numbers.\n *\n * @example\n * Filter for categories that have an average revenue greater than 50 and less than\n * 100 in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.measureBetweenNotEqual(\n * measureFactory.average(DM.Commerce.Revenue),\n * 50,\n * 100\n * )\n * \\`\\`\\`\n * @param measure - Measure to filter by\n * @param valueA - Min value\n * @param valueB - Max value\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function measureBetweenNotEqual(\n\tmeasure: BaseMeasure,\n\tvalueA: number,\n\tvalueB: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items that rank towards the top for a given measure.\n *\n * @example\n * Filter for age ranges with the top 3 highest total revenue in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.topRanking(\n * DM.Commerce.AgeRange,\n * measureFactory.sum(DM.Commerce.Revenue),\n * 3\n * )\n * \\`\\`\\`\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param count - Number of members to return\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function topRanking(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\tcount: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter to isolate items that rank towards the bottom for a given measure.\n *\n * @example\n * Filter for age ranges with the bottom 3 lowest total revenue in the Sample ECommerce data model.\n * \\`\\`\\`ts\n * filterFactory.bottomRanking(\n * DM.Commerce.AgeRange,\n * measureFactory.sum(DM.Commerce.Revenue),\n * 3\n * )\n * \\`\\`\\`\n * @param attribute - Attribute to filter\n * @param measure - Measure to filter by\n * @param count - Number of members to return\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function bottomRanking(\n\tattribute: Attribute,\n\tmeasure: Measure,\n\tcount: number,\n\tconfig?: BaseFilterConfig,\n): Filter;\n/**\n * Creates a filter that contains a list of dependent/cascading filters,\n * where each filter depends on the results or state of the previous ones in the array.\n *\n * Each filter in the array operates in the context of its predecessors, and the\n * cascading behavior ensures that all filters are applied sequentially.\n *\n * @example\n * \\`\\`\\`ts\n * // Create a cascading filter for gender and age range\n * const cascadingFilter = filterFactory.cascading(\n * [\n * filterFactory.members(DM.Commerce.Gender, ['Male', 'Female']),\n * filterFactory.members(DM.Commerce.AgeRange, ['0-18']),\n * ],\n * { disabled: true }, // Optional configuration to disable the cascading filter\n * );\n * \\`\\`\\`\n * @param filters - Array of dependent filters\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n */\nexport declare function cascading(filters: Filter[], config?: BaseFilterConfig): Filter;\n/**\n * Set of logic operators for filter relations construction\n *\n * These operators are still in beta.\n *\n * @example\n * \\`\\`\\`ts\n * import { filters } from '@sisense/sdk-data';\n *\n * // define filters\n * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 1000);\n * const countryFilter = filterFactory.members(DM.Commerce.Country, ['USA', 'Canada']);\n * const genderFilter = filterFactory.doesntContain(DM.Commerce.Gender, 'Unspecified');\n * const costFilter = filterFactory.between(DM.Commerce.Cost, 1000, 2000);\n *\n * // create filter relations of two filters\n * const orFilerRelations = filterFactory.logic.or(revenueFilter, countryFilter);\n * // revenueFilter OR countryFilter\n *\n * // filter relations can have nested filter relations\n * const mixedFilterRelations = filterFactory.logic.and(genderFilter, orFilerRelations);\n * // genderFilter AND (revenueFilter OR countryFilter)\n *\n * // array, specified in filter relations, will be converted to an intersection of filters automatically\n * const arrayFilterRelations = filterFactory.logic.or([genderFilter, costFilter], mixedFilterRelations);\n * // (genderFilter AND costFilter) OR (genderFilter AND (revenueFilter OR countryFilter))\n * \\`\\`\\`\n * @beta\n */\nexport declare namespace logic {\n\t/**\n\t * Creates an 'AND' filter relations\n\t *\n\t * @example\n\t * Create filter relations for items that have a revenue greater than 100 and are in new condition\n\t * in the Sample ECommerce data model.\n\t * \\`\\`\\`ts\n\t * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 100);\n\t * const conditionFilter = filterFactory.equals(DM.Commerce.Condition, 'New');\n\t *\n\t * const andFilerRelation = filterFactory.logic.and(revenueFilter, conditionFilter);\n\t * \\`\\`\\`\n\t * @param left First filter or filter relations\n\t * @param right Second filter or filter relations\n\t * @returns Filter relations\n\t * @beta\n\t */\n\tconst and: (left: FilterRelationsNode, right: FilterRelationsNode) => FilterRelations;\n\t/**\n\t * Creates an 'OR' filter relations\n\t *\n\t * @example\n\t * Create filter relations for items that have a revenue greater than 100 or are in new condition\n\t * in the Sample ECommerce data model.\n\t * \\`\\`\\`ts\n\t * const revenueFilter = filterFactory.greaterThan(DM.Commerce.Revenue, 100);\n\t * const conditionFilter = filterFactory.equals(DM.Commerce.Condition, 'New');\n\t *\n\t * const orFilerRelation = filterFactory.logic.or(revenueFilter, conditionFilter);\n\t * \\`\\`\\`\n\t * @param left First filter or filter relations\n\t * @param right Second filter or filter relations\n\t * @returns Filter relations\n\t * @beta\n\t */\n\tconst or: (left: FilterRelationsNode, right: FilterRelationsNode) => FilterRelations;\n}\n/**\n * Creates a filter from JAQL\n *\n * @param attribute - Attribute to filter\n * @param jaql - Filter Jaql\n * @param config - Optional configuration for the filter\n * @returns A filter instance\n * @internal\n */\nexport declare function customFilter(\n\tattribute: Attribute,\n\tjaql: any,\n\tconfig?: BaseFilterConfig,\n): Filter;` as const;\n","export const MEASURE_FACTORY_TYPES = `import {\n\tAttribute,\n\tMeasure,\n\tFilter,\n\tCalculatedMeasure,\n\tBaseMeasure,\n\tCustomFormulaContext,\n} from '../interfaces.js';\nimport { ForecastFormulaOptions, TrendFormulaOptions } from '../../interfaces.js';\nimport { CustomFormulaJaql } from '../filters/utils/types.js';\n/**\n * Defines the different numeric operators that can be used with numeric filters\n *\n * @internal\n */\nexport declare const RankingTypes: {\n\t/**\n\t * In competition ranking, items that rank equally receive the same ranking number, and then a gap is left after the equally ranked items in the ranking numbers.\n\t */\n\tStandardCompetition: string;\n\t/**\n\t * In modified competition ranking, items that rank equally receive the same ranking number, and a gap is left before the equally ranked items in the ranking numbers.\n\t */\n\tModifiedCompetition: string;\n\t/**\n\t * In dense ranking, items that rank equally receive the same ranking number, and the next items receive the immediately following ranking number.\n\t */\n\tDense: string;\n\t/**\n\t * In ordinal ranking, all items receive distinct ordinal numbers, including items that rank equally. The assignment of distinct ordinal numbers for equal-ranking items is arbitrary.\n\t */\n\tOrdinal: string;\n};\n/**\n * Defines the different ranking sorting types supported by rank measure\n *\n * @internal\n */\nexport declare const RankingSortTypes: {\n\tAscending: string;\n\tDescending: string;\n};\n/**\n * Transforms a custom formula jaql into a calculated measure instance.\n *\n * As custom formulas can be nested, the function performs a recursive transformation via a helper function.\n *\n * @param jaql - Custom formula jaql\n * @returns Calculated measure instance\n * @internal\n */\nexport declare function transformCustomFormulaJaql(jaql: CustomFormulaJaql): CalculatedMeasure;\n/**\n * Creates a calculated measure for a valid custom formula built from [base functions](/guides/sdk/reference/functions.html#measured-value-functions).\n *\n * Use square brackets (\\`[]\\`) within the \\`formula\\` property to include dimensions, measures, or filters.\n * Each unique dimension, measure, or filter included in the \\`formula\\` must be defined using a property:value pair in the \\`context\\` parameter.\n *\n * You can nest custom formulas by placing one inside the \\`formula\\` parameter of another.\n *\n * Note: To use [shared formulas](https://docs.sisense.com/main/SisenseLinux/shared-formulas.htm)\n * from a Fusion instance, you must fetch them first using {@link @sisense/sdk-ui!useGetSharedFormula | useGetSharedFormula}.\n *\n * @example\n * An example of constructing a custom formulas using dimensions, measures, and nested custom formulas\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * // Custom formula\n * const profitabilityRatio = measureFactory.customFormula(\n * 'Profitability Ratio',\n * '([totalRevenue] - SUM([cost])) / [totalRevenue]',\n * {\n * totalRevenue: measureFactory.sum(DM.Commerce.Revenue),\n * cost: DM.Commerce.Cost,\n * },\n * );\n *\n * // Nested custom formula\n * const profitabilityRatioRank = measureFactory.customFormula(\n * 'Profitability Ratio Rank',\n * 'RANK([profRatio], \"ASC\", \"1224\")',\n * {\n * profRatio: profitabilityRatio,\n * },\n * );\n * \\`\\`\\`\n *\n * Another example of constructing a custom formula using measures and filters\n * \\`\\`\\`ts\n * const totalCostWithFilter = measureFactory.customFormula(\n * 'Total Cost with Filter',\n * '(SUM([cost]), [categoryFilter])',\n * {\n * cost: DM.Commerce.Cost,\n * categoryFilter: filterFactory.members(DM.Category.Category, ['Apple Mac Desktops']),\n * },\n * );\n * \\`\\`\\`\n * @param title - Title of the measure to be displayed in legend\n * @param formula - Formula to be used for the measure\n * @param context - Formula context as a map of strings to attributes, measures, or filters\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function customFormula(\n\ttitle: string,\n\tformula: string,\n\tcontext: CustomFormulaContext,\n): CalculatedMeasure;\n/**\n * Creates an aggregated measure.\n *\n * This is a base function to build other aggregation functions (e.g., \\`sum\\`, \\`average\\`, etc.)\n * as listed in {@link AggregationTypes}.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.aggregate(DM.Commerce.Cost, 'sum'),\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param aggregationType - Aggregation type. See {@link AggregationTypes}\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function aggregate(\n\tattribute: Attribute,\n\taggregationType: string,\n\tname?: string,\n\tformat?: string,\n): BaseMeasure;\n/**\n * Creates a calculated measure from a numeric value.\n *\n * @example\n * Creates a calculated measure from a numeric value.\n * \\`\\`\\`ts\n * measureFactory.constant(42)\n * \\`\\`\\`\n * @param value - Value to be returned as a measure\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function constant(value: number): CalculatedMeasure;\n/**\n * Creates a sum aggregation measure over the given attribute.\n *\n * To create a running sum, use {@link runningSum}.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.sum(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function sum(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates an average aggregation measure over the given attribute.\n *\n * Both \\`average()\\` and \\`avg()\\` can be used interchangeably.\n *\n * @example\n * Calculate the average cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.average(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function average(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * {@inheritDoc average}\n *\n * @example\n * Calculate the average cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.avg(DM.Commerce.Cost)\n * \\`\\`\\`\n * @group Aggregation\n */\nexport declare function avg(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a min aggregation measure over the given attribute.\n *\n * @example\n * Calculate the minimum cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.min(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function min(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a max aggregation measure over the given attribute.\n *\n * @example\n * Calculate the maximum cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.max(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function max(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a median aggregation measure over the given attribute.\n *\n * @example\n * Calculate the median cost across all items in a category from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.median(DM.Commerce.Cost)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function median(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a count aggregation measure over the given attribute.\n *\n * To count distinct values in the given attribute, use {@link countDistinct}.\n *\n * @example\n * Counts the number of Commerce items from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.count(DM.Commerce.BrandID)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function count(attribute: Attribute, name?: string, format?: string): BaseMeasure;\n/**\n * Creates a count distinct aggregation measure over the given attribute.\n *\n * To count all values in the given attribute, use {@link count}.\n *\n * @example\n * Calculate the number of distinct brands from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.countDistinct(DM.Brand.BrandID)\n * \\`\\`\\`\n * @param attribute - Attribute to aggregate\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A measure instance\n * @group Aggregation\n */\nexport declare function countDistinct(\n\tattribute: Attribute,\n\tname?: string,\n\tformat?: string,\n): BaseMeasure;\n/**\n * Creates a measured value with the given measure and set of filters.\n *\n * A measured value only includes values from items that match the provided filters.\n *\n * For example you can use a measured value to get a total cost for all items where the cost is greater than 100.\n *\n * Note that the filters on the measured value override the filters on the query, chart, or table the\n * measured value is used in.\n *\n * @example\n * Calculate the total cost across all items in a category from the Sample Ecommerce data model,\n * where the cost is greater than 100. Additional filtering on the cost will not affect this measure.\n * \\`\\`\\`ts\n * measureFactory.measuredValue(\n * measureFactory.sum(DM.Commerce.Cost),\n * [filterFactory.greaterThan(DM.Commerce.Cost, 100)],\n * 'Cost Greater Than 100'\n * ),\n * \\`\\`\\`\n * @param measure - Measure to filter\n * @param filters - Filters to apply to the measure\n * @param name - Optional name for the new measure\n * @param format - Optional numeric formatting to apply using a Numeral.js format string. Can only be used for explicit queries. Cannot be used in charts, tables, etc.\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function measuredValue(\n\tmeasure: Measure,\n\tfilters: Filter[],\n\tname?: string,\n\tformat?: string,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by adding two given numbers or measures.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureSum = measureFactory.add(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function add(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by subtracting two given numbers or measures. Subtracts \\`value2\\` from \\`value1\\`.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureDifference = measureFactory.subtract(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function subtract(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by multiplying two given numbers or measures.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureProduct = measureFactory.multiply(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function multiply(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure by dividing two given numbers or measures. Divides \\`value1\\` by \\`value2\\`.\n *\n * @example\n * \\`\\`\\`ts\n * const measure1 = measureFactory.sum(DM.Dimension.Attribute1);\n * const measure2 = measureFactory.sum(DM.Dimension.Attribute2);\n * const measureQuotient = measureFactory.divide(measure1, measure2);\n * \\`\\`\\`\n * @param value1 - First value\n * @param value2 - Second value\n * @param name - Optional name for the new measure\n * @param withParentheses - Optional boolean flag whether to wrap the arithmetic operation with parentheses\n * @returns A calculated measure instance\n * @group Arithmetic\n */\nexport declare function divide(\n\tvalue1: Measure | number,\n\tvalue2: Measure | number,\n\tname?: string,\n\twithParentheses?: boolean,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the year up to the current day, week, month, or quarter.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the year up to the current day, week, month, or quarter.\n * \\`\\`\\`ts\n * measureFactory.yearToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the YTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function yearToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the quarter up to the current day, week, or month.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the quarter up to the current day, week, or month.\n * \\`\\`\\`ts\n * measureFactory.quarterToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the QTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function quarterToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the month up to the current day or week.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the month up to the current day or week.\n * \\`\\`\\`ts\n * measureFactory.monthToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the MTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function monthToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total starting from the beginning\n * of the week up to the current day.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the running total of total cost from the Sample Ecommerce data model, starting from the\n * beginning of the week up to the current day.\n * \\`\\`\\`ts\n * measureFactory.weekToDateSum(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the WTD Sum to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function weekToDateSum(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the running total of a given measure.\n *\n * The running sum is calculated using the current sort order of the query it's used in.\n *\n * @example\n * Calculate the running sum of the total cost from the Sample Ecommerce data model across all categories.\n * \\`\\`\\`ts\n * measureFactory.runningSum(measureFactory.sum(DM.Commerce.Cost)),\n * \\`\\`\\`\n *\n * Running sum values from the Sample Ecommerce data model when categorizing by age range.\n * | AgeRange | Cost | Running Cost |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 4.32M |\n * | 19-24 | 8.66M | 12.98M |\n * | 25-34 | 21.19M | 34.16M |\n * | 35-44 | 23.64M | 57.8M |\n * | 45-54 | 20.39M | 78.19M |\n * | 55-64 | 11.82M | 90.01M |\n * | 65+ | 17.26M | 107.27M |\n * @param measure - Measure to apply the running sum to\n * @param _continuous - Boolean flag whether to accumulate the sum continuously\n * when there are two or more dimensions. The default value is false.\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function runningSum(\n\tmeasure: Measure,\n\t_continuous?: boolean,\n\tname?: string,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates growth over a period of time.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentPeriod – previousPeriod) / previousPeriod\\`.\n *\n * For example, if this period the value is 12 and the previous period's value was 10, the growth for\n * this period is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous period's value is greater than the current period, the growth will be negative.\n *\n * For example, if this period the value is 80, and the previous period's was 100, the growth for\n * this period is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this period in comparison to the previous period from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates growth rate over a period of time.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * Growth rate is calculated using the following formula: \\`currentPeriod / previousPeriod\\`.\n *\n * For example, if this period the value is 12 and the previous period's value was 10, the growth rate for\n * this period is 120%, returned as '1.2' (calculation: \\`12 / 10 = 1.2\\`).\n *\n * If the previous period's value is greater than the current period, the growth rate will be less than one.\n *\n * For example, if this period the value is 80, and the previous period's was 100, the growth for\n * this period is 80%, returned as \\`0.8\\` (calculation: \\`80 / 100 = .8\\`).\n *\n * @example\n * Calculate the growth rate in total cost this period in comparison to the previous period from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthRate(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply the Growth rate\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthRate(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous week to the current week.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentWeek – previousWeek) / previousWeek\\`.\n *\n * For example, if this week the value is 12 and the previous week's value was 10, the growth for\n * this week is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous week's value is greater than the current week, the growth will be negative.\n *\n * For example, if this week the value is 80, and the previous week's was 100, the growth for\n * this week is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this week in comparison to the previous week from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous month to the current month.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentMonth – previousMonth) / previousMonth\\`.\n *\n * For example, if this month the value is 12 and the previous month's value was 10, the growth for\n * this month is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous month's value is greater than the current month, the growth will be negative.\n *\n * For example, if this month the value is 80, and the previous month's was 100, the growth for\n * this month is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this month in comparison to the previous month from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous quarter to the current quarter.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentQuarter – previousQuarter) / previousQuarter\\`.\n *\n * For example, if this quarter the value is 12 and the previous quarter's value was 10, the growth for\n * this quarter is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous quarter's value is greater than the current quarter, the growth will be negative.\n *\n * For example, if this quarter the value is 80, and the previous quarter's was 100, the growth for\n * this quarter is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this quarter in comparison to the previous quarter from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the growth from the previous year to the current year.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * Growth is calculated using the following formula: \\`(currentYear – previousYear) / previousYear\\`.\n *\n * For example, if this year the value is 12 and the previous year's value was 10, the growth for\n * this year is 20%, returned as '0.2' (calculation: \\`(12 – 10) / 10 = 0.2\\`).\n *\n * If the previous year's value is greater than the current year, the growth will be negative.\n *\n * For example, if this year the value is 80, and the previous year's was 100, the growth for\n * this year is -20%, returned as \\`-0.2\\` (calculation: \\`(80 – 100) / 100 = -0.2\\`).\n *\n * @example\n * Calculate the growth in total cost this year in comparison to the previous year from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.growthPastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply growth to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function growthPastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this period's data\n * and the data from the previous period for the given measure.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate the difference between this period's total cost and the previous period's total cost\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.difference(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function difference(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this week's data\n * and the data from the previous week for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this week's total cost and the previous week's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this month's data\n * and the data from the previous month for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this month's total cost and the previous month's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this quarter's data\n * and the data from the previous quarter for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this quarter's total cost and the previous quarter's total cost\n * from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the difference between this year's data\n * and the data from the previous year for the given measure.\n *\n * The date dimension will be dynamically taken from the query that uses the returned measure.\n *\n * @example\n * Calculate the difference between this year's total cost and the previous year's total cost from\n * the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.diffPastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply difference to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function diffPastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the previous day.\n *\n * @example\n * Calculate total cost for the previous day from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastDay(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastDay(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day in the previous week.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day one week ago from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastWeek(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastWeek(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day or week in the previous month.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day or week one month ago from the Sample Ecommerce\n * data model.\n * \\`\\`\\`ts\n * measureFactory.pastMonth(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastMonth(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day, week, or month in the previous quarter.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day, week, or month one quarter ago from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastQuarter(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastQuarter(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the value for the same day, week, month, or quarter in the previous year.\n *\n * The time resolution is determined by the minimum date level of the date dimension in the query\n * that uses the returned measure.\n *\n * @example\n * Calculate total cost for the corresponding day, week, month, or quarter one year ago from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.pastYear(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n * @param measure - Measure to apply past value to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Time-based\n */\nexport declare function pastYear(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated contribution measure.\n *\n * A contribution measure calculates the contribution, in percentage, of a measure towards the total.\n * Percentages are expressed as a number between 0 and 1 (e.g. 42% is \\`0.42\\`).\n *\n * For example, using the Sample Ecommerce data model you can retrieve the total cost of products\n * categorized by age range. Using a contribution measure you can calculate how much each age range's\n * total cost contributes to the total cost across all age ranges. So, the total cost for the 35-44\n * age range is 23.64M, which is 22% of the 107.27M of all age ranges together. Therefore, the\n * contribution of the 35-44 age range is \\`.22\\`.\n *\n * @example\n * Calculates the percentage of the total cost across all categories for items in a category from the\n * Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.contribution(measureFactory.sum(DM.Commerce.Cost))\n * \\`\\`\\`\n *\n * Contribution values from the Sample Ecommerce data model when categorizing by age range.\n * | AgeRange | Cost | Contribution |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 0.04 |\n * | 19-24 | 8.66M | 0.08 |\n * | 25-34 | 21.19M | 0.2 |\n * | 35-44 | 23.64M | 0.22 |\n * | 45-54 | 20.39M | 0.19 |\n * | 55-64 | 11.82M | 0.11 |\n * | 65+ | 17.26M | 0.16 |\n * @param measure - Measure to apply the Contribution logic to\n * @param name - Name for the new measure\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function contribution(measure: Measure, name?: string): CalculatedMeasure;\n/**\n * Creates a calculated measure that computes a specified trend type for a given measure.\n *\n * The trend types include linear (the default), logarithmic, advanced smoothing, and local estimates.\n * You can also opt to automatically identify and ignore anomalous values in the series.\n *\n * Trend requires a Sisense instance version of L2023.6.0 or greater.\n *\n * @example\n * Calculate the trend in total cost from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.trend(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Total Cost Trend',\n * {\n * modelType: 'advancedSmoothing',\n * ignoreAnomalies: true,\n * }\n * )\n * \\`\\`\\`\n * @param measure - Measure to apply the trend logic to\n * @param name - Name for the new measure\n * @param options - Trend options\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function trend(\n\tmeasure: Measure,\n\tname?: string,\n\toptions?: TrendFormulaOptions,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that generates a forecast based on a specified measure employing\n * advanced autoML techniques.\n *\n * This function offers flexible options allowing you to:\n * + Let the function auto-select the best statistical model or explicitly choose a preferred model\n * + Control the time period used for training the model\n * + Set additional options to improve forecast accuracy by supplying expected lower and upper limits.\n *\n * In addition to the forecast, upper and lower confidence intervals are returned\n * with the name of the new measure and a suffix of _upper and _lower\n * respectively.\n *\n * Forecast requires a Sisense instance version of L2023.6.0 or greater.\n *\n * @example\n * Calculate a forecast for total cost from the Sample Ecommerce data model from the Sample\n * Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.forecast(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Total Cost Forecast',\n * {\n * modelType: 'prophet',\n * roundToInt: true,\n * }\n * )\n * \\`\\`\\`\n * @param measure - Measure to apply the forecast logic to\n * @param name - Name for the new measure\n * @param options - Forecast options\n * @returns A calculated measure instance\n * @group Advanced Analytics\n */\nexport declare function forecast(\n\tmeasure: Measure,\n\tname?: string,\n\toptions?: ForecastFormulaOptions,\n): CalculatedMeasure;\n/**\n * Creates a calculated measure that calculates the rank of a value in a list of values.\n *\n * This function includes options that allow you do customize the ranking order and how to handle\n * equally ranked items.\n *\n * The order options are:\n * + \\`'DESC'\\` (default): Descending, meaning the largest number is ranked first.\n * + \\`'ASC'\\`: Ascending, meaning the smallest number is ranked first.\n *\n * The rank type options are:\n * + \\`'1224'\\`: Standard competition, meaning items that rank equally receive the same ranking number,\n * and then a gap is left after the equally ranked items in the ranking numbers.\n * + \\`'1334'\\`: Modified competition ranking, meaning items that rank equally receive the same ranking number,\n * and a gap is left before the equally ranked items in the ranking numbers.\n * + \\`'1223'\\`: Dense ranking, meaning items that rank equally receive the same ranking number,\n * and the next items receive the immediately following ranking number.\n * + \\`'1234'\\`: Ordinal ranking, meaning all items receive distinct ordinal numbers,\n * including items that rank equally. The assignment of distinct ordinal numbers for equal-ranking items is arbitrary.\n *\n * @example\n * Calculate the rank of the total cost per category, sorted with the smallest cost ranked first,\n * and ranking ties are handled using the ordinal ranking type from the Sample Ecommerce data model.\n * \\`\\`\\`ts\n * measureFactory.rank(\n * measureFactory.sum(DM.Commerce.Cost),\n * 'Cost Rank',\n * measureFactory.RankingSortTypes.Ascending,\n * measureFactory.RankingTypes.Ordinal\n * )\n * \\`\\`\\`\n *\n * Ranking values from the Sample Ecommerce data model when categorizing by age range using the above ranking.\n * | AgeRange | Cost | Cost Rank |\n * | --- | --- | --- |\n * | 0-18 | 4.32M | 1 |\n * | 19-24 | 8.66M | 2 |\n * | 25-34 | 21.19M | 6 |\n * | 35-44 | 23.64M | 7 |\n * | 45-54 | 20.39M | 5 |\n * | 55-64 | 11.82M | 3 |\n * | 65+ | 17.26M | 4 |\n * @param measure - Measure to apply the ranking logic to\n * @param name - Name for the new measure\n * @param sort - Sorting for ranking. By default sort order is descending, where the largest number is ranked first.\n * @param rankType - How to handle equally ranked items. By default the type is standard competition ranking.\n * @param groupBy - Rank partition attributes\n * @returns A calculated measure instance\n * @group Statistics\n */\nexport declare function rank(\n\tmeasure: Measure,\n\tname?: string,\n\tsort?: string,\n\trankType?: string,\n\tgroupBy?: Attribute[],\n): CalculatedMeasure;` as const;\n","import { FILTER_FACTORY_TYPES } from './filter-factory-types';\nimport { MEASURE_FACTORY_TYPES } from './measure-factory-types';\n\nexport function generateFilterSystemPrompt() {\n\treturn `You are an expert in translating natural language into JSON filter expressions for data filtering.\n\n**Task:** Convert user prompts into JSON filter objects using the provided resources. DO NOT use any tools.\n\n**Available Resources:**\n1. **Measure Factory Types:**\n${MEASURE_FACTORY_TYPES}\n\n2. **Filter Factory Types:**\n${FILTER_FACTORY_TYPES}\n\n**Data Model Structure:**\n- DM.TableName.ColumnName (e.g., DM.Commerce.Revenue) - Use exact names.\n\n**Instructions:**\n1. **Default Filtering:**\n - Measures (without specified values): Filter for values > 0.\n - Categorical Attributes (without specified values): Use \\`members\\` filter with \\`[]\\` to filter for all members.\n - Date Level Attributes (without specified values): Use \\`members\\` filter with \\`[]\\` to filter for all members.\n - Explain any default behavior assumptions in plain English.\n\n2. **Filter Logic:**\n - Match user requirements to exact data fields.\n - Combine filters with \\`filterFactory.logic.or\\`/\\`and\\`.\n - Adhere to factory function names and argument order.\n - Output JSON with \\`\"function\"\\` and \\`\"args\"\\` properties (including nested).\n - Use exact function names from factory types.\n - Create measures with \\`measureFactory\\` for measure-based filters (unless no aggregation is specified).\n - Use corresponding date level fields for specified granularities (Years, Quarters, Months, Weeks, Days).\n - Always use \\`members\\` filter for concrete date level values in an array. Do not use \\`equals\\` filter for date level values.\n\n3. **Field Matching:**\n - Use exact field names.\n - Use closest match if exact name not found.\n - Refer to the data fields list for verification.\n\n**Output Format:**\n\\`\\`\\`json\n{\n \"function\": \"<factoryFunctionName>\",\n \"args\": [...]\n}\n\\`\\`\\`\n\n**Example Input/Output:**\n\\`\\`\\`\nInput: \"Filter for countries that start with 'A'\"\nOutput:\n{\n \"function\": \"filterFactory.startsWith\",\n \"args\": [\"DM.Country.Country\", \"A\"]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Filter for total revenue between 1000 and 2000\"\nOutput:\n{\n \"function\": \"filterFactory.measureBetween\",\n \"args\": [\n {\n \"function\": \"measureFactory.sum\",\n \"args\": [\"DM.Commerce.Revenue\", \"Total Revenue\"]\n },\n 1000,\n 2000\n ]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Filter for countries that start with 'A' OR have revenue > 1000\"\nOutput:\n{\n \"function\": \"filterFactory.logic.or\",\n \"args\": [\n {\n \"function\": \"filterFactory.startsWith\",\n \"args\": [\"DM.Country.Country\", \"A\"]\n },\n {\n \"function\": \"filterFactory.greaterThan\",\n \"args\": [\n \"DM.Commerce.Revenue\",\n 1000\n ]\n }\n ]\n}\n\\`\\`\\`\n\\`\\`\\`\nInput: \"Show all years\"\nOutput:\n{\n \"function\": \"filterFactory.members\",\n \"args\": [\"DM.Date.Years\", []]\n}\n\\`\\`\\`\n`;\n}\n","import {\n\tBaseMeasure,\n\tCalculatedMeasure,\n\tcreateAttributeHelper,\n\tFilter,\n\tFilterRelations,\n\tisFilterRelations,\n\tisMembersFilter,\n\tJaqlDataSourceForDto,\n} from '@sisense/sdk-data';\nimport { filterFactory, measureFactory } from '@sisense/sdk-data';\nimport { NormalizedDataSourceField } from '@/services/data-sources/data-sources-service';\n\n// Type to represent a function arg\ntype ParsedArg = string | number | ParsedFunctionCall;\n\n// Type to represent the structure parsed from the JSON\ntype ParsedFunctionCall = {\n\tfunction: string;\n\targs: ParsedArg[];\n};\n\nexport function getFactoryFunctionsMap(\n\tfactoryName: string,\n\tfactoryObject: Record<string, any>,\n): Record<string, (...args: any[]) => any> {\n\tconst functionsMap: Record<string, (...args: any[]) => any> = {};\n\tconst prefix = factoryName !== '' ? factoryName + '.' : '';\n\tfor (const key in factoryObject) {\n\t\tif (typeof factoryObject[key] === 'function') {\n\t\t\tfunctionsMap[`${prefix}${key}`] = factoryObject[key];\n\t\t} else if (typeof factoryObject[key] === 'object') {\n\t\t\tconst nestedFunctionsMap = getFactoryFunctionsMap(\n\t\t\t\t'',\n\t\t\t\tfactoryObject[key],\n\t\t\t);\n\t\t\tfor (const nestedKey in nestedFunctionsMap) {\n\t\t\t\tfunctionsMap[`${prefix}${key}.${nestedKey}`] =\n\t\t\t\t\tnestedFunctionsMap[nestedKey];\n\t\t\t}\n\t\t}\n\t}\n\treturn functionsMap;\n}\n\nexport const measureFactoryFunctionsMap = getFactoryFunctionsMap(\n\t'measureFactory',\n\tmeasureFactory,\n);\nexport const filterFactoryFunctionsMap = getFactoryFunctionsMap(\n\t'filterFactory',\n\tfilterFactory,\n);\n\nfunction executeFunction(\n\tfunctionPath: string,\n\targs: any[],\n): Filter | FilterRelations | BaseMeasure | CalculatedMeasure {\n\tconst parts = functionPath.split('.');\n\tconst factoryName = parts[0];\n\n\tif (factoryName === 'filterFactory') {\n\t\tif (filterFactoryFunctionsMap[functionPath]) {\n\t\t\treturn (\n\t\t\t\tfilterFactoryFunctionsMap[functionPath] as (\n\t\t\t\t\t...params: any[]\n\t\t\t\t) => Filter | FilterRelations\n\t\t\t)(...args);\n\t\t}\n\t} else if (factoryName === 'measureFactory') {\n\t\tif (measureFactoryFunctionsMap[functionPath]) {\n\t\t\treturn (\n\t\t\t\tmeasureFactoryFunctionsMap[functionPath] as (\n\t\t\t\t\t...params: any[]\n\t\t\t\t) => BaseMeasure | CalculatedMeasure\n\t\t\t)(...args);\n\t\t}\n\t}\n\n\tthrow new Error(\n\t\t`Function \"${functionPath}\" not found in filterFactory or measureFactory.`,\n\t);\n}\n\nfunction createAttribute(\n\tattributeName: string,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n) {\n\tconst dataField = dataFields.find(\n\t\t(field) => `DM.${field.table}.${field.column}` === attributeName,\n\t);\n\tif (!dataField) {\n\t\tthrow new Error(\n\t\t\t`Data field \"${attributeName}\" not found in data fields.`,\n\t\t);\n\t}\n\treturn createAttributeHelper({\n\t\texpression: dataField.expression,\n\t\tdataType: dataField.type,\n\t\tgranularity: dataField.level,\n\t\tformat: undefined,\n\t\tsort: undefined,\n\t\tdataSource,\n\t});\n}\n\nfunction processArg(\n\targ: ParsedArg,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n) {\n\tif (typeof arg === 'object' && arg !== null && arg.function && arg.args) {\n\t\treturn processNode(arg, dataSource, dataFields);\n\t}\n\tif (typeof arg === 'string' && arg.startsWith('DM.')) {\n\t\treturn createAttribute(arg, dataSource, dataFields);\n\t}\n\treturn arg;\n}\n\n/**\n * Recursively processes a parsed JSON object to execute filterFactory and measureFactory functions.\n *\n * @param parsedObject - The parsed JSON object representing a function call or a nested structure.\n * @returns The result of the executed function or the processed nested structure.\n */\nfunction processNode(\n\tparsedObject: ParsedFunctionCall,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n): Filter | FilterRelations | BaseMeasure | CalculatedMeasure {\n\tconst { function: functionPath, args } = parsedObject;\n\t// Recursively process arguments that are also function calls\n\tconst processedArgs = args.map((arg) =>\n\t\tprocessArg(arg, dataSource, dataFields),\n\t);\n\treturn executeFunction(functionPath, processedArgs);\n}\n\nfunction postProcessFilter(filter: Filter) {\n\tconst { attribute, config } = filter;\n\tif (isMembersFilter(filter) && 'granularity' in attribute) {\n\t\tconst granularity = attribute.granularity;\n\t\t// Convert values to ISO 8601 string -- e.g., 2011 to \"2011-01-01\"\n\t\treturn filterFactory.members(\n\t\t\tattribute,\n\t\t\tfilter.members.map((member) => {\n\t\t\t\tif (granularity === 'Years' && !isNaN(Number(member))) {\n\t\t\t\t\treturn `${member}-01-01T00:00:00`;\n\t\t\t\t}\n\t\t\t\treturn member;\n\t\t\t}),\n\t\t\tconfig,\n\t\t);\n\t}\n\treturn filter;\n}\n\nfunction postProcessFilters(\n\tfilters: Filter | FilterRelations,\n): Filter[] | FilterRelations {\n\tif (isFilterRelations(filters as FilterRelations | Filter[])) {\n\t\treturn filters as FilterRelations;\n\t}\n\treturn [filters as Filter].map(postProcessFilter);\n}\n\n/**\n * Translate JSON string to filters\n *\n * @example\n *\n * {\n * \"function\": \"filterFactory.logic.or\",\n * \"args\": [\n * {\n * \"function\": \"filterFactory.startsWith\",\n * \"args\": [\"DM.Country.Country\", \"A\"]\n * },\n * {\n * \"function\": \"filterFactory.measureGreaterThan\",\n * \"args\": [\n * {\n * \"function\": \"measureFactory.sum\",\n * \"args\": [\"DM.Commerce.Revenue\", \"Total Revenue\"]\n * },\n * 1000\n * ]\n * }\n * ]\n * }\n *\n * is translated to the following Filter[] or FilterRelations object:\n * filterFactory.logic.or([\n * filterFactory.startsWith(\"DM.Country.Country\", \"A\"),\n * filterFactory.measureGreaterThan(\n * measureFactory.sum(\"DM.Commerce.Revenue\", \"Total Revenue\"),\n * 1000\n * )\n * ])\n *\n * @param filtersJson - A JSON string representing the filters\n * @returns A Filter[] or FilterRelations object\n */\nexport const translateFiltersFromJsonFunctionCall = (\n\tfiltersJson: string,\n\tdataSource: JaqlDataSourceForDto,\n\tdataFields: NormalizedDataSourceField[],\n): Filter[] | FilterRelations => {\n\tconst parsedJson = JSON.parse(filtersJson);\n\tconst result = processNode(parsedJson, dataSource, dataFields) as\n\t\t| Filter\n\t\t| FilterRelations;\n\n\tconst postProcessedFilters = postProcessFilters(result);\n\treturn postProcessedFilters;\n};\n","import { z } from 'zod';\nimport { getNormalizedDataSourceFields } from '@/services/data-sources/data-sources-service';\nimport { generateFilterSystemPrompt } from './dashboard-filters-system-prompt';\nimport { translateFiltersFromJsonFunctionCall } from './translate-filters';\nimport { DashboardProps } from '@sisense/sdk-ui';\nimport { getDashboardDataSourcesMap } from '@/services/dashboards/dashboards-service';\nimport { mergeFiltersOrFilterRelations } from '@sisense/sdk-data';\nimport { createStructuredCompletion } from '@/utils/chat-completion-utils';\nimport { OpenAI } from 'openai';\n\nconst schema = z.object({\n\tfiltersJson: z.string().describe('A JSON string representing the filters'),\n\texplanation: z\n\t\t.string()\n\t\t.describe(\n\t\t\t'A non-technical explanation of how the filters were manipulated',\n\t\t),\n});\n\nexport const manipulateDashboardFilters = async (\n\tuserPrompt: string,\n\tdataSourceTitle: string,\n\tdashboardProps: DashboardProps,\n\topenAIClient?: OpenAI,\n): Promise<{ dashboardProps: DashboardProps; explanation: string }> => {\n\tconst dataSourcesMap = getDashboardDataSourcesMap(dashboardProps);\n\tconst dataSource = dataSourcesMap.get(dataSourceTitle);\n\tif (!dataSource) {\n\t\tthrow new Error(\n\t\t\t`Data source \"${dataSourceTitle}\" not found in dashboard. Please ask the user to specify a valid data source.`,\n\t\t);\n\t}\n\n\tconst systemPrompt = generateFilterSystemPrompt();\n\n\tconst dataFields = await getNormalizedDataSourceFields(dataSourceTitle);\n\n\tconst fullUserPrompt = `${userPrompt}\\n\\nAvailable Data Fields:\\n${JSON.stringify(\n\t\tdataFields,\n\t\tnull,\n\t\t2,\n\t)}`;\n\n\tconst response = await createStructuredCompletion({\n\t\tsystemPrompt,\n\t\tuserPrompt: fullUserPrompt,\n\t\topenAIClient,\n\t\tresponseFormat: {\n\t\t\ttype: 'json_schema',\n\t\t\tschema,\n\t\t\tname: 'filters',\n\t\t},\n\t});\n\n\tconst { filtersJson, explanation } = response;\n\tif (!filtersJson) {\n\t\tthrow new Error('Failed to manipulate filters');\n\t}\n\n\tconst filters = translateFiltersFromJsonFunctionCall(\n\t\tfiltersJson,\n\t\tdataSource,\n\t\tdataFields,\n\t);\n\n\t// Always return local dashboard props with merged filters\n\tconst updatedDashboardProps = {\n\t\t...dashboardProps,\n\t\tfilters: mergeFiltersOrFilterRelations(dashboardProps.filters, filters),\n\t};\n\n\treturn {\n\t\tdashboardProps: updatedDashboardProps,\n\t\texplanation,\n\t};\n};\n","import { AddDashboardFiltersParams, BuildDashboardContext } from './types';\nimport { manipulateDashboardFilters } from './dashboard-filters/manipulate-dashboard-filters';\n\nexport const addDashboardFilters = async (\n\t{ dashboardId, userPrompt }: AddDashboardFiltersParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconst { dataSourceTitle, retrieveDashboard, saveDashboard, openAIClient } =\n\t\tcontext;\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'addDashboardFilters',\n\t\tdashboardId,\n\t\tuserPrompt,\n\t\tdataSourceTitle,\n\t);\n\n\tconst currentDashboard = retrieveDashboard?.(dashboardId);\n\tif (!currentDashboard) {\n\t\tthrow new Error('Dashboard not found');\n\t}\n\n\tconst { dashboardProps: updatedDashboardProps, explanation } =\n\t\tawait manipulateDashboardFilters(\n\t\t\tuserPrompt,\n\t\t\tdataSourceTitle,\n\t\t\tcurrentDashboard,\n\t\t\topenAIClient,\n\t\t);\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage: `${explanation} Click \"Save\" to persist changes to My Dashboards.`,\n\t};\n};\n","import {\n\tCreateChartWidgetForDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport {\n\taddWidgetsToExistingDashboard,\n\tcreateEmptyDashboard,\n\tresetWidgetForDashboard,\n} from '@/services/dashboards/dashboards-service';\nimport { buildChartEngine } from '../chart-builder/chart-builder-engine';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n} from '../chart-builder/types';\nimport { WidgetProps } from '@sisense/sdk-ui';\n\nexport const createChartWidgetForDashboard = async (\n\t{ dashboardId, userPrompt }: CreateChartWidgetForDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'createChartWidgetForDashboard',\n\t\tdashboardId,\n\t\tuserPrompt,\n\t);\n\n\tconst {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard,\n\t\tsaveDashboard,\n\t\thttpClient,\n\t\topenAIClient,\n\t\tisNlqV3Enabled,\n\t} = context;\n\tif (!toolCallId) {\n\t\tthrow new Error('Error: Invalid tool call ID. Please try again.');\n\t}\n\n\tlet isNewDashboard = false;\n\tlet currentDashboard;\n\ttry {\n\t\tcurrentDashboard = retrieveDashboard?.(dashboardId);\n\t\tif (!currentDashboard) {\n\t\t\tthrow new Error('Dashboard not found. Creating a new dashboard.');\n\t\t}\n\t} catch (error) {\n\t\tcurrentDashboard = await createEmptyDashboard(\n\t\t\tdataSourceTitle,\n\t\t\t`Dashboard for ${dataSourceTitle}`,\n\t\t\thttpClient,\n\t\t);\n\t\tisNewDashboard = true;\n\t}\n\n\t// reuse chart builder engine to create a new chart widget\n\tlet newChartWidgetProps: ExtendedChartWidgetProps | null = null;\n\tconst buildChartContext: BuildChartContext = {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tretrieveChart: (_: string) => newChartWidgetProps,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tsaveChart: (_: string, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\tnewChartWidgetProps = chartWidgetProps;\n\t\t},\n\t\tisNlqV3Enabled,\n\t\thttpClient,\n\t\topenAIClient,\n\t};\n\n\tconst chartSummary = await buildChartEngine(\n\t\t{ dataSourceTitle, userPrompt },\n\t\tbuildChartContext,\n\t);\n\n\tif (chartSummary.isError) {\n\t\tthrow new Error(chartSummary.message);\n\t}\n\n\tif (!newChartWidgetProps) {\n\t\tthrow new Error('Error: Failed to create chart widget');\n\t}\n\n\tconst resetChartWidgetProps: WidgetProps =\n\t\tresetWidgetForDashboard(newChartWidgetProps);\n\n\tconst updatedDashboardProps = addWidgetsToExistingDashboard(\n\t\tcurrentDashboard,\n\t\t[resetChartWidgetProps],\n\t);\n\n\tsaveDashboard?.(updatedDashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\tisNewDashboard && newChartWidgetProps\n\t\t\t\t? 'Dashboard created and chart widget added successfully. Click \"Save\" to persist changes to My Dashboards.'\n\t\t\t\t: `Chart widget (widgetId: ${resetChartWidgetProps.id}) added to the dashboard successfully. Click \"Save\" to persist changes to My Dashboards.`,\n\t};\n};\n","import {\n\tUpdateChartWidgetForDashboardParams,\n\tBuildDashboardContext,\n} from './types';\nimport { buildChartEngine } from '../chart-builder/chart-builder-engine';\nimport { getBaseChartSummary } from '../chart-builder/chart-builder-service';\nimport {\n\tBuildChartContext,\n\tExtendedChartWidgetProps,\n} from '../chart-builder/types';\nimport { isChartWidgetProps } from '@sisense/sdk-ui';\n\nexport const updateChartWidgetForDashboard = async (\n\t{ dashboardId, widgetId, userPrompt }: UpdateChartWidgetForDashboardParams,\n\tcontext: BuildDashboardContext,\n) => {\n\tconsole.debug(\n\t\t'toolCall',\n\t\t'updateChartWidgetForDashboard',\n\t\tdashboardId,\n\t\twidgetId,\n\t\tuserPrompt,\n\t);\n\n\tconst {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard,\n\t\tsaveDashboard,\n\t\thttpClient,\n\t\topenAIClient,\n\t\tisNlqV3Enabled,\n\t} = context;\n\tif (!toolCallId) {\n\t\tthrow new Error('Error: Invalid tool call ID. Please try again.');\n\t}\n\n\tconst dashboardProps = retrieveDashboard?.(dashboardId);\n\tif (!dashboardProps) {\n\t\tthrow new Error('Dashboard not found.');\n\t}\n\n\tlet widgetIndex = dashboardProps.widgets.findIndex(\n\t\t(widget) => widget.id === widgetId,\n\t);\n\tif (widgetIndex === -1) {\n\t\tconsole.debug(\n\t\t\t'Widget not found. Retrieving the last chart widget from dashboard.',\n\t\t);\n\t\twidgetIndex = dashboardProps.widgets.length - 1;\n\t}\n\n\tconst widgetProps = dashboardProps.widgets[widgetIndex];\n\n\tif (!isChartWidgetProps(widgetProps)) {\n\t\tthrow new Error('Widget is not a chart widget.');\n\t}\n\n\tlet savedChartWidgetProps = widgetProps;\n\n\tconst chartSummaries = [\n\t\t{\n\t\t\tmessage: 'This is the current chart widget',\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tchartId: widgetId,\n\t\t\tchart: getBaseChartSummary(savedChartWidgetProps, dataSourceTitle),\n\t\t},\n\t];\n\n\tconst buildChartContext: BuildChartContext = {\n\t\ttoolCallId,\n\t\tdataSourceTitle,\n\t\tchartSummaries,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tretrieveChart: (_: string) => savedChartWidgetProps,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\tsaveChart: (_: string, chartWidgetProps: ExtendedChartWidgetProps) => {\n\t\t\t// Preserve the original widget ID to maintain dashboard layout references\n\t\t\tconst updatedWidgetProps: ExtendedChartWidgetProps = {\n\t\t\t\t...chartWidgetProps,\n\t\t\t\tid: widgetId,\n\t\t\t};\n\t\t\tdashboardProps.widgets[widgetIndex] = updatedWidgetProps;\n\t\t\tsavedChartWidgetProps = updatedWidgetProps;\n\t\t},\n\t\tisNlqV3Enabled,\n\t\thttpClient,\n\t\topenAIClient,\n\t};\n\n\tconst chartSummary = await buildChartEngine(\n\t\t{ dataSourceTitle, userPrompt },\n\t\tbuildChartContext,\n\t);\n\n\tif (chartSummary.isError) {\n\t\tthrow new Error(chartSummary.message);\n\t}\n\n\tsaveDashboard?.(dashboardProps);\n\n\treturn {\n\t\tmessage:\n\t\t\t'Chart widget updated successfully. Click \"Save\" to persist changes to My Dashboards.',\n\t};\n};\n","import { isChartWidgetProps, isPivotTableWidgetProps } from '@sisense/sdk-ui';\nimport { BaseDashboardSummary, ExtendedDashboardProps } from './types';\n\n/**\n * Get a base dashboard summary from dashboard props\n * This is used by the engine to create a summary for LLM consumption\n */\nexport const getBaseDashboardSummary = (\n\tdashboardProps: ExtendedDashboardProps,\n\tdataSourceTitle: string,\n): BaseDashboardSummary => {\n\treturn {\n\t\tfusionDashboardId: dashboardProps.id,\n\t\tdashboardTitle: dashboardProps.title,\n\t\tdefaultDataSourceTitle: dataSourceTitle,\n\t\twidgets: dashboardProps.widgets.map((widgetProps) => ({\n\t\t\twidgetId: widgetProps.id,\n\t\t\t...(isChartWidgetProps(widgetProps)\n\t\t\t\t? {\n\t\t\t\t\t\twidgetTitle: widgetProps.title,\n\t\t\t\t\t\twidgetType: widgetProps.widgetType,\n\t\t\t\t\t\tchartType: widgetProps.chartType,\n\t\t\t\t }\n\t\t\t\t: {}),\n\t\t\t...(isPivotTableWidgetProps(widgetProps)\n\t\t\t\t? {\n\t\t\t\t\t\twidgetTitle: widgetProps.title,\n\t\t\t\t\t\twidgetType: widgetProps.widgetType,\n\t\t\t\t }\n\t\t\t\t: {}),\n\t\t})),\n\t};\n};\n","import { zodFunction } from '@/utils/zod-utils';\nimport {\n\tBuildDashboardContext,\n\tChartListSummary,\n\tDashboardSummary,\n\tExtendedDashboardProps,\n\tbuildDashboardSchema,\n\tcreateDashboardSchema,\n\tloadExistingFusionDashboardSchema,\n\tupdateDashboardSchema,\n\taddDashboardWidgetsSchema,\n\taddDashboardFiltersSchema,\n\tcreateChartWidgetForDashboardSchema,\n\tupdateChartWidgetForDashboardSchema,\n} from './types';\nimport { ChartSummary } from '../chart-builder/types';\nimport { createDashboard } from './create-dashboard';\nimport { loadExistingFusionDashboard } from './load-existing-fusion-dashboard';\nimport { updateDashboard } from './update-dashboard';\nimport { addDashboardWidgets } from './add-dashboard-widgets';\nimport { addDashboardFilters } from './add-dashboard-filters';\nimport { createChartWidgetForDashboard } from './create-chart-widget';\nimport { updateChartWidgetForDashboard } from './update-chart-widget';\nimport { getBaseDashboardSummary } from './dashboard-builder-service';\nimport {\n\tTOOL_CONTEXT_MAX_ASSETS,\n\tTOOL_NAME_DASHBOARD_BUILDER,\n} from '@/constants';\nimport { createToolsCompletion } from '@/utils/chat-completion-utils';\nimport { resetWidgetForDashboard } from '@/services/dashboards/dashboards-service';\nimport z from 'zod';\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 description - The description of the tool\n * @param originalFunction - The function to call when the tool is used\n * @param boundContext - The context for the dashboard builder\n * @returns A zod function for the tool\n */\nconst createDashboardTool = (\n\toriginalSchema: any,\n\tname: string,\n\tdescription: string,\n\toriginalFunction: any,\n\tboundContext: BuildDashboardContext,\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 dashboard builder with injected dependencies\n * @param context - The bound context for the dashboard builder.\n * @returns A set of tools for the dashboard builder.\n */\nconst createDashboardTools = (context: BuildDashboardContext) => {\n\treturn [\n\t\tcreateDashboardTool(\n\t\t\tloadExistingFusionDashboardSchema,\n\t\t\t'loadExistingFusionDashboard',\n\t\t\t'Load an existing Fusion dashboard by title',\n\t\t\tloadExistingFusionDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tcreateDashboardSchema,\n\t\t\t'createDashboard',\n\t\t\t'Create a new dashboard with optional widgets',\n\t\t\tcreateDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tupdateDashboardSchema,\n\t\t\t'updateDashboard',\n\t\t\t'Update the title of an existing dashboard',\n\t\t\tupdateDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\taddDashboardWidgetsSchema,\n\t\t\t'addDashboardWidgets',\n\t\t\t'Add existing chart or chart list to an existing dashboard',\n\t\t\taddDashboardWidgets,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tcreateChartWidgetForDashboardSchema,\n\t\t\t'createChartWidgetForDashboard',\n\t\t\t'Create a new chart widget and add it to the dashboard',\n\t\t\tcreateChartWidgetForDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\tupdateChartWidgetForDashboardSchema,\n\t\t\t'updateChartWidgetForDashboard',\n\t\t\t'Update an existing chart widget in the dashboard.',\n\t\t\tupdateChartWidgetForDashboard,\n\t\t\tcontext,\n\t\t),\n\t\tcreateDashboardTool(\n\t\t\taddDashboardFiltersSchema,\n\t\t\t'addDashboardFilters',\n\t\t\t'Add combined filters to an existing dashboard. Do not split the prompt into multiple filters.',\n\t\t\taddDashboardFilters,\n\t\t\tcontext,\n\t\t),\n\t];\n};\n\n/**\n * Build contextual system prompt for dashboard builder\n */\nexport function buildContextualSystemPrompt(\n\tchartSummaries: ChartSummary[],\n\tchartListSummaries: ChartListSummary[],\n\tdashboardSummaries: DashboardSummary[],\n) {\n\treturn `You are an intelligent and proactive dashboard assistant. \n\tYour role is to create, load, and update a dashboard, its widgets, and its filters based on natural language requests by using the available tools.\n\t\n\t \n\tIMPORTANT INSTRUCTIONS:\n\t1. Use the available tools to build the dashboard. Politely decline if asked to do something not related to the available tools.\n\t2. If the user prompt can be handled by a single tool, use that tool without splitting the prompt into multiple steps. \n\t3. Use the assets in the following context to build the dashboard: ${JSON.stringify(\n\t\t{\n\t\t\tcharts: chartSummaries,\n\t\t\tchartLists: chartListSummaries,\n\t\t\tdashboards: dashboardSummaries,\n\t\t},\n\t\tnull,\n\t\t2,\n\t)}\n\t4. Always reference the assets by their IDs instead of their titles.\n 5. Always use the last dashboard in the context as the current dashboard unless the user prompt specifies otherwise.\n\t6. To add a widget to the dashboard, use the last chart or chart list in the context.\n\t7. If no charts or chart lists exist in the context, run the \\`createChartWidgetForDashboard\\` tool to build a chart and add it to the dashboard.\n\t8. To update a chart widget, make sure the widget exists within the dashboard.\n\t`;\n}\n\n/**\n * Standalone dashboard builder engine - completely decoupled from any UI or store\n * @param params - The parameters for the dashboard builder\n * @param context - All external dependencies injected\n * @returns The dashboard summary\n */\nexport async function buildDashboardEngine(\n\tparams: z.infer<typeof buildDashboardSchema>,\n\tcontext: BuildDashboardContext,\n): Promise<DashboardSummary> {\n\tconst { dataSourceTitle, userPrompt } = params;\n\n\tconsole.debug(TOOL_NAME_DASHBOARD_BUILDER, dataSourceTitle, userPrompt);\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 dashboard id\n\tconst newDashboardId = context.toolCallId;\n\n\tlet savedDashboardProps: ExtendedDashboardProps | null = null;\n\n\tlet message = '';\n\tlet isError = false;\n\n\tconst updatedContext: BuildDashboardContext = {\n\t\t...context,\n\t\tdataSourceTitle,\n\t\tretrieveDashboard: (dashboardId: string) => {\n\t\t\t// Prioritize savedDashboardProps in case of subsequent tool calls\n\t\t\tif (savedDashboardProps) {\n\t\t\t\treturn savedDashboardProps;\n\t\t\t}\n\t\t\tif (dashboardId && context.retrieveDashboard) {\n\t\t\t\treturn context.retrieveDashboard(dashboardId);\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsaveDashboard: (dashboardProps: ExtendedDashboardProps) => {\n\t\t\tcontext.saveDashboard?.(dashboardProps);\n\t\t\tsavedDashboardProps = dashboardProps;\n\t\t},\n\t\tgetWidgetList: (widgetIds: string[]) => {\n\t\t\tif (context.getWidgetList) {\n\t\t\t\treturn context\n\t\t\t\t\t.getWidgetList(widgetIds)\n\t\t\t\t\t.map(resetWidgetForDashboard);\n\t\t\t}\n\t\t\treturn [];\n\t\t},\n\t};\n\n\t// Update dashboard summaries with latest changes from context\n\t// (dashboard tool call results may be manually updated by the user using the UI)\n\tconst updatedDashboardSummaries: DashboardSummary[] = (\n\t\tcontext.dashboardSummaries ?? []\n\t).map((dashboardSummary) => {\n\t\tif (!dashboardSummary.dashboard) {\n\t\t\treturn dashboardSummary;\n\t\t}\n\n\t\tif (context.retrieveDashboard) {\n\t\t\ttry {\n\t\t\t\tconst dashboardProps = context.retrieveDashboard(\n\t\t\t\t\tdashboardSummary.dashboardId,\n\t\t\t\t);\n\t\t\t\tif (dashboardProps) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...dashboardSummary,\n\t\t\t\t\t\tdashboard: getBaseDashboardSummary(\n\t\t\t\t\t\t\tdashboardProps,\n\t\t\t\t\t\t\tdashboardSummary.dashboard\n\t\t\t\t\t\t\t\t?.defaultDataSourceTitle || dataSourceTitle,\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// If loading fails, return original summary\n\t\t\t}\n\t\t}\n\t\treturn dashboardSummary;\n\t});\n\n\tconst systemPrompt = buildContextualSystemPrompt(\n\t\t(context.chartSummaries ?? []).slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t\t// only use the latest chart list summary so that the LLM can focus on the latest recommendations\n\t\t(context.chartListSummaries ?? []).slice(-1),\n\t\tupdatedDashboardSummaries.slice(-TOOL_CONTEXT_MAX_ASSETS),\n\t);\n\n\tconst internalTools = createDashboardTools(updatedContext);\n\n\t// Use createToolsCompletion to let LLM choose and execute the appropriate sub-tool\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\tconst resultForLLM: DashboardSummary = {\n\t\tmessage,\n\t\tcreatedAt: new Date().toISOString(),\n\t\tdashboardId: newDashboardId,\n\t\tdashboard: savedDashboardProps\n\t\t\t? getBaseDashboardSummary(savedDashboardProps, dataSourceTitle)\n\t\t\t: undefined,\n\t};\n\n\treturn resultForLLM;\n}\n","import { z } from 'zod';\nimport { WidgetProps, ChartType } from '@sisense/sdk-ui';\nimport { HttpClient } from '@sisense/sdk-rest-client';\nimport type { OpenAI } from 'openai';\n\n/**\n * Default number of query recommendations to return\n */\nexport const DEFAULT_QUERY_COUNT = 4;\n\n/**\n * Schema for recommendQueries engine parameters\n */\nexport const recommendQueriesSchema = z.object({\n\tdataSourceTitle: z.string().describe('Data source title'),\n\tqueryCount: z\n\t\t.number()\n\t\t.optional()\n\t\t.describe('Number of recommended queries to return.'),\n\tuserPrompt: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'User prompt or context to guide recommendations. Used to filter and prioritize relevant queries.',\n\t\t),\n\texistingWidgets: z\n\t\t.array(z.string())\n\t\t.optional()\n\t\t.describe(\n\t\t\t'List of existing widget titles/descriptions to avoid duplicates when adding to existing dashboard.',\n\t\t),\n});\n\n/**\n * Context interface for recommendQueriesEngine\n */\nexport interface RecommendQueriesContext {\n\t/**\n\t * Tool call ID\n\t */\n\ttoolCallId: string;\n\t/** Whether NLQ V3 is enabled */\n\tisNlqV3Enabled?: boolean;\n\thttpClient?: HttpClient;\n\topenAIClient?: OpenAI;\n}\n\n/**\n * Query and chart recommendation type\n */\nexport type QueryAndChartRecommendation = {\n\tdetailedDescription: string;\n\tnlqPrompt: string;\n} & WidgetProps;\n\n/**\n * Result from recommendQueriesEngine\n */\nexport interface RecommendQueriesResult {\n\t/**\n\t * List of query and chart recommendations\n\t */\n\trecommendations: QueryAndChartRecommendation[];\n}\n\n/**\n * Callback for receiving intermediate recommendations (before chart generation)\n */\nexport type OnIntermediateResultsCallback = (\n\trecommendations: QueryAndChartRecommendation[],\n) => void;\n\n/**\n * Chart type keywords mapping for extraction from user prompts\n */\nexport const CHART_TYPE_KEYWORDS: Record<string, ChartType> = {\n\tbar: 'bar',\n\tcolumn: 'column',\n\tline: 'line',\n\tpie: 'pie',\n\tscatter: 'scatter',\n\tarea: 'area',\n\tfunnel: 'funnel',\n\tpolar: 'polar',\n\ttreemap: 'treemap',\n\tsunburst: 'sunburst',\n\tboxplot: 'boxplot',\n};\n","import { z } from 'zod';\nimport { ChartType } from '@sisense/sdk-ui';\nimport { getQueryRecommendationsLight } from '@/services/nlq/nlq-service';\nimport { getDataSourceSchema } from '@/services/data-models/data-models-service';\nimport { generateChart } from '@/engines/chart-builder/create-chart/create-chart';\nimport { TOOL_NAME_RECOMMEND_QUERIES } from '@/constants';\nimport {\n\trecommendQueriesSchema,\n\tRecommendQueriesContext,\n\tRecommendQueriesResult,\n\tQueryAndChartRecommendation,\n\tOnIntermediateResultsCallback,\n\tDEFAULT_QUERY_COUNT,\n\tCHART_TYPE_KEYWORDS,\n} from './types';\n\n/**\n * Helper function to extract chart type preference from user prompt\n */\nexport function extractChartTypeFromPrompt(\n\tuserPrompt: string,\n): ChartType | undefined {\n\tconst lowerPrompt = userPrompt.toLowerCase();\n\tfor (const [keyword, chartType] of Object.entries(CHART_TYPE_KEYWORDS)) {\n\t\tif (lowerPrompt.includes(keyword)) {\n\t\t\treturn chartType;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Helper function to build context-aware user prompt\n */\nexport function buildContextualPrompt(\n\tuserPrompt?: string,\n\texistingWidgets?: string[],\n): string | undefined {\n\tif (!userPrompt && !existingWidgets?.length) {\n\t\treturn undefined;\n\t}\n\n\tlet contextualPrompt = '';\n\n\t// Add the user's original prompt\n\tif (userPrompt) {\n\t\tcontextualPrompt = userPrompt;\n\t}\n\n\t// Add context about existing widgets to avoid duplicates\n\tif (existingWidgets?.length) {\n\t\t// also unique the existing widgets\n\t\tconst uniqueExistingWidgets = [...new Set(existingWidgets)];\n\t\tconst widgetContext = `DO NOT recommend queries that are similar to these:\\n${uniqueExistingWidgets\n\t\t\t.map((widget) => `- ${widget}`)\n\t\t\t.join('\\n')}`;\n\t\tcontextualPrompt = contextualPrompt\n\t\t\t? `<INSTRUCTIONS>${widgetContext}</INSTRUCTIONS>\\n\\n<USER-PROMPT> ${contextualPrompt}</USER-PROMPT>`\n\t\t\t: widgetContext;\n\t}\n\n\treturn contextualPrompt;\n}\n\n/**\n * Standalone recommend queries engine - completely decoupled from any UI or store\n * @param params - The parameters for getting query recommendations\n * @param context - Context with tool call ID for tracking\n * @param onIntermediateResults - Optional callback for intermediate results (before chart generation)\n * @returns The recommendations result with query and chart recommendations\n */\nexport async function recommendQueriesEngine(\n\tparams: z.infer<typeof recommendQueriesSchema>,\n\tcontext: RecommendQueriesContext,\n\tonIntermediateResults?: OnIntermediateResultsCallback,\n): Promise<RecommendQueriesResult> {\n\tconst {\n\t\tdataSourceTitle,\n\t\tqueryCount = DEFAULT_QUERY_COUNT,\n\t\tuserPrompt,\n\t\texistingWidgets,\n\t} = params;\n\n\tconst defaultErrorMessage = 'Error: Failed to get recommended queries';\n\n\tconsole.debug(\n\t\tTOOL_NAME_RECOMMEND_QUERIES,\n\t\tdataSourceTitle,\n\t\tcontext.toolCallId,\n\t);\n\n\t// Validate required parameters\n\tif (!dataSourceTitle) {\n\t\tthrow new Error('Error: Please specify data source title');\n\t}\n\n\t// Verify data source exists\n\tconst dataSources = await getDataSourceSchema(\n\t\tdataSourceTitle,\n\t\tcontext.httpClient,\n\t);\n\tif (!dataSources) {\n\t\tthrow new Error(\n\t\t\t'Error: Data source not found. Make sure to create a model first',\n\t\t);\n\t}\n\n\t// Build contextual prompt that includes user intent and existing widgets\n\tconst contextualPrompt = buildContextualPrompt(userPrompt, existingWidgets);\n\n\tconst recommendedQueries = await getQueryRecommendationsLight(\n\t\tdataSourceTitle,\n\t\t{\n\t\t\tnumOfRecommendations: queryCount,\n\t\t\tuserPrompt: contextualPrompt,\n\t\t},\n\t\tcontext.httpClient,\n\t);\n\n\tif (!recommendedQueries) {\n\t\tthrow new Error(defaultErrorMessage);\n\t}\n\n\t// Notify intermediate results (queries without charts) if callback provided\n\tif (onIntermediateResults && recommendedQueries.length > 0) {\n\t\tconst intermediateResults = recommendedQueries.map((query) => ({\n\t\t\tnlqPrompt: query.nlqPrompt,\n\t\t\tdetailedDescription: query.detailedDescription,\n\t\t})) as QueryAndChartRecommendation[];\n\t\tonIntermediateResults(intermediateResults);\n\t}\n\n\t// Extract chart type preference from user prompt\n\tconst preferredChartType = userPrompt\n\t\t? extractChartTypeFromPrompt(userPrompt)\n\t\t: undefined;\n\n\t// Generate chart for each recommended query\n\tconst recommendedCharts = await Promise.all(\n\t\trecommendedQueries.map(async (query) => {\n\t\t\t// query.nlqPrompt is already data-focused, use it as queryPrompt\n\t\t\t// Create a simple chartPrompt based on preferred chart type or generic\n\t\t\tconst chartPrompt = preferredChartType\n\t\t\t\t? `Create a ${preferredChartType} chart visualization`\n\t\t\t\t: 'Create a chart visualization';\n\n\t\t\tconst chartWidgetProps = await generateChart(\n\t\t\t\t{\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tqueryPrompt: query.nlqPrompt,\n\t\t\t\t\tchartPrompt,\n\t\t\t\t\tchartType: preferredChartType,\n\t\t\t\t\tchartTitle: query.nlqPrompt,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttoolCallId: context.toolCallId,\n\t\t\t\t\tdataSourceTitle,\n\t\t\t\t\tisNlqV3Enabled: context.isNlqV3Enabled,\n\t\t\t\t\thttpClient: context.httpClient,\n\t\t\t\t\topenAIClient: context.openAIClient,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\t...chartWidgetProps,\n\t\t\t\tnlqPrompt: query.nlqPrompt,\n\t\t\t\tdetailedDescription: query.detailedDescription,\n\t\t\t};\n\t\t}),\n\t);\n\n\treturn {\n\t\trecommendations: recommendedCharts,\n\t};\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","opt","processSchemaProperties","propertyNames","mode","z","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","queryIdSchema","chartRecommendationsSchema","buildChartSchema","buildChartSchemaNaturalConversation","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","getHttpErrorStatus","err","raw","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_NAME_BUILD_QUERY","TOOL_CONTEXT_MAX_ASSETS","MAX_DATA_SOURCE_FIELDS_SUMMARY","DEFAULT_LLM","HEADER_USER_ACTION_ID","HEADER_TRACEPARENT","HEADER_INTERFACE_NAME","HEADER_FEATURE_NAME","HEADER_QUOTA_ID","ALLOWED_HEADERS","CONSUMPTION_CAPTURE_PATH","CONSUMPTION_REPORT_PATH","QuotaExceededError","captureConsumption","requestOptions","client","getHttpClient","response","status","reportConsumption","quotaId","generateUserActionId","generateTraceparent","traceId","spanId","UserActionContext","interfaceName","featureName","captureUuid","withTrackingHeaders","e","userActionContext","startUserAction","getUserActionHeaders","DEFAULT_HTTP_CLIENT_HEADERS","normalizeHeaders","headers","trackingHeaders","normalizedHeaders","endUserAction","runWithUserAction","started","createCustomFetch","httpClient","init","isBearerAuth","lowerKey","header","newInit","OPENAI_API_URL_PATH","createOpenAIClientHelper","baseURL","fetchFn","OpenAI","createOpenAIClient","initializeHttpClient","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","mapColumnIndicesToObjects","indices","columns","column","mapChartDataToColumns","recommendations","mapping","generateChartRecommendations","cols","prompt","updatedRecommendations","getNlqResult","contextTitle","request","getNlqResultLight","getNlqV3Result","getQueryRecommendations","getQueryRecommendationsLight","buildQueryEngine","dataSourceTitle","queryPrompt","nlqResult","dataSchema","dataset","queryId","generateChartTableFromNlqV2","widgetProps","widgetComposer","isChartWidgetProps","generateChartTableFromNlqV3","retrieveQuery","chartTitle","queryResult","translationResult","translateQueryFromJSON","translatedParams","jaql","translateQueryToJaql","convertDataSource","generateChartTable","isNlqV3Enabled","generateChart","chartPrompt","dataColumns","chartRecommendations","newChartType","baseStyleOptions","getChartStyleOptions","createChart","paramsQueryId","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","buildSystemPromptForDataOptions","filteredSchema","additionalInstructions","currentDataOptions","updateChartDataOptionsHelper","currentChartType","baseSchema","responseDataOptions","mergedDataOptions","mergeDataOptions","original","aiResponse","merged","dataOptionsKey","incomingList","originalList","originalItem","originalName","updatedItem","updateChartDataOptions","createUpdateChartDataOptionsTool","updateChartTypeOfMeasuresConfig","updateChartSortingConfig","updateTrendAndForecastConfig","updateOtherChartDataOptionsConfig","updateChartTypeOfMeasures","updateChartSorting","updateTrendAndForecast","updateOtherChartDataOptions","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","getBaseChartSummary","createChartTool","originalSchema","originalFunction","boundContext","createChartTools","buildContextualSystemPrompt","chartSummaries","querySummaries","buildChartEngine","newChartId","savedChartWidgetProps","updatedContext","internalTools","isErrorInToolsCompletion","buildQuerySchema","DATA_MODELS_API_URL_PATH","getDataSourceSchema","dataSourceName","DATA_SOURCES_API_URL_PATH","addDescriptionToFields","fields","datasets","schemaDataDescriptionsMap","map","table","field","getDataSources","getDataSourceByTitle","getDataSourceFields","getDataSourceFieldsWithDescriptions","dataSourceSchema","normalizeFields","normalizedFields","normalizedName","normalizeName","baseField","DateLevels","level","getNormalizedDataSourceFields","getFieldsFn","getDataSourcesEngine","dataSources","ds","getDataSourcesSchema","ALIAS","DOC","MAP","PAIR","SCALAR","SEQ","NODE_TYPE","isAlias","node","isDocument","isMap","isPair","isScalar","isSeq","isCollection","isNode","hasAnchor","BREAK","SKIP","REMOVE","visit","visitor","visitor_","initVisitor","visit_","path","ctrl","callVisitor","replaceNode","ci","ck","cv","parent","pt","escapeChars","escapeTagName","tn","ch","Directives","yaml","tags","copy","line","onError","parts","handle","prefix","version","isValid","verbatim","suffix","tag","doc","lines","tagEntries","tagNames","_key","anchorIsValid","anchor","msg","anchorNames","root","anchors","findNewAnchor","exclude","createNodeAnchors","aliasObjects","sourceObjects","prevAnchors","ref","applyReviver","reviver","len","v0","v1","toJS","arg","ctx","data","NodeBase","mapAsMap","maxAliasCount","onAnchor","count","Alias","nodes","found","_arg","getAliasCount","_onComment","_onChompKeep","src","kc","vc","isScalarValue","Scalar","defaultTagPrefix","findTagObject","tagName","match","t","tagObj","createNode","aliasDuplicateObjects","onTagObj","collectionFromPath","isEmptyPath","Collection","it","keepScalar","allowScalar","stringifyComment","str","indentComment","comment","lineComment","FOLD_FLOW","FOLD_BLOCK","FOLD_QUOTED","foldFlowLines","text","indentAtStart","lineWidth","minContentWidth","onFold","onOverflow","endStep","folds","escapedFolds","end","split","overflow","escStart","escEnd","consumeMoreIndentedLines","fold","start","getFoldOptions","isBlock","containsDocumentMarker","lineLengthOverLimit","indentLength","limit","strLen","doubleQuotedString","json","implicitKey","minMultiLineLength","code","singleQuotedString","quotedString","singleQuote","qs","hasDouble","hasSingle","blockEndNewlines","blockString","onComment","onChompKeep","blockQuote","commentString","chomp","endStart","endNlPos","startWithSpace","startEnd","startNlPos","foldedValue","literalFallback","foldOptions","body","plainString","actualString","indentStep","inFlow","test","compat","stringifyString","ss","_stringify","_type","defaultKeyType","defaultStringType","createStringifyContext","getTagObject","testMatch","stringifyProps","stringify","stringifyPair","allNullValues","indentSeq","simpleKeys","keyComment","explicitKey","keyCommentDone","chompKeep","vsb","vcb","valueComment","valueCommentDone","valueStr","ws","cs","vs0","nl0","hasNewline","flow","hasPropsLine","sp0","warn","logLevel","warning","MERGE_KEY","merge","addMergeToJSMap","isMergeKey","mergeValue","srcMap","addPairToJSMap","jsKey","stringKey","stringifyKey","jsValue","strCtx","strKey","jsonStr","createPair","Pair","pair","stringifyCollection","collection","stringifyFlowCollection","stringifyBlockCollection","items","blockItemPrefix","flowChars","itemIndent","itemCtx","addCommentBefore","ik","fcPadding","reqNewline","linesAtValue","iv","sum","ic","findPair","YAMLMap","keepUndefined","replacer","add","overwrite","_pair","sortEntries","Type","YAMLSeq","idx","asItemIndex","seq","string","nullTag","boolTag","sv","stringifyNumber","format","minFractionDigits","num","d","floatNaN","floatExp","float","dot","intIdentify","intResolve","offset","radix","intAsBigInt","intStringify","intOct","_onError","int","intHex","stringifyJSON","jsonScalars","jsonError","binary","buffer","buf","s","resolvePairs","cn","createPairs","iterable","pairs","YAMLOMap","omap","seenKeys","boolStringify","trueTag","falseTag","f","sign","intBin","YAMLSet","keepPair","set","parseSexagesimal","asBigInt","p","stringifySexagesimal","_60","intTime","floatTime","timestamp","year","month","day","hour","minute","second","millisec","date","tz","schemas","schema$1","schema$2","tagsByName","coreKnownTags","getTags","customTags","schemaName","addMergeTag","schemaTags","sortMapEntriesByKey","Schema","resolveKnownTags","sortMapEntries","toStringDefaults","stringifyDocument","hasDirectives","dir","contentComment","dc","Document","_replacer","assertCollection","keyToStr","asStr","anchorPrefix","setAnchors","jsonArg","contents","getDataSourceFieldsEngine","buildCompactSchema","isTruncated","tables","intro","tablesYaml","getDataSourceFieldsSummary","totalFields","tableCount","truncatedFields","tableName","fieldsLabel","tablesLabel","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","getDashboardsEngine","getDashboardsSchema","buildDashboardSchema","createDashboardSchema","loadExistingFusionDashboardSchema","updateDashboardSchema","addDashboardWidgetsSchema","createChartWidgetForDashboardSchema","updateChartWidgetForDashboardSchema","addDashboardFiltersSchema","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","createDashboard","widgetIdsToAdd","getWidgetList","saveDashboard","newWidgetList","loadExistingFusionDashboard","fusionDashboard","updateDashboard","retrieveDashboard","currentDashboard","addDashboardWidgets","FILTER_FACTORY_TYPES","MEASURE_FACTORY_TYPES","generateFilterSystemPrompt","getFactoryFunctionsMap","factoryName","factoryObject","functionsMap","nestedFunctionsMap","nestedKey","measureFactoryFunctionsMap","measureFactory","filterFactoryFunctionsMap","filterFactory","executeFunction","functionPath","createAttribute","attributeName","dataFields","dataField","createAttributeHelper","processArg","processNode","parsedObject","processedArgs","postProcessFilter","filter","attribute","isMembersFilter","granularity","member","postProcessFilters","isFilterRelations","translateFiltersFromJsonFunctionCall","filtersJson","parsedJson","manipulateDashboardFilters","fullUserPrompt","explanation","mergeFiltersOrFilterRelations","addDashboardFilters","createChartWidgetForDashboard","toolCallId","isNewDashboard","newChartWidgetProps","chartSummary","resetChartWidgetProps","updateChartWidgetForDashboard","widgetIndex","updatedWidgetProps","getBaseDashboardSummary","isPivotTableWidgetProps","createDashboardTool","createDashboardTools","chartListSummaries","dashboardSummaries","buildDashboardEngine","newDashboardId","savedDashboardProps","updatedDashboardSummaries","dashboardSummary","DEFAULT_QUERY_COUNT","recommendQueriesSchema","CHART_TYPE_KEYWORDS","extractChartTypeFromPrompt","lowerPrompt","keyword","buildContextualPrompt","existingWidgets","contextualPrompt","widgetContext","recommendQueriesEngine","onIntermediateResults","queryCount","defaultErrorMessage","recommendedQueries","intermediateResults","query","preferredChartType","createElasticube","getCSVSchemaDetails","filePath","fileName","getPerspectiveOid","elasticubeOid","addDataSet","perspectiveOid","tableId","oid","buildElasticube","buildStatus","addRelation","getElasticubes","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,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C,SAAOA;AACR;AAEA,eAAsBu3B,GACrBC,GACuB;AACvB,QAAM91B,IAAa3B,EAAA,GAEb03B,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,iBAAM91B,EAAW,KAAU21B,IAA2BI,CAAU,GAIzDD;AAAA,EACR,SAASj6B,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,99,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,162]}