@wix/bex-core 2.329.0 → 2.331.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 (93) hide show
  1. package/dist/cjs/assets/visual-e2e-locale/messages_visuale2e.json +1 -0
  2. package/dist/cjs/hooks/useImport.js +2 -0
  3. package/dist/cjs/hooks/useImport.js.map +1 -1
  4. package/dist/cjs/hooks/useImportConfig.js.map +1 -1
  5. package/dist/cjs/index.js +5 -2
  6. package/dist/cjs/index.js.map +1 -1
  7. package/dist/cjs/services/DataExtensionFieldOperationsService.js +3 -3
  8. package/dist/cjs/services/DataExtensionFieldOperationsService.js.map +1 -1
  9. package/dist/cjs/state/ArchiveFieldModalState.js +5 -8
  10. package/dist/cjs/state/ArchiveFieldModalState.js.map +1 -1
  11. package/dist/cjs/state/CustomFieldModalBiReporter.js +5 -9
  12. package/dist/cjs/state/CustomFieldModalBiReporter.js.map +1 -1
  13. package/dist/cjs/state/CustomFieldModalState.js +32 -71
  14. package/dist/cjs/state/CustomFieldModalState.js.map +1 -1
  15. package/dist/cjs/state/DataExtensionState.js +0 -12
  16. package/dist/cjs/state/DataExtensionState.js.map +1 -1
  17. package/dist/cjs/state/DeleteFieldModalState.js +9 -11
  18. package/dist/cjs/state/DeleteFieldModalState.js.map +1 -1
  19. package/dist/cjs/state/{DataExtensionStateBIReporter.js → FieldOperationsBIReporter.js} +7 -32
  20. package/dist/cjs/state/FieldOperationsBIReporter.js.map +1 -0
  21. package/dist/cjs/state/ImportState/ImportState.js +47 -3
  22. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  23. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +139 -0
  24. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  25. package/dist/cjs/state/formatPermissionsForBi.js +36 -0
  26. package/dist/cjs/state/formatPermissionsForBi.js.map +1 -0
  27. package/dist/cjs/types/FieldsSource.js +4 -0
  28. package/dist/cjs/types/FieldsSource.js.map +1 -0
  29. package/dist/cjs/types/Schema.js.map +1 -1
  30. package/dist/cjs/types/SchemaSource.js +81 -0
  31. package/dist/cjs/types/SchemaSource.js.map +1 -0
  32. package/dist/esm/assets/visual-e2e-locale/messages_visuale2e.json +1 -0
  33. package/dist/esm/hooks/useImport.js +2 -1
  34. package/dist/esm/hooks/useImport.js.map +1 -1
  35. package/dist/esm/hooks/useImportConfig.js.map +1 -1
  36. package/dist/esm/index.js +1 -0
  37. package/dist/esm/index.js.map +1 -1
  38. package/dist/esm/services/DataExtensionFieldOperationsService.js +3 -3
  39. package/dist/esm/services/DataExtensionFieldOperationsService.js.map +1 -1
  40. package/dist/esm/state/ArchiveFieldModalState.js +4 -7
  41. package/dist/esm/state/ArchiveFieldModalState.js.map +1 -1
  42. package/dist/esm/state/CustomFieldModalBiReporter.js +5 -8
  43. package/dist/esm/state/CustomFieldModalBiReporter.js.map +1 -1
  44. package/dist/esm/state/CustomFieldModalState.js +28 -52
  45. package/dist/esm/state/CustomFieldModalState.js.map +1 -1
  46. package/dist/esm/state/DataExtensionState.js +0 -10
  47. package/dist/esm/state/DataExtensionState.js.map +1 -1
  48. package/dist/esm/state/DeleteFieldModalState.js +7 -10
  49. package/dist/esm/state/DeleteFieldModalState.js.map +1 -1
  50. package/dist/esm/state/{DataExtensionStateBIReporter.js → FieldOperationsBIReporter.js} +5 -25
  51. package/dist/esm/state/FieldOperationsBIReporter.js.map +1 -0
  52. package/dist/esm/state/ImportState/ImportState.js +43 -3
  53. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  54. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +89 -0
  55. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  56. package/dist/esm/state/formatPermissionsForBi.js +26 -0
  57. package/dist/esm/state/formatPermissionsForBi.js.map +1 -0
  58. package/dist/esm/types/FieldsSource.js +2 -0
  59. package/dist/esm/types/FieldsSource.js.map +1 -0
  60. package/dist/esm/types/SchemaSource.js +52 -0
  61. package/dist/esm/types/SchemaSource.js.map +1 -0
  62. package/dist/types/hooks/useImport.d.ts +11 -2
  63. package/dist/types/hooks/useImport.d.ts.map +1 -1
  64. package/dist/types/hooks/useImportConfig.d.ts +13 -2
  65. package/dist/types/hooks/useImportConfig.d.ts.map +1 -1
  66. package/dist/types/index.d.ts +4 -1
  67. package/dist/types/index.d.ts.map +1 -1
  68. package/dist/types/state/ArchiveFieldModalState.d.ts +7 -5
  69. package/dist/types/state/ArchiveFieldModalState.d.ts.map +1 -1
  70. package/dist/types/state/CustomFieldModalBiReporter.d.ts +4 -3
  71. package/dist/types/state/CustomFieldModalBiReporter.d.ts.map +1 -1
  72. package/dist/types/state/CustomFieldModalState.d.ts +12 -6
  73. package/dist/types/state/CustomFieldModalState.d.ts.map +1 -1
  74. package/dist/types/state/DataExtensionState.d.ts +0 -2
  75. package/dist/types/state/DataExtensionState.d.ts.map +1 -1
  76. package/dist/types/state/DeleteFieldModalState.d.ts +8 -5
  77. package/dist/types/state/DeleteFieldModalState.d.ts.map +1 -1
  78. package/dist/types/state/{DataExtensionStateBIReporter.d.ts → FieldOperationsBIReporter.d.ts} +4 -5
  79. package/dist/types/state/FieldOperationsBIReporter.d.ts.map +1 -0
  80. package/dist/types/state/ImportState/ImportState.d.ts +32 -4
  81. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  82. package/dist/types/state/formatPermissionsForBi.d.ts +7 -0
  83. package/dist/types/state/formatPermissionsForBi.d.ts.map +1 -0
  84. package/dist/types/types/FieldsSource.d.ts +116 -0
  85. package/dist/types/types/FieldsSource.d.ts.map +1 -0
  86. package/dist/types/types/Schema.d.ts +28 -11
  87. package/dist/types/types/Schema.d.ts.map +1 -1
  88. package/dist/types/types/SchemaSource.d.ts +60 -0
  89. package/dist/types/types/SchemaSource.d.ts.map +1 -0
  90. package/package.json +4 -4
  91. package/dist/cjs/state/DataExtensionStateBIReporter.js.map +0 -1
  92. package/dist/esm/state/DataExtensionStateBIReporter.js.map +0 -1
  93. package/dist/types/state/DataExtensionStateBIReporter.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","header","words","split","filter","Boolean","length","map","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","displayName","suffix","key","has","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","fields","collectionId","backup","updateSchema","collection","importModalState","translate","errorHandler","showToast","downloadCsv","onJobError","_detectColumnType","detectColumnType","hubJobClient","createHubJobClient","httpClient","makeObservable","currentStep","observable","ref","importStatus","fileName","csvHeaders","csvRows","mappingByHeader","writePolicy","processedCount","totalCount","result","isBackingUp","isRestoring","hasParsedRows","computed","hasMappings","hasNoMappedData","selectedFieldIds","idMappedHeader","setWritePolicy","action","bound","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","close","onFileSelected","startImport","reset","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","Set","m","kind","fieldId","entry","entries","find","mapping","policy","canCreateNewField","_this$_abortControlle","_abortController","abort","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","field","id","forEach","normalizedHeader","matched","fieldType","_columnValues","columnIndex","TYPE_SAMPLE_SIZE","applyParsedCsv","parsedCsv","rows","file","bytes","_readFileBytes","_showFileReadErrorToast","content","_decodeUtf8","_rejectFile","parseCsv","name","arrayBuffer","e","TextDecoder","fatal","decode","messageKey","_this$showToast","call","type","message","_this$showToast2","text","onClick","removeToastOnClick","_showPartialSuccessToast","_this$showToast3","String","imported","_downloadFailedRows","_this$downloadCsv","jobId","_fetchFailedRowIndices","failedRows","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","undefined","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","hasNext","cursors","next","indexOf","edit","config","_editingHeader","toFieldEdit","_runImportJob","resolvedMapping","csv","rewriteParsedCsvForImport","File","fileId","uploadFile","submitImportJob","destination","_destination","catch","job","pollImportJob","getJob","isCancelled","onProgress","polled","_applyJobProgress","status","JobStatus","FAILED","_job$error","assign","Error","code","response","data","details","applicationError","run","Promise","reject","wixDataCollection","progress","itemsSuccessful","itemsRejected","current","Math","min","_runBackup","restore","_lingerOnCompletion","resolve","setTimeout","_resolveFieldMapping","resolved","newFields","_mapping$displayName","baseName","add","backupFailed","loading","success"],"sources":["../../../../src/state/ImportState/ImportState.ts"],"sourcesContent":["import {\n action,\n computed,\n makeObservable,\n observable,\n runInAction,\n} from 'mobx';\nimport {\n queryStatus,\n ShowToast,\n TaskStatus,\n PatternsErrorHandler,\n} from '../../model';\nimport type { HttpClient } from '../../model/httpClient';\nimport { Translate, TranslationsKeys } from '../../services';\nimport { ModalState } from '../ModalState';\nimport { ConditionalModalState } from '../ConditionalModalState';\nimport { CreateExportAsyncJobRequest } from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';\nimport {\n JobStatus,\n WritePolicy,\n type Destination,\n type DataMovementJob,\n} from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\nimport { ParseCsvResult, parseCsv, unparseCsv } from './parseCsv';\nimport { rewriteParsedCsvForImport } from './rewriteCsv';\nimport { createHubJobClient, HubJobClient } from './hubJobClient';\nimport { pollImportJob } from './importJobPoller';\nimport {\n detectColumnType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { FieldSpec, NonReferenceField } from '../../types/Field';\nimport { toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n}\n\n/** Outcome of a server-side import job, derived from the job's progress. */\nexport interface ImportResult {\n succeeded: number;\n failed: number;\n}\n\nexport interface BackupResult {\n /**\n * Reverts the collection to its pre-import state. Called only when the user\n * cancels mid-import (matching the previous client-side behavior); a job\n * failure leaves partial rows in place and offers \"Try again\".\n *\n * Must fully revert to the snapshot taken before the import — including rows\n * the import overwrote in place. The default `writePolicy` is upsert (OVERWRITE\n * by `_id`), so it is NOT enough to delete newly-inserted ids; previously\n * existing rows may have been overwritten and must be restored to their prior\n * values.\n */\n restore(signal: AbortSignal): Promise<void>;\n}\n\n/**\n * Optional snapshot taken before the import runs, returning a `restore` used to\n * undo the import on cancel. See {@link BackupResult.restore} for the revert\n * contract under upsert.\n */\nexport type BackupFn = (signal: AbortSignal) => Promise<BackupResult | void>;\n\nexport type DownloadCsvFn = (content: string, fileName: string) => void;\n\n/**\n * Consumer hook for resolving a failed import job's message. An import runs\n * server-side, so a failure arrives on a 200 (the poll succeeds; the job\n * doesn't) with no HTTP error to carry the application error. Cairo hands the\n * consumer `run` — an operation that rejects with a synthetic, HTTP-error-shaped\n * error carrying the job's application error — and the consumer wraps it with\n * their own `withErrorHandler` + error-code map (their codes, their\n * translations), keeping the map coupled to the `withErrorHandler` call as\n * everywhere else (e.g. `fetchData`). The map is keyed by application-error code\n * (the v2 errorHandler shape, like `getExportAsyncJobErrors`):\n *\n * onJobError: (run) =>\n * errorHandler.withErrorHandler(run, {\n * [jobErrorCode]: (error) => ({ message: translate(...) }),\n * })\n *\n * `withErrorHandler` attaches the map to the error object and re-rejects it, so\n * the progress step resolves a consumer-specific message via `getResolvedError`.\n * When omitted, the error still surfaces but resolves to the generic message.\n */\nexport type OnImportJobError = (\n run: () => Promise<unknown>,\n) => Promise<unknown>;\n\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number];\n\n// `NewFieldType`, `detectColumnType`, etc. are re-exported from the package via\n// the `ImportState` barrel (`./index`), which also exports `./detectFieldType`.\n\n// Re-export the write-policy enum so consumers (and the cairo UI) reference it\n// from `@wix/bex-core` rather than the bundled ambassador path.\nexport { WritePolicy } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n\n// Per-type configuration for a new field, captured from the \"Edit field\" editor\n// (CAIRO-4398). All optional — an unedited field carries none and is created\n// from detected defaults only. `displayName` is intentionally not here: the\n// (possibly user-overridden) name is deduped and surfaced as\n// `NewFieldDefinition.displayName`.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n}\n\n// A new field to add to the collection schema during import. `key` is decided by\n// Cairo (derived from the column header — or the user's name override — deduped)\n// and is also the key the column's values are written under, so the consumer\n// must add the field under exactly this key. `config` carries any per-type\n// configuration the field editor produced; create the field with it.\nexport interface NewFieldDefinition {\n key: string;\n type: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n}\n\n/**\n * Consumer-supplied callback that adds the given new fields to the collection\n * schema in a single call, before the rows are uploaded. Mirrors the cm-import\n * `beforeImport`/`updateSchema` flow: Cairo decides the fields (and their keys),\n * the consumer performs one schema mutation (e.g. `updateSchema(collectionId,\n * ...addField(key, config))`). Its presence is also the opt-in for the \"create\n * new field\" default — see `getDefaultMapping`.\n */\nexport type UpdateSchemaFn = (fields: NewFieldDefinition[]) => Promise<void>;\n\n/**\n * How a CSV column is mapped:\n * - `existing` — into an existing collection field by id\n * - `new` — into a new field created during import. `fieldType` is the detected\n * type, or the type the user picked in the field editor. `displayName` and\n * `config` are present only once the user edited the pending field via the\n * \"Edit field\" editor — `displayName` overrides the header-derived name and\n * `config` carries the per-type configuration.\n * - `null` — don't import (skip)\n */\nexport type ColumnMapping =\n | { kind: 'existing'; fieldId: string }\n | {\n kind: 'new';\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n }\n | null;\n\nexport interface ImportStateProps {\n fields: CreateExportAsyncJobRequest['fields'];\n /** Wix httpClient used to drive the Hub Job (data-movement) API. */\n httpClient: HttpClient;\n /** Destination data collection the import writes into. */\n collectionId: string;\n backup?: BackupFn;\n updateSchema?: UpdateSchemaFn;\n /**\n * Infers a new field's type from its column data. Defaults to the primitive\n * detector (number / date / boolean / url / text). `@wix/patterns` injects a\n * media-aware detector from `@wix/patterns-fields` (image / video / document /\n * audio) — that detection needs the media URI parser, which core can't depend\n * on.\n */\n detectColumnType?: DetectColumnType;\n collection: ImportCollection;\n importModalState: ModalState;\n translate: Translate;\n errorHandler: PatternsErrorHandler;\n showToast?: ShowToast;\n downloadCsv?: DownloadCsvFn;\n /** See {@link OnImportJobError}. */\n onJobError?: OnImportJobError;\n}\n\nexport type ImportStep = 'upload' | 'configuration' | 'progress';\n\n// How long to keep the completed progress bar (100%) on screen before closing\n// the modal on a clean import. Without it, an import of very few rows finishes\n// near-instantly and the modal appears to vanish without ever showing the bar\n// reaching completion.\nconst COMPLETION_LINGER_MS = 600;\n\n// The Wix Data collection's id field key. A CSV column mapped to this field lets\n// the user choose how rows that collide on `_id` are written (writePolicy).\nconst ID_FIELD_KEY = '_id';\n\nfunction normalize(value: string) {\n return value.trim().toLowerCase();\n}\n\n// camelCase key for a field created from a column header\n// (e.g. \"Product Name\" -> \"productName\").\nfunction toFieldKey(header: string): string {\n const words = header\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n if (words.length === 0) {\n return 'field';\n }\n return words\n .map((word, index) =>\n index === 0\n ? word.charAt(0).toLowerCase() + word.slice(1)\n : word.charAt(0).toUpperCase() + word.slice(1),\n )\n .join('');\n}\n\n// A display name + key for a field created from a column header, unique against\n// both `usedNames` (existing field display names + names already assigned to\n// earlier new columns) and `usedKeys` (existing field ids + keys already\n// assigned). Mirrors cm-import `generateFieldNameAndKey`: when the name or its\n// derived key collides, suffix the *display name* as `\"<header>-<n>\"` and\n// re-derive the key from it — so the created field's name and key are both\n// unique (otherwise two columns with the same header would create fields showing\n// the same name).\nfunction uniqueFieldNameAndKey(\n header: string,\n usedNames: Set<string>,\n usedKeys: Set<string>,\n): { displayName: string; key: string } {\n let displayName = header;\n for (let suffix = 1; ; suffix++) {\n const key = toFieldKey(displayName);\n if (!usedNames.has(displayName) && !usedKeys.has(key)) {\n return { displayName, key };\n }\n displayName = `${header}-${suffix}`;\n }\n}\n\nexport class ImportState {\n readonly fields: ImportField[];\n readonly collectionId: string;\n readonly backup?: BackupFn;\n readonly updateSchema?: UpdateSchemaFn;\n readonly collection: ImportCollection;\n readonly importModalState: ModalState;\n readonly translate: Translate;\n readonly errorHandler: PatternsErrorHandler;\n readonly showToast?: ShowToast;\n readonly downloadCsv?: DownloadCsvFn;\n readonly onJobError?: OnImportJobError;\n private readonly hubJobClient: HubJobClient;\n private readonly _detectColumnType: DetectColumnType;\n readonly discardChangesModal = new ConditionalModalState<\n 'goBack' | 'close'\n >();\n\n currentStep: ImportStep = 'upload';\n importStatus: TaskStatus<ImportResult, unknown> = {\n ...queryStatus.idle,\n };\n fileName = '';\n csvHeaders: string[] = [];\n csvRows: string[][] = [];\n mappingByHeader: Record<string, ColumnMapping> = {};\n // How rows that collide on `_id` are written. Only meaningful (and only sent\n // to the server) when a CSV column is mapped to the `_id` field — see\n // `idMappedHeader` and `_destination`. Defaults to the server default\n // (`OVERWRITE` = upsert by `_id`).\n //\n // Retention: the choice is deliberately kept while editing mappings within a\n // file — remapping `_id` away and back keeps the user's selection rather than\n // silently reverting it. It resets to the default only on a *new file* upload\n // (`applyParsedCsv`) or a full `reset()`.\n writePolicy: WritePolicy = WritePolicy.OVERWRITE;\n processedCount = 0;\n totalCount = 0;\n result: ImportResult = {\n succeeded: 0,\n failed: 0,\n };\n isBackingUp = false;\n isRestoring = false;\n private restoreFn: ((signal: AbortSignal) => Promise<void>) | null = null;\n private _cancelled = false;\n private _abortController: AbortController | null = null;\n // Id of the running data-movement job, set once submitted — used to cancel it\n // (`terminateJob`) if the user closes mid-import.\n private _jobId: string | null = null;\n // The column whose pending new field the field editor is currently editing.\n // Not observable — transient wiring between `beginFieldEdit` and the editor's\n // `applyFieldEdit` callback, never rendered.\n private _editingHeader: string | null = null;\n\n constructor(props: ImportStateProps) {\n this.fields = (props.fields ?? []) as ImportField[];\n this.collectionId = props.collectionId;\n this.backup = props.backup;\n this.updateSchema = props.updateSchema;\n this.collection = props.collection;\n this.importModalState = props.importModalState;\n this.translate = props.translate;\n this.errorHandler = props.errorHandler;\n this.showToast = props.showToast;\n this.downloadCsv = props.downloadCsv;\n this.onJobError = props.onJobError;\n this._detectColumnType = props.detectColumnType ?? detectColumnType;\n this.hubJobClient = createHubJobClient({\n httpClient: props.httpClient,\n errorHandler: props.errorHandler,\n });\n\n makeObservable(this, {\n currentStep: observable.ref,\n importStatus: observable.ref,\n fileName: observable.ref,\n csvHeaders: observable.ref,\n csvRows: observable.ref,\n mappingByHeader: observable.ref,\n writePolicy: observable.ref,\n processedCount: observable.ref,\n totalCount: observable.ref,\n result: observable.ref,\n isBackingUp: observable.ref,\n isRestoring: observable.ref,\n hasParsedRows: computed,\n hasMappings: computed,\n hasNoMappedData: computed,\n selectedFieldIds: computed,\n idMappedHeader: computed,\n setWritePolicy: action.bound,\n onUploadContinue: action.bound,\n goToUpload: action.bound,\n setMapping: action.bound,\n setNewFieldMapping: action.bound,\n setNewFieldConfig: action.bound,\n beginFieldEdit: action.bound,\n applyFieldEdit: action.bound,\n close: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n init() {\n return () => {\n // Unmounting mid-import stops the poll loop (it checks `_cancelled`) so it\n // doesn't run to terminal holding references. We deliberately do NOT abort\n // the AbortController: during a cancel-triggered restore it holds the\n // restore controller, and aborting it would cancel an in-progress restore.\n // The server-side job is also left running — an unmount isn't an explicit\n // user cancel.\n this._cancelled = true;\n };\n }\n\n get hasParsedRows() {\n return this.csvHeaders.length > 0 && this.csvRows.length > 0;\n }\n\n get hasMappings() {\n return Object.values(this.mappingByHeader).some((value) => value != null);\n }\n\n /**\n * True when there are mappings but none of the mapped columns contain any\n * data in any row (including the case of zero data rows). Drives the\n * non-blocking \"no rows found\" warning in the configuration step. Returns\n * false when nothing is mapped yet — that case is handled by the disabled\n * import button instead.\n */\n get hasNoMappedData(): boolean {\n if (!this.hasMappings) {\n return false;\n }\n\n const mappedIndices = this.csvHeaders.reduce<number[]>(\n (indices, header, index) => {\n if (this.mappingByHeader[header] != null) {\n indices.push(index);\n }\n return indices;\n },\n [],\n );\n\n return !this.csvRows.some((row) =>\n mappedIndices.some((index) => (row[index] ?? '').trim() !== ''),\n );\n }\n\n get selectedFieldIds(): Set<string> {\n return new Set(\n Object.values(this.mappingByHeader)\n .filter(\n (m): m is { kind: 'existing'; fieldId: string } =>\n m?.kind === 'existing',\n )\n .map((m) => m.fieldId),\n );\n }\n\n /**\n * The CSV header currently mapped to the collection's `_id` field, or `null`\n * when no column targets it. Drives both the \"When items share the same ID\"\n * control (only shown on this row) and whether `writePolicy` is sent at all —\n * with no `_id` mapped, every row is a fresh insert and collisions can't occur.\n */\n get idMappedHeader(): string | null {\n const entry = Object.entries(this.mappingByHeader).find(\n ([, mapping]) =>\n mapping?.kind === 'existing' && mapping.fieldId === ID_FIELD_KEY,\n );\n return entry ? entry[0] : null;\n }\n\n setWritePolicy(policy: WritePolicy) {\n this.writePolicy = policy;\n }\n\n /**\n * Whether columns may be mapped to a brand-new field created during import.\n * Driven purely by the presence of the `updateSchema` callback — providing the\n * capability is the opt-in (see `getDefaultMapping`). Never changes after\n * construction, so it isn't an observable.\n */\n get canCreateNewField(): boolean {\n return this.updateSchema != null;\n }\n\n reset() {\n this._abortController?.abort();\n this._abortController = null;\n this.currentStep = 'upload';\n this.importStatus = {\n ...queryStatus.idle,\n };\n this.fileName = '';\n this.csvHeaders = [];\n this.csvRows = [];\n this.mappingByHeader = {};\n this.writePolicy = WritePolicy.OVERWRITE;\n this.processedCount = 0;\n this.totalCount = 0;\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this.isBackingUp = false;\n this.isRestoring = false;\n this.restoreFn = null;\n this._cancelled = false;\n this._jobId = null;\n }\n\n async close() {\n // While on the progress step we treat close as a cancel — terminate the job\n // and restore the backup — UNLESS the import already succeeded. On the\n // success path `startImport` lingers ~600ms on the completed bar with the\n // step still 'progress'; closing during that window must NOT restore (it\n // would undo a clean import). A successful close just closes the modal and\n // lets the success path do its collection refresh.\n if (this.currentStep === 'progress' && !this.importStatus.isSuccess) {\n this._cancelled = true;\n this._abortController?.abort();\n\n // Stop the server-side job. It does not roll back rows already written —\n // that's what the backup restore below is for.\n if (this._jobId) {\n try {\n await this.hubJobClient.terminateJob(this._jobId);\n } catch (error) {\n console.error('Terminate import job failed', error);\n }\n }\n\n if (!this.isBackingUp) {\n await this._restoreBackup();\n }\n\n this.collection.clearResultAndMoveToStart({\n force: true,\n });\n }\n\n this.importModalState.close();\n }\n\n private async _restoreBackup() {\n const restoreFn = this.restoreFn;\n if (!restoreFn) {\n return;\n }\n\n const restoreController = new AbortController();\n this._abortController = restoreController;\n\n this.isRestoring = true;\n try {\n await restoreFn(restoreController.signal);\n } catch (error) {\n console.error('Restore failed', error);\n }\n runInAction(() => {\n this.isRestoring = false;\n this.restoreFn = null;\n });\n }\n\n goToUpload() {\n this.currentStep = 'upload';\n }\n\n async discardAndGoBack() {\n this.discardChangesModal.open('goBack');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.goToUpload();\n }\n }\n\n async discardAndClose() {\n this.discardChangesModal.open('close');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.close();\n }\n }\n\n onUploadContinue() {\n if (this.hasParsedRows) {\n this.currentStep = 'configuration';\n }\n }\n\n private getDefaultMapping(headers: string[]) {\n const mapping: Record<string, ColumnMapping> = {};\n const fields = this.fields.map((field) => ({\n id: field.id ?? '',\n header: field.header ?? '',\n }));\n\n headers.forEach((header, index) => {\n const normalizedHeader = normalize(header);\n const matched = fields.find(\n (field) =>\n normalize(field.id) === normalizedHeader ||\n normalize(field.header) === normalizedHeader,\n );\n\n if (matched?.id) {\n mapping[header] = { kind: 'existing', fieldId: matched.id };\n } else {\n // Unmatched columns default to creating a new field (type inferred from\n // the column's data) when the consumer supplied `updateSchema`;\n // otherwise they default to skip.\n mapping[header] = this.canCreateNewField\n ? {\n kind: 'new',\n fieldType: this._detectColumnType(this._columnValues(index)),\n }\n : null;\n }\n });\n\n return mapping;\n }\n\n // The column's values, capped at the detection sample size — detection only\n // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole\n // column (a wide CSV would otherwise allocate rows × columns strings).\n private _columnValues(columnIndex: number): string[] {\n return this.csvRows\n .slice(0, TYPE_SAMPLE_SIZE)\n .map((row) => row[columnIndex] ?? '');\n }\n\n private applyParsedCsv(fileName: string, parsedCsv: ParseCsvResult) {\n this.fileName = fileName;\n this.csvHeaders = parsedCsv.headers;\n this.csvRows = parsedCsv.rows;\n this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);\n // A new file is a fresh import: start from the default policy so a prior\n // file's Skip choice doesn't silently carry over (only the new-file path\n // resets — remapping `_id` within the same file keeps the user's choice).\n this.writePolicy = WritePolicy.OVERWRITE;\n this.currentStep = 'configuration';\n }\n\n async onFileSelected(file: File | null) {\n if (file == null) {\n return;\n }\n\n const bytes = await this._readFileBytes(file);\n if (bytes == null) {\n this._showFileReadErrorToast(file);\n return;\n }\n\n const content = this._decodeUtf8(bytes);\n if (content == null) {\n this._rejectFile(file, 'cairo.import.encodingFailed');\n return;\n }\n\n const parsedCsv = parseCsv(content);\n if ('code' in parsedCsv) {\n this._rejectFile(file, 'cairo.import.processFailed');\n return;\n }\n\n runInAction(() => {\n this.applyParsedCsv(file.name, parsedCsv);\n });\n }\n\n private async _readFileBytes(file: File): Promise<ArrayBuffer | null> {\n try {\n return await file.arrayBuffer();\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _decodeUtf8(bytes: ArrayBuffer): string | null {\n try {\n // `fatal: true` throws on any byte sequence that isn't valid UTF-8,\n // so encoding is validated against the raw bytes before decoding —\n // unlike `File.text()`, which silently substitutes U+FFFD.\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _rejectFile(file: File, messageKey: TranslationsKeys) {\n runInAction(() => {\n this.fileName = file.name;\n this.csvHeaders = [];\n this.csvRows = [];\n this.mappingByHeader = {};\n this.currentStep = 'upload';\n });\n this.showToast?.({\n type: 'ERROR',\n message: this.translate(messageKey),\n });\n }\n\n private _showFileReadErrorToast(file: File) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.fileReadFailed'),\n action: {\n text: this.translate('cairo.import.tryAgain'),\n onClick: () => this.onFileSelected(file),\n removeToastOnClick: true,\n },\n });\n }\n\n private _showPartialSuccessToast() {\n this.showToast?.({\n type: 'WARNING',\n message: this.translate('cairo.import.partialSuccessToast', {\n failed: String(this.result.failed),\n imported: String(this.result.succeeded),\n }),\n action: {\n text: this.translate('cairo.import.downloadFailedRows'),\n onClick: () => this._downloadFailedRows(),\n removeToastOnClick: true,\n },\n });\n }\n\n /**\n * Builds a plain, re-importable CSV of the rows the server rejected — the\n * original headers plus just the failed rows — and hands it to `downloadCsv`.\n * The failed rows come from the job's movement logs (which row failed), mapped\n * back to the parsed `csvRows` we still hold in memory.\n */\n private async _downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let indices: number[];\n try {\n indices = await this._fetchFailedRowIndices(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const failedRows = indices\n .map((index) => this.csvRows[index])\n .filter((row): row is string[] => row != null);\n\n if (failedRows.length === 0) {\n return;\n }\n\n const content = unparseCsv(this.csvHeaders, failedRows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns the `csvRows` indices of\n // the rows that failed. data-hub's CSV decoder\n // (wix-data-hub: packages/wix-data-hub-executor-c/src/plugins/formats/csv/\n // csv-binary-decoder.ts) parses with the `csv-parse` library (`columns: true`)\n // and sets `sourceItemId = \"row ${++index + 1}\"`, incrementing once **per\n // record** — not per physical line. So N is the 1-based record number with\n // the header consumed as columns: the first data record is `\"row 2\"` →\n // `csvRows[0]`, i.e. `csvRows[N - 2]`. Because `csv-parse` is RFC-4180,\n // quoted cells containing embedded newlines are a single record, so they do\n // NOT shift the numbering. Out-of-range indices are guarded below.\n private async _fetchFailedRowIndices(jobId: string): Promise<number[]> {\n const indices: number[] = [];\n let cursor: string | undefined;\n\n do {\n const { logs, pagingMetadata } = await this.hubJobClient.listMovementLogs(\n jobId,\n cursor ? { cursor } : undefined,\n );\n\n for (const log of logs ?? []) {\n if (!log.failure || log.sourceItemId == null) {\n continue;\n }\n const fileLine = Number(/\\d+/.exec(log.sourceItemId)?.[0]);\n const index = fileLine - 2;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < this.csvRows.length\n ) {\n indices.push(index);\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return indices;\n }\n\n setMapping(header: string, fieldId: string | null) {\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: fieldId == null ? null : { kind: 'existing', fieldId },\n };\n }\n\n setNewFieldMapping(header: string) {\n const index = this.csvHeaders.indexOf(header);\n const fieldType =\n index >= 0 ? this._detectColumnType(this._columnValues(index)) : 'text';\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: { kind: 'new', fieldType },\n };\n }\n\n /**\n * Persists the result of the \"Edit field\" editor for a column's pending new\n * field: the (possibly overridden) type, an optional display-name override,\n * and the per-type configuration. No-op if the column isn't currently mapped\n * to a new field.\n */\n setNewFieldConfig(\n header: string,\n edit: {\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n },\n ) {\n const mapping = this.mappingByHeader[header];\n if (mapping?.kind !== 'new') {\n return;\n }\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: {\n kind: 'new',\n fieldType: edit.fieldType,\n ...(edit.displayName != null && { displayName: edit.displayName }),\n ...(edit.config && { config: edit.config }),\n },\n };\n }\n\n /**\n * Marks which column's pending new field the field editor is currently\n * editing, so a later `applyFieldEdit` (the editor's `onSubmit`) knows where to\n * write the result.\n */\n beginFieldEdit(header: string) {\n this._editingHeader = header;\n }\n\n /**\n * `onSubmit` handler for the field editor: maps the edited field spec into the\n * column being edited (set via `beginFieldEdit`). No-op if nothing is being\n * edited.\n */\n applyFieldEdit(field: FieldSpec) {\n if (this._editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this._editingHeader, toFieldEdit(field));\n }\n\n /**\n * Runs the server-side import: align the CSV to the resolved field keys,\n * upload it, submit a data-movement job, then poll until terminal. Throws on\n * a failed job so `startImport` surfaces the error state; partial success is\n * reported via `result.failed` and the partial toast.\n */\n private async _runImportJob(\n resolvedMapping: Record<string, string | null>,\n ): Promise<ImportResult> {\n const csv = rewriteParsedCsvForImport(\n this.csvHeaders,\n this.csvRows,\n resolvedMapping,\n );\n const file = new File([csv], this.fileName || 'import.csv', {\n type: 'text/csv',\n });\n\n const fileId = await this.hubJobClient.uploadFile(file);\n if (this._cancelled) {\n return this.result;\n }\n\n const jobId = await this.hubJobClient.submitImportJob({\n fileId,\n name: this.fileName,\n destination: this._destination(),\n });\n runInAction(() => {\n this._jobId = jobId;\n });\n if (this._cancelled) {\n // The user cancelled while `submitImportJob` was in flight, so `close()`\n // saw no `_jobId` and couldn't terminate it. Terminate it here, otherwise\n // the job keeps importing server-side after cancel (and would overwrite a\n // restored backup).\n await this.hubJobClient.terminateJob(jobId).catch(() => undefined);\n return this.result;\n }\n\n const job = await pollImportJob(\n (id) => this.hubJobClient.getJob(id),\n jobId,\n {\n isCancelled: () => this._cancelled,\n onProgress: (polled) => this._applyJobProgress(polled),\n },\n );\n\n // `null` means cancelled mid-poll — leave whatever progress we have.\n if (!job) {\n return this.result;\n }\n\n if (job.status === JobStatus.FAILED) {\n // The job ran server-side, so a failure arrives on a 200 (the poll\n // succeeded; the job didn't) with no HTTP error to carry the application\n // error. Build a synthetic, HTTP-error-shaped error (the error handler\n // reads the code from `response.data.details.applicationError`) and hand\n // the throwing operation to the consumer's `onJobError` so THEY wrap it\n // with their own `withErrorHandler` + error-code map — `job.error` is the\n // consumer's application error (their import business logic), so only they\n // can map its codes, and the map stays coupled to the `withErrorHandler`\n // call as everywhere else (e.g. `fetchData`). The map is attached to the\n // error object, which the progress step resolves via `getResolvedError`.\n // Without a handler the same error still throws, falling back to the\n // generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n const run = (): Promise<unknown> => Promise.reject(error);\n\n if (this.onJobError) {\n // The consumer wraps `run` with `withErrorHandler`; it re-rejects with\n // `error` (now carrying their map), which propagates from here.\n await this.onJobError(run);\n }\n throw error;\n }\n\n this._applyJobProgress(job);\n return this.result;\n }\n\n // Destination: the consumer's Wix Data collection. `writePolicy` is sent only\n // when a CSV column is mapped to `_id` (the only case collisions can occur);\n // otherwise it's omitted and the server applies its default (upsert by `_id`).\n private _destination(): Destination {\n return {\n wixDataCollection: {\n collectionId: this.collectionId,\n ...(this.idMappedHeader != null && { writePolicy: this.writePolicy }),\n },\n };\n }\n\n private _applyJobProgress(job: DataMovementJob) {\n const progress = job.progress;\n const succeeded = progress?.itemsSuccessful ?? 0;\n const failed = progress?.itemsRejected ?? 0;\n const current = progress?.current ?? succeeded + failed;\n\n // `totalCount` is fixed up front in `startImport` from the CSV row count\n // (one uploaded row per CSV row); polling only advances `processedCount`.\n runInAction(() => {\n this.processedCount = Math.min(current, this.totalCount);\n this.result = { succeeded, failed };\n });\n }\n\n private async _runBackup(): Promise<boolean> {\n const backup = this.backup;\n if (!backup) {\n return false;\n }\n\n try {\n const result = await backup(this._abortController!.signal);\n if (this._cancelled) {\n return true;\n }\n if (result?.restore) {\n this.restoreFn = result.restore;\n }\n } catch (error) {\n if (this._cancelled) {\n return true;\n }\n runInAction(() => {\n this.isBackingUp = false;\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return true;\n }\n\n runInAction(() => {\n this.isBackingUp = false;\n });\n return false;\n }\n\n private _lingerOnCompletion() {\n return new Promise<void>((resolve) =>\n setTimeout(resolve, COMPLETION_LINGER_MS),\n );\n }\n\n /**\n * Resolves every column to the final destination key used in the upload\n * payload: an existing field id, a new field's (Cairo-decided) key, or `null`\n * to skip. All new fields are added to the schema in a single `updateSchema`\n * call before the rows upload — mirroring the cm-import `beforeImport` flow.\n * `updateSchema` may throw — `startImport` surfaces that as the error state.\n */\n private async _resolveFieldMapping(): Promise<Record<string, string | null>> {\n const resolved: Record<string, string | null> = {};\n const newFields: NewFieldDefinition[] = [];\n // Seed with existing field ids/display names so derived keys and names never\n // collide with them or with each other.\n const usedKeys = new Set(\n this.fields.map((field) => field.id).filter((id): id is string => !!id),\n );\n const usedNames = new Set(\n this.fields\n .map((field) => field.header)\n .filter((header): header is string => !!header),\n );\n\n for (const header of this.csvHeaders) {\n const mapping = this.mappingByHeader[header];\n\n if (mapping == null) {\n resolved[header] = null;\n } else if (mapping.kind === 'existing') {\n resolved[header] = mapping.fieldId;\n } else if (this.updateSchema) {\n // The user's name override (from the field editor) seeds the unique\n // name/key derivation; otherwise fall back to the column header.\n const baseName = mapping.displayName?.trim() || header;\n const { displayName, key } = uniqueFieldNameAndKey(\n baseName,\n usedNames,\n usedKeys,\n );\n usedKeys.add(key);\n usedNames.add(displayName);\n newFields.push({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n });\n resolved[header] = key;\n } else {\n // \"new\" mapping without an `updateSchema` callback — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (newFields.length > 0 && this.updateSchema) {\n await this.updateSchema(newFields);\n }\n\n return resolved;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n this._cancelled = false;\n this._abortController = new AbortController();\n\n // One uploaded row per CSV row (the rewrite drops columns, not rows), so the\n // total is known up front from the parsed CSV and stays fixed through polling.\n const totalCount = this.csvRows.length;\n\n runInAction(() => {\n this.currentStep = 'progress';\n this.totalCount = totalCount;\n this.processedCount = 0;\n this.isBackingUp = !!this.backup;\n // Clear any error/result from a previous attempt so \"Try again\" starts\n // from a clean slate (e.g. after a backup failure).\n this.importStatus = { ...queryStatus.idle };\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this._jobId = null;\n });\n\n const backupFailed = await this._runBackup();\n if (backupFailed) {\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n // Create any new fields and resolve every column to its destination key\n // before uploading. A creation failure surfaces as the error state with a\n // \"Try again\" CTA, like an upload/job failure.\n let resolvedMapping: Record<string, string | null>;\n try {\n resolvedMapping = await this._resolveFieldMapping();\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n const promise = this._runImportJob(resolvedMapping);\n\n this.importStatus = {\n ...queryStatus.loading,\n promise,\n };\n\n try {\n await promise;\n if (this._cancelled) {\n return;\n }\n\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.success,\n data: this.result,\n };\n });\n\n // On a clean import, hold the completed (100%) progress bar on screen\n // briefly so the completion is perceptible even for very few rows. Skip\n // the wait when there are failed rows — that path closes and surfaces a\n // toast instead.\n if (this.result.failed === 0) {\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n }\n\n runInAction(() => {\n // Rows the server rejected are reported via a toast (the downloadable\n // failed-rows report is added by the failed-rows-report task).\n if (this.result.failed > 0) {\n this._showPartialSuccessToast();\n }\n\n this.importModalState.close();\n this.collection.clearResultAndMoveToStart({ force: true });\n });\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAOA,IAAA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AC,MAAM;QAChB,IAAI,CAACnE,YAAY,GAAG;UAClB,GAAGzB,kBAAW,CAACoF,KAAK;UACpBA;QACF,CAAC;MACH,CAAC,CAAC;IACJ;EACF;AACF;AAAC7H,OAAA,CAAAmC,WAAA,GAAAA,WAAA","ignoreList":[]}
1
+ {"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","header","words","split","filter","Boolean","length","map","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","displayName","suffix","key","has","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","fields","collectionId","destination","backup","updateSchema","collection","importModalState","translate","errorHandler","showToast","downloadCsv","onJobError","_detectColumnType","detectColumnType","hubJobClient","createHubJobClient","httpClient","makeObservable","currentStep","observable","ref","importStatus","fileName","csvHeaders","csvRows","orderedHeaders","mappingByHeader","writePolicy","processedCount","totalCount","result","isBackingUp","isRestoring","hasParsedRows","computed","hasMappings","hasNoMappedData","selectedFieldIds","idMappedHeader","setWritePolicy","action","bound","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","close","onFileSelected","startImport","reset","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","Set","m","kind","fieldId","entry","entries","find","mapping","policy","canCreateNewField","canConfigureWritePolicy","_this$_abortControlle","_abortController","abort","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","field","id","forEach","normalizedHeader","matched","fieldType","_columnValues","columnIndex","TYPE_SAMPLE_SIZE","_orderHeadersWithIdFirst","idHeader","applyParsedCsv","parsedCsv","rows","file","bytes","_readFileBytes","_showFileReadErrorToast","content","_decodeUtf8","_rejectFile","parseCsv","name","arrayBuffer","e","TextDecoder","fatal","decode","messageKey","_this$showToast","call","type","message","_this$showToast2","text","onClick","removeToastOnClick","_showPartialSuccessToast","_this$showToast3","String","imported","_downloadFailedRows","_this$downloadCsv","jobId","_fetchFailedRowIndices","failedRows","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","undefined","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","hasNext","cursors","next","indexOf","edit","config","_editingHeader","toFieldEdit","_runImportJob","resolvedMapping","csv","rewriteParsedCsvForImport","File","fileId","uploadFile","submitImportJob","_destination","catch","job","pollImportJob","getJob","isCancelled","onProgress","polled","_applyJobProgress","status","JobStatus","FAILED","_job$error","assign","Error","code","response","data","details","applicationError","run","Promise","reject","wixDataCollection","progress","itemsSuccessful","itemsRejected","current","Math","min","_runBackup","restore","_lingerOnCompletion","resolve","setTimeout","_resolveFieldMapping","resolved","newFields","_mapping$displayName","baseName","add","backupFailed","loading","success"],"sources":["../../../../src/state/ImportState/ImportState.ts"],"sourcesContent":["import {\n action,\n computed,\n makeObservable,\n observable,\n runInAction,\n} from 'mobx';\nimport {\n queryStatus,\n ShowToast,\n TaskStatus,\n PatternsErrorHandler,\n} from '../../model';\nimport type { HttpClient } from '../../model/httpClient';\nimport { Translate, TranslationsKeys } from '../../services';\nimport { ModalState } from '../ModalState';\nimport { ConditionalModalState } from '../ConditionalModalState';\nimport { CreateExportAsyncJobRequest } from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';\nimport {\n JobStatus,\n WritePolicy,\n type Destination,\n type DataMovementJob,\n} from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\nimport { ParseCsvResult, parseCsv, unparseCsv } from './parseCsv';\nimport { rewriteParsedCsvForImport } from './rewriteCsv';\nimport { createHubJobClient, HubJobClient } from './hubJobClient';\nimport { pollImportJob } from './importJobPoller';\nimport {\n detectColumnType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { FieldSpec, NonReferenceField } from '../../types/Field';\nimport { toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n}\n\n/** Outcome of a server-side import job, derived from the job's progress. */\nexport interface ImportResult {\n succeeded: number;\n failed: number;\n}\n\nexport interface BackupResult {\n /**\n * Reverts the collection to its pre-import state. Called only when the user\n * cancels mid-import (matching the previous client-side behavior); a job\n * failure leaves partial rows in place and offers \"Try again\".\n *\n * Must fully revert to the snapshot taken before the import — including rows\n * the import overwrote in place. The default `writePolicy` is upsert (OVERWRITE\n * by `_id`), so it is NOT enough to delete newly-inserted ids; previously\n * existing rows may have been overwritten and must be restored to their prior\n * values.\n */\n restore(signal: AbortSignal): Promise<void>;\n}\n\n/**\n * Optional snapshot taken before the import runs, returning a `restore` used to\n * undo the import on cancel. See {@link BackupResult.restore} for the revert\n * contract under upsert.\n */\nexport type BackupFn = (signal: AbortSignal) => Promise<BackupResult | void>;\n\nexport type DownloadCsvFn = (content: string, fileName: string) => void;\n\n/**\n * Consumer hook for resolving a failed import job's message. An import runs\n * server-side, so a failure arrives on a 200 (the poll succeeds; the job\n * doesn't) with no HTTP error to carry the application error. Cairo hands the\n * consumer `run` — an operation that rejects with a synthetic, HTTP-error-shaped\n * error carrying the job's application error — and the consumer wraps it with\n * their own `withErrorHandler` + error-code map (their codes, their\n * translations), keeping the map coupled to the `withErrorHandler` call as\n * everywhere else (e.g. `fetchData`). The map is keyed by application-error code\n * (the v2 errorHandler shape, like `getExportAsyncJobErrors`):\n *\n * onJobError: (run) =>\n * errorHandler.withErrorHandler(run, {\n * [jobErrorCode]: (error) => ({ message: translate(...) }),\n * })\n *\n * `withErrorHandler` attaches the map to the error object and re-rejects it, so\n * the progress step resolves a consumer-specific message via `getResolvedError`.\n * When omitted, the error still surfaces but resolves to the generic message.\n */\nexport type OnImportJobError = (\n run: () => Promise<unknown>,\n) => Promise<unknown>;\n\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number];\n\n// `NewFieldType`, `detectColumnType`, etc. are re-exported from the package via\n// the `ImportState` barrel (`./index`), which also exports `./detectFieldType`.\n\n// Re-export the write-policy enum so consumers (and the cairo UI) reference it\n// from `@wix/bex-core` rather than the bundled ambassador path.\nexport { WritePolicy } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n// Re-export the destination type for platformized consumers that supply their\n// own variant (e.g. `{ storesCatalogProducts: {} }`) — same reason as above.\nexport type { Destination } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n\n// Per-type configuration for a new field, captured from the \"Edit field\" editor\n// (CAIRO-4398). All optional — an unedited field carries none and is created\n// from detected defaults only. `displayName` is intentionally not here: the\n// (possibly user-overridden) name is deduped and surfaced as\n// `NewFieldDefinition.displayName`.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n}\n\n// A new field to add to the collection schema during import. `key` is decided by\n// Cairo (derived from the column header — or the user's name override — deduped)\n// and is also the key the column's values are written under, so the consumer\n// must add the field under exactly this key. `config` carries any per-type\n// configuration the field editor produced; create the field with it.\nexport interface NewFieldDefinition {\n key: string;\n type: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n}\n\n/**\n * Consumer-supplied callback that adds the given new fields to the collection\n * schema in a single call, before the rows are uploaded. Mirrors the cm-import\n * `beforeImport`/`updateSchema` flow: Cairo decides the fields (and their keys),\n * the consumer performs one schema mutation (e.g. `updateSchema(collectionId,\n * ...addField(key, config))`). Its presence is also the opt-in for the \"create\n * new field\" default — see `getDefaultMapping`.\n */\nexport type UpdateSchemaFn = (fields: NewFieldDefinition[]) => Promise<void>;\n\n/**\n * How a CSV column is mapped:\n * - `existing` — into an existing collection field by id\n * - `new` — into a new field created during import. `fieldType` is the detected\n * type, or the type the user picked in the field editor. `displayName` and\n * `config` are present only once the user edited the pending field via the\n * \"Edit field\" editor — `displayName` overrides the header-derived name and\n * `config` carries the per-type configuration.\n * - `null` — don't import (skip)\n */\nexport type ColumnMapping =\n | { kind: 'existing'; fieldId: string }\n | {\n kind: 'new';\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n }\n | null;\n\nexport interface ImportStateProps {\n fields: CreateExportAsyncJobRequest['fields'];\n /** Wix httpClient used to drive the Hub Job (data-movement) API. */\n httpClient: HttpClient;\n /**\n * Destination data collection the import writes into. Used to build the\n * default Wix Data destination. Optional only because a platformized consumer\n * may instead supply its own `destination` — exactly one of `collectionId` or\n * `destination` must be provided.\n */\n collectionId?: string;\n /**\n * Where the job writes, for platformized (non–Wix-Data) consumers. data-hub's\n * `Destination` is a union, and internal services write through their own\n * variant (e.g. `{ storesCatalogProducts: {} }`), not `wixDataCollection`.\n * When provided, it's sent verbatim and `collectionId`/`writePolicy` are\n * ignored. When omitted, Cairo builds `{ wixDataCollection: { collectionId,\n * writePolicy } }` from `collectionId` (the common CMS case). See plan O6.\n */\n destination?: Destination;\n backup?: BackupFn;\n updateSchema?: UpdateSchemaFn;\n /**\n * Infers a new field's type from its column data. Defaults to the primitive\n * detector (number / date / boolean / url / text). `@wix/patterns` injects a\n * media-aware detector from `@wix/patterns-fields` (image / video / document /\n * audio) — that detection needs the media URI parser, which core can't depend\n * on.\n */\n detectColumnType?: DetectColumnType;\n collection: ImportCollection;\n importModalState: ModalState;\n translate: Translate;\n errorHandler: PatternsErrorHandler;\n showToast?: ShowToast;\n downloadCsv?: DownloadCsvFn;\n /** See {@link OnImportJobError}. */\n onJobError?: OnImportJobError;\n}\n\nexport type ImportStep = 'upload' | 'configuration' | 'progress';\n\n// How long to keep the completed progress bar (100%) on screen before closing\n// the modal on a clean import. Without it, an import of very few rows finishes\n// near-instantly and the modal appears to vanish without ever showing the bar\n// reaching completion.\nconst COMPLETION_LINGER_MS = 600;\n\n// The Wix Data collection's id field key. A CSV column mapped to this field lets\n// the user choose how rows that collide on `_id` are written (writePolicy).\nconst ID_FIELD_KEY = '_id';\n\nfunction normalize(value: string) {\n return value.trim().toLowerCase();\n}\n\n// camelCase key for a field created from a column header\n// (e.g. \"Product Name\" -> \"productName\").\nfunction toFieldKey(header: string): string {\n const words = header\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n if (words.length === 0) {\n return 'field';\n }\n return words\n .map((word, index) =>\n index === 0\n ? word.charAt(0).toLowerCase() + word.slice(1)\n : word.charAt(0).toUpperCase() + word.slice(1),\n )\n .join('');\n}\n\n// A display name + key for a field created from a column header, unique against\n// both `usedNames` (existing field display names + names already assigned to\n// earlier new columns) and `usedKeys` (existing field ids + keys already\n// assigned). Mirrors cm-import `generateFieldNameAndKey`: when the name or its\n// derived key collides, suffix the *display name* as `\"<header>-<n>\"` and\n// re-derive the key from it — so the created field's name and key are both\n// unique (otherwise two columns with the same header would create fields showing\n// the same name).\nfunction uniqueFieldNameAndKey(\n header: string,\n usedNames: Set<string>,\n usedKeys: Set<string>,\n): { displayName: string; key: string } {\n let displayName = header;\n for (let suffix = 1; ; suffix++) {\n const key = toFieldKey(displayName);\n if (!usedNames.has(displayName) && !usedKeys.has(key)) {\n return { displayName, key };\n }\n displayName = `${header}-${suffix}`;\n }\n}\n\nexport class ImportState {\n readonly fields: ImportField[];\n readonly collectionId?: string;\n readonly destination?: Destination;\n readonly backup?: BackupFn;\n readonly updateSchema?: UpdateSchemaFn;\n readonly collection: ImportCollection;\n readonly importModalState: ModalState;\n readonly translate: Translate;\n readonly errorHandler: PatternsErrorHandler;\n readonly showToast?: ShowToast;\n readonly downloadCsv?: DownloadCsvFn;\n readonly onJobError?: OnImportJobError;\n private readonly hubJobClient: HubJobClient;\n private readonly _detectColumnType: DetectColumnType;\n readonly discardChangesModal = new ConditionalModalState<\n 'goBack' | 'close'\n >();\n\n currentStep: ImportStep = 'upload';\n importStatus: TaskStatus<ImportResult, unknown> = {\n ...queryStatus.idle,\n };\n fileName = '';\n csvHeaders: string[] = [];\n csvRows: string[][] = [];\n // Header display order for the configuration step, snapshotted when the file\n // is parsed. The column auto-mapped to `_id` floats to the top (CAIRO-4418);\n // the order then stays fixed while the user edits mappings, so clearing or\n // remapping the `_id` column can't reorder the row under the user's cursor.\n // Recomputed only on a new file (`applyParsedCsv`) or a full `reset()`.\n orderedHeaders: string[] = [];\n mappingByHeader: Record<string, ColumnMapping> = {};\n // How rows that collide on `_id` are written. Only meaningful (and only sent\n // to the server) when a CSV column is mapped to the `_id` field — see\n // `idMappedHeader` and `_destination`. Defaults to the server default\n // (`OVERWRITE` = upsert by `_id`).\n //\n // Retention: the choice is deliberately kept while editing mappings within a\n // file — remapping `_id` away and back keeps the user's selection rather than\n // silently reverting it. It resets to the default only on a *new file* upload\n // (`applyParsedCsv`) or a full `reset()`.\n writePolicy: WritePolicy = WritePolicy.OVERWRITE;\n processedCount = 0;\n totalCount = 0;\n result: ImportResult = {\n succeeded: 0,\n failed: 0,\n };\n isBackingUp = false;\n isRestoring = false;\n private restoreFn: ((signal: AbortSignal) => Promise<void>) | null = null;\n private _cancelled = false;\n private _abortController: AbortController | null = null;\n // Id of the running data-movement job, set once submitted — used to cancel it\n // (`terminateJob`) if the user closes mid-import.\n private _jobId: string | null = null;\n // The column whose pending new field the field editor is currently editing.\n // Not observable — transient wiring between `beginFieldEdit` and the editor's\n // `applyFieldEdit` callback, never rendered.\n private _editingHeader: string | null = null;\n\n constructor(props: ImportStateProps) {\n this.fields = (props.fields ?? []) as ImportField[];\n this.collectionId = props.collectionId;\n this.destination = props.destination;\n this.backup = props.backup;\n this.updateSchema = props.updateSchema;\n this.collection = props.collection;\n this.importModalState = props.importModalState;\n this.translate = props.translate;\n this.errorHandler = props.errorHandler;\n this.showToast = props.showToast;\n this.downloadCsv = props.downloadCsv;\n this.onJobError = props.onJobError;\n this._detectColumnType = props.detectColumnType ?? detectColumnType;\n this.hubJobClient = createHubJobClient({\n httpClient: props.httpClient,\n errorHandler: props.errorHandler,\n });\n\n makeObservable(this, {\n currentStep: observable.ref,\n importStatus: observable.ref,\n fileName: observable.ref,\n csvHeaders: observable.ref,\n csvRows: observable.ref,\n orderedHeaders: observable.ref,\n mappingByHeader: observable.ref,\n writePolicy: observable.ref,\n processedCount: observable.ref,\n totalCount: observable.ref,\n result: observable.ref,\n isBackingUp: observable.ref,\n isRestoring: observable.ref,\n hasParsedRows: computed,\n hasMappings: computed,\n hasNoMappedData: computed,\n selectedFieldIds: computed,\n idMappedHeader: computed,\n setWritePolicy: action.bound,\n onUploadContinue: action.bound,\n goToUpload: action.bound,\n setMapping: action.bound,\n setNewFieldMapping: action.bound,\n setNewFieldConfig: action.bound,\n beginFieldEdit: action.bound,\n applyFieldEdit: action.bound,\n close: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n init() {\n return () => {\n // Unmounting mid-import stops the poll loop (it checks `_cancelled`) so it\n // doesn't run to terminal holding references. We deliberately do NOT abort\n // the AbortController: during a cancel-triggered restore it holds the\n // restore controller, and aborting it would cancel an in-progress restore.\n // The server-side job is also left running — an unmount isn't an explicit\n // user cancel.\n this._cancelled = true;\n };\n }\n\n get hasParsedRows() {\n return this.csvHeaders.length > 0 && this.csvRows.length > 0;\n }\n\n get hasMappings() {\n return Object.values(this.mappingByHeader).some((value) => value != null);\n }\n\n /**\n * True when there are mappings but none of the mapped columns contain any\n * data in any row (including the case of zero data rows). Drives the\n * non-blocking \"no rows found\" warning in the configuration step. Returns\n * false when nothing is mapped yet — that case is handled by the disabled\n * import button instead.\n */\n get hasNoMappedData(): boolean {\n if (!this.hasMappings) {\n return false;\n }\n\n const mappedIndices = this.csvHeaders.reduce<number[]>(\n (indices, header, index) => {\n if (this.mappingByHeader[header] != null) {\n indices.push(index);\n }\n return indices;\n },\n [],\n );\n\n return !this.csvRows.some((row) =>\n mappedIndices.some((index) => (row[index] ?? '').trim() !== ''),\n );\n }\n\n get selectedFieldIds(): Set<string> {\n return new Set(\n Object.values(this.mappingByHeader)\n .filter(\n (m): m is { kind: 'existing'; fieldId: string } =>\n m?.kind === 'existing',\n )\n .map((m) => m.fieldId),\n );\n }\n\n /**\n * The CSV header currently mapped to the collection's `_id` field, or `null`\n * when no column targets it. Drives both the \"When items share the same ID\"\n * control (only shown on this row) and whether `writePolicy` is sent at all —\n * with no `_id` mapped, every row is a fresh insert and collisions can't occur.\n */\n get idMappedHeader(): string | null {\n const entry = Object.entries(this.mappingByHeader).find(\n ([, mapping]) =>\n mapping?.kind === 'existing' && mapping.fieldId === ID_FIELD_KEY,\n );\n return entry ? entry[0] : null;\n }\n\n setWritePolicy(policy: WritePolicy) {\n this.writePolicy = policy;\n }\n\n /**\n * Whether columns may be mapped to a brand-new field created during import.\n * Driven purely by the presence of the `updateSchema` callback — providing the\n * capability is the opt-in (see `getDefaultMapping`). Never changes after\n * construction, so it isn't an observable.\n */\n get canCreateNewField(): boolean {\n return this.updateSchema != null;\n }\n\n /**\n * Whether the write-policy (id-collision) choice is meaningful for this import.\n * `writePolicy` is a `wixDataCollection`-only concept, and `_destination` only\n * attaches it when Cairo builds that destination itself. A consumer-supplied\n * (platformized) `destination` is sent verbatim with no place to carry it, so\n * the choice would be a no-op — the UI hides the control in that case. Fixed at\n * construction (depends only on the `destination` prop), so it isn't an\n * observable.\n */\n get canConfigureWritePolicy(): boolean {\n return this.destination == null;\n }\n\n reset() {\n this._abortController?.abort();\n this._abortController = null;\n this.currentStep = 'upload';\n this.importStatus = {\n ...queryStatus.idle,\n };\n this.fileName = '';\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.writePolicy = WritePolicy.OVERWRITE;\n this.processedCount = 0;\n this.totalCount = 0;\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this.isBackingUp = false;\n this.isRestoring = false;\n this.restoreFn = null;\n this._cancelled = false;\n this._jobId = null;\n }\n\n async close() {\n // While on the progress step we treat close as a cancel — terminate the job\n // and restore the backup — UNLESS the import already succeeded. On the\n // success path `startImport` lingers ~600ms on the completed bar with the\n // step still 'progress'; closing during that window must NOT restore (it\n // would undo a clean import). A successful close just closes the modal and\n // lets the success path do its collection refresh.\n if (this.currentStep === 'progress' && !this.importStatus.isSuccess) {\n this._cancelled = true;\n this._abortController?.abort();\n\n // Stop the server-side job. It does not roll back rows already written —\n // that's what the backup restore below is for.\n if (this._jobId) {\n try {\n await this.hubJobClient.terminateJob(this._jobId);\n } catch (error) {\n console.error('Terminate import job failed', error);\n }\n }\n\n if (!this.isBackingUp) {\n await this._restoreBackup();\n }\n\n this.collection.clearResultAndMoveToStart({\n force: true,\n });\n }\n\n this.importModalState.close();\n }\n\n private async _restoreBackup() {\n const restoreFn = this.restoreFn;\n if (!restoreFn) {\n return;\n }\n\n const restoreController = new AbortController();\n this._abortController = restoreController;\n\n this.isRestoring = true;\n try {\n await restoreFn(restoreController.signal);\n } catch (error) {\n console.error('Restore failed', error);\n }\n runInAction(() => {\n this.isRestoring = false;\n this.restoreFn = null;\n });\n }\n\n goToUpload() {\n this.currentStep = 'upload';\n }\n\n async discardAndGoBack() {\n this.discardChangesModal.open('goBack');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.goToUpload();\n }\n }\n\n async discardAndClose() {\n this.discardChangesModal.open('close');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.close();\n }\n }\n\n onUploadContinue() {\n if (this.hasParsedRows) {\n this.currentStep = 'configuration';\n }\n }\n\n private getDefaultMapping(headers: string[]) {\n const mapping: Record<string, ColumnMapping> = {};\n const fields = this.fields.map((field) => ({\n id: field.id ?? '',\n header: field.header ?? '',\n }));\n\n headers.forEach((header, index) => {\n const normalizedHeader = normalize(header);\n const matched = fields.find(\n (field) =>\n normalize(field.id) === normalizedHeader ||\n normalize(field.header) === normalizedHeader,\n );\n\n if (matched?.id) {\n mapping[header] = { kind: 'existing', fieldId: matched.id };\n } else {\n // Unmatched columns default to creating a new field (type inferred from\n // the column's data) when the consumer supplied `updateSchema`;\n // otherwise they default to skip.\n mapping[header] = this.canCreateNewField\n ? {\n kind: 'new',\n fieldType: this._detectColumnType(this._columnValues(index)),\n }\n : null;\n }\n });\n\n return mapping;\n }\n\n // The column's values, capped at the detection sample size — detection only\n // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole\n // column (a wide CSV would otherwise allocate rows × columns strings).\n private _columnValues(columnIndex: number): string[] {\n return this.csvRows\n .slice(0, TYPE_SAMPLE_SIZE)\n .map((row) => row[columnIndex] ?? '');\n }\n\n // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the\n // rest. Returns a fresh array so the snapshot doesn't alias `csvHeaders`.\n private _orderHeadersWithIdFirst(headers: string[]): string[] {\n const idHeader = this.idMappedHeader;\n return idHeader != null\n ? [idHeader, ...headers.filter((header) => header !== idHeader)]\n : [...headers];\n }\n\n private applyParsedCsv(fileName: string, parsedCsv: ParseCsvResult) {\n this.fileName = fileName;\n this.csvHeaders = parsedCsv.headers;\n this.csvRows = parsedCsv.rows;\n this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);\n // Snapshot the row order for this file with the auto-mapped `_id` column\n // first. Reads `idMappedHeader`, so it must run after `mappingByHeader` is\n // set. Kept stable until the next file so mapping edits don't reorder rows.\n this.orderedHeaders = this._orderHeadersWithIdFirst(parsedCsv.headers);\n // A new file is a fresh import: start from the default policy so a prior\n // file's Skip choice doesn't silently carry over (only the new-file path\n // resets — remapping `_id` within the same file keeps the user's choice).\n this.writePolicy = WritePolicy.OVERWRITE;\n this.currentStep = 'configuration';\n }\n\n async onFileSelected(file: File | null) {\n if (file == null) {\n return;\n }\n\n const bytes = await this._readFileBytes(file);\n if (bytes == null) {\n this._showFileReadErrorToast(file);\n return;\n }\n\n const content = this._decodeUtf8(bytes);\n if (content == null) {\n this._rejectFile(file, 'cairo.import.encodingFailed');\n return;\n }\n\n const parsedCsv = parseCsv(content);\n if ('code' in parsedCsv) {\n this._rejectFile(file, 'cairo.import.processFailed');\n return;\n }\n\n runInAction(() => {\n this.applyParsedCsv(file.name, parsedCsv);\n });\n }\n\n private async _readFileBytes(file: File): Promise<ArrayBuffer | null> {\n try {\n return await file.arrayBuffer();\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _decodeUtf8(bytes: ArrayBuffer): string | null {\n try {\n // `fatal: true` throws on any byte sequence that isn't valid UTF-8,\n // so encoding is validated against the raw bytes before decoding —\n // unlike `File.text()`, which silently substitutes U+FFFD.\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _rejectFile(file: File, messageKey: TranslationsKeys) {\n runInAction(() => {\n this.fileName = file.name;\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.currentStep = 'upload';\n });\n this.showToast?.({\n type: 'ERROR',\n message: this.translate(messageKey),\n });\n }\n\n private _showFileReadErrorToast(file: File) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.fileReadFailed'),\n action: {\n text: this.translate('cairo.import.tryAgain'),\n onClick: () => this.onFileSelected(file),\n removeToastOnClick: true,\n },\n });\n }\n\n private _showPartialSuccessToast() {\n this.showToast?.({\n type: 'WARNING',\n message: this.translate('cairo.import.partialSuccessToast', {\n failed: String(this.result.failed),\n imported: String(this.result.succeeded),\n }),\n action: {\n text: this.translate('cairo.import.downloadFailedRows'),\n onClick: () => this._downloadFailedRows(),\n removeToastOnClick: true,\n },\n });\n }\n\n /**\n * Builds a plain, re-importable CSV of the rows the server rejected — the\n * original headers plus just the failed rows — and hands it to `downloadCsv`.\n * The failed rows come from the job's movement logs (which row failed), mapped\n * back to the parsed `csvRows` we still hold in memory.\n */\n private async _downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let indices: number[];\n try {\n indices = await this._fetchFailedRowIndices(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const failedRows = indices\n .map((index) => this.csvRows[index])\n .filter((row): row is string[] => row != null);\n\n if (failedRows.length === 0) {\n return;\n }\n\n const content = unparseCsv(this.csvHeaders, failedRows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns the `csvRows` indices of\n // the rows that failed. data-hub's CSV decoder\n // (wix-data-hub: packages/wix-data-hub-executor-c/src/plugins/formats/csv/\n // csv-binary-decoder.ts) parses with the `csv-parse` library (`columns: true`)\n // and sets `sourceItemId = \"row ${++index + 1}\"`, incrementing once **per\n // record** — not per physical line. So N is the 1-based record number with\n // the header consumed as columns: the first data record is `\"row 2\"` →\n // `csvRows[0]`, i.e. `csvRows[N - 2]`. Because `csv-parse` is RFC-4180,\n // quoted cells containing embedded newlines are a single record, so they do\n // NOT shift the numbering. Out-of-range indices are guarded below.\n private async _fetchFailedRowIndices(jobId: string): Promise<number[]> {\n const indices: number[] = [];\n let cursor: string | undefined;\n\n do {\n const { logs, pagingMetadata } = await this.hubJobClient.listMovementLogs(\n jobId,\n cursor ? { cursor } : undefined,\n );\n\n for (const log of logs ?? []) {\n if (!log.failure || log.sourceItemId == null) {\n continue;\n }\n const fileLine = Number(/\\d+/.exec(log.sourceItemId)?.[0]);\n const index = fileLine - 2;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < this.csvRows.length\n ) {\n indices.push(index);\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return indices;\n }\n\n setMapping(header: string, fieldId: string | null) {\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: fieldId == null ? null : { kind: 'existing', fieldId },\n };\n }\n\n setNewFieldMapping(header: string) {\n const index = this.csvHeaders.indexOf(header);\n const fieldType =\n index >= 0 ? this._detectColumnType(this._columnValues(index)) : 'text';\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: { kind: 'new', fieldType },\n };\n }\n\n /**\n * Persists the result of the \"Edit field\" editor for a column's pending new\n * field: the (possibly overridden) type, an optional display-name override,\n * and the per-type configuration. No-op if the column isn't currently mapped\n * to a new field.\n */\n setNewFieldConfig(\n header: string,\n edit: {\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n },\n ) {\n const mapping = this.mappingByHeader[header];\n if (mapping?.kind !== 'new') {\n return;\n }\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: {\n kind: 'new',\n fieldType: edit.fieldType,\n ...(edit.displayName != null && { displayName: edit.displayName }),\n ...(edit.config && { config: edit.config }),\n },\n };\n }\n\n /**\n * Marks which column's pending new field the field editor is currently\n * editing, so a later `applyFieldEdit` (the editor's `onSubmit`) knows where to\n * write the result.\n */\n beginFieldEdit(header: string) {\n this._editingHeader = header;\n }\n\n /**\n * `onSubmit` handler for the field editor: maps the edited field spec into the\n * column being edited (set via `beginFieldEdit`). No-op if nothing is being\n * edited.\n */\n applyFieldEdit(field: FieldSpec) {\n if (this._editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this._editingHeader, toFieldEdit(field));\n }\n\n /**\n * Runs the server-side import: align the CSV to the resolved field keys,\n * upload it, submit a data-movement job, then poll until terminal. Throws on\n * a failed job so `startImport` surfaces the error state; partial success is\n * reported via `result.failed` and the partial toast.\n */\n private async _runImportJob(\n resolvedMapping: Record<string, string | null>,\n ): Promise<ImportResult> {\n const csv = rewriteParsedCsvForImport(\n this.csvHeaders,\n this.csvRows,\n resolvedMapping,\n );\n const file = new File([csv], this.fileName || 'import.csv', {\n type: 'text/csv',\n });\n\n const fileId = await this.hubJobClient.uploadFile(file);\n if (this._cancelled) {\n return this.result;\n }\n\n const jobId = await this.hubJobClient.submitImportJob({\n fileId,\n name: this.fileName,\n destination: this._destination(),\n });\n runInAction(() => {\n this._jobId = jobId;\n });\n if (this._cancelled) {\n // The user cancelled while `submitImportJob` was in flight, so `close()`\n // saw no `_jobId` and couldn't terminate it. Terminate it here, otherwise\n // the job keeps importing server-side after cancel (and would overwrite a\n // restored backup).\n await this.hubJobClient.terminateJob(jobId).catch(() => undefined);\n return this.result;\n }\n\n const job = await pollImportJob(\n (id) => this.hubJobClient.getJob(id),\n jobId,\n {\n isCancelled: () => this._cancelled,\n onProgress: (polled) => this._applyJobProgress(polled),\n },\n );\n\n // `null` means cancelled mid-poll — leave whatever progress we have.\n if (!job) {\n return this.result;\n }\n\n if (job.status === JobStatus.FAILED) {\n // The job ran server-side, so a failure arrives on a 200 (the poll\n // succeeded; the job didn't) with no HTTP error to carry the application\n // error. Build a synthetic, HTTP-error-shaped error (the error handler\n // reads the code from `response.data.details.applicationError`) and hand\n // the throwing operation to the consumer's `onJobError` so THEY wrap it\n // with their own `withErrorHandler` + error-code map — `job.error` is the\n // consumer's application error (their import business logic), so only they\n // can map its codes, and the map stays coupled to the `withErrorHandler`\n // call as everywhere else (e.g. `fetchData`). The map is attached to the\n // error object, which the progress step resolves via `getResolvedError`.\n // Without a handler the same error still throws, falling back to the\n // generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n const run = (): Promise<unknown> => Promise.reject(error);\n\n if (this.onJobError) {\n // The consumer wraps `run` with `withErrorHandler`; it re-rejects with\n // `error` (now carrying their map), which propagates from here.\n await this.onJobError(run);\n }\n throw error;\n }\n\n this._applyJobProgress(job);\n return this.result;\n }\n\n // Destination the job writes into. A platformized consumer supplies its own\n // variant (e.g. `{ storesCatalogProducts: {} }`), which is sent verbatim.\n // Otherwise this is the consumer's Wix Data collection, built from\n // `collectionId`; `writePolicy` is sent only when a CSV column is mapped to\n // `_id` (the only case collisions can occur), otherwise it's omitted and the\n // server applies its default (upsert by `_id`).\n private _destination(): Destination {\n if (this.destination) {\n return this.destination;\n }\n return {\n wixDataCollection: {\n collectionId: this.collectionId,\n ...(this.idMappedHeader != null && { writePolicy: this.writePolicy }),\n },\n };\n }\n\n private _applyJobProgress(job: DataMovementJob) {\n const progress = job.progress;\n const succeeded = progress?.itemsSuccessful ?? 0;\n const failed = progress?.itemsRejected ?? 0;\n const current = progress?.current ?? succeeded + failed;\n\n // `totalCount` is fixed up front in `startImport` from the CSV row count\n // (one uploaded row per CSV row); polling only advances `processedCount`.\n runInAction(() => {\n this.processedCount = Math.min(current, this.totalCount);\n this.result = { succeeded, failed };\n });\n }\n\n private async _runBackup(): Promise<boolean> {\n const backup = this.backup;\n if (!backup) {\n return false;\n }\n\n try {\n const result = await backup(this._abortController!.signal);\n if (this._cancelled) {\n return true;\n }\n if (result?.restore) {\n this.restoreFn = result.restore;\n }\n } catch (error) {\n if (this._cancelled) {\n return true;\n }\n runInAction(() => {\n this.isBackingUp = false;\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return true;\n }\n\n runInAction(() => {\n this.isBackingUp = false;\n });\n return false;\n }\n\n private _lingerOnCompletion() {\n return new Promise<void>((resolve) =>\n setTimeout(resolve, COMPLETION_LINGER_MS),\n );\n }\n\n /**\n * Resolves every column to the final destination key used in the upload\n * payload: an existing field id, a new field's (Cairo-decided) key, or `null`\n * to skip. All new fields are added to the schema in a single `updateSchema`\n * call before the rows upload — mirroring the cm-import `beforeImport` flow.\n * `updateSchema` may throw — `startImport` surfaces that as the error state.\n */\n private async _resolveFieldMapping(): Promise<Record<string, string | null>> {\n const resolved: Record<string, string | null> = {};\n const newFields: NewFieldDefinition[] = [];\n // Seed with existing field ids/display names so derived keys and names never\n // collide with them or with each other.\n const usedKeys = new Set(\n this.fields.map((field) => field.id).filter((id): id is string => !!id),\n );\n const usedNames = new Set(\n this.fields\n .map((field) => field.header)\n .filter((header): header is string => !!header),\n );\n\n for (const header of this.csvHeaders) {\n const mapping = this.mappingByHeader[header];\n\n if (mapping == null) {\n resolved[header] = null;\n } else if (mapping.kind === 'existing') {\n resolved[header] = mapping.fieldId;\n } else if (this.updateSchema) {\n // The user's name override (from the field editor) seeds the unique\n // name/key derivation; otherwise fall back to the column header.\n const baseName = mapping.displayName?.trim() || header;\n const { displayName, key } = uniqueFieldNameAndKey(\n baseName,\n usedNames,\n usedKeys,\n );\n usedKeys.add(key);\n usedNames.add(displayName);\n newFields.push({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n });\n resolved[header] = key;\n } else {\n // \"new\" mapping without an `updateSchema` callback — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (newFields.length > 0 && this.updateSchema) {\n await this.updateSchema(newFields);\n }\n\n return resolved;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n this._cancelled = false;\n this._abortController = new AbortController();\n\n // One uploaded row per CSV row (the rewrite drops columns, not rows), so the\n // total is known up front from the parsed CSV and stays fixed through polling.\n const totalCount = this.csvRows.length;\n\n runInAction(() => {\n this.currentStep = 'progress';\n this.totalCount = totalCount;\n this.processedCount = 0;\n this.isBackingUp = !!this.backup;\n // Clear any error/result from a previous attempt so \"Try again\" starts\n // from a clean slate (e.g. after a backup failure).\n this.importStatus = { ...queryStatus.idle };\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this._jobId = null;\n });\n\n const backupFailed = await this._runBackup();\n if (backupFailed) {\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n // Create any new fields and resolve every column to its destination key\n // before uploading. A creation failure surfaces as the error state with a\n // \"Try again\" CTA, like an upload/job failure.\n let resolvedMapping: Record<string, string | null>;\n try {\n resolvedMapping = await this._resolveFieldMapping();\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n const promise = this._runImportJob(resolvedMapping);\n\n this.importStatus = {\n ...queryStatus.loading,\n promise,\n };\n\n try {\n await promise;\n if (this._cancelled) {\n return;\n }\n\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.success,\n data: this.result,\n };\n });\n\n // On a clean import, hold the completed (100%) progress bar on screen\n // briefly so the completion is perceptible even for very few rows. Skip\n // the wait when there are failed rows — that path closes and surfaces a\n // toast instead.\n if (this.result.failed === 0) {\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n }\n\n runInAction(() => {\n // Rows the server rejected are reported via a toast (the downloadable\n // failed-rows report is added by the failed-rows-report task).\n if (this.result.failed > 0) {\n this._showPartialSuccessToast();\n }\n\n this.importModalState.close();\n this.collection.clearResultAndMoveToStart({ force: true });\n });\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAOA,IAAAC,MAAA,GAAAD,OAAA;AASA,IAAAE,sBAAA,GAAAF,OAAA;AAEA,IAAAG,MAAA,GAAAH,OAAA;AAKyDI,OAAA,CAAAC,WAAA,GAAAF,MAAA,CAAAE,WAAA;AACzD,IAAAC,SAAA,GAAAN,OAAA;AACA,IAAAO,WAAA,GAAAP,OAAA;AACA,IAAAQ,aAAA,GAAAR,OAAA;AACA,IAAAS,gBAAA,GAAAT,OAAA;AACA,IAAAU,gBAAA,GAAAV,OAAA;AAOA,IAAAW,UAAA,GAAAX,OAAA;AAMA;;AAqBA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;;AAEA;AACA;;AAEA;AACA;;AAGA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAqDA;AACA;AACA;AACA;AACA,MAAMY,oBAAoB,GAAG,GAAG;;AAEhC;AACA;AACA,MAAMC,YAAY,GAAG,KAAK;AAE1B,SAASC,SAASA,CAACC,KAAa,EAAE;EAChC,OAAOA,KAAK,CAACC,IAAI,CAAC,CAAC,CAACC,WAAW,CAAC,CAA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AAW,EAAC,MAAM;QAChB,IAAI,CAACrE,YAAY,GAAG;UAClB,GAAG1B,kBAAW,CAACuF,KAAK;UACpBA;QACF,CAAC;MACH,CAAC,CAAC;IACJ;EACF;AACF;AAAChI,OAAA,CAAAmC,WAAA,GAAAA,WAAA","ignoreList":[]}
@@ -533,4 +533,143 @@ describe('ImportState writePolicy (id-collision handling)', () => {
533
533
  }));
534
534
  });
535
535
  });
536
+ describe('ImportState orderedHeaders (row order stability)', () => {
537
+ beforeEach(() => {
538
+ jest.useRealTimers();
539
+ });
540
+
541
+ // Parse a CSV whose `ID` column auto-maps to `_id` (a field with that id
542
+ // exists), so the `_id` row floats to the top of the ordered list.
543
+ async function parseWithIdColumn(state) {
544
+ const csv = 'Name,ID,Handle\nApple,id-1,a\nPear,id-2,p\n';
545
+ const file = {
546
+ name: 'data.csv',
547
+ arrayBuffer: async () => new _util.TextEncoder().encode(csv).buffer
548
+ };
549
+ await state.onFileSelected(file);
550
+ }
551
+ it('floats the `_id`-mapped column to the top for a freshly parsed file', async () => {
552
+ const {
553
+ state
554
+ } = setup({}, {
555
+ fields: [{
556
+ id: '_id',
557
+ header: 'ID'
558
+ }]
559
+ });
560
+ await parseWithIdColumn(state);
561
+ expect(state.idMappedHeader).toBe('ID');
562
+ expect(state.orderedHeaders).toEqual(['ID', 'Name', 'Handle']);
563
+ });
564
+ it('keeps row order stable when the `_id` mapping is cleared and re-added', async () => {
565
+ const {
566
+ state
567
+ } = setup({}, {
568
+ fields: [{
569
+ id: '_id',
570
+ header: 'ID'
571
+ }]
572
+ });
573
+ await parseWithIdColumn(state);
574
+
575
+ // Clearing the `_id` dropdown must not reorder the row under the cursor:
576
+ // the snapshot stays fixed even though `idMappedHeader` becomes null.
577
+ state.setMapping('ID', null);
578
+ expect(state.idMappedHeader).toBeNull();
579
+ expect(state.orderedHeaders).toEqual(['ID', 'Name', 'Handle']);
580
+
581
+ // Re-mapping `_id` also leaves the order untouched.
582
+ state.setMapping('ID', '_id');
583
+ expect(state.idMappedHeader).toBe('ID');
584
+ expect(state.orderedHeaders).toEqual(['ID', 'Name', 'Handle']);
585
+ });
586
+ it('re-snapshots the order for a new file and clears it on reset', async () => {
587
+ const {
588
+ state
589
+ } = setup({}, {
590
+ fields: [{
591
+ id: '_id',
592
+ header: 'ID'
593
+ }]
594
+ });
595
+ await parseWithIdColumn(state);
596
+ expect(state.orderedHeaders).toEqual(['ID', 'Name', 'Handle']);
597
+
598
+ // A file with no `_id` column keeps plain CSV order.
599
+ const csv = 'First,Second\n1,2\n';
600
+ const file = {
601
+ name: 'other.csv',
602
+ arrayBuffer: async () => new _util.TextEncoder().encode(csv).buffer
603
+ };
604
+ await state.onFileSelected(file);
605
+ expect(state.orderedHeaders).toEqual(['First', 'Second']);
606
+ state.reset();
607
+ expect(state.orderedHeaders).toEqual([]);
608
+ });
609
+ });
610
+ describe('ImportState platformized destination (non–Wix-Data)', () => {
611
+ beforeEach(() => {
612
+ jest.useRealTimers();
613
+ });
614
+ it('sends a consumer-supplied destination verbatim, ignoring collectionId', async () => {
615
+ const {
616
+ state,
617
+ client
618
+ } = setup({}, {
619
+ destination: {
620
+ storesCatalogProducts: {}
621
+ }
622
+ });
623
+ await state.startImport();
624
+ expect(client.submitImportJob).toHaveBeenCalledWith(expect.objectContaining({
625
+ destination: {
626
+ storesCatalogProducts: {}
627
+ }
628
+ }));
629
+ });
630
+ it('does not add writePolicy to a platformized destination even when `_id` is mapped', async () => {
631
+ const {
632
+ state,
633
+ client
634
+ } = setup({}, {
635
+ destination: {
636
+ storesCatalogInventory: {}
637
+ }
638
+ });
639
+ // Map a column to `_id` and pick a non-default policy — for a platformized
640
+ // destination this must NOT leak into the destination (writePolicy is a
641
+ // wixDataCollection-only concern).
642
+ (0, _mobx.runInAction)(() => {
643
+ state.csvHeaders = ['Name', 'ID'];
644
+ state.csvRows = [['Apple', '1'], ['Pear', '2']];
645
+ state.mappingByHeader = {
646
+ Name: {
647
+ kind: 'existing',
648
+ fieldId: 'name'
649
+ },
650
+ ID: {
651
+ kind: 'existing',
652
+ fieldId: '_id'
653
+ }
654
+ };
655
+ });
656
+ state.setWritePolicy(_types.WritePolicy.SKIP_EXISTING);
657
+ await state.startImport();
658
+ expect(client.submitImportJob).toHaveBeenCalledWith(expect.objectContaining({
659
+ destination: {
660
+ storesCatalogInventory: {}
661
+ }
662
+ }));
663
+ });
664
+ it('reports canConfigureWritePolicy=false for a custom destination (control hidden), true for the default path', () => {
665
+ const platformized = setup({}, {
666
+ destination: {
667
+ storesCatalogProducts: {}
668
+ }
669
+ }).state;
670
+ expect(platformized.canConfigureWritePolicy).toBe(false);
671
+ const wixData = setup().state;
672
+ expect(wixData.canConfigureWritePolicy).toBe(true);
673
+ });
674
+ });
536
675
  //# sourceMappingURL=ImportState.engine.spec.js.map