@catamorphic/fastify-plugin 0.0.0-stage → 0.1.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/README.md +143 -2
- package/dist/app-presentation-tools.d.ts +4 -0
- package/dist/app-presentation-tools.d.ts.map +1 -0
- package/dist/app.d.ts +27 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/chunk-baagvvm3.js +164 -0
- package/dist/chunk-baagvvm3.js.map +10 -0
- package/dist/http-identity.d.ts +52 -0
- package/dist/http-identity.d.ts.map +1 -0
- package/dist/hung-up.d.ts +7 -0
- package/dist/hung-up.d.ts.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10884 -0
- package/dist/index.js.map +56 -0
- package/dist/mcp-shared.d.ts +117 -0
- package/dist/mcp-shared.d.ts.map +1 -0
- package/dist/mcp.d.ts +6 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +13 -0
- package/dist/mcp.js.map +9 -0
- package/dist/plugin.d.ts +113 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/project-capabilities.d.ts +25 -0
- package/dist/project-capabilities.d.ts.map +1 -0
- package/dist/project-mcp-program.d.ts +15 -0
- package/dist/project-mcp-program.d.ts.map +1 -0
- package/dist/project-mcp-surface.d.ts +16 -0
- package/dist/project-mcp-surface.d.ts.map +1 -0
- package/dist/request-logging.d.ts +18 -0
- package/dist/request-logging.d.ts.map +1 -0
- package/dist/routes/agent-capabilities.d.ts +4 -0
- package/dist/routes/agent-capabilities.d.ts.map +1 -0
- package/dist/routes/agent.d.ts +4 -0
- package/dist/routes/agent.d.ts.map +1 -0
- package/dist/routes/apps-mcp.d.ts +4 -0
- package/dist/routes/apps-mcp.d.ts.map +1 -0
- package/dist/routes/apps.d.ts +12 -0
- package/dist/routes/apps.d.ts.map +1 -0
- package/dist/routes/client-runners.d.ts +11 -0
- package/dist/routes/client-runners.d.ts.map +1 -0
- package/dist/routes/code-hosts.d.ts +11 -0
- package/dist/routes/code-hosts.d.ts.map +1 -0
- package/dist/routes/connection-mcp.d.ts +10 -0
- package/dist/routes/connection-mcp.d.ts.map +1 -0
- package/dist/routes/connections.d.ts +4 -0
- package/dist/routes/connections.d.ts.map +1 -0
- package/dist/routes/documents.d.ts +11 -0
- package/dist/routes/documents.d.ts.map +1 -0
- package/dist/routes/environments.d.ts +4 -0
- package/dist/routes/environments.d.ts.map +1 -0
- package/dist/routes/git-gateway.d.ts +21 -0
- package/dist/routes/git-gateway.d.ts.map +1 -0
- package/dist/routes/http-gateway.d.ts +13 -0
- package/dist/routes/http-gateway.d.ts.map +1 -0
- package/dist/routes/me.d.ts +12 -0
- package/dist/routes/me.d.ts.map +1 -0
- package/dist/routes/memberships.d.ts +12 -0
- package/dist/routes/memberships.d.ts.map +1 -0
- package/dist/routes/model-gateway.d.ts +12 -0
- package/dist/routes/model-gateway.d.ts.map +1 -0
- package/dist/routes/notifications.d.ts +4 -0
- package/dist/routes/notifications.d.ts.map +1 -0
- package/dist/routes/parse.d.ts +5 -0
- package/dist/routes/parse.d.ts.map +1 -0
- package/dist/routes/personal-environment.d.ts +13 -0
- package/dist/routes/personal-environment.d.ts.map +1 -0
- package/dist/routes/plugins.d.ts +4 -0
- package/dist/routes/plugins.d.ts.map +1 -0
- package/dist/routes/project-mcp.d.ts +25 -0
- package/dist/routes/project-mcp.d.ts.map +1 -0
- package/dist/routes/projects.d.ts +4 -0
- package/dist/routes/projects.d.ts.map +1 -0
- package/dist/routes/publications.d.ts +15 -0
- package/dist/routes/publications.d.ts.map +1 -0
- package/dist/routes/run-errors.d.ts +8 -0
- package/dist/routes/run-errors.d.ts.map +1 -0
- package/dist/routes/runs.d.ts +4 -0
- package/dist/routes/runs.d.ts.map +1 -0
- package/dist/routes/session-artifacts.d.ts +27 -0
- package/dist/routes/session-artifacts.d.ts.map +1 -0
- package/dist/routes/session-mailboxes.d.ts +4 -0
- package/dist/routes/session-mailboxes.d.ts.map +1 -0
- package/dist/routes/session-previews.d.ts +40 -0
- package/dist/routes/session-previews.d.ts.map +1 -0
- package/dist/routes/session-terminals.d.ts +15 -0
- package/dist/routes/session-terminals.d.ts.map +1 -0
- package/dist/routes/triggers.d.ts +20 -0
- package/dist/routes/triggers.d.ts.map +1 -0
- package/dist/routes/watchers.d.ts +4 -0
- package/dist/routes/watchers.d.ts.map +1 -0
- package/dist/routes/webhooks.d.ts +11 -0
- package/dist/routes/webhooks.d.ts.map +1 -0
- package/dist/routes/workflow-enablements.d.ts +4 -0
- package/dist/routes/workflow-enablements.d.ts.map +1 -0
- package/dist/routes/workflows.d.ts +4 -0
- package/dist/routes/workflows.d.ts.map +1 -0
- package/dist/schemas.d.ts +17776 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/session-artifact-tools.d.ts +5 -0
- package/dist/session-artifact-tools.d.ts.map +1 -0
- package/dist/session-event-stream.d.ts +45 -0
- package/dist/session-event-stream.d.ts.map +1 -0
- package/dist/spa.d.ts +24 -0
- package/dist/spa.d.ts.map +1 -0
- package/dist/telemetry.d.ts +4 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/package.json +73 -4
- package/src/app-presentation-tools.ts +46 -0
- package/src/app.ts +115 -0
- package/src/http-identity.ts +145 -0
- package/src/hung-up.ts +13 -0
- package/src/index.ts +25 -0
- package/src/mcp-shared.ts +331 -0
- package/src/mcp.ts +10 -0
- package/src/plugin.ts +332 -0
- package/src/project-capabilities.ts +153 -0
- package/src/project-mcp-program.ts +607 -0
- package/src/project-mcp-surface.ts +881 -0
- package/src/request-logging.ts +47 -0
- package/src/routes/agent-capabilities.ts +109 -0
- package/src/routes/agent.ts +1566 -0
- package/src/routes/apps-mcp.ts +303 -0
- package/src/routes/apps.ts +692 -0
- package/src/routes/client-runners.ts +251 -0
- package/src/routes/code-hosts.ts +247 -0
- package/src/routes/connection-mcp.ts +135 -0
- package/src/routes/connections.ts +494 -0
- package/src/routes/documents.ts +538 -0
- package/src/routes/environments.ts +72 -0
- package/src/routes/git-gateway.ts +106 -0
- package/src/routes/http-gateway.ts +141 -0
- package/src/routes/me.ts +122 -0
- package/src/routes/memberships.ts +173 -0
- package/src/routes/model-gateway.ts +134 -0
- package/src/routes/notifications.ts +101 -0
- package/src/routes/parse.ts +32 -0
- package/src/routes/personal-environment.ts +146 -0
- package/src/routes/plugins.ts +341 -0
- package/src/routes/project-mcp.ts +394 -0
- package/src/routes/projects.ts +708 -0
- package/src/routes/publications.ts +222 -0
- package/src/routes/run-errors.ts +86 -0
- package/src/routes/runs.ts +253 -0
- package/src/routes/session-artifacts.ts +293 -0
- package/src/routes/session-mailboxes.ts +80 -0
- package/src/routes/session-previews.ts +224 -0
- package/src/routes/session-terminals.ts +209 -0
- package/src/routes/triggers.ts +241 -0
- package/src/routes/watchers.ts +94 -0
- package/src/routes/webhooks.ts +171 -0
- package/src/routes/workflow-enablements.ts +331 -0
- package/src/routes/workflows.ts +323 -0
- package/src/schemas.ts +2735 -0
- package/src/session-artifact-tools.ts +170 -0
- package/src/session-event-stream.ts +122 -0
- package/src/spa.ts +135 -0
- package/src/telemetry.ts +93 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { APP_ICON_NAMES } from "@catamorphic/app";
|
|
2
|
+
import type { CatamorphicCore, Identity } from "@catamorphic/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { toolError, toolValue } from "./mcp-shared.js";
|
|
5
|
+
import type { SurfaceTool } from "./project-mcp-surface.js";
|
|
6
|
+
|
|
7
|
+
const Input = z.object({
|
|
8
|
+
action: z.enum(["create", "list", "read", "update", "discard", "run"]),
|
|
9
|
+
sessionId: z.string().uuid().optional(),
|
|
10
|
+
artifactId: z.string().uuid().optional(),
|
|
11
|
+
kind: z.enum(["app", "workflow"]).optional(),
|
|
12
|
+
name: z.string().max(100).optional(),
|
|
13
|
+
title: z.string().max(200).optional(),
|
|
14
|
+
icon: z.enum(APP_ICON_NAMES).optional(),
|
|
15
|
+
source: z.string().optional(),
|
|
16
|
+
files: z.record(z.string(), z.string().nullable()).optional(),
|
|
17
|
+
revision: z.number().int().positive().optional(),
|
|
18
|
+
environment: z.string().optional(),
|
|
19
|
+
input: z.json().optional(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
/** The same source lifecycle is available to every harness through project MCP. */
|
|
23
|
+
export function sessionArtifactTool(
|
|
24
|
+
core: CatamorphicCore,
|
|
25
|
+
identity: Identity,
|
|
26
|
+
projectId: string,
|
|
27
|
+
currentSessionId?: string,
|
|
28
|
+
): SurfaceTool {
|
|
29
|
+
return {
|
|
30
|
+
definition: {
|
|
31
|
+
name: "session_artifact",
|
|
32
|
+
description:
|
|
33
|
+
"Create, read, update, run or discard a temporary app or workflow owned by this session. Load the session-artifacts skill first. App source is a React component exporting default; the host supplies the standard app scaffold and builds it immediately. Additional files use ordinary workspace paths and may include shared components, dependencies and helper workflows. Workflow source is an ordinary exported defineWorkflow. No files are added to the user's checkout. Results survive closing tabs and remain available with the chat. Update requires the revision returned by read; files are explicit changed paths. Apps return their ordinary app:<appName> target. Creating a workflow does not run or enable it; use run for a one-off invocation, and the watcher tool for temporary scheduled activation. Discard prevents new use. Saving reusable work into the project is a separate selected-file change.",
|
|
34
|
+
inputSchema: z.toJSONSchema(Input),
|
|
35
|
+
},
|
|
36
|
+
call: async (raw) => {
|
|
37
|
+
try {
|
|
38
|
+
const input = Input.parse(raw);
|
|
39
|
+
const sessionId = input.sessionId ?? currentSessionId;
|
|
40
|
+
if (!sessionId) throw new Error("sessionId is required");
|
|
41
|
+
if (input.action === "list")
|
|
42
|
+
return toolValue(
|
|
43
|
+
await core.sessionArtifacts.list({
|
|
44
|
+
identity,
|
|
45
|
+
projectId,
|
|
46
|
+
sessionId,
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
if (input.action === "create") {
|
|
50
|
+
if (!input.kind || !input.name || !input.source)
|
|
51
|
+
throw new Error("kind, name and source are required");
|
|
52
|
+
if (input.kind === "app" && !core.apps)
|
|
53
|
+
throw new Error("App building is unavailable");
|
|
54
|
+
const artifact = await core.sessionArtifacts.create({
|
|
55
|
+
identity,
|
|
56
|
+
projectId,
|
|
57
|
+
sessionId,
|
|
58
|
+
kind: input.kind,
|
|
59
|
+
name: input.name,
|
|
60
|
+
title: input.title,
|
|
61
|
+
source: input.source,
|
|
62
|
+
files: input.files
|
|
63
|
+
? Object.fromEntries(
|
|
64
|
+
Object.entries(input.files).filter(
|
|
65
|
+
(entry): entry is [string, string] => entry[1] !== null,
|
|
66
|
+
),
|
|
67
|
+
)
|
|
68
|
+
: undefined,
|
|
69
|
+
});
|
|
70
|
+
const build =
|
|
71
|
+
artifact.appName && core.apps
|
|
72
|
+
? await core.apps.build({
|
|
73
|
+
identity,
|
|
74
|
+
projectId,
|
|
75
|
+
appName: artifact.appName,
|
|
76
|
+
artifactId: artifact.id,
|
|
77
|
+
kind: "preview",
|
|
78
|
+
})
|
|
79
|
+
: null;
|
|
80
|
+
if (artifact.appName && input.icon && core.apps)
|
|
81
|
+
await core.apps.updatePresentation({
|
|
82
|
+
identity,
|
|
83
|
+
projectId,
|
|
84
|
+
appName: artifact.appName,
|
|
85
|
+
icon: input.icon,
|
|
86
|
+
});
|
|
87
|
+
return toolValue({
|
|
88
|
+
artifact,
|
|
89
|
+
build,
|
|
90
|
+
target: artifact.appName
|
|
91
|
+
? `app:${artifact.appName}`
|
|
92
|
+
: `artifact:${artifact.id}`,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (!input.artifactId) throw new Error("artifactId is required");
|
|
96
|
+
const address = { identity, projectId, artifactId: input.artifactId };
|
|
97
|
+
if (input.action === "discard") {
|
|
98
|
+
const items = await core.sessionArtifacts.list({
|
|
99
|
+
identity,
|
|
100
|
+
projectId,
|
|
101
|
+
sessionId,
|
|
102
|
+
});
|
|
103
|
+
if (!items.some((item) => item.id === input.artifactId))
|
|
104
|
+
throw new Error("Artifact belongs to another session");
|
|
105
|
+
await core.sessionArtifacts.discard(address);
|
|
106
|
+
await core.watchers?.stop({
|
|
107
|
+
identity,
|
|
108
|
+
projectId,
|
|
109
|
+
sessionId,
|
|
110
|
+
watcherId: input.artifactId,
|
|
111
|
+
});
|
|
112
|
+
return toolValue({ discarded: true });
|
|
113
|
+
}
|
|
114
|
+
const artifact = await core.sessionArtifacts.get(address);
|
|
115
|
+
if (artifact.sessionId !== sessionId)
|
|
116
|
+
throw new Error("Artifact belongs to another session");
|
|
117
|
+
if (input.action === "read")
|
|
118
|
+
return toolValue({
|
|
119
|
+
artifact,
|
|
120
|
+
files: await core.sessionArtifacts.files(address),
|
|
121
|
+
});
|
|
122
|
+
if (input.action === "update") {
|
|
123
|
+
if (!input.revision || !input.files)
|
|
124
|
+
throw new Error("revision and files are required");
|
|
125
|
+
const updated = await core.sessionArtifacts.update({
|
|
126
|
+
...address,
|
|
127
|
+
revision: input.revision,
|
|
128
|
+
files: input.files,
|
|
129
|
+
title: input.title,
|
|
130
|
+
});
|
|
131
|
+
const build =
|
|
132
|
+
updated.appName && core.apps
|
|
133
|
+
? await core.apps.build({
|
|
134
|
+
identity,
|
|
135
|
+
projectId,
|
|
136
|
+
appName: updated.appName,
|
|
137
|
+
artifactId: updated.id,
|
|
138
|
+
kind: "preview",
|
|
139
|
+
})
|
|
140
|
+
: null;
|
|
141
|
+
return toolValue({
|
|
142
|
+
artifact: updated,
|
|
143
|
+
build,
|
|
144
|
+
target: updated.appName
|
|
145
|
+
? `app:${updated.appName}`
|
|
146
|
+
: `artifact:${updated.id}`,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
if (artifact.kind !== "workflow")
|
|
150
|
+
throw new Error("Only workflow artifacts can be run");
|
|
151
|
+
await core.sessionArtifacts.assertActive(address);
|
|
152
|
+
return toolValue(
|
|
153
|
+
await core.runs.triggerAtCommit({
|
|
154
|
+
identity,
|
|
155
|
+
projectId,
|
|
156
|
+
workflowName: artifact.name,
|
|
157
|
+
commitSha: artifact.commitSha,
|
|
158
|
+
remoteBranch: artifact.remoteBranch,
|
|
159
|
+
environment: input.environment,
|
|
160
|
+
input: input.input,
|
|
161
|
+
}),
|
|
162
|
+
);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
return toolError(
|
|
165
|
+
error instanceof Error ? error.message : String(error),
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
import type { SessionStreamMessage } from "@catamorphic/agent-protocol";
|
|
3
|
+
|
|
4
|
+
/** How often an idle stream says it is still there. */
|
|
5
|
+
export const SESSION_STREAM_HEARTBEAT_MS = 15_000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One session's event stream as server-sent events (ADR 0197). Each
|
|
9
|
+
* {@link SessionStreamMessage} is one SSE message, `data: <JSON>`, whose
|
|
10
|
+
* `id:` is the stream's sequence after it, so a reconnecting EventSource
|
|
11
|
+
* resumes from `Last-Event-ID`.
|
|
12
|
+
*
|
|
13
|
+
* The core subscription starts sending (the gap after the cursor) before
|
|
14
|
+
* the route knows the caller may read the session, so frames wait here
|
|
15
|
+
* until {@link open} writes the response head; a refusal is then still an
|
|
16
|
+
* ordinary HTTP error.
|
|
17
|
+
*/
|
|
18
|
+
export class SessionEventStream {
|
|
19
|
+
private readonly raw: ServerResponse;
|
|
20
|
+
private readonly heartbeatMs: number;
|
|
21
|
+
private sequence: number;
|
|
22
|
+
/** Frames sent before the response opened; null once it has. */
|
|
23
|
+
private buffered: string[] | null = [];
|
|
24
|
+
private unsubscribe: (() => void) | undefined;
|
|
25
|
+
private heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
26
|
+
private ended = false;
|
|
27
|
+
|
|
28
|
+
constructor(input: {
|
|
29
|
+
raw: ServerResponse;
|
|
30
|
+
/** The cursor the stream starts after. */
|
|
31
|
+
sequence: number;
|
|
32
|
+
heartbeatMs?: number;
|
|
33
|
+
}) {
|
|
34
|
+
this.raw = input.raw;
|
|
35
|
+
this.sequence = input.sequence;
|
|
36
|
+
this.heartbeatMs = input.heartbeatMs ?? SESSION_STREAM_HEARTBEAT_MS;
|
|
37
|
+
// The response closes when the client goes away or the stream ends.
|
|
38
|
+
this.raw.on("close", () => this.end());
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Hold the core subscription; a stream that already ended releases it. */
|
|
42
|
+
attach(unsubscribe: () => void): void {
|
|
43
|
+
if (this.ended) unsubscribe();
|
|
44
|
+
else this.unsubscribe = unsubscribe;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Write one message. False when the socket is buffering: the core
|
|
49
|
+
* subscription counts what waits and closes a reader that falls too far
|
|
50
|
+
* behind (it resumes from its cursor).
|
|
51
|
+
*/
|
|
52
|
+
send(message: SessionStreamMessage): boolean {
|
|
53
|
+
if (this.ended) return true;
|
|
54
|
+
const frame = this.frame(message);
|
|
55
|
+
if (this.buffered) {
|
|
56
|
+
this.buffered.push(frame);
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
return this.raw.write(frame);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Write the response head (with the reply's own headers) and what waited. */
|
|
63
|
+
open(headers: Record<string, string | number | string[] | undefined>): void {
|
|
64
|
+
const frames = this.buffered ?? [];
|
|
65
|
+
this.buffered = null;
|
|
66
|
+
if (this.raw.destroyed) {
|
|
67
|
+
this.end();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const own: Record<string, string | string[]> = {};
|
|
71
|
+
for (const [name, value] of Object.entries(headers))
|
|
72
|
+
if (value !== undefined)
|
|
73
|
+
own[name] = typeof value === "number" ? String(value) : value;
|
|
74
|
+
this.raw.writeHead(200, {
|
|
75
|
+
...own,
|
|
76
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
77
|
+
"cache-control": "no-cache, no-transform",
|
|
78
|
+
connection: "keep-alive",
|
|
79
|
+
// Proxies that buffer responses (nginx) would hold the stream back.
|
|
80
|
+
"x-accel-buffering": "no",
|
|
81
|
+
});
|
|
82
|
+
// The client learns the stream is open before the first event.
|
|
83
|
+
this.raw.flushHeaders();
|
|
84
|
+
for (const frame of frames) this.raw.write(frame);
|
|
85
|
+
if (this.ended) {
|
|
86
|
+
this.raw.end();
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
// A quiet session says it is there now, not at the first heartbeat:
|
|
90
|
+
// clients mark a stream live on a message, and some fetches resolve
|
|
91
|
+
// only once a body byte arrives.
|
|
92
|
+
if (frames.length === 0)
|
|
93
|
+
this.send({ type: "heartbeat", sequence: this.sequence });
|
|
94
|
+
this.heartbeat = setInterval(() => {
|
|
95
|
+
this.send({ type: "heartbeat", sequence: this.sequence });
|
|
96
|
+
}, this.heartbeatMs);
|
|
97
|
+
this.heartbeat.unref?.();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** End the stream: release the subscription and close the response. */
|
|
101
|
+
end(): void {
|
|
102
|
+
if (this.ended) return;
|
|
103
|
+
this.ended = true;
|
|
104
|
+
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
105
|
+
this.unsubscribe?.();
|
|
106
|
+
this.unsubscribe = undefined;
|
|
107
|
+
// Before it opened, `open` ends the response after flushing.
|
|
108
|
+
if (!this.buffered && !this.raw.writableEnded) this.raw.end();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private frame(message: SessionStreamMessage): string {
|
|
112
|
+
const sequence =
|
|
113
|
+
message.type === "events"
|
|
114
|
+
? message.events.at(-1)?.sequence
|
|
115
|
+
: message.type === "reset"
|
|
116
|
+
? message.snapshot.sequence
|
|
117
|
+
: undefined;
|
|
118
|
+
if (sequence === undefined) return `data: ${JSON.stringify(message)}\n\n`;
|
|
119
|
+
this.sequence = sequence;
|
|
120
|
+
return `id: ${sequence}\ndata: ${JSON.stringify(message)}\n\n`;
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/spa.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { contentTypeFor } from "@catamorphic/core";
|
|
4
|
+
import type { FastifyInstance } from "fastify";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Serve a built single-page app (the mobile PWA) from a dist directory:
|
|
8
|
+
* static assets by path, `index.html` for everything else (hash-routed
|
|
9
|
+
* SPA). Shared by the stock server's root and the desktop's LAN pairing
|
|
10
|
+
* listener, so path handling and headers stay identical on both origins.
|
|
11
|
+
*
|
|
12
|
+
* Registered as a catch-all `GET /*`; register AFTER every specific
|
|
13
|
+
* route. `fallback` renders when the dist has no index.html (e.g. the
|
|
14
|
+
* stock server's landing page).
|
|
15
|
+
*/
|
|
16
|
+
export function serveSpaDist(
|
|
17
|
+
app: FastifyInstance,
|
|
18
|
+
resolveDist: () => string,
|
|
19
|
+
fallback?: (reply: SpaReply) => unknown,
|
|
20
|
+
): void {
|
|
21
|
+
app.get("/*", async (request, reply) => {
|
|
22
|
+
const dist = resolveDist();
|
|
23
|
+
const index = path.join(dist, "index.html");
|
|
24
|
+
if (!(await exists(index))) {
|
|
25
|
+
if (fallback) return fallback(reply);
|
|
26
|
+
return reply
|
|
27
|
+
.status(503)
|
|
28
|
+
.type("text/plain")
|
|
29
|
+
.send(
|
|
30
|
+
"The app bundle is missing. Build it first: bun run --filter catamorphic-pwa build",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
const requested = decodeURIComponent(
|
|
34
|
+
(request.url.split("?")[0] ?? "/").replace(/^\/+/, ""),
|
|
35
|
+
);
|
|
36
|
+
const resolved = path.resolve(dist, requested || "index.html");
|
|
37
|
+
// Boundary check via relative path: a plain startsWith(dist) would
|
|
38
|
+
// also match sibling directories like `dist-evil`.
|
|
39
|
+
const relative = path.relative(dist, resolved);
|
|
40
|
+
const inside =
|
|
41
|
+
relative !== "" &&
|
|
42
|
+
!relative.startsWith("..") &&
|
|
43
|
+
!path.isAbsolute(relative);
|
|
44
|
+
const file = inside && (await isFile(resolved)) ? resolved : index;
|
|
45
|
+
// Vite emits content-hashed filenames under assets/: immutable. The
|
|
46
|
+
// HTML shell (and anything unhashed) must revalidate so deploys land.
|
|
47
|
+
reply.header(
|
|
48
|
+
"cache-control",
|
|
49
|
+
file !== index && relative.startsWith("assets/")
|
|
50
|
+
? "public, max-age=31536000, immutable"
|
|
51
|
+
: "no-cache",
|
|
52
|
+
);
|
|
53
|
+
const contents = await fs.readFile(file);
|
|
54
|
+
if (file.endsWith(".webmanifest")) {
|
|
55
|
+
const launch = new URL(
|
|
56
|
+
request.url,
|
|
57
|
+
"http://catamorphic.local",
|
|
58
|
+
).searchParams.get("launch");
|
|
59
|
+
if (launch) {
|
|
60
|
+
return reply
|
|
61
|
+
.type(spaContentType(file))
|
|
62
|
+
.send(
|
|
63
|
+
JSON.stringify(
|
|
64
|
+
pwaManifestWithLaunch(
|
|
65
|
+
JSON.parse(contents.toString("utf8")) as Record<
|
|
66
|
+
string,
|
|
67
|
+
unknown
|
|
68
|
+
>,
|
|
69
|
+
launch,
|
|
70
|
+
),
|
|
71
|
+
),
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return reply.type(spaContentType(file)).send(contents);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Carry a credential-free connection locator into an installed PWA without
|
|
81
|
+
* allowing a manifest query to turn the app into an open redirect.
|
|
82
|
+
*/
|
|
83
|
+
export function pwaManifestWithLaunch(
|
|
84
|
+
manifest: Record<string, unknown>,
|
|
85
|
+
rawLaunch: string | undefined,
|
|
86
|
+
): Record<string, unknown> {
|
|
87
|
+
if (!rawLaunch) return manifest;
|
|
88
|
+
try {
|
|
89
|
+
const base = new URL("http://catamorphic.local/");
|
|
90
|
+
const launch = new URL(rawLaunch, base);
|
|
91
|
+
if (
|
|
92
|
+
launch.origin !== base.origin ||
|
|
93
|
+
launch.pathname !== "/" ||
|
|
94
|
+
launch.username ||
|
|
95
|
+
launch.password ||
|
|
96
|
+
launch.hash
|
|
97
|
+
) {
|
|
98
|
+
return manifest;
|
|
99
|
+
}
|
|
100
|
+
return { ...manifest, start_url: `${launch.pathname}${launch.search}` };
|
|
101
|
+
} catch {
|
|
102
|
+
return manifest;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type SpaReply = {
|
|
107
|
+
status: (code: number) => SpaReply;
|
|
108
|
+
type: (contentType: string) => SpaReply;
|
|
109
|
+
send: (payload: unknown) => unknown;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** Core's map plus the web-app types it doesn't carry. */
|
|
113
|
+
function spaContentType(file: string): string {
|
|
114
|
+
if (file.endsWith(".webmanifest")) return "application/manifest+json";
|
|
115
|
+
if (file.endsWith(".woff2")) return "font/woff2";
|
|
116
|
+
if (file.endsWith(".ico")) return "image/x-icon";
|
|
117
|
+
return contentTypeFor(file);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function exists(file: string): Promise<boolean> {
|
|
121
|
+
try {
|
|
122
|
+
await fs.access(file);
|
|
123
|
+
return true;
|
|
124
|
+
} catch {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function isFile(file: string): Promise<boolean> {
|
|
130
|
+
try {
|
|
131
|
+
return (await fs.stat(file)).isFile();
|
|
132
|
+
} catch {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import {
|
|
2
|
+
emitLog,
|
|
3
|
+
extractTelemetryContext,
|
|
4
|
+
getMeter,
|
|
5
|
+
getTracer,
|
|
6
|
+
SeverityNumber,
|
|
7
|
+
} from "@catamorphic/otel";
|
|
8
|
+
import { context, SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
9
|
+
import type { FastifyInstance } from "fastify";
|
|
10
|
+
|
|
11
|
+
/** Explicit host opt-in; works under Bun and bundlers without module patching. */
|
|
12
|
+
export function instrumentHttpServer(app: FastifyInstance): void {
|
|
13
|
+
const tracer = getTracer("@catamorphic/http");
|
|
14
|
+
app.addHook("onRequest", (request, reply, done) => {
|
|
15
|
+
const projectId =
|
|
16
|
+
request.params &&
|
|
17
|
+
typeof request.params === "object" &&
|
|
18
|
+
"projectId" in request.params &&
|
|
19
|
+
typeof request.params.projectId === "string"
|
|
20
|
+
? request.params.projectId
|
|
21
|
+
: undefined;
|
|
22
|
+
const parent = extractTelemetryContext({ carrier: request.headers });
|
|
23
|
+
const method =
|
|
24
|
+
/^(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH)$/.test(
|
|
25
|
+
request.method,
|
|
26
|
+
)
|
|
27
|
+
? request.method
|
|
28
|
+
: "_OTHER";
|
|
29
|
+
const span = tracer.startSpan(
|
|
30
|
+
method,
|
|
31
|
+
{
|
|
32
|
+
kind: SpanKind.SERVER,
|
|
33
|
+
attributes: {
|
|
34
|
+
"http.request.method": method,
|
|
35
|
+
...(projectId ? { "catamorphic.project.id": projectId } : {}),
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
parent,
|
|
39
|
+
);
|
|
40
|
+
const state = {
|
|
41
|
+
span,
|
|
42
|
+
context: trace.setSpan(parent, span),
|
|
43
|
+
started: performance.now(),
|
|
44
|
+
finished: false,
|
|
45
|
+
};
|
|
46
|
+
const finish = (aborted = false) => {
|
|
47
|
+
if (state.finished) return;
|
|
48
|
+
state.finished = true;
|
|
49
|
+
const route = request.routeOptions.url;
|
|
50
|
+
const status = reply.statusCode;
|
|
51
|
+
const attributes = {
|
|
52
|
+
"http.request.method": method,
|
|
53
|
+
...(route ? { "http.route": route } : {}),
|
|
54
|
+
...(aborted
|
|
55
|
+
? { "error.type": "client_cancelled" }
|
|
56
|
+
: { "http.response.status_code": status }),
|
|
57
|
+
...(!aborted && status >= 500 ? { "error.type": String(status) } : {}),
|
|
58
|
+
};
|
|
59
|
+
span.updateName(route ? `${method} ${route}` : method);
|
|
60
|
+
span.setAttributes(attributes);
|
|
61
|
+
if (!aborted && status >= 500)
|
|
62
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
63
|
+
context.with(state.context, () => {
|
|
64
|
+
getMeter("@catamorphic/http")
|
|
65
|
+
.createHistogram("http.server.request.duration", {
|
|
66
|
+
unit: "s",
|
|
67
|
+
advice: {
|
|
68
|
+
explicitBucketBoundaries: [
|
|
69
|
+
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5,
|
|
70
|
+
5, 7.5, 10,
|
|
71
|
+
],
|
|
72
|
+
},
|
|
73
|
+
})
|
|
74
|
+
.record((performance.now() - state.started) / 1000, attributes);
|
|
75
|
+
emitLog({
|
|
76
|
+
scope: "@catamorphic/http",
|
|
77
|
+
body: aborted
|
|
78
|
+
? "HTTP request disconnected"
|
|
79
|
+
: "HTTP request completed",
|
|
80
|
+
attributes,
|
|
81
|
+
severity:
|
|
82
|
+
!aborted && status >= 500
|
|
83
|
+
? SeverityNumber.ERROR
|
|
84
|
+
: SeverityNumber.INFO,
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
span.end();
|
|
88
|
+
};
|
|
89
|
+
reply.raw.once("finish", () => finish());
|
|
90
|
+
reply.raw.once("close", () => finish(!reply.raw.writableFinished));
|
|
91
|
+
context.with(state.context, done);
|
|
92
|
+
});
|
|
93
|
+
}
|