Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

9.0 KB
Raw Blame
import type { CustomSectionType, ResumeData } from "@reactive-resume/schema/resume/data";
import z from "zod";
import { customSectionItemDefinitionByType, sectionTypeSchema } from "@reactive-resume/schema/resume/data";
import { readLegacyDates } from "@reactive-resume/schema/resume/dates";
import { sectionDefaults } from "@reactive-resume/schema/resume/default";
import { generateId } from "@reactive-resume/utils/string";
import { applyResumePatches } from "./patch";

export const resumeFieldTargetSchema = z.strictObject({
	sectionId: z.string(),
	itemId: z.string().optional(),
	roleId: z.string().optional(),
	field: z.string(),
});
const why = z.string().trim().min(1).max(240);
export const resumeEntryTypeSchema = sectionTypeSchema.exclude(["cover-letter"]);

/** Typed structural payloads are validated separately from prose, independent of document language. */
export const resumeChangeSchema = z.discriminatedUnion("kind", [
	z.strictObject({
		kind: z.literal("text"),
		sectionId: z.string().describe("The section the user wants to edit; must match the passage's sectionId."),
		passageId: z.string(),
		text: z
			.string()
			.trim()
			.min(1)
			.max(2_000)
			.describe(
				"Plain text for one paragraph or bullet. No section headings, entry records or lists; use the matching structural operation instead.",
			),
		add: z.boolean().optional(),
		why,
	}),
	z.strictObject({
		kind: z.literal("field"),
		target: resumeFieldTargetSchema,
		before: z.string(),
		value: z.string().max(2_000),
		why,
	}),
	z.strictObject({
		kind: z.literal("entry"),
		sectionId: z.string(),
		type: resumeEntryTypeSchema,
		entryJson: z
			.string()
			.max(20_000)
			.describe(
				"JSON entry object, using the matching entry template from read_resume. IDs are generated by the server.",
			),
		why,
	}),
	z.strictObject({
		kind: z.literal("section"),
		type: resumeEntryTypeSchema,
		title: z.string().trim().min(1).max(120),
		entriesJson: z
			.string()
			.max(40_000)
			.describe(
				"JSON array of entries using the matching entry template. Use publications for Patents. IDs are generated by the server.",
			),
		why,
	}),
]);
export type ResumeChange = z.infer<typeof resumeChangeSchema>;

const pointer = (value: string) => value.replaceAll("~", "~0").replaceAll("/", "~1");

function sectionAt(data: ResumeData, id: string) {
	const builtin = Object.hasOwn(data.sections, id) ? data.sections[id as keyof ResumeData["sections"]] : null;
	if (builtin) {
		if (builtin.hidden) throw new Error("This section is hidden. Show it in Write before asking for changes.");
		return { section: builtin, type: id as CustomSectionType, path: `/sections/${pointer(id)}` };
	}
	const index = data.customSections.findIndex((section) => section.id === id);
	const section = data.customSections[index];
	if (!section) throw new Error("This section no longer exists. Open Write to choose a section.");
	if (section.type === "cover-letter") throw new Error("Create or open cover letters in Documents.");
	if (section.hidden) throw new Error("This section is hidden. Show it in Write before asking for changes.");
	return { section, type: section.type, path: `/customSections/${index}` };
}

function fieldPath(data: ResumeData, target: z.infer<typeof resumeFieldTargetSchema>) {
	const { sectionId, itemId, roleId, field } = target;
	if (
		["__proto__", "prototype", "constructor", "id", "hidden", "description", "content", "date", "period"].includes(
			field,
		)
	)
		throw new Error(
			"Use a text edit for descriptions and the summary. Other unsupported fields can be changed in Write.",
		);
	if (
		sectionId === "basics" &&
		!itemId &&
		!roleId &&
		["name", "headline", "email", "phone", "location"].includes(field)
	)
		return { path: `/basics/${field}`, value: data.basics[field as "name"] };
	if (sectionId === "summary" && !itemId && !roleId && field === "title") {
		if (data.summary.hidden) throw new Error("The summary is hidden. Show it in Write before asking for changes.");
		return { path: "/summary/title", value: data.summary.title };
	}
	const { section, path, type } = sectionAt(data, sectionId);
	if (!itemId && !roleId && field === "title") return { path: `${path}/title`, value: section.title };
	const index = section.items.findIndex((item) => item.id === itemId);
	let entry = section.items[index] as Record<string, unknown> | undefined;
	let entryPath = `${path}/items/${index}`;
	if (entry?.hidden) throw new Error("This entry is hidden. Show it in Write before asking for changes.");
	if (!Object.hasOwn(customSectionItemDefinitionByType[type].schema.shape, field))
		throw new Error("This field doesn't belong in this section. Open Write to choose the matching entry.");
	if (roleId) {
		if (!entry || !Array.isArray(entry.roles)) throw new Error("This role no longer exists. Read the resume again.");
		const roleIndex = entry.roles.findIndex((role: { id: string }) => role.id === roleId);
		entry = entry.roles[roleIndex];
		entryPath += `/roles/${roleIndex}`;
	}
	if (!entry || !Object.hasOwn(entry, field) || typeof entry[field] !== "string")
		throw new Error("This field can't be changed here. Open Write to edit it.");
	return { path: `${entryPath}/${pointer(field)}`, value: entry[field] as string };
}

function preserveNewEntryDates(entry: Record<string, unknown>, locale: string) {
	const dates = entry.dates;
	const text = typeof entry.period === "string" ? entry.period : entry.date;
	// Templates start with empty structured dates; don't let those erase supplied date text during schema sync.
	if (
		typeof text === "string" &&
		text.trim() &&
		dates &&
		typeof dates === "object" &&
		!Array.isArray(dates) &&
		Object.keys(dates).every((key) => ["start", "end", "present", "raw"].includes(key)) &&
		"start" in dates &&
		dates.start === null &&
		"end" in dates &&
		dates.end === null &&
		"present" in dates &&
		dates.present === false &&
		(!("raw" in dates) || dates.raw === "" || dates.raw === undefined)
	)
		return { ...entry, dates: readLegacyDates(text, { locale, single: typeof entry.date === "string" }) };
	return entry;
}

function newEntry(type: CustomSectionType, input: unknown, locale: string) {
	if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Provide an entry's fields.");
	const schema = customSectionItemDefinitionByType[type].schema;
	// Read schemas allow extra fields for historical data; assistant-created records must match their type exactly.
	for (const key of Object.keys(input)) {
		if (!Object.hasOwn(schema.shape, key))
			throw new Error("These fields don't belong in this section. Choose the matching section in Write.");
	}
	const entry = preserveNewEntryDates({ ...input, id: generateId(), hidden: false }, locale);
	if (type === "experience" && Array.isArray(entry.roles))
		entry.roles = entry.roles.map((role: unknown) => {
			if (!role || typeof role !== "object" || Array.isArray(role)) return role;
			const next = preserveNewEntryDates({ ...role, id: generateId() }, locale);
			return next;
		});
	return entry;
}

/** Validated structure changes only; prose belongs to resolveEdits, with stable passage/section IDs. */
export function applyResumeStructureChange(data: ResumeData, change: Exclude<ResumeChange, { kind: "text" }>) {
	if (change.kind === "field") {
		const { path, value } = fieldPath(data, change.target);
		if (value !== change.before) throw new Error("This field changed. Read the resume again before proposing an edit.");
		return applyResumePatches(data, [
			{ op: "test", path, value: change.before },
			{ op: "replace", path, value: change.value },
		]);
	}
	if (change.kind === "entry") {
		const { type, path } = sectionAt(data, change.sectionId);
		if (type !== change.type)
			throw new Error("This entry belongs in a different section. Choose the matching section in Write.");
		const entry = newEntry(type, JSON.parse(change.entryJson), data.metadata.page.locale);
		const changes = [{ op: "add" as const, path: `${path}/items/-`, value: entry }];
		if (!data.metadata.layout.pages.some((page) => [...page.main, ...page.sidebar].includes(change.sectionId))) {
			const pages = structuredClone(data.metadata.layout.pages);
			if (!pages[0]) pages.push({ fullWidth: false, main: [], sidebar: [] });
			pages[0]?.main.push(change.sectionId);
			return applyResumePatches(data, [...changes, { op: "replace", path: "/metadata/layout/pages", value: pages }]);
		}
		return applyResumePatches(data, changes);
	}
	const entries: unknown = JSON.parse(change.entriesJson);
	if (!Array.isArray(entries) || entries.length === 0)
		throw new Error("Provide at least one entry for the new section.");
	const section = {
		...sectionDefaults(""),
		id: generateId(),
		type: change.type,
		title: change.title,
		items: entries.map((entry) => newEntry(change.type, entry, data.metadata.page.locale)),
	};
	const pages = structuredClone(data.metadata.layout.pages);
	if (!pages[0]) pages.push({ fullWidth: false, main: [], sidebar: [] });
	pages[0]?.main.push(section.id);
	return applyResumePatches(data, [
		{ op: "add", path: "/customSections/-", value: section },
		{ op: "replace", path: "/metadata/layout/pages", value: pages },
	]);
}