{"version":3,"file":"split_by_axes.cjs","names":["deriveAxisValuesLabels","hasReachableData","TreeNodeAccessor","isDataInfoEntries","getUniquePartitionKeys","getAxisId","readAnnotation","Annotation","canonicalizeAxisId","ColumnFilteredRecipe","ColumnOverriddenRecipe"],"sources":["../../src/columns/split_by_axes.ts"],"sourcesContent":["import type {\n  AxisFilterByIdx,\n  AxisFilterValue,\n  AxisId,\n  TraceEntry,\n} from \"@milaboratories/pl-model-common\";\nimport {\n  Annotation,\n  canonicalizeAxisId,\n  getAxisId,\n  isDataInfoEntries,\n  readAnnotation,\n} from \"@milaboratories/pl-model-common\";\nimport { TreeNodeAccessor } from \"../render/accessor\";\nimport { getUniquePartitionKeys } from \"../render/util/pcolumn_data\";\nimport { deriveAxisValuesLabels } from \"./derive_axis_values_labels\";\nimport type { ColumnRecipe } from \"./column_recipes\";\nimport { ColumnFilteredRecipe } from \"./column_recipes/column_filtered_recipe\";\nimport { ColumnOverriddenRecipe } from \"./column_recipes/column_overrided_recipe\";\nimport { Column } from \"./column\";\nimport { hasReachableData } from \"./utils\";\n\n// --- Types ---\n\nexport interface SplitAxis {\n  /** Index of the axis in the column's axesSpec to split by. */\n  readonly idx: number;\n}\n\nexport interface SplitByAxesOpts {\n  /**\n   * Resolve axis values to human-readable labels.\n   *\n   * Defaults to {@link deriveAxisValuesLabels} over the ambient render ctx\n   * (current block outputs + result pool), resolved lazily on the first\n   * lookup. Pass an explicit callback to narrow the label source, or\n   * `() => undefined` to keep raw axis values.\n   */\n  axisValuesLabels?: (axisId: AxisId) => undefined | Record<string | number, string>;\n}\n\n// --- Implementation ---\n\nconst MAX_KEY_COMBINATIONS = 10_000;\n\n/**\n * Split each input column along the requested axes into one\n * {@link ColumnRecipe} per Cartesian combination of the axes' distinct values.\n *\n * The split axes must be partition-key axes of the input's data — the distinct\n * values are read off the partition keys.\n *\n * Each split is produced as `ColumnOverriddenRecipe.wrap(ColumnFilteredRecipe.wrap(inner, axisFilters), { domain, annotations })`:\n *   - `ColumnFilteredRecipe` pins all split axes at once (one wrap call with\n *     every `[idx, value]` pair) and removes them from `axesSpec`. The\n *     engine performs the data slicing via the `sliceAxes` query node.\n *   - `ColumnOverriddenRecipe` overlays a `domain[axisName] = String(value)`\n *     entry per split axis and appends a `split:<canonicalAxisId>` trace\n *     entry per split axis to the existing `pl7.app/trace` annotation.\n *\n * The recipe id is a canonical\n * `ColumnOverriddenId(source: ColumnFilteredId(source: inner.id, axisFilters), specOverrides)`\n * — distinct per split combination, parseable by `extractPObjectId`, and\n * traversable by recipe walkers.\n *\n * Returns `undefined` when any input's `getData()` is not a\n * {@link TreeNodeAccessor} — partition inspection is not yet possible.\n */\nexport function splitByAxes(\n  inputs: Column[],\n  splitAxes: SplitAxis[],\n  opts?: SplitByAxesOpts,\n): ColumnRecipe[] | undefined {\n  if (splitAxes.length === 0) {\n    return [...inputs];\n  }\n\n  const axisValuesLabels = opts?.axisValuesLabels ?? deriveAxisValuesLabels();\n\n  const splitAxisIdxs = splitAxes.map((a) => a.idx).sort((a, b) => a - b);\n  const maxSplitIdx = splitAxisIdxs[splitAxisIdxs.length - 1];\n\n  const result: ColumnRecipe[] = [];\n\n  for (const inner of inputs) {\n    const data = hasReachableData(inner) ? inner.getData() : undefined;\n    // Partition inspection requires either a live tree-accessor or already\n    // parsed DataInfoEntries. Anything else means the input is not yet ready.\n    if (!(data instanceof TreeNodeAccessor) && !isDataInfoEntries(data)) {\n      return undefined;\n    }\n\n    const uniqueKeys = getUniquePartitionKeys(data);\n    if (uniqueKeys === undefined) return undefined;\n\n    if (maxSplitIdx >= uniqueKeys.length) {\n      throw new Error(\n        `Not enough partition keys (${uniqueKeys.length}) for requested split axes (max index ${maxSplitIdx}) in column ${inner.getSpec().name}`,\n      );\n    }\n\n    const spec = inner.getSpec();\n    const axesSpec = spec.axesSpec;\n    const splitAxisSpecs = splitAxisIdxs.map((idx) => axesSpec[idx]);\n    const splitAxisIds = splitAxisSpecs.map((axisSpec) => getAxisId(axisSpec));\n    const axesLabels = splitAxisIds.map((axisId) => axisValuesLabels(axisId));\n\n    const existingTraceRaw = readAnnotation(spec, Annotation.Trace);\n    const baseTrace: TraceEntry[] = existingTraceRaw\n      ? ((JSON.parse(existingTraceRaw) as TraceEntry[]) ?? [])\n      : [];\n\n    const keyCombinations = generateKeyCombinations(uniqueKeys, splitAxisIdxs);\n    if (keyCombinations.length === 0) continue;\n\n    for (const keyCombo of keyCombinations) {\n      const axisFilters: AxisFilterByIdx[] = keyCombo.map((value, sAxisIdx): AxisFilterByIdx => [\n        splitAxisIdxs[sAxisIdx],\n        value as AxisFilterValue,\n      ]);\n\n      const domain: Record<string, string> = {};\n      const traceEntries: TraceEntry[] = [];\n      for (let sAxisIdx = 0; sAxisIdx < keyCombo.length; sAxisIdx++) {\n        const value = keyCombo[sAxisIdx];\n        const axisSpec = splitAxisSpecs[sAxisIdx];\n        const axisId = splitAxisIds[sAxisIdx];\n        const labelMap = axesLabels[sAxisIdx];\n        const label = labelMap?.[value] ?? String(value);\n        domain[axisSpec.name] = String(value);\n        traceEntries.push({\n          type: `split:${canonicalizeAxisId(axisId)}`,\n          label,\n          importance: 1_000_000,\n        });\n      }\n\n      const filtered = ColumnFilteredRecipe.wrap(inner, axisFilters);\n      const overrided = ColumnOverriddenRecipe.wrap(filtered, {\n        domain,\n        annotations: {\n          [Annotation.Trace]: JSON.stringify([...baseTrace, ...traceEntries]),\n        },\n      });\n\n      result.push(overrided);\n    }\n  }\n\n  return result;\n}\n\nfunction generateKeyCombinations(\n  uniqueKeys: (string | number)[][],\n  splitAxisIdxs: number[],\n): (string | number)[][] {\n  const combinations: (string | number)[][] = [];\n\n  function generate(currentCombo: (string | number)[], sAxisIdx: number): void {\n    if (sAxisIdx >= splitAxisIdxs.length) {\n      combinations.push([...currentCombo]);\n      if (combinations.length > MAX_KEY_COMBINATIONS) {\n        throw new Error(\"Too many key combinations, aborting.\");\n      }\n      return;\n    }\n\n    const axisIdx = splitAxisIdxs[sAxisIdx];\n    if (axisIdx >= uniqueKeys.length) {\n      throw new Error(\n        `Axis index ${axisIdx} out of bounds for unique keys array (length ${uniqueKeys.length})`,\n      );\n    }\n\n    const axisValues = uniqueKeys[axisIdx];\n    if (!axisValues || axisValues.length === 0) {\n      combinations.length = 0;\n      return;\n    }\n\n    for (const val of axisValues) {\n      currentCombo.push(val);\n      generate(currentCombo, sAxisIdx + 1);\n      currentCombo.pop();\n    }\n  }\n\n  generate([], 0);\n  return combinations;\n}\n"],"mappings":";;;;;;;;AA2CA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;AAyB7B,SAAgB,YACd,QACA,WACA,MAC4B;CAC5B,IAAI,UAAU,WAAW,GACvB,OAAO,CAAC,GAAG,MAAM;CAGnB,MAAM,mBAAmB,MAAM,oBAAoBA,kCAAAA,uBAAuB;CAE1E,MAAM,gBAAgB,UAAU,KAAK,MAAM,EAAE,GAAG,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;CACtE,MAAM,cAAc,cAAc,cAAc,SAAS;CAEzD,MAAM,SAAyB,CAAC;CAEhC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,OAAOC,cAAAA,iBAAiB,KAAK,IAAI,MAAM,QAAQ,IAAI,KAAA;EAGzD,IAAI,EAAE,gBAAgBC,iBAAAA,qBAAqB,EAAA,GAACC,gCAAAA,kBAAAA,CAAkB,IAAI,GAChE;EAGF,MAAM,aAAaC,qBAAAA,uBAAuB,IAAI;EAC9C,IAAI,eAAe,KAAA,GAAW,OAAO,KAAA;EAErC,IAAI,eAAe,WAAW,QAC5B,MAAM,IAAI,MACR,8BAA8B,WAAW,OAAO,wCAAwC,YAAY,cAAc,MAAM,QAAQ,CAAC,CAAC,MACpI;EAGF,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,WAAW,KAAK;EACtB,MAAM,iBAAiB,cAAc,KAAK,QAAQ,SAAS,IAAI;EAC/D,MAAM,eAAe,eAAe,KAAK,cAAA,GAAaC,gCAAAA,UAAAA,C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