-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathindex.ts
176 lines (163 loc) · 5.28 KB
/
index.ts
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import type {
ServerRenderOptions,
ServerRequestEvent,
} from '@builder.io/qwik-city/middleware/request-handler';
import {
mergeHeadersCookies,
requestHandler,
} from '@builder.io/qwik-city/middleware/request-handler';
import { getNotFound } from '@qwik-city-not-found-paths';
import { isStaticPath } from '@qwik-city-static-paths';
import { _deserializeData, _serializeData, _verifySerializable } from '@builder.io/qwik';
import { setServerPlatform } from '@builder.io/qwik/server';
// @builder.io/qwik-city/middleware/cloudflare-pages
/** @public */
export function createQwikCity(opts: QwikCityCloudflarePagesOptions) {
try {
// https://developers.cloudflare.com/workers/configuration/compatibility-dates/#streams-constructors
// this will throw if CF compatibility_date < 2022-11-30
new globalThis.TextEncoderStream();
} catch (e) {
(globalThis as any).TextEncoderStream = TextEncoderStream;
}
const qwikSerializer = {
_deserializeData,
_serializeData,
_verifySerializable,
};
if (opts.manifest) {
setServerPlatform(opts.manifest);
}
async function onCloudflarePagesFetch(
request: PlatformCloudflarePages['request'],
env: PlatformCloudflarePages['env'] & { ASSETS: { fetch: (req: Request) => Response } },
ctx: PlatformCloudflarePages['ctx']
) {
try {
const url = new URL(request.url);
if (isStaticPath(request.method, url)) {
// known static path, let cloudflare handle it
return env.ASSETS.fetch(request);
}
// https://developers.cloudflare.com/workers/runtime-apis/cache/
const useCache =
url.hostname !== '127.0.0.1' &&
url.hostname !== 'localhost' &&
url.port === '' &&
request.method === 'GET';
const cacheKey = new Request(url.href, request);
const cache = useCache ? await caches.open('custom:qwikcity') : null;
if (cache) {
const cachedResponse = await cache.match(cacheKey);
if (cachedResponse) {
return cachedResponse;
}
}
const serverRequestEv: ServerRequestEvent<Response> = {
mode: 'server',
locale: undefined,
url,
request,
env: {
get(key) {
return env[key];
},
},
getWritableStream: (status, headers, cookies, resolve) => {
const { readable, writable } = new TransformStream<Uint8Array>();
const response = new Response(readable, {
status,
headers: mergeHeadersCookies(headers, cookies),
});
resolve(response);
return writable;
},
getClientConn: () => {
return {
ip: request.headers.get('CF-connecting-ip') || '',
country: request.headers.get('CF-IPCountry') || '',
};
},
platform: {
request,
env,
ctx,
},
};
// send request to qwik city request handler
const handledResponse = await requestHandler(serverRequestEv, opts, qwikSerializer);
if (handledResponse) {
handledResponse.completion.then((v) => {
if (v) {
console.error(v);
}
});
const response = await handledResponse.response;
if (response) {
if (response.ok && cache && response.headers.has('Cache-Control')) {
// Store the fetched response as cacheKey
// Use waitUntil so you can return the response without blocking on
// writing to cache
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
return response;
}
}
// qwik city did not have a route for this request
// response with 404 for this pathname
const notFoundHtml = getNotFound(url.pathname);
return new Response(notFoundHtml, {
status: 404,
headers: { 'Content-Type': 'text/html; charset=utf-8', 'X-Not-Found': url.pathname },
});
} catch (e: any) {
console.error(e);
return new Response(String(e || 'Error'), {
status: 500,
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Error': 'cloudflare-pages' },
});
}
}
return onCloudflarePagesFetch;
}
/** @public */
export interface QwikCityCloudflarePagesOptions extends ServerRenderOptions {}
/** @public */
export interface PlatformCloudflarePages {
request: Request;
env?: Record<string, any>;
ctx: { waitUntil: (promise: Promise<any>) => void };
}
const resolved = Promise.resolve();
class TextEncoderStream {
// minimal polyfill implementation of TextEncoderStream
// since Cloudflare Pages doesn't support readable.pipeTo()
_writer: any;
readable: any;
writable: any;
constructor() {
this._writer = null;
this.readable = {
pipeTo: (writableStream: any) => {
this._writer = writableStream.getWriter();
},
};
this.writable = {
getWriter: () => {
if (!this._writer) {
throw new Error('No writable stream');
}
const encoder = new TextEncoder();
return {
write: async (chunk: any) => {
if (chunk != null) {
await this._writer.write(encoder.encode(chunk));
}
},
close: () => this._writer.close(),
ready: resolved,
};
},
};
}
}