{"version":3,"file":"column_discovered_recipe.cjs","names":["distillColumnDiscoveredKey","Column","ColumnRecipe","stringifyColumnDiscoveredId","extractPObjectId","throwError","ColumnOverriddenRecipe","rebrandLeafId"],"sources":["../../../src/columns/column_recipes/column_discovered_recipe.ts"],"sourcesContent":["import {\n  distillColumnDiscoveredKey,\n  extractPObjectId,\n  stringifyColumnDiscoveredId,\n  type AxisQualification,\n  type ColumnDiscoveredId,\n  type ColumnDiscoveredKey,\n  type ColumnUniversalId,\n  type PColumnSpec,\n  type PObjectId,\n  type SpecOverrides,\n  type SpecQuery,\n} from \"@milaboratories/pl-model-common\";\nimport type { GlobalCfgRenderCtx } from \"../../render/internal\";\nimport type { ColumnFieldStatus, ColumnResolutionStatus } from \"./types\";\nimport { ColumnRecipe } from \"./index\";\nimport { ColumnOverriddenRecipe } from \"./column_overrided_recipe\";\nimport { Column } from \"../column\";\nimport { rebrandLeafId } from \"./leaf_rebrand\";\nimport { throwError } from \"@milaboratories/helpers\";\n\n/**\n * Recipe for columns identified by a {@link ColumnDiscoveredKey}: a base\n * column + a `path` of linkers + qualifications.\n *\n * Specifics:\n *  - References more than one column (`column` + each `path[i].column`);\n *    {@link getDataStatus} aggregates across the whole set.\n *  - {@link getQuery} assembles the {@link SpecQuery} locally\n *    ({@link buildSpecQuery}) — the hit is inlined as its own recipe's query\n *    tree, linkers fold inside-out into nested `linkerJoin` nodes.\n *  - {@link getSpec} passes through to the hit column's own spec: the linker\n *    chain only enables co-indexing and does not remap the hit's `axesSpec`, so\n *    no engine round-trip is needed (mirrors the Discovered branch of\n *    `reconstructSpecFromId` on the host side).\n */\nexport class ColumnDiscoveredRecipe implements ColumnRecipe<ColumnDiscoveredId> {\n  /**\n   * Validate the key + resolve every referenced column via\n   * {@link DataColumnRecipe.fromId} (which itself checks the leaf accessor reports\n   * `hasData()`). Returns `undefined` if the key is malformed or any\n   * referenced column is not yet spec-resolvable.\n   *\n   * Spec JSON is deserialized lazily on first {@link getSpec}/{@link getQuery}.\n   */\n  static fromKey(\n    key: ColumnDiscoveredKey,\n    opts: { ctx?: GlobalCfgRenderCtx } = {},\n  ): undefined | ColumnDiscoveredRecipe {\n    const distilled = distillColumnDiscoveredKey(key);\n    const columns: Record<ColumnUniversalId, Column> = {};\n    for (const uniId of referencedUniIdsOf(distilled)) {\n      const recipe = Column(uniId, opts);\n      if (recipe === undefined) return undefined;\n      columns[uniId] = recipe;\n    }\n    return new ColumnDiscoveredRecipe(distilled, columns);\n  }\n\n  /**\n   * Static counterpart to {@link fromKey}: returns the resolution status of\n   * a {@link ColumnDiscoveredKey} without constructing the recipe. Worst-wins\n   * across every referenced {@link ColumnUniversalId} (hit + path linkers),\n   * each resolved via the top-level {@link ColumnRecipe.getStatus} dispatcher.\n   */\n  static getStatusByKey(\n    key: ColumnDiscoveredKey,\n    opts: { ctx?: GlobalCfgRenderCtx } = {},\n  ): ColumnResolutionStatus {\n    const distilled = distillColumnDiscoveredKey(key);\n    let worst: ColumnResolutionStatus = \"present\";\n    for (const uniId of referencedUniIdsOf(distilled)) {\n      const s = ColumnRecipe.getStatus(uniId, opts);\n      if (s === \"absent\") return \"absent\";\n      if (s === \"resolving\") worst = \"resolving\";\n    }\n    return worst;\n  }\n\n  readonly id: ColumnDiscoveredId;\n  private specCache?: { readonly value: PColumnSpec };\n  private queryCache?: { readonly value: SpecQuery };\n  private dataStatusCache?: { readonly value: ColumnFieldStatus };\n\n  private constructor(\n    private readonly key: ColumnDiscoveredKey,\n    private readonly columns: Record<ColumnUniversalId, ColumnRecipe>,\n  ) {\n    this.id = stringifyColumnDiscoveredId(this.key);\n  }\n\n  /**\n   * Universal id of the hit column (excluding path/qualifications on top).\n   * May itself be a wrapped id (Overridden / Filtered / nested Discovered) —\n   * preserves projections applied to the underlying column.\n   */\n  getHitId(): ColumnUniversalId {\n    return this.key.column;\n  }\n\n  /**\n   * Axis qualifications attached to the hit column itself — applied to the\n   * outer-join entry that wraps this column at the consumer boundary.\n   */\n  getColumnQualifications(): readonly AxisQualification[] {\n    return this.key.columnQualifications ?? [];\n  }\n\n  /**\n   * Per-primary-column qualifications applied to the primary anchors on\n   * this group's side. Keyed by the external primary column id.\n   */\n  getQueriesQualifications(): Readonly<Record<PObjectId, AxisQualification[]>> {\n    return this.key.queriesQualifications ?? {};\n  }\n\n  /**\n   * Leaf {@link PObjectId}s the recipe physically depends on: hit column +\n   * each linker in `path`, with any projection wrappers unwrapped down to\n   * their underlying storage column. Used to track real-data dependencies\n   * (e.g. {@link getDataStatus}), not projected identities.\n   */\n  getReferencedIds(): PObjectId[] {\n    return [...new Set([...referencedUniIdsOf(this.key)].map((uniId) => extractPObjectId(uniId)))];\n  }\n\n  /**\n   * Final spec of a discovered hit is just the hit column's own spec: the\n   * linker chain only enables co-indexing, it does not remap the hit's\n   * `axesSpec`, and axis qualifications live on the outer join entry (see\n   * {@link buildSpecQuery}), not in the spec. So pass through to the hit\n   * recipe's `getSpec()` — no engine round-trip needed. This mirrors the\n   * Discovered branch of `reconstructSpecFromId` on the host side.\n   */\n  getSpec(): PColumnSpec {\n    if (this.specCache === undefined) {\n      const hit =\n        this.columns[this.key.column] ??\n        throwError(`ColumnDiscoveredRecipe.getSpec: missing column ${this.key.column}`);\n      this.specCache = { value: hit.getSpec() };\n    }\n    return this.specCache.value;\n  }\n\n  /** IR for building the final spec — see {@link buildSpecQuery}. */\n  getQuery(): SpecQuery {\n    if (this.queryCache === undefined) {\n      this.queryCache = { value: this.buildSpecQuery() };\n    }\n    return this.queryCache.value;\n  }\n\n  getDataStatus(): ColumnFieldStatus {\n    if (this.dataStatusCache === undefined) {\n      this.dataStatusCache = {\n        value: Object.values(this.columns).reduce<ColumnFieldStatus>((worst, lazy) => {\n          const s = lazy.getDataStatus();\n          if (s === \"absent\" || worst === \"absent\") return \"absent\";\n          if (s === \"resolving\") return \"resolving\";\n          return worst;\n        }, \"present\"),\n      };\n    }\n    return this.dataStatusCache.value;\n  }\n\n  /**\n   * Discovered + overrides → Overridden<Discovered>. Delegates to the\n   * flat-merge factory of ColumnOverriddenRecipe; subsequent `withSpecs`\n   * calls merge at the Overridden level (one wrapper, no nesting).\n   */\n  withSpecs(overrides: SpecOverrides): ColumnRecipe {\n    return ColumnOverriddenRecipe.wrap(this, overrides);\n  }\n\n  /**\n   * Assembles the SpecQuery for this discovered hit by folding `key.path`\n   * around the hit column.\n   *\n   * The hit (innermost) is built by inlining `columns[key.column].getQuery()`\n   * — recursing into the hit's own recipe — so wrapping layers on the hit\n   * (Overridden / Filtered / nested Discovered) appear in the produced tree.\n   * The previous `pframeSpec.buildQuery` path was a flat\n   * {@link PObjectId}-only call and could not express that.\n   *\n   * Linkers stay as plain column references on the linker side of\n   * `linkerJoin` (the spec node has no slot for a query-side linker); the\n   * linker's recipe id is used directly. The frame registered in\n   * {@link getSpec} carries each recipe's final spec under that same id, so\n   * the engine resolves linker axes from the post-projection spec.\n   *\n   * Path ordering matches {@link ColumnDiscoveredKey.path}: `path[0]` is\n   * outermost, `path[N-1]` is closest to the hit. We fold from the inside\n   * out — innermost wrap first — so the result lines up with that convention.\n   *\n   * `columnQualifications` / `queriesQualifications` are not emitted here —\n   * qualifications live on a {@link SpecQueryJoinEntry} wrapper (lost on\n   * unwrapping to {@link SpecQuery}). External consumers apply them at the\n   * outer join via {@link getColumnQualifications} / {@link getQueriesQualifications}.\n   */\n  private buildSpecQuery(): SpecQuery {\n    // Preserve the inner hit recipe's full query tree — it may carry\n    // wrappers (specOverride / sliceAxes / nested linkerJoin) that the\n    // host needs to apply correctly. We only rebrand the terminal column\n    // leaf to this.id so two variants of the same physical hit reached via\n    // different linker chains stay distinct columns in the engine output.\n    const hitRecipe =\n      this.columns[this.key.column] ??\n      throwError(`ColumnDiscoveredRecipe.buildSpecQuery: missing column ${this.key.column}`);\n    let query: SpecQuery = rebrandLeafId(hitRecipe.getQuery(), hitRecipe.id, this.id);\n    const path = this.key.path ?? [];\n\n    for (let i = path.length - 1; i >= 0; i--) {\n      const linker =\n        this.columns[path[i].column] ??\n        throwError(\n          `ColumnDiscoveredRecipe.buildSpecQuery: missing linker column ${path[i].column}`,\n        );\n      query = {\n        type: \"linkerJoin\",\n        linker: linker.getQuery(),\n        secondary: [{ entry: query }],\n      };\n    }\n    return query;\n  }\n}\n\nfunction referencedUniIdsOf(key: ColumnDiscoveredKey): Set<ColumnUniversalId> {\n  return new Set<ColumnUniversalId>([key.column, ...(key.path ?? []).map((item) => item.column)]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,yBAAb,MAAa,uBAAmE;CAiD3D;CACA;;;;;;;;;CAzCnB,OAAO,QACL,KACA,OAAqC,CAAC,GACF;EACpC,MAAM,aAAA,GAAYA,gCAAAA,2BAAAA,CAA2B,GAAG;EAChD,MAAM,UAA6C,CAAC;EACpD,KAAK,MAAM,SAAS,mBAAmB,SAAS,GAAG;GACjD,MAAM,SAASC,eAAAA,OAAO,OAAO,IAAI;GACjC,IAAI,WAAW,KAAA,GAAW,OAAO,KAAA;GACjC,QAAQ,SAAS;EACnB;EACA,OAAO,IAAI,uBAAuB,WAAW,OAAO;CACtD;;;;;;;CAQA,OAAO,eACL,KACA,OAAqC,CAAC,GACd;EACxB,MAAM,aAAA,GAAYD,gCAAAA,2BAAAA,CAA2B,GAAG;EAChD,IAAI,QAAgC;EACpC,KAAK,MAAM,SAAS,mBAAmB,SAAS,GAAG;GACjD,MAAM,IAAIE,cAAAA,aAAa,UAAU,OAAO,IAAI;GAC5C,IAAI,MAAM,UAAU,OAAO;GAC3B,IAAI,MAAM,aAAa,QAAQ;EACjC;EACA,OAAO;CACT;CAEA;CACA;CACA;CACA;CAEA,YACE,KACA,SACA;EAFiB,KAAA,MAAA;EACA,KAAA,UAAA;EAEjB,KAAK,MAAA,GAAKC,gCAAAA,4BAAAA,CAA4B,KAAK,GAAG;CAChD;;;;;;CAOA,WAA8B;EAC5B,OAAO,KAAK,IAAI;CAClB;;;;;CAMA,0BAAwD;EACtD,OAAO,KAAK,IAAI,wBAAwB,CAAC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