@murumets-ee/imports 0.0.0-preview-20261014110621

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 (72) hide show
  1. package/LICENSE +94 -0
  2. package/dist/analyze/index.d.mts +265 -0
  3. package/dist/analyze/index.d.mts.map +1 -0
  4. package/dist/analyze/index.mjs +2 -0
  5. package/dist/analyze/index.mjs.map +1 -0
  6. package/dist/carmaker-feed-B-QYr3PI.mjs +2 -0
  7. package/dist/carmaker-feed-B-QYr3PI.mjs.map +1 -0
  8. package/dist/carmaker-feed-CWrZLYUt.d.mts +59 -0
  9. package/dist/carmaker-feed-CWrZLYUt.d.mts.map +1 -0
  10. package/dist/cleanup-DDljBe0Z.mjs +2 -0
  11. package/dist/cleanup-DDljBe0Z.mjs.map +1 -0
  12. package/dist/engine-B0ExE4jL.mjs +2 -0
  13. package/dist/engine-B0ExE4jL.mjs.map +1 -0
  14. package/dist/engine-tkbUXKxB.d.mts +609 -0
  15. package/dist/engine-tkbUXKxB.d.mts.map +1 -0
  16. package/dist/index-Bm69N5DW.d.mts +97 -0
  17. package/dist/index-Bm69N5DW.d.mts.map +1 -0
  18. package/dist/index.d.mts +390 -0
  19. package/dist/index.d.mts.map +1 -0
  20. package/dist/index.mjs +2 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/mapping/index.d.mts +42 -0
  23. package/dist/mapping/index.d.mts.map +1 -0
  24. package/dist/mapping/index.mjs +1 -0
  25. package/dist/mapping-transform-CO4MNhMe.mjs +2 -0
  26. package/dist/mapping-transform-CO4MNhMe.mjs.map +1 -0
  27. package/dist/matching/index.d.mts +2 -0
  28. package/dist/matching/index.mjs +1 -0
  29. package/dist/matching-Sr0z4HvN.mjs +2 -0
  30. package/dist/matching-Sr0z4HvN.mjs.map +1 -0
  31. package/dist/parts-schema-M1AtjNJt.d.mts +61 -0
  32. package/dist/parts-schema-M1AtjNJt.d.mts.map +1 -0
  33. package/dist/parts-schema-QqLci_Pl.mjs +2 -0
  34. package/dist/parts-schema-QqLci_Pl.mjs.map +1 -0
  35. package/dist/plugin.d.mts +148 -0
  36. package/dist/plugin.d.mts.map +1 -0
  37. package/dist/plugin.mjs +2 -0
  38. package/dist/plugin.mjs.map +1 -0
  39. package/dist/publish-DCXIPwTE.mjs +2 -0
  40. package/dist/publish-DCXIPwTE.mjs.map +1 -0
  41. package/dist/read-feed-DsLgRDNR.mjs +2 -0
  42. package/dist/read-feed-DsLgRDNR.mjs.map +1 -0
  43. package/dist/realtime/index.d.mts +123 -0
  44. package/dist/realtime/index.d.mts.map +1 -0
  45. package/dist/realtime/index.mjs +1 -0
  46. package/dist/rolldown-runtime-DK3Fl9T5.mjs +1 -0
  47. package/dist/runner-BnFvID1z.mjs +2 -0
  48. package/dist/runner-BnFvID1z.mjs.map +1 -0
  49. package/dist/schema-registry-DB5aIZMN.mjs +2 -0
  50. package/dist/schema-registry-DB5aIZMN.mjs.map +1 -0
  51. package/dist/storage-resolver.d.mts +32 -0
  52. package/dist/storage-resolver.d.mts.map +1 -0
  53. package/dist/storage-resolver.mjs +2 -0
  54. package/dist/storage-resolver.mjs.map +1 -0
  55. package/dist/storage.d.mts +31 -0
  56. package/dist/storage.d.mts.map +1 -0
  57. package/dist/storage.mjs +2 -0
  58. package/dist/storage.mjs.map +1 -0
  59. package/dist/transform-Cu5YEoOl.mjs +2 -0
  60. package/dist/transform-Cu5YEoOl.mjs.map +1 -0
  61. package/dist/transform-WeiiLdYP.d.mts +246 -0
  62. package/dist/transform-WeiiLdYP.d.mts.map +1 -0
  63. package/dist/transforms.d.mts +2 -0
  64. package/dist/transforms.mjs +1 -0
  65. package/dist/worker-CRH_PjKO.d.mts +940 -0
  66. package/dist/worker-CRH_PjKO.d.mts.map +1 -0
  67. package/dist/worker.d.mts +2 -0
  68. package/dist/worker.mjs +2 -0
  69. package/dist/worker.mjs.map +1 -0
  70. package/dist/xlsx-reader-D9Ntxm29.mjs +2 -0
  71. package/dist/xlsx-reader-D9Ntxm29.mjs.map +1 -0
  72. package/package.json +81 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/mapping/discount-table-schema.ts","../../src/mapping/mapping-transform.ts","../../src/mapping/schema-registry.ts"],"mappings":";;;;;;UAqBiB,gBAAA;EACf,aAAA;EACA,WAAW;AAAA;AAAA,cAQA,mBAAA,EAAqB,YAAY,CAAC,gBAAA;;;;cCClC,sBAAA;;;;ACPb;;cDmCa,gBAAA,EAAkB,YAAY;;;;iBCnC3B,eAAA,CAAgB,IAAA,WAAe,YAAY;AFM3D;AAAA,iBEDgB,iBAAA;;UAKC,mBAAA;EACf,IAAA;EACA,MAAA,WAAiB,WAAW;AAAA;;ADL9B;;;;AAAmC;iBCcnB,qBAAA,IAAyB,mBAAmB"}
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"../parts-schema-QqLci_Pl.mjs";import{a as l,c as u,i as d,n as f,o as p,r as m,s as h,t as g}from"../engine-B0ExE4jL.mjs";import{i as _,n as v,r as y,t as b}from"../schema-registry-DB5aIZMN.mjs";import{n as x,t as S}from"../mapping-transform-CO4MNhMe.mjs";export{p as COLUMN_TRANSFORM_OPS,S as MAPPING_TRANSFORM_NAME,h as applyColumnTransforms,g as buildMappingTransform,u as columnTransformSchema,b as describeTargetSchemas,_ as discountTableSchema,v as getTargetSchema,y as listTargetSchemas,f as mappingColumnSchema,m as mappingConfigSchema,x as mappingTransform,c as normalizeCode,n as numberCell,d as numberFormatSchema,s as parseEuropeanNumber,t as parseNumber,i as partsParamsSchema,o as partsSchema,l as resolveMapping,e as rowError,a as textOrNull,r as toMinorUnits};
@@ -0,0 +1,2 @@
1
+ import{r as e,t}from"./engine-B0ExE4jL.mjs";import{n,r}from"./schema-registry-DB5aIZMN.mjs";import{z as i}from"zod";const a=`commerce:mapping`,o=i.object({mapping:e}),s=new WeakMap;function c(e){let i=s.get(e);if(i)return i;let{mapping:a}=o.parse(e),c=n(a.targetSchema);if(!c)throw Error(`Unknown target schema "${a.targetSchema}" (registered: ${r().join(`, `)})`);let l=t(a,c);return s.set(e,l),l}const l=async(e,t)=>c(t.params)(e,t);export{l as n,a as t};
2
+ //# sourceMappingURL=mapping-transform-CO4MNhMe.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapping-transform-CO4MNhMe.mjs","names":[],"sources":["../src/mapping/mapping-transform.ts"],"sourcesContent":["/**\n * `commerce:mapping` β€” the registered transform for runs driven by a saved\n * `import_mapping` (commerce-demo phase 02; the PR3 wizard enqueues these).\n *\n * The run's `params.mapping` carries a SNAPSHOT of the mapping config, so the run\n * is reproducible (it records the exact mapping used) and the transform stays a\n * pure function of `(row, ctx)` with no per-row DB I/O. This transform compiles\n * the snapshot once per `ctx.params` reference (memoized via a `WeakMap`, the same\n * shape as the carmaker path) and applies it.\n *\n * Output type is `unknown` because the target schema (parts vs discount_table)\n * isn't known until the snapshot is read at runtime. The parts schema additionally\n * reads brand/supplier identity from the SAME `params` object (alongside `mapping`).\n *\n * **Sink caveat.** The `runImport` runner bulk-writes whatever doc this produces\n * into the ES `parts` index. That's correct for a `parts` mapping but WRONG for a\n * `discount_table` mapping β€” its rows belong in Postgres (`supplier_discount_group`),\n * not ES. PR2 ships the discount_table SCHEMA (so the engine parses it) but no sink;\n * a `discount_table` run must NOT be enqueued through the parts-ES `runImport` path.\n * PR4 wires the Postgres sink + the route that enqueues discount runs.\n *\n * PR2 shipped + tested this transform; the wizard that creates the mappings +\n * sets `params.feed` for the reader landed in PR3. Registration is plugin-owned:\n * the `imports()` plugin registers this transform at its own init.\n */\n\nimport { z } from 'zod'\nimport type { RowTransform } from '../transform.js'\nimport { buildMappingTransform, mappingConfigSchema } from './engine.js'\nimport { getTargetSchema, listTargetSchemas } from './schema-registry.js'\n\n/** Stable name under which the mapping-driven transform is registered. */\nexport const MAPPING_TRANSFORM_NAME = 'commerce:mapping'\n\n/** The mapping snapshot lives under `params.mapping`; other params flow to the schema. */\nconst mappingParamsSchema = z.object({ mapping: mappingConfigSchema })\n\n/** Compiled-transform cache, keyed on the `ctx.params` object identity (per run). */\nconst compiledCache = new WeakMap<object, RowTransform<unknown>>()\n\nfunction compile(params: Record<string, unknown>): RowTransform<unknown> {\n const cached = compiledCache.get(params)\n if (cached) return cached\n const { mapping } = mappingParamsSchema.parse(params)\n const schema = getTargetSchema(mapping.targetSchema)\n if (!schema) {\n throw new Error(\n `Unknown target schema \"${mapping.targetSchema}\" (registered: ${listTargetSchemas().join(', ')})`,\n )\n }\n const transform = buildMappingTransform(mapping, schema)\n compiledCache.set(params, transform)\n return transform\n}\n\n/**\n * The registered transform. Resolves + compiles the mapping snapshot from\n * `ctx.params` (memoized), then delegates each row to it. A malformed snapshot or\n * unknown schema throws β€” surfaced by the runner as a row-level `transform_threw`.\n */\nexport const mappingTransform: RowTransform<unknown> = async (row, ctx) => {\n const transform = compile(ctx.params)\n return transform(row, ctx)\n}\n"],"mappings":"oHAgCA,MAAa,EAAyB,mBAGhC,EAAsB,EAAE,OAAO,CAAE,QAAS,CAAoB,CAAC,EAG/D,EAAgB,IAAI,QAE1B,SAAS,EAAQ,EAAwD,CACvE,IAAM,EAAS,EAAc,IAAI,CAAM,EACvC,GAAI,EAAQ,OAAO,EACnB,GAAM,CAAE,WAAY,EAAoB,MAAM,CAAM,EAC9C,EAAS,EAAgB,EAAQ,YAAY,EACnD,GAAI,CAAC,EACH,MAAU,MACR,0BAA0B,EAAQ,aAAa,iBAAiB,EAAkB,CAAC,CAAC,KAAK,IAAI,EAAE,EACjG,EAEF,IAAM,EAAY,EAAsB,EAAS,CAAM,EAEvD,OADA,EAAc,IAAI,EAAQ,CAAS,EAC5B,CACT,CAOA,MAAa,EAA0C,MAAO,EAAK,IAC/C,EAAQ,EAAI,MACf,CAAC,CAAC,EAAK,CAAG"}
@@ -0,0 +1,2 @@
1
+ import { a as SNAPSHOT_MAX_ROWS, c as AutoAssignField, i as SNAPSHOT_MAX_COLUMN_CHARS, l as suggestTargets, n as SNAPSHOT_MAX_CELL_CHARS, o as SNAPSHOT_MAX_SERIALIZED_CHARS, r as SNAPSHOT_MAX_COLUMNS, s as toHeaderSnapshot, t as HeaderSample, u as tokenizeHeader } from "../index-Bm69N5DW.mjs";
2
+ export { type AutoAssignField, type HeaderSample, SNAPSHOT_MAX_CELL_CHARS, SNAPSHOT_MAX_COLUMNS, SNAPSHOT_MAX_COLUMN_CHARS, SNAPSHOT_MAX_ROWS, SNAPSHOT_MAX_SERIALIZED_CHARS, suggestTargets, toHeaderSnapshot, tokenizeHeader };
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"../matching-Sr0z4HvN.mjs";export{s as SNAPSHOT_MAX_CELL_CHARS,r as SNAPSHOT_MAX_COLUMNS,a as SNAPSHOT_MAX_COLUMN_CHARS,n as SNAPSHOT_MAX_ROWS,e as SNAPSHOT_MAX_SERIALIZED_CHARS,o as suggestTargets,i as toHeaderSnapshot,t as tokenizeHeader};
@@ -0,0 +1,2 @@
1
+ function e(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function t(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase().split(/[^a-z0-9]+/).filter(e=>e!==``).slice(0,12)}function n(e){let t=[];for(let n=0;n<e.length;n++){let r=``;for(let i=n;i<e.length;i++)r+=e[i]??``,t.push(r)}return t}function r(r,i){let a=i.map(t=>{let n=new Set([e(t.key),e(t.label)]);for(let r of t.aliases??[])n.add(e(r));return n.delete(``),n}),o=[];r.forEach((r,i)=>{let s=e(r);if(s===``)return;let c=new Set(n(t(r)));a.forEach((e,t)=>{let n=0;for(let t of e)s===t?n=Math.max(n,1e3+t.length):c.has(t)&&(n=Math.max(n,t.length));n>0&&o.push({columnIndex:i,fieldIndex:t,score:n})})}),o.sort((e,t)=>t.score-e.score||e.fieldIndex-t.fieldIndex||e.columnIndex-t.columnIndex);let s=new Map,c=new Set,l=new Set;for(let e of o){if(c.has(e.columnIndex)||l.has(e.fieldIndex))continue;let t=r[e.columnIndex],n=i[e.fieldIndex];t===void 0||n===void 0||(c.add(e.columnIndex),l.add(e.fieldIndex),s.set(t,n.key))}return s}const i=256,a=256,o=5,s=500,c=1e5;function l(e){let t=e.columns.filter(e=>e.length>0);if(t.length===0||t.length>256||t.some(e=>e.length>256))return null;let n={columns:t,rows:e.rows.slice(0,5).map(e=>{let t={};for(let[n,r]of Object.entries(e))n.length!==0&&(t[n]=u(r));return t})};return JSON.stringify(n).length>1e5?null:n}function u(e){if(e.length<=500)return e;let t=e.slice(0,500),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}export{c as a,t as c,o as i,i as n,l as o,a as r,r as s,s as t};
2
+ //# sourceMappingURL=matching-Sr0z4HvN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matching-Sr0z4HvN.mjs","names":[],"sources":["../src/matching/auto-assign.ts","../src/matching/header-snapshot.ts"],"sourcesContent":["/**\n * Auto-assignment of a previewed feed's columns to target fields β€” the wizard's first guess\n * when an operator uploads a sample file.\n *\n * Kept pure (no React, no server imports) so the matching rules are unit-testable against real\n * supplier headers instead of only being visible by driving the UI.\n *\n * ## Why this is not a substring match\n *\n * The previous rule accepted a match when either string contained the other, which is wrong in\n * both directions at once. It fired where it should not β€” `Barcode` contains `code`, so the\n * barcode column was offered as the REQUIRED part-code field while the actual code column\n * (`ArticleName`, `partno`) matched nothing β€” and it stayed silent where it mattered, because\n * no real feed names a column after our internal key. Measured against the three ground-truth\n * supplier samples, it assigned two columns correctly, one wrongly, and missed the rest,\n * including every supersession column. A missed price column is loud; a missed supersession\n * column is silent (prices import, the run succeeds, the replacement tables stay empty), which\n * is how the supersession feature shipped switched-off and stayed that way.\n *\n * ## The rules\n *\n * 1. A field's candidate spellings are its `key`, its `label`, and its declared `aliases`, each\n * reduced to lowercase alphanumerics.\n * 2. A column matches a candidate only on a TOKEN BOUNDARY β€” the header is split on\n * punctuation, whitespace and camelCase humps, and a candidate must equal a contiguous run\n * of those tokens. So `Net Price EUR` and `NetPrice/Discount` still reach `net_price`, while\n * `Barcode` can no longer reach `code`, because `code` is not one of its tokens.\n * 3. Every (column, field) match competes globally and the strongest wins: a whole-header hit\n * beats a partial one, and a longer candidate beats a shorter one. Assignment is greedy over\n * that order, so `Description1` claims `description1` even when a plain `Description` column\n * sits earlier in the file.\n * 4. One target is used at most once. Two columns claiming the same field would be rejected by\n * the mapping validator at save time, so the weaker claimant is left unassigned for the\n * operator to resolve rather than silently producing an unsaveable mapping.\n */\n\n/** The subset of a target field this matcher reads. */\nexport interface AutoAssignField {\n key: string\n label: string\n aliases?: readonly string[] | undefined\n}\n\n/** Lowercase alphanumerics β€” the comparison form for both headers and candidates. */\nfunction normalize(s: string): string {\n return s.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\n/**\n * Tokens considered per header. Matching enumerates every contiguous run of tokens, which is\n * quadratic in their count AND in their total length, so this cap is load-bearing rather than\n * tidy: a mis-detected delimiter collapses an entire line β€” sometimes an entire file β€” into ONE\n * \"column\", and this runs in the operator's browser the moment a preview returns. Measured\n * uncapped: 500 tokens β†’ 207 MB of run strings and 0.6s; 1,000 β†’ 1.7 GB and 5.4s; 2,000 β†’ 14 GB\n * and 40s, all retained in a Set. The wizard has a dedicated banner for exactly that mistake\n * (`delimiterSuggestion`), but auto-assign runs before it can paint. No real column header is\n * a dozen words long, so capping costs nothing and bounds the work at ~78 runs per column.\n */\nconst MAX_HEADER_TOKENS = 12\n\n/**\n * Split a header into comparison tokens: on punctuation/whitespace, and on camelCase humps so\n * `ArticleName` β†’ `article` + `name` and `CurrencyCd` β†’ `currency` + `cd`. Truncated to\n * {@link MAX_HEADER_TOKENS}.\n *\n * **Acronym boundaries are deliberately NOT split.** Adding `([A-Z]+)([A-Z][a-z])` looks like a\n * free improvement β€” it makes `EANCode` read as `ean` + `code` β€” and it re-opens this module's\n * founding bug: the standalone `code` token then outscores `barcode`'s `ean` alias (4 vs 3), so\n * the BARCODE column gets offered as the required part-code field, silently, exactly as the old\n * substring matcher did. It generalises to any `<Acronym>Code` header, which no alias list can\n * enumerate. Compound spellings that matter are handled as whole-header aliases instead, which\n * beat any partial run.\n */\nexport function tokenizeHeader(header: string): string[] {\n return header\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t !== '')\n .slice(0, MAX_HEADER_TOKENS)\n}\n\n/** Every contiguous run of tokens, joined β€” the strings a candidate may equal. */\nfunction tokenRuns(tokens: readonly string[]): string[] {\n const runs: string[] = []\n for (let start = 0; start < tokens.length; start++) {\n let joined = ''\n for (let end = start; end < tokens.length; end++) {\n joined += tokens[end] ?? ''\n runs.push(joined)\n }\n }\n return runs\n}\n\ninterface Candidate {\n columnIndex: number\n fieldIndex: number\n /** Whole-header hits outrank partial ones; longer candidates outrank shorter ones. */\n score: number\n}\n\n/**\n * Suggest a target field for each column. Returns `column β†’ target key`, omitting any column\n * with no confident match β€” an absent entry means \"the operator decides\", never \"no mapping\n * needed\".\n */\nexport function suggestTargets(\n columns: readonly string[],\n fields: readonly AutoAssignField[],\n): Map<string, string> {\n const candidatesByField = fields.map((f) => {\n const spellings = new Set<string>([normalize(f.key), normalize(f.label)])\n for (const alias of f.aliases ?? []) spellings.add(normalize(alias))\n spellings.delete('')\n return spellings\n })\n\n const matches: Candidate[] = []\n columns.forEach((column, columnIndex) => {\n const full = normalize(column)\n if (full === '') return\n const runs = new Set(tokenRuns(tokenizeHeader(column)))\n candidatesByField.forEach((spellings, fieldIndex) => {\n let best = 0\n for (const spelling of spellings) {\n // A whole-header hit is worth more than a run hit of the same length, so a column\n // named exactly `code` beats one that merely contains the token.\n if (full === spelling) best = Math.max(best, 1000 + spelling.length)\n else if (runs.has(spelling)) best = Math.max(best, spelling.length)\n }\n if (best > 0) matches.push({ columnIndex, fieldIndex, score: best })\n })\n })\n\n // Strongest first; ties resolved by declaration order then file order so the result is\n // independent of Set/array iteration incidentals.\n matches.sort(\n (a, b) => b.score - a.score || a.fieldIndex - b.fieldIndex || a.columnIndex - b.columnIndex,\n )\n\n const assigned = new Map<string, string>()\n const takenColumns = new Set<number>()\n const takenFields = new Set<number>()\n for (const m of matches) {\n if (takenColumns.has(m.columnIndex) || takenFields.has(m.fieldIndex)) continue\n const column = columns[m.columnIndex]\n const field = fields[m.fieldIndex]\n if (column === undefined || field === undefined) continue\n takenColumns.add(m.columnIndex)\n takenFields.add(m.fieldIndex)\n assigned.set(column, field.key)\n }\n return assigned\n}\n","/**\n * The parsed-sample shape this builder consumes and emits β€” structurally identical to\n * `FeedPreview` from `preview-feed.ts` and to the wizard's `FeedPreviewResponse`, and\n * declared HERE rather than imported from either so this module keeps zero dependencies.\n * That is what lets one implementation serve the browser wizard and the `lumi` CLI: an\n * import of `preview-feed.js` would pull `csv-parse` and the xlsx reader toward a client\n * bundle, and an import of the wizard's types would point the dependency the wrong way.\n */\nexport interface HeaderSample {\n /** Source column names, in first-seen order. */\n columns: string[]\n /** Sample data rows, each `{ column -> cell }`. */\n rows: Array<Record<string, string>>\n}\n\n// Snapshot caps β€” mirror `../entities/import-mapping-validation.ts`'s\n// `headerSnapshotSchema` + `HEADER_SNAPSHOT_MAX_CHARS` ceiling, so a snapshot this\n// builder emits always passes the server's save validation.\n//\n// Still deliberately duplicated rather than imported, and the reason has changed with\n// the module's address: it is no longer \"don't drag server code into the browser\" (this\n// file now lives in the server package), it is that `import-mapping-validation.ts` pulls\n// zod and the schema registry, which would end this subpath's zero-dependency property β€”\n// the one thing that lets the wizard and the CLI share ONE matcher. The contract is\n// pinned the way it always was, by the round-trip test in `header-snapshot.test.ts`\n// feeding this builder's output through the real `assertValidMapping`.\nexport const SNAPSHOT_MAX_COLUMNS = 256\nexport const SNAPSHOT_MAX_COLUMN_CHARS = 256\nexport const SNAPSHOT_MAX_ROWS = 5\nexport const SNAPSHOT_MAX_CELL_CHARS = 500\nexport const SNAPSHOT_MAX_SERIALIZED_CHARS = 100_000\n\n/**\n * Build the file-less-edit `headerSnapshot` (#667) from the current preview.\n * Rows are capped + cells truncated (they're display samples, not data); a\n * preview that can't fit the caps at all (pathological column count / column\n * names) returns `null` β€” the mapping saves fine, it just won't support\n * file-less editing.\n *\n * Pure module (no React, no 'use client') so the caps mirror is unit-testable\n * without page infrastructure β€” same shape as `find-saved-mapping.ts`.\n */\nexport function toHeaderSnapshot(preview: HeaderSample): HeaderSample | null {\n // Drop blank-named columns rather than rejecting the snapshot: csv-parse\n // treats '' as a valid column name, so a header with a trailing delimiter or\n // blank middle cell (`code,price,`) reaches here from perfectly ordinary\n // feeds β€” while the server schema (rightly) refuses empty names. A blank\n // column is unmappable anyway (columnMap sources require min-1 names).\n const columns = preview.columns.filter((c) => c.length > 0)\n if (\n columns.length === 0 ||\n columns.length > SNAPSHOT_MAX_COLUMNS ||\n columns.some((c) => c.length > SNAPSHOT_MAX_COLUMN_CHARS)\n ) {\n return null\n }\n const snapshot: HeaderSample = {\n columns,\n rows: preview.rows.slice(0, SNAPSHOT_MAX_ROWS).map((row) => {\n const out: Record<string, string> = {}\n for (const [col, cell] of Object.entries(row)) {\n if (col.length === 0) continue // cell of a dropped blank column\n out[col] = truncateCell(cell)\n }\n return out\n }),\n }\n // Mirror the server's serialized ceiling too β€” without this, a wide feed\n // with long sample cells (~40+ columns Γ— 500-char cells) passes the per-axis\n // caps here but hard-fails the SAVE server-side with an error the operator\n // can't act on. Over the ceiling β†’ no file-less support, save proceeds.\n if (JSON.stringify(snapshot).length > SNAPSHOT_MAX_SERIALIZED_CHARS) return null\n return snapshot\n}\n\n/**\n * Truncate a sample cell to the cap WITHOUT splitting a surrogate pair: a\n * `.slice()` cut through an astral character (emoji in a product name) leaves\n * a trailing lone high surrogate, which zod accepts but Postgres rejects as\n * jsonb input β€” the save would die at the DB layer instead of degrading.\n */\nfunction truncateCell(cell: string): string {\n if (cell.length <= SNAPSHOT_MAX_CELL_CHARS) return cell\n const cut = cell.slice(0, SNAPSHOT_MAX_CELL_CHARS)\n const last = cut.charCodeAt(cut.length - 1)\n const endsWithLoneHighSurrogate = last >= 0xd800 && last <= 0xdbff\n return endsWithLoneHighSurrogate ? cut.slice(0, -1) : cut\n}\n"],"mappings":"AA4CA,SAAS,EAAU,EAAmB,CACpC,OAAO,EAAE,YAAY,CAAC,CAAC,QAAQ,aAAc,EAAE,CACjD,CA2BA,SAAgB,EAAe,EAA0B,CACvD,OAAO,EACJ,QAAQ,qBAAsB,OAAO,CAAC,CACtC,YAAY,CAAC,CACb,MAAM,YAAY,CAAC,CACnB,OAAQ,GAAM,IAAM,EAAE,CAAC,CACvB,MAAM,EAAG,EAAiB,CAC/B,CAGA,SAAS,EAAU,EAAqC,CACtD,IAAM,EAAiB,CAAC,EACxB,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,IAAS,CAClD,IAAI,EAAS,GACb,IAAK,IAAI,EAAM,EAAO,EAAM,EAAO,OAAQ,IACzC,GAAU,EAAO,IAAQ,GACzB,EAAK,KAAK,CAAM,CAEpB,CACA,OAAO,CACT,CAcA,SAAgB,EACd,EACA,EACqB,CACrB,IAAM,EAAoB,EAAO,IAAK,GAAM,CAC1C,IAAM,EAAY,IAAI,IAAY,CAAC,EAAU,EAAE,GAAG,EAAG,EAAU,EAAE,KAAK,CAAC,CAAC,EACxE,IAAK,IAAM,KAAS,EAAE,SAAW,CAAC,EAAG,EAAU,IAAI,EAAU,CAAK,CAAC,EAEnE,OADA,EAAU,OAAO,EAAE,EACZ,CACT,CAAC,EAEK,EAAuB,CAAC,EAC9B,EAAQ,SAAS,EAAQ,IAAgB,CACvC,IAAM,EAAO,EAAU,CAAM,EAC7B,GAAI,IAAS,GAAI,OACjB,IAAM,EAAO,IAAI,IAAI,EAAU,EAAe,CAAM,CAAC,CAAC,EACtD,EAAkB,SAAS,EAAW,IAAe,CACnD,IAAI,EAAO,EACX,IAAK,IAAM,KAAY,EAGjB,IAAS,EAAU,EAAO,KAA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,OAAA,IAA+C,KACrE,CACT,CAQA,SAAS,EAAa,EAAsB,CAC1C,GAAI,EAAK,QAAA,IAAmC,OAAO,EACnD,IAAM,EAAM,EAAK,MAAM,EAAA,GAA0B,EAC3C,EAAO,EAAI,WAAW,EAAI,OAAS,CAAC,EAE1C,OADkC,GAAQ,OAAU,GAAQ,MACzB,EAAI,MAAM,EAAG,EAAE,EAAI,CACxD"}
@@ -0,0 +1,61 @@
1
+ import { p as TargetSchema } from "./engine-tkbUXKxB.mjs";
2
+ import { z } from "zod";
3
+ import { PartsDocument } from "@murumets-ee/search-elasticsearch";
4
+
5
+ //#region src/mapping/parts-schema.d.ts
6
+ /**
7
+ * Params the `parts` schema reads from the run β€” the per-(supplier, brand)
8
+ * identity resolved at enqueue time. Identical to the carmaker transform's params
9
+ * (the carmaker path re-exports this), so brand/supplier injection + the optional
10
+ * supplier code-prefix strip are validated the same way everywhere.
11
+ */
12
+ declare const partsParamsSchema: z.ZodObject<{
13
+ brandId: z.ZodString;
14
+ brandSlug: z.ZodString;
15
+ supplierId: z.ZodString;
16
+ supplierDisplayName: z.ZodString;
17
+ importBatchId: z.ZodString; /** Supplier code prefix to strip before normalization (e.g. `'ME-'`). Optional. */
18
+ supplierCodePrefix: z.ZodOptional<z.ZodString>;
19
+ /**
20
+ * Purchase-discount map for this supplier (commerce-demo PR4, phase 03 Β§2):
21
+ * `{ groupCode β†’ discountPct }`, resolved from `supplier_discount_group` at
22
+ * enqueue time and snapshotted onto the run so `buildRow` stays a pure function
23
+ * (no per-row DB I/O; `@murumets-ee/imports` stays a leaf). Absent for direct-net
24
+ * suppliers + the carmaker path. Percentages are 0–100 (the entity constrains them).
25
+ */
26
+ discountGroups: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
27
+ }, "strip", z.ZodTypeAny, {
28
+ brandSlug: string;
29
+ supplierDisplayName: string;
30
+ brandId: string;
31
+ supplierId: string;
32
+ importBatchId: string;
33
+ supplierCodePrefix?: string | undefined;
34
+ discountGroups?: Record<string, number> | undefined;
35
+ }, {
36
+ brandSlug: string;
37
+ supplierDisplayName: string;
38
+ brandId: string;
39
+ supplierId: string;
40
+ importBatchId: string;
41
+ supplierCodePrefix?: string | undefined;
42
+ discountGroups?: Record<string, number> | undefined;
43
+ }>;
44
+ type PartsParams = z.infer<typeof partsParamsSchema>;
45
+ /**
46
+ * Uppercase + dash/whitespace-stripped (D2). `*`/other chars are preserved (e.g. `*S`
47
+ * markers). EXPORTED so downstream consumers that key off `code_normalized` β€” the
48
+ * replacement editor (commerce-demo PR6), which normalizes admin-typed codes before
49
+ * matching members β€” use the IDENTICAL rule (R05 Q7: normalization must match across
50
+ * every code source or merge-on-collision silently fails to collide).
51
+ */
52
+ declare function normalizeCode(s: string): string;
53
+ /**
54
+ * The `parts` schema. `buildRow` THROWS on invalid run params (so a misconfigured
55
+ * run surfaces as a transform error, matching the carmaker contract) and returns a
56
+ * typed `RowResult` per row otherwise.
57
+ */
58
+ declare const partsSchema: TargetSchema<PartsDocument>;
59
+ //#endregion
60
+ export { partsSchema as i, normalizeCode as n, partsParamsSchema as r, PartsParams as t };
61
+ //# sourceMappingURL=parts-schema-M1AtjNJt.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parts-schema-M1AtjNJt.d.mts","names":[],"sources":["../src/mapping/parts-schema.ts"],"mappings":";;;;;;;;;;;cAmDa,iBAAA,EAAiB,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAqBlB,WAAA,GAAc,CAAA,CAAE,KAAK,QAAQ,iBAAA;;;;;AAAzC;;;iBAsMgB,aAAA,CAAc,CAAS;;;;;AAtMmB;cA6R7C,WAAA,EAAa,YAAY,CAAC,aAAA"}
@@ -0,0 +1,2 @@
1
+ import{z as e}from"zod";const t=/^-?\d+(\.\d+)?$/;function n(e,n){let r=e.trim();if(r===``||r.toUpperCase()===`NA`)return null;let{decimal:i,thousands:a}=n,o=r;if(a!==``&&(o=o.split(a).join(``)),i===`,`){if(o.includes(`.`))return NaN;o=o.split(`,`).join(`.`)}else if(o.includes(`,`))return NaN;return t.test(o)?Number.parseFloat(o):NaN}function r(e){return Math.round(e*100)}function i(e){let n=e.trim();if(n===``||n.toUpperCase()===`NA`)return null;let r=n.includes(`,`),i=n.includes(`.`),a;if(r&&i)a=n.replace(/\./g,``).replace(`,`,`.`);else if(r)a=n.replace(`,`,`.`);else if(i)return NaN;else a=n;return t.test(a)?Number.parseFloat(a):NaN}function a(e){if(typeof e!=`string`)return null;let t=e.trim();return t===``?null:t}function o(e){return e==null?{kind:`absent`}:typeof e==`number`?Number.isNaN(e)?{kind:`invalid`}:{kind:`value`,value:e}:e.trim()===``?{kind:`absent`}:{kind:`invalid`}}function s(e,t,n){return{kind:`error`,error:{errorType:e,message:t,field:n}}}const c=e.object({brandId:e.string().uuid(),brandSlug:e.string().min(1).max(64),supplierId:e.string().uuid(),supplierDisplayName:e.string().min(1).max(255),importBatchId:e.string().uuid(),supplierCodePrefix:e.string().max(8).regex(/^[A-Z0-9-]+$/,`must be uppercase alphanumeric or "-"`).optional(),discountGroups:e.record(e.string(),e.number().min(0).max(100)).optional()}),l=new WeakMap;function u(e){let t=l.get(e);if(t)return t;let n=c.parse(e);return l.set(e,n),n}const d=[`de`,`en`,`es`,`fr`,`it`,`nl`,`pt`,`ro`],f=e=>`name_${e}`,p=[{key:`code`,label:`Code`,required:!0,type:`string`,aliases:[`part no`,`part number`,`article name`,`article no`,`article number`,`sku`,`varuosa kood`,`kood`,`artikelnummer`,`artikel nr`]},{key:`net_price`,label:`Net price`,required:!1,type:`number`,aliases:[`price`,`net price discount`,`nettopreis`,`netto`]},{key:`gross_price`,label:`Gross price`,required:!1,type:`number`,aliases:[`bruttopreis`,`brutto`]},{key:`list_price`,label:`List price`,required:!1,type:`number`,aliases:[`retail price`,`rrp`,`jaehind`,`jaehind km ta`,`listenpreis`]},{key:`currency`,label:`Currency`,required:!1,type:`string`,aliases:[`currency cd`,`currency code`,`valuuta`]},{key:`barcode`,label:`Barcode`,required:!1,type:`string`,aliases:[`ean`,`ean code`,`gtin`,`gtin code`,`triipkood`]},{key:`description1`,label:`Description 1`,required:!1,type:`string`,aliases:[`description`,`kirjeldus`,`beschreibung`]},{key:`description2`,label:`Description 2`,required:!1,type:`string`},{key:`discount_group`,label:`Discount group`,required:!1,type:`string`,aliases:[`product group`,`tootegrupp`,`rabattgruppe`]},{key:`superseding_code`,label:`Replaced by (newer code)`,required:!1,type:`string`,aliases:[`replaced by`,`successor`,`successor code`,`new code`,`ersetzt durch`,`wird ersetzt durch`,`nachfolgenummer`,`vervangen door`]},{key:`replaces_code`,label:`Replaces (older code)`,required:!1,type:`string`,aliases:[`replaces`,`supersedes`,`old code`,`previous code`,`predecessor`,`vorgaengernummer`]},{key:`core_charge`,label:`Core charge`,required:!1,type:`number`,aliases:[`surcharge`,`deposit`,`core deposit`,`korpusetasu`,`pfand`]},...d.map(e=>({key:f(e),label:`Name (${e})`,required:!1,type:`string`,aliases:[`description ${e}`,`name ${e}`]}))],m=/[\s-]/g;function h(e){return e.toUpperCase().replace(m,``)}function g(e,t){let n=a(e);if(n===null)return null;let r=h(t&&n.startsWith(t)?n.slice(t.length):n);return r===``?null:r}function _(e,t){return Math.round(e*(1-t/100))}function v(e){return e===null?{core_charge_minor:null,core_charge_currency:null,core_charge_refundable:null,core_charge_tax_class:null,core_charge_tax_inclusive:null}:{core_charge_minor:e,core_charge_currency:`EUR`,core_charge_refundable:!0,core_charge_tax_class:null,core_charge_tax_inclusive:!1}}const y={name:`parts`,fields:p,buildRow(e,t){let n=u(t.params),i=typeof e.code==`string`?e.code.trim():``;if(!i)return s(`missing_code`,`code is empty`,`code`);let c=h(n.supplierCodePrefix&&i.startsWith(n.supplierCodePrefix)?i.slice(n.supplierCodePrefix.length):i);if(!c)return s(`empty_normalized_code`,`Code "${i}" is empty after normalization`,`code`);let l=a(e.currency)??`EUR`;if(l!==`EUR`)return s(`unsupported_currency`,`Currency "${l}" not supported (EUR-only)`,`currency`);if(c.endsWith(`*S`)){let t=c.slice(0,-2);if(!t)return s(`core_charge_no_parent`,`Core-fee row "${i}" has no part code before the "*S" marker`,`code`);let a=o(e.net_price);if(a.kind===`invalid`)return s(`invalid_core_charge`,`core-fee (*S) row net_price is not a number`,`net_price`);if(a.kind===`absent`)return s(`missing_core_charge`,`core-fee (*S) row has no net_price to use as the deposit`,`net_price`);let l=r(a.value);return l<=0?{kind:`skip`,reason:`core_fee_zero`}:{kind:`skip`,reason:`core_charge_marker`,patches:[{id:`${t}__${n.supplierId}`,doc:v(l),orphanWarning:{warningType:`orphan_core_charge`,message:`core-fee (*S) row references a part not present in this import`,field:`code`}}]}}let d=o(e.net_price);if(d.kind===`invalid`)return s(`invalid_net_price`,`net_price is not a number`,`net_price`);let f=o(e.gross_price);if(f.kind===`invalid`)return s(`invalid_gross_price`,`gross_price is not a number`,`gross_price`);let p=o(e.list_price);if(p.kind===`invalid`)return s(`invalid_list_price`,`list_price is not a number`,`list_price`);let m=d.kind===`value`?d.value:null,y=p.kind===`value`?p.value:null,b=m??y;if(b===null)return s(`missing_price`,`no net_price or list_price provided`,`price`);let x=a(e.discount_group),S=y===null?null:r(y),C=null,w=[];if(m!==null)C=r(m);else if(S!==null){let e=x===null?void 0:n.discountGroups?.[x];e===void 0?w.push({warningType:`no_purchase_price`,message:x===null?`list price present but no discount group on the row β€” cost pending`:`no discount group "${x}" configured for this supplier β€” cost pending`,field:`discount_group`}):C=_(S,e)}let T=[],E=g(e.superseding_code,n.supplierCodePrefix);E!==null&&E!==c&&T.push({from:c,to:E});let D=g(e.replaces_code,n.supplierCodePrefix);D!==null&&D!==c&&T.push({from:D,to:c});let O=o(e.core_charge);if(O.kind===`invalid`)return s(`invalid_core_charge`,`core_charge is not a number`,`core_charge`);let k=O.kind===`value`?r(O.value):null,A=k!==null&&k>0?k:null,j=`${c}__${n.supplierId}`;return{kind:`success`,id:j,doc:{doc_id:j,code:i,code_normalized:c,brand_id:n.brandId,brand_slug:n.brandSlug,supplier_id:n.supplierId,supplier_display_name:n.supplierDisplayName,net_price_eur:b,gross_price_eur:f.kind===`value`?f.value:null,currency:`EUR`,barcode:a(e.barcode),name_de:a(e.name_de),name_en:a(e.name_en),name_es:a(e.name_es),name_fr:a(e.name_fr),name_it:a(e.name_it),name_nl:a(e.name_nl),name_pt:a(e.name_pt),name_ro:a(e.name_ro),description1:a(e.description1),description2:a(e.description2),list_price_minor:S,discount_group:x,superseding_code:a(e.superseding_code),purchase_price_minor:C,...v(A),import_batch_id:n.importBatchId,imported_at:new Date().toISOString()},...w.length>0&&{warnings:w},...T.length>0&&{pairs:T},...C!==null&&{priceSample:C}}}};export{s as a,n as c,o as i,r as l,c as n,a as o,y as r,i as s,h as t};
2
+ //# sourceMappingURL=parts-schema-QqLci_Pl.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parts-schema-QqLci_Pl.mjs","names":[],"sources":["../src/mapping/number-format.ts","../src/mapping/target-schema.ts","../src/mapping/parts-schema.ts"],"sourcesContent":["/**\n * Number parsing for the configurable mapping engine (commerce-demo phase 02).\n *\n * Real supplier feeds (R03) disagree on decimal AND thousands separators:\n * `55.02` (dot decimal), `326,88` (comma decimal), `1.234,56` (EU\n * thousands+decimal), `1,234.56` (US), `1 234,56` (space-grouped). The mapping\n * stores an explicit `{ decimal, thousands }` per profile so there is no guessing\n * β€” `parseNumber` trusts the configured format.\n *\n * Two parsers live here:\n * - `parseNumber(raw, format)` β€” the format-driven parser used by the generic\n * `number` per-column transform.\n * - `parseEuropeanNumber(raw)` β€” the carmaker-feed legacy parser (comma decimal,\n * dot thousands, **bare-dot rejected as ambiguous**). Carries the carmaker feed's\n * documented format with two intentional broadenings vs the old inline parser:\n * it trims surrounding whitespace, and returns `null` (not `NaN`) for an empty /\n * `'NA'` cell so both number ops share absent-vs-malformed semantics. The\n * carmaker doc-shape suite (27 tests) is the regression net.\n */\n\n/** Separator config for {@link parseNumber}. Stored per `import_mapping`. */\nexport interface NumberFormat {\n /** Decimal separator. */\n decimal: '.' | ','\n /** Thousands grouping separator. `''` = none. */\n thousands: '' | '.' | ',' | ' '\n}\n\n/** Post-cleanup numeric form: optional sign, digits, optional single decimal. */\nconst STRICT_NUMBER_RE = /^-?\\d+(\\.\\d+)?$/\n\n/**\n * Parse a feed cell into a number using an EXPLICIT `{ decimal, thousands }`\n * format. No ambiguity: thousands separators are stripped, the decimal separator\n * is normalised to `.`, and the result is strict-validated.\n *\n * Returns:\n * - `null` for an empty / `'NA'` cell (a legitimately-absent value β€” the caller\n * decides whether that's allowed for a given target field).\n * - `NaN` for a non-empty but unparseable cell (malformed β€” the caller surfaces\n * a row-level error rather than coercing to 0).\n * - the parsed number otherwise.\n *\n * A character that is neither a digit, the configured decimal, the configured\n * thousands separator, nor a leading `-` makes the cell unparseable (`NaN`) β€”\n * e.g. a literal `.` when the format's decimal is `,` and thousands is not `.`.\n */\nexport function parseNumber(raw: string, format: NumberFormat): number | null {\n const trimmed = raw.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n\n const { decimal, thousands } = format\n let s = trimmed\n // 1. Remove every thousands separator (when one is configured).\n if (thousands !== '') s = s.split(thousands).join('')\n\n // 2. Normalise the decimal separator to `.`. After thousands removal, the\n // \"other\" separator must not appear β€” if it does, the cell doesn't match\n // the declared format and is unparseable.\n if (decimal === ',') {\n if (s.includes('.')) return Number.NaN\n s = s.split(',').join('.')\n } else {\n // decimal === '.'\n if (s.includes(',')) return Number.NaN\n }\n\n if (!STRICT_NUMBER_RE.test(s)) return Number.NaN\n return Number.parseFloat(s)\n}\n\n/**\n * Convert a major-unit money value (e.g. `55.02` EUR) to integer MINOR units\n * (`5502`). Rounds to the nearest cent to absorb float drift. The commerce-demo\n * PartsDocument money fields (`list_price_minor`, `purchase_price_minor`,\n * `core_charge_minor`) are integer minor units so derived prices (PR4) don't\n * accrue rounding error β€” see F003 in progress.md.\n */\nexport function toMinorUnits(value: number): number {\n return Math.round(value * 100)\n}\n\n/**\n * Parse a European-formatted decimal: `,` is the decimal separator, `.` is the\n * (optional) thousands separator. Returns `null` for an empty / `'NA'` cell and\n * `NaN` on unparseable (malformed) input.\n *\n * This is the carmaker-feed legacy parser, preserved from the hardcoded transform.\n * Crucially it **rejects bare-dot** input (`1.98`, `1.234`) as ambiguous rather\n * than guessing β€” the carmaker feeds are documented as comma-decimal, and a `.`\n * without a `,` could mean a US-format decimal OR a thousands marker. The\n * format-driven {@link parseNumber} doesn't need this guard (its separators are\n * explicit); the carmaker path keeps it.\n *\n * The `null` (absent) vs `NaN` (malformed) split mirrors {@link parseNumber} so\n * the mapping engine treats both number ops uniformly: a target field's `buildRow`\n * reads `null` as \"not provided\" and `NaN` as \"invalid\". This is what lets the\n * reimplemented carmaker transform keep its `GrossPrice 'NA' β†’ null` behaviour\n * (optional field) while still erroring on a malformed `NetPrice` (required).\n *\n * Cases: `'1,98'`β†’`1.98`, `'1.234,56'`β†’`1234.56`, `'5'`β†’`5`, `'-5,00'`β†’`-5`,\n * empty / `'NA'` β†’ `null`. Rejected (`NaN`): bare-dot (`'1.98'`, `'1.234'`),\n * trailing junk (`'1,98EUR'`), multiple commas (`'1,2,3'`), other non-numeric.\n */\nexport function parseEuropeanNumber(s: string): number | null {\n const trimmed = s.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n const hasComma = trimmed.includes(',')\n const hasDot = trimmed.includes('.')\n let cleaned: string\n if (hasComma && hasDot) {\n // European thousands+decimal: strip every `.`, then swap the (sole) `,` for\n // `.`. The strict regex below catches multi-comma input.\n cleaned = trimmed.replace(/\\./g, '').replace(',', '.')\n } else if (hasComma) {\n cleaned = trimmed.replace(',', '.')\n } else if (hasDot) {\n return Number.NaN\n } else {\n cleaned = trimmed\n }\n if (!STRICT_NUMBER_RE.test(cleaned)) return Number.NaN\n return Number.parseFloat(cleaned)\n}\n","/**\n * TargetSchema β€” the contract a mapping writes INTO (commerce-demo phase 02, D005).\n *\n * A mapping's `column_map` points source columns at a schema's whitelisted target\n * fields; the engine applies the per-column transforms to build a `MappedRow`, then\n * hands it to `schema.buildRow` to produce the typed output document (an ES\n * `PartsDocument` for `parts`, a discount row for `discount_table`).\n *\n * The `fields` list is the SECOND injection-boundary whitelist (the first is the\n * registered schema name): a `column_map` entry whose `target` is not a field key\n * here is rejected at validation time (R02). Two schemas ship in PR2 β€” `parts` and\n * `discount_table`.\n */\n\nimport type { RowResult } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\n\n/** One whitelisted target field on a schema. */\nexport interface TargetField {\n /** Stable target key referenced by `column_map[].target`. */\n key: string\n /** Human label for the wizard dropdown (PR3). */\n label: string\n /** Whether a mapping for this schema MUST include this target. */\n required: boolean\n /** Coarse type β€” drives the wizard's transform suggestions; `buildRow` does the real coercion. */\n type: 'string' | 'number'\n /**\n * Header spellings this field should be SUGGESTED for when the wizard auto-assigns a freshly\n * previewed file. Purely advisory: the operator can always override, and nothing here widens\n * the injection-boundary whitelist β€” `key` remains the only accepted `column_map[].target`.\n *\n * Real feeds do not name their columns after our keys (a supplier ships `partno`, `VARUOSA\n * KOOD`, `ArticleName`, never `code`), so without aliases the wizard suggests nothing for the\n * columns that matter and the operator has to know the schema by heart. `describeTargetSchemas`\n * ships this to the wizard verbatim, so a field's synonyms live next to the field itself\n * rather than in a lookup table on the client.\n *\n * Only add a spelling whose meaning is UNAMBIGUOUS. An alias is a silent decision applied to\n * somebody's catalogue β€” see the supersession fields below, where two spellings that both read\n * as \"replacement\" denote opposite directions and are therefore deliberately absent.\n */\n aliases?: readonly string[]\n}\n\n/** The per-row product of the engine: target field key β†’ cleaned value. */\nexport type MappedRow = Record<string, CellValue>\n\n/** Per-row context handed to `buildRow`. `params` is the opaque per-run params object. */\nexport interface BuildRowContext {\n importRunId: string\n rowNumber: number\n /**\n * Opaque per-run params (the parts schema reads brand/supplier identity from\n * it; `discount_table` ignores it). The schema validates the shape it needs.\n */\n params: Record<string, unknown>\n}\n\n/** A registered target schema: a whitelist + a row builder. */\nexport interface TargetSchema<TOut> {\n /** Registered name β€” also the `import_mapping.target_schema` value. */\n name: string\n /** The target-field whitelist (injection boundary). */\n fields: readonly TargetField[]\n /** Build a typed output (success) / skip / error from a mapped row. */\n buildRow(mapped: MappedRow, ctx: BuildRowContext): RowResult<TOut>\n}\n\n// ---------------------------------------------------------------------------\n// Shared `buildRow` helpers (used by every concrete schema).\n// ---------------------------------------------------------------------------\n\n/**\n * A nullable text cell β†’ trimmed string, or `null` for empty / non-string. Accepts\n * `undefined` (an UNMAPPED target β€” indexed access under `noUncheckedIndexedAccess`)\n * and treats it as absent.\n */\nexport function textOrNull(v: CellValue | undefined): string | null {\n if (typeof v !== 'string') return null\n const t = v.trim()\n return t === '' ? null : t\n}\n\n/** The three outcomes a `number` / `europeanNumber` op produces for a cell. */\nexport type NumberOutcome =\n | { kind: 'value'; value: number }\n | { kind: 'absent' }\n | { kind: 'invalid' }\n\n/**\n * Classify a cell that should hold a number. `undefined` (unmapped) / `null` β†’\n * absent; a real number β†’ value (`NaN` β†’ invalid); a non-empty raw string (no\n * number op declared) β†’ invalid; a blank raw string β†’ absent.\n */\nexport function numberCell(v: CellValue | undefined): NumberOutcome {\n if (v === undefined || v === null) return { kind: 'absent' }\n if (typeof v === 'number') {\n return Number.isNaN(v) ? { kind: 'invalid' } : { kind: 'value', value: v }\n }\n return v.trim() === '' ? { kind: 'absent' } : { kind: 'invalid' }\n}\n\n/** Build a `RowResult` error variant (assignable to any `TargetSchema<TOut>`). */\nexport function rowError(errorType: string, message: string, field: string) {\n return { kind: 'error' as const, error: { errorType, message, field } }\n}\n","/**\n * `parts` target schema β€” maps a cleaned feed row into the ES `PartsDocument`\n * (commerce-demo phase 02, D005). This is the SHARED assembly + validation logic\n * the reimplemented carmaker transform and every operator-built `parts` mapping\n * run through, so the row taxonomy (code normalization, currency gate, price\n * validation) is uniform across all supplier feeds.\n *\n * **Field coverage.** This schema populates the direct passthroughs (the existing\n * `PartsDocument` columns plus `list_price_minor`, `discount_group`,\n * `superseding_code`) AND the DERIVED `purchase_price_minor` (PR4 β€” direct net, or\n * two-file `list Γ— (1 βˆ’ groupDiscount)` resolved from `params.discountGroups`). Core\n * charge (Korpusetasu, PR7, D004) has TWO encodings β†’ one `core_charge_minor`:\n * Encoding A is a `surcharge`/`core_charge` COLUMN on the saleable row (written here);\n * Encoding B is a separate `<code>*S` core-fee row that skips the saleable index and\n * emits a doc-patch attaching its deposit to the PARENT part in the runner's phase-2\n * pass. Replacement-pair SIDE EFFECTS (separate entity) are PR6 β€” emitted from\n * `superseding_code` and/or `replaces_code`, which name the same relationship from\n * opposite ends and are pairs-only (`replaces_code` has no `PartsDocument` column).\n *\n * **Money.** Every money field is integer minor units via `toMinorUnits` (F003), and\n * the two-file derivation stays in minor units end-to-end (no major↔minor\n * round-trip). The legacy `net_price_eur` stays a major-unit float for back-compat:\n * it holds the direct net price, or β€” for a two-file LIST feed with no direct net β€”\n * the list price as a display placeholder (the true cost is `purchase_price_minor`).\n *\n * **Cost-pending warning.** A list-only row whose `discount_group` doesn't resolve\n * against `params.discountGroups` is still indexed (list set, `purchase_price_minor`\n * null) and carries a `no_purchase_price` WARNING β€” not a row error (phase 03 Β§5).\n */\n\nimport type { PartsDocument } from '@murumets-ee/search-elasticsearch'\nimport { z } from 'zod'\nimport type { DirectionalPair, DocPatch, RowWarning } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\nimport { toMinorUnits } from './number-format.js'\nimport {\n type BuildRowContext,\n type MappedRow,\n numberCell,\n rowError,\n type TargetField,\n type TargetSchema,\n textOrNull,\n} from './target-schema.js'\n\n/**\n * Params the `parts` schema reads from the run β€” the per-(supplier, brand)\n * identity resolved at enqueue time. Identical to the carmaker transform's params\n * (the carmaker path re-exports this), so brand/supplier injection + the optional\n * supplier code-prefix strip are validated the same way everywhere.\n */\nexport const partsParamsSchema = z.object({\n brandId: z.string().uuid(),\n brandSlug: z.string().min(1).max(64),\n supplierId: z.string().uuid(),\n supplierDisplayName: z.string().min(1).max(255),\n importBatchId: z.string().uuid(),\n /** Supplier code prefix to strip before normalization (e.g. `'ME-'`). Optional. */\n supplierCodePrefix: z\n .string()\n .max(8)\n .regex(/^[A-Z0-9-]+$/, 'must be uppercase alphanumeric or \"-\"')\n .optional(),\n /**\n * Purchase-discount map for this supplier (commerce-demo PR4, phase 03 Β§2):\n * `{ groupCode β†’ discountPct }`, resolved from `supplier_discount_group` at\n * enqueue time and snapshotted onto the run so `buildRow` stays a pure function\n * (no per-row DB I/O; `@murumets-ee/imports` stays a leaf). Absent for direct-net\n * suppliers + the carmaker path. Percentages are 0–100 (the entity constrains them).\n */\n discountGroups: z.record(z.string(), z.number().min(0).max(100)).optional(),\n})\nexport type PartsParams = z.infer<typeof partsParamsSchema>\n\n/** Per-run memoization of the parsed params (keyed on the `ctx.params` reference). */\nconst paramsCache = new WeakMap<object, PartsParams>()\n\nfunction resolveParams(raw: Record<string, unknown>): PartsParams {\n const cached = paramsCache.get(raw)\n if (cached) return cached\n const parsed = partsParamsSchema.parse(raw)\n paramsCache.set(raw, parsed)\n return parsed\n}\n\n/** Per-locale display-name target fields (8 locales). */\nconst NAME_LOCALES = ['de', 'en', 'es', 'fr', 'it', 'nl', 'pt', 'ro'] as const\ntype NameLocale = (typeof NAME_LOCALES)[number]\nconst nameKey = (l: NameLocale): `name_${NameLocale}` => `name_${l}`\n\n/**\n * The `parts` target-field whitelist.\n *\n * **On the two supersession fields.** They exist as a PAIR because the direction of a\n * \"replacement\" column cannot be read off its name. TecDoc's data format defines `SupersNo` /\n * `ErsatzNr` as *\"Article ArtNo supersedes Article SupersNo\"* β€” the column holds the OLD code\n * and the row is current. German `ersetzt durch` and English `replaced by` mean the exact\n * opposite: the column holds the NEW code and the row is obsolete. Both are \"replacement\"\n * words; only the grammatical voice distinguishes them, and a bare noun like `Ersatznummer`\n * carries no voice at all. TecDoc's own SOAP API resolved this by shipping `replacesArticles`\n * and `replacedByArticles` as separate elements rather than one ambiguous field, and that is\n * what these two keys are.\n *\n * Getting it backwards is silent β€” an inverted feed builds well-formed chains with valid heads\n * and no warnings, and the union-find merge is append-only, so re-importing the right way round\n * does NOT repair it. Hence: no alias in this file is ambiguous about direction, and the\n * genuinely ambiguous spellings (`superseded no`, `Ersatznummer`, `Ersatz-Nr`) are deliberately\n * aliased to NEITHER field, so an operator meeting one has to state the direction rather than\n * inherit a guess.\n */\nconst PARTS_FIELDS: readonly TargetField[] = [\n {\n key: 'code',\n label: 'Code',\n required: true,\n type: 'string',\n // `part no` already covers a `partno` header: aliases are compared as bare alphanumerics,\n // and a header matches on a run of its own tokens, so both spellings reduce to `partno`.\n aliases: [\n 'part no',\n 'part number',\n 'article name',\n 'article no',\n 'article number',\n 'sku',\n 'varuosa kood',\n 'kood',\n 'artikelnummer',\n 'artikel nr',\n ],\n },\n {\n key: 'net_price',\n label: 'Net price',\n required: false,\n type: 'number',\n aliases: ['price', 'net price discount', 'nettopreis', 'netto'],\n },\n {\n key: 'gross_price',\n label: 'Gross price',\n required: false,\n type: 'number',\n aliases: ['bruttopreis', 'brutto'],\n },\n {\n key: 'list_price',\n label: 'List price',\n required: false,\n type: 'number',\n // `JAEHIND KM-TA` is Estonian for \"retail price, VAT-excluded\" (R03 sample A).\n aliases: ['retail price', 'rrp', 'jaehind', 'jaehind km ta', 'listenpreis'],\n },\n {\n key: 'currency',\n label: 'Currency',\n required: false,\n type: 'string',\n aliases: ['currency cd', 'currency code', 'valuuta'],\n },\n {\n key: 'barcode',\n label: 'Barcode',\n required: false,\n type: 'string',\n // `ean code` / `gtin code` are whole-header aliases on purpose: without them a header\n // spelled `EAN Code` matches the bare `code` token and claims the REQUIRED part-code\n // field, because `code` (4 chars) outscores the `ean` alias (3). A whole-header hit\n // outranks any partial run, so naming the compound form settles it.\n aliases: ['ean', 'ean code', 'gtin', 'gtin code', 'triipkood'],\n },\n {\n key: 'description1',\n label: 'Description 1',\n required: false,\n type: 'string',\n aliases: ['description', 'kirjeldus', 'beschreibung'],\n },\n { key: 'description2', label: 'Description 2', required: false, type: 'string' },\n {\n key: 'discount_group',\n label: 'Discount group',\n required: false,\n type: 'string',\n // `TOOTEGRUPP` is Estonian for \"product group\" (R03 sample A), which IS the discount key.\n // A bare `group` is deliberately NOT here: on a parts feed it is as likely an assortment\n // or category group, and a wrong-but-colliding value resolves against\n // `params.discountGroups` and derives a wrong `purchase_price_minor` with no warning at all\n // (only a NON-colliding code raises `no_purchase_price`). A silent money error is worth\n // more than a saved click.\n aliases: ['product group', 'tootegrupp', 'rabattgruppe'],\n },\n {\n /**\n * The NEWER code that supersedes THIS row β€” the row's own code is the obsolete one.\n * Emits `(this row β†’ the value)`.\n */\n key: 'superseding_code',\n label: 'Replaced by (newer code)',\n required: false,\n type: 'string',\n // Every entry states direction by grammar: a passive (\"replaced by\", \"ersetzt durch\",\n // \"vervangen door\") or a word that means \"the one after\" (\"successor\", \"new code\",\n // \"Nachfolgenummer\"). A bare noun phrase like `replacement code` does NOT β€” it reads just\n // as easily as \"the code this replaces\" β€” so it is excluded for the same reason\n // `Ersatznummer` is.\n aliases: [\n 'replaced by',\n 'successor',\n 'successor code',\n 'new code',\n 'ersetzt durch',\n 'wird ersetzt durch',\n 'nachfolgenummer',\n 'vervangen door',\n ],\n },\n {\n /**\n * The OLDER code THIS row supersedes β€” the row's own code is the current one. Emits the\n * INVERSE pair `(the value β†’ this row)`. This is TecDoc table 204's shape.\n */\n key: 'replaces_code',\n label: 'Replaces (older code)',\n required: false,\n type: 'string',\n // Same rule from the other side: active verbs (\"replaces\", \"supersedes\") or words meaning\n // \"the one before\" (\"predecessor\", \"old code\", \"VorgΓ€ngernummer\"). `superseded article` is\n // NOT here β€” TecDoc reads that phrasing as the old code, but it is the same bare\n // past-participle family as `superseded no`, which this file refuses to auto-assign;\n // excluding one and accepting the other would be incoherent.\n aliases: [\n 'replaces',\n 'supersedes',\n 'old code',\n 'previous code',\n 'predecessor',\n 'vorgaengernummer',\n ],\n },\n // Core charge (Korpusetasu, commerce-demo PR7, D004). Encoding A: a supplier's\n // `surcharge`/`core_charge` COLUMN maps here β†’ this row's deposit. (Encoding B β€”\n // a separate `<code>*S` row β€” needs no whitelist field; it's detected on the code.)\n {\n key: 'core_charge',\n label: 'Core charge',\n required: false,\n type: 'number',\n aliases: ['surcharge', 'deposit', 'core deposit', 'korpusetasu', 'pfand'],\n },\n ...NAME_LOCALES.map(\n (l): TargetField => ({\n key: nameKey(l),\n label: `Name (${l})`,\n required: false,\n type: 'string',\n // The carmaker feed ships these as `Description_<LOCALE>` (R03 sample D).\n aliases: [`description ${l}`, `name ${l}`],\n }),\n ),\n] as const\n\nconst NORMALIZE_CODE_RE = /[\\s-]/g\n/**\n * Uppercase + dash/whitespace-stripped (D2). `*`/other chars are preserved (e.g. `*S`\n * markers). EXPORTED so downstream consumers that key off `code_normalized` β€” the\n * replacement editor (commerce-demo PR6), which normalizes admin-typed codes before\n * matching members β€” use the IDENTICAL rule (R05 Q7: normalization must match across\n * every code source or merge-on-collision silently fails to collide).\n */\nexport function normalizeCode(s: string): string {\n return s.toUpperCase().replace(NORMALIZE_CODE_RE, '')\n}\n\n/**\n * A supersession cell β†’ one normalized code, or `null` when there is no usable edge end:\n * unmapped, blank, or punctuation-only (a `'---'` placeholder normalizes to the empty string).\n *\n * **The supplier prefix must be stripped here too.** `code_normalized` removes\n * `params.supplierCodePrefix` before normalizing, so a feed that writes `FO-1120698` in its own\n * code column also writes `FO-1091888` in its supersession column. Normalizing one with the\n * prefix and the other without produces an edge between a code that exists in the catalogue and\n * one that never will β€” the chain builds cleanly and matches nothing, which is indistinguishable\n * from having no supersession data at all.\n */\nfunction normalizeCodeCell(\n cell: CellValue | undefined,\n supplierCodePrefix: string | undefined,\n): string | null {\n const raw = textOrNull(cell)\n if (raw === null) return null\n const stripped =\n supplierCodePrefix && raw.startsWith(supplierCodePrefix)\n ? raw.slice(supplierCodePrefix.length)\n : raw\n const normalized = normalizeCode(stripped)\n return normalized === '' ? null : normalized\n}\n\n/**\n * Two-file purchase price (phase 03 Β§2): `list Γ— (1 βˆ’ discountPct/100)`, computed\n * ENTIRELY in integer minor units so no major↔minor round-trip can introduce drift\n * (F003). `listMinor` is already minor units; the result is rounded to the nearest\n * minor unit. Worked (R03 A+B): `5502 Γ— 0.74 = 4071.48 β†’ 4071` (€40.71).\n */\nfunction deriveTwoFilePurchaseMinor(listMinor: number, discountPct: number): number {\n return Math.round(listMinor * (1 - discountPct / 100))\n}\n\n/**\n * The core-charge marker suffix on a NORMALIZED code (D004, SD002). `normalizeCode`\n * uppercases + strips dashes/spaces but PRESERVES `*`, so a `<code>*S` core-fee row\n * arrives here intact β€” e.g. `1120698*S`. A code ending in `*S` is a core-fee line,\n * not a saleable part (Encoding B).\n */\nconst CORE_FEE_SUFFIX = '*S'\n\n/** The five core-charge doc fields the two encodings write. */\ntype CoreChargeFields = Pick<\n PartsDocument,\n | 'core_charge_minor'\n | 'core_charge_currency'\n | 'core_charge_refundable'\n | 'core_charge_tax_class'\n | 'core_charge_tax_inclusive'\n>\n\n/**\n * The tax-NEUTRAL core-charge block (D004 / D007) for a deposit amount in minor\n * units, or all-null when there's no core charge. EUR (D9) + refundable by default;\n * the imported EU feed amounts are net so `tax_inclusive = false`; `tax_class` stays\n * null β€” no rate is baked in here, the future pluggable EU/US tax engine maps it (D007).\n */\nfunction coreChargeFields(minor: number | null): CoreChargeFields {\n if (minor === null) {\n return {\n core_charge_minor: null,\n core_charge_currency: null,\n core_charge_refundable: null,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: null,\n }\n }\n return {\n core_charge_minor: minor,\n core_charge_currency: 'EUR',\n core_charge_refundable: true,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: false,\n }\n}\n\n/**\n * The `parts` schema. `buildRow` THROWS on invalid run params (so a misconfigured\n * run surfaces as a transform error, matching the carmaker contract) and returns a\n * typed `RowResult` per row otherwise.\n */\nexport const partsSchema: TargetSchema<PartsDocument> = {\n name: 'parts',\n fields: PARTS_FIELDS,\n buildRow(mapped: MappedRow, ctx: BuildRowContext) {\n const params = resolveParams(ctx.params)\n\n // 1. Code (required) β†’ raw `code` + normalized `code_normalized` + doc id.\n const codeRaw = typeof mapped.code === 'string' ? mapped.code.trim() : ''\n if (!codeRaw) return rowError('missing_code', 'code is empty', 'code')\n const stripped =\n params.supplierCodePrefix && codeRaw.startsWith(params.supplierCodePrefix)\n ? codeRaw.slice(params.supplierCodePrefix.length)\n : codeRaw\n const codeNormalized = normalizeCode(stripped)\n if (!codeNormalized) {\n return rowError(\n 'empty_normalized_code',\n `Code \"${codeRaw}\" is empty after normalization`,\n 'code',\n )\n }\n\n // 2. Currency gate (D9 EUR-only). Unmapped/blank defaults to EUR. Runs BEFORE the\n // `*S` detection so a non-EUR core-fee row is rejected too β€” Encoding A and B keep\n // the SAME currency contract (a `*S` deposit is never silently coerced to EUR).\n const currencyText = textOrNull(mapped.currency)\n const currency = currencyText ?? 'EUR'\n if (currency !== 'EUR') {\n return rowError(\n 'unsupported_currency',\n `Currency \"${currency}\" not supported (EUR-only)`,\n 'currency',\n )\n }\n\n // 2b. Core-fee line β€” Encoding B (D004, SD002). A `<code>*S` normalized code is a\n // core-fee MARKER row, not a saleable part: strip the `*S`, take THIS row's net\n // price as the deposit, and emit a doc-patch that attaches it onto the PARENT\n // part's core-charge fields. The row itself SKIPS the saleable index (never a\n // `*S` SKU β€” D004). The runner applies the patch in a phase-2 pass; a parent\n // that isn't in the import becomes an `orphan_core_charge` warning (never a\n // phantom doc, never a silent drop). A `*S` with no parent code, or no/invalid\n // amount, is a row error.\n if (codeNormalized.endsWith(CORE_FEE_SUFFIX)) {\n const parentNormalized = codeNormalized.slice(0, -CORE_FEE_SUFFIX.length)\n if (!parentNormalized) {\n return rowError(\n 'core_charge_no_parent',\n `Core-fee row \"${codeRaw}\" has no part code before the \"*S\" marker`,\n 'code',\n )\n }\n const deposit = numberCell(mapped.net_price)\n if (deposit.kind === 'invalid') {\n return rowError(\n 'invalid_core_charge',\n 'core-fee (*S) row net_price is not a number',\n 'net_price',\n )\n }\n if (deposit.kind === 'absent') {\n return rowError(\n 'missing_core_charge',\n 'core-fee (*S) row has no net_price to use as the deposit',\n 'net_price',\n )\n }\n // Gate on the MINOR-unit result (a sub-cent value like 0.004 β†’ round to 0):\n // 0 / sub-cent / negative deposit β†’ nothing to attach; drop it without a patch\n // rather than zeroing a parent's core charge.\n const depositMinor = toMinorUnits(deposit.value)\n if (depositMinor <= 0) {\n return { kind: 'skip', reason: 'core_fee_zero' }\n }\n const patch: DocPatch<PartsDocument> = {\n id: `${parentNormalized}__${params.supplierId}`,\n doc: coreChargeFields(depositMinor),\n orphanWarning: {\n warningType: 'orphan_core_charge',\n message: 'core-fee (*S) row references a part not present in this import',\n field: 'code',\n },\n }\n return { kind: 'skip', reason: 'core_charge_marker', patches: [patch] }\n }\n\n // 3. Prices. net/gross/list each: absent β†’ null, invalid β†’ error, value β†’ number.\n const net = numberCell(mapped.net_price)\n if (net.kind === 'invalid')\n return rowError('invalid_net_price', 'net_price is not a number', 'net_price')\n const gross = numberCell(mapped.gross_price)\n if (gross.kind === 'invalid') {\n return rowError('invalid_gross_price', 'gross_price is not a number', 'gross_price')\n }\n const list = numberCell(mapped.list_price)\n if (list.kind === 'invalid')\n return rowError('invalid_list_price', 'list_price is not a number', 'list_price')\n\n const netValue = net.kind === 'value' ? net.value : null\n const listValue = list.kind === 'value' ? list.value : null\n // At least one price must resolve. `net_price_eur` is non-nullable on the doc,\n // so it takes the direct net or β€” for a list-only two-file feed β€” the list\n // price as a display placeholder (the true cost is `purchase_price_minor`).\n const displayPrice = netValue ?? listValue\n if (displayPrice === null) {\n return rowError('missing_price', 'no net_price or list_price provided', 'price')\n }\n\n // 4. Purchase-price derivation (phase 03 Β§2, PR4). All money stays in integer\n // minor units (F003 β€” never round-trip back to major).\n // - direct net column (R03 C/D) β†’ purchase = net\n // - two-file list Γ— (1 βˆ’ groupDiscount) β†’ purchase = round(list Γ— (1 βˆ’ d/100))\n // - neither resolvable β†’ cost pending: index list-only + WARN\n // (a `no_purchase_price` warning, NOT a row error β€” the part is still indexed).\n const discountGroup = textOrNull(mapped.discount_group)\n const listMinor = listValue === null ? null : toMinorUnits(listValue)\n let purchasePriceMinor: number | null = null\n const warnings: RowWarning[] = []\n if (netValue !== null) {\n purchasePriceMinor = toMinorUnits(netValue)\n } else if (listMinor !== null) {\n // List-only row: resolve the supplier's discount group β†’ derive cost.\n const discountPct =\n discountGroup !== null ? params.discountGroups?.[discountGroup] : undefined\n if (discountPct !== undefined) {\n purchasePriceMinor = deriveTwoFilePurchaseMinor(listMinor, discountPct)\n } else {\n warnings.push({\n warningType: 'no_purchase_price',\n message:\n discountGroup === null\n ? 'list price present but no discount group on the row β€” cost pending'\n : `no discount group \"${discountGroup}\" configured for this supplier β€” cost pending`,\n field: 'discount_group',\n })\n }\n }\n\n // 5. Replacement-pair side-output (commerce-demo PR6, SD007). Both supersession columns\n // are SPARSE on a full manufacturer catalogue, and both produce the same\n // `(from = older β†’ to = newer)` edge the chain engine consumes β€” they differ only in\n // which end of the edge the row itself is:\n // `superseding_code` β†’ the value is NEWER, so the edge runs (this row β†’ value);\n // `replaces_code` β†’ the value is OLDER, so the edge runs (value β†’ this row).\n // Every code is normalized the SAME way as `code_normalized` so the downstream merge\n // collides codes across feeds (R05 Q7). A value that is empty, normalizes to empty\n // (e.g. `'---'`), or self-pairs yields no edge. A row MAY carry both columns β€” that is\n // a legitimate three-code chain (older β†’ this β†’ newer), not a conflict.\n const pairs: DirectionalPair[] = []\n const supersedingNormalized = normalizeCodeCell(\n mapped.superseding_code,\n params.supplierCodePrefix,\n )\n if (supersedingNormalized !== null && supersedingNormalized !== codeNormalized) {\n pairs.push({ from: codeNormalized, to: supersedingNormalized })\n }\n const replacesNormalized = normalizeCodeCell(mapped.replaces_code, params.supplierCodePrefix)\n if (replacesNormalized !== null && replacesNormalized !== codeNormalized) {\n pairs.push({ from: replacesNormalized, to: codeNormalized })\n }\n\n // 6. Core charge β€” Encoding A (D004). A `surcharge`/`core_charge` COLUMN on this\n // saleable row is the deposit for THIS part. 0 / empty / absent / sub-cent β†’ no\n // core charge. (Encoding B β€” a separate `<code>*S` row β€” is handled at step 1b\n // and attaches to the parent in phase-2, so it never reaches here. In the unusual\n // case a part has BOTH a `core_charge` column AND a sibling `*S` row β€” suppliers\n // use one encoding β€” the `*S` phase-2 patch runs after indexing and wins.)\n const coreChargeCell = numberCell(mapped.core_charge)\n if (coreChargeCell.kind === 'invalid') {\n return rowError('invalid_core_charge', 'core_charge is not a number', 'core_charge')\n }\n // Gate on the MINOR-unit result so a sub-cent value (rounds to 0) yields no charge.\n const coreChargeMinorRaw =\n coreChargeCell.kind === 'value' ? toMinorUnits(coreChargeCell.value) : null\n const coreChargeMinor =\n coreChargeMinorRaw !== null && coreChargeMinorRaw > 0 ? coreChargeMinorRaw : null\n\n const docId = `${codeNormalized}__${params.supplierId}`\n const doc: PartsDocument = {\n doc_id: docId,\n code: codeRaw,\n code_normalized: codeNormalized,\n brand_id: params.brandId,\n brand_slug: params.brandSlug,\n supplier_id: params.supplierId,\n supplier_display_name: params.supplierDisplayName,\n net_price_eur: displayPrice,\n gross_price_eur: gross.kind === 'value' ? gross.value : null,\n currency: 'EUR',\n barcode: textOrNull(mapped.barcode),\n name_de: textOrNull(mapped.name_de),\n name_en: textOrNull(mapped.name_en),\n name_es: textOrNull(mapped.name_es),\n name_fr: textOrNull(mapped.name_fr),\n name_it: textOrNull(mapped.name_it),\n name_nl: textOrNull(mapped.name_nl),\n name_pt: textOrNull(mapped.name_pt),\n name_ro: textOrNull(mapped.name_ro),\n description1: textOrNull(mapped.description1),\n description2: textOrNull(mapped.description2),\n // commerce-demo: list price β†’ minor units; group + code passthroughs.\n list_price_minor: listMinor,\n discount_group: discountGroup,\n superseding_code: textOrNull(mapped.superseding_code),\n // Derived purchase cost (PR4 β€” direct net or two-file list Γ— (1 βˆ’ d)); null = cost pending.\n purchase_price_minor: purchasePriceMinor,\n // Core charge (PR7, Encoding A column) β€” or all-null when this row has none.\n ...coreChargeFields(coreChargeMinor),\n import_batch_id: params.importBatchId,\n imported_at: new Date().toISOString(),\n }\n\n return {\n kind: 'success',\n id: docId,\n doc,\n ...(warnings.length > 0 && { warnings }),\n ...(pairs.length > 0 && { pairs }),\n // Value-drift sampling (F010 / #602) β€” the DERIVED cost, not the raw\n // net/list price, so a decimal-format flip on either the direct-net\n // or two-file source column shows up here regardless of which pricing\n // path this supplier's feed uses. `null` (cost-pending) is omitted,\n // same as `no_purchase_price` warnings already do β€” the collector\n // counts it toward `nullRate` instead.\n ...(purchasePriceMinor !== null && { priceSample: purchasePriceMinor }),\n }\n },\n}\n"],"mappings":"wBA6BA,MAAM,EAAmB,kBAkBzB,SAAgB,EAAY,EAAa,EAAqC,CAC5E,IAAM,EAAU,EAAI,KAAK,EACzB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAE7D,GAAM,CAAE,UAAS,aAAc,EAC3B,EAAI,EAOR,GALI,IAAc,KAAI,EAAI,EAAE,MAAM,CAAS,CAAC,CAAC,KAAK,EAAE,GAKhD,IAAY,IAAK,CACnB,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAC5B,EAAI,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAC3B,MAEE,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAI9B,OADK,EAAiB,KAAK,CAAC,EACrB,OAAO,WAAW,CAAC,EADY,GAExC,CASA,SAAgB,EAAa,EAAuB,CAClD,OAAO,KAAK,MAAM,EAAQ,GAAG,CAC/B,CAwBA,SAAgB,EAAoB,EAA0B,CAC5D,IAAM,EAAU,EAAE,KAAK,EACvB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAC7D,IAAM,EAAW,EAAQ,SAAS,GAAG,EAC/B,EAAS,EAAQ,SAAS,GAAG,EAC/B,EACJ,GAAI,GAAY,EAGd,EAAU,EAAQ,QAAQ,MAAO,EAAE,CAAC,CAAC,QAAQ,IAAK,GAA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WACpB,sBAAuB,EAAO,oBAC9B,cAAe,EACf,gBAAiB,EAAM,OAAS,QAAU,EAAM,MAAQ,KACxD,SAAU,MACV,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,aAAc,EAAW,EAAO,YAAY,EAC5C,aAAc,EAAW,EAAO,YAAY,EAE5C,iBAAkB,EAClB,eAAgB,EAChB,iBAAkB,EAAW,EAAO,gBAAgB,EAEpD,qBAAsB,EAEtB,GAAG,EAAiB,CAAe,EACnC,gBAAiB,EAAO,cACxB,YAAa,IAAI,KAAK,CAAA,CAAE,YAAY,CAMlC,EACF,GAAI,EAAS,OAAS,GAAK,CAAE,UAAS,EACtC,GAAI,EAAM,OAAS,GAAK,CAAE,OAAM,EAOhC,GAAI,IAAuB,MAAQ,CAAE,YAAa,CAAmB,CACvE,CACF,CACF"}
@@ -0,0 +1,148 @@
1
+ import { n as EsClientResolver, r as FilePathResolver, s as PairSink, t as EnsureIndexResolver } from "./worker-CRH_PjKO.mjs";
2
+ import { ImportsStorageFactory } from "./storage.mjs";
3
+ import { IndexConfig } from "@murumets-ee/search-elasticsearch";
4
+
5
+ //#region src/plugin.d.ts
6
+ interface ImportsPluginOptions {
7
+ /**
8
+ * Elasticsearch client resolver. Lazy so consumers can construct
9
+ * the client inside a route initialiser instead of at plugin-init
10
+ * time. Required β€” without it, the worker can't bulk-write.
11
+ */
12
+ esClient: EsClientResolver;
13
+ /**
14
+ * ES index alias to write to. Per D6 always pass an ALIAS, never a physical
15
+ * index β€” that is what makes {@link importsReindexJob}'s atomic swap possible.
16
+ *
17
+ * **Required, deliberately.** It defaulted to `'parts'` until #665: two apps
18
+ * sharing one Elasticsearch cluster both took that default and wrote the same
19
+ * physical index, so staging's 858k-row Ford import surfaced in production's
20
+ * parts search. The pod workaround was to set the alias per deployment β€” but
21
+ * a DEFAULT here means an app can set `PARTS_INDEX_ALIAS`, wire it into the
22
+ * read path, forget this option, and have its reads and writes silently name
23
+ * different indices. That is the same defect one level down, and it fails
24
+ * SILENTLY. Making the option required turns it into a compile error instead.
25
+ *
26
+ * Pass the SAME value the search provider's `indexAlias` uses; the app's
27
+ * `lib/parts-search.ts` exports one `partsIndexAlias` const for exactly this.
28
+ */
29
+ esIndex: string;
30
+ /**
31
+ * Optional bootstrap for the destination index/alias, run once per import
32
+ * job before any bulk-write (see {@link EnsureIndexResolver}). Wire your
33
+ * app's `ensureAliasedIndex`-backed helper here so the worker can never
34
+ * auto-create a mis-mapped physical index β€” WITHOUT gating app boot on ES.
35
+ *
36
+ * Omit only when the index is bootstrapped out-of-band; without it a
37
+ * first-ever import against an unbootstrapped alias lets ES auto-create a
38
+ * `text`-mapped physical index, breaking aggregations (issue #610).
39
+ */
40
+ ensureIndex?: EnsureIndexResolver;
41
+ /**
42
+ * Settings + mappings the `imports:reindex` job creates its DESTINATION index
43
+ * with. Pass the same config `ensureIndex` bootstraps the alias from (for the
44
+ * parts catalog: `partsIndexConfig` from `@murumets-ee/search-elasticsearch`).
45
+ *
46
+ * Omit it and the job still registers, but refuses to run with an actionable
47
+ * error β€” a reindex into an index Elasticsearch auto-created with inferred
48
+ * `text` mappings would silently discard the mapping change the reindex
49
+ * exists to ship, which is a worse outcome than not running.
50
+ *
51
+ * This is what makes a mapping change deployable at all: `ensureAliasedIndex`
52
+ * returns as soon as the alias resolves and never issues a `put_mapping`, so
53
+ * on an already-bootstrapped cluster, editing the mapping config has no
54
+ * effect whatsoever without a reindex.
55
+ */
56
+ indexConfig?: IndexConfig;
57
+ /**
58
+ * Resolve `import_run.filePath` to a local FS path before streaming.
59
+ * **Required when uploads land in remote storage** (R2/S3/etc.) β€”
60
+ * without it, the worker hands the storage key to `createReadStream`
61
+ * and crashes with `ENOENT`.
62
+ *
63
+ * Typical wiring downloads the storage object to a tmpfile and
64
+ * returns its path; the optional `cleanup` callback runs after the
65
+ * run finishes (success or failure).
66
+ *
67
+ * Omit this option for the original on-disk PoC setup where the
68
+ * upload route writes directly to a local directory and persists
69
+ * the absolute path on `import_run.filePath`.
70
+ */
71
+ resolveFilePath?: FilePathResolver;
72
+ /**
73
+ * Optional consumer for the directional supersession pairs the runner harvests as
74
+ * a side-output (commerce-demo PR6, SD007). The app composes it β€” commerce exports
75
+ * the replacement-merge sink and passes it here, same injection shape as
76
+ * {@link esClient} / {@link resolveFilePath}. Omit when not ingesting replacement
77
+ * codes; the pairs are then discarded after the run.
78
+ */
79
+ pairSink?: PairSink;
80
+ /**
81
+ * Optional dedicated `StorageClient` factory for imports. When
82
+ * provided, the upload route (in `@murumets-ee/commerce`) and the
83
+ * worker resolver consult this client instead of the global
84
+ * `getStorageConfig()` default β€” so a deployment can pin imports
85
+ * to a local-disk adapter (single-VPS / dev) while media,
86
+ * ticketing attachments, and the rest of the app keep using the
87
+ * default R2 (or S3) adapter.
88
+ *
89
+ * Lazy / async so consumers can defer adapter construction until
90
+ * the first import β€” useful when the local-disk root is
91
+ * environment-dependent or when the factory needs `getApp()` to
92
+ * have resolved.
93
+ *
94
+ * Omit to keep the legacy single-storage behaviour (everything on
95
+ * the global default).
96
+ */
97
+ storage?: ImportsStorageFactory;
98
+ /**
99
+ * Bucket name to scope the orphan-cleanup queue job. Rows in
100
+ * `toolkit_files` with this bucket value AND no matching
101
+ * `import_run.filePath` AND `createdAt < cutoff` get garbage-
102
+ * collected on each cleanup tick. Defaults to `'lumi-imports'` β€”
103
+ * the convention `apps/admin/lib/imports-storage.ts`
104
+ * uses by default. Override if your deployment pins a different
105
+ * bucket name via `IMPORTS_STORAGE_BUCKET` or equivalent.
106
+ *
107
+ * Set to `null` to DISABLE the cleanup job entirely (e.g. for
108
+ * deployments that handle their own retention via S3 lifecycle
109
+ * rules). Disabling without an alternative will leak storage
110
+ * over time as failed uploads accumulate.
111
+ */
112
+ storageBucket?: string | null;
113
+ /**
114
+ * Hours after which an unreferenced `toolkit_files` row in the
115
+ * imports bucket is considered orphaned and deleted by the
116
+ * cleanup job. Default 2h β€” long enough that a normal
117
+ * upload-then-register round-trip never wipes a fresh upload,
118
+ * short enough that storage waste from failed uploads doesn't
119
+ * accumulate.
120
+ *
121
+ * The upload→register flow happens client-side automatically (no
122
+ * "operator clicks register" step in the current UI), so the TTL
123
+ * just needs to cover network blips + retries. Bumping the TTL
124
+ * is safe if your operators commonly upload then wait before
125
+ * processing.
126
+ */
127
+ orphanUploadTtlHours?: number;
128
+ /**
129
+ * Days after which a terminal-status `import_run`'s source file is
130
+ * deleted from `toolkit_files`. Default 7 days β€” gives operators a
131
+ * reprocess window if a transform bug surfaces post-success, while
132
+ * keeping storage costs bounded. Set to 0 for instant cleanup at
133
+ * the next cleanup tick after `import_run.status` becomes terminal
134
+ * (`succeeded` / `failed` / `cancelled`).
135
+ *
136
+ * The `import_run` row itself is preserved β€” the audit trail and
137
+ * History panel still show the past run; only the source feed
138
+ * file is removed.
139
+ */
140
+ processedRetentionDays?: number;
141
+ }
142
+ declare function imports(options: ImportsPluginOptions): Pick<import("@murumets-ee/core").Plugin, "server" | "adminUi" | "postInstall" | "requires" | "contributes"> & {
143
+ readonly name: "@murumets-ee/imports";
144
+ readonly shared?: undefined;
145
+ };
146
+ //#endregion
147
+ export { ImportsPluginOptions, imports };
148
+ //# sourceMappingURL=plugin.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.mts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;;;UAwFiB,oBAAA;;;;;;EAMf,QAAA,EAAU,gBAAA;;;;;;;;;;;;;;;;;EAiBV,OAAA;;;;;;;;;;;EAWA,WAAA,GAAc,mBAAA;;;;;;;;;;;;;;;;EAgBd,WAAA,GAAc,WAAA;;;;;;;;;;;;;;;EAed,eAAA,GAAkB,gBAAA;;;;;;;;EAQlB,QAAA,GAAW,QAAA;;;;;;;;;;;;;;;;;;EAkBX,OAAA,GAAU,qBAAA;;;;;;;;;;;;;;;EAeV,aAAA;;;;;;;;;;;;;;;EAeA,oBAAA;;;;;;;;;;;;;EAaA,sBAAA;AAAA;AAAA,iBAGc,OAAA,CAAQ,OAAA,EAAS,oBAAA,GAAoB,IAAA,6BAAA,MAAA;EAAA"}
@@ -0,0 +1,2 @@
1
+ import{n as e,o as t,u as n}from"./transform-Cu5YEoOl.mjs";import{registerImportsStorageFactory as r}from"./storage.mjs";import{i,t as a}from"./carmaker-feed-B-QYr3PI.mjs";import{n as o,t as s}from"./mapping-transform-CO4MNhMe.mjs";import{createImportsRunDeadListener as c,createRunImportHandler as l,importsRunJob as u}from"./worker.mjs";import{definePlugin as d}from"@murumets-ee/core";import{z as f}from"zod";import{inArray as p}from"drizzle-orm";import{createIndex as m,dropIndex as h,readAliasTargets as g,reindex as _}from"@murumets-ee/search-elasticsearch";import{defineJob as v}from"@murumets-ee/queue/client";const y=f.object({toIndex:f.string().min(1).optional(),allowExisting:f.boolean().optional(),dropOld:f.boolean().optional(),batchSize:f.number().int().min(1).max(1e4).optional()}),b=v({name:`imports:reindex`,description:`Copy the aliased parts index into a new physical index built with the current mapping, then atomically swap the alias onto it.`,schema:y,defaultRetries:0}),x=[`pending`,`running`];async function S(e){let t=e.getTable();return e.count({where:p(t.status,[...x])})}function C(e){let t=/^(.*)_v(\d+)$/.exec(e);if(!t)return null;let[,n,r]=t;if(n===void 0||r===void 0)return null;let i=Number.parseInt(r,10)+1;return Number.isSafeInteger(i)?`${n}_v${i}`:null}function w(e){let{esClient:t,esIndex:n,indexConfig:r,importRuns:i,logger:a}=e;return async e=>{let o=a?.child({jobId:e.id,type:`imports:reindex`});if(r===void 0)throw Error(`imports:reindex requires imports({ indexConfig }) β€” the destination index must be created with the settings + mappings this app intends, otherwise Elasticsearch auto-creates it with inferred text mappings and the reindex silently discards the mapping change it exists to ship. Pass your app's index config (for the parts catalog: partsIndexConfig from @murumets-ee/search-elasticsearch).`);let s=y.parse(e.payload);if(i!==void 0){let e=await S(i);if(e>0)throw Error(`imports:reindex: ${e} feed import(s) are pending or running. An import writes through the alias "${n}", which points at the SOURCE index for the whole copy, so anything it writes now would be lost at the swap. Wait for them to finish (or cancel them) and re-run.`)}let c=await t(),l=Object.keys(await g(c,n)).sort();if(l.length>1)throw Error(`imports:reindex: alias "${n}" points at ${l.length} indices (${l.join(`, `)}). Reindexing would copy only one of them and then swap, leaving the alias on a mix of stale and fresh data. Resolve the alias to a single index first, then re-run. An interrupted reindex cannot cause this β€” swapAlias sends its remove with must_exist, so a stale swap fails instead of adding a second target. Look for a manual alias edit, another tool writing to this cluster, or a swap issued before that guard existed.`);let u=l[0];if(u===void 0)throw Error(`imports:reindex: alias "${n}" does not exist, so there is nothing to reindex. Run an import first β€” imports({ ensureIndex }) bootstraps the alias on the import path.`);let d=s.toIndex??C(u);if(d===null)throw Error(`imports:reindex: alias "${n}" points at "${u}", which does not follow the "<name>_v<N>" convention, so the next version cannot be derived. Pass an explicit destination (\`lumi imports:reindex --to <index>\`).`);let f=d;if(f===u)throw Error(`imports:reindex: destination "${f}" is the index the alias already points at. Reindexing an index onto itself would copy every document over itself and swap the alias onto where it already is. Pass a different --to.`);let p=await c.indices.exists({index:f});if(p&&s.allowExisting!==!0)throw Error(`imports:reindex: destination "${f}" already exists. If it is debris from a failed run, re-run with --resume to continue into it (bulkUpsert is idempotent by _id, so already-copied documents are simply overwritten); if it was created by hand with a different mapping, delete it or pass --to <another-index> instead. Refusing to reuse it silently, because doing so would apply ITS mapping rather than the one you changed.`);e.updateProgress({phase:p?`resuming`:`creating`,fromIndex:u,toIndex:f,processed:0,total:0}),p?o?.warn({fromIndex:u,toIndex:f},`imports:reindex: resuming into an existing destination index (--resume); its EXISTING mapping applies, not indexConfig`):(o?.info({fromIndex:u,toIndex:f},`imports:reindex: creating destination index`),await m(c,{name:f,config:r})),o?.info({fromIndex:u,toIndex:f},`imports:reindex: copying documents`);let v=await _({client:c,alias:n,fromIndex:u,toIndex:f,refreshOnCompletion:!0,...s.batchSize!==void 0&&{batchSize:s.batchSize},...i!==void 0&&{beforeSwap:async()=>{let e=await S(i);if(e>0)throw Error(`imports:reindex: ${e} feed import(s) started while the copy was running. Their documents went to the source index through the alias and are NOT in "${f}", so swapping now would drop them. The alias is untouched and "${f}" is left in place β€” wait for the import(s), then re-run with --resume to finish.`)}},reportProgress:async({processed:t,total:n})=>{e.updateProgress({phase:`copying`,fromIndex:u,toIndex:f,processed:t,total:n})}});e.updateProgress({phase:`swapped`,fromIndex:u,toIndex:f,processed:v.processed,total:v.processed+v.skipped,skipped:v.skipped}),o?.info({fromIndex:u,toIndex:f,processed:v.processed,skipped:v.skipped},`imports:reindex: alias swapped onto destination`),s.dropOld===!0&&(await h(c,u),o?.info({fromIndex:u},`imports:reindex: dropped source index (--drop-old)`))}}const T=Symbol.for(`@murumets-ee/imports:dead-listener-unsubscribe`);function E(f){let p=f.esIndex,m=f.storageBucket===null?null:{bucket:f.storageBucket??`lumi-imports`,orphanTtlHours:f.orphanUploadTtlHours??2,processedRetentionDays:f.processedRetentionDays??7};return f.storage&&r(f.storage),d({name:`@murumets-ee/imports`,server:{entities:[n,t],init:async t=>{let r=e();if(r.has(`commerce:mapping`)||r.register(s,o),r.has(`commerce:carmaker-feed`)||r.register(a,i),!t.plugins.all().some(e=>e.name===`@murumets-ee/queue`)){t.logger.warn(`imports: queue() plugin not in plugins array β€” imports:run jobs will not be processed`);return}let d=await import(`@murumets-ee/queue/client`),h=t.getClient(n);d.registerJob(u,l({importRuns:h,transforms:r,esClient:f.esClient,esIndex:p,...f.ensureIndex!==void 0&&{ensureIndex:f.ensureIndex},...f.resolveFilePath!==void 0&&{resolveFilePath:f.resolveFilePath},...f.pairSink!==void 0&&{pairSink:f.pairSink},logger:t.logger.child({pkg:`imports`})})),d.registerJob(b,w({esClient:f.esClient,esIndex:p,importRuns:h,...f.indexConfig!==void 0&&{indexConfig:f.indexConfig},logger:t.logger.child({pkg:`imports`})}));let g=globalThis[T];g&&g();let _=d.addQueueTerminalListener(c({importRuns:h,logger:t.logger.child({pkg:`imports`})}));if(globalThis[T]=_,m!==null){let{cleanupOrphanedImports:e,cleanupProcessedImports:n}=await import(`./cleanup-DDljBe0Z.mjs`).then(e=>e.r),{runAsCli:r}=await import(`@murumets-ee/core`),i=t.logger.child({pkg:`imports`,job:`cleanup`});d.registerJob(d.defineJob({name:`imports:cleanup-orphaned-uploads`,description:`Delete toolkit_files rows in the imports bucket with no matching import_run reference and createdAt older than the configured TTL.`,schedule:`@every 1h`}),async()=>{await r(()=>e({app:t,bucket:m.bucket,ttlHours:m.orphanTtlHours,logger:i}))}),d.registerJob(d.defineJob({name:`imports:cleanup-processed-uploads`,description:`Delete toolkit_files rows for import_runs in terminal status (succeeded/failed/cancelled) whose finishedAt is older than the configured retention window. The import_run row itself is preserved.`,schedule:`@every 1h`}),async()=>{await r(()=>n({app:t,bucket:m.bucket,retentionDays:m.processedRetentionDays,logger:i}))})}t.logger.info({esIndex:p,cleanup:m===null?{enabled:!1}:{enabled:!0,...m}},`Imports plugin initialized`)}}})}export{E as imports};
2
+ //# sourceMappingURL=plugin.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.mjs","names":[],"sources":["../src/reindex-job.ts","../src/plugin.ts"],"sourcesContent":["/**\n * Queue handler for `imports:reindex` β€” the OPERATOR ENTRY POINT for the\n * alias-versioned reindex (PLAN-ECOMMERCE D6).\n *\n * `@murumets-ee/search-elasticsearch` has shipped `createIndex` β†’ `reindex` β†’\n * `swapAlias` since commerce-demo PR1, and until now nothing could invoke them\n * on a running box: `reindex()` was exported, unit-tested, and had zero callers\n * outside its own test file. That is not a cosmetic gap. `ensureAliasedIndex`\n * returns the moment the alias resolves and NEVER issues a `put_mapping`, so\n * editing `partsIndexConfig` has no effect whatsoever on a cluster that has\n * already been bootstrapped β€” which makes every future mapping change\n * unshippable until this job exists. commerce-launch PR 13 hit exactly that\n * constraint and routed around it (reading `supplier.leadTimeDaysDefault` live\n * rather than denormalising it into the doc).\n *\n * **Why a queue job and not a CLI command that does the work itself.** The ES\n * client is APP-level wiring (`apps/<app>/lib/parts-search.ts`), injected into this\n * plugin as `imports({ esClient })`. `@murumets-ee/cli` has no Elasticsearch\n * dependency and should not grow one for a parts-shaped command. So the CLI\n * enqueues by job NAME (`lumi imports:reindex`) exactly as `lumi paths:rebuild`\n * enqueues `content:paths-rebuild`, and the worker β€” which already holds the\n * client β€” does the work. The job also shows up in the queue admin page with\n * live progress, for free.\n *\n * **Safety contract**, inherited from `reindex()` and extended here:\n * - The destination is created explicitly with the app-supplied\n * {@link ImportsPluginOptions.indexConfig}, so the new mapping is what\n * actually lands. Reindexing into an auto-created index would silently\n * defeat the entire point.\n * - The alias is swapped ONLY when every document that could be copied WAS\n * copied. A bulk failure leaves the alias pointing at the source, so the live\n * read target is never half-built. Note the exact shape: `reindex()` also\n * counts `skipped` hits (a source document with no `_id` or no `_source`) and\n * those do NOT block the swap β€” so this job surfaces the count in its\n * progress blob and the CLI prints it, because a silent skip plus\n * `--drop-old` is how you lose documents and are told it succeeded.\n * - ⚠️ **The job cannot be interrupted once it starts.** `JobContext` carries\n * no `AbortSignal`, so the queue admin's \"cancel\" only flips the ROW to\n * `dead` β€” the handler runs to completion and still swaps the alias (and\n * still drops the source, if `--drop-old`). Treat the enqueue as the\n * point of no return, not the poll.\n * - A pre-existing destination is REFUSED unless `allowExisting` is set. The\n * resume case is real (`bulkUpsert` is idempotent by `_id`, so re-running\n * into a partly-filled destination is correct and cheap), but it must be an\n * explicit operator decision β€” silently reusing an index somebody created by\n * hand, with who-knows-what mapping, is how a mapping change gets lost.\n * - The OLD index is never dropped automatically. `dropOld` exists, defaults\n * off, and the confidence window is the operator's call.\n * - ⚠️ **Documents written to the SOURCE while the copy runs are LOST at the\n * swap.** The alias still points at the source throughout, so a concurrent\n * `imports:run` writes there, and a page this job already read is never\n * re-read.\n *\n * GUARDED, NOT SOLVED. The job refuses to start while any `import_run` is\n * `pending` or `running`, and refuses to swap if one appears during the copy\n * (`beforeSwap`) β€” which covers the realistic case, an operator running both\n * at once. It does NOT close the window: a write landing between the final\n * check and the swap is still lost, as is one that landed on a page already\n * copied. Closing it properly means dual-writing during the copy;\n * `django-elasticsearch-dsl` documents the identical hole in its own\n * alias-swap path rather than solving it. The guard needs `importRuns`\n * wired β€” without it nothing stands between an import and this race.\n *\n * That last one is a DELIBERATE deviation from prior art, so it is worth the\n * sentence: searchkick, django-elasticsearch-dsl and Elastic's own runbook all\n * delete the old index by default (retention is the opt-in flag). They can,\n * because their reindex rebuilds from the system of record β€” a Rails model, a\n * Django queryset β€” so the old index is a derived artifact that can always be\n * regenerated. Ours copies index β†’ index. The source index IS the only copy of\n * pre-swap state, so dropping it by default would make a bad mapping\n * discovered after the swap unrecoverable, when keeping it makes recovery a\n * single `swapAlias` back. It also matches the D6 contract already written on\n * `reindex()`: \"caller decides when to dropIndex(fromIndex) after a confidence\n * window\".\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { defineJob, type JobDefinition } from '@murumets-ee/queue/client'\nimport {\n createIndex,\n dropIndex,\n type IndexConfig,\n readAliasTargets,\n reindex,\n} from '@murumets-ee/search-elasticsearch'\nimport { inArray } from 'drizzle-orm'\nimport type { PgColumn } from 'drizzle-orm/pg-core'\nimport { z } from 'zod'\nimport type { ImportRunClient } from './entities/import-run.js'\nimport type { EsClientResolver } from './worker.js'\n\n/**\n * Payload schema. Every field is optional β€” the common invocation is\n * `lumi imports:reindex` with no flags, which reads the alias, derives\n * `<alias>_v<N+1>`, and copies.\n */\nexport const importsReindexJobPayloadSchema = z.object({\n /**\n * Destination physical index. Omit to derive `<alias>_v<N+1>` from whatever\n * the alias currently points at. Pass explicitly when the current physical\n * index does not follow the `_v<N>` convention, or to reindex into a name of\n * your own choosing.\n */\n toIndex: z.string().min(1).optional(),\n /**\n * Continue into a destination index that already exists. Off by default: an\n * existing destination is normally the debris of a failed run, and reusing it\n * blind would apply whatever mapping it was created with rather than the one\n * you just changed.\n */\n allowExisting: z.boolean().optional(),\n /** Drop the source index after a successful swap. Off by default. */\n dropOld: z.boolean().optional(),\n /** Documents per copy batch. Defaults to `reindex()`'s own default (1000). */\n batchSize: z.number().int().min(1).max(10_000).optional(),\n})\nexport type ImportsReindexJobPayload = z.infer<typeof importsReindexJobPayloadSchema>\n\n/**\n * Progress blob written to `toolkit_jobs.progress`. Small and fixed-shape β€” the\n * queue caps the blob at ~7 KB and silently DROPS anything larger, so this\n * carries counters and index names only.\n */\nexport interface ImportsReindexProgress {\n phase: 'creating' | 'resuming' | 'copying' | 'swapped'\n fromIndex: string\n toIndex: string\n processed: number\n total: number\n /**\n * Source hits `reindex()` could not copy (missing `_id` or `_source`). Carried\n * here rather than left in the worker log because it does NOT block the swap:\n * without it the CLI would report a clean success over an index that is\n * missing rows, and `--drop-old` would then delete the only copy of them.\n */\n skipped?: number\n}\n\n/**\n * Job definition. Registered by `imports()` in `plugin.ts`.\n *\n * `defaultRetries: 0` β€” a reindex is a deliberate operator action over a large\n * index, and an automatic retry would race the run it is retrying (both writing\n * the same destination, both racing to swap). The operator re-runs, which is\n * safe by design: `bulkUpsert` is idempotent by `_id`, so a re-run with\n * `allowExisting` resumes rather than duplicates.\n *\n * ⚠️ **This field does NOT bind a caller that enqueues by NAME.**\n * `QueueClient.enqueue` reads `defaultRetries` off this OBJECT, and the only\n * shipped caller β€” `lumi imports:reindex` β€” enqueues by string, because this\n * module sits behind the queue client that the CLI keeps off its load graph. It\n * therefore passes `{ maxRetries: 0 }` explicitly (`REINDEX_ENQUEUE_OPTIONS` in\n * `@murumets-ee/cli`), and any FUTURE by-name caller must do the same or\n * silently get 3 retries β€” reproducing the exact failure this setting exists to\n * prevent, with the real cause hidden behind an \"already exists\" `lastError`\n * from a bounced retry.\n */\nexport const importsReindexJob: JobDefinition<ImportsReindexJobPayload> = defineJob({\n name: 'imports:reindex',\n description:\n 'Copy the aliased parts index into a new physical index built with the current mapping, then atomically swap the alias onto it.',\n schema: importsReindexJobPayloadSchema,\n defaultRetries: 0,\n})\n\n/** Structural subset of `JobContext` this handler reads β€” mirrors `ImportsRunJobContext`. */\nexport interface ImportsReindexJobContext {\n id: string\n payload: ImportsReindexJobPayload\n updateProgress(data: ImportsReindexProgress): void\n}\n\nexport interface ReindexHandlerConfig {\n /** Resolver for the ES client. */\n esClient: EsClientResolver\n /** The alias to reindex. Same value the import path writes to. */\n esIndex: string\n /**\n * Settings + mappings the DESTINATION index is created with. Without it there\n * is no way to apply a mapping change, so the handler refuses to run rather\n * than copy into a default-mapped index.\n */\n indexConfig?: IndexConfig\n /**\n * AdminClient over `import_run`, used to refuse a reindex while a feed import\n * is in flight. Optional so a consumer without the entity wired still gets a\n * working reindex β€” but omitting it removes the ONLY guard against the\n * lost-writes race described in the safety contract.\n */\n importRuns?: ImportRunClient\n /** Optional structured logger. Defaults to silent. */\n logger?: Logger\n}\n\n/** Statuses that mean a feed import is writing, or is about to. */\nconst ACTIVE_IMPORT_STATUSES = ['pending', 'running'] as const\n\n/**\n * Count `import_run` rows that are writing or about to write.\n *\n * A feed import bulk-writes THROUGH THE ALIAS, which points at the source for\n * the whole copy β€” so its documents land in the index we are replacing and are\n * never copied forward. `pending` counts as active because a queued run can\n * start mid-copy.\n */\nasync function countActiveImports(importRuns: ImportRunClient): Promise<number> {\n // `getTable()` returns `PgTableWithColumns<any>`; narrow just the column we\n // touch so `inArray()` and type-coverage both see a typed value. Same shape\n // the dead-listener in `worker.ts` uses.\n const table = importRuns.getTable() as unknown as { status: PgColumn }\n return importRuns.count({ where: inArray(table.status, [...ACTIVE_IMPORT_STATUSES]) })\n}\n\n/** `<base>_v<N>` β†’ `<base>_v<N+1>`. Returns null when the name doesn't follow the convention. */\nexport function nextVersionedIndexName(current: string): string | null {\n const match = /^(.*)_v(\\d+)$/.exec(current)\n if (!match) return null\n const [, base, version] = match\n if (base === undefined || version === undefined) return null\n const next = Number.parseInt(version, 10) + 1\n if (!Number.isSafeInteger(next)) return null\n return `${base}_v${next}`\n}\n\n/**\n * Build the `JobHandler` for {@link importsReindexJob}.\n *\n * Deliberately NOT wrapped in `runAsCli`, unlike `createRunImportHandler`. That\n * wrapper is a privilege grant (`checker: () => true`, `groups: ['admin']`) and\n * this handler performs no entity operation at all β€” it only talks to\n * Elasticsearch. Per CLAUDE.md's \"reach is not authority\", acquiring an admin\n * identity for a path that never uses one is exactly the habit that makes the\n * elevation allowlist meaningless. If a future change here needs an\n * `AdminClient`, add the wrapper then, with the reason.\n */\nexport function createReindexHandler(\n config: ReindexHandlerConfig,\n): (job: ImportsReindexJobContext) => Promise<void> {\n const { esClient, esIndex, indexConfig, importRuns, logger } = config\n\n return async (job: ImportsReindexJobContext): Promise<void> => {\n const log = logger?.child({ jobId: job.id, type: 'imports:reindex' })\n\n if (indexConfig === undefined) {\n throw new Error(\n `imports:reindex requires imports({ indexConfig }) β€” the destination index must be ` +\n `created with the settings + mappings this app intends, otherwise Elasticsearch ` +\n `auto-creates it with inferred text mappings and the reindex silently discards the ` +\n `mapping change it exists to ship. Pass your app's index config (for the parts ` +\n `catalog: partsIndexConfig from @murumets-ee/search-elasticsearch).`,\n )\n }\n\n // Validate the payload HERE, not at enqueue. The job's Zod schema is\n // applied by `QueueClient.enqueue` only for the `defineJob`-object form,\n // and the CLI enqueues by NAME (the definition sits behind the queue\n // client, which the CLI keeps off its load graph) β€” so without this parse\n // the schema is decorative and `batchSize` is unbounded on the worker\n // side. `content:paths-rebuild` parses in its handler for the same reason.\n //\n // Ordered AFTER the `indexConfig` check on purpose: a misconfigured app\n // should read \"pass imports({ indexConfig })\", not a multi-line ZodError\n // dump, and the CLI is the only thing that produces payloads anyway.\n const payload = importsReindexJobPayloadSchema.parse(job.payload)\n\n // Refuse to START while a feed import is in flight. An import writes\n // THROUGH the alias, which points at the source for the whole copy, so its\n // documents land in the index being replaced and are never copied forward β€”\n // the swap would silently drop them. Checked here so the operator is told\n // before minutes of copying, and again just before the swap for a run that\n // started in between.\n if (importRuns !== undefined) {\n const active = await countActiveImports(importRuns)\n if (active > 0) {\n throw new Error(\n `imports:reindex: ${active} feed import(s) are pending or running. An import writes ` +\n `through the alias \"${esIndex}\", which points at the SOURCE index for the whole copy, ` +\n `so anything it writes now would be lost at the swap. Wait for them to finish (or ` +\n `cancel them) and re-run.`,\n )\n }\n }\n\n const client = await esClient()\n\n // An alias may legitimately point at MORE than one physical index (that is\n // how a rolling reindex looks mid-flight). `readAliasIndex` collapses that\n // to a single name, so proceeding would copy only one of them, then swap β€”\n // leaving the alias on {untouched sibling + new index} and quietly serving\n // a union of stale and fresh documents, with `--drop-old` deleting only\n // the one that was read. Refuse, and name what we found.\n const aliasTargets = Object.keys(await readAliasTargets(client, esIndex)).sort()\n if (aliasTargets.length > 1) {\n throw new Error(\n `imports:reindex: alias \"${esIndex}\" points at ${aliasTargets.length} indices ` +\n `(${aliasTargets.join(', ')}). Reindexing would copy only one of them and then ` +\n `swap, leaving the alias on a mix of stale and fresh data. Resolve the alias to a ` +\n `single index first, then re-run. An interrupted reindex cannot cause this β€” ` +\n `swapAlias sends its remove with must_exist, so a stale swap fails instead of ` +\n `adding a second target. Look for a manual alias edit, another tool writing to this ` +\n `cluster, or a swap issued before that guard existed.`,\n )\n }\n\n // Taken from the SAME read as the guard above, not a second `getAlias`. Two\n // round trips would leave a window in which a target added between them\n // passes the guard and is then silently collapsed by `readAliasIndex`'s\n // tiebreak β€” the guard defeated by the very state it exists to refuse.\n const fromIndex = aliasTargets[0]\n if (fromIndex === undefined) {\n throw new Error(\n `imports:reindex: alias \"${esIndex}\" does not exist, so there is nothing to reindex. ` +\n `Run an import first β€” imports({ ensureIndex }) bootstraps the alias on the import path.`,\n )\n }\n\n const derived = payload.toIndex ?? nextVersionedIndexName(fromIndex)\n if (derived === null) {\n throw new Error(\n `imports:reindex: alias \"${esIndex}\" points at \"${fromIndex}\", which does not follow the ` +\n `\"<name>_v<N>\" convention, so the next version cannot be derived. Pass an explicit ` +\n `destination (\\`lumi imports:reindex --to <index>\\`).`,\n )\n }\n const toIndex = derived\n\n if (toIndex === fromIndex) {\n throw new Error(\n `imports:reindex: destination \"${toIndex}\" is the index the alias already points at. ` +\n `Reindexing an index onto itself would copy every document over itself and swap the ` +\n `alias onto where it already is. Pass a different --to.`,\n )\n }\n\n const destExists = await client.indices.exists({ index: toIndex })\n if (destExists && payload.allowExisting !== true) {\n throw new Error(\n `imports:reindex: destination \"${toIndex}\" already exists. If it is debris from a failed ` +\n `run, re-run with --resume to continue into it (bulkUpsert is idempotent by _id, so ` +\n `already-copied documents are simply overwritten); if it was created by hand with a ` +\n `different mapping, delete it or pass --to <another-index> instead. Refusing to reuse ` +\n `it silently, because doing so would apply ITS mapping rather than the one you changed.`,\n )\n }\n\n // Distinct phases, because they are materially different operations and\n // the operator can only see the progress blob. A `--resume` reuses an\n // index somebody else created, so `indexConfig` is NOT applied β€” and if\n // the reason for the reindex was a mapping change, that means it silently\n // does not ship. Saying so in the worker log alone would be saying it\n // where the person running the command cannot read it.\n job.updateProgress({\n phase: destExists ? 'resuming' : 'creating',\n fromIndex,\n toIndex,\n processed: 0,\n total: 0,\n })\n\n if (!destExists) {\n log?.info({ fromIndex, toIndex }, 'imports:reindex: creating destination index')\n await createIndex(client, { name: toIndex, config: indexConfig })\n } else {\n log?.warn(\n { fromIndex, toIndex },\n 'imports:reindex: resuming into an existing destination index (--resume); its EXISTING mapping applies, not indexConfig',\n )\n }\n\n log?.info({ fromIndex, toIndex }, 'imports:reindex: copying documents')\n const result = await reindex({\n client,\n alias: esIndex,\n fromIndex,\n toIndex,\n // ONE refresh before the swap. NOT `refresh: 'wait_for'`, which is the\n // obvious-looking choice and is a trap: it blocks until the next\n // SCHEDULED refresh, per batch, and the parts index sets\n // `refresh_interval: '30s'` β€” hours of waiting for a large catalogue,\n // to achieve what one final refresh achieves in milliseconds.\n refreshOnCompletion: true,\n ...(payload.batchSize !== undefined && { batchSize: payload.batchSize }),\n // Re-check immediately before the swap: an import that STARTED during the\n // copy wrote to the source and is not in the destination. Throwing here\n // leaves the alias untouched and the destination in place, so `--resume`\n // can finish the job once the import has.\n //\n // ⚠️ Narrows the race, does not close it. A write landing between this\n // check and the swap is still lost, and so is one that landed on a page\n // already copied. Closing it properly needs dual-writes during the copy.\n ...(importRuns !== undefined && {\n beforeSwap: async () => {\n const active = await countActiveImports(importRuns)\n if (active > 0) {\n throw new Error(\n `imports:reindex: ${active} feed import(s) started while the copy was running. ` +\n `Their documents went to the source index through the alias and are NOT in ` +\n `\"${toIndex}\", so swapping now would drop them. The alias is untouched and ` +\n `\"${toIndex}\" is left in place β€” wait for the import(s), then re-run with ` +\n `--resume to finish.`,\n )\n }\n },\n }),\n reportProgress: async ({ processed, total }) => {\n job.updateProgress({ phase: 'copying', fromIndex, toIndex, processed, total })\n },\n })\n\n job.updateProgress({\n phase: 'swapped',\n fromIndex,\n toIndex,\n processed: result.processed,\n total: result.processed + result.skipped,\n skipped: result.skipped,\n })\n log?.info(\n { fromIndex, toIndex, processed: result.processed, skipped: result.skipped },\n 'imports:reindex: alias swapped onto destination',\n )\n\n if (payload.dropOld === true) {\n await dropIndex(client, fromIndex)\n log?.info({ fromIndex }, 'imports:reindex: dropped source index (--drop-old)')\n }\n }\n}\n","/**\n * Imports plugin β€” registers the `import_run` entity and (when ES + queue\n * are wired) registers the `imports:run` and `imports:reindex` job handlers.\n *\n * Per PLAN-ECOMMERCE.md PR 7 (PoC scope): plumbing only. The bespoke\n * admin pages (upload form, parts search) live in PR 8a.\n *\n * **Built-in transforms register HERE, at plugin init.** Both transforms\n * this package ships (`commerce:mapping`, `commerce:carmaker-feed`) go\n * into the process-global registry inside `init`, so every process that\n * boots the plugin β€” Next.js web server, standalone queue worker β€” can\n * dispatch them with zero app-side wiring. Registration used to be the\n * app's job (`lib/app.ts` calling `registry.register(...)`), which is\n * exactly the drift foot-gun CLAUDE.md's \"no forgotten registrations\"\n * rule warns about: an app scaffolded before the mapping transform\n * existed keeps its old `lib/app.ts` through `pnpm up` toolkit upgrades,\n * and every mapping-driven run then dies in the worker with\n * `No transform registered for name \"commerce:mapping\"`. App-side\n * registration remains harmless even when unguarded β€”\n * `registerImportTransform` overwrites last-wins instead of throwing β€”\n * it is just no longer required.\n *\n * @example\n * ```ts\n * import { defineLumiConfig } from '@murumets-ee/core'\n * import { imports } from '@murumets-ee/imports/plugin'\n * import { Client } from '@elastic/elasticsearch'\n *\n * const es = new Client({ node: process.env.ES_URL })\n *\n * export default defineLumiConfig({\n * plugins: [\n * // queue() must be present too β€” it runs the imports:run jobs.\n * queue(),\n * imports({ esClient: () => es, esIndex: 'parts', indexConfig: partsIndexConfig }),\n * ],\n * })\n * ```\n */\n\nimport { definePlugin } from '@murumets-ee/core'\nimport type { IndexConfig } from '@murumets-ee/search-elasticsearch'\n// **Why no static `@murumets-ee/core/clients` import in this file.**\n//\n// `@murumets-ee/core/clients` begins with `import 'server-only'`, which\n// throws when this plugin module is loaded at `lumi.config.ts`\n// evaluation time by the CLI (`lumi migrate`/`seed`/`doctor` use jiti,\n// which doesn't apply the `react-server` export condition).\n// Static-importing would propagate that throw all the way through\n// `lumi.config.ts` β†’ CLI startup, blocking every CLI invocation.\n//\n// **Today (after PLAN-DECLARATIVE-PLUGINS PR 2):** plugin `init`\n// reaches `AdminClient` via the framework-provided `app.getClient(\n// entity)` accessor β€” no `createAdminClient` call, no dynamic import\n// either. The remaining `@murumets-ee/core/clients` dependency lives\n// in `./admin/cleanup.js`, which IS still dynamic-imported inside\n// `init` and which still benefits from this rationale. The pattern\n// matches `getDb()` in `@murumets-ee/queue/admin.ts`.\nimport { ImportMapping } from './entities/import-mapping.js'\nimport { ImportRun } from './entities/import-run.js'\nimport { MAPPING_TRANSFORM_NAME, mappingTransform } from './mapping/mapping-transform.js'\nimport { createReindexHandler, importsReindexJob } from './reindex-job.js'\nimport { type ImportsStorageFactory, registerImportsStorageFactory } from './storage.js'\nimport { getTransformRegistry } from './transform.js'\nimport { CARMAKER_FEED_TRANSFORM_NAME, carmakerFeedTransform } from './transforms/carmaker-feed.js'\nimport {\n createImportsRunDeadListener,\n createRunImportHandler,\n type EnsureIndexResolver,\n type EsClientResolver,\n type FilePathResolver,\n importsRunJob,\n type PairSink,\n} from './worker.js'\n\n/**\n * `Symbol.for`-keyed slot for the active dead-listener unsubscribe\n * handle. Symbol.for so an HMR-replaced module instance still finds\n * the previous unsubscribe (`Symbol`-by-reference would skip the\n * lookup across module-evaluation boundaries). Same pattern as\n * `transform.ts`'s registry slot and `storage.ts`'s factory slot.\n */\nconst IMPORTS_DEAD_LISTENER_KEY = Symbol.for('@murumets-ee/imports:dead-listener-unsubscribe')\n\ninterface GlobalThisWithUnsubscribe {\n [IMPORTS_DEAD_LISTENER_KEY]?: () => void\n}\n\nexport interface ImportsPluginOptions {\n /**\n * Elasticsearch client resolver. Lazy so consumers can construct\n * the client inside a route initialiser instead of at plugin-init\n * time. Required β€” without it, the worker can't bulk-write.\n */\n esClient: EsClientResolver\n /**\n * ES index alias to write to. Per D6 always pass an ALIAS, never a physical\n * index β€” that is what makes {@link importsReindexJob}'s atomic swap possible.\n *\n * **Required, deliberately.** It defaulted to `'parts'` until #665: two apps\n * sharing one Elasticsearch cluster both took that default and wrote the same\n * physical index, so staging's 858k-row Ford import surfaced in production's\n * parts search. The pod workaround was to set the alias per deployment β€” but\n * a DEFAULT here means an app can set `PARTS_INDEX_ALIAS`, wire it into the\n * read path, forget this option, and have its reads and writes silently name\n * different indices. That is the same defect one level down, and it fails\n * SILENTLY. Making the option required turns it into a compile error instead.\n *\n * Pass the SAME value the search provider's `indexAlias` uses; the app's\n * `lib/parts-search.ts` exports one `partsIndexAlias` const for exactly this.\n */\n esIndex: string\n /**\n * Optional bootstrap for the destination index/alias, run once per import\n * job before any bulk-write (see {@link EnsureIndexResolver}). Wire your\n * app's `ensureAliasedIndex`-backed helper here so the worker can never\n * auto-create a mis-mapped physical index β€” WITHOUT gating app boot on ES.\n *\n * Omit only when the index is bootstrapped out-of-band; without it a\n * first-ever import against an unbootstrapped alias lets ES auto-create a\n * `text`-mapped physical index, breaking aggregations (issue #610).\n */\n ensureIndex?: EnsureIndexResolver\n /**\n * Settings + mappings the `imports:reindex` job creates its DESTINATION index\n * with. Pass the same config `ensureIndex` bootstraps the alias from (for the\n * parts catalog: `partsIndexConfig` from `@murumets-ee/search-elasticsearch`).\n *\n * Omit it and the job still registers, but refuses to run with an actionable\n * error β€” a reindex into an index Elasticsearch auto-created with inferred\n * `text` mappings would silently discard the mapping change the reindex\n * exists to ship, which is a worse outcome than not running.\n *\n * This is what makes a mapping change deployable at all: `ensureAliasedIndex`\n * returns as soon as the alias resolves and never issues a `put_mapping`, so\n * on an already-bootstrapped cluster, editing the mapping config has no\n * effect whatsoever without a reindex.\n */\n indexConfig?: IndexConfig\n /**\n * Resolve `import_run.filePath` to a local FS path before streaming.\n * **Required when uploads land in remote storage** (R2/S3/etc.) β€”\n * without it, the worker hands the storage key to `createReadStream`\n * and crashes with `ENOENT`.\n *\n * Typical wiring downloads the storage object to a tmpfile and\n * returns its path; the optional `cleanup` callback runs after the\n * run finishes (success or failure).\n *\n * Omit this option for the original on-disk PoC setup where the\n * upload route writes directly to a local directory and persists\n * the absolute path on `import_run.filePath`.\n */\n resolveFilePath?: FilePathResolver\n /**\n * Optional consumer for the directional supersession pairs the runner harvests as\n * a side-output (commerce-demo PR6, SD007). The app composes it β€” commerce exports\n * the replacement-merge sink and passes it here, same injection shape as\n * {@link esClient} / {@link resolveFilePath}. Omit when not ingesting replacement\n * codes; the pairs are then discarded after the run.\n */\n pairSink?: PairSink\n /**\n * Optional dedicated `StorageClient` factory for imports. When\n * provided, the upload route (in `@murumets-ee/commerce`) and the\n * worker resolver consult this client instead of the global\n * `getStorageConfig()` default β€” so a deployment can pin imports\n * to a local-disk adapter (single-VPS / dev) while media,\n * ticketing attachments, and the rest of the app keep using the\n * default R2 (or S3) adapter.\n *\n * Lazy / async so consumers can defer adapter construction until\n * the first import β€” useful when the local-disk root is\n * environment-dependent or when the factory needs `getApp()` to\n * have resolved.\n *\n * Omit to keep the legacy single-storage behaviour (everything on\n * the global default).\n */\n storage?: ImportsStorageFactory\n /**\n * Bucket name to scope the orphan-cleanup queue job. Rows in\n * `toolkit_files` with this bucket value AND no matching\n * `import_run.filePath` AND `createdAt < cutoff` get garbage-\n * collected on each cleanup tick. Defaults to `'lumi-imports'` β€”\n * the convention `apps/admin/lib/imports-storage.ts`\n * uses by default. Override if your deployment pins a different\n * bucket name via `IMPORTS_STORAGE_BUCKET` or equivalent.\n *\n * Set to `null` to DISABLE the cleanup job entirely (e.g. for\n * deployments that handle their own retention via S3 lifecycle\n * rules). Disabling without an alternative will leak storage\n * over time as failed uploads accumulate.\n */\n storageBucket?: string | null\n /**\n * Hours after which an unreferenced `toolkit_files` row in the\n * imports bucket is considered orphaned and deleted by the\n * cleanup job. Default 2h β€” long enough that a normal\n * upload-then-register round-trip never wipes a fresh upload,\n * short enough that storage waste from failed uploads doesn't\n * accumulate.\n *\n * The uploadβ†’register flow happens client-side automatically (no\n * \"operator clicks register\" step in the current UI), so the TTL\n * just needs to cover network blips + retries. Bumping the TTL\n * is safe if your operators commonly upload then wait before\n * processing.\n */\n orphanUploadTtlHours?: number\n /**\n * Days after which a terminal-status `import_run`'s source file is\n * deleted from `toolkit_files`. Default 7 days β€” gives operators a\n * reprocess window if a transform bug surfaces post-success, while\n * keeping storage costs bounded. Set to 0 for instant cleanup at\n * the next cleanup tick after `import_run.status` becomes terminal\n * (`succeeded` / `failed` / `cancelled`).\n *\n * The `import_run` row itself is preserved β€” the audit trail and\n * History panel still show the past run; only the source feed\n * file is removed.\n */\n processedRetentionDays?: number\n}\n\nexport function imports(options: ImportsPluginOptions) {\n const esIndex = options.esIndex\n // Resolve the cleanup config eagerly. `storageBucket === null` is the\n // explicit opt-out path; `undefined` falls back to the convention.\n // Two cleanup jobs share the same bucket but have independent TTLs:\n // orphans (no import_run ref) churn fast (2h); processed runs\n // (terminal status) get a longer reprocess window (7d).\n const cleanupConfig =\n options.storageBucket === null\n ? null\n : {\n bucket: options.storageBucket ?? 'lumi-imports',\n orphanTtlHours: options.orphanUploadTtlHours ?? 2,\n processedRetentionDays: options.processedRetentionDays ?? 7,\n }\n\n // Register the storage factory eagerly β€” runs at `imports()` factory\n // call time during `lumi.config.ts` evaluation, NOT inside the\n // `init` hook. The hook only fires at `createApp()` time (Next.js\n // request boot / worker boot), but the factory needs to be visible\n // to consumers that read it at module-load (e.g. the commerce\n // route's lazy `getStorageClient` thunk closes over a value that\n // resolves the moment a request comes in). Late registration in\n // `init` would race the first request.\n if (options.storage) {\n registerImportsStorageFactory(options.storage)\n }\n\n return definePlugin({\n name: '@murumets-ee/imports',\n server: {\n entities: [ImportRun, ImportMapping],\n init: async (app) => {\n // Built-in transforms β€” registered FIRST, before the queue-plugin\n // probe below, so the registry reflects this package's dispatch\n // capability even in queue-less processes (the admin Catalog tab\n // lists registry names). The `has()` guards make this idempotent\n // under dev HMR re-init AND let older scaffolds that still\n // self-register from `lib/app.ts` coexist (their registration is\n // also `has()`-guarded; whichever runs first wins β€” it's the same\n // function either way). See the module JSDoc for why app-side-only\n // registration was a drift foot-gun.\n //\n // Why imperative-in-init rather than a declarative `contributes`\n // slot (CLAUDE.md's default for contributions): these are this\n // package's OWN built-ins landing in this package's OWN\n // process-global registry β€” nothing crosses a plugin boundary, and\n // the registry is consumed at job-dispatch time, not at the\n // framework's merge step. A contributes slot buys cross-plugin\n // introspection we don't need at the cost of a core-visible slot\n // type for an imports-internal concern.\n const transformRegistry = getTransformRegistry()\n if (!transformRegistry.has(MAPPING_TRANSFORM_NAME)) {\n transformRegistry.register(MAPPING_TRANSFORM_NAME, mappingTransform)\n }\n if (!transformRegistry.has(CARMAKER_FEED_TRANSFORM_NAME)) {\n transformRegistry.register(CARMAKER_FEED_TRANSFORM_NAME, carmakerFeedTransform)\n }\n\n // Queue PACKAGE being importable doesn't mean the queue() PLUGIN\n // is in the consumer's plugins array. Without it, registerJob()\n // succeeds but no worker ever picks up the job. Probe and warn.\n const queuePluginPresent = app.plugins.all().some((p) => p.name === '@murumets-ee/queue')\n if (!queuePluginPresent) {\n app.logger.warn(\n 'imports: queue() plugin not in plugins array β€” imports:run jobs will not be processed',\n )\n return\n }\n\n // Queue client stays dynamic-imported: we already early-returned\n // above when the queue() plugin isn't in the consumer's plugins\n // array, so static-importing here would force-load the queue\n // client module in deployments that don't enable the worker.\n // `@murumets-ee/core/clients` is NO LONGER imported here β€”\n // `app.getClient(entity)` gives us a typed, app-bound\n // AdminClient without the F1+F2 foot-guns from\n // PLAN-DECLARATIVE-PLUGINS.md.\n const queueClientModule = await import('@murumets-ee/queue/client')\n\n const importRuns = app.getClient(ImportRun)\n\n queueClientModule.registerJob(\n importsRunJob,\n createRunImportHandler({\n importRuns,\n transforms: transformRegistry,\n esClient: options.esClient,\n esIndex,\n ...(options.ensureIndex !== undefined && { ensureIndex: options.ensureIndex }),\n ...(options.resolveFilePath !== undefined && {\n resolveFilePath: options.resolveFilePath,\n }),\n ...(options.pairSink !== undefined && { pairSink: options.pairSink }),\n logger: app.logger.child({ pkg: 'imports' }),\n }),\n )\n\n // The operator entry point for the alias-versioned reindex (D6).\n // Registered unconditionally: a missing `indexConfig` is reported by\n // the handler with an actionable message, which beats a job that\n // silently never exists and leaves `lumi imports:reindex` enqueuing\n // work no worker will ever claim.\n queueClientModule.registerJob(\n importsReindexJob,\n createReindexHandler({\n esClient: options.esClient,\n esIndex,\n // Lets the reindex refuse to run (and refuse to swap) while a feed\n // import is in flight β€” those writes go to the SOURCE through the\n // alias and would be dropped by the swap.\n importRuns,\n ...(options.indexConfig !== undefined && { indexConfig: options.indexConfig }),\n logger: app.logger.child({ pkg: 'imports' }),\n }),\n )\n\n // Subscribe to the queue's terminal-state event stream so a\n // worker that crashes mid-import β€” and whose `imports:run` job\n // ultimately reaches `dead` without the handler reaching its\n // own `markFailed` path β€” flips the mirror `import_run` row to\n // `failed`. This replaces what would otherwise be a per-domain\n // periodic sweep; the queue's terminal notifier is the generic\n // primitive (graphile-worker's `job:failed` event, BullMQ's\n // `failed` listener β€” same shape).\n //\n // The listener is multi-subscriber, so we coexist with the\n // notifications plugin's admin-email handler without either of\n // us clobbering the other. Filtering on `event.jobType` keeps\n // this listener cheap on jobs we don't own.\n //\n // **HMR**: each re-init of this `init` hook constructs a new\n // listener instance. The notifier registry stores listeners\n // by reference, so without explicit cleanup an HMR cycle would\n // STACK duplicate listeners β€” `findMany`+`update` per dead\n // event growing linearly with the number of HMR rounds. Stash\n // the unsubscribe on a globalThis Symbol-keyed slot (same\n // pattern as `transform.ts` / `storage.ts`) and call it before\n // re-subscribing so HMR is idempotent.\n const previousUnsubscribe = (globalThis as GlobalThisWithUnsubscribe)[\n IMPORTS_DEAD_LISTENER_KEY\n ]\n if (previousUnsubscribe) previousUnsubscribe()\n const unsubscribe = queueClientModule.addQueueTerminalListener(\n createImportsRunDeadListener({\n importRuns,\n logger: app.logger.child({ pkg: 'imports' }),\n }),\n )\n ;(globalThis as GlobalThisWithUnsubscribe)[IMPORTS_DEAD_LISTENER_KEY] = unsubscribe\n\n // Storage-cleanup jobs. Two passes, same bucket:\n // 1. Orphan sweep β€” uploads whose register handshake never\n // completed (no `import_run` reference). 2h TTL.\n // 2. Processed sweep β€” uploads whose `import_run` is terminal\n // (succeeded / failed / cancelled). 7-day reprocess\n // window then drop.\n // `defineJob({ schedule })` declares the cadence; the queue\n // worker reads the metadata at startup, materialises a\n // `toolkit_scheduled_jobs` row, and its cron loop fires the\n // registered handler each tick. No explicit\n // `client.schedule()` call needed β€” the worker owns the\n // schedule, not the handler. Same helper-signature shape as\n // ticketing's cleanup.\n if (cleanupConfig !== null) {\n const { cleanupOrphanedImports, cleanupProcessedImports } = await import(\n './admin/cleanup.js'\n )\n const { runAsCli } = await import('@murumets-ee/core')\n const cleanupLogger = app.logger.child({ pkg: 'imports', job: 'cleanup' })\n\n queueClientModule.registerJob(\n queueClientModule.defineJob({\n name: 'imports:cleanup-orphaned-uploads',\n description:\n 'Delete toolkit_files rows in the imports bucket with no matching import_run reference and createdAt older than the configured TTL.',\n schedule: '@every 1h',\n }),\n async () => {\n // `runAsCli` is load-bearing today: the queue worker's\n // handler context (see `packages/queue/src/handler-context.ts`)\n // tracks the job type but NOT a user / RequestContext.\n // Any AdminClient call reachable from the cleanup\n // helpers β€” currently `createAdminClient(ImportRun).getTable()`\n // for column-metadata resolution β€” runs without a user\n // unless we enter a CLI scope. The synthetic CLI user\n // is the right attribution for scheduled-job work\n // (matches ticketing's `cleanupOrphanedUploads` shape).\n await runAsCli(() =>\n cleanupOrphanedImports({\n app,\n bucket: cleanupConfig.bucket,\n ttlHours: cleanupConfig.orphanTtlHours,\n logger: cleanupLogger,\n }),\n )\n },\n )\n\n queueClientModule.registerJob(\n queueClientModule.defineJob({\n name: 'imports:cleanup-processed-uploads',\n description:\n 'Delete toolkit_files rows for import_runs in terminal status (succeeded/failed/cancelled) whose finishedAt is older than the configured retention window. The import_run row itself is preserved.',\n schedule: '@every 1h',\n }),\n async () => {\n await runAsCli(() =>\n cleanupProcessedImports({\n app,\n bucket: cleanupConfig.bucket,\n retentionDays: cleanupConfig.processedRetentionDays,\n logger: cleanupLogger,\n }),\n )\n },\n )\n }\n\n app.logger.info(\n {\n esIndex,\n // Stable shape regardless of enabled/disabled so structured-\n // log queries (`cleanup.enabled = false`) don't have to\n // handle a string fallback.\n cleanup:\n cleanupConfig === null ? { enabled: false } : { enabled: true, ...cleanupConfig },\n },\n 'Imports plugin initialized',\n )\n },\n },\n })\n}\n"],"mappings":"0mBAgGA,MAAa,EAAiC,EAAE,OAAO,CAOrD,QAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EAOpC,cAAe,EAAE,QAAQ,CAAC,CAAC,SAAS,EAEpC,QAAS,EAAE,QAAQ,CAAC,CAAC,SAAS,EAE9B,UAAW,EAAE,OAAO,CAAC,CAAC,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CAAc,CACpF,EACA,4BACF,CACF,CACF,CACF,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ import{createLogger as e}from"@murumets-ee/logging";const t={runCreated:`imports.run.created`,runStarted:`imports.run.started`,runSucceeded:`imports.run.succeeded`,runFailed:`imports.run.failed`},n=e({name:`imports:realtime`}),r={admin:!0};let i=null;function a(e,t){e instanceof Error&&e.name===`RealtimeOversizeError`?n.error({err:e,topic:t},`realtime publish failed β€” payload oversize`):n.warn({err:e,topic:t},`realtime publish failed β€” event dropped`)}function o(e,t){if(i){try{i({topic:e,payload:t,scope:r})}catch(t){a(t,e)}return}import(`@murumets-ee/core/realtime`).then(n=>{i=n.publishEvent,i({topic:e,payload:t,scope:r})}).catch(t=>{a(t,e)})}async function s(){i||=(await import(`@murumets-ee/core/realtime`)).publishEvent}function c(e,n){o(t.runCreated,{importRunId:e,...n.brandSlug!==void 0&&{brandSlug:n.brandSlug},...n.supplierDisplayName!==void 0&&{supplierDisplayName:n.supplierDisplayName},filename:n.filename})}function l(e){o(t.runStarted,{importRunId:e})}function u(e,n){o(t.runSucceeded,{importRunId:e,rowsRead:n.rowsRead,rowsSucceeded:n.rowsSucceeded,rowsFailed:n.rowsFailed})}function d(e,n){o(t.runFailed,{importRunId:e,reason:n})}export{u as a,l as i,c as n,t as o,d as r,s as t};
2
+ //# sourceMappingURL=publish-DCXIPwTE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publish-DCXIPwTE.mjs","names":[],"sources":["../src/realtime/topics.ts","../src/realtime/publish.ts"],"sourcesContent":["/**\n * Imports realtime topic registry.\n *\n * Topics use the `imports.run.<event>` namespace. Subscribers listen\n * via `imports.run.**` for everything or narrow per event.\n *\n * Payload shapes are intentionally untyped here β€” callers pass\n * `Record<string, unknown>` and consumers (the imports admin page)\n * read fields by name. The point of this layer is \"an import_run\n * row's status changed, refetch\" rather than diffing event payloads\n * against the page's snapshot.\n *\n * Why a separate namespace from `queue.job.*`: queue events are\n * job-shaped (id, type, attempts, …) and admin-only. Imports events\n * are row-shaped (importRunId, status, brand, supplier, …) and\n * track the entity lifecycle independent of the underlying queue\n * mechanics β€” a future refactor could swap the queue for a different\n * driver without changing the imports event surface.\n */\n\nexport const IMPORTS_TOPICS = {\n /**\n * The upload route inserted an `import_run` row + enqueued its\n * driving queue job. Fired AFTER the outbox txn commits, so a\n * subscriber's refetch sees the row.\n */\n runCreated: 'imports.run.created',\n /**\n * The worker claimed the row and transitioned its status to\n * `running` β€” the streaming reader is open, the first batch is\n * about to bulk-write. Distinct from `queue.job.claimed` because\n * imports' state machine flips on the row, not the job.\n */\n runStarted: 'imports.run.started',\n /**\n * The worker finished cleanly β€” `import_run.status = 'succeeded'`,\n * `errorSummary` populated, totals locked in. Subscribers refetch\n * the history slice to bring the row out of the Active panel and\n * into Recent.\n */\n runSucceeded: 'imports.run.succeeded',\n /**\n * The worker (or `markFailed`) wrote `import_run.status = 'failed'`\n * with an error in `errorSummary`. Same refetch trigger; the page\n * differentiates terminal-success vs terminal-failure by reading\n * the row.\n */\n runFailed: 'imports.run.failed',\n} as const\n\nexport type ImportsTopic = (typeof IMPORTS_TOPICS)[keyof typeof IMPORTS_TOPICS]\n","/**\n * Typed publisher wrappers around `@murumets-ee/core/realtime.publishEvent`\n * for the `imports.run.*` topic surface.\n *\n * Like queue events, every imports event is admin-only β€” a future\n * refactor that opens these to non-admin operators (e.g. an\n * `imports:view` permission scope) would update {@link ADMIN_SCOPE}\n * here, not the call sites.\n *\n * Publish failures are caught and logged, never thrown β€” these\n * wrappers are called from worker state-transition paths and the\n * upload route, and a missing realtime delivery must NEVER roll back\n * the database write that triggered it.\n *\n * Why dynamic import: `@murumets-ee/core/realtime` carries\n * `import 'server-only'`, but this module is reachable from the\n * imports package's entrypoints (e.g. `worker.ts`), which are loaded\n * by jiti/tsx in `lumi doctor` / `lumi migrate` / `pnpm worker` β€”\n * none of which set the `react-server` export condition that turns\n * `server-only` into the empty stub. A static value-import would\n * therefore throw at boot. Same dynamic-import pattern as\n * `packages/queue/src/realtime/publish.ts` and\n * `packages/ticketing/src/realtime/publish.ts`.\n *\n * The `cachedPublish` + `publishSafe` + `_warmRealtimePublisher`\n * scaffolding here is the third copy of the same shape (queue,\n * ticketing, imports). Tracked for extraction to a shared\n * `@murumets-ee/core/realtime/safe-publisher` helper in #201 β€”\n * reach for that when it lands instead of copy-pasting a fourth\n * time.\n */\n\nimport type { Scope } from '@murumets-ee/core/realtime'\nimport { createLogger } from '@murumets-ee/logging'\nimport { IMPORTS_TOPICS } from './topics.js'\n\nconst logger = createLogger({ name: 'imports:realtime' })\n\n/** All imports events fan out to admin connections only. */\nconst ADMIN_SCOPE: Scope = { admin: true }\n\n// Cached publisher β€” once the dynamic import has resolved, every\n// subsequent publish is fully synchronous. Only the very first call\n// after process start pays the import cost.\nlet cachedPublish: typeof import('@murumets-ee/core/realtime').publishEvent | null = null\n\nfunction logPublishError(err: unknown, topic: string): void {\n if (err instanceof Error && err.name === 'RealtimeOversizeError') {\n // Oversize is a code bug (payload above the 7900-byte pg_notify\n // cap). For imports row events the payload is tiny β€” id, status,\n // brand/supplier label fragments β€” well under the cap. If this\n // ever fires the deriver smuggled too much in.\n logger.error({ err, topic }, 'realtime publish failed β€” payload oversize')\n } else {\n logger.warn({ err, topic }, 'realtime publish failed β€” event dropped')\n }\n}\n\nfunction publishSafe(topic: string, payload: Record<string, unknown>): void {\n if (cachedPublish) {\n try {\n cachedPublish({ topic, payload, scope: ADMIN_SCOPE })\n } catch (err) {\n logPublishError(err, topic)\n }\n return\n }\n // First call: resolve the import then fan out. Subsequent calls in\n // the same microtask race the import β€” that's fine, they queue\n // behind the same promise and use the resolved cache when it lands.\n import('@murumets-ee/core/realtime')\n .then((mod) => {\n cachedPublish = mod.publishEvent\n cachedPublish({ topic, payload, scope: ADMIN_SCOPE })\n })\n .catch((err: unknown) => {\n logPublishError(err, topic)\n })\n}\n\n/**\n * @internal β€” tests pre-resolve the dynamic import so the first\n * publish is synchronous, matching the post-warmup behaviour in\n * production.\n */\nexport async function _warmRealtimePublisher(): Promise<void> {\n if (cachedPublish) return\n const mod = await import('@murumets-ee/core/realtime')\n cachedPublish = mod.publishEvent\n}\n\n/**\n * Fire after the upload route's outbox txn commits, NOT inside it.\n * The realtime fanout is best-effort and a failure must not roll\n * back the row insert.\n */\nexport function publishImportRunCreated(\n importRunId: string,\n fields: { brandSlug?: string; supplierDisplayName?: string; filename: string },\n): void {\n publishSafe(IMPORTS_TOPICS.runCreated, {\n importRunId,\n ...(fields.brandSlug !== undefined && { brandSlug: fields.brandSlug }),\n ...(fields.supplierDisplayName !== undefined && {\n supplierDisplayName: fields.supplierDisplayName,\n }),\n filename: fields.filename,\n })\n}\n\n/**\n * Fire after the worker writes `status: 'running'` on the row.\n * Subscribers refetch to move the row from \"queued\" to \"running\" in\n * the Active panel and update the History snapshot.\n */\nexport function publishImportRunStarted(importRunId: string): void {\n publishSafe(IMPORTS_TOPICS.runStarted, { importRunId })\n}\n\n/**\n * Fire after the worker writes `status: 'succeeded'` + final totals.\n * Subscribers refetch to move the row from Active β†’ Recent.\n */\nexport function publishImportRunSucceeded(\n importRunId: string,\n totals: { rowsRead: number; rowsSucceeded: number; rowsFailed: number },\n): void {\n publishSafe(IMPORTS_TOPICS.runSucceeded, {\n importRunId,\n rowsRead: totals.rowsRead,\n rowsSucceeded: totals.rowsSucceeded,\n rowsFailed: totals.rowsFailed,\n })\n}\n\n/**\n * Fire after the worker writes `status: 'failed'` with an error in\n * `errorSummary`. Subscribers refetch to surface the failure in\n * Recent.\n */\nexport function publishImportRunFailed(importRunId: string, reason: string): void {\n publishSafe(IMPORTS_TOPICS.runFailed, { importRunId, reason })\n}\n"],"mappings":"oDAoBA,MAAa,EAAiB,CAM5B,WAAY,sBAOZ,WAAY,sBAOZ,aAAc,wBAOd,UAAW,oBACb,ECZM,EAAS,EAAa,CAAE,KAAM,kBAAmB,CAAC,EAGlD,EAAqB,CAAE,MAAO,EAAK,EAKzC,IAAI,EAAiF,KAEr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