import { FieldContent, FieldContentType, isTimestampContent, } from "@prismicio/types-internal/lib/content" import type { Timestamp } from "@prismicio/types-internal/lib/customtypes" import { DiffChange, DiffOperation, } from "@prismicio/types-internal/lib/customtypes/diff" import type { NestableMock, Patch } from "../../Mock" import type { MockConfig } from "../../MockConfig" export interface TimestampMockConfig extends MockConfig { start?: Date end?: Date } function formatDate(date: Date): string { return date.toISOString().slice(0, 19) + "Z" } function random(start = new Date(2012, 0, 1), end = new Date()): string { const genDate = new Date( start.getTime() + Math.random() * (end.getTime() - start.getTime()), ) return formatDate(genDate) } export const TimestampMock: NestableMock< Timestamp, FieldContent, TimestampMockConfig > = { generate(_def: Timestamp, config?: TimestampMockConfig): FieldContent { const value = (() => { if (config?.value) return formatDate(config.value) if (config?.start && config?.end) return random(config.start, config.end) return random(new Date(2012, 0, 1), new Date()) })() return { __TYPE__: FieldContentType, type: "Timestamp", value, } }, applyPatch(data: Patch): | { result: FieldContent | undefined } | undefined { if (data.diff.op === DiffOperation.Removed) return { result: undefined } if (data.diff.value.type === "Timestamp") { const patched = this.patch( data.diff, isTimestampContent(data.content) ? data.content : undefined, data.config?.type === "Timestamp" ? data.config : undefined, ) return { result: patched } } return }, patch( diff: DiffChange, _content: FieldContent, config?: TimestampMockConfig, ): FieldContent | undefined { switch (diff.op) { case DiffOperation.Removed: return case DiffOperation.Updated: case DiffOperation.Added: return this.generate(diff.value, config) } }, }