wrangler 0.0.0-e6733a3 → 0.0.0-e6ada079

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.

Potentially problematic release.


This version of wrangler might be problematic. Click here for more details.

Files changed (119) hide show
  1. package/README.md +47 -16
  2. package/bin/wrangler.js +94 -31
  3. package/config-schema.json +3100 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +154 -82
  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 +170 -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 +15 -0
  28. package/templates/new-worker.ts +33 -0
  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 +22 -0
  39. package/templates/tsconfig.json +8 -0
  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 +26391 -0
  45. package/wrangler-dist/cli.js +204293 -116652
  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 -39
  53. package/pages/functions/filepath-routing.ts +0 -221
  54. package/pages/functions/identifiers.ts +0 -78
  55. package/pages/functions/routes.ts +0 -158
  56. package/pages/functions/template-worker.ts +0 -144
  57. package/src/__tests__/clipboardy-mock.js +0 -4
  58. package/src/__tests__/dev.test.tsx +0 -66
  59. package/src/__tests__/index.test.ts +0 -287
  60. package/src/__tests__/jest.setup.ts +0 -22
  61. package/src/__tests__/kv.test.ts +0 -1098
  62. package/src/__tests__/mock-cfetch.ts +0 -171
  63. package/src/__tests__/mock-dialogs.ts +0 -65
  64. package/src/__tests__/run-in-tmp.ts +0 -19
  65. package/src/__tests__/run-wrangler.ts +0 -32
  66. package/src/api/form_data.ts +0 -131
  67. package/src/api/preview.ts +0 -128
  68. package/src/api/worker.ts +0 -155
  69. package/src/cfetch/index.ts +0 -102
  70. package/src/cfetch/internal.ts +0 -69
  71. package/src/cli.ts +0 -9
  72. package/src/config.ts +0 -487
  73. package/src/dev.tsx +0 -771
  74. package/src/dialogs.tsx +0 -77
  75. package/src/index.tsx +0 -1974
  76. package/src/inspect.ts +0 -524
  77. package/src/kv.tsx +0 -267
  78. package/src/module-collection.ts +0 -64
  79. package/src/pages.tsx +0 -1031
  80. package/src/proxy.ts +0 -294
  81. package/src/publish.ts +0 -358
  82. package/src/sites.tsx +0 -114
  83. package/src/tail.tsx +0 -73
  84. package/src/user.tsx +0 -1025
  85. package/static-asset-facade.js +0 -47
  86. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  87. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  88. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  89. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  90. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  91. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  92. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  93. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  94. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  95. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  96. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  97. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  98. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  99. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  100. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  101. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  102. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  103. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  104. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  105. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  106. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  107. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  108. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  109. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  110. package/vendor/wrangler-mime/LICENSE +0 -21
  111. package/vendor/wrangler-mime/Mime.js +0 -97
  112. package/vendor/wrangler-mime/README.md +0 -187
  113. package/vendor/wrangler-mime/cli.js +0 -46
  114. package/vendor/wrangler-mime/index.js +0 -4
  115. package/vendor/wrangler-mime/lite.js +0 -4
  116. package/vendor/wrangler-mime/package.json +0 -52
  117. package/vendor/wrangler-mime/types/other.js +0 -1
  118. package/vendor/wrangler-mime/types/standard.js +0 -1
  119. package/wrangler-dist/cli.js.map +0 -7
@@ -1,245 +0,0 @@
1
- # @cloudflare/kv-asset-handler
2
-
3
- [![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler)  
4
- [![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml)  
5
- [![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml)  
6
-
7
- `kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects.
8
-
9
- `kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client.
10
-
11
- Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations!
12
-
13
- For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV.
14
-
15
- The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers-sites` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.gg/cloudflaredev)!
16
-
17
- - [Installation](#installation)
18
- - [Usage](#usage)
19
- - [`getAssetFromKV`](#-getassetfromkv)
20
- - [Example](#example)
21
- * [Return](#return)
22
- * [Optional Arguments](#optional-arguments)
23
- - [`mapRequestToAsset`](#-maprequesttoasset)
24
- - [Example](#example-1)
25
- - [`cacheControl`](#-cachecontrol)
26
- - [`browserTTL`](#-browserttl)
27
- - [`edgeTTL`](#-edgettl)
28
- - [`bypassCache`](#-bypasscache)
29
- - [`ASSET_NAMESPACE`](#-asset-namespace)
30
- - [`ASSET_MANIFEST` (optional)](#-asset-manifest---optional)
31
-
32
- * [Helper functions](#helper-functions)
33
- - [`mapRequestToAsset`](#-maprequesttoasset-1)
34
- - [`serveSinglePageApp`](#-servesinglepageapp)
35
- * [Cache revalidation and etags](#cache-revalidation-and-etags)
36
-
37
- ## Installation
38
-
39
- Add this package to your `package.json` by running this in the root of your
40
- project's directory:
41
-
42
- ```
43
- npm i @cloudflare/kv-asset-handler
44
- ```
45
-
46
- ## Usage
47
-
48
- This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites).
49
-
50
- ## `getAssetFromKV`
51
-
52
- getAssetFromKV(FetchEvent) => Promise<Response>
53
-
54
- `getAssetFromKV` is an async function that takes a `FetchEvent` object and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`.
55
-
56
- #### Example
57
-
58
- This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`.
59
-
60
- ### Return
61
-
62
- `getAssetFromKV` returns a `Promise<Response>` with `Response` being the body of the asset requested.
63
-
64
- Known errors to be thrown are:
65
-
66
- - MethodNotAllowedError
67
- - NotFoundError
68
- - InternalError
69
-
70
- ```js
71
- import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler'
72
-
73
- addEventListener('fetch', (event) => {
74
- event.respondWith(handleEvent(event))
75
- })
76
-
77
- async function handleEvent(event) {
78
- if (event.request.url.includes('/docs')) {
79
- try {
80
- return await getAssetFromKV(event)
81
- } catch (e) {
82
- if (e instanceof NotFoundError) {
83
- // ...
84
- } else if (e instanceof MethodNotAllowedError) {
85
- // ...
86
- } else {
87
- return new Response('An unexpected error occurred', { status: 500 })
88
- }
89
- }
90
- } else return fetch(event.request)
91
- }
92
- ```
93
-
94
- ### Optional Arguments
95
-
96
- You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument.
97
-
98
- ```
99
- getAssetFromKV(event, { mapRequestToAsset: ... })
100
- ```
101
-
102
- #### `mapRequestToAsset`
103
-
104
- mapRequestToAsset(Request) => Request
105
-
106
- Maps the incoming request to the value that will be looked up in Cloudflare's KV
107
-
108
- By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV.
109
-
110
- For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function
111
-
112
- #### Example
113
-
114
- Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV.
115
-
116
- ```js
117
- import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
118
- ...
119
- const customKeyModifier = request => {
120
- let url = request.url
121
- //custom key mapping optional
122
- url = url.replace('/docs', '').replace(/^\/+/, '')
123
- return mapRequestToAsset(new Request(url, request))
124
- }
125
- let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier })
126
- ```
127
-
128
- #### `cacheControl`
129
-
130
- type: object
131
-
132
- `cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows:
133
-
134
- ```javascript
135
- let cacheControl = {
136
- browserTTL: null, // do not set cache control ttl on responses
137
- edgeTTL: 2 * 60 * 60 * 24, // 2 days
138
- bypassCache: false, // do not bypass Cloudflare's cache
139
- }
140
- ```
141
-
142
- ##### `browserTTL`
143
-
144
- type: number | null
145
- nullable: true
146
-
147
- Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all.
148
-
149
- ##### `edgeTTL`
150
-
151
- type: number | null
152
- nullable: true
153
-
154
- Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all.
155
-
156
- ##### `bypassCache`
157
-
158
- type: boolean
159
-
160
- Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing.
161
-
162
- #### `ASSET_NAMESPACE`
163
-
164
- type: KV Namespace Binding
165
-
166
- The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`.
167
-
168
- It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request.
169
-
170
- ```
171
- return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE })
172
- ```
173
-
174
- #### `ASSET_MANIFEST` (optional)
175
-
176
- type: text blob (JSON formatted)
177
-
178
- The mapping of requested file path to the key stored on Cloudflare.
179
-
180
- Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace.
181
-
182
- ```
183
- let assetManifest = { "index.html": "index.special.html" }
184
- return getAssetFromKV(event, { ASSET_MANIFEST: JSON.stringify(assetManifest) })
185
- ```
186
-
187
- #### `defaultMimeType` (optional)
188
-
189
- type: string
190
-
191
- This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`.
192
-
193
- If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`.
194
-
195
- #### `defaultDocument` (optional)
196
-
197
- type: string
198
-
199
- This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`.
200
-
201
- # Helper functions
202
-
203
- ## `mapRequestToAsset`
204
-
205
- mapRequestToAsset(Request) => Request
206
-
207
- The default function for mapping incoming requests to keys in Cloudflare's KV.
208
-
209
- Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace.
210
-
211
- ## `serveSinglePageApp`
212
-
213
- serveSinglePageApp(Request) => Request
214
-
215
- A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments.
216
-
217
- ```js
218
- import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
219
- ...
220
- let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })
221
- ```
222
-
223
- # Cache revalidation and etags
224
-
225
- All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: <filename>.<hash of file contents>.<extension>` (ex. `etag: index.54321.html`).
226
-
227
- Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits:
228
-
229
- - When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth.
230
- - Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired.
231
-
232
- #### Disable the `etag`
233
-
234
- To turn `etags` **off**, you must bypass cache:
235
-
236
- ```js
237
- /* Turn etags off */
238
- let cacheControl = {
239
- bypassCache: true,
240
- }
241
- ```
242
-
243
- #### Syntax and comparison context
244
-
245
- `kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client.
@@ -1,32 +0,0 @@
1
- import { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } from './types';
2
- declare global {
3
- var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string;
4
- }
5
- /**
6
- * maps the path of incoming request to the request pathKey to look up
7
- * in bucket and in cache
8
- * e.g. for a path '/' returns '/index.html' which serves
9
- * the content of bucket/index.html
10
- * @param {Request} request incoming request
11
- */
12
- declare const mapRequestToAsset: (request: Request, options?: Partial<Options>) => Request;
13
- /**
14
- * maps the path of incoming request to /index.html if it evaluates to
15
- * any HTML file.
16
- * @param {Request} request incoming request
17
- */
18
- declare function serveSinglePageApp(request: Request, options?: Partial<Options>): Request;
19
- /**
20
- * takes the path of the incoming request, gathers the appropriate content from KV, and returns
21
- * the response
22
- *
23
- * @param {FetchEvent} event the fetch event of the triggered request
24
- * @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
25
- * @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
26
- * @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
27
- * @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
28
- * @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
29
- * */
30
- declare const getAssetFromKV: (event: FetchEvent, options?: Partial<Options>) => Promise<Response>;
31
- export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
32
- export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError };
@@ -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>;