wrangler 0.0.0-e64812e → 0.0.0-e6488257

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 (185) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +2947 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +114 -77
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +0 -4
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +24215 -0
  45. package/wrangler-dist/cli.js +188741 -107044
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/Cloudflare_CA.pem +0 -18
  48. package/import_meta_url.js +0 -3
  49. package/miniflare-config-stubs/.env.empty +0 -0
  50. package/miniflare-config-stubs/package.empty.json +0 -1
  51. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  52. package/miniflare-dist/index.mjs +0 -4886
  53. package/pages/functions/buildPlugin.ts +0 -105
  54. package/pages/functions/buildWorker.ts +0 -151
  55. package/pages/functions/filepath-routing.test.ts +0 -234
  56. package/pages/functions/filepath-routing.ts +0 -189
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -156
  59. package/pages/functions/template-plugin.ts +0 -147
  60. package/pages/functions/template-worker.ts +0 -143
  61. package/src/__tests__/config-cache.test.ts +0 -36
  62. package/src/__tests__/configuration.test.ts +0 -3374
  63. package/src/__tests__/dev.test.tsx +0 -980
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  71. package/src/__tests__/helpers/mock-console.ts +0 -87
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -27
  75. package/src/__tests__/helpers/mock-kv.ts +0 -33
  76. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  80. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  81. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  82. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  83. package/src/__tests__/https-options.test.ts +0 -130
  84. package/src/__tests__/index.test.ts +0 -256
  85. package/src/__tests__/init.test.ts +0 -1634
  86. package/src/__tests__/jest.setup.ts +0 -77
  87. package/src/__tests__/kv.test.ts +0 -1481
  88. package/src/__tests__/logger.test.ts +0 -115
  89. package/src/__tests__/package-manager.test.ts +0 -353
  90. package/src/__tests__/pages.test.ts +0 -754
  91. package/src/__tests__/parse.test.ts +0 -330
  92. package/src/__tests__/publish.test.ts +0 -5468
  93. package/src/__tests__/r2.test.ts +0 -233
  94. package/src/__tests__/route.test.ts +0 -45
  95. package/src/__tests__/secret.test.ts +0 -481
  96. package/src/__tests__/tail.test.ts +0 -690
  97. package/src/__tests__/user.test.ts +0 -131
  98. package/src/__tests__/whoami.test.tsx +0 -105
  99. package/src/abort.d.ts +0 -3
  100. package/src/bundle.ts +0 -200
  101. package/src/cfetch/index.ts +0 -121
  102. package/src/cfetch/internal.ts +0 -145
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -420
  108. package/src/config/index.ts +0 -225
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1539
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -185
  113. package/src/create-worker-upload-form.ts +0 -254
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -419
  116. package/src/dev/local.tsx +0 -318
  117. package/src/dev/remote.tsx +0 -227
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -135
  120. package/src/durable.ts +0 -102
  121. package/src/entry.ts +0 -322
  122. package/src/environment-variables.ts +0 -35
  123. package/src/errors.ts +0 -11
  124. package/src/https-options.ts +0 -123
  125. package/src/index.tsx +0 -2864
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/kv.ts +0 -408
  129. package/src/logger.ts +0 -66
  130. package/src/miniflare-cli/README.md +0 -30
  131. package/src/miniflare-cli/enum-keys.ts +0 -17
  132. package/src/miniflare-cli/index.ts +0 -41
  133. package/src/miniflare-cli/request-context.ts +0 -40
  134. package/src/module-collection.ts +0 -258
  135. package/src/open-in-browser.ts +0 -19
  136. package/src/package-manager.ts +0 -174
  137. package/src/pages.tsx +0 -2038
  138. package/src/parse.ts +0 -202
  139. package/src/paths.ts +0 -26
  140. package/src/proxy.ts +0 -465
  141. package/src/publish.ts +0 -583
  142. package/src/r2.ts +0 -50
  143. package/src/selfsigned.d.ts +0 -29
  144. package/src/sites.tsx +0 -295
  145. package/src/tail/filters.ts +0 -279
  146. package/src/tail/index.ts +0 -299
  147. package/src/tail/printing.ts +0 -67
  148. package/src/update-check.ts +0 -19
  149. package/src/user.tsx +0 -1203
  150. package/src/whoami.tsx +0 -70
  151. package/src/worker.ts +0 -180
  152. package/templates/static-asset-facade.js +0 -47
  153. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  155. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  156. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  158. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  160. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  168. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  169. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  170. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  171. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  174. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  175. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  176. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  177. package/vendor/wrangler-mime/LICENSE +0 -21
  178. package/vendor/wrangler-mime/Mime.js +0 -97
  179. package/vendor/wrangler-mime/README.md +0 -187
  180. package/vendor/wrangler-mime/cli.js +0 -46
  181. package/vendor/wrangler-mime/index.js +0 -4
  182. package/vendor/wrangler-mime/lite.js +0 -4
  183. package/vendor/wrangler-mime/package.json +0 -52
  184. package/vendor/wrangler-mime/types/other.js +0 -1
  185. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -0,0 +1,32 @@
1
+ // @ts-ignore entry point will get replaced
2
+ import worker from "__ENTRY_POINT__";
3
+ import { isRoutingRuleMatch } from "./pages-dev-util";
4
+
5
+ // @ts-ignore entry point will get replaced
6
+ export * from "__ENTRY_POINT__";
7
+
8
+ // @ts-ignore routes are injected
9
+ const routes = __ROUTES__;
10
+
11
+ export default <ExportedHandler<{ ASSETS: Fetcher }>>{
12
+ fetch(request, env, context) {
13
+ const { pathname } = new URL(request.url);
14
+
15
+ for (const exclude of routes.exclude) {
16
+ if (isRoutingRuleMatch(pathname, exclude)) {
17
+ return env.ASSETS.fetch(request);
18
+ }
19
+ }
20
+
21
+ for (const include of routes.include) {
22
+ if (isRoutingRuleMatch(pathname, include)) {
23
+ if (worker.fetch === undefined) {
24
+ throw new TypeError("Entry point missing `fetch` handler");
25
+ }
26
+ return worker.fetch(request, env, context);
27
+ }
28
+ }
29
+
30
+ return env.ASSETS.fetch(request);
31
+ },
32
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @param pathname A pathname string, such as `/foo` or `/foo/bar`
3
+ * @param routingRule The routing rule, such as `/foo/*`
4
+ * @returns True if pathname matches the routing rule
5
+ *
6
+ * / -> /
7
+ * /* -> /*
8
+ * /foo -> /foo
9
+ * /foo* -> /foo, /foo-bar, /foo/*
10
+ * /foo/* -> /foo, /foo/bar
11
+ */
12
+ export function isRoutingRuleMatch(
13
+ pathname: string,
14
+ routingRule: string
15
+ ): boolean {
16
+ // sanity checks
17
+ if (!pathname) {
18
+ throw new Error("Pathname is undefined.");
19
+ }
20
+ if (!routingRule) {
21
+ throw new Error("Routing rule is undefined.");
22
+ }
23
+
24
+ const ruleRegExp = transformRoutingRuleToRegExp(routingRule);
25
+ return pathname.match(ruleRegExp) !== null;
26
+ }
27
+
28
+ function transformRoutingRuleToRegExp(rule: string): RegExp {
29
+ let transformedRule;
30
+
31
+ if (rule === "/" || rule === "/*") {
32
+ transformedRule = rule;
33
+ } else if (rule.endsWith("/*")) {
34
+ // make `/*` an optional group so we can match both /foo/* and /foo
35
+ // /foo/* => /foo(/*)?
36
+ transformedRule = `${rule.substring(0, rule.length - 2)}(/*)?`;
37
+ } else if (rule.endsWith("/")) {
38
+ // make `/` an optional group so we can match both /foo/ and /foo
39
+ // /foo/ => /foo(/)?
40
+ transformedRule = `${rule.substring(0, rule.length - 1)}(/)?`;
41
+ } else if (rule.endsWith("*")) {
42
+ transformedRule = rule;
43
+ } else {
44
+ transformedRule = `${rule}(/)?`;
45
+ }
46
+
47
+ // /foo* => /foo.* => ^/foo.*$
48
+ // /*.* => /*\.* => /.*\..* => ^/.*\..*$
49
+ transformedRule = `^${transformedRule
50
+ .replaceAll(/\./g, "\\.")
51
+ .replaceAll(/\*/g, ".*")}$`;
52
+
53
+ // ^/foo.*$ => /^\/foo.*$/
54
+ return new RegExp(transformedRule);
55
+ }
@@ -0,0 +1,9 @@
1
+ // This Worker is used as a default when no Pages Functions are present.
2
+ // It proxies the request directly on to the asset server binding.
3
+
4
+ export default <ExportedHandler<{ ASSETS: Fetcher }>>{
5
+ async fetch(request, env, context) {
6
+ const response = await env.ASSETS.fetch(request.url, request);
7
+ return new Response(response.body, response);
8
+ },
9
+ };
@@ -0,0 +1,190 @@
1
+ import { match } from "path-to-regexp";
2
+
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
6
+ type HTTPMethod =
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
14
+
15
+ /* TODO: Grab these from @cloudflare/workers-types instead */
16
+ type Params<P extends string = string> = Record<P, string | string[]>;
17
+
18
+ type EventContext<Env, P extends string, Data> = {
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ passThroughOnException: () => void;
23
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
24
+ env: Env & { ASSETS: { fetch: typeof fetch } };
25
+ params: Params<P>;
26
+ data: Data;
27
+ };
28
+
29
+ type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
30
+ request: Request;
31
+ functionPath: string;
32
+ waitUntil: (promise: Promise<unknown>) => void;
33
+ passThroughOnException: () => void;
34
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
35
+ env: Env & { ASSETS: { fetch: typeof fetch } };
36
+ params: Params<P>;
37
+ data: Data;
38
+ pluginArgs: PluginArgs;
39
+ };
40
+
41
+ declare type PagesFunction<
42
+ Env = unknown,
43
+ P extends string = string,
44
+ Data extends Record<string, unknown> = Record<string, unknown>,
45
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
46
+
47
+ declare type PagesPluginFunction<
48
+ Env = unknown,
49
+ P extends string = string,
50
+ Data extends Record<string, unknown> = Record<string, unknown>,
51
+ PluginArgs = unknown,
52
+ > = (
53
+ context: EventPluginContext<Env, P, Data, PluginArgs>
54
+ ) => Response | Promise<Response>;
55
+ /* end @cloudflare/workers-types */
56
+
57
+ type RouteHandler = {
58
+ routePath: string;
59
+ mountPath: string;
60
+ method?: HTTPMethod;
61
+ modules: PagesFunction[];
62
+ middlewares: PagesFunction[];
63
+ };
64
+
65
+ // inject `routes` via ESBuild
66
+ declare const routes: RouteHandler[];
67
+
68
+ function* executeRequest(request: Request, relativePathname: string) {
69
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
70
+ for (const route of [...routes].reverse()) {
71
+ if (route.method && route.method !== request.method) {
72
+ continue;
73
+ }
74
+
75
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
76
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
77
+ end: false,
78
+ });
79
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
80
+ end: false,
81
+ });
82
+ const matchResult = routeMatcher(relativePathname);
83
+ const mountMatchResult = mountMatcher(relativePathname);
84
+ if (matchResult && mountMatchResult) {
85
+ for (const handler of route.middlewares.flat()) {
86
+ yield {
87
+ handler,
88
+ params: matchResult.params as Params,
89
+ path: mountMatchResult.path,
90
+ };
91
+ }
92
+ }
93
+ }
94
+
95
+ // Then look for the first exact route match and execute its "modules"
96
+ for (const route of routes) {
97
+ if (route.method && route.method !== request.method) {
98
+ continue;
99
+ }
100
+
101
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
102
+ end: true,
103
+ });
104
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
105
+ end: false,
106
+ });
107
+ const matchResult = routeMatcher(relativePathname);
108
+ const mountMatchResult = mountMatcher(relativePathname);
109
+ if (matchResult && mountMatchResult && route.modules.length) {
110
+ for (const handler of route.modules.flat()) {
111
+ yield {
112
+ handler,
113
+ params: matchResult.params as Params,
114
+ path: matchResult.path,
115
+ };
116
+ }
117
+ break;
118
+ }
119
+ }
120
+ }
121
+
122
+ export default function (pluginArgs: unknown) {
123
+ const onRequest: PagesPluginFunction = async (workerContext) => {
124
+ let { request } = workerContext;
125
+ const { env, next } = workerContext;
126
+ let { data } = workerContext;
127
+
128
+ const url = new URL(request.url);
129
+ // TODO: Replace this with something actually legible.
130
+ const relativePathname = `/${
131
+ url.pathname.replace(workerContext.functionPath, "") || ""
132
+ }`.replace(/^\/\//, "/");
133
+
134
+ const handlerIterator = executeRequest(request, relativePathname);
135
+ const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
136
+ if (input !== undefined) {
137
+ let url = input;
138
+ if (typeof input === "string") {
139
+ url = new URL(input, request.url).toString();
140
+ }
141
+ request = new Request(url, init);
142
+ }
143
+
144
+ const result = handlerIterator.next();
145
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
146
+ if (result.done === false) {
147
+ const { handler, params, path } = result.value;
148
+ const context = {
149
+ request: new Request(request.clone()),
150
+ functionPath: workerContext.functionPath + path,
151
+ next: pluginNext,
152
+ params,
153
+ get data() {
154
+ return data;
155
+ },
156
+ set data(value) {
157
+ if (typeof value !== "object" || value === null) {
158
+ throw new Error("context.data must be an object");
159
+ }
160
+ // user has overriden context.data, so we need to merge it with the existing data
161
+ data = value;
162
+ },
163
+ pluginArgs,
164
+ env,
165
+ waitUntil: workerContext.waitUntil.bind(workerContext),
166
+ passThroughOnException:
167
+ workerContext.passThroughOnException.bind(workerContext),
168
+ };
169
+
170
+ const response = await handler(context);
171
+
172
+ return cloneResponse(response);
173
+ } else {
174
+ return next(request);
175
+ }
176
+ };
177
+
178
+ return pluginNext();
179
+ };
180
+
181
+ return onRequest;
182
+ }
183
+
184
+ // This makes a Response mutable
185
+ const cloneResponse = (response: Response) =>
186
+ // https://fetch.spec.whatwg.org/#null-body-status
187
+ new Response(
188
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
189
+ response
190
+ );
@@ -0,0 +1,198 @@
1
+ import { match } from "path-to-regexp";
2
+
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
6
+ type HTTPMethod =
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
14
+
15
+ /* TODO: Grab these from @cloudflare/workers-types instead */
16
+ type Params<P extends string = string> = Record<P, string | string[]>;
17
+
18
+ type EventContext<Env, P extends string, Data> = {
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ passThroughOnException: () => void;
23
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
24
+ env: Env & { ASSETS: { fetch: typeof fetch } };
25
+ params: Params<P>;
26
+ data: Data;
27
+ };
28
+
29
+ declare type PagesFunction<
30
+ Env = unknown,
31
+ P extends string = string,
32
+ Data extends Record<string, unknown> = Record<string, unknown>,
33
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
34
+ /* end @cloudflare/workers-types */
35
+
36
+ type RouteHandler = {
37
+ routePath: string;
38
+ mountPath: string;
39
+ method?: HTTPMethod;
40
+ modules: PagesFunction[];
41
+ middlewares: PagesFunction[];
42
+ };
43
+
44
+ // inject `routes` via ESBuild
45
+ declare const routes: RouteHandler[];
46
+ // define `__FALLBACK_SERVICE__` via ESBuild
47
+ declare const __FALLBACK_SERVICE__: string;
48
+
49
+ // expect an ASSETS fetcher binding pointing to the asset-server stage
50
+ type FetchEnv = {
51
+ [name: string]: { fetch: typeof fetch };
52
+ ASSETS: { fetch: typeof fetch };
53
+ };
54
+
55
+ type WorkerContext = {
56
+ waitUntil: (promise: Promise<unknown>) => void;
57
+ passThroughOnException: () => void;
58
+ };
59
+
60
+ function* executeRequest(request: Request) {
61
+ const requestPath = new URL(request.url).pathname;
62
+
63
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
64
+ for (const route of [...routes].reverse()) {
65
+ if (route.method && route.method !== request.method) {
66
+ continue;
67
+ }
68
+
69
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
70
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
71
+ end: false,
72
+ });
73
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
74
+ end: false,
75
+ });
76
+ const matchResult = routeMatcher(requestPath);
77
+ const mountMatchResult = mountMatcher(requestPath);
78
+ if (matchResult && mountMatchResult) {
79
+ for (const handler of route.middlewares.flat()) {
80
+ yield {
81
+ handler,
82
+ params: matchResult.params as Params,
83
+ path: mountMatchResult.path,
84
+ };
85
+ }
86
+ }
87
+ }
88
+
89
+ // Then look for the first exact route match and execute its "modules"
90
+ for (const route of routes) {
91
+ if (route.method && route.method !== request.method) {
92
+ continue;
93
+ }
94
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
95
+ end: true,
96
+ });
97
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
98
+ end: false,
99
+ });
100
+ const matchResult = routeMatcher(requestPath);
101
+ const mountMatchResult = mountMatcher(requestPath);
102
+ if (matchResult && mountMatchResult && route.modules.length) {
103
+ for (const handler of route.modules.flat()) {
104
+ yield {
105
+ handler,
106
+ params: matchResult.params as Params,
107
+ path: matchResult.path,
108
+ };
109
+ }
110
+ break;
111
+ }
112
+ }
113
+ }
114
+
115
+ export default {
116
+ async fetch(
117
+ originalRequest: Request,
118
+ env: FetchEnv,
119
+ workerContext: WorkerContext
120
+ ) {
121
+ let request = originalRequest;
122
+ const handlerIterator = executeRequest(request);
123
+ let data = {}; // arbitrary data the user can set between functions
124
+ let isFailOpen = false;
125
+
126
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
127
+ if (input !== undefined) {
128
+ let url = input;
129
+ if (typeof input === "string") {
130
+ url = new URL(input, request.url).toString();
131
+ }
132
+ request = new Request(url, init);
133
+ }
134
+
135
+ const result = handlerIterator.next();
136
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
137
+ if (result.done === false) {
138
+ const { handler, params, path } = result.value;
139
+ const context = {
140
+ request: new Request(request.clone()),
141
+ functionPath: path,
142
+ next,
143
+ params,
144
+ get data() {
145
+ return data;
146
+ },
147
+ set data(value) {
148
+ if (typeof value !== "object" || value === null) {
149
+ throw new Error("context.data must be an object");
150
+ }
151
+ // user has overriden context.data, so we need to merge it with the existing data
152
+ data = value;
153
+ },
154
+ env,
155
+ waitUntil: workerContext.waitUntil.bind(workerContext),
156
+ passThroughOnException: () => {
157
+ isFailOpen = true;
158
+ },
159
+ };
160
+
161
+ const response = await handler(context);
162
+
163
+ if (!(response instanceof Response)) {
164
+ throw new Error("Your Pages function should return a Response");
165
+ }
166
+
167
+ return cloneResponse(response);
168
+ } else if (__FALLBACK_SERVICE__) {
169
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
170
+ const response = await env[__FALLBACK_SERVICE__].fetch(request);
171
+ return cloneResponse(response);
172
+ } else {
173
+ // There was not fallback service so actually make the request to the origin.
174
+ const response = await fetch(request);
175
+ return cloneResponse(response);
176
+ }
177
+ };
178
+
179
+ try {
180
+ return await next();
181
+ } catch (error) {
182
+ if (isFailOpen) {
183
+ const response = await env[__FALLBACK_SERVICE__].fetch(request);
184
+ return cloneResponse(response);
185
+ }
186
+
187
+ throw error;
188
+ }
189
+ },
190
+ };
191
+
192
+ // This makes a Response mutable
193
+ const cloneResponse = (response: Response) =>
194
+ // https://fetch.spec.whatwg.org/#null-body-status
195
+ new Response(
196
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
197
+ response
198
+ );