All files / apps/wp-editor/server/adapters store.ts

92.37% Statements 109/118
86.11% Branches 31/36
97.82% Functions 45/46
96% Lines 96/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252                                  2x 2704x 2150x   432x   2206x 3518x 2109x         2x 326x   2x 1734x 1734x   462x       2x 1142x   1142x     2x 410x 410x       2x       2x 35x 2306x   2305x   35x 1751x   1750x     35x 296x   296x   296x           35x 297x 296x   296x   296x                   35x     73x           4x     59x 59x   34x 5x 34x     59x       139x     85x     46x 46x       48x 48x   48x           47x   47x   47x 3x 44x       83x     96x                     18x 18x 8x   18x   1x 8x     18x             184x 27x 244x   92x   243x     92x 139x     139x         2x 3x 3x   3x   1x       2x 3x 3x             2x 4x   4x   4x 5x 5x           5x   2x   3x     3x   3x 3x 2x           1x      
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { isMainThread } from "node:worker_threads";
import type { BaseMeta } from "../../shared/types/BaseMeta.ts";
import type { Changeset } from "../../shared/types/Changeset.ts";
import type { Item } from "../../shared/types/Item.ts";
import type { ItemKey } from "../../shared/types/ItemKey.ts";
import type { ItemState } from "../../shared/types/ItemState.ts";
import type { Proposal } from "../../shared/types/Proposal.ts";
import type { RunReport } from "../../shared/types/RunReport.ts";
import type { Settings } from "../../shared/types/Settings.ts";
import type { Snapshot } from "../../shared/types/Snapshot.ts";
import { DEFAULT_SETTINGS } from "../../shared/constants.ts";
import { parseKey } from "../utils/itemKey.ts";
import { Refusal } from "../../shared/refusal.ts";
 
const sortKeys = (value: unknown): unknown => {
    if (Array.isArray(value)) return value.map(sortKeys);
    if (value === null || typeof value !== "object") return value;
 
    return Object.fromEntries(
        Object.entries(value)
            .filter(([, entry]) => entry !== undefined)
            .sort(([a], [b]) => a.localeCompare(b))
            .map(([key, entry]) => [key, sortKeys(entry)]),
    );
};
 
/** Stable formatting, so the store diffs cleanly when it is a git repo. */
export const stableJson = (value: unknown): string =>
    `${JSON.stringify(sortKeys(value), null, 2)}\n`;
 
const readText = async (path: string): Promise<string | null> => {
    try {
        return await readFile(path, "utf8");
    } catch {
        return null;
    }
};
 
const readJson = async <T>(path: string): Promise<T | null> => {
    const text = await readText(path);
 
    return text === null ? null : (JSON.parse(text) as T);
};
 
const write = async (path: string, text: string): Promise<void> => {
    await mkdir(dirname(path), { recursive: true });
    await writeFile(path, text, "utf8");
};
 
// Ids and keys arrive as route params, so anything else could walk out of the store.
const CHANGESET_ID = /^[\w-]+$/;
 
export type Store = ReturnType<typeof createStore>;
 
export const createStore = (root: string) => {
    const changesetDir = (id: string) => {
        if (!CHANGESET_ID.test(id)) throw new Refusal(`"${id}" is not a changeset id.`);
 
        return join(root, "changesets", id);
    };
    const file = (id: string, kind: "base" | "proposed" | "state", key: ItemKey, ext: string) => {
        if (!parseKey(key)) throw new Refusal(`"${key}" is not a <posts|pages>-<id> key.`);
 
        return join(changesetDir(id), kind, `${key}.${ext}`);
    };
 
    const readProposal = async (id: string, key: ItemKey): Promise<Proposal | null> => {
        const content = await readText(file(id, "proposed", key, "html"));
 
        Iif (content === null) return null;
 
        return {
            content,
            ...(await readJson<Omit<Proposal, "content">>(file(id, "proposed", key, "json"))),
        };
    };
 
    const readItem = async (id: string, key: ItemKey): Promise<Item | undefined> => {
        const content = await readText(file(id, "base", key, "html"));
        const meta = await readJson<BaseMeta>(file(id, "base", key, "json"));
 
        Iif (content === null || meta === null) return undefined;
 
        return {
            key,
            base: { ...meta, content },
            proposal: await readProposal(id, key),
            state: (await readJson<ItemState>(file(id, "state", key, "json"))) ?? {
                level: "unreviewed",
            },
        };
    };
 
    return {
        root,
 
        readSettings: async (): Promise<Settings> => ({
            ...DEFAULT_SETTINGS,
            ...(await readJson<Partial<Settings>>(join(root, "settings.json"))),
        }),
 
        writeSettings: (settings: Settings) =>
            write(join(root, "settings.json"), stableJson(settings)),
 
        listChangesets: async (): Promise<Changeset[]> => {
            const ids = await readdir(join(root, "changesets")).catch(() => []);
            const all = await Promise.all(
                ids
                    .filter((id) => CHANGESET_ID.test(id))
                    .sort((a, b) => a.localeCompare(b))
                    .map((id) => readJson<Changeset>(join(changesetDir(id), "changeset.json"))),
            );
 
            return all.filter((changeset) => changeset !== null);
        },
 
        readChangeset: (id: string) =>
            readJson<Changeset>(join(changesetDir(id), "changeset.json")),
 
        writeChangeset: (changeset: Changeset) =>
            write(join(changesetDir(changeset.id), "changeset.json"), stableJson(changeset)),
 
        writeBase: async (id: string, key: ItemKey, { content, ...meta }: Snapshot & BaseMeta) => {
            await write(file(id, "base", key, "html"), content);
            await write(file(id, "base", key, "json"), stableJson(meta));
        },
 
        writeProposal: async (id: string, key: ItemKey, proposal: Proposal | null) => {
            const html = file(id, "proposed", key, "html");
            const json = file(id, "proposed", key, "json");
 
            Iif (proposal === null) {
                await rm(html, { force: true });
                await rm(json, { force: true });
                return;
            }
 
            const { content, ...fields } = proposal;
 
            await write(html, content);
 
            if (Object.values<string | undefined>(fields).some((value) => value !== undefined)) {
                await write(json, stableJson(fields));
            } else await rm(json, { force: true });
        },
 
        writeState: (id: string, key: ItemKey, state: ItemState) =>
            write(file(id, "state", key, "json"), stableJson(state)),
 
        writeRun: (id: string, report: RunReport) =>
            write(
                join(
                    changesetDir(id),
                    "runs",
                    `${report.at.replace(/[:.]/g, "-")}-${report.kind}.json`,
                ),
                stableJson(report),
            ),
 
        /** Newest first. */
        listRuns: async (id: string): Promise<RunReport[]> => {
            const dir = join(changesetDir(id), "runs");
            const names = (await readdir(dir).catch(() => [])).filter((name) =>
                name.endsWith(".json"),
            );
            const runs = await Promise.all(
                [...names]
                    .sort((a, b) => b.localeCompare(a))
                    .map((name) => readJson<RunReport>(join(dir, name))),
            );
 
            return runs.filter((run) => run !== null);
        },
 
        readItem,
 
        /** Every item with a proposal or a recorded state; keys Claude left unchanged are skipped. */
        readItems: async (id: string): Promise<Item[]> => {
            const names = async (kind: "proposed" | "state") =>
                (await readdir(join(changesetDir(id), kind)).catch(() => [])).filter((name) =>
                    name.endsWith(kind === "proposed" ? ".html" : ".json"),
                );
            const keys = new Set(
                [...(await names("proposed")), ...(await names("state"))].map(
                    (name) => name.replace(/\.(?:html|json)$/, "") as ItemKey,
                ),
            );
            const items = await Promise.all(
                [...keys].sort((a, b) => a.localeCompare(b)).map((key) => readItem(id, key)),
            );
 
            return items.filter((item) => item !== undefined);
        },
    };
};
 
const isAlive = (pid: number): boolean => {
    try {
        process.kill(pid, 0);
 
        return true;
    } catch (error) {
        return (error as NodeJS.ErrnoException).code === "EPERM";
    }
};
 
const readHolder = (path: string): { pid: number; startedAt: string } | null => {
    try {
        return JSON.parse(readFileSync(path, "utf8")) as { pid: number; startedAt: string };
    } catch {
        return null;
    }
};
 
/** Claims `root` for this process, refusing while another live process holds it. */
export const lockStore = (root: string): void => {
    const path = join(root, ".server.lock");
 
    mkdirSync(root, { recursive: true });
 
    for (;;) {
        try {
            writeFileSync(
                path,
                stableJson({ pid: process.pid, startedAt: new Date().toISOString() }),
                { flag: "wx" },
            );
            // Nuxt dev reloads Nitro in a worker of the same process, so only the process may release.
            if (isMainThread) process.once("exit", () => rmSync(path, { force: true }));
 
            return;
        } catch (error) {
            Iif ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
        }
 
        const holder = readHolder(path);
 
        Iif (holder?.pid === process.pid) return;
        if (holder && isAlive(holder.pid)) {
            throw new Refusal(
                `Another server (pid ${holder.pid}, started ${holder.startedAt}) is using ` +
                    `${root}; stop it first, or delete ${path} if it is gone.`,
            );
        }
 
        rmSync(path, { force: true });
    }
};