The best way to control Claude Code, Codex and more from any computer or phone

main
ts 70 lines 2.21 KB
Raw
1 import * as Clock from "effect/Clock";
2 import * as Effect from "effect/Effect";
3 import * as Schema from "effect/Schema";
4
5 export const makeSubscriptionCleanup = () => {
6 let deadline: number | undefined;
7 return <A, E, R>(effect: Effect.Effect<A, E, R>) =>
8 Effect.gen(function* () {
9 const now = yield* Clock.currentTimeMillis;
10 deadline ??= now + 20_000;
11 const remaining = deadline - now;
12 if (remaining <= 0) {
13 return yield* Effect.die(new Error("Subscription cleanup deadline exceeded"));
14 }
15 return yield* effect.pipe(Effect.timeout(Math.min(5_000, remaining)));
16 }).pipe(Effect.orDie, Effect.interruptible);
17 };
18
19 export const SubscriptionEvent = Schema.fromJsonString(
20 Schema.Struct({
21 type: Schema.String,
22 source: Schema.Struct({ type: Schema.String }),
23 metadata: Schema.Struct({
24 accountId: Schema.String,
25 eventSubscriptionId: Schema.String,
26 eventTimestamp: Schema.String,
27 }),
28 payload: Schema.Struct({
29 id: Schema.optional(Schema.String),
30 name: Schema.optional(Schema.String),
31 }),
32 }),
33 );
34
35 export type SubscriptionEvent = typeof SubscriptionEvent.Type;
36
37 interface SubscriptionEventTarget {
38 source: "images" | "kv" | "r2" | "vectorize";
39 type: string;
40 accountId: string;
41 subscriptionId: string;
42 identity: string;
43 }
44
45 export interface SubscriptionProbe {
46 identity: string;
47 createdAt: number;
48 }
49
50 export const hasReadySubscriptionEvent = (
51 events: readonly SubscriptionEvent[],
52 probes: readonly SubscriptionProbe[],
53 expected: Omit<SubscriptionEventTarget, "identity"> & { readyAfter: number },
54 ) =>
55 probes.some(
56 ({ identity, createdAt }) =>
57 createdAt >= expected.readyAfter &&
58 events.some((event) => matchesSubscriptionEvent(event, { ...expected, identity })),
59 );
60
61 export const matchesSubscriptionEvent = (
62 event: SubscriptionEvent,
63 expected: SubscriptionEventTarget,
64 ) =>
65 event.type === `cf.${expected.source}.${expected.type}` &&
66 event.source.type === expected.source &&
67 event.metadata.accountId === expected.accountId &&
68 event.metadata.eventSubscriptionId === expected.subscriptionId &&
69 event.payload[expected.source === "kv" || expected.source === "images" ? "id" : "name"] ===
70 expected.identity;