wrangler 0.0.0-e9a1820 → 0.0.0-e9c2b04a

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 (113) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +122 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +168 -74
  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 +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -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 +31 -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 +652 -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 +460 -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 +23507 -0
  47. package/wrangler-dist/cli.js +153110 -109544
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/src/__tests__/clipboardy-mock.js +0 -4
  54. package/src/__tests__/index.test.ts +0 -287
  55. package/src/__tests__/jest.setup.ts +0 -18
  56. package/src/__tests__/kv.test.ts +0 -322
  57. package/src/__tests__/mock-cfetch.ts +0 -63
  58. package/src/__tests__/mock-dialogs.ts +0 -65
  59. package/src/__tests__/run-in-tmp.ts +0 -19
  60. package/src/__tests__/run-wrangler.ts +0 -32
  61. package/src/api/form_data.ts +0 -131
  62. package/src/api/inspect.ts +0 -430
  63. package/src/api/preview.ts +0 -128
  64. package/src/api/worker.ts +0 -155
  65. package/src/cfetch.ts +0 -72
  66. package/src/cli.ts +0 -9
  67. package/src/config.ts +0 -131
  68. package/src/dev.tsx +0 -879
  69. package/src/dialogs.tsx +0 -77
  70. package/src/index.tsx +0 -1902
  71. package/src/kv.tsx +0 -257
  72. package/src/module-collection.ts +0 -64
  73. package/src/pages.tsx +0 -851
  74. package/src/proxy.ts +0 -103
  75. package/src/publish.ts +0 -350
  76. package/src/sites.tsx +0 -115
  77. package/src/tail.tsx +0 -71
  78. package/src/user.tsx +0 -1022
  79. package/static-asset-facade.js +0 -47
  80. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  81. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  82. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  83. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  84. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  85. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  86. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  87. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  88. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  89. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  90. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  91. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  92. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  93. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  94. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  95. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  96. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  97. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  98. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  99. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  100. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  101. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  102. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  103. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  104. package/vendor/wrangler-mime/LICENSE +0 -21
  105. package/vendor/wrangler-mime/Mime.js +0 -97
  106. package/vendor/wrangler-mime/README.md +0 -187
  107. package/vendor/wrangler-mime/cli.js +0 -46
  108. package/vendor/wrangler-mime/index.js +0 -4
  109. package/vendor/wrangler-mime/lite.js +0 -4
  110. package/vendor/wrangler-mime/package.json +0 -52
  111. package/vendor/wrangler-mime/types/other.js +0 -1
  112. package/vendor/wrangler-mime/types/standard.js +0 -1
  113. package/wrangler-dist/cli.js.map +0 -7
package/src/proxy.ts DELETED
@@ -1,103 +0,0 @@
1
- import { connect } from "node:http2";
2
- import { createServer } from "node:http";
3
- import type { Server, IncomingHttpHeaders, RequestListener } from "node:http";
4
- import WebSocket from "faye-websocket";
5
- import serveStatic from "serve-static";
6
-
7
- export interface HttpProxyInit {
8
- host: string;
9
- assetPath?: string | null;
10
- onRequest?: (headers: IncomingHttpHeaders) => void;
11
- onResponse?: (headers: IncomingHttpHeaders) => void;
12
- }
13
-
14
- /**
15
- * Creates a HTTP/1 proxy that sends requests over HTTP/2.
16
- */
17
- export function createHttpProxy(init: HttpProxyInit): Server {
18
- const { host, assetPath, onRequest = () => {}, onResponse = () => {} } = init;
19
- const remote = connect(`https://${host}`);
20
- const local = createServer();
21
- // HTTP/2 -> HTTP/2
22
- local.on("stream", (stream, headers: IncomingHttpHeaders) => {
23
- onRequest(headers);
24
- headers[":authority"] = host;
25
- const request = stream.pipe(remote.request(headers));
26
- request.on("response", (responseHeaders: IncomingHttpHeaders) => {
27
- onResponse(responseHeaders);
28
- stream.respond(responseHeaders);
29
- request.pipe(stream, { end: true });
30
- });
31
- });
32
- // HTTP/1 -> HTTP/2
33
- const handleRequest: RequestListener = (message, response) => {
34
- const { httpVersionMajor, headers, method, url } = message;
35
- if (httpVersionMajor >= 2) {
36
- return; // Already handled by the "stream" event.
37
- }
38
- onRequest(headers);
39
- headers[":method"] = method;
40
- headers[":path"] = url;
41
- headers[":authority"] = host;
42
- headers[":scheme"] = "https";
43
- for (const name of Object.keys(headers)) {
44
- if (HTTP1_HEADERS.has(name.toLowerCase())) {
45
- delete headers[name];
46
- }
47
- }
48
- const request = message.pipe(remote.request(headers));
49
- request.on("response", (responseHeaders) => {
50
- const status = responseHeaders[":status"];
51
- onResponse(responseHeaders);
52
- for (const name of Object.keys(responseHeaders)) {
53
- if (name.startsWith(":")) {
54
- delete responseHeaders[name];
55
- }
56
- }
57
- response.writeHead(status, responseHeaders);
58
- request.pipe(response, { end: true });
59
- });
60
- };
61
- // If an asset path is defined, check the file system
62
- // for a file first and serve if it exists.
63
- if (assetPath) {
64
- const handleAsset = serveStatic(assetPath, {
65
- cacheControl: false,
66
- });
67
- local.on("request", (request, response) => {
68
- handleAsset(request, response, () => {
69
- handleRequest(request, response);
70
- });
71
- });
72
- } else {
73
- local.on("request", handleRequest);
74
- }
75
- // HTTP/1 -> WebSocket (over HTTP/1)
76
- local.on("upgrade", (message, socket, body) => {
77
- const { headers, url } = message;
78
- onRequest(headers);
79
- headers["host"] = host;
80
- const localWebsocket = new WebSocket(message, socket, body);
81
- // TODO(soon): Custom WebSocket protocol is not working?
82
- const remoteWebsocketClient = new WebSocket.Client(
83
- `wss://${host}${url}`,
84
- [],
85
- { headers }
86
- );
87
- localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
88
- });
89
- remote.on("close", () => {
90
- local.close();
91
- });
92
- return local;
93
- }
94
-
95
- const HTTP1_HEADERS = new Set([
96
- "host",
97
- "connection",
98
- "upgrade",
99
- "keep-alive",
100
- "proxy-connection",
101
- "transfer-encoding",
102
- "http2-settings",
103
- ]);
package/src/publish.ts DELETED
@@ -1,350 +0,0 @@
1
- import type { CfWorkerInit } from "./api/worker";
2
- import { toFormData } from "./api/form_data";
3
- import esbuild from "esbuild";
4
- import tmp from "tmp-promise";
5
- import type { Config } from "./config";
6
- import path from "path";
7
- import { readFile } from "fs/promises";
8
- import cfetch from "./cfetch";
9
- import assert from "node:assert";
10
- import { syncAssets } from "./sites";
11
- import makeModuleCollector from "./module-collection";
12
- import { execa } from "execa";
13
-
14
- type CfScriptFormat = void | "modules" | "service-worker";
15
-
16
- type Props = {
17
- config: Config;
18
- format?: CfScriptFormat;
19
- script?: string;
20
- name?: string;
21
- env?: string;
22
- public?: string;
23
- site?: string;
24
- triggers?: (string | number)[];
25
- routes?: (string | number)[];
26
- legacyEnv?: boolean;
27
- jsxFactory: void | string;
28
- jsxFragment: void | string;
29
- };
30
-
31
- function sleep(ms: number) {
32
- return new Promise((resolve) => setTimeout(resolve, ms));
33
- }
34
-
35
- export default async function publish(props: Props): Promise<void> {
36
- if (props.public && props.format === "service-worker") {
37
- // TODO: check config too
38
- throw new Error(
39
- "You cannot use the service worker format with a public directory."
40
- );
41
- }
42
- // TODO: warn if git/hg has uncommitted changes
43
- const { config } = props;
44
- const {
45
- account_id: accountId,
46
- build,
47
- // @ts-expect-error hidden
48
- __path__,
49
- } = config;
50
-
51
- const triggers = props.triggers || config.triggers?.crons;
52
- const routes = props.routes || config.routes;
53
-
54
- const jsxFactory = props.jsxFactory || config.jsx_factory;
55
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
56
-
57
- assert(config.account_id, "missing account id");
58
-
59
- let scriptName = props.name || config.name;
60
- assert(
61
- scriptName,
62
- 'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
63
- );
64
-
65
- let file: string;
66
- if (props.script) {
67
- file = props.script;
68
- } else {
69
- assert(build?.upload?.main, "missing main file");
70
- file = path.join(path.dirname(__path__), build.upload.main);
71
- }
72
-
73
- if (props.legacyEnv) {
74
- scriptName += props.env ? `-${props.env}` : "";
75
- }
76
- const envName = props.env ?? "production";
77
-
78
- const destination = await tmp.dir({ unsafeCleanup: true });
79
-
80
- if (props.config.build?.command) {
81
- // TODO: add a deprecation message here?
82
- console.log("running:", props.config.build.command);
83
- const buildCommandPieces = props.config.build.command.split(" ");
84
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
85
- stdout: "inherit",
86
- stderr: "inherit",
87
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
88
- });
89
- }
90
-
91
- const moduleCollector = makeModuleCollector();
92
- const result = await esbuild.build({
93
- ...(props.public
94
- ? {
95
- stdin: {
96
- contents: (
97
- await readFile(
98
- path.join(__dirname, "../static-asset-facade.js"),
99
- "utf8"
100
- )
101
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
102
- sourcefile: "static-asset-facade.js",
103
- resolveDir: path.dirname(file),
104
- },
105
- }
106
- : { entryPoints: [file] }),
107
- bundle: true,
108
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
109
- outdir: destination.path,
110
- external: ["__STATIC_CONTENT_MANIFEST"],
111
- format: "esm",
112
- sourcemap: true,
113
- metafile: true,
114
- conditions: ["worker", "browser"],
115
- loader: {
116
- ".js": "jsx",
117
- },
118
- plugins: [moduleCollector.plugin],
119
- ...(jsxFactory && { jsxFactory }),
120
- ...(jsxFragment && { jsxFragment }),
121
- });
122
-
123
- const chunks = Object.entries(result.metafile.outputs).find(
124
- ([_path, { entryPoint }]) =>
125
- entryPoint ===
126
- (props.public
127
- ? path.join(path.dirname(file), "static-asset-facade.js")
128
- : file)
129
- );
130
-
131
- const { format } = props;
132
- const bundle = {
133
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
134
- exports: chunks[1].exports,
135
- };
136
-
137
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
138
- // That way we'll be able to accurately tell if this is a service worker or not.
139
-
140
- if (format === "modules" && bundle.type === "commonjs") {
141
- console.error("⎔ Cannot use modules with a commonjs bundle.");
142
- // TODO: a much better error message here, with what to do next
143
- return;
144
- }
145
- if (format === "service-worker" && bundle.type !== "esm") {
146
- console.error("⎔ Cannot use service-worker with a esm bundle.");
147
- // TODO: a much better error message here, with what to do next
148
- return;
149
- }
150
-
151
- const content = await readFile(chunks[0], { encoding: "utf-8" });
152
- await destination.cleanup();
153
-
154
- // if config.migrations
155
- // get current migration tag
156
- let migrations;
157
- if ("migrations" in config) {
158
- const scripts = await cfetch<{ id: string; migration_tag: string }[]>(
159
- `/accounts/${accountId}/workers/scripts`
160
- );
161
- const script = scripts.find(({ id }) => id === scriptName);
162
- if (script?.migration_tag) {
163
- // was already published once
164
- const foundIndex = config.migrations.findIndex(
165
- (migration) => migration.tag === script.migration_tag
166
- );
167
- if (foundIndex === -1) {
168
- console.warn(
169
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
170
- );
171
- migrations = {
172
- old_tag: script.migration_tag,
173
- new_tag: config.migrations[config.migrations.length - 1].tag,
174
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
175
- };
176
- } else {
177
- migrations = {
178
- old_tag: script.migration_tag,
179
- new_tag: config.migrations[config.migrations.length - 1].tag,
180
- steps: config.migrations
181
- .slice(foundIndex + 1)
182
- .map(({ tag: _tag, ...rest }) => rest),
183
- };
184
- }
185
- } else {
186
- migrations = {
187
- new_tag: config.migrations[config.migrations.length - 1].tag,
188
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
189
- };
190
- }
191
- }
192
-
193
- const assets =
194
- props.public || props.site || props.config.site?.bucket // TODO: allow both
195
- ? await syncAssets(
196
- accountId,
197
- scriptName,
198
- props.public || props.site || props.config.site?.bucket,
199
- false
200
- )
201
- : { manifest: undefined, namespace: undefined };
202
-
203
- const envRootObj = props.env ? config.env[props.env] || {} : config;
204
- const bindings: CfWorkerInit["bindings"] = {
205
- kv_namespaces: envRootObj.kv_namespaces?.concat(
206
- assets.namespace
207
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
208
- : []
209
- ),
210
- vars: envRootObj.vars,
211
- durable_objects: envRootObj.durable_objects,
212
- services: envRootObj.experimental_services,
213
- };
214
-
215
- const worker: CfWorkerInit = {
216
- name: scriptName,
217
- main: {
218
- name: path.basename(chunks[0]),
219
- content: content,
220
- type: bundle.type === "esm" ? "esm" : "commonjs",
221
- },
222
- bindings,
223
- ...(migrations && { migrations }),
224
- modules: moduleCollector.modules.concat(
225
- assets.manifest
226
- ? {
227
- name: "__STATIC_CONTENT_MANIFEST",
228
- content: JSON.stringify(assets.manifest),
229
- type: "text",
230
- }
231
- : []
232
- ),
233
- compatibility_date: config.compatibility_date,
234
- compatibility_flags: config.compatibility_flags,
235
- usage_model: config.usage_model,
236
- };
237
-
238
- const start = Date.now();
239
- function formatTime(duration: number) {
240
- return `(${(duration / 1000).toFixed(2)} sec)`;
241
- }
242
-
243
- const notProd = !props.legacyEnv && props.env;
244
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
245
- const workerUrl = notProd
246
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
247
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
248
-
249
- // Upload the script so it has time to propogate.
250
- const { available_on_subdomain } = await cfetch(
251
- `${workerUrl}?available_on_subdomain=true`,
252
- {
253
- method: "PUT",
254
- // @ts-expect-error: TODO: fix this type error!
255
- body: toFormData(worker),
256
- }
257
- );
258
-
259
- const uploadMs = Date.now() - start;
260
- console.log("Uploaded", workerName, formatTime(uploadMs));
261
- const deployments: Promise<string[]>[] = [];
262
-
263
- const userSubdomain = (
264
- await cfetch<{ subdomain: string }>(
265
- `/accounts/${accountId}/workers/subdomain`
266
- )
267
- ).subdomain;
268
-
269
- const scriptURL =
270
- props.legacyEnv || !props.env
271
- ? `${scriptName}.${userSubdomain}.workers.dev`
272
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
273
-
274
- // Enable the `workers.dev` subdomain.
275
- // TODO: Make this configurable.
276
- if (!available_on_subdomain) {
277
- deployments.push(
278
- cfetch(`${workerUrl}/subdomain`, {
279
- method: "POST",
280
- body: JSON.stringify({ enabled: true }),
281
- headers: {
282
- "Content-Type": "application/json",
283
- },
284
- })
285
- .then(() => [scriptURL])
286
- // Add a delay when the subdomain is first created.
287
- // This is to prevent an issue where a negative cache-hit
288
- // causes the subdomain to be unavailable for 30 seconds.
289
- // This is a temporary measure until we fix this on the edge.
290
- .then(async (url) => {
291
- await sleep(3000);
292
- return url;
293
- })
294
- );
295
- } else {
296
- deployments.push(Promise.resolve([scriptURL]));
297
- }
298
-
299
- // Update routing table for the script.
300
- if (routes && routes.length) {
301
- deployments.push(
302
- cfetch(`${workerUrl}/routes`, {
303
- // TODO: PATCH will not delete previous routes on this script,
304
- // whereas PUT will. We need to decide on the default behaviour
305
- // and how to configure it.
306
- method: "PUT",
307
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
308
- headers: {
309
- "Content-Type": "application/json",
310
- },
311
- }).then(() => {
312
- if (routes.length > 10) {
313
- return routes
314
- .slice(0, 9)
315
- .map(String)
316
- .concat([`...and ${routes.length - 10} more routes`]);
317
- }
318
- return routes.map(String);
319
- })
320
- );
321
- }
322
-
323
- // Configure any schedules for the script.
324
- // TODO: rename this to `schedules`?
325
- if (triggers && triggers.length) {
326
- deployments.push(
327
- cfetch(`${workerUrl}/schedules`, {
328
- // TODO: Unlike routes, this endpoint does not support PATCH.
329
- // So technically, this will override any previous schedules.
330
- // We should change the endpoint to support PATCH.
331
- method: "PUT",
332
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
333
- headers: {
334
- "Content-Type": "application/json",
335
- },
336
- }).then(() => triggers.map(String))
337
- );
338
- }
339
-
340
- if (!deployments.length) {
341
- return;
342
- }
343
-
344
- const targets = await Promise.all(deployments);
345
- const deployMs = Date.now() - start - uploadMs;
346
- console.log("Deployed", workerName, formatTime(deployMs));
347
- for (const target of targets.flat()) {
348
- console.log(" ", target);
349
- }
350
- }
package/src/sites.tsx DELETED
@@ -1,115 +0,0 @@
1
- import { readdir, readFile } from "node:fs/promises";
2
- import { createReadStream } from "node:fs";
3
- import cfetch from "./cfetch";
4
- import { listNamespaceKeys, listNamespaces, putBulkKeyValue } from "./kv";
5
-
6
- import * as path from "path";
7
- import crypto from "node:crypto";
8
-
9
- async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
10
- const files = await readdir(dirPath, { withFileTypes: true });
11
- for (const file of files) {
12
- if (file.isDirectory()) {
13
- yield* await getFilesInFolder(path.join(dirPath, file.name));
14
- } else {
15
- yield path.join(dirPath, file.name);
16
- }
17
- }
18
- }
19
-
20
- async function hashFileContent(filePath: string): Promise<string> {
21
- return new Promise((resolve, reject) => {
22
- const hash = crypto.createHash("sha1");
23
- const rs = createReadStream(filePath);
24
- rs.on("error", reject);
25
- rs.on("data", (chunk) => hash.update(chunk));
26
- rs.on("end", () => resolve(hash.digest("hex")));
27
- });
28
- }
29
-
30
- async function hashFile(filePath: string): Promise<{
31
- filePath: string;
32
- hash: string;
33
- }> {
34
- const extName = path.extname(filePath);
35
- const baseName = path.basename(filePath, extName);
36
- const hash = await hashFileContent(filePath);
37
- return {
38
- filePath: `${baseName}.${hash}${extName || ""}`,
39
- hash,
40
- };
41
- }
42
-
43
- async function createKVNamespaceIfNotAlreadyExisting(
44
- title: string,
45
- accountId: string
46
- ) {
47
- // check if it already exists
48
- // TODO: this is super inefficient, should be made better
49
- const namespaces = await listNamespaces(accountId);
50
- const found = namespaces.find((x) => x.title === title);
51
- if (found) {
52
- return { created: false, id: found.id };
53
- }
54
-
55
- // else we make the namespace
56
- // TODO: use an export from ./kv
57
- const json = await cfetch<{ id: string }>(
58
- `/accounts/${accountId}/storage/kv/namespaces`,
59
- {
60
- method: "POST",
61
- headers: {
62
- "Content-Type": "application/json",
63
- },
64
- body: JSON.stringify({ title }),
65
- }
66
- );
67
-
68
- return {
69
- created: true,
70
- id: json.id,
71
- };
72
- }
73
-
74
- export async function syncAssets(
75
- accountId: string,
76
- scriptName: string,
77
- dirPath: string,
78
- preview: boolean,
79
- _env?: string
80
- ) {
81
- const title = `__${scriptName}_sites_assets${preview ? "_preview" : ""}`;
82
- const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
83
- title,
84
- accountId
85
- );
86
-
87
- // let's get all the keys in this namespace
88
- const keys = new Set(
89
- (await listNamespaceKeys(accountId, namespace)).map((x) => x.name)
90
- );
91
-
92
- const manifest = {};
93
- const upload = [];
94
- // TODO: this can be more efficient by parallelising
95
- for await (const file of getFilesInFolder(dirPath)) {
96
- // TODO: "exclude:" config
97
- const { filePath } = await hashFile(file);
98
- // now put each of the files into kv
99
- if (!keys.has(filePath)) {
100
- console.log(`uploading ${file}...`);
101
- const content = await readFile(file, "base64");
102
- if (content.length > 25 * 1024 * 1024) {
103
- throw new Error(`File ${file} is too big, it should be under 25 mb.`);
104
- }
105
- upload.push({
106
- key: filePath,
107
- value: content,
108
- base64: true,
109
- });
110
- }
111
- manifest[path.relative(dirPath, file)] = filePath;
112
- }
113
- await putBulkKeyValue(accountId, namespace, JSON.stringify(upload));
114
- return { manifest, namespace };
115
- }
package/src/tail.tsx DELETED
@@ -1,71 +0,0 @@
1
- import WebSocket from "ws";
2
- import cfetch from "./cfetch";
3
- import { version as packageVersion } from "../package.json";
4
-
5
- export type TailApiResponse = {
6
- id: string;
7
- url: string;
8
- expires_at: Date;
9
- };
10
-
11
- function makeCreateTailUrl(accountId: string, workerName: string): string {
12
- return `/accounts/${accountId}/workers/scripts/${workerName}/tails`;
13
- }
14
-
15
- function makeDeleteTailUrl(
16
- accountId: string,
17
- workerName: string,
18
- tailId: string
19
- ): string {
20
- return `/accounts/${accountId}/workers/scripts/${workerName}/tails/${tailId}`;
21
- }
22
-
23
- /// Creates a tail, but doesn't connect to it.
24
- async function createTailButDontConnect(
25
- accountId: string,
26
- workerName: string
27
- ): Promise<TailApiResponse> {
28
- const createTailUrl = makeCreateTailUrl(accountId, workerName);
29
- /// https://api.cloudflare.com/#worker-tail-logs-start-tail
30
- return await cfetch<TailApiResponse>(createTailUrl, { method: "POST" });
31
- }
32
-
33
- export async function createTail(
34
- accountId: string,
35
- workerName: string,
36
- _filters: Filters
37
- ): Promise<{
38
- tail: WebSocket;
39
- expiration: Date;
40
- deleteTail: () => Promise<void>;
41
- }> {
42
- const {
43
- id: tailId,
44
- url: websocketUrl,
45
- expires_at: expiration,
46
- } = await createTailButDontConnect(accountId, workerName);
47
- const deleteUrl = makeDeleteTailUrl(accountId, workerName, tailId);
48
-
49
- // deletes the tail
50
- async function deleteTail() {
51
- await cfetch(deleteUrl, { method: "DELETE" });
52
- }
53
-
54
- const tail = new WebSocket(websocketUrl, "trace-v1", {
55
- headers: {
56
- "Sec-WebSocket-Protocol": "trace-v1", // needs to be `trace-v1` to be accepted
57
- "User-Agent": `wrangler-js/${packageVersion}`,
58
- },
59
- });
60
-
61
- // TODO: send filters as well
62
- return { tail, expiration, deleteTail };
63
- }
64
-
65
- export type Filters = {
66
- status?: "ok" | "error" | "canceled";
67
- header?: string;
68
- method?: string;
69
- "sampling-rate"?: number;
70
- search?: string;
71
- };