/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__lib_response_cache__ = __webpack_require__(1);
// this imports a utility class for caching HTTP responses


// Handle HTTP requests
fly.http.respondWith(async function (req) {
  const cacheKey = req.url.replace(/\?status=\d+$/, '')

  // Fetch from
  let resp = await origin(req)

  if (resp.status < 400 || resp.status > 599) {
    // response is good, cache it forever
    await __WEBPACK_IMPORTED_MODULE_0__lib_response_cache__["a" /* default */].set(cacheKey, resp)
    // and return it
    return resp
  }

  let cachedResponse = await __WEBPACK_IMPORTED_MODULE_0__lib_response_cache__["a" /* default */].get(cacheKey)

  if (cachedResponse) {
    // set origin status in headers and return cached response
    cachedResponse.headers.set("Origin-Status", resp.status.toString())
    return cachedResponse
  }

  // if we got here, it's an error and we have nothing cached :()
  return resp
})

/**
 * This is just a basic origin http server that 
 * lets us control status codes.
 * 
 *   `/` => successful response
 *   `/?status=404` => serves a 404
 *   `/?status=500` => serves a 500
 */
async function origin(req, init) {
  const url = new URL(req.url)
  const status = parseInt(url.searchParams.get('status') || '200')

  if (status === 200) {
    return new Response(`hello from ${req.url} on ${new Date()}`)
  } else {
    return new Response(`an error! Number ${status}`, { status: status })
  }
}

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export get */
/* unused harmony export set */
/**
 * A basic cache handler for Response objects. This should
 * be modified to vary the key based on application logic 
 * like "logged in user" or "account number"
 */

/**
 * Gets an HTTP response from the cache
 * @param {string} key Key to retrieve
 * @returns {Response | null}.
 */
async function get(key) {
  let meta = await fly.cache.getString(key + ":meta")
  if (!meta) return null// cache miss
  try {
    meta = JSON.parse(meta)
  } catch (err) {
    return null// also a miss
  }

  let body = await fly.cache.get(key + ":body")
  if (!body) return null// miss
  if (meta.at) {
    meta.headers.Age = parseInt(Date.now() / 1000) - meta.at
    meta.headers['Fly-Age'] = meta.headers.Age
    delete meta.at
  }
  return new Response(body, meta)
}

const goodHeaders = [
  'content-type',
  'content-length',
  'content-encoding',
  'cache-control',
  'expires',
  'link',
  'set-cookie'
]
/**
 * Stores a Response in the cache
 * 
 * @param {string} key The key to store the response at
 * @param {Response} response An HTTP response to cache
 * @param {number | undefined} ttl Expire after seconds
 */
async function set(key, response, ttl) {
  let meta = {
    status: response.status,
    headers: {},
    at: parseInt(Date.now() / 1000)
  }
  for (const h of goodHeaders) {
    const v = response.headers.getAll(h)
    if (v && v.length > 0) {
      meta.headers[h] = v.join(", ")
    }
  }

  const body = await response.clone().arrayBuffer()
  const result = Promise.all([
    fly.cache.set(key + ":meta", JSON.stringify(meta), ttl),
    fly.cache.set(key + ":body", body, ttl)
  ])

  return result[0] && result[1]
}

/* harmony default export */ __webpack_exports__["a"] = ({
  get,
  set
});

/***/ })
/******/ ]);
//# sourceMappingURL=bundle.map.json