@murumets-ee/imports 0.49.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/analyze/index.d.mts +265 -0
  2. package/dist/analyze/index.d.mts.map +1 -0
  3. package/dist/analyze/index.mjs +2 -0
  4. package/dist/analyze/index.mjs.map +1 -0
  5. package/dist/carmaker-feed-B-QYr3PI.mjs +2 -0
  6. package/dist/{carmaker-feed-CxhZBrkO.mjs.map → carmaker-feed-B-QYr3PI.mjs.map} +1 -1
  7. package/dist/carmaker-feed-_QVQFLUl.d.mts +59 -0
  8. package/dist/carmaker-feed-_QVQFLUl.d.mts.map +1 -0
  9. package/dist/{cleanup-CHjDgvKT.mjs → cleanup-DDljBe0Z.mjs} +2 -2
  10. package/dist/{cleanup-CHjDgvKT.mjs.map → cleanup-DDljBe0Z.mjs.map} +1 -1
  11. package/dist/engine-B0ExE4jL.mjs +2 -0
  12. package/dist/engine-B0ExE4jL.mjs.map +1 -0
  13. package/dist/{parts-schema-x8_GRYWc.d.mts → engine-DiM4r2Vj.d.mts} +349 -49
  14. package/dist/engine-DiM4r2Vj.d.mts.map +1 -0
  15. package/dist/index-Bm69N5DW.d.mts +97 -0
  16. package/dist/index-Bm69N5DW.d.mts.map +1 -0
  17. package/dist/index.d.mts +30 -6
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +1 -1
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/mapping/index.d.mts +3 -359
  22. package/dist/mapping/index.d.mts.map +1 -1
  23. package/dist/mapping/index.mjs +1 -1
  24. package/dist/mapping-transform-CO4MNhMe.mjs +2 -0
  25. package/dist/{mapping-transform-D76b-P-p.mjs.map → mapping-transform-CO4MNhMe.mjs.map} +1 -1
  26. package/dist/matching/index.d.mts +2 -0
  27. package/dist/matching/index.mjs +1 -0
  28. package/dist/matching-Sr0z4HvN.mjs +2 -0
  29. package/dist/matching-Sr0z4HvN.mjs.map +1 -0
  30. package/dist/parts-schema-DOWhBJYh.d.mts +61 -0
  31. package/dist/parts-schema-DOWhBJYh.d.mts.map +1 -0
  32. package/dist/parts-schema-QqLci_Pl.mjs +2 -0
  33. package/dist/parts-schema-QqLci_Pl.mjs.map +1 -0
  34. package/dist/plugin.d.mts +1 -1
  35. package/dist/plugin.mjs +1 -1
  36. package/dist/plugin.mjs.map +1 -1
  37. package/dist/read-feed-DGjqejw3.mjs +2 -0
  38. package/dist/read-feed-DGjqejw3.mjs.map +1 -0
  39. package/dist/runner-C9GIe5Dr.mjs +2 -0
  40. package/dist/runner-C9GIe5Dr.mjs.map +1 -0
  41. package/dist/{schema-registry-C_lQje-K.mjs → schema-registry-DB5aIZMN.mjs} +2 -2
  42. package/dist/{schema-registry-C_lQje-K.mjs.map → schema-registry-DB5aIZMN.mjs.map} +1 -1
  43. package/dist/storage-resolver.d.mts +1 -1
  44. package/dist/transform-Cu5YEoOl.mjs +2 -0
  45. package/dist/transform-Cu5YEoOl.mjs.map +1 -0
  46. package/dist/{transform-CABBaYmF.d.mts → transform-WeiiLdYP.d.mts} +12 -1
  47. package/dist/transform-WeiiLdYP.d.mts.map +1 -0
  48. package/dist/transforms.d.mts +2 -46
  49. package/dist/transforms.mjs +1 -1
  50. package/dist/{worker-DRTgbtT7.d.mts → worker-_MlRH5hd.d.mts} +209 -8
  51. package/dist/worker-_MlRH5hd.d.mts.map +1 -0
  52. package/dist/worker.d.mts +1 -1
  53. package/dist/worker.mjs +1 -1
  54. package/dist/worker.mjs.map +1 -1
  55. package/dist/xlsx-reader-_ioPAqm5.mjs +2 -0
  56. package/dist/{xlsx-reader-Ccesszbc.mjs.map → xlsx-reader-_ioPAqm5.mjs.map} +1 -1
  57. package/package.json +16 -8
  58. package/dist/carmaker-feed-CxhZBrkO.mjs +0 -2
  59. package/dist/mapping-transform-D76b-P-p.mjs +0 -2
  60. package/dist/parts-schema-D0gMhNWj.mjs +0 -2
  61. package/dist/parts-schema-D0gMhNWj.mjs.map +0 -1
  62. package/dist/parts-schema-x8_GRYWc.d.mts.map +0 -1
  63. package/dist/runner-C-s6SD7t.mjs +0 -2
  64. package/dist/runner-C-s6SD7t.mjs.map +0 -1
  65. package/dist/transform-CABBaYmF.d.mts.map +0 -1
  66. package/dist/transform-DIzWppgJ.mjs +0 -2
  67. package/dist/transform-DIzWppgJ.mjs.map +0 -1
  68. package/dist/transforms.d.mts.map +0 -1
  69. package/dist/worker-DRTgbtT7.d.mts.map +0 -1
  70. package/dist/xlsx-reader-Ccesszbc.mjs +0 -2
@@ -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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AsB,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"}
package/dist/plugin.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as EsClientResolver, r as FilePathResolver, s as PairSink, t as EnsureIndexResolver } from "./worker-DRTgbtT7.mjs";
1
+ import { n as EsClientResolver, r as FilePathResolver, s as PairSink, t as EnsureIndexResolver } from "./worker-_MlRH5hd.mjs";
2
2
  import { ImportsStorageFactory } from "./storage.mjs";
3
3
  import { IndexConfig } from "@murumets-ee/search-elasticsearch";
4
4
 
package/dist/plugin.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,o as t,u as n}from"./transform-DIzWppgJ.mjs";import{registerImportsStorageFactory as r}from"./storage.mjs";import{n as i,t as a}from"./mapping-transform-D76b-P-p.mjs";import{r as o,t as s}from"./carmaker-feed-CxhZBrkO.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(a,i),r.has(`commerce:carmaker-feed`)||r.register(s,o),!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-CHjDgvKT.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};
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
2
  //# sourceMappingURL=plugin.mjs.map
@@ -1 +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":"+mBAgGA,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,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAM,CAAC,CAAC,SAAS,CAC1D,CAAC,EA0CY,EAA6D,EAAU,CAClF,KAAM,kBACN,YACE,iIACF,OAAQ,EACR,eAAgB,CAClB,CAAC,EAgCK,EAAyB,CAAC,UAAW,SAAS,EAUpD,eAAe,EAAmB,EAA8C,CAI9E,IAAM,EAAQ,EAAW,SAAS,EAClC,OAAO,EAAW,MAAM,CAAE,MAAO,EAAQ,EAAM,OAAQ,CAAC,GAAG,CAAsB,CAAC,CAAE,CAAC,CACvF,CAGA,SAAgB,EAAuB,EAAgC,CACrE,IAAM,EAAQ,gBAAgB,KAAK,CAAO,EAC1C,GAAI,CAAC,EAAO,OAAO,KACnB,GAAM,EAAG,EAAM,GAAW,EAC1B,GAAI,IAAS,IAAA,IAAa,IAAY,IAAA,GAAW,OAAO,KACxD,IAAM,EAAO,OAAO,SAAS,EAAS,EAAE,EAAI,EAE5C,OADK,OAAO,cAAc,CAAI,EACvB,GAAG,EAAK,IAAI,IADqB,IAE1C,CAaA,SAAgB,EACd,EACkD,CAClD,GAAM,CAAE,WAA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K,UAAW,IAAK,SAAU,CAAC,EAEzE,EAAkB,YAChB,EAAkB,UAAU,CAC1B,KAAM,mCACN,YACE,qIACF,SAAU,WACZ,CAAC,EACD,SAAY,CAUV,MAAM,MACJ,EAAuB,CACrB,MACA,OAAQ,EAAc,OACtB,SAAU,EAAc,eACxB,OAAQ,CACV,CAAC,CACH,CACF,CACF,EAEA,EAAkB,YAChB,EAAkB,UAAU,CAC1B,KAAM,oCACN,YACE,oMACF,SAAU,WACZ,CAAC,EACD,SAAY,CACV,MAAM,MACJ,EAAwB,CACtB,MACA,OAAQ,EAAc,OACtB,cAAe,EAAc,uBAC7B,OAAQ,CACV,CAAC,CACH,CACF,CACF,CACF,CAEA,EAAI,OAAO,KACT,CACE,UAIA,QACE,IAAkB,KAAO,CAAE,QAAS,EAAM,EAAI,CAAE,QAAS,GAAM,GAAG,CAAc,CACpF,EACA,4BACF,CACF,CACF,CACF,CAAC,CACH"}
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,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAM,CAAC,CAAC,SAAS,CAC1D,CAAC,EA0CY,EAA6D,EAAU,CAClF,KAAM,kBACN,YACE,iIACF,OAAQ,EACR,eAAgB,CAClB,CAAC,EAgCK,EAAyB,CAAC,UAAW,SAAS,EAUpD,eAAe,EAAmB,EAA8C,CAI9E,IAAM,EAAQ,EAAW,SAAS,EAClC,OAAO,EAAW,MAAM,CAAE,MAAO,EAAQ,EAAM,OAAQ,CAAC,GAAG,CAAsB,CAAC,CAAE,CAAC,CACvF,CAGA,SAAgB,EAAuB,EAAgC,CACrE,IAAM,EAAQ,gBAAgB,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EAA6B,CAC3B,aACA,OAAQ,EAAI,OAAO,MAAM,CAAE,IAAK,SAAU,CAAC,CAC7C,CAAC,CACH,EAgBA,GAfC,WAA0C,GAA6B,EAepE,IAAkB,KAAM,CAC1B,GAAM,CAAE,yBAAwB,2BAA4B,MAAM,OAChE,yBACD,CAAA,KAAA,GAAA,EAAA,CAAA,EACK,CAAE,YAAa,MAAM,OAAO,qBAC5B,EAAgB,EAAI,OAAO,MAAM,CAAE,IAAK,UAAW,IAAK,SAAU,CAAC,EAEzE,EAAkB,YAChB,EAAkB,UAAU,CAC1B,KAAM,mCACN,YACE,qIACF,SAAU,WACZ,CAAC,EACD,SAAY,CAUV,MAAM,MACJ,EAAuB,CACrB,MACA,OAAQ,EAAc,OACtB,SAAU,EAAc,eACxB,OAAQ,CACV,CAAC,CACH,CACF,CACF,EAEA,EAAkB,YAChB,EAAkB,UAAU,CAC1B,KAAM,oCACN,YACE,oMACF,SAAU,WACZ,CAAC,EACD,SAAY,CACV,MAAM,MACJ,EAAwB,CACtB,MACA,OAAQ,EAAc,OACtB,cAAe,EAAc,uBAC7B,OAAQ,CACV,CAAC,CACH,CACF,CACF,CACF,CAEA,EAAI,OAAO,KACT,CACE,UAIA,QACE,IAAkB,KAAO,CAAE,QAAS,EAAM,EAAI,CAAE,QAAS,GAAM,GAAG,CAAc,CACpF,EACA,4BACF,CACF,CACF,CACF,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ import{z as e}from"zod";import{createReadStream as t}from"node:fs";import{parse as n}from"csv-parse";function r(e){let t=new Set;for(let n of e)if(n!==``){if(t.has(n))throw Error(`Duplicate header "${n}" after trimming — column names must be unique`);t.add(n)}}async function i(e,n={}){let{hasHeader:r=!0}=n,i=t(e),a=0,o=0;for await(let e of i){for(let t=0;t<e.length;t+=1)e[t]===10&&(a+=1);e.length>0&&(o=e[e.length-1]??0)}return o!==0&&o!==10&&(a+=1),r?Math.max(0,a-1):a}async function*a(e){let{filePath:i,delimiter:a=` `,hasHeader:o=!0,columns:s,relaxColumnCount:c=!1,quote:l=!1}=e,u=s?Array.from(s):o?e=>{let t=e.map(e=>e.trim());return r(t),t}:!1,d=t(i),f=d.pipe(n({delimiter:a,columns:u,bom:!0,skip_empty_lines:!0,relax_column_count:c,quote:l})),p=0;try{for await(let e of f){p+=1;let t={};if(Array.isArray(e)){let n=e;for(let e=0;e<n.length;e+=1)t[String(e)]=n[e]??``}else for(let[n,r]of Object.entries(e))t[n]=r??``;yield{rowNumber:p,row:t}}}finally{d.destroy()}}const o=e.object({format:e.enum([`csv`,`tsv`,`xlsx`]).optional(),delimiter:e.string().min(1).max(4).optional(),hasHeader:e.boolean().optional(),headerRowIndex:e.number().int().min(0).optional(),sheet:e.string().min(1).max(128).optional(),quote:e.union([e.string().length(1),e.literal(!1)]).optional()}).strict();function s(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n=t.feed===void 0||t.feed===null?{}:t.feed;return o.safeParse(n)}function c(e){let t=e.delimiter??(e.format===`csv`?`,`:` `);return{filePath:e.filePath,delimiter:t,...e.hasHeader!==void 0&&{hasHeader:e.hasHeader},...e.columns!==void 0&&{columns:e.columns},...e.relaxColumnCount!==void 0&&{relaxColumnCount:e.relaxColumnCount},...e.quote!==void 0&&{quote:e.quote}}}async function*l(e){if(e.format===`xlsx`){let{streamXlsx:t}=await import(`./xlsx-reader-_ioPAqm5.mjs`);yield*t({filePath:e.filePath,...e.hasHeader!==void 0&&{hasHeader:e.hasHeader},...e.headerRowIndex!==void 0&&{headerRowIndex:e.headerRowIndex},...e.sheet!==void 0&&{sheet:e.sheet}});return}yield*a(c(e))}export{i as a,r as i,l as n,a as o,s as r,o as t};
2
+ //# sourceMappingURL=read-feed-DGjqejw3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-feed-DGjqejw3.mjs","names":[],"sources":["../src/streaming.ts","../src/read-feed.ts"],"sourcesContent":["/**\n * Tab-delimited / CSV streaming reader. Generic over delimiter so the\n * same path handles `.txt` (tab), `.csv` (comma), and the rare `;`\n * European export dialect.\n *\n * Built on `csv-parse` per giga-test precedent — node-stream-based, low\n * memory, handles UTF-8 BOM (the carmaker feeds are Windows-exported\n * and ship with a BOM that breaks naive split-on-tab parsers).\n *\n * The reader yields `{ rowNumber, row }` pairs where:\n * - `rowNumber` is 1-based and counts the header as row 0.\n * - `row` is `Record<string, string>` keyed by header name. Empty cells\n * are the empty string, NOT `undefined` — feed transforms test with\n * `value === ''` consistently.\n *\n * Why this lives in a streaming reader and not inside the transform\n * itself: the transform sees one already-parsed row at a time, never\n * the file. That keeps transform implementations free of I/O concerns\n * and makes them trivially unit-testable with a fixture row map.\n */\n\nimport { createReadStream } from 'node:fs'\nimport { parse } from 'csv-parse'\n\n/**\n * Throw if two (non-empty) header names collide. Headers are the keys the mapping\n * engine matches a `source` against; after trimming, two columns differing only in\n * whitespace would collapse to one key and silently overwrite each other's data.\n * Fail fast instead — the operator fixes the feed or the mapping. Shared by the\n * csv/tsv reader (below) and the xlsx reader. Blank columns are ignored (unmapped).\n */\nexport function assertUniqueHeaders(header: readonly string[]): void {\n const seen = new Set<string>()\n for (const h of header) {\n if (h === '') continue\n if (seen.has(h)) {\n throw new Error(`Duplicate header \"${h}\" after trimming — column names must be unique`)\n }\n seen.add(h)\n }\n}\n\n/**\n * Pre-pass: count data rows in a delimited file (excluding the header\n * row when `hasHeader` is true; default `true` to match `streamFeed`).\n *\n * Implementation: stream the file as raw bytes and tally `\\n`. NOT a\n * full parse — escaped newlines inside quoted fields would over-count.\n * That was unconditionally fine while `quote: false` was the only\n * behaviour available; a mapping can now declare RFC 4180 (`quote`),\n * and an embedded newline in a quoted field then makes this an UPPER\n * BOUND rather than a count. It is used only as the progress\n * denominator (`totalRows`), so the visible consequence is a bar that\n * stops short of 100%, never a wrong import. The parsed row count from\n * `streamFeed` is authoritative and is what the run records.\n *\n * Why bytes-only and not csv-parse: a 16 MB feed counts in ~50 ms with\n * `\\n` tally vs ~500 ms with csv-parse parsing. For 500 MB the gap\n * matters — pre-pass needs to be a small fraction of the actual import\n * or the operator perceives the run as \"stuck on pre-pass\" with no UI.\n *\n * Returns the number of DATA rows (header excluded when present).\n * Empty trailing lines (no `\\n` after the final row, or a single\n * trailing `\\n`) are handled identically to how csv-parse treats them\n * with `skip_empty_lines: true`.\n */\nexport async function countDataRows(\n filePath: string,\n options: { hasHeader?: boolean } = {},\n): Promise<number> {\n const { hasHeader = true } = options\n const stream = createReadStream(filePath)\n let count = 0\n let lastByte = 0\n for await (const chunk of stream as AsyncIterable<Buffer>) {\n for (let i = 0; i < chunk.length; i += 1) {\n if (chunk[i] === 0x0a /* \\n */) count += 1\n }\n if (chunk.length > 0) lastByte = chunk[chunk.length - 1] ?? 0\n }\n // If the file doesn't end with a newline, the final row didn't get\n // counted by the `\\n` tally — add one. Skipping when the file is\n // entirely empty (count=0 and lastByte=0).\n if (lastByte !== 0 && lastByte !== 0x0a) count += 1\n return hasHeader ? Math.max(0, count - 1) : count\n}\n\nexport interface StreamFeedOptions {\n /** Path to the file on disk. The PoC uploads land on local disk; S3-keyed reads come later. */\n filePath: string\n /**\n * Single-character field delimiter. Default `\\t` (the carmaker feed\n * format). Pass `,` for CSV, `;` for some European dialects.\n */\n delimiter?: string\n /**\n * `true` (default): the first row is the header and column names come\n * from it. `false`: rows are emitted as positional `{ \"0\": ..., \"1\": ... }`\n * and the transform reads by index — useful for headerless feeds that\n * commit to a documented column order.\n */\n hasHeader?: boolean\n /**\n * Optional explicit column-name list. When provided, takes precedence\n * over `hasHeader` (header row, if present, is skipped but its values\n * are ignored). Useful when the upstream header is unstable but the\n * positional shape isn't.\n */\n columns?: ReadonlyArray<string>\n /**\n * Forward to `csv-parse` `relax_column_count`. Default `false` —\n * a row whose column count doesn't match the header surfaces as a\n * parser error so the transform isn't silently fed truncated data.\n */\n relaxColumnCount?: boolean\n /**\n * Forward to `csv-parse` `quote`. The character (or `false`) that\n * encloses fields containing the delimiter. Default `false` — most\n * supplier feeds in this package's target use case are tab-delimited\n * exports that contain literal `\"` characters in description fields\n * (e.g. `LIVRE \"INVERSION D'IMAGE\"` from the Mercedes carmaker feed)\n * with NO quote-as-field-wrapper convention. csv-parse's library\n * default `'\"'` then misreads the literal `\"` as an opening quote\n * and rejects the row with `Invalid Opening Quote`.\n *\n * Pass `'\"'` (or any character) to opt back into RFC-4180-style\n * CSV parsing for genuine quoted-CSV inputs. Pass `'\\''` for\n * single-quoted dialects.\n */\n quote?: string | false\n}\n\nexport interface StreamFeedRow {\n /** 1-based row number. Header (when present) is row 0; first data row is row 1. */\n rowNumber: number\n /**\n * Cell values keyed by column name (or string-position when\n * `hasHeader: false` AND no `columns`).\n *\n * **Cell-value invariants:**\n * - Empty cells (`A\\t\\tC`) → `''` (empty string).\n * - Missing TRAILING cells in `relaxColumnCount: true` mode → the\n * key is **absent** from the object, not present-with-`''`. csv-parse\n * does not emit keys for short rows. Transforms reading those\n * columns get `undefined` from `row['col']` and must handle it\n * (`row['col'] ?? ''` is the canonical idiom).\n * - With the default `relaxColumnCount: false`, short rows reject at\n * the parser, so this case never reaches the transform.\n */\n row: Record<string, string>\n}\n\n/**\n * Async-iterable over the parsed rows of a delimited file. Use with\n * `for await (const { rowNumber, row } of streamFeed({ filePath, ... }))`.\n *\n * The iterator owns its file descriptor — the `for await` loop closes\n * the underlying stream when it returns or breaks. Aborting mid-stream\n * (`break`, `throw`, signal) is safe; csv-parse propagates the close.\n */\nexport async function* streamFeed(options: StreamFeedOptions): AsyncIterable<StreamFeedRow> {\n const {\n filePath,\n delimiter = '\\t',\n hasHeader = true,\n columns,\n relaxColumnCount = false,\n quote = false,\n } = options\n\n // When the caller provides explicit `columns`, prefer them. When the file\n // has a header but no explicit `columns`, derive the column names from the\n // first row via a function so we can TRIM them — real supplier feeds ship\n // leading/trailing-space headers (R03 Samples A/C: `\" JAEHIND KM-TA\"`), and\n // an untrimmed key wouldn't match a mapping's `source`. The xlsx reader trims\n // headers the same way. When neither is true, rows get string-position keys.\n //\n // csv-parse's `columns` accepts `ColumnOption[] | boolean | ((record) =>\n // ColumnOption[])`; `string[]` satisfies `ColumnOption[]`.\n const columnConfig: string[] | boolean | ((header: string[]) => string[]) = columns\n ? Array.from(columns)\n : hasHeader\n ? (header: string[]) => {\n const trimmed = header.map((h) => h.trim())\n assertUniqueHeaders(trimmed)\n return trimmed\n }\n : false\n\n const stream = createReadStream(filePath)\n const parser = stream.pipe(\n parse({\n delimiter,\n columns: columnConfig,\n bom: true,\n skip_empty_lines: true,\n // csv-parse defaults to strict column count; opt-in relaxation only.\n relax_column_count: relaxColumnCount,\n // Default `quote: false` — see StreamFeedOptions.quote JSDoc.\n // Carmaker / parts-feed exports contain literal `\"` characters\n // in description fields and would otherwise reject as\n // `Invalid Opening Quote`. Genuine RFC-4180 CSV consumers opt\n // back in by passing `quote: '\"'`.\n quote,\n }),\n )\n\n let rowNumber = 0\n try {\n for await (const rawRow of parser as AsyncIterable<\n ReadonlyArray<string> | Record<string, string | undefined>\n >) {\n rowNumber += 1\n // csv-parse emits records with string keys when `columns` is\n // truthy, otherwise an Array. Normalise both shapes to\n // `Record<string, string>` so transforms can rely on `value === ''`\n // for missing cells (csv-parse leaves trailing missing cells as\n // `undefined` when `relax_column_count: true`; this collapses\n // them to `''` to keep the contract uniform).\n const row: Record<string, string> = {}\n if (Array.isArray(rawRow)) {\n const arr = rawRow as ReadonlyArray<string | undefined>\n for (let i = 0; i < arr.length; i += 1) {\n row[String(i)] = arr[i] ?? ''\n }\n } else {\n for (const [k, v] of Object.entries(rawRow)) {\n row[k] = v ?? ''\n }\n }\n yield { rowNumber, row }\n }\n } finally {\n // Safety: ensure the underlying file descriptor closes even if the\n // consumer breaks mid-iteration. Node closes streams on\n // garbage-collection but this makes it deterministic under tests.\n stream.destroy()\n }\n}\n","/**\n * Feed reader dispatcher (commerce-demo phase 02, D005). Selects the reader by\n * `format` and yields the uniform `AsyncIterable<{ rowNumber, row }>` the runner\n * consumes — csv/tsv via the existing `streamFeed` (csv-parse), xlsx via the\n * exceljs-backed `streamXlsx`.\n *\n * **Back-compat**: with no `format` (the carmaker worker passes only `filePath`),\n * this defaults to tab-delimited — the original `streamFeed` behaviour — so the\n * existing import path is unchanged.\n *\n * **Bundle safety**: the xlsx reader (and its heavy, Node-only exceljs dep) is\n * `await import()`-ed ONLY for `format: 'xlsx'`, so the csv/tsv path — and anything\n * that statically imports the runner — never pulls exceljs into its module graph.\n */\n\nimport { z } from 'zod'\nimport { type StreamFeedOptions, type StreamFeedRow, streamFeed } from './streaming.js'\n\n/**\n * The reader-config subset safe to persist in `import_run.params.feed` and rehydrate\n * in the worker (commerce-demo PR3). It is exactly the {@link ReadFeedOptions} fields\n * that describe HOW to parse a feed — `filePath` is supplied by the worker after it\n * materialises the upload, never carried in params. Validated at BOTH ends: the\n * commerce run route builds it from a saved `import_mapping`, the worker re-parses it\n * before handing it to {@link readFeed} (defense-in-depth against a tampered row).\n */\nexport const feedReaderConfigSchema = z\n .object({\n format: z.enum(['csv', 'tsv', 'xlsx']).optional(),\n delimiter: z.string().min(1).max(4).optional(),\n hasHeader: z.boolean().optional(),\n headerRowIndex: z.number().int().min(0).optional(),\n sheet: z.string().min(1).max(128).optional(),\n /**\n * csv-parse's `quote`. Absent (or `false`) = quotes are ordinary data, which is this\n * package's long-standing default and what the tab-delimited supplier dumps require. A\n * single character opts into RFC 4180 for feeds that genuinely quote their fields.\n *\n * Persisted deliberately: the two shapes are mutually exclusive on real data (R027 —\n * each of the three ground-truth feeds hard-fails under the other's setting), so this\n * is a per-file fact a mapping has to carry. Deriving it from `format` would be the\n * same class of mistake as a global decimal separator.\n */\n quote: z.union([z.string().length(1), z.literal(false)]).optional(),\n })\n .strict()\nexport type FeedReaderConfig = z.infer<typeof feedReaderConfigSchema>\n\n/**\n * Rehydrate the reader config a run persisted in `import_run.params.feed`.\n *\n * ONE implementation, because two would drift and drift here is silent: the\n * worker uses it to decide how to READ a feed, and the #842 audit uses it to\n * re-read the same file the same way. An audit that rehydrates differently from\n * the run it is auditing invents corruption, or misses it.\n *\n * ABSENT means \"the carmaker default\", i.e. tab-delimited, which is what an\n * empty config parses to — so a non-object `params`, or `params` with no\n * `feed`, is a real answer rather than a gap. A PRESENT `feed` is validated\n * whatever its shape: a scalar or an array there is a malformed persisted blob,\n * and reading it as \"no config\" would silently import an xlsx run as tsv.\n */\nexport function readPersistedFeedConfig(\n params: unknown,\n): ReturnType<typeof feedReaderConfigSchema.safeParse> {\n const record =\n params && typeof params === 'object' && !Array.isArray(params)\n ? (params as Record<string, unknown>)\n : {}\n // `null` is how \"absent\" round-trips through JSONB, so it defaults with\n // `undefined`. Everything else present goes to the schema and is rejected on\n // its merits rather than being flattened into the default.\n const feed = record.feed === undefined || record.feed === null ? {} : record.feed\n return feedReaderConfigSchema.safeParse(feed)\n}\n\nexport interface ReadFeedOptions {\n /** Path to the file on local disk. */\n filePath: string\n /** Feed format. Omitted → tab-delimited (tsv), matching the legacy carmaker reader. */\n format?: 'csv' | 'tsv' | 'xlsx'\n /** Explicit delimiter override (csv/tsv). Defaults from `format` (`csv` → `,`, else `\\t`). */\n delimiter?: string\n /** First row is the header. Default `true`. */\n hasHeader?: boolean\n /** 0-based header row index (xlsx). */\n headerRowIndex?: number\n /** xlsx worksheet as a 1-based index string. Omit → first sheet. */\n sheet?: string\n /** Explicit column-name list (csv/tsv) — see `streamFeed`. */\n columns?: ReadonlyArray<string>\n /** Forward to csv-parse `relax_column_count` (csv/tsv). */\n relaxColumnCount?: boolean\n /** Forward to csv-parse `quote` (csv/tsv). */\n quote?: string | false\n}\n\nfunction toStreamFeedOptions(o: ReadFeedOptions): StreamFeedOptions {\n // No format → tab (the carmaker feed default). `csv` → comma; everything else → tab.\n const delimiter = o.delimiter ?? (o.format === 'csv' ? ',' : '\\t')\n return {\n filePath: o.filePath,\n delimiter,\n ...(o.hasHeader !== undefined && { hasHeader: o.hasHeader }),\n ...(o.columns !== undefined && { columns: o.columns }),\n ...(o.relaxColumnCount !== undefined && { relaxColumnCount: o.relaxColumnCount }),\n ...(o.quote !== undefined && { quote: o.quote }),\n }\n}\n\n/** Stream a feed file's data rows, dispatching on `format`. */\nexport async function* readFeed(options: ReadFeedOptions): AsyncIterable<StreamFeedRow> {\n if (options.format === 'xlsx') {\n const { streamXlsx } = await import('./xlsx-reader.js')\n yield* streamXlsx({\n filePath: options.filePath,\n ...(options.hasHeader !== undefined && { hasHeader: options.hasHeader }),\n ...(options.headerRowIndex !== undefined && { headerRowIndex: options.headerRowIndex }),\n ...(options.sheet !== undefined && { sheet: options.sheet }),\n })\n return\n }\n yield* streamFeed(toStreamFeedOptions(options))\n}\n"],"mappings":"qGA+BA,SAAgB,EAAoB,EAAiC,CACnE,IAAM,EAAO,IAAI,IACjB,IAAK,IAAM,KAAK,EACV,OAAM,GACV,IAAI,EAAK,IAAI,CAAC,EACZ,MAAU,MAAM,qBAAqB,EAAE,+CAA+C,EAExF,EAAK,IAAI,CAAC,CAF8E,CAI5F,CA0BA,eAAsB,EACpB,EACA,EAAmC,CAAC,EACnB,CACjB,GAAM,CAAE,YAAY,IAAS,EACvB,EAAS,EAAiB,CAAQ,EACpC,EAAQ,EACR,EAAW,EACf,UAAW,IAAM,KAAS,EAAiC,CACzD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,GAAK,EACjC,EAAM,KAAO,KAAe,GAAS,GAEvC,EAAM,OAAS,IAAG,EAAW,EAAM,EAAM,OAAS,IAAM,EAC9D,CAKA,OADI,IAAa,GAAK,IAAa,KAAM,GAAS,GAC3C,EAAY,KAAK,IAAI,EAAG,EAAQ,CAAC,EAAI,CAC9C,CA2EA,eAAuB,EAAW,EAA0D,CAC1F,GAAM,CACJ,WACA,YAAY,IACZ,YAAY,GACZ,UACA,mBAAmB,GACnB,QAAQ,IACN,EAWE,EAAsE,EACxE,MAAM,KAAK,CAAO,EAClB,EACG,GAAqB,CACpB,IAAM,EAAU,EAAO,IAAK,GAAM,EAAE,KAAK,CAAC,EAE1C,OADA,EAAoB,CAAO,EACpB,CACT,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EAAO,OAAS,IAAA,IAAa,EAAO,OAAS,KAAO,CAAC,EAAI,EAAO,KAC7E,OAAO,EAAuB,UAAU,CAAI,CAC9C,CAuBA,SAAS,EAAoB,EAAuC,CAElE,IAAM,EAAY,EAAE,YAAc,EAAE,SAAW,MAAQ,IAAM,KAC7D,MAAO,CACL,SAAU,EAAE,SACZ,YACA,GAAI,EAAE,YAAc,IAAA,IAAa,CAAE,UAAW,EAAE,SAAU,EAC1D,GAAI,EAAE,UAAY,IAAA,IAAa,CAAE,QAAS,EAAE,OAAQ,EACpD,GAAI,EAAE,mBAAqB,IAAA,IAAa,CAAE,iBAAkB,EAAE,gBAAiB,EAC/E,GAAI,EAAE,QAAU,IAAA,IAAa,CAAE,MAAO,EAAE,KAAM,CAChD,CACF,CAGA,eAAuB,EAAS,EAAwD,CACtF,GAAI,EAAQ,SAAW,OAAQ,CAC7B,GAAM,CAAE,cAAe,MAAM,OAAO,8BACpC,MAAO,EAAW,CAChB,SAAU,EAAQ,SAClB,GAAI,EAAQ,YAAc,IAAA,IAAa,CAAE,UAAW,EAAQ,SAAU,EACtE,GAAI,EAAQ,iBAAmB,IAAA,IAAa,CAAE,eAAgB,EAAQ,cAAe,EACrF,GAAI,EAAQ,QAAU,IAAA,IAAa,CAAE,MAAO,EAAQ,KAAM,CAC5D,CAAC,EACD,MACF,CACA,MAAO,EAAW,EAAoB,CAAO,CAAC,CAChD"}
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./read-feed-DGjqejw3.mjs";import{bulkPartialUpdate as t,bulkUpsert as n}from"@murumets-ee/search-elasticsearch";const r=50,i=5;var a=class{patterns=new Map;maxPatterns;maxSamplesPerPattern;droppedSignatures=0;constructor(e={}){this.maxPatterns=e.maxPatterns??50,this.maxSamplesPerPattern=e.maxSamplesPerPattern??5}addError(e,t,n,r,i){let a=`${t}:${r??`GENERAL`}:${n}`,o=this.patterns.get(a);if(!o){if(this.patterns.size>=this.maxPatterns){this.droppedSignatures+=1;return}o={errorType:t,field:r??null,message:n,count:0,firstOccurrence:e,lastOccurrence:e,samples:[]},this.patterns.set(a,o)}o.count+=1,o.lastOccurrence=e,o.samples.length<this.maxSamplesPerPattern&&o.samples.push({rowNumber:e,rowData:i})}getTotalErrorCount(){let e=0;for(let t of this.patterns.values())e+=t.count;return e}getDistinctPatternCount(){return this.patterns.size}getDroppedSignatureCount(){return this.droppedSignatures}getTopPatterns(){let e=Array.from(this.patterns.values()).sort((e,t)=>t.count-e.count),t=e.reduce((e,t)=>e+t.count,0);return e.map(e=>({errorType:e.errorType,field:e.field,message:e.message,count:e.count,firstOccurrence:e.firstOccurrence,lastOccurrence:e.lastOccurrence,samples:e.samples.slice(),percentage:t>0?e.count/t*100:0}))}snapshot(){return{totalErrors:this.getTotalErrorCount(),distinctPatterns:this.getDistinctPatternCount(),droppedSignatures:this.droppedSignatures,patterns:this.getTopPatterns()}}};function o(e,t){let n=e.totalErrors+t.totalErrors,r=e=>({...e,percentage:n>0?e.count/n*100:0});return{totalErrors:n,distinctPatterns:e.distinctPatterns+t.distinctPatterns,droppedSignatures:e.droppedSignatures+t.droppedSignatures,patterns:[...e.patterns.map(r),...t.patterns.map(r)]}}const s={count:0,nullRate:0,min:null,median:null,max:null},c=5e4;var l=class{count=0;nullCount=0;nonNullSeen=0;samples=[];record(e){if(this.count+=1,e===void 0){this.nullCount+=1;return}if(this.nonNullSeen+=1,this.samples.length<5e4){this.samples.push(e);return}let t=Math.floor(Math.random()*this.nonNullSeen);t<5e4&&(this.samples[t]=e)}snapshot(){if(this.count===0)return{...s};let e=this.nullCount/this.count;if(this.samples.length===0)return{count:this.count,nullRate:e,min:null,median:null,max:null};let t=[...this.samples].sort((e,t)=>e-t),n=t[0]??null,r=t[t.length-1]??null,i=Math.floor(t.length/2),a;if(t.length%2==0){let e=t[i-1],n=t[i];a=e!==void 0&&n!==void 0?(e+n)/2:null}else a=t[i]??null;return{count:this.count,nullRate:e,min:n,median:a,max:r}}};const u=10;function d(e,t){if(e.median===null||t.median===null||e.median<=0||t.median<=0)return null;let n=t.median/e.median;return n>=10||n<=1/10?{ratio:n,prevMedian:e.median,currMedian:t.median}:null}function f(e){if(typeof e!=`object`||!e)return null;let t=e;return typeof t.count!=`number`||typeof t.nullRate!=`number`?null:{count:t.count,nullRate:t.nullRate,min:typeof t.min==`number`?t.min:null,median:typeof t.median==`number`?t.median:null,max:typeof t.max==`number`?t.max:null}}const p=1e3;async function m(r){let{importRunId:i,runLabel:o,params:s,transform:c,feed:u,esClient:d,esIndex:f,batchSize:m=p,onProgress:h,rowLimit:g,signal:_,errorTracker:v=new a,warningTracker:y=new a,priceStats:b=new l,logger:x}=r;if(m<1)throw Error(`batchSize must be >= 1 (got ${m})`);let S=Date.now();x?.info({importRunId:i,runLabel:o,batchSize:m,esIndex:f},`imports.runner: started`);let C=0,w=0,T=0,E=0,D=0,O=0,k=[],A=[],j=[],M=async()=>{if(j.length===0)return;let e=j;j=[];let t=Date.now(),r;try{r=await n(d,{index:f,docs:e.map(({id:e,doc:t})=>({id:e,doc:t})),..._!==void 0&&{signal:_}})}catch(t){let n=_?.aborted??(t instanceof Error&&(t.name===`AbortError`||/abort/i.test(t.message)))?`aborted`:`bulk_request_failed`,r=t instanceof Error?t.message:String(t);for(let{rowNumber:t}of e)v.addError(t,n,r,void 0,null);throw T+=e.length,t}w+=r.succeeded,T+=r.failures.length,O+=1;let a=Date.now()-t,o=(Date.now()-S)/1e3;if(x?.info({importRunId:i,batch:O,flushMs:a,submitted:e.length,succeeded:r.succeeded,failed:r.failures.length,rowsRead:C,rowsPerSecond:o>0?Math.round(C/o):0},`imports.runner: batch flushed`),r.failures.length>0){let t=new Map(e.map(e=>[e.id,e.rowNumber]));for(let e of r.failures){let n=t.get(e.id)??-1;v.addError(n,e.type,e.reason,void 0,{id:e.id})}}let s=new Set(r.failures.map(e=>e.id));for(let t of e)if(!(!t.warnings||t.warnings.length===0)&&!s.has(t.id)){D+=1;for(let e of t.warnings)y.addError(t.rowNumber,e.warningType,e.message,e.field,t.rowData)}for(let t of e)!t.pairs||t.pairs.length===0||s.has(t.id)||k.push(...t.pairs);for(let t of e)s.has(t.id)||b.record(t.priceSample);if(h){let e=(Date.now()-S)/1e3;h({rowsRead:C,rowsSucceeded:w,rowsFailed:T,rowsSkipped:E,rowsWarned:D,batchesCompleted:O,elapsedSeconds:e,rowsPerSecond:e>0?C/e:0,distinctErrorPatterns:v.getDistinctPatternCount()})}},N=m,P=new Map;for await(let{rowNumber:t,row:n}of e(u)){if(_?.aborted||g!==void 0&&C>=g)break;if(C+=1,C===1&&x?.info({importRunId:i,rowNumber:t,sampleKeys:Object.keys(n)},`imports.runner: STREAM_FIRST_ROW`),C%N===0){let e=(Date.now()-S)/1e3;x?.info({importRunId:i,rowsRead:C,rowsSucceeded:w,rowsFailed:T,rowsSkipped:E,pending:j.length,elapsedSec:Math.round(e*10)/10,rowsPerSecond:e>0?Math.round(C/e):0,distinctFirstErrorTypes:P.size},`imports.runner: STREAM_TICK`)}let e={importRunId:i,params:s,runLabel:o,rowNumber:t},r;try{r=await c(n,e)}catch(e){let r=e instanceof Error?e.message:String(e);v.addError(t,`transform_threw`,r,void 0,n),P.has(`transform_threw`)||(P.set(`transform_threw`,{rowNumber:t,message:r}),x?.warn({importRunId:i,rowNumber:t,errorType:`transform_threw`,message:r},`imports.runner: FIRST_ERROR transform_threw`)),T+=1;continue}if(r.kind===`skip`){E+=1,r.patches&&r.patches.length>0&&A.push(...r.patches);continue}if(r.kind===`error`){v.addError(t,r.error.errorType,r.error.message,r.error.field,n),P.has(r.error.errorType)||(P.set(r.error.errorType,{rowNumber:t,message:r.error.message}),x?.warn({importRunId:i,rowNumber:t,errorType:r.error.errorType,field:r.error.field,message:r.error.message},`imports.runner: FIRST_ERROR ${r.error.errorType}`)),T+=1;continue}j.push({id:r.id,doc:r.doc,rowNumber:t,rowData:n,...r.warnings&&r.warnings.length>0&&{warnings:r.warnings},...r.pairs&&r.pairs.length>0&&{pairs:r.pairs},...r.priceSample!==void 0&&{priceSample:r.priceSample}}),j.length>=m&&await M()}await M();let F=0,I=0;for(let e=0;e<A.length;e+=m){if(_?.aborted)throw Error(`imports: run aborted during core-charge attach (phase 2)`);let n=A.slice(e,e+m),r;try{r=await t(d,{index:f,updates:n.map(({id:e,doc:t})=>({id:e,doc:t})),..._!==void 0&&{signal:_}})}catch(e){if(_?.aborted??(e instanceof Error&&(e.name===`AbortError`||/abort/i.test(e.message))))throw e;let t=e instanceof Error?e.message:String(e);for(let e of n)y.addError(-1,`patch_attach_failed`,t,e.orphanWarning?.field,{target:e.id});continue}if(F+=r.succeeded,r.failures.length>0){let e=new Map(n.map(e=>[e.id,e]));for(let t of r.failures){let n=e.get(t.id)?.orphanWarning;t.status===404||t.type===`document_missing_exception`?(I+=1,y.addError(-1,n?.warningType??`orphan_patch`,n?.message??t.reason,n?.field,{target:t.id})):y.addError(-1,`patch_attach_failed`,t.reason,n?.field,{target:t.id})}}}let L=(Date.now()-S)/1e3;return x?.info({importRunId:i,rowsRead:C,rowsSucceeded:w,rowsFailed:T,rowsSkipped:E,batchesCompleted:O,patchesApplied:F,patchesOrphaned:I,totalSec:Math.round(L*10)/10,rowsPerSecond:L>0?Math.round(C/L):0},`imports.runner: finished`),{rowsRead:C,rowsSucceeded:w,rowsFailed:T,rowsSkipped:E,rowsWarned:D,batchesCompleted:O,errors:v.snapshot(),warnings:y.snapshot(),pairs:k,patchesApplied:F,patchesOrphaned:I,priceStats:b.snapshot()}}export{c as a,f as c,a as d,o as f,u as i,r as l,m as n,l as o,s as r,d as s,p as t,i as u};
2
+ //# sourceMappingURL=runner-C9GIe5Dr.mjs.map