{"version":3,"file":"utils.cjs","names":["extractPObjectId","collectSpecQueryColumns","DataColumnImpl","throwError","getResultPoolDatasetAxes","findPeerLinks","TreeNodeAccessor","isDataInfo","ColumnDiscoveredRecipe","ColumnOverriddenRecipe","ColumnFilteredRecipe","DataColumnOverriddenRecipe","isColumnsCollection","ColumnsCollection","deriveDistinctLabels","describePeerLinks","peerLinkedLast"],"sources":["../../src/columns/utils.ts"],"sourcesContent":["import {\n  collectSpecQueryColumns,\n  extractPObjectId,\n  isDataInfo,\n  visitDataInfo,\n  type AxisQualification,\n  type ColumnUniversalId,\n  type PObjectId,\n} from \"@milaboratories/pl-model-common\";\nimport { throwError } from \"@milaboratories/helpers\";\nimport type { GlobalCfgRenderCtx } from \"../render/internal\";\nimport { TreeNodeAccessor } from \"../render\";\nimport { deriveDistinctLabels, type DeriveLabelsOptions } from \"../labels/derive_distinct_labels\";\nimport { DataColumnRecipe, DataColumnImpl, type ColumnData } from \"./data_column\";\nimport { ColumnDiscoveredRecipe } from \"./column_recipes/column_discovered_recipe\";\nimport { ColumnFilteredRecipe } from \"./column_recipes/column_filtered_recipe\";\nimport {\n  ColumnOverriddenRecipe,\n  DataColumnOverriddenRecipe,\n} from \"./column_recipes/column_overrided_recipe\";\nimport type { ColumnRecipe } from \"./column_recipes/types\";\nimport { ColumnsCollection, isColumnsCollection } from \"./columns_collection\";\nimport type { ColumnsSource } from \"./column_providers/types\";\nimport {\n  describePeerLinks,\n  findPeerLinks,\n  getResultPoolDatasetAxes,\n  peerLinkedLast,\n} from \"./peer_links\";\n\n/**\n * PObjectIds of every non-hit column referenced by `recipe.getQuery()`,\n * deduped in traversal order. The hit column is\n * `extractPObjectId(recipe.id)`; anything else in the query is a linker or\n * other engine-consumed column.\n *\n * Pure query walk — no registry access. Use {@link collectLinkerColumns} for\n * the resolved {@link DataColumnRecipe} variant.\n */\nexport function collectLinkerIds(recipe: ColumnRecipe): PObjectId[] {\n  const hit = extractPObjectId(recipe.id);\n  const seen = new Set<PObjectId>();\n  const out: PObjectId[] = [];\n  for (const id of collectSpecQueryColumns(recipe.getQuery())) {\n    // Leaf ids in SpecQuery may be rich (e.g. ColumnDiscoveredId) — drop to\n    // bare PObjectId before comparing/registering so we hand the ambient\n    // ColumnRegistry physical ids it can resolve.\n    const bare = extractPObjectId(id);\n    if (bare === hit) continue;\n    if (seen.has(bare)) continue;\n    seen.add(bare);\n    out.push(bare);\n  }\n  return out;\n}\n\n/**\n * {@link collectLinkerIds} resolved against the ambient context as\n * {@link DataColumnRecipe} leaves. Throws if any id fails to resolve —\n * matches the contract of the legacy `resolveLinkers` it replaces.\n */\nexport function collectLinkerColumns(\n  recipe: ColumnRecipe,\n  opts: { ctx?: GlobalCfgRenderCtx } = {},\n): DataColumnRecipe<PObjectId>[] {\n  return collectLinkerIds(recipe).map(\n    (id) =>\n      DataColumnImpl.fromId(id, opts) ??\n      throwError(`materializeLinkers: linker ${id} not resolvable`),\n  );\n}\n\n/** Peer link labels for a column, checked against the result pool's datasets. */\nexport function createPeerLinkFinder(): (recipe: ColumnRecipe) => string[] {\n  const datasetAxes = getResultPoolDatasetAxes();\n  return (recipe) =>\n    findPeerLinks(\n      collectLinkerColumns(recipe).map((l) => l.getSpec()),\n      datasetAxes,\n    );\n}\n\n/**\n * Hit-side axis qualifications for the recipe — the ones that should land on\n * the outer-join entry wrapping this column at the consumer boundary.\n *\n * Descends {@link ColumnOverriddenRecipe} / {@link ColumnFilteredRecipe} via\n * `getInner()` until it finds a {@link ColumnDiscoveredRecipe}; otherwise\n * returns `[]`. Pure recipe walk — no query-tree introspection.\n */\nexport function hitQualifications(recipe: ColumnRecipe): readonly AxisQualification[] {\n  const discovered = findDiscovered(recipe);\n  return discovered?.getColumnQualifications() ?? [];\n}\n\n/**\n * Per-primary-column axis qualifications for the recipe — applied to the\n * outer primary anchors on this recipe's group side. Keyed by the external\n * primary column id (NOT by columns inside this recipe's own query).\n *\n * Same walk strategy as {@link hitQualifications}.\n */\nexport function queriesQualifications(\n  recipe: ColumnRecipe,\n): Readonly<Record<PObjectId, AxisQualification[]>> {\n  const discovered = findDiscovered(recipe);\n  return discovered?.getQueriesQualifications() ?? {};\n}\n\n/**\n * Whether the recipe's underlying data resources actually carry bytes —\n * strictly stronger than `getDataStatus() === \"present\"`, which only tells\n * that the `.data` field is wired onto the accessor.\n *\n * Walks every physical leaf the recipe depends on via\n * {@link ColumnRecipe.getReferencedIds} (resolves each id back to a\n * {@link DataColumnRecipe} through the ambient ctx) and ANDs `hasData()` across\n * all of them. Inline {@link PColumnValues} payloads count as present.\n *\n * Returns `false` if any leaf cannot be re-resolved in `opts.ctx` (treat as\n * \"not yet ready\") rather than throwing — this is a UI-facing predicate, not\n * a contract assertion.\n */\nexport function hasColumnData(\n  recipe: ColumnRecipe,\n  opts: { ctx?: GlobalCfgRenderCtx } = {},\n): boolean {\n  for (const id of recipe.getReferencedIds()) {\n    const leaf = DataColumnImpl.fromId(id, opts);\n    if (leaf === undefined) return false;\n    if (leaf.getDataStatus() !== \"present\") return false;\n    if (!isLeafDataPresent(leaf.getData())) return false;\n  }\n  return true;\n}\n\nfunction isLeafDataPresent(data: ColumnData): boolean {\n  if (data === undefined) return false;\n  if (Array.isArray(data)) return true;\n  if (data instanceof TreeNodeAccessor) return data.hasData();\n  if (isDataInfo(data)) {\n    let ok = true;\n    visitDataInfo(data, (blob) => {\n      ok &&= blob.hasData();\n    });\n    return ok;\n  }\n  return false;\n}\n\n/**\n * Walk wrapper layers (Overridden, Filtered) until a {@link\n * ColumnDiscoveredRecipe} is found. Returns `undefined` if the recipe chain\n * has no Discovered layer (bare leaves and Overridden-over-leaf cases).\n *\n * Invariant from the wrapper classes themselves: there is at most one\n * Discovered layer in any recipe chain — Discovered is constructed only via\n * its own factory and is never re-wrapped by Discovered.\n */\nfunction findDiscovered(recipe: ColumnRecipe): undefined | ColumnDiscoveredRecipe {\n  let current: ColumnRecipe = recipe;\n  while (true) {\n    if (current instanceof ColumnDiscoveredRecipe) return current;\n    if (current instanceof ColumnOverriddenRecipe || current instanceof ColumnFilteredRecipe) {\n      current = current.getInner();\n      continue;\n    }\n    return undefined;\n  }\n}\n\n/**\n * Whether the recipe reads exactly one data column — its own — rather than\n * reaching through others.\n *\n * True for a bare leaf and for projections over one (spec overrides, axis\n * slicing): those add layers but no new columns. False when the recipe gets at\n * its data through further columns, which happens when discovery reached it via\n * a linker chain.\n *\n * **Why callers care.** A recipe over a single data column is co-indexed by its\n * own axes, so its spec is the whole truth about them. One that needs other\n * columns only lines up after they are joined in, and therefore drags axes into\n * the join that its own spec never mentions — which is why it cannot serve as a\n * primary column, and why `createPlDataTableV3` splits on this.\n *\n * The count comes from {@link ColumnRecipe.getReferencedIds}, which resolves\n * through the whole wrapper chain, so no class walk is involved and foreign\n * `ColumnRecipe` implementations are handled too.\n */\nexport function hasSingleDataColumn(recipe: ColumnRecipe): boolean {\n  return recipe.getReferencedIds().length === 1;\n}\n\n/**\n * @deprecated Renamed to {@link hasSingleDataColumn} — \"leaf\" read as \"you can\n * get data out of it\", which is a different question (see\n * {@link hasReachableData}). Same semantics.\n */\nexport const isLeafColumn = hasSingleDataColumn;\n\n/**\n * Whether the column's data can be read here and now, consistent with its\n * spec — narrows to {@link DataColumnRecipe}, which exposes `getData()`.\n *\n * True for a bare leaf and for a spec-override over a bare leaf. False for an\n * axis-filtered recipe (its spec has dropped axes the underlying data still\n * carries, so the two no longer line up) and for anything reached through\n * other columns (nothing to read until the engine joins them). In both of\n * those cases the data exists only engine-side: pass `recipe.id` to\n * `createPFrame` / `createPTable` instead of trying to read it.\n *\n * The distinction is settled when the recipe is built, not here — recipes that\n * carry data are instances of a class that declares `getData`. So a `true`\n * result narrows to a value that really has the method, and there is no\n * throwing path behind the guard.\n */\nexport function hasReachableData(recipe: ColumnRecipe): recipe is DataColumnRecipe {\n  return recipe instanceof DataColumnImpl || recipe instanceof DataColumnOverriddenRecipe;\n}\n\n/** Drop-down option built over a {@link ColumnsCollection} — universal-id valued. */\nexport type ColumnOption = {\n  readonly id: ColumnUniversalId;\n  readonly label: string;\n  /** Set for columns reached through a peer link; the dropdown shows it beside a link icon. */\n  readonly linkHint?: string;\n};\n\n/**\n * Enumerates every column already in `source` and renders distinct labels\n * from each recipe's spec. Filtering is the caller's job — pass a\n * {@link ColumnsCollection} that was already narrowed via `.filter(...)` /\n * `.discover(...)`, or hand over a raw {@link ColumnsSource} (provider,\n * accessor, column array, or `\"result_pool\"` / `\"current_block\"` shorthand)\n * to be wrapped on the fly.\n */\nexport function deriveColumnOptions(\n  source: ColumnsCollection | ColumnsSource[],\n  labelOptions: DeriveLabelsOptions = {},\n): ColumnOption[] {\n  const collection = isColumnsCollection(source) ? source : ColumnsCollection(source);\n  return deriveRecipeOptions(collection.getColumns(), labelOptions).map(\n    ({ id, label, linkHint }) => ({ id, label, linkHint }),\n  );\n}\n\n/**\n * {@link ColumnOption}s for `recipes`, each with its recipe. Peer-linked columns go last, the rest\n * keep their order.\n */\nexport function deriveRecipeOptions<R extends ColumnRecipe>(\n  recipes: R[],\n  labelOptions: DeriveLabelsOptions = {},\n): (ColumnOption & { readonly recipe: R })[] {\n  const labels = deriveDistinctLabels(\n    recipes.map((r) => r.getSpec()),\n    labelOptions,\n  );\n  const findPeerLinks = createPeerLinkFinder();\n  const options = recipes.map((recipe, i) => {\n    const links = findPeerLinks(recipe);\n    return {\n      id: recipe.id,\n      label: labels[i],\n      linkHint: links.length > 0 ? describePeerLinks(links) : undefined,\n      recipe,\n    };\n  });\n  return peerLinkedLast(options, (o) => o.linkHint !== undefined);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,iBAAiB,QAAmC;CAClE,MAAM,OAAA,GAAMA,gCAAAA,iBAAAA,CAAiB,OAAO,EAAE;CACtC,MAAM,uBAAO,IAAI,IAAe;CAChC,MAAM,MAAmB,CAAC;CAC1B,KAAK,MAAM,OAAA,GAAMC,gCAAAA,wBAAAA,CAAwB,OAAO,SAAS,CAAC,GAAG;EAI3D,MAAM,QAAA,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