File size: 5,504 Bytes
489b6e2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
export type StoredUser = {
id: string;
name: string;
email: string;
passwordHash: string;
emailVerified: boolean;
createdAt: string;
};
export type StoredBooking = {
id: string;
userId: string;
campsiteId: string;
siteId?: string;
checkIn: string;
checkOut: string;
guests: number;
adults?: number;
children?: number;
pets?: number;
subtotal: number;
serviceFee: number;
total: number;
status: "confirmed" | "requested" | "cancelled";
paymentMode: "simulation" | "stripe_test";
paymentProvider: "local_test" | "stripe";
paymentIntentId: string;
paymentStatus: "succeeded" | "requires_capture";
currency: "usd";
idempotencyKey?: string;
createdAt: string;
};
export type StoredBookingEvent = {
id: string;
bookingId: string;
userId: string;
type: "payment_confirmed" | "booking_created" | "booking_idempotent_replayed" | "booking_cancelled" | "payment_refund_simulated";
message: string;
metadata: Record<string, string | number | boolean>;
createdAt: string;
};
export type StoredHostListing = {
id: string;
ownerId: string;
title: string;
location: string;
type: "Tent" | "RV" | "Cabin" | "Glamping";
price: number;
description: string;
accessInstructions: string;
rules: string;
minimumNights: number;
checkInWindow: string;
availabilityWindow: string;
cancellationPolicy: "Flexible" | "Moderate" | "Strict";
status: "draft" | "submitted" | "published";
createdAt: string;
};
export type StoredHostListingEvent = {
id: string;
listingId: string;
ownerId: string;
type: "host_listing_submitted" | "host_listing_status_changed" | "host_listing_published" | "host_listing_returned_to_draft";
message: string;
metadata: Record<string, string | number | boolean>;
createdAt: string;
};
export type StoredAvailabilityAlert = {
id: string;
userId: string;
park: string;
arrival: string;
departure: string;
status: "active" | "paused" | "cancelled";
createdAt: string;
};
export type StoredMessage = {
id: string;
bookingId: string;
userId: string;
campsiteId: string;
sender: "guest" | "host";
body: string;
createdAt: string;
};
export type StoredAccountSettings = {
userId: string;
tripUpdates: boolean;
hostMessages: boolean;
availabilityAlerts: boolean;
productResearch: boolean;
updatedAt: string;
};
type StoreData = {
users: StoredUser[];
favorites: Array<{ id: string; userId: string; campsiteId: string; createdAt: string }>;
bookings: StoredBooking[];
bookingEvents: StoredBookingEvent[];
hostListings: StoredHostListing[];
hostListingEvents: StoredHostListingEvent[];
availabilityAlerts: StoredAvailabilityAlert[];
messages: StoredMessage[];
accountSettings: StoredAccountSettings[];
};
const emptyStore: StoreData = {
users: [],
favorites: [],
bookings: [],
bookingEvents: [],
hostListings: [],
hostListingEvents: [],
availabilityAlerts: [],
messages: [],
accountSettings: [],
};
type StoreGlobal = typeof globalThis & {
hipcampMemoryStore?: StoreData;
hipcampStoreQueue?: Promise<unknown>;
};
const storeGlobal = globalThis as StoreGlobal;
function storePath() {
return resolve(process.env.PERSISTENT_STORE_PATH || "./data/store.json");
}
export function makeId(prefix: string) {
return `${prefix}_${crypto.randomUUID().replaceAll("-", "")}`;
}
function normalizeStore(parsed: Partial<StoreData> | undefined): StoreData {
return {
users: (parsed?.users ?? []).map((user) => ({ ...user, emailVerified: user.emailVerified === true })),
favorites: parsed?.favorites ?? [],
bookings: parsed?.bookings ?? [],
bookingEvents: parsed?.bookingEvents ?? [],
hostListings: parsed?.hostListings ?? [],
hostListingEvents: parsed?.hostListingEvents ?? [],
availabilityAlerts: parsed?.availabilityAlerts ?? [],
messages: parsed?.messages ?? [],
accountSettings: parsed?.accountSettings ?? [],
};
}
export async function loadStore(): Promise<StoreData> {
try {
const parsed = JSON.parse(await readFile(storePath(), "utf8")) as Partial<StoreData>;
const data = normalizeStore(parsed);
storeGlobal.hipcampMemoryStore = structuredClone(data);
return data;
} catch {
return structuredClone(normalizeStore(storeGlobal.hipcampMemoryStore ?? emptyStore));
}
}
async function saveStoreDirect(data: StoreData) {
storeGlobal.hipcampMemoryStore = structuredClone(data);
const path = storePath();
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.${crypto.randomUUID()}.tmp`;
await writeFile(temporary, JSON.stringify(data, null, 2), "utf8");
await rename(temporary, path);
}
export async function updateStore<T>(operation: (data: StoreData) => Promise<T> | T): Promise<T> {
const run = async () => {
const data = await loadStore();
const result = await operation(data);
try {
await saveStoreDirect(data);
} catch (error) {
storeGlobal.hipcampMemoryStore = structuredClone(data);
const code = (error as NodeJS.ErrnoException).code;
if (code !== "EPERM" && code !== "EROFS" && code !== "ENOSYS") {
throw error;
}
}
return result;
};
const previous = storeGlobal.hipcampStoreQueue ?? Promise.resolve();
const next = previous.then(run, run);
storeGlobal.hipcampStoreQueue = next.catch(() => undefined);
return next;
}
|