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

main
ts 317 lines 10.1 KB
Raw
1 import { assert, describe, it } from "@effect/vitest"
2 import * as ByteSize from "effect/ByteSize"
3 import * as Effect from "effect/Effect"
4 import * as FileSystem from "effect/FileSystem"
5 import {
6 HttpEffect,
7 HttpPlatform,
8 HttpRouter,
9 HttpServerError,
10 HttpServerRequest,
11 HttpServerResponse,
12 HttpStaticServer
13 } from "effect/http"
14 import * as Layer from "effect/Layer"
15 import * as Option from "effect/Option"
16 import * as Path from "effect/Path"
17 import * as PlatformError from "effect/PlatformError"
18
19 const root = "/root"
20 const filePath = `${root}/file.txt`
21 const fileBody = "hello static"
22 const lastModified = "Wed, 01 Jan 2025 00:00:00 GMT"
23
24 const notFoundError = (path: string) =>
25 PlatformError.systemError({
26 _tag: "NotFound",
27 module: "FileSystem",
28 method: "stat",
29 description: "No such file or directory",
30 pathOrDescriptor: path
31 })
32
33 const permissionDeniedError = (path: string) =>
34 PlatformError.systemError({
35 _tag: "PermissionDenied",
36 module: "FileSystem",
37 method: "stat",
38 description: "Operation not permitted",
39 pathOrDescriptor: path
40 })
41
42 const fileInfo: FileSystem.File.Info = {
43 type: "File",
44 mtime: Option.some(new Date(lastModified)),
45 atime: Option.none(),
46 birthtime: Option.none(),
47 dev: 0n,
48 ino: Option.none(),
49 mode: 0,
50 nlink: Option.none(),
51 uid: Option.none(),
52 gid: Option.none(),
53 rdev: Option.none(),
54 size: ByteSize.bytes(fileBody.length),
55 blksize: Option.none(),
56 blocks: Option.none()
57 }
58
59 const stubCompression: HttpPlatform.Compression = {
60 algorithms: new Set(),
61 compressResponse: Effect.succeed
62 }
63
64 const makeHandler = async () => {
65 const fileSystem = FileSystem.makeNoop({
66 stat: (path) => path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
67 })
68
69 const httpPlatform = HttpPlatform.HttpPlatform.of({
70 platform: "node",
71 compression: stubCompression,
72 fileResponse: (_path, options) =>
73 Effect.succeed(HttpServerResponse.text(fileBody, {
74 status: options?.status,
75 headers: {
76 "Content-Location": "/file.txt",
77 Date: lastModified,
78 ETag: "\"etag-value\"",
79 Expires: "Thu, 02 Jan 2025 00:00:00 GMT",
80 "Last-Modified": lastModified,
81 Vary: "Accept-Encoding"
82 }
83 })),
84 fileWebResponse: () => Effect.die("not implemented")
85 })
86
87 const app = await Effect.runPromise(
88 HttpStaticServer.make({
89 root,
90 cacheControl: "public, max-age=60"
91 }).pipe(
92 Effect.provide(Path.layer),
93 Effect.provideService(FileSystem.FileSystem, fileSystem),
94 Effect.provideService(HttpPlatform.HttpPlatform, httpPlatform)
95 )
96 )
97
98 return HttpEffect.toWebHandler(app)
99 }
100
101 const makeFailingApp = async (options: {
102 readonly statError?: PlatformError.PlatformError
103 readonly fileResponseError?: PlatformError.PlatformError
104 }) => {
105 const fileSystem = FileSystem.makeNoop({
106 stat: (path) => {
107 if (options.statError !== undefined) {
108 return Effect.fail(options.statError)
109 }
110 return path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
111 }
112 })
113
114 const httpPlatform = HttpPlatform.HttpPlatform.of({
115 platform: "node",
116 compression: stubCompression,
117 fileResponse: (_path, fileOptions) => {
118 if (options.fileResponseError !== undefined) {
119 return Effect.fail(options.fileResponseError)
120 }
121 return Effect.succeed(HttpServerResponse.text(fileBody, {
122 status: fileOptions?.status,
123 headers: {
124 ETag: "\"etag-value\"",
125 "Last-Modified": lastModified
126 }
127 }))
128 },
129 fileWebResponse: () => Effect.die("not implemented")
130 })
131
132 return Effect.runPromise(
133 HttpStaticServer.make({ root }).pipe(
134 Effect.provide(Path.layer),
135 Effect.provideService(FileSystem.FileSystem, fileSystem),
136 Effect.provideService(HttpPlatform.HttpPlatform, httpPlatform)
137 )
138 )
139 }
140
141 const makeLayerHandler = (options: {
142 readonly statError?: PlatformError.PlatformError
143 readonly fileResponseError?: PlatformError.PlatformError
144 }) => {
145 const fileSystem = FileSystem.makeNoop({
146 stat: (path) => {
147 if (options.statError !== undefined) {
148 return Effect.fail(options.statError)
149 }
150 return path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
151 }
152 })
153 const httpPlatform = HttpPlatform.HttpPlatform.of({
154 platform: "node",
155 compression: stubCompression,
156 fileResponse: () =>
157 options.fileResponseError !== undefined
158 ? Effect.fail(options.fileResponseError)
159 : Effect.succeed(HttpServerResponse.text(fileBody)),
160 fileWebResponse: () => Effect.die("not implemented")
161 })
162
163 const dependencies = Layer.mergeAll(
164 Path.layer,
165 Layer.succeed(FileSystem.FileSystem, fileSystem),
166 Layer.succeed(HttpPlatform.HttpPlatform, httpPlatform)
167 )
168
169 return HttpRouter.toWebHandler(
170 HttpStaticServer.layer({ root }).pipe(Layer.provideMerge(dependencies)),
171 { disableLogger: true }
172 )
173 }
174
175 describe("HttpStaticServer", () => {
176 it("304 with If-None-Match exact, weak, and wildcard", async () => {
177 const handler = await makeHandler()
178 const warmupResponse = await handler(new Request("http://localhost/file.txt"))
179 const etag = warmupResponse.headers.get("etag")
180 assert.strictEqual(etag, "\"etag-value\"")
181 if (etag === null) {
182 throw new Error("expected ETag header")
183 }
184
185 const exact = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": etag } }))
186 const weak = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": `W/${etag}` } }))
187 const list = await handler(
188 new Request("http://localhost/file.txt", { headers: { "If-None-Match": `"other", W/${etag}` } })
189 )
190 const any = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": "*" } }))
191
192 assert.deepStrictEqual([exact.status, weak.status, list.status, any.status], [304, 304, 304, 304])
193 assert.strictEqual(exact.headers.get("etag"), "\"etag-value\"")
194 assert.strictEqual(exact.headers.get("cache-control"), "public, max-age=60")
195 assert.strictEqual(exact.headers.get("last-modified"), lastModified)
196 assert.strictEqual(exact.headers.get("content-location"), "/file.txt")
197 assert.strictEqual(exact.headers.get("date"), lastModified)
198 assert.strictEqual(exact.headers.get("expires"), "Thu, 02 Jan 2025 00:00:00 GMT")
199 assert.strictEqual(exact.headers.get("vary"), "Accept-Encoding")
200 assert.strictEqual(exact.headers.get("content-type"), null)
201 assert.strictEqual(exact.headers.get("content-length"), null)
202 })
203
204 it("304 with If-Modified-Since and no If-None-Match", async () => {
205 const handler = await makeHandler()
206
207 const notModified = await handler(
208 new Request("http://localhost/file.txt", {
209 headers: {
210 "If-Modified-Since": lastModified
211 }
212 })
213 )
214 const modified = await handler(
215 new Request("http://localhost/file.txt", {
216 headers: {
217 "If-Modified-Since": "Tue, 31 Dec 2024 23:59:59 GMT"
218 }
219 })
220 )
221 const invalidDate = await handler(
222 new Request("http://localhost/file.txt", {
223 headers: {
224 "If-Modified-Since": "not-a-date"
225 }
226 })
227 )
228
229 assert.strictEqual(notModified.status, 304)
230 assert.strictEqual(modified.status, 200)
231 assert.strictEqual(invalidDate.status, 200)
232 })
233
234 it("If-None-Match takes precedence over If-Modified-Since", async () => {
235 const handler = await makeHandler()
236
237 const response = await handler(
238 new Request("http://localhost/file.txt", {
239 headers: {
240 "If-None-Match": "\"different\"",
241 "If-Modified-Since": "Thu, 02 Jan 2025 00:00:00 GMT"
242 }
243 })
244 )
245
246 assert.strictEqual(response.status, 200)
247 })
248
249 it("matched If-None-Match takes precedence over Range", async () => {
250 const handler = await makeHandler()
251
252 const response = await handler(
253 new Request("http://localhost/file.txt", {
254 headers: {
255 "If-None-Match": "\"etag-value\"",
256 "If-Range": "\"stale\"",
257 Range: "bytes=1000-1001"
258 }
259 })
260 )
261
262 assert.strictEqual(response.status, 304)
263 assert.strictEqual(response.headers.get("etag"), "\"etag-value\"")
264 assert.strictEqual(response.headers.get("cache-control"), "public, max-age=60")
265 assert.strictEqual(response.headers.get("last-modified"), lastModified)
266 assert.strictEqual(response.headers.get("content-range"), null)
267 assert.strictEqual(response.headers.get("accept-ranges"), null)
268 assert.strictEqual(response.headers.get("content-type"), null)
269 assert.strictEqual(response.headers.get("content-length"), null)
270 })
271
272 it("wraps missing routes as HttpServerError RouteNotFound", async () => {
273 const app = await makeFailingApp({})
274 const error = await Effect.runPromise(
275 app.pipe(
276 Effect.provideService(
277 HttpServerRequest.HttpServerRequest,
278 HttpServerRequest.fromWeb(new Request("http://localhost/missing.txt"))
279 ),
280 Effect.flip
281 )
282 )
283
284 assert.instanceOf(error, HttpServerError.HttpServerError)
285 assert.strictEqual(error.reason._tag, "RouteNotFound")
286 })
287
288 it("maps non-NotFound platform failures to HttpServerError InternalError", async () => {
289 const statError = permissionDeniedError(filePath)
290 const app = await makeFailingApp({ statError })
291 const error = await Effect.runPromise(
292 app.pipe(
293 Effect.provideService(
294 HttpServerRequest.HttpServerRequest,
295 HttpServerRequest.fromWeb(new Request("http://localhost/file.txt"))
296 ),
297 Effect.flip
298 )
299 )
300
301 assert.instanceOf(error, HttpServerError.HttpServerError)
302 assert.strictEqual(error.reason._tag, "InternalError")
303 assert.strictEqual(error.reason.cause, statError)
304 })
305
306 it("layer renders InternalError responses as 500", async () => {
307 const { handler, dispose } = makeLayerHandler({
308 fileResponseError: permissionDeniedError(filePath)
309 })
310 try {
311 const response = await handler(new Request("http://localhost/file.txt"))
312 assert.strictEqual(response.status, 500)
313 } finally {
314 await dispose()
315 }
316 })
317 })