blob: ac76d02e4aab6e8c96cf8c64642f9df8bfbb7235 [file] [log] [blame]
{"version":3,"file":"workbox-streams.prod.js","sources":["../_version.mjs","../concatenate.mjs","../utils/createHeaders.mjs","../concatenateToResponse.mjs","../isSupported.mjs","../strategy.mjs"],"sourcesContent":["try{self['workbox:streams:4.3.1']&&_()}catch(e){}// eslint-disable-line","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport {logger} from 'workbox-core/_private/logger.mjs';\nimport {assert} from 'workbox-core/_private/assert.mjs';\n\nimport './_version.mjs';\n\n/**\n * Takes either a Response, a ReadableStream, or a\n * [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the\n * ReadableStreamReader object associated with it.\n *\n * @param {workbox.streams.StreamSource} source\n * @return {ReadableStreamReader}\n * @private\n */\nfunction _getReaderFromSource(source) {\n if (source.body && source.body.getReader) {\n return source.body.getReader();\n }\n\n if (source.getReader) {\n return source.getReader();\n }\n\n // TODO: This should be possible to do by constructing a ReadableStream, but\n // I can't get it to work. As a hack, construct a new Response, and use the\n // reader associated with its body.\n return new Response(source).body.getReader();\n}\n\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).\n *\n * Returns an object exposing a ReadableStream with each individual stream's\n * data returned in sequence, along with a Promise which signals when the\n * stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array<Promise<workbox.streams.StreamSource>>} sourcePromises\n * @return {Object<{done: Promise, stream: ReadableStream}>}\n *\n * @memberof workbox.streams\n */\nfunction concatenate(sourcePromises) {\n if (process.env.NODE_ENV !== 'production') {\n assert.isArray(sourcePromises, {\n moduleName: 'workbox-streams',\n funcName: 'concatenate',\n paramName: 'sourcePromises',\n });\n }\n\n const readerPromises = sourcePromises.map((sourcePromise) => {\n return Promise.resolve(sourcePromise).then((source) => {\n return _getReaderFromSource(source);\n });\n });\n\n let fullyStreamedResolve;\n let fullyStreamedReject;\n const done = new Promise((resolve, reject) => {\n fullyStreamedResolve = resolve;\n fullyStreamedReject = reject;\n });\n\n let i = 0;\n const logMessages = [];\n const stream = new ReadableStream({\n pull(controller) {\n return readerPromises[i]\n .then((reader) => reader.read())\n .then((result) => {\n if (result.done) {\n if (process.env.NODE_ENV !== 'production') {\n logMessages.push(['Reached the end of source:',\n sourcePromises[i]]);\n }\n\n i++;\n if (i >= readerPromises.length) {\n // Log all the messages in the group at once in a single group.\n if (process.env.NODE_ENV !== 'production') {\n logger.groupCollapsed(\n `Concatenating ${readerPromises.length} sources.`);\n for (const message of logMessages) {\n if (Array.isArray(message)) {\n logger.log(...message);\n } else {\n logger.log(message);\n }\n }\n logger.log('Finished reading all sources.');\n logger.groupEnd();\n }\n\n controller.close();\n fullyStreamedResolve();\n return;\n }\n\n return this.pull(controller);\n } else {\n controller.enqueue(result.value);\n }\n }).catch((error) => {\n if (process.env.NODE_ENV !== 'production') {\n logger.error('An error occurred:', error);\n }\n fullyStreamedReject(error);\n throw error;\n });\n },\n\n cancel() {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('The ReadableStream was cancelled.');\n }\n\n fullyStreamedResolve();\n },\n });\n\n return {done, stream};\n}\n\nexport {concatenate};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport '../_version.mjs';\n\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * is available.\n *\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox.streams\n */\nfunction createHeaders(headersInit = {}) {\n // See https://github.com/GoogleChrome/workbox/issues/1461\n const headers = new Headers(headersInit);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'text/html');\n }\n return headers;\n}\n\nexport {createHeaders};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport {createHeaders} from './utils/createHeaders.mjs';\nimport {concatenate} from './concatenate.mjs';\n\nimport './_version.mjs';\n\n/**\n * Takes multiple source Promises, each of which could resolve to a Response, a\n * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit),\n * along with a\n * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit).\n *\n * Returns an object exposing a Response whose body consists of each individual\n * stream's data returned in sequence, along with a Promise which signals when\n * the stream is finished (useful for passing to a FetchEvent's waitUntil()).\n *\n * @param {Array<Promise<workbox.streams.StreamSource>>} sourcePromises\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {Object<{done: Promise, response: Response}>}\n *\n * @memberof workbox.streams\n */\nfunction concatenateToResponse(sourcePromises, headersInit) {\n const {done, stream} = concatenate(sourcePromises);\n\n const headers = createHeaders(headersInit);\n const response = new Response(stream, {headers});\n\n return {done, response};\n}\n\nexport {concatenateToResponse};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport './_version.mjs';\n\nlet cachedIsSupported = undefined;\n\n/**\n * This is a utility method that determines whether the current browser supports\n * the features required to create streamed responses. Currently, it checks if\n * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream)\n * can be created.\n *\n * @return {boolean} `true`, if the current browser meets the requirements for\n * streaming responses, and `false` otherwise.\n *\n * @memberof workbox.streams\n */\nfunction isSupported() {\n if (cachedIsSupported === undefined) {\n // See https://github.com/GoogleChrome/workbox/issues/1473\n try {\n new ReadableStream({start() {}});\n cachedIsSupported = true;\n } catch (error) {\n cachedIsSupported = false;\n }\n }\n\n return cachedIsSupported;\n}\n\nexport {isSupported};\n","/*\n Copyright 2018 Google LLC\n\n Use of this source code is governed by an MIT-style\n license that can be found in the LICENSE file or at\n https://opensource.org/licenses/MIT.\n*/\n\nimport {logger} from 'workbox-core/_private/logger.mjs';\n\nimport {createHeaders} from './utils/createHeaders.mjs';\nimport {concatenateToResponse} from './concatenateToResponse.mjs';\nimport {isSupported} from './isSupported.mjs';\n\nimport './_version.mjs';\n\n/**\n * A shortcut to create a strategy that could be dropped-in to Workbox's router.\n *\n * On browsers that do not support constructing new `ReadableStream`s, this\n * strategy will automatically wait for all the `sourceFunctions` to complete,\n * and create a final response that concatenates their values together.\n *\n * @param {\n * Array<function(workbox.routing.Route~handlerCallback)>} sourceFunctions\n * Each function should return a {@link workbox.streams.StreamSource} (or a\n * Promise which resolves to one).\n * @param {HeadersInit} [headersInit] If there's no `Content-Type` specified,\n * `'text/html'` will be used by default.\n * @return {workbox.routing.Route~handlerCallback}\n *\n * @memberof workbox.streams\n */\nexport function strategy(sourceFunctions, headersInit) {\n return async ({event, url, params}) => {\n if (isSupported()) {\n const {done, response} = concatenateToResponse(sourceFunctions.map(\n (fn) => fn({event, url, params})), headersInit);\n event.waitUntil(done);\n return response;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`The current browser doesn't support creating response ` +\n `streams. Falling back to non-streaming response instead.`);\n }\n\n // Fallback to waiting for everything to finish, and concatenating the\n // responses.\n const parts = await Promise.all(\n sourceFunctions.map(\n (sourceFunction) => sourceFunction({event, url, params})\n ).map(async (responsePromise) => {\n const response = await responsePromise;\n if (response instanceof Response) {\n return response.blob();\n }\n\n // Otherwise, assume it's something like a string which can be used\n // as-is when constructing the final composite blob.\n return response;\n })\n );\n\n const headers = createHeaders(headersInit);\n // Constructing a new Response from a Blob source is well-supported.\n // So is constructing a new Blob from multiple source Blobs or strings.\n return new Response(new Blob(parts), {headers});\n };\n}\n"],"names":["self","_","e","concatenate","sourcePromises","readerPromises","map","sourcePromise","Promise","resolve","then","source","body","getReader","Response","_getReaderFromSource","fullyStreamedResolve","fullyStreamedReject","done","reject","i","stream","ReadableStream","pull","controller","reader","read","result","length","close","this","enqueue","value","catch","error","cancel","createHeaders","headersInit","headers","Headers","has","set","concatenateToResponse","response","cachedIsSupported","undefined","isSupported","start","sourceFunctions","async","event","url","params","fn","waitUntil","parts","all","sourceFunction","responsePromise","blob","Blob"],"mappings":"4EAAA,IAAIA,KAAK,0BAA0BC,IAAI,MAAMC,ICkD7C,SAASC,EAAYC,SASbC,EAAiBD,EAAeE,IAAKC,GAClCC,QAAQC,QAAQF,GAAeG,KAAMC,IAtChD,SAA8BA,UACxBA,EAAOC,MAAQD,EAAOC,KAAKC,UACtBF,EAAOC,KAAKC,YAGjBF,EAAOE,UACFF,EAAOE,YAMT,IAAIC,SAASH,GAAQC,KAAKC,aA2BtBE,CAAqBJ,SAI5BK,EACAC,QACEC,EAAO,IAAIV,QAAQ,CAACC,EAASU,KACjCH,EAAuBP,EACvBQ,EAAsBE,QAGpBC,EAAI,QAyDD,CAACF,KAAAA,EAAMG,OAvDC,IAAIC,eAAe,CAChCC,KAAKC,UACInB,EAAee,GACjBV,KAAMe,GAAWA,EAAOC,QACxBhB,KAAMiB,OACDA,EAAOT,aAMTE,GACSf,EAAeuB,QAgBtBJ,EAAWK,aACXb,KAIKc,KAAKP,KAAKC,GAEjBA,EAAWO,QAAQJ,EAAOK,SAE3BC,MAAOC,UAIRjB,EAAoBiB,GACdA,KAIdC,SAKEnB,QCtGN,SAASoB,EAAcC,EAAc,UAE7BC,EAAU,IAAIC,QAAQF,UACvBC,EAAQE,IAAI,iBACfF,EAAQG,IAAI,eAAgB,aAEvBH,ECCT,SAASI,EAAsBtC,EAAgBiC,SACvCnB,KAACA,EAADG,OAAOA,GAAUlB,EAAYC,GAE7BkC,EAAUF,EAAcC,SAGvB,CAACnB,KAAAA,EAAMyB,SAFG,IAAI7B,SAASO,EAAQ,CAACiB,QAAAA,KCxBzC,IAAIM,OAAoBC,EAaxB,SAASC,YACmBD,IAAtBD,UAGItB,eAAe,CAACyB,YACpBH,GAAoB,EACpB,MAAOV,GACPU,GAAoB,SAIjBA,8ECDF,SAAkBI,EAAiBX,UACjCY,OAAQC,MAAAA,EAAOC,IAAAA,EAAKC,OAAAA,SACrBN,IAAe,OACX5B,KAACA,EAADyB,SAAOA,GAAYD,EAAsBM,EAAgB1C,IAC1D+C,GAAOA,EAAG,CAACH,MAAAA,EAAOC,IAAAA,EAAKC,OAAAA,KAAWf,UACvCa,EAAMI,UAAUpC,GACTyB,QAUHY,QAAc/C,QAAQgD,IACxBR,EAAgB1C,IACXmD,GAAmBA,EAAe,CAACP,MAAAA,EAAOC,IAAAA,EAAKC,OAAAA,KAClD9C,IAAI2C,MAAAA,UACEN,QAAiBe,SACnBf,aAAoB7B,SACf6B,EAASgB,OAKXhB,KAIPL,EAAUF,EAAcC,UAGvB,IAAIvB,SAAS,IAAI8C,KAAKL,GAAQ,CAACjB,QAAAA"}