-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-utils.js
More file actions
342 lines (313 loc) · 10.5 KB
/
Copy pathsync-utils.js
File metadata and controls
342 lines (313 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
(function(root, factory) {
const api = factory();
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
root.RentMapSyncUtils = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function() {
function mapPropertyToRecord(prop, userId) {
const scoreRaw = prop.score;
const scoreNum = scoreRaw == null || scoreRaw === '' ? null : Number(scoreRaw);
return {
id: prop.id,
user_id: userId,
title: prop.title || null,
address: prop.address || null,
price: prop.price ?? null,
area: prop.area ?? null,
room_type: prop.roomType || null,
decor: prop.decor || null,
layout: prop.layout || null,
pet: prop.pet || null,
parking: prop.parking || null,
notes: prop.notes || null,
source_text: prop.sourceText || null,
status: prop.status || 'new',
score: Number.isFinite(scoreNum) ? scoreNum : null,
tags_json: Array.isArray(prop.tags) ? prop.tags : [],
client_updated_at: prop.clientUpdatedAt || null,
starred: !!prop.starred,
lng: prop.lng ?? null,
lat: prop.lat ?? null,
commute_json: prop.commute || {},
};
}
function mapPropertyFromRecord(row) {
const scoreRaw = row.score;
const scoreNum = scoreRaw == null || scoreRaw === '' ? null : Number(scoreRaw);
return {
id: row.id,
title: row.title,
address: row.address,
price: row.price,
area: row.area,
roomType: row.room_type,
decor: row.decor,
layout: row.layout,
pet: row.pet,
parking: row.parking,
notes: row.notes,
sourceText: row.source_text || null,
status: row.status || 'new',
score: Number.isFinite(scoreNum) ? scoreNum : null,
tags: Array.isArray(row.tags_json) ? row.tags_json : [],
clientUpdatedAt: row.client_updated_at || null,
updatedAt: row.updated_at || null,
starred: !!row.starred,
lng: row.lng,
lat: row.lat,
commute: row.commute_json || {},
};
}
function mapDestinationToRecord(dest, userId) {
return {
id: dest.id,
user_id: userId,
name: dest.name || null,
address: dest.address || null,
lng: dest.lng ?? null,
lat: dest.lat ?? null,
mode: dest.mode || 'transit',
active_mode: dest.activeMode || dest.mode || 'transit',
reverse_dir: !!dest.reverseDir,
color: dest.color || '#0F766E',
client_updated_at: dest.clientUpdatedAt || null,
};
}
function mapDestinationFromRecord(row) {
return {
id: row.id,
name: row.name,
address: row.address,
lng: row.lng,
lat: row.lat,
mode: row.mode || 'transit',
activeMode: row.active_mode || row.mode || 'transit',
reverseDir: !!row.reverse_dir,
color: row.color || '#0F766E',
updatedAt: row.updated_at || null,
clientUpdatedAt: row.client_updated_at || null,
};
}
function shouldOfferCloudMigration(localProps, localDests, remoteProps, remoteDests) {
const hasLocalData = (localProps?.length || 0) > 0 || (localDests?.length || 0) > 0;
const hasRemoteData = (remoteProps?.length || 0) > 0 || (remoteDests?.length || 0) > 0;
return hasLocalData && !hasRemoteData;
}
function hasMeaningfulLocalData(localProps, localDests, defaultDests) {
if ((localProps?.length || 0) > 0) return true;
if ((localDests?.length || 0) === 0) return false;
if ((localDests?.length || 0) !== (defaultDests?.length || 0)) return true;
return localDests.some((dest, idx) => {
const baseline = defaultDests[idx] || {};
return dest.name !== baseline.name || dest.address !== baseline.address;
});
}
/** @param {'auto'|'paused'} policy */
function shouldAllowAutoCloudSync(policy) {
return policy !== 'paused';
}
/**
* Pure decision for hydrate conflict UI outcomes.
* @returns {{ applyRemote: boolean, uploadLocal: boolean, policy: 'auto'|'paused' }}
*/
function resolveHydrateDecision(input) {
const {
shouldMigrate,
migrateAccepted,
localHasMeaningfulData,
remoteHasData,
useRemote,
uploadLocalAccepted,
} = input;
if (shouldMigrate) {
if (migrateAccepted) {
return { applyRemote: false, uploadLocal: true, policy: 'auto' };
}
return { applyRemote: false, uploadLocal: false, policy: 'paused' };
}
if (localHasMeaningfulData && remoteHasData) {
if (useRemote) {
return { applyRemote: true, uploadLocal: false, policy: 'auto' };
}
if (uploadLocalAccepted) {
return { applyRemote: false, uploadLocal: true, policy: 'auto' };
}
return { applyRemote: false, uploadLocal: false, policy: 'paused' };
}
if (remoteHasData) {
return { applyRemote: true, uploadLocal: false, policy: 'auto' };
}
return { applyRemote: false, uploadLocal: false, policy: 'auto' };
}
function getRecordTimestamp(item) {
if (!item || typeof item !== 'object') return 0;
const raw = item.clientUpdatedAt || item.updatedAt || item.updated_at || item.client_updated_at || null;
if (!raw) return 0;
const t = Date.parse(raw);
return Number.isFinite(t) ? t : 0;
}
/**
* Merge local/remote arrays by id using timestamps (newer wins).
* @param {object} [options]
* @param {(item:any)=>any} [options.getId]
* @param {Iterable<string>} [options.deletedIds] local intentional deletes (tombstones)
* @returns {{ merged: any[], toUpload: any[], localOnly: any[], remoteOnly: any[], toDeleteRemote: any[] }}
*/
function mergeByUpdatedAt(localItems, remoteItems, options = {}) {
const idOf = typeof options.getId === 'function' ? options.getId : (x) => x?.id;
const deletedIds = new Set(options.deletedIds || []);
const map = new Map();
for (const remote of remoteItems || []) {
const id = idOf(remote);
if (id == null) continue;
map.set(id, { remote });
}
for (const local of localItems || []) {
const id = idOf(local);
if (id == null) continue;
const entry = map.get(id) || {};
entry.local = local;
map.set(id, entry);
}
const merged = [];
const toUpload = [];
const localOnly = [];
const remoteOnly = [];
const toDeleteRemote = [];
for (const [id, { local, remote }] of map) {
if (deletedIds.has(id)) {
// Local intentionally deleted — do not resurrect from cloud
if (remote) toDeleteRemote.push(remote);
continue;
}
if (local && remote) {
const lt = getRecordTimestamp(local);
const rt = getRecordTimestamp(remote);
if (lt >= rt) {
merged.push(local);
toUpload.push(local);
} else {
merged.push(remote);
}
} else if (local) {
merged.push(local);
toUpload.push(local);
localOnly.push(local);
} else if (remote) {
merged.push(remote);
remoteOnly.push(remote);
}
}
return { merged, toUpload, localOnly, remoteOnly, toDeleteRemote };
}
function rememberDeletedId(deletedIds, id) {
if (id == null) return Array.isArray(deletedIds) ? deletedIds.slice() : [];
const next = new Set(deletedIds || []);
next.add(id);
return [...next];
}
/** Alias: mark an id dirty for incremental upsert (same set semantics). */
function markDirtyId(dirtyIds, id) {
return rememberDeletedId(dirtyIds, id);
}
function forgetDeletedIds(deletedIds, ids) {
if (!deletedIds?.length) return [];
if (!ids?.length) return deletedIds.slice();
const drop = new Set(ids);
return deletedIds.filter((id) => !drop.has(id));
}
/**
* Diff old→next item lists into tombstone updates.
* @returns {{ deletedIds: string[] }}
*/
function diffTombstones(oldItems, nextItems, deletedIds) {
const nextIds = new Set((nextItems || []).map((x) => x?.id).filter((id) => id != null));
let nextDeleted = Array.isArray(deletedIds) ? deletedIds.slice() : [];
for (const item of oldItems || []) {
const id = item?.id;
if (id == null) continue;
if (!nextIds.has(id)) nextDeleted = rememberDeletedId(nextDeleted, id);
}
nextDeleted = forgetDeletedIds(nextDeleted, [...nextIds]);
return { deletedIds: nextDeleted };
}
/**
* Local side has sync-relevant intent (data or pending deletes).
*/
function hasLocalSyncIntent(input = {}) {
const {
props = [],
dests = [],
defaultDests = [],
deletedPropIds = [],
deletedDestIds = [],
} = input;
if ((deletedPropIds?.length || 0) > 0 || (deletedDestIds?.length || 0) > 0) return true;
return hasMeaningfulLocalData(props, dests, defaultDests);
}
/**
* Filter rows for incremental upsert (by dirty id set).
* Empty dirty set → upsert nothing (caller still may push deletes).
*/
function selectDirtyRows(rows, dirtyIds) {
if (!rows?.length) return [];
if (!dirtyIds || (Array.isArray(dirtyIds) ? dirtyIds.length === 0 : dirtyIds.size === 0)) {
return [];
}
const set = dirtyIds instanceof Set ? dirtyIds : new Set(dirtyIds);
return rows.filter((row) => set.has(row.id));
}
function mapTombstoneToRecord(entityType, entityId, userId) {
return {
user_id: userId,
entity_type: entityType,
entity_id: entityId,
};
}
function partitionTombstones(rows) {
const propIds = [];
const destIds = [];
for (const row of rows || []) {
if (row.entity_type === 'property' && row.entity_id != null) propIds.push(row.entity_id);
else if (row.entity_type === 'destination' && row.entity_id != null) destIds.push(row.entity_id);
}
return { propIds, destIds };
}
function mergeDeletedIdLists(...lists) {
const set = new Set();
for (const list of lists) {
for (const id of list || []) {
if (id != null) set.add(id);
}
}
return [...set];
}
function entityTypeForTable(table) {
if (table === 'properties') return 'property';
if (table === 'destinations') return 'destination';
return null;
}
return {
mapPropertyToRecord,
mapPropertyFromRecord,
mapDestinationToRecord,
mapDestinationFromRecord,
hasMeaningfulLocalData,
shouldOfferCloudMigration,
shouldAllowAutoCloudSync,
resolveHydrateDecision,
getRecordTimestamp,
mergeByUpdatedAt,
rememberDeletedId,
markDirtyId,
forgetDeletedIds,
diffTombstones,
hasLocalSyncIntent,
selectDirtyRows,
mapTombstoneToRecord,
partitionTombstones,
mergeDeletedIdLists,
entityTypeForTable,
};
});