@wix/bex-core 2.336.0 → 2.337.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 (58) hide show
  1. package/dist/cjs/hooks/useImport.js.map +1 -1
  2. package/dist/cjs/index.js +7 -0
  3. package/dist/cjs/index.js.map +1 -1
  4. package/dist/cjs/state/ImportState/ImportState.js +6 -5
  5. package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
  6. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +28 -0
  7. package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  8. package/dist/cjs/testkit/createInMemorySchemaSource.js +2 -0
  9. package/dist/cjs/testkit/createInMemorySchemaSource.js.map +1 -1
  10. package/dist/cjs/testkit/hubJobImportMocks.js +14 -4
  11. package/dist/cjs/testkit/hubJobImportMocks.js.map +1 -1
  12. package/dist/cjs/types/Field.js.map +1 -1
  13. package/dist/cjs/types/FieldTypeDefinition.js +79 -0
  14. package/dist/cjs/types/FieldTypeDefinition.js.map +1 -0
  15. package/dist/cjs/types/FieldsSource.js.map +1 -1
  16. package/dist/cjs/types/SchemaSource.js +14 -2
  17. package/dist/cjs/types/SchemaSource.js.map +1 -1
  18. package/dist/cjs/types/__tests__/defineSchemaSource.fieldTypes.spec.js +78 -0
  19. package/dist/cjs/types/__tests__/defineSchemaSource.fieldTypes.spec.js.map +1 -0
  20. package/dist/esm/hooks/useImport.js +1 -1
  21. package/dist/esm/hooks/useImport.js.map +1 -1
  22. package/dist/esm/index.js +1 -0
  23. package/dist/esm/index.js.map +1 -1
  24. package/dist/esm/state/ImportState/ImportState.js +6 -4
  25. package/dist/esm/state/ImportState/ImportState.js.map +1 -1
  26. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +28 -1
  27. package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
  28. package/dist/esm/testkit/createInMemorySchemaSource.js +2 -1
  29. package/dist/esm/testkit/createInMemorySchemaSource.js.map +1 -1
  30. package/dist/esm/testkit/hubJobImportMocks.js +14 -4
  31. package/dist/esm/testkit/hubJobImportMocks.js.map +1 -1
  32. package/dist/esm/types/FieldTypeDefinition.js +16 -0
  33. package/dist/esm/types/FieldTypeDefinition.js.map +1 -0
  34. package/dist/esm/types/SchemaSource.js +15 -3
  35. package/dist/esm/types/SchemaSource.js.map +1 -1
  36. package/dist/esm/types/__tests__/defineSchemaSource.fieldTypes.spec.js +51 -0
  37. package/dist/esm/types/__tests__/defineSchemaSource.fieldTypes.spec.js.map +1 -0
  38. package/dist/types/hooks/useImport.d.ts.map +1 -1
  39. package/dist/types/index.d.ts +2 -1
  40. package/dist/types/index.d.ts.map +1 -1
  41. package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
  42. package/dist/types/testkit/WixPatternsContainer.driver.d.ts +2 -0
  43. package/dist/types/testkit/WixPatternsContainer.driver.d.ts.map +1 -1
  44. package/dist/types/testkit/createInMemorySchemaSource.d.ts +3 -0
  45. package/dist/types/testkit/createInMemorySchemaSource.d.ts.map +1 -1
  46. package/dist/types/testkit/hubJobImportMocks.d.ts +8 -0
  47. package/dist/types/testkit/hubJobImportMocks.d.ts.map +1 -1
  48. package/dist/types/types/Field.d.ts +3 -1
  49. package/dist/types/types/Field.d.ts.map +1 -1
  50. package/dist/types/types/FieldTypeDefinition.d.ts +253 -0
  51. package/dist/types/types/FieldTypeDefinition.d.ts.map +1 -0
  52. package/dist/types/types/FieldsSource.d.ts +29 -1
  53. package/dist/types/types/FieldsSource.d.ts.map +1 -1
  54. package/dist/types/types/SchemaSource.d.ts +21 -2
  55. package/dist/types/types/SchemaSource.d.ts.map +1 -1
  56. package/dist/types/types/__tests__/defineSchemaSource.fieldTypes.spec.d.ts +2 -0
  57. package/dist/types/types/__tests__/defineSchemaSource.fieldTypes.spec.d.ts.map +1 -0
  58. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"names":["_react","require","_providers","_state","useCreateImport","params","config","importInputs","fieldsSource","detectColumnType","importModalState","showToast","translate","errorHandler","window","httpClient","useWixPatternsContainer","collection","useCollectionContext","useCallback","ImportState","downloadCsv","content","fileName","download","encodeURIComponent"],"sources":["../../../src/hooks/useImport.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useWixPatternsContainer, useCollectionContext } from '../providers';\nimport {\n ModalState,\n ImportState,\n ResolvedImportConfig,\n ImportConfig,\n DetectColumnType,\n} from '../state';\nimport type { FieldsSource } from '../types/FieldsSource';\nimport { FiltersMap } from '../model';\n\nexport interface UseImportParams {\n /** Consumer inputs (destination, extra fields, backup, …). The collection,\n * fields, and create-new-field are read from `fieldsSource`. */\n importInputs?: ImportConfig;\n /** The table's live fields source; `ImportState` builds the config from it. */\n fieldsSource?: FieldsSource;\n /** A fully pre-built config, used instead of building from the inputs/source. */\n config?: ResolvedImportConfig;\n detectColumnType?: DetectColumnType;\n importModalState: ModalState;\n}\n\nexport function useCreateImport<T = unknown, F extends FiltersMap = FiltersMap>(\n params: UseImportParams,\n) {\n const { config, importInputs, fieldsSource, detectColumnType, importModalState } =\n params;\n const { showToast, translate, errorHandler, window, httpClient } =\n useWixPatternsContainer();\n const collection = useCollectionContext<T, F>();\n\n return useCallback(() => {\n return new ImportState({\n config,\n importInputs,\n fieldsSource,\n httpClient,\n detectColumnType,\n collection,\n importModalState,\n showToast,\n translate,\n errorHandler,\n downloadCsv: (content, fileName) => {\n window.download(\n `data:text/csv;charset=utf-8,${encodeURIComponent(content)}`,\n fileName,\n );\n },\n });\n }, []);\n}\n"],"mappings":";;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAsBO,SAASG,eAAeA,CAC7BC,MAAuB,EACvB;EACA,MAAM;IAAEC,MAAM;IAAEC,YAAY;IAAEC,YAAY;IAAEC,gBAAgB;IAAEC;EAAiB,CAAC,GAC9EL,MAAM;EACR,MAAM;IAAEM,SAAS;IAAEC,SAAS;IAAEC,YAAY;IAAEC,MAAM;IAAEC;EAAW,CAAC,GAC9D,IAAAC,kCAAuB,EAAC,CAAC;EAC3B,MAAMC,UAAU,GAAG,IAAAC,+BAAoB,EAAO,CAAC;EAE/C,OAAO,IAAAC,kBAAW,EAAC,MAAM;IACvB,OAAO,IAAIC,kBAAW,CAAC;MACrBd,MAAM;MACNC,YAAY;MACZC,YAAY;MACZO,UAAU;MACVN,gBAAgB;MAChBQ,UAAU;MACVP,gBAAgB;MAChBC,SAAS;MACTC,SAAS;MACTC,YAAY;MACZQ,WAAW,EAAEA,CAACC,OAAO,EAAEC,QAAQ,KAAK;QAClCT,MAAM,CAACU,QAAQ,CACb,+BAA+BC,kBAAkB,CAACH,OAAO,CAAC,EAAE,EAC5DC,QACF,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,EAAE,EAAE,CAAC;AACR","ignoreList":[]}
1
+ {"version":3,"names":["_react","require","_providers","_state","useCreateImport","params","config","importInputs","fieldsSource","detectColumnType","importModalState","showToast","translate","errorHandler","window","httpClient","useWixPatternsContainer","collection","useCollectionContext","useCallback","ImportState","downloadCsv","content","fileName","download","encodeURIComponent"],"sources":["../../../src/hooks/useImport.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useWixPatternsContainer, useCollectionContext } from '../providers';\nimport {\n ModalState,\n ImportState,\n ResolvedImportConfig,\n ImportConfig,\n DetectColumnType,\n} from '../state';\nimport type { FieldsSource } from '../types/FieldsSource';\nimport { FiltersMap } from '../model';\n\nexport interface UseImportParams {\n /** Consumer inputs (destination, extra fields, backup, …). The collection,\n * fields, and create-new-field are read from `fieldsSource`. */\n importInputs?: ImportConfig;\n /** The table's live fields source; `ImportState` builds the config from it. */\n fieldsSource?: FieldsSource;\n /** A fully pre-built config, used instead of building from the inputs/source. */\n config?: ResolvedImportConfig;\n detectColumnType?: DetectColumnType;\n importModalState: ModalState;\n}\n\nexport function useCreateImport<T = unknown, F extends FiltersMap = FiltersMap>(\n params: UseImportParams,\n) {\n const {\n config,\n importInputs,\n fieldsSource,\n detectColumnType,\n importModalState,\n } = params;\n const { showToast, translate, errorHandler, window, httpClient } =\n useWixPatternsContainer();\n const collection = useCollectionContext<T, F>();\n\n return useCallback(() => {\n return new ImportState({\n config,\n importInputs,\n fieldsSource,\n httpClient,\n detectColumnType,\n collection,\n importModalState,\n showToast,\n translate,\n errorHandler,\n downloadCsv: (content, fileName) => {\n window.download(\n `data:text/csv;charset=utf-8,${encodeURIComponent(content)}`,\n fileName,\n );\n },\n });\n }, []);\n}\n"],"mappings":";;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,UAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AAsBO,SAASG,eAAeA,CAC7BC,MAAuB,EACvB;EACA,MAAM;IACJC,MAAM;IACNC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAChBC;EACF,CAAC,GAAGL,MAAM;EACV,MAAM;IAAEM,SAAS;IAAEC,SAAS;IAAEC,YAAY;IAAEC,MAAM;IAAEC;EAAW,CAAC,GAC9D,IAAAC,kCAAuB,EAAC,CAAC;EAC3B,MAAMC,UAAU,GAAG,IAAAC,+BAAoB,EAAO,CAAC;EAE/C,OAAO,IAAAC,kBAAW,EAAC,MAAM;IACvB,OAAO,IAAIC,kBAAW,CAAC;MACrBd,MAAM;MACNC,YAAY;MACZC,YAAY;MACZO,UAAU;MACVN,gBAAgB;MAChBQ,UAAU;MACVP,gBAAgB;MAChBC,SAAS;MACTC,SAAS;MACTC,YAAY;MACZQ,WAAW,EAAEA,CAACC,OAAO,EAAEC,QAAQ,KAAK;QAClCT,MAAM,CAACU,QAAQ,CACb,+BAA+BC,kBAAkB,CAACH,OAAO,CAAC,EAAE,EAC5DC,QACF,CAAC;MACH;IACF,CAAC,CAAC;EACJ,CAAC,EAAE,EAAE,CAAC;AACR","ignoreList":[]}
package/dist/cjs/index.js CHANGED
@@ -80,4 +80,11 @@ exports.DeepPartial = _DeepPartial.DeepPartial;
80
80
  var _SchemaSource = require("./types/SchemaSource");
81
81
  exports.defineSchemaSource = _SchemaSource.defineSchemaSource;
82
82
  exports.sourceFetchData = _SchemaSource.sourceFetchData;
83
+ var _FieldTypeDefinition = require("./types/FieldTypeDefinition");
84
+ Object.keys(_FieldTypeDefinition).forEach(function (key) {
85
+ if (key === "default" || key === "__esModule") return;
86
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
87
+ if (key in exports && exports[key] === _FieldTypeDefinition[key]) return;
88
+ exports[key] = _FieldTypeDefinition[key];
89
+ });
83
90
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_model","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","_state","_services","_util","_useExport","_useImport","_createCollection","_useCollectionDatasetSync","_hooks","CollectionConfigWithConditionals","CollectionFactory","useSyncProps","useSelector","_core","QueryCache","_DeepPartial","DeepPartial","_SchemaSource","defineSchemaSource","sourceFetchData"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './model';\nexport * from './state';\nexport * from './services';\nexport * from './util';\nexport * from './hooks/useExport';\nexport * from './hooks/useImport';\nexport * from './hooks/createCollection';\nexport * from './hooks/useCollectionDatasetSync';\nexport {\n CollectionConfigWithConditionals,\n CollectionFactory,\n useSyncProps,\n useSelector,\n} from './hooks';\nexport { QueryCache } from 'react-query/core';\nexport { DeepPartial } from './types/DeepPartial';\nexport type {\n PatternsFieldType,\n QueryOperator,\n NumberRange,\n StringLengthRange,\n BaseReferenceField,\n ReferenceField,\n MultiReferenceField,\n NonReferenceField,\n Field,\n FieldSpec,\n} from './types/Field';\nexport type {\n Schema,\n SchemaPermissions,\n ItemPermissions,\n CollectionBackendBase,\n CollectionBackend,\n FieldActions,\n BackupConfig,\n BulkInsertResult,\n BulkInsertError,\n LoadedSchema,\n SchemaLoader,\n FindOptions,\n} from './types/Schema';\nexport type {\n FieldsSource,\n FieldManagement,\n FieldArchive,\n ArchivedFieldItem,\n FieldTypeOption,\n FieldPermissions,\n FieldDraft,\n} from './types/FieldsSource';\nexport { defineSchemaSource, sourceFetchData } from './types/SchemaSource';\nexport type {\n SchemaSource,\n SchemaSourceInput,\n CreatableFieldType,\n} from './types/SchemaSource';\nexport type {\n CursorQuery,\n OffsetQuery,\n CursorQueryResult,\n OffsetQueryResult,\n CursorFetchDataFn,\n OffsetFetchDataFn,\n FetchTotalFn,\n} from './hooks/paginationModeConfig';\n"],"mappings":";;;;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,MAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAL,MAAA,CAAAK,GAAA;EAAAK,OAAA,CAAAL,GAAA,IAAAL,MAAA,CAAAK,GAAA;AAAA;AACA,IAAAM,MAAA,GAAAV,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAQ,MAAA,EAAAP,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAM,MAAA,CAAAN,GAAA;EAAAK,OAAA,CAAAL,GAAA,IAAAM,MAAA,CAAAN,GAAA;AAAA;AACA,IAAAO,SAAA,GAAAX,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAS,SAAA,EAAAR,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAA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AAA;AAA2ES,OAAA,CAAAkB,kBAAA,GAAAD,aAAA,CAAAC,kBAAA;AAAAlB,OAAA,CAAAmB,eAAA,GAAAF,aAAA,CAAAE,eAAA","ignoreList":[]}
1
+ {"version":3,"names":["_model","require","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","_state","_services","_util","_useExport","_useImport","_createCollection","_useCollectionDatasetSync","_hooks","CollectionConfigWithConditionals","CollectionFactory","useSyncProps","useSelector","_core","QueryCache","_DeepPartial","DeepPartial","_SchemaSource","defineSchemaSource","sourceFetchData","_FieldTypeDefinition"],"sources":["../../src/index.ts"],"sourcesContent":["export * from './model';\nexport * from './state';\nexport * from './services';\nexport * from './util';\nexport * from './hooks/useExport';\nexport * from './hooks/useImport';\nexport * from './hooks/createCollection';\nexport * from './hooks/useCollectionDatasetSync';\nexport {\n CollectionConfigWithConditionals,\n CollectionFactory,\n useSyncProps,\n useSelector,\n} from './hooks';\nexport { QueryCache } from 'react-query/core';\nexport { DeepPartial } from './types/DeepPartial';\nexport type {\n PatternsFieldType,\n QueryOperator,\n NumberRange,\n StringLengthRange,\n BaseReferenceField,\n ReferenceField,\n MultiReferenceField,\n NonReferenceField,\n Field,\n FieldSpec,\n} from './types/Field';\nexport type {\n Schema,\n SchemaPermissions,\n ItemPermissions,\n CollectionBackendBase,\n CollectionBackend,\n FieldActions,\n BackupConfig,\n BulkInsertResult,\n BulkInsertError,\n LoadedSchema,\n SchemaLoader,\n FindOptions,\n} from './types/Schema';\nexport type {\n FieldsSource,\n FieldManagement,\n FieldArchive,\n ArchivedFieldItem,\n FieldTypeOption,\n FieldPermissions,\n FieldDraft,\n FieldModalText,\n FieldModalSubtitle,\n} from './types/FieldsSource';\nexport { defineSchemaSource, sourceFetchData } from './types/SchemaSource';\nexport type {\n SchemaSource,\n SchemaSourceInput,\n CreatableFieldType,\n} from './types/SchemaSource';\nexport * from './types/FieldTypeDefinition';\nexport type {\n CursorQuery,\n OffsetQuery,\n CursorQueryResult,\n O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AAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAyB,oBAAA,CAAAzB,GAAA;EAAAK,OAAA,CAAAL,GAAA,IAAAyB,oBAAA,CAAAzB,GAAA;AAAA","ignoreList":[]}
@@ -1045,16 +1045,17 @@ class ImportState {
1045
1045
  };
1046
1046
  }
1047
1047
  _applyJobProgress(job) {
1048
- var _progress$itemsSucces, _progress$itemsSucces2;
1049
1048
  const progress = job.progress;
1050
1049
  const succeeded = (progress == null ? void 0 : progress.itemsSuccessful) ?? 0;
1051
1050
  const failed = (progress == null ? void 0 : progress.itemsRejected) ?? 0;
1052
1051
  const current = (progress == null ? void 0 : progress.current) ?? succeeded + failed;
1053
1052
  // The server splits successful items into created (new) and updated
1054
- // (existing) — the summary step reports each. Absent on older jobs, in
1055
- // which case both stay 0 and only the total `succeeded` is shown.
1056
- const created = (progress == null || (_progress$itemsSucces = progress.itemsSuccessfulInfo) == null ? void 0 : _progress$itemsSucces.itemsCreated) ?? 0;
1057
- const updated = (progress == null || (_progress$itemsSucces2 = progress.itemsSuccessfulInfo) == null ? void 0 : _progress$itemsSucces2.itemsUpdated) ?? 0;
1053
+ // (existing) — the summary step reports each. Some jobs omit this split
1054
+ // entirely (`itemsSuccessfulInfo` absent); in that case treat every success
1055
+ // as created so the summary still shows a count instead of a blank step.
1056
+ const successInfo = progress == null ? void 0 : progress.itemsSuccessfulInfo;
1057
+ const created = successInfo ? successInfo.itemsCreated ?? 0 : succeeded;
1058
+ const updated = (successInfo == null ? void 0 : successInfo.itemsUpdated) ?? 0;
1058
1059
 
1059
1060
  // `totalCount` is fixed up front in `startImport` from the CSV row count
1060
1061
  // (one uploaded row per CSV row); polling only advances `processedCount`.
@@ -1 +1 @@
1
- {"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","toField","def","_def$config","_def$config2","_def$config3","id","key","displayName","type","toPatternsFieldType","config","validation","isPii","helpText","buildImportConfig","fieldsSource","collection","inputs","destination","fields","backup","idFieldKey","jobApplicationErrorMap","seen","Set","map","f","live","filter","has","_f$validation","header","required","dataSource","_fieldsSource$fieldMa","_fieldsSource$fieldAc","add","fieldManagement","canAddFields","fieldActions","addFields","undefined","collectionId","queryName","updateSchema","defs","mergeFields","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","words","split","Boolean","length","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","suffix","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","created","updated","importInputs","importModalState","translate","errorHandler","showToast","downloadCsv","_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","missingRequiredFields","hasMissingRequiredFields","idMappedHeader","editingHeader","editingMapping","endFieldEdit","action","bound","setWritePolicy","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","applyDataExtensionFieldEdit","close","done","downloadFailedRows","onFileSelected","startImport","reset","ds","createDataExtensionFields","createFields","dataExtensionFieldManagement","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","m","kind","fieldId","field","_missingRequiredFieldNames","entry","entries","find","mapping","policy","canCreateNewField","canConfigureWritePolicy","_this$_abortControlle","_abortController","abort","_pendingFieldsMap","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","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","message","_this$showToast2","text","onClick","removeToastOnClick","_this$downloadCsv","jobId","failures","_fetchFailedRows","reason","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","description","hasNext","cursors","next","indexOf","edit","_this$mappingByHeader","toFieldEdit","draft","toDataExtensionFieldEdit","_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","appError","errorCodesMap","fromEntries","resolve","withErrorHandler","Promise","reject","wixDataCollection","_progress$itemsSucces","_progress$itemsSucces2","progress","itemsSuccessful","itemsRejected","current","itemsSuccessfulInfo","itemsCreated","itemsUpdated","Math","min","_lingerOnCompletion","setTimeout","_runBackup","restore","_resolveFieldMapping","resolved","pending","canCreate","_mapping$displayName","baseName","_createPendingFields","keys","_this$showToast3","backupFailed","loading","createdFields","success","_this$config$mergeFie","_this$config"],"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 toPatternsFieldType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { Field, FieldSpec, NonReferenceField } from '../../types/Field';\nimport type { Schema } from '../../types/Schema';\nimport type {\n FieldDraft,\n FieldManagement,\n FieldPermissions,\n FieldsSource,\n} from '../../types/FieldsSource';\nimport { toDataExtensionFieldEdit, toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n /** The collection's query name — its id, used as the CMS import destination. */\n readonly queryName: string;\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 /** New items created in the destination (subset of `succeeded`). */\n created: number;\n /** Existing items updated in the destination (subset of `succeeded`). */\n updated: number;\n}\n\n/** A rejected row: its index into `csvRows` and the server's failure reason. */\ninterface FailedRow {\n index: number;\n reason: string;\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/** The application error from a failed import job, handed to a resolver. */\nexport type ImportJobApplicationError = {\n code?: string;\n description?: string;\n /** Any structured payload the server attached to the error (e.g. a field list). */\n data?: Record<string, any>;\n};\n\n/**\n * Consumer-supplied map from a failed import job's application-error code to a\n * resolver that returns the message to show. An import runs server-side, so a\n * failure arrives on a 200 (the poll succeeds; the job doesn't) with the\n * application error in the job status. The consumer supplies only the\n * code→message map (their codes, their translations) — ImportState applies it\n * through the container's `errorHandler` internally, so the progress step can\n * resolve the message via `getResolvedError`. The resolver receives the job's\n * application error (its `code`/`description`/`data`):\n *\n * jobApplicationErrorMap: {\n * [jobErrorCode]: (error) => ({ message: translate(..., error.data) }),\n * }\n *\n * When omitted, a failed job falls back to the generic error message.\n */\nexport type JobApplicationErrorMap = Record<\n string,\n (error: ImportJobApplicationError) => { message: string }\n>;\n\n// `required` is added on top of the ambassador descriptor (which carries only\n// `id`/`header`): a field the destination mandates. Consumers set it — the\n// schema-backed config forwards `validation.required`, manual/platformized\n// configs set it per field — and the mapping step blocks import while any\n// required field has no column mapped to it (CAIRO-4452).\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number] & { required?: boolean };\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 the field def's\n// `displayName`.\n//\n// This is core-internal storage on the column mapping, shared by both sources —\n// the CMS editor fills `validation`/`isPii`/`helpText`, the DataExtension editor\n// fills `permissions`/`isPii`/`helpText`/`deType`. The two never cross: which\n// subset is read is decided by the config's `dataSource` branch when the field\n// def is built (`_resolveFieldMapping`). The consumer-facing create callbacks\n// still receive distinct def types (`NewFieldDefinition` vs\n// `NewDataExtensionFieldDef`), so this superset is not part of the public API.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n /** DataExtension-only: read/write permission defaults chosen in the editor. */\n permissions?: FieldPermissions;\n /**\n * DataExtension-only: the precise DataExtension field-type id the user picked\n * (e.g. `'decimal'`), finer than the coarse detected `NewFieldType`. Absent ⇒\n * the type is derived from the column's detected `NewFieldType`.\n */\n deType?: 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 *\n * Optionally returns the collection's updated fields map, mirroring the schema's\n * `FieldActions`. When it does, the import merges that map into the table's field\n * source on success so the new columns appear with no manual reload (CAIRO-4400).\n * Returning `void` still imports fine — the columns just wait for the next schema\n * load.\n */\nexport type UpdateSchemaFn = (\n fields: NewFieldDefinition[],\n) => Promise<Schema['fields'] | void>;\n\n/**\n * Creates the pending new DataExtension custom fields before the rows are\n * uploaded — the `destination` branch's counterpart to `updateSchema`. Its\n * presence is the \"create new field\" opt-in for a DataExtension import. Receives\n * the source-neutral pending columns (Cairo-decided keys + names + the edited\n * config); the DataExtension source builds its own field shape from them, so no\n * DataExtension-specific shape leaks into core.\n * Optionally returns the updated fields map to merge into the table (CAIRO-4400);\n * DataExtension refreshes its own schema in place, so returning `void` is fine.\n */\nexport type CreateDataExtensionFieldsFn = (\n fields: PendingNewField[],\n) => Promise<Schema['fields'] | 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\n/** A `new`-mapped column with its deduped key + display name, handed to a\n * source's create callback so it can build its own field shape. */\nexport type PendingNewField = {\n key: string;\n displayName: string;\n mapping: Extract<ColumnMapping, { kind: 'new' }>;\n};\n\n/**\n * Where the import writes and how it creates new fields, split per source. The\n * discriminant (`collectionId` vs `destination`) makes the two mutually\n * exclusive and pairs each target with its own create-fields callback, so a CMS\n * target can't be paired with a DataExtension create callback (or vice versa).\n * Each branch's create members are optional — a plain import supplies none and\n * is mapping-only.\n */\nexport type ImportDataSource =\n | {\n /** Wix Data collection the import writes into (the common CMS case). */\n collectionId: string;\n /** Creates new schema fields before upload; resolves with the updated map. */\n updateSchema?: UpdateSchemaFn;\n }\n | {\n /**\n * Platformized (non–Wix-Data) destination, sent to the job verbatim (e.g.\n * `{ storesCatalogProducts: {} }`). `writePolicy` is never attached to it.\n */\n destination: Destination;\n /** Creates new DataExtension custom fields before upload. */\n createFields?: CreateDataExtensionFieldsFn;\n /**\n * The source's field-management contract, used by the DataExtension\n * \"create/edit field\" editor (creatable types, permissions, existing keys).\n * Present when the source permits adding fields.\n */\n fieldManagement?: FieldManagement;\n };\n\n/**\n * The effective import config. Satisfied both by a plain object (a fully\n * hand-built config) and by the object `buildImportConfig` assembles, whose\n * members are getters read on demand — so the async schema load needn't resolve\n * before `ImportState` is built. `ImportState` holds it by reference (never\n * spreads it) so those getters stay live.\n */\nexport interface ResolvedImportConfig {\n /** Existing collection fields, for column auto-mapping. */\n fields: ImportField[];\n /** Where the import writes, and how it creates new fields — see {@link ImportDataSource}. */\n dataSource: ImportDataSource;\n /**\n * Optional snapshot taken before the rows are uploaded. The returned\n * `restore` is invoked only if the user cancels mid-import — a job failure\n * leaves partial rows and offers \"Try again\" instead.\n */\n backup?: BackupFn;\n /**\n * Merges a create callback's returned fields map into the table after a\n * successful import, so the new columns appear with no reload (CAIRO-4400). A\n * schema-backed config (`buildImportConfig`) wires this to its live schema;\n * when omitted, the new columns wait for the next schema load.\n */\n mergeFields?: (fields: Schema['fields']) => void;\n /** See {@link JobApplicationErrorMap}. */\n jobApplicationErrorMap?: JobApplicationErrorMap;\n /**\n * The collection's id-field key, for the id-collision write policy. Defaults\n * to `_id` (the Wix Data default) when unset.\n */\n idFieldKey?: string;\n}\n\n/**\n * The inputs a consumer passes to `<ImportButton config={...} />`. Everything the\n * table's source provides — the collection, its fields, create-new-field and\n * merge-back — is read live off the `fieldsSource`, so only what isn't derivable\n * lives here. Omit `destination` to import into the table's own collection (Wix\n * Data); set it to write to a platformized target instead.\n */\nexport interface ImportConfig {\n /** A platformized (non–Wix-Data) destination, e.g. `{ storesCatalogProducts: {} }`. */\n destination?: Destination;\n /** Existing fields for column auto-mapping, merged with the source's live\n * fields (these first, deduped by id). */\n fields?: ImportField[];\n /** Snapshot taken before the rows upload; its `restore` undoes a cancelled import. */\n backup?: BackupFn;\n /** The collection's id-field key, for the id-collision write policy. Defaults to `_id`. */\n idFieldKey?: string;\n /** See {@link JobApplicationErrorMap}. */\n jobApplicationErrorMap?: JobApplicationErrorMap;\n}\n\n// Builds the Field to create from a pending new column: import decides the key,\n// and the detected NewFieldType maps to the schema's PatternsFieldType. Import\n// only ever creates non-reference fields, so the cast is safe.\nconst toField = (def: NewFieldDefinition): Field =>\n ({\n id: def.key,\n displayName: def.displayName,\n type: toPatternsFieldType(def.type),\n ...(def.config?.validation && { validation: def.config.validation }),\n ...(def.config?.isPii && { isPii: true }),\n ...(def.config?.helpText && { helpText: def.config.helpText }),\n } as Field);\n\n/**\n * Assembles a `ResolvedImportConfig` from the table's live `fieldsSource` and the\n * consumer `inputs`. The schema-derived members are getters so they read the\n * source live — fields import creates and fields added through the\n * field-management panel show up immediately. Empty before a source attaches;\n * nothing imports until then.\n *\n * Exported for tests.\n */\nexport const buildImportConfig = (\n fieldsSource: FieldsSource | undefined,\n collection: ImportCollection,\n inputs: ImportConfig = {},\n): ResolvedImportConfig => {\n const {\n destination,\n fields = [],\n backup,\n idFieldKey,\n jobApplicationErrorMap,\n } = inputs;\n return {\n get fields(): ImportField[] {\n const seen = new Set(fields.map((f) => f.id));\n const live = (fieldsSource?.fields ?? [])\n .filter((f) => !seen.has(f.id))\n .map((f) => ({\n id: f.id,\n header: f.displayName,\n required: f.validation?.required,\n }));\n return [...fields, ...live];\n },\n get dataSource(): ImportDataSource {\n if (destination) {\n return { destination };\n }\n const add = fieldsSource?.fieldManagement?.canAddFields\n ? fieldsSource.fieldActions?.addFields\n : undefined;\n return {\n collectionId: collection.queryName,\n ...(add && {\n updateSchema: (defs: NewFieldDefinition[]) => add(defs.map(toField)),\n }),\n };\n },\n mergeFields: (f: Schema['fields']) => fieldsSource?.mergeFields?.(f),\n ...(backup && { backup }),\n ...(idFieldKey && { idFieldKey }),\n ...(jobApplicationErrorMap && { jobApplicationErrorMap }),\n };\n};\n\nexport interface ImportStateProps {\n /**\n * A pre-built import config. Usually omitted — pass `fieldsSource` + `importInputs`\n * instead and `ImportState` builds it. Kept for a fully hand-built config.\n */\n config?: ResolvedImportConfig;\n /** The table's live fields source; the built config reads fields/create/merge\n * from it (unless a pre-built `config` is passed). */\n fieldsSource?: FieldsSource;\n /** The consumer inputs that aren't derived from the source. */\n importInputs?: ImportConfig;\n /** Wix httpClient used to drive the Hub Job (data-movement) API. */\n httpClient: HttpClient;\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}\n\nexport type ImportStep = 'upload' | 'configuration' | 'progress' | 'summary';\n\n// How long to hold the completed (100%) progress bar on screen before moving to\n// the summary step (CAIRO-4476). The job reports counts only when it finishes,\n// so the bar sits at 0 for the whole import and would otherwise flip straight to\n// the summary without the user ever seeing it reach 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 // The import inputs, held by reference so a live schema-backed config's getters\n // stay live (never spread). The public getters below read from it on demand.\n private readonly config: ResolvedImportConfig;\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 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 created: 0,\n updated: 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, or\n // `null` when the editor is closed. Observable so the source's field-editor\n // component (rendered via `renderFieldEditor`) opens/prefills itself when this\n // is set and closes when it clears — the editor is decoupled from the layout.\n editingHeader: string | null = null;\n // Holds `updateSchema`'s returned fields map between field creation (pre-upload)\n // and success. Kept private/non-observable so it can't update columns mid-import;\n // it's promoted to the observable `createdFieldsMap` only on success.\n private _pendingFieldsMap?: Schema['fields'];\n\n constructor(props: ImportStateProps) {\n this.collection = props.collection;\n // A pre-built config wins (hand-built / tests); otherwise assemble it from\n // the live source + inputs.\n this.config =\n props.config ??\n buildImportConfig(\n props.fieldsSource,\n props.collection,\n props.importInputs,\n );\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._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 missingRequiredFields: computed,\n hasMissingRequiredFields: computed,\n idMappedHeader: computed,\n editingHeader: observable.ref,\n editingMapping: computed,\n endFieldEdit: action.bound,\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 applyDataExtensionFieldEdit: action.bound,\n close: action.bound,\n done: action.bound,\n downloadFailedRows: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n // Import inputs read live from `config` — a live schema-backed config exposes\n // these as getters, a manual config as plain values; both read the same way.\n\n /** Existing collection fields, for column auto-mapping. */\n get fields(): ImportField[] {\n return this.config.fields;\n }\n\n /** Wix Data collection the import writes into (unset for platformized). */\n get collectionId(): string | undefined {\n const ds = this.config.dataSource;\n return 'collectionId' in ds ? ds.collectionId : undefined;\n }\n\n get destination(): Destination | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.destination : undefined;\n }\n\n get backup(): BackupFn | undefined {\n return this.config.backup;\n }\n\n /** CMS create-fields callback, present only on the `collectionId` branch. */\n get updateSchema(): UpdateSchemaFn | undefined {\n const ds = this.config.dataSource;\n return 'collectionId' in ds ? ds.updateSchema : undefined;\n }\n\n /** DataExtension create-fields callback, present only on the `destination` branch. */\n get createDataExtensionFields(): CreateDataExtensionFieldsFn | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.createFields : undefined;\n }\n\n /** DataExtension field-management for the editor, on the `destination` branch. */\n get dataExtensionFieldManagement(): FieldManagement | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.fieldManagement : undefined;\n }\n\n get jobApplicationErrorMap(): JobApplicationErrorMap | undefined {\n return this.config.jobApplicationErrorMap;\n }\n\n // The collection's id-field key; a schema-backed config may report a non-`_id`\n // identifier. Defaults to the Wix Data `_id`.\n private get idFieldKey(): string {\n return this.config.idFieldKey ?? ID_FIELD_KEY;\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 * Required destination fields that no CSV column is mapped to (CAIRO-4452).\n * A required field is an existing collection field, so only an `existing`\n * mapping can satisfy it — a \"create new field\" column can't. Covers both\n * ways a required field ends up unmapped: the CSV has no matching column at\n * all, or the user set its column to \"don't import\". Drives the footer\n * indicator and blocks `startImport`.\n */\n get missingRequiredFields(): ImportField[] {\n return this.fields.filter(\n (field) =>\n field.required &&\n field.id != null &&\n !this.selectedFieldIds.has(field.id),\n );\n }\n\n get hasMissingRequiredFields(): boolean {\n return this.missingRequiredFields.length > 0;\n }\n\n // Comma-separated display names of the missing required fields, for the block\n // toast. Falls back to the field id when a field carries no header.\n private _missingRequiredFieldNames(): string {\n return this.missingRequiredFields\n .map((field) => field.header || field.id || '')\n .filter(Boolean)\n .join(', ');\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 idFieldKey = this.idFieldKey;\n const entry = Object.entries(this.mappingByHeader).find(\n ([, mapping]) =>\n mapping?.kind === 'existing' && mapping.fieldId === idFieldKey,\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 * The opt-in is the presence of the active `dataSource` branch's create\n * callback — `updateSchema` (CMS) or `createFields` (DataExtension). A source\n * that can't create fields (e.g. no create permission) supplies neither, so\n * columns fall back to \"don't import\" (see `getDefaultMapping`).\n */\n get canCreateNewField(): boolean {\n return this.updateSchema != null || this.createDataExtensionFields != 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 created: 0,\n updated: 0,\n };\n this._pendingFieldsMap = undefined;\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 success\n // `startImport` moves straight to the 'summary' step, so a close from there\n // just closes the modal (the summary's own `done` is the normal exit); this\n // guard covers only closing mid-import.\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 /**\n * Closes the summary step at the end of a completed import. The collection was\n * already refreshed when the summary opened, so this only dismisses the modal.\n */\n done() {\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 /**\n * Builds a re-importable CSV of the rows the server rejected and hands it to\n * `downloadCsv`. Each failed row is prefixed with a leading \"why it failed\"\n * column holding the server's error message, so the user can see and fix each\n * reason. The failed rows (and their reasons) come from the job's movement\n * logs, mapped back to the parsed `csvRows` we still hold in memory.\n */\n async downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let failures: FailedRow[];\n try {\n failures = await this._fetchFailedRows(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const rows = failures\n .map(({ index, reason }) => {\n const row = this.csvRows[index];\n return row != null ? [reason, ...row] : null;\n })\n .filter((row): row is string[] => row != null);\n\n if (rows.length === 0) {\n return;\n }\n\n const headers = [\n this.translate('cairo.import.failureReasonColumn'),\n ...this.csvHeaders,\n ];\n const content = unparseCsv(headers, rows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns, for each row that failed,\n // its `csvRows` index and the server's failure reason. 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 _fetchFailedRows(jobId: string): Promise<FailedRow[]> {\n const failures: FailedRow[] = [];\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 failures.push({ index, reason: log.failure.description ?? '' });\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return failures;\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 * Opens the field editor for a column's pending new field: sets\n * `editingHeader`, which the source's editor component watches to open and\n * prefill itself. No-op if the column isn't mapped to a new field.\n */\n beginFieldEdit(header: string) {\n if (this.mappingByHeader[header]?.kind === 'new') {\n this.editingHeader = header;\n }\n }\n\n /** Closes the field editor (clears `editingHeader`). */\n endFieldEdit() {\n this.editingHeader = null;\n }\n\n /**\n * The `new` mapping currently being edited, or `null` when the editor is\n * closed. The editor component reads this to prefill its form.\n */\n get editingMapping(): Extract<ColumnMapping, { kind: 'new' }> | null {\n if (this.editingHeader == null) {\n return null;\n }\n const mapping = this.mappingByHeader[this.editingHeader];\n return mapping?.kind === 'new' ? mapping : null;\n }\n\n /**\n * `onSubmit` handler for the CMS field editor: maps the edited field spec into\n * the 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 * `onSubmit` handler for the DataExtension field editor: maps the edited\n * DataExtension draft (which carries per-audience permissions) into the column\n * being edited. The `destination`-branch counterpart to `applyFieldEdit`.\n */\n applyDataExtensionFieldEdit(draft: FieldDraft) {\n if (this.editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this.editingHeader, toDataExtensionFieldEdit(draft));\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`), then\n // resolve it through the consumer's per-code map via `withErrorHandler` —\n // the same way as `fetchData` etc. `job.error` is the consumer's\n // application error (their import business logic), so only they can map\n // its codes; they supply just the code→message map and we do the\n // wrapping. `withErrorHandler` attaches the map to the error and\n // re-rejects it, so the progress step resolves a consumer-specific\n // message via `getResolvedError`. Without a map the same error still\n // throws, falling back to the generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n\n const jobApplicationErrorMap = this.jobApplicationErrorMap;\n if (jobApplicationErrorMap) {\n // Adapt the consumer's code→message map into the error handler's\n // `errorCodesMap`: each entry, when its code matches the job's\n // application error, resolves with that error. `withErrorHandler`\n // attaches the resolved message to `error` and re-rejects it, so the\n // progress step surfaces it via `getResolvedError` — the consumer only\n // supplies the map, not the wrapping.\n const appError = (job.error ?? {}) as ImportJobApplicationError;\n const errorCodesMap = Object.fromEntries(\n Object.entries(jobApplicationErrorMap).map(([code, resolve]) => [\n code,\n () => resolve(appError),\n ]),\n );\n await this.errorHandler.withErrorHandler(\n (): Promise<unknown> => Promise.reject(error),\n errorCodesMap,\n );\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 // The server splits successful items into created (new) and updated\n // (existing) — the summary step reports each. Absent on older jobs, in\n // which case both stay 0 and only the total `succeeded` is shown.\n const created = progress?.itemsSuccessfulInfo?.itemsCreated ?? 0;\n const updated = progress?.itemsSuccessfulInfo?.itemsUpdated ?? 0;\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, created, updated };\n });\n }\n\n private _lingerOnCompletion(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, COMPLETION_LINGER_MS));\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 /**\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 // Pending new columns with their deduped key + display name. Source-neutral;\n // the per-source field def is built from these in `_createPendingFields`.\n const pending: PendingNewField[] = [];\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 const canCreate = this.canCreateNewField;\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 (canCreate) {\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 pending.push({ key, displayName, mapping });\n resolved[header] = key;\n } else {\n // \"new\" mapping with no create callback on this source — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (pending.length > 0) {\n // Stash the returned fields map to merge into the table on success; kept off\n // the observable until then so columns don't update mid-import.\n this._pendingFieldsMap = await this._createPendingFields(pending);\n }\n\n return resolved;\n }\n\n /**\n * Creates the pending new fields via the active `dataSource` branch's callback\n * — `updateSchema` (CMS) or `createFields` (DataExtension) — building the\n * source-specific field def from the shared, already-deduped pending columns.\n * The callback may throw; `startImport` surfaces that as the error state.\n */\n private async _createPendingFields(\n pending: PendingNewField[],\n ): Promise<Schema['fields'] | undefined> {\n const updateSchema = this.updateSchema;\n const createDataExtensionFields = this.createDataExtensionFields;\n\n let updated: Schema['fields'] | void;\n if (updateSchema) {\n updated = await updateSchema(\n pending.map(({ key, displayName, mapping }) => ({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n })),\n );\n } else if (createDataExtensionFields) {\n // The DataExtension source builds its own field shape from the neutral\n // pending columns — no DataExtension-specific def-building in core.\n updated = await createDataExtensionFields(pending);\n } else {\n return undefined;\n }\n\n // Guard the empty map: SchemaState.mergeFields is a full replace, so merging\n // `{}` would wipe every column — treat a missing/empty return as \"nothing to\n // merge\".\n return updated && Object.keys(updated).length > 0 ? updated : undefined;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n // Block import while any required destination field is unmapped and tell the\n // user which (CAIRO-4452). The footer already flags this; the Import button\n // stays enabled, so this is where the click is stopped.\n if (this.hasMissingRequiredFields) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.missingRequiredMessage', {\n fields: this._missingRequiredFieldNames(),\n }),\n });\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 created: 0,\n updated: 0,\n };\n this._jobId = null;\n // Drop any fields map from a prior attempt so a no-new-fields \"Try again\"\n // can't merge stale fields.\n this._pendingFieldsMap = undefined;\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 // Assigned only on the success path below, so the post-import merge (after the\n // try/catch) fires only for a completed import — without re-checking status\n // there. Reading `_pendingFieldsMap` directly wouldn't do: it's set pre-upload,\n // so it stays truthy even when the job later fails.\n let createdFields: Schema['fields'] | undefined;\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 // The job reports counts only when it finishes, so the bar sat at 0 for\n // the whole import (CAIRO-4476). Snap it to 100% and hold it (below)\n // before the summary step replaces the progress step, so the user sees\n // the import reach completion.\n this.processedCount = this.totalCount;\n });\n\n // Keep the completed bar on screen briefly before moving on. `importStatus`\n // is already success, so a close during this window just dismisses the\n // modal (the `close()` guard doesn't treat it as a cancel).\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n\n // Success path only. `_pendingFieldsMap` holds this run's returned map — it's\n // cleared at the start of `startImport` (the stale-guard) and set by\n // `_resolveFieldMapping`; snapshotting here keeps the merge success-gated.\n createdFields = this._pendingFieldsMap;\n\n runInAction(() => {\n // Import finished: show the summary step (created / updated / failed\n // counts, plus a \"Download CSV\" of the failed rows when any failed).\n // The modal stays open; the user dismisses it from the summary via\n // `done`. Refresh the collection now so the table behind the modal is\n // up to date by the time it closes.\n this.currentStep = 'summary';\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 // Merge the created fields into the table so the new columns appear with no\n // manual reload (CAIRO-4400). Called imperatively here, outside the try/catch\n // above, so a merge failure can't flip a completed import into the error state\n // (whose \"Try again\" re-imports every row). `createdFields` is set only on the\n // success path and only when fields were created.\n if (createdFields) {\n try {\n this.config.mergeFields?.(createdFields);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('ImportState config.mergeFields failed', error);\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;AAeA,IAAAW,UAAA,GAAAX,OAAA;AAQA;;AAUA;;AAqBA;AACA;AACA;AACA;AACA;;AAKA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;;AAKA;AACA;;AAEA;AACA;;AAEA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AI,CAACpJ,iBAAiB;MAEtC,IAAAc,iBAAW,EAAC,MAAM;QAChB;QACA;QACA;QACA;QACA;QACA,IAAI,CAACtF,WAAW,GAAG,SAAS;QAC5B,IAAI,CAAC7E,UAAU,CAAC8J,yBAAyB,CAAC;UAAEC,KAAK,EAAE;QAAK,CAAC,CAAC;MAC5D,CAAC,CAAC;IACJ,CAAC,CAAC,OAAOJ,KAAK,EAAE;MACd,IAAAQ,iBAAW,EAAC,MAAM;QAChB,IAAI,CAACnF,YAAY,GAAG;UAClB,GAAGtB,kBAAW,CAACiG,KAAK;UACpBA;QACF,CAAC;MACH,CAAC,CAAC;IACJ;;IAEA;IACA;IACA;IACA;IACA;IACA,IAAI8I,aAAa,EAAE;MACjB,IAAI;QAAA,IAAAE,qBAAA,EAAAC,YAAA;QACF,CAAAD,qBAAA,IAAAC,YAAA,OAAI,CAAClT,MAAM,EAACoC,WAAW,aAAvB6Q,qBAAA,CAAAnG,IAAA,CAAAoG,YAAA,EAA0BH,aAAa,CAAC;MAC1C,CAAC,CAAC,OAAO9I,KAAK,EAAE;QACd;QACAC,OAAO,CAACD,KAAK,CAAC,uCAAuC,EAAEA,KAAK,CAAC;MAC/D;IACF;EACF;AACF;AAACnL,OAAA,CAAA4E,WAAA,GAAAA,WAAA","ignoreList":[]}
1
+ {"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","toField","def","_def$config","_def$config2","_def$config3","id","key","displayName","type","toPatternsFieldType","config","validation","isPii","helpText","buildImportConfig","fieldsSource","collection","inputs","destination","fields","backup","idFieldKey","jobApplicationErrorMap","seen","Set","map","f","live","filter","has","_f$validation","header","required","dataSource","_fieldsSource$fieldMa","_fieldsSource$fieldAc","add","fieldManagement","canAddFields","fieldActions","addFields","undefined","collectionId","queryName","updateSchema","defs","mergeFields","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","words","split","Boolean","length","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","suffix","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","created","updated","importInputs","importModalState","translate","errorHandler","showToast","downloadCsv","_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","missingRequiredFields","hasMissingRequiredFields","idMappedHeader","editingHeader","editingMapping","endFieldEdit","action","bound","setWritePolicy","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","applyDataExtensionFieldEdit","close","done","downloadFailedRows","onFileSelected","startImport","reset","ds","createDataExtensionFields","createFields","dataExtensionFieldManagement","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","m","kind","fieldId","field","_missingRequiredFieldNames","entry","entries","find","mapping","policy","canCreateNewField","canConfigureWritePolicy","_this$_abortControlle","_abortController","abort","_pendingFieldsMap","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","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","message","_this$showToast2","text","onClick","removeToastOnClick","_this$downloadCsv","jobId","failures","_fetchFailedRows","reason","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","description","hasNext","cursors","next","indexOf","edit","_this$mappingByHeader","toFieldEdit","draft","toDataExtensionFieldEdit","_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","appError","errorCodesMap","fromEntries","resolve","withErrorHandler","Promise","reject","wixDataCollection","progress","itemsSuccessful","itemsRejected","current","successInfo","itemsSuccessfulInfo","itemsCreated","itemsUpdated","Math","min","_lingerOnCompletion","setTimeout","_runBackup","restore","_resolveFieldMapping","resolved","pending","canCreate","_mapping$displayName","baseName","_createPendingFields","keys","_this$showToast3","backupFailed","loading","createdFields","success","_this$config$mergeFie","_this$config"],"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 toPatternsFieldType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { Field, FieldSpec, NonReferenceField } from '../../types/Field';\nimport type { Schema } from '../../types/Schema';\nimport type {\n FieldDraft,\n FieldManagement,\n FieldPermissions,\n FieldsSource,\n} from '../../types/FieldsSource';\nimport { toDataExtensionFieldEdit, toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n /** The collection's query name — its id, used as the CMS import destination. */\n readonly queryName: string;\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 /** New items created in the destination (subset of `succeeded`). */\n created: number;\n /** Existing items updated in the destination (subset of `succeeded`). */\n updated: number;\n}\n\n/** A rejected row: its index into `csvRows` and the server's failure reason. */\ninterface FailedRow {\n index: number;\n reason: string;\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/** The application error from a failed import job, handed to a resolver. */\nexport type ImportJobApplicationError = {\n code?: string;\n description?: string;\n /** Any structured payload the server attached to the error (e.g. a field list). */\n data?: Record<string, any>;\n};\n\n/**\n * Consumer-supplied map from a failed import job's application-error code to a\n * resolver that returns the message to show. An import runs server-side, so a\n * failure arrives on a 200 (the poll succeeds; the job doesn't) with the\n * application error in the job status. The consumer supplies only the\n * code→message map (their codes, their translations) — ImportState applies it\n * through the container's `errorHandler` internally, so the progress step can\n * resolve the message via `getResolvedError`. The resolver receives the job's\n * application error (its `code`/`description`/`data`):\n *\n * jobApplicationErrorMap: {\n * [jobErrorCode]: (error) => ({ message: translate(..., error.data) }),\n * }\n *\n * When omitted, a failed job falls back to the generic error message.\n */\nexport type JobApplicationErrorMap = Record<\n string,\n (error: ImportJobApplicationError) => { message: string }\n>;\n\n// `required` is added on top of the ambassador descriptor (which carries only\n// `id`/`header`): a field the destination mandates. Consumers set it — the\n// schema-backed config forwards `validation.required`, manual/platformized\n// configs set it per field — and the mapping step blocks import while any\n// required field has no column mapped to it (CAIRO-4452).\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number] & { required?: boolean };\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 the field def's\n// `displayName`.\n//\n// This is core-internal storage on the column mapping, shared by both sources —\n// the CMS editor fills `validation`/`isPii`/`helpText`, the DataExtension editor\n// fills `permissions`/`isPii`/`helpText`/`deType`. The two never cross: which\n// subset is read is decided by the config's `dataSource` branch when the field\n// def is built (`_resolveFieldMapping`). The consumer-facing create callbacks\n// still receive distinct def types (`NewFieldDefinition` vs\n// `NewDataExtensionFieldDef`), so this superset is not part of the public API.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n /** DataExtension-only: read/write permission defaults chosen in the editor. */\n permissions?: FieldPermissions;\n /**\n * DataExtension-only: the precise DataExtension field-type id the user picked\n * (e.g. `'decimal'`), finer than the coarse detected `NewFieldType`. Absent ⇒\n * the type is derived from the column's detected `NewFieldType`.\n */\n deType?: 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 *\n * Optionally returns the collection's updated fields map, mirroring the schema's\n * `FieldActions`. When it does, the import merges that map into the table's field\n * source on success so the new columns appear with no manual reload (CAIRO-4400).\n * Returning `void` still imports fine — the columns just wait for the next schema\n * load.\n */\nexport type UpdateSchemaFn = (\n fields: NewFieldDefinition[],\n) => Promise<Schema['fields'] | void>;\n\n/**\n * Creates the pending new DataExtension custom fields before the rows are\n * uploaded — the `destination` branch's counterpart to `updateSchema`. Its\n * presence is the \"create new field\" opt-in for a DataExtension import. Receives\n * the source-neutral pending columns (Cairo-decided keys + names + the edited\n * config); the DataExtension source builds its own field shape from them, so no\n * DataExtension-specific shape leaks into core.\n * Optionally returns the updated fields map to merge into the table (CAIRO-4400);\n * DataExtension refreshes its own schema in place, so returning `void` is fine.\n */\nexport type CreateDataExtensionFieldsFn = (\n fields: PendingNewField[],\n) => Promise<Schema['fields'] | 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\n/** A `new`-mapped column with its deduped key + display name, handed to a\n * source's create callback so it can build its own field shape. */\nexport type PendingNewField = {\n key: string;\n displayName: string;\n mapping: Extract<ColumnMapping, { kind: 'new' }>;\n};\n\n/**\n * Where the import writes and how it creates new fields, split per source. The\n * discriminant (`collectionId` vs `destination`) makes the two mutually\n * exclusive and pairs each target with its own create-fields callback, so a CMS\n * target can't be paired with a DataExtension create callback (or vice versa).\n * Each branch's create members are optional — a plain import supplies none and\n * is mapping-only.\n */\nexport type ImportDataSource =\n | {\n /** Wix Data collection the import writes into (the common CMS case). */\n collectionId: string;\n /** Creates new schema fields before upload; resolves with the updated map. */\n updateSchema?: UpdateSchemaFn;\n }\n | {\n /**\n * Platformized (non–Wix-Data) destination, sent to the job verbatim (e.g.\n * `{ storesCatalogProducts: {} }`). `writePolicy` is never attached to it.\n */\n destination: Destination;\n /** Creates new DataExtension custom fields before upload. */\n createFields?: CreateDataExtensionFieldsFn;\n /**\n * The source's field-management contract, used by the DataExtension\n * \"create/edit field\" editor (creatable types, permissions, existing keys).\n * Present when the source permits adding fields.\n */\n fieldManagement?: FieldManagement;\n };\n\n/**\n * The effective import config. Satisfied both by a plain object (a fully\n * hand-built config) and by the object `buildImportConfig` assembles, whose\n * members are getters read on demand — so the async schema load needn't resolve\n * before `ImportState` is built. `ImportState` holds it by reference (never\n * spreads it) so those getters stay live.\n */\nexport interface ResolvedImportConfig {\n /** Existing collection fields, for column auto-mapping. */\n fields: ImportField[];\n /** Where the import writes, and how it creates new fields — see {@link ImportDataSource}. */\n dataSource: ImportDataSource;\n /**\n * Optional snapshot taken before the rows are uploaded. The returned\n * `restore` is invoked only if the user cancels mid-import — a job failure\n * leaves partial rows and offers \"Try again\" instead.\n */\n backup?: BackupFn;\n /**\n * Merges a create callback's returned fields map into the table after a\n * successful import, so the new columns appear with no reload (CAIRO-4400). A\n * schema-backed config (`buildImportConfig`) wires this to its live schema;\n * when omitted, the new columns wait for the next schema load.\n */\n mergeFields?: (fields: Schema['fields']) => void;\n /** See {@link JobApplicationErrorMap}. */\n jobApplicationErrorMap?: JobApplicationErrorMap;\n /**\n * The collection's id-field key, for the id-collision write policy. Defaults\n * to `_id` (the Wix Data default) when unset.\n */\n idFieldKey?: string;\n}\n\n/**\n * The inputs a consumer passes to `<ImportButton config={...} />`. Everything the\n * table's source provides — the collection, its fields, create-new-field and\n * merge-back — is read live off the `fieldsSource`, so only what isn't derivable\n * lives here. Omit `destination` to import into the table's own collection (Wix\n * Data); set it to write to a platformized target instead.\n */\nexport interface ImportConfig {\n /** A platformized (non–Wix-Data) destination, e.g. `{ storesCatalogProducts: {} }`. */\n destination?: Destination;\n /** Existing fields for column auto-mapping, merged with the source's live\n * fields (these first, deduped by id). */\n fields?: ImportField[];\n /** Snapshot taken before the rows upload; its `restore` undoes a cancelled import. */\n backup?: BackupFn;\n /** The collection's id-field key, for the id-collision write policy. Defaults to `_id`. */\n idFieldKey?: string;\n /** See {@link JobApplicationErrorMap}. */\n jobApplicationErrorMap?: JobApplicationErrorMap;\n}\n\n// Builds the Field to create from a pending new column: import decides the key,\n// and the detected NewFieldType maps to the schema's PatternsFieldType. Import\n// only ever creates non-reference fields, so the cast is safe.\nconst toField = (def: NewFieldDefinition): Field =>\n ({\n id: def.key,\n displayName: def.displayName,\n type: toPatternsFieldType(def.type),\n ...(def.config?.validation && { validation: def.config.validation }),\n ...(def.config?.isPii && { isPii: true }),\n ...(def.config?.helpText && { helpText: def.config.helpText }),\n } as Field);\n\n/**\n * Assembles a `ResolvedImportConfig` from the table's live `fieldsSource` and the\n * consumer `inputs`. The schema-derived members are getters so they read the\n * source live — fields import creates and fields added through the\n * field-management panel show up immediately. Empty before a source attaches;\n * nothing imports until then.\n *\n * Exported for tests.\n */\nexport const buildImportConfig = (\n fieldsSource: FieldsSource | undefined,\n collection: ImportCollection,\n inputs: ImportConfig = {},\n): ResolvedImportConfig => {\n const {\n destination,\n fields = [],\n backup,\n idFieldKey,\n jobApplicationErrorMap,\n } = inputs;\n return {\n get fields(): ImportField[] {\n const seen = new Set(fields.map((f) => f.id));\n const live = (fieldsSource?.fields ?? [])\n .filter((f) => !seen.has(f.id))\n .map((f) => ({\n id: f.id,\n header: f.displayName,\n required: f.validation?.required,\n }));\n return [...fields, ...live];\n },\n get dataSource(): ImportDataSource {\n if (destination) {\n return { destination };\n }\n const add = fieldsSource?.fieldManagement?.canAddFields\n ? fieldsSource.fieldActions?.addFields\n : undefined;\n return {\n collectionId: collection.queryName,\n ...(add && {\n updateSchema: (defs: NewFieldDefinition[]) => add(defs.map(toField)),\n }),\n };\n },\n mergeFields: (f: Schema['fields']) => fieldsSource?.mergeFields?.(f),\n ...(backup && { backup }),\n ...(idFieldKey && { idFieldKey }),\n ...(jobApplicationErrorMap && { jobApplicationErrorMap }),\n };\n};\n\nexport interface ImportStateProps {\n /**\n * A pre-built import config. Usually omitted — pass `fieldsSource` + `importInputs`\n * instead and `ImportState` builds it. Kept for a fully hand-built config.\n */\n config?: ResolvedImportConfig;\n /** The table's live fields source; the built config reads fields/create/merge\n * from it (unless a pre-built `config` is passed). */\n fieldsSource?: FieldsSource;\n /** The consumer inputs that aren't derived from the source. */\n importInputs?: ImportConfig;\n /** Wix httpClient used to drive the Hub Job (data-movement) API. */\n httpClient: HttpClient;\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}\n\nexport type ImportStep = 'upload' | 'configuration' | 'progress' | 'summary';\n\n// How long to hold the completed (100%) progress bar on screen before moving to\n// the summary step (CAIRO-4476). The job reports counts only when it finishes,\n// so the bar sits at 0 for the whole import and would otherwise flip straight to\n// the summary without the user ever seeing it reach 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 // The import inputs, held by reference so a live schema-backed config's getters\n // stay live (never spread). The public getters below read from it on demand.\n private readonly config: ResolvedImportConfig;\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 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 created: 0,\n updated: 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, or\n // `null` when the editor is closed. Observable so the source's field-editor\n // component (rendered via `renderFieldEditor`) opens/prefills itself when this\n // is set and closes when it clears — the editor is decoupled from the layout.\n editingHeader: string | null = null;\n // Holds `updateSchema`'s returned fields map between field creation (pre-upload)\n // and success. Kept private/non-observable so it can't update columns mid-import;\n // it's promoted to the observable `createdFieldsMap` only on success.\n private _pendingFieldsMap?: Schema['fields'];\n\n constructor(props: ImportStateProps) {\n this.collection = props.collection;\n // A pre-built config wins (hand-built / tests); otherwise assemble it from\n // the live source + inputs.\n this.config =\n props.config ??\n buildImportConfig(\n props.fieldsSource,\n props.collection,\n props.importInputs,\n );\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._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 missingRequiredFields: computed,\n hasMissingRequiredFields: computed,\n idMappedHeader: computed,\n editingHeader: observable.ref,\n editingMapping: computed,\n endFieldEdit: action.bound,\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 applyDataExtensionFieldEdit: action.bound,\n close: action.bound,\n done: action.bound,\n downloadFailedRows: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n // Import inputs read live from `config` — a live schema-backed config exposes\n // these as getters, a manual config as plain values; both read the same way.\n\n /** Existing collection fields, for column auto-mapping. */\n get fields(): ImportField[] {\n return this.config.fields;\n }\n\n /** Wix Data collection the import writes into (unset for platformized). */\n get collectionId(): string | undefined {\n const ds = this.config.dataSource;\n return 'collectionId' in ds ? ds.collectionId : undefined;\n }\n\n get destination(): Destination | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.destination : undefined;\n }\n\n get backup(): BackupFn | undefined {\n return this.config.backup;\n }\n\n /** CMS create-fields callback, present only on the `collectionId` branch. */\n get updateSchema(): UpdateSchemaFn | undefined {\n const ds = this.config.dataSource;\n return 'collectionId' in ds ? ds.updateSchema : undefined;\n }\n\n /** DataExtension create-fields callback, present only on the `destination` branch. */\n get createDataExtensionFields(): CreateDataExtensionFieldsFn | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.createFields : undefined;\n }\n\n /** DataExtension field-management for the editor, on the `destination` branch. */\n get dataExtensionFieldManagement(): FieldManagement | undefined {\n const ds = this.config.dataSource;\n return 'destination' in ds ? ds.fieldManagement : undefined;\n }\n\n get jobApplicationErrorMap(): JobApplicationErrorMap | undefined {\n return this.config.jobApplicationErrorMap;\n }\n\n // The collection's id-field key; a schema-backed config may report a non-`_id`\n // identifier. Defaults to the Wix Data `_id`.\n private get idFieldKey(): string {\n return this.config.idFieldKey ?? ID_FIELD_KEY;\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 * Required destination fields that no CSV column is mapped to (CAIRO-4452).\n * A required field is an existing collection field, so only an `existing`\n * mapping can satisfy it — a \"create new field\" column can't. Covers both\n * ways a required field ends up unmapped: the CSV has no matching column at\n * all, or the user set its column to \"don't import\". Drives the footer\n * indicator and blocks `startImport`.\n */\n get missingRequiredFields(): ImportField[] {\n return this.fields.filter(\n (field) =>\n field.required &&\n field.id != null &&\n !this.selectedFieldIds.has(field.id),\n );\n }\n\n get hasMissingRequiredFields(): boolean {\n return this.missingRequiredFields.length > 0;\n }\n\n // Comma-separated display names of the missing required fields, for the block\n // toast. Falls back to the field id when a field carries no header.\n private _missingRequiredFieldNames(): string {\n return this.missingRequiredFields\n .map((field) => field.header || field.id || '')\n .filter(Boolean)\n .join(', ');\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 idFieldKey = this.idFieldKey;\n const entry = Object.entries(this.mappingByHeader).find(\n ([, mapping]) =>\n mapping?.kind === 'existing' && mapping.fieldId === idFieldKey,\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 * The opt-in is the presence of the active `dataSource` branch's create\n * callback — `updateSchema` (CMS) or `createFields` (DataExtension). A source\n * that can't create fields (e.g. no create permission) supplies neither, so\n * columns fall back to \"don't import\" (see `getDefaultMapping`).\n */\n get canCreateNewField(): boolean {\n return this.updateSchema != null || this.createDataExtensionFields != 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 created: 0,\n updated: 0,\n };\n this._pendingFieldsMap = undefined;\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 success\n // `startImport` moves straight to the 'summary' step, so a close from there\n // just closes the modal (the summary's own `done` is the normal exit); this\n // guard covers only closing mid-import.\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 /**\n * Closes the summary step at the end of a completed import. The collection was\n * already refreshed when the summary opened, so this only dismisses the modal.\n */\n done() {\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 /**\n * Builds a re-importable CSV of the rows the server rejected and hands it to\n * `downloadCsv`. Each failed row is prefixed with a leading \"why it failed\"\n * column holding the server's error message, so the user can see and fix each\n * reason. The failed rows (and their reasons) come from the job's movement\n * logs, mapped back to the parsed `csvRows` we still hold in memory.\n */\n async downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let failures: FailedRow[];\n try {\n failures = await this._fetchFailedRows(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const rows = failures\n .map(({ index, reason }) => {\n const row = this.csvRows[index];\n return row != null ? [reason, ...row] : null;\n })\n .filter((row): row is string[] => row != null);\n\n if (rows.length === 0) {\n return;\n }\n\n const headers = [\n this.translate('cairo.import.failureReasonColumn'),\n ...this.csvHeaders,\n ];\n const content = unparseCsv(headers, rows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns, for each row that failed,\n // its `csvRows` index and the server's failure reason. 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 _fetchFailedRows(jobId: string): Promise<FailedRow[]> {\n const failures: FailedRow[] = [];\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 failures.push({ index, reason: log.failure.description ?? '' });\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return failures;\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 * Opens the field editor for a column's pending new field: sets\n * `editingHeader`, which the source's editor component watches to open and\n * prefill itself. No-op if the column isn't mapped to a new field.\n */\n beginFieldEdit(header: string) {\n if (this.mappingByHeader[header]?.kind === 'new') {\n this.editingHeader = header;\n }\n }\n\n /** Closes the field editor (clears `editingHeader`). */\n endFieldEdit() {\n this.editingHeader = null;\n }\n\n /**\n * The `new` mapping currently being edited, or `null` when the editor is\n * closed. The editor component reads this to prefill its form.\n */\n get editingMapping(): Extract<ColumnMapping, { kind: 'new' }> | null {\n if (this.editingHeader == null) {\n return null;\n }\n const mapping = this.mappingByHeader[this.editingHeader];\n return mapping?.kind === 'new' ? mapping : null;\n }\n\n /**\n * `onSubmit` handler for the CMS field editor: maps the edited field spec into\n * the 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 * `onSubmit` handler for the DataExtension field editor: maps the edited\n * DataExtension draft (which carries per-audience permissions) into the column\n * being edited. The `destination`-branch counterpart to `applyFieldEdit`.\n */\n applyDataExtensionFieldEdit(draft: FieldDraft) {\n if (this.editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this.editingHeader, toDataExtensionFieldEdit(draft));\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`), then\n // resolve it through the consumer's per-code map via `withErrorHandler` —\n // the same way as `fetchData` etc. `job.error` is the consumer's\n // application error (their import business logic), so only they can map\n // its codes; they supply just the code→message map and we do the\n // wrapping. `withErrorHandler` attaches the map to the error and\n // re-rejects it, so the progress step resolves a consumer-specific\n // message via `getResolvedError`. Without a map the same error still\n // throws, falling back to the generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n\n const jobApplicationErrorMap = this.jobApplicationErrorMap;\n if (jobApplicationErrorMap) {\n // Adapt the consumer's code→message map into the error handler's\n // `errorCodesMap`: each entry, when its code matches the job's\n // application error, resolves with that error. `withErrorHandler`\n // attaches the resolved message to `error` and re-rejects it, so the\n // progress step surfaces it via `getResolvedError` — the consumer only\n // supplies the map, not the wrapping.\n const appError = (job.error ?? {}) as ImportJobApplicationError;\n const errorCodesMap = Object.fromEntries(\n Object.entries(jobApplicationErrorMap).map(([code, resolve]) => [\n code,\n () => resolve(appError),\n ]),\n );\n await this.errorHandler.withErrorHandler(\n (): Promise<unknown> => Promise.reject(error),\n errorCodesMap,\n );\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 // The server splits successful items into created (new) and updated\n // (existing) — the summary step reports each. Some jobs omit this split\n // entirely (`itemsSuccessfulInfo` absent); in that case treat every success\n // as created so the summary still shows a count instead of a blank step.\n const successInfo = progress?.itemsSuccessfulInfo;\n const created = successInfo ? successInfo.itemsCreated ?? 0 : succeeded;\n const updated = successInfo?.itemsUpdated ?? 0;\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, created, updated };\n });\n }\n\n private _lingerOnCompletion(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, COMPLETION_LINGER_MS));\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 /**\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 // Pending new columns with their deduped key + display name. Source-neutral;\n // the per-source field def is built from these in `_createPendingFields`.\n const pending: PendingNewField[] = [];\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 const canCreate = this.canCreateNewField;\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 (canCreate) {\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 pending.push({ key, displayName, mapping });\n resolved[header] = key;\n } else {\n // \"new\" mapping with no create callback on this source — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (pending.length > 0) {\n // Stash the returned fields map to merge into the table on success; kept off\n // the observable until then so columns don't update mid-import.\n this._pendingFieldsMap = await this._createPendingFields(pending);\n }\n\n return resolved;\n }\n\n /**\n * Creates the pending new fields via the active `dataSource` branch's callback\n * — `updateSchema` (CMS) or `createFields` (DataExtension) — building the\n * source-specific field def from the shared, already-deduped pending columns.\n * The callback may throw; `startImport` surfaces that as the error state.\n */\n private async _createPendingFields(\n pending: PendingNewField[],\n ): Promise<Schema['fields'] | undefined> {\n const updateSchema = this.updateSchema;\n const createDataExtensionFields = this.createDataExtensionFields;\n\n let updated: Schema['fields'] | void;\n if (updateSchema) {\n updated = await updateSchema(\n pending.map(({ key, displayName, mapping }) => ({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n })),\n );\n } else if (createDataExtensionFields) {\n // The DataExtension source builds its own field shape from the neutral\n // pending columns — no DataExtension-specific def-building in core.\n updated = await createDataExtensionFields(pending);\n } else {\n return undefined;\n }\n\n // Guard the empty map: SchemaState.mergeFields is a full replace, so merging\n // `{}` would wipe every column — treat a missing/empty return as \"nothing to\n // merge\".\n return updated && Object.keys(updated).length > 0 ? updated : undefined;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n // Block import while any required destination field is unmapped and tell the\n // user which (CAIRO-4452). The footer already flags this; the Import button\n // stays enabled, so this is where the click is stopped.\n if (this.hasMissingRequiredFields) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.missingRequiredMessage', {\n fields: this._missingRequiredFieldNames(),\n }),\n });\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 created: 0,\n updated: 0,\n };\n this._jobId = null;\n // Drop any fields map from a prior attempt so a no-new-fields \"Try again\"\n // can't merge stale fields.\n this._pendingFieldsMap = undefined;\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 // Assigned only on the success path below, so the post-import merge (after the\n // try/catch) fires only for a completed import — without re-checking status\n // there. Reading `_pendingFieldsMap` directly wouldn't do: it's set pre-upload,\n // so it stays truthy even when the job later fails.\n let createdFields: Schema['fields'] | undefined;\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 // The job reports counts only when it finishes, so the bar sat at 0 for\n // the whole import (CAIRO-4476). Snap it to 100% and hold it (below)\n // before the summary step replaces the progress step, so the user sees\n // the import reach completion.\n this.processedCount = this.totalCount;\n });\n\n // Keep the completed bar on screen briefly before moving on. `importStatus`\n // is already success, so a close during this window just dismisses the\n // modal (the `close()` guard doesn't treat it as a cancel).\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n\n // Success path only. `_pendingFieldsMap` holds this run's returned map — it's\n // cleared at the start of `startImport` (the stale-guard) and set by\n // `_resolveFieldMapping`; snapshotting here keeps the merge success-gated.\n createdFields = this._pendingFieldsMap;\n\n runInAction(() => {\n // Import finished: show the summary step (created / updated / failed\n // counts, plus a \"Download CSV\" of the failed rows when any failed).\n // The modal stays open; the user dismisses it from the summary via\n // `done`. Refresh the collection now so the table behind the modal is\n // up to date by the time it closes.\n this.currentStep = 'summary';\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 // Merge the created fields into the table so the new columns appear with no\n // manual reload (CAIRO-4400). Called imperatively here, outside the try/catch\n // above, so a merge failure can't flip a completed import into the error state\n // (whose \"Try again\" re-imports every row). `createdFields` is set only on the\n // success path and only when fields were created.\n if (createdFields) {\n try {\n this.config.mergeFields?.(createdFields);\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('ImportState config.mergeFields failed', error);\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;AAeA,IAAAW,UAAA,GAAAX,OAAA;AAQA;;AAUA;;AAqBA;AACA;AACA;AACA;AACA;;AAKA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA;;AAKA;AACA;;AAEA;AACA;;AAEA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA;AACA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAwBA;AACA;AACA;AACA;AACA;AACA;AACA;;AA4BA;AACA;AACA;AACA;AACA;AACA;AACA;;AAeA;AACA;AACA;AACA,MAAMY,OAAO,GAAIC,GAAuB;EAAA,IAAAC,WAAA,EAAAC,YAAA,EAAAC,YAAA;EAAA,OACrC;IACCC,EAAE,EAAEJ,GA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