Open History to see the last commit
1import type {
2 OrchestrationV2ArchivedShellStreamItem,
3 OrchestrationV2ThreadShellSnapshot,
4 OrchestrationV2ShellStreamItem,
5 OrchestrationV2StoredEvent,
6} from "@t3tools/contracts";
7
8/** Converts a committed event and its resulting shell snapshot into one delta. */
9export function shellStreamItemFromSnapshot(input: {
10 readonly stored: OrchestrationV2StoredEvent;
11 readonly snapshot: OrchestrationV2ThreadShellSnapshot;
12}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
13 const active = input.snapshot.threads.find((thread) => thread.id === input.stored.event.threadId);
14 if (active !== undefined) {
15 return {
16 kind: "thread.updated",
17 sequence: input.stored.sequence,
18 location: "active",
19 thread: active,
20 };
21 }
22
23 const archived = input.snapshot.archivedThreads.find(
24 (thread) => thread.id === input.stored.event.threadId,
25 );
26 if (archived !== undefined) {
27 return {
28 kind: "thread.updated",
29 sequence: input.stored.sequence,
30 location: "archive",
31 thread: archived,
32 };
33 }
34
35 return {
36 kind: "thread.removed",
37 sequence: input.stored.sequence,
38 location:
39 input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null
40 ? "archive"
41 : "active",
42 threadId: input.stored.event.threadId,
43 };
44}
45
46/** Converts a committed event into an archive-only delta when it changes archive membership. */
47export function archivedShellStreamItemFromSnapshot(input: {
48 readonly stored: OrchestrationV2StoredEvent;
49 readonly snapshot: OrchestrationV2ThreadShellSnapshot;
50}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
51 const archived = input.snapshot.archivedThreads.find(
52 (thread) => thread.id === input.stored.event.threadId,
53 );
54 if (archived !== undefined) {
55 return {
56 kind: "thread.updated",
57 sequence: input.stored.sequence,
58 thread: archived,
59 };
60 }
61 if (
62 input.stored.event.type === "thread.unarchived" ||
63 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
64 ) {
65 return {
66 kind: "thread.removed",
67 sequence: input.stored.sequence,
68 threadId: input.stored.event.threadId,
69 };
70 }
71 return null;
72}