@superbright/indexeddb-orm 1.0.30 → 1.0.31
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 +3 -21
- package/dist/stores/store.mjs +72 -120
- 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
|
@@ -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,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,OA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,EAAM,WAAWA,EAAM,iBAAiB,KAAK,OAAO;AAAA,EACvF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,gBAAgBsB,GAAiE;AACrF,UAAMtB,IAAQ,MAAM,KAAK,SAAA,GACnB0B,IAAKJ,KAAc,OAAOtB,EAAM,oBAAoB,OAAOsB,CAAU;AAC3E,WAAOI,IAAK1B,EAAM,WAAW0B,CAAE,KAAK,OAAO;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAA0C;AAC9C,WAAO,KAAK,SAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAA4B;AAEhC,UAAM,KAAK,SAAS,CAAA1B,OAAU,EAAE,GAAGF,GAAyB,GAAGE,IAAQ;AAAA,EACzE;AAEF;AAGO,MAAMkE,IAAQ,IAAInE,EAAA;"}
|
|
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 * 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 // === UTILITY METHODS ===\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","unitId","url","today","formattedDate","updatedViewedUnits","_a","results","filters","apiParams","transformFiltersToUnitsSearchParams","mode","sortBy","name","values","user","vid","safe","_","rest","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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GF,GAAyB,GAAGE,IAAQ;AAAA,EACzE;AAEF;AAGO,MAAMiE,IAAQ,IAAIlE,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","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K,MAAMX,EAA6BD,CAAU,GACzC,SAASW,CAAM;AACnC,SAAOD,EAAgBV,GAAYW,GAAQC,CAAE;AAC/C;AAEA,eAAsBM,EACpBlB,GACAW,GACkB;AAElB,UADa,MAAMV,EAA6BD,CAAU,GAC9C,SAASW,CAAM;AAC7B;"}
|
package/dist/api/properties.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("../storage.cjs"),s=require("../schema.cjs"),c={data:{},propertySlug:null,propertyId:null,hasPreviouslySearched:[]};class l{async getState(){const e=await y.kvGet("property");if(!e)return c;const t={...e,propertyId:e.propertyId==null?null:String(e.propertyId),propertySlug:e.propertySlug??null,hasPreviouslySearched:Array.isArray(e.hasPreviouslySearched)?e.hasPreviouslySearched.map(String):[]},r=s.PropertyStoreDataSchema.safeParse(t);if(r.success)return r.data;const a=Object.entries(t.data??{}).reduce((i,[d,p])=>{const u=s.UserPropertyStateSchema.safeParse(p);return u.success&&(i[d]=u.data),i},{}),n={...c,...t,data:a},o=s.PropertyStoreDataSchema.safeParse(n);return o.success?o.data:c}async setState(e){const t=await this.getState(),r=e(t),a=s.PropertyStoreDataSchema.parse(r);await y.kvSet("property",a)}async setHasPreviouslySearched(e){await this.setState(t=>({...t,hasPreviouslySearched:Array.from(new Set([...t.hasPreviouslySearched,e]))}))}async setTourContactedOn(){await this.setState(e=>{const t=e.propertyId;if(!t)return e;const r=e.data[t];return r?{...e,data:{...e.data,[t]:{...r,tourContactedOn:new Date().toISOString()}}}:e})}async getTourContactedOn(){var r;const e=await this.getState(),t=e.propertyId;return t?((r=e.data[t])==null?void 0:r.tourContactedOn)??null:null}async setQuestionnaireResults(e){await this.setState(t=>{const r=t.propertyId;if(!r)return t;const a=t.data[r];return a?{...t,data:{...t.data,[r]:{...a,questionnaireResults:e}}}:t})}async setTourContactData(e){await this.setState(t=>{const r=t.propertyId;if(!r)return t;const a=t.data[r];return a?{...t,data:{...t.data,[r]:{...a,tourContactData:e}}}:t})}async toggleFavorite(e){await this.setState(t=>{const r=t.propertyId;if(!r)return t;const a=t.data[r];if(!a)return t;const o=a.favoritedUnits.includes(e)?a.favoritedUnits.filter(i=>i!==e):[...a.favoritedUnits,e];return{...t,data:{...t.data,[r]:{...a,favoritedUnits:o}}}})}async markUnitAsViewed(e,t){const r=new Date,a=`${String(r.getMonth()+1).padStart(2,"0")}/${String(r.getDate()).padStart(2,"0")}`;await this.setState(n=>{const o=n.propertyId;if(!o)return n;const i=n.data[o];if(!i)return n;const d=[...i.viewedUnits.filter(p=>p.unitId!==e),{unitId:e,viewedDate:a}];return{...n,data:{...n.data,[o]:{...i,viewedUnits:d}}}}),typeof window<"u"&&window.open(`//${t}`,"_blank")}async getUnitState(e){var a;const t=await this.getState(),r=t.propertyId?t.data[t.propertyId]:null;return{isFavorite:(r==null?void 0:r.favoritedUnits.includes(e))??!1,viewedDate:((a=r==null?void 0:r.viewedUnits.find(n=>n.unitId===e))==null?void 0:a.viewedDate)??""}}async getPropertyData(e){const t=await this.getState(),r=e==null?t.propertyId:String(e);return r?t.data[r]??null:null}async getCurrentProperty(){const e=await this.getState();return e.propertyId?e.data[e.propertyId]??null:null}async getFullState(){return this.getState()}async initializeProperty(e,t){const r=String(e);await this.setState(a=>a.data[r]?{...a,propertyId:r,propertySlug:t}:{...a,propertyId:r,propertySlug:t,data:{...a.data,[r]:{id:r,slug:t,favoritedUnits:[],tourContactedOn:null,viewedUnits:[],questionnaireResults:null,tourContactData:null}}})}}const S=new l;exports.PropertyStore=l;exports.propertyStore=S;
|
|
2
|
-
//# sourceMappingURL=properties.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"properties.cjs","sources":["../../src/api/properties.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport {\n ViewedUnitSchema,\n TourContactDataSchema,\n UserPropertyStateSchema,\n PropertyStoreDataSchema,\n type ViewedUnit,\n type TourContactData,\n type UserPropertyState,\n type PropertyStoreData,\n} from \"../schema\";\n\n// Re-export types for legacy import paths\nexport type { ViewedUnit, TourContactData, UserPropertyState, PropertyStoreData } from \"../schema\";\n\n// Default state\nconst defaultPropertyStoreData: PropertyStoreData = {\n data: {},\n propertySlug: null,\n propertyId: null,\n hasPreviouslySearched: [],\n};\n\n// Core property store API\nexport class PropertyStore {\n private async getState(): Promise<PropertyStoreData> {\n const state = await kvGet<PropertyStoreData>(\"property\");\n if (!state) return defaultPropertyStoreData;\n\n const normalized = {\n ...state,\n propertyId: state.propertyId == null ? null : String(state.propertyId),\n propertySlug: state.propertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = PropertyStoreDataSchema.safeParse(normalized);\n if (parsed.success) return parsed.data;\n\n const sanitizedData = Object.entries(normalized.data ?? {}).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 fallbackState = {\n ...defaultPropertyStoreData,\n ...normalized,\n data: sanitizedData,\n };\n\n const fallbackParsed = PropertyStoreDataSchema.safeParse(fallbackState);\n return fallbackParsed.success ? fallbackParsed.data : defaultPropertyStoreData;\n }\n\n private async setState(updater: (state: PropertyStoreData) => PropertyStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = PropertyStoreDataSchema.parse(newState);\n await kvSet(\"property\", validatedState);\n }\n\n // Basic state operations (legacy direct setters removed in vNext)\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 // Property-specific operations\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.propertyId;\n if (!propertyId) return null;\n\n return state.data[propertyId]?.tourContactedOn ?? null;\n }\n\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n async setTourContactData(data: TourContactData): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n async toggleFavorite(unitId: string): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[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 data: {\n ...state.data,\n [propertyId]: {\n ...property,\n favoritedUnits: updatedFavoritedUnits,\n },\n },\n };\n });\n }\n\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\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.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n // Remove existing entry if it exists\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n // Add updated one\n {\n unitId,\n viewedDate: formattedDate,\n },\n ];\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n // Note: This opens a new window - you might want to handle this in the consuming app\n if (typeof window !== 'undefined') {\n window.open(`//${slug}`, \"_blank\");\n }\n }\n\n // Utility methods for getting specific data\n async getUnitState(unitId: string): Promise<{\n isFavorite: boolean;\n viewedDate: string;\n }> {\n const state = await this.getState();\n const property = state.propertyId ? state.data[state.propertyId] : 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 async getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null> {\n const state = await this.getState();\n const id = propertyId == null ? state.propertyId : String(propertyId);\n return id ? state.data[id] ?? null : null;\n }\n\n async getCurrentProperty(): Promise<UserPropertyState | null> {\n const state = await this.getState();\n return state.propertyId ? state.data[state.propertyId] ?? null : null;\n }\n\n async getFullState(): Promise<PropertyStoreData> {\n return this.getState();\n }\n\n // Initialize property if it doesn't exist\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.data[id]) {\n return { ...state, propertyId: id, propertySlug: slug };\n }\n\n return {\n ...state,\n propertyId: id,\n propertySlug: slug,\n data: {\n ...state.data,\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\n// Export singleton instance\nexport const propertyStore = new PropertyStore();\n"],"names":["defaultPropertyStoreData","PropertyStore","state","kvGet","normalized","parsed","PropertyStoreDataSchema","sanitizedData","acc","key","value","entry","UserPropertyStateSchema","fallbackState","fallbackParsed","updater","currentState","newState","validatedState","kvSet","slug","propertyId","property","_a","results","data","unitId","updatedFavoritedUnits","id","today","formattedDate","updatedViewedUnits","u","propertyStore"],"mappings":"6IAgBMA,EAA8C,CAClD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L,YAAYoB,GAAA,YAAAA,EAAU,eAAe,SAASI,KAAW,GACzD,aACEH,EAAAD,GAAA,YAAAA,EAAU,YAAY,KAAMU,GAAMA,EAAE,SAAWN,KAA/C,YAAAH,EAAwD,aAAc,EAAA,CAE5E,CAEA,MAAM,gBAAgBF,EAAiE,CACrF,MAAMnB,EAAQ,MAAM,KAAK,SAAA,EACnB0B,EAAKP,GAAc,KAAOnB,EAAM,WAAa,OAAOmB,CAAU,EACpE,OAAOO,EAAK1B,EAAM,KAAK0B,CAAE,GAAK,KAAO,IACvC,CAEA,MAAM,oBAAwD,CAC5D,MAAM1B,EAAQ,MAAM,KAAK,SAAA,EACzB,OAAOA,EAAM,WAAaA,EAAM,KAAKA,EAAM,UAAU,GAAK,KAAO,IACnE,CAEA,MAAM,cAA2C,CAC/C,OAAO,KAAK,SAAA,CACd,CAGA,MAAM,mBAAmBmB,EAA6BD,EAA6B,CACjF,MAAMQ,EAAK,OAAOP,CAAU,EAC5B,MAAM,KAAK,SAASnB,GACdA,EAAM,KAAK0B,CAAE,EACR,CAAE,GAAG1B,EAAO,WAAY0B,EAAI,aAAcR,CAAA,EAG5C,CACL,GAAGlB,EACH,WAAY0B,EACZ,aAAcR,EACd,KAAM,CACJ,GAAGlB,EAAM,KACT,CAAC0B,CAAE,EAAG,CACJ,GAAAA,EACA,KAAAR,EACA,eAAgB,CAAA,EAChB,gBAAiB,KACjB,YAAa,CAAA,EACb,qBAAsB,KACtB,gBAAiB,IAAA,CACnB,CACF,CAEH,CACH,CACF,CAGO,MAAMa,EAAgB,IAAIhC"}
|
package/dist/api/properties.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { type TourContactData, type UserPropertyState, type PropertyStoreData } from "../schema";
|
|
2
|
-
export type { ViewedUnit, TourContactData, UserPropertyState, PropertyStoreData } from "../schema";
|
|
3
|
-
export declare class PropertyStore {
|
|
4
|
-
private getState;
|
|
5
|
-
private setState;
|
|
6
|
-
setHasPreviouslySearched(slug: string): Promise<void>;
|
|
7
|
-
setTourContactedOn(): Promise<void>;
|
|
8
|
-
getTourContactedOn(): Promise<string | null>;
|
|
9
|
-
setQuestionnaireResults(results: unknown): Promise<void>;
|
|
10
|
-
setTourContactData(data: TourContactData): Promise<void>;
|
|
11
|
-
toggleFavorite(unitId: string): Promise<void>;
|
|
12
|
-
markUnitAsViewed(unitId: string, slug: string): Promise<void>;
|
|
13
|
-
getUnitState(unitId: string): Promise<{
|
|
14
|
-
isFavorite: boolean;
|
|
15
|
-
viewedDate: string;
|
|
16
|
-
}>;
|
|
17
|
-
getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null>;
|
|
18
|
-
getCurrentProperty(): Promise<UserPropertyState | null>;
|
|
19
|
-
getFullState(): Promise<PropertyStoreData>;
|
|
20
|
-
initializeProperty(propertyId: string | number, slug: string): Promise<void>;
|
|
21
|
-
}
|
|
22
|
-
export declare const propertyStore: PropertyStore;
|
package/dist/api/properties.mjs
DELETED
|
@@ -1,197 +0,0 @@
|
|
|
1
|
-
import { kvGet as y, kvSet as l } from "../storage.mjs";
|
|
2
|
-
import { PropertyStoreDataSchema as p, UserPropertyStateSchema as S } from "../schema.mjs";
|
|
3
|
-
const c = {
|
|
4
|
-
data: {},
|
|
5
|
-
propertySlug: null,
|
|
6
|
-
propertyId: null,
|
|
7
|
-
hasPreviouslySearched: []
|
|
8
|
-
};
|
|
9
|
-
class f {
|
|
10
|
-
async getState() {
|
|
11
|
-
const e = await y("property");
|
|
12
|
-
if (!e) return c;
|
|
13
|
-
const t = {
|
|
14
|
-
...e,
|
|
15
|
-
propertyId: e.propertyId == null ? null : String(e.propertyId),
|
|
16
|
-
propertySlug: e.propertySlug ?? null,
|
|
17
|
-
hasPreviouslySearched: Array.isArray(e.hasPreviouslySearched) ? e.hasPreviouslySearched.map(String) : []
|
|
18
|
-
}, r = p.safeParse(t);
|
|
19
|
-
if (r.success) return r.data;
|
|
20
|
-
const a = Object.entries(t.data ?? {}).reduce((i, [s, d]) => {
|
|
21
|
-
const u = S.safeParse(d);
|
|
22
|
-
return u.success && (i[s] = u.data), i;
|
|
23
|
-
}, {}), n = {
|
|
24
|
-
...c,
|
|
25
|
-
...t,
|
|
26
|
-
data: a
|
|
27
|
-
}, o = p.safeParse(n);
|
|
28
|
-
return o.success ? o.data : c;
|
|
29
|
-
}
|
|
30
|
-
async setState(e) {
|
|
31
|
-
const t = await this.getState(), r = e(t), a = p.parse(r);
|
|
32
|
-
await l("property", a);
|
|
33
|
-
}
|
|
34
|
-
// Basic state operations (legacy direct setters removed in vNext)
|
|
35
|
-
async setHasPreviouslySearched(e) {
|
|
36
|
-
await this.setState((t) => ({
|
|
37
|
-
...t,
|
|
38
|
-
hasPreviouslySearched: Array.from(
|
|
39
|
-
/* @__PURE__ */ new Set([...t.hasPreviouslySearched, e])
|
|
40
|
-
)
|
|
41
|
-
}));
|
|
42
|
-
}
|
|
43
|
-
// Property-specific operations
|
|
44
|
-
async setTourContactedOn() {
|
|
45
|
-
await this.setState((e) => {
|
|
46
|
-
const t = e.propertyId;
|
|
47
|
-
if (!t) return e;
|
|
48
|
-
const r = e.data[t];
|
|
49
|
-
return r ? {
|
|
50
|
-
...e,
|
|
51
|
-
data: {
|
|
52
|
-
...e.data,
|
|
53
|
-
[t]: {
|
|
54
|
-
...r,
|
|
55
|
-
tourContactedOn: (/* @__PURE__ */ new Date()).toISOString()
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
} : e;
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
async getTourContactedOn() {
|
|
62
|
-
var r;
|
|
63
|
-
const e = await this.getState(), t = e.propertyId;
|
|
64
|
-
return t ? ((r = e.data[t]) == null ? void 0 : r.tourContactedOn) ?? null : null;
|
|
65
|
-
}
|
|
66
|
-
async setQuestionnaireResults(e) {
|
|
67
|
-
await this.setState((t) => {
|
|
68
|
-
const r = t.propertyId;
|
|
69
|
-
if (!r) return t;
|
|
70
|
-
const a = t.data[r];
|
|
71
|
-
return a ? {
|
|
72
|
-
...t,
|
|
73
|
-
data: {
|
|
74
|
-
...t.data,
|
|
75
|
-
[r]: {
|
|
76
|
-
...a,
|
|
77
|
-
questionnaireResults: e
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
} : t;
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
async setTourContactData(e) {
|
|
84
|
-
await this.setState((t) => {
|
|
85
|
-
const r = t.propertyId;
|
|
86
|
-
if (!r) return t;
|
|
87
|
-
const a = t.data[r];
|
|
88
|
-
return a ? {
|
|
89
|
-
...t,
|
|
90
|
-
data: {
|
|
91
|
-
...t.data,
|
|
92
|
-
[r]: {
|
|
93
|
-
...a,
|
|
94
|
-
tourContactData: e
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
} : t;
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
async toggleFavorite(e) {
|
|
101
|
-
await this.setState((t) => {
|
|
102
|
-
const r = t.propertyId;
|
|
103
|
-
if (!r) return t;
|
|
104
|
-
const a = t.data[r];
|
|
105
|
-
if (!a) return t;
|
|
106
|
-
const o = a.favoritedUnits.includes(e) ? a.favoritedUnits.filter((i) => i !== e) : [...a.favoritedUnits, e];
|
|
107
|
-
return {
|
|
108
|
-
...t,
|
|
109
|
-
data: {
|
|
110
|
-
...t.data,
|
|
111
|
-
[r]: {
|
|
112
|
-
...a,
|
|
113
|
-
favoritedUnits: o
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
};
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
async markUnitAsViewed(e, t) {
|
|
120
|
-
const r = /* @__PURE__ */ new Date(), a = `${String(r.getMonth() + 1).padStart(
|
|
121
|
-
2,
|
|
122
|
-
"0"
|
|
123
|
-
)}/${String(r.getDate()).padStart(2, "0")}`;
|
|
124
|
-
await this.setState((n) => {
|
|
125
|
-
const o = n.propertyId;
|
|
126
|
-
if (!o) return n;
|
|
127
|
-
const i = n.data[o];
|
|
128
|
-
if (!i) return n;
|
|
129
|
-
const s = [
|
|
130
|
-
// Remove existing entry if it exists
|
|
131
|
-
...i.viewedUnits.filter((d) => d.unitId !== e),
|
|
132
|
-
// Add updated one
|
|
133
|
-
{
|
|
134
|
-
unitId: e,
|
|
135
|
-
viewedDate: a
|
|
136
|
-
}
|
|
137
|
-
];
|
|
138
|
-
return {
|
|
139
|
-
...n,
|
|
140
|
-
data: {
|
|
141
|
-
...n.data,
|
|
142
|
-
[o]: {
|
|
143
|
-
...i,
|
|
144
|
-
viewedUnits: s
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
};
|
|
148
|
-
}), typeof window < "u" && window.open(`//${t}`, "_blank");
|
|
149
|
-
}
|
|
150
|
-
// Utility methods for getting specific data
|
|
151
|
-
async getUnitState(e) {
|
|
152
|
-
var a;
|
|
153
|
-
const t = await this.getState(), r = t.propertyId ? t.data[t.propertyId] : null;
|
|
154
|
-
return {
|
|
155
|
-
isFavorite: (r == null ? void 0 : r.favoritedUnits.includes(e)) ?? !1,
|
|
156
|
-
viewedDate: ((a = r == null ? void 0 : r.viewedUnits.find((n) => n.unitId === e)) == null ? void 0 : a.viewedDate) ?? ""
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
async getPropertyData(e) {
|
|
160
|
-
const t = await this.getState(), r = e == null ? t.propertyId : String(e);
|
|
161
|
-
return r ? t.data[r] ?? null : null;
|
|
162
|
-
}
|
|
163
|
-
async getCurrentProperty() {
|
|
164
|
-
const e = await this.getState();
|
|
165
|
-
return e.propertyId ? e.data[e.propertyId] ?? null : null;
|
|
166
|
-
}
|
|
167
|
-
async getFullState() {
|
|
168
|
-
return this.getState();
|
|
169
|
-
}
|
|
170
|
-
// Initialize property if it doesn't exist
|
|
171
|
-
async initializeProperty(e, t) {
|
|
172
|
-
const r = String(e);
|
|
173
|
-
await this.setState((a) => a.data[r] ? { ...a, propertyId: r, propertySlug: t } : {
|
|
174
|
-
...a,
|
|
175
|
-
propertyId: r,
|
|
176
|
-
propertySlug: t,
|
|
177
|
-
data: {
|
|
178
|
-
...a.data,
|
|
179
|
-
[r]: {
|
|
180
|
-
id: r,
|
|
181
|
-
slug: t,
|
|
182
|
-
favoritedUnits: [],
|
|
183
|
-
tourContactedOn: null,
|
|
184
|
-
viewedUnits: [],
|
|
185
|
-
questionnaireResults: null,
|
|
186
|
-
tourContactData: null
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
const g = new f();
|
|
193
|
-
export {
|
|
194
|
-
f as PropertyStore,
|
|
195
|
-
g as propertyStore
|
|
196
|
-
};
|
|
197
|
-
//# sourceMappingURL=properties.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"properties.mjs","sources":["../../src/api/properties.ts"],"sourcesContent":["import { kvGet, kvSet } from \"../storage\";\nimport {\n ViewedUnitSchema,\n TourContactDataSchema,\n UserPropertyStateSchema,\n PropertyStoreDataSchema,\n type ViewedUnit,\n type TourContactData,\n type UserPropertyState,\n type PropertyStoreData,\n} from \"../schema\";\n\n// Re-export types for legacy import paths\nexport type { ViewedUnit, TourContactData, UserPropertyState, PropertyStoreData } from \"../schema\";\n\n// Default state\nconst defaultPropertyStoreData: PropertyStoreData = {\n data: {},\n propertySlug: null,\n propertyId: null,\n hasPreviouslySearched: [],\n};\n\n// Core property store API\nexport class PropertyStore {\n private async getState(): Promise<PropertyStoreData> {\n const state = await kvGet<PropertyStoreData>(\"property\");\n if (!state) return defaultPropertyStoreData;\n\n const normalized = {\n ...state,\n propertyId: state.propertyId == null ? null : String(state.propertyId),\n propertySlug: state.propertySlug ?? null,\n hasPreviouslySearched: Array.isArray(state.hasPreviouslySearched)\n ? state.hasPreviouslySearched.map(String)\n : [],\n };\n\n const parsed = PropertyStoreDataSchema.safeParse(normalized);\n if (parsed.success) return parsed.data;\n\n const sanitizedData = Object.entries(normalized.data ?? {}).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 fallbackState = {\n ...defaultPropertyStoreData,\n ...normalized,\n data: sanitizedData,\n };\n\n const fallbackParsed = PropertyStoreDataSchema.safeParse(fallbackState);\n return fallbackParsed.success ? fallbackParsed.data : defaultPropertyStoreData;\n }\n\n private async setState(updater: (state: PropertyStoreData) => PropertyStoreData): Promise<void> {\n const currentState = await this.getState();\n const newState = updater(currentState);\n const validatedState = PropertyStoreDataSchema.parse(newState);\n await kvSet(\"property\", validatedState);\n }\n\n // Basic state operations (legacy direct setters removed in vNext)\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 // Property-specific operations\n async setTourContactedOn(): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n tourContactedOn: new Date().toISOString(),\n },\n },\n };\n });\n }\n\n async getTourContactedOn(): Promise<string | null> {\n const state = await this.getState();\n const propertyId = state.propertyId;\n if (!propertyId) return null;\n\n return state.data[propertyId]?.tourContactedOn ?? null;\n }\n\n async setQuestionnaireResults(results: unknown): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n questionnaireResults: results,\n },\n },\n };\n });\n }\n\n async setTourContactData(data: TourContactData): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n tourContactData: data,\n },\n },\n };\n });\n }\n\n async toggleFavorite(unitId: string): Promise<void> {\n await this.setState(state => {\n const propertyId = state.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[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 data: {\n ...state.data,\n [propertyId]: {\n ...property,\n favoritedUnits: updatedFavoritedUnits,\n },\n },\n };\n });\n }\n\n async markUnitAsViewed(unitId: string, slug: string): Promise<void> {\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.propertyId;\n if (!propertyId) return state;\n\n const property = state.data[propertyId];\n if (!property) return state;\n\n const updatedViewedUnits = [\n // Remove existing entry if it exists\n ...property.viewedUnits.filter((u) => u.unitId !== unitId),\n // Add updated one\n {\n unitId,\n viewedDate: formattedDate,\n },\n ];\n\n return {\n ...state,\n data: {\n ...state.data,\n [propertyId]: {\n ...property,\n viewedUnits: updatedViewedUnits,\n },\n },\n };\n });\n\n // Note: This opens a new window - you might want to handle this in the consuming app\n if (typeof window !== 'undefined') {\n window.open(`//${slug}`, \"_blank\");\n }\n }\n\n // Utility methods for getting specific data\n async getUnitState(unitId: string): Promise<{\n isFavorite: boolean;\n viewedDate: string;\n }> {\n const state = await this.getState();\n const property = state.propertyId ? state.data[state.propertyId] : 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 async getPropertyData(propertyId?: string | number): Promise<UserPropertyState | null> {\n const state = await this.getState();\n const id = propertyId == null ? state.propertyId : String(propertyId);\n return id ? state.data[id] ?? null : null;\n }\n\n async getCurrentProperty(): Promise<UserPropertyState | null> {\n const state = await this.getState();\n return state.propertyId ? state.data[state.propertyId] ?? null : null;\n }\n\n async getFullState(): Promise<PropertyStoreData> {\n return this.getState();\n }\n\n // Initialize property if it doesn't exist\n async initializeProperty(propertyId: string | number, slug: string): Promise<void> {\n const id = String(propertyId);\n await this.setState(state => {\n if (state.data[id]) {\n return { ...state, propertyId: id, propertySlug: slug };\n }\n\n return {\n ...state,\n propertyId: id,\n propertySlug: slug,\n data: {\n ...state.data,\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\n// Export singleton instance\nexport const propertyStore = new PropertyStore();\n"],"names":["defaultPropertyStoreData","PropertyStore","state","kvGet","normalized","parsed","PropertyStoreDataSchema","sanitizedData","acc","key","value","entry","UserPropertyStateSchema","fallbackState","fallbackParsed","updater","currentState","newState","validatedState","kvSet","slug","propertyId","property","_a","results","data","unitId","updatedFavoritedUnits","id","today","formattedDate","updatedViewedUnits","u","propertyStore"],"mappings":";;AAgBA,MAAMA,IAA8C;AAAA,EAClD,MAAM,CAAA;AAAA,EACN,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,uBAAuB,CAAA;AACzB;AAGO,MAAMC,EAAc;AAAA,EACzB,MAAc,WAAuC;AACnD,UAAMC,IAAQ,MAAMC,EAAyB,UAAU;AACvD,QAAI,CAACD,EAAO,QAAOF;AAEnB,UAAMI,IAAa;AAAA,MACjB,GAAGF;AAAA,MACH,YAAYA,EAAM,cAAc,OAAO,OAAO,OAAOA,EAAM,UAAU;AAAA,MACrE,cAAcA,EAAM,gBAAgB;AAAA,MACpC,uBAAuB,MAAM,QAAQA,EAAM,qBAAqB,IAC5DA,EAAM,sBAAsB,IAAI,MAAM,IACtC,CAAA;AAAA,IAAC,GAGDG,IAASC,EAAwB,UAAUF,CAAU;AAC3D,QAAIC,EAAO,QAAS,QAAOA,EAAO;AAElC,UAAME,IAAgB,OAAO,QAAQH,EAAW,QAAQ,CAAA,CAAE,EAAE,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dist/api/users.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("../db.cjs"),i=require("../schema.cjs"),u="user",d=()=>{var a;return typeof((a=globalThis.crypto)==null?void 0:a.randomUUID)=="function"?globalThis.crypto.randomUUID():(()=>{var t,r;const e=((r=(t=globalThis.crypto)==null?void 0:t.getRandomValues)==null?void 0:r.call(t,new Uint8Array(16)))??Uint8Array.from({length:16},()=>Math.random()*256|0);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const s=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`})()},c=a=>{var e,s;return((e=a==null?void 0:a.value)==null?void 0:e.useruuid)??((s=a==null?void 0:a.value)==null?void 0:s.uuid)};async function U(a=d){const e=await g.getDB(),s=c(await e.kv.get(u));if(s){const t=await e.users.get(s);if(t)return i.UserSchema.parse(t)}try{return await e.transaction("rw",e.kv,e.users,async()=>{const t=c(await e.kv.get(u));if(t){const o=await e.users.get(t);if(o)return i.UserSchema.parse(o)}const r=a();await e.kv.add({key:u,value:{useruuid:r}});const n=i.UserSchema.parse({uuid:r,createdAt:new Date().toISOString()});return await e.users.add(n),n})}catch(t){if((t==null?void 0:t.name)==="ConstraintError"){const r=c(await e.kv.get(u));if(r){const n=await e.users.get(r);if(n)return i.UserSchema.parse(n)}}throw t}}const l=async a=>(await U(a)).uuid;exports.defaultIdGenerator=d;exports.ensureUser=U;exports.getUserUUID=l;
|
|
2
|
-
//# sourceMappingURL=users.cjs.map
|
package/dist/api/users.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"users.cjs","sources":["../../src/api/users.ts"],"sourcesContent":["import { getDB } from \"../db\";\nimport { UserSchema, type User } from \"../schema\";\n\nconst USER_POINTER_KEY = \"user\";\n\nexport type IdGenerator = () => string;\nexport const defaultIdGenerator: IdGenerator = () =>\n typeof globalThis.crypto?.randomUUID === \"function\"\n ? globalThis.crypto.randomUUID()\n : (() => {\n const b =\n globalThis.crypto?.getRandomValues?.(new Uint8Array(16)) ??\n Uint8Array.from({ length: 16 }, () => (Math.random() * 256) | 0);\n b[6] = (b[6] & 0x0f) | 0x40; // v4\n b[8] = (b[8] & 0x3f) | 0x80; // variant\n const h = [...b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n })();\n\nconst getPointerUuid = (row: any) => row?.value?.useruuid ?? row?.value?.uuid;\n\nexport async function ensureUser(\n gen: IdGenerator = defaultIdGenerator,\n): Promise<User> {\n const db = await getDB();\n\n // Fast path\n const ptrUuid = getPointerUuid(await db.kv.get(USER_POINTER_KEY));\n if (ptrUuid) {\n const existing = await db.users.get(ptrUuid);\n if (existing) return UserSchema.parse(existing);\n }\n\n // Race-safe creation\n try {\n return await db.transaction(\"rw\", db.kv, db.users, async () => {\n const insideUuid = getPointerUuid(await db.kv.get(USER_POINTER_KEY));\n if (insideUuid) {\n const existing = await db.users.get(insideUuid);\n if (existing) return UserSchema.parse(existing);\n }\n\n const uuid = gen();\n await db.kv.add({ key: USER_POINTER_KEY, value: { useruuid: uuid } }); // claim pointer\n const newUser: User = UserSchema.parse({\n uuid,\n createdAt: new Date().toISOString(),\n });\n await db.users.add(newUser);\n return newUser;\n });\n } catch (e: any) {\n if (e?.name === \"ConstraintError\") {\n // Lost the race → read winner\n const uuid = getPointerUuid(await db.kv.get(USER_POINTER_KEY));\n if (uuid) {\n const winner = await db.users.get(uuid);\n if (winner) return UserSchema.parse(winner);\n }\n }\n throw e;\n }\n}\n\nexport const getUserUUID = async (gen?: IdGenerator) =>\n (await ensureUser(gen)).uuid;\n"],"names":["USER_POINTER_KEY","defaultIdGenerator","_a","b","_b","h","x","getPointerUuid","row","ensureUser","gen","db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AAMA,EAAG,GAAIA,EAAG,MAAO,SAAY,CAC7D,MAAMK,EAAaT,EAAe,MAAMI,EAAG,GAAG,IAAIX,CAAgB,CAAC,EACnE,GAAIgB,EAAY,CACd,MAAMF,EAAW,MAAMH,EAAG,MAAM,IAAIK,CAAU,EAC9C,GAAIF,EAAU,OAAOC,aAAW,MAAMD,CAAQ,CAChD,CAEA,MAAMG,EAAOP,EAAA,EACb,MAAMC,EAAG,GAAG,IAAI,CAAE,IAAKX,EAAkB,MAAO,CAAE,SAAUiB,CAAA,EAAQ,EACpE,MAAMC,EAAgBH,EAAAA,WAAW,MAAM,CACrC,KAAAE,EACA,UAAW,IAAI,KAAA,EAAO,YAAA,CAAY,CACnC,EACD,aAAMN,EAAG,MAAM,IAAIO,CAAO,EACnBA,CACT,CAAC,CACH,OAASC,EAAQ,CACf,IAAIA,GAAA,YAAAA,EAAG,QAAS,kBAAmB,CAEjC,MAAMF,EAAOV,EAAe,MAAMI,EAAG,GAAG,IAAIX,CAAgB,CAAC,EAC7D,GAAIiB,EAAM,CACR,MAAMG,EAAS,MAAMT,EAAG,MAAM,IAAIM,CAAI,EACtC,GAAIG,EAAQ,OAAOL,aAAW,MAAMK,CAAM,CAC5C,CACF,CACA,MAAMD,CACR,CACF,CAEO,MAAME,EAAc,MAAOX,IAC/B,MAAMD,EAAWC,CAAG,GAAG"}
|
package/dist/api/users.d.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { type User } from "../schema";
|
|
2
|
-
export type IdGenerator = () => string;
|
|
3
|
-
export declare const defaultIdGenerator: IdGenerator;
|
|
4
|
-
export declare function ensureUser(gen?: IdGenerator): Promise<User>;
|
|
5
|
-
export declare const getUserUUID: (gen?: IdGenerator) => Promise<string>;
|