acrylblends 0.6.1 → 0.6.2

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.
Files changed (119) hide show
  1. package/README.md +8 -6
  2. package/docs/framework/UPSTREAM.md +1 -1
  3. package/docs/framework/api/presets.md +0 -3
  4. package/docs/framework/cordis/acryl-in-a-cordis-app.md +3 -0
  5. package/docs/framework/getting-started/basic.md +4 -4
  6. package/docs/framework/guides/jsx.md +1 -1
  7. package/docs/framework/guides/middleware.md +1 -1
  8. package/docs/framework/helpers/cookie.md +1 -1
  9. package/docs/framework/helpers/dev.md +0 -3
  10. package/docs/framework/helpers/jwt.md +1 -1
  11. package/docs/framework/helpers/proxy.md +0 -3
  12. package/docs/framework/middleware/builtin/basic-auth.md +6 -6
  13. package/docs/framework/middleware/builtin/cache.md +0 -3
  14. package/docs/framework/middleware/builtin/combine.md +1 -1
  15. package/docs/framework/middleware/builtin/ip-restriction.md +1 -1
  16. package/docs/framework/middleware/builtin/logger.md +1 -1
  17. package/docs/framework/middleware/builtin/mount.md +0 -3
  18. package/docs/framework/upstream.json +2 -2
  19. package/lib/accepts.d.ts +1 -1
  20. package/lib/acryl-base.d.ts +1 -1
  21. package/lib/adapter.d.ts +1 -1
  22. package/lib/{app-CmAYW1Al.d.ts → app-BdrVHBlJ.d.ts} +1 -1
  23. package/lib/basic-auth.d.ts +1 -1
  24. package/lib/bearer-auth.d.ts +1 -1
  25. package/lib/body-limit.d.ts +1 -1
  26. package/lib/cache.d.ts +43 -0
  27. package/lib/cache.js +169 -0
  28. package/lib/client.d.ts +2 -2
  29. package/lib/combine.d.ts +1 -1
  30. package/lib/compress.d.ts +1 -1
  31. package/lib/conninfo.d.ts +2 -2
  32. package/lib/{context-Bm7rI-oK.d.ts → context-B5Y1lLha.d.ts} +1 -1
  33. package/lib/context-storage.d.ts +1 -1
  34. package/lib/{cookie-ClMaKDQf.d.ts → cookie-D9_nQbsM.d.ts} +1 -1
  35. package/lib/cookie.d.ts +3 -3
  36. package/lib/cors.d.ts +1 -1
  37. package/lib/csrf.d.ts +1 -1
  38. package/lib/dev.d.ts +19 -0
  39. package/lib/dev.js +50 -0
  40. package/lib/etag.d.ts +1 -1
  41. package/lib/factory.d.ts +2 -2
  42. package/lib/{index-B-3F4wt2.d.ts → index-DtEoak1i.d.ts} +2 -2
  43. package/lib/{index-UTBmM3GX.d.ts → index-Kqou8Fjh.d.ts} +2 -2
  44. package/lib/{index-oOClm_Xk.d.ts → index-m12zcmph.d.ts} +3 -3
  45. package/lib/index.d.ts +4 -4
  46. package/lib/ip-restriction.d.ts +2 -2
  47. package/lib/jwk.d.ts +4 -4
  48. package/lib/{jwt-Dg493Tai.d.ts → jwt-BA65QhnJ.d.ts} +1 -1
  49. package/lib/jwt.d.ts +4 -4
  50. package/lib/language.d.ts +1 -1
  51. package/lib/linear-router-C3FPib6h.js +96 -0
  52. package/lib/logger.d.ts +1 -1
  53. package/lib/loopback-only.d.ts +1 -1
  54. package/lib/method-not-allowed.d.ts +2 -2
  55. package/lib/method-override.d.ts +2 -2
  56. package/lib/mount.d.ts +44 -0
  57. package/lib/mount.js +67 -0
  58. package/lib/node-server/conninfo.d.ts +1 -1
  59. package/lib/node-server/serve-static.d.ts +1 -1
  60. package/lib/node-server.d.ts +1 -1
  61. package/lib/pattern-router-HZxjDGEQ.js +41 -0
  62. package/lib/powered-by.d.ts +1 -1
  63. package/lib/pretty-json.d.ts +1 -1
  64. package/lib/proxy.d.ts +72 -0
  65. package/lib/proxy.js +121 -0
  66. package/lib/quick.d.ts +8 -0
  67. package/lib/quick.js +17 -0
  68. package/lib/request-id.d.ts +1 -1
  69. package/lib/request.d.ts +1 -1
  70. package/lib/route.d.ts +1 -1
  71. package/lib/router/linear-router.js +1 -95
  72. package/lib/router/pattern-router.js +1 -40
  73. package/lib/schema-validator.d.ts +1 -1
  74. package/lib/secure-headers.d.ts +1 -1
  75. package/lib/serve-static.d.ts +1 -1
  76. package/lib/streaming.d.ts +1 -1
  77. package/lib/testing.d.ts +4 -4
  78. package/lib/timeout.d.ts +1 -1
  79. package/lib/timing.d.ts +1 -1
  80. package/lib/tiny.d.ts +8 -0
  81. package/lib/tiny.js +15 -0
  82. package/lib/trailing-slash.d.ts +1 -1
  83. package/lib/{types-CHesD1KG.d.ts → types-Bd29gh2o.d.ts} +3 -3
  84. package/lib/{types-CwrQjlaM.d.ts → types-D9DEXMjE.d.ts} +3 -1
  85. package/lib/{types-CDO6I3B0.d.ts → types-ZM9gIiKh.d.ts} +1 -1
  86. package/lib/types.d.ts +1 -1
  87. package/lib/utils/body.d.ts +1 -1
  88. package/lib/utils/cookie.d.ts +1 -1
  89. package/lib/utils/crypto.d.ts +1 -1
  90. package/lib/utils/ipaddr.d.ts +1 -1
  91. package/lib/utils/jwt.d.ts +1 -1
  92. package/lib/utils/types.d.ts +2 -2
  93. package/lib/validator.d.ts +2 -2
  94. package/lib/ws.d.ts +1 -1
  95. package/package.json +25 -1
  96. package/plugins/acryl-inspect/upstream.json +1 -1
  97. package/plugins/acryl-node-server/upstream.json +1 -1
  98. package/plugins/acryl-router/src/core/helper/dev/index.test.ts +181 -0
  99. package/plugins/acryl-router/src/core/helper/dev/index.ts +79 -0
  100. package/plugins/acryl-router/src/core/helper/proxy/index.test.ts +356 -0
  101. package/plugins/acryl-router/src/core/helper/proxy/index.ts +203 -0
  102. package/plugins/acryl-router/src/core/middleware/cache/index.test.ts +1211 -0
  103. package/plugins/acryl-router/src/core/middleware/cache/index.ts +323 -0
  104. package/plugins/acryl-router/src/core/middleware/mount/index.test.ts +334 -0
  105. package/plugins/acryl-router/src/core/middleware/mount/index.ts +108 -0
  106. package/plugins/acryl-router/src/core/preset/quick.test.ts +42 -0
  107. package/plugins/acryl-router/src/core/preset/quick.ts +24 -0
  108. package/plugins/acryl-router/src/core/preset/tiny.test.ts +42 -0
  109. package/plugins/acryl-router/src/core/preset/tiny.ts +20 -0
  110. package/plugins/acryl-router/src/core/utils/types.ts +3 -0
  111. package/plugins/acryl-router/src/helpers/index.ts +2 -0
  112. package/plugins/acryl-router/src/middleware/index.ts +2 -0
  113. package/plugins/acryl-router/src/service.ts +22 -5
  114. package/plugins/acryl-router/upstream.json +2 -2
  115. package/plugins/acryl-router-http/upstream.json +1 -1
  116. package/plugins/acryl-state/upstream.json +1 -1
  117. package/plugins/desktop/upstream.json +1 -1
  118. package/plugins/desktop-web/upstream.json +1 -1
  119. package/templates/todo/upstream.json +1 -1
@@ -0,0 +1,181 @@
1
+ import { getRouterName, inspectRoutes, showRoutes } from './index.ts'
2
+ import { Acryl } from '../../app.ts'
3
+ import { RegExpRouter } from '../../router/reg-exp-router/index.ts'
4
+ import type { Handler, MiddlewareHandler } from '../../types.ts'
5
+
6
+ const namedMiddleware: MiddlewareHandler = (_, next) => next()
7
+ const namedHandler: Handler = (c) => c.text('hi')
8
+ const app = new Acryl()
9
+ .use('*', (_c, next) => next())
10
+ .get(
11
+ '/',
12
+ (_, next) => next(),
13
+ (c) => c.text('hi')
14
+ )
15
+ .get('/named', namedMiddleware, namedHandler)
16
+ .post('/', (c) => c.text('hi'))
17
+ .put('/', (c) => c.text('hi'))
18
+ .patch('/', (c) => c.text('hi'))
19
+ .delete('/', (c) => c.text('hi'))
20
+ .options('/', (c) => c.text('hi'))
21
+ .get('/static', () => new Response('hi'))
22
+
23
+ describe('inspectRoutes()', () => {
24
+ it('should return correct data', async () => {
25
+ expect(inspectRoutes(app)).toEqual([
26
+ { path: '/*', method: 'ALL', name: '[middleware]', isMiddleware: true },
27
+ { path: '/', method: 'GET', name: '[middleware]', isMiddleware: true },
28
+ { path: '/', method: 'GET', name: '[handler]', isMiddleware: false },
29
+ { path: '/named', method: 'GET', name: 'namedMiddleware', isMiddleware: true },
30
+ { path: '/named', method: 'GET', name: 'namedHandler', isMiddleware: false },
31
+ { path: '/', method: 'POST', name: '[handler]', isMiddleware: false },
32
+ { path: '/', method: 'PUT', name: '[handler]', isMiddleware: false },
33
+ { path: '/', method: 'PATCH', name: '[handler]', isMiddleware: false },
34
+ { path: '/', method: 'DELETE', name: '[handler]', isMiddleware: false },
35
+ { path: '/', method: 'OPTIONS', name: '[handler]', isMiddleware: false },
36
+ { path: '/static', method: 'GET', name: '[handler]', isMiddleware: false },
37
+ ])
38
+ })
39
+
40
+ it('should return [handler] also for sub app', async () => {
41
+ const subApp = new Acryl()
42
+
43
+ subApp.get('/', (c) => c.json(0))
44
+ subApp.onError((_, c) => c.json(0))
45
+
46
+ const mainApp = new Acryl()
47
+ mainApp.route('/', subApp)
48
+ expect(inspectRoutes(mainApp)).toEqual([
49
+ {
50
+ isMiddleware: false,
51
+ method: 'GET',
52
+ name: '[handler]',
53
+ path: '/',
54
+ },
55
+ ])
56
+ })
57
+ })
58
+
59
+ describe('showRoutes()', () => {
60
+ let logs: string[] = []
61
+
62
+ let originalLog: typeof console.log
63
+ beforeAll(() => {
64
+ originalLog = console.log
65
+ console.log = (...args) => logs.push(...args)
66
+ })
67
+ afterAll(() => {
68
+ console.log = originalLog
69
+ })
70
+
71
+ beforeEach(() => {
72
+ logs = []
73
+ })
74
+ it('should render simple output', async () => {
75
+ showRoutes(app)
76
+ expect(logs).toEqual([
77
+ '\x1b[32mGET\x1b[0m /',
78
+ '\x1b[32mGET\x1b[0m /named',
79
+ '\x1b[32mPOST\x1b[0m /',
80
+ '\x1b[32mPUT\x1b[0m /',
81
+ '\x1b[32mPATCH\x1b[0m /',
82
+ '\x1b[32mDELETE\x1b[0m /',
83
+ '\x1b[32mOPTIONS\x1b[0m /',
84
+ '\x1b[32mGET\x1b[0m /static',
85
+ ])
86
+ })
87
+
88
+ it('should render output includes handlers and middlewares', async () => {
89
+ showRoutes(app, { verbose: true })
90
+ expect(logs).toEqual([
91
+ '\x1b[32mALL\x1b[0m /*',
92
+ ' [middleware]',
93
+ '\x1b[32mGET\x1b[0m /',
94
+ ' [middleware]',
95
+ ' [handler]',
96
+ '\x1b[32mGET\x1b[0m /named',
97
+ ' namedMiddleware',
98
+ ' namedHandler',
99
+ '\x1b[32mPOST\x1b[0m /',
100
+ ' [handler]',
101
+ '\x1b[32mPUT\x1b[0m /',
102
+ ' [handler]',
103
+ '\x1b[32mPATCH\x1b[0m /',
104
+ ' [handler]',
105
+ '\x1b[32mDELETE\x1b[0m /',
106
+ ' [handler]',
107
+ '\x1b[32mOPTIONS\x1b[0m /',
108
+ ' [handler]',
109
+ '\x1b[32mGET\x1b[0m /static',
110
+ ' [handler]',
111
+ ])
112
+ })
113
+
114
+ it('should render not colorized output', async () => {
115
+ showRoutes(app, { colorize: false })
116
+ expect(logs).toEqual([
117
+ 'GET /',
118
+ 'GET /named',
119
+ 'POST /',
120
+ 'PUT /',
121
+ 'PATCH /',
122
+ 'DELETE /',
123
+ 'OPTIONS /',
124
+ 'GET /static',
125
+ ])
126
+ })
127
+ })
128
+
129
+ describe('showRoutes() in NO_COLOR', () => {
130
+ let logs: string[] = []
131
+
132
+ let originalLog: typeof console.log
133
+ beforeAll(() => {
134
+ vi.stubEnv('NO_COLOR', '1')
135
+ originalLog = console.log
136
+ console.log = (...args) => logs.push(...args)
137
+ })
138
+ afterAll(() => {
139
+ vi.unstubAllEnvs()
140
+ console.log = originalLog
141
+ })
142
+
143
+ beforeEach(() => {
144
+ logs = []
145
+ })
146
+ it('should render not colorized output', async () => {
147
+ showRoutes(app)
148
+ expect(logs).toEqual([
149
+ 'GET /',
150
+ 'GET /named',
151
+ 'POST /',
152
+ 'PUT /',
153
+ 'PATCH /',
154
+ 'DELETE /',
155
+ 'OPTIONS /',
156
+ 'GET /static',
157
+ ])
158
+ })
159
+ it('should render colorized output if colorize: true', async () => {
160
+ showRoutes(app, { colorize: true })
161
+ expect(logs).toEqual([
162
+ '\x1b[32mGET\x1b[0m /',
163
+ '\x1b[32mGET\x1b[0m /named',
164
+ '\x1b[32mPOST\x1b[0m /',
165
+ '\x1b[32mPUT\x1b[0m /',
166
+ '\x1b[32mPATCH\x1b[0m /',
167
+ '\x1b[32mDELETE\x1b[0m /',
168
+ '\x1b[32mOPTIONS\x1b[0m /',
169
+ '\x1b[32mGET\x1b[0m /static',
170
+ ])
171
+ })
172
+ })
173
+
174
+ describe('getRouterName()', () => {
175
+ it('Should return the correct router name', async () => {
176
+ const app = new Acryl({
177
+ router: new RegExpRouter(),
178
+ })
179
+ expect(getRouterName(app)).toBe('RegExpRouter')
180
+ })
181
+ })
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @module
3
+ * Dev Helper for Acryl.
4
+ */
5
+
6
+ import type { Acryl } from '../../app.ts'
7
+ import type { Env, RouterRoute } from '../../types.ts'
8
+ import { getColorEnabled } from '../../utils/color.ts'
9
+ import { findTargetHandler, isMiddleware } from '../../utils/handler.ts'
10
+
11
+ interface ShowRoutesOptions {
12
+ verbose?: boolean
13
+ colorize?: boolean
14
+ }
15
+
16
+ interface RouteData {
17
+ path: string
18
+ method: string
19
+ name: string
20
+ isMiddleware: boolean
21
+ }
22
+
23
+ const handlerName = (handler: Function): string => {
24
+ return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')
25
+ }
26
+
27
+ export const inspectRoutes = <E extends Env>(acryl: Acryl<E>): RouteData[] => {
28
+ return acryl.routes.map(({ path, method, handler }: RouterRoute) => {
29
+ const targetHandler = findTargetHandler(handler)
30
+ return {
31
+ path,
32
+ method,
33
+ name: handlerName(targetHandler),
34
+ isMiddleware: isMiddleware(targetHandler),
35
+ }
36
+ })
37
+ }
38
+
39
+ export const showRoutes = <E extends Env>(acryl: Acryl<E>, opts?: ShowRoutesOptions): void => {
40
+ const colorEnabled = opts?.colorize ?? getColorEnabled()
41
+ const routeData: Record<string, RouteData[]> = {}
42
+ let maxMethodLength = 0
43
+ let maxPathLength = 0
44
+
45
+ inspectRoutes(acryl)
46
+ .filter(({ isMiddleware }) => opts?.verbose || !isMiddleware)
47
+ .map((route) => {
48
+ const key = `${route.method}-${route.path}`
49
+ ;(routeData[key] ||= []).push(route)
50
+ if (routeData[key].length > 1) {
51
+ return
52
+ }
53
+ maxMethodLength = Math.max(maxMethodLength, route.method.length)
54
+ maxPathLength = Math.max(maxPathLength, route.path.length)
55
+ return { method: route.method, path: route.path, routes: routeData[key] }
56
+ })
57
+ .forEach((data) => {
58
+ if (!data) {
59
+ return
60
+ }
61
+ const { method, path, routes } = data
62
+
63
+ const methodStr = colorEnabled ? `\x1b[32m${method}\x1b[0m` : method
64
+ console.log(`${methodStr} ${' '.repeat(maxMethodLength - method.length)} ${path}`)
65
+
66
+ if (!opts?.verbose) {
67
+ return
68
+ }
69
+
70
+ routes.forEach(({ name }) => {
71
+ console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)
72
+ })
73
+ })
74
+ }
75
+
76
+ export const getRouterName = <E extends Env>(app: Acryl<E>): string => {
77
+ app.router.match('GET', '/')
78
+ return app.router.name
79
+ }
@@ -0,0 +1,356 @@
1
+ import { proxy } from './index.ts'
2
+ import { Acryl } from '../../app.ts'
3
+
4
+ describe('Proxy Middleware', () => {
5
+ describe('proxy', () => {
6
+ beforeEach(() => {
7
+ global.fetch = vi.fn().mockImplementation(async (req) => {
8
+ if (req.url === 'https://example.com/ok') {
9
+ return Promise.resolve(new Response('ok'))
10
+ } else if (req.url === 'https://example.com/disconnect') {
11
+ const reader = req.body.getReader()
12
+ let response
13
+
14
+ req.signal.addEventListener('abort', () => {
15
+ response = req.signal.reason
16
+ reader.cancel()
17
+ })
18
+
19
+ await reader.read()
20
+
21
+ return Promise.resolve(new Response(response))
22
+ } else if (req.url === 'https://example.com/compressed') {
23
+ return Promise.resolve(
24
+ new Response('ok', {
25
+ headers: {
26
+ 'Content-Encoding': 'gzip',
27
+ 'Content-Length': '1',
28
+ 'Content-Range': 'bytes 0-2/1024',
29
+ 'X-Response-Id': '456',
30
+ },
31
+ })
32
+ )
33
+ } else if (req.url === 'https://example.com/uncompressed') {
34
+ return Promise.resolve(
35
+ new Response('ok', {
36
+ headers: {
37
+ 'Content-Length': '2',
38
+ 'Content-Range': 'bytes 0-2/1024',
39
+ 'X-Response-Id': '456',
40
+ },
41
+ })
42
+ )
43
+ } else if (req.url === 'https://example.com/post' && req.method === 'POST') {
44
+ return Promise.resolve(new Response(`request body: ${await req.text()}`))
45
+ } else if (req.url === 'https://example.com/hop-by-hop') {
46
+ return Promise.resolve(
47
+ new Response('ok', {
48
+ headers: {
49
+ 'Transfer-Encoding': 'chunked',
50
+ },
51
+ })
52
+ )
53
+ } else if (req.url === 'https://example.com/connection-listed') {
54
+ return Promise.resolve(
55
+ new Response('ok', {
56
+ headers: {
57
+ Connection: 'x-connection-scoped, bad name',
58
+ 'X-Connection-Scoped': 'should not be forwarded',
59
+ 'X-Normal': 'kept',
60
+ },
61
+ })
62
+ )
63
+ } else if (req.url === 'https://example.com/set-cookie') {
64
+ return Promise.resolve(
65
+ new Response('ok', {
66
+ headers: {
67
+ 'Set-Cookie': 'test=123',
68
+ },
69
+ })
70
+ )
71
+ }
72
+ return Promise.resolve(new Response('not found', { status: 404 }))
73
+ })
74
+ })
75
+
76
+ it('compressed', async () => {
77
+ const app = new Acryl()
78
+ app.get('/proxy/:path', (c) =>
79
+ proxy(
80
+ new Request(`https://example.com/${c.req.param('path')}`, {
81
+ headers: {
82
+ 'X-Request-Id': '123',
83
+ 'Accept-Encoding': 'gzip',
84
+ },
85
+ })
86
+ )
87
+ )
88
+ const res = await app.request('/proxy/compressed')
89
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
90
+
91
+ expect(req.url).toBe('https://example.com/compressed')
92
+ expect(req.headers.get('X-Request-Id')).toBe('123')
93
+ expect(req.headers.get('Accept-Encoding')).toBeNull()
94
+
95
+ expect(res.status).toBe(200)
96
+ expect(res.headers.get('X-Response-Id')).toBe('456')
97
+ expect(res.headers.get('Content-Encoding')).toBeNull()
98
+ expect(res.headers.get('Content-Length')).toBeNull()
99
+ expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024')
100
+ })
101
+
102
+ it('uncompressed', async () => {
103
+ const app = new Acryl()
104
+ app.get('/proxy/:path', (c) =>
105
+ proxy(
106
+ new Request(`https://example.com/${c.req.param('path')}`, {
107
+ headers: {
108
+ 'X-Request-Id': '123',
109
+ 'Accept-Encoding': 'gzip',
110
+ },
111
+ })
112
+ )
113
+ )
114
+ const res = await app.request('/proxy/uncompressed')
115
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
116
+
117
+ expect(req.url).toBe('https://example.com/uncompressed')
118
+ expect(req.headers.get('X-Request-Id')).toBe('123')
119
+ expect(req.headers.get('Accept-Encoding')).toBeNull()
120
+
121
+ expect(res.status).toBe(200)
122
+ expect(res.headers.get('X-Response-Id')).toBe('456')
123
+ expect(res.headers.get('Content-Length')).toBe('2')
124
+ expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024')
125
+ })
126
+
127
+ it('POST request', async () => {
128
+ const app = new Acryl()
129
+ app.all('/proxy/:path', (c) => {
130
+ return proxy(`https://example.com/${c.req.param('path')}`, {
131
+ ...c.req,
132
+ headers: {
133
+ ...c.req.header(),
134
+ 'X-Request-Id': '123',
135
+ 'Accept-Encoding': 'gzip',
136
+ },
137
+ })
138
+ })
139
+ const res = await app.request('/proxy/post', {
140
+ method: 'POST',
141
+ body: 'test',
142
+ })
143
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
144
+
145
+ expect(req.url).toBe('https://example.com/post')
146
+
147
+ expect(res.status).toBe(200)
148
+ expect(await res.text()).toBe('request body: test')
149
+ })
150
+
151
+ it('remove hop-by-hop headers', async () => {
152
+ const app = new Acryl()
153
+ app.get('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`, c.req))
154
+
155
+ const res = await app.request('/proxy/hop-by-hop', {
156
+ headers: {
157
+ Host: 'example.com',
158
+ Connection: 'keep-alive, custom-header',
159
+ 'Keep-Alive': 'timeout=5, max=1000',
160
+ 'Proxy-Authorization': 'Basic 123456',
161
+ 'Custom-Header': 'test',
162
+ 'Allowed-Custom-Header': 'test',
163
+ },
164
+ })
165
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
166
+
167
+ expect(req.headers.get('Host')).toBe('example.com')
168
+ expect(req.headers.get('Connection')).toBeNull()
169
+ expect(req.headers.get('Keep-Alive')).toBeNull()
170
+ expect(req.headers.get('Proxy-Authorization')).toBeNull()
171
+ expect(req.headers.get('Custom-Header')).toBe('test')
172
+ expect(req.headers.get('Allowed-Custom-Header')).toBe('test')
173
+
174
+ expect(res.headers.get('Transfer-Encoding')).toBeNull()
175
+ })
176
+
177
+ it('remove hop-by-hop headers with strictConnectionProcessing', async () => {
178
+ const app = new Acryl()
179
+ app.get('/proxy/:path', (c) =>
180
+ proxy(`https://example.com/${c.req.param('path')}`, {
181
+ ...c.req,
182
+ strictConnectionProcessing: true,
183
+ })
184
+ )
185
+
186
+ const res = await app.request('/proxy/hop-by-hop', {
187
+ headers: {
188
+ Host: 'example.com',
189
+ Connection: 'keep-alive, custom-header',
190
+ 'Keep-Alive': 'timeout=5, max=1000',
191
+ 'Proxy-Authorization': 'Basic 123456',
192
+ 'Custom-Header': 'test',
193
+ 'Allowed-Custom-Header': 'test',
194
+ },
195
+ })
196
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
197
+
198
+ expect(req.headers.get('Host')).toBe('example.com')
199
+ expect(req.headers.get('Connection')).toBeNull()
200
+ expect(req.headers.get('Keep-Alive')).toBeNull()
201
+ expect(req.headers.get('Proxy-Authorization')).toBeNull()
202
+ expect(req.headers.get('Custom-Header')).toBeNull()
203
+ expect(req.headers.get('Allowed-Custom-Header')).toBe('test')
204
+
205
+ expect(res.headers.get('Transfer-Encoding')).toBeNull()
206
+ })
207
+
208
+ it('invalid hop-by-hop headers with strictConnectionProcessing', async () => {
209
+ const app = new Acryl()
210
+ app.get('/proxy/:path', (c) =>
211
+ proxy(`https://example.com/${c.req.param('path')}`, {
212
+ ...c.req,
213
+ strictConnectionProcessing: true,
214
+ })
215
+ )
216
+
217
+ const res = await app.request('/proxy/hop-by-hop', {
218
+ headers: {
219
+ Host: 'example.com',
220
+ Connection: 'keep-alive, invalid-header invalid-header',
221
+ 'Keep-Alive': 'timeout=5, max=1000',
222
+ },
223
+ })
224
+
225
+ expect(res.status).toBe(400)
226
+ })
227
+
228
+ it('specify hop-by-hop header by options', async () => {
229
+ const app = new Acryl()
230
+ app.get('/proxy/:path', (c) =>
231
+ proxy(`https://example.com/${c.req.param('path')}`, {
232
+ headers: {
233
+ 'Proxy-Authorization': 'Basic 123456',
234
+ },
235
+ })
236
+ )
237
+
238
+ const res = await app.request('/proxy/hop-by-hop')
239
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
240
+
241
+ expect(req.headers.get('Proxy-Authorization')).toBe('Basic 123456')
242
+
243
+ expect(res.headers.get('Transfer-Encoding')).toBeNull()
244
+ })
245
+
246
+ it('remove response headers listed in the Connection header', async () => {
247
+ const app = new Acryl()
248
+ app.get('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`))
249
+ const res = await app.request('/proxy/connection-listed')
250
+ expect(res.status).toBe(200)
251
+ expect(res.headers.get('Connection')).toBeNull()
252
+ expect(res.headers.get('X-Connection-Scoped')).toBeNull()
253
+ expect(res.headers.get('X-Normal')).toBe('kept')
254
+ })
255
+
256
+ it('modify header', async () => {
257
+ const app = new Acryl()
258
+ app.get('/proxy/:path', (c) =>
259
+ proxy(`https://example.com/${c.req.param('path')}`, {
260
+ headers: {
261
+ 'Set-Cookie': 'test=123',
262
+ },
263
+ }).then((res) => {
264
+ res.headers.delete('Set-Cookie')
265
+ res.headers.set('X-Response-Id', '456')
266
+ return res
267
+ })
268
+ )
269
+ const res = await app.request('/proxy/set-cookie')
270
+ expect(res.headers.get('Set-Cookie')).toBeNull()
271
+ expect(res.headers.get('X-Response-Id')).toBe('456')
272
+ })
273
+
274
+ it('does not propagate undefined request headers', async () => {
275
+ const app = new Acryl()
276
+ app.get('/proxy/:path', (c) =>
277
+ proxy(`https://example.com/${c.req.param('path')}`, {
278
+ headers: {
279
+ ...c.req.header(),
280
+ Authorization: undefined,
281
+ },
282
+ })
283
+ )
284
+ await app.request('/proxy/ok', {
285
+ headers: {
286
+ Authorization: 'Bearer 123',
287
+ },
288
+ })
289
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
290
+ expect(req.headers.get('Authorization')).toBeNull()
291
+ })
292
+
293
+ it('client disconnect', async () => {
294
+ const app = new Acryl()
295
+ const controller = new AbortController()
296
+ app.post('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`, c.req))
297
+ const resPromise = app.request('/proxy/disconnect', {
298
+ method: 'POST',
299
+ body: 'test',
300
+ signal: controller.signal,
301
+ })
302
+ controller.abort('client disconnect')
303
+ const res = await resPromise
304
+ expect(await res.text()).toBe('client disconnect')
305
+ })
306
+
307
+ it('not found', async () => {
308
+ const app = new Acryl()
309
+ app.get('/proxy/:path', (c) => proxy(`https://example.com/${c.req.param('path')}`))
310
+ const res = await app.request('/proxy/404')
311
+ expect(res.status).toBe(404)
312
+ })
313
+
314
+ it('pass a Request object to proxyInit', async () => {
315
+ const app = new Acryl()
316
+ app.get('/proxy/:path', (c) => {
317
+ const req = new Request(c.req.raw, {
318
+ headers: {
319
+ 'X-Request-Id': '123',
320
+ 'Accept-Encoding': 'gzip',
321
+ },
322
+ })
323
+ return proxy(`https://example.com/${c.req.param('path')}`, req)
324
+ })
325
+ const res = await app.request('/proxy/compressed')
326
+ const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]
327
+
328
+ expect(req.url).toBe('https://example.com/compressed')
329
+ expect(req.headers.get('X-Request-Id')).toBe('123')
330
+ expect(req.headers.get('Accept-Encoding')).toBeNull()
331
+
332
+ expect(res.status).toBe(200)
333
+ expect(await res.text()).toBe('ok')
334
+ })
335
+
336
+ it('Should call the custom fetch method when specified', async () => {
337
+ const customFetch = vi.fn().mockImplementation(async (req: Request) => {
338
+ const text = await req.text()
339
+ return new Response('custom fetch response. message:' + text)
340
+ })
341
+ const app = new Acryl()
342
+ app.post('/', (c) => {
343
+ return proxy(`https://example.com/`, {
344
+ customFetch,
345
+ ...c.req,
346
+ })
347
+ })
348
+ const res = await app.request('/', {
349
+ method: 'POST',
350
+ body: 'hi',
351
+ })
352
+ expect(res.status).toBe(200)
353
+ expect(await res.text()).toBe('custom fetch response. message:hi')
354
+ })
355
+ })
356
+ })