Repository navigation
Expand file tree
/
Copy pathworker.ts
More file actions
162 lines (148 loc) · 5.67 KB
/
Copy pathworker.ts
File metadata and controls
162 lines (148 loc) · 5.67 KB
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
/**
* App Worker — explicit assembly for DeepSpace app routes and Durable Objects.
*
* Route implementations live under src/server. Keep their registration order
* here: specific API and WebSocket handlers must precede the SPA fallback.
*/
import { Hono } from "hono";
import { cors } from "hono/cors";
import {
armCronRoom,
CanvasRoom,
CronRoom,
JobRoom,
PresenceRoom,
RecordRoom,
resolveAppRole,
YjsRoom,
} from "deepspace/worker";
import type { DOBindings, DOManifest, Job, JobContext } from "deepspace/worker";
import { AI_CHATS_SCHEMA } from "deepspace/schema";
import { registerAgent } from "./src/ai/agent.js";
import { buildTools } from "./src/ai/tools.js";
import { tasks as cronTasks, runTask as runCronTask } from "./src/cron.js";
import { runJob } from "./src/jobs.js";
import { schemas } from "./src/schemas.js";
import { registerActionRoutes } from "./src/server/action-routes.js";
import {
registerAuthAndIntegrationRoutes,
registerPlatformProxyRoutes,
registerStaticRoutes,
resolveAuth,
} from "./src/server/http-routes.js";
import { registerRealtimeRoutes } from "./src/server/realtime-routes.js";
// Dynamic deploy reads this manifest to create the app's DO bindings.
export const __DO_MANIFEST__ = [
{ binding: "RECORD_ROOMS", className: "AppRecordRoom", sqlite: true },
{ binding: "YJS_ROOMS", className: "AppYjsRoom", sqlite: true },
{ binding: "CANVAS_ROOMS", className: "AppCanvasRoom", sqlite: true },
{ binding: "PRESENCE_ROOMS", className: "AppPresenceRoom", sqlite: true },
{ binding: "CRON_ROOMS", className: "AppCronRoom", sqlite: true },
{ binding: "JOB_ROOMS", className: "AppJobRoom", sqlite: true },
] as const satisfies DOManifest;
export class AppRecordRoom extends RecordRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, schemas, { ownerUserId: env.OWNER_USER_ID });
}
}
export class AppYjsRoom extends YjsRoom<Env> {}
export class AppCanvasRoom extends CanvasRoom<Env> {}
export class AppPresenceRoom extends PresenceRoom<Env> {}
/** Runs the scheduled tasks defined in src/cron.ts. */
export class AppCronRoom extends CronRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, { tasks: cronTasks });
}
protected async onTask(taskName: string): Promise<void> {
await runCronTask(taskName, this.env);
}
}
/** Runs durable background work defined in src/jobs.ts. */
export class AppJobRoom extends JobRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, {
authorizeWrite: async (user) => {
if (user.userId.startsWith("anon-")) return false;
const role = await resolveAppRole(env, user.userId);
return role === "member" || role === "admin";
},
});
}
protected async onJob(job: Job, context: JobContext): Promise<unknown> {
return await runJob(job, context, this.env);
}
}
export interface Env extends DOBindings<typeof __DO_MANIFEST__> {
ASSETS: Fetcher;
/**
* Platform service binding in production; deepspace dev supplies the URL
* fallback. Standard app files use the platform's shared, app-scoped R2
* bucket rather than a local binding.
*/
PLATFORM_WORKER?: Fetcher;
PLATFORM_WORKER_URL?: string;
/**
* HMAC app credential minted on first deploy. Proxy routes omit identity
* headers when it is absent so upstream services fail closed.
*/
APP_IDENTITY_TOKEN?: string;
/** API service binding in production with a deepspace-dev URL fallback. */
API_WORKER?: Fetcher;
API_WORKER_URL?: string;
AUTH_JWT_PUBLIC_KEY: string;
AUTH_JWT_ISSUER: string;
AUTH_WORKER_URL: string;
APP_NAME: string;
/** Immutable record-scope and platform identity. */
DEEPSPACE_APP_ID: string;
OWNER_USER_ID: string;
/**
* Long-lived owner JWT used for developer-billed server calls. User-billed
* calls always forward the signed-in caller's JWT instead.
*/
APP_OWNER_JWT: string;
/**
* Enables /api/debug/* only when exactly "true". The route still requires
* an authenticated app owner/admin. deepspace dev/test set it locally.
*/
ALLOW_DEBUG_ROUTES?: string;
}
export type AppContext = { Bindings: Env };
const app = new Hono<AppContext>();
app.use("/api/*", cors());
// A Durable Object exists only once something fetches it, and the CronRoom
// arms its alarm in that first fetch — so wake it from the request path, or a
// deployed schedule waits for a visitor. Once per isolate; no-op without tasks.
app.use("*", async (c, next) => {
armCronRoom(
c.executionCtx,
c.env.CRON_ROOMS,
`app:${c.env.DEEPSPACE_APP_ID}`,
cronTasks,
);
await next();
});
// Registration order is part of the worker contract. The wildcard auth route
// follows its special cases, AI precedes platform proxies, and static is last.
registerAuthAndIntegrationRoutes(app);
registerRealtimeRoutes(app);
registerActionRoutes(app, resolveAuth);
// The in-app assistant stores chat history in `ai-chats` / `ai-messages`,
// which only the copilot overlay declares. When present, registerAgent enables
// both that website AI and the user's local Codex/Claude/etc. assistant.
if (schemas.some((schema) => schema.name === AI_CHATS_SCHEMA.name)) {
registerAgent(app, { tools: buildTools });
}
registerPlatformProxyRoutes(app);
registerStaticRoutes(app);
// Hono's default handler logs a thrown Error as `console.error(err)`, which
// the runtime renders as its stack frames only — the message never reaches
// `deepspace logs`. Log the message as text, then answer 500 as before.
app.onError((err, c) => {
console.error(
`[error] ${c.req.method} ${new URL(c.req.url).pathname}: ${err.message}`,
err.stack ?? "",
);
return c.text("Internal Server Error", 500);
});
export default app;