wrangler 0.0.0-e61907d → 0.0.0-e61dba50

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 (87) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +82 -0
  3. package/bin/wrangler.js +127 -2
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +179 -44
  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 +17 -0
  11. package/templates/gitignore +172 -0
  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 +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +15 -0
  30. package/templates/new-worker.ts +33 -0
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +32 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +105 -0
  41. package/templates/tsconfig.json +8 -0
  42. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  43. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  44. package/wrangler-dist/ProxyWorker.js +186 -0
  45. package/wrangler-dist/ProxyWorker.js.map +6 -0
  46. package/wrangler-dist/cli.d.ts +23850 -0
  47. package/wrangler-dist/cli.js +169454 -0
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  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/static-asset-facade.js +0 -47
  53. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  54. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  55. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  56. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  57. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  58. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  59. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  60. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  61. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  62. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  63. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  64. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  65. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  66. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  67. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  68. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  69. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  70. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  71. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  72. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  73. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  74. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  75. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  76. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  77. package/vendor/wrangler-mime/LICENSE +0 -21
  78. package/vendor/wrangler-mime/Mime.js +0 -97
  79. package/vendor/wrangler-mime/README.md +0 -187
  80. package/vendor/wrangler-mime/cli.js +0 -46
  81. package/vendor/wrangler-mime/index.js +0 -4
  82. package/vendor/wrangler-mime/lite.js +0 -4
  83. package/vendor/wrangler-mime/package.json +0 -52
  84. package/vendor/wrangler-mime/types/other.js +0 -1
  85. package/vendor/wrangler-mime/types/standard.js +0 -1
  86. package/wrangler-dist/index_node.js +0 -102507
  87. package/wrangler-dist/index_node.js.map +0 -7
@@ -0,0 +1,17 @@
1
+ declare module "__ENTRY_POINT__" {
2
+ import type { Middleware } from "./middleware/common";
3
+ const worker: ExportedHandler & {
4
+ middleware?: Middleware[];
5
+ envWrappers: ((env: Record<string, unknown>) => Record<string, unknown>)[];
6
+ };
7
+ export default worker;
8
+ }
9
+
10
+ declare module "__KV_ASSET_HANDLER__" {
11
+ export * from "@cloudflare/kv-asset-handler";
12
+ }
13
+
14
+ declare module "__STATIC_CONTENT_MANIFEST" {
15
+ const manifest: string;
16
+ export default manifest;
17
+ }
@@ -0,0 +1,172 @@
1
+ # Logs
2
+
3
+ logs
4
+ _.log
5
+ npm-debug.log_
6
+ yarn-debug.log*
7
+ yarn-error.log*
8
+ lerna-debug.log*
9
+ .pnpm-debug.log*
10
+
11
+ # Diagnostic reports (https://nodejs.org/api/report.html)
12
+
13
+ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
14
+
15
+ # Runtime data
16
+
17
+ pids
18
+ _.pid
19
+ _.seed
20
+ \*.pid.lock
21
+
22
+ # Directory for instrumented libs generated by jscoverage/JSCover
23
+
24
+ lib-cov
25
+
26
+ # Coverage directory used by tools like istanbul
27
+
28
+ coverage
29
+ \*.lcov
30
+
31
+ # nyc test coverage
32
+
33
+ .nyc_output
34
+
35
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
36
+
37
+ .grunt
38
+
39
+ # Bower dependency directory (https://bower.io/)
40
+
41
+ bower_components
42
+
43
+ # node-waf configuration
44
+
45
+ .lock-wscript
46
+
47
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
48
+
49
+ build/Release
50
+
51
+ # Dependency directories
52
+
53
+ node_modules/
54
+ jspm_packages/
55
+
56
+ # Snowpack dependency directory (https://snowpack.dev/)
57
+
58
+ web_modules/
59
+
60
+ # TypeScript cache
61
+
62
+ \*.tsbuildinfo
63
+
64
+ # Optional npm cache directory
65
+
66
+ .npm
67
+
68
+ # Optional eslint cache
69
+
70
+ .eslintcache
71
+
72
+ # Optional stylelint cache
73
+
74
+ .stylelintcache
75
+
76
+ # Microbundle cache
77
+
78
+ .rpt2_cache/
79
+ .rts2_cache_cjs/
80
+ .rts2_cache_es/
81
+ .rts2_cache_umd/
82
+
83
+ # Optional REPL history
84
+
85
+ .node_repl_history
86
+
87
+ # Output of 'npm pack'
88
+
89
+ \*.tgz
90
+
91
+ # Yarn Integrity file
92
+
93
+ .yarn-integrity
94
+
95
+ # dotenv environment variable files
96
+
97
+ .env
98
+ .env.development.local
99
+ .env.test.local
100
+ .env.production.local
101
+ .env.local
102
+
103
+ # parcel-bundler cache (https://parceljs.org/)
104
+
105
+ .cache
106
+ .parcel-cache
107
+
108
+ # Next.js build output
109
+
110
+ .next
111
+ out
112
+
113
+ # Nuxt.js build / generate output
114
+
115
+ .nuxt
116
+ dist
117
+
118
+ # Gatsby files
119
+
120
+ .cache/
121
+
122
+ # Comment in the public line in if your project uses Gatsby and not Next.js
123
+
124
+ # https://nextjs.org/blog/next-9-1#public-directory-support
125
+
126
+ # public
127
+
128
+ # vuepress build output
129
+
130
+ .vuepress/dist
131
+
132
+ # vuepress v2.x temp and cache directory
133
+
134
+ .temp
135
+ .cache
136
+
137
+ # Docusaurus cache and generated files
138
+
139
+ .docusaurus
140
+
141
+ # Serverless directories
142
+
143
+ .serverless/
144
+
145
+ # FuseBox cache
146
+
147
+ .fusebox/
148
+
149
+ # DynamoDB Local files
150
+
151
+ .dynamodb/
152
+
153
+ # TernJS port file
154
+
155
+ .tern-port
156
+
157
+ # Stores VSCode versions used for testing VSCode extensions
158
+
159
+ .vscode-test
160
+
161
+ # yarn v2
162
+
163
+ .yarn/cache
164
+ .yarn/unplugged
165
+ .yarn/build-state.yml
166
+ .yarn/install-state.gz
167
+ .pnp.\*
168
+
169
+ # wrangler project
170
+
171
+ .dev.vars
172
+ .wrangler/
@@ -0,0 +1,23 @@
1
+ const { unstable_dev } = require("wrangler");
2
+
3
+ describe("Worker", () => {
4
+ let worker;
5
+
6
+ beforeAll(async () => {
7
+ worker = await unstable_dev("src/index.js", {
8
+ experimental: { disableExperimentalWarning: true },
9
+ });
10
+ });
11
+
12
+ afterAll(async () => {
13
+ await worker.stop();
14
+ });
15
+
16
+ it("should return Hello World", async () => {
17
+ const resp = await worker.fetch();
18
+ if (resp) {
19
+ const text = await resp.text();
20
+ expect(text).toMatchInlineSnapshot(`"Hello World!"`);
21
+ }
22
+ });
23
+ });
@@ -0,0 +1,24 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
2
+ import { unstable_dev } from "wrangler";
3
+
4
+ describe("Worker", () => {
5
+ let worker;
6
+
7
+ beforeAll(async () => {
8
+ worker = await unstable_dev("src/index.js", {
9
+ experimental: { disableExperimentalWarning: true },
10
+ });
11
+ });
12
+
13
+ afterAll(async () => {
14
+ await worker.stop();
15
+ });
16
+
17
+ it("should return Hello World", async () => {
18
+ const resp = await worker.fetch();
19
+ if (resp) {
20
+ const text = await resp.text();
21
+ expect(text).toMatchInlineSnapshot(`"Hello World!"`);
22
+ }
23
+ });
24
+ });
@@ -0,0 +1,25 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
2
+ import { unstable_dev } from "wrangler";
3
+ import type { UnstableDevWorker } from "wrangler";
4
+
5
+ describe("Worker", () => {
6
+ let worker: UnstableDevWorker;
7
+
8
+ beforeAll(async () => {
9
+ worker = await unstable_dev("src/index.ts", {
10
+ experimental: { disableExperimentalWarning: true },
11
+ });
12
+ });
13
+
14
+ afterAll(async () => {
15
+ await worker.stop();
16
+ });
17
+
18
+ it("should return Hello World", async () => {
19
+ const resp = await worker.fetch();
20
+ if (resp) {
21
+ const text = await resp.text();
22
+ expect(text).toMatchInlineSnapshot(`"Hello World!"`);
23
+ }
24
+ });
25
+ });
@@ -0,0 +1,67 @@
1
+ export type Awaitable<T> = T | Promise<T>;
2
+ // TODO: allow dispatching more events?
3
+ export type Dispatcher = (
4
+ type: "scheduled",
5
+ init: { cron?: string }
6
+ ) => Awaitable<void>;
7
+
8
+ export type IncomingRequest = Request<
9
+ unknown,
10
+ IncomingRequestCfProperties<unknown>
11
+ >;
12
+
13
+ export interface MiddlewareContext {
14
+ dispatch: Dispatcher;
15
+ next(request: IncomingRequest, env: any): Awaitable<Response>;
16
+ }
17
+
18
+ export type Middleware = (
19
+ request: IncomingRequest,
20
+ env: any,
21
+ ctx: ExecutionContext,
22
+ middlewareCtx: MiddlewareContext
23
+ ) => Awaitable<Response>;
24
+
25
+ const __facade_middleware__: Middleware[] = [];
26
+
27
+ // The register functions allow for the insertion of one or many middleware,
28
+ // We register internal middleware first in the stack, but have no way of controlling
29
+ // the order that addMiddleware is run in service workers so need an internal function.
30
+ export function __facade_register__(...args: (Middleware | Middleware[])[]) {
31
+ __facade_middleware__.push(...args.flat());
32
+ }
33
+ export function __facade_registerInternal__(
34
+ ...args: (Middleware | Middleware[])[]
35
+ ) {
36
+ __facade_middleware__.unshift(...args.flat());
37
+ }
38
+
39
+ function __facade_invokeChain__(
40
+ request: IncomingRequest,
41
+ env: any,
42
+ ctx: ExecutionContext,
43
+ dispatch: Dispatcher,
44
+ middlewareChain: Middleware[]
45
+ ): Awaitable<Response> {
46
+ const [head, ...tail] = middlewareChain;
47
+ const middlewareCtx: MiddlewareContext = {
48
+ dispatch,
49
+ next(newRequest, newEnv) {
50
+ return __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail);
51
+ },
52
+ };
53
+ return head(request, env, ctx, middlewareCtx);
54
+ }
55
+
56
+ export function __facade_invoke__(
57
+ request: IncomingRequest,
58
+ env: any,
59
+ ctx: ExecutionContext,
60
+ dispatch: Dispatcher,
61
+ finalMiddleware: Middleware
62
+ ): Awaitable<Response> {
63
+ return __facade_invokeChain__(request, env, ctx, dispatch, [
64
+ ...__facade_middleware__,
65
+ finalMiddleware,
66
+ ]);
67
+ }
@@ -0,0 +1,136 @@
1
+ // // This loads all middlewares exposed on the middleware object
2
+ // // and then starts the invocation chain.
3
+ // // The big idea is that we can add these to the middleware export dynamically
4
+ // // through wrangler, or we can potentially let users directly add them as a sort
5
+ // // of "plugin" system.
6
+
7
+ import worker from "__ENTRY_POINT__";
8
+ import {
9
+ __facade_invoke__,
10
+ __facade_register__,
11
+ Dispatcher,
12
+ Middleware,
13
+ } from "./common";
14
+
15
+ // We need to preserve all of the exports from the worker
16
+ export * from "__ENTRY_POINT__";
17
+
18
+ class __Facade_ScheduledController__ implements ScheduledController {
19
+ #noRetry: ScheduledController["noRetry"];
20
+
21
+ constructor(
22
+ readonly scheduledTime: number,
23
+ readonly cron: string,
24
+ noRetry: ScheduledController["noRetry"]
25
+ ) {
26
+ this.#noRetry = noRetry;
27
+ }
28
+
29
+ noRetry() {
30
+ if (!(this instanceof __Facade_ScheduledController__)) {
31
+ throw new TypeError("Illegal invocation");
32
+ }
33
+ // Need to call native method immediately in case uncaught error thrown
34
+ this.#noRetry();
35
+ }
36
+ }
37
+
38
+ const __facade_modules_fetch__: ExportedHandlerFetchHandler = function (
39
+ request,
40
+ env,
41
+ ctx
42
+ ) {
43
+ if (worker.fetch === undefined)
44
+ throw new Error("Handler does not export a fetch() function.");
45
+ return worker.fetch(request, env, ctx);
46
+ };
47
+
48
+ function getMaskedEnv(rawEnv: unknown) {
49
+ let env = rawEnv as Record<string, unknown>;
50
+ if (worker.envWrappers && worker.envWrappers.length > 0) {
51
+ for (const wrapFn of worker.envWrappers) {
52
+ env = wrapFn(env);
53
+ }
54
+ }
55
+ return env;
56
+ }
57
+
58
+ /**
59
+ * This type is here to cause a type error if a new export handler is added to
60
+ * `ExportHandler` without it being included in the `facade` below.
61
+ */
62
+ type MissingExportHandlers = Omit<
63
+ Required<ExportedHandler>,
64
+ "tail" | "trace" | "scheduled" | "queue" | "test" | "email" | "fetch"
65
+ >;
66
+
67
+ let registeredMiddleware = false;
68
+
69
+ const facade: ExportedHandler<unknown> & MissingExportHandlers = {
70
+ ...(worker.tail && {
71
+ tail: maskHandlerEnv(worker.tail),
72
+ }),
73
+ ...(worker.trace && {
74
+ trace: maskHandlerEnv(worker.trace),
75
+ }),
76
+ ...(worker.scheduled && {
77
+ scheduled: maskHandlerEnv(worker.scheduled),
78
+ }),
79
+ ...(worker.queue && {
80
+ queue: maskHandlerEnv(worker.queue),
81
+ }),
82
+ ...(worker.test && {
83
+ test: maskHandlerEnv(worker.test),
84
+ }),
85
+ ...(worker.email && {
86
+ email: maskHandlerEnv(worker.email),
87
+ }),
88
+
89
+ fetch(request, rawEnv, ctx) {
90
+ const env = getMaskedEnv(rawEnv);
91
+ // Get the chain of middleware from the worker object
92
+ if (worker.middleware && worker.middleware.length > 0) {
93
+ // Make sure we only register middleware once:
94
+ // https://github.com/cloudflare/workers-sdk/issues/2386#issuecomment-1614715911
95
+ if (!registeredMiddleware) {
96
+ registeredMiddleware = true;
97
+ for (const middleware of worker.middleware) {
98
+ __facade_register__(middleware);
99
+ }
100
+ }
101
+
102
+ const __facade_modules_dispatch__: Dispatcher = function (type, init) {
103
+ if (type === "scheduled" && worker.scheduled !== undefined) {
104
+ const controller = new __Facade_ScheduledController__(
105
+ Date.now(),
106
+ init.cron ?? "",
107
+ () => {}
108
+ );
109
+ return worker.scheduled(controller, env, ctx);
110
+ }
111
+ };
112
+
113
+ return __facade_invoke__(
114
+ request,
115
+ env,
116
+ ctx,
117
+ __facade_modules_dispatch__,
118
+ __facade_modules_fetch__
119
+ );
120
+ } else {
121
+ // We didn't have any middleware so we can skip the invocation chain,
122
+ // and just call the fetch handler directly
123
+
124
+ // We "don't care" if this is undefined as we want to have the same behavior
125
+ // as if the worker completely bypassed middleware.
126
+ return __facade_modules_fetch__(request, env, ctx);
127
+ }
128
+ },
129
+ };
130
+
131
+ type HandlerFn<D, R> = (data: D, env: unknown, ctx: ExecutionContext) => R;
132
+ function maskHandlerEnv<D, R>(handler: HandlerFn<D, R>): HandlerFn<D, R> {
133
+ return (data, env, ctx) => handler(data, getMaskedEnv(env), ctx);
134
+ }
135
+
136
+ export default facade;
@@ -0,0 +1,229 @@
1
+ import {
2
+ __facade_invoke__,
3
+ __facade_register__,
4
+ __facade_registerInternal__,
5
+ Awaitable,
6
+ Dispatcher,
7
+ IncomingRequest,
8
+ Middleware,
9
+ } from "./common";
10
+
11
+ export { __facade_register__, __facade_registerInternal__ };
12
+
13
+ // Miniflare 2's `EventTarget` follows the spec and doesn't allow exceptions to
14
+ // be caught by `dispatchEvent`. Instead it has a custom `ThrowingEventTarget`
15
+ // class that rethrows errors from event listeners in `dispatchEvent`.
16
+ // We'd like errors to be propagated to the top-level `addEventListener`, so
17
+ // we'd like to use `ThrowingEventTarget`. Unfortunately, `ThrowingEventTarget`
18
+ // isn't exposed on the global scope, but `WorkerGlobalScope` (which extends
19
+ // `ThrowingEventTarget`) is. Therefore, we get at it in this nasty way.
20
+ let __FACADE_EVENT_TARGET__: EventTarget;
21
+ if ((globalThis as any).MINIFLARE) {
22
+ __FACADE_EVENT_TARGET__ = new (Object.getPrototypeOf(WorkerGlobalScope))();
23
+ } else {
24
+ __FACADE_EVENT_TARGET__ = new EventTarget();
25
+ }
26
+
27
+ function __facade_isSpecialEvent__(
28
+ type: string
29
+ ): type is "fetch" | "scheduled" {
30
+ return type === "fetch" || type === "scheduled";
31
+ }
32
+ const __facade__originalAddEventListener__ = globalThis.addEventListener;
33
+ const __facade__originalRemoveEventListener__ = globalThis.removeEventListener;
34
+ const __facade__originalDispatchEvent__ = globalThis.dispatchEvent;
35
+
36
+ globalThis.addEventListener = function (type, listener, options) {
37
+ if (__facade_isSpecialEvent__(type)) {
38
+ __FACADE_EVENT_TARGET__.addEventListener(
39
+ type,
40
+ listener as EventListenerOrEventListenerObject,
41
+ options
42
+ );
43
+ } else {
44
+ __facade__originalAddEventListener__(type, listener, options);
45
+ }
46
+ };
47
+ globalThis.removeEventListener = function (type, listener, options) {
48
+ if (__facade_isSpecialEvent__(type)) {
49
+ __FACADE_EVENT_TARGET__.removeEventListener(
50
+ type,
51
+ listener as EventListenerOrEventListenerObject,
52
+ options
53
+ );
54
+ } else {
55
+ __facade__originalRemoveEventListener__(type, listener, options);
56
+ }
57
+ };
58
+ globalThis.dispatchEvent = function (event) {
59
+ if (__facade_isSpecialEvent__(event.type)) {
60
+ return __FACADE_EVENT_TARGET__.dispatchEvent(event);
61
+ } else {
62
+ return __facade__originalDispatchEvent__(event);
63
+ }
64
+ };
65
+
66
+ declare global {
67
+ var addMiddleware: typeof __facade_register__;
68
+ var addMiddlewareInternal: typeof __facade_registerInternal__;
69
+ }
70
+ globalThis.addMiddleware = __facade_register__;
71
+ globalThis.addMiddlewareInternal = __facade_registerInternal__;
72
+
73
+ const __facade_waitUntil__ = Symbol("__facade_waitUntil__");
74
+ const __facade_response__ = Symbol("__facade_response__");
75
+ const __facade_dispatched__ = Symbol("__facade_dispatched__");
76
+
77
+ class __Facade_ExtendableEvent__ extends Event {
78
+ [__facade_waitUntil__]: Awaitable<unknown>[] = [];
79
+
80
+ waitUntil(promise: Awaitable<any>) {
81
+ if (!(this instanceof __Facade_ExtendableEvent__)) {
82
+ throw new TypeError("Illegal invocation");
83
+ }
84
+ this[__facade_waitUntil__].push(promise);
85
+ }
86
+ }
87
+
88
+ interface FetchEventInit extends EventInit {
89
+ request: Request;
90
+ passThroughOnException: FetchEvent["passThroughOnException"];
91
+ }
92
+
93
+ class __Facade_FetchEvent__ extends __Facade_ExtendableEvent__ {
94
+ #request: Request;
95
+ #passThroughOnException: FetchEvent["passThroughOnException"];
96
+ [__facade_response__]?: Awaitable<Response>;
97
+ [__facade_dispatched__] = false;
98
+
99
+ constructor(type: "fetch", init: FetchEventInit) {
100
+ super(type);
101
+ this.#request = init.request;
102
+ this.#passThroughOnException = init.passThroughOnException;
103
+ }
104
+
105
+ get request() {
106
+ return this.#request;
107
+ }
108
+
109
+ respondWith(response: Awaitable<Response>) {
110
+ if (!(this instanceof __Facade_FetchEvent__)) {
111
+ throw new TypeError("Illegal invocation");
112
+ }
113
+ if (this[__facade_response__] !== undefined) {
114
+ throw new DOMException(
115
+ "FetchEvent.respondWith() has already been called; it can only be called once.",
116
+ "InvalidStateError"
117
+ );
118
+ }
119
+ if (this[__facade_dispatched__]) {
120
+ throw new DOMException(
121
+ "Too late to call FetchEvent.respondWith(). It must be called synchronously in the event handler.",
122
+ "InvalidStateError"
123
+ );
124
+ }
125
+ this.stopImmediatePropagation();
126
+ this[__facade_response__] = response;
127
+ }
128
+
129
+ passThroughOnException() {
130
+ if (!(this instanceof __Facade_FetchEvent__)) {
131
+ throw new TypeError("Illegal invocation");
132
+ }
133
+ // Need to call native method immediately in case uncaught error thrown
134
+ this.#passThroughOnException();
135
+ }
136
+ }
137
+
138
+ interface ScheduledEventInit extends EventInit {
139
+ scheduledTime: number;
140
+ cron: string;
141
+ noRetry: ScheduledEvent["noRetry"];
142
+ }
143
+
144
+ class __Facade_ScheduledEvent__ extends __Facade_ExtendableEvent__ {
145
+ #scheduledTime: number;
146
+ #cron: string;
147
+ #noRetry: ScheduledEvent["noRetry"];
148
+
149
+ constructor(type: "scheduled", init: ScheduledEventInit) {
150
+ super(type);
151
+ this.#scheduledTime = init.scheduledTime;
152
+ this.#cron = init.cron;
153
+ this.#noRetry = init.noRetry;
154
+ }
155
+
156
+ get scheduledTime() {
157
+ return this.#scheduledTime;
158
+ }
159
+
160
+ get cron() {
161
+ return this.#cron;
162
+ }
163
+
164
+ noRetry() {
165
+ if (!(this instanceof __Facade_ScheduledEvent__)) {
166
+ throw new TypeError("Illegal invocation");
167
+ }
168
+ // Need to call native method immediately in case uncaught error thrown
169
+ this.#noRetry();
170
+ }
171
+ }
172
+
173
+ __facade__originalAddEventListener__("fetch", (event) => {
174
+ const ctx: ExecutionContext = {
175
+ waitUntil: event.waitUntil.bind(event),
176
+ passThroughOnException: event.passThroughOnException.bind(event),
177
+ };
178
+
179
+ const __facade_sw_dispatch__: Dispatcher = function (type, init) {
180
+ if (type === "scheduled") {
181
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
182
+ scheduledTime: Date.now(),
183
+ cron: init.cron ?? "",
184
+ noRetry() {},
185
+ });
186
+
187
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
188
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
189
+ }
190
+ };
191
+
192
+ const __facade_sw_fetch__: Middleware = function (request, _env, ctx) {
193
+ const facadeEvent = new __Facade_FetchEvent__("fetch", {
194
+ request,
195
+ passThroughOnException: ctx.passThroughOnException,
196
+ });
197
+
198
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
199
+ facadeEvent[__facade_dispatched__] = true;
200
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
201
+
202
+ const response = facadeEvent[__facade_response__];
203
+ if (response === undefined) {
204
+ throw new Error("No response!"); // TODO: proper error message
205
+ }
206
+ return response;
207
+ };
208
+
209
+ event.respondWith(
210
+ __facade_invoke__(
211
+ event.request as IncomingRequest,
212
+ globalThis,
213
+ ctx,
214
+ __facade_sw_dispatch__,
215
+ __facade_sw_fetch__
216
+ )
217
+ );
218
+ });
219
+
220
+ __facade__originalAddEventListener__("scheduled", (event) => {
221
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
222
+ scheduledTime: event.scheduledTime,
223
+ cron: event.cron,
224
+ noRetry: event.noRetry.bind(event),
225
+ });
226
+
227
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
228
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
229
+ });
@@ -0,0 +1,3 @@
1
+ declare module "config:middleware/d1-beta" {
2
+ export const D1_IMPORTS: string[];
3
+ }