DSH-Arch-Setup/plugins/dsh-touched-git/lib/mutation-store.js
Шурупов Илья Викторович cf9443753e Add one-command Arch DSH setup
Package the portable DSH profiles, local plugins, desktop integration, Firefox wrapper, and ownership-aware installer lifecycle. Bundle checksum-pinned OpenVSCode, editor extensions, translation assets, and cloudflared so unreliable upstream artifact downloads cannot break a clean installation.
2026-09-12 19:13:36 +03:00

60 lines
2.2 KiB
JavaScript

import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
import { dirname, isAbsolute } from 'node:path'
export class MutationStore {
constructor(filePath) {
this.filePath = filePath
this.sessions = new Map()
this.loadError = null
this.ready = this.load().catch(error => { this.loadError = error })
this.pendingWrite = Promise.resolve()
}
async load() {
let content
try {
content = await readFile(this.filePath, 'utf8')
} catch (error) {
if (error.code === 'ENOENT') return
throw error
}
const sessions = JSON.parse(content)
if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) throw new Error('Invalid mutation record store.')
for (const [sessionId, entries] of Object.entries(sessions)) {
if (!Array.isArray(entries)) throw new Error('Invalid mutation record list.')
const records = new Map()
for (const entry of entries) {
if (!entry || typeof entry.callId !== 'string' || !isAbsolute(entry.filePath || '')) throw new Error('Invalid mutation record.')
records.set(entry.callId, entry)
}
this.sessions.set(sessionId, records)
}
}
async get(sessionId, callId) {
await this.ready
if (this.loadError) throw this.loadError
return this.sessions.get(sessionId)?.get(callId) || null
}
async record(mutation) {
await this.ready
if (this.loadError) throw this.loadError
let records = this.sessions.get(mutation.sessionId)
if (!records) {
records = new Map()
this.sessions.set(mutation.sessionId, records)
}
records.set(mutation.callId, { ...mutation, recordedAt: new Date().toISOString() })
this.pendingWrite = this.pendingWrite.catch(() => {}).then(() => this.persist())
await this.pendingWrite
}
async persist() {
await mkdir(dirname(this.filePath), { recursive: true, mode: 0o700 })
const data = Object.fromEntries([...this.sessions].map(([sessionId, records]) => [sessionId, [...records.values()]]))
const temporaryPath = `${this.filePath}.tmp-${process.pid}`
await writeFile(temporaryPath, `${JSON.stringify(data)}\n`, { mode: 0o600 })
await rename(temporaryPath, this.filePath)
}
}