{"version":3,"file":"with-response-cleanup.mjs","names":[],"sources":["../../../src/libs/runtime/with-response-cleanup.ts"],"sourcesContent":["/**\n * Keeps invocation-owned resources alive until a streamed response finishes,\n * then releases them when the body completes, fails or is cancelled.\n */\nconst withResponseCleanup = async (\n\tresponse: Response,\n\tcleanup: () => void | Promise<void>,\n): Promise<Response> => {\n\tif (!response.body) {\n\t\tawait cleanup();\n\t\treturn response;\n\t}\n\n\tconst reader = response.body.getReader();\n\tlet cleaned = false;\n\tconst runCleanup = async () => {\n\t\tif (cleaned) return;\n\t\tcleaned = true;\n\t\tawait cleanup();\n\t};\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst result = await reader.read();\n\t\t\t\tif (result.done) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\tawait runCleanup();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t\tawait runCleanup();\n\t\t\t}\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\ttry {\n\t\t\t\tawait reader.cancel(reason);\n\t\t\t} finally {\n\t\t\t\tawait runCleanup();\n\t\t\t}\n\t\t},\n\t});\n\n\tconst wrapped = new Response(body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders: response.headers,\n\t});\n\tfor (const key of Object.getOwnPropertyNames(response)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(response, key);\n\t\tif (descriptor) Object.defineProperty(wrapped, key, descriptor);\n\t}\n\tfor (const key of [\"redirected\", \"type\", \"url\"] as const) {\n\t\tif (Object.hasOwn(wrapped, key)) continue;\n\t\tObject.defineProperty(wrapped, key, {\n\t\t\tconfigurable: true,\n\t\t\tvalue: response[key],\n\t\t});\n\t}\n\treturn wrapped;\n};\n\nexport default withResponseCleanup;\n"],"mappings":"AAIA,MAAM,EAAsB,MAC3B,EACA,IACuB,CACvB,GAAI,CAAC,EAAS,KAEb,OADA,MAAM,EAAQ,EACP,EAGR,IAAM,EAAS,EAAS,KAAK,UAAU,EACnC,EAAU,GACR,EAAa,SAAY,CAC1B,IACJ,EAAU,GACV,MAAM,EAAQ,EACf,EACM,EAAO,IAAI,eAA2B,CAC3C,MAAM,KAAK,EAAY,CACtB,GAAI,CACH,IAAM,EAAS,MAAM,EAAO,KAAK,EACjC,GAAI,EAAO,KAAM,CAChB,EAAW,MAAM,EACjB,MAAM,EAAW,EACjB,MACD,CACA,EAAW,QAAQ,EAAO,KAAK,CAChC,OAAS,EAAO,CACf,EAAW,MAAM,CAAK,EACtB,MAAM,EAAW,CAClB,CACD,EACA,MAAM,OAAO,EAAQ,CACpB,GAAI,CACH,MAAM,EAAO,OAAO,CAAM,CAC3B,QAAU,CACT,MAAM,EAAW,CAClB,CACD,CACD,CAAC,EAEK,EAAU,IAAI,SAAS,EAAM,CAClC,OAAQ,EAAS,OACjB,WAAY,EAAS,WACrB,QAAS,EAAS,OACnB,CAAC,EACD,IAAK,IAAM,KAAO,OAAO,oBAAoB,CAAQ,EAAG,CACvD,IAAM,EAAa,OAAO,yBAAyB,EAAU,CAAG,EAC5D,GAAY,OAAO,eAAe,EAAS,EAAK,CAAU,CAC/D,CACA,IAAK,IAAM,IAAO,CAAC,aAAc,OAAQ,KAAK,EACzC,OAAO,OAAO,EAAS,CAAG,GAC9B,OAAO,eAAe,EAAS,EAAK,CACnC,aAAc,GACd,MAAO,EAAS,EACjB,CAAC,EAEF,OAAO,CACR"}