Open History to see the last commit
1import { z } from "zod";
2import { createHash } from "node:crypto";
3
4export const uuid = z.uuid().transform((s) => s.toLowerCase());
5export const recordSchema = z
6 .object({
7 version: z.literal(1),
8 id: uuid,
9 date: z.number().finite(),
10 event: z.enum([
11 "created",
12 "entry",
13 "textAppended",
14 "textReplaced",
15 "detailsAppended",
16 "state",
17 "titleChanged",
18 "redacted",
19 ]),
20 expedition: z
21 .object({
22 id: uuid,
23 date: z.number().finite(),
24 title: z.string().max(200),
25 })
26 .optional(),
27 entry: z
28 .object({
29 id: uuid,
30 date: z.number().finite(),
31 kind: z.enum(["request", "response", "activity"]),
32 text: z.string().max(500_000),
33 details: z.string().max(500_000),
34 photo: z
35 .string()
36 .regex(/^[a-f0-9-]{36}\.jpg$/i)
37 .optional(),
38 })
39 .optional(),
40 entryID: uuid.optional(),
41 text: z.string().max(500_000).optional(),
42 status: z.string().max(1000).optional(),
43 isRunning: z.boolean().optional(),
44 isFinished: z.boolean().optional(),
45 })
46 .superRefine((r, c) => {
47 const required = (ok: unknown) => {
48 if (!ok) c.addIssue({ code: "custom", message: "Missing event payload" });
49 };
50 if (r.event === "created") required(r.expedition);
51 if (r.event === "entry") required(r.entry);
52 if (["textAppended", "textReplaced", "detailsAppended"].includes(r.event))
53 required(r.entryID && r.text !== undefined);
54 if (r.event === "titleChanged") required(r.text !== undefined);
55 });
56export type JournalRecord = z.infer<typeof recordSchema>;
57export const detailChangeSchema = z.object({
58 sequence: z.number().int().min(1).max(2_000_000_000),
59 id: uuid,
60 date: z.number().finite(),
61 event: z.enum(["entry", "detailsAppended"]),
62 entryID: uuid,
63 text: z.string().min(1).max(500_000),
64});
65export type DetailChange = z.infer<typeof detailChangeSchema>;
66export const batchSchema = z.object({
67 start: z.number().int().min(1).max(2_000_000_000),
68 records: z.array(recordSchema).min(1).max(100),
69});
70export const commandSchema = z
71 .object({
72 id: uuid,
73 deviceID: uuid,
74 expeditionID: uuid.optional(),
75 kind: z.enum(["start", "continue", "stop", "finish"]),
76 prompt: z.string().trim().max(20_000).default(""),
77 ttlMinutes: z.number().int().min(1).max(1440).default(60),
78 })
79 .superRefine((x, c) => {
80 if (["continue", "finish", "stop"].includes(x.kind) && !x.expeditionID)
81 c.addIssue({ code: "custom", message: "Choose the target expedition" });
82 if (["start", "continue"].includes(x.kind) && !x.prompt)
83 c.addIssue({ code: "custom", message: "Enter a direction" });
84 });
85export function digest(value: unknown) {
86 return createHash("sha256").update(JSON.stringify(value)).digest("hex");
87}
88export class APIError extends Error {
89 constructor(
90 public status: number,
91 message: string,
92 ) {
93 super(message);
94 }
95}