@superbright/indexeddb-orm 1.0.30 → 1.0.32
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/adapters/zustand-store.cjs +1 -1
- package/dist/adapters/zustand-store.cjs.map +1 -1
- package/dist/adapters/zustand-store.d.ts +2 -6
- package/dist/adapters/zustand-store.mjs +212 -167
- package/dist/adapters/zustand-store.mjs.map +1 -1
- package/dist/base/enums.cjs +1 -1
- package/dist/base/enums.cjs.map +1 -1
- package/dist/base/enums.d.ts +4 -0
- package/dist/base/enums.mjs +2 -1
- package/dist/base/enums.mjs.map +1 -1
- package/dist/base/userinquiry.d.ts +23 -0
- package/dist/base/visitor.d.ts +17 -0
- package/dist/base/visitorfilter.d.ts +25 -0
- package/dist/base/visitorquestionnaire.d.ts +25 -0
- package/dist/base/visitorunitengagement.d.ts +24 -0
- package/dist/features/units/transformers.cjs.map +1 -1
- package/dist/features/units/transformers.d.ts +2 -0
- package/dist/features/units/transformers.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -5
- package/dist/index.mjs +111 -127
- package/dist/index.mjs.map +1 -1
- package/dist/schema.cjs +1 -1
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.ts +13 -41
- package/dist/schema.mjs +63 -74
- package/dist/schema.mjs.map +1 -1
- package/dist/stores/store.cjs +1 -1
- package/dist/stores/store.cjs.map +1 -1
- package/dist/stores/store.d.ts +5 -73
- package/dist/stores/store.mjs +53 -254
- package/dist/stores/store.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/api/favorites.cjs +0 -2
- package/dist/api/favorites.cjs.map +0 -1
- package/dist/api/favorites.d.ts +0 -4
- package/dist/api/favorites.mjs +0 -34
- package/dist/api/favorites.mjs.map +0 -1
- package/dist/api/properties.cjs +0 -2
- package/dist/api/properties.cjs.map +0 -1
- package/dist/api/properties.d.ts +0 -22
- package/dist/api/properties.mjs +0 -197
- package/dist/api/properties.mjs.map +0 -1
- package/dist/api/users.cjs +0 -2
- package/dist/api/users.cjs.map +0 -1
- package/dist/api/users.d.ts +0 -5
- package/dist/api/users.mjs +0 -54
- package/dist/api/users.mjs.map +0 -1
- package/dist/units/favorites.cjs +0 -2
- package/dist/units/favorites.cjs.map +0 -1
- package/dist/units/favorites.d.ts +0 -7
- package/dist/units/favorites.mjs +0 -19
- package/dist/units/favorites.mjs.map +0 -1
package/dist/stores/store.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { kvGet as
|
|
2
|
-
import { UnifiedStoreDataSchema as
|
|
3
|
-
import { validate as
|
|
4
|
-
import { transformFiltersToUnitsSearchParams as
|
|
1
|
+
import { kvGet as l, kvSet as y } from "../storage.mjs";
|
|
2
|
+
import { UnifiedStoreDataSchema as d, UserPropertyStateSchema as P, UnitSchema as h } from "../schema.mjs";
|
|
3
|
+
import { validate as m } from "../validation.mjs";
|
|
4
|
+
import { transformFiltersToUnitsSearchParams as v } from "../features/filters/transformers.mjs";
|
|
5
5
|
const w = {
|
|
6
6
|
date_availability: void 0,
|
|
7
7
|
qty_bedrooms: void 0,
|
|
8
8
|
base_price: void 0,
|
|
9
9
|
highlights: void 0
|
|
10
|
-
},
|
|
10
|
+
}, S = {
|
|
11
11
|
// Property data
|
|
12
12
|
properties: {},
|
|
13
13
|
currentPropertyId: null,
|
|
@@ -26,37 +26,37 @@ const w = {
|
|
|
26
26
|
resolvedQuestionnaireValues: {},
|
|
27
27
|
sortBy: "relevance"
|
|
28
28
|
};
|
|
29
|
-
class
|
|
29
|
+
class g {
|
|
30
30
|
/**
|
|
31
31
|
* Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema
|
|
32
32
|
* and sanitizing invalid entries where possible.
|
|
33
33
|
*/
|
|
34
34
|
async getState() {
|
|
35
|
-
const t = await
|
|
35
|
+
const t = await l("app");
|
|
36
36
|
if (!t)
|
|
37
|
-
return
|
|
37
|
+
return S;
|
|
38
38
|
const e = {
|
|
39
|
-
...
|
|
39
|
+
...S,
|
|
40
40
|
...t,
|
|
41
41
|
properties: t.properties ?? {},
|
|
42
42
|
unitResults: t.unitResults ?? [],
|
|
43
43
|
currentPropertyId: t.currentPropertyId == null ? null : String(t.currentPropertyId),
|
|
44
44
|
currentPropertySlug: t.currentPropertySlug ?? null,
|
|
45
45
|
hasPreviouslySearched: Array.isArray(t.hasPreviouslySearched) ? t.hasPreviouslySearched.map(String) : []
|
|
46
|
-
}, r =
|
|
46
|
+
}, r = d.safeParse(e);
|
|
47
47
|
if (r.success) return r.data;
|
|
48
|
-
const s = Object.entries(e.properties ?? {}).reduce((
|
|
49
|
-
const
|
|
50
|
-
return
|
|
51
|
-
}, {}), i = (Array.isArray(e.unitResults) ? e.unitResults : e.unitResults && typeof e.unitResults == "object" ? Object.values(e.unitResults) : []).reduce((
|
|
52
|
-
const c =
|
|
53
|
-
return c.success &&
|
|
54
|
-
}, []),
|
|
48
|
+
const s = Object.entries(e.properties ?? {}).reduce((o, [p, c]) => {
|
|
49
|
+
const f = P.safeParse(c);
|
|
50
|
+
return f.success && (o[p] = f.data), o;
|
|
51
|
+
}, {}), i = (Array.isArray(e.unitResults) ? e.unitResults : e.unitResults && typeof e.unitResults == "object" ? Object.values(e.unitResults) : []).reduce((o, p) => {
|
|
52
|
+
const c = h.safeParse(p);
|
|
53
|
+
return c.success && o.push(c.data), o;
|
|
54
|
+
}, []), a = {
|
|
55
55
|
...e,
|
|
56
56
|
properties: s,
|
|
57
57
|
unitResults: i
|
|
58
|
-
},
|
|
59
|
-
return
|
|
58
|
+
}, n = d.safeParse(a);
|
|
59
|
+
return n.success ? n.data : S;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
62
|
* Applies an updater function to the current store state, validates the result, and persists it.
|
|
@@ -64,8 +64,8 @@ class U {
|
|
|
64
64
|
* @param updater - Pure function that maps the current state to the next state.
|
|
65
65
|
*/
|
|
66
66
|
async setState(t) {
|
|
67
|
-
const e = await this.getState(), r = t(e), s =
|
|
68
|
-
await
|
|
67
|
+
const e = await this.getState(), r = t(e), s = d.parse(r);
|
|
68
|
+
await y("app", s);
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
71
|
* Polls the persisted state until a current property pointer is available or the timeout elapses.
|
|
@@ -77,9 +77,9 @@ class U {
|
|
|
77
77
|
async waitForCurrentProperty(t = 1e3) {
|
|
78
78
|
const e = Date.now() + t;
|
|
79
79
|
for (; Date.now() < e; ) {
|
|
80
|
-
const
|
|
81
|
-
if (i &&
|
|
82
|
-
await new Promise((
|
|
80
|
+
const u = await this.getState(), i = u.currentPropertyId;
|
|
81
|
+
if (i && u.properties[i]) return i;
|
|
82
|
+
await new Promise((a) => setTimeout(a, 16));
|
|
83
83
|
}
|
|
84
84
|
const r = await this.getState(), s = r.currentPropertyId;
|
|
85
85
|
if (s && r.properties[s]) return s;
|
|
@@ -124,10 +124,10 @@ class U {
|
|
|
124
124
|
* @param schema - Optional override schema when the default `UnitSchema` is not sufficient.
|
|
125
125
|
*/
|
|
126
126
|
async setUnitResults(t, e) {
|
|
127
|
-
const r = e ??
|
|
128
|
-
(Array.isArray(t) ? t : t && typeof t == "object" ? Object.values(t) : []).forEach((i,
|
|
129
|
-
const
|
|
130
|
-
|
|
127
|
+
const r = e ?? h, s = [];
|
|
128
|
+
(Array.isArray(t) ? t : t && typeof t == "object" ? Object.values(t) : []).forEach((i, a) => {
|
|
129
|
+
const n = m(r, i, `unitResults[${a}]`);
|
|
130
|
+
n && s.push(n);
|
|
131
131
|
}), await this.setState((i) => ({
|
|
132
132
|
...i,
|
|
133
133
|
unitResults: s
|
|
@@ -142,118 +142,6 @@ class U {
|
|
|
142
142
|
unitResults: []
|
|
143
143
|
}));
|
|
144
144
|
}
|
|
145
|
-
// === PROPERTY DATA BAG (full property payloads & custom data) ===
|
|
146
|
-
/**
|
|
147
|
-
* Replaces the persisted property payload with validated data.
|
|
148
|
-
*
|
|
149
|
-
* @param propertyId - ID of the property to mutate.
|
|
150
|
-
* @param data - New property payload.
|
|
151
|
-
* @param schema - Optional schema override used for validation.
|
|
152
|
-
*/
|
|
153
|
-
async setPropertyData(t, e, r) {
|
|
154
|
-
const s = String(t), a = r ?? h;
|
|
155
|
-
await this.setState((i) => {
|
|
156
|
-
const n = i.properties[s];
|
|
157
|
-
if (!n) return i;
|
|
158
|
-
const o = d(a, e, `properties.${s}.data`);
|
|
159
|
-
return o ? {
|
|
160
|
-
...i,
|
|
161
|
-
properties: {
|
|
162
|
-
...i.properties,
|
|
163
|
-
[s]: {
|
|
164
|
-
...n,
|
|
165
|
-
data: o
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
} : i;
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Merges partial property data into the persisted payload with validation safeguards.
|
|
173
|
-
*
|
|
174
|
-
* @param propertyId - ID of the property to update.
|
|
175
|
-
* @param partial - Partial payload to merge.
|
|
176
|
-
* @param schema - Optional schema override for validation.
|
|
177
|
-
*/
|
|
178
|
-
async mergePropertyData(t, e, r) {
|
|
179
|
-
const s = String(t), a = r ?? h;
|
|
180
|
-
await this.setState((i) => {
|
|
181
|
-
const n = i.properties[s];
|
|
182
|
-
if (!n) return i;
|
|
183
|
-
const o = n.data;
|
|
184
|
-
if (!o) {
|
|
185
|
-
const l = d(a, e, `properties.${s}.data`);
|
|
186
|
-
return l ? {
|
|
187
|
-
...i,
|
|
188
|
-
properties: {
|
|
189
|
-
...i.properties,
|
|
190
|
-
[s]: {
|
|
191
|
-
...n,
|
|
192
|
-
data: l
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
} : i;
|
|
196
|
-
}
|
|
197
|
-
const p = a.partial(), u = d(
|
|
198
|
-
p,
|
|
199
|
-
e,
|
|
200
|
-
`properties.${s}.data.partial`
|
|
201
|
-
);
|
|
202
|
-
if (!u) return i;
|
|
203
|
-
const c = d(
|
|
204
|
-
a,
|
|
205
|
-
{ ...o, ...u },
|
|
206
|
-
`properties.${s}.data`
|
|
207
|
-
);
|
|
208
|
-
return c ? {
|
|
209
|
-
...i,
|
|
210
|
-
properties: {
|
|
211
|
-
...i.properties,
|
|
212
|
-
[s]: {
|
|
213
|
-
...n,
|
|
214
|
-
data: c
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
} : i;
|
|
218
|
-
});
|
|
219
|
-
}
|
|
220
|
-
// Accepts a full API property object, validates, and stores it into the
|
|
221
|
-
// per-property `data` bag. Ensures the property entry exists/updated.
|
|
222
|
-
/**
|
|
223
|
-
* Inserts or updates a property entry from an API payload, enforcing schema validation.
|
|
224
|
-
*
|
|
225
|
-
* @param apiProperty - Raw property object returned by an API.
|
|
226
|
-
* @param schema - Optional schema override.
|
|
227
|
-
*/
|
|
228
|
-
async upsertPropertyFromApi(t, e) {
|
|
229
|
-
const s = (e ?? h).parse(t), a = s.id ?? s.propertyId;
|
|
230
|
-
if (a == null)
|
|
231
|
-
throw new Error("upsertPropertyFromApi: property id is required");
|
|
232
|
-
const i = String(a), n = s.slug ?? void 0;
|
|
233
|
-
await this.setState((o) => {
|
|
234
|
-
const p = o.properties[i], u = p ? {
|
|
235
|
-
...p,
|
|
236
|
-
...n ? { slug: n } : {},
|
|
237
|
-
data: s
|
|
238
|
-
} : {
|
|
239
|
-
id: i,
|
|
240
|
-
slug: n ?? "",
|
|
241
|
-
favoritedUnits: [],
|
|
242
|
-
tourContactedOn: null,
|
|
243
|
-
viewedUnits: [],
|
|
244
|
-
questionnaireResults: null,
|
|
245
|
-
tourContactData: null,
|
|
246
|
-
data: s
|
|
247
|
-
};
|
|
248
|
-
return {
|
|
249
|
-
...o,
|
|
250
|
-
properties: {
|
|
251
|
-
...o.properties,
|
|
252
|
-
[i]: u
|
|
253
|
-
}
|
|
254
|
-
};
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
145
|
/**
|
|
258
146
|
* Marks the provided property as current and optionally updates the slug.
|
|
259
147
|
*
|
|
@@ -292,50 +180,6 @@ class U {
|
|
|
292
180
|
)
|
|
293
181
|
}));
|
|
294
182
|
}
|
|
295
|
-
/**
|
|
296
|
-
* Replaces the favoritedUnits list for the current property with the provided array.
|
|
297
|
-
* Intended for seeding IndexedDB from an API response (e.g. bootstrap endpoint).
|
|
298
|
-
*
|
|
299
|
-
* @param unitIds - Canonical list of favorited unit IDs from the API.
|
|
300
|
-
*/
|
|
301
|
-
async setFavoriteUnitIds(t) {
|
|
302
|
-
await this.setState((e) => {
|
|
303
|
-
const r = e.currentPropertyId;
|
|
304
|
-
if (!r) return e;
|
|
305
|
-
const s = e.properties[r];
|
|
306
|
-
return s ? {
|
|
307
|
-
...e,
|
|
308
|
-
properties: {
|
|
309
|
-
...e.properties,
|
|
310
|
-
[r]: { ...s, favoritedUnits: t }
|
|
311
|
-
}
|
|
312
|
-
} : e;
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Toggles a unit's favorite state for the currently active property.
|
|
317
|
-
*
|
|
318
|
-
* @param unitId - Unit identifier to toggle.
|
|
319
|
-
*/
|
|
320
|
-
async toggleFavorite(t) {
|
|
321
|
-
await this.setState((e) => {
|
|
322
|
-
const r = e.currentPropertyId;
|
|
323
|
-
if (!r) return e;
|
|
324
|
-
const s = e.properties[r];
|
|
325
|
-
if (!s) return e;
|
|
326
|
-
const i = s.favoritedUnits.includes(t) ? s.favoritedUnits.filter((n) => n !== t) : [...s.favoritedUnits, t];
|
|
327
|
-
return {
|
|
328
|
-
...e,
|
|
329
|
-
properties: {
|
|
330
|
-
...e.properties,
|
|
331
|
-
[r]: {
|
|
332
|
-
...s,
|
|
333
|
-
favoritedUnits: i
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
};
|
|
337
|
-
});
|
|
338
|
-
}
|
|
339
183
|
/**
|
|
340
184
|
* Records the most recent view date for a unit and opens the unit URL in the browser when available.
|
|
341
185
|
*
|
|
@@ -345,26 +189,26 @@ class U {
|
|
|
345
189
|
async markUnitAsViewed(t, e) {
|
|
346
190
|
const r = `https://${e}`;
|
|
347
191
|
window.open(r, "_blank", "noopener,noreferrer");
|
|
348
|
-
const s = /* @__PURE__ */ new Date(),
|
|
192
|
+
const s = /* @__PURE__ */ new Date(), u = `${String(s.getMonth() + 1).padStart(
|
|
349
193
|
2,
|
|
350
194
|
"0"
|
|
351
195
|
)}/${String(s.getDate()).padStart(2, "0")}`;
|
|
352
196
|
await this.setState((i) => {
|
|
353
|
-
const
|
|
197
|
+
const a = i.currentPropertyId;
|
|
198
|
+
if (!a) return i;
|
|
199
|
+
const n = i.properties[a];
|
|
354
200
|
if (!n) return i;
|
|
355
|
-
const o =
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
...o.viewedUnits.filter((u) => u.unitId !== t),
|
|
359
|
-
{ unitId: t, viewedDate: a }
|
|
201
|
+
const o = [
|
|
202
|
+
...n.viewedUnits.filter((p) => p.unitId !== t),
|
|
203
|
+
{ unitId: t, viewedDate: u }
|
|
360
204
|
];
|
|
361
205
|
return {
|
|
362
206
|
...i,
|
|
363
207
|
properties: {
|
|
364
208
|
...i.properties,
|
|
365
|
-
[
|
|
366
|
-
...
|
|
367
|
-
viewedUnits:
|
|
209
|
+
[a]: {
|
|
210
|
+
...n,
|
|
211
|
+
viewedUnits: o
|
|
368
212
|
}
|
|
369
213
|
}
|
|
370
214
|
};
|
|
@@ -501,7 +345,7 @@ class U {
|
|
|
501
345
|
*/
|
|
502
346
|
async submitFilterUpdate() {
|
|
503
347
|
await this.setState((t) => {
|
|
504
|
-
const e =
|
|
348
|
+
const e = v(
|
|
505
349
|
{
|
|
506
350
|
...t.filters,
|
|
507
351
|
limit: t.apiFilters.limit,
|
|
@@ -560,7 +404,7 @@ class U {
|
|
|
560
404
|
* @returns The visitor UUID string or null when not yet set.
|
|
561
405
|
*/
|
|
562
406
|
async getVisitorUUID() {
|
|
563
|
-
const t = await
|
|
407
|
+
const t = await l("user");
|
|
564
408
|
return (t == null ? void 0 : t.visitor_uuid) ?? null;
|
|
565
409
|
}
|
|
566
410
|
/**
|
|
@@ -569,69 +413,24 @@ class U {
|
|
|
569
413
|
* @param vid - Visitor UUID string returned by the session API.
|
|
570
414
|
*/
|
|
571
415
|
async setVisitorUUID(t) {
|
|
572
|
-
const e = await
|
|
573
|
-
await
|
|
574
|
-
}
|
|
575
|
-
// === UTILITY METHODS ===
|
|
576
|
-
/**
|
|
577
|
-
* Returns convenience state for a unit within the current property.
|
|
578
|
-
*
|
|
579
|
-
* @param unitId - Identifier of the unit to inspect.
|
|
580
|
-
* @returns Favorite flag and last viewed date.
|
|
581
|
-
*/
|
|
582
|
-
async getUnitState(t) {
|
|
583
|
-
var s;
|
|
584
|
-
const e = await this.getState(), r = e.currentPropertyId ? e.properties[e.currentPropertyId] : null;
|
|
585
|
-
return {
|
|
586
|
-
isFavorite: (r == null ? void 0 : r.favoritedUnits.includes(t)) ?? !1,
|
|
587
|
-
viewedDate: ((s = r == null ? void 0 : r.viewedUnits.find((a) => a.unitId === t)) == null ? void 0 : s.viewedDate) ?? ""
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
/**
|
|
591
|
-
* Builds a canonical results URL based on the current property slug.
|
|
592
|
-
*
|
|
593
|
-
* @returns Relative results URL or null when no property is selected.
|
|
594
|
-
*/
|
|
595
|
-
async getResultsUrl() {
|
|
596
|
-
const t = await this.getState();
|
|
597
|
-
return t.currentPropertySlug ? `/${t.currentPropertySlug}/results` : null;
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Retrieves the currently selected property entry.
|
|
601
|
-
*
|
|
602
|
-
* @returns Property state or null when unset.
|
|
603
|
-
*/
|
|
604
|
-
async getCurrentProperty() {
|
|
605
|
-
const t = await this.getState();
|
|
606
|
-
return t.currentPropertyId ? t.properties[t.currentPropertyId] ?? null : null;
|
|
607
|
-
}
|
|
608
|
-
/**
|
|
609
|
-
* Retrieves property data for a specific property or defaults to the current property.
|
|
610
|
-
*
|
|
611
|
-
* @param propertyId - Optional property identifier to fetch.
|
|
612
|
-
* @returns Property state or null when unavailable.
|
|
613
|
-
*/
|
|
614
|
-
async getPropertyData(t) {
|
|
615
|
-
const e = await this.getState(), r = t == null ? e.currentPropertyId : String(t);
|
|
616
|
-
return r ? e.properties[r] ?? null : null;
|
|
617
|
-
}
|
|
618
|
-
/**
|
|
619
|
-
* Reads and returns the full validated unified store state.
|
|
620
|
-
*/
|
|
621
|
-
async getFullState() {
|
|
622
|
-
return this.getState();
|
|
416
|
+
const e = await l("user"), r = e !== null && typeof e == "object" && !Array.isArray(e) ? e : {};
|
|
417
|
+
await y("user", { ...r, visitor_uuid: t });
|
|
623
418
|
}
|
|
624
419
|
/**
|
|
625
|
-
*
|
|
420
|
+
* Removes the visitor UUID from the KV store.
|
|
421
|
+
* Use when the stored UUID is stale (e.g. bootstrap returns 404).
|
|
626
422
|
*/
|
|
627
|
-
async
|
|
628
|
-
|
|
423
|
+
async clearVisitorUUID() {
|
|
424
|
+
const t = await l("user");
|
|
425
|
+
if (t === null || typeof t != "object" || Array.isArray(t)) return;
|
|
426
|
+
const { visitor_uuid: e, ...r } = t;
|
|
427
|
+
await y("user", r);
|
|
629
428
|
}
|
|
630
429
|
}
|
|
631
|
-
const
|
|
430
|
+
const b = new g();
|
|
632
431
|
export {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
432
|
+
g as Store,
|
|
433
|
+
g as UnifiedStore,
|
|
434
|
+
b as store
|
|
636
435
|
};
|
|
637
436
|
//# sourceMappingURL=store.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.mjs","sources":["../../src/stores/store.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport type { ZodObject, ZodType, ZodTypeAny } from \"zod\";\nimport {\n UnifiedStoreDataSchema,\n UserPropertyStateSchema,\n type UnifiedStoreData,\n type UserPropertyState,\n type Property,\n type Filters,\n type QueryParams,\n type ResultsMode,\n type SortBy,\n type TourContactData,\n type Unit,\n PropertySchema,\n TourContactDataSchema,\n UnitSchema,\n} from \"../schema\";\nimport { validate } from \"../validation\";\nimport { transformFiltersToUnitsSearchParams } from \"../features/filters/transformers\";\n\n// Default values\nconst defaultFilters: Filters = {\n date_availability: undefined,\n qty_bedrooms: undefined,\n base_price: undefined,\n highlights: undefined,\n};\n\nconst defaultUnifiedStoreData: UnifiedStoreData = {\n // Property data\n properties: {},\n currentPropertyId: null,\n currentPropertySlug: null,\n hasPreviouslySearched: [],\n\n // App data\n unitResults: [],\n filters: defaultFilters,\n tempFilters: defaultFilters,\n apiFilters: {\n limit: 10,\n page: 1,\n sortBy: \"relevance\",\n },\n resultsMode: \"all\",\n resolvedQuestionnaireValues: {},\n sortBy: \"relevance\",\n};\n\nconst toArray = (input: unknown): unknown[] => {\n if (input == null) return [];\n return Array.isArray(input) ? input : [input];\n};\n\nconst extractFilterValues = (value: unknown): unknown[] => {\n return toArray(value).flatMap(item => {\n if (item == null) return [];\n if (Array.isArray(item)) return item;\n if (typeof item === \"object\" && \"value\" in (item as any)) {\n const v = (item as any).value;\n return Array.isArray(v) ? v : v != null ? [v] : [];\n }\n return [item];\n });\n};\n\nconst toStringArray = (value: unknown): string[] =>\n extractFilterValues(value)\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .map(v => String(v))\n .map(v => v.trim())\n .filter(v => v.length > 0);\n\nconst toNumberArray = (value: unknown): number[] =>\n extractFilterValues(value)\n .map(v => {\n if (typeof v === \"number\" && Number.isFinite(v)) return v;\n const num = Number(v);\n return Number.isFinite(num) ? num : null;\n })\n .filter((v): v is number => v !== null);\n\nconst toNumberValue = (value: unknown): number | null => {\n if (value == null) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"object\" && \"value\" in (value as any)) {\n return toNumberValue((value as any).value);\n }\n const num = Number(value);\n return Number.isFinite(num) ? num : null;\n};\n\n// Unified store class\nexport class UnifiedStore {\n /**\n * Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema\n * and sanitizing invalid entries where possible.\n */\n private async getState(): Promise<UnifiedStoreData> {\n const state = await kvGet<UnifiedStoreData>(\"app\");\n if (!state) {\n return defaultUnifiedStoreData;\n }\n\n const merged = {\n ...defaultUnifiedStoreData,\n ...state,\n properties: state.properties ?? {},\n unitResults: state.unitResults ?? [],\n currentPropertyId:\n state.currentPropertyId == null ? null : String(state.currentPropertyId),\n currentPropertySlug: state.currentPropertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = UnifiedStoreDataSchema.safeParse(merged);\n if (parsed.success) return parsed.data;\n\n // Sanitize by dropping invalid property entries and unit results\n const sanitizedProperties = Object.entries(merged.properties ?? {}).reduce<\n Record<string, UserPropertyState>\n >((acc, [key, value]) => {\n const entry = UserPropertyStateSchema.safeParse(value);\n if (entry.success) acc[key] = entry.data;\n return acc;\n }, {});\n\n const rawUnitResults = Array.isArray(merged.unitResults)\n ? merged.unitResults\n : merged.unitResults && typeof merged.unitResults === \"object\"\n ? Object.values(merged.unitResults as Record<string, unknown>)\n : [];\n\n const sanitizedUnitResults = rawUnitResults.reduce<Unit[]>((acc, value) => {\n const entry = UnitSchema.safeParse(value);\n if (entry.success) acc.push(entry.data);\n return acc;\n }, []);\n\n const fallback = {\n ...merged,\n properties: sanitizedProperties,\n unitResults: sanitizedUnitResults,\n };\n\n const fallbackParsed = UnifiedStoreDataSchema.safeParse(fallback);\n return fallbackParsed.success ? fallbackParsed.data : defaultUnifiedStoreData;\n }\n\n /**\n * Applies an updater function to the current store state, validates the result, and persists it.\n *\n * @param updater - Pure function that maps the current state to the next state.\n */\n private async setState(updater: (state: UnifiedStoreData) => UnifiedStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = UnifiedStoreDataSchema.parse(newState);\n await kvSet(\"app\", validatedState);\n }\n\n /**\n * Polls the persisted state until a current property pointer is available or the timeout elapses.\n *\n * @param timeoutMs - Maximum time in milliseconds to wait before failing.\n * @returns The active property ID once it becomes available.\n * @throws Error if the property pointer is not set before the timeout expires.\n */\n private async waitForCurrentProperty(timeoutMs = 1000): Promise<string> {\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (propertyId && state.properties[propertyId]) return propertyId;\n\n await new Promise(resolve => setTimeout(resolve, 16));\n }\n\n const finalState = await this.getState();\n const propertyId = finalState.currentPropertyId;\n if (propertyId && finalState.properties[propertyId]) return propertyId;\n\n throw new Error(\"UnifiedStore: current property was not initialized in time\");\n }\n\n // === PROPERTY OPERATIONS ===\n\n /**\n * Ensures a property entry exists and registers it as the current property.\n *\n * @param propertyId - Identifier used to track the property.\n * @param slug - Canonical slug associated with the property.\n */\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.properties && state.properties[id]) {\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug\n };\n }\n\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug,\n properties: {\n ...state.properties,\n [id]: {\n id,\n slug,\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n },\n },\n };\n });\n }\n\n // === UNIT RESULTS CACHE ===\n /**\n * Persists a collection of units after validating each entry against the provided schema.\n *\n * @param units - Raw units collection returned by an API call.\n * @param schema - Optional override schema when the default `UnitSchema` is not sufficient.\n */\n async setUnitResults(\n units: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const baseSchema = (schema ?? UnitSchema) as ZodType<Unit>;\n const validatedUnits: Unit[] = [];\n const collection = Array.isArray(units)\n ? units\n : units && typeof units === \"object\"\n ? Object.values(units as Record<string, unknown>)\n : [];\n\n collection.forEach((unit, index) => {\n const parsed = validate(baseSchema, unit, `unitResults[${index}]`);\n if (parsed) validatedUnits.push(parsed);\n });\n await this.setState(state => ({\n ...state,\n unitResults: validatedUnits,\n }));\n }\n\n /**\n * Clears the cached unit results array.\n */\n async clearUnitResults(): Promise<void> {\n await this.setState(state => ({\n ...state,\n unitResults: [],\n }));\n }\n\n // === PROPERTY DATA BAG (full property payloads & custom data) ===\n /**\n * Replaces the persisted property payload with validated data.\n *\n * @param propertyId - ID of the property to mutate.\n * @param data - New property payload.\n * @param schema - Optional schema override used for validation.\n */\n async setPropertyData(\n propertyId: string | number,\n data: unknown,\n schema?: ZodObject<any, any, any, any, any>,\n ): Promise<void> {\n const id = String(propertyId);\n const baseSchema = (schema ?? PropertySchema) as ZodObject<any, any, any, any, any>;\n await this.setState(state => {\n const property = state.properties[id];\n if (!property) return state;\n const validated = validate(baseSchema, data, `properties.${id}.data`) as Property | null;\n if (!validated) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: validated,\n },\n },\n };\n });\n }\n\n /**\n * Merges partial property data into the persisted payload with validation safeguards.\n *\n * @param propertyId - ID of the property to update.\n * @param partial - Partial payload to merge.\n * @param schema - Optional schema override for validation.\n */\n async mergePropertyData(\n propertyId: string | number,\n partial: unknown,\n schema?: ZodObject<any, any, any, any, any>,\n ): Promise<void> {\n const id = String(propertyId);\n const baseSchema = (schema ?? PropertySchema) as ZodObject<any, any, any, any, any>;\n await this.setState(state => {\n const property = state.properties[id];\n if (!property) return state;\n const current = property.data;\n if (!current) {\n const full = validate(baseSchema, partial, `properties.${id}.data`) as Property | null;\n if (!full) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: full,\n },\n },\n };\n }\n\n const partialSchema = baseSchema.partial();\n const validatedPartial = validate(\n partialSchema,\n partial,\n `properties.${id}.data.partial`,\n ) as Partial<Property> | null;\n if (!validatedPartial) return state;\n const merged = validate(\n baseSchema,\n { ...current, ...validatedPartial },\n `properties.${id}.data`,\n ) as Property | null;\n if (!merged) return state;\n return {\n ...state,\n properties: {\n ...state.properties,\n [id]: {\n ...property,\n data: merged,\n },\n },\n };\n });\n }\n\n // Accepts a full API property object, validates, and stores it into the\n // per-property `data` bag. Ensures the property entry exists/updated.\n /**\n * Inserts or updates a property entry from an API payload, enforcing schema validation.\n *\n * @param apiProperty - Raw property object returned by an API.\n * @param schema - Optional schema override.\n */\n async upsertPropertyFromApi(\n apiProperty: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const s = schema ?? PropertySchema;\n const parsed: any = s.parse(apiProperty);\n const id = parsed.id ?? parsed.propertyId;\n if (id === undefined || id === null) {\n throw new Error(\"upsertPropertyFromApi: property id is required\");\n }\n const propertyId = String(id);\n const slug: string | undefined = parsed.slug ?? undefined;\n\n await this.setState(state => {\n const existing = state.properties[propertyId];\n const next: UserPropertyState = existing\n ? {\n ...existing,\n ...(slug ? { slug } : {}),\n data: parsed,\n }\n : {\n id: propertyId,\n slug: slug ?? \"\",\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n data: parsed,\n };\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: next,\n },\n };\n });\n }\n\n /**\n * Marks the provided property as current and optionally updates the slug.\n *\n * @param propertyId - Property identifier to focus.\n * @param slug - Optional slug override.\n */\n async setCurrentProperty(propertyId: string | number, slug?: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => ({\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug || state.currentPropertySlug,\n }));\n }\n\n /**\n * Updates the slug for the current property selection.\n *\n * @param slug - New slug to persist.\n */\n async setCurrentPropertySlug(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n currentPropertySlug: slug\n }));\n }\n\n /**\n * Adds a slug to the `hasPreviouslySearched` list without duplicating existing entries.\n *\n * @param slug - Slug to record.\n */\n async setHasPreviouslySearched(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n hasPreviouslySearched: Array.from(\n new Set([...state.hasPreviouslySearched, slug])\n ),\n }));\n }\n\n /**\n * Replaces the favoritedUnits list for the current property with the provided array.\n * Intended for seeding IndexedDB from an API response (e.g. bootstrap endpoint).\n *\n * @param unitIds - Canonical list of favorited unit IDs from the API.\n */\n async setFavoriteUnitIds(unitIds: string[]): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: { ...property, favoritedUnits: unitIds },\n },\n };\n });\n }\n\n /**\n * Toggles a unit's favorite state for the currently active property.\n *\n * @param unitId - Unit identifier to toggle.\n */\n async toggleFavorite(unitId: string): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const isFavorited = property.favoritedUnits.includes(unitId);\n const updatedFavoritedUnits = isFavorited\n ? property.favoritedUnits.filter((id) => id !== unitId)\n : [...property.favoritedUnits, unitId];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n favoritedUnits: updatedFavoritedUnits,\n },\n },\n };\n });\n }\n\n /**\n * Records the most recent view date for a unit and opens the unit URL in the browser when available.\n *\n * @param unitId - Identifier of the viewed unit.\n * @param slug - Property slug used to construct the URL.\n */\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\n\n const url = `https://${slug}`;\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n\n const today = new Date();\n const formattedDate = `${String(today.getMonth() + 1).padStart(\n 2,\n \"0\"\n )}/${String(today.getDate()).padStart(2, \"0\")}`;\n\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n { unitId, viewedDate: formattedDate },\n ];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n\n }\n\n /**\n * Stamps the current property with the moment the tour outreach occurred.\n */\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n /**\n * Reads the stored tour contact timestamp for the current property.\n *\n * @returns ISO string or null when no timestamp exists.\n */\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (!propertyId) return null;\n\n return state.properties[propertyId]?.tourContactedOn ?? null;\n }\n\n /**\n * Persists questionnaire results captured for the current property.\n *\n * @param results - Arbitrary questionnaire data.\n */\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n /**\n * Persists structured tour contact preferences for the active property. The method waits until\n * a current property is available, allowing callers to invoke it before initialization completes.\n *\n * @param data - Contact preferences captured from the UI.\n */\n async setTourContactData(data: TourContactData): Promise<void> {\n const propertyId = await this.waitForCurrentProperty();\n\n await this.setState(state => {\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n\n\n\n\n\n\n // === FILTER OPERATIONS ===\n\n /**\n * Merges the provided filter values into the committed filter state.\n *\n * @param filters - Partial filter payload to apply.\n */\n async setFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n filters: { ...state.filters, ...filters }\n }));\n }\n\n /**\n * Updates the transient filters used for in-progress UI interactions.\n *\n * @param filters - Partial staging filter payload.\n */\n async setTempFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, ...filters }\n }));\n }\n\n /**\n * Resets the committed filters to their default values.\n */\n async setFiltersToDefault(): Promise<void> {\n await this.setState(state => ({ ...state, filters: defaultFilters }));\n }\n\n /**\n * Merges partial values into the API filters payload used for network requests.\n *\n * @param filters - Partial query parameters to persist.\n */\n async setApiFilters(filters: Partial<QueryParams>): Promise<void> {\n await this.setState(state => ({\n ...state,\n apiFilters: { ...state.apiFilters, ...filters }\n }));\n }\n\n /**\n * Updates a single temporary filter field without touching the rest of the staged filters.\n *\n * @param key - Filter key to mutate.\n * @param value - New value to assign.\n */\n async handleTempFilterChange<K extends keyof Filters>(\n key: K,\n value: Filters[K]\n ): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, [key]: value }\n }));\n }\n\n /**\n * Normalizes the committed filters into API-ready structures and persists the result.\n */\n async submitFilterUpdate(): Promise<void> {\n await this.setState(state => {\n const apiParams: QueryParams = transformFiltersToUnitsSearchParams(\n {\n ...state.filters,\n limit: state.apiFilters.limit,\n page: state.apiFilters.page,\n sortBy: state.sortBy,\n },\n {\n defaultLimit: state.apiFilters.limit,\n defaultPage: state.apiFilters.page,\n defaultSort: state.sortBy,\n },\n );\n\n return {\n ...state,\n apiFilters: apiParams,\n };\n });\n }\n\n // === RESULTS AND SORTING ===\n\n /**\n * Persists the selected results mode (e.g. \"all\" or \"favorites\").\n *\n * @param mode - Mode identifier to store.\n */\n async setResultsMode(mode: ResultsMode): Promise<void> {\n await this.setState(state => ({ ...state, resultsMode: mode }));\n }\n\n /**\n * Persists the currently selected sort option.\n *\n * @param sortBy - Sort identifier.\n */\n async setSortBy(sortBy: SortBy): Promise<void> {\n await this.setState(state => ({ ...state, sortBy }));\n }\n\n // === QUESTIONNAIRE ===\n\n /**\n * Stores resolved questionnaire answers keyed by questionnaire name.\n *\n * @param name - Questionnaire identifier.\n * @param values - Selected option values.\n */\n async setResolvedQuestionnaireValues(name: string, values: string[]): Promise<void> {\n await this.setState(state => ({\n ...state,\n resolvedQuestionnaireValues: {\n ...state.resolvedQuestionnaireValues,\n [name]: values\n }\n }));\n }\n\n // === VISITOR UUID ===\n\n /**\n * Reads the persisted visitor UUID from the KV store.\n *\n * @returns The visitor UUID string or null when not yet set.\n */\n async getVisitorUUID(): Promise<string | null> {\n const user = await kvGet<{ visitor_uuid?: string }>(\"user\");\n return user?.visitor_uuid ?? null;\n }\n\n /**\n * Persists a visitor UUID to the KV store.\n *\n * @param vid - Visitor UUID string returned by the session API.\n */\n async setVisitorUUID(vid: string): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n const safe = current !== null && typeof current === \"object\" && !Array.isArray(current) ? current : {};\n await kvSet(\"user\", { ...safe, visitor_uuid: vid });\n }\n\n // === UTILITY METHODS ===\n\n /**\n * Returns convenience state for a unit within the current property.\n *\n * @param unitId - Identifier of the unit to inspect.\n * @returns Favorite flag and last viewed date.\n */\n async getUnitState(unitId: string): Promise<{\n isFavorite: boolean;\n viewedDate: string;\n }> {\n const state = await this.getState();\n const property = state.currentPropertyId ? state.properties[state.currentPropertyId] : null;\n\n return {\n isFavorite: property?.favoritedUnits.includes(unitId) ?? false,\n viewedDate:\n property?.viewedUnits.find((u) => u.unitId === unitId)?.viewedDate ?? \"\",\n };\n }\n\n /**\n * Builds a canonical results URL based on the current property slug.\n *\n * @returns Relative results URL or null when no property is selected.\n */\n async getResultsUrl(): Promise<string | null> {\n const state = await this.getState();\n return state.currentPropertySlug ? `/${state.currentPropertySlug}/results` : null;\n }\n\n /**\n * Retrieves the currently selected property entry.\n *\n * @returns Property state or null when unset.\n */\n async getCurrentProperty(): Promise<UserPropertyState | null> {\n const state = await this.getState();\n return state.currentPropertyId ? state.properties[state.currentPropertyId] ?? null : null;\n }\n\n /**\n * Retrieves property data for a specific property or defaults to the current property.\n *\n * @param propertyId - Optional property identifier to fetch.\n * @returns Property state or null when unavailable.\n */\n async getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null> {\n const state = await this.getState();\n const id = propertyId == null ? state.currentPropertyId : String(propertyId);\n return id ? state.properties[id] ?? null : null;\n }\n\n /**\n * Reads and returns the full validated unified store state.\n */\n async getFullState(): Promise<UnifiedStoreData> {\n return this.getState();\n }\n\n /**\n * Hydrates the store with the default scaffold when no data has been persisted yet.\n */\n async initialize(): Promise<void> {\n // Ensure default shape is present; no-op if already initialized\n await this.setState(state => ({ ...defaultUnifiedStoreData, ...state }));\n }\n\n}\n\n// Export singleton instance\nexport const store = new UnifiedStore();\n// Alias to prefer neutral naming going forward\nexport { UnifiedStore as Store };\n// Re-export types for convenience (tests import from this module)\nexport type { UserPropertyState, Filters } from \"../schema\";\n"],"names":["defaultFilters","defaultUnifiedStoreData","UnifiedStore","state","kvGet","merged","parsed","UnifiedStoreDataSchema","sanitizedProperties","acc","key","value","entry","UserPropertyStateSchema","sanitizedUnitResults","UnitSchema","fallback","fallbackParsed","updater","currentState","newState","validatedState","kvSet","timeoutMs","deadline","propertyId","resolve","finalState","slug","id","units","schema","baseSchema","validatedUnits","unit","index","validate","data","PropertySchema","property","validated","partial","current","full","partialSchema","validatedPartial","apiProperty","existing","next","unitIds","unitId","updatedFavoritedUnits","url","today","formattedDate","updatedViewedUnits","_a","results","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","safe","u","store"],"mappings":";;;;AAsBA,MAAMA,IAA0B;AAAA,EAC9B,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,YAAY;AACd,GAEMC,IAA4C;AAAA;AAAA,EAEhD,YAAY,CAAA;AAAA,EACZ,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,uBAAuB,CAAA;AAAA;AAAA,EAGvB,aAAa,CAAA;AAAA,EACb,SAASD;AAAA,EACT,aAAaA;AAAA,EACb,YAAY;AAAA,IACV,OAAO;AAAA,IACP,MAAM;AAAA,IACN,QAAQ;AAAA,EAAA;AAAA,EAEV,aAAa;AAAA,EACb,6BAA6B,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":["../../src/stores/store.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport type { ZodType, ZodTypeAny } from \"zod\";\nimport {\n UnifiedStoreDataSchema,\n UserPropertyStateSchema,\n type UnifiedStoreData,\n type UserPropertyState,\n type Filters,\n type QueryParams,\n type ResultsMode,\n type SortBy,\n type TourContactData,\n type Unit,\n UnitSchema,\n} from \"../schema\";\nimport { validate } from \"../validation\";\nimport { transformFiltersToUnitsSearchParams } from \"../features/filters/transformers\";\n\n// Default values\nconst defaultFilters: Filters = {\n date_availability: undefined,\n qty_bedrooms: undefined,\n base_price: undefined,\n highlights: undefined,\n};\n\nconst defaultUnifiedStoreData: UnifiedStoreData = {\n // Property data\n properties: {},\n currentPropertyId: null,\n currentPropertySlug: null,\n hasPreviouslySearched: [],\n\n // App data\n unitResults: [],\n filters: defaultFilters,\n tempFilters: defaultFilters,\n apiFilters: {\n limit: 10,\n page: 1,\n sortBy: \"relevance\",\n },\n resultsMode: \"all\",\n resolvedQuestionnaireValues: {},\n sortBy: \"relevance\",\n};\n\nconst toArray = (input: unknown): unknown[] => {\n if (input == null) return [];\n return Array.isArray(input) ? input : [input];\n};\n\nconst extractFilterValues = (value: unknown): unknown[] => {\n return toArray(value).flatMap(item => {\n if (item == null) return [];\n if (Array.isArray(item)) return item;\n if (typeof item === \"object\" && \"value\" in (item as any)) {\n const v = (item as any).value;\n return Array.isArray(v) ? v : v != null ? [v] : [];\n }\n return [item];\n });\n};\n\nconst toStringArray = (value: unknown): string[] =>\n extractFilterValues(value)\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .map(v => String(v))\n .map(v => v.trim())\n .filter(v => v.length > 0);\n\nconst toNumberArray = (value: unknown): number[] =>\n extractFilterValues(value)\n .map(v => {\n if (typeof v === \"number\" && Number.isFinite(v)) return v;\n const num = Number(v);\n return Number.isFinite(num) ? num : null;\n })\n .filter((v): v is number => v !== null);\n\nconst toNumberValue = (value: unknown): number | null => {\n if (value == null) return null;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"object\" && \"value\" in (value as any)) {\n return toNumberValue((value as any).value);\n }\n const num = Number(value);\n return Number.isFinite(num) ? num : null;\n};\n\n// Unified store class\nexport class UnifiedStore {\n /**\n * Resolves the persisted unified store snapshot, coercing legacy shapes into the latest schema\n * and sanitizing invalid entries where possible.\n */\n private async getState(): Promise<UnifiedStoreData> {\n const state = await kvGet<UnifiedStoreData>(\"app\");\n if (!state) {\n return defaultUnifiedStoreData;\n }\n\n const merged = {\n ...defaultUnifiedStoreData,\n ...state,\n properties: state.properties ?? {},\n unitResults: state.unitResults ?? [],\n currentPropertyId:\n state.currentPropertyId == null ? null : String(state.currentPropertyId),\n currentPropertySlug: state.currentPropertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = UnifiedStoreDataSchema.safeParse(merged);\n if (parsed.success) return parsed.data;\n\n // Sanitize by dropping invalid property entries and unit results\n const sanitizedProperties = Object.entries(merged.properties ?? {}).reduce<\n Record<string, UserPropertyState>\n >((acc, [key, value]) => {\n const entry = UserPropertyStateSchema.safeParse(value);\n if (entry.success) acc[key] = entry.data;\n return acc;\n }, {});\n\n const rawUnitResults = Array.isArray(merged.unitResults)\n ? merged.unitResults\n : merged.unitResults && typeof merged.unitResults === \"object\"\n ? Object.values(merged.unitResults as Record<string, unknown>)\n : [];\n\n const sanitizedUnitResults = rawUnitResults.reduce<Unit[]>((acc, value) => {\n const entry = UnitSchema.safeParse(value);\n if (entry.success) acc.push(entry.data);\n return acc;\n }, []);\n\n const fallback = {\n ...merged,\n properties: sanitizedProperties,\n unitResults: sanitizedUnitResults,\n };\n\n const fallbackParsed = UnifiedStoreDataSchema.safeParse(fallback);\n return fallbackParsed.success ? fallbackParsed.data : defaultUnifiedStoreData;\n }\n\n /**\n * Applies an updater function to the current store state, validates the result, and persists it.\n *\n * @param updater - Pure function that maps the current state to the next state.\n */\n private async setState(updater: (state: UnifiedStoreData) => UnifiedStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = UnifiedStoreDataSchema.parse(newState);\n await kvSet(\"app\", validatedState);\n }\n\n /**\n * Polls the persisted state until a current property pointer is available or the timeout elapses.\n *\n * @param timeoutMs - Maximum time in milliseconds to wait before failing.\n * @returns The active property ID once it becomes available.\n * @throws Error if the property pointer is not set before the timeout expires.\n */\n private async waitForCurrentProperty(timeoutMs = 1000): Promise<string> {\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() < deadline) {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (propertyId && state.properties[propertyId]) return propertyId;\n\n await new Promise(resolve => setTimeout(resolve, 16));\n }\n\n const finalState = await this.getState();\n const propertyId = finalState.currentPropertyId;\n if (propertyId && finalState.properties[propertyId]) return propertyId;\n\n throw new Error(\"UnifiedStore: current property was not initialized in time\");\n }\n\n // === PROPERTY OPERATIONS ===\n\n /**\n * Ensures a property entry exists and registers it as the current property.\n *\n * @param propertyId - Identifier used to track the property.\n * @param slug - Canonical slug associated with the property.\n */\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.properties && state.properties[id]) {\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug\n };\n }\n\n return {\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug,\n properties: {\n ...state.properties,\n [id]: {\n id,\n slug,\n favoritedUnits: [],\n tourContactedOn: null,\n viewedUnits: [],\n questionnaireResults: null,\n tourContactData: null,\n },\n },\n };\n });\n }\n\n // === UNIT RESULTS CACHE ===\n /**\n * Persists a collection of units after validating each entry against the provided schema.\n *\n * @param units - Raw units collection returned by an API call.\n * @param schema - Optional override schema when the default `UnitSchema` is not sufficient.\n */\n async setUnitResults(\n units: unknown,\n schema?: ZodTypeAny,\n ): Promise<void> {\n const baseSchema = (schema ?? UnitSchema) as ZodType<Unit>;\n const validatedUnits: Unit[] = [];\n const collection = Array.isArray(units)\n ? units\n : units && typeof units === \"object\"\n ? Object.values(units as Record<string, unknown>)\n : [];\n\n collection.forEach((unit, index) => {\n const parsed = validate(baseSchema, unit, `unitResults[${index}]`);\n if (parsed) validatedUnits.push(parsed);\n });\n await this.setState(state => ({\n ...state,\n unitResults: validatedUnits,\n }));\n }\n\n /**\n * Clears the cached unit results array.\n */\n async clearUnitResults(): Promise<void> {\n await this.setState(state => ({\n ...state,\n unitResults: [],\n }));\n }\n\n /**\n * Marks the provided property as current and optionally updates the slug.\n *\n * @param propertyId - Property identifier to focus.\n * @param slug - Optional slug override.\n */\n async setCurrentProperty(propertyId: string | number, slug?: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => ({\n ...state,\n currentPropertyId: id,\n currentPropertySlug: slug || state.currentPropertySlug,\n }));\n }\n\n /**\n * Updates the slug for the current property selection.\n *\n * @param slug - New slug to persist.\n */\n async setCurrentPropertySlug(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n currentPropertySlug: slug\n }));\n }\n\n /**\n * Adds a slug to the `hasPreviouslySearched` list without duplicating existing entries.\n *\n * @param slug - Slug to record.\n */\n async setHasPreviouslySearched(slug: string): Promise<void> {\n await this.setState(state => ({\n ...state,\n hasPreviouslySearched: Array.from(\n new Set([...state.hasPreviouslySearched, slug])\n ),\n }));\n }\n\n /**\n * Records the most recent view date for a unit and opens the unit URL in the browser when available.\n *\n * @param unitId - Identifier of the viewed unit.\n * @param slug - Property slug used to construct the URL.\n */\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\n\n const url = `https://${slug}`;\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n\n const today = new Date();\n const formattedDate = `${String(today.getMonth() + 1).padStart(\n 2,\n \"0\"\n )}/${String(today.getDate()).padStart(2, \"0\")}`;\n\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n { unitId, viewedDate: formattedDate },\n ];\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n\n }\n\n /**\n * Stamps the current property with the moment the tour outreach occurred.\n */\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n /**\n * Reads the stored tour contact timestamp for the current property.\n *\n * @returns ISO string or null when no timestamp exists.\n */\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.currentPropertyId;\n if (!propertyId) return null;\n\n return state.properties[propertyId]?.tourContactedOn ?? null;\n }\n\n /**\n * Persists questionnaire results captured for the current property.\n *\n * @param results - Arbitrary questionnaire data.\n */\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.currentPropertyId;\n if (!propertyId) return state;\n\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n /**\n * Persists structured tour contact preferences for the active property. The method waits until\n * a current property is available, allowing callers to invoke it before initialization completes.\n *\n * @param data - Contact preferences captured from the UI.\n */\n async setTourContactData(data: TourContactData): Promise<void> {\n const propertyId = await this.waitForCurrentProperty();\n\n await this.setState(state => {\n const property = state.properties[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n properties: {\n ...state.properties,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n\n\n\n\n\n\n // === FILTER OPERATIONS ===\n\n /**\n * Merges the provided filter values into the committed filter state.\n *\n * @param filters - Partial filter payload to apply.\n */\n async setFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n filters: { ...state.filters, ...filters }\n }));\n }\n\n /**\n * Updates the transient filters used for in-progress UI interactions.\n *\n * @param filters - Partial staging filter payload.\n */\n async setTempFilters(filters: Partial<Filters>): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, ...filters }\n }));\n }\n\n /**\n * Resets the committed filters to their default values.\n */\n async setFiltersToDefault(): Promise<void> {\n await this.setState(state => ({ ...state, filters: defaultFilters }));\n }\n\n /**\n * Merges partial values into the API filters payload used for network requests.\n *\n * @param filters - Partial query parameters to persist.\n */\n async setApiFilters(filters: Partial<QueryParams>): Promise<void> {\n await this.setState(state => ({\n ...state,\n apiFilters: { ...state.apiFilters, ...filters }\n }));\n }\n\n /**\n * Updates a single temporary filter field without touching the rest of the staged filters.\n *\n * @param key - Filter key to mutate.\n * @param value - New value to assign.\n */\n async handleTempFilterChange<K extends keyof Filters>(\n key: K,\n value: Filters[K]\n ): Promise<void> {\n await this.setState(state => ({\n ...state,\n tempFilters: { ...state.tempFilters, [key]: value }\n }));\n }\n\n /**\n * Normalizes the committed filters into API-ready structures and persists the result.\n */\n async submitFilterUpdate(): Promise<void> {\n await this.setState(state => {\n const apiParams: QueryParams = transformFiltersToUnitsSearchParams(\n {\n ...state.filters,\n limit: state.apiFilters.limit,\n page: state.apiFilters.page,\n sortBy: state.sortBy,\n },\n {\n defaultLimit: state.apiFilters.limit,\n defaultPage: state.apiFilters.page,\n defaultSort: state.sortBy,\n },\n );\n\n return {\n ...state,\n apiFilters: apiParams,\n };\n });\n }\n\n // === RESULTS AND SORTING ===\n\n /**\n * Persists the selected results mode (e.g. \"all\" or \"favorites\").\n *\n * @param mode - Mode identifier to store.\n */\n async setResultsMode(mode: ResultsMode): Promise<void> {\n await this.setState(state => ({ ...state, resultsMode: mode }));\n }\n\n /**\n * Persists the currently selected sort option.\n *\n * @param sortBy - Sort identifier.\n */\n async setSortBy(sortBy: SortBy): Promise<void> {\n await this.setState(state => ({ ...state, sortBy }));\n }\n\n // === QUESTIONNAIRE ===\n\n /**\n * Stores resolved questionnaire answers keyed by questionnaire name.\n *\n * @param name - Questionnaire identifier.\n * @param values - Selected option values.\n */\n async setResolvedQuestionnaireValues(name: string, values: string[]): Promise<void> {\n await this.setState(state => ({\n ...state,\n resolvedQuestionnaireValues: {\n ...state.resolvedQuestionnaireValues,\n [name]: values\n }\n }));\n }\n\n // === VISITOR UUID ===\n\n /**\n * Reads the persisted visitor UUID from the KV store.\n *\n * @returns The visitor UUID string or null when not yet set.\n */\n async getVisitorUUID(): Promise<string | null> {\n const user = await kvGet<{ visitor_uuid?: string }>(\"user\");\n return user?.visitor_uuid ?? null;\n }\n\n /**\n * Persists a visitor UUID to the KV store.\n *\n * @param vid - Visitor UUID string returned by the session API.\n */\n async setVisitorUUID(vid: string): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n const safe = current !== null && typeof current === \"object\" && !Array.isArray(current) ? current : {};\n await kvSet(\"user\", { ...safe, visitor_uuid: vid });\n }\n\n /**\n * Removes the visitor UUID from the KV store.\n * Use when the stored UUID is stale (e.g. bootstrap returns 404).\n */\n async clearVisitorUUID(): Promise<void> {\n const current = await kvGet<Record<string, unknown>>(\"user\");\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) return;\n const { visitor_uuid: _, ...rest } = current;\n await kvSet(\"user\", rest);\n }\n\n}\n\n// Export singleton instance\nexport const store = new UnifiedStore();\n// Alias to prefer neutral naming going forward\nexport { UnifiedStore as Store };\n// Re-export types for convenience (tests import from this module)\nexport type { UserPropertyState, Filters } from \"../schema\";\n"],"names":["defaultFilters","defaultUnifiedStoreData","UnifiedStore","state","kvGet","merged","parsed","UnifiedStoreDataSchema","sanitizedProperties","acc","key","value","entry","UserPropertyStateSchema","sanitizedUnitResults","UnitSchema","fallback","fallbackParsed","updater","currentState","newState","validatedState","kvSet","timeoutMs","deadline","propertyId","resolve","finalState","slug","id","units","schema","baseSchema","validatedUnits","unit","index","validate","unitId","url","today","formattedDate","property","updatedViewedUnits","u","_a","results","data","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","current","safe","_","rest","store"],"mappings":";;;;AAmBA,MAAMA,IAA0B;AAAA,EAC9B,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,YAAY;AACd,GAEMC,IAA4C;AAAA;AAAA,EAEhD,YAAY,CAAA;AAAA,EACZ,mBAAmB;AAAA,EACnB,qBAAqB;AAAA,EACrB,uBAAuB,CAAA;AAAA;AAAA,EAGvB,aAAa,CAAA;AAAA,EACb,SAASD;AAAA,EACT,aAAaA;AAAA,EACb,YAAY;AAAA,IACV,OAAO;AAAA,IACP,MAAM;AAAA,IACN,QAAQ;AAAA,EAAA;AAAA,EAEV,aAAa;AAAA,EACb,6BAA6B,CAAA;AAAA,EAC7B,QAAQ;AACV;AA8CO,MAAME,EAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAKxB,MAAc,WAAsC;AAClD,UAAMC,IAAQ,MAAMC,EAAwB,KAAK;AACjD,QAAI,CAACD;AACH,aAAOF;AAGT,UAAMI,IAAS;AAAA,MACb,GAAGJ;AAAA,MACH,GAAGE;AAAA,MACH,YAAYA,EAAM,cAAc,CAAA;AAAA,MAChC,aAAaA,EAAM,eAAe,CAAA;AAAA,MAClC,mBACEA,EAAM,qBAAqB,OAAO,OAAO,OAAOA,EAAM,iBAAiB;AAAA,MACzE,qBAAqBA,EAAM,uBAAuB;AAAA,MAClD,uBAAuB,MAAM,QAAQA,EAAM,qBAAqB,IAC5DA,EAAM,sBAAsB,IAAI,MAAM,IACtC,CAAA;AAAA,IAAC,GAGDG,IAASC,EAAuB,UAAUF,CAAM;AACtD,QAAIC,EAAO,QAAS,QAAOA,EAAO;AAGlC,UAAME,IAAsB,OAAO,QAAQH,EAAO,cAAc,CAAA,CAAE,EAAE,OAElE,CAACI,GAAK,CAACC,GAAKC,CAAK,MAAM;A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GA,GAAO,QAAAgD,IAAS;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,+BAA+BC,GAAcC,GAAiC;AAClF,UAAM,KAAK,SAAS,CAAAlD,OAAU;AAAA,MAC5B,GAAGA;AAAA,MACH,6BAA6B;AAAA,QAC3B,GAAGA,EAAM;AAAA,QACT,CAACiD,CAAI,GAAGC;AAAA,MAAA;AAAA,IACV,EACA;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,iBAAyC;AAC7C,UAAMC,IAAO,MAAMlD,EAAiC,MAAM;AAC1D,YAAOkD,KAAA,gBAAAA,EAAM,iBAAgB;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,eAAeC,GAA4B;AAC/C,UAAMC,IAAU,MAAMpD,EAA+B,MAAM,GACrDqD,IAAOD,MAAY,QAAQ,OAAOA,KAAY,YAAY,CAAC,MAAM,QAAQA,CAAO,IAAIA,IAAU,CAAA;AACpG,UAAMlC,EAAM,QAAQ,EAAE,GAAGmC,GAAM,cAAcF,GAAK;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,mBAAkC;AACtC,UAAMC,IAAU,MAAMpD,EAA+B,MAAM;AAC3D,QAAIoD,MAAY,QAAQ,OAAOA,KAAY,YAAY,MAAM,QAAQA,CAAO,EAAG;AAC/E,UAAM,EAAE,cAAcE,GAAG,GAAGC,MAASH;AACrC,UAAMlC,EAAM,QAAQqC,CAAI;AAAA,EAC1B;AAEF;AAGO,MAAMC,IAAQ,IAAI1D,EAAA;"}
|
package/package.json
CHANGED
package/dist/api/favorites.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("../db.cjs"),l=require("./users.cjs"),c=require("../schema.cjs"),g=(e,t)=>`favorites:${e}:${t}`;async function u(e){const t=await v.getDB(),{uuid:a}=await l.ensureUser(),n=g(a,String(e)),r=await t.kv.get(n),s=r?c.FavoritesSchema.safeParse(r.value):null;return s!=null&&s.success?s.data.unitIds:[]}async function w(e,t,a){const n=await v.getDB(),{uuid:r}=await l.ensureUser(),s=g(r,String(e));return n.transaction("rw",n.kv,async()=>{const i=await n.kv.get(s),F=i&&c.FavoritesSchema.safeParse(i.value).success?i.value:{unitIds:[],updatedAt:new Date().toISOString()},o=new Set(F.unitIds);a?o.add(t):o.delete(t);const S={unitIds:[...o],updatedAt:new Date().toISOString()},d=c.FavoritesSchema.parse(S);return await n.kv.put({key:s,value:d}),d.unitIds})}async function y(e,t){const n=!(await u(e)).includes(t);return w(e,t,n)}async function U(e,t){return(await u(e)).includes(t)}exports.getFavoritedUnitsForProperty=u;exports.isUnitFavorited=U;exports.setFavoriteUnit=w;exports.toggleFavoriteUnit=y;
|
|
2
|
-
//# sourceMappingURL=favorites.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"favorites.cjs","sources":["../../src/api/favorites.ts"],"sourcesContent":["// src/api/favourites.ts\nimport { getDB } from \"../db\";\nimport { ensureUser } from \"./users\";\nimport { FavoritesSchema } from \"../schema\";\n\nconst keyFor = (userId: string, propertyId: string) =>\n `favorites:${userId}:${propertyId}`;\n\nexport async function getFavoritedUnitsForProperty(\n propertyId: string | number,\n): Promise<string[]> {\n const db = await getDB();\n const { uuid } = await ensureUser();\n const key = keyFor(uuid, String(propertyId));\n const row = await db.kv.get(key);\n const parsed = row ? FavoritesSchema.safeParse(row.value) : null;\n return parsed?.success ? parsed.data.unitIds : [];\n}\n\nexport async function setFavoriteUnit(\n propertyId: string | number,\n unitId: string,\n on: boolean,\n): Promise<string[]> {\n const db = await getDB();\n const { uuid } = await ensureUser();\n const key = keyFor(uuid, String(propertyId));\n\n return db.transaction(\"rw\", db.kv, async () => {\n const row = await db.kv.get(key);\n const current =\n row && FavoritesSchema.safeParse(row.value).success\n ? (row!.value as any)\n : { unitIds: [] as string[], updatedAt: new Date().toISOString() };\n\n const nextSet = new Set<string>(current.unitIds);\n on ? nextSet.add(unitId) : nextSet.delete(unitId);\n\n const next = {\n unitIds: [...nextSet],\n updatedAt: new Date().toISOString(),\n };\n const validated = FavoritesSchema.parse(next);\n await db.kv.put({ key, value: validated });\n return validated.unitIds;\n });\n}\n\nexport async function toggleFavoriteUnit(\n propertyId: string | number,\n unitId: string,\n): Promise<string[]> {\n const current = await getFavoritedUnitsForProperty(propertyId);\n const on = !current.includes(unitId);\n return setFavoriteUnit(propertyId, unitId, on);\n}\n\nexport async function isUnitFavorited(\n propertyId: string | number,\n unitId: string,\n): Promise<boolean> {\n const list = await getFavoritedUnitsForProperty(propertyId);\n return list.includes(unitId);\n}\n"],"names":["keyFor","userId","propertyId","getFavoritedUnitsForProperty","db","getDB","uuid","ensureUser","key","row","parsed","FavoritesSchema","setFavoriteUnit","unitId","on","current","nextSet","next","validated","toggleFavoriteUnit","isUnitFavorited"],"mappings":"iKAKMA,EAAS,CAACC,EAAgBC,IAC9B,aAAaD,CAAM,IAAIC,CAAU,GAEnC,eAAsBC,EACpBD,EACmB,CACnB,MAAME,EAAK,MAAMC,QAAA,EACX,CAAE,KAAAC,GAAS,MAAMC,aAAA,EACjBC,EAAMR,EAAOM,EAAM,OAAOJ,CAAU,CAAC,EACrCO,EAAM,MAAML,EAAG,GAAG,IAAII,CAAG,EACzBE,EAASD,EAAME,EAAAA,gBAAgB,UAAUF,EAAI,KAAK,EAAI,KAC5D,OAAOC,GAAA,MAAAA,EAAQ,QAAUA,EAAO,KAAK,QAAU,CAAA,CACjD,CAEA,eAAsBE,EACpBV,EACAW,EACAC,EACmB,CACnB,MAAMV,EAAK,MAAMC,QAAA,EACX,CAAE,KAAAC,GAAS,MAAMC,aAAA,EACjBC,EAAMR,EAAOM,EAAM,OAAOJ,CAAU,CAAC,EAE3C,OAAOE,EAAG,YAAY,KAAMA,EAAG,GAAI,SAAY,CAC7C,MAAMK,EAAM,MAAML,EAAG,GAAG,IAAII,CAAG,EACzBO,EACJN,GAAOE,EAAAA,gBAAgB,UAAUF,EAAI,KAAK,EAAE,QACvCA,EAAK,MACN,CAAE,QAAS,GAAgB,cAAe,KAAA,EAAO,aAAY,EAE7DO,EAAU,IAAI,IAAYD,EAAQ,OAAO,EAC/CD,EAAKE,EAAQ,IAAIH,CAAM,EAAIG,EAAQ,OAAOH,CAAM,EAEhD,MAAMI,EAAO,CACX,QAAS,CAAC,GAAGD,CAAO,EACpB,UAAW,IAAI,KAAA,EAAO,YAAA,CAAY,EAE9BE,EAAYP,EAAAA,gBAAgB,MAAMM,CAAI,EAC5C,aAAMb,EAAG,GAAG,IAAI,CAAE,IAAAI,EAAK,MAAOU,EAAW,EAClCA,EAAU,OACnB,CAAC,CACH,CAEA,eAAsBC,EACpBjB,EACAW,EACmB,CAEnB,MAAMC,EAAK,EADK,MAAMX,EAA6BD,CAAU,GACzC,SAASW,CAAM,EACnC,OAAOD,EAAgBV,EAAYW,EAAQC,CAAE,CAC/C,CAEA,eAAsBM,EACpBlB,EACAW,EACkB,CAElB,OADa,MAAMV,EAA6BD,CAAU,GAC9C,SAASW,CAAM,CAC7B"}
|
package/dist/api/favorites.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
export declare function getFavoritedUnitsForProperty(propertyId: string | number): Promise<string[]>;
|
|
2
|
-
export declare function setFavoriteUnit(propertyId: string | number, unitId: string, on: boolean): Promise<string[]>;
|
|
3
|
-
export declare function toggleFavoriteUnit(propertyId: string | number, unitId: string): Promise<string[]>;
|
|
4
|
-
export declare function isUnitFavorited(propertyId: string | number, unitId: string): Promise<boolean>;
|
package/dist/api/favorites.mjs
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { getDB as d } from "../db.mjs";
|
|
2
|
-
import { ensureUser as v } from "./users.mjs";
|
|
3
|
-
import { FavoritesSchema as c } from "../schema.mjs";
|
|
4
|
-
const w = (n, t) => `favorites:${n}:${t}`;
|
|
5
|
-
async function l(n) {
|
|
6
|
-
const t = await d(), { uuid: s } = await v(), e = w(s, String(n)), o = await t.kv.get(e), a = o ? c.safeParse(o.value) : null;
|
|
7
|
-
return a != null && a.success ? a.data.unitIds : [];
|
|
8
|
-
}
|
|
9
|
-
async function S(n, t, s) {
|
|
10
|
-
const e = await d(), { uuid: o } = await v(), a = w(o, String(n));
|
|
11
|
-
return e.transaction("rw", e.kv, async () => {
|
|
12
|
-
const r = await e.kv.get(a), f = r && c.safeParse(r.value).success ? r.value : { unitIds: [], updatedAt: (/* @__PURE__ */ new Date()).toISOString() }, i = new Set(f.unitIds);
|
|
13
|
-
s ? i.add(t) : i.delete(t);
|
|
14
|
-
const g = {
|
|
15
|
-
unitIds: [...i],
|
|
16
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
17
|
-
}, u = c.parse(g);
|
|
18
|
-
return await e.kv.put({ key: a, value: u }), u.unitIds;
|
|
19
|
-
});
|
|
20
|
-
}
|
|
21
|
-
async function F(n, t) {
|
|
22
|
-
const e = !(await l(n)).includes(t);
|
|
23
|
-
return S(n, t, e);
|
|
24
|
-
}
|
|
25
|
-
async function p(n, t) {
|
|
26
|
-
return (await l(n)).includes(t);
|
|
27
|
-
}
|
|
28
|
-
export {
|
|
29
|
-
l as getFavoritedUnitsForProperty,
|
|
30
|
-
p as isUnitFavorited,
|
|
31
|
-
S as setFavoriteUnit,
|
|
32
|
-
F as toggleFavoriteUnit
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=favorites.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"favorites.mjs","sources":["../../src/api/favorites.ts"],"sourcesContent":["// src/api/favourites.ts\nimport { getDB } from \"../db\";\nimport { ensureUser } from \"./users\";\nimport { FavoritesSchema } from \"../schema\";\n\nconst keyFor = (userId: string, propertyId: string) =>\n `favorites:${userId}:${propertyId}`;\n\nexport async function getFavoritedUnitsForProperty(\n propertyId: string | number,\n): Promise<string[]> {\n const db = await getDB();\n const { uuid } = await ensureUser();\n const key = keyFor(uuid, String(propertyId));\n const row = await db.kv.get(key);\n const parsed = row ? FavoritesSchema.safeParse(row.value) : null;\n return parsed?.success ? parsed.data.unitIds : [];\n}\n\nexport async function setFavoriteUnit(\n propertyId: string | number,\n unitId: string,\n on: boolean,\n): Promise<string[]> {\n const db = await getDB();\n const { uuid } = await ensureUser();\n const key = keyFor(uuid, String(propertyId));\n\n return db.transaction(\"rw\", db.kv, async () => {\n const row = await db.kv.get(key);\n const current =\n row && FavoritesSchema.safeParse(row.value).success\n ? (row!.value as any)\n : { unitIds: [] as string[], updatedAt: new Date().toISOString() };\n\n const nextSet = new Set<string>(current.unitIds);\n on ? nextSet.add(unitId) : nextSet.delete(unitId);\n\n const next = {\n unitIds: [...nextSet],\n updatedAt: new Date().toISOString(),\n };\n const validated = FavoritesSchema.parse(next);\n await db.kv.put({ key, value: validated });\n return validated.unitIds;\n });\n}\n\nexport async function toggleFavoriteUnit(\n propertyId: string | number,\n unitId: string,\n): Promise<string[]> {\n const current = await getFavoritedUnitsForProperty(propertyId);\n const on = !current.includes(unitId);\n return setFavoriteUnit(propertyId, unitId, on);\n}\n\nexport async function isUnitFavorited(\n propertyId: string | number,\n unitId: string,\n): Promise<boolean> {\n const list = await getFavoritedUnitsForProperty(propertyId);\n return list.includes(unitId);\n}\n"],"names":["keyFor","userId","propertyId","getFavoritedUnitsForProperty","db","getDB","uuid","ensureUser","key","row","parsed","FavoritesSchema","setFavoriteUnit","unitId","on","current","nextSet","next","validated","toggleFavoriteUnit","isUnitFavorited"],"mappings":";;;AAKA,MAAMA,IAAS,CAACC,GAAgBC,MAC9B,aAAaD,CAAM,IAAIC,CAAU;AAEnC,eAAsBC,EACpBD,GACmB;AACnB,QAAME,IAAK,MAAMC,EAAA,GACX,EAAE,MAAAC,MAAS,MAAMC,EAAA,GACjBC,IAAMR,EAAOM,GAAM,OAAOJ,CAAU,CAAC,GACrCO,IAAM,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