~james/core

core/web/src/fixtures/pull.ts -rw-r--r-- 14.0 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import type { CommentView } from "#lib/components/comment/comments.ts";
import type { CommitSummary } from "#lib/api/repo.ts";
import type { MirrorFileDiff } from "#lib/api/knotmirror.ts";
import type { Revspec } from "#lib/api/pullRoute.ts";
import type { PipelineSummary } from "#lib/components/repo/types.ts";
import type { Did, Handle } from "@atcute/lexicons/syntax";

export const bobbinUrl = "https://bobbin.example.test";

export const repoDid = "did:plc:core";
export const sourceRepoDid = "did:plc:alice-core";
export const pullRkey = "3mreview";
export const targetBranch = "sv-fe";
export const sourceBranch = "feature/notifs-ui";

export const pullAuthor = { did: "did:plc:bob", handle: "bob.tngl.sh" } satisfies {
	did: Did;
	handle: Handle;
};
export const pullCollaborator = { did: "did:plc:charlie", handle: "charlie.tngl.sh" } satisfies {
	did: Did;
	handle: Handle;
};

export const pullUri = `at://${pullAuthor.did}/sh.tangled.repo.pull/${pullRkey}`;

// the merge base every version was cut from, and the target branch tip
export const base = "ffffffffffffffffffffffffffffffffffffffff";
export const targetHead = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";

const subjects = [
	"mark notifications read on visit",
	"move mention parsing",
	"fan out mention notifications",
	"remove unread toggle",
	"fix notification links",
	"load notifications from deliberi",
	"ingest pull state collections",
	"update hydrant filters",
	"add subscription lookups",
	"watch notification preferences"
];

const oid = (index: number) => index.toString(16).repeat(40).slice(0, 40);

// newest first, the order the pull page's commit rows expect
export const pullCommits: CommitSummary[] = subjects.map((subject, index) => ({
	hash: oid(index),
	shortHash: oid(index).slice(0, 8),
	subject,
	body: "",
	authorName: index % 2 === 0 ? "bob" : "charlie",
	authorEmail: index % 2 === 0 ? "bob@tangled.org" : "charlie@tangled.org",
	when: `2026-08-${String(18 - index).padStart(2, "0")}T12:00:00Z`,
	// the row below it, and the merge base under the oldest one
	parent: index === subjects.length - 1 ? base : oid(index + 1),
	changeId: `I${oid(index).slice(0, 12)}`,
	commentCount: index === 0 ? 1 : index === 3 ? 1 : 0
}));

// each resubmit brought one more commit, so the heads walk the list backwards
export const pullVersions: (Revspec & { createdAt: string })[] = [
	{ base, head: oid(2), createdAt: "2026-08-16T09:00:00Z" },
	{ base, head: oid(1), createdAt: "2026-08-17T15:30:00Z" },
	{ base, head: oid(0), createdAt: "2026-08-18T12:00:00Z" }
];

export const pullHead = pullVersions[pullVersions.length - 1]!.head;

const commentUri = (rkey: string, did: string) => `at://${did}/sh.tangled.feed.comment/${rkey}`;

const pinned = (oid: string) => ({ repo: sourceRepoDid, commit: oid }) as CommentView["embed"];

// two loose comments and two pinned to a commit, spread across the versions so
// the discussion shows its version headers and the range filter has something
// to hide
export const pullComments: CommentView[] = [
	{
		uri: commentUri("3mcone", pullCollaborator.did),
		rkey: "3mcone",
		authorDid: pullCollaborator.did,
		authorHandle: pullCollaborator.handle,
		createdAt: "2026-08-16T18:00:00Z",
		body: "The fan-out looks right, but can the mention parser move first? It reads like two changes."
	},
	{
		uri: commentUri("3mctwo", pullAuthor.did),
		rkey: "3mctwo",
		authorDid: pullAuthor.did,
		authorHandle: pullAuthor.handle,
		createdAt: "2026-08-17T09:10:00Z",
		body: "Split out, and the unread toggle is gone in v1."
	},
	{
		uri: commentUri("3mcthree", pullCollaborator.did),
		rkey: "3mcthree",
		authorDid: pullCollaborator.did,
		authorHandle: pullCollaborator.handle,
		createdAt: "2026-08-17T19:45:00Z",
		body: "This one drops the toggle without touching its preference key.",
		embed: pinned(oid(3))
	},
	{
		uri: commentUri("3mcfour", pullCollaborator.did),
		rkey: "3mcfour",
		authorDid: pullCollaborator.did,
		authorHandle: pullCollaborator.handle,
		createdAt: "2026-08-18T14:20:00Z",
		body: "Marking on visit is the part I wanted. Ship it.",
		embed: pinned(oid(0))
	}
];

// one fixture file: its two snapshots, and the commit row that changed it, so a
// narrowed commit range answers with the files that range really touches
export interface FixtureFile {
	path: string;
	oldPath?: string;
	row: number;
	old?: string;
	next?: string;
	binary?: boolean;
}

export const pullFiles: FixtureFile[] = [
	{
		path: "src/lib/notifications.svelte.ts",
		row: 0,
		old: `import { getContext, setContext } from "svelte";

export const NOTIFICATIONS_KEY = Symbol("notifications");

export const createNotifications = () => {
	let unread = $state(0);

	return {
		get unread() {
			return unread;
		},
		set unread(value: number) {
			unread = value;
		}
	};
};
`,
		next: `import { getContext, setContext } from "svelte";

export const NOTIFICATIONS_KEY = Symbol("notifications");

export const createNotifications = () => {
	let unread = $state(0);
	const visited = new SvelteSet<string>();

	return {
		get unread() {
			return unread;
		},
		markEntityVisited: async (uri: string) => {
			if (visited.has(uri)) return;
			visited.add(uri);
			unread = Math.max(unread - 1, 0);
		}
	};
};
`
	},
	{
		path: "src/lib/components/notifications/NotificationList.svelte",
		row: 2,
		next: `<script lang="ts">
	import NotificationRow from "./NotificationRow.svelte";
	import type { NotificationView } from "#lib/api/notifications.ts";

	interface Props {
		notifications: NotificationView[];
	}

	let { notifications }: Props = $props();
</script>

<ul class="divide-y divide-border-default">
	{#each notifications as notification (notification.uri)}
		<li><NotificationRow {notification} /></li>
	{/each}
</ul>
`
	}
];

const rowOf = (ref: string, commits: CommitSummary[] = pullCommits): number => {
	const row = commits.findIndex((commit) => commit.hash === ref);
	// the merge base and anything unknown sit under the oldest commit
	return row === -1 ? commits.length : row;
};

// rows are newest first, so a file reads as changed at every ref at or above the
// row that changed it
const textAt = (file: FixtureFile, ref: string, commits?: CommitSummary[]): string =>
	(rowOf(ref, commits) <= file.row ? file.next : file.old) ?? "";

const zeroOid = "0".repeat(40);
const blobOid = (path: string, side: "lhs" | "rhs") =>
	`${side === "lhs" ? "a" : "b"}${path.length.toString(16)}`
		.padEnd(40, "1a2b3c4d5e6f7809")
		.slice(0, 40);

const src = (file: FixtureFile, side: "lhs" | "rhs", text: string | undefined) => ({
	path: text === undefined ? "" : side === "lhs" ? (file.oldPath ?? file.path) : file.path,
	oid: text === undefined ? zeroOid : blobOid(file.path, side),
	size: file.binary ? 12_384 : new TextEncoder().encode(text ?? "").length,
	isBinary: !!file.binary,
	isSubmodule: false
});

// the payload carries aligned line numbers only -- pierre diffs the two texts
// itself -- so one hunk over the changed span is all a card needs to size itself
const hunkOf = (oldText: string, newText: string) => {
	const lhs = oldText === "" ? [] : oldText.split("\n");
	const rhs = newText === "" ? [] : newText.split("\n");
	let start = 0;
	while (start < lhs.length && start < rhs.length && lhs[start] === rhs[start]) start++;
	let tail = 0;
	while (
		tail < lhs.length - start &&
		tail < rhs.length - start &&
		lhs[lhs.length - 1 - tail] === rhs[rhs.length - 1 - tail]
	)
		tail++;
	const lhsSpan = lhs.length - tail - start;
	const rhsSpan = rhs.length - tail - start;
	const lines = Array.from({ length: Math.max(lhsSpan, rhsSpan) }, (_, index) => ({
		lhs: index < lhsSpan ? start + index : undefined,
		rhs: index < rhsSpan ? start + index : undefined
	}));
	return {
		lines,
		novelLhs: lines.filter((line) => line.lhs !== undefined).map((line) => line.lhs as number),
		novelRhs: lines.filter((line) => line.rhs !== undefined).map((line) => line.rhs as number)
	};
};

const fileDiff = (
	file: FixtureFile,
	version: Revspec,
	commits?: CommitSummary[]
): MirrorFileDiff => {
	const oldText = file.old === undefined ? undefined : textAt(file, version.base, commits);
	const newText = file.next === undefined ? undefined : textAt(file, version.head, commits);
	return {
		lhsSrc: src(file, "lhs", oldText),
		rhsSrc: src(file, "rhs", newText),
		hasSyntacticChanges: !file.binary,
		hunks: file.binary ? [] : [hunkOf(oldText ?? "", newText ?? "")]
	};
};

// a range is [head row, base row), the same half-open span the commit list uses
const inRange = (file: FixtureFile, version: Revspec, commits?: CommitSummary[]) =>
	file.row >= rowOf(version.head, commits) && file.row < rowOf(version.base, commits);

export type DiffOutcome = "ok" | "empty" | "error" | "pending";
export type SubscriptionState = "none" | "active" | "error";

export interface PullFetchOptions {
	/** the source branch tip; a value past the newest head arms Resubmit */
	sourceHead?: string;
	conflicted?: boolean;
	subscription?: SubscriptionState;
	diff?: DiffOutcome;
	// a whole other pull to answer for, so a story can swap its dataset at the fetch boundary
	dataset?: PullFetchDataset;
	/** the head's pipeline. an approval moves its blocked workflows to running */
	pipeline?: PipelineSummary;
	refuseApproval?: boolean;
}

export interface PullFetchDataset {
	commits: CommitSummary[];
	head: string;
	files: FixtureFile[];
	conflicts?: { filename: string; reason: string }[];
}

const json = (body: unknown) => Response.json(body);
const notFound = () => new Response(null, { status: 404 });
const failed = (message: string) =>
	Response.json({ error: "InternalError", message }, { status: 500 });

const mirrorCommit = (commit: CommitSummary) => ({
	oid: commit.hash,
	message: commit.subject,
	author: { name: commit.authorName, email: commit.authorEmail, when: commit.when },
	committer: { name: commit.authorName, email: commit.authorEmail, when: commit.when },
	parents: commit.parent ? [commit.parent] : [],
	extraHeaders: commit.changeId ? [{ key: "change-id", value: commit.changeId }] : []
});

/**
 * Answers every read the pull page makes: the subscription lookup, the branch
 * and merge-base resolutions, the merge check, the diff payloads and the blob
 * reads behind each file card. Install it before the page mounts -- the page
 * captures `globalThis.fetch` when it builds its clients.
 */
export const mockPullFetch = (options: PullFetchOptions = {}): typeof fetch => {
	let approved = false;
	return (async (input: RequestInfo | URL) => {
		const url = new URL(String(input instanceof Request ? input.url : input), location.href);
		const nsid = url.pathname.replace(/^\/xrpc\//, "");
		const param = (name: string) => url.searchParams.get(name) ?? "";
		const commits = options.dataset?.commits ?? pullCommits;
		const head = options.dataset?.head ?? pullHead;
		const shown = options.dataset?.files ?? pullFiles;

		if (url.pathname.endsWith("/commit-statuses")) {
			const pipeline = options.pipeline;
			if (!pipeline) return json({});
			const workflows = pipeline.workflows.map((workflow) =>
				approved && workflow.status === "blocked"
					? { ...workflow, status: "running" as const }
					: workflow
			);
			return json({ [pipeline.sha]: { ...pipeline, workflows } });
		}

		switch (nsid) {
			case "org.tangled.ci.approvePipeline":
				if (options.refuseApproval) {
					return Response.json(
						{
							error: "PipelineNotBlocked",
							message: "the pipeline has no blocked workflow"
						},
						{ status: 400 }
					);
				}
				approved = true;
				return new Response(null, { status: 200 });

			case "org.tangled.feed.subscription.getForActor":
				switch (options.subscription ?? "none") {
					case "active":
						return json({
							uri: `at://${param("actor")}/org.tangled.feed.subscription/3msub`
						});
					case "error":
						return failed("bobbin is down");
					default:
						return notFound();
				}

			case "org.tangled.temp.git.getRef":
				return json({
					name: param("ref"),
					oid:
						param("ref") === `refs/heads/${sourceBranch}`
							? (options.sourceHead ?? head)
							: targetHead
				});

			case "org.tangled.temp.git.getMergeBase":
				return json({ commit: base });

			case "sh.tangled.git.temp2.mergeCheck":
				return json({
					isConflicted: !!options.conflicted,
					// two files, so a conflict list exercises both the file the diff
					// opens on and one the reader has to be carried to
					conflicts: options.conflicted
						? (options.dataset?.conflicts ?? [
								{
									filename: "src/lib/notifications.svelte.ts",
									reason: "both modified"
								},
								{
									filename:
										"src/lib/components/notifications/NotificationList.svelte",
									reason: "both added"
								}
							])
						: []
				});

			case "org.tangled.temp.git.listCommits":
			case "org.tangled.temp.git.listCommitsByRef":
				return json({ commits: commits.map(mirrorCommit) });

			case "sh.tangled.git.temp2.getDiff":
			case "sh.tangled.git.temp2.getInterdiff": {
				if (options.diff === "pending") return new Promise<Response>(() => {});
				if (options.diff === "error") return failed("knotmirror is unreachable");
				if (options.diff === "empty") return json({ diffs: [] });
				// an interdiff's spans don't map onto one commit range, so it
				// answers with the whole set
				const version =
					nsid === "sh.tangled.git.temp2.getDiff"
						? { base: param("baseCommit"), head: param("headCommit") }
						: { base, head };
				return json({
					diffs: shown
						.filter((file) => inRange(file, version, commits))
						.map((file) => fileDiff(file, version, commits))
				});
			}

			case "org.tangled.temp.git.getEntry": {
				const file = shown.find(
					(entry) => entry.path === param("path") || entry.oldPath === param("path")
				);
				if (!file) return notFound();
				return json({
					name: param("path").split("/").pop(),
					mode: "100644",
					size: file.binary
						? 12_384
						: new TextEncoder().encode(textAt(file, param("ref"), commits)).length
				});
			}

			case "org.tangled.temp.git.getBlob": {
				const file = shown.find(
					(entry) => entry.path === param("path") || entry.oldPath === param("path")
				);
				if (!file) return notFound();
				return new Response(textAt(file, param("ref"), commits));
			}
		}
		return notFound();
	}) as typeof fetch;
};