wrangler 0.0.0-e3cab74 → 0.0.0-e3d46ab3

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 (158) hide show
  1. package/README.md +47 -16
  2. package/bin/wrangler.js +95 -32
  3. package/config-schema.json +2939 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +135 -84
  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 +167 -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 +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 +17 -0
  26. package/templates/new-worker-scheduled.ts +32 -0
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +22 -4
  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 +24056 -0
  45. package/wrangler-dist/cli.js +199391 -131806
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/pages/functions/buildWorker.ts +0 -62
  52. package/pages/functions/filepath-routing.test.ts +0 -123
  53. package/pages/functions/filepath-routing.ts +0 -178
  54. package/pages/functions/identifiers.ts +0 -78
  55. package/pages/functions/routes.ts +0 -151
  56. package/pages/functions/template-worker.ts +0 -130
  57. package/src/__tests__/configuration.test.ts +0 -2185
  58. package/src/__tests__/dev.test.tsx +0 -113
  59. package/src/__tests__/guess-worker-format.test.ts +0 -66
  60. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  61. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  62. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  63. package/src/__tests__/helpers/mock-account-id.ts +0 -30
  64. package/src/__tests__/helpers/mock-bin.ts +0 -36
  65. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  66. package/src/__tests__/helpers/mock-console.ts +0 -62
  67. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  68. package/src/__tests__/helpers/mock-kv.ts +0 -40
  69. package/src/__tests__/helpers/mock-user.ts +0 -27
  70. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  71. package/src/__tests__/helpers/run-in-tmp.ts +0 -29
  72. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  73. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  74. package/src/__tests__/index.test.ts +0 -866
  75. package/src/__tests__/jest.setup.ts +0 -57
  76. package/src/__tests__/kv.test.ts +0 -1141
  77. package/src/__tests__/logout.test.ts +0 -50
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/parse.test.ts +0 -322
  80. package/src/__tests__/publish.test.ts +0 -2406
  81. package/src/__tests__/r2.test.ts +0 -198
  82. package/src/__tests__/secret.test.ts +0 -326
  83. package/src/__tests__/sentry.test.ts +0 -146
  84. package/src/__tests__/tail.test.ts +0 -564
  85. package/src/__tests__/whoami.test.tsx +0 -86
  86. package/src/api/form_data.ts +0 -217
  87. package/src/api/preview.ts +0 -147
  88. package/src/api/worker.ts +0 -186
  89. package/src/bundle.ts +0 -133
  90. package/src/cfetch/index.ts +0 -104
  91. package/src/cfetch/internal.ts +0 -133
  92. package/src/cli.ts +0 -19
  93. package/src/config/README.md +0 -107
  94. package/src/config/config.ts +0 -265
  95. package/src/config/diagnostics.ts +0 -80
  96. package/src/config/environment.ts +0 -305
  97. package/src/config/index.ts +0 -52
  98. package/src/config/validation-helpers.ts +0 -370
  99. package/src/config/validation.ts +0 -1017
  100. package/src/dev.tsx +0 -961
  101. package/src/dialogs.tsx +0 -77
  102. package/src/entry.ts +0 -57
  103. package/src/environment-variables.ts +0 -33
  104. package/src/guess-worker-format.ts +0 -68
  105. package/src/index.tsx +0 -2327
  106. package/src/inspect.ts +0 -609
  107. package/src/kv.tsx +0 -275
  108. package/src/module-collection.ts +0 -170
  109. package/src/open-in-browser.ts +0 -13
  110. package/src/package-manager.ts +0 -126
  111. package/src/pages.tsx +0 -1045
  112. package/src/parse.ts +0 -183
  113. package/src/paths.ts +0 -26
  114. package/src/proxy.ts +0 -376
  115. package/src/publish.ts +0 -368
  116. package/src/r2.ts +0 -50
  117. package/src/reporting.ts +0 -115
  118. package/src/sites.tsx +0 -241
  119. package/src/tail/filters.ts +0 -279
  120. package/src/tail/index.ts +0 -299
  121. package/src/tail/printing.ts +0 -62
  122. package/src/user.tsx +0 -1049
  123. package/src/whoami.tsx +0 -69
  124. package/templates/static-asset-facade.js +0 -47
  125. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  126. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  127. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  128. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  129. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  130. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  131. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  132. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  133. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  134. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  137. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  138. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  139. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  140. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  141. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  142. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  143. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  144. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  145. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  146. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  147. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  148. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  149. package/vendor/wrangler-mime/LICENSE +0 -21
  150. package/vendor/wrangler-mime/Mime.js +0 -97
  151. package/vendor/wrangler-mime/README.md +0 -187
  152. package/vendor/wrangler-mime/cli.js +0 -46
  153. package/vendor/wrangler-mime/index.js +0 -4
  154. package/vendor/wrangler-mime/lite.js +0 -4
  155. package/vendor/wrangler-mime/package.json +0 -52
  156. package/vendor/wrangler-mime/types/other.js +0 -1
  157. package/vendor/wrangler-mime/types/standard.js +0 -1
  158. package/wrangler-dist/cli.js.map +0 -7
@@ -1,217 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { FormData, File } from "undici";
3
- import type {
4
- CfWorkerInit,
5
- CfModuleType,
6
- CfDurableObjectMigrations,
7
- } from "./worker.js";
8
-
9
- export function toMimeType(type: CfModuleType): string {
10
- switch (type) {
11
- case "esm":
12
- return "application/javascript+module";
13
- case "commonjs":
14
- return "application/javascript";
15
- case "compiled-wasm":
16
- return "application/wasm";
17
- case "buffer":
18
- return "application/octet-stream";
19
- case "text":
20
- return "text/plain";
21
- default:
22
- throw new TypeError("Unsupported module: " + type);
23
- }
24
- }
25
-
26
- export interface WorkerMetadata {
27
- /** The name of the entry point module. Only exists when the worker is in the ES module format */
28
- main_module?: string;
29
- /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
30
- body_part?: string;
31
- compatibility_date?: string;
32
- compatibility_flags?: string[];
33
- usage_model?: "bundled" | "unbound";
34
- migrations?: CfDurableObjectMigrations;
35
- bindings: (
36
- | { type: "kv_namespace"; name: string; namespace_id: string }
37
- | { type: "plain_text"; name: string; text: string }
38
- | { type: "json"; name: string; json: unknown }
39
- | { type: "wasm_module"; name: string; part: string }
40
- | { type: "text_blob"; name: string; part: string }
41
- | {
42
- type: "durable_object_namespace";
43
- name: string;
44
- class_name: string;
45
- script_name?: string;
46
- }
47
- | { type: "r2_bucket"; name: string; bucket_name: string }
48
- )[];
49
- }
50
-
51
- /**
52
- * Creates a `FormData` upload from a `CfWorkerInit`.
53
- */
54
- export function toFormData(worker: CfWorkerInit): FormData {
55
- const formData = new FormData();
56
- const {
57
- main,
58
- bindings,
59
- migrations,
60
- usage_model,
61
- compatibility_date,
62
- compatibility_flags,
63
- } = worker;
64
-
65
- let { modules } = worker;
66
-
67
- const metadataBindings: WorkerMetadata["bindings"] = [];
68
-
69
- bindings.kv_namespaces?.forEach(({ id, binding }) => {
70
- metadataBindings.push({
71
- name: binding,
72
- type: "kv_namespace",
73
- namespace_id: id,
74
- });
75
- });
76
-
77
- bindings.durable_objects?.bindings.forEach(
78
- ({ name, class_name, script_name }) => {
79
- metadataBindings.push({
80
- name,
81
- type: "durable_object_namespace",
82
- class_name: class_name,
83
- ...(script_name && { script_name }),
84
- });
85
- }
86
- );
87
-
88
- bindings.r2_buckets?.forEach(({ binding, bucket_name }) => {
89
- metadataBindings.push({
90
- name: binding,
91
- type: "r2_bucket",
92
- bucket_name,
93
- });
94
- });
95
-
96
- Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
97
- if (typeof value === "string") {
98
- metadataBindings.push({ name: key, type: "plain_text", text: value });
99
- } else {
100
- metadataBindings.push({ name: key, type: "json", json: value });
101
- }
102
- });
103
-
104
- for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
105
- metadataBindings.push({
106
- name,
107
- type: "wasm_module",
108
- part: name,
109
- });
110
-
111
- formData.set(
112
- name,
113
- new File([readFileSync(filePath)], filePath, {
114
- type: "application/wasm",
115
- })
116
- );
117
- }
118
-
119
- for (const [name, filePath] of Object.entries(bindings.text_blobs || {})) {
120
- metadataBindings.push({
121
- name,
122
- type: "text_blob",
123
- part: name,
124
- });
125
-
126
- if (name !== "__STATIC_CONTENT_MANIFEST") {
127
- formData.set(
128
- name,
129
- new File([readFileSync(filePath)], filePath, {
130
- type: "text/plain",
131
- })
132
- );
133
- }
134
- }
135
-
136
- if (main.type === "commonjs") {
137
- // This is a service-worker format worker.
138
- for (const module of Object.values([...(modules || [])])) {
139
- if (module.name === "__STATIC_CONTENT_MANIFEST") {
140
- // Add the manifest to the form data.
141
- formData.set(
142
- module.name,
143
- new File([module.content], module.name, {
144
- type: "text/plain",
145
- })
146
- );
147
- // And then remove it from the modules collection
148
- modules = modules?.filter((m) => m !== module);
149
- } else if (module.type === "compiled-wasm" || module.type === "text") {
150
- // Convert all wasm/text modules into `wasm_module`/`text_blob` bindings.
151
- // The "name" of the module is a file path. We use it
152
- // to instead be a "part" of the body, and a reference
153
- // that we can use inside our source. This identifier has to be a valid
154
- // JS identifier, so we replace all non alphanumeric characters
155
- // with an underscore.
156
- const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
157
- metadataBindings.push({
158
- name,
159
- type: module.type === "compiled-wasm" ? "wasm_module" : "text_blob",
160
- part: name,
161
- });
162
-
163
- // Add the module to the form data.
164
- formData.set(
165
- name,
166
- new File([module.content], module.name, {
167
- type:
168
- module.type === "compiled-wasm"
169
- ? "application/wasm"
170
- : "text/plain",
171
- })
172
- );
173
- // And then remove it from the modules collection
174
- modules = modules?.filter((m) => m !== module);
175
- } else if (module.type === "buffer") {
176
- throw new Error(
177
- 'The "buffer" module type is not yet supported in service worker format workers'
178
- );
179
- }
180
- }
181
- }
182
-
183
- if (bindings.unsafe) {
184
- // @ts-expect-error unsafe bindings don't need to match a specific type here
185
- metadataBindings.push(...bindings.unsafe);
186
- }
187
-
188
- const metadata: WorkerMetadata = {
189
- ...(main.type !== "commonjs"
190
- ? { main_module: main.name }
191
- : { body_part: main.name }),
192
- bindings: metadataBindings,
193
- ...(compatibility_date && { compatibility_date }),
194
- ...(compatibility_flags && { compatibility_flags }),
195
- ...(usage_model && { usage_model }),
196
- ...(migrations && { migrations }),
197
- };
198
-
199
- formData.set("metadata", JSON.stringify(metadata));
200
-
201
- if (main.type === "commonjs" && modules && modules.length > 0) {
202
- throw new TypeError(
203
- "More than one module can only be specified when type = 'esm'"
204
- );
205
- }
206
-
207
- for (const module of [main].concat(modules || [])) {
208
- formData.set(
209
- module.name,
210
- new File([module.content], module.name, {
211
- type: toMimeType(module.type ?? main.type ?? "esm"),
212
- })
213
- );
214
- }
215
-
216
- return formData;
217
- }
@@ -1,147 +0,0 @@
1
- import { URL } from "node:url";
2
- import { fetch } from "undici";
3
- import { fetchResult } from "../cfetch";
4
- import { toFormData } from "./form_data";
5
- import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
6
-
7
- /**
8
- * A preview mode.
9
- *
10
- * * If true, then using a `workers.dev` subdomain.
11
- * * Otherwise, a list of routes under a single zone.
12
- */
13
- type CfPreviewMode = { workers_dev: boolean } | { routes: string[] };
14
-
15
- /**
16
- * A preview token.
17
- */
18
- export interface CfPreviewToken {
19
- /**
20
- * The header value required to trigger a preview.
21
- *
22
- * @example
23
- * const headers = { 'cf-workers-preview-token': value }
24
- * const response = await fetch('https://' + host, { headers })
25
- */
26
- value: string;
27
- /**
28
- * The host where the preview is available.
29
- */
30
- host: string;
31
- /**
32
- * A websocket url to a DevTools inspector.
33
- *
34
- * Workers does not have a fully-featured implementation
35
- * of the Chrome DevTools protocol, but supports the following:
36
- * * `console.log()` output.
37
- * * `Error` stack traces.
38
- * * `fetch()` events.
39
- *
40
- * There is no support for breakpoints, but we want to implement
41
- * this eventually.
42
- *
43
- * @link https://chromedevtools.github.io/devtools-protocol/
44
- */
45
- inspectorUrl: URL;
46
- /**
47
- * A url to prewarm the preview session.
48
- *
49
- * @example
50
- * fetch(prewarmUrl, { method: 'POST' })
51
- */
52
- prewarmUrl: URL;
53
- }
54
-
55
- /**
56
- * Generates a preview session token.
57
- */
58
- async function sessionToken(
59
- account: CfAccount,
60
- ctx: CfWorkerContext
61
- ): Promise<CfPreviewToken> {
62
- const { accountId } = account;
63
- const initUrl = ctx.zone
64
- ? `/zones/${ctx.zone}/workers/edge-preview`
65
- : `/accounts/${accountId}/workers/subdomain/edge-preview`;
66
-
67
- const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
68
- const { inspector_websocket, token } = (await (
69
- await fetch(exchange_url)
70
- ).json()) as { inspector_websocket: string; token: string };
71
- const { host } = new URL(inspector_websocket);
72
- const query = `cf_workers_preview_token=${token}`;
73
-
74
- return {
75
- value: token,
76
- host,
77
- inspectorUrl: new URL(`${inspector_websocket}?${query}`),
78
- prewarmUrl: new URL(
79
- `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
80
- ),
81
- };
82
- }
83
-
84
- // Credit: https://stackoverflow.com/a/2117523
85
- function randomId(): string {
86
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
87
- const r = (Math.random() * 16) | 0,
88
- v = c == "x" ? r : (r & 0x3) | 0x8;
89
- return v.toString(16);
90
- });
91
- }
92
-
93
- /**
94
- * Creates a preview token.
95
- */
96
- export async function previewToken(
97
- account: CfAccount,
98
- worker: CfWorkerInit,
99
- ctx: CfWorkerContext
100
- ): Promise<CfPreviewToken> {
101
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
102
- account,
103
- ctx
104
- );
105
-
106
- const { accountId } = account;
107
- const scriptId = ctx.zone ? randomId() : worker.name || host.split(".")[0];
108
- const url =
109
- ctx.env && !ctx.legacyEnv
110
- ? `/accounts/${accountId}/workers/services/${scriptId}/environments/${ctx.env}/edge-preview`
111
- : `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
112
-
113
- const mode: CfPreviewMode = ctx.zone
114
- ? { routes: ["*/*"] }
115
- : { workers_dev: true };
116
-
117
- const formData = toFormData(worker);
118
- formData.set("wrangler-session-config", JSON.stringify(mode));
119
-
120
- const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
121
- method: "POST",
122
- body: formData,
123
- headers: {
124
- "cf-preview-upload-config-token": value,
125
- },
126
- });
127
-
128
- return {
129
- value: preview_token,
130
- // TODO: verify this works with zoned workers
131
- host:
132
- worker.name && !ctx.zone
133
- ? // hrmm this might need change as well
134
- `${
135
- worker.name
136
- // TODO: this should also probably have the env prefix
137
- // but it doesn't appear to work yet, instead giving us the
138
- // "There is nothing here yet" screen
139
- // ctx.env && !ctx.legacyEnv
140
- // ? `${ctx.env}.${worker.name}`
141
- // : worker.name
142
- }.${host.split(".").slice(1).join(".")}`
143
- : host,
144
- inspectorUrl,
145
- prewarmUrl,
146
- };
147
- }
package/src/api/worker.ts DELETED
@@ -1,186 +0,0 @@
1
- import { fetch } from "undici";
2
- import { previewToken } from "./preview";
3
- import type { CfPreviewToken } from "./preview";
4
-
5
- /**
6
- * A Cloudflare account.
7
- */
8
- export interface CfAccount {
9
- /**
10
- * An API token.
11
- *
12
- * @link https://api.cloudflare.com/#user-api-tokens-properties
13
- */
14
- apiToken: string;
15
- /**
16
- * An account ID.
17
- */
18
- accountId: string;
19
- }
20
-
21
- /**
22
- * The type of Worker
23
- */
24
- export type CfScriptFormat = "modules" | "service-worker";
25
-
26
- /**
27
- * A module type.
28
- */
29
- export type CfModuleType =
30
- | "esm"
31
- | "commonjs"
32
- | "compiled-wasm"
33
- | "text"
34
- | "buffer";
35
-
36
- /**
37
- * An imported module.
38
- */
39
- export interface CfModule {
40
- /**
41
- * The module name.
42
- *
43
- * @example
44
- * './src/index.js'
45
- */
46
- name: string;
47
- /**
48
- * The module content, usually JavaScript or WASM code.
49
- *
50
- * @example
51
- * export default {
52
- * async fetch(request) {
53
- * return new Response('Ok')
54
- * }
55
- * }
56
- */
57
- content: string | Buffer;
58
- /**
59
- * The module type.
60
- *
61
- * If absent, will default to the main module's type.
62
- */
63
- type?: CfModuleType;
64
- }
65
-
66
- /**
67
- * A map of variable names to values.
68
- */
69
- interface CfVars {
70
- [key: string]: unknown;
71
- }
72
-
73
- /**
74
- * A KV namespace.
75
- */
76
- interface CfKvNamespace {
77
- binding: string;
78
- id: string;
79
- }
80
-
81
- /**
82
- * A binding to a wasm module (in service worker format)
83
- */
84
-
85
- interface CfWasmModuleBindings {
86
- [key: string]: string;
87
- }
88
-
89
- /**
90
- * A binding to a text blob (in service worker format)
91
- */
92
-
93
- interface CfTextBlobBindings {
94
- [key: string]: string;
95
- }
96
-
97
- /**
98
- * A Durable Object.
99
- */
100
- interface CfDurableObject {
101
- name: string;
102
- class_name: string;
103
- script_name?: string;
104
- }
105
-
106
- interface CfR2Bucket {
107
- binding: string;
108
- bucket_name: string;
109
- }
110
-
111
- interface CfUnsafeBinding {
112
- name: string;
113
- type: string;
114
- }
115
-
116
- export interface CfDurableObjectMigrations {
117
- old_tag?: string;
118
- new_tag: string;
119
- steps: {
120
- new_classes?: string[];
121
- renamed_classes?: {
122
- from: string;
123
- to: string;
124
- }[];
125
- deleted_classes?: string[];
126
- }[];
127
- }
128
-
129
- /**
130
- * Options for creating a `CfWorker`.
131
- */
132
- export interface CfWorkerInit {
133
- /**
134
- * The name of the worker.
135
- */
136
- name: string | undefined;
137
- /**
138
- * The entrypoint module.
139
- */
140
- main: CfModule;
141
- /**
142
- * The list of additional modules.
143
- */
144
- modules: undefined | CfModule[];
145
- /**
146
- * All the bindings
147
- */
148
- bindings: {
149
- vars: CfVars | undefined;
150
- kv_namespaces: CfKvNamespace[] | undefined;
151
- wasm_modules: CfWasmModuleBindings | undefined;
152
- text_blobs: CfTextBlobBindings | undefined;
153
- durable_objects: { bindings: CfDurableObject[] } | undefined;
154
- r2_buckets: CfR2Bucket[] | undefined;
155
- unsafe: CfUnsafeBinding[] | undefined;
156
- };
157
- migrations: undefined | CfDurableObjectMigrations;
158
- compatibility_date: string | undefined;
159
- compatibility_flags: undefined | string[];
160
- usage_model: undefined | "bundled" | "unbound";
161
- }
162
-
163
- export interface CfWorkerContext {
164
- env: string | undefined;
165
- legacyEnv: boolean | undefined;
166
- zone: string | undefined;
167
- }
168
-
169
- /**
170
- * A stub to create a Cloudflare Worker preview.
171
- *
172
- * @example
173
- * const {value, host} = await createWorker(init, acct);
174
- */
175
- export async function createWorker(
176
- init: CfWorkerInit,
177
- account: CfAccount,
178
- ctx: CfWorkerContext
179
- ): Promise<CfPreviewToken> {
180
- const token = await previewToken(account, init, ctx);
181
- const response = await fetch(token.prewarmUrl.href, { method: "POST" });
182
- if (!response.ok) {
183
- // console.error("worker failed to prewarm: ", response.statusText);
184
- }
185
- return token;
186
- }
package/src/bundle.ts DELETED
@@ -1,133 +0,0 @@
1
- import assert from "node:assert";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import * as esbuild from "esbuild";
5
- import makeModuleCollector from "./module-collection";
6
- import type { CfModule, CfScriptFormat } from "./api/worker";
7
- import type { Config } from "./config";
8
- import type { Entry } from "./entry";
9
-
10
- type BundleResult = {
11
- modules: CfModule[];
12
- resolvedEntryPointPath: string;
13
- bundleType: "esm" | "commonjs";
14
- stop: (() => void) | undefined;
15
- };
16
-
17
- /**
18
- * Generate a bundle for the worker identified by the arguments passed in.
19
- */
20
- export async function bundleWorker(
21
- entry: Entry,
22
- destination: string,
23
- options: {
24
- serveAssetsFromWorker: boolean;
25
- jsxFactory: string | undefined;
26
- jsxFragment: string | undefined;
27
- format: CfScriptFormat;
28
- rules: Config["rules"];
29
- watch?: esbuild.WatchMode;
30
- }
31
- ): Promise<BundleResult> {
32
- const {
33
- serveAssetsFromWorker,
34
- jsxFactory,
35
- jsxFragment,
36
- format,
37
- rules,
38
- watch,
39
- } = options;
40
- const moduleCollector = makeModuleCollector({ format, rules });
41
- const result = await esbuild.build({
42
- ...getEntryPoint(entry.file, serveAssetsFromWorker),
43
- bundle: true,
44
- absWorkingDir: entry.directory,
45
- outdir: destination,
46
- external: ["__STATIC_CONTENT_MANIFEST"],
47
- format: "esm",
48
- sourcemap: true,
49
- metafile: true,
50
- conditions: ["worker", "browser"],
51
- loader: {
52
- ".js": "jsx",
53
- ".mjs": "jsx",
54
- ".cjs": "jsx",
55
- },
56
- plugins: [moduleCollector.plugin],
57
- ...(jsxFactory && { jsxFactory }),
58
- ...(jsxFragment && { jsxFragment }),
59
- watch,
60
- });
61
-
62
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
63
- ([_path, output]) => output.entryPoint !== undefined
64
- );
65
- assert(
66
- entryPointOutputs.length > 0,
67
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
68
- listEntryPoints(entryPointOutputs)
69
- );
70
- assert(
71
- entryPointOutputs.length < 2,
72
- "More than one entry-point found for generated bundle." +
73
- listEntryPoints(entryPointOutputs)
74
- );
75
-
76
- const entryPointExports = entryPointOutputs[0][1].exports;
77
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
78
-
79
- return {
80
- modules: moduleCollector.modules,
81
- resolvedEntryPointPath: path.resolve(
82
- entry.directory,
83
- entryPointOutputs[0][0]
84
- ),
85
- bundleType,
86
- stop: result.stop,
87
- };
88
- }
89
-
90
- type EntryPoint =
91
- | { stdin: esbuild.StdinOptions; nodePaths: string[] }
92
- | { entryPoints: string[] };
93
-
94
- /**
95
- * Create an object that describes the entry point for esbuild.
96
- *
97
- * If we are using the experimental asset handling, then the entry point is
98
- * actually a shim worker that will either return an asset from a KV store,
99
- * or delegate to the actual worker.
100
- */
101
- function getEntryPoint(
102
- entryFile: string,
103
- serveAssetsFromWorker: boolean
104
- ): EntryPoint {
105
- if (serveAssetsFromWorker) {
106
- return {
107
- stdin: {
108
- contents: fs
109
- .readFileSync(
110
- path.join(__dirname, "../templates/static-asset-facade.js"),
111
- "utf8"
112
- )
113
- .replace("__ENTRY_POINT__", entryFile),
114
- sourcefile: "static-asset-facade.js",
115
- resolveDir: path.dirname(entryFile),
116
- },
117
- nodePaths: [path.join(__dirname, "../vendor")],
118
- };
119
- } else {
120
- return { entryPoints: [entryFile] };
121
- }
122
- }
123
-
124
- /**
125
- * Generate a string that describes the entry-points that were identified by esbuild.
126
- */
127
- function listEntryPoints(
128
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
129
- ): string {
130
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
131
- }
132
-
133
- type ValueOf<T> = T[keyof T];