wrangler 0.0.0-e33294b0 → 0.0.0-e351afcf

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 (127) hide show
  1. package/bin/wrangler.js +1 -1
  2. package/miniflare-dist/index.mjs +183 -92
  3. package/package.json +15 -10
  4. package/src/__tests__/api-devregistry.test.ts +121 -0
  5. package/src/__tests__/api.test.ts +27 -5
  6. package/src/__tests__/configuration.test.ts +294 -18
  7. package/src/__tests__/constellation.test.ts +371 -0
  8. package/src/__tests__/d1/execute.test.ts +3 -1
  9. package/src/__tests__/d1/migrate.test.ts +102 -0
  10. package/src/__tests__/delete.test.ts +6 -0
  11. package/src/__tests__/deployments.test.ts +335 -95
  12. package/src/__tests__/dev.test.tsx +87 -57
  13. package/src/__tests__/generate.test.ts +3 -4
  14. package/src/__tests__/guess-worker-format.test.ts +35 -0
  15. package/src/__tests__/helpers/mock-console.ts +6 -0
  16. package/src/__tests__/helpers/msw/handlers/deployments.ts +70 -3
  17. package/src/__tests__/helpers/msw/index.ts +4 -2
  18. package/src/__tests__/helpers/worker-scripts/parent-worker.js +4 -1
  19. package/src/__tests__/index.test.ts +14 -6
  20. package/src/__tests__/init.test.ts +136 -104
  21. package/src/__tests__/jest.setup.ts +4 -0
  22. package/src/__tests__/kv.test.ts +9 -9
  23. package/src/__tests__/logger.test.ts +68 -2
  24. package/src/__tests__/middleware.scheduled.test.ts +2 -2
  25. package/src/__tests__/middleware.test.ts +4 -3
  26. package/src/__tests__/mtls-certificates.test.ts +7 -3
  27. package/src/__tests__/pages/deployment-list.test.ts +2 -0
  28. package/src/__tests__/pages/functions-build.test.ts +159 -39
  29. package/src/__tests__/pages/project-list.test.ts +2 -0
  30. package/src/__tests__/pages/project-upload.test.ts +43 -24
  31. package/src/__tests__/pages/publish.test.ts +267 -148
  32. package/src/__tests__/publish.test.ts +1040 -339
  33. package/src/__tests__/pubsub.test.ts +3 -0
  34. package/src/__tests__/queues.test.ts +5 -2
  35. package/src/__tests__/test-old-node-version.js +3 -3
  36. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  37. package/src/__tests__/tsconfig.tsbuildinfo +1 -1
  38. package/src/__tests__/type-generation.test.ts +1 -0
  39. package/src/__tests__/user.test.ts +2 -2
  40. package/src/__tests__/worker-namespace.test.ts +1 -0
  41. package/src/api/dev.ts +15 -22
  42. package/src/api/pages/create-worker-bundle-contents.ts +1 -0
  43. package/src/api/pages/publish.tsx +64 -61
  44. package/src/bundle.ts +51 -16
  45. package/src/config/environment.ts +36 -4
  46. package/src/config/index.ts +30 -2
  47. package/src/config/validation-helpers.ts +1 -1
  48. package/src/config/validation.ts +149 -5
  49. package/src/constellation/createProject.tsx +51 -0
  50. package/src/constellation/deleteProject.ts +51 -0
  51. package/src/constellation/deleteProjectModel.ts +68 -0
  52. package/src/constellation/index.ts +75 -0
  53. package/src/constellation/listCatalog.tsx +35 -0
  54. package/src/constellation/listModel.tsx +41 -0
  55. package/src/constellation/listProject.tsx +28 -0
  56. package/src/constellation/listRuntime.tsx +28 -0
  57. package/src/constellation/options.ts +17 -0
  58. package/src/constellation/types.ts +17 -0
  59. package/src/constellation/uploadModel.tsx +64 -0
  60. package/src/constellation/utils.ts +90 -0
  61. package/src/create-worker-preview.ts +19 -8
  62. package/src/create-worker-upload-form.ts +28 -3
  63. package/src/d1/backups.tsx +19 -15
  64. package/src/d1/create.tsx +45 -39
  65. package/src/d1/delete.ts +1 -1
  66. package/src/d1/execute.tsx +23 -20
  67. package/src/d1/list.tsx +14 -12
  68. package/src/d1/migrations/apply.tsx +36 -30
  69. package/src/d1/migrations/create.tsx +15 -12
  70. package/src/d1/migrations/helpers.ts +5 -8
  71. package/src/d1/migrations/list.tsx +10 -7
  72. package/src/deployments.ts +260 -8
  73. package/src/dev/dev.tsx +6 -4
  74. package/src/dev/local.tsx +65 -40
  75. package/src/dev/start-server.ts +57 -52
  76. package/src/dev/use-esbuild.ts +59 -52
  77. package/src/dev/validate-dev-props.ts +9 -0
  78. package/src/dev-registry.ts +2 -1
  79. package/src/dev.tsx +38 -18
  80. package/src/docs/helpers.ts +50 -0
  81. package/src/docs/index.ts +25 -68
  82. package/src/entry.ts +19 -9
  83. package/src/environment-variables/factory.ts +2 -1
  84. package/src/generate/index.ts +2 -2
  85. package/src/index.ts +87 -24
  86. package/src/init.ts +144 -134
  87. package/src/inspect.ts +16 -1
  88. package/src/kv/helpers.ts +7 -4
  89. package/src/logger.ts +23 -4
  90. package/src/metrics/send-event.ts +2 -1
  91. package/src/miniflare-cli/assets.ts +8 -7
  92. package/src/miniflare-cli/index.ts +3 -3
  93. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -1
  94. package/src/module-collection.ts +92 -26
  95. package/src/pages/build.ts +290 -100
  96. package/src/pages/buildFunctions.ts +20 -10
  97. package/src/pages/deployments.tsx +3 -5
  98. package/src/pages/dev.ts +44 -26
  99. package/src/pages/errors.ts +1 -0
  100. package/src/pages/functions/buildPlugin.ts +57 -34
  101. package/src/pages/functions/buildWorker.ts +91 -31
  102. package/src/pages/functions/tsconfig.tsbuildinfo +1 -1
  103. package/src/pages/projects.tsx +2 -5
  104. package/src/pages/publish.tsx +1 -10
  105. package/src/pages/upload.tsx +29 -9
  106. package/src/paths.ts +1 -1
  107. package/src/publish/index.ts +1 -1
  108. package/src/publish/publish.ts +29 -34
  109. package/src/queues/cli/commands/consumer/add.ts +6 -0
  110. package/src/queues/client.ts +1 -0
  111. package/src/r2/helpers.ts +1 -0
  112. package/src/secret/index.ts +2 -1
  113. package/src/sites.ts +164 -52
  114. package/src/traverse-module-graph.ts +53 -0
  115. package/src/type-generation.ts +1 -1
  116. package/src/user/user.ts +2 -1
  117. package/src/utils/render.ts +93 -0
  118. package/src/worker.ts +18 -1
  119. package/templates/d1-beta-facade.js +5 -2
  120. package/templates/gitignore +1 -0
  121. package/templates/middleware/middleware-miniflare3-json-error.ts +17 -5
  122. package/templates/pages-template-plugin.ts +7 -3
  123. package/templates/tsconfig.init.json +1 -2
  124. package/templates/tsconfig.tsbuildinfo +1 -1
  125. package/wrangler-dist/cli.d.ts +552 -16
  126. package/wrangler-dist/cli.js +32141 -24052
  127. package/src/__tests__/api-devregistry.test.js +0 -64
package/src/sites.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import assert from "node:assert";
2
2
  import { readdir, readFile, stat } from "node:fs/promises";
3
3
  import * as path from "node:path";
4
+ import chalk from "chalk";
4
5
  import ignore from "ignore";
5
6
  import xxhash from "xxhash-wasm";
6
7
  import {
@@ -9,8 +10,10 @@ import {
9
10
  listKVNamespaces,
10
11
  putKVBulkKeyValue,
11
12
  deleteKVBulkKeyValue,
13
+ BATCH_KEY_MAX,
14
+ formatNumber,
12
15
  } from "./kv/helpers";
13
- import { logger } from "./logger";
16
+ import { logger, LOGGER_LEVELS } from "./logger";
14
17
  import type { Config } from "./config";
15
18
  import type { KeyValue } from "./kv/helpers";
16
19
  import type { XXHashAPI } from "xxhash-wasm";
@@ -92,6 +95,15 @@ async function createKVNamespaceIfNotAlreadyExisting(
92
95
  };
93
96
  }
94
97
 
98
+ const MAX_DIFF_LINES = 100;
99
+ const MAX_BUCKET_SIZE = 98 * 1000 * 1000;
100
+ const MAX_BUCKET_KEYS = BATCH_KEY_MAX;
101
+ const MAX_BATCH_OPERATIONS = 5;
102
+
103
+ function pluralise(count: number) {
104
+ return count === 1 ? "" : "s";
105
+ }
106
+
95
107
  /**
96
108
  * Upload the assets found within the `dirPath` directory to the sites assets KV namespace for
97
109
  * the worker given by `scriptName`.
@@ -116,13 +128,13 @@ export async function syncAssets(
116
128
  if (siteAssets === undefined) {
117
129
  return { manifest: undefined, namespace: undefined };
118
130
  }
119
-
120
131
  if (dryRun) {
121
132
  logger.log("(Note: doing a dry run, not uploading or deleting anything.)");
122
133
  return { manifest: undefined, namespace: undefined };
123
134
  }
124
135
  assert(accountId, "Missing accountId");
125
136
 
137
+ // Create assets namespace if it doesn't exist
126
138
  const title = `__${scriptName}-workers_sites_assets${
127
139
  preview ? "_preview" : ""
128
140
  }`;
@@ -131,55 +143,81 @@ export async function syncAssets(
131
143
  title,
132
144
  accountId
133
145
  );
134
-
135
- // let's get all the keys in this namespace
146
+ // Get all existing keys in asset namespace
147
+ logger.info("Fetching list of already uploaded assets...");
136
148
  const namespaceKeysResponse = await listKVNamespaceKeys(accountId, namespace);
137
149
  const namespaceKeys = new Set(namespaceKeysResponse.map((x) => x.name));
138
150
 
139
- const manifest: Record<string, string> = {};
140
-
141
- // A batch of uploads where each bucket has to be less than 98mb
142
- const uploadBuckets: KeyValue[][] = [];
143
- // The "live" bucket that we'll keep filling until it's just below 98mb
144
- let uploadBucket: KeyValue[] = [];
145
- // A size counter for the live bucket
146
- let uploadBucketSize = 0;
147
-
148
- const include = createPatternMatcher(siteAssets.includePatterns, false);
149
- const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
150
- const hasher = await xxhash();
151
-
152
151
  const assetDirectory = path.join(
153
152
  siteAssets.baseDirectory,
154
153
  siteAssets.assetDirectory
155
154
  );
155
+ const include = createPatternMatcher(siteAssets.includePatterns, false);
156
+ const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
157
+ const hasher = await xxhash();
158
+
159
+ // Find and validate all assets before we make any changes (can't store base64
160
+ // contents in memory for upload as users may have *lots* of files, and we
161
+ // don't want to OOM: https://github.com/cloudflare/workers-sdk/issues/2223)
162
+
163
+ const manifest: Record<string, string> = {};
164
+ type PathKey = [path: string, key: string];
165
+ // A batch of uploads where each bucket has to be less than 100 MiB and
166
+ // contain less than 10,000 keys (although we limit to 98 MB and 5000 keys)
167
+ const uploadBuckets: PathKey[][] = [];
168
+ // The "live" bucket we'll keep filling until it's just below the size limit
169
+ let uploadBucket: PathKey[] = [];
170
+ // Current size of the live bucket in bytes (just base64 encoded values)
171
+ let uploadBucketSize = 0;
172
+
173
+ let uploadCount = 0;
174
+ let skipCount = 0;
175
+
176
+ // Always log the first MAX_DIFF_LINES lines, then require the debug log level
177
+ let diffCount = 0;
178
+ function logDiff(line: string) {
179
+ const level = logger.loggerLevel;
180
+ if (LOGGER_LEVELS[level] >= LOGGER_LEVELS.debug) {
181
+ // If we're logging as debug level, we want *all* diff lines to be logged
182
+ // at debug level, not just the first MAX_DIFF_LINES
183
+ logger.debug(line);
184
+ } else if (diffCount < MAX_DIFF_LINES) {
185
+ // Otherwise, log the first MAX_DIFF_LINES diffs at info level...
186
+ logger.info(line);
187
+ } else if (diffCount === MAX_DIFF_LINES) {
188
+ // ...and warn when we start to truncate it
189
+ const msg =
190
+ " (truncating changed assets log, set `WRANGLER_LOG=debug` environment variable to see full diff)";
191
+ logger.info(chalk.dim(msg));
192
+ }
193
+ diffCount++;
194
+ }
195
+
196
+ logger.info("Building list of assets to upload...");
156
197
  for await (const absAssetFile of getFilesInFolder(assetDirectory)) {
157
198
  const assetFile = path.relative(assetDirectory, absAssetFile);
158
- if (!include(assetFile)) {
159
- continue;
160
- }
161
- if (exclude(assetFile)) {
162
- continue;
163
- }
199
+ if (!include(assetFile) || exclude(assetFile)) continue;
164
200
 
165
- logger.log(`Reading ${assetFile}...`);
166
201
  const content = await readFile(absAssetFile, "base64");
167
- await validateAssetSize(absAssetFile, assetFile);
168
- // while KV accepts files that are 25 MiB **before** b64 encoding
202
+ // While KV accepts files that are 25 MiB **before** b64 encoding
169
203
  // the overall bucket size must be below 100 MB **after** b64 encoding
170
- const assetSize = Buffer.from(content).length;
204
+ const assetSize = Buffer.byteLength(content);
205
+ await validateAssetSize(absAssetFile, assetFile);
171
206
  const assetKey = hashAsset(hasher, assetFile, content);
172
207
  validateAssetKey(assetKey);
173
208
 
174
- // now put each of the files into kv
175
209
  if (!namespaceKeys.has(assetKey)) {
176
- logger.log(`Uploading as ${assetKey}...`);
177
-
178
- // Check if adding this asset to the bucket would
179
- // push it over the 98 MiB limit KV bulk API limit
180
- if (uploadBucketSize + assetSize > 98 * 1000 * 1000) {
181
- // If so, move the current bucket into the batch,
182
- // and reset the counter/bucket
210
+ logDiff(
211
+ chalk.green(` + ${assetKey} (uploading new version of ${assetFile})`)
212
+ );
213
+
214
+ // Check if adding this asset to the bucket would push it over the KV
215
+ // bulk API limits
216
+ if (
217
+ uploadBucketSize + assetSize > MAX_BUCKET_SIZE ||
218
+ uploadBucket.length + 1 > MAX_BUCKET_KEYS
219
+ ) {
220
+ // If so, record the current bucket and reset it
183
221
  uploadBuckets.push(uploadBucket);
184
222
  uploadBucketSize = 0;
185
223
  uploadBucket = [];
@@ -187,13 +225,11 @@ export async function syncAssets(
187
225
 
188
226
  // Update the bucket and the size counter
189
227
  uploadBucketSize += assetSize;
190
- uploadBucket.push({
191
- key: assetKey,
192
- value: content,
193
- base64: true,
194
- });
228
+ uploadBucket.push([absAssetFile, assetKey]);
229
+ uploadCount++;
195
230
  } else {
196
- logger.log(`Skipping - already uploaded.`);
231
+ logDiff(chalk.dim(` = ${assetKey} (already uploaded ${assetFile})`));
232
+ skipCount++;
197
233
  }
198
234
 
199
235
  // Remove the key from the set so we know what we've already uploaded
@@ -203,23 +239,99 @@ export async function syncAssets(
203
239
  const manifestKey = urlSafe(path.relative(assetDirectory, absAssetFile));
204
240
  manifest[manifestKey] = assetKey;
205
241
  }
242
+ // Add the last (potentially only or empty) bucket to the batch
243
+ if (uploadBucket.length > 0) uploadBuckets.push(uploadBucket);
206
244
 
207
- // Add the last (potentially only) bucket to the batch
208
- uploadBuckets.push(uploadBucket);
209
-
210
- // keys now contains all the files we're deleting
211
245
  for (const key of namespaceKeys) {
212
- logger.log(`Deleting ${key} from the asset store...`);
246
+ logDiff(chalk.red(` - ${key} (removing as stale)`));
247
+ }
248
+
249
+ // Upload new assets, with 5 concurrent uploaders
250
+ if (uploadCount > 0) {
251
+ const s = pluralise(uploadCount);
252
+ logger.info(`Uploading ${formatNumber(uploadCount)} new asset${s}...`);
253
+ }
254
+ if (skipCount > 0) {
255
+ const s = pluralise(skipCount);
256
+ logger.info(
257
+ `Skipped uploading ${formatNumber(skipCount)} existing asset${s}.`
258
+ );
213
259
  }
260
+ let uploadedCount = 0;
261
+ const controller = new AbortController();
262
+ const uploaders = Array.from(Array(MAX_BATCH_OPERATIONS)).map(async () => {
263
+ while (!controller.signal.aborted) {
264
+ // Get the next bucket to upload. If there is none, stop this uploader.
265
+ // JavaScript is single(ish)-threaded, so we don't need to worry about
266
+ // parallel access here.
267
+ const nextBucket = uploadBuckets.shift();
268
+ if (nextBucket === undefined) break;
269
+
270
+ // Read all files in the bucket as base64
271
+ // TODO(perf): consider streaming the bulk upload body, rather than
272
+ // buffering all base64 contents then JSON-stringifying. This probably
273
+ // doesn't matter *too* much: we know buckets will be about 100MB, so
274
+ // with 5 uploaders, we could load about 500MB into memory (+ extra
275
+ // object keys/tags/copies/etc).
276
+ const bucket: KeyValue[] = [];
277
+ for (const [absAssetFile, assetKey] of nextBucket) {
278
+ bucket.push({
279
+ key: assetKey,
280
+ value: await readFile(absAssetFile, "base64"),
281
+ base64: true,
282
+ });
283
+ if (controller.signal.aborted) break;
284
+ }
214
285
 
215
- // upload each bucket in parallel
216
- const bucketsToPut = [];
217
- for (const bucket of uploadBuckets) {
218
- bucketsToPut.push(putKVBulkKeyValue(accountId, namespace, bucket));
286
+ // Upload the bucket to the KV namespace, suppressing logs, we do our own
287
+ try {
288
+ await putKVBulkKeyValue(
289
+ accountId,
290
+ namespace,
291
+ bucket,
292
+ /* quiet */ true,
293
+ controller.signal
294
+ );
295
+ } catch (e) {
296
+ // https://developer.mozilla.org/en-US/docs/Web/API/DOMException#error_names
297
+ // https://github.com/nodejs/undici/blob/a3efc9814447001a43a976f1c64adc41995df7e3/lib/core/errors.js#L89
298
+ if (
299
+ typeof e === "object" &&
300
+ e !== null &&
301
+ "name" in e &&
302
+ // @ts-expect-error `e.name` should be typed `unknown`, fixed in
303
+ // TypeScript 4.9
304
+ e.name === "AbortError"
305
+ ) {
306
+ break;
307
+ }
308
+ throw e;
309
+ }
310
+ uploadedCount += nextBucket.length;
311
+ const percent = Math.floor((100 * uploadedCount) / uploadCount);
312
+ logger.info(
313
+ `Uploaded ${percent}% [${formatNumber(
314
+ uploadedCount
315
+ )} out of ${formatNumber(uploadCount)}]`
316
+ );
317
+ }
318
+ });
319
+ try {
320
+ // Wait for all uploaders to complete, or one to fail
321
+ await Promise.all(uploaders);
322
+ } catch (e) {
323
+ // If any uploader fails, abort the others
324
+ logger.info(`Upload failed, aborting...`);
325
+ controller.abort();
326
+ throw e;
219
327
  }
220
- await Promise.all(bucketsToPut);
221
328
 
222
- // then delete all the assets that aren't used anymore
329
+ // Delete stale assets
330
+ const deleteCount = namespaceKeys.size;
331
+ if (deleteCount > 0) {
332
+ const s = pluralise(deleteCount);
333
+ logger.info(`Removing ${formatNumber(deleteCount)} stale asset${s}...`);
334
+ }
223
335
  await deleteKVBulkKeyValue(accountId, namespace, Array.from(namespaceKeys));
224
336
 
225
337
  logger.log("↗️ Done syncing assets");
@@ -0,0 +1,53 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import chalk from "chalk";
4
+ import { logger } from "./logger";
5
+ import { matchFiles, parseRules } from "./module-collection";
6
+ import type { BundleResult } from "./bundle";
7
+ import type { Config } from "./config";
8
+ import type { Entry } from "./entry";
9
+
10
+ async function getFiles(root: string, relativeTo: string): Promise<string[]> {
11
+ const files = [];
12
+ for (const file of await readdir(root, { withFileTypes: true })) {
13
+ if (file.isDirectory()) {
14
+ files.push(...(await getFiles(path.join(root, file.name), relativeTo)));
15
+ } else {
16
+ files.push(path.relative(relativeTo, path.join(root, file.name)));
17
+ }
18
+ }
19
+ return files;
20
+ }
21
+
22
+ export default async function traverseModuleGraph(
23
+ entry: Entry,
24
+ rules: Config["rules"]
25
+ ): Promise<BundleResult> {
26
+ const files = await getFiles(entry.moduleRoot, entry.moduleRoot);
27
+ const relativeEntryPoint = path.relative(entry.moduleRoot, entry.file);
28
+
29
+ const modules = (await matchFiles(files, entry.moduleRoot, parseRules(rules)))
30
+ .filter((m) => m.name !== relativeEntryPoint)
31
+ .map((m) => ({
32
+ ...m,
33
+ name: m.name,
34
+ }));
35
+
36
+ const bundleType = entry.format === "modules" ? "esm" : "commonjs";
37
+
38
+ if (modules.length > 0) {
39
+ logger.info(`Uploading additional modules:`);
40
+ modules.forEach(({ name, type }) => {
41
+ logger.info(`- ${chalk.blue(name)} (${chalk.green(type ?? "")})`);
42
+ });
43
+ }
44
+
45
+ return {
46
+ modules,
47
+ dependencies: {},
48
+ resolvedEntryPointPath: entry.file,
49
+ bundleType,
50
+ stop: undefined,
51
+ sourceMapPath: undefined,
52
+ };
53
+ }
@@ -89,7 +89,7 @@ export async function generateTypes(
89
89
  }
90
90
  }
91
91
 
92
- if (configToDTS.unsafe) {
92
+ if (configToDTS.unsafe?.bindings) {
93
93
  for (const unsafe of configToDTS.unsafe.bindings) {
94
94
  envTypeStructure.push(`${unsafe.name}: any;`);
95
95
  }
package/src/user/user.ts CHANGED
@@ -347,6 +347,7 @@ const Scopes = {
347
347
  "See and change Cloudflare Pages projects, settings and deployments.",
348
348
  "zone:read": "Grants read level access to account zone.",
349
349
  "ssl_certs:write": "See and manage mTLS certificates for your account",
350
+ "constellation:write": "Manage Constellation AI projects/models",
350
351
  } as const;
351
352
 
352
353
  /**
@@ -1153,7 +1154,7 @@ export async function requireAuth(config: {
1153
1154
  if (!loggedIn) {
1154
1155
  if (!isInteractive() || CI.isCI()) {
1155
1156
  throw new Error(
1156
- "In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/api/tokens/create/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
1157
+ "In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
1157
1158
  );
1158
1159
  } else {
1159
1160
  // didn't login, let's just quit
@@ -0,0 +1,93 @@
1
+ import { EventEmitter } from "events";
2
+ import { render as inkRender } from "ink";
3
+ import type { ReactElement } from "react";
4
+ import type { WriteStream } from "tty";
5
+
6
+ export function renderToString(tree: ReactElement): string {
7
+ const { output, cleanup } = render(tree);
8
+ cleanup();
9
+ return output;
10
+ }
11
+
12
+ // The code below is mostly copied from ink-render-string.
13
+ // See https://github.com/zhanwang626/ink-render-string.git.
14
+
15
+ // MIT License
16
+
17
+ // Copyright (c) 2021 Zhan Wang
18
+
19
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
20
+ // of this software and associated documentation files (the "Software"), to deal
21
+ // in the Software without restriction, including without limitation the rights
22
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23
+ // copies of the Software, and to permit persons to whom the Software is
24
+ // furnished to do so, subject to the following conditions:
25
+
26
+ // The above copyright notice and this permission notice shall be included in all
27
+ // copies or substantial portions of the Software.
28
+
29
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35
+ // SOFTWARE.
36
+
37
+ interface Instance {
38
+ output: string;
39
+ unmount: () => void;
40
+ cleanup: () => void;
41
+ stdout: OutputStream;
42
+ stderr: OutputStream;
43
+ frames: string[];
44
+ }
45
+
46
+ const LASTFRAME_UNDEFINED = "value of stdout.lastframe() is undefined";
47
+
48
+ export class OutputStream extends EventEmitter {
49
+ readonly frames: string[] = [];
50
+ private _lastFrame?: string;
51
+
52
+ get columns(): number {
53
+ return this._originalStream.columns;
54
+ }
55
+ get rows(): number {
56
+ return this._originalStream.rows;
57
+ }
58
+
59
+ constructor(private _originalStream: WriteStream) {
60
+ super();
61
+ }
62
+
63
+ write = (frame: string) => {
64
+ this.frames.push(frame);
65
+ this._lastFrame = frame;
66
+ };
67
+
68
+ lastFrame = () => {
69
+ return this._lastFrame;
70
+ };
71
+ }
72
+
73
+ export const render = (tree: ReactElement): Instance => {
74
+ const stdout = new OutputStream(process.stdout);
75
+ const stderr = new OutputStream(process.stderr);
76
+
77
+ const instance = inkRender(tree, {
78
+ stdout: stdout as unknown as WriteStream,
79
+ stderr: stderr as unknown as WriteStream,
80
+ debug: true,
81
+ exitOnCtrlC: false,
82
+ patchConsole: false,
83
+ });
84
+
85
+ return {
86
+ output: stdout.lastFrame() || LASTFRAME_UNDEFINED,
87
+ stdout,
88
+ stderr,
89
+ cleanup: instance.cleanup,
90
+ unmount: instance.unmount,
91
+ frames: stdout.frames,
92
+ };
93
+ };
package/src/worker.ts CHANGED
@@ -79,6 +79,15 @@ export interface CfKvNamespace {
79
79
  id: string;
80
80
  }
81
81
 
82
+ /**
83
+ * A binding to send email.
84
+ */
85
+ export interface CfSendEmailBindings {
86
+ name: string;
87
+ destination_address?: string;
88
+ allowed_destination_addresses?: string[];
89
+ }
90
+
82
91
  /**
83
92
  * A binding to a wasm module (in service-worker format)
84
93
  */
@@ -174,6 +183,13 @@ interface CfUnsafeBinding {
174
183
  type: string;
175
184
  }
176
185
 
186
+ type CfUnsafeMetadata = Record<string, unknown>;
187
+
188
+ interface CfUnsafe {
189
+ bindings: CfUnsafeBinding[] | undefined;
190
+ metadata: CfUnsafeMetadata | undefined;
191
+ }
192
+
177
193
  export interface CfDurableObjectMigrations {
178
194
  old_tag?: string;
179
195
  new_tag: string;
@@ -209,6 +225,7 @@ export interface CfWorkerInit {
209
225
  bindings: {
210
226
  vars: CfVars | undefined;
211
227
  kv_namespaces: CfKvNamespace[] | undefined;
228
+ send_email: CfSendEmailBindings[] | undefined;
212
229
  wasm_modules: CfWasmModuleBindings | undefined;
213
230
  text_blobs: CfTextBlobBindings | undefined;
214
231
  data_blobs: CfDataBlobBindings | undefined;
@@ -221,7 +238,7 @@ export interface CfWorkerInit {
221
238
  dispatch_namespaces: CfDispatchNamespace[] | undefined;
222
239
  mtls_certificates: CfMTlsCertificate[] | undefined;
223
240
  logfwdr: CfLogfwdr | undefined;
224
- unsafe: CfUnsafeBinding[] | undefined;
241
+ unsafe: CfUnsafe | undefined;
225
242
  };
226
243
  migrations: CfDurableObjectMigrations | undefined;
227
244
  compatibility_date: string | undefined;
@@ -11,7 +11,7 @@ var D1Database = class {
11
11
  return new D1PreparedStatement(this, query);
12
12
  }
13
13
  async dump() {
14
- const response = await this.binding.fetch("/dump", {
14
+ const response = await this.binding.fetch("http://d1/dump", {
15
15
  method: "POST",
16
16
  headers: {
17
17
  "content-type": "application/json",
@@ -79,7 +79,7 @@ var D1Database = class {
79
79
  params,
80
80
  }
81
81
  );
82
- const response = await this.binding.fetch(endpoint, {
82
+ const response = await this.binding.fetch(new URL(endpoint, "http://d1"), {
83
83
  method: "POST",
84
84
  headers: {
85
85
  "content-type": "application/json",
@@ -237,5 +237,8 @@ var shim_default = {
237
237
  async trace(traces, env, ctx) {
238
238
  return worker.trace(traces, getMaskedEnv(env), ctx);
239
239
  },
240
+ async email(message, env, ctx) {
241
+ return worker.email(message, getMaskedEnv(env), ctx);
242
+ },
240
243
  };
241
244
  export { shim_default as default };
@@ -169,3 +169,4 @@ dist
169
169
  # wrangler project
170
170
 
171
171
  .dev.vars
172
+ .wrangler/
@@ -1,15 +1,27 @@
1
1
  import type { Middleware } from "./common";
2
2
 
3
+ interface JsonError {
4
+ message?: string;
5
+ name?: string;
6
+ stack?: string;
7
+ cause?: JsonError;
8
+ }
9
+
10
+ function reduceError(e: any): JsonError {
11
+ return {
12
+ name: e?.name,
13
+ message: e?.message ?? String(e),
14
+ stack: e?.stack,
15
+ cause: e?.cause === undefined ? undefined : reduceError(e.cause),
16
+ };
17
+ }
18
+
3
19
  // See comment in `bundle.ts` for details on why this is needed
4
20
  const jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {
5
21
  try {
6
22
  return await middlewareCtx.next(request, env);
7
23
  } catch (e: any) {
8
- const error = {
9
- name: e?.name,
10
- message: e?.message ?? String(e),
11
- stack: e?.stack,
12
- };
24
+ const error = reduceError(e);
13
25
  return Response.json(error, {
14
26
  status: 500,
15
27
  headers: { "MF-Experimental-Error-Stack": "true" },
@@ -133,7 +133,11 @@ export default function (pluginArgs: unknown) {
133
133
  const handlerIterator = executeRequest(request, relativePathname);
134
134
  const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
135
135
  if (input !== undefined) {
136
- request = new Request(input, init);
136
+ let url = input;
137
+ if (typeof input === "string") {
138
+ url = new URL(input, request.url).toString();
139
+ }
140
+ request = new Request(url, init);
137
141
  }
138
142
 
139
143
  const result = handlerIterator.next();
@@ -141,7 +145,7 @@ export default function (pluginArgs: unknown) {
141
145
  if (result.done === false) {
142
146
  const { handler, params, path } = result.value;
143
147
  const context = {
144
- request,
148
+ request: new Request(request.clone()),
145
149
  functionPath: workerContext.functionPath + path,
146
150
  next: pluginNext,
147
151
  params,
@@ -157,7 +161,7 @@ export default function (pluginArgs: unknown) {
157
161
 
158
162
  return cloneResponse(response);
159
163
  } else {
160
- return next();
164
+ return next(request);
161
165
  }
162
166
  };
163
167
 
@@ -34,8 +34,7 @@
34
34
  // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
35
  // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
36
36
  "types": [
37
- "@cloudflare/workers-types",
38
- "vitest"
37
+ "@cloudflare/workers-types"
39
38
  ] /* Specify type package names to be included without being referenced in a source file. */,
40
39
  // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
41
40
  "resolveJsonModule": true /* Enable importing .json files */,