index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0;
  4. const mime = require("mime");
  5. const types_1 = require("./types");
  6. Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } });
  7. Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } });
  8. Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } });
  9. const defaultCacheControl = {
  10. browserTTL: null,
  11. edgeTTL: 2 * 60 * 60 * 24,
  12. bypassCache: false, // do not bypass Cloudflare's cache
  13. };
  14. const parseStringAsObject = (maybeString) => typeof maybeString === 'string' ? JSON.parse(maybeString) : maybeString;
  15. const getAssetFromKVDefaultOptions = {
  16. ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined,
  17. ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== 'undefined'
  18. ? parseStringAsObject(__STATIC_CONTENT_MANIFEST)
  19. : {},
  20. cacheControl: defaultCacheControl,
  21. defaultMimeType: 'text/plain',
  22. defaultDocument: 'index.html',
  23. pathIsEncoded: false,
  24. };
  25. function assignOptions(options) {
  26. // Assign any missing options passed in to the default
  27. // options.mapRequestToAsset is handled manually later
  28. return Object.assign({}, getAssetFromKVDefaultOptions, options);
  29. }
  30. /**
  31. * maps the path of incoming request to the request pathKey to look up
  32. * in bucket and in cache
  33. * e.g. for a path '/' returns '/index.html' which serves
  34. * the content of bucket/index.html
  35. * @param {Request} request incoming request
  36. */
  37. const mapRequestToAsset = (request, options) => {
  38. options = assignOptions(options);
  39. const parsedUrl = new URL(request.url);
  40. let pathname = parsedUrl.pathname;
  41. if (pathname.endsWith('/')) {
  42. // If path looks like a directory append options.defaultDocument
  43. // e.g. If path is /about/ -> /about/index.html
  44. pathname = pathname.concat(options.defaultDocument);
  45. }
  46. else if (!mime.getType(pathname)) {
  47. // If path doesn't look like valid content
  48. // e.g. /about.me -> /about.me/index.html
  49. pathname = pathname.concat('/' + options.defaultDocument);
  50. }
  51. parsedUrl.pathname = pathname;
  52. return new Request(parsedUrl.toString(), request);
  53. };
  54. exports.mapRequestToAsset = mapRequestToAsset;
  55. /**
  56. * maps the path of incoming request to /index.html if it evaluates to
  57. * any HTML file.
  58. * @param {Request} request incoming request
  59. */
  60. function serveSinglePageApp(request, options) {
  61. options = assignOptions(options);
  62. // First apply the default handler, which already has logic to detect
  63. // paths that should map to HTML files.
  64. request = mapRequestToAsset(request, options);
  65. const parsedUrl = new URL(request.url);
  66. // Detect if the default handler decided to map to
  67. // a HTML file in some specific directory.
  68. if (parsedUrl.pathname.endsWith('.html')) {
  69. // If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
  70. return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request);
  71. }
  72. else {
  73. // The default handler decided this is not an HTML page. It's probably
  74. // an image, CSS, or JS file. Leave it as-is.
  75. return request;
  76. }
  77. }
  78. exports.serveSinglePageApp = serveSinglePageApp;
  79. const getAssetFromKV = async (event, options) => {
  80. options = assignOptions(options);
  81. const request = event.request;
  82. const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
  83. const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST);
  84. if (typeof ASSET_NAMESPACE === 'undefined') {
  85. throw new types_1.InternalError(`there is no KV namespace bound to the script`);
  86. }
  87. const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ''); // strip any preceding /'s
  88. let pathIsEncoded = options.pathIsEncoded;
  89. let requestKey;
  90. // if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
  91. // otherwise handle request as normal, with default mapRequestToAsset below
  92. if (options.mapRequestToAsset) {
  93. requestKey = options.mapRequestToAsset(request);
  94. }
  95. else if (ASSET_MANIFEST[rawPathKey]) {
  96. requestKey = request;
  97. }
  98. else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
  99. pathIsEncoded = true;
  100. requestKey = request;
  101. }
  102. else {
  103. const mappedRequest = mapRequestToAsset(request);
  104. const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '');
  105. if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
  106. pathIsEncoded = true;
  107. requestKey = mappedRequest;
  108. }
  109. else {
  110. // use default mapRequestToAsset
  111. requestKey = mapRequestToAsset(request, options);
  112. }
  113. }
  114. const SUPPORTED_METHODS = ['GET', 'HEAD'];
  115. if (!SUPPORTED_METHODS.includes(requestKey.method)) {
  116. throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`);
  117. }
  118. const parsedUrl = new URL(requestKey.url);
  119. const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname; // decode percentage encoded path only when necessary
  120. // pathKey is the file path to look up in the manifest
  121. let pathKey = pathname.replace(/^\/+/, ''); // remove prepended /
  122. // @ts-ignore
  123. const cache = caches.default;
  124. let mimeType = mime.getType(pathKey) || options.defaultMimeType;
  125. if (mimeType.startsWith('text') || mimeType === 'application/javascript') {
  126. mimeType += '; charset=utf-8';
  127. }
  128. let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash
  129. // check manifest for map from file path to hash
  130. if (typeof ASSET_MANIFEST !== 'undefined') {
  131. if (ASSET_MANIFEST[pathKey]) {
  132. pathKey = ASSET_MANIFEST[pathKey];
  133. // if path key is in asset manifest, we can assume it contains a content hash and can be cached
  134. shouldEdgeCache = true;
  135. }
  136. }
  137. // TODO this excludes search params from cache, investigate ideal behavior
  138. let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
  139. // if argument passed in for cacheControl is a function then
  140. // evaluate that function. otherwise return the Object passed in
  141. // or default Object
  142. const evalCacheOpts = (() => {
  143. switch (typeof options.cacheControl) {
  144. case 'function':
  145. return options.cacheControl(request);
  146. case 'object':
  147. return options.cacheControl;
  148. default:
  149. return defaultCacheControl;
  150. }
  151. })();
  152. // formats the etag depending on the response context. if the entityId
  153. // is invalid, returns an empty string (instead of null) to prevent the
  154. // the potentially disastrous scenario where the value of the Etag resp
  155. // header is "null". Could be modified in future to base64 encode etc
  156. const formatETag = (entityId = pathKey, validatorType = 'strong') => {
  157. if (!entityId) {
  158. return '';
  159. }
  160. switch (validatorType) {
  161. case 'weak':
  162. if (!entityId.startsWith('W/')) {
  163. return `W/${entityId}`;
  164. }
  165. return entityId;
  166. case 'strong':
  167. if (entityId.startsWith(`W/"`)) {
  168. entityId = entityId.replace('W/', '');
  169. }
  170. if (!entityId.endsWith(`"`)) {
  171. entityId = `"${entityId}"`;
  172. }
  173. return entityId;
  174. default:
  175. return '';
  176. }
  177. };
  178. options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
  179. // override shouldEdgeCache if options say to bypassCache
  180. if (options.cacheControl.bypassCache ||
  181. options.cacheControl.edgeTTL === null ||
  182. request.method == 'HEAD') {
  183. shouldEdgeCache = false;
  184. }
  185. // only set max-age if explicitly passed in a number as an arg
  186. const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number';
  187. let response = null;
  188. if (shouldEdgeCache) {
  189. response = await cache.match(cacheKey);
  190. }
  191. if (response) {
  192. if (response.status > 300 && response.status < 400) {
  193. if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) {
  194. // Body exists and environment supports readable streams
  195. response.body.cancel();
  196. }
  197. else {
  198. // Environment doesnt support readable streams, or null repsonse body. Nothing to do
  199. }
  200. response = new Response(null, response);
  201. }
  202. else {
  203. // fixes #165
  204. let opts = {
  205. headers: new Headers(response.headers),
  206. status: 0,
  207. statusText: '',
  208. };
  209. opts.headers.set('cf-cache-status', 'HIT');
  210. if (response.status) {
  211. opts.status = response.status;
  212. opts.statusText = response.statusText;
  213. }
  214. else if (opts.headers.has('Content-Range')) {
  215. opts.status = 206;
  216. opts.statusText = 'Partial Content';
  217. }
  218. else {
  219. opts.status = 200;
  220. opts.statusText = 'OK';
  221. }
  222. response = new Response(response.body, opts);
  223. }
  224. }
  225. else {
  226. const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer');
  227. if (body === null) {
  228. throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`);
  229. }
  230. response = new Response(body);
  231. if (shouldEdgeCache) {
  232. response.headers.set('Accept-Ranges', 'bytes');
  233. response.headers.set('Content-Length', body.length);
  234. // set etag before cache insertion
  235. if (!response.headers.has('etag')) {
  236. response.headers.set('etag', formatETag(pathKey, 'strong'));
  237. }
  238. // determine Cloudflare cache behavior
  239. response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`);
  240. event.waitUntil(cache.put(cacheKey, response.clone()));
  241. response.headers.set('CF-Cache-Status', 'MISS');
  242. }
  243. }
  244. response.headers.set('Content-Type', mimeType);
  245. if (response.status === 304) {
  246. let etag = formatETag(response.headers.get('etag'), 'strong');
  247. let ifNoneMatch = cacheKey.headers.get('if-none-match');
  248. let proxyCacheStatus = response.headers.get('CF-Cache-Status');
  249. if (etag) {
  250. if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') {
  251. response.headers.set('CF-Cache-Status', 'EXPIRED');
  252. }
  253. else {
  254. response.headers.set('CF-Cache-Status', 'REVALIDATED');
  255. }
  256. response.headers.set('etag', formatETag(etag, 'weak'));
  257. }
  258. }
  259. if (shouldSetBrowserCache) {
  260. response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`);
  261. }
  262. else {
  263. response.headers.delete('Cache-Control');
  264. }
  265. return response;
  266. };
  267. exports.getAssetFromKV = getAssetFromKV;