wrangler 0.0.0-e88a54e → 0.0.0-e8df68ee

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 (167) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +46 -15
  3. package/bin/wrangler.js +118 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -143
  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 +23 -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 +127 -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-d1-beta.ts +244 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -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 +3 -3
  30. package/templates/new-worker.ts +22 -4
  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/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/cli.d.ts +1726 -0
  41. package/wrangler-dist/cli.js +134048 -126481
  42. package/wrangler-dist/wasm-sync.wasm +0 -0
  43. package/import_meta_url.js +0 -3
  44. package/miniflare-config-stubs/.env.empty +0 -0
  45. package/miniflare-config-stubs/package.empty.json +0 -1
  46. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  47. package/miniflare-dist/index.mjs +0 -79
  48. package/miniflare-dist/index.mjs.map +0 -7
  49. package/pages/functions/buildWorker.ts +0 -62
  50. package/pages/functions/filepath-routing.test.ts +0 -223
  51. package/pages/functions/filepath-routing.ts +0 -181
  52. package/pages/functions/identifiers.ts +0 -78
  53. package/pages/functions/routes.ts +0 -151
  54. package/pages/functions/template-worker.ts +0 -130
  55. package/src/__tests__/configuration.test.ts +0 -2796
  56. package/src/__tests__/dev.test.tsx +0 -496
  57. package/src/__tests__/dev2.test.tsx +0 -154
  58. package/src/__tests__/guess-worker-format.test.ts +0 -58
  59. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  60. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  61. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  62. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  65. package/src/__tests__/helpers/mock-console.ts +0 -70
  66. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  69. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  72. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  73. package/src/__tests__/https-options.test.ts +0 -127
  74. package/src/__tests__/index.test.ts +0 -991
  75. package/src/__tests__/jest.setup.ts +0 -69
  76. package/src/__tests__/kv.test.ts +0 -1382
  77. package/src/__tests__/logout.test.ts +0 -52
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/pages.test.ts +0 -44
  80. package/src/__tests__/parse.test.ts +0 -322
  81. package/src/__tests__/publish.test.ts +0 -2704
  82. package/src/__tests__/r2.test.ts +0 -198
  83. package/src/__tests__/route.test.ts +0 -45
  84. package/src/__tests__/secret.test.ts +0 -425
  85. package/src/__tests__/sentry.test.ts +0 -146
  86. package/src/__tests__/tail.test.ts +0 -564
  87. package/src/__tests__/whoami.test.tsx +0 -100
  88. package/src/bundle.ts +0 -142
  89. package/src/cfetch/index.ts +0 -104
  90. package/src/cfetch/internal.ts +0 -139
  91. package/src/cli.ts +0 -19
  92. package/src/config/README.md +0 -107
  93. package/src/config/config.ts +0 -218
  94. package/src/config/diagnostics.ts +0 -80
  95. package/src/config/environment.ts +0 -366
  96. package/src/config/index.ts +0 -62
  97. package/src/config/validation-helpers.ts +0 -486
  98. package/src/config/validation.ts +0 -1090
  99. package/src/create-worker-preview.ts +0 -166
  100. package/src/create-worker-upload-form.ts +0 -217
  101. package/src/dev/dev.tsx +0 -364
  102. package/src/dev/local.tsx +0 -232
  103. package/src/dev/remote.tsx +0 -203
  104. package/src/dev/use-esbuild.ts +0 -100
  105. package/src/dialogs.tsx +0 -77
  106. package/src/entry.ts +0 -208
  107. package/src/environment-variables.ts +0 -33
  108. package/src/https-options.ts +0 -122
  109. package/src/index.tsx +0 -2373
  110. package/src/inspect.ts +0 -617
  111. package/src/kv.ts +0 -319
  112. package/src/miniflare-cli/README.md +0 -30
  113. package/src/miniflare-cli/enum-keys.ts +0 -17
  114. package/src/miniflare-cli/index.ts +0 -37
  115. package/src/module-collection.ts +0 -258
  116. package/src/open-in-browser.ts +0 -25
  117. package/src/package-manager.ts +0 -126
  118. package/src/pages.tsx +0 -1047
  119. package/src/parse.ts +0 -183
  120. package/src/paths.ts +0 -26
  121. package/src/proxy.ts +0 -440
  122. package/src/publish.ts +0 -347
  123. package/src/r2.ts +0 -50
  124. package/src/reporting.ts +0 -131
  125. package/src/selfsigned.d.ts +0 -29
  126. package/src/sites.tsx +0 -280
  127. package/src/tail/filters.ts +0 -279
  128. package/src/tail/index.ts +0 -299
  129. package/src/tail/printing.ts +0 -62
  130. package/src/user.tsx +0 -1118
  131. package/src/whoami.tsx +0 -69
  132. package/src/worker.ts +0 -163
  133. package/templates/static-asset-facade.js +0 -47
  134. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  135. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  136. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  137. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  138. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  139. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  140. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  141. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  142. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  148. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  149. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  150. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  151. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  152. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  153. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  156. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  157. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  158. package/vendor/wrangler-mime/LICENSE +0 -21
  159. package/vendor/wrangler-mime/Mime.js +0 -97
  160. package/vendor/wrangler-mime/README.md +0 -187
  161. package/vendor/wrangler-mime/cli.js +0 -46
  162. package/vendor/wrangler-mime/index.js +0 -4
  163. package/vendor/wrangler-mime/lite.js +0 -4
  164. package/vendor/wrangler-mime/package.json +0 -52
  165. package/vendor/wrangler-mime/types/other.js +0 -1
  166. package/vendor/wrangler-mime/types/standard.js +0 -1
  167. package/wrangler-dist/cli.js.map +0 -7
@@ -1,354 +0,0 @@
1
- "use strict";
2
- var __awaiter =
3
- (this && this.__awaiter) ||
4
- function (thisArg, _arguments, P, generator) {
5
- function adopt(value) {
6
- return value instanceof P
7
- ? value
8
- : new P(function (resolve) {
9
- resolve(value);
10
- });
11
- }
12
- return new (P || (P = Promise))(function (resolve, reject) {
13
- function fulfilled(value) {
14
- try {
15
- step(generator.next(value));
16
- } catch (e) {
17
- reject(e);
18
- }
19
- }
20
- function rejected(value) {
21
- try {
22
- step(generator["throw"](value));
23
- } catch (e) {
24
- reject(e);
25
- }
26
- }
27
- function step(result) {
28
- result.done
29
- ? resolve(result.value)
30
- : adopt(result.value).then(fulfilled, rejected);
31
- }
32
- step((generator = generator.apply(thisArg, _arguments || [])).next());
33
- });
34
- };
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.InternalError =
37
- exports.NotFoundError =
38
- exports.MethodNotAllowedError =
39
- exports.serveSinglePageApp =
40
- exports.mapRequestToAsset =
41
- exports.getAssetFromKV =
42
- void 0;
43
- const mime = require("wrangler-mime");
44
- const types_1 = require("./types");
45
- Object.defineProperty(exports, "MethodNotAllowedError", {
46
- enumerable: true,
47
- get: function () {
48
- return types_1.MethodNotAllowedError;
49
- },
50
- });
51
- Object.defineProperty(exports, "NotFoundError", {
52
- enumerable: true,
53
- get: function () {
54
- return types_1.NotFoundError;
55
- },
56
- });
57
- Object.defineProperty(exports, "InternalError", {
58
- enumerable: true,
59
- get: function () {
60
- return types_1.InternalError;
61
- },
62
- });
63
- const defaultCacheControl = {
64
- browserTTL: null,
65
- edgeTTL: 2 * 60 * 60 * 24,
66
- bypassCache: false, // do not bypass Cloudflare's cache
67
- };
68
- function assignOptions(options) {
69
- // Assign any missing options passed in to the default
70
- // options.mapRequestToAsset is handled manually later
71
- return Object.assign(
72
- {
73
- ASSET_NAMESPACE: __STATIC_CONTENT,
74
- ASSET_MANIFEST: __STATIC_CONTENT_MANIFEST,
75
- cacheControl: defaultCacheControl,
76
- defaultMimeType: "text/plain",
77
- defaultDocument: "index.html",
78
- },
79
- options
80
- );
81
- }
82
- /**
83
- * maps the path of incoming request to the request pathKey to look up
84
- * in bucket and in cache
85
- * e.g. for a path '/' returns '/index.html' which serves
86
- * the content of bucket/index.html
87
- * @param {Request} request incoming request
88
- */
89
- const mapRequestToAsset = (request, options) => {
90
- options = assignOptions(options);
91
- const parsedUrl = new URL(request.url);
92
- let pathname = parsedUrl.pathname;
93
- if (pathname.endsWith("/")) {
94
- // If path looks like a directory append options.defaultDocument
95
- // e.g. If path is /about/ -> /about/index.html
96
- pathname = pathname.concat(options.defaultDocument);
97
- } else if (!mime.getType(pathname)) {
98
- // If path doesn't look like valid content
99
- // e.g. /about.me -> /about.me/index.html
100
- pathname = pathname.concat("/" + options.defaultDocument);
101
- }
102
- parsedUrl.pathname = pathname;
103
- return new Request(parsedUrl.toString(), request);
104
- };
105
- exports.mapRequestToAsset = mapRequestToAsset;
106
- /**
107
- * maps the path of incoming request to /index.html if it evaluates to
108
- * any HTML file.
109
- * @param {Request} request incoming request
110
- */
111
- function serveSinglePageApp(request, options) {
112
- options = assignOptions(options);
113
- // First apply the default handler, which already has logic to detect
114
- // paths that should map to HTML files.
115
- request = mapRequestToAsset(request, options);
116
- const parsedUrl = new URL(request.url);
117
- // Detect if the default handler decided to map to
118
- // a HTML file in some specific directory.
119
- if (parsedUrl.pathname.endsWith(".html")) {
120
- // If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
121
- return new Request(
122
- `${parsedUrl.origin}/${options.defaultDocument}`,
123
- request
124
- );
125
- } else {
126
- // The default handler decided this is not an HTML page. It's probably
127
- // an image, CSS, or JS file. Leave it as-is.
128
- return request;
129
- }
130
- }
131
- exports.serveSinglePageApp = serveSinglePageApp;
132
- /**
133
- * takes the path of the incoming request, gathers the appropriate content from KV, and returns
134
- * the response
135
- *
136
- * @param {FetchEvent} event the fetch event of the triggered request
137
- * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
138
- * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
139
- * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
140
- * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
141
- * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
142
- * */
143
- const getAssetFromKV = (event, options) =>
144
- __awaiter(void 0, void 0, void 0, function* () {
145
- options = assignOptions(options);
146
- const request = event.request;
147
- const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
148
- const ASSET_MANIFEST =
149
- typeof options.ASSET_MANIFEST === "string"
150
- ? JSON.parse(options.ASSET_MANIFEST)
151
- : options.ASSET_MANIFEST;
152
- if (typeof ASSET_NAMESPACE === "undefined") {
153
- throw new types_1.InternalError(
154
- `there is no KV namespace bound to the script`
155
- );
156
- }
157
- const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ""); // strip any preceding /'s
158
- let pathIsEncoded = false;
159
- let requestKey;
160
- // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
161
- // otherwise handle request as normal, with default mapRequestToAsset below
162
- if (options.mapRequestToAsset) {
163
- requestKey = options.mapRequestToAsset(request);
164
- } else if (ASSET_MANIFEST[rawPathKey]) {
165
- requestKey = request;
166
- } else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
167
- pathIsEncoded = true;
168
- requestKey = request;
169
- } else {
170
- const mappedRequest = mapRequestToAsset(request);
171
- const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(
172
- /^\/+/,
173
- ""
174
- );
175
- if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
176
- pathIsEncoded = true;
177
- requestKey = mappedRequest;
178
- } else {
179
- // use default mapRequestToAsset
180
- requestKey = mapRequestToAsset(request, options);
181
- }
182
- }
183
- const SUPPORTED_METHODS = ["GET", "HEAD"];
184
- if (!SUPPORTED_METHODS.includes(requestKey.method)) {
185
- throw new types_1.MethodNotAllowedError(
186
- `${requestKey.method} is not a valid request method`
187
- );
188
- }
189
- const parsedUrl = new URL(requestKey.url);
190
- const pathname = pathIsEncoded
191
- ? decodeURIComponent(parsedUrl.pathname)
192
- : parsedUrl.pathname; // decode percentage encoded path only when necessary
193
- // pathKey is the file path to look up in the manifest
194
- let pathKey = pathname.replace(/^\/+/, ""); // remove prepended /
195
- // @ts-ignore
196
- const cache = caches.default;
197
- let mimeType = mime.getType(pathKey) || options.defaultMimeType;
198
- if (mimeType.startsWith("text") || mimeType === "application/javascript") {
199
- mimeType += "; charset=utf-8";
200
- }
201
- let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash
202
- // check manifest for map from file path to hash
203
- if (typeof ASSET_MANIFEST !== "undefined") {
204
- if (ASSET_MANIFEST[pathKey]) {
205
- pathKey = ASSET_MANIFEST[pathKey];
206
- // if path key is in asset manifest, we can assume it contains a content hash and can be cached
207
- shouldEdgeCache = true;
208
- }
209
- }
210
- // TODO this excludes search params from cache, investigate ideal behavior
211
- let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
212
- // if argument passed in for cacheControl is a function then
213
- // evaluate that function. otherwise return the Object passed in
214
- // or default Object
215
- const evalCacheOpts = (() => {
216
- switch (typeof options.cacheControl) {
217
- case "function":
218
- return options.cacheControl(request);
219
- case "object":
220
- return options.cacheControl;
221
- default:
222
- return defaultCacheControl;
223
- }
224
- })();
225
- // formats the etag depending on the response context. if the entityId
226
- // is invalid, returns an empty string (instead of null) to prevent the
227
- // the potentially disastrous scenario where the value of the Etag resp
228
- // header is "null". Could be modified in future to base64 encode etc
229
- const formatETag = (entityId = pathKey, validatorType = "strong") => {
230
- if (!entityId) {
231
- return "";
232
- }
233
- switch (validatorType) {
234
- case "weak":
235
- if (!entityId.startsWith("W/")) {
236
- return `W/${entityId}`;
237
- }
238
- return entityId;
239
- case "strong":
240
- if (entityId.startsWith(`W/"`)) {
241
- entityId = entityId.replace("W/", "");
242
- }
243
- if (!entityId.endsWith(`"`)) {
244
- entityId = `"${entityId}"`;
245
- }
246
- return entityId;
247
- default:
248
- return "";
249
- }
250
- };
251
- options.cacheControl = Object.assign(
252
- {},
253
- defaultCacheControl,
254
- evalCacheOpts
255
- );
256
- // override shouldEdgeCache if options say to bypassCache
257
- if (
258
- options.cacheControl.bypassCache ||
259
- options.cacheControl.edgeTTL === null ||
260
- request.method == "HEAD"
261
- ) {
262
- shouldEdgeCache = false;
263
- }
264
- // only set max-age if explicitly passed in a number as an arg
265
- const shouldSetBrowserCache =
266
- typeof options.cacheControl.browserTTL === "number";
267
- let response = null;
268
- if (shouldEdgeCache) {
269
- response = yield cache.match(cacheKey);
270
- }
271
- if (response) {
272
- if (response.status > 300 && response.status < 400) {
273
- if (response.body && "cancel" in Object.getPrototypeOf(response.body)) {
274
- response.body.cancel();
275
- console.log(
276
- "Body exists and environment supports readable streams. Body cancelled"
277
- );
278
- } else {
279
- console.log("Environment doesnt support readable streams");
280
- }
281
- response = new Response(null, response);
282
- } else {
283
- // fixes #165
284
- let opts = {
285
- headers: new Headers(response.headers),
286
- status: 0,
287
- statusText: "",
288
- };
289
- opts.headers.set("cf-cache-status", "HIT");
290
- if (response.status) {
291
- opts.status = response.status;
292
- opts.statusText = response.statusText;
293
- } else if (opts.headers.has("Content-Range")) {
294
- opts.status = 206;
295
- opts.statusText = "Partial Content";
296
- } else {
297
- opts.status = 200;
298
- opts.statusText = "OK";
299
- }
300
- response = new Response(response.body, opts);
301
- }
302
- } else {
303
- const body = yield ASSET_NAMESPACE.get(pathKey, "arrayBuffer");
304
- if (body === null) {
305
- throw new types_1.NotFoundError(
306
- `could not find ${pathKey} in your content namespace`
307
- );
308
- }
309
- response = new Response(body);
310
- if (shouldEdgeCache) {
311
- response.headers.set("Accept-Ranges", "bytes");
312
- response.headers.set("Content-Length", body.length);
313
- // set etag before cache insertion
314
- if (!response.headers.has("etag")) {
315
- response.headers.set("etag", formatETag(pathKey, "strong"));
316
- }
317
- // determine Cloudflare cache behavior
318
- response.headers.set(
319
- "Cache-Control",
320
- `max-age=${options.cacheControl.edgeTTL}`
321
- );
322
- event.waitUntil(cache.put(cacheKey, response.clone()));
323
- response.headers.set("CF-Cache-Status", "MISS");
324
- }
325
- }
326
- response.headers.set("Content-Type", mimeType);
327
- if (response.status === 304) {
328
- let etag = formatETag(response.headers.get("etag"), "strong");
329
- let ifNoneMatch = cacheKey.headers.get("if-none-match");
330
- let proxyCacheStatus = response.headers.get("CF-Cache-Status");
331
- if (etag) {
332
- if (
333
- ifNoneMatch &&
334
- ifNoneMatch === etag &&
335
- proxyCacheStatus === "MISS"
336
- ) {
337
- response.headers.set("CF-Cache-Status", "EXPIRED");
338
- } else {
339
- response.headers.set("CF-Cache-Status", "REVALIDATED");
340
- }
341
- response.headers.set("etag", formatETag(etag, "weak"));
342
- }
343
- }
344
- if (shouldSetBrowserCache) {
345
- response.headers.set(
346
- "Cache-Control",
347
- `max-age=${options.cacheControl.browserTTL}`
348
- );
349
- } else {
350
- response.headers.delete("Cache-Control");
351
- }
352
- return response;
353
- });
354
- exports.getAssetFromKV = getAssetFromKV;
@@ -1,13 +0,0 @@
1
- export declare const getEvent: (request: Request) => any;
2
- export declare const mockKV: (store: any) => {
3
- get: (path: string) => any;
4
- };
5
- export declare const mockManifest: () => string;
6
- export declare const mockCaches: () => {
7
- default: {
8
- match(key: any): Promise<any>;
9
- put(key: any, val: Response): Promise<void>;
10
- };
11
- };
12
- export declare function mockGlobal(): void;
13
- export declare const sleep: (milliseconds: number) => Promise<unknown>;
@@ -1,148 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.sleep = exports.mockGlobal = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0;
13
- const makeServiceWorkerEnv = require('service-worker-mock');
14
- const HASH = '123HASHBROWN';
15
- const getEvent = (request) => {
16
- const waitUntil = (callback) => __awaiter(void 0, void 0, void 0, function* () {
17
- yield callback;
18
- });
19
- return {
20
- request,
21
- waitUntil,
22
- };
23
- };
24
- exports.getEvent = getEvent;
25
- const store = {
26
- 'key1.123HASHBROWN.txt': 'val1',
27
- 'key1.123HASHBROWN.png': 'val1',
28
- 'index.123HASHBROWN.html': 'index.html',
29
- 'cache.123HASHBROWN.html': 'cache me if you can',
30
- '测试.123HASHBROWN.html': 'My filename is non-ascii',
31
- '%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded',
32
- '%2F.123HASHBROWN.html': 'user percent encoded',
33
- '你好.123HASHBROWN.html': 'I shouldnt be served',
34
- '%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important',
35
- 'nohash.txt': 'no hash but still got some result',
36
- 'sub/blah.123HASHBROWN.png': 'picturedis',
37
- 'sub/index.123HASHBROWN.html': 'picturedis',
38
- 'client.123HASHBROWN': 'important file',
39
- 'client.123HASHBROWN/index.html': 'Im here but serve my big bro above',
40
- '你好/index.123HASHBROWN.html': 'My path is non-ascii',
41
- };
42
- const mockKV = (store) => {
43
- return {
44
- get: (path) => store[path] || null,
45
- };
46
- };
47
- exports.mockKV = mockKV;
48
- const mockManifest = () => {
49
- return JSON.stringify({
50
- 'key1.txt': `key1.${HASH}.txt`,
51
- 'key1.png': `key1.${HASH}.png`,
52
- 'cache.html': `cache.${HASH}.html`,
53
- '测试.html': `测试.${HASH}.html`,
54
- '你好.html': `你好.${HASH}.html`,
55
- '%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`,
56
- '%2F.html': `%2F.${HASH}.html`,
57
- '%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`,
58
- 'index.html': `index.${HASH}.html`,
59
- 'sub/blah.png': `sub/blah.${HASH}.png`,
60
- 'sub/index.html': `sub/index.${HASH}.html`,
61
- client: `client.${HASH}`,
62
- 'client/index.html': `client.${HASH}`,
63
- '你好/index.html': `你好/index.${HASH}.html`,
64
- });
65
- };
66
- exports.mockManifest = mockManifest;
67
- let cacheStore = new Map();
68
- const mockCaches = () => {
69
- return {
70
- default: {
71
- match(key) {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- let cacheKey = {
74
- url: key.url,
75
- headers: {},
76
- };
77
- let response;
78
- if (key.headers.has('if-none-match')) {
79
- let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '');
80
- Reflect.set(cacheKey.headers, 'etag', makeStrongEtag);
81
- response = cacheStore.get(JSON.stringify(cacheKey));
82
- }
83
- else {
84
- // if client doesn't send if-none-match, we need to iterate through these keys
85
- // and just test the URL
86
- const activeCacheKeys = Array.from(cacheStore.keys());
87
- for (const cacheStoreKey of activeCacheKeys) {
88
- if (JSON.parse(cacheStoreKey).url === key.url) {
89
- response = cacheStore.get(cacheStoreKey);
90
- }
91
- }
92
- }
93
- // TODO: write test to accomodate for rare scenarios with where range requests accomodate etags
94
- if (response && !key.headers.has('if-none-match')) {
95
- // this appears overly verbose, but is necessary to document edge cache behavior
96
- // The Range request header triggers the response header Content-Range ...
97
- const range = key.headers.get('range');
98
- if (range) {
99
- response.headers.set('content-range', `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`);
100
- }
101
- // ... which we are using in this repository to set status 206
102
- if (response.headers.has('content-range')) {
103
- response.status = 206;
104
- }
105
- else {
106
- response.status = 200;
107
- }
108
- let etag = response.headers.get('etag');
109
- if (etag && !etag.includes('W/')) {
110
- response.headers.set('etag', `W/${etag}`);
111
- }
112
- }
113
- return response;
114
- });
115
- },
116
- put(key, val) {
117
- return __awaiter(this, void 0, void 0, function* () {
118
- let headers = new Headers(val.headers);
119
- let url = new URL(key.url);
120
- let resWithBody = new Response(val.body, { headers, status: 200 });
121
- let resNoBody = new Response(null, { headers, status: 304 });
122
- let cacheKey = {
123
- url: key.url,
124
- headers: {
125
- etag: `"${url.pathname.replace('/', '')}"`,
126
- },
127
- };
128
- cacheStore.set(JSON.stringify(cacheKey), resNoBody);
129
- cacheKey.headers = {};
130
- cacheStore.set(JSON.stringify(cacheKey), resWithBody);
131
- return;
132
- });
133
- },
134
- },
135
- };
136
- };
137
- exports.mockCaches = mockCaches;
138
- function mockGlobal() {
139
- Object.assign(global, makeServiceWorkerEnv());
140
- Object.assign(global, { __STATIC_CONTENT_MANIFEST: exports.mockManifest() });
141
- Object.assign(global, { __STATIC_CONTENT: exports.mockKV(store) });
142
- Object.assign(global, { caches: exports.mockCaches() });
143
- }
144
- exports.mockGlobal = mockGlobal;
145
- const sleep = (milliseconds) => {
146
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
147
- };
148
- exports.sleep = sleep;