@wix/bex-core 2.331.0 → 2.332.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.
- package/dist/cjs/assets/locale/messages_ar.json +8 -0
- package/dist/cjs/assets/locale/messages_bg.json +8 -0
- package/dist/cjs/assets/locale/messages_ca.json +8 -0
- package/dist/cjs/assets/locale/messages_cs.json +8 -0
- package/dist/cjs/assets/locale/messages_da.json +8 -0
- package/dist/cjs/assets/locale/messages_de.json +8 -0
- package/dist/cjs/assets/locale/messages_el.json +8 -0
- package/dist/cjs/assets/locale/messages_en.json +8 -0
- package/dist/cjs/assets/locale/messages_es.json +8 -0
- package/dist/cjs/assets/locale/messages_fi.json +8 -0
- package/dist/cjs/assets/locale/messages_fr.json +8 -0
- package/dist/cjs/assets/locale/messages_he.json +8 -0
- package/dist/cjs/assets/locale/messages_hi.json +8 -0
- package/dist/cjs/assets/locale/messages_hu.json +8 -0
- package/dist/cjs/assets/locale/messages_id.json +8 -0
- package/dist/cjs/assets/locale/messages_it.json +8 -0
- package/dist/cjs/assets/locale/messages_ja.json +8 -0
- package/dist/cjs/assets/locale/messages_ko.json +8 -0
- package/dist/cjs/assets/locale/messages_lt.json +8 -0
- package/dist/cjs/assets/locale/messages_ms.json +8 -0
- package/dist/cjs/assets/locale/messages_nl.json +8 -0
- package/dist/cjs/assets/locale/messages_no.json +8 -0
- package/dist/cjs/assets/locale/messages_pl.json +8 -0
- package/dist/cjs/assets/locale/messages_pt.json +8 -0
- package/dist/cjs/assets/locale/messages_ro.json +8 -0
- package/dist/cjs/assets/locale/messages_ru.json +8 -0
- package/dist/cjs/assets/locale/messages_sk.json +8 -0
- package/dist/cjs/assets/locale/messages_sl.json +8 -0
- package/dist/cjs/assets/locale/messages_sv.json +8 -0
- package/dist/cjs/assets/locale/messages_th.json +8 -0
- package/dist/cjs/assets/locale/messages_tl.json +8 -0
- package/dist/cjs/assets/locale/messages_tr.json +8 -0
- package/dist/cjs/assets/locale/messages_uk.json +8 -0
- package/dist/cjs/assets/locale/messages_vi.json +8 -0
- package/dist/cjs/assets/locale/messages_zh.json +8 -0
- package/dist/cjs/assets/locale/version_file +1 -1
- package/dist/cjs/hooks/useImport.js +3 -13
- package/dist/cjs/hooks/useImport.js.map +1 -1
- package/dist/cjs/hooks/useImportConfig.js +2 -0
- package/dist/cjs/hooks/useImportConfig.js.map +1 -1
- package/dist/cjs/services/translations.js.map +1 -1
- package/dist/cjs/state/ImportState/ImportState.js +95 -18
- package/dist/cjs/state/ImportState/ImportState.js.map +1 -1
- package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js +278 -3
- package/dist/cjs/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
- package/dist/cjs/state/TagsState/TagsManagementState.js +17 -44
- package/dist/cjs/state/TagsState/TagsManagementState.js.map +1 -1
- package/dist/cjs/state/TagsState/TagsSearchState.js +0 -6
- package/dist/cjs/state/TagsState/TagsSearchState.js.map +1 -1
- package/dist/cjs/types/FieldsSource.js.map +1 -1
- package/dist/cjs/types/Schema.js.map +1 -1
- package/dist/esm/assets/locale/messages_ar.json +8 -0
- package/dist/esm/assets/locale/messages_bg.json +8 -0
- package/dist/esm/assets/locale/messages_ca.json +8 -0
- package/dist/esm/assets/locale/messages_cs.json +8 -0
- package/dist/esm/assets/locale/messages_da.json +8 -0
- package/dist/esm/assets/locale/messages_de.json +8 -0
- package/dist/esm/assets/locale/messages_el.json +8 -0
- package/dist/esm/assets/locale/messages_en.json +8 -0
- package/dist/esm/assets/locale/messages_es.json +8 -0
- package/dist/esm/assets/locale/messages_fi.json +8 -0
- package/dist/esm/assets/locale/messages_fr.json +8 -0
- package/dist/esm/assets/locale/messages_he.json +8 -0
- package/dist/esm/assets/locale/messages_hi.json +8 -0
- package/dist/esm/assets/locale/messages_hu.json +8 -0
- package/dist/esm/assets/locale/messages_id.json +8 -0
- package/dist/esm/assets/locale/messages_it.json +8 -0
- package/dist/esm/assets/locale/messages_ja.json +8 -0
- package/dist/esm/assets/locale/messages_ko.json +8 -0
- package/dist/esm/assets/locale/messages_lt.json +8 -0
- package/dist/esm/assets/locale/messages_ms.json +8 -0
- package/dist/esm/assets/locale/messages_nl.json +8 -0
- package/dist/esm/assets/locale/messages_no.json +8 -0
- package/dist/esm/assets/locale/messages_pl.json +8 -0
- package/dist/esm/assets/locale/messages_pt.json +8 -0
- package/dist/esm/assets/locale/messages_ro.json +8 -0
- package/dist/esm/assets/locale/messages_ru.json +8 -0
- package/dist/esm/assets/locale/messages_sk.json +8 -0
- package/dist/esm/assets/locale/messages_sl.json +8 -0
- package/dist/esm/assets/locale/messages_sv.json +8 -0
- package/dist/esm/assets/locale/messages_th.json +8 -0
- package/dist/esm/assets/locale/messages_tl.json +8 -0
- package/dist/esm/assets/locale/messages_tr.json +8 -0
- package/dist/esm/assets/locale/messages_uk.json +8 -0
- package/dist/esm/assets/locale/messages_vi.json +8 -0
- package/dist/esm/assets/locale/messages_zh.json +8 -0
- package/dist/esm/assets/locale/version_file +1 -1
- package/dist/esm/hooks/useImport.js +2 -7
- package/dist/esm/hooks/useImport.js.map +1 -1
- package/dist/esm/hooks/useImportConfig.js.map +1 -1
- package/dist/esm/state/ImportState/ImportState.js +68 -12
- package/dist/esm/state/ImportState/ImportState.js.map +1 -1
- package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js +164 -3
- package/dist/esm/state/ImportState/__tests__/ImportState.engine.spec.js.map +1 -1
- package/dist/esm/state/TagsState/TagsManagementState.js +17 -33
- package/dist/esm/state/TagsState/TagsManagementState.js.map +1 -1
- package/dist/esm/state/TagsState/TagsSearchState.js +0 -6
- package/dist/esm/state/TagsState/TagsSearchState.js.map +1 -1
- package/dist/types/hooks/useImport.d.ts +3 -18
- package/dist/types/hooks/useImport.d.ts.map +1 -1
- package/dist/types/hooks/useImportConfig.d.ts +4 -20
- package/dist/types/hooks/useImportConfig.d.ts.map +1 -1
- package/dist/types/services/translations.d.ts +14 -1
- package/dist/types/services/translations.d.ts.map +1 -1
- package/dist/types/state/ImportState/ImportState.d.ts +63 -28
- package/dist/types/state/ImportState/ImportState.d.ts.map +1 -1
- package/dist/types/state/TagsState/TagsManagementState.d.ts.map +1 -1
- package/dist/types/state/TagsState/TagsSearchState.d.ts.map +1 -1
- package/dist/types/types/FieldsSource.d.ts +5 -1
- package/dist/types/types/FieldsSource.d.ts.map +1 -1
- package/dist/types/types/Schema.d.ts +6 -0
- package/dist/types/types/Schema.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -72,6 +72,12 @@ var _fieldEdit = require("./fieldEdit");
|
|
|
72
72
|
* the consumer performs one schema mutation (e.g. `updateSchema(collectionId,
|
|
73
73
|
* ...addField(key, config))`). Its presence is also the opt-in for the "create
|
|
74
74
|
* new field" default — see `getDefaultMapping`.
|
|
75
|
+
*
|
|
76
|
+
* Optionally returns the collection's updated fields map, mirroring the schema's
|
|
77
|
+
* `FieldActions`. When it does, the import merges that map into the table's field
|
|
78
|
+
* source on success so the new columns appear with no manual reload (CAIRO-4400).
|
|
79
|
+
* Returning `void` still imports fine — the columns just wait for the next schema
|
|
80
|
+
* load.
|
|
75
81
|
*/
|
|
76
82
|
|
|
77
83
|
/**
|
|
@@ -85,6 +91,14 @@ var _fieldEdit = require("./fieldEdit");
|
|
|
85
91
|
* - `null` — don't import (skip)
|
|
86
92
|
*/
|
|
87
93
|
|
|
94
|
+
/**
|
|
95
|
+
* The import inputs a consumer supplies. Satisfied both by a plain object (the
|
|
96
|
+
* manual case) and by a live schema reference (`useSchemaImport` in
|
|
97
|
+
* `@wix/patterns`) whose members are getters read on demand — so the async
|
|
98
|
+
* schema load needn't resolve before `ImportState` is built. `ImportState` holds
|
|
99
|
+
* it by reference (never spreads it) so those getters stay live.
|
|
100
|
+
*/
|
|
101
|
+
|
|
88
102
|
// How long to keep the completed progress bar (100%) on screen before closing
|
|
89
103
|
// the modal on a clean import. Without it, an import of very few rows finishes
|
|
90
104
|
// near-instantly and the modal appears to vanish without ever showing the bar
|
|
@@ -131,18 +145,15 @@ function uniqueFieldNameAndKey(header, usedNames, usedKeys) {
|
|
|
131
145
|
}
|
|
132
146
|
class ImportState {
|
|
133
147
|
constructor(props) {
|
|
134
|
-
|
|
135
|
-
(
|
|
136
|
-
(0, _defineProperty2.default)(this, "
|
|
137
|
-
(0, _defineProperty2.default)(this, "backup", void 0);
|
|
138
|
-
(0, _defineProperty2.default)(this, "updateSchema", void 0);
|
|
148
|
+
// The import inputs, held by reference so a live schema-backed config's getters
|
|
149
|
+
// stay live (never spread). The public getters below read from it on demand.
|
|
150
|
+
(0, _defineProperty2.default)(this, "config", void 0);
|
|
139
151
|
(0, _defineProperty2.default)(this, "collection", void 0);
|
|
140
152
|
(0, _defineProperty2.default)(this, "importModalState", void 0);
|
|
141
153
|
(0, _defineProperty2.default)(this, "translate", void 0);
|
|
142
154
|
(0, _defineProperty2.default)(this, "errorHandler", void 0);
|
|
143
155
|
(0, _defineProperty2.default)(this, "showToast", void 0);
|
|
144
156
|
(0, _defineProperty2.default)(this, "downloadCsv", void 0);
|
|
145
|
-
(0, _defineProperty2.default)(this, "onJobError", void 0);
|
|
146
157
|
(0, _defineProperty2.default)(this, "hubJobClient", void 0);
|
|
147
158
|
(0, _defineProperty2.default)(this, "_detectColumnType", void 0);
|
|
148
159
|
(0, _defineProperty2.default)(this, "discardChangesModal", new _ConditionalModalState.ConditionalModalState());
|
|
@@ -188,18 +199,17 @@ class ImportState {
|
|
|
188
199
|
// Not observable — transient wiring between `beginFieldEdit` and the editor's
|
|
189
200
|
// `applyFieldEdit` callback, never rendered.
|
|
190
201
|
(0, _defineProperty2.default)(this, "_editingHeader", null);
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
this
|
|
195
|
-
this.
|
|
202
|
+
// Holds `updateSchema`'s returned fields map between field creation (pre-upload)
|
|
203
|
+
// and success. Kept private/non-observable so it can't update columns mid-import;
|
|
204
|
+
// it's promoted to the observable `createdFieldsMap` only on success.
|
|
205
|
+
(0, _defineProperty2.default)(this, "_pendingFieldsMap", void 0);
|
|
206
|
+
this.config = props.config;
|
|
196
207
|
this.collection = props.collection;
|
|
197
208
|
this.importModalState = props.importModalState;
|
|
198
209
|
this.translate = props.translate;
|
|
199
210
|
this.errorHandler = props.errorHandler;
|
|
200
211
|
this.showToast = props.showToast;
|
|
201
212
|
this.downloadCsv = props.downloadCsv;
|
|
202
|
-
this.onJobError = props.onJobError;
|
|
203
213
|
this._detectColumnType = props.detectColumnType ?? _detectFieldType.detectColumnType;
|
|
204
214
|
this.hubJobClient = (0, _hubJobClient.createHubJobClient)({
|
|
205
215
|
httpClient: props.httpClient,
|
|
@@ -238,6 +248,37 @@ class ImportState {
|
|
|
238
248
|
reset: _mobx.action.bound
|
|
239
249
|
});
|
|
240
250
|
}
|
|
251
|
+
|
|
252
|
+
// Import inputs read live from `config` — a live schema-backed config exposes
|
|
253
|
+
// these as getters, a manual config as plain values; both read the same way.
|
|
254
|
+
|
|
255
|
+
/** Existing collection fields, for column auto-mapping. */
|
|
256
|
+
get fields() {
|
|
257
|
+
return this.config.fields;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Wix Data collection the import writes into (unset for platformized). */
|
|
261
|
+
get collectionId() {
|
|
262
|
+
return this.config.collectionId;
|
|
263
|
+
}
|
|
264
|
+
get destination() {
|
|
265
|
+
return this.config.destination;
|
|
266
|
+
}
|
|
267
|
+
get backup() {
|
|
268
|
+
return this.config.backup;
|
|
269
|
+
}
|
|
270
|
+
get updateSchema() {
|
|
271
|
+
return this.config.updateSchema;
|
|
272
|
+
}
|
|
273
|
+
get onJobError() {
|
|
274
|
+
return this.config.onJobError;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The collection's id-field key; a schema-backed config may report a non-`_id`
|
|
278
|
+
// identifier. Defaults to the Wix Data `_id`.
|
|
279
|
+
get idFieldKey() {
|
|
280
|
+
return this.config.idFieldKey ?? ID_FIELD_KEY;
|
|
281
|
+
}
|
|
241
282
|
init() {
|
|
242
283
|
return () => {
|
|
243
284
|
// Unmounting mid-import stops the poll loop (it checks `_cancelled`) so it
|
|
@@ -286,7 +327,8 @@ class ImportState {
|
|
|
286
327
|
* with no `_id` mapped, every row is a fresh insert and collisions can't occur.
|
|
287
328
|
*/
|
|
288
329
|
get idMappedHeader() {
|
|
289
|
-
const
|
|
330
|
+
const idFieldKey = this.idFieldKey;
|
|
331
|
+
const entry = Object.entries(this.mappingByHeader).find(([, mapping]) => (mapping == null ? void 0 : mapping.kind) === 'existing' && mapping.fieldId === idFieldKey);
|
|
290
332
|
return entry ? entry[0] : null;
|
|
291
333
|
}
|
|
292
334
|
setWritePolicy(policy) {
|
|
@@ -295,12 +337,12 @@ class ImportState {
|
|
|
295
337
|
|
|
296
338
|
/**
|
|
297
339
|
* Whether columns may be mapped to a brand-new field created during import.
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
340
|
+
* When the config sets `canAddFields` (e.g. a schema's create-field permission)
|
|
341
|
+
* that gates it; otherwise the presence of `updateSchema` is the opt-in (see
|
|
342
|
+
* `getDefaultMapping`).
|
|
301
343
|
*/
|
|
302
344
|
get canCreateNewField() {
|
|
303
|
-
return this.updateSchema != null;
|
|
345
|
+
return this.config.canAddFields ?? this.config.updateSchema != null;
|
|
304
346
|
}
|
|
305
347
|
|
|
306
348
|
/**
|
|
@@ -335,6 +377,7 @@ class ImportState {
|
|
|
335
377
|
succeeded: 0,
|
|
336
378
|
failed: 0
|
|
337
379
|
};
|
|
380
|
+
this._pendingFieldsMap = undefined;
|
|
338
381
|
this.isBackingUp = false;
|
|
339
382
|
this.isRestoring = false;
|
|
340
383
|
this.restoreFn = null;
|
|
@@ -879,7 +922,12 @@ class ImportState {
|
|
|
879
922
|
}
|
|
880
923
|
}
|
|
881
924
|
if (newFields.length > 0 && this.updateSchema) {
|
|
882
|
-
|
|
925
|
+
// Stash the returned fields map to merge into the table on success; kept off
|
|
926
|
+
// the observable until then so columns don't update mid-import. Guard the
|
|
927
|
+
// empty map: SchemaState.mergeFields is a full replace, so merging `{}` would
|
|
928
|
+
// wipe every column — treat a missing/empty return as "nothing to merge".
|
|
929
|
+
const updated = await this.updateSchema(newFields);
|
|
930
|
+
this._pendingFieldsMap = updated && Object.keys(updated).length > 0 ? updated : undefined;
|
|
883
931
|
}
|
|
884
932
|
return resolved;
|
|
885
933
|
}
|
|
@@ -908,6 +956,9 @@ class ImportState {
|
|
|
908
956
|
failed: 0
|
|
909
957
|
};
|
|
910
958
|
this._jobId = null;
|
|
959
|
+
// Drop any fields map from a prior attempt so a no-new-fields "Try again"
|
|
960
|
+
// can't merge stale fields.
|
|
961
|
+
this._pendingFieldsMap = undefined;
|
|
911
962
|
});
|
|
912
963
|
const backupFailed = await this._runBackup();
|
|
913
964
|
if (backupFailed) {
|
|
@@ -940,6 +991,12 @@ class ImportState {
|
|
|
940
991
|
..._model.queryStatus.loading,
|
|
941
992
|
promise
|
|
942
993
|
};
|
|
994
|
+
|
|
995
|
+
// Assigned only on the success path below, so the post-import merge (after the
|
|
996
|
+
// try/catch) fires only for a completed import — without re-checking status
|
|
997
|
+
// there. Reading `_pendingFieldsMap` directly wouldn't do: it's set pre-upload,
|
|
998
|
+
// so it stays truthy even when the job later fails.
|
|
999
|
+
let createdFields;
|
|
943
1000
|
try {
|
|
944
1001
|
await promise;
|
|
945
1002
|
if (this._cancelled) {
|
|
@@ -962,6 +1019,11 @@ class ImportState {
|
|
|
962
1019
|
return;
|
|
963
1020
|
}
|
|
964
1021
|
}
|
|
1022
|
+
|
|
1023
|
+
// Success path only. `_pendingFieldsMap` holds this run's returned map — it's
|
|
1024
|
+
// cleared at the start of `startImport` (the stale-guard) and set by
|
|
1025
|
+
// `_resolveFieldMapping`; snapshotting here keeps the merge success-gated.
|
|
1026
|
+
createdFields = this._pendingFieldsMap;
|
|
965
1027
|
(0, _mobx.runInAction)(() => {
|
|
966
1028
|
// Rows the server rejected are reported via a toast (the downloadable
|
|
967
1029
|
// failed-rows report is added by the failed-rows-report task).
|
|
@@ -981,6 +1043,21 @@ class ImportState {
|
|
|
981
1043
|
};
|
|
982
1044
|
});
|
|
983
1045
|
}
|
|
1046
|
+
|
|
1047
|
+
// Merge the created fields into the table so the new columns appear with no
|
|
1048
|
+
// manual reload (CAIRO-4400). Called imperatively here, outside the try/catch
|
|
1049
|
+
// above, so a merge failure can't flip a completed import into the error state
|
|
1050
|
+
// (whose "Try again" re-imports every row). `createdFields` is set only on the
|
|
1051
|
+
// success path and only when fields were created.
|
|
1052
|
+
if (createdFields) {
|
|
1053
|
+
try {
|
|
1054
|
+
var _this$config$mergeFie, _this$config;
|
|
1055
|
+
(_this$config$mergeFie = (_this$config = this.config).mergeFields) == null || _this$config$mergeFie.call(_this$config, createdFields);
|
|
1056
|
+
} catch (error) {
|
|
1057
|
+
// eslint-disable-next-line no-console
|
|
1058
|
+
console.error('ImportState config.mergeFields failed', error);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
984
1061
|
}
|
|
985
1062
|
}
|
|
986
1063
|
exports.ImportState = ImportState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","header","words","split","filter","Boolean","length","map","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","displayName","suffix","key","has","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","fields","collectionId","destination","backup","updateSchema","collection","importModalState","translate","errorHandler","showToast","downloadCsv","onJobError","_detectColumnType","detectColumnType","hubJobClient","createHubJobClient","httpClient","makeObservable","currentStep","observable","ref","importStatus","fileName","csvHeaders","csvRows","orderedHeaders","mappingByHeader","writePolicy","processedCount","totalCount","result","isBackingUp","isRestoring","hasParsedRows","computed","hasMappings","hasNoMappedData","selectedFieldIds","idMappedHeader","setWritePolicy","action","bound","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","close","onFileSelected","startImport","reset","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","Set","m","kind","fieldId","entry","entries","find","mapping","policy","canCreateNewField","canConfigureWritePolicy","_this$_abortControlle","_abortController","abort","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","field","id","forEach","normalizedHeader","matched","fieldType","_columnValues","columnIndex","TYPE_SAMPLE_SIZE","_orderHeadersWithIdFirst","idHeader","applyParsedCsv","parsedCsv","rows","file","bytes","_readFileBytes","_showFileReadErrorToast","content","_decodeUtf8","_rejectFile","parseCsv","name","arrayBuffer","e","TextDecoder","fatal","decode","messageKey","_this$showToast","call","type","message","_this$showToast2","text","onClick","removeToastOnClick","_showPartialSuccessToast","_this$showToast3","String","imported","_downloadFailedRows","_this$downloadCsv","jobId","_fetchFailedRowIndices","failedRows","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","undefined","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","hasNext","cursors","next","indexOf","edit","config","_editingHeader","toFieldEdit","_runImportJob","resolvedMapping","csv","rewriteParsedCsvForImport","File","fileId","uploadFile","submitImportJob","_destination","catch","job","pollImportJob","getJob","isCancelled","onProgress","polled","_applyJobProgress","status","JobStatus","FAILED","_job$error","assign","Error","code","response","data","details","applicationError","run","Promise","reject","wixDataCollection","progress","itemsSuccessful","itemsRejected","current","Math","min","_runBackup","restore","_lingerOnCompletion","resolve","setTimeout","_resolveFieldMapping","resolved","newFields","_mapping$displayName","baseName","add","backupFailed","loading","success"],"sources":["../../../../src/state/ImportState/ImportState.ts"],"sourcesContent":["import {\n action,\n computed,\n makeObservable,\n observable,\n runInAction,\n} from 'mobx';\nimport {\n queryStatus,\n ShowToast,\n TaskStatus,\n PatternsErrorHandler,\n} from '../../model';\nimport type { HttpClient } from '../../model/httpClient';\nimport { Translate, TranslationsKeys } from '../../services';\nimport { ModalState } from '../ModalState';\nimport { ConditionalModalState } from '../ConditionalModalState';\nimport { CreateExportAsyncJobRequest } from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';\nimport {\n JobStatus,\n WritePolicy,\n type Destination,\n type DataMovementJob,\n} from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\nimport { ParseCsvResult, parseCsv, unparseCsv } from './parseCsv';\nimport { rewriteParsedCsvForImport } from './rewriteCsv';\nimport { createHubJobClient, HubJobClient } from './hubJobClient';\nimport { pollImportJob } from './importJobPoller';\nimport {\n detectColumnType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { FieldSpec, NonReferenceField } from '../../types/Field';\nimport { toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n}\n\n/** Outcome of a server-side import job, derived from the job's progress. */\nexport interface ImportResult {\n succeeded: number;\n failed: number;\n}\n\nexport interface BackupResult {\n /**\n * Reverts the collection to its pre-import state. Called only when the user\n * cancels mid-import (matching the previous client-side behavior); a job\n * failure leaves partial rows in place and offers \"Try again\".\n *\n * Must fully revert to the snapshot taken before the import — including rows\n * the import overwrote in place. The default `writePolicy` is upsert (OVERWRITE\n * by `_id`), so it is NOT enough to delete newly-inserted ids; previously\n * existing rows may have been overwritten and must be restored to their prior\n * values.\n */\n restore(signal: AbortSignal): Promise<void>;\n}\n\n/**\n * Optional snapshot taken before the import runs, returning a `restore` used to\n * undo the import on cancel. See {@link BackupResult.restore} for the revert\n * contract under upsert.\n */\nexport type BackupFn = (signal: AbortSignal) => Promise<BackupResult | void>;\n\nexport type DownloadCsvFn = (content: string, fileName: string) => void;\n\n/**\n * Consumer hook for resolving a failed import job's message. An import runs\n * server-side, so a failure arrives on a 200 (the poll succeeds; the job\n * doesn't) with no HTTP error to carry the application error. Cairo hands the\n * consumer `run` — an operation that rejects with a synthetic, HTTP-error-shaped\n * error carrying the job's application error — and the consumer wraps it with\n * their own `withErrorHandler` + error-code map (their codes, their\n * translations), keeping the map coupled to the `withErrorHandler` call as\n * everywhere else (e.g. `fetchData`). The map is keyed by application-error code\n * (the v2 errorHandler shape, like `getExportAsyncJobErrors`):\n *\n * onJobError: (run) =>\n * errorHandler.withErrorHandler(run, {\n * [jobErrorCode]: (error) => ({ message: translate(...) }),\n * })\n *\n * `withErrorHandler` attaches the map to the error object and re-rejects it, so\n * the progress step resolves a consumer-specific message via `getResolvedError`.\n * When omitted, the error still surfaces but resolves to the generic message.\n */\nexport type OnImportJobError = (\n run: () => Promise<unknown>,\n) => Promise<unknown>;\n\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number];\n\n// `NewFieldType`, `detectColumnType`, etc. are re-exported from the package via\n// the `ImportState` barrel (`./index`), which also exports `./detectFieldType`.\n\n// Re-export the write-policy enum so consumers (and the cairo UI) reference it\n// from `@wix/bex-core` rather than the bundled ambassador path.\nexport { WritePolicy } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n// Re-export the destination type for platformized consumers that supply their\n// own variant (e.g. `{ storesCatalogProducts: {} }`) — same reason as above.\nexport type { Destination } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n\n// Per-type configuration for a new field, captured from the \"Edit field\" editor\n// (CAIRO-4398). All optional — an unedited field carries none and is created\n// from detected defaults only. `displayName` is intentionally not here: the\n// (possibly user-overridden) name is deduped and surfaced as\n// `NewFieldDefinition.displayName`.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n}\n\n// A new field to add to the collection schema during import. `key` is decided by\n// Cairo (derived from the column header — or the user's name override — deduped)\n// and is also the key the column's values are written under, so the consumer\n// must add the field under exactly this key. `config` carries any per-type\n// configuration the field editor produced; create the field with it.\nexport interface NewFieldDefinition {\n key: string;\n type: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n}\n\n/**\n * Consumer-supplied callback that adds the given new fields to the collection\n * schema in a single call, before the rows are uploaded. Mirrors the cm-import\n * `beforeImport`/`updateSchema` flow: Cairo decides the fields (and their keys),\n * the consumer performs one schema mutation (e.g. `updateSchema(collectionId,\n * ...addField(key, config))`). Its presence is also the opt-in for the \"create\n * new field\" default — see `getDefaultMapping`.\n */\nexport type UpdateSchemaFn = (fields: NewFieldDefinition[]) => Promise<void>;\n\n/**\n * How a CSV column is mapped:\n * - `existing` — into an existing collection field by id\n * - `new` — into a new field created during import. `fieldType` is the detected\n * type, or the type the user picked in the field editor. `displayName` and\n * `config` are present only once the user edited the pending field via the\n * \"Edit field\" editor — `displayName` overrides the header-derived name and\n * `config` carries the per-type configuration.\n * - `null` — don't import (skip)\n */\nexport type ColumnMapping =\n | { kind: 'existing'; fieldId: string }\n | {\n kind: 'new';\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n }\n | null;\n\nexport interface ImportStateProps {\n fields: CreateExportAsyncJobRequest['fields'];\n /** Wix httpClient used to drive the Hub Job (data-movement) API. */\n httpClient: HttpClient;\n /**\n * Destination data collection the import writes into. Used to build the\n * default Wix Data destination. Optional only because a platformized consumer\n * may instead supply its own `destination` — exactly one of `collectionId` or\n * `destination` must be provided.\n */\n collectionId?: string;\n /**\n * Where the job writes, for platformized (non–Wix-Data) consumers. data-hub's\n * `Destination` is a union, and internal services write through their own\n * variant (e.g. `{ storesCatalogProducts: {} }`), not `wixDataCollection`.\n * When provided, it's sent verbatim and `collectionId`/`writePolicy` are\n * ignored. When omitted, Cairo builds `{ wixDataCollection: { collectionId,\n * writePolicy } }` from `collectionId` (the common CMS case). See plan O6.\n */\n destination?: Destination;\n backup?: BackupFn;\n updateSchema?: UpdateSchemaFn;\n /**\n * Infers a new field's type from its column data. Defaults to the primitive\n * detector (number / date / boolean / url / text). `@wix/patterns` injects a\n * media-aware detector from `@wix/patterns-fields` (image / video / document /\n * audio) — that detection needs the media URI parser, which core can't depend\n * on.\n */\n detectColumnType?: DetectColumnType;\n collection: ImportCollection;\n importModalState: ModalState;\n translate: Translate;\n errorHandler: PatternsErrorHandler;\n showToast?: ShowToast;\n downloadCsv?: DownloadCsvFn;\n /** See {@link OnImportJobError}. */\n onJobError?: OnImportJobError;\n}\n\nexport type ImportStep = 'upload' | 'configuration' | 'progress';\n\n// How long to keep the completed progress bar (100%) on screen before closing\n// the modal on a clean import. Without it, an import of very few rows finishes\n// near-instantly and the modal appears to vanish without ever showing the bar\n// reaching completion.\nconst COMPLETION_LINGER_MS = 600;\n\n// The Wix Data collection's id field key. A CSV column mapped to this field lets\n// the user choose how rows that collide on `_id` are written (writePolicy).\nconst ID_FIELD_KEY = '_id';\n\nfunction normalize(value: string) {\n return value.trim().toLowerCase();\n}\n\n// camelCase key for a field created from a column header\n// (e.g. \"Product Name\" -> \"productName\").\nfunction toFieldKey(header: string): string {\n const words = header\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n if (words.length === 0) {\n return 'field';\n }\n return words\n .map((word, index) =>\n index === 0\n ? word.charAt(0).toLowerCase() + word.slice(1)\n : word.charAt(0).toUpperCase() + word.slice(1),\n )\n .join('');\n}\n\n// A display name + key for a field created from a column header, unique against\n// both `usedNames` (existing field display names + names already assigned to\n// earlier new columns) and `usedKeys` (existing field ids + keys already\n// assigned). Mirrors cm-import `generateFieldNameAndKey`: when the name or its\n// derived key collides, suffix the *display name* as `\"<header>-<n>\"` and\n// re-derive the key from it — so the created field's name and key are both\n// unique (otherwise two columns with the same header would create fields showing\n// the same name).\nfunction uniqueFieldNameAndKey(\n header: string,\n usedNames: Set<string>,\n usedKeys: Set<string>,\n): { displayName: string; key: string } {\n let displayName = header;\n for (let suffix = 1; ; suffix++) {\n const key = toFieldKey(displayName);\n if (!usedNames.has(displayName) && !usedKeys.has(key)) {\n return { displayName, key };\n }\n displayName = `${header}-${suffix}`;\n }\n}\n\nexport class ImportState {\n readonly fields: ImportField[];\n readonly collectionId?: string;\n readonly destination?: Destination;\n readonly backup?: BackupFn;\n readonly updateSchema?: UpdateSchemaFn;\n readonly collection: ImportCollection;\n readonly importModalState: ModalState;\n readonly translate: Translate;\n readonly errorHandler: PatternsErrorHandler;\n readonly showToast?: ShowToast;\n readonly downloadCsv?: DownloadCsvFn;\n readonly onJobError?: OnImportJobError;\n private readonly hubJobClient: HubJobClient;\n private readonly _detectColumnType: DetectColumnType;\n readonly discardChangesModal = new ConditionalModalState<\n 'goBack' | 'close'\n >();\n\n currentStep: ImportStep = 'upload';\n importStatus: TaskStatus<ImportResult, unknown> = {\n ...queryStatus.idle,\n };\n fileName = '';\n csvHeaders: string[] = [];\n csvRows: string[][] = [];\n // Header display order for the configuration step, snapshotted when the file\n // is parsed. The column auto-mapped to `_id` floats to the top (CAIRO-4418);\n // the order then stays fixed while the user edits mappings, so clearing or\n // remapping the `_id` column can't reorder the row under the user's cursor.\n // Recomputed only on a new file (`applyParsedCsv`) or a full `reset()`.\n orderedHeaders: string[] = [];\n mappingByHeader: Record<string, ColumnMapping> = {};\n // How rows that collide on `_id` are written. Only meaningful (and only sent\n // to the server) when a CSV column is mapped to the `_id` field — see\n // `idMappedHeader` and `_destination`. Defaults to the server default\n // (`OVERWRITE` = upsert by `_id`).\n //\n // Retention: the choice is deliberately kept while editing mappings within a\n // file — remapping `_id` away and back keeps the user's selection rather than\n // silently reverting it. It resets to the default only on a *new file* upload\n // (`applyParsedCsv`) or a full `reset()`.\n writePolicy: WritePolicy = WritePolicy.OVERWRITE;\n processedCount = 0;\n totalCount = 0;\n result: ImportResult = {\n succeeded: 0,\n failed: 0,\n };\n isBackingUp = false;\n isRestoring = false;\n private restoreFn: ((signal: AbortSignal) => Promise<void>) | null = null;\n private _cancelled = false;\n private _abortController: AbortController | null = null;\n // Id of the running data-movement job, set once submitted — used to cancel it\n // (`terminateJob`) if the user closes mid-import.\n private _jobId: string | null = null;\n // The column whose pending new field the field editor is currently editing.\n // Not observable — transient wiring between `beginFieldEdit` and the editor's\n // `applyFieldEdit` callback, never rendered.\n private _editingHeader: string | null = null;\n\n constructor(props: ImportStateProps) {\n this.fields = (props.fields ?? []) as ImportField[];\n this.collectionId = props.collectionId;\n this.destination = props.destination;\n this.backup = props.backup;\n this.updateSchema = props.updateSchema;\n this.collection = props.collection;\n this.importModalState = props.importModalState;\n this.translate = props.translate;\n this.errorHandler = props.errorHandler;\n this.showToast = props.showToast;\n this.downloadCsv = props.downloadCsv;\n this.onJobError = props.onJobError;\n this._detectColumnType = props.detectColumnType ?? detectColumnType;\n this.hubJobClient = createHubJobClient({\n httpClient: props.httpClient,\n errorHandler: props.errorHandler,\n });\n\n makeObservable(this, {\n currentStep: observable.ref,\n importStatus: observable.ref,\n fileName: observable.ref,\n csvHeaders: observable.ref,\n csvRows: observable.ref,\n orderedHeaders: observable.ref,\n mappingByHeader: observable.ref,\n writePolicy: observable.ref,\n processedCount: observable.ref,\n totalCount: observable.ref,\n result: observable.ref,\n isBackingUp: observable.ref,\n isRestoring: observable.ref,\n hasParsedRows: computed,\n hasMappings: computed,\n hasNoMappedData: computed,\n selectedFieldIds: computed,\n idMappedHeader: computed,\n setWritePolicy: action.bound,\n onUploadContinue: action.bound,\n goToUpload: action.bound,\n setMapping: action.bound,\n setNewFieldMapping: action.bound,\n setNewFieldConfig: action.bound,\n beginFieldEdit: action.bound,\n applyFieldEdit: action.bound,\n close: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n init() {\n return () => {\n // Unmounting mid-import stops the poll loop (it checks `_cancelled`) so it\n // doesn't run to terminal holding references. We deliberately do NOT abort\n // the AbortController: during a cancel-triggered restore it holds the\n // restore controller, and aborting it would cancel an in-progress restore.\n // The server-side job is also left running — an unmount isn't an explicit\n // user cancel.\n this._cancelled = true;\n };\n }\n\n get hasParsedRows() {\n return this.csvHeaders.length > 0 && this.csvRows.length > 0;\n }\n\n get hasMappings() {\n return Object.values(this.mappingByHeader).some((value) => value != null);\n }\n\n /**\n * True when there are mappings but none of the mapped columns contain any\n * data in any row (including the case of zero data rows). Drives the\n * non-blocking \"no rows found\" warning in the configuration step. Returns\n * false when nothing is mapped yet — that case is handled by the disabled\n * import button instead.\n */\n get hasNoMappedData(): boolean {\n if (!this.hasMappings) {\n return false;\n }\n\n const mappedIndices = this.csvHeaders.reduce<number[]>(\n (indices, header, index) => {\n if (this.mappingByHeader[header] != null) {\n indices.push(index);\n }\n return indices;\n },\n [],\n );\n\n return !this.csvRows.some((row) =>\n mappedIndices.some((index) => (row[index] ?? '').trim() !== ''),\n );\n }\n\n get selectedFieldIds(): Set<string> {\n return new Set(\n Object.values(this.mappingByHeader)\n .filter(\n (m): m is { kind: 'existing'; fieldId: string } =>\n m?.kind === 'existing',\n )\n .map((m) => m.fieldId),\n );\n }\n\n /**\n * The CSV header currently mapped to the collection's `_id` field, or `null`\n * when no column targets it. Drives both the \"When items share the same ID\"\n * control (only shown on this row) and whether `writePolicy` is sent at all —\n * with no `_id` mapped, every row is a fresh insert and collisions can't occur.\n */\n get idMappedHeader(): string | null {\n const entry = Object.entries(this.mappingByHeader).find(\n ([, mapping]) =>\n mapping?.kind === 'existing' && mapping.fieldId === ID_FIELD_KEY,\n );\n return entry ? entry[0] : null;\n }\n\n setWritePolicy(policy: WritePolicy) {\n this.writePolicy = policy;\n }\n\n /**\n * Whether columns may be mapped to a brand-new field created during import.\n * Driven purely by the presence of the `updateSchema` callback — providing the\n * capability is the opt-in (see `getDefaultMapping`). Never changes after\n * construction, so it isn't an observable.\n */\n get canCreateNewField(): boolean {\n return this.updateSchema != null;\n }\n\n /**\n * Whether the write-policy (id-collision) choice is meaningful for this import.\n * `writePolicy` is a `wixDataCollection`-only concept, and `_destination` only\n * attaches it when Cairo builds that destination itself. A consumer-supplied\n * (platformized) `destination` is sent verbatim with no place to carry it, so\n * the choice would be a no-op — the UI hides the control in that case. Fixed at\n * construction (depends only on the `destination` prop), so it isn't an\n * observable.\n */\n get canConfigureWritePolicy(): boolean {\n return this.destination == null;\n }\n\n reset() {\n this._abortController?.abort();\n this._abortController = null;\n this.currentStep = 'upload';\n this.importStatus = {\n ...queryStatus.idle,\n };\n this.fileName = '';\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.writePolicy = WritePolicy.OVERWRITE;\n this.processedCount = 0;\n this.totalCount = 0;\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this.isBackingUp = false;\n this.isRestoring = false;\n this.restoreFn = null;\n this._cancelled = false;\n this._jobId = null;\n }\n\n async close() {\n // While on the progress step we treat close as a cancel — terminate the job\n // and restore the backup — UNLESS the import already succeeded. On the\n // success path `startImport` lingers ~600ms on the completed bar with the\n // step still 'progress'; closing during that window must NOT restore (it\n // would undo a clean import). A successful close just closes the modal and\n // lets the success path do its collection refresh.\n if (this.currentStep === 'progress' && !this.importStatus.isSuccess) {\n this._cancelled = true;\n this._abortController?.abort();\n\n // Stop the server-side job. It does not roll back rows already written —\n // that's what the backup restore below is for.\n if (this._jobId) {\n try {\n await this.hubJobClient.terminateJob(this._jobId);\n } catch (error) {\n console.error('Terminate import job failed', error);\n }\n }\n\n if (!this.isBackingUp) {\n await this._restoreBackup();\n }\n\n this.collection.clearResultAndMoveToStart({\n force: true,\n });\n }\n\n this.importModalState.close();\n }\n\n private async _restoreBackup() {\n const restoreFn = this.restoreFn;\n if (!restoreFn) {\n return;\n }\n\n const restoreController = new AbortController();\n this._abortController = restoreController;\n\n this.isRestoring = true;\n try {\n await restoreFn(restoreController.signal);\n } catch (error) {\n console.error('Restore failed', error);\n }\n runInAction(() => {\n this.isRestoring = false;\n this.restoreFn = null;\n });\n }\n\n goToUpload() {\n this.currentStep = 'upload';\n }\n\n async discardAndGoBack() {\n this.discardChangesModal.open('goBack');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.goToUpload();\n }\n }\n\n async discardAndClose() {\n this.discardChangesModal.open('close');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.close();\n }\n }\n\n onUploadContinue() {\n if (this.hasParsedRows) {\n this.currentStep = 'configuration';\n }\n }\n\n private getDefaultMapping(headers: string[]) {\n const mapping: Record<string, ColumnMapping> = {};\n const fields = this.fields.map((field) => ({\n id: field.id ?? '',\n header: field.header ?? '',\n }));\n\n headers.forEach((header, index) => {\n const normalizedHeader = normalize(header);\n const matched = fields.find(\n (field) =>\n normalize(field.id) === normalizedHeader ||\n normalize(field.header) === normalizedHeader,\n );\n\n if (matched?.id) {\n mapping[header] = { kind: 'existing', fieldId: matched.id };\n } else {\n // Unmatched columns default to creating a new field (type inferred from\n // the column's data) when the consumer supplied `updateSchema`;\n // otherwise they default to skip.\n mapping[header] = this.canCreateNewField\n ? {\n kind: 'new',\n fieldType: this._detectColumnType(this._columnValues(index)),\n }\n : null;\n }\n });\n\n return mapping;\n }\n\n // The column's values, capped at the detection sample size — detection only\n // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole\n // column (a wide CSV would otherwise allocate rows × columns strings).\n private _columnValues(columnIndex: number): string[] {\n return this.csvRows\n .slice(0, TYPE_SAMPLE_SIZE)\n .map((row) => row[columnIndex] ?? '');\n }\n\n // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the\n // rest. Returns a fresh array so the snapshot doesn't alias `csvHeaders`.\n private _orderHeadersWithIdFirst(headers: string[]): string[] {\n const idHeader = this.idMappedHeader;\n return idHeader != null\n ? [idHeader, ...headers.filter((header) => header !== idHeader)]\n : [...headers];\n }\n\n private applyParsedCsv(fileName: string, parsedCsv: ParseCsvResult) {\n this.fileName = fileName;\n this.csvHeaders = parsedCsv.headers;\n this.csvRows = parsedCsv.rows;\n this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);\n // Snapshot the row order for this file with the auto-mapped `_id` column\n // first. Reads `idMappedHeader`, so it must run after `mappingByHeader` is\n // set. Kept stable until the next file so mapping edits don't reorder rows.\n this.orderedHeaders = this._orderHeadersWithIdFirst(parsedCsv.headers);\n // A new file is a fresh import: start from the default policy so a prior\n // file's Skip choice doesn't silently carry over (only the new-file path\n // resets — remapping `_id` within the same file keeps the user's choice).\n this.writePolicy = WritePolicy.OVERWRITE;\n this.currentStep = 'configuration';\n }\n\n async onFileSelected(file: File | null) {\n if (file == null) {\n return;\n }\n\n const bytes = await this._readFileBytes(file);\n if (bytes == null) {\n this._showFileReadErrorToast(file);\n return;\n }\n\n const content = this._decodeUtf8(bytes);\n if (content == null) {\n this._rejectFile(file, 'cairo.import.encodingFailed');\n return;\n }\n\n const parsedCsv = parseCsv(content);\n if ('code' in parsedCsv) {\n this._rejectFile(file, 'cairo.import.processFailed');\n return;\n }\n\n runInAction(() => {\n this.applyParsedCsv(file.name, parsedCsv);\n });\n }\n\n private async _readFileBytes(file: File): Promise<ArrayBuffer | null> {\n try {\n return await file.arrayBuffer();\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _decodeUtf8(bytes: ArrayBuffer): string | null {\n try {\n // `fatal: true` throws on any byte sequence that isn't valid UTF-8,\n // so encoding is validated against the raw bytes before decoding —\n // unlike `File.text()`, which silently substitutes U+FFFD.\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _rejectFile(file: File, messageKey: TranslationsKeys) {\n runInAction(() => {\n this.fileName = file.name;\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.currentStep = 'upload';\n });\n this.showToast?.({\n type: 'ERROR',\n message: this.translate(messageKey),\n });\n }\n\n private _showFileReadErrorToast(file: File) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.fileReadFailed'),\n action: {\n text: this.translate('cairo.import.tryAgain'),\n onClick: () => this.onFileSelected(file),\n removeToastOnClick: true,\n },\n });\n }\n\n private _showPartialSuccessToast() {\n this.showToast?.({\n type: 'WARNING',\n message: this.translate('cairo.import.partialSuccessToast', {\n failed: String(this.result.failed),\n imported: String(this.result.succeeded),\n }),\n action: {\n text: this.translate('cairo.import.downloadFailedRows'),\n onClick: () => this._downloadFailedRows(),\n removeToastOnClick: true,\n },\n });\n }\n\n /**\n * Builds a plain, re-importable CSV of the rows the server rejected — the\n * original headers plus just the failed rows — and hands it to `downloadCsv`.\n * The failed rows come from the job's movement logs (which row failed), mapped\n * back to the parsed `csvRows` we still hold in memory.\n */\n private async _downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let indices: number[];\n try {\n indices = await this._fetchFailedRowIndices(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const failedRows = indices\n .map((index) => this.csvRows[index])\n .filter((row): row is string[] => row != null);\n\n if (failedRows.length === 0) {\n return;\n }\n\n const content = unparseCsv(this.csvHeaders, failedRows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns the `csvRows` indices of\n // the rows that failed. data-hub's CSV decoder\n // (wix-data-hub: packages/wix-data-hub-executor-c/src/plugins/formats/csv/\n // csv-binary-decoder.ts) parses with the `csv-parse` library (`columns: true`)\n // and sets `sourceItemId = \"row ${++index + 1}\"`, incrementing once **per\n // record** — not per physical line. So N is the 1-based record number with\n // the header consumed as columns: the first data record is `\"row 2\"` →\n // `csvRows[0]`, i.e. `csvRows[N - 2]`. Because `csv-parse` is RFC-4180,\n // quoted cells containing embedded newlines are a single record, so they do\n // NOT shift the numbering. Out-of-range indices are guarded below.\n private async _fetchFailedRowIndices(jobId: string): Promise<number[]> {\n const indices: number[] = [];\n let cursor: string | undefined;\n\n do {\n const { logs, pagingMetadata } = await this.hubJobClient.listMovementLogs(\n jobId,\n cursor ? { cursor } : undefined,\n );\n\n for (const log of logs ?? []) {\n if (!log.failure || log.sourceItemId == null) {\n continue;\n }\n const fileLine = Number(/\\d+/.exec(log.sourceItemId)?.[0]);\n const index = fileLine - 2;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < this.csvRows.length\n ) {\n indices.push(index);\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return indices;\n }\n\n setMapping(header: string, fieldId: string | null) {\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: fieldId == null ? null : { kind: 'existing', fieldId },\n };\n }\n\n setNewFieldMapping(header: string) {\n const index = this.csvHeaders.indexOf(header);\n const fieldType =\n index >= 0 ? this._detectColumnType(this._columnValues(index)) : 'text';\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: { kind: 'new', fieldType },\n };\n }\n\n /**\n * Persists the result of the \"Edit field\" editor for a column's pending new\n * field: the (possibly overridden) type, an optional display-name override,\n * and the per-type configuration. No-op if the column isn't currently mapped\n * to a new field.\n */\n setNewFieldConfig(\n header: string,\n edit: {\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n },\n ) {\n const mapping = this.mappingByHeader[header];\n if (mapping?.kind !== 'new') {\n return;\n }\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: {\n kind: 'new',\n fieldType: edit.fieldType,\n ...(edit.displayName != null && { displayName: edit.displayName }),\n ...(edit.config && { config: edit.config }),\n },\n };\n }\n\n /**\n * Marks which column's pending new field the field editor is currently\n * editing, so a later `applyFieldEdit` (the editor's `onSubmit`) knows where to\n * write the result.\n */\n beginFieldEdit(header: string) {\n this._editingHeader = header;\n }\n\n /**\n * `onSubmit` handler for the field editor: maps the edited field spec into the\n * column being edited (set via `beginFieldEdit`). No-op if nothing is being\n * edited.\n */\n applyFieldEdit(field: FieldSpec) {\n if (this._editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this._editingHeader, toFieldEdit(field));\n }\n\n /**\n * Runs the server-side import: align the CSV to the resolved field keys,\n * upload it, submit a data-movement job, then poll until terminal. Throws on\n * a failed job so `startImport` surfaces the error state; partial success is\n * reported via `result.failed` and the partial toast.\n */\n private async _runImportJob(\n resolvedMapping: Record<string, string | null>,\n ): Promise<ImportResult> {\n const csv = rewriteParsedCsvForImport(\n this.csvHeaders,\n this.csvRows,\n resolvedMapping,\n );\n const file = new File([csv], this.fileName || 'import.csv', {\n type: 'text/csv',\n });\n\n const fileId = await this.hubJobClient.uploadFile(file);\n if (this._cancelled) {\n return this.result;\n }\n\n const jobId = await this.hubJobClient.submitImportJob({\n fileId,\n name: this.fileName,\n destination: this._destination(),\n });\n runInAction(() => {\n this._jobId = jobId;\n });\n if (this._cancelled) {\n // The user cancelled while `submitImportJob` was in flight, so `close()`\n // saw no `_jobId` and couldn't terminate it. Terminate it here, otherwise\n // the job keeps importing server-side after cancel (and would overwrite a\n // restored backup).\n await this.hubJobClient.terminateJob(jobId).catch(() => undefined);\n return this.result;\n }\n\n const job = await pollImportJob(\n (id) => this.hubJobClient.getJob(id),\n jobId,\n {\n isCancelled: () => this._cancelled,\n onProgress: (polled) => this._applyJobProgress(polled),\n },\n );\n\n // `null` means cancelled mid-poll — leave whatever progress we have.\n if (!job) {\n return this.result;\n }\n\n if (job.status === JobStatus.FAILED) {\n // The job ran server-side, so a failure arrives on a 200 (the poll\n // succeeded; the job didn't) with no HTTP error to carry the application\n // error. Build a synthetic, HTTP-error-shaped error (the error handler\n // reads the code from `response.data.details.applicationError`) and hand\n // the throwing operation to the consumer's `onJobError` so THEY wrap it\n // with their own `withErrorHandler` + error-code map — `job.error` is the\n // consumer's application error (their import business logic), so only they\n // can map its codes, and the map stays coupled to the `withErrorHandler`\n // call as everywhere else (e.g. `fetchData`). The map is attached to the\n // error object, which the progress step resolves via `getResolvedError`.\n // Without a handler the same error still throws, falling back to the\n // generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n const run = (): Promise<unknown> => Promise.reject(error);\n\n if (this.onJobError) {\n // The consumer wraps `run` with `withErrorHandler`; it re-rejects with\n // `error` (now carrying their map), which propagates from here.\n await this.onJobError(run);\n }\n throw error;\n }\n\n this._applyJobProgress(job);\n return this.result;\n }\n\n // Destination the job writes into. A platformized consumer supplies its own\n // variant (e.g. `{ storesCatalogProducts: {} }`), which is sent verbatim.\n // Otherwise this is the consumer's Wix Data collection, built from\n // `collectionId`; `writePolicy` is sent only when a CSV column is mapped to\n // `_id` (the only case collisions can occur), otherwise it's omitted and the\n // server applies its default (upsert by `_id`).\n private _destination(): Destination {\n if (this.destination) {\n return this.destination;\n }\n return {\n wixDataCollection: {\n collectionId: this.collectionId,\n ...(this.idMappedHeader != null && { writePolicy: this.writePolicy }),\n },\n };\n }\n\n private _applyJobProgress(job: DataMovementJob) {\n const progress = job.progress;\n const succeeded = progress?.itemsSuccessful ?? 0;\n const failed = progress?.itemsRejected ?? 0;\n const current = progress?.current ?? succeeded + failed;\n\n // `totalCount` is fixed up front in `startImport` from the CSV row count\n // (one uploaded row per CSV row); polling only advances `processedCount`.\n runInAction(() => {\n this.processedCount = Math.min(current, this.totalCount);\n this.result = { succeeded, failed };\n });\n }\n\n private async _runBackup(): Promise<boolean> {\n const backup = this.backup;\n if (!backup) {\n return false;\n }\n\n try {\n const result = await backup(this._abortController!.signal);\n if (this._cancelled) {\n return true;\n }\n if (result?.restore) {\n this.restoreFn = result.restore;\n }\n } catch (error) {\n if (this._cancelled) {\n return true;\n }\n runInAction(() => {\n this.isBackingUp = false;\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return true;\n }\n\n runInAction(() => {\n this.isBackingUp = false;\n });\n return false;\n }\n\n private _lingerOnCompletion() {\n return new Promise<void>((resolve) =>\n setTimeout(resolve, COMPLETION_LINGER_MS),\n );\n }\n\n /**\n * Resolves every column to the final destination key used in the upload\n * payload: an existing field id, a new field's (Cairo-decided) key, or `null`\n * to skip. All new fields are added to the schema in a single `updateSchema`\n * call before the rows upload — mirroring the cm-import `beforeImport` flow.\n * `updateSchema` may throw — `startImport` surfaces that as the error state.\n */\n private async _resolveFieldMapping(): Promise<Record<string, string | null>> {\n const resolved: Record<string, string | null> = {};\n const newFields: NewFieldDefinition[] = [];\n // Seed with existing field ids/display names so derived keys and names never\n // collide with them or with each other.\n const usedKeys = new Set(\n this.fields.map((field) => field.id).filter((id): id is string => !!id),\n );\n const usedNames = new Set(\n this.fields\n .map((field) => field.header)\n .filter((header): header is string => !!header),\n );\n\n for (const header of this.csvHeaders) {\n const mapping = this.mappingByHeader[header];\n\n if (mapping == null) {\n resolved[header] = null;\n } else if (mapping.kind === 'existing') {\n resolved[header] = mapping.fieldId;\n } else if (this.updateSchema) {\n // The user's name override (from the field editor) seeds the unique\n // name/key derivation; otherwise fall back to the column header.\n const baseName = mapping.displayName?.trim() || header;\n const { displayName, key } = uniqueFieldNameAndKey(\n baseName,\n usedNames,\n usedKeys,\n );\n usedKeys.add(key);\n usedNames.add(displayName);\n newFields.push({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n });\n resolved[header] = key;\n } else {\n // \"new\" mapping without an `updateSchema` callback — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (newFields.length > 0 && this.updateSchema) {\n await this.updateSchema(newFields);\n }\n\n return resolved;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n this._cancelled = false;\n this._abortController = new AbortController();\n\n // One uploaded row per CSV row (the rewrite drops columns, not rows), so the\n // total is known up front from the parsed CSV and stays fixed through polling.\n const totalCount = this.csvRows.length;\n\n runInAction(() => {\n this.currentStep = 'progress';\n this.totalCount = totalCount;\n this.processedCount = 0;\n this.isBackingUp = !!this.backup;\n // Clear any error/result from a previous attempt so \"Try again\" starts\n // from a clean slate (e.g. after a backup failure).\n this.importStatus = { ...queryStatus.idle };\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this._jobId = null;\n });\n\n const backupFailed = await this._runBackup();\n if (backupFailed) {\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n // Create any new fields and resolve every column to its destination key\n // before uploading. A creation failure surfaces as the error state with a\n // \"Try again\" CTA, like an upload/job failure.\n let resolvedMapping: Record<string, string | null>;\n try {\n resolvedMapping = await this._resolveFieldMapping();\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return;\n }\n if (this._cancelled) {\n return;\n }\n\n const promise = this._runImportJob(resolvedMapping);\n\n this.importStatus = {\n ...queryStatus.loading,\n promise,\n };\n\n try {\n await promise;\n if (this._cancelled) {\n return;\n }\n\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.success,\n data: this.result,\n };\n });\n\n // On a clean import, hold the completed (100%) progress bar on screen\n // briefly so the completion is perceptible even for very few rows. Skip\n // the wait when there are failed rows — that path closes and surfaces a\n // toast instead.\n if (this.result.failed === 0) {\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n }\n\n runInAction(() => {\n // Rows the server rejected are reported via a toast (the downloadable\n // failed-rows report is added by the failed-rows-report task).\n if (this.result.failed > 0) {\n this._showPartialSuccessToast();\n }\n\n this.importModalState.close();\n this.collection.clearResultAndMoveToStart({ force: true });\n });\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAOA,IAAAC,MAAA,GAAAD,OAAA;AASA,IAAAE,sBAAA,GAAAF,OAAA;AAEA,IAAAG,MAAA,GAAAH,OAAA;AAKyDI,OAAA,CAAAC,WAAA,GAAAF,MAAA,CAAAE,WAAA;AACzD,IAAAC,SAAA,GAAAN,OAAA;AACA,IAAAO,WAAA,GAAAP,OAAA;AACA,IAAAQ,aAAA,GAAAR,OAAA;AACA,IAAAS,gBAAA,GAAAT,OAAA;AACA,IAAAU,gBAAA,GAAAV,OAAA;AAOA,IAAAW,UAAA,GAAAX,OAAA;AAMA;;AA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CAAC/B,MAAM,KAAK,CAAC,EAAE;QAC5B,MAAM,IAAI,CAACiN,mBAAmB,CAAC,CAAC;QAChC,IAAI,IAAI,CAAC1J,UAAU,EAAE;UACnB;QACF;MACF;MAEA,IAAAoC,iBAAW,EAAC,MAAM;QAChB;QACA;QACA,IAAI,IAAI,CAAC5D,MAAM,CAAC/B,MAAM,GAAG,CAAC,EAAE;UAC1B,IAAI,CAACyI,wBAAwB,CAAC,CAAC;QACjC;QAEA,IAAI,CAAClI,gBAAgB,CAAC2C,KAAK,CAAC,CAAC;QAC7B,IAAI,CAAC5C,UAAU,CAACgF,yBAAyB,CAAC;UAAEC,KAAK,EAAE;QAAK,CAAC,CAAC;MAC5D,CAAC,CAAC;IACJ,CAAC,CAAC,OAAOJ,KAAK,EAAE;MACd,IAAAQ,iBAAW,EAAC,MAAM;QAChB,IAAI,CAACrE,YAAY,GAAG;UAClB,GAAG1B,kBAAW,CAACuF,KAAK;UACpBA;QACF,CAAC;MACH,CAAC,CAAC;IACJ;EACF;AACF;AAAChI,OAAA,CAAAmC,WAAA,GAAAA,WAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_mobx","require","_model","_ConditionalModalState","_types","exports","WritePolicy","_parseCsv","_rewriteCsv","_hubJobClient","_importJobPoller","_detectFieldType","_fieldEdit","COMPLETION_LINGER_MS","ID_FIELD_KEY","normalize","value","trim","toLowerCase","toFieldKey","header","words","split","filter","Boolean","length","map","word","index","charAt","slice","toUpperCase","join","uniqueFieldNameAndKey","usedNames","usedKeys","displayName","suffix","key","has","ImportState","constructor","props","_defineProperty2","default","ConditionalModalState","queryStatus","idle","OVERWRITE","succeeded","failed","config","collection","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","idMappedHeader","setWritePolicy","action","bound","onUploadContinue","goToUpload","setMapping","setNewFieldMapping","setNewFieldConfig","beginFieldEdit","applyFieldEdit","close","onFileSelected","startImport","reset","fields","collectionId","destination","backup","updateSchema","onJobError","idFieldKey","init","_cancelled","Object","values","some","mappedIndices","reduce","indices","push","row","Set","m","kind","fieldId","entry","entries","find","mapping","policy","canCreateNewField","canAddFields","canConfigureWritePolicy","_this$_abortControlle","_abortController","abort","_pendingFieldsMap","undefined","restoreFn","_jobId","isSuccess","_this$_abortControlle2","terminateJob","error","console","_restoreBackup","clearResultAndMoveToStart","force","restoreController","AbortController","signal","runInAction","discardAndGoBack","discardChangesModal","open","modal","promise","discardAndClose","getDefaultMapping","headers","field","id","forEach","normalizedHeader","matched","fieldType","_columnValues","columnIndex","TYPE_SAMPLE_SIZE","_orderHeadersWithIdFirst","idHeader","applyParsedCsv","parsedCsv","rows","file","bytes","_readFileBytes","_showFileReadErrorToast","content","_decodeUtf8","_rejectFile","parseCsv","name","arrayBuffer","e","TextDecoder","fatal","decode","messageKey","_this$showToast","call","type","message","_this$showToast2","text","onClick","removeToastOnClick","_showPartialSuccessToast","_this$showToast3","String","imported","_downloadFailedRows","_this$downloadCsv","jobId","_fetchFailedRowIndices","failedRows","unparseCsv","cursor","_pagingMetadata$curso","logs","pagingMetadata","listMovementLogs","log","_exec","failure","sourceItemId","fileLine","Number","exec","isInteger","hasNext","cursors","next","indexOf","edit","_editingHeader","toFieldEdit","_runImportJob","resolvedMapping","csv","rewriteParsedCsvForImport","File","fileId","uploadFile","submitImportJob","_destination","catch","job","pollImportJob","getJob","isCancelled","onProgress","polled","_applyJobProgress","status","JobStatus","FAILED","_job$error","assign","Error","code","response","data","details","applicationError","run","Promise","reject","wixDataCollection","progress","itemsSuccessful","itemsRejected","current","Math","min","_runBackup","restore","_lingerOnCompletion","resolve","setTimeout","_resolveFieldMapping","resolved","newFields","_mapping$displayName","baseName","add","updated","keys","backupFailed","loading","createdFields","success","_this$config$mergeFie","_this$config","mergeFields"],"sources":["../../../../src/state/ImportState/ImportState.ts"],"sourcesContent":["import {\n action,\n computed,\n makeObservable,\n observable,\n runInAction,\n} from 'mobx';\nimport {\n queryStatus,\n ShowToast,\n TaskStatus,\n PatternsErrorHandler,\n} from '../../model';\nimport type { HttpClient } from '../../model/httpClient';\nimport { Translate, TranslationsKeys } from '../../services';\nimport { ModalState } from '../ModalState';\nimport { ConditionalModalState } from '../ConditionalModalState';\nimport { CreateExportAsyncJobRequest } from '@wix/bex-utils/@wix/ambassador-fedinfra-exportservice-v1-export-async-job/types';\nimport {\n JobStatus,\n WritePolicy,\n type Destination,\n type DataMovementJob,\n} from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\nimport { ParseCsvResult, parseCsv, unparseCsv } from './parseCsv';\nimport { rewriteParsedCsvForImport } from './rewriteCsv';\nimport { createHubJobClient, HubJobClient } from './hubJobClient';\nimport { pollImportJob } from './importJobPoller';\nimport {\n detectColumnType,\n TYPE_SAMPLE_SIZE,\n type DetectColumnType,\n type NewFieldType,\n} from './detectFieldType';\nimport type { FieldSpec, NonReferenceField } from '../../types/Field';\nimport type { Schema } from '../../types/Schema';\nimport { toFieldEdit } from './fieldEdit';\n\nexport interface ImportCollection {\n clearResultAndMoveToStart(params?: { force?: boolean }): void;\n}\n\n/** Outcome of a server-side import job, derived from the job's progress. */\nexport interface ImportResult {\n succeeded: number;\n failed: number;\n}\n\nexport interface BackupResult {\n /**\n * Reverts the collection to its pre-import state. Called only when the user\n * cancels mid-import (matching the previous client-side behavior); a job\n * failure leaves partial rows in place and offers \"Try again\".\n *\n * Must fully revert to the snapshot taken before the import — including rows\n * the import overwrote in place. The default `writePolicy` is upsert (OVERWRITE\n * by `_id`), so it is NOT enough to delete newly-inserted ids; previously\n * existing rows may have been overwritten and must be restored to their prior\n * values.\n */\n restore(signal: AbortSignal): Promise<void>;\n}\n\n/**\n * Optional snapshot taken before the import runs, returning a `restore` used to\n * undo the import on cancel. See {@link BackupResult.restore} for the revert\n * contract under upsert.\n */\nexport type BackupFn = (signal: AbortSignal) => Promise<BackupResult | void>;\n\nexport type DownloadCsvFn = (content: string, fileName: string) => void;\n\n/**\n * Consumer hook for resolving a failed import job's message. An import runs\n * server-side, so a failure arrives on a 200 (the poll succeeds; the job\n * doesn't) with no HTTP error to carry the application error. Cairo hands the\n * consumer `run` — an operation that rejects with a synthetic, HTTP-error-shaped\n * error carrying the job's application error — and the consumer wraps it with\n * their own `withErrorHandler` + error-code map (their codes, their\n * translations), keeping the map coupled to the `withErrorHandler` call as\n * everywhere else (e.g. `fetchData`). The map is keyed by application-error code\n * (the v2 errorHandler shape, like `getExportAsyncJobErrors`):\n *\n * onJobError: (run) =>\n * errorHandler.withErrorHandler(run, {\n * [jobErrorCode]: (error) => ({ message: translate(...) }),\n * })\n *\n * `withErrorHandler` attaches the map to the error object and re-rejects it, so\n * the progress step resolves a consumer-specific message via `getResolvedError`.\n * When omitted, the error still surfaces but resolves to the generic message.\n */\nexport type OnImportJobError = (\n run: () => Promise<unknown>,\n) => Promise<unknown>;\n\nexport type ImportField = NonNullable<\n CreateExportAsyncJobRequest['fields']\n>[number];\n\n// `NewFieldType`, `detectColumnType`, etc. are re-exported from the package via\n// the `ImportState` barrel (`./index`), which also exports `./detectFieldType`.\n\n// Re-export the write-policy enum so consumers (and the cairo UI) reference it\n// from `@wix/bex-core` rather than the bundled ambassador path.\nexport { WritePolicy } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n// Re-export the destination type for platformized consumers that supply their\n// own variant (e.g. `{ storesCatalogProducts: {} }`) — same reason as above.\nexport type { Destination } from '@wix/bex-utils/@wix/ambassador-hub-v1-job/types';\n\n// Per-type configuration for a new field, captured from the \"Edit field\" editor\n// (CAIRO-4398). All optional — an unedited field carries none and is created\n// from detected defaults only. `displayName` is intentionally not here: the\n// (possibly user-overridden) name is deduped and surfaced as\n// `NewFieldDefinition.displayName`.\nexport interface NewFieldConfig {\n validation?: NonReferenceField['validation'];\n isPii?: boolean;\n helpText?: string;\n}\n\n// A new field to add to the collection schema during import. `key` is decided by\n// Cairo (derived from the column header — or the user's name override — deduped)\n// and is also the key the column's values are written under, so the consumer\n// must add the field under exactly this key. `config` carries any per-type\n// configuration the field editor produced; create the field with it.\nexport interface NewFieldDefinition {\n key: string;\n type: NewFieldType;\n displayName: string;\n config?: NewFieldConfig;\n}\n\n/**\n * Consumer-supplied callback that adds the given new fields to the collection\n * schema in a single call, before the rows are uploaded. Mirrors the cm-import\n * `beforeImport`/`updateSchema` flow: Cairo decides the fields (and their keys),\n * the consumer performs one schema mutation (e.g. `updateSchema(collectionId,\n * ...addField(key, config))`). Its presence is also the opt-in for the \"create\n * new field\" default — see `getDefaultMapping`.\n *\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 * 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/**\n * The import inputs a consumer supplies. Satisfied both by a plain object (the\n * manual case) and by a live schema reference (`useSchemaImport` in\n * `@wix/patterns`) whose members are getters read on demand — so the async\n * schema load needn't resolve before `ImportState` is built. `ImportState` holds\n * it by reference (never spreads it) so those getters stay live.\n */\nexport interface ImportButtonConfig {\n /** Existing collection fields, for column auto-mapping. */\n fields: ImportField[];\n /** Wix Data collection the import writes into (the common CMS case). */\n collectionId?: string;\n /**\n * Platformized (non–Wix-Data) destination, sent to the job verbatim (e.g.\n * `{ storesCatalogProducts: {} }`). When provided, `collectionId`/`writePolicy`\n * are ignored.\n */\n destination?: Destination;\n backup?: BackupFn;\n /** Creates new fields before upload; resolves with the updated fields map. */\n updateSchema?: UpdateSchemaFn;\n /**\n * Merges `updateSchema`'s returned fields map into the table after a successful\n * import, so the new columns appear with no reload (CAIRO-4400). A schema-backed\n * config (see `useSchemaImport` in `@wix/patterns`) wires this to its live\n * schema; when omitted, the new columns wait for the next schema load.\n */\n mergeFields?: (fields: Schema['fields']) => void;\n /** See {@link OnImportJobError}. */\n onJobError?: OnImportJobError;\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 * Whether the user may create new fields. When set, it gates create-new-field\n * directly (e.g. a schema's `createField` permission); when unset, the presence\n * of `updateSchema` is the opt-in.\n */\n canAddFields?: boolean;\n}\n\nexport interface ImportStateProps {\n /** The import inputs (existing fields, destination, create-new-field, backup). */\n config: ImportButtonConfig;\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';\n\n// How long to keep the completed progress bar (100%) on screen before closing\n// the modal on a clean import. Without it, an import of very few rows finishes\n// near-instantly and the modal appears to vanish without ever showing the bar\n// reaching completion.\nconst COMPLETION_LINGER_MS = 600;\n\n// The Wix Data collection's id field key. A CSV column mapped to this field lets\n// the user choose how rows that collide on `_id` are written (writePolicy).\nconst ID_FIELD_KEY = '_id';\n\nfunction normalize(value: string) {\n return value.trim().toLowerCase();\n}\n\n// camelCase key for a field created from a column header\n// (e.g. \"Product Name\" -> \"productName\").\nfunction toFieldKey(header: string): string {\n const words = header\n .trim()\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean);\n if (words.length === 0) {\n return 'field';\n }\n return words\n .map((word, index) =>\n index === 0\n ? word.charAt(0).toLowerCase() + word.slice(1)\n : word.charAt(0).toUpperCase() + word.slice(1),\n )\n .join('');\n}\n\n// A display name + key for a field created from a column header, unique against\n// both `usedNames` (existing field display names + names already assigned to\n// earlier new columns) and `usedKeys` (existing field ids + keys already\n// assigned). Mirrors cm-import `generateFieldNameAndKey`: when the name or its\n// derived key collides, suffix the *display name* as `\"<header>-<n>\"` and\n// re-derive the key from it — so the created field's name and key are both\n// unique (otherwise two columns with the same header would create fields showing\n// the same name).\nfunction uniqueFieldNameAndKey(\n header: string,\n usedNames: Set<string>,\n usedKeys: Set<string>,\n): { displayName: string; key: string } {\n let displayName = header;\n for (let suffix = 1; ; suffix++) {\n const key = toFieldKey(displayName);\n if (!usedNames.has(displayName) && !usedKeys.has(key)) {\n return { displayName, key };\n }\n displayName = `${header}-${suffix}`;\n }\n}\n\nexport class ImportState {\n // 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: ImportButtonConfig;\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 };\n isBackingUp = false;\n isRestoring = false;\n private restoreFn: ((signal: AbortSignal) => Promise<void>) | null = null;\n private _cancelled = false;\n private _abortController: AbortController | null = null;\n // Id of the running data-movement job, set once submitted — used to cancel it\n // (`terminateJob`) if the user closes mid-import.\n private _jobId: string | null = null;\n // The column whose pending new field the field editor is currently editing.\n // Not observable — transient wiring between `beginFieldEdit` and the editor's\n // `applyFieldEdit` callback, never rendered.\n private _editingHeader: string | null = null;\n // 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.config = props.config;\n this.collection = props.collection;\n this.importModalState = props.importModalState;\n this.translate = props.translate;\n this.errorHandler = props.errorHandler;\n this.showToast = props.showToast;\n this.downloadCsv = props.downloadCsv;\n this._detectColumnType = props.detectColumnType ?? detectColumnType;\n this.hubJobClient = createHubJobClient({\n httpClient: props.httpClient,\n errorHandler: props.errorHandler,\n });\n\n makeObservable(this, {\n currentStep: observable.ref,\n importStatus: observable.ref,\n fileName: observable.ref,\n csvHeaders: observable.ref,\n csvRows: observable.ref,\n orderedHeaders: observable.ref,\n mappingByHeader: observable.ref,\n writePolicy: observable.ref,\n processedCount: observable.ref,\n totalCount: observable.ref,\n result: observable.ref,\n isBackingUp: observable.ref,\n isRestoring: observable.ref,\n hasParsedRows: computed,\n hasMappings: computed,\n hasNoMappedData: computed,\n selectedFieldIds: computed,\n idMappedHeader: computed,\n setWritePolicy: action.bound,\n onUploadContinue: action.bound,\n goToUpload: action.bound,\n setMapping: action.bound,\n setNewFieldMapping: action.bound,\n setNewFieldConfig: action.bound,\n beginFieldEdit: action.bound,\n applyFieldEdit: action.bound,\n close: action.bound,\n onFileSelected: action.bound,\n startImport: action.bound,\n reset: action.bound,\n });\n }\n\n // 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 return this.config.collectionId;\n }\n\n get destination(): Destination | undefined {\n return this.config.destination;\n }\n\n get backup(): BackupFn | undefined {\n return this.config.backup;\n }\n\n get updateSchema(): UpdateSchemaFn | undefined {\n return this.config.updateSchema;\n }\n\n get onJobError(): OnImportJobError | undefined {\n return this.config.onJobError;\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 * 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 * When the config sets `canAddFields` (e.g. a schema's create-field permission)\n * that gates it; otherwise the presence of `updateSchema` is the opt-in (see\n * `getDefaultMapping`).\n */\n get canCreateNewField(): boolean {\n return this.config.canAddFields ?? this.config.updateSchema != null;\n }\n\n /**\n * Whether the write-policy (id-collision) choice is meaningful for this import.\n * `writePolicy` is a `wixDataCollection`-only concept, and `_destination` only\n * attaches it when Cairo builds that destination itself. A consumer-supplied\n * (platformized) `destination` is sent verbatim with no place to carry it, so\n * the choice would be a no-op — the UI hides the control in that case. Fixed at\n * construction (depends only on the `destination` prop), so it isn't an\n * observable.\n */\n get canConfigureWritePolicy(): boolean {\n return this.destination == null;\n }\n\n reset() {\n this._abortController?.abort();\n this._abortController = null;\n this.currentStep = 'upload';\n this.importStatus = {\n ...queryStatus.idle,\n };\n this.fileName = '';\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.writePolicy = WritePolicy.OVERWRITE;\n this.processedCount = 0;\n this.totalCount = 0;\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this._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 the\n // success path `startImport` lingers ~600ms on the completed bar with the\n // step still 'progress'; closing during that window must NOT restore (it\n // would undo a clean import). A successful close just closes the modal and\n // lets the success path do its collection refresh.\n if (this.currentStep === 'progress' && !this.importStatus.isSuccess) {\n this._cancelled = true;\n this._abortController?.abort();\n\n // Stop the server-side job. It does not roll back rows already written —\n // that's what the backup restore below is for.\n if (this._jobId) {\n try {\n await this.hubJobClient.terminateJob(this._jobId);\n } catch (error) {\n console.error('Terminate import job failed', error);\n }\n }\n\n if (!this.isBackingUp) {\n await this._restoreBackup();\n }\n\n this.collection.clearResultAndMoveToStart({\n force: true,\n });\n }\n\n this.importModalState.close();\n }\n\n private async _restoreBackup() {\n const restoreFn = this.restoreFn;\n if (!restoreFn) {\n return;\n }\n\n const restoreController = new AbortController();\n this._abortController = restoreController;\n\n this.isRestoring = true;\n try {\n await restoreFn(restoreController.signal);\n } catch (error) {\n console.error('Restore failed', error);\n }\n runInAction(() => {\n this.isRestoring = false;\n this.restoreFn = null;\n });\n }\n\n goToUpload() {\n this.currentStep = 'upload';\n }\n\n async discardAndGoBack() {\n this.discardChangesModal.open('goBack');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.goToUpload();\n }\n }\n\n async discardAndClose() {\n this.discardChangesModal.open('close');\n const { result } = await this.discardChangesModal.modal.promise();\n if (result === 'confirmed') {\n this.close();\n }\n }\n\n onUploadContinue() {\n if (this.hasParsedRows) {\n this.currentStep = 'configuration';\n }\n }\n\n private getDefaultMapping(headers: string[]) {\n const mapping: Record<string, ColumnMapping> = {};\n const fields = this.fields.map((field) => ({\n id: field.id ?? '',\n header: field.header ?? '',\n }));\n\n headers.forEach((header, index) => {\n const normalizedHeader = normalize(header);\n const matched = fields.find(\n (field) =>\n normalize(field.id) === normalizedHeader ||\n normalize(field.header) === normalizedHeader,\n );\n\n if (matched?.id) {\n mapping[header] = { kind: 'existing', fieldId: matched.id };\n } else {\n // Unmatched columns default to creating a new field (type inferred from\n // the column's data) when the consumer supplied `updateSchema`;\n // otherwise they default to skip.\n mapping[header] = this.canCreateNewField\n ? {\n kind: 'new',\n fieldType: this._detectColumnType(this._columnValues(index)),\n }\n : null;\n }\n });\n\n return mapping;\n }\n\n // The column's values, capped at the detection sample size — detection only\n // looks at the first `TYPE_SAMPLE_SIZE` values, so avoid copying the whole\n // column (a wide CSV would otherwise allocate rows × columns strings).\n private _columnValues(columnIndex: number): string[] {\n return this.csvRows\n .slice(0, TYPE_SAMPLE_SIZE)\n .map((row) => row[columnIndex] ?? '');\n }\n\n // Puts the `_id`-mapped column first (CAIRO-4418), preserving CSV order for the\n // rest. Returns a fresh array so the snapshot doesn't alias `csvHeaders`.\n private _orderHeadersWithIdFirst(headers: string[]): string[] {\n const idHeader = this.idMappedHeader;\n return idHeader != null\n ? [idHeader, ...headers.filter((header) => header !== idHeader)]\n : [...headers];\n }\n\n private applyParsedCsv(fileName: string, parsedCsv: ParseCsvResult) {\n this.fileName = fileName;\n this.csvHeaders = parsedCsv.headers;\n this.csvRows = parsedCsv.rows;\n this.mappingByHeader = this.getDefaultMapping(parsedCsv.headers);\n // Snapshot the row order for this file with the auto-mapped `_id` column\n // first. Reads `idMappedHeader`, so it must run after `mappingByHeader` is\n // set. Kept stable until the next file so mapping edits don't reorder rows.\n this.orderedHeaders = this._orderHeadersWithIdFirst(parsedCsv.headers);\n // A new file is a fresh import: start from the default policy so a prior\n // file's Skip choice doesn't silently carry over (only the new-file path\n // resets — remapping `_id` within the same file keeps the user's choice).\n this.writePolicy = WritePolicy.OVERWRITE;\n this.currentStep = 'configuration';\n }\n\n async onFileSelected(file: File | null) {\n if (file == null) {\n return;\n }\n\n const bytes = await this._readFileBytes(file);\n if (bytes == null) {\n this._showFileReadErrorToast(file);\n return;\n }\n\n const content = this._decodeUtf8(bytes);\n if (content == null) {\n this._rejectFile(file, 'cairo.import.encodingFailed');\n return;\n }\n\n const parsedCsv = parseCsv(content);\n if ('code' in parsedCsv) {\n this._rejectFile(file, 'cairo.import.processFailed');\n return;\n }\n\n runInAction(() => {\n this.applyParsedCsv(file.name, parsedCsv);\n });\n }\n\n private async _readFileBytes(file: File): Promise<ArrayBuffer | null> {\n try {\n return await file.arrayBuffer();\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _decodeUtf8(bytes: ArrayBuffer): string | null {\n try {\n // `fatal: true` throws on any byte sequence that isn't valid UTF-8,\n // so encoding is validated against the raw bytes before decoding —\n // unlike `File.text()`, which silently substitutes U+FFFD.\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (e) {\n console.error(e);\n return null;\n }\n }\n\n private _rejectFile(file: File, messageKey: TranslationsKeys) {\n runInAction(() => {\n this.fileName = file.name;\n this.csvHeaders = [];\n this.csvRows = [];\n this.orderedHeaders = [];\n this.mappingByHeader = {};\n this.currentStep = 'upload';\n });\n this.showToast?.({\n type: 'ERROR',\n message: this.translate(messageKey),\n });\n }\n\n private _showFileReadErrorToast(file: File) {\n this.showToast?.({\n type: 'ERROR',\n message: this.translate('cairo.import.fileReadFailed'),\n action: {\n text: this.translate('cairo.import.tryAgain'),\n onClick: () => this.onFileSelected(file),\n removeToastOnClick: true,\n },\n });\n }\n\n private _showPartialSuccessToast() {\n this.showToast?.({\n type: 'WARNING',\n message: this.translate('cairo.import.partialSuccessToast', {\n failed: String(this.result.failed),\n imported: String(this.result.succeeded),\n }),\n action: {\n text: this.translate('cairo.import.downloadFailedRows'),\n onClick: () => this._downloadFailedRows(),\n removeToastOnClick: true,\n },\n });\n }\n\n /**\n * Builds a plain, re-importable CSV of the rows the server rejected — the\n * original headers plus just the failed rows — and hands it to `downloadCsv`.\n * The failed rows come from the job's movement logs (which row failed), mapped\n * back to the parsed `csvRows` we still hold in memory.\n */\n private async _downloadFailedRows() {\n const jobId = this._jobId;\n if (!jobId) {\n return;\n }\n\n let indices: number[];\n try {\n indices = await this._fetchFailedRowIndices(jobId);\n } catch (error) {\n console.error('Fetching failed rows report failed', error);\n return;\n }\n\n const failedRows = indices\n .map((index) => this.csvRows[index])\n .filter((row): row is string[] => row != null);\n\n if (failedRows.length === 0) {\n return;\n }\n\n const content = unparseCsv(this.csvHeaders, failedRows);\n this.downloadCsv?.(content, `failed-${this.fileName || 'import.csv'}`);\n }\n\n // Pages through the job's movement logs and returns the `csvRows` indices of\n // the rows that failed. data-hub's CSV decoder\n // (wix-data-hub: packages/wix-data-hub-executor-c/src/plugins/formats/csv/\n // csv-binary-decoder.ts) parses with the `csv-parse` library (`columns: true`)\n // and sets `sourceItemId = \"row ${++index + 1}\"`, incrementing once **per\n // record** — not per physical line. So N is the 1-based record number with\n // the header consumed as columns: the first data record is `\"row 2\"` →\n // `csvRows[0]`, i.e. `csvRows[N - 2]`. Because `csv-parse` is RFC-4180,\n // quoted cells containing embedded newlines are a single record, so they do\n // NOT shift the numbering. Out-of-range indices are guarded below.\n private async _fetchFailedRowIndices(jobId: string): Promise<number[]> {\n const indices: number[] = [];\n let cursor: string | undefined;\n\n do {\n const { logs, pagingMetadata } = await this.hubJobClient.listMovementLogs(\n jobId,\n cursor ? { cursor } : undefined,\n );\n\n for (const log of logs ?? []) {\n if (!log.failure || log.sourceItemId == null) {\n continue;\n }\n const fileLine = Number(/\\d+/.exec(log.sourceItemId)?.[0]);\n const index = fileLine - 2;\n if (\n Number.isInteger(index) &&\n index >= 0 &&\n index < this.csvRows.length\n ) {\n indices.push(index);\n }\n }\n\n cursor =\n (pagingMetadata?.hasNext && pagingMetadata.cursors?.next) || undefined;\n } while (cursor);\n\n return indices;\n }\n\n setMapping(header: string, fieldId: string | null) {\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: fieldId == null ? null : { kind: 'existing', fieldId },\n };\n }\n\n setNewFieldMapping(header: string) {\n const index = this.csvHeaders.indexOf(header);\n const fieldType =\n index >= 0 ? this._detectColumnType(this._columnValues(index)) : 'text';\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: { kind: 'new', fieldType },\n };\n }\n\n /**\n * Persists the result of the \"Edit field\" editor for a column's pending new\n * field: the (possibly overridden) type, an optional display-name override,\n * and the per-type configuration. No-op if the column isn't currently mapped\n * to a new field.\n */\n setNewFieldConfig(\n header: string,\n edit: {\n fieldType: NewFieldType;\n displayName?: string;\n config?: NewFieldConfig;\n },\n ) {\n const mapping = this.mappingByHeader[header];\n if (mapping?.kind !== 'new') {\n return;\n }\n this.mappingByHeader = {\n ...this.mappingByHeader,\n [header]: {\n kind: 'new',\n fieldType: edit.fieldType,\n ...(edit.displayName != null && { displayName: edit.displayName }),\n ...(edit.config && { config: edit.config }),\n },\n };\n }\n\n /**\n * Marks which column's pending new field the field editor is currently\n * editing, so a later `applyFieldEdit` (the editor's `onSubmit`) knows where to\n * write the result.\n */\n beginFieldEdit(header: string) {\n this._editingHeader = header;\n }\n\n /**\n * `onSubmit` handler for the field editor: maps the edited field spec into the\n * column being edited (set via `beginFieldEdit`). No-op if nothing is being\n * edited.\n */\n applyFieldEdit(field: FieldSpec) {\n if (this._editingHeader == null) {\n return;\n }\n this.setNewFieldConfig(this._editingHeader, toFieldEdit(field));\n }\n\n /**\n * Runs the server-side import: align the CSV to the resolved field keys,\n * upload it, submit a data-movement job, then poll until terminal. Throws on\n * a failed job so `startImport` surfaces the error state; partial success is\n * reported via `result.failed` and the partial toast.\n */\n private async _runImportJob(\n resolvedMapping: Record<string, string | null>,\n ): Promise<ImportResult> {\n const csv = rewriteParsedCsvForImport(\n this.csvHeaders,\n this.csvRows,\n resolvedMapping,\n );\n const file = new File([csv], this.fileName || 'import.csv', {\n type: 'text/csv',\n });\n\n const fileId = await this.hubJobClient.uploadFile(file);\n if (this._cancelled) {\n return this.result;\n }\n\n const jobId = await this.hubJobClient.submitImportJob({\n fileId,\n name: this.fileName,\n destination: this._destination(),\n });\n runInAction(() => {\n this._jobId = jobId;\n });\n if (this._cancelled) {\n // The user cancelled while `submitImportJob` was in flight, so `close()`\n // saw no `_jobId` and couldn't terminate it. Terminate it here, otherwise\n // the job keeps importing server-side after cancel (and would overwrite a\n // restored backup).\n await this.hubJobClient.terminateJob(jobId).catch(() => undefined);\n return this.result;\n }\n\n const job = await pollImportJob(\n (id) => this.hubJobClient.getJob(id),\n jobId,\n {\n isCancelled: () => this._cancelled,\n onProgress: (polled) => this._applyJobProgress(polled),\n },\n );\n\n // `null` means cancelled mid-poll — leave whatever progress we have.\n if (!job) {\n return this.result;\n }\n\n if (job.status === JobStatus.FAILED) {\n // The job ran server-side, so a failure arrives on a 200 (the poll\n // succeeded; the job didn't) with no HTTP error to carry the application\n // error. Build a synthetic, HTTP-error-shaped error (the error handler\n // reads the code from `response.data.details.applicationError`) and hand\n // the throwing operation to the consumer's `onJobError` so THEY wrap it\n // with their own `withErrorHandler` + error-code map — `job.error` is the\n // consumer's application error (their import business logic), so only they\n // can map its codes, and the map stays coupled to the `withErrorHandler`\n // call as everywhere else (e.g. `fetchData`). The map is attached to the\n // error object, which the progress step resolves via `getResolvedError`.\n // Without a handler the same error still throws, falling back to the\n // generic message.\n const error = Object.assign(\n new Error(`ImportJob.${job.error?.code ?? 'failed'}`),\n { response: { data: { details: { applicationError: job.error } } } },\n );\n const run = (): Promise<unknown> => Promise.reject(error);\n\n if (this.onJobError) {\n // The consumer wraps `run` with `withErrorHandler`; it re-rejects with\n // `error` (now carrying their map), which propagates from here.\n await this.onJobError(run);\n }\n throw error;\n }\n\n this._applyJobProgress(job);\n return this.result;\n }\n\n // Destination the job writes into. A platformized consumer supplies its own\n // variant (e.g. `{ storesCatalogProducts: {} }`), which is sent verbatim.\n // Otherwise this is the consumer's Wix Data collection, built from\n // `collectionId`; `writePolicy` is sent only when a CSV column is mapped to\n // `_id` (the only case collisions can occur), otherwise it's omitted and the\n // server applies its default (upsert by `_id`).\n private _destination(): Destination {\n if (this.destination) {\n return this.destination;\n }\n return {\n wixDataCollection: {\n collectionId: this.collectionId,\n ...(this.idMappedHeader != null && { writePolicy: this.writePolicy }),\n },\n };\n }\n\n private _applyJobProgress(job: DataMovementJob) {\n const progress = job.progress;\n const succeeded = progress?.itemsSuccessful ?? 0;\n const failed = progress?.itemsRejected ?? 0;\n const current = progress?.current ?? succeeded + failed;\n\n // `totalCount` is fixed up front in `startImport` from the CSV row count\n // (one uploaded row per CSV row); polling only advances `processedCount`.\n runInAction(() => {\n this.processedCount = Math.min(current, this.totalCount);\n this.result = { succeeded, failed };\n });\n }\n\n private async _runBackup(): Promise<boolean> {\n const backup = this.backup;\n if (!backup) {\n return false;\n }\n\n try {\n const result = await backup(this._abortController!.signal);\n if (this._cancelled) {\n return true;\n }\n if (result?.restore) {\n this.restoreFn = result.restore;\n }\n } catch (error) {\n if (this._cancelled) {\n return true;\n }\n runInAction(() => {\n this.isBackingUp = false;\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n return true;\n }\n\n runInAction(() => {\n this.isBackingUp = false;\n });\n return false;\n }\n\n private _lingerOnCompletion() {\n return new Promise<void>((resolve) =>\n setTimeout(resolve, COMPLETION_LINGER_MS),\n );\n }\n\n /**\n * Resolves every column to the final destination key used in the upload\n * payload: an existing field id, a new field's (Cairo-decided) key, or `null`\n * to skip. All new fields are added to the schema in a single `updateSchema`\n * call before the rows upload — mirroring the cm-import `beforeImport` flow.\n * `updateSchema` may throw — `startImport` surfaces that as the error state.\n */\n private async _resolveFieldMapping(): Promise<Record<string, string | null>> {\n const resolved: Record<string, string | null> = {};\n const newFields: NewFieldDefinition[] = [];\n // Seed with existing field ids/display names so derived keys and names never\n // collide with them or with each other.\n const usedKeys = new Set(\n this.fields.map((field) => field.id).filter((id): id is string => !!id),\n );\n const usedNames = new Set(\n this.fields\n .map((field) => field.header)\n .filter((header): header is string => !!header),\n );\n\n for (const header of this.csvHeaders) {\n const mapping = this.mappingByHeader[header];\n\n if (mapping == null) {\n resolved[header] = null;\n } else if (mapping.kind === 'existing') {\n resolved[header] = mapping.fieldId;\n } else if (this.updateSchema) {\n // The user's name override (from the field editor) seeds the unique\n // name/key derivation; otherwise fall back to the column header.\n const baseName = mapping.displayName?.trim() || header;\n const { displayName, key } = uniqueFieldNameAndKey(\n baseName,\n usedNames,\n usedKeys,\n );\n usedKeys.add(key);\n usedNames.add(displayName);\n newFields.push({\n key,\n type: mapping.fieldType,\n displayName,\n ...(mapping.config && { config: mapping.config }),\n });\n resolved[header] = key;\n } else {\n // \"new\" mapping without an `updateSchema` callback — nothing to map into.\n resolved[header] = null;\n }\n }\n\n if (newFields.length > 0 && this.updateSchema) {\n // 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. Guard the\n // empty map: SchemaState.mergeFields is a full replace, so merging `{}` would\n // wipe every column — treat a missing/empty return as \"nothing to merge\".\n const updated = await this.updateSchema(newFields);\n this._pendingFieldsMap =\n updated && Object.keys(updated).length > 0 ? updated : undefined;\n }\n\n return resolved;\n }\n\n async startImport() {\n if (!this.hasMappings) {\n return;\n }\n\n this._cancelled = false;\n this._abortController = new AbortController();\n\n // One uploaded row per CSV row (the rewrite drops columns, not rows), so the\n // total is known up front from the parsed CSV and stays fixed through polling.\n const totalCount = this.csvRows.length;\n\n runInAction(() => {\n this.currentStep = 'progress';\n this.totalCount = totalCount;\n this.processedCount = 0;\n this.isBackingUp = !!this.backup;\n // Clear any error/result from a previous attempt so \"Try again\" starts\n // from a clean slate (e.g. after a backup failure).\n this.importStatus = { ...queryStatus.idle };\n this.result = {\n succeeded: 0,\n failed: 0,\n };\n this._jobId = null;\n // 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 });\n\n // On a clean import, hold the completed (100%) progress bar on screen\n // briefly so the completion is perceptible even for very few rows. Skip\n // the wait when there are failed rows — that path closes and surfaces a\n // toast instead.\n if (this.result.failed === 0) {\n await this._lingerOnCompletion();\n if (this._cancelled) {\n return;\n }\n }\n\n // 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 // Rows the server rejected are reported via a toast (the downloadable\n // failed-rows report is added by the failed-rows-report task).\n if (this.result.failed > 0) {\n this._showPartialSuccessToast();\n }\n\n this.importModalState.close();\n this.collection.clearResultAndMoveToStart({ force: true });\n });\n } catch (error) {\n runInAction(() => {\n this.importStatus = {\n ...queryStatus.error,\n error,\n };\n });\n }\n\n // 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;AAQA,IAAAW,UAAA,GAAAX,OAAA;AAMA;;AAqBA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA;AACA;;AAEA;AACA;;AAEA;AACA;;AAGA;AACA;AACA;AACA;AACA;;AAOA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;;AA4DA;AACA;AACA;AACA;AACA,MAAMY,oBAAoB,GAAG,GAAG;;AAEhC;AACA;AACA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