@caeliq/llms 1.0.57 → 1.0.59

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.
Files changed (75) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +82 -685
  3. package/dist/api/routes.d.ts +2 -0
  4. package/dist/cjs/server.cjs +279 -226
  5. package/dist/cjs/server.cjs.map +4 -4
  6. package/dist/cursor-sdk/hooks-template.d.ts +2 -1
  7. package/dist/cursor-sdk/host-env.d.ts +38 -0
  8. package/dist/cursor-sdk/lifecycle-planner.d.ts +69 -0
  9. package/dist/cursor-sdk/prompt.d.ts +33 -3
  10. package/dist/cursor-sdk/runner.d.ts +29 -0
  11. package/dist/cursor-sdk/session.d.ts +55 -1
  12. package/dist/cursor-sdk/shared.d.ts +14 -0
  13. package/dist/cursor-sdk/tool-paths.d.ts +26 -0
  14. package/dist/cursor-sdk/tools.d.ts +12 -1
  15. package/dist/cursor-sdk/turn-identity.d.ts +46 -0
  16. package/dist/cursor-sdk/turn-output.d.ts +77 -0
  17. package/dist/esm/server.mjs +280 -227
  18. package/dist/esm/server.mjs.map +4 -4
  19. package/dist/routing/inbound-pipeline.d.ts +31 -0
  20. package/dist/routing/protocol-adapter.d.ts +37 -0
  21. package/dist/routing/protocol-endpoints.d.ts +77 -0
  22. package/dist/routing/protocol-errors.d.ts +10 -0
  23. package/dist/server.d.ts +3 -1
  24. package/dist/services/provider.d.ts +1 -1
  25. package/dist/tests/anthropic.provider-wire.d.ts +1 -0
  26. package/dist/tests/anthropic.tool-call-id-sanitize.d.ts +1 -0
  27. package/dist/tests/anthropic.turn-intent.d.ts +1 -0
  28. package/dist/tests/claude-auth.identity.d.ts +1 -0
  29. package/dist/tests/client-abort-classification.test.d.ts +1 -0
  30. package/dist/tests/cursor-sdk.host-env.d.ts +1 -0
  31. package/dist/tests/cursor-sdk.interrupt-reentry.d.ts +1 -0
  32. package/dist/tests/cursor-sdk.lifecycle-planner.d.ts +1 -0
  33. package/dist/tests/cursor-sdk.pending-next-rejection.d.ts +1 -0
  34. package/dist/tests/cursor-sdk.scratch-paths.d.ts +1 -0
  35. package/dist/tests/cursor-sdk.scratch-report.d.ts +1 -0
  36. package/dist/tests/cursor-sdk.tool-call-id.d.ts +1 -0
  37. package/dist/tests/cursor-sdk.trailing-turn-fallback.d.ts +1 -0
  38. package/dist/tests/cursor-sdk.turn-coordination.d.ts +1 -0
  39. package/dist/tests/cursor-sdk.turn-identity.d.ts +1 -0
  40. package/dist/tests/inbound-protocol-routes.d.ts +1 -0
  41. package/dist/tests/inbound-routing-pipeline.d.ts +1 -0
  42. package/dist/tests/openai.inbound-chat.d.ts +1 -0
  43. package/dist/tests/openai.inbound-responses.d.ts +1 -0
  44. package/dist/tests/protocol-endpoints.d.ts +1 -0
  45. package/dist/tests/redact.body-for-log.d.ts +1 -0
  46. package/dist/tests/responses.call-id-sanitize.d.ts +1 -0
  47. package/dist/tests/responses.parallel-and-failure.d.ts +1 -0
  48. package/dist/tests/router-scenario-precedence.d.ts +1 -0
  49. package/dist/tests/stream.upstream-terminated.d.ts +1 -0
  50. package/dist/tests/system-instructions-fold.d.ts +1 -0
  51. package/dist/tests/upstream-error-semantics.d.ts +1 -0
  52. package/dist/transformer/anthropic.transformer.d.ts +16 -3
  53. package/dist/transformer/claude-auth.transformer.d.ts +36 -4
  54. package/dist/transformer/cursor-sdk.transformer.d.ts +4 -2
  55. package/dist/transformer/openai.responses.transformer.d.ts +17 -1
  56. package/dist/transformer/openai.transformer.d.ts +26 -32
  57. package/dist/transformer/tooluse.transformer.d.ts +1 -1
  58. package/dist/transformer/vercel.transformer.d.ts +1 -1
  59. package/dist/transformer/vertex-claude.transformer.d.ts +1 -1
  60. package/dist/transformer/vertex-gemini.transformer.d.ts +1 -1
  61. package/dist/types/transformer.d.ts +15 -0
  62. package/dist/types/turn-intent.d.ts +26 -0
  63. package/dist/utils/claude-auth.d.ts +9 -2
  64. package/dist/utils/claude-billing.d.ts +58 -0
  65. package/dist/utils/claude-model-catalog.d.ts +49 -0
  66. package/dist/utils/headers.d.ts +10 -0
  67. package/dist/utils/mistral.util.d.ts +1 -1
  68. package/dist/utils/openai.responses.util.d.ts +53 -0
  69. package/dist/utils/redact.d.ts +18 -0
  70. package/dist/utils/request.d.ts +1 -1
  71. package/dist/utils/retry.d.ts +7 -0
  72. package/dist/utils/router.d.ts +7 -0
  73. package/dist/utils/stream.d.ts +2 -0
  74. package/dist/utils/toolCallId.d.ts +23 -0
  75. package/package.json +25 -21
@@ -1,308 +1,356 @@
1
- "use strict";var MA=Object.create;var wa=Object.defineProperty;var UA=Object.getOwnPropertyDescriptor;var LA=Object.getOwnPropertyNames;var qA=Object.getPrototypeOf,$A=Object.prototype.hasOwnProperty;var fr=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bd=(t,e)=>{for(var n in e)wa(t,n,{get:e[n],enumerable:!0})},jy=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of LA(e))!$A.call(t,o)&&o!==n&&wa(t,o,{get:()=>e[o],enumerable:!(r=UA(e,o))||r.enumerable});return t};var st=(t,e,n)=>(n=t!=null?MA(qA(t)):{},jy(e||!t||!t.__esModule?wa(n,"default",{value:t,enumerable:!0}):n,t)),zA=t=>jy(wa({},"__esModule",{value:!0}),t);var My=V((uN,Ca)=>{Ca.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Ca.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Ca.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Md=V((lN,Uy)=>{var jd=My();Uy.exports={isSpaceSeparator(t){return typeof t=="string"&&jd.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||jd.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||jd.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var Hy=V((dN,zy)=>{var Ze=Md(),Ld,pt,jn,Sa,hr,Xt,et,zd,zs;zy.exports=function(e,n){Ld=String(e),pt="start",jn=[],Sa=0,hr=1,Xt=0,et=void 0,zd=void 0,zs=void 0;do et=HA(),JA[pt]();while(et.type!=="eof");return typeof n=="function"?qd({"":zs},"",n):zs};function qd(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),a=qd(r,s,n);a===void 0?delete r[s]:Object.defineProperty(r,s,{value:a,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=qd(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Se,_e,$s,Bn,Ae;function HA(){for(Se="default",_e="",$s=!1,Bn=1;;){Ae=Mn();let t=qy[Se]();if(t)return t}}function Mn(){if(Ld[Sa])return String.fromCodePoint(Ld.codePointAt(Sa))}function G(){let t=Mn();return t===`
2
- `?(hr++,Xt=0):t?Xt+=t.length:Xt++,t&&(Sa+=t.length),t}var qy={default(){switch(Ae){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
3
- `:case"\r":case"\u2028":case"\u2029":G();return;case"/":G(),Se="comment";return;case void 0:return G(),Le("eof")}if(Ze.isSpaceSeparator(Ae)){G();return}return qy[pt]()},comment(){switch(Ae){case"*":G(),Se="multiLineComment";return;case"/":G(),Se="singleLineComment";return}throw qe(G())},multiLineComment(){switch(Ae){case"*":G(),Se="multiLineCommentAsterisk";return;case void 0:throw qe(G())}G()},multiLineCommentAsterisk(){switch(Ae){case"*":G();return;case"/":G(),Se="default";return;case void 0:throw qe(G())}G(),Se="multiLineComment"},singleLineComment(){switch(Ae){case`
4
- `:case"\r":case"\u2028":case"\u2029":G(),Se="default";return;case void 0:return G(),Le("eof")}G()},value(){switch(Ae){case"{":case"[":return Le("punctuator",G());case"n":return G(),Br("ull"),Le("null",null);case"t":return G(),Br("rue"),Le("boolean",!0);case"f":return G(),Br("alse"),Le("boolean",!1);case"-":case"+":G()==="-"&&(Bn=-1),Se="sign";return;case".":_e=G(),Se="decimalPointLeading";return;case"0":_e=G(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":_e=G(),Se="decimalInteger";return;case"I":return G(),Br("nfinity"),Le("numeric",1/0);case"N":return G(),Br("aN"),Le("numeric",NaN);case'"':case"'":$s=G()==='"',_e="",Se="string";return}throw qe(G())},identifierNameStartEscape(){if(Ae!=="u")throw qe(G());G();let t=$d();switch(t){case"$":case"_":break;default:if(!Ze.isIdStartChar(t))throw Ly();break}_e+=t,Se="identifierName"},identifierName(){switch(Ae){case"$":case"_":case"\u200C":case"\u200D":_e+=G();return;case"\\":G(),Se="identifierNameEscape";return}if(Ze.isIdContinueChar(Ae)){_e+=G();return}return Le("identifier",_e)},identifierNameEscape(){if(Ae!=="u")throw qe(G());G();let t=$d();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!Ze.isIdContinueChar(t))throw Ly();break}_e+=t,Se="identifierName"},sign(){switch(Ae){case".":_e=G(),Se="decimalPointLeading";return;case"0":_e=G(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":_e=G(),Se="decimalInteger";return;case"I":return G(),Br("nfinity"),Le("numeric",Bn*(1/0));case"N":return G(),Br("aN"),Le("numeric",NaN)}throw qe(G())},zero(){switch(Ae){case".":_e+=G(),Se="decimalPoint";return;case"e":case"E":_e+=G(),Se="decimalExponent";return;case"x":case"X":_e+=G(),Se="hexadecimal";return}return Le("numeric",Bn*0)},decimalInteger(){switch(Ae){case".":_e+=G(),Se="decimalPoint";return;case"e":case"E":_e+=G(),Se="decimalExponent";return}if(Ze.isDigit(Ae)){_e+=G();return}return Le("numeric",Bn*Number(_e))},decimalPointLeading(){if(Ze.isDigit(Ae)){_e+=G(),Se="decimalFraction";return}throw qe(G())},decimalPoint(){switch(Ae){case"e":case"E":_e+=G(),Se="decimalExponent";return}if(Ze.isDigit(Ae)){_e+=G(),Se="decimalFraction";return}return Le("numeric",Bn*Number(_e))},decimalFraction(){switch(Ae){case"e":case"E":_e+=G(),Se="decimalExponent";return}if(Ze.isDigit(Ae)){_e+=G();return}return Le("numeric",Bn*Number(_e))},decimalExponent(){switch(Ae){case"+":case"-":_e+=G(),Se="decimalExponentSign";return}if(Ze.isDigit(Ae)){_e+=G(),Se="decimalExponentInteger";return}throw qe(G())},decimalExponentSign(){if(Ze.isDigit(Ae)){_e+=G(),Se="decimalExponentInteger";return}throw qe(G())},decimalExponentInteger(){if(Ze.isDigit(Ae)){_e+=G();return}return Le("numeric",Bn*Number(_e))},hexadecimal(){if(Ze.isHexDigit(Ae)){_e+=G(),Se="hexadecimalInteger";return}throw qe(G())},hexadecimalInteger(){if(Ze.isHexDigit(Ae)){_e+=G();return}return Le("numeric",Bn*Number(_e))},string(){switch(Ae){case"\\":G(),_e+=WA();return;case'"':if($s)return G(),Le("string",_e);_e+=G();return;case"'":if(!$s)return G(),Le("string",_e);_e+=G();return;case`
5
- `:case"\r":throw qe(G());case"\u2028":case"\u2029":VA(Ae);break;case void 0:throw qe(G())}_e+=G()},start(){switch(Ae){case"{":case"[":return Le("punctuator",G())}Se="value"},beforePropertyName(){switch(Ae){case"$":case"_":_e=G(),Se="identifierName";return;case"\\":G(),Se="identifierNameStartEscape";return;case"}":return Le("punctuator",G());case'"':case"'":$s=G()==='"',Se="string";return}if(Ze.isIdStartChar(Ae)){_e+=G(),Se="identifierName";return}throw qe(G())},afterPropertyName(){if(Ae===":")return Le("punctuator",G());throw qe(G())},beforePropertyValue(){Se="value"},afterPropertyValue(){switch(Ae){case",":case"}":return Le("punctuator",G())}throw qe(G())},beforeArrayValue(){if(Ae==="]")return Le("punctuator",G());Se="value"},afterArrayValue(){switch(Ae){case",":case"]":return Le("punctuator",G())}throw qe(G())},end(){throw qe(G())}};function Le(t,e){return{type:t,value:e,line:hr,column:Xt}}function Br(t){for(let e of t){if(Mn()!==e)throw qe(G());G()}}function WA(){switch(Mn()){case"b":return G(),"\b";case"f":return G(),"\f";case"n":return G(),`
6
- `;case"r":return G(),"\r";case"t":return G()," ";case"v":return G(),"\v";case"0":if(G(),Ze.isDigit(Mn()))throw qe(G());return"\0";case"x":return G(),GA();case"u":return G(),$d();case`
7
- `:case"\u2028":case"\u2029":return G(),"";case"\r":return G(),Mn()===`
8
- `&&G(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw qe(G());case void 0:throw qe(G())}return G()}function GA(){let t="",e=Mn();if(!Ze.isHexDigit(e)||(t+=G(),e=Mn(),!Ze.isHexDigit(e)))throw qe(G());return t+=G(),String.fromCodePoint(parseInt(t,16))}function $d(){let t="",e=4;for(;e-- >0;){let n=Mn();if(!Ze.isHexDigit(n))throw qe(G());t+=G()}return String.fromCodePoint(parseInt(t,16))}var JA={start(){if(et.type==="eof")throw jr();Ud()},beforePropertyName(){switch(et.type){case"identifier":case"string":zd=et.value,pt="afterPropertyName";return;case"punctuator":ka();return;case"eof":throw jr()}},afterPropertyName(){if(et.type==="eof")throw jr();pt="beforePropertyValue"},beforePropertyValue(){if(et.type==="eof")throw jr();Ud()},beforeArrayValue(){if(et.type==="eof")throw jr();if(et.type==="punctuator"&&et.value==="]"){ka();return}Ud()},afterPropertyValue(){if(et.type==="eof")throw jr();switch(et.value){case",":pt="beforePropertyName";return;case"}":ka()}},afterArrayValue(){if(et.type==="eof")throw jr();switch(et.value){case",":pt="beforeArrayValue";return;case"]":ka()}},end(){}};function Ud(){let t;switch(et.type){case"punctuator":switch(et.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=et.value;break}if(zs===void 0)zs=t;else{let e=jn[jn.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,zd,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")jn.push(t),Array.isArray(t)?pt="beforeArrayValue":pt="beforePropertyName";else{let e=jn[jn.length-1];e==null?pt="end":Array.isArray(e)?pt="afterArrayValue":pt="afterPropertyValue"}}function ka(){jn.pop();let t=jn[jn.length-1];t==null?pt="end":Array.isArray(t)?pt="afterArrayValue":pt="afterPropertyValue"}function qe(t){return Aa(t===void 0?`JSON5: invalid end of input at ${hr}:${Xt}`:`JSON5: invalid character '${$y(t)}' at ${hr}:${Xt}`)}function jr(){return Aa(`JSON5: invalid end of input at ${hr}:${Xt}`)}function Ly(){return Xt-=5,Aa(`JSON5: invalid identifier character at ${hr}:${Xt}`)}function VA(t){console.warn(`JSON5: '${$y(t)}' in strings is not valid ECMAScript; consider escaping`)}function $y(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function Aa(t){let e=new SyntaxError(t);return e.lineNumber=hr,e.columnNumber=Xt,e}});var Gy=V((fN,Wy)=>{var Hd=Md();Wy.exports=function(e,n,r){let o=[],s="",a,c,l="",f;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,f=n.quote,n=n.replacer),typeof n=="function")c=n;else if(Array.isArray(n)){a=[];for(let w of n){let b;typeof w=="string"?b=w:(typeof w=="number"||w instanceof String||w instanceof Number)&&(b=String(w)),b!==void 0&&a.indexOf(b)<0&&a.push(b)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),l=" ".substr(0,r)):typeof r=="string"&&(l=r.substr(0,10)),d("",{"":e});function d(w,b){let _=b[w];switch(_!=null&&(typeof _.toJSON5=="function"?_=_.toJSON5(w):typeof _.toJSON=="function"&&(_=_.toJSON(w))),c&&(_=c.call(b,w,_)),_ instanceof Number?_=Number(_):_ instanceof String?_=String(_):_ instanceof Boolean&&(_=_.valueOf()),_){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof _=="string")return h(_,!1);if(typeof _=="number")return String(_);if(typeof _=="object")return Array.isArray(_)?y(_):m(_)}function h(w){let b={"'":.1,'"':.2},_={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},D="";for(let v=0;v<w.length;v++){let x=w[v];switch(x){case"'":case'"':b[x]++,D+=x;continue;case"\0":if(Hd.isDigit(w[v+1])){D+="\\x00";continue}}if(_[x]){D+=_[x];continue}if(x<" "){let R=x.charCodeAt(0).toString(16);D+="\\x"+("00"+R).substring(R.length);continue}D+=x}let k=f||Object.keys(b).reduce((v,x)=>b[v]<b[x]?v:x);return D=D.replace(new RegExp(k,"g"),_[k]),k+D+k}function m(w){if(o.indexOf(w)>=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let b=s;s=s+l;let _=a||Object.keys(w),D=[];for(let v of _){let x=d(v,w);if(x!==void 0){let R=S(v)+":";l!==""&&(R+=" "),R+=x,D.push(R)}}let k;if(D.length===0)k="{}";else{let v;if(l==="")v=D.join(","),k="{"+v+"}";else{let x=`,
9
- `+s;v=D.join(x),k=`{
10
- `+s+v+`,
11
- `+b+"}"}}return o.pop(),s=b,k}function S(w){if(w.length===0)return h(w,!0);let b=String.fromCodePoint(w.codePointAt(0));if(!Hd.isIdStartChar(b))return h(w,!0);for(let _=b.length;_<w.length;_++)if(!Hd.isIdContinueChar(String.fromCodePoint(w.codePointAt(_))))return h(w,!0);return w}function y(w){if(o.indexOf(w)>=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let b=s;s=s+l;let _=[];for(let k=0;k<w.length;k++){let v=d(String(k),w);_.push(v!==void 0?v:"null")}let D;if(_.length===0)D="[]";else if(l==="")D="["+_.join(",")+"]";else{let k=`,
12
- `+s,v=_.join(k);D=`[
13
- `+s+v+`,
14
- `+b+"]"}return o.pop(),s=b,D}}});var Wd=V((hN,Jy)=>{var KA=Hy(),YA=Gy(),XA={parse:KA,stringify:YA};Jy.exports=XA});var k_=V((uB,TE)=>{TE.exports={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",i:"\u1D62",o:"\u2092",r:"\u1D63",u:"\u1D64",v:"\u1D65",x:"\u2093",\u03B2:"\u1D66",\u03B3:"\u1D67",\u03C1:"\u1D68",\u03C6:"\u1D69",\u03C7:"\u1D6A"}});var S_=V((lB,RE)=>{RE.exports={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",\u03B1:"\u1D45",\u03B2:"\u1D5D",\u03B3:"\u1D5E",\u03B4:"\u1D5F","\u220A":"\u1D4B",\u03B8:"\u1DBF",\u03B9:"\u1DA5",\u03A6:"\u1DB2",\u03C6:"\u1D60",\u03C7:"\u1D61"}});var A_=V((dB,DE)=>{DE.exports={"\\texttrademark":"\u2122","\\trademark":"\u2122","\\textregistered":"\xAE","\\registered":"\xAE","\\copyright":"\xA9","\\pilcrow":"\xB6","\\pound":"\xA3","\\euro":"\u20AC","\\cents":"\xA2","\\section":"\xA7","\\space":"\u2423","\\degree":"\xB0","\\zeta":"\u03B6","\\Xi":"\u039E","\\xi":"\u03BE","\\wr":"\u2240","\\wp":"\u2118","\\wedge":"\u2227","\\Vvdash":"\u22AA","\\veebar":"\u22BB","\\vee":"\u2228","\\vdots":"\u22EE","\\Vdash":"\u22A9","\\vDash":"\u22A8","\\vdash":"\u22A2","\\vartriangleright":"\u22B3","\\vartriangleleft":"\u22B2","\\vartriangle":"\u25B3","\\vartheta":"\u03D1","\\varsigma":"\u03C2","\\varrho":"\u03F1","\\varpropto":"\u221D","\\varpi":"\u03D6","\\varphi":"\u03C6","\\varnothing":"\u2205","\\varkappa":"\u03F0","\\varepsilon":"\u03B5","\\upuparrows":"\u21C8","\\Upsilon":"\u03A5","\\upsilon":"\u03C5","\\uplus":"\u228E","\\upharpoonright":"\u21BE","\\upharpoonleft":"\u21BF","\\Updownarrow":"\u21D5","\\updownarrow":"\u2195","\\Uparrow":"\u21D1","\\uparrow":"\u2191","\\unrhd":"\u22B5","\\unlhd":"\u22B4","\\twoheadrightarrow":"\u21A0","\\twoheadleftarrow":"\u219E","\\trianglerighteq":"\u22B5","\\triangleright":"\u25B7","\\triangleq":"\u225C","\\trianglelefteq":"\u22B4","\\triangleleft":"\u25C1","\\triangledown":"\u25BD","\\triangle":"\u25B3","\\top":"\u22A4","\\times":"\xD7","\\thicksim":"\u223C","\\thickapprox":"\u2248","\\Theta":"\u0398","\\theta":"\u03B8","\\therefore":"\u2234","\\tau":"\u03C4","\\swarrow":"\u2199","\\surd":"\u221A","\\supseteq":"\u2287","\\Supset":"\u22D1","\\supset":"\u2283","\\sum":"\u2211","\\succsim":"\u227F","\\succeq":"\u227D","\\succcurlyeq":"\u227D","\\succ":"\u227B","\\subseteq":"\u2286","\\Subset":"\u22D0","\\subset":"\u2282","\\star":"\u22C6","\\square":"\u25A1","\\sqsupseteq":"\u2292","\\sqsupset":"\u2290","\\sqsubseteq":"\u2291","\\sqsubset":"\u228F","\\sqcup":"\u2294","\\sqcap":"\u2293","\\sphericalangle":"\u2222","\\spadesuit":"\u2660","\\smile":"\u2323","\\smallsmile":"\u2323","\\smallsetminus":"\u2216","\\smallfrown":"\u2322","\\simeq":"\u2243","\\sim":"\u223C","\\sigma":"\u03C3","\\shortparallel":"\u2225","\\sharp":"\u266F","\\setminus":"\u2216","\\searrow":"\u2198","\\rtimes":"\u22C8","\\Rsh":"\u21B1","\\Rrightarrow":"\u21DB","\\risingdotseq":"\u2253","\\rightthreetimes":"\u22CC","\\rightsquigarrow":"\u21DD","\\rightrightarrows":"\u21C9","\\rightleftharpoons":"\u21CC","\\rightleftarrows":"\u21C4","\\rightharpoonup":"\u21C0","\\rightharpoondown":"\u21C1","\\rightarrowtail":"\u21A3","\\Rightarrow":"\u21D2","\\rightarrow":"\u2192","\\rho":"\u03C1","\\rhd":"\u22B3","\\rfloor":"\u230B","\\Re":"\u211C","\\rceil":"\u2309","\\Psi":"\u03A8","\\psi":"\u03C8","\\propto":"\u221D","\\prod":"\u220F","\\prime":"\u2032","\\precsim":"\u227E","\\preceq":"\u227C","\\preccurlyeq":"\u227C","\\prec":"\u227A","\\pm":"\xB1","\\Pi":"\u03A0","\\pi":"\u03C0","\\pitchfork":"\u22D4","\\Phi":"\u03A6","\\phi":"\u03D5","\\perp":"\u22A5","\\partial":"\u2202","\\parallel":"\u2225","\\otimes":"\u2297","\\oslash":"\u2298","\\oplus":"\u2295","\\ominus":"\u2296","\\Omega":"\u03A9","\\omega":"\u03C9","\\oint":"\u222E","\\odot":"\u2299","\\nwarrow":"\u2196","\\nu":"\u03BD","\\notin":"\u2209","\\ni":"\u220B","\\nexists":"\u2204","\\neq":"\u2260","\\neg":"\xAC","\\nearrow":"\u2197","\\natural":"\u266E","\\nabla":"\u2207","\\mu":"\u03BC","\\multimap":"\u22B8","\\mp":"\u2213","\\models":"\u22A8","\\mid":"\u2223","\\mho":"\u2127","\\measuredangle":"\u2221","\\mapsto":"\u21A6","\\ltimes":"\u22C9","\\Lsh":"\u21B0","\\lozenge":"\u25CA","\\looparrowright":"\u21AC","\\looparrowleft":"\u21AB","\\Longrightarrow":"\u21D2","\\longrightarrow":"\u2192","\\longmapsto":"\u21D6","\\Longleftrightarrow":"\u21D4","\\longleftrightarrow":"\u2194","\\Longleftarrow":"\u21D0","\\longleftarrow":"\u2190","\\lll":"\u22D8","\\Lleftarrow":"\u21DA","\\ll":"\u226A","\\lhd":"\u22B2","\\lfloor":"\u230A","\\lesssim":"\u2272","\\lessgtr":"\u2276","\\lesseqgtr":"\u22DA","\\lessdot":"\u22D6","\\leqslant":"\u2264","\\leqq":"\u2266","\\leq":"\u2264","\\leftthreetimes":"\u22CB","\\leftrightsquigarrow":"\u21AD","\\leftrightharpoons":"\u21CB","\\leftrightarrows":"\u21C6","\\Leftrightarrow":"\u21D4","\\leftrightarrow":"\u2194","\\leftleftarrows":"\u21C7","\\leftharpoonup":"\u21BC","\\leftharpoondown":"\u21BD","\\leftarrowtail":"\u21A2","\\Leftarrow":"\u21D0","\\leftarrow":"\u2190","\\leadsto":"\u219D","\\le":"\u2264","\\lceil":"\u2308","\\Lambda":"\u039B","\\lambda":"\u03BB","\\kappa":"\u03BA","\\Join":"\u22C8","\\iota":"\u03B9","\\intercal":"\u22BA","\\int":"\u222B","\\infty":"\u221E","\\in":"\u2208","\\implies":"\u21D2","\\Im":"\u2111","\\hslash":"\u210F","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\heartsuit":"\u2661","\\hbar":"\u210F","\\gtrsim":"\u2273","\\gtrless":"\u2277","\\gtreqless":"\u22DB","\\gtrdot":"\u22D7","\\gimel":"\u05D2","\\ggg":"\u22D9","\\gg":"\u226B","\\geqq":"\u2267","\\geq":"\u2265","\\ge":"\u2265","\\Gamma":"\u0393","\\gamma":"\u03B3","\\frown":"\u2322","\\forall":"\u2200","\\flat":"\u266D","\\Finv":"\u2132","\\fallingdotseq":"\u2252","\\exists":"\u2203","\\eth":"\xF0","\\eta":"\u03B7","\\equiv":"\u2261","\\eqcirc":"\u2256","\\epsilon":"\u220A","\\emptyset":"\u2205","\\ell":"\u2113","\\downharpoonright":"\u21C2","\\downharpoonleft":"\u21C3","\\downdownarrows":"\u21CA","\\Downarrow":"\u21D3","\\downarrow":"\u2193","\\dots":"\u2026","\\dotplus":"\u2214","\\doteqdot":"\u2251","\\doteq":"\u2250","\\divideontimes":"\u22C7","\\div":"\xF7","\\digamma":"\u03DC","\\diamondsuit":"\u2662","\\Diamond":"\u25C7","\\diamond":"\u22C4","\\Delta":"\u0394","\\delta":"\u03B4","\\ddots":"\u22F1","\\ddagger":"\u2021","\\dashv":"\u22A3","\\dashrightarrow":"\u21E2","\\dashleftarrow":"\u21E0","\\daleth":"\u05D3","\\dagger":"\u2020","\\curvearrowright":"\u21B7","\\curvearrowleft":"\u21B6","\\curlywedge":"\u22CF","\\curlyvee":"\u22CE","\\curlyeqsucc":"\u22DF","\\curlyeqprec":"\u22DE","\\Cup":"\u22D3","\\cup":"\u222A","\\coprod":"\u2210","\\cong":"\u2245","\\complement":"\u2201","\\clubsuit":"\u2663","\\circledS":"\u24C8","\\circleddash":"\u229D","\\circledcirc":"\u229A","\\circledast":"\u229B","\\circlearrowright":"\u21BB","\\circlearrowleft":"\u21BA","\\circeq":"\u2257","\\circ":"\u2218","\\chi":"\u03C7","\\centerdot":"\u22C5","\\cdots":"\u22EF","\\cdot":"\u22C5","\\Cap":"\u22D2","\\cap":"\u2229","\\Bumpeq":"\u224E","\\bumpeq":"\u224F","\\bullet":"\u2219","\\boxtimes":"\u22A0","\\boxplus":"\u229E","\\boxminus":"\u229F","\\boxdot":"\u22A1","\\Box":"\u25A1","\\bowtie":"\u22C8","\\bot":"\u22A5","\\blacktriangleright":"\u25B7","\\blacktriangleleft":"\u25C0","\\blacktriangledown":"\u25BC","\\blacktriangle":"\u25B2","\\blacksquare":"\u25A0","\\blacklozenge":"\u25C6","\\bigwedge":"\u22C0","\\bigvee":"\u22C1","\\biguplus":"\u228E","\\bigtriangleup":"\u25B3","\\bigtriangledown":"\u25BD","\\bigstar":"\u2605","\\bigsqcup":"\u2294","\\bigotimes":"\u2297","\\bigoplus":"\u2295","\\bigodot":"\u2299","\\bigcup":"\u22C3","\\bigcirc":"\u25CB","\\bigcap":"\u22C2","\\between":"\u226C","\\beth":"\u05D1","\\beta":"\u03B2","\\because":"\u2235","\\barwedge":"\u22BC","\\backsim":"\u223D","\\backprime":"\u2035","\\backepsilon":"\u220D","\\asymp":"\u224D","\\ast":"\u2217","\\approxeq":"\u224A","\\approx":"\u2248","\\angle":"\u2220","\\alpha":"\u03B1","\\aleph":"\u05D0"}});var E_=V((fB,xE)=>{xE.exports={A:"\u{1D538}",B:"\u{1D539}",C:"\u2102",D:"\u{1D53B}",E:"\u{1D53C}",F:"\u{1D53D}",G:"\u{1D53E}",H:"\u210D",I:"\u{1D540}",J:"\u{1D541}",K:"\u{1D542}",L:"\u{1D543}",M:"\u{1D544}",N:"\u2115",O:"\u{1D546}",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\u{1D54A}",T:"\u{1D54B}",U:"\u{1D54C}",V:"\u{1D54D}",W:"\u{1D54E}",X:"\u{1D54F}",Y:"\u{1D550}",Z:"\u2124",a:"\u{1D552}",b:"\u{1D553}",c:"\u{1D554}",d:"\u{1D555}",e:"\u{1D556}",f:"\u{1D557}",g:"\u{1D558}",h:"\u{1D559}",i:"\u{1D55A}",j:"\u{1D55B}",k:"\u{1D55C}",l:"\u{1D55D}",m:"\u{1D55E}",n:"\u{1D55F}",o:"\u{1D560}",p:"\u{1D561}",q:"\u{1D562}",r:"\u{1D563}",s:"\u{1D564}",t:"\u{1D565}",u:"\u{1D566}",v:"\u{1D567}",w:"\u{1D568}",x:"\u{1D569}",y:"\u{1D56A}",z:"\u{1D56B}","0":"\u{1D7D8}","1":"\u{1D7D9}","2":"\u{1D7DA}","3":"\u{1D7DB}","4":"\u{1D7DC}","5":"\u{1D7DD}","6":"\u{1D7DE}","7":"\u{1D7DF}","8":"\u{1D7E0}","9":"\u{1D7E1}"}});var v_=V((hB,OE)=>{OE.exports={A:"\u{1D400}",B:"\u{1D401}",C:"\u{1D402}",D:"\u{1D403}",E:"\u{1D404}",F:"\u{1D405}",G:"\u{1D406}",H:"\u{1D407}",I:"\u{1D408}",J:"\u{1D409}",K:"\u{1D40A}",L:"\u{1D40B}",M:"\u{1D40C}",N:"\u{1D40D}",O:"\u{1D40E}",P:"\u{1D40F}",Q:"\u{1D410}",R:"\u{1D411}",S:"\u{1D412}",T:"\u{1D413}",U:"\u{1D414}",V:"\u{1D415}",W:"\u{1D416}",X:"\u{1D417}",Y:"\u{1D418}",Z:"\u{1D419}",a:"\u{1D41A}",b:"\u{1D41B}",c:"\u{1D41C}",d:"\u{1D41D}",e:"\u{1D41E}",f:"\u{1D41F}",g:"\u{1D420}",h:"\u{1D421}",i:"\u{1D422}",j:"\u{1D423}",k:"\u{1D424}",l:"\u{1D425}",m:"\u{1D426}",n:"\u{1D427}",o:"\u{1D428}",p:"\u{1D429}",q:"\u{1D42A}",r:"\u{1D42B}",s:"\u{1D42C}",t:"\u{1D42D}",u:"\u{1D42E}",v:"\u{1D42F}",w:"\u{1D430}",x:"\u{1D431}",y:"\u{1D432}",z:"\u{1D433}",\u0391:"\u{1D6A8}",\u0392:"\u{1D6A9}",\u0393:"\u{1D6AA}",\u0394:"\u{1D6AB}",\u0395:"\u{1D6AC}",\u0396:"\u{1D6AD}",\u0397:"\u{1D6AE}",\u0398:"\u{1D6AF}",\u0399:"\u{1D6B0}",\u039A:"\u{1D6B1}",\u039B:"\u{1D6B2}",\u039C:"\u{1D6B3}",\u039D:"\u{1D6B4}",\u039E:"\u{1D6B5}",\u039F:"\u{1D6B6}",\u03A0:"\u{1D6B7}",\u03A1:"\u{1D6B8}","\u03F4":"\u{1D6B9}",\u03A3:"\u{1D6BA}",\u03A4:"\u{1D6BB}",\u03A5:"\u{1D6BC}",\u03A6:"\u{1D6BD}",\u03A7:"\u{1D6BE}",\u03A8:"\u{1D6BF}",\u03A9:"\u{1D6C0}","\u2207":"\u{1D6C1}",\u03B1:"\u{1D6C2}",\u03B2:"\u{1D6C3}",\u03B3:"\u{1D6C4}",\u03B4:"\u{1D6C5}",\u03B5:"\u{1D6C6}",\u03B6:"\u{1D6C7}",\u03B7:"\u{1D6C8}",\u03B8:"\u{1D6C9}",\u03B9:"\u{1D6CA}",\u03BA:"\u{1D6CB}",\u03BB:"\u{1D6CC}",\u03BC:"\u{1D6CD}",\u03BD:"\u{1D6CE}",\u03BE:"\u{1D6CF}",\u03BF:"\u{1D6D0}",\u03C0:"\u{1D6D1}",\u03C1:"\u{1D6D2}",\u03C2:"\u{1D6D3}",\u03C3:"\u{1D6D4}",\u03C4:"\u{1D6D5}",\u03C5:"\u{1D6D6}",\u03C6:"\u{1D6D7}",\u03C7:"\u{1D6D8}",\u03C8:"\u{1D6D9}",\u03C9:"\u{1D6DA}","\u2202":"\u{1D6DB}","\u03F5":"\u{1D6DC}",\u03D1:"\u{1D6DD}",\u03F0:"\u{1D6DE}",\u03D5:"\u{1D6DF}",\u03F1:"\u{1D6E0}",\u03D6:"\u{1D6E1}","0":"\u{1D7CE}","1":"\u{1D7CF}","2":"\u{1D7D0}","3":"\u{1D7D1}","4":"\u{1D7D2}","5":"\u{1D7D3}","6":"\u{1D7D4}","7":"\u{1D7D5}","8":"\u{1D7D6}","9":"\u{1D7D7}"}});var T_=V((pB,FE)=>{FE.exports={A:"\u{1D4D0}",B:"\u{1D4D1}",C:"\u{1D4D2}",D:"\u{1D4D3}",E:"\u{1D4D4}",F:"\u{1D4D5}",G:"\u{1D4D6}",H:"\u{1D4D7}",I:"\u{1D4D8}",J:"\u{1D4D9}",K:"\u{1D4DA}",L:"\u{1D4DB}",M:"\u{1D4DC}",N:"\u{1D4DD}",O:"\u{1D4DE}",P:"\u{1D4DF}",Q:"\u{1D4E0}",R:"\u{1D4E1}",S:"\u{1D4E2}",T:"\u{1D4E3}",U:"\u{1D4E4}",V:"\u{1D4E5}",W:"\u{1D4E6}",X:"\u{1D4E7}",Y:"\u{1D4E8}",Z:"\u{1D4E9}",a:"\u{1D4EA}",b:"\u{1D4EB}",c:"\u{1D4EC}",d:"\u{1D4ED}",e:"\u{1D4EE}",f:"\u{1D4EF}",g:"\u{1D4F0}",h:"\u{1D4F1}",i:"\u{1D4F2}",j:"\u{1D4F3}",k:"\u{1D4F4}",l:"\u{1D4F5}",m:"\u{1D4F6}",n:"\u{1D4F7}",o:"\u{1D4F8}",p:"\u{1D4F9}",q:"\u{1D4FA}",r:"\u{1D4FB}",s:"\u{1D4FC}",t:"\u{1D4FD}",u:"\u{1D4FE}",v:"\u{1D4FF}",w:"\u{1D500}",x:"\u{1D501}",y:"\u{1D502}",z:"\u{1D503}"}});var R_=V((gB,PE)=>{PE.exports={A:"\u{1D504}",B:"\u{1D505}",C:"\u212D",D:"\u{1D507}",E:"\u{1D508}",F:"\u{1D509}",G:"\u{1D50A}",H:"\u210C",I:"\u2111",J:"\u{1D50D}",K:"\u{1D50E}",L:"\u{1D50F}",M:"\u{1D510}",N:"\u{1D511}",O:"\u{1D512}",P:"\u{1D513}",Q:"\u{1D514}",R:"\u211C",S:"\u{1D516}",T:"\u{1D517}",U:"\u{1D518}",V:"\u{1D519}",W:"\u{1D51A}",X:"\u{1D51B}",Y:"\u{1D51C}",Z:"\u2128",a:"\u{1D51E}",b:"\u{1D51F}",c:"\u{1D520}",d:"\u{1D521}",e:"\u{1D522}",f:"\u{1D523}",g:"\u{1D524}",h:"\u{1D525}",i:"\u{1D526}",j:"\u{1D527}",k:"\u{1D528}",l:"\u{1D529}",m:"\u{1D52A}",n:"\u{1D52B}",o:"\u{1D52C}",p:"\u{1D52D}",q:"\u{1D52E}",r:"\u{1D52F}",s:"\u{1D530}",t:"\u{1D531}",u:"\u{1D532}",v:"\u{1D533}",w:"\u{1D534}",x:"\u{1D535}",y:"\u{1D536}",z:"\u{1D537}"}});var D_=V((mB,IE)=>{IE.exports={A:"\u{1D434}",B:"\u{1D435}",C:"\u{1D436}",D:"\u{1D437}",E:"\u{1D438}",F:"\u{1D439}",G:"\u{1D43A}",H:"\u{1D43B}",I:"\u{1D43C}",J:"\u{1D43D}",K:"\u{1D43E}",L:"\u{1D43F}",M:"\u{1D440}",N:"\u{1D441}",O:"\u{1D442}",P:"\u{1D443}",Q:"\u{1D444}",R:"\u{1D445}",S:"\u{1D446}",T:"\u{1D447}",U:"\u{1D448}",V:"\u{1D449}",W:"\u{1D44A}",X:"\u{1D44B}",Y:"\u{1D44C}",Z:"\u{1D44D}",a:"\u{1D44E}",b:"\u{1D44F}",c:"\u{1D450}",d:"\u{1D451}",e:"\u{1D452}",f:"\u{1D453}",g:"\u{1D454}",h:"\u210E",i:"\u{1D456}",j:"\u{1D457}",k:"\u{1D458}",l:"\u{1D459}",m:"\u{1D45A}",n:"\u{1D45B}",o:"\u{1D45C}",p:"\u{1D45D}",q:"\u{1D45E}",r:"\u{1D45F}",s:"\u{1D460}",t:"\u{1D461}",u:"\u{1D462}",v:"\u{1D463}",w:"\u{1D464}",x:"\u{1D465}",y:"\u{1D466}",z:"\u{1D467}",\u0391:"\u{1D6E2}",\u0392:"\u{1D6E3}",\u0393:"\u{1D6E4}",\u0394:"\u{1D6E5}",\u0395:"\u{1D6E6}",\u0396:"\u{1D6E7}",\u0397:"\u{1D6E8}",\u0398:"\u{1D6E9}",\u0399:"\u{1D6EA}",\u039A:"\u{1D6EB}",\u039B:"\u{1D6EC}",\u039C:"\u{1D6ED}",\u039D:"\u{1D6EE}",\u039E:"\u{1D6EF}",\u039F:"\u{1D6F0}",\u03A0:"\u{1D6F1}",\u03A1:"\u{1D6F2}","\u03F4":"\u{1D6F3}",\u03A3:"\u{1D6F4}",\u03A4:"\u{1D6F5}",\u03A5:"\u{1D6F6}",\u03A6:"\u{1D6F7}",\u03A7:"\u{1D6F8}",\u03A8:"\u{1D6F9}",\u03A9:"\u{1D6FA}","\u2207":"\u{1D6FB}",\u03B1:"\u{1D6FC}",\u03B2:"\u{1D6FD}",\u03B3:"\u{1D6FE}",\u03B4:"\u{1D6FF}",\u03B5:"\u{1D700}",\u03B6:"\u{1D701}",\u03B7:"\u{1D702}",\u03B8:"\u{1D703}",\u03B9:"\u{1D704}",\u03BA:"\u{1D705}",\u03BB:"\u{1D706}",\u03BC:"\u{1D707}",\u03BD:"\u{1D708}",\u03BE:"\u{1D709}",\u03BF:"\u{1D70A}",\u03C0:"\u{1D70B}",\u03C1:"\u{1D70C}",\u03C2:"\u{1D70D}",\u03C3:"\u{1D70E}",\u03C4:"\u{1D70F}",\u03C5:"\u{1D710}",\u03C6:"\u{1D711}",\u03C7:"\u{1D712}",\u03C8:"\u{1D713}",\u03C9:"\u{1D714}","\u2202":"\u{1D715}","\u03F5":"\u{1D716}",\u03D1:"\u{1D717}",\u03F0:"\u{1D718}",\u03D5:"\u{1D719}",\u03F1:"\u{1D71A}",\u03D6:"\u{1D71B}"}});var x_=V((yB,NE)=>{NE.exports={A:"\u{1D670}",B:"\u{1D671}",C:"\u{1D672}",D:"\u{1D673}",E:"\u{1D674}",F:"\u{1D675}",G:"\u{1D676}",H:"\u{1D677}",I:"\u{1D678}",J:"\u{1D679}",K:"\u{1D67A}",L:"\u{1D67B}",M:"\u{1D67C}",N:"\u{1D67D}",O:"\u{1D67E}",P:"\u{1D67F}",Q:"\u{1D680}",R:"\u{1D681}",S:"\u{1D682}",T:"\u{1D683}",U:"\u{1D684}",V:"\u{1D685}",W:"\u{1D686}",X:"\u{1D687}",Y:"\u{1D688}",Z:"\u{1D689}",a:"\u{1D68A}",b:"\u{1D68B}",c:"\u{1D68C}",d:"\u{1D68D}",e:"\u{1D68E}",f:"\u{1D68F}",g:"\u{1D690}",h:"\u{1D691}",i:"\u{1D692}",j:"\u{1D693}",k:"\u{1D694}",l:"\u{1D695}",m:"\u{1D696}",n:"\u{1D697}",o:"\u{1D698}",p:"\u{1D699}",q:"\u{1D69A}",r:"\u{1D69B}",s:"\u{1D69C}",t:"\u{1D69D}",u:"\u{1D69E}",v:"\u{1D69F}",w:"\u{1D6A0}",x:"\u{1D6A1}",y:"\u{1D6A2}",z:"\u{1D6A3}","0":"\u{1D7F6}","1":"\u{1D7F7}","2":"\u{1D7F8}","3":"\u{1D7F9}","4":"\u{1D7FA}","5":"\u{1D7FB}","6":"\u{1D7FC}","7":"\u{1D7FD}","8":"\u{1D7FE}","9":"\u{1D7FF}"}});var I_=V((_B,P_)=>{var BE=k_(),jE=S_(),O_=A_(),ME=E_(),UE=v_(),LE=T_(),qE=R_(),$E=D_(),zE=x_(),F_=function(t,e){return t[e]!==void 0?t[e]:e};function mr(t,e,n){t=t.replace(e,"^");var r="",o="normal",s,a;for(s=0;s<t.length;s++){if(a=t[s],o==="normal"&&a==="^"){o="modified";continue}else if(o==="modified"&&a==="{"){o="long";continue}else if(o==="modified"){r+=F_(n,a),o="normal";continue}else if(o==="long"&&a==="}"){o="normal";continue}o==="normal"?r+=a:r+=F_(n,a)}return r}P_.exports=function(t){return Object.keys(O_).forEach(function(e){var n=O_[e];t=t.replace(e,n)}),t=mr(t,"^",jE),t=mr(t,"_",BE),t=mr(t,"\\bb",ME),t=mr(t,"\\bf",UE),t=mr(t,"\\it",$E),t=mr(t,"\\cal",LE),t=mr(t,"\\frak",qE),t=mr(t,"\\mono",zE),t}});var sf=V((FB,X_)=>{"use strict";var Wa=Object.prototype.hasOwnProperty,Y_=Object.prototype.toString,H_=Object.defineProperty,W_=Object.getOwnPropertyDescriptor,G_=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Y_.call(e)==="[object Array]"},J_=function(e){if(!e||Y_.call(e)!=="[object Object]")return!1;var n=Wa.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Wa.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Wa.call(e,o)},V_=function(e,n){H_&&n.name==="__proto__"?H_(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},K_=function(e,n){if(n==="__proto__")if(Wa.call(e,n)){if(W_)return W_(e,n).value}else return;return e[n]};X_.exports=function t(){var e,n,r,o,s,a,c=arguments[0],l=1,f=arguments.length,d=!1;for(typeof c=="boolean"&&(d=c,c=arguments[1]||{},l=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});l<f;++l)if(e=arguments[l],e!=null)for(n in e)r=K_(c,n),o=K_(e,n),c!==o&&(d&&o&&(J_(o)||(s=G_(o)))?(s?(s=!1,a=r&&G_(r)?r:[]):a=r&&J_(r)?r:{},V_(c,{name:n,newValue:t(d,a,o)})):typeof o<"u"&&V_(c,{name:n,newValue:o}));return c}});var Q_=V((PB,ZE)=>{ZE.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var e0=V((IB,Z_)=>{"use strict";var ev=Q_();Z_.exports={pkg:ev}});var uf=V(Mt=>{"use strict";var n0=Mt&&Mt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.GaxiosError=Mt.GAXIOS_ERROR_SYMBOL=void 0;Mt.defaultErrorRedactor=r0;var t0=n0(sf()),tv=n0(e0()),af=tv.default.pkg;Mt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${af.name}-gaxios-error`);var cf=class t extends Error{config;response;code;status;error;[Mt.GAXIOS_ERROR_SYMBOL]=af.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Mt.GAXIOS_ERROR_SYMBOL in e&&e[Mt.GAXIOS_ERROR_SYMBOL]===af.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,t0.default)(!0,{},n),this.response&&(this.response.config=(0,t0.default)(!0,{},this.response.config)),this.response){try{this.response.data=nv(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let a=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&a.push(c.message);return Object.assign({message:a.join(`
15
- `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Mt.GaxiosError=cf;function nv(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function r0(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((a,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(s,a){if(typeof s=="object"&&s!==null&&typeof s[a]=="string"){let c=s[a];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[a]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((a,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(r0({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var s0=V(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});lf.getRetryConfig=rv;async function rv(t){let e=o0(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||ov)(t))return{shouldRetry:!1,config:t.config};let o=sv(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(a=>{setTimeout(a,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function ov(t){let e=o0(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function o0(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function sv(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var ff=V(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.GaxiosInterceptorManager=void 0;var df=class extends Set{};Ga.GaxiosInterceptorManager=df});var a0=V((MB,i0)=>{var xo=1e3,Oo=xo*60,Fo=Oo*60,Wr=Fo*24,iv=Wr*7,av=Wr*365.25;i0.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return cv(t);if(n==="number"&&isFinite(t))return e.long?lv(t):uv(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function cv(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*av;case"weeks":case"week":case"w":return n*iv;case"days":case"day":case"d":return n*Wr;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Fo;case"minutes":case"minute":case"mins":case"min":case"m":return n*Oo;case"seconds":case"second":case"secs":case"sec":case"s":return n*xo;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function uv(t){var e=Math.abs(t);return e>=Wr?Math.round(t/Wr)+"d":e>=Fo?Math.round(t/Fo)+"h":e>=Oo?Math.round(t/Oo)+"m":e>=xo?Math.round(t/xo)+"s":t+"ms"}function lv(t){var e=Math.abs(t);return e>=Wr?Ja(t,e,Wr,"day"):e>=Fo?Ja(t,e,Fo,"hour"):e>=Oo?Ja(t,e,Oo,"minute"):e>=xo?Ja(t,e,xo,"second"):t+" ms"}function Ja(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var hf=V((UB,c0)=>{function dv(t){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=o,n.enabled=c,n.humanize=a0(),n.destroy=f,Object.keys(t).forEach(d=>{n[d]=t[d]}),n.names=[],n.skips=[],n.formatters={};function e(d){let h=0;for(let m=0;m<d.length;m++)h=(h<<5)-h+d.charCodeAt(m),h|=0;return n.colors[Math.abs(h)%n.colors.length]}n.selectColor=e;function n(d){let h,m=null,S,y;function w(...b){if(!w.enabled)return;let _=w,D=Number(new Date),k=D-(h||D);_.diff=k,_.prev=h,_.curr=D,h=D,b[0]=n.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let v=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(R,j)=>{if(R==="%%")return"%";v++;let W=n.formatters[j];if(typeof W=="function"){let U=b[v];R=W.call(_,U),b.splice(v,1),v--}return R}),n.formatArgs.call(_,b),(_.log||n.log).apply(_,b)}return w.namespace=d,w.useColors=n.useColors(),w.color=n.selectColor(d),w.extend=r,w.destroy=n.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(S!==n.namespaces&&(S=n.namespaces,y=n.enabled(d)),y),set:b=>{m=b}}),typeof n.init=="function"&&n.init(w),w}function r(d,h){let m=n(this.namespace+(typeof h>"u"?":":h)+d);return m.log=this.log,m}function o(d){n.save(d),n.namespaces=d,n.names=[],n.skips=[];let h=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of h)m[0]==="-"?n.skips.push(m.slice(1)):n.names.push(m)}function s(d,h){let m=0,S=0,y=-1,w=0;for(;m<d.length;)if(S<h.length&&(h[S]===d[m]||h[S]==="*"))h[S]==="*"?(y=S,w=m,S++):(m++,S++);else if(y!==-1)S=y+1,w++,m=w;else return!1;for(;S<h.length&&h[S]==="*";)S++;return S===h.length}function a(){let d=[...n.names,...n.skips.map(h=>"-"+h)].join(",");return n.enable(""),d}function c(d){for(let h of n.skips)if(s(d,h))return!1;for(let h of n.names)if(s(d,h))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}c0.exports=dv});var u0=V((wt,Va)=>{wt.formatArgs=hv;wt.save=pv;wt.load=gv;wt.useColors=fv;wt.storage=mv();wt.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();wt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function fv(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function hv(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Va.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}wt.log=console.debug||console.log||(()=>{});function pv(t){try{t?wt.storage.setItem("debug",t):wt.storage.removeItem("debug")}catch{}}function gv(){let t;try{t=wt.storage.getItem("debug")||wt.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function mv(){try{return localStorage}catch{}}Va.exports=hf()(wt);var{formatters:yv}=Va.exports;yv.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var d0=V((LB,l0)=>{"use strict";l0.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var p0=V((qB,h0)=>{"use strict";var _v=require("os"),f0=require("tty"),Ut=d0(),{env:nt}=process,Ka;Ut("no-color")||Ut("no-colors")||Ut("color=false")||Ut("color=never")?Ka=0:(Ut("color")||Ut("colors")||Ut("color=true")||Ut("color=always"))&&(Ka=1);function bv(){if("FORCE_COLOR"in nt)return nt.FORCE_COLOR==="true"?1:nt.FORCE_COLOR==="false"?0:nt.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(nt.FORCE_COLOR,10),3)}function wv(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function Cv(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=bv();r!==void 0&&(Ka=r);let o=n?Ka:r;if(o===0)return 0;if(n){if(Ut("color=16m")||Ut("color=full")||Ut("color=truecolor"))return 3;if(Ut("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(nt.TERM==="dumb")return s;if(process.platform==="win32"){let a=_v.release().split(".");return Number(a[0])>=10&&Number(a[2])>=10586?Number(a[2])>=14931?3:2:1}if("CI"in nt)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(a=>a in nt)||nt.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in nt)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(nt.TEAMCITY_VERSION)?1:0;if(nt.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in nt){let a=Number.parseInt((nt.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(nt.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(nt.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(nt.TERM)||"COLORTERM"in nt?1:s}function pf(t,e={}){let n=Cv(t,{streamIsTTY:t&&t.isTTY,...e});return wv(n)}h0.exports={supportsColor:pf,stdout:pf({isTTY:f0.isatty(1)}),stderr:pf({isTTY:f0.isatty(2)})}});var m0=V((rt,Xa)=>{var kv=require("tty"),Ya=require("util");rt.init=Dv;rt.log=vv;rt.formatArgs=Av;rt.save=Tv;rt.load=Rv;rt.useColors=Sv;rt.destroy=Ya.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");rt.colors=[6,2,3,4,5,1];try{let t=p0();t&&(t.stderr||t).level>=2&&(rt.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}rt.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function Sv(){return"colors"in rt.inspectOpts?!!rt.inspectOpts.colors:kv.isatty(process.stderr.fd)}function Av(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
1
+ "use strict";var rR=Object.create;var $a=Object.defineProperty;var oR=Object.getOwnPropertyDescriptor;var sR=Object.getOwnPropertyNames;var iR=Object.getPrototypeOf,aR=Object.prototype.hasOwnProperty;var _r=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var J=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},Rf=(t,e)=>{for(var n in e)$a(t,n,{get:e[n],enumerable:!0})},R0=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sR(e))!aR.call(t,o)&&o!==n&&$a(t,o,{get:()=>e[o],enumerable:!(r=oR(e,o))||r.enumerable});return t};var tt=(t,e,n)=>(n=t!=null?rR(iR(t)):{},R0(e||!t||!t.__esModule?$a(n,"default",{value:t,enumerable:!0}):n,t)),cR=t=>R0($a({},"__esModule",{value:!0}),t);var D0=J((NL,xf)=>{"use strict";var uR=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,lR=/(\w*(\.\w*)*)\..*/;xf.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,x0(r.stack)}};function x0(t){let e=t.match(uR);return e?e[1].split(/[/\\]/).slice(-1)[0].match(lR)[1]:"anonymous"}xf.exports.extractPluginName=x0});var P0=J((ML,O0)=>{"use strict";O0.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var I0=J((BL,za)=>{"use strict";var dR=D0(),fR=P0(),pR=0;function Df(t,e={}){let n=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(n=!0,e.name=dR(t)+"-auto-"+pR++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let r=fR(e.name);return!n&&!t[r]&&(t[r]=t),t}za.exports=Df;za.exports.default=Df;za.exports.fastifyPlugin=Df});var F0=J(Pf=>{var hR=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,Ha=1e3,Wa=Ha*60,Ga=Wa*60,ui=Ga*24,Of=ui*365.25;function mR(t){var e,n=t.toLowerCase().match(hR);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*Ha:n[4]!=null?e*Wa:n[5]!=null?e*Ga:n[6]!=null?e*ui:n[7]!=null?e*ui*7:n[8]!=null?e*Of:e}function ci(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function gR(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<Ha?t+(e?" ms":"ms"):r<Wa?ci(r/Ha,n,"second",e):r<Ga?ci(r/Wa,n,"minute",e):r<ui?ci(r/Ga,n,"hour",e):r<Of?ci(r/ui,n,"day",e):ci(r/Of,n,"year",e)}Pf.format=gR;Pf.parse=mR});var M0=J(pn=>{"use strict";function Ya(t,e){if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("Invalid max value");if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("Invalid ttl value")}var If=class{constructor(e=1e3,n=0){Ya(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},Ja=class{constructor(e=1e3,n=0){Ya(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function Ff(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var Va=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:Ff()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=Ff()}getStatistics(){return this.records}},Nf=class{constructor(e=1e3,n=0){Ya(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},li=class{constructor(e=1e3,n=0){Ya(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function N0(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var Mf=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=N0(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new Va,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=Ff()),e[this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){Date.now()>=this.archiveAfter&&(this.collectionStart=new Date,this.currentTimeStamp=N0(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},Ka=class extends li{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Mf(r,s!==void 0?s:24,o)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,n){super.set(e,n),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){let e=this.size>0;super.evict(),e&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,n=!1){let r=this.items[e]!==void 0;super.delete(e),r&&!n&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(n),n.value||(this.hitStatistics.addFalsyHit(),(n.value===void 0||n.value===null||n.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),n.value}this.hitStatistics.addMiss()}};pn.Fifo=Ja;pn.FifoMap=If;pn.FifoObject=Ja;pn.HitStatisticsRecord=Va;pn.Lru=li;pn.LruHitStatistics=Ka;pn.LruMap=Nf;pn.LruObject=li;pn.LruObjectHitStatistics=Ka});var U0=J((LL,B0)=>{"use strict";var{LruMap:yR}=M0();function Xa(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new yR(n)}Xa.prototype.incr=function(t,e,n,r){let o=Date.now(),s=this.lru.get(t);if(!s)s={current:1,ttl:n,iterationStartMs:o};else if(s.iterationStartMs+n<=o)s.current=1,s.ttl=n,s.iterationStartMs=o;else if(++s.current,this.continueExceeding&&s.current>r)s.ttl=n,s.iterationStartMs=o;else if(this.exponentialBackoff&&s.current>r){let i=s.current-r-1,c=n*2**i;s.ttl=Number.isSafeInteger(c)?c:Number.MAX_SAFE_INTEGER,s.iterationStartMs=o}else s.ttl=n-(o-s.iterationStartMs);this.lru.set(t,s),e(null,s)};Xa.prototype.child=function(t){return new Xa(t.continueExceeding,t.exponentialBackoff,t.cache)};B0.exports=Xa});var L0=J((qL,j0)=>{"use strict";var _R=`
2
+ -- Key to operate on
3
+ local key = KEYS[1]
4
+ -- Time window for the TTL
5
+ local timeWindow = tonumber(ARGV[1])
6
+ -- Max requests
7
+ local max = tonumber(ARGV[2])
8
+ -- Flag to determine if TTL should be reset after exceeding
9
+ local continueExceeding = ARGV[3] == 'true'
10
+ --Flag to determine if exponential backoff should be applied
11
+ local exponentialBackoff = ARGV[4] == 'true'
12
+
13
+ --Max safe integer
14
+ local MAX_SAFE_INTEGER = (2^53) - 1
15
+
16
+ -- Increment the key's value
17
+ local current = redis.call('INCR', key)
18
+
19
+ if current == 1 or (continueExceeding and current > max) then
20
+ redis.call('PEXPIRE', key, timeWindow)
21
+ elseif exponentialBackoff and current > max then
22
+ local backoffExponent = current - max - 1
23
+ timeWindow = math.min(timeWindow * (2 ^ backoffExponent), MAX_SAFE_INTEGER)
24
+ redis.call('PEXPIRE', key, timeWindow)
25
+ else
26
+ timeWindow = redis.call('PTTL', key)
27
+ end
28
+
29
+ return {current, timeWindow}
30
+ `;function Qa(t,e,n,r="fastify-rate-limit-"){this.continueExceeding=t,this.exponentialBackoff=e,this.redis=n,this.key=r,this.redis.rateLimit||this.redis.defineCommand("rateLimit",{numberOfKeys:1,lua:_R})}Qa.prototype.incr=function(t,e,n,r){this.redis.rateLimit(this.key+t,n,r,this.continueExceeding,this.exponentialBackoff,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};Qa.prototype.child=function(t){return new Qa(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};j0.exports=Qa});var K0=J(($L,Za)=>{"use strict";var bR=I0(),{parse:z0,format:CR}=F0(),wR=U0(),kR=L0(),H0=1e3,W0=6e4,SR="onRequest",ER={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},vR={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},Bf=()=>{},AR=t=>t.ip,TR=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Uf(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=vR):(n.enableDraftSpec=!1,n.labels=ER),n.addHeaders=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0,[n.labels.retryAfter]:!0},e.addHeaders),n.addHeadersOnExceeding=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0},e.addHeadersOnExceeding),Number.isFinite(e.max)&&e.max>=0?n.max=Math.trunc(e.max):typeof e.max=="function"?n.max=e.max:n.max=H0,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=z0(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=W0,n.hook=e.hook||SR,n.allowList=e.allowList||e.whitelist||null,n.ban=Number.isFinite(e.ban)&&e.ban>=0?Math.trunc(e.ban):-1,n.onBanReach=typeof e.onBanReach=="function"?e.onBanReach:Bf,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:Bf,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:Bf,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:AR,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=TR,n.isCustomErrorMessage=!1),n.skipOnError=typeof e.skipOnError=="boolean"?e.skipOnError:!1;let r={rateLimitRan:Symbol("fastify.request.rateLimitRan"),store:null};if(e.store){let o=e.store;r.store=new o(n)}else e.redis?r.store=new kR(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new wR(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=q0(r,n,o);return i=>J0.apply(this,s.concat(i))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=q0(r,n,o);return V0(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=G0(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),$0(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&$0(r,n,o)})}function G0(...t){let e=Object.assign({},...t);if(Number.isFinite(e.timeWindow)&&e.timeWindow>=0?e.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?e.timeWindow=z0(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=W0),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=H0),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function q0(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=G0(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function $0(t,e,n){let r=e.hook,o=V0(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function J0(t,e,n){let{store:r}=t,o=await e.keyGenerator(n),s=n.routeOptions.config?.rateLimit?.groupId;if(s&&(o+=s),e.allowList){if(typeof e.allowList=="function"){if(await e.allowList(n,o))return{isAllowed:!0,key:o}}else if(e.allowList.indexOf(o)!==-1)return{isAllowed:!0,key:o}}let i=typeof e.max=="number"?e.max:await e.max(n,o),c=typeof e.timeWindow=="number"?e.timeWindow:await e.timeWindow(n,o),u=0,f=0,d=0;try{let p=await new Promise((h,_)=>{r.incr(o,(b,y)=>{b?_(b):h(y)},c,i)});u=p.current,f=p.ttl,d=Math.ceil(p.ttl/1e3)}catch(p){if(!e.skipOnError)throw p}return{isAllowed:!1,key:o,max:i,timeWindow:c,remaining:Math.max(0,i-u),ttl:f,ttlInSeconds:d,isExceeded:u>i,isBanned:e.ban!==-1&&u-i>e.ban}}function V0(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await J0(t,e,r);if(s.isAllowed)return;let{key:i,max:c,remaining:u,ttl:f,ttlInSeconds:d,isExceeded:p,isBanned:h}=s;if(!p){e.addHeadersOnExceeding[e.labels.rateLimit]&&o.header(e.labels.rateLimit,c),e.addHeadersOnExceeding[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,u),e.addHeadersOnExceeding[e.labels.rateReset]&&o.header(e.labels.rateReset,d),e.onExceeding(r,i);return}e.onExceeded(r,i),e.addHeaders[e.labels.rateLimit]&&o.header(e.labels.rateLimit,c),e.addHeaders[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,0),e.addHeaders[e.labels.rateReset]&&o.header(e.labels.rateReset,d),e.addHeaders[e.labels.retryAfter]&&o.header(e.labels.retryAfter,d);let _={statusCode:429,ban:!1,max:c,ttl:f,after:CR(d*1e3,!0)};throw h&&(_.statusCode=403,_.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,_)}}Za.exports=bR(Uf,{fastify:"5.x",name:"@fastify/rate-limit"});Za.exports.default=Uf;Za.exports.fastifyRateLimit=Uf});var Y0=J((zL,ec)=>{ec.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;ec.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;ec.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Lf=J((HL,X0)=>{var jf=Y0();X0.exports={isSpaceSeparator(t){return typeof t=="string"&&jf.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||jf.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||jf.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var nb=J((WL,tb)=>{var nt=Lf(),$f,mt,Ln,nc,br,Kt,rt,Wf,fi;tb.exports=function(e,n){$f=String(e),mt="start",Ln=[],nc=0,br=1,Kt=0,rt=void 0,Wf=void 0,fi=void 0;do rt=RR(),OR[mt]();while(rt.type!=="eof");return typeof n=="function"?zf({"":fi},"",n):fi};function zf(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),i=zf(r,s,n);i===void 0?delete r[s]:Object.defineProperty(r,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=zf(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Se,Ce,di,jn,ve;function RR(){for(Se="default",Ce="",di=!1,jn=1;;){ve=qn();let t=Z0[Se]();if(t)return t}}function qn(){if($f[nc])return String.fromCodePoint($f.codePointAt(nc))}function V(){let t=qn();return t===`
31
+ `?(br++,Kt=0):t?Kt+=t.length:Kt++,t&&(nc+=t.length),t}var Z0={default(){switch(ve){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
32
+ `:case"\r":case"\u2028":case"\u2029":V();return;case"/":V(),Se="comment";return;case void 0:return V(),je("eof")}if(nt.isSpaceSeparator(ve)){V();return}return Z0[mt]()},comment(){switch(ve){case"*":V(),Se="multiLineComment";return;case"/":V(),Se="singleLineComment";return}throw Le(V())},multiLineComment(){switch(ve){case"*":V(),Se="multiLineCommentAsterisk";return;case void 0:throw Le(V())}V()},multiLineCommentAsterisk(){switch(ve){case"*":V();return;case"/":V(),Se="default";return;case void 0:throw Le(V())}V(),Se="multiLineComment"},singleLineComment(){switch(ve){case`
33
+ `:case"\r":case"\u2028":case"\u2029":V(),Se="default";return;case void 0:return V(),je("eof")}V()},value(){switch(ve){case"{":case"[":return je("punctuator",V());case"n":return V(),Jr("ull"),je("null",null);case"t":return V(),Jr("rue"),je("boolean",!0);case"f":return V(),Jr("alse"),je("boolean",!1);case"-":case"+":V()==="-"&&(jn=-1),Se="sign";return;case".":Ce=V(),Se="decimalPointLeading";return;case"0":Ce=V(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=V(),Se="decimalInteger";return;case"I":return V(),Jr("nfinity"),je("numeric",1/0);case"N":return V(),Jr("aN"),je("numeric",NaN);case'"':case"'":di=V()==='"',Ce="",Se="string";return}throw Le(V())},identifierNameStartEscape(){if(ve!=="u")throw Le(V());V();let t=Hf();switch(t){case"$":case"_":break;default:if(!nt.isIdStartChar(t))throw Q0();break}Ce+=t,Se="identifierName"},identifierName(){switch(ve){case"$":case"_":case"\u200C":case"\u200D":Ce+=V();return;case"\\":V(),Se="identifierNameEscape";return}if(nt.isIdContinueChar(ve)){Ce+=V();return}return je("identifier",Ce)},identifierNameEscape(){if(ve!=="u")throw Le(V());V();let t=Hf();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!nt.isIdContinueChar(t))throw Q0();break}Ce+=t,Se="identifierName"},sign(){switch(ve){case".":Ce=V(),Se="decimalPointLeading";return;case"0":Ce=V(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=V(),Se="decimalInteger";return;case"I":return V(),Jr("nfinity"),je("numeric",jn*(1/0));case"N":return V(),Jr("aN"),je("numeric",NaN)}throw Le(V())},zero(){switch(ve){case".":Ce+=V(),Se="decimalPoint";return;case"e":case"E":Ce+=V(),Se="decimalExponent";return;case"x":case"X":Ce+=V(),Se="hexadecimal";return}return je("numeric",jn*0)},decimalInteger(){switch(ve){case".":Ce+=V(),Se="decimalPoint";return;case"e":case"E":Ce+=V(),Se="decimalExponent";return}if(nt.isDigit(ve)){Ce+=V();return}return je("numeric",jn*Number(Ce))},decimalPointLeading(){if(nt.isDigit(ve)){Ce+=V(),Se="decimalFraction";return}throw Le(V())},decimalPoint(){switch(ve){case"e":case"E":Ce+=V(),Se="decimalExponent";return}if(nt.isDigit(ve)){Ce+=V(),Se="decimalFraction";return}return je("numeric",jn*Number(Ce))},decimalFraction(){switch(ve){case"e":case"E":Ce+=V(),Se="decimalExponent";return}if(nt.isDigit(ve)){Ce+=V();return}return je("numeric",jn*Number(Ce))},decimalExponent(){switch(ve){case"+":case"-":Ce+=V(),Se="decimalExponentSign";return}if(nt.isDigit(ve)){Ce+=V(),Se="decimalExponentInteger";return}throw Le(V())},decimalExponentSign(){if(nt.isDigit(ve)){Ce+=V(),Se="decimalExponentInteger";return}throw Le(V())},decimalExponentInteger(){if(nt.isDigit(ve)){Ce+=V();return}return je("numeric",jn*Number(Ce))},hexadecimal(){if(nt.isHexDigit(ve)){Ce+=V(),Se="hexadecimalInteger";return}throw Le(V())},hexadecimalInteger(){if(nt.isHexDigit(ve)){Ce+=V();return}return je("numeric",jn*Number(Ce))},string(){switch(ve){case"\\":V(),Ce+=xR();return;case'"':if(di)return V(),je("string",Ce);Ce+=V();return;case"'":if(!di)return V(),je("string",Ce);Ce+=V();return;case`
34
+ `:case"\r":throw Le(V());case"\u2028":case"\u2029":PR(ve);break;case void 0:throw Le(V())}Ce+=V()},start(){switch(ve){case"{":case"[":return je("punctuator",V())}Se="value"},beforePropertyName(){switch(ve){case"$":case"_":Ce=V(),Se="identifierName";return;case"\\":V(),Se="identifierNameStartEscape";return;case"}":return je("punctuator",V());case'"':case"'":di=V()==='"',Se="string";return}if(nt.isIdStartChar(ve)){Ce+=V(),Se="identifierName";return}throw Le(V())},afterPropertyName(){if(ve===":")return je("punctuator",V());throw Le(V())},beforePropertyValue(){Se="value"},afterPropertyValue(){switch(ve){case",":case"}":return je("punctuator",V())}throw Le(V())},beforeArrayValue(){if(ve==="]")return je("punctuator",V());Se="value"},afterArrayValue(){switch(ve){case",":case"]":return je("punctuator",V())}throw Le(V())},end(){throw Le(V())}};function je(t,e){return{type:t,value:e,line:br,column:Kt}}function Jr(t){for(let e of t){if(qn()!==e)throw Le(V());V()}}function xR(){switch(qn()){case"b":return V(),"\b";case"f":return V(),"\f";case"n":return V(),`
35
+ `;case"r":return V(),"\r";case"t":return V()," ";case"v":return V(),"\v";case"0":if(V(),nt.isDigit(qn()))throw Le(V());return"\0";case"x":return V(),DR();case"u":return V(),Hf();case`
36
+ `:case"\u2028":case"\u2029":return V(),"";case"\r":return V(),qn()===`
37
+ `&&V(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw Le(V());case void 0:throw Le(V())}return V()}function DR(){let t="",e=qn();if(!nt.isHexDigit(e)||(t+=V(),e=qn(),!nt.isHexDigit(e)))throw Le(V());return t+=V(),String.fromCodePoint(parseInt(t,16))}function Hf(){let t="",e=4;for(;e-- >0;){let n=qn();if(!nt.isHexDigit(n))throw Le(V());t+=V()}return String.fromCodePoint(parseInt(t,16))}var OR={start(){if(rt.type==="eof")throw Vr();qf()},beforePropertyName(){switch(rt.type){case"identifier":case"string":Wf=rt.value,mt="afterPropertyName";return;case"punctuator":tc();return;case"eof":throw Vr()}},afterPropertyName(){if(rt.type==="eof")throw Vr();mt="beforePropertyValue"},beforePropertyValue(){if(rt.type==="eof")throw Vr();qf()},beforeArrayValue(){if(rt.type==="eof")throw Vr();if(rt.type==="punctuator"&&rt.value==="]"){tc();return}qf()},afterPropertyValue(){if(rt.type==="eof")throw Vr();switch(rt.value){case",":mt="beforePropertyName";return;case"}":tc()}},afterArrayValue(){if(rt.type==="eof")throw Vr();switch(rt.value){case",":mt="beforeArrayValue";return;case"]":tc()}},end(){}};function qf(){let t;switch(rt.type){case"punctuator":switch(rt.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=rt.value;break}if(fi===void 0)fi=t;else{let e=Ln[Ln.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Wf,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")Ln.push(t),Array.isArray(t)?mt="beforeArrayValue":mt="beforePropertyName";else{let e=Ln[Ln.length-1];e==null?mt="end":Array.isArray(e)?mt="afterArrayValue":mt="afterPropertyValue"}}function tc(){Ln.pop();let t=Ln[Ln.length-1];t==null?mt="end":Array.isArray(t)?mt="afterArrayValue":mt="afterPropertyValue"}function Le(t){return rc(t===void 0?`JSON5: invalid end of input at ${br}:${Kt}`:`JSON5: invalid character '${eb(t)}' at ${br}:${Kt}`)}function Vr(){return rc(`JSON5: invalid end of input at ${br}:${Kt}`)}function Q0(){return Kt-=5,rc(`JSON5: invalid identifier character at ${br}:${Kt}`)}function PR(t){console.warn(`JSON5: '${eb(t)}' in strings is not valid ECMAScript; consider escaping`)}function eb(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function rc(t){let e=new SyntaxError(t);return e.lineNumber=br,e.columnNumber=Kt,e}});var ob=J((GL,rb)=>{var Gf=Lf();rb.exports=function(e,n,r){let o=[],s="",i,c,u="",f;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,f=n.quote,n=n.replacer),typeof n=="function")c=n;else if(Array.isArray(n)){i=[];for(let y of n){let w;typeof y=="string"?w=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(w=String(y)),w!==void 0&&i.indexOf(w)<0&&i.push(w)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),d("",{"":e});function d(y,w){let C=w[y];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(y):typeof C.toJSON=="function"&&(C=C.toJSON(y))),c&&(C=c.call(w,y,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return p(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?b(C):h(C)}function p(y){let w={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},v="";for(let T=0;T<y.length;T++){let x=y[T];switch(x){case"'":case'"':w[x]++,v+=x;continue;case"\0":if(Gf.isDigit(y[T+1])){v+="\\x00";continue}}if(C[x]){v+=C[x];continue}if(x<" "){let O=x.charCodeAt(0).toString(16);v+="\\x"+("00"+O).substring(O.length);continue}v+=x}let A=f||Object.keys(w).reduce((T,x)=>w[T]<w[x]?T:x);return v=v.replace(new RegExp(A,"g"),C[A]),A+v+A}function h(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let w=s;s=s+u;let C=i||Object.keys(y),v=[];for(let T of C){let x=d(T,y);if(x!==void 0){let O=_(T)+":";u!==""&&(O+=" "),O+=x,v.push(O)}}let A;if(v.length===0)A="{}";else{let T;if(u==="")T=v.join(","),A="{"+T+"}";else{let x=`,
38
+ `+s;T=v.join(x),A=`{
39
+ `+s+T+`,
40
+ `+w+"}"}}return o.pop(),s=w,A}function _(y){if(y.length===0)return p(y,!0);let w=String.fromCodePoint(y.codePointAt(0));if(!Gf.isIdStartChar(w))return p(y,!0);for(let C=w.length;C<y.length;C++)if(!Gf.isIdContinueChar(String.fromCodePoint(y.codePointAt(C))))return p(y,!0);return y}function b(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let w=s;s=s+u;let C=[];for(let A=0;A<y.length;A++){let T=d(String(A),y);C.push(T!==void 0?T:"null")}let v;if(C.length===0)v="[]";else if(u==="")v="["+C.join(",")+"]";else{let A=`,
41
+ `+s,T=C.join(A);v=`[
42
+ `+s+T+`,
43
+ `+w+"]"}return o.pop(),s=w,v}}});var Jf=J((JL,sb)=>{var IR=nb(),FR=ob(),NR={parse:IR,stringify:FR};sb.exports=NR});var pC=J((h2,Vx)=>{Vx.exports={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",i:"\u1D62",o:"\u2092",r:"\u1D63",u:"\u1D64",v:"\u1D65",x:"\u2093",\u03B2:"\u1D66",\u03B3:"\u1D67",\u03C1:"\u1D68",\u03C6:"\u1D69",\u03C7:"\u1D6A"}});var hC=J((m2,Kx)=>{Kx.exports={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",\u03B1:"\u1D45",\u03B2:"\u1D5D",\u03B3:"\u1D5E",\u03B4:"\u1D5F","\u220A":"\u1D4B",\u03B8:"\u1DBF",\u03B9:"\u1DA5",\u03A6:"\u1DB2",\u03C6:"\u1D60",\u03C7:"\u1D61"}});var mC=J((g2,Yx)=>{Yx.exports={"\\texttrademark":"\u2122","\\trademark":"\u2122","\\textregistered":"\xAE","\\registered":"\xAE","\\copyright":"\xA9","\\pilcrow":"\xB6","\\pound":"\xA3","\\euro":"\u20AC","\\cents":"\xA2","\\section":"\xA7","\\space":"\u2423","\\degree":"\xB0","\\zeta":"\u03B6","\\Xi":"\u039E","\\xi":"\u03BE","\\wr":"\u2240","\\wp":"\u2118","\\wedge":"\u2227","\\Vvdash":"\u22AA","\\veebar":"\u22BB","\\vee":"\u2228","\\vdots":"\u22EE","\\Vdash":"\u22A9","\\vDash":"\u22A8","\\vdash":"\u22A2","\\vartriangleright":"\u22B3","\\vartriangleleft":"\u22B2","\\vartriangle":"\u25B3","\\vartheta":"\u03D1","\\varsigma":"\u03C2","\\varrho":"\u03F1","\\varpropto":"\u221D","\\varpi":"\u03D6","\\varphi":"\u03C6","\\varnothing":"\u2205","\\varkappa":"\u03F0","\\varepsilon":"\u03B5","\\upuparrows":"\u21C8","\\Upsilon":"\u03A5","\\upsilon":"\u03C5","\\uplus":"\u228E","\\upharpoonright":"\u21BE","\\upharpoonleft":"\u21BF","\\Updownarrow":"\u21D5","\\updownarrow":"\u2195","\\Uparrow":"\u21D1","\\uparrow":"\u2191","\\unrhd":"\u22B5","\\unlhd":"\u22B4","\\twoheadrightarrow":"\u21A0","\\twoheadleftarrow":"\u219E","\\trianglerighteq":"\u22B5","\\triangleright":"\u25B7","\\triangleq":"\u225C","\\trianglelefteq":"\u22B4","\\triangleleft":"\u25C1","\\triangledown":"\u25BD","\\triangle":"\u25B3","\\top":"\u22A4","\\times":"\xD7","\\thicksim":"\u223C","\\thickapprox":"\u2248","\\Theta":"\u0398","\\theta":"\u03B8","\\therefore":"\u2234","\\tau":"\u03C4","\\swarrow":"\u2199","\\surd":"\u221A","\\supseteq":"\u2287","\\Supset":"\u22D1","\\supset":"\u2283","\\sum":"\u2211","\\succsim":"\u227F","\\succeq":"\u227D","\\succcurlyeq":"\u227D","\\succ":"\u227B","\\subseteq":"\u2286","\\Subset":"\u22D0","\\subset":"\u2282","\\star":"\u22C6","\\square":"\u25A1","\\sqsupseteq":"\u2292","\\sqsupset":"\u2290","\\sqsubseteq":"\u2291","\\sqsubset":"\u228F","\\sqcup":"\u2294","\\sqcap":"\u2293","\\sphericalangle":"\u2222","\\spadesuit":"\u2660","\\smile":"\u2323","\\smallsmile":"\u2323","\\smallsetminus":"\u2216","\\smallfrown":"\u2322","\\simeq":"\u2243","\\sim":"\u223C","\\sigma":"\u03C3","\\shortparallel":"\u2225","\\sharp":"\u266F","\\setminus":"\u2216","\\searrow":"\u2198","\\rtimes":"\u22C8","\\Rsh":"\u21B1","\\Rrightarrow":"\u21DB","\\risingdotseq":"\u2253","\\rightthreetimes":"\u22CC","\\rightsquigarrow":"\u21DD","\\rightrightarrows":"\u21C9","\\rightleftharpoons":"\u21CC","\\rightleftarrows":"\u21C4","\\rightharpoonup":"\u21C0","\\rightharpoondown":"\u21C1","\\rightarrowtail":"\u21A3","\\Rightarrow":"\u21D2","\\rightarrow":"\u2192","\\rho":"\u03C1","\\rhd":"\u22B3","\\rfloor":"\u230B","\\Re":"\u211C","\\rceil":"\u2309","\\Psi":"\u03A8","\\psi":"\u03C8","\\propto":"\u221D","\\prod":"\u220F","\\prime":"\u2032","\\precsim":"\u227E","\\preceq":"\u227C","\\preccurlyeq":"\u227C","\\prec":"\u227A","\\pm":"\xB1","\\Pi":"\u03A0","\\pi":"\u03C0","\\pitchfork":"\u22D4","\\Phi":"\u03A6","\\phi":"\u03D5","\\perp":"\u22A5","\\partial":"\u2202","\\parallel":"\u2225","\\otimes":"\u2297","\\oslash":"\u2298","\\oplus":"\u2295","\\ominus":"\u2296","\\Omega":"\u03A9","\\omega":"\u03C9","\\oint":"\u222E","\\odot":"\u2299","\\nwarrow":"\u2196","\\nu":"\u03BD","\\notin":"\u2209","\\ni":"\u220B","\\nexists":"\u2204","\\neq":"\u2260","\\neg":"\xAC","\\nearrow":"\u2197","\\natural":"\u266E","\\nabla":"\u2207","\\mu":"\u03BC","\\multimap":"\u22B8","\\mp":"\u2213","\\models":"\u22A8","\\mid":"\u2223","\\mho":"\u2127","\\measuredangle":"\u2221","\\mapsto":"\u21A6","\\ltimes":"\u22C9","\\Lsh":"\u21B0","\\lozenge":"\u25CA","\\looparrowright":"\u21AC","\\looparrowleft":"\u21AB","\\Longrightarrow":"\u21D2","\\longrightarrow":"\u2192","\\longmapsto":"\u21D6","\\Longleftrightarrow":"\u21D4","\\longleftrightarrow":"\u2194","\\Longleftarrow":"\u21D0","\\longleftarrow":"\u2190","\\lll":"\u22D8","\\Lleftarrow":"\u21DA","\\ll":"\u226A","\\lhd":"\u22B2","\\lfloor":"\u230A","\\lesssim":"\u2272","\\lessgtr":"\u2276","\\lesseqgtr":"\u22DA","\\lessdot":"\u22D6","\\leqslant":"\u2264","\\leqq":"\u2266","\\leq":"\u2264","\\leftthreetimes":"\u22CB","\\leftrightsquigarrow":"\u21AD","\\leftrightharpoons":"\u21CB","\\leftrightarrows":"\u21C6","\\Leftrightarrow":"\u21D4","\\leftrightarrow":"\u2194","\\leftleftarrows":"\u21C7","\\leftharpoonup":"\u21BC","\\leftharpoondown":"\u21BD","\\leftarrowtail":"\u21A2","\\Leftarrow":"\u21D0","\\leftarrow":"\u2190","\\leadsto":"\u219D","\\le":"\u2264","\\lceil":"\u2308","\\Lambda":"\u039B","\\lambda":"\u03BB","\\kappa":"\u03BA","\\Join":"\u22C8","\\iota":"\u03B9","\\intercal":"\u22BA","\\int":"\u222B","\\infty":"\u221E","\\in":"\u2208","\\implies":"\u21D2","\\Im":"\u2111","\\hslash":"\u210F","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\heartsuit":"\u2661","\\hbar":"\u210F","\\gtrsim":"\u2273","\\gtrless":"\u2277","\\gtreqless":"\u22DB","\\gtrdot":"\u22D7","\\gimel":"\u05D2","\\ggg":"\u22D9","\\gg":"\u226B","\\geqq":"\u2267","\\geq":"\u2265","\\ge":"\u2265","\\Gamma":"\u0393","\\gamma":"\u03B3","\\frown":"\u2322","\\forall":"\u2200","\\flat":"\u266D","\\Finv":"\u2132","\\fallingdotseq":"\u2252","\\exists":"\u2203","\\eth":"\xF0","\\eta":"\u03B7","\\equiv":"\u2261","\\eqcirc":"\u2256","\\epsilon":"\u220A","\\emptyset":"\u2205","\\ell":"\u2113","\\downharpoonright":"\u21C2","\\downharpoonleft":"\u21C3","\\downdownarrows":"\u21CA","\\Downarrow":"\u21D3","\\downarrow":"\u2193","\\dots":"\u2026","\\dotplus":"\u2214","\\doteqdot":"\u2251","\\doteq":"\u2250","\\divideontimes":"\u22C7","\\div":"\xF7","\\digamma":"\u03DC","\\diamondsuit":"\u2662","\\Diamond":"\u25C7","\\diamond":"\u22C4","\\Delta":"\u0394","\\delta":"\u03B4","\\ddots":"\u22F1","\\ddagger":"\u2021","\\dashv":"\u22A3","\\dashrightarrow":"\u21E2","\\dashleftarrow":"\u21E0","\\daleth":"\u05D3","\\dagger":"\u2020","\\curvearrowright":"\u21B7","\\curvearrowleft":"\u21B6","\\curlywedge":"\u22CF","\\curlyvee":"\u22CE","\\curlyeqsucc":"\u22DF","\\curlyeqprec":"\u22DE","\\Cup":"\u22D3","\\cup":"\u222A","\\coprod":"\u2210","\\cong":"\u2245","\\complement":"\u2201","\\clubsuit":"\u2663","\\circledS":"\u24C8","\\circleddash":"\u229D","\\circledcirc":"\u229A","\\circledast":"\u229B","\\circlearrowright":"\u21BB","\\circlearrowleft":"\u21BA","\\circeq":"\u2257","\\circ":"\u2218","\\chi":"\u03C7","\\centerdot":"\u22C5","\\cdots":"\u22EF","\\cdot":"\u22C5","\\Cap":"\u22D2","\\cap":"\u2229","\\Bumpeq":"\u224E","\\bumpeq":"\u224F","\\bullet":"\u2219","\\boxtimes":"\u22A0","\\boxplus":"\u229E","\\boxminus":"\u229F","\\boxdot":"\u22A1","\\Box":"\u25A1","\\bowtie":"\u22C8","\\bot":"\u22A5","\\blacktriangleright":"\u25B7","\\blacktriangleleft":"\u25C0","\\blacktriangledown":"\u25BC","\\blacktriangle":"\u25B2","\\blacksquare":"\u25A0","\\blacklozenge":"\u25C6","\\bigwedge":"\u22C0","\\bigvee":"\u22C1","\\biguplus":"\u228E","\\bigtriangleup":"\u25B3","\\bigtriangledown":"\u25BD","\\bigstar":"\u2605","\\bigsqcup":"\u2294","\\bigotimes":"\u2297","\\bigoplus":"\u2295","\\bigodot":"\u2299","\\bigcup":"\u22C3","\\bigcirc":"\u25CB","\\bigcap":"\u22C2","\\between":"\u226C","\\beth":"\u05D1","\\beta":"\u03B2","\\because":"\u2235","\\barwedge":"\u22BC","\\backsim":"\u223D","\\backprime":"\u2035","\\backepsilon":"\u220D","\\asymp":"\u224D","\\ast":"\u2217","\\approxeq":"\u224A","\\approx":"\u2248","\\angle":"\u2220","\\alpha":"\u03B1","\\aleph":"\u05D0"}});var gC=J((y2,Xx)=>{Xx.exports={A:"\u{1D538}",B:"\u{1D539}",C:"\u2102",D:"\u{1D53B}",E:"\u{1D53C}",F:"\u{1D53D}",G:"\u{1D53E}",H:"\u210D",I:"\u{1D540}",J:"\u{1D541}",K:"\u{1D542}",L:"\u{1D543}",M:"\u{1D544}",N:"\u2115",O:"\u{1D546}",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\u{1D54A}",T:"\u{1D54B}",U:"\u{1D54C}",V:"\u{1D54D}",W:"\u{1D54E}",X:"\u{1D54F}",Y:"\u{1D550}",Z:"\u2124",a:"\u{1D552}",b:"\u{1D553}",c:"\u{1D554}",d:"\u{1D555}",e:"\u{1D556}",f:"\u{1D557}",g:"\u{1D558}",h:"\u{1D559}",i:"\u{1D55A}",j:"\u{1D55B}",k:"\u{1D55C}",l:"\u{1D55D}",m:"\u{1D55E}",n:"\u{1D55F}",o:"\u{1D560}",p:"\u{1D561}",q:"\u{1D562}",r:"\u{1D563}",s:"\u{1D564}",t:"\u{1D565}",u:"\u{1D566}",v:"\u{1D567}",w:"\u{1D568}",x:"\u{1D569}",y:"\u{1D56A}",z:"\u{1D56B}","0":"\u{1D7D8}","1":"\u{1D7D9}","2":"\u{1D7DA}","3":"\u{1D7DB}","4":"\u{1D7DC}","5":"\u{1D7DD}","6":"\u{1D7DE}","7":"\u{1D7DF}","8":"\u{1D7E0}","9":"\u{1D7E1}"}});var yC=J((_2,Qx)=>{Qx.exports={A:"\u{1D400}",B:"\u{1D401}",C:"\u{1D402}",D:"\u{1D403}",E:"\u{1D404}",F:"\u{1D405}",G:"\u{1D406}",H:"\u{1D407}",I:"\u{1D408}",J:"\u{1D409}",K:"\u{1D40A}",L:"\u{1D40B}",M:"\u{1D40C}",N:"\u{1D40D}",O:"\u{1D40E}",P:"\u{1D40F}",Q:"\u{1D410}",R:"\u{1D411}",S:"\u{1D412}",T:"\u{1D413}",U:"\u{1D414}",V:"\u{1D415}",W:"\u{1D416}",X:"\u{1D417}",Y:"\u{1D418}",Z:"\u{1D419}",a:"\u{1D41A}",b:"\u{1D41B}",c:"\u{1D41C}",d:"\u{1D41D}",e:"\u{1D41E}",f:"\u{1D41F}",g:"\u{1D420}",h:"\u{1D421}",i:"\u{1D422}",j:"\u{1D423}",k:"\u{1D424}",l:"\u{1D425}",m:"\u{1D426}",n:"\u{1D427}",o:"\u{1D428}",p:"\u{1D429}",q:"\u{1D42A}",r:"\u{1D42B}",s:"\u{1D42C}",t:"\u{1D42D}",u:"\u{1D42E}",v:"\u{1D42F}",w:"\u{1D430}",x:"\u{1D431}",y:"\u{1D432}",z:"\u{1D433}",\u0391:"\u{1D6A8}",\u0392:"\u{1D6A9}",\u0393:"\u{1D6AA}",\u0394:"\u{1D6AB}",\u0395:"\u{1D6AC}",\u0396:"\u{1D6AD}",\u0397:"\u{1D6AE}",\u0398:"\u{1D6AF}",\u0399:"\u{1D6B0}",\u039A:"\u{1D6B1}",\u039B:"\u{1D6B2}",\u039C:"\u{1D6B3}",\u039D:"\u{1D6B4}",\u039E:"\u{1D6B5}",\u039F:"\u{1D6B6}",\u03A0:"\u{1D6B7}",\u03A1:"\u{1D6B8}","\u03F4":"\u{1D6B9}",\u03A3:"\u{1D6BA}",\u03A4:"\u{1D6BB}",\u03A5:"\u{1D6BC}",\u03A6:"\u{1D6BD}",\u03A7:"\u{1D6BE}",\u03A8:"\u{1D6BF}",\u03A9:"\u{1D6C0}","\u2207":"\u{1D6C1}",\u03B1:"\u{1D6C2}",\u03B2:"\u{1D6C3}",\u03B3:"\u{1D6C4}",\u03B4:"\u{1D6C5}",\u03B5:"\u{1D6C6}",\u03B6:"\u{1D6C7}",\u03B7:"\u{1D6C8}",\u03B8:"\u{1D6C9}",\u03B9:"\u{1D6CA}",\u03BA:"\u{1D6CB}",\u03BB:"\u{1D6CC}",\u03BC:"\u{1D6CD}",\u03BD:"\u{1D6CE}",\u03BE:"\u{1D6CF}",\u03BF:"\u{1D6D0}",\u03C0:"\u{1D6D1}",\u03C1:"\u{1D6D2}",\u03C2:"\u{1D6D3}",\u03C3:"\u{1D6D4}",\u03C4:"\u{1D6D5}",\u03C5:"\u{1D6D6}",\u03C6:"\u{1D6D7}",\u03C7:"\u{1D6D8}",\u03C8:"\u{1D6D9}",\u03C9:"\u{1D6DA}","\u2202":"\u{1D6DB}","\u03F5":"\u{1D6DC}",\u03D1:"\u{1D6DD}",\u03F0:"\u{1D6DE}",\u03D5:"\u{1D6DF}",\u03F1:"\u{1D6E0}",\u03D6:"\u{1D6E1}","0":"\u{1D7CE}","1":"\u{1D7CF}","2":"\u{1D7D0}","3":"\u{1D7D1}","4":"\u{1D7D2}","5":"\u{1D7D3}","6":"\u{1D7D4}","7":"\u{1D7D5}","8":"\u{1D7D6}","9":"\u{1D7D7}"}});var _C=J((b2,Zx)=>{Zx.exports={A:"\u{1D4D0}",B:"\u{1D4D1}",C:"\u{1D4D2}",D:"\u{1D4D3}",E:"\u{1D4D4}",F:"\u{1D4D5}",G:"\u{1D4D6}",H:"\u{1D4D7}",I:"\u{1D4D8}",J:"\u{1D4D9}",K:"\u{1D4DA}",L:"\u{1D4DB}",M:"\u{1D4DC}",N:"\u{1D4DD}",O:"\u{1D4DE}",P:"\u{1D4DF}",Q:"\u{1D4E0}",R:"\u{1D4E1}",S:"\u{1D4E2}",T:"\u{1D4E3}",U:"\u{1D4E4}",V:"\u{1D4E5}",W:"\u{1D4E6}",X:"\u{1D4E7}",Y:"\u{1D4E8}",Z:"\u{1D4E9}",a:"\u{1D4EA}",b:"\u{1D4EB}",c:"\u{1D4EC}",d:"\u{1D4ED}",e:"\u{1D4EE}",f:"\u{1D4EF}",g:"\u{1D4F0}",h:"\u{1D4F1}",i:"\u{1D4F2}",j:"\u{1D4F3}",k:"\u{1D4F4}",l:"\u{1D4F5}",m:"\u{1D4F6}",n:"\u{1D4F7}",o:"\u{1D4F8}",p:"\u{1D4F9}",q:"\u{1D4FA}",r:"\u{1D4FB}",s:"\u{1D4FC}",t:"\u{1D4FD}",u:"\u{1D4FE}",v:"\u{1D4FF}",w:"\u{1D500}",x:"\u{1D501}",y:"\u{1D502}",z:"\u{1D503}"}});var bC=J((C2,eD)=>{eD.exports={A:"\u{1D504}",B:"\u{1D505}",C:"\u212D",D:"\u{1D507}",E:"\u{1D508}",F:"\u{1D509}",G:"\u{1D50A}",H:"\u210C",I:"\u2111",J:"\u{1D50D}",K:"\u{1D50E}",L:"\u{1D50F}",M:"\u{1D510}",N:"\u{1D511}",O:"\u{1D512}",P:"\u{1D513}",Q:"\u{1D514}",R:"\u211C",S:"\u{1D516}",T:"\u{1D517}",U:"\u{1D518}",V:"\u{1D519}",W:"\u{1D51A}",X:"\u{1D51B}",Y:"\u{1D51C}",Z:"\u2128",a:"\u{1D51E}",b:"\u{1D51F}",c:"\u{1D520}",d:"\u{1D521}",e:"\u{1D522}",f:"\u{1D523}",g:"\u{1D524}",h:"\u{1D525}",i:"\u{1D526}",j:"\u{1D527}",k:"\u{1D528}",l:"\u{1D529}",m:"\u{1D52A}",n:"\u{1D52B}",o:"\u{1D52C}",p:"\u{1D52D}",q:"\u{1D52E}",r:"\u{1D52F}",s:"\u{1D530}",t:"\u{1D531}",u:"\u{1D532}",v:"\u{1D533}",w:"\u{1D534}",x:"\u{1D535}",y:"\u{1D536}",z:"\u{1D537}"}});var CC=J((w2,tD)=>{tD.exports={A:"\u{1D434}",B:"\u{1D435}",C:"\u{1D436}",D:"\u{1D437}",E:"\u{1D438}",F:"\u{1D439}",G:"\u{1D43A}",H:"\u{1D43B}",I:"\u{1D43C}",J:"\u{1D43D}",K:"\u{1D43E}",L:"\u{1D43F}",M:"\u{1D440}",N:"\u{1D441}",O:"\u{1D442}",P:"\u{1D443}",Q:"\u{1D444}",R:"\u{1D445}",S:"\u{1D446}",T:"\u{1D447}",U:"\u{1D448}",V:"\u{1D449}",W:"\u{1D44A}",X:"\u{1D44B}",Y:"\u{1D44C}",Z:"\u{1D44D}",a:"\u{1D44E}",b:"\u{1D44F}",c:"\u{1D450}",d:"\u{1D451}",e:"\u{1D452}",f:"\u{1D453}",g:"\u{1D454}",h:"\u210E",i:"\u{1D456}",j:"\u{1D457}",k:"\u{1D458}",l:"\u{1D459}",m:"\u{1D45A}",n:"\u{1D45B}",o:"\u{1D45C}",p:"\u{1D45D}",q:"\u{1D45E}",r:"\u{1D45F}",s:"\u{1D460}",t:"\u{1D461}",u:"\u{1D462}",v:"\u{1D463}",w:"\u{1D464}",x:"\u{1D465}",y:"\u{1D466}",z:"\u{1D467}",\u0391:"\u{1D6E2}",\u0392:"\u{1D6E3}",\u0393:"\u{1D6E4}",\u0394:"\u{1D6E5}",\u0395:"\u{1D6E6}",\u0396:"\u{1D6E7}",\u0397:"\u{1D6E8}",\u0398:"\u{1D6E9}",\u0399:"\u{1D6EA}",\u039A:"\u{1D6EB}",\u039B:"\u{1D6EC}",\u039C:"\u{1D6ED}",\u039D:"\u{1D6EE}",\u039E:"\u{1D6EF}",\u039F:"\u{1D6F0}",\u03A0:"\u{1D6F1}",\u03A1:"\u{1D6F2}","\u03F4":"\u{1D6F3}",\u03A3:"\u{1D6F4}",\u03A4:"\u{1D6F5}",\u03A5:"\u{1D6F6}",\u03A6:"\u{1D6F7}",\u03A7:"\u{1D6F8}",\u03A8:"\u{1D6F9}",\u03A9:"\u{1D6FA}","\u2207":"\u{1D6FB}",\u03B1:"\u{1D6FC}",\u03B2:"\u{1D6FD}",\u03B3:"\u{1D6FE}",\u03B4:"\u{1D6FF}",\u03B5:"\u{1D700}",\u03B6:"\u{1D701}",\u03B7:"\u{1D702}",\u03B8:"\u{1D703}",\u03B9:"\u{1D704}",\u03BA:"\u{1D705}",\u03BB:"\u{1D706}",\u03BC:"\u{1D707}",\u03BD:"\u{1D708}",\u03BE:"\u{1D709}",\u03BF:"\u{1D70A}",\u03C0:"\u{1D70B}",\u03C1:"\u{1D70C}",\u03C2:"\u{1D70D}",\u03C3:"\u{1D70E}",\u03C4:"\u{1D70F}",\u03C5:"\u{1D710}",\u03C6:"\u{1D711}",\u03C7:"\u{1D712}",\u03C8:"\u{1D713}",\u03C9:"\u{1D714}","\u2202":"\u{1D715}","\u03F5":"\u{1D716}",\u03D1:"\u{1D717}",\u03F0:"\u{1D718}",\u03D5:"\u{1D719}",\u03F1:"\u{1D71A}",\u03D6:"\u{1D71B}"}});var wC=J((k2,nD)=>{nD.exports={A:"\u{1D670}",B:"\u{1D671}",C:"\u{1D672}",D:"\u{1D673}",E:"\u{1D674}",F:"\u{1D675}",G:"\u{1D676}",H:"\u{1D677}",I:"\u{1D678}",J:"\u{1D679}",K:"\u{1D67A}",L:"\u{1D67B}",M:"\u{1D67C}",N:"\u{1D67D}",O:"\u{1D67E}",P:"\u{1D67F}",Q:"\u{1D680}",R:"\u{1D681}",S:"\u{1D682}",T:"\u{1D683}",U:"\u{1D684}",V:"\u{1D685}",W:"\u{1D686}",X:"\u{1D687}",Y:"\u{1D688}",Z:"\u{1D689}",a:"\u{1D68A}",b:"\u{1D68B}",c:"\u{1D68C}",d:"\u{1D68D}",e:"\u{1D68E}",f:"\u{1D68F}",g:"\u{1D690}",h:"\u{1D691}",i:"\u{1D692}",j:"\u{1D693}",k:"\u{1D694}",l:"\u{1D695}",m:"\u{1D696}",n:"\u{1D697}",o:"\u{1D698}",p:"\u{1D699}",q:"\u{1D69A}",r:"\u{1D69B}",s:"\u{1D69C}",t:"\u{1D69D}",u:"\u{1D69E}",v:"\u{1D69F}",w:"\u{1D6A0}",x:"\u{1D6A1}",y:"\u{1D6A2}",z:"\u{1D6A3}","0":"\u{1D7F6}","1":"\u{1D7F7}","2":"\u{1D7F8}","3":"\u{1D7F9}","4":"\u{1D7FA}","5":"\u{1D7FB}","6":"\u{1D7FC}","7":"\u{1D7FD}","8":"\u{1D7FE}","9":"\u{1D7FF}"}});var vC=J((S2,EC)=>{var rD=pC(),oD=hC(),kC=mC(),sD=gC(),iD=yC(),aD=_C(),cD=bC(),uD=CC(),lD=wC(),SC=function(t,e){return t[e]!==void 0?t[e]:e};function Sr(t,e,n){t=t.replace(e,"^");var r="",o="normal",s,i;for(s=0;s<t.length;s++){if(i=t[s],o==="normal"&&i==="^"){o="modified";continue}else if(o==="modified"&&i==="{"){o="long";continue}else if(o==="modified"){r+=SC(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=SC(n,i)}return r}EC.exports=function(t){return Object.keys(kC).forEach(function(e){var n=kC[e];t=t.replace(e,n)}),t=Sr(t,"^",oD),t=Sr(t,"_",rD),t=Sr(t,"\\bb",sD),t=Sr(t,"\\bf",iD),t=Sr(t,"\\it",uD),t=Sr(t,"\\cal",aD),t=Sr(t,"\\frak",cD),t=Sr(t,"\\mono",lD),t}});var wp=J((Z2,JC)=>{"use strict";var Ic=Object.prototype.hasOwnProperty,GC=Object.prototype.toString,LC=Object.defineProperty,qC=Object.getOwnPropertyDescriptor,$C=function(e){return typeof Array.isArray=="function"?Array.isArray(e):GC.call(e)==="[object Array]"},zC=function(e){if(!e||GC.call(e)!=="[object Object]")return!1;var n=Ic.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Ic.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Ic.call(e,o)},HC=function(e,n){LC&&n.name==="__proto__"?LC(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},WC=function(e,n){if(n==="__proto__")if(Ic.call(e,n)){if(qC)return qC(e,n).value}else return;return e[n]};JC.exports=function t(){var e,n,r,o,s,i,c=arguments[0],u=1,f=arguments.length,d=!1;for(typeof c=="boolean"&&(d=c,c=arguments[1]||{},u=2),(c==null||typeof c!="object"&&typeof c!="function")&&(c={});u<f;++u)if(e=arguments[u],e!=null)for(n in e)r=WC(c,n),o=WC(e,n),c!==o&&(d&&o&&(zC(o)||(s=$C(o)))?(s?(s=!1,i=r&&$C(r)?r:[]):i=r&&zC(r)?r:{},HC(c,{name:n,newValue:t(d,i,o)})):typeof o<"u"&&HC(c,{name:n,newValue:o}));return c}});var VC=J((e$,RD)=>{RD.exports={name:"gaxios",version:"7.3.0",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.6","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var YC=J((t$,KC)=>{"use strict";var xD=VC();KC.exports={pkg:xD}});var Ep=J(Mt=>{"use strict";var QC=Mt&&Mt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Mt,"__esModule",{value:!0});Mt.GaxiosError=Mt.GAXIOS_ERROR_SYMBOL=void 0;Mt.defaultErrorRedactor=ZC;var XC=QC(wp()),DD=QC(YC()),kp=DD.default.pkg;Mt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${kp.name}-gaxios-error`);var Sp=class t extends Error{config;response;code;status;error;[Mt.GAXIOS_ERROR_SYMBOL]=kp.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Mt.GAXIOS_ERROR_SYMBOL in e&&e[Mt.GAXIOS_ERROR_SYMBOL]===kp.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,XC.default)(!0,{},n),this.response&&(this.response.config=(0,XC.default)(!0,{},this.response.config)),this.response){try{this.response.data=OD(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let c of e.data.error.errors)typeof c=="object"&&"message"in c&&typeof c.message=="string"&&i.push(c.message);return Object.assign({message:i.join(`
44
+ `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};Mt.GaxiosError=Sp;function OD(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function ZC(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((i,c)=>{(/^authentication$/i.test(c)||/^authorization$/i.test(c)||/secret/i.test(c))&&s.set(c,e)})}function r(s,i){if(typeof s=="object"&&s!==null&&typeof s[i]=="string"){let c=s[i];(/grant_type=/i.test(c)||/assertion=/i.test(c)||/secret/i.test(c))&&(s[i]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((i,c)=>{(["grant_type","assertion"].includes(c)||/secret/.test(c))&&s.set(c,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(ZC({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var tw=J(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.getRetryConfig=PD;async function PD(t){let e=ew(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||ID)(t))return{shouldRetry:!1,config:t.config};let o=FD(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function ID(t){let e=ew(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function ew(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function FD(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var Tp=J(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.GaxiosInterceptorManager=void 0;var Ap=class extends Set{};Fc.GaxiosInterceptorManager=Ap});var rw=J((s$,nw)=>{var Go=1e3,Jo=Go*60,Vo=Jo*60,ro=Vo*24,ND=ro*7,MD=ro*365.25;nw.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return BD(t);if(n==="number"&&isFinite(t))return e.long?jD(t):UD(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function BD(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*MD;case"weeks":case"week":case"w":return n*ND;case"days":case"day":case"d":return n*ro;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Vo;case"minutes":case"minute":case"mins":case"min":case"m":return n*Jo;case"seconds":case"second":case"secs":case"sec":case"s":return n*Go;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function UD(t){var e=Math.abs(t);return e>=ro?Math.round(t/ro)+"d":e>=Vo?Math.round(t/Vo)+"h":e>=Jo?Math.round(t/Jo)+"m":e>=Go?Math.round(t/Go)+"s":t+"ms"}function jD(t){var e=Math.abs(t);return e>=ro?Nc(t,e,ro,"day"):e>=Vo?Nc(t,e,Vo,"hour"):e>=Jo?Nc(t,e,Jo,"minute"):e>=Go?Nc(t,e,Go,"second"):t+" ms"}function Nc(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var Rp=J((i$,ow)=>{function LD(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=c,n.humanize=rw(),n.destroy=f,Object.keys(t).forEach(d=>{n[d]=t[d]}),n.names=[],n.skips=[],n.formatters={};function e(d){let p=0;for(let h=0;h<d.length;h++)p=(p<<5)-p+d.charCodeAt(h),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(d){let p,h=null,_,b;function y(...w){if(!y.enabled)return;let C=y,v=Number(new Date),A=v-(p||v);C.diff=A,C.prev=p,C.curr=v,p=v,w[0]=n.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let T=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";T++;let $=n.formatters[q];if(typeof $=="function"){let H=w[T];O=$.call(C,H),w.splice(T,1),T--}return O}),n.formatArgs.call(C,w),(C.log||n.log).apply(C,w)}return y.namespace=d,y.useColors=n.useColors(),y.color=n.selectColor(d),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(_!==n.namespaces&&(_=n.namespaces,b=n.enabled(d)),b),set:w=>{h=w}}),typeof n.init=="function"&&n.init(y),y}function r(d,p){let h=n(this.namespace+(typeof p>"u"?":":p)+d);return h.log=this.log,h}function o(d){n.save(d),n.namespaces=d,n.names=[],n.skips=[];let p=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of p)h[0]==="-"?n.skips.push(h.slice(1)):n.names.push(h)}function s(d,p){let h=0,_=0,b=-1,y=0;for(;h<d.length;)if(_<p.length&&(p[_]===d[h]||p[_]==="*"))p[_]==="*"?(b=_,y=h,_++):(h++,_++);else if(b!==-1)_=b+1,y++,h=y;else return!1;for(;_<p.length&&p[_]==="*";)_++;return _===p.length}function i(){let d=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),d}function c(d){for(let p of n.skips)if(s(d,p))return!1;for(let p of n.names)if(s(d,p))return!0;return!1}function u(d){return d instanceof Error?d.stack||d.message:d}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}ow.exports=LD});var sw=J((wt,Mc)=>{wt.formatArgs=$D;wt.save=zD;wt.load=HD;wt.useColors=qD;wt.storage=WD();wt.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();wt.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function qD(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function $D(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Mc.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}wt.log=console.debug||console.log||(()=>{});function zD(t){try{t?wt.storage.setItem("debug",t):wt.storage.removeItem("debug")}catch{}}function HD(){let t;try{t=wt.storage.getItem("debug")||wt.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function WD(){try{return localStorage}catch{}}Mc.exports=Rp()(wt);var{formatters:GD}=Mc.exports;GD.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var aw=J((a$,iw)=>{"use strict";iw.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var lw=J((c$,uw)=>{"use strict";var JD=require("os"),cw=require("tty"),Bt=aw(),{env:ot}=process,Bc;Bt("no-color")||Bt("no-colors")||Bt("color=false")||Bt("color=never")?Bc=0:(Bt("color")||Bt("colors")||Bt("color=true")||Bt("color=always"))&&(Bc=1);function VD(){if("FORCE_COLOR"in ot)return ot.FORCE_COLOR==="true"?1:ot.FORCE_COLOR==="false"?0:ot.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ot.FORCE_COLOR,10),3)}function KD(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function YD(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=VD();r!==void 0&&(Bc=r);let o=n?Bc:r;if(o===0)return 0;if(n){if(Bt("color=16m")||Bt("color=full")||Bt("color=truecolor"))return 3;if(Bt("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(ot.TERM==="dumb")return s;if(process.platform==="win32"){let i=JD.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ot)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in ot)||ot.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in ot)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ot.TEAMCITY_VERSION)?1:0;if(ot.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ot){let i=Number.parseInt((ot.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ot.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ot.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ot.TERM)||"COLORTERM"in ot?1:s}function xp(t,e={}){let n=YD(t,{streamIsTTY:t&&t.isTTY,...e});return KD(n)}uw.exports={supportsColor:xp,stdout:xp({isTTY:cw.isatty(1)}),stderr:xp({isTTY:cw.isatty(2)})}});var fw=J((st,jc)=>{var XD=require("tty"),Uc=require("util");st.init=oO;st.log=tO;st.formatArgs=ZD;st.save=nO;st.load=rO;st.useColors=QD;st.destroy=Uc.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");st.colors=[6,2,3,4,5,1];try{let t=lw();t&&(t.stderr||t).level>=2&&(st.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}st.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function QD(){return"colors"in st.inspectOpts?!!st.inspectOpts.colors:XD.isatty(process.stderr.fd)}function ZD(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
16
45
  `).join(`
17
- `+s),t.push(o+"m+"+Xa.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=Ev()+e+" "+t[0]}function Ev(){return rt.inspectOpts.hideDate?"":new Date().toISOString()+" "}function vv(...t){return process.stderr.write(Ya.formatWithOptions(rt.inspectOpts,...t)+`
18
- `)}function Tv(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function Rv(){return process.env.DEBUG}function Dv(t){t.inspectOpts={};let e=Object.keys(rt.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=rt.inspectOpts[e[n]]}Xa.exports=hf()(rt);var{formatters:g0}=Xa.exports;g0.o=function(t){return this.inspectOpts.colors=this.useColors,Ya.inspect(t,this.inspectOpts).split(`
19
- `).map(e=>e.trim()).join(" ")};g0.O=function(t){return this.inspectOpts.colors=this.useColors,Ya.inspect(t,this.inspectOpts)}});var mf=V(($B,gf)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?gf.exports=u0():gf.exports=m0()});var b0=V(Ct=>{"use strict";var xv=Ct&&Ct.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Ov=Ct&&Ct.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),y0=Ct&&Ct.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&xv(e,t,n);return Ov(e,t),e};Object.defineProperty(Ct,"__esModule",{value:!0});Ct.req=Ct.json=Ct.toBuffer=void 0;var Fv=y0(require("http")),Pv=y0(require("https"));async function _0(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}Ct.toBuffer=_0;async function Iv(t){let n=(await _0(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}Ct.json=Iv;function Nv(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?Pv:Fv).request(t,e),o=new Promise((s,a)=>{r.once("response",s).once("error",a).end()});return r.then=o.then.bind(o),r}Ct.req=Nv});var S0=V(Et=>{"use strict";var C0=Et&&Et.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Bv=Et&&Et.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),k0=Et&&Et.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&C0(e,t,n);return Bv(e,t),e},jv=Et&&Et.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&C0(e,t,n)};Object.defineProperty(Et,"__esModule",{value:!0});Et.Agent=void 0;var Mv=k0(require("net")),w0=k0(require("http")),Uv=require("https");jv(b0(),Et);var fn=Symbol("AgentBaseInternalState"),yf=class extends w0.Agent{constructor(e){super(e),this[fn]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
20
- `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new Mv.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?Uv.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),a=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,a),c instanceof w0.Agent)try{return c.addRequest(e,o)}catch(l){return r(l)}this[fn].currentSocket=c,super.createSocket(e,n,r)},c=>{this.decrementSockets(s,a),r(c)})}createConnection(){let e=this[fn].currentSocket;if(this[fn].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[fn].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[fn]&&(this[fn].defaultPort=e)}get protocol(){return this[fn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[fn]&&(this[fn].protocol=e)}};Et.Agent=yf});var A0=V(Po=>{"use strict";var Lv=Po&&Po.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Po,"__esModule",{value:!0});Po.parseProxyResponse=void 0;var qv=Lv(mf()),Qa=(0,qv.default)("https-proxy-agent:parse-proxy-response");function $v(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function a(){t.removeListener("end",c),t.removeListener("error",l),t.removeListener("readable",s)}function c(){a(),Qa("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function l(d){a(),Qa("onerror %o",d),n(d)}function f(d){o.push(d),r+=d.length;let h=Buffer.concat(o,r),m=h.indexOf(`\r
46
+ `+s),t.push(o+"m+"+jc.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=eO()+e+" "+t[0]}function eO(){return st.inspectOpts.hideDate?"":new Date().toISOString()+" "}function tO(...t){return process.stderr.write(Uc.formatWithOptions(st.inspectOpts,...t)+`
47
+ `)}function nO(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function rO(){return process.env.DEBUG}function oO(t){t.inspectOpts={};let e=Object.keys(st.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=st.inspectOpts[e[n]]}jc.exports=Rp()(st);var{formatters:dw}=jc.exports;dw.o=function(t){return this.inspectOpts.colors=this.useColors,Uc.inspect(t,this.inspectOpts).split(`
48
+ `).map(e=>e.trim()).join(" ")};dw.O=function(t){return this.inspectOpts.colors=this.useColors,Uc.inspect(t,this.inspectOpts)}});var Op=J((u$,Dp)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Dp.exports=sw():Dp.exports=fw()});var mw=J(kt=>{"use strict";var sO=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),iO=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pw=kt&&kt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&sO(e,t,n);return iO(e,t),e};Object.defineProperty(kt,"__esModule",{value:!0});kt.req=kt.json=kt.toBuffer=void 0;var aO=pw(require("http")),cO=pw(require("https"));async function hw(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}kt.toBuffer=hw;async function uO(t){let n=(await hw(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}kt.json=uO;function lO(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?cO:aO).request(t,e),o=new Promise((s,i)=>{r.once("response",s).once("error",i).end()});return r.then=o.then.bind(o),r}kt.req=lO});var bw=J(Tt=>{"use strict";var yw=Tt&&Tt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dO=Tt&&Tt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),_w=Tt&&Tt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&yw(e,t,n);return dO(e,t),e},fO=Tt&&Tt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yw(e,t,n)};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.Agent=void 0;var pO=_w(require("net")),gw=_w(require("http")),hO=require("https");fO(mw(),Tt);var gn=Symbol("AgentBaseInternalState"),Pp=class extends gw.Agent{constructor(e){super(e),this[gn]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
49
+ `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new pO.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?hO.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),i=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(c=>{if(this.decrementSockets(s,i),c instanceof gw.Agent)try{return c.addRequest(e,o)}catch(u){return r(u)}this[gn].currentSocket=c,super.createSocket(e,n,r)},c=>{this.decrementSockets(s,i),r(c)})}createConnection(){let e=this[gn].currentSocket;if(this[gn].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[gn].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[gn]&&(this[gn].defaultPort=e)}get protocol(){return this[gn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[gn]&&(this[gn].protocol=e)}};Tt.Agent=Pp});var Cw=J(Ko=>{"use strict";var mO=Ko&&Ko.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ko,"__esModule",{value:!0});Ko.parseProxyResponse=void 0;var gO=mO(Op()),Lc=(0,gO.default)("https-proxy-agent:parse-proxy-response");function yO(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let d=t.read();d?f(d):t.once("readable",s)}function i(){t.removeListener("end",c),t.removeListener("error",u),t.removeListener("readable",s)}function c(){i(),Lc("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(d){i(),Lc("onerror %o",d),n(d)}function f(d){o.push(d),r+=d.length;let p=Buffer.concat(o,r),h=p.indexOf(`\r
21
50
  \r
22
- `);if(m===-1){Qa("have not received end of HTTP headers yet..."),s();return}let S=h.slice(0,m).toString("ascii").split(`\r
23
- `),y=S.shift();if(!y)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let w=y.split(" "),b=+w[1],_=w.slice(2).join(" "),D={};for(let k of S){if(!k)continue;let v=k.indexOf(":");if(v===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${k}"`));let x=k.slice(0,v).toLowerCase(),R=k.slice(v+1).trimStart(),j=D[x];typeof j=="string"?D[x]=[j,R]:Array.isArray(j)?j.push(R):D[x]=R}Qa("got proxy server response: %o %o",y,D),a(),e({connect:{statusCode:b,statusText:_,headers:D},buffered:h})}t.on("error",l),t.on("end",c),s()})}Po.parseProxyResponse=$v});var x0=V(Lt=>{"use strict";var zv=Lt&&Lt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Hv=Lt&&Lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),R0=Lt&&Lt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&zv(e,t,n);return Hv(e,t),e},D0=Lt&&Lt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Lt,"__esModule",{value:!0});Lt.HttpsProxyAgent=void 0;var Za=R0(require("net")),E0=R0(require("tls")),Wv=D0(require("assert")),Gv=D0(mf()),Jv=S0(),Vv=require("url"),Kv=A0(),Xs=(0,Gv.default)("https-proxy-agent"),v0=t=>t.servername===void 0&&t.host&&!Za.isIP(t.host)?{...t,servername:t.host}:t,ec=class extends Jv.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new Vv.URL(e):e,this.proxyHeaders=n?.headers??{},Xs("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?T0(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(Xs("Creating `tls.Socket`: %o",this.connectOpts),o=E0.connect(v0(this.connectOpts))):(Xs("Creating `net.Socket`: %o",this.connectOpts),o=Za.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},a=Za.isIPv6(n.host)?`[${n.host}]`:n.host,c=`CONNECT ${a}:${n.port} HTTP/1.1\r
24
- `;if(r.username||r.password){let m=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(m).toString("base64")}`}s.Host=`${a}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let m of Object.keys(s))c+=`${m}: ${s[m]}\r
25
- `;let l=(0,Kv.parseProxyResponse)(o);o.write(`${c}\r
26
- `);let{connect:f,buffered:d}=await l;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",Yv),n.secureEndpoint?(Xs("Upgrading socket connection to TLS"),E0.connect({...T0(v0(n),"host","path","port"),socket:o})):o;o.destroy();let h=new Za.Socket({writable:!1});return h.readable=!0,e.once("socket",m=>{Xs("Replaying proxy buffer for failed request"),(0,Wv.default)(m.listenerCount("data")>0),m.push(d),m.push(null)}),h}};ec.protocols=["http","https"];Lt.HttpsProxyAgent=ec;function Yv(t){t.resume()}function T0(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function bf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Xv,Qv,_f,tc=fr(()=>{Xv=Object.defineProperty,Qv=(t,e)=>Xv(t,"name",{value:e,configurable:!0}),_f=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};Qv(bf,"getDefaultExportFromCjs")});var N0={};Bd(N0,{toFormData:()=>I0});function P0(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function I0(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new sT(n[1]||n[2]),o,s,a,c,l,f,d=[],h=new Jr,m=vt(_=>{a+=b.decode(_,{stream:!0})},"onPartData"),S=vt(_=>{d.push(_)},"appendToFile"),y=vt(()=>{let _=new Io(d,f,{type:l});h.append(c,_)},"appendFileToFormData"),w=vt(()=>{h.append(c,a)},"appendEntryToFormData"),b=new TextDecoder("utf-8");b.decode(),r.onPartBegin=function(){r.onPartData=m,r.onPartEnd=w,o="",s="",a="",c="",l="",f=null,d.length=0},r.onHeaderField=function(_){o+=b.decode(_,{stream:!0})},r.onHeaderValue=function(_){s+=b.decode(_,{stream:!0})},r.onHeaderEnd=function(){if(s+=b.decode(),o=o.toLowerCase(),o==="content-disposition"){let _=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);_&&(c=_[2]||_[3]||""),f=P0(s),f&&(r.onPartData=S,r.onPartEnd=y)}else o==="content-type"&&(l=s);s="",o=""};for await(let _ of t)r.write(_);return r.end(),h}var Zv,vt,hn,Me,O0,yr,nc,rc,eT,Qs,tT,nT,rT,oT,Gr,F0,sT,B0=fr(()=>{oc();tc();Zv=Object.defineProperty,vt=(t,e)=>Zv(t,"name",{value:e,configurable:!0}),hn=0,Me={START_BOUNDARY:hn++,HEADER_FIELD_START:hn++,HEADER_FIELD:hn++,HEADER_VALUE_START:hn++,HEADER_VALUE:hn++,HEADER_VALUE_ALMOST_DONE:hn++,HEADERS_ALMOST_DONE:hn++,PART_DATA_START:hn++,PART_DATA:hn++,END:hn++},O0=1,yr={PART_BOUNDARY:O0,LAST_BOUNDARY:O0*=2},nc=10,rc=13,eT=32,Qs=45,tT=58,nT=97,rT=122,oT=vt(t=>t|32,"lower"),Gr=vt(()=>{},"noop"),F0=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Gr,this.onHeaderField=Gr,this.onHeadersEnd=Gr,this.onHeaderValue=Gr,this.onPartBegin=Gr,this.onPartData=Gr,this.onPartEnd=Gr,this.boundaryChars={},e=`\r
27
- --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Me.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:a,boundaryChars:c,index:l,state:f,flags:d}=this,h=this.boundary.length,m=h-1,S=e.length,y,w,b=vt(v=>{this[v+"Mark"]=n},"mark"),_=vt(v=>{delete this[v+"Mark"]},"clear"),D=vt((v,x,R,j)=>{(x===void 0||x!==R)&&this[v](j&&j.subarray(x,R))},"callback"),k=vt((v,x)=>{let R=v+"Mark";R in this&&(x?(D(v,this[R],n,e),delete this[R]):(D(v,this[R],e.length,e),this[R]=0))},"dataCallback");for(n=0;n<r;n++)switch(y=e[n],f){case Me.START_BOUNDARY:if(l===a.length-2){if(y===Qs)d|=yr.LAST_BOUNDARY;else if(y!==rc)return;l++;break}else if(l-1===a.length-2){if(d&yr.LAST_BOUNDARY&&y===Qs)f=Me.END,d=0;else if(!(d&yr.LAST_BOUNDARY)&&y===nc)l=0,D("onPartBegin"),f=Me.HEADER_FIELD_START;else return;break}y!==a[l+2]&&(l=-2),y===a[l+2]&&l++;break;case Me.HEADER_FIELD_START:f=Me.HEADER_FIELD,b("onHeaderField"),l=0;case Me.HEADER_FIELD:if(y===rc){_("onHeaderField"),f=Me.HEADERS_ALMOST_DONE;break}if(l++,y===Qs)break;if(y===tT){if(l===1)return;k("onHeaderField",!0),f=Me.HEADER_VALUE_START;break}if(w=oT(y),w<nT||w>rT)return;break;case Me.HEADER_VALUE_START:if(y===eT)break;b("onHeaderValue"),f=Me.HEADER_VALUE;case Me.HEADER_VALUE:y===rc&&(k("onHeaderValue",!0),D("onHeaderEnd"),f=Me.HEADER_VALUE_ALMOST_DONE);break;case Me.HEADER_VALUE_ALMOST_DONE:if(y!==nc)return;f=Me.HEADER_FIELD_START;break;case Me.HEADERS_ALMOST_DONE:if(y!==nc)return;D("onHeadersEnd"),f=Me.PART_DATA_START;break;case Me.PART_DATA_START:f=Me.PART_DATA,b("onPartData");case Me.PART_DATA:if(o=l,l===0){for(n+=m;n<S&&!(e[n]in c);)n+=h;n-=m,y=e[n]}if(l<a.length)a[l]===y?(l===0&&k("onPartData",!0),l++):l=0;else if(l===a.length)l++,y===rc?d|=yr.PART_BOUNDARY:y===Qs?d|=yr.LAST_BOUNDARY:l=0;else if(l-1===a.length)if(d&yr.PART_BOUNDARY){if(l=0,y===nc){d&=~yr.PART_BOUNDARY,D("onPartEnd"),D("onPartBegin"),f=Me.HEADER_FIELD_START;break}}else d&yr.LAST_BOUNDARY&&y===Qs?(D("onPartEnd"),f=Me.END,d=0):l=0;if(l>0)s[l-1]=y;else if(o>0){let v=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);D("onPartData",0,o,v),o=0,b("onPartData"),n--}break;case Me.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}k("onHeaderField"),k("onHeaderValue"),k("onPartData"),this.index=l,this.state=f,this.flags=d}end(){if(this.state===Me.HEADER_FIELD_START&&this.index===0||this.state===Me.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Me.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};vt(F0,"MultipartParser");sT=F0;vt(P0,"_fileName");vt(I0,"toFormData")});function Z0(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",a=s;for(let d=1;d<n.length;d++)n[d]==="base64"?o=!0:n[d]&&(a+=`;${n[d]}`,n[d].indexOf("charset=")===0&&(r=n[d].substring(8)));!n[0]&&!r.length&&(a+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",l=unescape(t.substring(e+1)),f=Buffer.from(l,c);return f.type=s,f.typeFull=a,f.charset=r,f}function eb(){return M0||(M0=1,(function(t,e){(function(n,r){r(e)})(aT,function(n){function r(){}p(r,"noop");function o(i){return typeof i=="object"&&i!==null||typeof i=="function"}p(o,"typeIsObject");let s=r;function a(i,u){try{Object.defineProperty(i,"name",{value:u,configurable:!0})}catch{}}p(a,"setFunctionName");let c=Promise,l=Promise.prototype.then,f=Promise.reject.bind(c);function d(i){return new c(i)}p(d,"newPromise");function h(i){return d(u=>u(i))}p(h,"promiseResolvedWith");function m(i){return f(i)}p(m,"promiseRejectedWith");function S(i,u,g){return l.call(i,u,g)}p(S,"PerformPromiseThen");function y(i,u,g){S(S(i,u,g),void 0,s)}p(y,"uponPromise");function w(i,u){y(i,u)}p(w,"uponFulfillment");function b(i,u){y(i,void 0,u)}p(b,"uponRejection");function _(i,u,g){return S(i,u,g)}p(_,"transformPromiseWith");function D(i){S(i,void 0,s)}p(D,"setPromiseIsHandledToTrue");let k=p(i=>{if(typeof queueMicrotask=="function")k=queueMicrotask;else{let u=h(void 0);k=p(g=>S(u,g),"_queueMicrotask")}return k(i)},"_queueMicrotask");function v(i,u,g){if(typeof i!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(i,u,g)}p(v,"reflectCall");function x(i,u,g){try{return h(v(i,u,g))}catch(A){return m(A)}}p(x,"promiseCall");let R=16384,j=class{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(u){let g=this._back,A=g;g._elements.length===R-1&&(A={_elements:[],_next:void 0}),g._elements.push(u),A!==g&&(this._back=A,g._next=A),++this._size}shift(){let u=this._front,g=u,A=this._cursor,P=A+1,q=u._elements,H=q[A];return P===R&&(g=u._next,P=0),--this._size,this._cursor=P,u!==g&&(this._front=g),q[A]=void 0,H}forEach(u){let g=this._cursor,A=this._front,P=A._elements;for(;(g!==P.length||A._next!==void 0)&&!(g===P.length&&(A=A._next,P=A._elements,g=0,P.length===0));)u(P[g]),++g}peek(){let u=this._front,g=this._cursor;return u._elements[g]}};p(j,"SimpleQueue");let W=j,U=Symbol("[[AbortSteps]]"),ue=Symbol("[[ErrorSteps]]"),Y=Symbol("[[CancelSteps]]"),ne=Symbol("[[PullSteps]]"),te=Symbol("[[ReleaseSteps]]");function re(i,u){i._ownerReadableStream=u,u._reader=i,u._state==="readable"?X(i):u._state==="closed"?Q(i):Z(i,u._storedError)}p(re,"ReadableStreamReaderGenericInitialize");function K(i,u){let g=i._ownerReadableStream;return Bt(g,u)}p(K,"ReadableStreamReaderGenericCancel");function se(i){let u=i._ownerReadableStream;u._state==="readable"?me(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):he(i,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),u._readableStreamController[te](),u._reader=void 0,i._ownerReadableStream=void 0}p(se,"ReadableStreamReaderGenericRelease");function ie(i){return new TypeError("Cannot "+i+" a stream using a released reader")}p(ie,"readerLockException");function X(i){i._closedPromise=d((u,g)=>{i._closedPromise_resolve=u,i._closedPromise_reject=g})}p(X,"defaultReaderClosedPromiseInitialize");function Z(i,u){X(i),me(i,u)}p(Z,"defaultReaderClosedPromiseInitializeAsRejected");function Q(i){X(i),z(i)}p(Q,"defaultReaderClosedPromiseInitializeAsResolved");function me(i,u){i._closedPromise_reject!==void 0&&(D(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}p(me,"defaultReaderClosedPromiseReject");function he(i,u){Z(i,u)}p(he,"defaultReaderClosedPromiseResetToRejected");function z(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0)}p(z,"defaultReaderClosedPromiseResolve");let ge=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},Fe=Math.trunc||function(i){return i<0?Math.ceil(i):Math.floor(i)};function xe(i){return typeof i=="object"||typeof i=="function"}p(xe,"isDictionary");function ye(i,u){if(i!==void 0&&!xe(i))throw new TypeError(`${u} is not an object.`)}p(ye,"assertDictionary");function be(i,u){if(typeof i!="function")throw new TypeError(`${u} is not a function.`)}p(be,"assertFunction");function C(i){return typeof i=="object"&&i!==null||typeof i=="function"}p(C,"isObject");function E(i,u){if(!C(i))throw new TypeError(`${u} is not an object.`)}p(E,"assertObject");function T(i,u,g){if(i===void 0)throw new TypeError(`Parameter ${u} is required in '${g}'.`)}p(T,"assertRequiredArgument");function I(i,u,g){if(i===void 0)throw new TypeError(`${u} is required in '${g}'.`)}p(I,"assertRequiredField");function F(i){return Number(i)}p(F,"convertUnrestrictedDouble");function B(i){return i===0?0:i}p(B,"censorNegativeZero");function $(i){return B(Fe(i))}p($,"integerPart");function O(i,u){let g=Number.MAX_SAFE_INTEGER,A=Number(i);if(A=B(A),!ge(A))throw new TypeError(`${u} is not a finite number`);if(A=$(A),A<0||A>g)throw new TypeError(`${u} is outside the accepted range of 0 to ${g}, inclusive`);return!ge(A)||A===0?0:A}p(O,"convertUnsignedLongLongWithEnforceRange");function N(i,u){if(!Fn(i))throw new TypeError(`${u} is not a ReadableStream.`)}p(N,"assertReadableStream");function L(i){return new Re(i)}p(L,"AcquireReadableStreamDefaultReader");function M(i,u){i._reader._readRequests.push(u)}p(M,"ReadableStreamAddReadRequest");function J(i,u,g){let A=i._reader._readRequests.shift();g?A._closeSteps():A._chunkSteps(u)}p(J,"ReadableStreamFulfillReadRequest");function oe(i){return i._reader._readRequests.length}p(oe,"ReadableStreamGetNumReadRequests");function ae(i){let u=i._reader;return!(u===void 0||!Oe(u))}p(ae,"ReadableStreamHasDefaultReader");let Ee=class{constructor(u){if(T(u,1,"ReadableStreamDefaultReader"),N(u,"First parameter"),Pn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");re(this,u),this._readRequests=new W}get closed(){return Oe(this)?this._closedPromise:m(ln("closed"))}cancel(u=void 0){return Oe(this)?this._ownerReadableStream===void 0?m(ie("cancel")):K(this,u):m(ln("cancel"))}read(){if(!Oe(this))return m(ln("read"));if(this._ownerReadableStream===void 0)return m(ie("read from"));let u,g,A=d((P,q)=>{u=P,g=q});return we(this,{_chunkSteps:p(P=>u({value:P,done:!1}),"_chunkSteps"),_closeSteps:p(()=>u({value:void 0,done:!0}),"_closeSteps"),_errorSteps:p(P=>g(P),"_errorSteps")}),A}releaseLock(){if(!Oe(this))throw ln("releaseLock");this._ownerReadableStream!==void 0&&De(this)}};p(Ee,"ReadableStreamDefaultReader");let Re=Ee;Object.defineProperties(Re.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(Re.prototype.cancel,"cancel"),a(Re.prototype.read,"read"),a(Re.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Re.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Oe(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_readRequests")?!1:i instanceof Re}p(Oe,"IsReadableStreamDefaultReader");function we(i,u){let g=i._ownerReadableStream;g._disturbed=!0,g._state==="closed"?u._closeSteps():g._state==="errored"?u._errorSteps(g._storedError):g._readableStreamController[ne](u)}p(we,"ReadableStreamDefaultReaderRead");function De(i){se(i);let u=new TypeError("Reader was released");Ke(i,u)}p(De,"ReadableStreamDefaultReaderRelease");function Ke(i,u){let g=i._readRequests;i._readRequests=new W,g.forEach(A=>{A._errorSteps(u)})}p(Ke,"ReadableStreamDefaultReaderErrorReadRequests");function ln(i){return new TypeError(`ReadableStreamDefaultReader.prototype.${i} can only be used on a ReadableStreamDefaultReader`)}p(ln,"defaultReaderBrandCheckException");let _s=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),fo=class{constructor(u,g){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=u,this._preventCancel=g}next(){let u=p(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,u,u):u(),this._ongoingPromise}return(u){let g=p(()=>this._returnSteps(u),"returnSteps");return this._ongoingPromise?_(this._ongoingPromise,g,g):g()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let u=this._reader,g,A,P=d((q,H)=>{g=q,A=H});return we(u,{_chunkSteps:p(q=>{this._ongoingPromise=void 0,k(()=>g({value:q,done:!1}))},"_chunkSteps"),_closeSteps:p(()=>{this._ongoingPromise=void 0,this._isFinished=!0,se(u),g({value:void 0,done:!0})},"_closeSteps"),_errorSteps:p(q=>{this._ongoingPromise=void 0,this._isFinished=!0,se(u),A(q)},"_errorSteps")}),P}_returnSteps(u){if(this._isFinished)return Promise.resolve({value:u,done:!0});this._isFinished=!0;let g=this._reader;if(!this._preventCancel){let A=K(g,u);return se(g),_(A,()=>({value:u,done:!0}))}return se(g),h({value:u,done:!0})}};p(fo,"ReadableStreamAsyncIteratorImpl");let St=fo,Zn={next(){return Xe(this)?this._asyncIteratorImpl.next():m(je("next"))},return(i){return Xe(this)?this._asyncIteratorImpl.return(i):m(je("return"))}};Object.setPrototypeOf(Zn,_s);function dt(i,u){let g=L(i),A=new St(g,u),P=Object.create(Zn);return P._asyncIteratorImpl=A,P}p(dt,"AcquireReadableStreamAsyncIterator");function Xe(i){if(!o(i)||!Object.prototype.hasOwnProperty.call(i,"_asyncIteratorImpl"))return!1;try{return i._asyncIteratorImpl instanceof St}catch{return!1}}p(Xe,"IsReadableStreamAsyncIterator");function je(i){return new TypeError(`ReadableStreamAsyncIterator.${i} can only be used on a ReadableSteamAsyncIterator`)}p(je,"streamAsyncIteratorBrandCheckException");let $g=Number.isNaN||function(i){return i!==i};var Pl,Il,Nl;function ho(i){return i.slice()}p(ho,"CreateArrayFromList");function Bl(i,u,g,A,P){new Uint8Array(i).set(new Uint8Array(g,A,P),u)}p(Bl,"CopyDataBlockBytes");let Tn=p(i=>(typeof i.transfer=="function"?Tn=p(u=>u.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Tn=p(u=>structuredClone(u,{transfer:[u]}),"TransferArrayBuffer"):Tn=p(u=>u,"TransferArrayBuffer"),Tn(i)),"TransferArrayBuffer"),er=p(i=>(typeof i.detached=="boolean"?er=p(u=>u.detached,"IsDetachedBuffer"):er=p(u=>u.byteLength===0,"IsDetachedBuffer"),er(i)),"IsDetachedBuffer");function jl(i,u,g){if(i.slice)return i.slice(u,g);let A=g-u,P=new ArrayBuffer(A);return Bl(P,0,i,u,A),P}p(jl,"ArrayBufferSlice");function bs(i,u){let g=i[u];if(g!=null){if(typeof g!="function")throw new TypeError(`${String(u)} is not a function`);return g}}p(bs,"GetMethod");function zg(i){let u={[Symbol.iterator]:()=>i.iterator},g=(async function*(){return yield*u})(),A=g.next;return{iterator:g,nextMethod:A,done:!1}}p(zg,"CreateAsyncFromSyncIterator");let Ml=(Nl=(Pl=Symbol.asyncIterator)!==null&&Pl!==void 0?Pl:(Il=Symbol.for)===null||Il===void 0?void 0:Il.call(Symbol,"Symbol.asyncIterator"))!==null&&Nl!==void 0?Nl:"@@asyncIterator";function Ul(i,u="sync",g){if(g===void 0)if(u==="async"){if(g=bs(i,Ml),g===void 0){let q=bs(i,Symbol.iterator),H=Ul(i,"sync",q);return zg(H)}}else g=bs(i,Symbol.iterator);if(g===void 0)throw new TypeError("The object is not iterable");let A=v(g,i,[]);if(!o(A))throw new TypeError("The iterator method must return an object");let P=A.next;return{iterator:A,nextMethod:P,done:!1}}p(Ul,"GetIterator");function Hg(i){let u=v(i.nextMethod,i.iterator,[]);if(!o(u))throw new TypeError("The iterator.next() method must return an object");return u}p(Hg,"IteratorNext");function Wg(i){return!!i.done}p(Wg,"IteratorComplete");function Gg(i){return i.value}p(Gg,"IteratorValue");function Jg(i){return!(typeof i!="number"||$g(i)||i<0)}p(Jg,"IsNonNegativeNumber");function Ll(i){let u=jl(i.buffer,i.byteOffset,i.byteOffset+i.byteLength);return new Uint8Array(u)}p(Ll,"CloneAsUint8Array");function Ji(i){let u=i._queue.shift();return i._queueTotalSize-=u.size,i._queueTotalSize<0&&(i._queueTotalSize=0),u.value}p(Ji,"DequeueValue");function Vi(i,u,g){if(!Jg(g)||g===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");i._queue.push({value:u,size:g}),i._queueTotalSize+=g}p(Vi,"EnqueueValueWithSize");function Vg(i){return i._queue.peek().value}p(Vg,"PeekQueueValue");function Rn(i){i._queue=new W,i._queueTotalSize=0}p(Rn,"ResetQueue");function ql(i){return i===DataView}p(ql,"isDataViewConstructor");function Kg(i){return ql(i.constructor)}p(Kg,"isDataView");function Yg(i){return ql(i)?1:i.BYTES_PER_ELEMENT}p(Yg,"arrayBufferViewElementSize");let Xg=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ki(this))throw ea("view");return this._view}respond(u){if(!Ki(this))throw ea("respond");if(T(u,1,"respond"),u=O(u,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(er(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ss(this._associatedReadableByteStreamController,u)}respondWithNewView(u){if(!Ki(this))throw ea("respondWithNewView");if(T(u,1,"respondWithNewView"),!ArrayBuffer.isView(u))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(er(u.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");As(this._associatedReadableByteStreamController,u)}};p(Xg,"ReadableStreamBYOBRequest");let Dr=Xg;Object.defineProperties(Dr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(Dr.prototype.respond,"respond"),a(Dr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let Qg=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!tr(this))throw go("byobRequest");return Zi(this)}get desiredSize(){if(!tr(this))throw go("desiredSize");return Xl(this)}close(){if(!tr(this))throw go("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let u=this._controlledReadableByteStream._state;if(u!=="readable")throw new TypeError(`The stream (in ${u} state) is not in the readable state and cannot be closed`);po(this)}enqueue(u){if(!tr(this))throw go("enqueue");if(T(u,1,"enqueue"),!ArrayBuffer.isView(u))throw new TypeError("chunk must be an array buffer view");if(u.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(u.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let g=this._controlledReadableByteStream._state;if(g!=="readable")throw new TypeError(`The stream (in ${g} state) is not in the readable state and cannot be enqueued to`);ks(this,u)}error(u=void 0){if(!tr(this))throw go("error");At(this,u)}[Y](u){$l(this),Rn(this);let g=this._cancelAlgorithm(u);return Cs(this),g}[ne](u){let g=this._controlledReadableByteStream;if(this._queueTotalSize>0){Yl(this,u);return}let A=this._autoAllocateChunkSize;if(A!==void 0){let P;try{P=new ArrayBuffer(A)}catch(H){u._errorSteps(H);return}let q={buffer:P,bufferByteLength:A,byteOffset:0,byteLength:A,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(q)}M(g,u),nr(this)}[te](){if(this._pendingPullIntos.length>0){let u=this._pendingPullIntos.peek();u.readerType="none",this._pendingPullIntos=new W,this._pendingPullIntos.push(u)}}};p(Qg,"ReadableByteStreamController");let Dn=Qg;Object.defineProperties(Dn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(Dn.prototype.close,"close"),a(Dn.prototype.enqueue,"enqueue"),a(Dn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function tr(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableByteStream")?!1:i instanceof Dn}p(tr,"IsReadableByteStreamController");function Ki(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_associatedReadableByteStreamController")?!1:i instanceof Dr}p(Ki,"IsReadableStreamBYOBRequest");function nr(i){if(!rm(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let u=i._pullAlgorithm();y(u,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,nr(i)),null),g=>(At(i,g),null))}p(nr,"ReadableByteStreamControllerCallPullIfNeeded");function $l(i){Xi(i),i._pendingPullIntos=new W}p($l,"ReadableByteStreamControllerClearPendingPullIntos");function Yi(i,u){let g=!1;i._state==="closed"&&(g=!0);let A=zl(u);u.readerType==="default"?J(i,A,g):um(i,A,g)}p(Yi,"ReadableByteStreamControllerCommitPullIntoDescriptor");function zl(i){let u=i.bytesFilled,g=i.elementSize;return new i.viewConstructor(i.buffer,i.byteOffset,u/g)}p(zl,"ReadableByteStreamControllerConvertPullIntoDescriptor");function ws(i,u,g,A){i._queue.push({buffer:u,byteOffset:g,byteLength:A}),i._queueTotalSize+=A}p(ws,"ReadableByteStreamControllerEnqueueChunkToQueue");function Hl(i,u,g,A){let P;try{P=jl(u,g,g+A)}catch(q){throw At(i,q),q}ws(i,P,0,A)}p(Hl,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function Wl(i,u){u.bytesFilled>0&&Hl(i,u.buffer,u.byteOffset,u.bytesFilled),xr(i)}p(Wl,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function Gl(i,u){let g=Math.min(i._queueTotalSize,u.byteLength-u.bytesFilled),A=u.bytesFilled+g,P=g,q=!1,H=A%u.elementSize,ee=A-H;ee>=u.minimumFill&&(P=ee-u.bytesFilled,q=!0);let ce=i._queue;for(;P>0;){let pe=ce.peek(),Ce=Math.min(P,pe.byteLength),ke=u.byteOffset+u.bytesFilled;Bl(u.buffer,ke,pe.buffer,pe.byteOffset,Ce),pe.byteLength===Ce?ce.shift():(pe.byteOffset+=Ce,pe.byteLength-=Ce),i._queueTotalSize-=Ce,Jl(i,Ce,u),P-=Ce}return q}p(Gl,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function Jl(i,u,g){g.bytesFilled+=u}p(Jl,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function Vl(i){i._queueTotalSize===0&&i._closeRequested?(Cs(i),ko(i._controlledReadableByteStream)):nr(i)}p(Vl,"ReadableByteStreamControllerHandleQueueDrain");function Xi(i){i._byobRequest!==null&&(i._byobRequest._associatedReadableByteStreamController=void 0,i._byobRequest._view=null,i._byobRequest=null)}p(Xi,"ReadableByteStreamControllerInvalidateBYOBRequest");function Qi(i){for(;i._pendingPullIntos.length>0;){if(i._queueTotalSize===0)return;let u=i._pendingPullIntos.peek();Gl(i,u)&&(xr(i),Yi(i._controlledReadableByteStream,u))}}p(Qi,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function Zg(i){let u=i._controlledReadableByteStream._reader;for(;u._readRequests.length>0;){if(i._queueTotalSize===0)return;let g=u._readRequests.shift();Yl(i,g)}}p(Zg,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function em(i,u,g,A){let P=i._controlledReadableByteStream,q=u.constructor,H=Yg(q),{byteOffset:ee,byteLength:ce}=u,pe=g*H,Ce;try{Ce=Tn(u.buffer)}catch(Ne){A._errorSteps(Ne);return}let ke={buffer:Ce,bufferByteLength:Ce.byteLength,byteOffset:ee,byteLength:ce,bytesFilled:0,minimumFill:pe,elementSize:H,viewConstructor:q,readerType:"byob"};if(i._pendingPullIntos.length>0){i._pendingPullIntos.push(ke),ed(P,A);return}if(P._state==="closed"){let Ne=new q(ke.buffer,ke.byteOffset,0);A._closeSteps(Ne);return}if(i._queueTotalSize>0){if(Gl(i,ke)){let Ne=zl(ke);Vl(i),A._chunkSteps(Ne);return}if(i._closeRequested){let Ne=new TypeError("Insufficient bytes to fill elements in the given buffer");At(i,Ne),A._errorSteps(Ne);return}}i._pendingPullIntos.push(ke),ed(P,A),nr(i)}p(em,"ReadableByteStreamControllerPullInto");function tm(i,u){u.readerType==="none"&&xr(i);let g=i._controlledReadableByteStream;if(ta(g))for(;td(g)>0;){let A=xr(i);Yi(g,A)}}p(tm,"ReadableByteStreamControllerRespondInClosedState");function nm(i,u,g){if(Jl(i,u,g),g.readerType==="none"){Wl(i,g),Qi(i);return}if(g.bytesFilled<g.minimumFill)return;xr(i);let A=g.bytesFilled%g.elementSize;if(A>0){let P=g.byteOffset+g.bytesFilled;Hl(i,g.buffer,P-A,A)}g.bytesFilled-=A,Yi(i._controlledReadableByteStream,g),Qi(i)}p(nm,"ReadableByteStreamControllerRespondInReadableState");function Kl(i,u){let g=i._pendingPullIntos.peek();Xi(i),i._controlledReadableByteStream._state==="closed"?tm(i,g):nm(i,u,g),nr(i)}p(Kl,"ReadableByteStreamControllerRespondInternal");function xr(i){return i._pendingPullIntos.shift()}p(xr,"ReadableByteStreamControllerShiftPendingPullInto");function rm(i){let u=i._controlledReadableByteStream;return u._state!=="readable"||i._closeRequested||!i._started?!1:!!(ae(u)&&oe(u)>0||ta(u)&&td(u)>0||Xl(i)>0)}p(rm,"ReadableByteStreamControllerShouldCallPull");function Cs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0}p(Cs,"ReadableByteStreamControllerClearAlgorithms");function po(i){let u=i._controlledReadableByteStream;if(!(i._closeRequested||u._state!=="readable")){if(i._queueTotalSize>0){i._closeRequested=!0;return}if(i._pendingPullIntos.length>0){let g=i._pendingPullIntos.peek();if(g.bytesFilled%g.elementSize!==0){let A=new TypeError("Insufficient bytes to fill elements in the given buffer");throw At(i,A),A}}Cs(i),ko(u)}}p(po,"ReadableByteStreamControllerClose");function ks(i,u){let g=i._controlledReadableByteStream;if(i._closeRequested||g._state!=="readable")return;let{buffer:A,byteOffset:P,byteLength:q}=u;if(er(A))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let H=Tn(A);if(i._pendingPullIntos.length>0){let ee=i._pendingPullIntos.peek();if(er(ee.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Xi(i),ee.buffer=Tn(ee.buffer),ee.readerType==="none"&&Wl(i,ee)}if(ae(g))if(Zg(i),oe(g)===0)ws(i,H,P,q);else{i._pendingPullIntos.length>0&&xr(i);let ee=new Uint8Array(H,P,q);J(g,ee,!1)}else ta(g)?(ws(i,H,P,q),Qi(i)):ws(i,H,P,q);nr(i)}p(ks,"ReadableByteStreamControllerEnqueue");function At(i,u){let g=i._controlledReadableByteStream;g._state==="readable"&&($l(i),Rn(i),Cs(i),Ad(g,u))}p(At,"ReadableByteStreamControllerError");function Yl(i,u){let g=i._queue.shift();i._queueTotalSize-=g.byteLength,Vl(i);let A=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);u._chunkSteps(A)}p(Yl,"ReadableByteStreamControllerFillReadRequestFromQueue");function Zi(i){if(i._byobRequest===null&&i._pendingPullIntos.length>0){let u=i._pendingPullIntos.peek(),g=new Uint8Array(u.buffer,u.byteOffset+u.bytesFilled,u.byteLength-u.bytesFilled),A=Object.create(Dr.prototype);sm(A,i,g),i._byobRequest=A}return i._byobRequest}p(Zi,"ReadableByteStreamControllerGetBYOBRequest");function Xl(i){let u=i._controlledReadableByteStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}p(Xl,"ReadableByteStreamControllerGetDesiredSize");function Ss(i,u){let g=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(u===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(g.bytesFilled+u>g.byteLength)throw new RangeError("bytesWritten out of range")}g.buffer=Tn(g.buffer),Kl(i,u)}p(Ss,"ReadableByteStreamControllerRespond");function As(i,u){let g=i._pendingPullIntos.peek();if(i._controlledReadableByteStream._state==="closed"){if(u.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(u.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(g.byteOffset+g.bytesFilled!==u.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(g.bufferByteLength!==u.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(g.bytesFilled+u.byteLength>g.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let A=u.byteLength;g.buffer=Tn(u.buffer),Kl(i,A)}p(As,"ReadableByteStreamControllerRespondWithNewView");function Ql(i,u,g,A,P,q,H){u._controlledReadableByteStream=i,u._pullAgain=!1,u._pulling=!1,u._byobRequest=null,u._queue=u._queueTotalSize=void 0,Rn(u),u._closeRequested=!1,u._started=!1,u._strategyHWM=q,u._pullAlgorithm=A,u._cancelAlgorithm=P,u._autoAllocateChunkSize=H,u._pendingPullIntos=new W,i._readableStreamController=u;let ee=g();y(h(ee),()=>(u._started=!0,nr(u),null),ce=>(At(u,ce),null))}p(Ql,"SetUpReadableByteStreamController");function om(i,u,g){let A=Object.create(Dn.prototype),P,q,H;u.start!==void 0?P=p(()=>u.start(A),"startAlgorithm"):P=p(()=>{},"startAlgorithm"),u.pull!==void 0?q=p(()=>u.pull(A),"pullAlgorithm"):q=p(()=>h(void 0),"pullAlgorithm"),u.cancel!==void 0?H=p(ce=>u.cancel(ce),"cancelAlgorithm"):H=p(()=>h(void 0),"cancelAlgorithm");let ee=u.autoAllocateChunkSize;if(ee===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ql(i,A,P,q,H,g,ee)}p(om,"SetUpReadableByteStreamControllerFromUnderlyingSource");function sm(i,u,g){i._associatedReadableByteStreamController=u,i._view=g}p(sm,"SetUpReadableStreamBYOBRequest");function ea(i){return new TypeError(`ReadableStreamBYOBRequest.prototype.${i} can only be used on a ReadableStreamBYOBRequest`)}p(ea,"byobRequestBrandCheckException");function go(i){return new TypeError(`ReadableByteStreamController.prototype.${i} can only be used on a ReadableByteStreamController`)}p(go,"byteStreamControllerBrandCheckException");function im(i,u){ye(i,u);let g=i?.mode;return{mode:g===void 0?void 0:am(g,`${u} has member 'mode' that`)}}p(im,"convertReaderOptions");function am(i,u){if(i=`${i}`,i!=="byob")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamReaderMode`);return i}p(am,"convertReadableStreamReaderMode");function cm(i,u){var g;ye(i,u);let A=(g=i?.min)!==null&&g!==void 0?g:1;return{min:O(A,`${u} has member 'min' that`)}}p(cm,"convertByobReadOptions");function Zl(i){return new rr(i)}p(Zl,"AcquireReadableStreamBYOBReader");function ed(i,u){i._reader._readIntoRequests.push(u)}p(ed,"ReadableStreamAddReadIntoRequest");function um(i,u,g){let A=i._reader._readIntoRequests.shift();g?A._closeSteps(u):A._chunkSteps(u)}p(um,"ReadableStreamFulfillReadIntoRequest");function td(i){return i._reader._readIntoRequests.length}p(td,"ReadableStreamGetNumReadIntoRequests");function ta(i){let u=i._reader;return!(u===void 0||!or(u))}p(ta,"ReadableStreamHasBYOBReader");let lm=class{constructor(u){if(T(u,1,"ReadableStreamBYOBReader"),N(u,"First parameter"),Pn(u))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!tr(u._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");re(this,u),this._readIntoRequests=new W}get closed(){return or(this)?this._closedPromise:m(Es("closed"))}cancel(u=void 0){return or(this)?this._ownerReadableStream===void 0?m(ie("cancel")):K(this,u):m(Es("cancel"))}read(u,g={}){if(!or(this))return m(Es("read"));if(!ArrayBuffer.isView(u))return m(new TypeError("view must be an array buffer view"));if(u.byteLength===0)return m(new TypeError("view must have non-zero byteLength"));if(u.buffer.byteLength===0)return m(new TypeError("view's buffer must have non-zero byteLength"));if(er(u.buffer))return m(new TypeError("view's buffer has been detached"));let A;try{A=cm(g,"options")}catch(ce){return m(ce)}let P=A.min;if(P===0)return m(new TypeError("options.min must be greater than 0"));if(Kg(u)){if(P>u.byteLength)return m(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(P>u.length)return m(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return m(ie("read from"));let q,H,ee=d((ce,pe)=>{q=ce,H=pe});return nd(this,u,P,{_chunkSteps:p(ce=>q({value:ce,done:!1}),"_chunkSteps"),_closeSteps:p(ce=>q({value:ce,done:!0}),"_closeSteps"),_errorSteps:p(ce=>H(ce),"_errorSteps")}),ee}releaseLock(){if(!or(this))throw Es("releaseLock");this._ownerReadableStream!==void 0&&dm(this)}};p(lm,"ReadableStreamBYOBReader");let rr=lm;Object.defineProperties(rr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(rr.prototype.cancel,"cancel"),a(rr.prototype.read,"read"),a(rr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function or(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_readIntoRequests")?!1:i instanceof rr}p(or,"IsReadableStreamBYOBReader");function nd(i,u,g,A){let P=i._ownerReadableStream;P._disturbed=!0,P._state==="errored"?A._errorSteps(P._storedError):em(P._readableStreamController,u,g,A)}p(nd,"ReadableStreamBYOBReaderRead");function dm(i){se(i);let u=new TypeError("Reader was released");rd(i,u)}p(dm,"ReadableStreamBYOBReaderRelease");function rd(i,u){let g=i._readIntoRequests;i._readIntoRequests=new W,g.forEach(A=>{A._errorSteps(u)})}p(rd,"ReadableStreamBYOBReaderErrorReadIntoRequests");function Es(i){return new TypeError(`ReadableStreamBYOBReader.prototype.${i} can only be used on a ReadableStreamBYOBReader`)}p(Es,"byobReaderBrandCheckException");function mo(i,u){let{highWaterMark:g}=i;if(g===void 0)return u;if($g(g)||g<0)throw new RangeError("Invalid highWaterMark");return g}p(mo,"ExtractHighWaterMark");function vs(i){let{size:u}=i;return u||(()=>1)}p(vs,"ExtractSizeAlgorithm");function Ts(i,u){ye(i,u);let g=i?.highWaterMark,A=i?.size;return{highWaterMark:g===void 0?void 0:F(g),size:A===void 0?void 0:fm(A,`${u} has member 'size' that`)}}p(Ts,"convertQueuingStrategy");function fm(i,u){return be(i,u),g=>F(i(g))}p(fm,"convertQueuingStrategySize");function hm(i,u){ye(i,u);let g=i?.abort,A=i?.close,P=i?.start,q=i?.type,H=i?.write;return{abort:g===void 0?void 0:pm(g,i,`${u} has member 'abort' that`),close:A===void 0?void 0:gm(A,i,`${u} has member 'close' that`),start:P===void 0?void 0:mm(P,i,`${u} has member 'start' that`),write:H===void 0?void 0:ym(H,i,`${u} has member 'write' that`),type:q}}p(hm,"convertUnderlyingSink");function pm(i,u,g){return be(i,g),A=>x(i,u,[A])}p(pm,"convertUnderlyingSinkAbortCallback");function gm(i,u,g){return be(i,g),()=>x(i,u,[])}p(gm,"convertUnderlyingSinkCloseCallback");function mm(i,u,g){return be(i,g),A=>v(i,u,[A])}p(mm,"convertUnderlyingSinkStartCallback");function ym(i,u,g){return be(i,g),(A,P)=>x(i,u,[A,P])}p(ym,"convertUnderlyingSinkWriteCallback");function od(i,u){if(!Or(i))throw new TypeError(`${u} is not a WritableStream.`)}p(od,"assertWritableStream");function _m(i){if(typeof i!="object"||i===null)return!1;try{return typeof i.aborted=="boolean"}catch{return!1}}p(_m,"isAbortSignal");let NA=typeof AbortController=="function";function bm(){if(NA)return new AbortController}p(bm,"createAbortController");let wm=class{constructor(u={},g={}){u===void 0?u=null:E(u,"First parameter");let A=Ts(g,"Second parameter"),P=hm(u,"First parameter");if(id(this),P.type!==void 0)throw new RangeError("Invalid type is specified");let q=vs(A),H=mo(A,1);jm(this,P,H,q)}get locked(){if(!Or(this))throw Fs("locked");return Fr(this)}abort(u=void 0){return Or(this)?Fr(this)?m(new TypeError("Cannot abort a stream that already has a writer")):Rs(this,u):m(Fs("abort"))}close(){return Or(this)?Fr(this)?m(new TypeError("Cannot close a stream that already has a writer")):Kt(this)?m(new TypeError("Cannot close an already-closing stream")):ad(this):m(Fs("close"))}getWriter(){if(!Or(this))throw Fs("getWriter");return sd(this)}};p(wm,"WritableStream");let sr=wm;Object.defineProperties(sr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(sr.prototype.abort,"abort"),a(sr.prototype.close,"close"),a(sr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function sd(i){return new xn(i)}p(sd,"AcquireWritableStreamDefaultWriter");function Cm(i,u,g,A,P=1,q=()=>1){let H=Object.create(sr.prototype);id(H);let ee=Object.create(yo.prototype);return fd(H,ee,i,u,g,A,P,q),H}p(Cm,"CreateWritableStream");function id(i){i._state="writable",i._storedError=void 0,i._writer=void 0,i._writableStreamController=void 0,i._writeRequests=new W,i._inFlightWriteRequest=void 0,i._closeRequest=void 0,i._inFlightCloseRequest=void 0,i._pendingAbortRequest=void 0,i._backpressure=!1}p(id,"InitializeWritableStream");function Or(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_writableStreamController")?!1:i instanceof sr}p(Or,"IsWritableStream");function Fr(i){return i._writer!==void 0}p(Fr,"IsWritableStreamLocked");function Rs(i,u){var g;if(i._state==="closed"||i._state==="errored")return h(void 0);i._writableStreamController._abortReason=u,(g=i._writableStreamController._abortController)===null||g===void 0||g.abort(u);let A=i._state;if(A==="closed"||A==="errored")return h(void 0);if(i._pendingAbortRequest!==void 0)return i._pendingAbortRequest._promise;let P=!1;A==="erroring"&&(P=!0,u=void 0);let q=d((H,ee)=>{i._pendingAbortRequest={_promise:void 0,_resolve:H,_reject:ee,_reason:u,_wasAlreadyErroring:P}});return i._pendingAbortRequest._promise=q,P||ra(i,u),q}p(Rs,"WritableStreamAbort");function ad(i){let u=i._state;if(u==="closed"||u==="errored")return m(new TypeError(`The stream (in ${u} state) is not in the writable state and cannot be closed`));let g=d((P,q)=>{let H={_resolve:P,_reject:q};i._closeRequest=H}),A=i._writer;return A!==void 0&&i._backpressure&&u==="writable"&&da(A),Mm(i._writableStreamController),g}p(ad,"WritableStreamClose");function km(i){return d((u,g)=>{let A={_resolve:u,_reject:g};i._writeRequests.push(A)})}p(km,"WritableStreamAddWriteRequest");function na(i,u){if(i._state==="writable"){ra(i,u);return}oa(i)}p(na,"WritableStreamDealWithRejection");function ra(i,u){let g=i._writableStreamController;i._state="erroring",i._storedError=u;let A=i._writer;A!==void 0&&ud(A,u),!Tm(i)&&g._started&&oa(i)}p(ra,"WritableStreamStartErroring");function oa(i){i._state="errored",i._writableStreamController[ue]();let u=i._storedError;if(i._writeRequests.forEach(P=>{P._reject(u)}),i._writeRequests=new W,i._pendingAbortRequest===void 0){Ds(i);return}let g=i._pendingAbortRequest;if(i._pendingAbortRequest=void 0,g._wasAlreadyErroring){g._reject(u),Ds(i);return}let A=i._writableStreamController[U](g._reason);y(A,()=>(g._resolve(),Ds(i),null),P=>(g._reject(P),Ds(i),null))}p(oa,"WritableStreamFinishErroring");function Sm(i){i._inFlightWriteRequest._resolve(void 0),i._inFlightWriteRequest=void 0}p(Sm,"WritableStreamFinishInFlightWrite");function Am(i,u){i._inFlightWriteRequest._reject(u),i._inFlightWriteRequest=void 0,na(i,u)}p(Am,"WritableStreamFinishInFlightWriteWithError");function Em(i){i._inFlightCloseRequest._resolve(void 0),i._inFlightCloseRequest=void 0,i._state==="erroring"&&(i._storedError=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._resolve(),i._pendingAbortRequest=void 0)),i._state="closed";let u=i._writer;u!==void 0&&md(u)}p(Em,"WritableStreamFinishInFlightClose");function vm(i,u){i._inFlightCloseRequest._reject(u),i._inFlightCloseRequest=void 0,i._pendingAbortRequest!==void 0&&(i._pendingAbortRequest._reject(u),i._pendingAbortRequest=void 0),na(i,u)}p(vm,"WritableStreamFinishInFlightCloseWithError");function Kt(i){return!(i._closeRequest===void 0&&i._inFlightCloseRequest===void 0)}p(Kt,"WritableStreamCloseQueuedOrInFlight");function Tm(i){return!(i._inFlightWriteRequest===void 0&&i._inFlightCloseRequest===void 0)}p(Tm,"WritableStreamHasOperationMarkedInFlight");function Rm(i){i._inFlightCloseRequest=i._closeRequest,i._closeRequest=void 0}p(Rm,"WritableStreamMarkCloseRequestInFlight");function Dm(i){i._inFlightWriteRequest=i._writeRequests.shift()}p(Dm,"WritableStreamMarkFirstWriteRequestInFlight");function Ds(i){i._closeRequest!==void 0&&(i._closeRequest._reject(i._storedError),i._closeRequest=void 0);let u=i._writer;u!==void 0&&ua(u,i._storedError)}p(Ds,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function sa(i,u){let g=i._writer;g!==void 0&&u!==i._backpressure&&(u?Wm(g):da(g)),i._backpressure=u}p(sa,"WritableStreamUpdateBackpressure");let xm=class{constructor(u){if(T(u,1,"WritableStreamDefaultWriter"),od(u,"First parameter"),Fr(u))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=u,u._writer=this;let g=u._state;if(g==="writable")!Kt(u)&&u._backpressure?Is(this):yd(this),Ps(this);else if(g==="erroring")la(this,u._storedError),Ps(this);else if(g==="closed")yd(this),zm(this);else{let A=u._storedError;la(this,A),gd(this,A)}}get closed(){return ir(this)?this._closedPromise:m(ar("closed"))}get desiredSize(){if(!ir(this))throw ar("desiredSize");if(this._ownerWritableStream===void 0)throw bo("desiredSize");return Im(this)}get ready(){return ir(this)?this._readyPromise:m(ar("ready"))}abort(u=void 0){return ir(this)?this._ownerWritableStream===void 0?m(bo("abort")):Om(this,u):m(ar("abort"))}close(){if(!ir(this))return m(ar("close"));let u=this._ownerWritableStream;return u===void 0?m(bo("close")):Kt(u)?m(new TypeError("Cannot close an already-closing stream")):cd(this)}releaseLock(){if(!ir(this))throw ar("releaseLock");this._ownerWritableStream!==void 0&&ld(this)}write(u=void 0){return ir(this)?this._ownerWritableStream===void 0?m(bo("write to")):dd(this,u):m(ar("write"))}};p(xm,"WritableStreamDefaultWriter");let xn=xm;Object.defineProperties(xn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(xn.prototype.abort,"abort"),a(xn.prototype.close,"close"),a(xn.prototype.releaseLock,"releaseLock"),a(xn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function ir(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_ownerWritableStream")?!1:i instanceof xn}p(ir,"IsWritableStreamDefaultWriter");function Om(i,u){let g=i._ownerWritableStream;return Rs(g,u)}p(Om,"WritableStreamDefaultWriterAbort");function cd(i){let u=i._ownerWritableStream;return ad(u)}p(cd,"WritableStreamDefaultWriterClose");function Fm(i){let u=i._ownerWritableStream,g=u._state;return Kt(u)||g==="closed"?h(void 0):g==="errored"?m(u._storedError):cd(i)}p(Fm,"WritableStreamDefaultWriterCloseWithErrorPropagation");function Pm(i,u){i._closedPromiseState==="pending"?ua(i,u):Hm(i,u)}p(Pm,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function ud(i,u){i._readyPromiseState==="pending"?_d(i,u):Gm(i,u)}p(ud,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function Im(i){let u=i._ownerWritableStream,g=u._state;return g==="errored"||g==="erroring"?null:g==="closed"?0:hd(u._writableStreamController)}p(Im,"WritableStreamDefaultWriterGetDesiredSize");function ld(i){let u=i._ownerWritableStream,g=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");ud(i,g),Pm(i,g),u._writer=void 0,i._ownerWritableStream=void 0}p(ld,"WritableStreamDefaultWriterRelease");function dd(i,u){let g=i._ownerWritableStream,A=g._writableStreamController,P=Um(A,u);if(g!==i._ownerWritableStream)return m(bo("write to"));let q=g._state;if(q==="errored")return m(g._storedError);if(Kt(g)||q==="closed")return m(new TypeError("The stream is closing or closed and cannot be written to"));if(q==="erroring")return m(g._storedError);let H=km(g);return Lm(A,u,P),H}p(dd,"WritableStreamDefaultWriterWrite");let Nm={},Bm=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!ia(this))throw ca("abortReason");return this._abortReason}get signal(){if(!ia(this))throw ca("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(u=void 0){if(!ia(this))throw ca("error");this._controlledWritableStream._state==="writable"&&pd(this,u)}[U](u){let g=this._abortAlgorithm(u);return xs(this),g}[ue](){Rn(this)}};p(Bm,"WritableStreamDefaultController");let yo=Bm;Object.defineProperties(yo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function ia(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledWritableStream")?!1:i instanceof yo}p(ia,"IsWritableStreamDefaultController");function fd(i,u,g,A,P,q,H,ee){u._controlledWritableStream=i,i._writableStreamController=u,u._queue=void 0,u._queueTotalSize=void 0,Rn(u),u._abortReason=void 0,u._abortController=bm(),u._started=!1,u._strategySizeAlgorithm=ee,u._strategyHWM=H,u._writeAlgorithm=A,u._closeAlgorithm=P,u._abortAlgorithm=q;let ce=aa(u);sa(i,ce);let pe=g(),Ce=h(pe);y(Ce,()=>(u._started=!0,Os(u),null),ke=>(u._started=!0,na(i,ke),null))}p(fd,"SetUpWritableStreamDefaultController");function jm(i,u,g,A){let P=Object.create(yo.prototype),q,H,ee,ce;u.start!==void 0?q=p(()=>u.start(P),"startAlgorithm"):q=p(()=>{},"startAlgorithm"),u.write!==void 0?H=p(pe=>u.write(pe,P),"writeAlgorithm"):H=p(()=>h(void 0),"writeAlgorithm"),u.close!==void 0?ee=p(()=>u.close(),"closeAlgorithm"):ee=p(()=>h(void 0),"closeAlgorithm"),u.abort!==void 0?ce=p(pe=>u.abort(pe),"abortAlgorithm"):ce=p(()=>h(void 0),"abortAlgorithm"),fd(i,P,q,H,ee,ce,g,A)}p(jm,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function xs(i){i._writeAlgorithm=void 0,i._closeAlgorithm=void 0,i._abortAlgorithm=void 0,i._strategySizeAlgorithm=void 0}p(xs,"WritableStreamDefaultControllerClearAlgorithms");function Mm(i){Vi(i,Nm,0),Os(i)}p(Mm,"WritableStreamDefaultControllerClose");function Um(i,u){try{return i._strategySizeAlgorithm(u)}catch(g){return _o(i,g),1}}p(Um,"WritableStreamDefaultControllerGetChunkSize");function hd(i){return i._strategyHWM-i._queueTotalSize}p(hd,"WritableStreamDefaultControllerGetDesiredSize");function Lm(i,u,g){try{Vi(i,u,g)}catch(P){_o(i,P);return}let A=i._controlledWritableStream;if(!Kt(A)&&A._state==="writable"){let P=aa(i);sa(A,P)}Os(i)}p(Lm,"WritableStreamDefaultControllerWrite");function Os(i){let u=i._controlledWritableStream;if(!i._started||u._inFlightWriteRequest!==void 0)return;if(u._state==="erroring"){oa(u);return}if(i._queue.length===0)return;let g=Vg(i);g===Nm?qm(i):$m(i,g)}p(Os,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function _o(i,u){i._controlledWritableStream._state==="writable"&&pd(i,u)}p(_o,"WritableStreamDefaultControllerErrorIfNeeded");function qm(i){let u=i._controlledWritableStream;Rm(u),Ji(i);let g=i._closeAlgorithm();xs(i),y(g,()=>(Em(u),null),A=>(vm(u,A),null))}p(qm,"WritableStreamDefaultControllerProcessClose");function $m(i,u){let g=i._controlledWritableStream;Dm(g);let A=i._writeAlgorithm(u);y(A,()=>{Sm(g);let P=g._state;if(Ji(i),!Kt(g)&&P==="writable"){let q=aa(i);sa(g,q)}return Os(i),null},P=>(g._state==="writable"&&xs(i),Am(g,P),null))}p($m,"WritableStreamDefaultControllerProcessWrite");function aa(i){return hd(i)<=0}p(aa,"WritableStreamDefaultControllerGetBackpressure");function pd(i,u){let g=i._controlledWritableStream;xs(i),ra(g,u)}p(pd,"WritableStreamDefaultControllerError");function Fs(i){return new TypeError(`WritableStream.prototype.${i} can only be used on a WritableStream`)}p(Fs,"streamBrandCheckException$2");function ca(i){return new TypeError(`WritableStreamDefaultController.prototype.${i} can only be used on a WritableStreamDefaultController`)}p(ca,"defaultControllerBrandCheckException$2");function ar(i){return new TypeError(`WritableStreamDefaultWriter.prototype.${i} can only be used on a WritableStreamDefaultWriter`)}p(ar,"defaultWriterBrandCheckException");function bo(i){return new TypeError("Cannot "+i+" a stream using a released writer")}p(bo,"defaultWriterLockException");function Ps(i){i._closedPromise=d((u,g)=>{i._closedPromise_resolve=u,i._closedPromise_reject=g,i._closedPromiseState="pending"})}p(Ps,"defaultWriterClosedPromiseInitialize");function gd(i,u){Ps(i),ua(i,u)}p(gd,"defaultWriterClosedPromiseInitializeAsRejected");function zm(i){Ps(i),md(i)}p(zm,"defaultWriterClosedPromiseInitializeAsResolved");function ua(i,u){i._closedPromise_reject!==void 0&&(D(i._closedPromise),i._closedPromise_reject(u),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="rejected")}p(ua,"defaultWriterClosedPromiseReject");function Hm(i,u){gd(i,u)}p(Hm,"defaultWriterClosedPromiseResetToRejected");function md(i){i._closedPromise_resolve!==void 0&&(i._closedPromise_resolve(void 0),i._closedPromise_resolve=void 0,i._closedPromise_reject=void 0,i._closedPromiseState="resolved")}p(md,"defaultWriterClosedPromiseResolve");function Is(i){i._readyPromise=d((u,g)=>{i._readyPromise_resolve=u,i._readyPromise_reject=g}),i._readyPromiseState="pending"}p(Is,"defaultWriterReadyPromiseInitialize");function la(i,u){Is(i),_d(i,u)}p(la,"defaultWriterReadyPromiseInitializeAsRejected");function yd(i){Is(i),da(i)}p(yd,"defaultWriterReadyPromiseInitializeAsResolved");function _d(i,u){i._readyPromise_reject!==void 0&&(D(i._readyPromise),i._readyPromise_reject(u),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="rejected")}p(_d,"defaultWriterReadyPromiseReject");function Wm(i){Is(i)}p(Wm,"defaultWriterReadyPromiseReset");function Gm(i,u){la(i,u)}p(Gm,"defaultWriterReadyPromiseResetToRejected");function da(i){i._readyPromise_resolve!==void 0&&(i._readyPromise_resolve(void 0),i._readyPromise_resolve=void 0,i._readyPromise_reject=void 0,i._readyPromiseState="fulfilled")}p(da,"defaultWriterReadyPromiseResolve");function Jm(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof _f<"u")return _f}p(Jm,"getGlobals");let BA=Jm();function Vm(i){if(!(typeof i=="function"||typeof i=="object")||i.name!=="DOMException")return!1;try{return new i,!0}catch{return!1}}p(Vm,"isDOMExceptionConstructor");function Km(){let i=BA?.DOMException;return Vm(i)?i:void 0}p(Km,"getFromGlobal");function Ym(){let i=p(function(u,g){this.message=u||"",this.name=g||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},"DOMException");return a(i,"DOMException"),i.prototype=Object.create(Error.prototype),Object.defineProperty(i.prototype,"constructor",{value:i,writable:!0,configurable:!0}),i}p(Ym,"createPolyfill");let jA=Km()||Ym();function bd(i,u,g,A,P,q){let H=L(i),ee=sd(u);i._disturbed=!0;let ce=!1,pe=h(void 0);return d((Ce,ke)=>{let Ne;if(q!==void 0){if(Ne=p(()=>{let de=q.reason!==void 0?q.reason:new jA("Aborted","AbortError"),ve=[];A||ve.push(()=>u._state==="writable"?Rs(u,de):h(void 0)),P||ve.push(()=>i._state==="readable"?Bt(i,de):h(void 0)),ft(()=>Promise.all(ve.map(Pe=>Pe())),!0,de)},"abortAlgorithm"),q.aborted){Ne();return}q.addEventListener("abort",Ne)}function mt(){return d((de,ve)=>{function Pe(ht){ht?de():S(In(),Pe,ve)}p(Pe,"next"),Pe(!1)})}p(mt,"pipeLoop");function In(){return ce?h(!0):S(ee._readyPromise,()=>d((de,ve)=>{we(H,{_chunkSteps:p(Pe=>{pe=S(dd(ee,Pe),void 0,r),de(!1)},"_chunkSteps"),_closeSteps:p(()=>de(!0),"_closeSteps"),_errorSteps:ve})}))}if(p(In,"pipeStep"),jt(i,H._closedPromise,de=>(A?yt(!0,de):ft(()=>Rs(u,de),!0,de),null)),jt(u,ee._closedPromise,de=>(P?yt(!0,de):ft(()=>Bt(i,de),!0,de),null)),Qe(i,H._closedPromise,()=>(g?yt():ft(()=>Fm(ee)),null)),Kt(u)||u._state==="closed"){let de=new TypeError("the destination writable stream closed before all data could be piped to it");P?yt(!0,de):ft(()=>Bt(i,de),!0,de)}D(mt());function Yt(){let de=pe;return S(pe,()=>de!==pe?Yt():void 0)}p(Yt,"waitForWritesToFinish");function jt(de,ve,Pe){de._state==="errored"?Pe(de._storedError):b(ve,Pe)}p(jt,"isOrBecomesErrored");function Qe(de,ve,Pe){de._state==="closed"?Pe():w(ve,Pe)}p(Qe,"isOrBecomesClosed");function ft(de,ve,Pe){if(ce)return;ce=!0,u._state==="writable"&&!Kt(u)?w(Yt(),ht):ht();function ht(){return y(de(),()=>Nn(ve,Pe),dr=>Nn(!0,dr)),null}p(ht,"doTheRest")}p(ft,"shutdownWithAction");function yt(de,ve){ce||(ce=!0,u._state==="writable"&&!Kt(u)?w(Yt(),()=>Nn(de,ve)):Nn(de,ve))}p(yt,"shutdown");function Nn(de,ve){return ld(ee),se(H),q!==void 0&&q.removeEventListener("abort",Ne),de?ke(ve):Ce(void 0),null}p(Nn,"finalize")})}p(bd,"ReadableStreamPipeTo");let Xm=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ns(this))throw js("desiredSize");return fa(this)}close(){if(!Ns(this))throw js("close");if(!Ir(this))throw new TypeError("The stream is not in a state that permits close");cr(this)}enqueue(u=void 0){if(!Ns(this))throw js("enqueue");if(!Ir(this))throw new TypeError("The stream is not in a state that permits enqueue");return Pr(this,u)}error(u=void 0){if(!Ns(this))throw js("error");Nt(this,u)}[Y](u){Rn(this);let g=this._cancelAlgorithm(u);return Bs(this),g}[ne](u){let g=this._controlledReadableStream;if(this._queue.length>0){let A=Ji(this);this._closeRequested&&this._queue.length===0?(Bs(this),ko(g)):wo(this),u._chunkSteps(A)}else M(g,u),wo(this)}[te](){}};p(Xm,"ReadableStreamDefaultController");let On=Xm;Object.defineProperties(On.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(On.prototype.close,"close"),a(On.prototype.enqueue,"enqueue"),a(On.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(On.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ns(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledReadableStream")?!1:i instanceof On}p(Ns,"IsReadableStreamDefaultController");function wo(i){if(!wd(i))return;if(i._pulling){i._pullAgain=!0;return}i._pulling=!0;let u=i._pullAlgorithm();y(u,()=>(i._pulling=!1,i._pullAgain&&(i._pullAgain=!1,wo(i)),null),g=>(Nt(i,g),null))}p(wo,"ReadableStreamDefaultControllerCallPullIfNeeded");function wd(i){let u=i._controlledReadableStream;return!Ir(i)||!i._started?!1:!!(Pn(u)&&oe(u)>0||fa(i)>0)}p(wd,"ReadableStreamDefaultControllerShouldCallPull");function Bs(i){i._pullAlgorithm=void 0,i._cancelAlgorithm=void 0,i._strategySizeAlgorithm=void 0}p(Bs,"ReadableStreamDefaultControllerClearAlgorithms");function cr(i){if(!Ir(i))return;let u=i._controlledReadableStream;i._closeRequested=!0,i._queue.length===0&&(Bs(i),ko(u))}p(cr,"ReadableStreamDefaultControllerClose");function Pr(i,u){if(!Ir(i))return;let g=i._controlledReadableStream;if(Pn(g)&&oe(g)>0)J(g,u,!1);else{let A;try{A=i._strategySizeAlgorithm(u)}catch(P){throw Nt(i,P),P}try{Vi(i,u,A)}catch(P){throw Nt(i,P),P}}wo(i)}p(Pr,"ReadableStreamDefaultControllerEnqueue");function Nt(i,u){let g=i._controlledReadableStream;g._state==="readable"&&(Rn(i),Bs(i),Ad(g,u))}p(Nt,"ReadableStreamDefaultControllerError");function fa(i){let u=i._controlledReadableStream._state;return u==="errored"?null:u==="closed"?0:i._strategyHWM-i._queueTotalSize}p(fa,"ReadableStreamDefaultControllerGetDesiredSize");function Qm(i){return!wd(i)}p(Qm,"ReadableStreamDefaultControllerHasBackpressure");function Ir(i){let u=i._controlledReadableStream._state;return!i._closeRequested&&u==="readable"}p(Ir,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function Cd(i,u,g,A,P,q,H){u._controlledReadableStream=i,u._queue=void 0,u._queueTotalSize=void 0,Rn(u),u._started=!1,u._closeRequested=!1,u._pullAgain=!1,u._pulling=!1,u._strategySizeAlgorithm=H,u._strategyHWM=q,u._pullAlgorithm=A,u._cancelAlgorithm=P,i._readableStreamController=u;let ee=g();y(h(ee),()=>(u._started=!0,wo(u),null),ce=>(Nt(u,ce),null))}p(Cd,"SetUpReadableStreamDefaultController");function Zm(i,u,g,A){let P=Object.create(On.prototype),q,H,ee;u.start!==void 0?q=p(()=>u.start(P),"startAlgorithm"):q=p(()=>{},"startAlgorithm"),u.pull!==void 0?H=p(()=>u.pull(P),"pullAlgorithm"):H=p(()=>h(void 0),"pullAlgorithm"),u.cancel!==void 0?ee=p(ce=>u.cancel(ce),"cancelAlgorithm"):ee=p(()=>h(void 0),"cancelAlgorithm"),Cd(i,P,q,H,ee,g,A)}p(Zm,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function js(i){return new TypeError(`ReadableStreamDefaultController.prototype.${i} can only be used on a ReadableStreamDefaultController`)}p(js,"defaultControllerBrandCheckException$1");function ey(i,u){return tr(i._readableStreamController)?ny(i):ty(i)}p(ey,"ReadableStreamTee");function ty(i,u){let g=L(i),A=!1,P=!1,q=!1,H=!1,ee,ce,pe,Ce,ke,Ne=d(Qe=>{ke=Qe});function mt(){return A?(P=!0,h(void 0)):(A=!0,we(g,{_chunkSteps:p(Qe=>{k(()=>{P=!1;let ft=Qe,yt=Qe;q||Pr(pe._readableStreamController,ft),H||Pr(Ce._readableStreamController,yt),A=!1,P&&mt()})},"_chunkSteps"),_closeSteps:p(()=>{A=!1,q||cr(pe._readableStreamController),H||cr(Ce._readableStreamController),(!q||!H)&&ke(void 0)},"_closeSteps"),_errorSteps:p(()=>{A=!1},"_errorSteps")}),h(void 0))}p(mt,"pullAlgorithm");function In(Qe){if(q=!0,ee=Qe,H){let ft=ho([ee,ce]),yt=Bt(i,ft);ke(yt)}return Ne}p(In,"cancel1Algorithm");function Yt(Qe){if(H=!0,ce=Qe,q){let ft=ho([ee,ce]),yt=Bt(i,ft);ke(yt)}return Ne}p(Yt,"cancel2Algorithm");function jt(){}return p(jt,"startAlgorithm"),pe=Co(jt,mt,In),Ce=Co(jt,mt,Yt),b(g._closedPromise,Qe=>(Nt(pe._readableStreamController,Qe),Nt(Ce._readableStreamController,Qe),(!q||!H)&&ke(void 0),null)),[pe,Ce]}p(ty,"ReadableStreamDefaultTee");function ny(i){let u=L(i),g=!1,A=!1,P=!1,q=!1,H=!1,ee,ce,pe,Ce,ke,Ne=d(de=>{ke=de});function mt(de){b(de._closedPromise,ve=>(de!==u||(At(pe._readableStreamController,ve),At(Ce._readableStreamController,ve),(!q||!H)&&ke(void 0)),null))}p(mt,"forwardReaderError");function In(){or(u)&&(se(u),u=L(i),mt(u)),we(u,{_chunkSteps:p(de=>{k(()=>{A=!1,P=!1;let ve=de,Pe=de;if(!q&&!H)try{Pe=Ll(de)}catch(ht){At(pe._readableStreamController,ht),At(Ce._readableStreamController,ht),ke(Bt(i,ht));return}q||ks(pe._readableStreamController,ve),H||ks(Ce._readableStreamController,Pe),g=!1,A?jt():P&&Qe()})},"_chunkSteps"),_closeSteps:p(()=>{g=!1,q||po(pe._readableStreamController),H||po(Ce._readableStreamController),pe._readableStreamController._pendingPullIntos.length>0&&Ss(pe._readableStreamController,0),Ce._readableStreamController._pendingPullIntos.length>0&&Ss(Ce._readableStreamController,0),(!q||!H)&&ke(void 0)},"_closeSteps"),_errorSteps:p(()=>{g=!1},"_errorSteps")})}p(In,"pullWithDefaultReader");function Yt(de,ve){Oe(u)&&(se(u),u=Zl(i),mt(u));let Pe=ve?Ce:pe,ht=ve?pe:Ce;nd(u,de,1,{_chunkSteps:p(dr=>{k(()=>{A=!1,P=!1;let So=ve?H:q;if(ve?q:H)So||As(Pe._readableStreamController,dr);else{let Ao;try{Ao=Ll(dr)}catch(Nd){At(Pe._readableStreamController,Nd),At(ht._readableStreamController,Nd),ke(Bt(i,Nd));return}So||As(Pe._readableStreamController,dr),ks(ht._readableStreamController,Ao)}g=!1,A?jt():P&&Qe()})},"_chunkSteps"),_closeSteps:p(dr=>{g=!1;let So=ve?H:q,Ao=ve?q:H;So||po(Pe._readableStreamController),Ao||po(ht._readableStreamController),dr!==void 0&&(So||As(Pe._readableStreamController,dr),!Ao&&ht._readableStreamController._pendingPullIntos.length>0&&Ss(ht._readableStreamController,0)),(!So||!Ao)&&ke(void 0)},"_closeSteps"),_errorSteps:p(()=>{g=!1},"_errorSteps")})}p(Yt,"pullWithBYOBReader");function jt(){if(g)return A=!0,h(void 0);g=!0;let de=Zi(pe._readableStreamController);return de===null?In():Yt(de._view,!1),h(void 0)}p(jt,"pull1Algorithm");function Qe(){if(g)return P=!0,h(void 0);g=!0;let de=Zi(Ce._readableStreamController);return de===null?In():Yt(de._view,!0),h(void 0)}p(Qe,"pull2Algorithm");function ft(de){if(q=!0,ee=de,H){let ve=ho([ee,ce]),Pe=Bt(i,ve);ke(Pe)}return Ne}p(ft,"cancel1Algorithm");function yt(de){if(H=!0,ce=de,q){let ve=ho([ee,ce]),Pe=Bt(i,ve);ke(Pe)}return Ne}p(yt,"cancel2Algorithm");function Nn(){}return p(Nn,"startAlgorithm"),pe=Sd(Nn,jt,ft),Ce=Sd(Nn,Qe,yt),mt(u),[pe,Ce]}p(ny,"ReadableByteStreamTee");function ry(i){return o(i)&&typeof i.getReader<"u"}p(ry,"isReadableStreamLike");function oy(i){return ry(i)?iy(i.getReader()):sy(i)}p(oy,"ReadableStreamFrom");function sy(i){let u,g=Ul(i,"async"),A=r;function P(){let H;try{H=Hg(g)}catch(ce){return m(ce)}let ee=h(H);return _(ee,ce=>{if(!o(ce))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(Wg(ce))cr(u._readableStreamController);else{let pe=Gg(ce);Pr(u._readableStreamController,pe)}})}p(P,"pullAlgorithm");function q(H){let ee=g.iterator,ce;try{ce=bs(ee,"return")}catch(ke){return m(ke)}if(ce===void 0)return h(void 0);let pe;try{pe=v(ce,ee,[H])}catch(ke){return m(ke)}let Ce=h(pe);return _(Ce,ke=>{if(!o(ke))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return p(q,"cancelAlgorithm"),u=Co(A,P,q,0),u}p(sy,"ReadableStreamFromIterable");function iy(i){let u,g=r;function A(){let q;try{q=i.read()}catch(H){return m(H)}return _(q,H=>{if(!o(H))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(H.done)cr(u._readableStreamController);else{let ee=H.value;Pr(u._readableStreamController,ee)}})}p(A,"pullAlgorithm");function P(q){try{return h(i.cancel(q))}catch(H){return m(H)}}return p(P,"cancelAlgorithm"),u=Co(g,A,P,0),u}p(iy,"ReadableStreamFromDefaultReader");function ay(i,u){ye(i,u);let g=i,A=g?.autoAllocateChunkSize,P=g?.cancel,q=g?.pull,H=g?.start,ee=g?.type;return{autoAllocateChunkSize:A===void 0?void 0:O(A,`${u} has member 'autoAllocateChunkSize' that`),cancel:P===void 0?void 0:cy(P,g,`${u} has member 'cancel' that`),pull:q===void 0?void 0:uy(q,g,`${u} has member 'pull' that`),start:H===void 0?void 0:ly(H,g,`${u} has member 'start' that`),type:ee===void 0?void 0:dy(ee,`${u} has member 'type' that`)}}p(ay,"convertUnderlyingDefaultOrByteSource");function cy(i,u,g){return be(i,g),A=>x(i,u,[A])}p(cy,"convertUnderlyingSourceCancelCallback");function uy(i,u,g){return be(i,g),A=>x(i,u,[A])}p(uy,"convertUnderlyingSourcePullCallback");function ly(i,u,g){return be(i,g),A=>v(i,u,[A])}p(ly,"convertUnderlyingSourceStartCallback");function dy(i,u){if(i=`${i}`,i!=="bytes")throw new TypeError(`${u} '${i}' is not a valid enumeration value for ReadableStreamType`);return i}p(dy,"convertReadableStreamType");function fy(i,u){return ye(i,u),{preventCancel:!!i?.preventCancel}}p(fy,"convertIteratorOptions");function kd(i,u){ye(i,u);let g=i?.preventAbort,A=i?.preventCancel,P=i?.preventClose,q=i?.signal;return q!==void 0&&hy(q,`${u} has member 'signal' that`),{preventAbort:!!g,preventCancel:!!A,preventClose:!!P,signal:q}}p(kd,"convertPipeOptions");function hy(i,u){if(!_m(i))throw new TypeError(`${u} is not an AbortSignal.`)}p(hy,"assertAbortSignal");function py(i,u){ye(i,u);let g=i?.readable;I(g,"readable","ReadableWritablePair"),N(g,`${u} has member 'readable' that`);let A=i?.writable;return I(A,"writable","ReadableWritablePair"),od(A,`${u} has member 'writable' that`),{readable:g,writable:A}}p(py,"convertReadableWritablePair");let gy=class{constructor(u={},g={}){u===void 0?u=null:E(u,"First parameter");let A=Ts(g,"Second parameter"),P=ay(u,"First parameter");if(ha(this),P.type==="bytes"){if(A.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let q=mo(A,0);om(this,P,q)}else{let q=vs(A),H=mo(A,1);Zm(this,P,H,q)}}get locked(){if(!Fn(this))throw ur("locked");return Pn(this)}cancel(u=void 0){return Fn(this)?Pn(this)?m(new TypeError("Cannot cancel a stream that already has a reader")):Bt(this,u):m(ur("cancel"))}getReader(u=void 0){if(!Fn(this))throw ur("getReader");return im(u,"First parameter").mode===void 0?L(this):Zl(this)}pipeThrough(u,g={}){if(!Fn(this))throw ur("pipeThrough");T(u,1,"pipeThrough");let A=py(u,"First parameter"),P=kd(g,"Second parameter");if(Pn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Fr(A.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let q=bd(this,A.writable,P.preventClose,P.preventAbort,P.preventCancel,P.signal);return D(q),A.readable}pipeTo(u,g={}){if(!Fn(this))return m(ur("pipeTo"));if(u===void 0)return m("Parameter 1 is required in 'pipeTo'.");if(!Or(u))return m(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let A;try{A=kd(g,"Second parameter")}catch(P){return m(P)}return Pn(this)?m(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Fr(u)?m(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):bd(this,u,A.preventClose,A.preventAbort,A.preventCancel,A.signal)}tee(){if(!Fn(this))throw ur("tee");let u=ey(this);return ho(u)}values(u=void 0){if(!Fn(this))throw ur("values");let g=fy(u,"First parameter");return dt(this,g.preventCancel)}[Ml](u){return this.values(u)}static from(u){return oy(u)}};p(gy,"ReadableStream");let ut=gy;Object.defineProperties(ut,{from:{enumerable:!0}}),Object.defineProperties(ut.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(ut.from,"from"),a(ut.prototype.cancel,"cancel"),a(ut.prototype.getReader,"getReader"),a(ut.prototype.pipeThrough,"pipeThrough"),a(ut.prototype.pipeTo,"pipeTo"),a(ut.prototype.tee,"tee"),a(ut.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ut.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(ut.prototype,Ml,{value:ut.prototype.values,writable:!0,configurable:!0});function Co(i,u,g,A=1,P=()=>1){let q=Object.create(ut.prototype);ha(q);let H=Object.create(On.prototype);return Cd(q,H,i,u,g,A,P),q}p(Co,"CreateReadableStream");function Sd(i,u,g){let A=Object.create(ut.prototype);ha(A);let P=Object.create(Dn.prototype);return Ql(A,P,i,u,g,0,void 0),A}p(Sd,"CreateReadableByteStream");function ha(i){i._state="readable",i._reader=void 0,i._storedError=void 0,i._disturbed=!1}p(ha,"InitializeReadableStream");function Fn(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_readableStreamController")?!1:i instanceof ut}p(Fn,"IsReadableStream");function Pn(i){return i._reader!==void 0}p(Pn,"IsReadableStreamLocked");function Bt(i,u){if(i._disturbed=!0,i._state==="closed")return h(void 0);if(i._state==="errored")return m(i._storedError);ko(i);let g=i._reader;if(g!==void 0&&or(g)){let P=g._readIntoRequests;g._readIntoRequests=new W,P.forEach(q=>{q._closeSteps(void 0)})}let A=i._readableStreamController[Y](u);return _(A,r)}p(Bt,"ReadableStreamCancel");function ko(i){i._state="closed";let u=i._reader;if(u!==void 0&&(z(u),Oe(u))){let g=u._readRequests;u._readRequests=new W,g.forEach(A=>{A._closeSteps()})}}p(ko,"ReadableStreamClose");function Ad(i,u){i._state="errored",i._storedError=u;let g=i._reader;g!==void 0&&(me(g,u),Oe(g)?Ke(g,u):rd(g,u))}p(Ad,"ReadableStreamError");function ur(i){return new TypeError(`ReadableStream.prototype.${i} can only be used on a ReadableStream`)}p(ur,"streamBrandCheckException$1");function Ed(i,u){ye(i,u);let g=i?.highWaterMark;return I(g,"highWaterMark","QueuingStrategyInit"),{highWaterMark:F(g)}}p(Ed,"convertQueuingStrategyInit");let my=p(i=>i.byteLength,"byteLengthSizeFunction");a(my,"size");let yy=class{constructor(u){T(u,1,"ByteLengthQueuingStrategy"),u=Ed(u,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Td(this))throw vd("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Td(this))throw vd("size");return my}};p(yy,"ByteLengthQueuingStrategy");let pa=yy;Object.defineProperties(pa.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pa.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function vd(i){return new TypeError(`ByteLengthQueuingStrategy.prototype.${i} can only be used on a ByteLengthQueuingStrategy`)}p(vd,"byteLengthBrandCheckException");function Td(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_byteLengthQueuingStrategyHighWaterMark")?!1:i instanceof pa}p(Td,"IsByteLengthQueuingStrategy");let _y=p(()=>1,"countSizeFunction");a(_y,"size");let by=class{constructor(u){T(u,1,"CountQueuingStrategy"),u=Ed(u,"First parameter"),this._countQueuingStrategyHighWaterMark=u.highWaterMark}get highWaterMark(){if(!Dd(this))throw Rd("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dd(this))throw Rd("size");return _y}};p(by,"CountQueuingStrategy");let ga=by;Object.defineProperties(ga.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ga.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Rd(i){return new TypeError(`CountQueuingStrategy.prototype.${i} can only be used on a CountQueuingStrategy`)}p(Rd,"countBrandCheckException");function Dd(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_countQueuingStrategyHighWaterMark")?!1:i instanceof ga}p(Dd,"IsCountQueuingStrategy");function wy(i,u){ye(i,u);let g=i?.cancel,A=i?.flush,P=i?.readableType,q=i?.start,H=i?.transform,ee=i?.writableType;return{cancel:g===void 0?void 0:Ay(g,i,`${u} has member 'cancel' that`),flush:A===void 0?void 0:Cy(A,i,`${u} has member 'flush' that`),readableType:P,start:q===void 0?void 0:ky(q,i,`${u} has member 'start' that`),transform:H===void 0?void 0:Sy(H,i,`${u} has member 'transform' that`),writableType:ee}}p(wy,"convertTransformer");function Cy(i,u,g){return be(i,g),A=>x(i,u,[A])}p(Cy,"convertTransformerFlushCallback");function ky(i,u,g){return be(i,g),A=>v(i,u,[A])}p(ky,"convertTransformerStartCallback");function Sy(i,u,g){return be(i,g),(A,P)=>x(i,u,[A,P])}p(Sy,"convertTransformerTransformCallback");function Ay(i,u,g){return be(i,g),A=>x(i,u,[A])}p(Ay,"convertTransformerCancelCallback");let Ey=class{constructor(u={},g={},A={}){u===void 0&&(u=null);let P=Ts(g,"Second parameter"),q=Ts(A,"Third parameter"),H=wy(u,"First parameter");if(H.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(H.writableType!==void 0)throw new RangeError("Invalid writableType specified");let ee=mo(q,0),ce=vs(q),pe=mo(P,1),Ce=vs(P),ke,Ne=d(mt=>{ke=mt});vy(this,Ne,pe,Ce,ee,ce),Dy(this,H),H.start!==void 0?ke(H.start(this._transformStreamController)):ke(void 0)}get readable(){if(!xd(this))throw Id("readable");return this._readable}get writable(){if(!xd(this))throw Id("writable");return this._writable}};p(Ey,"TransformStream");let ma=Ey;Object.defineProperties(ma.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ma.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function vy(i,u,g,A,P,q){function H(){return u}p(H,"startAlgorithm");function ee(Ne){return Fy(i,Ne)}p(ee,"writeAlgorithm");function ce(Ne){return Py(i,Ne)}p(ce,"abortAlgorithm");function pe(){return Iy(i)}p(pe,"closeAlgorithm"),i._writable=Cm(H,ee,pe,ce,g,A);function Ce(){return Ny(i)}p(Ce,"pullAlgorithm");function ke(Ne){return By(i,Ne)}p(ke,"cancelAlgorithm"),i._readable=Co(H,Ce,ke,P,q),i._backpressure=void 0,i._backpressureChangePromise=void 0,i._backpressureChangePromise_resolve=void 0,Ms(i,!0),i._transformStreamController=void 0}p(vy,"InitializeTransformStream");function xd(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_transformStreamController")?!1:i instanceof ma}p(xd,"IsTransformStream");function Od(i,u){Nt(i._readable._readableStreamController,u),ya(i,u)}p(Od,"TransformStreamError");function ya(i,u){Ls(i._transformStreamController),_o(i._writable._writableStreamController,u),_a(i)}p(ya,"TransformStreamErrorWritableAndUnblockWrite");function _a(i){i._backpressure&&Ms(i,!1)}p(_a,"TransformStreamUnblockWrite");function Ms(i,u){i._backpressureChangePromise!==void 0&&i._backpressureChangePromise_resolve(),i._backpressureChangePromise=d(g=>{i._backpressureChangePromise_resolve=g}),i._backpressure=u}p(Ms,"TransformStreamSetBackpressure");let Ty=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Us(this))throw qs("desiredSize");let u=this._controlledTransformStream._readable._readableStreamController;return fa(u)}enqueue(u=void 0){if(!Us(this))throw qs("enqueue");Fd(this,u)}error(u=void 0){if(!Us(this))throw qs("error");xy(this,u)}terminate(){if(!Us(this))throw qs("terminate");Oy(this)}};p(Ty,"TransformStreamDefaultController");let lr=Ty;Object.defineProperties(lr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(lr.prototype.enqueue,"enqueue"),a(lr.prototype.error,"error"),a(lr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(lr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Us(i){return!o(i)||!Object.prototype.hasOwnProperty.call(i,"_controlledTransformStream")?!1:i instanceof lr}p(Us,"IsTransformStreamDefaultController");function Ry(i,u,g,A,P){u._controlledTransformStream=i,i._transformStreamController=u,u._transformAlgorithm=g,u._flushAlgorithm=A,u._cancelAlgorithm=P,u._finishPromise=void 0,u._finishPromise_resolve=void 0,u._finishPromise_reject=void 0}p(Ry,"SetUpTransformStreamDefaultController");function Dy(i,u){let g=Object.create(lr.prototype),A,P,q;u.transform!==void 0?A=p(H=>u.transform(H,g),"transformAlgorithm"):A=p(H=>{try{return Fd(g,H),h(void 0)}catch(ee){return m(ee)}},"transformAlgorithm"),u.flush!==void 0?P=p(()=>u.flush(g),"flushAlgorithm"):P=p(()=>h(void 0),"flushAlgorithm"),u.cancel!==void 0?q=p(H=>u.cancel(H),"cancelAlgorithm"):q=p(()=>h(void 0),"cancelAlgorithm"),Ry(i,g,A,P,q)}p(Dy,"SetUpTransformStreamDefaultControllerFromTransformer");function Ls(i){i._transformAlgorithm=void 0,i._flushAlgorithm=void 0,i._cancelAlgorithm=void 0}p(Ls,"TransformStreamDefaultControllerClearAlgorithms");function Fd(i,u){let g=i._controlledTransformStream,A=g._readable._readableStreamController;if(!Ir(A))throw new TypeError("Readable side is not in a state that permits enqueue");try{Pr(A,u)}catch(P){throw ya(g,P),g._readable._storedError}Qm(A)!==g._backpressure&&Ms(g,!0)}p(Fd,"TransformStreamDefaultControllerEnqueue");function xy(i,u){Od(i._controlledTransformStream,u)}p(xy,"TransformStreamDefaultControllerError");function Pd(i,u){let g=i._transformAlgorithm(u);return _(g,void 0,A=>{throw Od(i._controlledTransformStream,A),A})}p(Pd,"TransformStreamDefaultControllerPerformTransform");function Oy(i){let u=i._controlledTransformStream,g=u._readable._readableStreamController;cr(g);let A=new TypeError("TransformStream terminated");ya(u,A)}p(Oy,"TransformStreamDefaultControllerTerminate");function Fy(i,u){let g=i._transformStreamController;if(i._backpressure){let A=i._backpressureChangePromise;return _(A,()=>{let P=i._writable;if(P._state==="erroring")throw P._storedError;return Pd(g,u)})}return Pd(g,u)}p(Fy,"TransformStreamDefaultSinkWriteAlgorithm");function Py(i,u){let g=i._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let A=i._readable;g._finishPromise=d((q,H)=>{g._finishPromise_resolve=q,g._finishPromise_reject=H});let P=g._cancelAlgorithm(u);return Ls(g),y(P,()=>(A._state==="errored"?Nr(g,A._storedError):(Nt(A._readableStreamController,u),ba(g)),null),q=>(Nt(A._readableStreamController,q),Nr(g,q),null)),g._finishPromise}p(Py,"TransformStreamDefaultSinkAbortAlgorithm");function Iy(i){let u=i._transformStreamController;if(u._finishPromise!==void 0)return u._finishPromise;let g=i._readable;u._finishPromise=d((P,q)=>{u._finishPromise_resolve=P,u._finishPromise_reject=q});let A=u._flushAlgorithm();return Ls(u),y(A,()=>(g._state==="errored"?Nr(u,g._storedError):(cr(g._readableStreamController),ba(u)),null),P=>(Nt(g._readableStreamController,P),Nr(u,P),null)),u._finishPromise}p(Iy,"TransformStreamDefaultSinkCloseAlgorithm");function Ny(i){return Ms(i,!1),i._backpressureChangePromise}p(Ny,"TransformStreamDefaultSourcePullAlgorithm");function By(i,u){let g=i._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let A=i._writable;g._finishPromise=d((q,H)=>{g._finishPromise_resolve=q,g._finishPromise_reject=H});let P=g._cancelAlgorithm(u);return Ls(g),y(P,()=>(A._state==="errored"?Nr(g,A._storedError):(_o(A._writableStreamController,u),_a(i),ba(g)),null),q=>(_o(A._writableStreamController,q),_a(i),Nr(g,q),null)),g._finishPromise}p(By,"TransformStreamDefaultSourceCancelAlgorithm");function qs(i){return new TypeError(`TransformStreamDefaultController.prototype.${i} can only be used on a TransformStreamDefaultController`)}p(qs,"defaultControllerBrandCheckException");function ba(i){i._finishPromise_resolve!==void 0&&(i._finishPromise_resolve(),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}p(ba,"defaultControllerFinishPromiseResolve");function Nr(i,u){i._finishPromise_reject!==void 0&&(D(i._finishPromise),i._finishPromise_reject(u),i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0)}p(Nr,"defaultControllerFinishPromiseReject");function Id(i){return new TypeError(`TransformStream.prototype.${i} can only be used on a TransformStream`)}p(Id,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=pa,n.CountQueuingStrategy=ga,n.ReadableByteStreamController=Dn,n.ReadableStream=ut,n.ReadableStreamBYOBReader=rr,n.ReadableStreamBYOBRequest=Dr,n.ReadableStreamDefaultController=On,n.ReadableStreamDefaultReader=Re,n.TransformStream=ma,n.TransformStreamDefaultController=lr,n.WritableStream=sr,n.WritableStreamDefaultController=yo,n.WritableStreamDefaultWriter=xn})})(cc,cc.exports)),cc.exports}function L0(){if(U0)return j0;U0=1;let t=65536;if(!globalThis.ReadableStream)try{let e=require("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,eb())}try{let{Blob:e}=require("buffer");e&&!e.prototype.stream&&(e.prototype.stream=p(function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let a=await o.slice(r,Math.min(o.size,r+t)).arrayBuffer();r+=a.byteLength,s.enqueue(new Uint8Array(a)),r===o.size&&s.close()}})},"name"))}catch{}return j0}async function*uc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,q0),a=n.buffer.slice(r,r+s);r+=a.byteLength,yield new Uint8Array(a)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let s=await o.slice(r,Math.min(o.size,r+q0)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function nb(t,e=Qr){var n=`${$0()}${$0()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
28
- Content-Disposition: form-data; name="`;return t.forEach((s,a)=>typeof s=="string"?r.push(o+Af(a)+`"\r
51
+ `);if(h===-1){Lc("have not received end of HTTP headers yet..."),s();return}let _=p.slice(0,h).toString("ascii").split(`\r
52
+ `),b=_.shift();if(!b)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let y=b.split(" "),w=+y[1],C=y.slice(2).join(" "),v={};for(let A of _){if(!A)continue;let T=A.indexOf(":");if(T===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${A}"`));let x=A.slice(0,T).toLowerCase(),O=A.slice(T+1).trimStart(),q=v[x];typeof q=="string"?v[x]=[q,O]:Array.isArray(q)?q.push(O):v[x]=O}Lc("got proxy server response: %o %o",b,v),i(),e({connect:{statusCode:w,statusText:C,headers:v},buffered:p})}t.on("error",u),t.on("end",c),s()})}Ko.parseProxyResponse=yO});var Aw=J(Ut=>{"use strict";var _O=Ut&&Ut.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bO=Ut&&Ut.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ew=Ut&&Ut.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&_O(e,t,n);return bO(e,t),e},vw=Ut&&Ut.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.HttpsProxyAgent=void 0;var qc=Ew(require("net")),ww=Ew(require("tls")),CO=vw(require("assert")),wO=vw(Op()),kO=bw(),SO=require("url"),EO=Cw(),vi=(0,wO.default)("https-proxy-agent"),kw=t=>t.servername===void 0&&t.host&&!qc.isIP(t.host)?{...t,servername:t.host}:t,$c=class extends kO.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new SO.URL(e):e,this.proxyHeaders=n?.headers??{},vi("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?Sw(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(vi("Creating `tls.Socket`: %o",this.connectOpts),o=ww.connect(kw(this.connectOpts))):(vi("Creating `net.Socket`: %o",this.connectOpts),o=qc.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=qc.isIPv6(n.host)?`[${n.host}]`:n.host,c=`CONNECT ${i}:${n.port} HTTP/1.1\r
53
+ `;if(r.username||r.password){let h=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(h).toString("base64")}`}s.Host=`${i}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let h of Object.keys(s))c+=`${h}: ${s[h]}\r
54
+ `;let u=(0,EO.parseProxyResponse)(o);o.write(`${c}\r
55
+ `);let{connect:f,buffered:d}=await u;if(e.emit("proxyConnect",f),this.emit("proxyConnect",f,e),f.statusCode===200)return e.once("socket",vO),n.secureEndpoint?(vi("Upgrading socket connection to TLS"),ww.connect({...Sw(kw(n),"host","path","port"),socket:o})):o;o.destroy();let p=new qc.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{vi("Replaying proxy buffer for failed request"),(0,CO.default)(h.listenerCount("data")>0),h.push(d),h.push(null)}),p}};$c.protocols=["http","https"];Ut.HttpsProxyAgent=$c;function vO(t){t.resume()}function Sw(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function Fp(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var AO,TO,Ip,zc=_r(()=>{AO=Object.defineProperty,TO=(t,e)=>AO(t,"name",{value:e,configurable:!0}),Ip=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};TO(Fp,"getDefaultExportFromCjs")});var Ow={};Rf(Ow,{toFormData:()=>Dw});function xw(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function Dw(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new FO(n[1]||n[2]),o,s,i,c,u,f,d=[],p=new so,h=Rt(C=>{i+=w.decode(C,{stream:!0})},"onPartData"),_=Rt(C=>{d.push(C)},"appendToFile"),b=Rt(()=>{let C=new Yo(d,f,{type:u});p.append(c,C)},"appendFileToFormData"),y=Rt(()=>{p.append(c,i)},"appendEntryToFormData"),w=new TextDecoder("utf-8");w.decode(),r.onPartBegin=function(){r.onPartData=h,r.onPartEnd=y,o="",s="",i="",c="",u="",f=null,d.length=0},r.onHeaderField=function(C){o+=w.decode(C,{stream:!0})},r.onHeaderValue=function(C){s+=w.decode(C,{stream:!0})},r.onHeaderEnd=function(){if(s+=w.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(c=C[2]||C[3]||""),f=xw(s),f&&(r.onPartData=_,r.onPartEnd=b)}else o==="content-type"&&(u=s);s="",o=""};for await(let C of t)r.write(C);return r.end(),p}var RO,Rt,yn,Me,Tw,Ar,Hc,Wc,xO,Ai,DO,OO,PO,IO,oo,Rw,FO,Pw=_r(()=>{Gc();zc();RO=Object.defineProperty,Rt=(t,e)=>RO(t,"name",{value:e,configurable:!0}),yn=0,Me={START_BOUNDARY:yn++,HEADER_FIELD_START:yn++,HEADER_FIELD:yn++,HEADER_VALUE_START:yn++,HEADER_VALUE:yn++,HEADER_VALUE_ALMOST_DONE:yn++,HEADERS_ALMOST_DONE:yn++,PART_DATA_START:yn++,PART_DATA:yn++,END:yn++},Tw=1,Ar={PART_BOUNDARY:Tw,LAST_BOUNDARY:Tw*=2},Hc=10,Wc=13,xO=32,Ai=45,DO=58,OO=97,PO=122,IO=Rt(t=>t|32,"lower"),oo=Rt(()=>{},"noop"),Rw=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=oo,this.onHeaderField=oo,this.onHeadersEnd=oo,this.onHeaderValue=oo,this.onPartBegin=oo,this.onPartData=oo,this.onPartEnd=oo,this.boundaryChars={},e=`\r
56
+ --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Me.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:i,boundaryChars:c,index:u,state:f,flags:d}=this,p=this.boundary.length,h=p-1,_=e.length,b,y,w=Rt(T=>{this[T+"Mark"]=n},"mark"),C=Rt(T=>{delete this[T+"Mark"]},"clear"),v=Rt((T,x,O,q)=>{(x===void 0||x!==O)&&this[T](q&&q.subarray(x,O))},"callback"),A=Rt((T,x)=>{let O=T+"Mark";O in this&&(x?(v(T,this[O],n,e),delete this[O]):(v(T,this[O],e.length,e),this[O]=0))},"dataCallback");for(n=0;n<r;n++)switch(b=e[n],f){case Me.START_BOUNDARY:if(u===i.length-2){if(b===Ai)d|=Ar.LAST_BOUNDARY;else if(b!==Wc)return;u++;break}else if(u-1===i.length-2){if(d&Ar.LAST_BOUNDARY&&b===Ai)f=Me.END,d=0;else if(!(d&Ar.LAST_BOUNDARY)&&b===Hc)u=0,v("onPartBegin"),f=Me.HEADER_FIELD_START;else return;break}b!==i[u+2]&&(u=-2),b===i[u+2]&&u++;break;case Me.HEADER_FIELD_START:f=Me.HEADER_FIELD,w("onHeaderField"),u=0;case Me.HEADER_FIELD:if(b===Wc){C("onHeaderField"),f=Me.HEADERS_ALMOST_DONE;break}if(u++,b===Ai)break;if(b===DO){if(u===1)return;A("onHeaderField",!0),f=Me.HEADER_VALUE_START;break}if(y=IO(b),y<OO||y>PO)return;break;case Me.HEADER_VALUE_START:if(b===xO)break;w("onHeaderValue"),f=Me.HEADER_VALUE;case Me.HEADER_VALUE:b===Wc&&(A("onHeaderValue",!0),v("onHeaderEnd"),f=Me.HEADER_VALUE_ALMOST_DONE);break;case Me.HEADER_VALUE_ALMOST_DONE:if(b!==Hc)return;f=Me.HEADER_FIELD_START;break;case Me.HEADERS_ALMOST_DONE:if(b!==Hc)return;v("onHeadersEnd"),f=Me.PART_DATA_START;break;case Me.PART_DATA_START:f=Me.PART_DATA,w("onPartData");case Me.PART_DATA:if(o=u,u===0){for(n+=h;n<_&&!(e[n]in c);)n+=p;n-=h,b=e[n]}if(u<i.length)i[u]===b?(u===0&&A("onPartData",!0),u++):u=0;else if(u===i.length)u++,b===Wc?d|=Ar.PART_BOUNDARY:b===Ai?d|=Ar.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(d&Ar.PART_BOUNDARY){if(u=0,b===Hc){d&=~Ar.PART_BOUNDARY,v("onPartEnd"),v("onPartBegin"),f=Me.HEADER_FIELD_START;break}}else d&Ar.LAST_BOUNDARY&&b===Ai?(v("onPartEnd"),f=Me.END,d=0):u=0;if(u>0)s[u-1]=b;else if(o>0){let T=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);v("onPartData",0,o,T),o=0,w("onPartData"),n--}break;case Me.END:break;default:throw new Error(`Unexpected state entered: ${f}`)}A("onHeaderField"),A("onHeaderValue"),A("onPartData"),this.index=u,this.state=f,this.flags=d}end(){if(this.state===Me.HEADER_FIELD_START&&this.index===0||this.state===Me.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Me.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};Rt(Rw,"MultipartParser");FO=Rw;Rt(xw,"_fileName");Rt(Dw,"toFormData")});function Kw(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",i=s;for(let d=1;d<n.length;d++)n[d]==="base64"?o=!0:n[d]&&(i+=`;${n[d]}`,n[d].indexOf("charset=")===0&&(r=n[d].substring(8)));!n[0]&&!r.length&&(i+=";charset=US-ASCII",r="US-ASCII");let c=o?"base64":"ascii",u=unescape(t.substring(e+1)),f=Buffer.from(u,c);return f.type=s,f.typeFull=i,f.charset=r,f}function Yw(){return Fw||(Fw=1,(function(t,e){(function(n,r){r(e)})(MO,function(n){function r(){}m(r,"noop");function o(a){return typeof a=="object"&&a!==null||typeof a=="function"}m(o,"typeIsObject");let s=r;function i(a,l){try{Object.defineProperty(a,"name",{value:l,configurable:!0})}catch{}}m(i,"setFunctionName");let c=Promise,u=Promise.prototype.then,f=Promise.reject.bind(c);function d(a){return new c(a)}m(d,"newPromise");function p(a){return d(l=>l(a))}m(p,"promiseResolvedWith");function h(a){return f(a)}m(h,"promiseRejectedWith");function _(a,l,g){return u.call(a,l,g)}m(_,"PerformPromiseThen");function b(a,l,g){_(_(a,l,g),void 0,s)}m(b,"uponPromise");function y(a,l){b(a,l)}m(y,"uponFulfillment");function w(a,l){b(a,void 0,l)}m(w,"uponRejection");function C(a,l,g){return _(a,l,g)}m(C,"transformPromiseWith");function v(a){_(a,void 0,s)}m(v,"setPromiseIsHandledToTrue");let A=m(a=>{if(typeof queueMicrotask=="function")A=queueMicrotask;else{let l=p(void 0);A=m(g=>_(l,g),"_queueMicrotask")}return A(a)},"_queueMicrotask");function T(a,l,g){if(typeof a!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(a,l,g)}m(T,"reflectCall");function x(a,l,g){try{return p(T(a,l,g))}catch(S){return h(S)}}m(x,"promiseCall");let O=16384,q=class{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(l){let g=this._back,S=g;g._elements.length===O-1&&(S={_elements:[],_next:void 0}),g._elements.push(l),S!==g&&(this._back=S,g._next=S),++this._size}shift(){let l=this._front,g=l,S=this._cursor,I=S+1,L=l._elements,z=L[S];return I===O&&(g=l._next,I=0),--this._size,this._cursor=I,l!==g&&(this._front=g),L[S]=void 0,z}forEach(l){let g=this._cursor,S=this._front,I=S._elements;for(;(g!==I.length||S._next!==void 0)&&!(g===I.length&&(S=S._next,I=S._elements,g=0,I.length===0));)l(I[g]),++g}peek(){let l=this._front,g=this._cursor;return l._elements[g]}};m(q,"SimpleQueue");let $=q,H=Symbol("[[AbortSteps]]"),ae=Symbol("[[ErrorSteps]]"),X=Symbol("[[CancelSteps]]"),te=Symbol("[[PullSteps]]"),Z=Symbol("[[ReleaseSteps]]");function De(a,l){a._ownerReadableStream=l,l._reader=a,l._state==="readable"?ee(a):l._state==="closed"?se(a):Q(a,l._storedError)}m(De,"ReadableStreamReaderGenericInitialize");function qe(a,l){let g=a._ownerReadableStream;return Ft(g,l)}m(qe,"ReadableStreamReaderGenericCancel");function Te(a){let l=a._ownerReadableStream;l._state==="readable"?le(a,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):be(a,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._readableStreamController[Z](),l._reader=void 0,a._ownerReadableStream=void 0}m(Te,"ReadableStreamReaderGenericRelease");function We(a){return new TypeError("Cannot "+a+" a stream using a released reader")}m(We,"readerLockException");function ee(a){a._closedPromise=d((l,g)=>{a._closedPromise_resolve=l,a._closedPromise_reject=g})}m(ee,"defaultReaderClosedPromiseInitialize");function Q(a,l){ee(a),le(a,l)}m(Q,"defaultReaderClosedPromiseInitializeAsRejected");function se(a){ee(a),K(a)}m(se,"defaultReaderClosedPromiseInitializeAsResolved");function le(a,l){a._closedPromise_reject!==void 0&&(v(a._closedPromise),a._closedPromise_reject(l),a._closedPromise_resolve=void 0,a._closedPromise_reject=void 0)}m(le,"defaultReaderClosedPromiseReject");function be(a,l){Q(a,l)}m(be,"defaultReaderClosedPromiseResetToRejected");function K(a){a._closedPromise_resolve!==void 0&&(a._closedPromise_resolve(void 0),a._closedPromise_resolve=void 0,a._closedPromise_reject=void 0)}m(K,"defaultReaderClosedPromiseResolve");let Ke=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Fe=Math.trunc||function(a){return a<0?Math.ceil(a):Math.floor(a)};function Y(a){return typeof a=="object"||typeof a=="function"}m(Y,"isDictionary");function ce(a,l){if(a!==void 0&&!Y(a))throw new TypeError(`${l} is not an object.`)}m(ce,"assertDictionary");function de(a,l){if(typeof a!="function")throw new TypeError(`${l} is not a function.`)}m(de,"assertFunction");function k(a){return typeof a=="object"&&a!==null||typeof a=="function"}m(k,"isObject");function E(a,l){if(!k(a))throw new TypeError(`${l} is not an object.`)}m(E,"assertObject");function R(a,l,g){if(a===void 0)throw new TypeError(`Parameter ${l} is required in '${g}'.`)}m(R,"assertRequiredArgument");function M(a,l,g){if(a===void 0)throw new TypeError(`${l} is required in '${g}'.`)}m(M,"assertRequiredField");function D(a){return Number(a)}m(D,"convertUnrestrictedDouble");function F(a){return a===0?0:a}m(F,"censorNegativeZero");function j(a){return F(Fe(a))}m(j,"integerPart");function P(a,l){let g=Number.MAX_SAFE_INTEGER,S=Number(a);if(S=F(S),!Ke(S))throw new TypeError(`${l} is not a finite number`);if(S=j(S),S<0||S>g)throw new TypeError(`${l} is outside the accepted range of 0 to ${g}, inclusive`);return!Ke(S)||S===0?0:S}m(P,"convertUnsignedLongLongWithEnforceRange");function N(a,l){if(!Nn(a))throw new TypeError(`${l} is not a ReadableStream.`)}m(N,"assertReadableStream");function U(a){return new ge(a)}m(U,"AcquireReadableStreamDefaultReader");function B(a,l){a._reader._readRequests.push(l)}m(B,"ReadableStreamAddReadRequest");function G(a,l,g){let S=a._reader._readRequests.shift();g?S._closeSteps():S._chunkSteps(l)}m(G,"ReadableStreamFulfillReadRequest");function oe(a){return a._reader._readRequests.length}m(oe,"ReadableStreamGetNumReadRequests");function ie(a){let l=a._reader;return!(l===void 0||!he(l))}m(ie,"ReadableStreamHasDefaultReader");let _e=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),Mn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");De(this,l),this._readRequests=new $}get closed(){return he(this)?this._closedPromise:h(fn("closed"))}cancel(l=void 0){return he(this)?this._ownerReadableStream===void 0?h(We("cancel")):qe(this,l):h(fn("cancel"))}read(){if(!he(this))return h(fn("read"));if(this._ownerReadableStream===void 0)return h(We("read from"));let l,g,S=d((I,L)=>{l=I,g=L});return ye(this,{_chunkSteps:m(I=>l({value:I,done:!1}),"_chunkSteps"),_closeSteps:m(()=>l({value:void 0,done:!0}),"_closeSteps"),_errorSteps:m(I=>g(I),"_errorSteps")}),S}releaseLock(){if(!he(this))throw fn("releaseLock");this._ownerReadableStream!==void 0&&xe(this)}};m(_e,"ReadableStreamDefaultReader");let ge=_e;Object.defineProperties(ge.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(ge.prototype.cancel,"cancel"),i(ge.prototype.read,"read"),i(ge.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ge.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function he(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_readRequests")?!1:a instanceof ge}m(he,"IsReadableStreamDefaultReader");function ye(a,l){let g=a._ownerReadableStream;g._disturbed=!0,g._state==="closed"?l._closeSteps():g._state==="errored"?l._errorSteps(g._storedError):g._readableStreamController[te](l)}m(ye,"ReadableStreamDefaultReaderRead");function xe(a){Te(a);let l=new TypeError("Reader was released");Ye(a,l)}m(xe,"ReadableStreamDefaultReaderRelease");function Ye(a,l){let g=a._readRequests;a._readRequests=new $,g.forEach(S=>{S._errorSteps(l)})}m(Ye,"ReadableStreamDefaultReaderErrorReadRequests");function fn(a){return new TypeError(`ReadableStreamDefaultReader.prototype.${a} can only be used on a ReadableStreamDefaultReader`)}m(fn,"defaultReaderBrandCheckException");let Us=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),Eo=class{constructor(l,g){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=g}next(){let l=m(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?C(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let g=m(()=>this._returnSteps(l),"returnSteps");return this._ongoingPromise?C(this._ongoingPromise,g,g):g()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,g,S,I=d((L,z)=>{g=L,S=z});return ye(l,{_chunkSteps:m(L=>{this._ongoingPromise=void 0,A(()=>g({value:L,done:!1}))},"_chunkSteps"),_closeSteps:m(()=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),g({value:void 0,done:!0})},"_closeSteps"),_errorSteps:m(L=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),S(L)},"_errorSteps")}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let g=this._reader;if(!this._preventCancel){let S=qe(g,l);return Te(g),C(S,()=>({value:l,done:!0}))}return Te(g),p({value:l,done:!0})}};m(Eo,"ReadableStreamAsyncIteratorImpl");let vt=Eo,sr={next(){return Qe(this)?this._asyncIteratorImpl.next():h(Ne("next"))},return(a){return Qe(this)?this._asyncIteratorImpl.return(a):h(Ne("return"))}};Object.setPrototypeOf(sr,Us);function ft(a,l){let g=U(a),S=new vt(g,l),I=Object.create(sr);return I._asyncIteratorImpl=S,I}m(ft,"AcquireReadableStreamAsyncIterator");function Qe(a){if(!o(a)||!Object.prototype.hasOwnProperty.call(a,"_asyncIteratorImpl"))return!1;try{return a._asyncIteratorImpl instanceof vt}catch{return!1}}m(Qe,"IsReadableStreamAsyncIterator");function Ne(a){return new TypeError(`ReadableStreamAsyncIterator.${a} can only be used on a ReadableSteamAsyncIterator`)}m(Ne,"streamAsyncIteratorBrandCheckException");let Iy=Number.isNaN||function(a){return a!==a};var Ed,vd,Ad;function vo(a){return a.slice()}m(vo,"CreateArrayFromList");function Td(a,l,g,S,I){new Uint8Array(a).set(new Uint8Array(g,S,I),l)}m(Td,"CopyDataBlockBytes");let Dn=m(a=>(typeof a.transfer=="function"?Dn=m(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Dn=m(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):Dn=m(l=>l,"TransferArrayBuffer"),Dn(a)),"TransferArrayBuffer"),ir=m(a=>(typeof a.detached=="boolean"?ir=m(l=>l.detached,"IsDetachedBuffer"):ir=m(l=>l.byteLength===0,"IsDetachedBuffer"),ir(a)),"IsDetachedBuffer");function Rd(a,l,g){if(a.slice)return a.slice(l,g);let S=g-l,I=new ArrayBuffer(S);return Td(I,0,a,l,S),I}m(Rd,"ArrayBufferSlice");function js(a,l){let g=a[l];if(g!=null){if(typeof g!="function")throw new TypeError(`${String(l)} is not a function`);return g}}m(js,"GetMethod");function Fy(a){let l={[Symbol.iterator]:()=>a.iterator},g=(async function*(){return yield*l})(),S=g.next;return{iterator:g,nextMethod:S,done:!1}}m(Fy,"CreateAsyncFromSyncIterator");let xd=(Ad=(Ed=Symbol.asyncIterator)!==null&&Ed!==void 0?Ed:(vd=Symbol.for)===null||vd===void 0?void 0:vd.call(Symbol,"Symbol.asyncIterator"))!==null&&Ad!==void 0?Ad:"@@asyncIterator";function Dd(a,l="sync",g){if(g===void 0)if(l==="async"){if(g=js(a,xd),g===void 0){let L=js(a,Symbol.iterator),z=Dd(a,"sync",L);return Fy(z)}}else g=js(a,Symbol.iterator);if(g===void 0)throw new TypeError("The object is not iterable");let S=T(g,a,[]);if(!o(S))throw new TypeError("The iterator method must return an object");let I=S.next;return{iterator:S,nextMethod:I,done:!1}}m(Dd,"GetIterator");function Ny(a){let l=T(a.nextMethod,a.iterator,[]);if(!o(l))throw new TypeError("The iterator.next() method must return an object");return l}m(Ny,"IteratorNext");function My(a){return!!a.done}m(My,"IteratorComplete");function By(a){return a.value}m(By,"IteratorValue");function Uy(a){return!(typeof a!="number"||Iy(a)||a<0)}m(Uy,"IsNonNegativeNumber");function Od(a){let l=Rd(a.buffer,a.byteOffset,a.byteOffset+a.byteLength);return new Uint8Array(l)}m(Od,"CloneAsUint8Array");function ma(a){let l=a._queue.shift();return a._queueTotalSize-=l.size,a._queueTotalSize<0&&(a._queueTotalSize=0),l.value}m(ma,"DequeueValue");function ga(a,l,g){if(!Uy(g)||g===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");a._queue.push({value:l,size:g}),a._queueTotalSize+=g}m(ga,"EnqueueValueWithSize");function jy(a){return a._queue.peek().value}m(jy,"PeekQueueValue");function On(a){a._queue=new $,a._queueTotalSize=0}m(On,"ResetQueue");function Pd(a){return a===DataView}m(Pd,"isDataViewConstructor");function Ly(a){return Pd(a.constructor)}m(Ly,"isDataView");function qy(a){return Pd(a)?1:a.BYTES_PER_ELEMENT}m(qy,"arrayBufferViewElementSize");let $y=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!ya(this))throw ka("view");return this._view}respond(l){if(!ya(this))throw ka("respond");if(R(l,1,"respond"),l=P(l,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(ir(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");zs(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!ya(this))throw ka("respondWithNewView");if(R(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(ir(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Hs(this._associatedReadableByteStreamController,l)}};m($y,"ReadableStreamBYOBRequest");let Lr=$y;Object.defineProperties(Lr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(Lr.prototype.respond,"respond"),i(Lr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Lr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let zy=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!ar(this))throw To("byobRequest");return wa(this)}get desiredSize(){if(!ar(this))throw To("desiredSize");return $d(this)}close(){if(!ar(this))throw To("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw new TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);Ao(this)}enqueue(l){if(!ar(this))throw To("enqueue");if(R(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let g=this._controlledReadableByteStream._state;if(g!=="readable")throw new TypeError(`The stream (in ${g} state) is not in the readable state and cannot be enqueued to`);$s(this,l)}error(l=void 0){if(!ar(this))throw To("error");At(this,l)}[X](l){Id(this),On(this);let g=this._cancelAlgorithm(l);return qs(this),g}[te](l){let g=this._controlledReadableByteStream;if(this._queueTotalSize>0){qd(this,l);return}let S=this._autoAllocateChunkSize;if(S!==void 0){let I;try{I=new ArrayBuffer(S)}catch(z){l._errorSteps(z);return}let L={buffer:I,bufferByteLength:S,byteOffset:0,byteLength:S,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(L)}B(g,l),cr(this)}[Z](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new $,this._pendingPullIntos.push(l)}}};m(zy,"ReadableByteStreamController");let Pn=zy;Object.defineProperties(Pn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Pn.prototype.close,"close"),i(Pn.prototype.enqueue,"enqueue"),i(Pn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function ar(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_controlledReadableByteStream")?!1:a instanceof Pn}m(ar,"IsReadableByteStreamController");function ya(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_associatedReadableByteStreamController")?!1:a instanceof Lr}m(ya,"IsReadableStreamBYOBRequest");function cr(a){if(!Vy(a))return;if(a._pulling){a._pullAgain=!0;return}a._pulling=!0;let l=a._pullAlgorithm();b(l,()=>(a._pulling=!1,a._pullAgain&&(a._pullAgain=!1,cr(a)),null),g=>(At(a,g),null))}m(cr,"ReadableByteStreamControllerCallPullIfNeeded");function Id(a){ba(a),a._pendingPullIntos=new $}m(Id,"ReadableByteStreamControllerClearPendingPullIntos");function _a(a,l){let g=!1;a._state==="closed"&&(g=!0);let S=Fd(l);l.readerType==="default"?G(a,S,g):e_(a,S,g)}m(_a,"ReadableByteStreamControllerCommitPullIntoDescriptor");function Fd(a){let l=a.bytesFilled,g=a.elementSize;return new a.viewConstructor(a.buffer,a.byteOffset,l/g)}m(Fd,"ReadableByteStreamControllerConvertPullIntoDescriptor");function Ls(a,l,g,S){a._queue.push({buffer:l,byteOffset:g,byteLength:S}),a._queueTotalSize+=S}m(Ls,"ReadableByteStreamControllerEnqueueChunkToQueue");function Nd(a,l,g,S){let I;try{I=Rd(l,g,g+S)}catch(L){throw At(a,L),L}Ls(a,I,0,S)}m(Nd,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function Md(a,l){l.bytesFilled>0&&Nd(a,l.buffer,l.byteOffset,l.bytesFilled),qr(a)}m(Md,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function Bd(a,l){let g=Math.min(a._queueTotalSize,l.byteLength-l.bytesFilled),S=l.bytesFilled+g,I=g,L=!1,z=S%l.elementSize,re=S-z;re>=l.minimumFill&&(I=re-l.bytesFilled,L=!0);let ue=a._queue;for(;I>0;){let me=ue.peek(),we=Math.min(I,me.byteLength),ke=l.byteOffset+l.bytesFilled;Td(l.buffer,ke,me.buffer,me.byteOffset,we),me.byteLength===we?ue.shift():(me.byteOffset+=we,me.byteLength-=we),a._queueTotalSize-=we,Ud(a,we,l),I-=we}return L}m(Bd,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function Ud(a,l,g){g.bytesFilled+=l}m(Ud,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function jd(a){a._queueTotalSize===0&&a._closeRequested?(qs(a),Fo(a._controlledReadableByteStream)):cr(a)}m(jd,"ReadableByteStreamControllerHandleQueueDrain");function ba(a){a._byobRequest!==null&&(a._byobRequest._associatedReadableByteStreamController=void 0,a._byobRequest._view=null,a._byobRequest=null)}m(ba,"ReadableByteStreamControllerInvalidateBYOBRequest");function Ca(a){for(;a._pendingPullIntos.length>0;){if(a._queueTotalSize===0)return;let l=a._pendingPullIntos.peek();Bd(a,l)&&(qr(a),_a(a._controlledReadableByteStream,l))}}m(Ca,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function Hy(a){let l=a._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(a._queueTotalSize===0)return;let g=l._readRequests.shift();qd(a,g)}}m(Hy,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function Wy(a,l,g,S){let I=a._controlledReadableByteStream,L=l.constructor,z=qy(L),{byteOffset:re,byteLength:ue}=l,me=g*z,we;try{we=Dn(l.buffer)}catch(Pe){S._errorSteps(Pe);return}let ke={buffer:we,bufferByteLength:we.byteLength,byteOffset:re,byteLength:ue,bytesFilled:0,minimumFill:me,elementSize:z,viewConstructor:L,readerType:"byob"};if(a._pendingPullIntos.length>0){a._pendingPullIntos.push(ke),Wd(I,S);return}if(I._state==="closed"){let Pe=new L(ke.buffer,ke.byteOffset,0);S._closeSteps(Pe);return}if(a._queueTotalSize>0){if(Bd(a,ke)){let Pe=Fd(ke);jd(a),S._chunkSteps(Pe);return}if(a._closeRequested){let Pe=new TypeError("Insufficient bytes to fill elements in the given buffer");At(a,Pe),S._errorSteps(Pe);return}}a._pendingPullIntos.push(ke),Wd(I,S),cr(a)}m(Wy,"ReadableByteStreamControllerPullInto");function Gy(a,l){l.readerType==="none"&&qr(a);let g=a._controlledReadableByteStream;if(Sa(g))for(;Gd(g)>0;){let S=qr(a);_a(g,S)}}m(Gy,"ReadableByteStreamControllerRespondInClosedState");function Jy(a,l,g){if(Ud(a,l,g),g.readerType==="none"){Md(a,g),Ca(a);return}if(g.bytesFilled<g.minimumFill)return;qr(a);let S=g.bytesFilled%g.elementSize;if(S>0){let I=g.byteOffset+g.bytesFilled;Nd(a,g.buffer,I-S,S)}g.bytesFilled-=S,_a(a._controlledReadableByteStream,g),Ca(a)}m(Jy,"ReadableByteStreamControllerRespondInReadableState");function Ld(a,l){let g=a._pendingPullIntos.peek();ba(a),a._controlledReadableByteStream._state==="closed"?Gy(a,g):Jy(a,l,g),cr(a)}m(Ld,"ReadableByteStreamControllerRespondInternal");function qr(a){return a._pendingPullIntos.shift()}m(qr,"ReadableByteStreamControllerShiftPendingPullInto");function Vy(a){let l=a._controlledReadableByteStream;return l._state!=="readable"||a._closeRequested||!a._started?!1:!!(ie(l)&&oe(l)>0||Sa(l)&&Gd(l)>0||$d(a)>0)}m(Vy,"ReadableByteStreamControllerShouldCallPull");function qs(a){a._pullAlgorithm=void 0,a._cancelAlgorithm=void 0}m(qs,"ReadableByteStreamControllerClearAlgorithms");function Ao(a){let l=a._controlledReadableByteStream;if(!(a._closeRequested||l._state!=="readable")){if(a._queueTotalSize>0){a._closeRequested=!0;return}if(a._pendingPullIntos.length>0){let g=a._pendingPullIntos.peek();if(g.bytesFilled%g.elementSize!==0){let S=new TypeError("Insufficient bytes to fill elements in the given buffer");throw At(a,S),S}}qs(a),Fo(l)}}m(Ao,"ReadableByteStreamControllerClose");function $s(a,l){let g=a._controlledReadableByteStream;if(a._closeRequested||g._state!=="readable")return;let{buffer:S,byteOffset:I,byteLength:L}=l;if(ir(S))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let z=Dn(S);if(a._pendingPullIntos.length>0){let re=a._pendingPullIntos.peek();if(ir(re.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");ba(a),re.buffer=Dn(re.buffer),re.readerType==="none"&&Md(a,re)}if(ie(g))if(Hy(a),oe(g)===0)Ls(a,z,I,L);else{a._pendingPullIntos.length>0&&qr(a);let re=new Uint8Array(z,I,L);G(g,re,!1)}else Sa(g)?(Ls(a,z,I,L),Ca(a)):Ls(a,z,I,L);cr(a)}m($s,"ReadableByteStreamControllerEnqueue");function At(a,l){let g=a._controlledReadableByteStream;g._state==="readable"&&(Id(a),On(a),qs(a),gf(g,l))}m(At,"ReadableByteStreamControllerError");function qd(a,l){let g=a._queue.shift();a._queueTotalSize-=g.byteLength,jd(a);let S=new Uint8Array(g.buffer,g.byteOffset,g.byteLength);l._chunkSteps(S)}m(qd,"ReadableByteStreamControllerFillReadRequestFromQueue");function wa(a){if(a._byobRequest===null&&a._pendingPullIntos.length>0){let l=a._pendingPullIntos.peek(),g=new Uint8Array(l.buffer,l.byteOffset+l.bytesFilled,l.byteLength-l.bytesFilled),S=Object.create(Lr.prototype);Yy(S,a,g),a._byobRequest=S}return a._byobRequest}m(wa,"ReadableByteStreamControllerGetBYOBRequest");function $d(a){let l=a._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:a._strategyHWM-a._queueTotalSize}m($d,"ReadableByteStreamControllerGetDesiredSize");function zs(a,l){let g=a._pendingPullIntos.peek();if(a._controlledReadableByteStream._state==="closed"){if(l!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(l===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(g.bytesFilled+l>g.byteLength)throw new RangeError("bytesWritten out of range")}g.buffer=Dn(g.buffer),Ld(a,l)}m(zs,"ReadableByteStreamControllerRespond");function Hs(a,l){let g=a._pendingPullIntos.peek();if(a._controlledReadableByteStream._state==="closed"){if(l.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(l.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(g.byteOffset+g.bytesFilled!==l.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(g.bufferByteLength!==l.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(g.bytesFilled+l.byteLength>g.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let S=l.byteLength;g.buffer=Dn(l.buffer),Ld(a,S)}m(Hs,"ReadableByteStreamControllerRespondWithNewView");function zd(a,l,g,S,I,L,z){l._controlledReadableByteStream=a,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,On(l),l._closeRequested=!1,l._started=!1,l._strategyHWM=L,l._pullAlgorithm=S,l._cancelAlgorithm=I,l._autoAllocateChunkSize=z,l._pendingPullIntos=new $,a._readableStreamController=l;let re=g();b(p(re),()=>(l._started=!0,cr(l),null),ue=>(At(l,ue),null))}m(zd,"SetUpReadableByteStreamController");function Ky(a,l,g){let S=Object.create(Pn.prototype),I,L,z;l.start!==void 0?I=m(()=>l.start(S),"startAlgorithm"):I=m(()=>{},"startAlgorithm"),l.pull!==void 0?L=m(()=>l.pull(S),"pullAlgorithm"):L=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?z=m(ue=>l.cancel(ue),"cancelAlgorithm"):z=m(()=>p(void 0),"cancelAlgorithm");let re=l.autoAllocateChunkSize;if(re===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");zd(a,S,I,L,z,g,re)}m(Ky,"SetUpReadableByteStreamControllerFromUnderlyingSource");function Yy(a,l,g){a._associatedReadableByteStreamController=l,a._view=g}m(Yy,"SetUpReadableStreamBYOBRequest");function ka(a){return new TypeError(`ReadableStreamBYOBRequest.prototype.${a} can only be used on a ReadableStreamBYOBRequest`)}m(ka,"byobRequestBrandCheckException");function To(a){return new TypeError(`ReadableByteStreamController.prototype.${a} can only be used on a ReadableByteStreamController`)}m(To,"byteStreamControllerBrandCheckException");function Xy(a,l){ce(a,l);let g=a?.mode;return{mode:g===void 0?void 0:Qy(g,`${l} has member 'mode' that`)}}m(Xy,"convertReaderOptions");function Qy(a,l){if(a=`${a}`,a!=="byob")throw new TypeError(`${l} '${a}' is not a valid enumeration value for ReadableStreamReaderMode`);return a}m(Qy,"convertReadableStreamReaderMode");function Zy(a,l){var g;ce(a,l);let S=(g=a?.min)!==null&&g!==void 0?g:1;return{min:P(S,`${l} has member 'min' that`)}}m(Zy,"convertByobReadOptions");function Hd(a){return new ur(a)}m(Hd,"AcquireReadableStreamBYOBReader");function Wd(a,l){a._reader._readIntoRequests.push(l)}m(Wd,"ReadableStreamAddReadIntoRequest");function e_(a,l,g){let S=a._reader._readIntoRequests.shift();g?S._closeSteps(l):S._chunkSteps(l)}m(e_,"ReadableStreamFulfillReadIntoRequest");function Gd(a){return a._reader._readIntoRequests.length}m(Gd,"ReadableStreamGetNumReadIntoRequests");function Sa(a){let l=a._reader;return!(l===void 0||!lr(l))}m(Sa,"ReadableStreamHasBYOBReader");let t_=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),Mn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!ar(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");De(this,l),this._readIntoRequests=new $}get closed(){return lr(this)?this._closedPromise:h(Ws("closed"))}cancel(l=void 0){return lr(this)?this._ownerReadableStream===void 0?h(We("cancel")):qe(this,l):h(Ws("cancel"))}read(l,g={}){if(!lr(this))return h(Ws("read"));if(!ArrayBuffer.isView(l))return h(new TypeError("view must be an array buffer view"));if(l.byteLength===0)return h(new TypeError("view must have non-zero byteLength"));if(l.buffer.byteLength===0)return h(new TypeError("view's buffer must have non-zero byteLength"));if(ir(l.buffer))return h(new TypeError("view's buffer has been detached"));let S;try{S=Zy(g,"options")}catch(ue){return h(ue)}let I=S.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(Ly(l)){if(I>l.byteLength)return h(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(I>l.length)return h(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return h(We("read from"));let L,z,re=d((ue,me)=>{L=ue,z=me});return Jd(this,l,I,{_chunkSteps:m(ue=>L({value:ue,done:!1}),"_chunkSteps"),_closeSteps:m(ue=>L({value:ue,done:!0}),"_closeSteps"),_errorSteps:m(ue=>z(ue),"_errorSteps")}),re}releaseLock(){if(!lr(this))throw Ws("releaseLock");this._ownerReadableStream!==void 0&&n_(this)}};m(t_,"ReadableStreamBYOBReader");let ur=t_;Object.defineProperties(ur.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(ur.prototype.cancel,"cancel"),i(ur.prototype.read,"read"),i(ur.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ur.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function lr(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_readIntoRequests")?!1:a instanceof ur}m(lr,"IsReadableStreamBYOBReader");function Jd(a,l,g,S){let I=a._ownerReadableStream;I._disturbed=!0,I._state==="errored"?S._errorSteps(I._storedError):Wy(I._readableStreamController,l,g,S)}m(Jd,"ReadableStreamBYOBReaderRead");function n_(a){Te(a);let l=new TypeError("Reader was released");Vd(a,l)}m(n_,"ReadableStreamBYOBReaderRelease");function Vd(a,l){let g=a._readIntoRequests;a._readIntoRequests=new $,g.forEach(S=>{S._errorSteps(l)})}m(Vd,"ReadableStreamBYOBReaderErrorReadIntoRequests");function Ws(a){return new TypeError(`ReadableStreamBYOBReader.prototype.${a} can only be used on a ReadableStreamBYOBReader`)}m(Ws,"byobReaderBrandCheckException");function Ro(a,l){let{highWaterMark:g}=a;if(g===void 0)return l;if(Iy(g)||g<0)throw new RangeError("Invalid highWaterMark");return g}m(Ro,"ExtractHighWaterMark");function Gs(a){let{size:l}=a;return l||(()=>1)}m(Gs,"ExtractSizeAlgorithm");function Js(a,l){ce(a,l);let g=a?.highWaterMark,S=a?.size;return{highWaterMark:g===void 0?void 0:D(g),size:S===void 0?void 0:r_(S,`${l} has member 'size' that`)}}m(Js,"convertQueuingStrategy");function r_(a,l){return de(a,l),g=>D(a(g))}m(r_,"convertQueuingStrategySize");function o_(a,l){ce(a,l);let g=a?.abort,S=a?.close,I=a?.start,L=a?.type,z=a?.write;return{abort:g===void 0?void 0:s_(g,a,`${l} has member 'abort' that`),close:S===void 0?void 0:i_(S,a,`${l} has member 'close' that`),start:I===void 0?void 0:a_(I,a,`${l} has member 'start' that`),write:z===void 0?void 0:c_(z,a,`${l} has member 'write' that`),type:L}}m(o_,"convertUnderlyingSink");function s_(a,l,g){return de(a,g),S=>x(a,l,[S])}m(s_,"convertUnderlyingSinkAbortCallback");function i_(a,l,g){return de(a,g),()=>x(a,l,[])}m(i_,"convertUnderlyingSinkCloseCallback");function a_(a,l,g){return de(a,g),S=>T(a,l,[S])}m(a_,"convertUnderlyingSinkStartCallback");function c_(a,l,g){return de(a,g),(S,I)=>x(a,l,[S,I])}m(c_,"convertUnderlyingSinkWriteCallback");function Kd(a,l){if(!$r(a))throw new TypeError(`${l} is not a WritableStream.`)}m(Kd,"assertWritableStream");function u_(a){if(typeof a!="object"||a===null)return!1;try{return typeof a.aborted=="boolean"}catch{return!1}}m(u_,"isAbortSignal");let eR=typeof AbortController=="function";function l_(){if(eR)return new AbortController}m(l_,"createAbortController");let d_=class{constructor(l={},g={}){l===void 0?l=null:E(l,"First parameter");let S=Js(g,"Second parameter"),I=o_(l,"First parameter");if(Xd(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let L=Gs(S),z=Ro(S,1);R_(this,I,z,L)}get locked(){if(!$r(this))throw Qs("locked");return zr(this)}abort(l=void 0){return $r(this)?zr(this)?h(new TypeError("Cannot abort a stream that already has a writer")):Vs(this,l):h(Qs("abort"))}close(){return $r(this)?zr(this)?h(new TypeError("Cannot close a stream that already has a writer")):Jt(this)?h(new TypeError("Cannot close an already-closing stream")):Qd(this):h(Qs("close"))}getWriter(){if(!$r(this))throw Qs("getWriter");return Yd(this)}};m(d_,"WritableStream");let dr=d_;Object.defineProperties(dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(dr.prototype.abort,"abort"),i(dr.prototype.close,"close"),i(dr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Yd(a){return new In(a)}m(Yd,"AcquireWritableStreamDefaultWriter");function f_(a,l,g,S,I=1,L=()=>1){let z=Object.create(dr.prototype);Xd(z);let re=Object.create(xo.prototype);return rf(z,re,a,l,g,S,I,L),z}m(f_,"CreateWritableStream");function Xd(a){a._state="writable",a._storedError=void 0,a._writer=void 0,a._writableStreamController=void 0,a._writeRequests=new $,a._inFlightWriteRequest=void 0,a._closeRequest=void 0,a._inFlightCloseRequest=void 0,a._pendingAbortRequest=void 0,a._backpressure=!1}m(Xd,"InitializeWritableStream");function $r(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_writableStreamController")?!1:a instanceof dr}m($r,"IsWritableStream");function zr(a){return a._writer!==void 0}m(zr,"IsWritableStreamLocked");function Vs(a,l){var g;if(a._state==="closed"||a._state==="errored")return p(void 0);a._writableStreamController._abortReason=l,(g=a._writableStreamController._abortController)===null||g===void 0||g.abort(l);let S=a._state;if(S==="closed"||S==="errored")return p(void 0);if(a._pendingAbortRequest!==void 0)return a._pendingAbortRequest._promise;let I=!1;S==="erroring"&&(I=!0,l=void 0);let L=d((z,re)=>{a._pendingAbortRequest={_promise:void 0,_resolve:z,_reject:re,_reason:l,_wasAlreadyErroring:I}});return a._pendingAbortRequest._promise=L,I||va(a,l),L}m(Vs,"WritableStreamAbort");function Qd(a){let l=a._state;if(l==="closed"||l==="errored")return h(new TypeError(`The stream (in ${l} state) is not in the writable state and cannot be closed`));let g=d((I,L)=>{let z={_resolve:I,_reject:L};a._closeRequest=z}),S=a._writer;return S!==void 0&&a._backpressure&&l==="writable"&&Ia(S),x_(a._writableStreamController),g}m(Qd,"WritableStreamClose");function p_(a){return d((l,g)=>{let S={_resolve:l,_reject:g};a._writeRequests.push(S)})}m(p_,"WritableStreamAddWriteRequest");function Ea(a,l){if(a._state==="writable"){va(a,l);return}Aa(a)}m(Ea,"WritableStreamDealWithRejection");function va(a,l){let g=a._writableStreamController;a._state="erroring",a._storedError=l;let S=a._writer;S!==void 0&&ef(S,l),!__(a)&&g._started&&Aa(a)}m(va,"WritableStreamStartErroring");function Aa(a){a._state="errored",a._writableStreamController[ae]();let l=a._storedError;if(a._writeRequests.forEach(I=>{I._reject(l)}),a._writeRequests=new $,a._pendingAbortRequest===void 0){Ks(a);return}let g=a._pendingAbortRequest;if(a._pendingAbortRequest=void 0,g._wasAlreadyErroring){g._reject(l),Ks(a);return}let S=a._writableStreamController[H](g._reason);b(S,()=>(g._resolve(),Ks(a),null),I=>(g._reject(I),Ks(a),null))}m(Aa,"WritableStreamFinishErroring");function h_(a){a._inFlightWriteRequest._resolve(void 0),a._inFlightWriteRequest=void 0}m(h_,"WritableStreamFinishInFlightWrite");function m_(a,l){a._inFlightWriteRequest._reject(l),a._inFlightWriteRequest=void 0,Ea(a,l)}m(m_,"WritableStreamFinishInFlightWriteWithError");function g_(a){a._inFlightCloseRequest._resolve(void 0),a._inFlightCloseRequest=void 0,a._state==="erroring"&&(a._storedError=void 0,a._pendingAbortRequest!==void 0&&(a._pendingAbortRequest._resolve(),a._pendingAbortRequest=void 0)),a._state="closed";let l=a._writer;l!==void 0&&cf(l)}m(g_,"WritableStreamFinishInFlightClose");function y_(a,l){a._inFlightCloseRequest._reject(l),a._inFlightCloseRequest=void 0,a._pendingAbortRequest!==void 0&&(a._pendingAbortRequest._reject(l),a._pendingAbortRequest=void 0),Ea(a,l)}m(y_,"WritableStreamFinishInFlightCloseWithError");function Jt(a){return!(a._closeRequest===void 0&&a._inFlightCloseRequest===void 0)}m(Jt,"WritableStreamCloseQueuedOrInFlight");function __(a){return!(a._inFlightWriteRequest===void 0&&a._inFlightCloseRequest===void 0)}m(__,"WritableStreamHasOperationMarkedInFlight");function b_(a){a._inFlightCloseRequest=a._closeRequest,a._closeRequest=void 0}m(b_,"WritableStreamMarkCloseRequestInFlight");function C_(a){a._inFlightWriteRequest=a._writeRequests.shift()}m(C_,"WritableStreamMarkFirstWriteRequestInFlight");function Ks(a){a._closeRequest!==void 0&&(a._closeRequest._reject(a._storedError),a._closeRequest=void 0);let l=a._writer;l!==void 0&&Oa(l,a._storedError)}m(Ks,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function Ta(a,l){let g=a._writer;g!==void 0&&l!==a._backpressure&&(l?M_(g):Ia(g)),a._backpressure=l}m(Ta,"WritableStreamUpdateBackpressure");let w_=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Kd(l,"First parameter"),zr(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let g=l._state;if(g==="writable")!Jt(l)&&l._backpressure?ei(this):uf(this),Zs(this);else if(g==="erroring")Pa(this,l._storedError),Zs(this);else if(g==="closed")uf(this),F_(this);else{let S=l._storedError;Pa(this,S),af(this,S)}}get closed(){return fr(this)?this._closedPromise:h(pr("closed"))}get desiredSize(){if(!fr(this))throw pr("desiredSize");if(this._ownerWritableStream===void 0)throw Oo("desiredSize");return v_(this)}get ready(){return fr(this)?this._readyPromise:h(pr("ready"))}abort(l=void 0){return fr(this)?this._ownerWritableStream===void 0?h(Oo("abort")):k_(this,l):h(pr("abort"))}close(){if(!fr(this))return h(pr("close"));let l=this._ownerWritableStream;return l===void 0?h(Oo("close")):Jt(l)?h(new TypeError("Cannot close an already-closing stream")):Zd(this)}releaseLock(){if(!fr(this))throw pr("releaseLock");this._ownerWritableStream!==void 0&&tf(this)}write(l=void 0){return fr(this)?this._ownerWritableStream===void 0?h(Oo("write to")):nf(this,l):h(pr("write"))}};m(w_,"WritableStreamDefaultWriter");let In=w_;Object.defineProperties(In.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(In.prototype.abort,"abort"),i(In.prototype.close,"close"),i(In.prototype.releaseLock,"releaseLock"),i(In.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(In.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function fr(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_ownerWritableStream")?!1:a instanceof In}m(fr,"IsWritableStreamDefaultWriter");function k_(a,l){let g=a._ownerWritableStream;return Vs(g,l)}m(k_,"WritableStreamDefaultWriterAbort");function Zd(a){let l=a._ownerWritableStream;return Qd(l)}m(Zd,"WritableStreamDefaultWriterClose");function S_(a){let l=a._ownerWritableStream,g=l._state;return Jt(l)||g==="closed"?p(void 0):g==="errored"?h(l._storedError):Zd(a)}m(S_,"WritableStreamDefaultWriterCloseWithErrorPropagation");function E_(a,l){a._closedPromiseState==="pending"?Oa(a,l):N_(a,l)}m(E_,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function ef(a,l){a._readyPromiseState==="pending"?lf(a,l):B_(a,l)}m(ef,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function v_(a){let l=a._ownerWritableStream,g=l._state;return g==="errored"||g==="erroring"?null:g==="closed"?0:of(l._writableStreamController)}m(v_,"WritableStreamDefaultWriterGetDesiredSize");function tf(a){let l=a._ownerWritableStream,g=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");ef(a,g),E_(a,g),l._writer=void 0,a._ownerWritableStream=void 0}m(tf,"WritableStreamDefaultWriterRelease");function nf(a,l){let g=a._ownerWritableStream,S=g._writableStreamController,I=D_(S,l);if(g!==a._ownerWritableStream)return h(Oo("write to"));let L=g._state;if(L==="errored")return h(g._storedError);if(Jt(g)||L==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if(L==="erroring")return h(g._storedError);let z=p_(g);return O_(S,l,I),z}m(nf,"WritableStreamDefaultWriterWrite");let A_={},T_=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ra(this))throw Da("abortReason");return this._abortReason}get signal(){if(!Ra(this))throw Da("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!Ra(this))throw Da("error");this._controlledWritableStream._state==="writable"&&sf(this,l)}[H](l){let g=this._abortAlgorithm(l);return Ys(this),g}[ae](){On(this)}};m(T_,"WritableStreamDefaultController");let xo=T_;Object.defineProperties(xo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Ra(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_controlledWritableStream")?!1:a instanceof xo}m(Ra,"IsWritableStreamDefaultController");function rf(a,l,g,S,I,L,z,re){l._controlledWritableStream=a,a._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,On(l),l._abortReason=void 0,l._abortController=l_(),l._started=!1,l._strategySizeAlgorithm=re,l._strategyHWM=z,l._writeAlgorithm=S,l._closeAlgorithm=I,l._abortAlgorithm=L;let ue=xa(l);Ta(a,ue);let me=g(),we=p(me);b(we,()=>(l._started=!0,Xs(l),null),ke=>(l._started=!0,Ea(a,ke),null))}m(rf,"SetUpWritableStreamDefaultController");function R_(a,l,g,S){let I=Object.create(xo.prototype),L,z,re,ue;l.start!==void 0?L=m(()=>l.start(I),"startAlgorithm"):L=m(()=>{},"startAlgorithm"),l.write!==void 0?z=m(me=>l.write(me,I),"writeAlgorithm"):z=m(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?re=m(()=>l.close(),"closeAlgorithm"):re=m(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?ue=m(me=>l.abort(me),"abortAlgorithm"):ue=m(()=>p(void 0),"abortAlgorithm"),rf(a,I,L,z,re,ue,g,S)}m(R_,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function Ys(a){a._writeAlgorithm=void 0,a._closeAlgorithm=void 0,a._abortAlgorithm=void 0,a._strategySizeAlgorithm=void 0}m(Ys,"WritableStreamDefaultControllerClearAlgorithms");function x_(a){ga(a,A_,0),Xs(a)}m(x_,"WritableStreamDefaultControllerClose");function D_(a,l){try{return a._strategySizeAlgorithm(l)}catch(g){return Do(a,g),1}}m(D_,"WritableStreamDefaultControllerGetChunkSize");function of(a){return a._strategyHWM-a._queueTotalSize}m(of,"WritableStreamDefaultControllerGetDesiredSize");function O_(a,l,g){try{ga(a,l,g)}catch(I){Do(a,I);return}let S=a._controlledWritableStream;if(!Jt(S)&&S._state==="writable"){let I=xa(a);Ta(S,I)}Xs(a)}m(O_,"WritableStreamDefaultControllerWrite");function Xs(a){let l=a._controlledWritableStream;if(!a._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){Aa(l);return}if(a._queue.length===0)return;let g=jy(a);g===A_?P_(a):I_(a,g)}m(Xs,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function Do(a,l){a._controlledWritableStream._state==="writable"&&sf(a,l)}m(Do,"WritableStreamDefaultControllerErrorIfNeeded");function P_(a){let l=a._controlledWritableStream;b_(l),ma(a);let g=a._closeAlgorithm();Ys(a),b(g,()=>(g_(l),null),S=>(y_(l,S),null))}m(P_,"WritableStreamDefaultControllerProcessClose");function I_(a,l){let g=a._controlledWritableStream;C_(g);let S=a._writeAlgorithm(l);b(S,()=>{h_(g);let I=g._state;if(ma(a),!Jt(g)&&I==="writable"){let L=xa(a);Ta(g,L)}return Xs(a),null},I=>(g._state==="writable"&&Ys(a),m_(g,I),null))}m(I_,"WritableStreamDefaultControllerProcessWrite");function xa(a){return of(a)<=0}m(xa,"WritableStreamDefaultControllerGetBackpressure");function sf(a,l){let g=a._controlledWritableStream;Ys(a),va(g,l)}m(sf,"WritableStreamDefaultControllerError");function Qs(a){return new TypeError(`WritableStream.prototype.${a} can only be used on a WritableStream`)}m(Qs,"streamBrandCheckException$2");function Da(a){return new TypeError(`WritableStreamDefaultController.prototype.${a} can only be used on a WritableStreamDefaultController`)}m(Da,"defaultControllerBrandCheckException$2");function pr(a){return new TypeError(`WritableStreamDefaultWriter.prototype.${a} can only be used on a WritableStreamDefaultWriter`)}m(pr,"defaultWriterBrandCheckException");function Oo(a){return new TypeError("Cannot "+a+" a stream using a released writer")}m(Oo,"defaultWriterLockException");function Zs(a){a._closedPromise=d((l,g)=>{a._closedPromise_resolve=l,a._closedPromise_reject=g,a._closedPromiseState="pending"})}m(Zs,"defaultWriterClosedPromiseInitialize");function af(a,l){Zs(a),Oa(a,l)}m(af,"defaultWriterClosedPromiseInitializeAsRejected");function F_(a){Zs(a),cf(a)}m(F_,"defaultWriterClosedPromiseInitializeAsResolved");function Oa(a,l){a._closedPromise_reject!==void 0&&(v(a._closedPromise),a._closedPromise_reject(l),a._closedPromise_resolve=void 0,a._closedPromise_reject=void 0,a._closedPromiseState="rejected")}m(Oa,"defaultWriterClosedPromiseReject");function N_(a,l){af(a,l)}m(N_,"defaultWriterClosedPromiseResetToRejected");function cf(a){a._closedPromise_resolve!==void 0&&(a._closedPromise_resolve(void 0),a._closedPromise_resolve=void 0,a._closedPromise_reject=void 0,a._closedPromiseState="resolved")}m(cf,"defaultWriterClosedPromiseResolve");function ei(a){a._readyPromise=d((l,g)=>{a._readyPromise_resolve=l,a._readyPromise_reject=g}),a._readyPromiseState="pending"}m(ei,"defaultWriterReadyPromiseInitialize");function Pa(a,l){ei(a),lf(a,l)}m(Pa,"defaultWriterReadyPromiseInitializeAsRejected");function uf(a){ei(a),Ia(a)}m(uf,"defaultWriterReadyPromiseInitializeAsResolved");function lf(a,l){a._readyPromise_reject!==void 0&&(v(a._readyPromise),a._readyPromise_reject(l),a._readyPromise_resolve=void 0,a._readyPromise_reject=void 0,a._readyPromiseState="rejected")}m(lf,"defaultWriterReadyPromiseReject");function M_(a){ei(a)}m(M_,"defaultWriterReadyPromiseReset");function B_(a,l){Pa(a,l)}m(B_,"defaultWriterReadyPromiseResetToRejected");function Ia(a){a._readyPromise_resolve!==void 0&&(a._readyPromise_resolve(void 0),a._readyPromise_resolve=void 0,a._readyPromise_reject=void 0,a._readyPromiseState="fulfilled")}m(Ia,"defaultWriterReadyPromiseResolve");function U_(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof Ip<"u")return Ip}m(U_,"getGlobals");let tR=U_();function j_(a){if(!(typeof a=="function"||typeof a=="object")||a.name!=="DOMException")return!1;try{return new a,!0}catch{return!1}}m(j_,"isDOMExceptionConstructor");function L_(){let a=tR?.DOMException;return j_(a)?a:void 0}m(L_,"getFromGlobal");function q_(){let a=m(function(l,g){this.message=l||"",this.name=g||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},"DOMException");return i(a,"DOMException"),a.prototype=Object.create(Error.prototype),Object.defineProperty(a.prototype,"constructor",{value:a,writable:!0,configurable:!0}),a}m(q_,"createPolyfill");let nR=L_()||q_();function df(a,l,g,S,I,L){let z=U(a),re=Yd(l);a._disturbed=!0;let ue=!1,me=p(void 0);return d((we,ke)=>{let Pe;if(L!==void 0){if(Pe=m(()=>{let fe=L.reason!==void 0?L.reason:new nR("Aborted","AbortError"),Ae=[];S||Ae.push(()=>l._state==="writable"?Vs(l,fe):p(void 0)),I||Ae.push(()=>a._state==="readable"?Ft(a,fe):p(void 0)),pt(()=>Promise.all(Ae.map(Oe=>Oe())),!0,fe)},"abortAlgorithm"),L.aborted){Pe();return}L.addEventListener("abort",Pe)}function yt(){return d((fe,Ae)=>{function Oe(ht){ht?fe():_(Bn(),Oe,Ae)}m(Oe,"next"),Oe(!1)})}m(yt,"pipeLoop");function Bn(){return ue?p(!0):_(re._readyPromise,()=>d((fe,Ae)=>{ye(z,{_chunkSteps:m(Oe=>{me=_(nf(re,Oe),void 0,r),fe(!1)},"_chunkSteps"),_closeSteps:m(()=>fe(!0),"_closeSteps"),_errorSteps:Ae})}))}if(m(Bn,"pipeStep"),Nt(a,z._closedPromise,fe=>(S?_t(!0,fe):pt(()=>Vs(l,fe),!0,fe),null)),Nt(l,re._closedPromise,fe=>(I?_t(!0,fe):pt(()=>Ft(a,fe),!0,fe),null)),Ze(a,z._closedPromise,()=>(g?_t():pt(()=>S_(re)),null)),Jt(l)||l._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");I?_t(!0,fe):pt(()=>Ft(a,fe),!0,fe)}v(yt());function Vt(){let fe=me;return _(me,()=>fe!==me?Vt():void 0)}m(Vt,"waitForWritesToFinish");function Nt(fe,Ae,Oe){fe._state==="errored"?Oe(fe._storedError):w(Ae,Oe)}m(Nt,"isOrBecomesErrored");function Ze(fe,Ae,Oe){fe._state==="closed"?Oe():y(Ae,Oe)}m(Ze,"isOrBecomesClosed");function pt(fe,Ae,Oe){if(ue)return;ue=!0,l._state==="writable"&&!Jt(l)?y(Vt(),ht):ht();function ht(){return b(fe(),()=>Un(Ae,Oe),yr=>Un(!0,yr)),null}m(ht,"doTheRest")}m(pt,"shutdownWithAction");function _t(fe,Ae){ue||(ue=!0,l._state==="writable"&&!Jt(l)?y(Vt(),()=>Un(fe,Ae)):Un(fe,Ae))}m(_t,"shutdown");function Un(fe,Ae){return tf(re),Te(z),L!==void 0&&L.removeEventListener("abort",Pe),fe?ke(Ae):we(void 0),null}m(Un,"finalize")})}m(df,"ReadableStreamPipeTo");let $_=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!ti(this))throw ri("desiredSize");return Fa(this)}close(){if(!ti(this))throw ri("close");if(!Wr(this))throw new TypeError("The stream is not in a state that permits close");hr(this)}enqueue(l=void 0){if(!ti(this))throw ri("enqueue");if(!Wr(this))throw new TypeError("The stream is not in a state that permits enqueue");return Hr(this,l)}error(l=void 0){if(!ti(this))throw ri("error");It(this,l)}[X](l){On(this);let g=this._cancelAlgorithm(l);return ni(this),g}[te](l){let g=this._controlledReadableStream;if(this._queue.length>0){let S=ma(this);this._closeRequested&&this._queue.length===0?(ni(this),Fo(g)):Po(this),l._chunkSteps(S)}else B(g,l),Po(this)}[Z](){}};m($_,"ReadableStreamDefaultController");let Fn=$_;Object.defineProperties(Fn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Fn.prototype.close,"close"),i(Fn.prototype.enqueue,"enqueue"),i(Fn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function ti(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_controlledReadableStream")?!1:a instanceof Fn}m(ti,"IsReadableStreamDefaultController");function Po(a){if(!ff(a))return;if(a._pulling){a._pullAgain=!0;return}a._pulling=!0;let l=a._pullAlgorithm();b(l,()=>(a._pulling=!1,a._pullAgain&&(a._pullAgain=!1,Po(a)),null),g=>(It(a,g),null))}m(Po,"ReadableStreamDefaultControllerCallPullIfNeeded");function ff(a){let l=a._controlledReadableStream;return!Wr(a)||!a._started?!1:!!(Mn(l)&&oe(l)>0||Fa(a)>0)}m(ff,"ReadableStreamDefaultControllerShouldCallPull");function ni(a){a._pullAlgorithm=void 0,a._cancelAlgorithm=void 0,a._strategySizeAlgorithm=void 0}m(ni,"ReadableStreamDefaultControllerClearAlgorithms");function hr(a){if(!Wr(a))return;let l=a._controlledReadableStream;a._closeRequested=!0,a._queue.length===0&&(ni(a),Fo(l))}m(hr,"ReadableStreamDefaultControllerClose");function Hr(a,l){if(!Wr(a))return;let g=a._controlledReadableStream;if(Mn(g)&&oe(g)>0)G(g,l,!1);else{let S;try{S=a._strategySizeAlgorithm(l)}catch(I){throw It(a,I),I}try{ga(a,l,S)}catch(I){throw It(a,I),I}}Po(a)}m(Hr,"ReadableStreamDefaultControllerEnqueue");function It(a,l){let g=a._controlledReadableStream;g._state==="readable"&&(On(a),ni(a),gf(g,l))}m(It,"ReadableStreamDefaultControllerError");function Fa(a){let l=a._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:a._strategyHWM-a._queueTotalSize}m(Fa,"ReadableStreamDefaultControllerGetDesiredSize");function z_(a){return!ff(a)}m(z_,"ReadableStreamDefaultControllerHasBackpressure");function Wr(a){let l=a._controlledReadableStream._state;return!a._closeRequested&&l==="readable"}m(Wr,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function pf(a,l,g,S,I,L,z){l._controlledReadableStream=a,l._queue=void 0,l._queueTotalSize=void 0,On(l),l._started=!1,l._closeRequested=!1,l._pullAgain=!1,l._pulling=!1,l._strategySizeAlgorithm=z,l._strategyHWM=L,l._pullAlgorithm=S,l._cancelAlgorithm=I,a._readableStreamController=l;let re=g();b(p(re),()=>(l._started=!0,Po(l),null),ue=>(It(l,ue),null))}m(pf,"SetUpReadableStreamDefaultController");function H_(a,l,g,S){let I=Object.create(Fn.prototype),L,z,re;l.start!==void 0?L=m(()=>l.start(I),"startAlgorithm"):L=m(()=>{},"startAlgorithm"),l.pull!==void 0?z=m(()=>l.pull(I),"pullAlgorithm"):z=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?re=m(ue=>l.cancel(ue),"cancelAlgorithm"):re=m(()=>p(void 0),"cancelAlgorithm"),pf(a,I,L,z,re,g,S)}m(H_,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function ri(a){return new TypeError(`ReadableStreamDefaultController.prototype.${a} can only be used on a ReadableStreamDefaultController`)}m(ri,"defaultControllerBrandCheckException$1");function W_(a,l){return ar(a._readableStreamController)?J_(a):G_(a)}m(W_,"ReadableStreamTee");function G_(a,l){let g=U(a),S=!1,I=!1,L=!1,z=!1,re,ue,me,we,ke,Pe=d(Ze=>{ke=Ze});function yt(){return S?(I=!0,p(void 0)):(S=!0,ye(g,{_chunkSteps:m(Ze=>{A(()=>{I=!1;let pt=Ze,_t=Ze;L||Hr(me._readableStreamController,pt),z||Hr(we._readableStreamController,_t),S=!1,I&&yt()})},"_chunkSteps"),_closeSteps:m(()=>{S=!1,L||hr(me._readableStreamController),z||hr(we._readableStreamController),(!L||!z)&&ke(void 0)},"_closeSteps"),_errorSteps:m(()=>{S=!1},"_errorSteps")}),p(void 0))}m(yt,"pullAlgorithm");function Bn(Ze){if(L=!0,re=Ze,z){let pt=vo([re,ue]),_t=Ft(a,pt);ke(_t)}return Pe}m(Bn,"cancel1Algorithm");function Vt(Ze){if(z=!0,ue=Ze,L){let pt=vo([re,ue]),_t=Ft(a,pt);ke(_t)}return Pe}m(Vt,"cancel2Algorithm");function Nt(){}return m(Nt,"startAlgorithm"),me=Io(Nt,yt,Bn),we=Io(Nt,yt,Vt),w(g._closedPromise,Ze=>(It(me._readableStreamController,Ze),It(we._readableStreamController,Ze),(!L||!z)&&ke(void 0),null)),[me,we]}m(G_,"ReadableStreamDefaultTee");function J_(a){let l=U(a),g=!1,S=!1,I=!1,L=!1,z=!1,re,ue,me,we,ke,Pe=d(fe=>{ke=fe});function yt(fe){w(fe._closedPromise,Ae=>(fe!==l||(At(me._readableStreamController,Ae),At(we._readableStreamController,Ae),(!L||!z)&&ke(void 0)),null))}m(yt,"forwardReaderError");function Bn(){lr(l)&&(Te(l),l=U(a),yt(l)),ye(l,{_chunkSteps:m(fe=>{A(()=>{S=!1,I=!1;let Ae=fe,Oe=fe;if(!L&&!z)try{Oe=Od(fe)}catch(ht){At(me._readableStreamController,ht),At(we._readableStreamController,ht),ke(Ft(a,ht));return}L||$s(me._readableStreamController,Ae),z||$s(we._readableStreamController,Oe),g=!1,S?Nt():I&&Ze()})},"_chunkSteps"),_closeSteps:m(()=>{g=!1,L||Ao(me._readableStreamController),z||Ao(we._readableStreamController),me._readableStreamController._pendingPullIntos.length>0&&zs(me._readableStreamController,0),we._readableStreamController._pendingPullIntos.length>0&&zs(we._readableStreamController,0),(!L||!z)&&ke(void 0)},"_closeSteps"),_errorSteps:m(()=>{g=!1},"_errorSteps")})}m(Bn,"pullWithDefaultReader");function Vt(fe,Ae){he(l)&&(Te(l),l=Hd(a),yt(l));let Oe=Ae?we:me,ht=Ae?me:we;Jd(l,fe,1,{_chunkSteps:m(yr=>{A(()=>{S=!1,I=!1;let No=Ae?z:L;if(Ae?L:z)No||Hs(Oe._readableStreamController,yr);else{let Mo;try{Mo=Od(yr)}catch(Tf){At(Oe._readableStreamController,Tf),At(ht._readableStreamController,Tf),ke(Ft(a,Tf));return}No||Hs(Oe._readableStreamController,yr),$s(ht._readableStreamController,Mo)}g=!1,S?Nt():I&&Ze()})},"_chunkSteps"),_closeSteps:m(yr=>{g=!1;let No=Ae?z:L,Mo=Ae?L:z;No||Ao(Oe._readableStreamController),Mo||Ao(ht._readableStreamController),yr!==void 0&&(No||Hs(Oe._readableStreamController,yr),!Mo&&ht._readableStreamController._pendingPullIntos.length>0&&zs(ht._readableStreamController,0)),(!No||!Mo)&&ke(void 0)},"_closeSteps"),_errorSteps:m(()=>{g=!1},"_errorSteps")})}m(Vt,"pullWithBYOBReader");function Nt(){if(g)return S=!0,p(void 0);g=!0;let fe=wa(me._readableStreamController);return fe===null?Bn():Vt(fe._view,!1),p(void 0)}m(Nt,"pull1Algorithm");function Ze(){if(g)return I=!0,p(void 0);g=!0;let fe=wa(we._readableStreamController);return fe===null?Bn():Vt(fe._view,!0),p(void 0)}m(Ze,"pull2Algorithm");function pt(fe){if(L=!0,re=fe,z){let Ae=vo([re,ue]),Oe=Ft(a,Ae);ke(Oe)}return Pe}m(pt,"cancel1Algorithm");function _t(fe){if(z=!0,ue=fe,L){let Ae=vo([re,ue]),Oe=Ft(a,Ae);ke(Oe)}return Pe}m(_t,"cancel2Algorithm");function Un(){}return m(Un,"startAlgorithm"),me=mf(Un,Nt,pt),we=mf(Un,Ze,_t),yt(l),[me,we]}m(J_,"ReadableByteStreamTee");function V_(a){return o(a)&&typeof a.getReader<"u"}m(V_,"isReadableStreamLike");function K_(a){return V_(a)?X_(a.getReader()):Y_(a)}m(K_,"ReadableStreamFrom");function Y_(a){let l,g=Dd(a,"async"),S=r;function I(){let z;try{z=Ny(g)}catch(ue){return h(ue)}let re=p(z);return C(re,ue=>{if(!o(ue))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(My(ue))hr(l._readableStreamController);else{let me=By(ue);Hr(l._readableStreamController,me)}})}m(I,"pullAlgorithm");function L(z){let re=g.iterator,ue;try{ue=js(re,"return")}catch(ke){return h(ke)}if(ue===void 0)return p(void 0);let me;try{me=T(ue,re,[z])}catch(ke){return h(ke)}let we=p(me);return C(we,ke=>{if(!o(ke))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return m(L,"cancelAlgorithm"),l=Io(S,I,L,0),l}m(Y_,"ReadableStreamFromIterable");function X_(a){let l,g=r;function S(){let L;try{L=a.read()}catch(z){return h(z)}return C(L,z=>{if(!o(z))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(z.done)hr(l._readableStreamController);else{let re=z.value;Hr(l._readableStreamController,re)}})}m(S,"pullAlgorithm");function I(L){try{return p(a.cancel(L))}catch(z){return h(z)}}return m(I,"cancelAlgorithm"),l=Io(g,S,I,0),l}m(X_,"ReadableStreamFromDefaultReader");function Q_(a,l){ce(a,l);let g=a,S=g?.autoAllocateChunkSize,I=g?.cancel,L=g?.pull,z=g?.start,re=g?.type;return{autoAllocateChunkSize:S===void 0?void 0:P(S,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:Z_(I,g,`${l} has member 'cancel' that`),pull:L===void 0?void 0:e0(L,g,`${l} has member 'pull' that`),start:z===void 0?void 0:t0(z,g,`${l} has member 'start' that`),type:re===void 0?void 0:n0(re,`${l} has member 'type' that`)}}m(Q_,"convertUnderlyingDefaultOrByteSource");function Z_(a,l,g){return de(a,g),S=>x(a,l,[S])}m(Z_,"convertUnderlyingSourceCancelCallback");function e0(a,l,g){return de(a,g),S=>x(a,l,[S])}m(e0,"convertUnderlyingSourcePullCallback");function t0(a,l,g){return de(a,g),S=>T(a,l,[S])}m(t0,"convertUnderlyingSourceStartCallback");function n0(a,l){if(a=`${a}`,a!=="bytes")throw new TypeError(`${l} '${a}' is not a valid enumeration value for ReadableStreamType`);return a}m(n0,"convertReadableStreamType");function r0(a,l){return ce(a,l),{preventCancel:!!a?.preventCancel}}m(r0,"convertIteratorOptions");function hf(a,l){ce(a,l);let g=a?.preventAbort,S=a?.preventCancel,I=a?.preventClose,L=a?.signal;return L!==void 0&&o0(L,`${l} has member 'signal' that`),{preventAbort:!!g,preventCancel:!!S,preventClose:!!I,signal:L}}m(hf,"convertPipeOptions");function o0(a,l){if(!u_(a))throw new TypeError(`${l} is not an AbortSignal.`)}m(o0,"assertAbortSignal");function s0(a,l){ce(a,l);let g=a?.readable;M(g,"readable","ReadableWritablePair"),N(g,`${l} has member 'readable' that`);let S=a?.writable;return M(S,"writable","ReadableWritablePair"),Kd(S,`${l} has member 'writable' that`),{readable:g,writable:S}}m(s0,"convertReadableWritablePair");let i0=class{constructor(l={},g={}){l===void 0?l=null:E(l,"First parameter");let S=Js(g,"Second parameter"),I=Q_(l,"First parameter");if(Na(this),I.type==="bytes"){if(S.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let L=Ro(S,0);Ky(this,I,L)}else{let L=Gs(S),z=Ro(S,1);H_(this,I,z,L)}}get locked(){if(!Nn(this))throw mr("locked");return Mn(this)}cancel(l=void 0){return Nn(this)?Mn(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):Ft(this,l):h(mr("cancel"))}getReader(l=void 0){if(!Nn(this))throw mr("getReader");return Xy(l,"First parameter").mode===void 0?U(this):Hd(this)}pipeThrough(l,g={}){if(!Nn(this))throw mr("pipeThrough");R(l,1,"pipeThrough");let S=s0(l,"First parameter"),I=hf(g,"Second parameter");if(Mn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(zr(S.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let L=df(this,S.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return v(L),S.readable}pipeTo(l,g={}){if(!Nn(this))return h(mr("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!$r(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let S;try{S=hf(g,"Second parameter")}catch(I){return h(I)}return Mn(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):zr(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):df(this,l,S.preventClose,S.preventAbort,S.preventCancel,S.signal)}tee(){if(!Nn(this))throw mr("tee");let l=W_(this);return vo(l)}values(l=void 0){if(!Nn(this))throw mr("values");let g=r0(l,"First parameter");return ft(this,g.preventCancel)}[xd](l){return this.values(l)}static from(l){return K_(l)}};m(i0,"ReadableStream");let dt=i0;Object.defineProperties(dt,{from:{enumerable:!0}}),Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(dt.from,"from"),i(dt.prototype.cancel,"cancel"),i(dt.prototype.getReader,"getReader"),i(dt.prototype.pipeThrough,"pipeThrough"),i(dt.prototype.pipeTo,"pipeTo"),i(dt.prototype.tee,"tee"),i(dt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(dt.prototype,xd,{value:dt.prototype.values,writable:!0,configurable:!0});function Io(a,l,g,S=1,I=()=>1){let L=Object.create(dt.prototype);Na(L);let z=Object.create(Fn.prototype);return pf(L,z,a,l,g,S,I),L}m(Io,"CreateReadableStream");function mf(a,l,g){let S=Object.create(dt.prototype);Na(S);let I=Object.create(Pn.prototype);return zd(S,I,a,l,g,0,void 0),S}m(mf,"CreateReadableByteStream");function Na(a){a._state="readable",a._reader=void 0,a._storedError=void 0,a._disturbed=!1}m(Na,"InitializeReadableStream");function Nn(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_readableStreamController")?!1:a instanceof dt}m(Nn,"IsReadableStream");function Mn(a){return a._reader!==void 0}m(Mn,"IsReadableStreamLocked");function Ft(a,l){if(a._disturbed=!0,a._state==="closed")return p(void 0);if(a._state==="errored")return h(a._storedError);Fo(a);let g=a._reader;if(g!==void 0&&lr(g)){let I=g._readIntoRequests;g._readIntoRequests=new $,I.forEach(L=>{L._closeSteps(void 0)})}let S=a._readableStreamController[X](l);return C(S,r)}m(Ft,"ReadableStreamCancel");function Fo(a){a._state="closed";let l=a._reader;if(l!==void 0&&(K(l),he(l))){let g=l._readRequests;l._readRequests=new $,g.forEach(S=>{S._closeSteps()})}}m(Fo,"ReadableStreamClose");function gf(a,l){a._state="errored",a._storedError=l;let g=a._reader;g!==void 0&&(le(g,l),he(g)?Ye(g,l):Vd(g,l))}m(gf,"ReadableStreamError");function mr(a){return new TypeError(`ReadableStream.prototype.${a} can only be used on a ReadableStream`)}m(mr,"streamBrandCheckException$1");function yf(a,l){ce(a,l);let g=a?.highWaterMark;return M(g,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(g)}}m(yf,"convertQueuingStrategyInit");let a0=m(a=>a.byteLength,"byteLengthSizeFunction");i(a0,"size");let c0=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=yf(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!bf(this))throw _f("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!bf(this))throw _f("size");return a0}};m(c0,"ByteLengthQueuingStrategy");let Ma=c0;Object.defineProperties(Ma.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ma.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function _f(a){return new TypeError(`ByteLengthQueuingStrategy.prototype.${a} can only be used on a ByteLengthQueuingStrategy`)}m(_f,"byteLengthBrandCheckException");function bf(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_byteLengthQueuingStrategyHighWaterMark")?!1:a instanceof Ma}m(bf,"IsByteLengthQueuingStrategy");let u0=m(()=>1,"countSizeFunction");i(u0,"size");let l0=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=yf(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!wf(this))throw Cf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!wf(this))throw Cf("size");return u0}};m(l0,"CountQueuingStrategy");let Ba=l0;Object.defineProperties(Ba.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ba.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Cf(a){return new TypeError(`CountQueuingStrategy.prototype.${a} can only be used on a CountQueuingStrategy`)}m(Cf,"countBrandCheckException");function wf(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_countQueuingStrategyHighWaterMark")?!1:a instanceof Ba}m(wf,"IsCountQueuingStrategy");function d0(a,l){ce(a,l);let g=a?.cancel,S=a?.flush,I=a?.readableType,L=a?.start,z=a?.transform,re=a?.writableType;return{cancel:g===void 0?void 0:m0(g,a,`${l} has member 'cancel' that`),flush:S===void 0?void 0:f0(S,a,`${l} has member 'flush' that`),readableType:I,start:L===void 0?void 0:p0(L,a,`${l} has member 'start' that`),transform:z===void 0?void 0:h0(z,a,`${l} has member 'transform' that`),writableType:re}}m(d0,"convertTransformer");function f0(a,l,g){return de(a,g),S=>x(a,l,[S])}m(f0,"convertTransformerFlushCallback");function p0(a,l,g){return de(a,g),S=>T(a,l,[S])}m(p0,"convertTransformerStartCallback");function h0(a,l,g){return de(a,g),(S,I)=>x(a,l,[S,I])}m(h0,"convertTransformerTransformCallback");function m0(a,l,g){return de(a,g),S=>x(a,l,[S])}m(m0,"convertTransformerCancelCallback");let g0=class{constructor(l={},g={},S={}){l===void 0&&(l=null);let I=Js(g,"Second parameter"),L=Js(S,"Third parameter"),z=d0(l,"First parameter");if(z.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(z.writableType!==void 0)throw new RangeError("Invalid writableType specified");let re=Ro(L,0),ue=Gs(L),me=Ro(I,1),we=Gs(I),ke,Pe=d(yt=>{ke=yt});y0(this,Pe,me,we,re,ue),C0(this,z),z.start!==void 0?ke(z.start(this._transformStreamController)):ke(void 0)}get readable(){if(!kf(this))throw Af("readable");return this._readable}get writable(){if(!kf(this))throw Af("writable");return this._writable}};m(g0,"TransformStream");let Ua=g0;Object.defineProperties(Ua.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ua.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function y0(a,l,g,S,I,L){function z(){return l}m(z,"startAlgorithm");function re(Pe){return S0(a,Pe)}m(re,"writeAlgorithm");function ue(Pe){return E0(a,Pe)}m(ue,"abortAlgorithm");function me(){return v0(a)}m(me,"closeAlgorithm"),a._writable=f_(z,re,me,ue,g,S);function we(){return A0(a)}m(we,"pullAlgorithm");function ke(Pe){return T0(a,Pe)}m(ke,"cancelAlgorithm"),a._readable=Io(z,we,ke,I,L),a._backpressure=void 0,a._backpressureChangePromise=void 0,a._backpressureChangePromise_resolve=void 0,oi(a,!0),a._transformStreamController=void 0}m(y0,"InitializeTransformStream");function kf(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_transformStreamController")?!1:a instanceof Ua}m(kf,"IsTransformStream");function Sf(a,l){It(a._readable._readableStreamController,l),ja(a,l)}m(Sf,"TransformStreamError");function ja(a,l){ii(a._transformStreamController),Do(a._writable._writableStreamController,l),La(a)}m(ja,"TransformStreamErrorWritableAndUnblockWrite");function La(a){a._backpressure&&oi(a,!1)}m(La,"TransformStreamUnblockWrite");function oi(a,l){a._backpressureChangePromise!==void 0&&a._backpressureChangePromise_resolve(),a._backpressureChangePromise=d(g=>{a._backpressureChangePromise_resolve=g}),a._backpressure=l}m(oi,"TransformStreamSetBackpressure");let _0=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!si(this))throw ai("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return Fa(l)}enqueue(l=void 0){if(!si(this))throw ai("enqueue");Ef(this,l)}error(l=void 0){if(!si(this))throw ai("error");w0(this,l)}terminate(){if(!si(this))throw ai("terminate");k0(this)}};m(_0,"TransformStreamDefaultController");let gr=_0;Object.defineProperties(gr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(gr.prototype.enqueue,"enqueue"),i(gr.prototype.error,"error"),i(gr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function si(a){return!o(a)||!Object.prototype.hasOwnProperty.call(a,"_controlledTransformStream")?!1:a instanceof gr}m(si,"IsTransformStreamDefaultController");function b0(a,l,g,S,I){l._controlledTransformStream=a,a._transformStreamController=l,l._transformAlgorithm=g,l._flushAlgorithm=S,l._cancelAlgorithm=I,l._finishPromise=void 0,l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}m(b0,"SetUpTransformStreamDefaultController");function C0(a,l){let g=Object.create(gr.prototype),S,I,L;l.transform!==void 0?S=m(z=>l.transform(z,g),"transformAlgorithm"):S=m(z=>{try{return Ef(g,z),p(void 0)}catch(re){return h(re)}},"transformAlgorithm"),l.flush!==void 0?I=m(()=>l.flush(g),"flushAlgorithm"):I=m(()=>p(void 0),"flushAlgorithm"),l.cancel!==void 0?L=m(z=>l.cancel(z),"cancelAlgorithm"):L=m(()=>p(void 0),"cancelAlgorithm"),b0(a,g,S,I,L)}m(C0,"SetUpTransformStreamDefaultControllerFromTransformer");function ii(a){a._transformAlgorithm=void 0,a._flushAlgorithm=void 0,a._cancelAlgorithm=void 0}m(ii,"TransformStreamDefaultControllerClearAlgorithms");function Ef(a,l){let g=a._controlledTransformStream,S=g._readable._readableStreamController;if(!Wr(S))throw new TypeError("Readable side is not in a state that permits enqueue");try{Hr(S,l)}catch(I){throw ja(g,I),g._readable._storedError}z_(S)!==g._backpressure&&oi(g,!0)}m(Ef,"TransformStreamDefaultControllerEnqueue");function w0(a,l){Sf(a._controlledTransformStream,l)}m(w0,"TransformStreamDefaultControllerError");function vf(a,l){let g=a._transformAlgorithm(l);return C(g,void 0,S=>{throw Sf(a._controlledTransformStream,S),S})}m(vf,"TransformStreamDefaultControllerPerformTransform");function k0(a){let l=a._controlledTransformStream,g=l._readable._readableStreamController;hr(g);let S=new TypeError("TransformStream terminated");ja(l,S)}m(k0,"TransformStreamDefaultControllerTerminate");function S0(a,l){let g=a._transformStreamController;if(a._backpressure){let S=a._backpressureChangePromise;return C(S,()=>{let I=a._writable;if(I._state==="erroring")throw I._storedError;return vf(g,l)})}return vf(g,l)}m(S0,"TransformStreamDefaultSinkWriteAlgorithm");function E0(a,l){let g=a._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let S=a._readable;g._finishPromise=d((L,z)=>{g._finishPromise_resolve=L,g._finishPromise_reject=z});let I=g._cancelAlgorithm(l);return ii(g),b(I,()=>(S._state==="errored"?Gr(g,S._storedError):(It(S._readableStreamController,l),qa(g)),null),L=>(It(S._readableStreamController,L),Gr(g,L),null)),g._finishPromise}m(E0,"TransformStreamDefaultSinkAbortAlgorithm");function v0(a){let l=a._transformStreamController;if(l._finishPromise!==void 0)return l._finishPromise;let g=a._readable;l._finishPromise=d((I,L)=>{l._finishPromise_resolve=I,l._finishPromise_reject=L});let S=l._flushAlgorithm();return ii(l),b(S,()=>(g._state==="errored"?Gr(l,g._storedError):(hr(g._readableStreamController),qa(l)),null),I=>(It(g._readableStreamController,I),Gr(l,I),null)),l._finishPromise}m(v0,"TransformStreamDefaultSinkCloseAlgorithm");function A0(a){return oi(a,!1),a._backpressureChangePromise}m(A0,"TransformStreamDefaultSourcePullAlgorithm");function T0(a,l){let g=a._transformStreamController;if(g._finishPromise!==void 0)return g._finishPromise;let S=a._writable;g._finishPromise=d((L,z)=>{g._finishPromise_resolve=L,g._finishPromise_reject=z});let I=g._cancelAlgorithm(l);return ii(g),b(I,()=>(S._state==="errored"?Gr(g,S._storedError):(Do(S._writableStreamController,l),La(a),qa(g)),null),L=>(Do(S._writableStreamController,L),La(a),Gr(g,L),null)),g._finishPromise}m(T0,"TransformStreamDefaultSourceCancelAlgorithm");function ai(a){return new TypeError(`TransformStreamDefaultController.prototype.${a} can only be used on a TransformStreamDefaultController`)}m(ai,"defaultControllerBrandCheckException");function qa(a){a._finishPromise_resolve!==void 0&&(a._finishPromise_resolve(),a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0)}m(qa,"defaultControllerFinishPromiseResolve");function Gr(a,l){a._finishPromise_reject!==void 0&&(v(a._finishPromise),a._finishPromise_reject(l),a._finishPromise_resolve=void 0,a._finishPromise_reject=void 0)}m(Gr,"defaultControllerFinishPromiseReject");function Af(a){return new TypeError(`TransformStream.prototype.${a} can only be used on a TransformStream`)}m(Af,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=Ma,n.CountQueuingStrategy=Ba,n.ReadableByteStreamController=Pn,n.ReadableStream=dt,n.ReadableStreamBYOBReader=ur,n.ReadableStreamBYOBRequest=Lr,n.ReadableStreamDefaultController=Fn,n.ReadableStreamDefaultReader=ge,n.TransformStream=Ua,n.TransformStreamDefaultController=gr,n.WritableStream=dr,n.WritableStreamDefaultController=xo,n.WritableStreamDefaultWriter=In})})(Yc,Yc.exports)),Yc.exports}function Mw(){if(Nw)return Iw;Nw=1;let t=65536;if(!globalThis.ReadableStream)try{let e=require("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,Yw())}try{let{Blob:e}=require("buffer");e&&!e.prototype.stream&&(e.prototype.stream=m(function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let i=await o.slice(r,Math.min(o.size,r+t)).arrayBuffer();r+=i.byteLength,s.enqueue(new Uint8Array(i)),r===o.size&&s.close()}})},"name"))}catch{}return Iw}async function*Xc(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,Bw),i=n.buffer.slice(r,r+s);r+=i.byteLength,yield new Uint8Array(i)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let s=await o.slice(r,Math.min(o.size,r+Bw)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function Qw(t,e=lo){var n=`${Uw()}${Uw()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
57
+ Content-Disposition: form-data; name="`;return t.forEach((s,i)=>typeof s=="string"?r.push(o+jp(i)+`"\r
29
58
  \r
30
59
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
31
60
  `)}\r
32
- `):r.push(o+Af(a)+`"; filename="${Af(s.name,1)}"\r
61
+ `):r.push(o+jp(i)+`"; filename="${jp(s.name,1)}"\r
33
62
  Content-Type: ${s.type||"application/octet-stream"}\r
34
63
  \r
35
64
  `,s,`\r
36
- `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function lc(t){if(t[kt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[kt].disturbed=!0,t[kt].error)throw t[kt].error;let{body:e}=t;if(e===null)return at.Buffer.alloc(0);if(!(e instanceof Ge.default))return at.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new qt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof _c?o:new qt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?at.Buffer.from(n.join("")):at.Buffer.concat(n,r)}catch(o){throw new qt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new qt(`Premature close of server response while trying to fetch ${t.url}`)}function lb(t=[]){return new $n(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return dc(e),vf(e,String(n)),!0}catch{return!1}}))}function Tf(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function hb(t){if(!fb.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function pb(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,X0.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function Yr(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:pb(t)}function gb(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Tf(o),a=Tf(o,!0);s.toString().length>4096&&(s=a),e&&(s=e(s)),n&&(a=n(a));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return a;case"unsafe-url":return s;case"strict-origin":return Yr(s)&&!Yr(c)?"no-referrer":a.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:Yr(s)&&!Yr(c)?"no-referrer":a;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:a;case"no-referrer-when-downgrade":return Yr(s)&&!Yr(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function mb(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&fb.has(r)&&(n=r);return n}function wb(){if(H0)return Ef;if(H0=1,!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}return Ef=globalThis.DOMException,Ef}async function jf(t,e){return new Promise((n,r)=>{let o=new si(t,e),{parsedURL:s,options:a}=ST(o);if(!vT.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let y=Z0(o.url),w=new pn(y,{headers:{"Content-Type":y.typeFull}});n(w);return}let c=(s.protocol==="https:"?K0.default:Uo.default).request,{signal:l}=o,f=null,d=p(()=>{let y=new Nf("The operation was aborted.");r(y),o.body&&o.body instanceof Ge.default.Readable&&o.body.destroy(y),!(!f||!f.body)&&f.body.emit("error",y)},"abort");if(l&&l.aborted){d();return}let h=p(()=>{d(),S()},"abortAndFinalize"),m=c(s.toString(),a);l&&l.addEventListener("abort",h);let S=p(()=>{m.abort(),l&&l.removeEventListener("abort",h)},"finalize");m.on("error",y=>{r(new qt(`request to ${o.url} failed, reason: ${y.message}`,"system",y)),S()}),xb(m,y=>{f&&f.body&&f.body.destroy(y)}),process.version<"v14"&&m.on("socket",y=>{let w;y.prependListener("end",()=>{w=y._eventsCount}),y.prependListener("close",b=>{if(f&&w<y._eventsCount&&!b){let _=new Error("Premature close");_.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",_)}})}),m.on("response",y=>{m.setTimeout(0);let w=lb(y.rawHeaders);if(bc(y.statusCode)){let v=w.get("Location"),x=null;try{x=v===null?null:new URL(v,o.url)}catch{if(o.redirect!=="manual"){r(new qt(`uri requested responds with an invalid redirect URL: ${v}`,"invalid-redirect")),S();return}}switch(o.redirect){case"error":r(new qt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),S();return;case"manual":break;case"follow":{if(x===null)break;if(o.counter>=o.follow){r(new qt(`maximum redirect reached at: ${o.url}`,"max-redirect")),S();return}let R={headers:new $n(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:If(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!hT(o.url,x)||!pT(o.url,x))for(let W of["authorization","www-authenticate","cookie","cookie2"])R.headers.delete(W);if(y.statusCode!==303&&o.body&&e.body instanceof Ge.default.Readable){r(new qt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),S();return}(y.statusCode===303||(y.statusCode===301||y.statusCode===302)&&o.method==="POST")&&(R.method="GET",R.body=void 0,R.headers.delete("content-length"));let j=mb(w);j&&(R.referrerPolicy=j),n(jf(new si(x,R))),S();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}l&&y.once("end",()=>{l.removeEventListener("abort",h)});let b=(0,Ge.pipeline)(y,new Ge.PassThrough,v=>{v&&r(v)});process.version<"v12.10"&&y.on("aborted",h);let _={url:o.url,status:y.statusCode,statusText:y.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},D=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||D===null||y.statusCode===204||y.statusCode===304){f=new pn(b,_),n(f);return}let k={flush:Kr.default.Z_SYNC_FLUSH,finishFlush:Kr.default.Z_SYNC_FLUSH};if(D==="gzip"||D==="x-gzip"){b=(0,Ge.pipeline)(b,Kr.default.createGunzip(k),v=>{v&&r(v)}),f=new pn(b,_),n(f);return}if(D==="deflate"||D==="x-deflate"){let v=(0,Ge.pipeline)(y,new Ge.PassThrough,x=>{x&&r(x)});v.once("data",x=>{(x[0]&15)===8?b=(0,Ge.pipeline)(b,Kr.default.createInflate(),R=>{R&&r(R)}):b=(0,Ge.pipeline)(b,Kr.default.createInflateRaw(),R=>{R&&r(R)}),f=new pn(b,_),n(f)}),v.once("end",()=>{f||(f=new pn(b,_),n(f))});return}if(D==="br"){b=(0,Ge.pipeline)(b,Kr.default.createBrotliDecompress(),v=>{v&&r(v)}),f=new pn(b,_),n(f);return}f=new pn(b,_),n(f)}),_T(m,o).catch(r)})}function xb(t,e){let n=at.Buffer.from(`0\r
65
+ `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function Qc(t){if(t[St].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[St].disturbed=!0,t[St].error)throw t[St].error;let{body:e}=t;if(e===null)return ut.Buffer.alloc(0);if(!(e instanceof He.default))return ut.Buffer.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new jt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof iu?o:new jt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?ut.Buffer.from(n.join("")):ut.Buffer.concat(n,r)}catch(o){throw new jt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new jt(`Premature close of server response while trying to fetch ${t.url}`)}function ik(t=[]){return new Jn(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return Zc(e),qp(e,String(n)),!0}catch{return!1}}))}function $p(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function uk(t){if(!ck.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function lk(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,Jw.isIP)(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function co(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:lk(t)}function dk(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=$p(o),i=$p(o,!0);s.toString().length>4096&&(s=i),e&&(s=e(s)),n&&(i=n(i));let c=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return s;case"strict-origin":return co(s)&&!co(c)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===c.origin?s:co(s)&&!co(c)?"no-referrer":i;case"same-origin":return s.origin===c.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===c.origin?s:i;case"no-referrer-when-downgrade":return co(s)&&!co(c)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function fk(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&ck.has(r)&&(n=r);return n}function gk(){if(Lw)return Lp;if(Lw=1,!globalThis.DOMException)try{let{MessageChannel:t}=require("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}return Lp=globalThis.DOMException,Lp}async function Qp(t,e){return new Promise((n,r)=>{let o=new Ii(t,e),{parsedURL:s,options:i}=QO(o);if(!t1.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let b=Kw(o.url),y=new _n(b,{headers:{"Content-Type":b.typeFull}});n(y);return}let c=(s.protocol==="https:"?Ww.default:ts.default).request,{signal:u}=o,f=null,d=m(()=>{let b=new Yp("The operation was aborted.");r(b),o.body&&o.body instanceof He.default.Readable&&o.body.destroy(b),!(!f||!f.body)&&f.body.emit("error",b)},"abort");if(u&&u.aborted){d();return}let p=m(()=>{d(),_()},"abortAndFinalize"),h=c(s.toString(),i);u&&u.addEventListener("abort",p);let _=m(()=>{h.abort(),u&&u.removeEventListener("abort",p)},"finalize");h.on("error",b=>{r(new jt(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),_()}),Ak(h,b=>{f&&f.body&&f.body.destroy(b)}),process.version<"v14"&&h.on("socket",b=>{let y;b.prependListener("end",()=>{y=b._eventsCount}),b.prependListener("close",w=>{if(f&&y<b._eventsCount&&!w){let C=new Error("Premature close");C.code="ERR_STREAM_PREMATURE_CLOSE",f.body.emit("error",C)}})}),h.on("response",b=>{h.setTimeout(0);let y=ik(b.rawHeaders);if(au(b.statusCode)){let T=y.get("Location"),x=null;try{x=T===null?null:new URL(T,o.url)}catch{if(o.redirect!=="manual"){r(new jt(`uri requested responds with an invalid redirect URL: ${T}`,"invalid-redirect")),_();return}}switch(o.redirect){case"error":r(new jt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),_();return;case"manual":break;case"follow":{if(x===null)break;if(o.counter>=o.follow){r(new jt(`maximum redirect reached at: ${o.url}`,"max-redirect")),_();return}let O={headers:new Jn(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Kp(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!$O(o.url,x)||!zO(o.url,x))for(let $ of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete($);if(b.statusCode!==303&&o.body&&e.body instanceof He.default.Readable){r(new jt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),_();return}(b.statusCode===303||(b.statusCode===301||b.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=fk(y);q&&(O.referrerPolicy=q),n(Qp(new Ii(x,O))),_();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}u&&b.once("end",()=>{u.removeEventListener("abort",p)});let w=(0,He.pipeline)(b,new He.PassThrough,T=>{T&&r(T)});process.version<"v12.10"&&b.on("aborted",p);let C={url:o.url,status:b.statusCode,statusText:b.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},v=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||v===null||b.statusCode===204||b.statusCode===304){f=new _n(w,C),n(f);return}let A={flush:ao.default.Z_SYNC_FLUSH,finishFlush:ao.default.Z_SYNC_FLUSH};if(v==="gzip"||v==="x-gzip"){w=(0,He.pipeline)(w,ao.default.createGunzip(A),T=>{T&&r(T)}),f=new _n(w,C),n(f);return}if(v==="deflate"||v==="x-deflate"){let T=(0,He.pipeline)(b,new He.PassThrough,x=>{x&&r(x)});T.once("data",x=>{(x[0]&15)===8?w=(0,He.pipeline)(w,ao.default.createInflate(),O=>{O&&r(O)}):w=(0,He.pipeline)(w,ao.default.createInflateRaw(),O=>{O&&r(O)}),f=new _n(w,C),n(f)}),T.once("end",()=>{f||(f=new _n(w,C),n(f))});return}if(v==="br"){w=(0,He.pipeline)(w,ao.default.createBrotliDecompress(),T=>{T&&r(T)}),f=new _n(w,C),n(f);return}f=new _n(w,C),n(f)}),JO(h,o).catch(r)})}function Ak(t,e){let n=ut.Buffer.from(`0\r
37
66
  \r
38
- `),r=!1,o=!1,s;t.on("response",a=>{let{headers:c}=a;r=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",a=>{let c=p(()=>{if(r&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},"onSocketClose"),l=p(f=>{o=at.Buffer.compare(f.slice(-5),n)===0,!o&&s&&(o=at.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&at.Buffer.compare(f.slice(-2),n.slice(3))===0),s=f},"onData");a.prependListener("close",c),a.on("data",l),t.on("close",()=>{a.removeListener("close",c),a.removeListener("data",l)})})}function Ue(t){let e=Ob.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function Df(t){if(t.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",t.passiveListener);return}t.event.cancelable&&(t.canceled=!0,typeof t.event.preventDefault=="function"&&t.event.preventDefault())}function Xr(t,e){Ob.set(this,{eventTarget:t,event:e,eventPhase:2,currentTarget:t,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:e.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let n=Object.keys(e);for(let r=0;r<n.length;++r){let o=n[r];o in this||Object.defineProperty(this,o,Mf(o))}}function Mf(t){return{get(){return Ue(this).event[t]},set(e){Ue(this).event[t]=e},configurable:!0,enumerable:!0}}function Fb(t){return{value(){let e=Ue(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function Pb(t,e){let n=Object.keys(e);if(n.length===0)return t;function r(o,s){t.call(this,o,s)}p(r,"CustomEvent"),r.prototype=Object.create(t.prototype,{constructor:{value:r,configurable:!0,writable:!0}});for(let o=0;o<n.length;++o){let s=n[o];if(!(s in t.prototype)){let a=typeof Object.getOwnPropertyDescriptor(e,s).value=="function";Object.defineProperty(r.prototype,s,a?Fb(s):Mf(s))}}return r}function Uf(t){if(t==null||t===Object.prototype)return Xr;let e=Rf.get(t);return e==null&&(e=Pb(Uf(Object.getPrototypeOf(t)),t),Rf.set(t,e)),e}function Ib(t,e){let n=Uf(Object.getPrototypeOf(e));return new n(t,e)}function Nb(t){return Ue(t).immediateStopped}function Bb(t,e){Ue(t).eventPhase=e}function jb(t,e){Ue(t).currentTarget=e}function xf(t,e){Ue(t).passiveListener=e}function oi(t){return t!==null&&typeof t=="object"}function Mo(t){let e=Mb.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function Ub(t){return{get(){let e=Mo(this).get(t);for(;e!=null;){if(e.listenerType===fc)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!oi(e)&&(e=null);let n=Mo(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===fc?r!==null?r.next=o.next:o.next!==null?n.set(t,o.next):n.delete(t):r=o,o=o.next;if(e!==null){let s={listener:e,listenerType:fc,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function Lf(t,e){Object.defineProperty(t,`on${e}`,Ub(e))}function Of(t){function e(){gn.call(this)}p(e,"CustomEventTarget"),e.prototype=Object.create(gn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)Lf(e.prototype,t[n]);return e}function gn(){if(this instanceof gn){Mb.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return Of(arguments[0]);if(arguments.length>0){let t=new Array(arguments.length);for(let e=0;e<arguments.length;++e)t[e]=arguments[e];return Of(t)}throw new TypeError("Cannot call a class as a function")}function qb(){let t=Object.create(gc.prototype);return gn.call(t),mc.set(t,!1),t}function $b(t){mc.get(t)===!1&&(mc.set(t,!0),t.dispatchEvent({type:"abort"}))}function Ff(t){let e=zb.get(t);if(e==null)throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${t===null?"null":typeof t}`);return e}function Pf(){!globalThis.process?.versions?.node&&!globalThis.process?.env?.DISABLE_NODE_FETCH_NATIVE_WARN&&console.warn("[node-fetch-native] Node.js compatible build of `node-fetch-native` is being used in a non-Node.js environment. Please make sure you are using proper export conditions or report this issue to https://github.com/unjs/node-fetch-native. You can set `process.env.DISABLE_NODE_FETCH_NATIVE_WARN` to disable this warning.")}var Uo,K0,Kr,Ge,at,$t,Y0,X0,Zr,Q0,iT,J0,p,V0,We,qn,tn,_r,sc,No,wf,Zs,ic,ac,Cf,Zt,kf,Bo,jo,Sf,j0,cc,aT,M0,U0,q0,tb,Qr,cT,Io,ni,uT,lT,$0,dT,z0,Af,Vr,Jr,rb,_c,ob,qt,hc,sb,pc,fT,hT,pT,gT,kt,ib,ri,If,mT,ab,yT,_T,dc,vf,cb,$n,bT,bc,en,db,pn,wT,fb,CT,ot,ei,kT,yb,si,ST,bb,Nf,Ef,H0,AT,ET,Bf,Cb,kb,Sb,Ab,Eb,vb,Tb,Db,vT,Ob,Rf,Mb,W0,G0,fc,Lb,gc,mc,yc,zb,TT,RT,Hb,oc=fr(()=>{Uo=st(require("node:http"),1),K0=st(require("node:https"),1),Kr=st(require("node:zlib"),1),Ge=st(require("node:stream"),1),at=require("node:buffer"),$t=require("node:util");tc();Y0=require("node:url"),X0=require("node:net"),Zr=require("node:fs"),Q0=require("node:path"),iT=Object.defineProperty,J0=t=>{throw TypeError(t)},p=(t,e)=>iT(t,"name",{value:e,configurable:!0}),V0=(t,e,n)=>e.has(t)||J0("Cannot "+n),We=(t,e,n)=>(V0(t,e,"read from private field"),n?n.call(t):e.get(t)),qn=(t,e,n)=>e.has(t)?J0("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),tn=(t,e,n,r)=>(V0(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);p(Z0,"dataUriToBuffer");j0={},cc={exports:{}};aT=cc.exports;p(eb,"requirePonyfill_es2018");p(L0,"requireStreams"),L0();q0=65536;p(uc,"toIterator");tb=(Zs=class{constructor(t=[],e={}){if(qn(this,_r,[]),qn(this,sc,""),qn(this,No,0),qn(this,wf,"transparent"),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof e!="object"&&typeof e!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");e===null&&(e={});let n=new TextEncoder;for(let o of t){let s;ArrayBuffer.isView(o)?s=new Uint8Array(o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)):o instanceof ArrayBuffer?s=new Uint8Array(o.slice(0)):o instanceof Zs?s=o:s=n.encode(`${o}`),tn(this,No,We(this,No)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),We(this,_r).push(s)}tn(this,wf,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);tn(this,sc,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return We(this,No)}get type(){return We(this,sc)}async text(){let t=new TextDecoder,e="";for await(let n of uc(We(this,_r),!1))e+=t.decode(n,{stream:!0});return e+=t.decode(),e}async arrayBuffer(){let t=new Uint8Array(this.size),e=0;for await(let n of uc(We(this,_r),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=uc(We(this,_r),!0);return new globalThis.ReadableStream({type:"bytes",async pull(e){let n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,e=this.size,n=""){let{size:r}=this,o=t<0?Math.max(r+t,0):Math.min(t,r),s=e<0?Math.max(r+e,0):Math.min(e,r),a=Math.max(s-o,0),c=We(this,_r),l=[],f=0;for(let h of c){if(f>=a)break;let m=ArrayBuffer.isView(h)?h.byteLength:h.size;if(o&&m<=o)o-=m,s-=m;else{let S;ArrayBuffer.isView(h)?(S=h.subarray(o,Math.min(m,s)),f+=S.byteLength):(S=h.slice(o,Math.min(m,s)),f+=S.size),s-=m,l.push(S),o=0}}let d=new Zs([],{type:String(n).toLowerCase()});return tn(d,No,a),tn(d,_r,l),d}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t=="object"&&typeof t.constructor=="function"&&(typeof t.stream=="function"||typeof t.arrayBuffer=="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}},_r=new WeakMap,sc=new WeakMap,No=new WeakMap,wf=new WeakMap,p(Zs,"Blob"),Zs);Object.defineProperties(tb.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Qr=tb,cT=(Cf=class extends Qr{constructor(t,e,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n),qn(this,ic,0),qn(this,ac,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||tn(this,ic,r),tn(this,ac,String(e))}get name(){return We(this,ac)}get lastModified(){return We(this,ic)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Qr&&/^(File)$/.test(t[Symbol.toStringTag])}},ic=new WeakMap,ac=new WeakMap,p(Cf,"File"),Cf),Io=cT;({toStringTag:ni,iterator:uT,hasInstance:lT}=Symbol),$0=Math.random,dT="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),z0=p((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[ni])?[(n=n!==void 0?n+"":e[ni]=="File"?e.name:"blob",t),e.name!==n||e[ni]=="blob"?new Io([e],n,e):e]:[t,e+""]),"f"),Af=p((t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
39
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),Vr=p((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),Jr=(kf=class{constructor(...t){if(qn(this,Zt,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ni](){return"FormData"}[uT](){return this.entries()}static[lT](t){return t&&typeof t=="object"&&t[ni]==="FormData"&&!dT.some(e=>typeof t[e]!="function")}append(...t){Vr("append",arguments,2),We(this,Zt).push(z0(...t))}delete(t){Vr("delete",arguments,1),t+="",tn(this,Zt,We(this,Zt).filter(([e])=>e!==t))}get(t){Vr("get",arguments,1),t+="";for(var e=We(this,Zt),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return Vr("getAll",arguments,1),e=[],t+="",We(this,Zt).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return Vr("has",arguments,1),t+="",We(this,Zt).some(e=>e[0]===t)}forEach(t,e){Vr("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){Vr("set",arguments,2);var e=[],n=!0;t=z0(...t),We(this,Zt).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),tn(this,Zt,e)}*entries(){yield*We(this,Zt)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},Zt=new WeakMap,p(kf,"FormData"),kf);p(nb,"formDataToBlob");rb=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};p(rb,"FetchBaseError");_c=rb,ob=class extends _c{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};p(ob,"FetchError");qt=ob,hc=Symbol.toStringTag,sb=p(t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[hc]==="URLSearchParams","isURLSearchParameters"),pc=p(t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[hc]),"isBlob"),fT=p(t=>typeof t=="object"&&(t[hc]==="AbortSignal"||t[hc]==="EventTarget"),"isAbortSignal"),hT=p((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),pT=p((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),gT=(0,$t.promisify)(Ge.default.pipeline),kt=Symbol("Body internals"),ib=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:sb(e)?e=at.Buffer.from(e.toString()):pc(e)||at.Buffer.isBuffer(e)||($t.types.isAnyArrayBuffer(e)?e=at.Buffer.from(e):ArrayBuffer.isView(e)?e=at.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Ge.default||(e instanceof Jr?(e=nb(e),r=e.type.split("=")[1]):e=at.Buffer.from(String(e))));let o=e;at.Buffer.isBuffer(e)?o=Ge.default.Readable.from(e):pc(e)&&(o=Ge.default.Readable.from(e.stream())),this[kt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Ge.default&&e.on("error",s=>{let a=s instanceof _c?s:new qt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[kt].error=a})}get body(){return this[kt].stream}get bodyUsed(){return this[kt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await lc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new Jr,o=new URLSearchParams(await this.text());for(let[s,a]of o)r.append(s,a);return r}let{toFormData:n}=await Promise.resolve().then(()=>(B0(),N0));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[kt].body&&this[kt].body.type||"",n=await this.arrayBuffer();return new Qr([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await lc(this);return new TextDecoder().decode(e)}buffer(){return lc(this)}};p(ib,"Body");ri=ib;ri.prototype.buffer=(0,$t.deprecate)(ri.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(ri.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,$t.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});p(lc,"consumeBody");If=p((t,e)=>{let n,r,{body:o}=t[kt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Ge.default&&typeof o.getBoundary!="function"&&(n=new Ge.PassThrough({highWaterMark:e}),r=new Ge.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[kt].stream=n,o=r),o},"clone"),mT=(0,$t.deprecate)(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),ab=p((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":sb(t)?"application/x-www-form-urlencoded;charset=UTF-8":pc(t)?t.type||null:at.Buffer.isBuffer(t)||$t.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Jr?`multipart/form-data; boundary=${e[kt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${mT(t)}`:t instanceof Ge.default?null:"text/plain;charset=UTF-8","extractContentType"),yT=p(t=>{let{body:e}=t[kt];return e===null?0:pc(e)?e.size:at.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),_T=p(async(t,{body:e})=>{e===null?t.end():await gT(e,t)},"writeToStream"),dc=typeof Uo.default.validateHeaderName=="function"?Uo.default.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},vf=typeof Uo.default.validateHeaderValue=="function"?Uo.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},cb=class ub extends URLSearchParams{constructor(e){let n=[];if(e instanceof ub){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(a=>[o,a]))}else if(e!=null)if(typeof e=="object"&&!$t.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||$t.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(dc(r),vf(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(a,c)=>(dc(a),vf(a,String(c)),URLSearchParams.prototype[o].call(r,String(a).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return a=>(dc(a),URLSearchParams.prototype[o].call(r,String(a).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};p(cb,"Headers");$n=cb;Object.defineProperties($n.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));p(lb,"fromRawHeaders");bT=new Set([301,302,303,307,308]),bc=p(t=>bT.has(t),"isRedirect"),en=Symbol("Response internals"),db=class ti extends ri{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new $n(n.headers);if(e!==null&&!o.has("Content-Type")){let s=ab(e,this);s&&o.append("Content-Type",s)}this[en]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[en].type}get url(){return this[en].url||""}get status(){return this[en].status}get ok(){return this[en].status>=200&&this[en].status<300}get redirected(){return this[en].counter>0}get statusText(){return this[en].statusText}get headers(){return this[en].headers}get highWaterMark(){return this[en].highWaterMark}clone(){return new ti(If(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!bc(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new ti(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new ti(null,{status:0,statusText:""});return e[en].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new $n(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new ti(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};p(db,"Response");pn=db;Object.defineProperties(pn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});wT=p(t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""},"getSearch");p(Tf,"stripURLForUseAsAReferrer");fb=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),CT="strict-origin-when-cross-origin";p(hb,"validateReferrerPolicy");p(pb,"isOriginPotentiallyTrustworthy");p(Yr,"isUrlPotentiallyTrustworthy");p(gb,"determineRequestsReferrer");p(mb,"parseReferrerPolicyFromHeader");ot=Symbol("Request internals"),ei=p(t=>typeof t=="object"&&typeof t[ot]=="object","isRequest"),kT=(0,$t.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),yb=class _b extends ri{constructor(e,n={}){let r;if(ei(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!ei(n)&&"data"in n&&kT(),(n.body!=null||ei(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:ei(e)&&e.body!==null?If(e):null;super(s,{size:n.size||e.size||0});let a=new $n(n.headers||e.headers||{});if(s!==null&&!a.has("Content-Type")){let f=ab(s,this);f&&a.set("Content-Type",f)}let c=ei(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!fT(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let l=n.referrer==null?e.referrer:n.referrer;if(l==="")l="no-referrer";else if(l){let f=new URL(l);l=/^about:(\/\/)?client$/.test(f)?"client":f}else l=void 0;this[ot]={method:o,redirect:n.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:c,referrer:l},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[ot].method}get url(){return(0,Y0.format)(this[ot].parsedURL)}get headers(){return this[ot].headers}get redirect(){return this[ot].redirect}get signal(){return this[ot].signal}get referrer(){if(this[ot].referrer==="no-referrer")return"";if(this[ot].referrer==="client")return"about:client";if(this[ot].referrer)return this[ot].referrer.toString()}get referrerPolicy(){return this[ot].referrerPolicy}set referrerPolicy(e){this[ot].referrerPolicy=hb(e)}clone(){return new _b(this)}get[Symbol.toStringTag](){return"Request"}};p(yb,"Request");si=yb;Object.defineProperties(si.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});ST=p(t=>{let{parsedURL:e}=t[ot],n=new $n(t[ot].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=yT(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=CT),t.referrer&&t.referrer!=="no-referrer"?t[ot].referrer=gb(t):t[ot].referrer="no-referrer",t[ot].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=wT(e),a={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:a}},"getNodeRequestOptions"),bb=class extends _c{constructor(e,n="aborted"){super(e,n)}};p(bb,"AbortError");Nf=bb;p(wb,"requireNodeDomexception");AT=wb(),ET=bf(AT),{stat:Bf}=Zr.promises,Cb=p((t,e)=>Eb((0,Zr.statSync)(t),t,e),"blobFromSync"),kb=p((t,e)=>Bf(t).then(n=>Eb(n,t,e)),"blobFrom"),Sb=p((t,e)=>Bf(t).then(n=>vb(n,t,e)),"fileFrom"),Ab=p((t,e)=>vb((0,Zr.statSync)(t),t,e),"fileFromSync"),Eb=p((t,e,n="")=>new Qr([new Db({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),vb=p((t,e,n="")=>new Io([new Db({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,Q0.basename)(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),Tb=class Rb{constructor(e){qn(this,Bo),qn(this,jo),tn(this,Bo,e.path),tn(this,jo,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new Rb({path:We(this,Bo),lastModified:this.lastModified,size:n-e,start:We(this,jo)+e})}async*stream(){let{mtimeMs:e}=await Bf(We(this,Bo));if(e>this.lastModified)throw new ET("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,Zr.createReadStream)(We(this,Bo),{start:We(this,jo),end:We(this,jo)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};Bo=new WeakMap,jo=new WeakMap,p(Tb,"BlobDataItem");Db=Tb,vT=new Set(["data:","http:","https:"]);p(jf,"fetch$1");p(xb,"fixResponseChunkedTransferBadEnding");Ob=new WeakMap,Rf=new WeakMap;p(Ue,"pd");p(Df,"setCancelFlag");p(Xr,"Event"),Xr.prototype={get type(){return Ue(this).event.type},get target(){return Ue(this).eventTarget},get currentTarget(){return Ue(this).currentTarget},composedPath(){let t=Ue(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Ue(this).eventPhase},stopPropagation(){let t=Ue(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Ue(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Ue(this).event.bubbles},get cancelable(){return!!Ue(this).event.cancelable},preventDefault(){Df(Ue(this))},get defaultPrevented(){return Ue(this).canceled},get composed(){return!!Ue(this).event.composed},get timeStamp(){return Ue(this).timeStamp},get srcElement(){return Ue(this).eventTarget},get cancelBubble(){return Ue(this).stopped},set cancelBubble(t){if(!t)return;let e=Ue(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Ue(this).canceled},set returnValue(t){t||Df(Ue(this))},initEvent(){}},Object.defineProperty(Xr.prototype,"constructor",{value:Xr,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Xr.prototype,window.Event.prototype),Rf.set(window.Event.prototype,Xr));p(Mf,"defineRedirectDescriptor");p(Fb,"defineCallDescriptor");p(Pb,"defineWrapper");p(Uf,"getWrapper");p(Ib,"wrapEvent");p(Nb,"isStopped");p(Bb,"setEventPhase");p(jb,"setCurrentTarget");p(xf,"setPassiveListener");Mb=new WeakMap,W0=1,G0=2,fc=3;p(oi,"isObject");p(Mo,"getListeners");p(Ub,"defineEventAttributeDescriptor");p(Lf,"defineEventAttribute");p(Of,"defineCustomEventTarget");p(gn,"EventTarget"),gn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!oi(e))throw new TypeError("'listener' should be a function or an object.");let r=Mo(this),o=oi(n),s=(o?n.capture:n)?W0:G0,a={listener:e,listenerType:s,passive:o&&!!n.passive,once:o&&!!n.once,next:null},c=r.get(t);if(c===void 0){r.set(t,a);return}let l=null;for(;c!=null;){if(c.listener===e&&c.listenerType===s)return;l=c,c=c.next}l.next=a},removeEventListener(t,e,n){if(e==null)return;let r=Mo(this),o=(oi(n)?n.capture:n)?W0:G0,s=null,a=r.get(t);for(;a!=null;){if(a.listener===e&&a.listenerType===o){s!==null?s.next=a.next:a.next!==null?r.set(t,a.next):r.delete(t);return}s=a,a=a.next}},dispatchEvent(t){if(t==null||typeof t.type!="string")throw new TypeError('"event.type" should be a string.');let e=Mo(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=Ib(this,t),s=null;for(;r!=null;){if(r.once?s!==null?s.next=r.next:r.next!==null?e.set(n,r.next):e.delete(n):s=r,xf(o,r.passive?r.listener:null),typeof r.listener=="function")try{r.listener.call(this,o)}catch(a){typeof console<"u"&&typeof console.error=="function"&&console.error(a)}else r.listenerType!==fc&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(Nb(o))break;r=r.next}return xf(o,null),Bb(o,0),jb(o,null),!o.defaultPrevented}},Object.defineProperty(gn.prototype,"constructor",{value:gn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(gn.prototype,window.EventTarget.prototype);Lb=class extends gn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=mc.get(this);if(typeof e!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return e}};p(Lb,"AbortSignal");gc=Lb;Lf(gc.prototype,"abort");p(qb,"createAbortSignal");p($b,"abortSignal");mc=new WeakMap;Object.defineProperties(gc.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gc.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});yc=(Sf=class{constructor(){zb.set(this,qb())}get signal(){return Ff(this)}abort(){$b(Ff(this))}},p(Sf,"AbortController"),Sf),zb=new WeakMap;p(Ff,"getSignal"),Object.defineProperties(yc.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(yc.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});TT=Object.defineProperty,RT=p((t,e)=>TT(t,"name",{value:e,configurable:!0}),"e"),Hb=jf;Pf();p(Pf,"s"),RT(Pf,"checkNodeEnvironment")});var Wb={};Bd(Wb,{AbortController:()=>BT,AbortError:()=>Nf,Blob:()=>xT,FetchError:()=>qt,File:()=>OT,FormData:()=>FT,Headers:()=>PT,Request:()=>IT,Response:()=>NT,blobFrom:()=>kb,blobFromSync:()=>Cb,default:()=>DT,fetch:()=>DT,fileFrom:()=>Sb,fileFromSync:()=>Ab,isRedirect:()=>bc});var br,DT,xT,OT,FT,PT,IT,NT,BT,Gb=fr(()=>{oc();oc();tc();br=!!globalThis.process?.env?.FORCE_NODE_FETCH,DT=!br&&globalThis.fetch||Hb,xT=!br&&globalThis.Blob||Qr,OT=!br&&globalThis.File||Io,FT=!br&&globalThis.FormData||Jr,PT=!br&&globalThis.Headers||$n,IT=!br&&globalThis.Request||si,NT=!br&&globalThis.Response||pn,BT=!br&&globalThis.AbortController||yc});var Kb=V(qo=>{"use strict";var jT=qo&&qo.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Lo;Object.defineProperty(qo,"__esModule",{value:!0});qo.Gaxios=void 0;var MT=jT(sf()),UT=require("https"),eo=uf(),LT=s0(),Jb=require("stream"),Vb=ff(),qT=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),wc=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Vb.GaxiosInterceptorManager,response:new Vb.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Lo.mergeHeaders(s,n.headers),r&&Lo.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Lo.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=o.toString()}let r=eo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new eo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof eo.GaxiosError?r=n:n instanceof Error?r=new eo.GaxiosError(n.message,e,void 0,n):r=new eo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,LT.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new eo.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":return n.json();case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let a of s)o.push(a.trim());for(let a of o)if(a instanceof RegExp){if(a.test(r.toString()))return!1}else if(a instanceof URL){if(a.origin===r.origin)return!1}else if(a.startsWith("*.")||a.startsWith(".")){let c=a.replace(/^\*\./,".");if(r.hostname.endsWith(c))return!1}else if(a===r.origin||a===r.hostname||a===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Lo.mergeHeaders(n,e.headers);let r=(0,MT.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let a=r.paramsSerializer(r.params);a.startsWith("?")&&(a=a.slice(1));let c=r.url.toString().includes("?")?"&":"?";r.url=r.url+c+a}else{let a=r.url instanceof URL?r.url:new URL(r.url);for(let[c,l]of new URLSearchParams(r.params))a.searchParams.append(c,l);r.url=a}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof Jb.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let a=await qT();n.set("content-type",`multipart/related; boundary=${a}`),r.body=Jb.Readable.from(this.getMultipartRequest(r.multipart,a))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let a=await Lo.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new a(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new UT.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=eo.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
67
+ `),r=!1,o=!1,s;t.on("response",i=>{let{headers:c}=i;r=c["transfer-encoding"]==="chunked"&&!c["content-length"]}),t.on("socket",i=>{let c=m(()=>{if(r&&!o){let f=new Error("Premature close");f.code="ERR_STREAM_PREMATURE_CLOSE",e(f)}},"onSocketClose"),u=m(f=>{o=ut.Buffer.compare(f.slice(-5),n)===0,!o&&s&&(o=ut.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&ut.Buffer.compare(f.slice(-2),n.slice(3))===0),s=f},"onData");i.prependListener("close",c),i.on("data",u),t.on("close",()=>{i.removeListener("close",c),i.removeListener("data",u)})})}function Be(t){let e=Tk.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function Hp(t){if(t.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",t.passiveListener);return}t.event.cancelable&&(t.canceled=!0,typeof t.event.preventDefault=="function"&&t.event.preventDefault())}function uo(t,e){Tk.set(this,{eventTarget:t,event:e,eventPhase:2,currentTarget:t,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:e.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let n=Object.keys(e);for(let r=0;r<n.length;++r){let o=n[r];o in this||Object.defineProperty(this,o,Zp(o))}}function Zp(t){return{get(){return Be(this).event[t]},set(e){Be(this).event[t]=e},configurable:!0,enumerable:!0}}function Rk(t){return{value(){let e=Be(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function xk(t,e){let n=Object.keys(e);if(n.length===0)return t;function r(o,s){t.call(this,o,s)}m(r,"CustomEvent"),r.prototype=Object.create(t.prototype,{constructor:{value:r,configurable:!0,writable:!0}});for(let o=0;o<n.length;++o){let s=n[o];if(!(s in t.prototype)){let i=typeof Object.getOwnPropertyDescriptor(e,s).value=="function";Object.defineProperty(r.prototype,s,i?Rk(s):Zp(s))}}return r}function eh(t){if(t==null||t===Object.prototype)return uo;let e=zp.get(t);return e==null&&(e=xk(eh(Object.getPrototypeOf(t)),t),zp.set(t,e)),e}function Dk(t,e){let n=eh(Object.getPrototypeOf(e));return new n(t,e)}function Ok(t){return Be(t).immediateStopped}function Pk(t,e){Be(t).eventPhase=e}function Ik(t,e){Be(t).currentTarget=e}function Wp(t,e){Be(t).passiveListener=e}function Pi(t){return t!==null&&typeof t=="object"}function es(t){let e=Fk.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function Nk(t){return{get(){let e=es(this).get(t);for(;e!=null;){if(e.listenerType===eu)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!Pi(e)&&(e=null);let n=es(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===eu?r!==null?r.next=o.next:o.next!==null?n.set(t,o.next):n.delete(t):r=o,o=o.next;if(e!==null){let s={listener:e,listenerType:eu,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function th(t,e){Object.defineProperty(t,`on${e}`,Nk(e))}function Gp(t){function e(){bn.call(this)}m(e,"CustomEventTarget"),e.prototype=Object.create(bn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)th(e.prototype,t[n]);return e}function bn(){if(this instanceof bn){Fk.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return Gp(arguments[0]);if(arguments.length>0){let t=new Array(arguments.length);for(let e=0;e<arguments.length;++e)t[e]=arguments[e];return Gp(t)}throw new TypeError("Cannot call a class as a function")}function Bk(){let t=Object.create(ru.prototype);return bn.call(t),ou.set(t,!1),t}function Uk(t){ou.get(t)===!1&&(ou.set(t,!0),t.dispatchEvent({type:"abort"}))}function Jp(t){let e=jk.get(t);if(e==null)throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${t===null?"null":typeof t}`);return e}function Vp(){!globalThis.process?.versions?.node&&!globalThis.process?.env?.DISABLE_NODE_FETCH_NATIVE_WARN&&console.warn("[node-fetch-native] Node.js compatible build of `node-fetch-native` is being used in a non-Node.js environment. Please make sure you are using proper export conditions or report this issue to https://github.com/unjs/node-fetch-native. You can set `process.env.DISABLE_NODE_FETCH_NATIVE_WARN` to disable this warning.")}var ts,Ww,ao,He,ut,Lt,Gw,Jw,fo,Vw,NO,zw,m,Hw,ze,Gn,Zt,Tr,Jc,Xo,Np,Ti,Vc,Kc,Mp,Xt,Bp,Qo,Zo,Up,Iw,Yc,MO,Fw,Nw,Bw,Xw,lo,BO,Yo,Di,UO,jO,Uw,LO,jw,jp,io,so,Zw,iu,ek,jt,tu,tk,nu,qO,$O,zO,HO,St,nk,Oi,Kp,WO,rk,GO,JO,Zc,qp,ok,Jn,VO,au,Qt,ak,_n,KO,ck,YO,it,Ri,XO,pk,Ii,QO,mk,Yp,Lp,Lw,ZO,e1,Xp,yk,_k,bk,Ck,wk,kk,Sk,vk,t1,Tk,zp,Fk,qw,$w,eu,Mk,ru,ou,su,jk,n1,r1,Lk,Gc=_r(()=>{ts=tt(require("node:http"),1),Ww=tt(require("node:https"),1),ao=tt(require("node:zlib"),1),He=tt(require("node:stream"),1),ut=require("node:buffer"),Lt=require("node:util");zc();Gw=require("node:url"),Jw=require("node:net"),fo=require("node:fs"),Vw=require("node:path"),NO=Object.defineProperty,zw=t=>{throw TypeError(t)},m=(t,e)=>NO(t,"name",{value:e,configurable:!0}),Hw=(t,e,n)=>e.has(t)||zw("Cannot "+n),ze=(t,e,n)=>(Hw(t,e,"read from private field"),n?n.call(t):e.get(t)),Gn=(t,e,n)=>e.has(t)?zw("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),Zt=(t,e,n,r)=>(Hw(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);m(Kw,"dataUriToBuffer");Iw={},Yc={exports:{}};MO=Yc.exports;m(Yw,"requirePonyfill_es2018");m(Mw,"requireStreams"),Mw();Bw=65536;m(Xc,"toIterator");Xw=(Ti=class{constructor(t=[],e={}){if(Gn(this,Tr,[]),Gn(this,Jc,""),Gn(this,Xo,0),Gn(this,Np,"transparent"),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof e!="object"&&typeof e!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");e===null&&(e={});let n=new TextEncoder;for(let o of t){let s;ArrayBuffer.isView(o)?s=new Uint8Array(o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)):o instanceof ArrayBuffer?s=new Uint8Array(o.slice(0)):o instanceof Ti?s=o:s=n.encode(`${o}`),Zt(this,Xo,ze(this,Xo)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),ze(this,Tr).push(s)}Zt(this,Np,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);Zt(this,Jc,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return ze(this,Xo)}get type(){return ze(this,Jc)}async text(){let t=new TextDecoder,e="";for await(let n of Xc(ze(this,Tr),!1))e+=t.decode(n,{stream:!0});return e+=t.decode(),e}async arrayBuffer(){let t=new Uint8Array(this.size),e=0;for await(let n of Xc(ze(this,Tr),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=Xc(ze(this,Tr),!0);return new globalThis.ReadableStream({type:"bytes",async pull(e){let n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,e=this.size,n=""){let{size:r}=this,o=t<0?Math.max(r+t,0):Math.min(t,r),s=e<0?Math.max(r+e,0):Math.min(e,r),i=Math.max(s-o,0),c=ze(this,Tr),u=[],f=0;for(let p of c){if(f>=i)break;let h=ArrayBuffer.isView(p)?p.byteLength:p.size;if(o&&h<=o)o-=h,s-=h;else{let _;ArrayBuffer.isView(p)?(_=p.subarray(o,Math.min(h,s)),f+=_.byteLength):(_=p.slice(o,Math.min(h,s)),f+=_.size),s-=h,u.push(_),o=0}}let d=new Ti([],{type:String(n).toLowerCase()});return Zt(d,Xo,i),Zt(d,Tr,u),d}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t=="object"&&typeof t.constructor=="function"&&(typeof t.stream=="function"||typeof t.arrayBuffer=="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}},Tr=new WeakMap,Jc=new WeakMap,Xo=new WeakMap,Np=new WeakMap,m(Ti,"Blob"),Ti);Object.defineProperties(Xw.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});lo=Xw,BO=(Mp=class extends lo{constructor(t,e,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n),Gn(this,Vc,0),Gn(this,Kc,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||Zt(this,Vc,r),Zt(this,Kc,String(e))}get name(){return ze(this,Kc)}get lastModified(){return ze(this,Vc)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof lo&&/^(File)$/.test(t[Symbol.toStringTag])}},Vc=new WeakMap,Kc=new WeakMap,m(Mp,"File"),Mp),Yo=BO;({toStringTag:Di,iterator:UO,hasInstance:jO}=Symbol),Uw=Math.random,LO="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),jw=m((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Di])?[(n=n!==void 0?n+"":e[Di]=="File"?e.name:"blob",t),e.name!==n||e[Di]=="blob"?new Yo([e],n,e):e]:[t,e+""]),"f"),jp=m((t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
68
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),io=m((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),so=(Bp=class{constructor(...t){if(Gn(this,Xt,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Di](){return"FormData"}[UO](){return this.entries()}static[jO](t){return t&&typeof t=="object"&&t[Di]==="FormData"&&!LO.some(e=>typeof t[e]!="function")}append(...t){io("append",arguments,2),ze(this,Xt).push(jw(...t))}delete(t){io("delete",arguments,1),t+="",Zt(this,Xt,ze(this,Xt).filter(([e])=>e!==t))}get(t){io("get",arguments,1),t+="";for(var e=ze(this,Xt),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return io("getAll",arguments,1),e=[],t+="",ze(this,Xt).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return io("has",arguments,1),t+="",ze(this,Xt).some(e=>e[0]===t)}forEach(t,e){io("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){io("set",arguments,2);var e=[],n=!0;t=jw(...t),ze(this,Xt).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),Zt(this,Xt,e)}*entries(){yield*ze(this,Xt)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},Xt=new WeakMap,m(Bp,"FormData"),Bp);m(Qw,"formDataToBlob");Zw=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};m(Zw,"FetchBaseError");iu=Zw,ek=class extends iu{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};m(ek,"FetchError");jt=ek,tu=Symbol.toStringTag,tk=m(t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[tu]==="URLSearchParams","isURLSearchParameters"),nu=m(t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[tu]),"isBlob"),qO=m(t=>typeof t=="object"&&(t[tu]==="AbortSignal"||t[tu]==="EventTarget"),"isAbortSignal"),$O=m((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),zO=m((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),HO=(0,Lt.promisify)(He.default.pipeline),St=Symbol("Body internals"),nk=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:tk(e)?e=ut.Buffer.from(e.toString()):nu(e)||ut.Buffer.isBuffer(e)||(Lt.types.isAnyArrayBuffer(e)?e=ut.Buffer.from(e):ArrayBuffer.isView(e)?e=ut.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof He.default||(e instanceof so?(e=Qw(e),r=e.type.split("=")[1]):e=ut.Buffer.from(String(e))));let o=e;ut.Buffer.isBuffer(e)?o=He.default.Readable.from(e):nu(e)&&(o=He.default.Readable.from(e.stream())),this[St]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof He.default&&e.on("error",s=>{let i=s instanceof iu?s:new jt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[St].error=i})}get body(){return this[St].stream}get bodyUsed(){return this[St].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await Qc(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new so,o=new URLSearchParams(await this.text());for(let[s,i]of o)r.append(s,i);return r}let{toFormData:n}=await Promise.resolve().then(()=>(Pw(),Ow));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[St].body&&this[St].body.type||"",n=await this.arrayBuffer();return new lo([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Qc(this);return new TextDecoder().decode(e)}buffer(){return Qc(this)}};m(nk,"Body");Oi=nk;Oi.prototype.buffer=(0,Lt.deprecate)(Oi.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Oi.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Lt.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});m(Qc,"consumeBody");Kp=m((t,e)=>{let n,r,{body:o}=t[St];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof He.default&&typeof o.getBoundary!="function"&&(n=new He.PassThrough({highWaterMark:e}),r=new He.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[St].stream=n,o=r),o},"clone"),WO=(0,Lt.deprecate)(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),rk=m((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":tk(t)?"application/x-www-form-urlencoded;charset=UTF-8":nu(t)?t.type||null:ut.Buffer.isBuffer(t)||Lt.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof so?`multipart/form-data; boundary=${e[St].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${WO(t)}`:t instanceof He.default?null:"text/plain;charset=UTF-8","extractContentType"),GO=m(t=>{let{body:e}=t[St];return e===null?0:nu(e)?e.size:ut.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),JO=m(async(t,{body:e})=>{e===null?t.end():await HO(e,t)},"writeToStream"),Zc=typeof ts.default.validateHeaderName=="function"?ts.default.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},qp=typeof ts.default.validateHeaderValue=="function"?ts.default.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},ok=class sk extends URLSearchParams{constructor(e){let n=[];if(e instanceof sk){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(i=>[o,i]))}else if(e!=null)if(typeof e=="object"&&!Lt.types.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||Lt.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(Zc(r),qp(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(i,c)=>(Zc(i),qp(i,String(c)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(c)));case"delete":case"has":case"getAll":return i=>(Zc(i),URLSearchParams.prototype[o].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};m(ok,"Headers");Jn=ok;Object.defineProperties(Jn.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));m(ik,"fromRawHeaders");VO=new Set([301,302,303,307,308]),au=m(t=>VO.has(t),"isRedirect"),Qt=Symbol("Response internals"),ak=class xi extends Oi{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new Jn(n.headers);if(e!==null&&!o.has("Content-Type")){let s=rk(e,this);s&&o.append("Content-Type",s)}this[Qt]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[Qt].type}get url(){return this[Qt].url||""}get status(){return this[Qt].status}get ok(){return this[Qt].status>=200&&this[Qt].status<300}get redirected(){return this[Qt].counter>0}get statusText(){return this[Qt].statusText}get headers(){return this[Qt].headers}get highWaterMark(){return this[Qt].highWaterMark}clone(){return new xi(Kp(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!au(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new xi(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new xi(null,{status:0,statusText:""});return e[Qt].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new Jn(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new xi(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};m(ak,"Response");_n=ak;Object.defineProperties(_n.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});KO=m(t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""},"getSearch");m($p,"stripURLForUseAsAReferrer");ck=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),YO="strict-origin-when-cross-origin";m(uk,"validateReferrerPolicy");m(lk,"isOriginPotentiallyTrustworthy");m(co,"isUrlPotentiallyTrustworthy");m(dk,"determineRequestsReferrer");m(fk,"parseReferrerPolicyFromHeader");it=Symbol("Request internals"),Ri=m(t=>typeof t=="object"&&typeof t[it]=="object","isRequest"),XO=(0,Lt.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),pk=class hk extends Oi{constructor(e,n={}){let r;if(Ri(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!Ri(n)&&"data"in n&&XO(),(n.body!=null||Ri(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:Ri(e)&&e.body!==null?Kp(e):null;super(s,{size:n.size||e.size||0});let i=new Jn(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let f=rk(s,this);f&&i.set("Content-Type",f)}let c=Ri(e)?e.signal:null;if("signal"in n&&(c=n.signal),c!=null&&!qO(c))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=n.referrer==null?e.referrer:n.referrer;if(u==="")u="no-referrer";else if(u){let f=new URL(u);u=/^about:(\/\/)?client$/.test(f)?"client":f}else u=void 0;this[it]={method:o,redirect:n.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:c,referrer:u},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[it].method}get url(){return(0,Gw.format)(this[it].parsedURL)}get headers(){return this[it].headers}get redirect(){return this[it].redirect}get signal(){return this[it].signal}get referrer(){if(this[it].referrer==="no-referrer")return"";if(this[it].referrer==="client")return"about:client";if(this[it].referrer)return this[it].referrer.toString()}get referrerPolicy(){return this[it].referrerPolicy}set referrerPolicy(e){this[it].referrerPolicy=uk(e)}clone(){return new hk(this)}get[Symbol.toStringTag](){return"Request"}};m(pk,"Request");Ii=pk;Object.defineProperties(Ii.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});QO=m(t=>{let{parsedURL:e}=t[it],n=new Jn(t[it].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let c=GO(t);typeof c=="number"&&!Number.isNaN(c)&&(r=String(c))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=YO),t.referrer&&t.referrer!=="no-referrer"?t[it].referrer=dk(t):t[it].referrer="no-referrer",t[it].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=KO(e),i={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:i}},"getNodeRequestOptions"),mk=class extends iu{constructor(e,n="aborted"){super(e,n)}};m(mk,"AbortError");Yp=mk;m(gk,"requireNodeDomexception");ZO=gk(),e1=Fp(ZO),{stat:Xp}=fo.promises,yk=m((t,e)=>wk((0,fo.statSync)(t),t,e),"blobFromSync"),_k=m((t,e)=>Xp(t).then(n=>wk(n,t,e)),"blobFrom"),bk=m((t,e)=>Xp(t).then(n=>kk(n,t,e)),"fileFrom"),Ck=m((t,e)=>kk((0,fo.statSync)(t),t,e),"fileFromSync"),wk=m((t,e,n="")=>new lo([new vk({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),kk=m((t,e,n="")=>new Yo([new vk({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,Vw.basename)(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),Sk=class Ek{constructor(e){Gn(this,Qo),Gn(this,Zo),Zt(this,Qo,e.path),Zt(this,Zo,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new Ek({path:ze(this,Qo),lastModified:this.lastModified,size:n-e,start:ze(this,Zo)+e})}async*stream(){let{mtimeMs:e}=await Xp(ze(this,Qo));if(e>this.lastModified)throw new e1("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,fo.createReadStream)(ze(this,Qo),{start:ze(this,Zo),end:ze(this,Zo)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};Qo=new WeakMap,Zo=new WeakMap,m(Sk,"BlobDataItem");vk=Sk,t1=new Set(["data:","http:","https:"]);m(Qp,"fetch$1");m(Ak,"fixResponseChunkedTransferBadEnding");Tk=new WeakMap,zp=new WeakMap;m(Be,"pd");m(Hp,"setCancelFlag");m(uo,"Event"),uo.prototype={get type(){return Be(this).event.type},get target(){return Be(this).eventTarget},get currentTarget(){return Be(this).currentTarget},composedPath(){let t=Be(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Be(this).eventPhase},stopPropagation(){let t=Be(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Be(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Be(this).event.bubbles},get cancelable(){return!!Be(this).event.cancelable},preventDefault(){Hp(Be(this))},get defaultPrevented(){return Be(this).canceled},get composed(){return!!Be(this).event.composed},get timeStamp(){return Be(this).timeStamp},get srcElement(){return Be(this).eventTarget},get cancelBubble(){return Be(this).stopped},set cancelBubble(t){if(!t)return;let e=Be(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Be(this).canceled},set returnValue(t){t||Hp(Be(this))},initEvent(){}},Object.defineProperty(uo.prototype,"constructor",{value:uo,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(uo.prototype,window.Event.prototype),zp.set(window.Event.prototype,uo));m(Zp,"defineRedirectDescriptor");m(Rk,"defineCallDescriptor");m(xk,"defineWrapper");m(eh,"getWrapper");m(Dk,"wrapEvent");m(Ok,"isStopped");m(Pk,"setEventPhase");m(Ik,"setCurrentTarget");m(Wp,"setPassiveListener");Fk=new WeakMap,qw=1,$w=2,eu=3;m(Pi,"isObject");m(es,"getListeners");m(Nk,"defineEventAttributeDescriptor");m(th,"defineEventAttribute");m(Gp,"defineCustomEventTarget");m(bn,"EventTarget"),bn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!Pi(e))throw new TypeError("'listener' should be a function or an object.");let r=es(this),o=Pi(n),s=(o?n.capture:n)?qw:$w,i={listener:e,listenerType:s,passive:o&&!!n.passive,once:o&&!!n.once,next:null},c=r.get(t);if(c===void 0){r.set(t,i);return}let u=null;for(;c!=null;){if(c.listener===e&&c.listenerType===s)return;u=c,c=c.next}u.next=i},removeEventListener(t,e,n){if(e==null)return;let r=es(this),o=(Pi(n)?n.capture:n)?qw:$w,s=null,i=r.get(t);for(;i!=null;){if(i.listener===e&&i.listenerType===o){s!==null?s.next=i.next:i.next!==null?r.set(t,i.next):r.delete(t);return}s=i,i=i.next}},dispatchEvent(t){if(t==null||typeof t.type!="string")throw new TypeError('"event.type" should be a string.');let e=es(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=Dk(this,t),s=null;for(;r!=null;){if(r.once?s!==null?s.next=r.next:r.next!==null?e.set(n,r.next):e.delete(n):s=r,Wp(o,r.passive?r.listener:null),typeof r.listener=="function")try{r.listener.call(this,o)}catch(i){typeof console<"u"&&typeof console.error=="function"&&console.error(i)}else r.listenerType!==eu&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(Ok(o))break;r=r.next}return Wp(o,null),Pk(o,0),Ik(o,null),!o.defaultPrevented}},Object.defineProperty(bn.prototype,"constructor",{value:bn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(bn.prototype,window.EventTarget.prototype);Mk=class extends bn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=ou.get(this);if(typeof e!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return e}};m(Mk,"AbortSignal");ru=Mk;th(ru.prototype,"abort");m(Bk,"createAbortSignal");m(Uk,"abortSignal");ou=new WeakMap;Object.defineProperties(ru.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ru.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});su=(Up=class{constructor(){jk.set(this,Bk())}get signal(){return Jp(this)}abort(){Uk(Jp(this))}},m(Up,"AbortController"),Up),jk=new WeakMap;m(Jp,"getSignal"),Object.defineProperties(su.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(su.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});n1=Object.defineProperty,r1=m((t,e)=>n1(t,"name",{value:e,configurable:!0}),"e"),Lk=Qp;Vp();m(Vp,"s"),r1(Vp,"checkNodeEnvironment")});var qk={};Rf(qk,{AbortController:()=>d1,AbortError:()=>Yp,Blob:()=>s1,FetchError:()=>jt,File:()=>i1,FormData:()=>a1,Headers:()=>c1,Request:()=>u1,Response:()=>l1,blobFrom:()=>_k,blobFromSync:()=>yk,default:()=>o1,fetch:()=>o1,fileFrom:()=>bk,fileFromSync:()=>Ck,isRedirect:()=>au});var Rr,o1,s1,i1,a1,c1,u1,l1,d1,$k=_r(()=>{Gc();Gc();zc();Rr=!!globalThis.process?.env?.FORCE_NODE_FETCH,o1=!Rr&&globalThis.fetch||Lk,s1=!Rr&&globalThis.Blob||lo,i1=!Rr&&globalThis.File||Yo,a1=!Rr&&globalThis.FormData||so,c1=!Rr&&globalThis.Headers||Jn,u1=!Rr&&globalThis.Request||Ii,l1=!Rr&&globalThis.Response||_n,d1=!Rr&&globalThis.AbortController||su});var Wk=J(rs=>{"use strict";var f1=rs&&rs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},ns;Object.defineProperty(rs,"__esModule",{value:!0});rs.Gaxios=void 0;var p1=f1(wp()),h1=require("https"),po=Ep(),m1=tw(),zk=require("stream"),Hk=Tp(),g1=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),y1=204,cu=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Hk.GaxiosInterceptorManager,response:new Hk.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&ns.mergeHeaders(s,n.headers),r&&ns.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await ns.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=Buffer.concat(o.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=po.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new po.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof po.GaxiosError?r=n:n instanceof Error?r=new po.GaxiosError(n.message,e,void 0,n):r=new po.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,m1.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===y1)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new po.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of s)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(r.toString()))return!1}else if(i instanceof URL){if(i.origin===r.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let c=i.replace(/^\*\./,".");if(r.hostname.endsWith(c))return!1}else if(i===r.origin||i===r.hostname||i===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);ns.mergeHeaders(n,e.headers);let r=(0,p1.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let i=r.paramsSerializer(r.params);i.startsWith("?")&&(i=i.slice(1));let c=r.url.toString().includes("?")?"&":"?";r.url=r.url+c+i}else{let i=r.url instanceof URL?r.url:new URL(r.url);for(let[c,u]of new URLSearchParams(r.params))i.searchParams.append(c,u);r.url=i}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof zk.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let i=await g1();n.set("content-type",`multipart/related; boundary=${i}`),r.body=zk.Readable.from(this.getMultipartRequest(r.multipart,i))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let i=await ns.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new i(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new h1.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=po.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
40
69
  Content-Type: ${s}\r
41
70
  \r
42
71
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
43
- `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>st(x0()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Gb(),Wb))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,a)=>{a==="set-cookie"?e.append(a,s):e.set(a,s)});return e}};qo.Gaxios=wc;Lo=wc});var ct=V(gt=>{"use strict";var $T=gt&&gt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),zT=gt&&gt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&$T(e,t,n)};Object.defineProperty(gt,"__esModule",{value:!0});gt.instance=gt.Gaxios=gt.GaxiosError=void 0;gt.request=WT;var Yb=Kb();Object.defineProperty(gt,"Gaxios",{enumerable:!0,get:function(){return Yb.Gaxios}});var HT=uf();Object.defineProperty(gt,"GaxiosError",{enumerable:!0,get:function(){return HT.GaxiosError}});zT(ff(),gt);gt.instance=new Yb.Gaxios;async function WT(t){return gt.instance.request(t)}});var qf=V((Xb,Cc)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",a=s+"Number primitive has more than 15 significant digits: ",c=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,m=1e9;function S(x){var R,j,W,U=z.prototype={constructor:z,toString:null,valueOf:null},ue=new z(1),Y=20,ne=4,te=-7,re=21,K=-1e7,se=1e7,ie=!1,X=1,Z=0,Q={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},me="0123456789abcdefghijklmnopqrstuvwxyz",he=!0;function z(C,E){var T,I,F,B,$,O,N,L,M=this;if(!(M instanceof z))return new z(C,E);if(E==null){if(C&&C._isBigNumber===!0){M.s=C.s,!C.c||C.e>se?M.c=M.e=null:C.e<K?M.c=[M.e=0]:(M.e=C.e,M.c=C.c.slice());return}if((O=typeof C=="number")&&C*0==0){if(M.s=1/C<0?(C=-C,-1):1,C===~~C){for(B=0,$=C;$>=10;$/=10,B++);B>se?M.c=M.e=null:(M.e=B,M.c=[C]);return}L=String(C)}else{if(!n.test(L=String(C)))return W(M,L,O);M.s=L.charCodeAt(0)==45?(L=L.slice(1),-1):1}(B=L.indexOf("."))>-1&&(L=L.replace(".","")),($=L.search(/e/i))>0?(B<0&&(B=$),B+=+L.slice($+1),L=L.substring(0,$)):B<0&&(B=L.length)}else{if(_(E,2,me.length,"Base"),E==10&&he)return M=new z(C),ye(M,Y+M.e+1,ne);if(L=String(C),O=typeof C=="number"){if(C*0!=0)return W(M,L,O,E);if(M.s=1/C<0?(L=L.slice(1),-1):1,z.DEBUG&&L.replace(/^0\.0*|\./,"").length>15)throw Error(a+C)}else M.s=L.charCodeAt(0)===45?(L=L.slice(1),-1):1;for(T=me.slice(0,E),B=$=0,N=L.length;$<N;$++)if(T.indexOf(I=L.charAt($))<0){if(I=="."){if($>B){B=N;continue}}else if(!F&&(L==L.toUpperCase()&&(L=L.toLowerCase())||L==L.toLowerCase()&&(L=L.toUpperCase()))){F=!0,$=-1,B=0;continue}return W(M,String(C),O,E)}O=!1,L=j(L,E,10,M.s),(B=L.indexOf("."))>-1?L=L.replace(".",""):B=L.length}for($=0;L.charCodeAt($)===48;$++);for(N=L.length;L.charCodeAt(--N)===48;);if(L=L.slice($,++N)){if(N-=$,O&&z.DEBUG&&N>15&&(C>f||C!==o(C)))throw Error(a+M.s*C);if((B=B-$-1)>se)M.c=M.e=null;else if(B<K)M.c=[M.e=0];else{if(M.e=B,M.c=[],$=(B+1)%l,B<0&&($+=l),$<N){for($&&M.c.push(+L.slice(0,$)),N-=l;$<N;)M.c.push(+L.slice($,$+=l));$=l-(L=L.slice($)).length}else $-=N;for(;$--;L+="0");M.c.push(+L)}}else M.c=[M.e=0]}z.clone=S,z.ROUND_UP=0,z.ROUND_DOWN=1,z.ROUND_CEIL=2,z.ROUND_FLOOR=3,z.ROUND_HALF_UP=4,z.ROUND_HALF_DOWN=5,z.ROUND_HALF_EVEN=6,z.ROUND_HALF_CEIL=7,z.ROUND_HALF_FLOOR=8,z.EUCLID=9,z.config=z.set=function(C){var E,T;if(C!=null)if(typeof C=="object"){if(C.hasOwnProperty(E="DECIMAL_PLACES")&&(T=C[E],_(T,0,m,E),Y=T),C.hasOwnProperty(E="ROUNDING_MODE")&&(T=C[E],_(T,0,8,E),ne=T),C.hasOwnProperty(E="EXPONENTIAL_AT")&&(T=C[E],T&&T.pop?(_(T[0],-m,0,E),_(T[1],0,m,E),te=T[0],re=T[1]):(_(T,-m,m,E),te=-(re=T<0?-T:T))),C.hasOwnProperty(E="RANGE"))if(T=C[E],T&&T.pop)_(T[0],-m,-1,E),_(T[1],1,m,E),K=T[0],se=T[1];else if(_(T,-m,m,E),T)K=-(se=T<0?-T:T);else throw Error(s+E+" cannot be zero: "+T);if(C.hasOwnProperty(E="CRYPTO"))if(T=C[E],T===!!T)if(T)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))ie=T;else throw ie=!T,Error(s+"crypto unavailable");else ie=T;else throw Error(s+E+" not true or false: "+T);if(C.hasOwnProperty(E="MODULO_MODE")&&(T=C[E],_(T,0,9,E),X=T),C.hasOwnProperty(E="POW_PRECISION")&&(T=C[E],_(T,0,m,E),Z=T),C.hasOwnProperty(E="FORMAT"))if(T=C[E],typeof T=="object")Q=T;else throw Error(s+E+" not an object: "+T);if(C.hasOwnProperty(E="ALPHABET"))if(T=C[E],typeof T=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(T))he=T.slice(0,10)=="0123456789",me=T;else throw Error(s+E+" invalid: "+T)}else throw Error(s+"Object expected: "+C);return{DECIMAL_PLACES:Y,ROUNDING_MODE:ne,EXPONENTIAL_AT:[te,re],RANGE:[K,se],CRYPTO:ie,MODULO_MODE:X,POW_PRECISION:Z,FORMAT:Q,ALPHABET:me}},z.isBigNumber=function(C){if(!C||C._isBigNumber!==!0)return!1;if(!z.DEBUG)return!0;var E,T,I=C.c,F=C.e,B=C.s;e:if({}.toString.call(I)=="[object Array]"){if((B===1||B===-1)&&F>=-m&&F<=m&&F===o(F)){if(I[0]===0){if(F===0&&I.length===1)return!0;break e}if(E=(F+1)%l,E<1&&(E+=l),String(I[0]).length==E){for(E=0;E<I.length;E++)if(T=I[E],T<0||T>=c||T!==o(T))break e;if(T!==0)return!0}}}else if(I===null&&F===null&&(B===null||B===1||B===-1))return!0;throw Error(s+"Invalid BigNumber: "+C)},z.maximum=z.max=function(){return Fe(arguments,-1)},z.minimum=z.min=function(){return Fe(arguments,1)},z.random=(function(){var C=9007199254740992,E=Math.random()*C&2097151?function(){return o(Math.random()*C)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(T){var I,F,B,$,O,N=0,L=[],M=new z(ue);if(T==null?T=Y:_(T,0,m),$=r(T/l),ie)if(crypto.getRandomValues){for(I=crypto.getRandomValues(new Uint32Array($*=2));N<$;)O=I[N]*131072+(I[N+1]>>>11),O>=9e15?(F=crypto.getRandomValues(new Uint32Array(2)),I[N]=F[0],I[N+1]=F[1]):(L.push(O%1e14),N+=2);N=$/2}else if(crypto.randomBytes){for(I=crypto.randomBytes($*=7);N<$;)O=(I[N]&31)*281474976710656+I[N+1]*1099511627776+I[N+2]*4294967296+I[N+3]*16777216+(I[N+4]<<16)+(I[N+5]<<8)+I[N+6],O>=9e15?crypto.randomBytes(7).copy(I,N):(L.push(O%1e14),N+=7);N=$/7}else throw ie=!1,Error(s+"crypto unavailable");if(!ie)for(;N<$;)O=E(),O<9e15&&(L[N++]=O%1e14);for($=L[--N],T%=l,$&&T&&(O=d[l-T],L[N]=o($/O)*O);L[N]===0;L.pop(),N--);if(N<0)L=[B=0];else{for(B=-1;L[0]===0;L.splice(0,1),B-=l);for(N=1,O=L[0];O>=10;O/=10,N++);N<l&&(B-=l-N)}return M.e=B,M.c=L,M}})(),z.sum=function(){for(var C=1,E=arguments,T=new z(E[0]);C<E.length;)T=T.plus(E[C++]);return T},j=(function(){var C="0123456789";function E(T,I,F,B){for(var $,O=[0],N,L=0,M=T.length;L<M;){for(N=O.length;N--;O[N]*=I);for(O[0]+=B.indexOf(T.charAt(L++)),$=0;$<O.length;$++)O[$]>F-1&&(O[$+1]==null&&(O[$+1]=0),O[$+1]+=O[$]/F|0,O[$]%=F)}return O.reverse()}return function(T,I,F,B,$){var O,N,L,M,J,oe,ae,Ee,Re=T.indexOf("."),Oe=Y,we=ne;for(Re>=0&&(M=Z,Z=0,T=T.replace(".",""),Ee=new z(I),oe=Ee.pow(T.length-Re),Z=M,Ee.c=E(v(w(oe.c),oe.e,"0"),10,F,C),Ee.e=Ee.c.length),ae=E(T,I,F,$?(O=me,C):(O=C,me)),L=M=ae.length;ae[--M]==0;ae.pop());if(!ae[0])return O.charAt(0);if(Re<0?--L:(oe.c=ae,oe.e=L,oe.s=B,oe=R(oe,Ee,Oe,we,F),ae=oe.c,J=oe.r,L=oe.e),N=L+Oe+1,Re=ae[N],M=F/2,J=J||N<0||ae[N+1]!=null,J=we<4?(Re!=null||J)&&(we==0||we==(oe.s<0?3:2)):Re>M||Re==M&&(we==4||J||we==6&&ae[N-1]&1||we==(oe.s<0?8:7)),N<1||!ae[0])T=J?v(O.charAt(1),-Oe,O.charAt(0)):O.charAt(0);else{if(ae.length=N,J)for(--F;++ae[--N]>F;)ae[N]=0,N||(++L,ae=[1].concat(ae));for(M=ae.length;!ae[--M];);for(Re=0,T="";Re<=M;T+=O.charAt(ae[Re++]));T=v(T,L,O.charAt(0))}return T}})(),R=(function(){function C(I,F,B){var $,O,N,L,M=0,J=I.length,oe=F%h,ae=F/h|0;for(I=I.slice();J--;)N=I[J]%h,L=I[J]/h|0,$=ae*N+L*oe,O=oe*N+$%h*h+M,M=(O/B|0)+($/h|0)+ae*L,I[J]=O%B;return M&&(I=[M].concat(I)),I}function E(I,F,B,$){var O,N;if(B!=$)N=B>$?1:-1;else for(O=N=0;O<B;O++)if(I[O]!=F[O]){N=I[O]>F[O]?1:-1;break}return N}function T(I,F,B,$){for(var O=0;B--;)I[B]-=O,O=I[B]<F[B]?1:0,I[B]=O*$+I[B]-F[B];for(;!I[0]&&I.length>1;I.splice(0,1));}return function(I,F,B,$,O){var N,L,M,J,oe,ae,Ee,Re,Oe,we,De,Ke,ln,_s,fo,St,Zn,dt=I.s==F.s?1:-1,Xe=I.c,je=F.c;if(!Xe||!Xe[0]||!je||!je[0])return new z(!I.s||!F.s||(Xe?je&&Xe[0]==je[0]:!je)?NaN:Xe&&Xe[0]==0||!je?dt*0:dt/0);for(Re=new z(dt),Oe=Re.c=[],L=I.e-F.e,dt=B+L+1,O||(O=c,L=y(I.e/l)-y(F.e/l),dt=dt/l|0),M=0;je[M]==(Xe[M]||0);M++);if(je[M]>(Xe[M]||0)&&L--,dt<0)Oe.push(1),J=!0;else{for(_s=Xe.length,St=je.length,M=0,dt+=2,oe=o(O/(je[0]+1)),oe>1&&(je=C(je,oe,O),Xe=C(Xe,oe,O),St=je.length,_s=Xe.length),ln=St,we=Xe.slice(0,St),De=we.length;De<St;we[De++]=0);Zn=je.slice(),Zn=[0].concat(Zn),fo=je[0],je[1]>=O/2&&fo++;do{if(oe=0,N=E(je,we,St,De),N<0){if(Ke=we[0],St!=De&&(Ke=Ke*O+(we[1]||0)),oe=o(Ke/fo),oe>1)for(oe>=O&&(oe=O-1),ae=C(je,oe,O),Ee=ae.length,De=we.length;E(ae,we,Ee,De)==1;)oe--,T(ae,St<Ee?Zn:je,Ee,O),Ee=ae.length,N=1;else oe==0&&(N=oe=1),ae=je.slice(),Ee=ae.length;if(Ee<De&&(ae=[0].concat(ae)),T(we,ae,De,O),De=we.length,N==-1)for(;E(je,we,St,De)<1;)oe++,T(we,St<De?Zn:je,De,O),De=we.length}else N===0&&(oe++,we=[0]);Oe[M++]=oe,we[0]?we[De++]=Xe[ln]||0:(we=[Xe[ln]],De=1)}while((ln++<_s||we[0]!=null)&&dt--);J=we[0]!=null,Oe[0]||Oe.splice(0,1)}if(O==c){for(M=1,dt=Oe[0];dt>=10;dt/=10,M++);ye(Re,B+(Re.e=M+L*l-1)+1,$,J)}else Re.e=L,Re.r=+J;return Re}})();function ge(C,E,T,I){var F,B,$,O,N;if(T==null?T=ne:_(T,0,8),!C.c)return C.toString();if(F=C.c[0],$=C.e,E==null)N=w(C.c),N=I==1||I==2&&($<=te||$>=re)?k(N,$):v(N,$,"0");else if(C=ye(new z(C),E,T),B=C.e,N=w(C.c),O=N.length,I==1||I==2&&(E<=B||B<=te)){for(;O<E;N+="0",O++);N=k(N,B)}else if(E-=$+(I===2&&B>$),N=v(N,B,"0"),B+1>O){if(--E>0)for(N+=".";E--;N+="0");}else if(E+=B-O,E>0)for(B+1==O&&(N+=".");E--;N+="0");return C.s<0&&F?"-"+N:N}function Fe(C,E){for(var T,I,F=1,B=new z(C[0]);F<C.length;F++)I=new z(C[F]),(!I.s||(T=b(B,I))===E||T===0&&B.s===E)&&(B=I);return B}function xe(C,E,T){for(var I=1,F=E.length;!E[--F];E.pop());for(F=E[0];F>=10;F/=10,I++);return(T=I+T*l-1)>se?C.c=C.e=null:T<K?C.c=[C.e=0]:(C.e=T,C.c=E),C}W=(function(){var C=/^(-?)0([xbo])(?=\w[\w.]*$)/i,E=/^([^.]+)\.$/,T=/^\.([^.]+)$/,I=/^-?(Infinity|NaN)$/,F=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(B,$,O,N){var L,M=O?$:$.replace(F,"");if(I.test(M))B.s=isNaN(M)?null:M<0?-1:1;else{if(!O&&(M=M.replace(C,function(J,oe,ae){return L=(ae=ae.toLowerCase())=="x"?16:ae=="b"?2:8,!N||N==L?oe:J}),N&&(L=N,M=M.replace(E,"$1").replace(T,"0.$1")),$!=M))return new z(M,L);if(z.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+$);B.s=null}B.c=B.e=null}})();function ye(C,E,T,I){var F,B,$,O,N,L,M,J=C.c,oe=d;if(J){e:{for(F=1,O=J[0];O>=10;O/=10,F++);if(B=E-F,B<0)B+=l,$=E,N=J[L=0],M=o(N/oe[F-$-1]%10);else if(L=r((B+1)/l),L>=J.length)if(I){for(;J.length<=L;J.push(0));N=M=0,F=1,B%=l,$=B-l+1}else break e;else{for(N=O=J[L],F=1;O>=10;O/=10,F++);B%=l,$=B-l+F,M=$<0?0:o(N/oe[F-$-1]%10)}if(I=I||E<0||J[L+1]!=null||($<0?N:N%oe[F-$-1]),I=T<4?(M||I)&&(T==0||T==(C.s<0?3:2)):M>5||M==5&&(T==4||I||T==6&&(B>0?$>0?N/oe[F-$]:0:J[L-1])%10&1||T==(C.s<0?8:7)),E<1||!J[0])return J.length=0,I?(E-=C.e+1,J[0]=oe[(l-E%l)%l],C.e=-E||0):J[0]=C.e=0,C;if(B==0?(J.length=L,O=1,L--):(J.length=L+1,O=oe[l-B],J[L]=$>0?o(N/oe[F-$]%oe[$])*O:0),I)for(;;)if(L==0){for(B=1,$=J[0];$>=10;$/=10,B++);for($=J[0]+=O,O=1;$>=10;$/=10,O++);B!=O&&(C.e++,J[0]==c&&(J[0]=1));break}else{if(J[L]+=O,J[L]!=c)break;J[L--]=0,O=1}for(B=J.length;J[--B]===0;J.pop());}C.e>se?C.c=C.e=null:C.e<K&&(C.c=[C.e=0])}return C}function be(C){var E,T=C.e;return T===null?C.toString():(E=w(C.c),E=T<=te||T>=re?k(E,T):v(E,T,"0"),C.s<0?"-"+E:E)}return U.absoluteValue=U.abs=function(){var C=new z(this);return C.s<0&&(C.s=1),C},U.comparedTo=function(C,E){return b(this,new z(C,E))},U.decimalPlaces=U.dp=function(C,E){var T,I,F,B=this;if(C!=null)return _(C,0,m),E==null?E=ne:_(E,0,8),ye(new z(B),C+B.e+1,E);if(!(T=B.c))return null;if(I=((F=T.length-1)-y(this.e/l))*l,F=T[F])for(;F%10==0;F/=10,I--);return I<0&&(I=0),I},U.dividedBy=U.div=function(C,E){return R(this,new z(C,E),Y,ne)},U.dividedToIntegerBy=U.idiv=function(C,E){return R(this,new z(C,E),0,1)},U.exponentiatedBy=U.pow=function(C,E){var T,I,F,B,$,O,N,L,M,J=this;if(C=new z(C),C.c&&!C.isInteger())throw Error(s+"Exponent not an integer: "+be(C));if(E!=null&&(E=new z(E)),O=C.e>14,!J.c||!J.c[0]||J.c[0]==1&&!J.e&&J.c.length==1||!C.c||!C.c[0])return M=new z(Math.pow(+be(J),O?C.s*(2-D(C)):+be(C))),E?M.mod(E):M;if(N=C.s<0,E){if(E.c?!E.c[0]:!E.s)return new z(NaN);I=!N&&J.isInteger()&&E.isInteger(),I&&(J=J.mod(E))}else{if(C.e>9&&(J.e>0||J.e<-1||(J.e==0?J.c[0]>1||O&&J.c[1]>=24e7:J.c[0]<8e13||O&&J.c[0]<=9999975e7)))return B=J.s<0&&D(C)?-0:0,J.e>-1&&(B=1/B),new z(N?1/B:B);Z&&(B=r(Z/l+2))}for(O?(T=new z(.5),N&&(C.s=1),L=D(C)):(F=Math.abs(+be(C)),L=F%2),M=new z(ue);;){if(L){if(M=M.times(J),!M.c)break;B?M.c.length>B&&(M.c.length=B):I&&(M=M.mod(E))}if(F){if(F=o(F/2),F===0)break;L=F%2}else if(C=C.times(T),ye(C,C.e+1,1),C.e>14)L=D(C);else{if(F=+be(C),F===0)break;L=F%2}J=J.times(J),B?J.c&&J.c.length>B&&(J.c.length=B):I&&(J=J.mod(E))}return I?M:(N&&(M=ue.div(M)),E?M.mod(E):B?ye(M,Z,ne,$):M)},U.integerValue=function(C){var E=new z(this);return C==null?C=ne:_(C,0,8),ye(E,E.e+1,C)},U.isEqualTo=U.eq=function(C,E){return b(this,new z(C,E))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(C,E){return b(this,new z(C,E))>0},U.isGreaterThanOrEqualTo=U.gte=function(C,E){return(E=b(this,new z(C,E)))===1||E===0},U.isInteger=function(){return!!this.c&&y(this.e/l)>this.c.length-2},U.isLessThan=U.lt=function(C,E){return b(this,new z(C,E))<0},U.isLessThanOrEqualTo=U.lte=function(C,E){return(E=b(this,new z(C,E)))===-1||E===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(C,E){var T,I,F,B,$=this,O=$.s;if(C=new z(C,E),E=C.s,!O||!E)return new z(NaN);if(O!=E)return C.s=-E,$.plus(C);var N=$.e/l,L=C.e/l,M=$.c,J=C.c;if(!N||!L){if(!M||!J)return M?(C.s=-E,C):new z(J?$:NaN);if(!M[0]||!J[0])return J[0]?(C.s=-E,C):new z(M[0]?$:ne==3?-0:0)}if(N=y(N),L=y(L),M=M.slice(),O=N-L){for((B=O<0)?(O=-O,F=M):(L=N,F=J),F.reverse(),E=O;E--;F.push(0));F.reverse()}else for(I=(B=(O=M.length)<(E=J.length))?O:E,O=E=0;E<I;E++)if(M[E]!=J[E]){B=M[E]<J[E];break}if(B&&(F=M,M=J,J=F,C.s=-C.s),E=(I=J.length)-(T=M.length),E>0)for(;E--;M[T++]=0);for(E=c-1;I>O;){if(M[--I]<J[I]){for(T=I;T&&!M[--T];M[T]=E);--M[T],M[I]+=c}M[I]-=J[I]}for(;M[0]==0;M.splice(0,1),--L);return M[0]?xe(C,M,L):(C.s=ne==3?-1:1,C.c=[C.e=0],C)},U.modulo=U.mod=function(C,E){var T,I,F=this;return C=new z(C,E),!F.c||!C.s||C.c&&!C.c[0]?new z(NaN):!C.c||F.c&&!F.c[0]?new z(F):(X==9?(I=C.s,C.s=1,T=R(F,C,0,3),C.s=I,T.s*=I):T=R(F,C,0,X),C=F.minus(T.times(C)),!C.c[0]&&X==1&&(C.s=F.s),C)},U.multipliedBy=U.times=function(C,E){var T,I,F,B,$,O,N,L,M,J,oe,ae,Ee,Re,Oe,we=this,De=we.c,Ke=(C=new z(C,E)).c;if(!De||!Ke||!De[0]||!Ke[0])return!we.s||!C.s||De&&!De[0]&&!Ke||Ke&&!Ke[0]&&!De?C.c=C.e=C.s=null:(C.s*=we.s,!De||!Ke?C.c=C.e=null:(C.c=[0],C.e=0)),C;for(I=y(we.e/l)+y(C.e/l),C.s*=we.s,N=De.length,J=Ke.length,N<J&&(Ee=De,De=Ke,Ke=Ee,F=N,N=J,J=F),F=N+J,Ee=[];F--;Ee.push(0));for(Re=c,Oe=h,F=J;--F>=0;){for(T=0,oe=Ke[F]%Oe,ae=Ke[F]/Oe|0,$=N,B=F+$;B>F;)L=De[--$]%Oe,M=De[$]/Oe|0,O=ae*L+M*oe,L=oe*L+O%Oe*Oe+Ee[B]+T,T=(L/Re|0)+(O/Oe|0)+ae*M,Ee[B--]=L%Re;Ee[B]=T}return T?++I:Ee.splice(0,1),xe(C,Ee,I)},U.negated=function(){var C=new z(this);return C.s=-C.s||null,C},U.plus=function(C,E){var T,I=this,F=I.s;if(C=new z(C,E),E=C.s,!F||!E)return new z(NaN);if(F!=E)return C.s=-E,I.minus(C);var B=I.e/l,$=C.e/l,O=I.c,N=C.c;if(!B||!$){if(!O||!N)return new z(F/0);if(!O[0]||!N[0])return N[0]?C:new z(O[0]?I:F*0)}if(B=y(B),$=y($),O=O.slice(),F=B-$){for(F>0?($=B,T=N):(F=-F,T=O),T.reverse();F--;T.push(0));T.reverse()}for(F=O.length,E=N.length,F-E<0&&(T=N,N=O,O=T,E=F),F=0;E;)F=(O[--E]=O[E]+N[E]+F)/c|0,O[E]=c===O[E]?0:O[E]%c;return F&&(O=[F].concat(O),++$),xe(C,O,$)},U.precision=U.sd=function(C,E){var T,I,F,B=this;if(C!=null&&C!==!!C)return _(C,1,m),E==null?E=ne:_(E,0,8),ye(new z(B),C,E);if(!(T=B.c))return null;if(F=T.length-1,I=F*l+1,F=T[F]){for(;F%10==0;F/=10,I--);for(F=T[0];F>=10;F/=10,I++);}return C&&B.e+1>I&&(I=B.e+1),I},U.shiftedBy=function(C){return _(C,-f,f),this.times("1e"+C)},U.squareRoot=U.sqrt=function(){var C,E,T,I,F,B=this,$=B.c,O=B.s,N=B.e,L=Y+4,M=new z("0.5");if(O!==1||!$||!$[0])return new z(!O||O<0&&(!$||$[0])?NaN:$?B:1/0);if(O=Math.sqrt(+be(B)),O==0||O==1/0?(E=w($),(E.length+N)%2==0&&(E+="0"),O=Math.sqrt(+E),N=y((N+1)/2)-(N<0||N%2),O==1/0?E="5e"+N:(E=O.toExponential(),E=E.slice(0,E.indexOf("e")+1)+N),T=new z(E)):T=new z(O+""),T.c[0]){for(N=T.e,O=N+L,O<3&&(O=0);;)if(F=T,T=M.times(F.plus(R(B,F,L,1))),w(F.c).slice(0,O)===(E=w(T.c)).slice(0,O))if(T.e<N&&--O,E=E.slice(O-3,O+1),E=="9999"||!I&&E=="4999"){if(!I&&(ye(F,F.e+Y+2,0),F.times(F).eq(B))){T=F;break}L+=4,O+=4,I=1}else{(!+E||!+E.slice(1)&&E.charAt(0)=="5")&&(ye(T,T.e+Y+2,1),C=!T.times(T).eq(B));break}}return ye(T,T.e+Y+1,ne,C)},U.toExponential=function(C,E){return C!=null&&(_(C,0,m),C++),ge(this,C,E,1)},U.toFixed=function(C,E){return C!=null&&(_(C,0,m),C=C+this.e+1),ge(this,C,E)},U.toFormat=function(C,E,T){var I,F=this;if(T==null)C!=null&&E&&typeof E=="object"?(T=E,E=null):C&&typeof C=="object"?(T=C,C=E=null):T=Q;else if(typeof T!="object")throw Error(s+"Argument not an object: "+T);if(I=F.toFixed(C,E),F.c){var B,$=I.split("."),O=+T.groupSize,N=+T.secondaryGroupSize,L=T.groupSeparator||"",M=$[0],J=$[1],oe=F.s<0,ae=oe?M.slice(1):M,Ee=ae.length;if(N&&(B=O,O=N,N=B,Ee-=B),O>0&&Ee>0){for(B=Ee%O||O,M=ae.substr(0,B);B<Ee;B+=O)M+=L+ae.substr(B,O);N>0&&(M+=L+ae.slice(B)),oe&&(M="-"+M)}I=J?M+(T.decimalSeparator||"")+((N=+T.fractionGroupSize)?J.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(T.fractionGroupSeparator||"")):J):M}return(T.prefix||"")+I+(T.suffix||"")},U.toFraction=function(C){var E,T,I,F,B,$,O,N,L,M,J,oe,ae=this,Ee=ae.c;if(C!=null&&(O=new z(C),!O.isInteger()&&(O.c||O.s!==1)||O.lt(ue)))throw Error(s+"Argument "+(O.isInteger()?"out of range: ":"not an integer: ")+be(O));if(!Ee)return new z(ae);for(E=new z(ue),L=T=new z(ue),I=N=new z(ue),oe=w(Ee),B=E.e=oe.length-ae.e-1,E.c[0]=d[($=B%l)<0?l+$:$],C=!C||O.comparedTo(E)>0?B>0?E:L:O,$=se,se=1/0,O=new z(oe),N.c[0]=0;M=R(O,E,0,1),F=T.plus(M.times(I)),F.comparedTo(C)!=1;)T=I,I=F,L=N.plus(M.times(F=L)),N=F,E=O.minus(M.times(F=E)),O=F;return F=R(C.minus(T),I,0,1),N=N.plus(F.times(L)),T=T.plus(F.times(I)),N.s=L.s=ae.s,B=B*2,J=R(L,I,B,ne).minus(ae).abs().comparedTo(R(N,T,B,ne).minus(ae).abs())<1?[L,I]:[N,T],se=$,J},U.toNumber=function(){return+be(this)},U.toPrecision=function(C,E){return C!=null&&_(C,1,m),ge(this,C,E,2)},U.toString=function(C){var E,T=this,I=T.s,F=T.e;return F===null?I?(E="Infinity",I<0&&(E="-"+E)):E="NaN":(C==null?E=F<=te||F>=re?k(w(T.c),F):v(w(T.c),F,"0"):C===10&&he?(T=ye(new z(T),Y+F+1,ne),E=v(w(T.c),T.e,"0")):(_(C,2,me.length,"Base"),E=j(v(w(T.c),F,"0"),10,C,I,!0)),I<0&&T.c[0]&&(E="-"+E)),E},U.valueOf=U.toJSON=function(){return be(this)},U._isBigNumber=!0,x!=null&&z.set(x),z}function y(x){var R=x|0;return x>0||x===R?R:R-1}function w(x){for(var R,j,W=1,U=x.length,ue=x[0]+"";W<U;){for(R=x[W++]+"",j=l-R.length;j--;R="0"+R);ue+=R}for(U=ue.length;ue.charCodeAt(--U)===48;);return ue.slice(0,U+1||1)}function b(x,R){var j,W,U=x.c,ue=R.c,Y=x.s,ne=R.s,te=x.e,re=R.e;if(!Y||!ne)return null;if(j=U&&!U[0],W=ue&&!ue[0],j||W)return j?W?0:-ne:Y;if(Y!=ne)return Y;if(j=Y<0,W=te==re,!U||!ue)return W?0:!U^j?1:-1;if(!W)return te>re^j?1:-1;for(ne=(te=U.length)<(re=ue.length)?te:re,Y=0;Y<ne;Y++)if(U[Y]!=ue[Y])return U[Y]>ue[Y]^j?1:-1;return te==re?0:te>re^j?1:-1}function _(x,R,j,W){if(x<R||x>j||x!==o(x))throw Error(s+(W||"Argument")+(typeof x=="number"?x<R||x>j?" out of range: ":" not an integer: ":" not a primitive number: ")+String(x))}function D(x){var R=x.c.length-1;return y(x.e/l)==R&&x.c[R]%2!=0}function k(x,R){return(x.length>1?x.charAt(0)+"."+x.slice(1):x)+(R<0?"e":"e+")+R}function v(x,R,j){var W,U;if(R<0){for(U=j+".";++R;U+=j);x=U+x}else if(W=x.length,++R>W){for(U=j,R-=W;--R;U+=j);x+=U}else R<W&&(x=x.slice(0,R)+"."+x.slice(R));return x}e=S(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof Cc<"u"&&Cc.exports?Cc.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Xb)});var tw=V((Rj,ew)=>{var Qb=qf(),Zb=ew.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},a;function c(f){return n.lastIndex=0,n.test(f)?'"'+f.replace(n,function(d){var h=s[d];return typeof h=="string"?h:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function l(f,d){var h,m,S,y,w=r,b,_=d[f],D=_!=null&&(_ instanceof Qb||Qb.isBigNumber(_));switch(_&&typeof _=="object"&&typeof _.toJSON=="function"&&(_=_.toJSON(f)),typeof a=="function"&&(_=a.call(d,f,_)),typeof _){case"string":return D?_:c(_);case"number":return isFinite(_)?String(_):"null";case"boolean":case"null":case"bigint":return String(_);case"object":if(!_)return"null";if(r+=o,b=[],Object.prototype.toString.apply(_)==="[object Array]"){for(y=_.length,h=0;h<y;h+=1)b[h]=l(h,_)||"null";return S=b.length===0?"[]":r?`[
44
- `+r+b.join(`,
72
+ `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>tt(Aw()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>($k(),qk))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,i)=>{i==="set-cookie"?e.append(i,s):e.set(i,s)});return e}};rs.Gaxios=cu;ns=cu});var lt=J(gt=>{"use strict";var _1=gt&&gt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),b1=gt&&gt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_1(e,t,n)};Object.defineProperty(gt,"__esModule",{value:!0});gt.instance=gt.Gaxios=gt.GaxiosError=void 0;gt.request=w1;var Gk=Wk();Object.defineProperty(gt,"Gaxios",{enumerable:!0,get:function(){return Gk.Gaxios}});var C1=Ep();Object.defineProperty(gt,"GaxiosError",{enumerable:!0,get:function(){return C1.GaxiosError}});b1(Tp(),gt);gt.instance=new Gk.Gaxios;async function w1(t){return gt.instance.request(t)}});var nh=J((Jk,uu)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",i=s+"Number primitive has more than 15 significant digits: ",c=1e14,u=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function _(x){var O,q,$,H=K.prototype={constructor:K,toString:null,valueOf:null},ae=new K(1),X=20,te=4,Z=-7,De=21,qe=-1e7,Te=1e7,We=!1,ee=1,Q=0,se={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},le="0123456789abcdefghijklmnopqrstuvwxyz",be=!0;function K(k,E){var R,M,D,F,j,P,N,U,B=this;if(!(B instanceof K))return new K(k,E);if(E==null){if(k&&k._isBigNumber===!0){B.s=k.s,!k.c||k.e>Te?B.c=B.e=null:k.e<qe?B.c=[B.e=0]:(B.e=k.e,B.c=k.c.slice());return}if((P=typeof k=="number")&&k*0==0){if(B.s=1/k<0?(k=-k,-1):1,k===~~k){for(F=0,j=k;j>=10;j/=10,F++);F>Te?B.c=B.e=null:(B.e=F,B.c=[k]);return}U=String(k)}else{if(!n.test(U=String(k)))return $(B,U,P);B.s=U.charCodeAt(0)==45?(U=U.slice(1),-1):1}(F=U.indexOf("."))>-1&&(U=U.replace(".","")),(j=U.search(/e/i))>0?(F<0&&(F=j),F+=+U.slice(j+1),U=U.substring(0,j)):F<0&&(F=U.length)}else{if(C(E,2,le.length,"Base"),E==10&&be)return B=new K(k),ce(B,X+B.e+1,te);if(U=String(k),P=typeof k=="number"){if(k*0!=0)return $(B,U,P,E);if(B.s=1/k<0?(U=U.slice(1),-1):1,K.DEBUG&&U.replace(/^0\.0*|\./,"").length>15)throw Error(i+k)}else B.s=U.charCodeAt(0)===45?(U=U.slice(1),-1):1;for(R=le.slice(0,E),F=j=0,N=U.length;j<N;j++)if(R.indexOf(M=U.charAt(j))<0){if(M=="."){if(j>F){F=N;continue}}else if(!D&&(U==U.toUpperCase()&&(U=U.toLowerCase())||U==U.toLowerCase()&&(U=U.toUpperCase()))){D=!0,j=-1,F=0;continue}return $(B,String(k),P,E)}P=!1,U=q(U,E,10,B.s),(F=U.indexOf("."))>-1?U=U.replace(".",""):F=U.length}for(j=0;U.charCodeAt(j)===48;j++);for(N=U.length;U.charCodeAt(--N)===48;);if(U=U.slice(j,++N)){if(N-=j,P&&K.DEBUG&&N>15&&(k>f||k!==o(k)))throw Error(i+B.s*k);if((F=F-j-1)>Te)B.c=B.e=null;else if(F<qe)B.c=[B.e=0];else{if(B.e=F,B.c=[],j=(F+1)%u,F<0&&(j+=u),j<N){for(j&&B.c.push(+U.slice(0,j)),N-=u;j<N;)B.c.push(+U.slice(j,j+=u));j=u-(U=U.slice(j)).length}else j-=N;for(;j--;U+="0");B.c.push(+U)}}else B.c=[B.e=0]}K.clone=_,K.ROUND_UP=0,K.ROUND_DOWN=1,K.ROUND_CEIL=2,K.ROUND_FLOOR=3,K.ROUND_HALF_UP=4,K.ROUND_HALF_DOWN=5,K.ROUND_HALF_EVEN=6,K.ROUND_HALF_CEIL=7,K.ROUND_HALF_FLOOR=8,K.EUCLID=9,K.config=K.set=function(k){var E,R;if(k!=null)if(typeof k=="object"){if(k.hasOwnProperty(E="DECIMAL_PLACES")&&(R=k[E],C(R,0,h,E),X=R),k.hasOwnProperty(E="ROUNDING_MODE")&&(R=k[E],C(R,0,8,E),te=R),k.hasOwnProperty(E="EXPONENTIAL_AT")&&(R=k[E],R&&R.pop?(C(R[0],-h,0,E),C(R[1],0,h,E),Z=R[0],De=R[1]):(C(R,-h,h,E),Z=-(De=R<0?-R:R))),k.hasOwnProperty(E="RANGE"))if(R=k[E],R&&R.pop)C(R[0],-h,-1,E),C(R[1],1,h,E),qe=R[0],Te=R[1];else if(C(R,-h,h,E),R)qe=-(Te=R<0?-R:R);else throw Error(s+E+" cannot be zero: "+R);if(k.hasOwnProperty(E="CRYPTO"))if(R=k[E],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))We=R;else throw We=!R,Error(s+"crypto unavailable");else We=R;else throw Error(s+E+" not true or false: "+R);if(k.hasOwnProperty(E="MODULO_MODE")&&(R=k[E],C(R,0,9,E),ee=R),k.hasOwnProperty(E="POW_PRECISION")&&(R=k[E],C(R,0,h,E),Q=R),k.hasOwnProperty(E="FORMAT"))if(R=k[E],typeof R=="object")se=R;else throw Error(s+E+" not an object: "+R);if(k.hasOwnProperty(E="ALPHABET"))if(R=k[E],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))be=R.slice(0,10)=="0123456789",le=R;else throw Error(s+E+" invalid: "+R)}else throw Error(s+"Object expected: "+k);return{DECIMAL_PLACES:X,ROUNDING_MODE:te,EXPONENTIAL_AT:[Z,De],RANGE:[qe,Te],CRYPTO:We,MODULO_MODE:ee,POW_PRECISION:Q,FORMAT:se,ALPHABET:le}},K.isBigNumber=function(k){if(!k||k._isBigNumber!==!0)return!1;if(!K.DEBUG)return!0;var E,R,M=k.c,D=k.e,F=k.s;e:if({}.toString.call(M)=="[object Array]"){if((F===1||F===-1)&&D>=-h&&D<=h&&D===o(D)){if(M[0]===0){if(D===0&&M.length===1)return!0;break e}if(E=(D+1)%u,E<1&&(E+=u),String(M[0]).length==E){for(E=0;E<M.length;E++)if(R=M[E],R<0||R>=c||R!==o(R))break e;if(R!==0)return!0}}}else if(M===null&&D===null&&(F===null||F===1||F===-1))return!0;throw Error(s+"Invalid BigNumber: "+k)},K.maximum=K.max=function(){return Fe(arguments,-1)},K.minimum=K.min=function(){return Fe(arguments,1)},K.random=(function(){var k=9007199254740992,E=Math.random()*k&2097151?function(){return o(Math.random()*k)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var M,D,F,j,P,N=0,U=[],B=new K(ae);if(R==null?R=X:C(R,0,h),j=r(R/u),We)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(j*=2));N<j;)P=M[N]*131072+(M[N+1]>>>11),P>=9e15?(D=crypto.getRandomValues(new Uint32Array(2)),M[N]=D[0],M[N+1]=D[1]):(U.push(P%1e14),N+=2);N=j/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(j*=7);N<j;)P=(M[N]&31)*281474976710656+M[N+1]*1099511627776+M[N+2]*4294967296+M[N+3]*16777216+(M[N+4]<<16)+(M[N+5]<<8)+M[N+6],P>=9e15?crypto.randomBytes(7).copy(M,N):(U.push(P%1e14),N+=7);N=j/7}else throw We=!1,Error(s+"crypto unavailable");if(!We)for(;N<j;)P=E(),P<9e15&&(U[N++]=P%1e14);for(j=U[--N],R%=u,j&&R&&(P=d[u-R],U[N]=o(j/P)*P);U[N]===0;U.pop(),N--);if(N<0)U=[F=0];else{for(F=-1;U[0]===0;U.splice(0,1),F-=u);for(N=1,P=U[0];P>=10;P/=10,N++);N<u&&(F-=u-N)}return B.e=F,B.c=U,B}})(),K.sum=function(){for(var k=1,E=arguments,R=new K(E[0]);k<E.length;)R=R.plus(E[k++]);return R},q=(function(){var k="0123456789";function E(R,M,D,F){for(var j,P=[0],N,U=0,B=R.length;U<B;){for(N=P.length;N--;P[N]*=M);for(P[0]+=F.indexOf(R.charAt(U++)),j=0;j<P.length;j++)P[j]>D-1&&(P[j+1]==null&&(P[j+1]=0),P[j+1]+=P[j]/D|0,P[j]%=D)}return P.reverse()}return function(R,M,D,F,j){var P,N,U,B,G,oe,ie,_e,ge=R.indexOf("."),he=X,ye=te;for(ge>=0&&(B=Q,Q=0,R=R.replace(".",""),_e=new K(M),oe=_e.pow(R.length-ge),Q=B,_e.c=E(T(y(oe.c),oe.e,"0"),10,D,k),_e.e=_e.c.length),ie=E(R,M,D,j?(P=le,k):(P=k,le)),U=B=ie.length;ie[--B]==0;ie.pop());if(!ie[0])return P.charAt(0);if(ge<0?--U:(oe.c=ie,oe.e=U,oe.s=F,oe=O(oe,_e,he,ye,D),ie=oe.c,G=oe.r,U=oe.e),N=U+he+1,ge=ie[N],B=D/2,G=G||N<0||ie[N+1]!=null,G=ye<4?(ge!=null||G)&&(ye==0||ye==(oe.s<0?3:2)):ge>B||ge==B&&(ye==4||G||ye==6&&ie[N-1]&1||ye==(oe.s<0?8:7)),N<1||!ie[0])R=G?T(P.charAt(1),-he,P.charAt(0)):P.charAt(0);else{if(ie.length=N,G)for(--D;++ie[--N]>D;)ie[N]=0,N||(++U,ie=[1].concat(ie));for(B=ie.length;!ie[--B];);for(ge=0,R="";ge<=B;R+=P.charAt(ie[ge++]));R=T(R,U,P.charAt(0))}return R}})(),O=(function(){function k(M,D,F){var j,P,N,U,B=0,G=M.length,oe=D%p,ie=D/p|0;for(M=M.slice();G--;)N=M[G]%p,U=M[G]/p|0,j=ie*N+U*oe,P=oe*N+j%p*p+B,B=(P/F|0)+(j/p|0)+ie*U,M[G]=P%F;return B&&(M=[B].concat(M)),M}function E(M,D,F,j){var P,N;if(F!=j)N=F>j?1:-1;else for(P=N=0;P<F;P++)if(M[P]!=D[P]){N=M[P]>D[P]?1:-1;break}return N}function R(M,D,F,j){for(var P=0;F--;)M[F]-=P,P=M[F]<D[F]?1:0,M[F]=P*j+M[F]-D[F];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,D,F,j,P){var N,U,B,G,oe,ie,_e,ge,he,ye,xe,Ye,fn,Us,Eo,vt,sr,ft=M.s==D.s?1:-1,Qe=M.c,Ne=D.c;if(!Qe||!Qe[0]||!Ne||!Ne[0])return new K(!M.s||!D.s||(Qe?Ne&&Qe[0]==Ne[0]:!Ne)?NaN:Qe&&Qe[0]==0||!Ne?ft*0:ft/0);for(ge=new K(ft),he=ge.c=[],U=M.e-D.e,ft=F+U+1,P||(P=c,U=b(M.e/u)-b(D.e/u),ft=ft/u|0),B=0;Ne[B]==(Qe[B]||0);B++);if(Ne[B]>(Qe[B]||0)&&U--,ft<0)he.push(1),G=!0;else{for(Us=Qe.length,vt=Ne.length,B=0,ft+=2,oe=o(P/(Ne[0]+1)),oe>1&&(Ne=k(Ne,oe,P),Qe=k(Qe,oe,P),vt=Ne.length,Us=Qe.length),fn=vt,ye=Qe.slice(0,vt),xe=ye.length;xe<vt;ye[xe++]=0);sr=Ne.slice(),sr=[0].concat(sr),Eo=Ne[0],Ne[1]>=P/2&&Eo++;do{if(oe=0,N=E(Ne,ye,vt,xe),N<0){if(Ye=ye[0],vt!=xe&&(Ye=Ye*P+(ye[1]||0)),oe=o(Ye/Eo),oe>1)for(oe>=P&&(oe=P-1),ie=k(Ne,oe,P),_e=ie.length,xe=ye.length;E(ie,ye,_e,xe)==1;)oe--,R(ie,vt<_e?sr:Ne,_e,P),_e=ie.length,N=1;else oe==0&&(N=oe=1),ie=Ne.slice(),_e=ie.length;if(_e<xe&&(ie=[0].concat(ie)),R(ye,ie,xe,P),xe=ye.length,N==-1)for(;E(Ne,ye,vt,xe)<1;)oe++,R(ye,vt<xe?sr:Ne,xe,P),xe=ye.length}else N===0&&(oe++,ye=[0]);he[B++]=oe,ye[0]?ye[xe++]=Qe[fn]||0:(ye=[Qe[fn]],xe=1)}while((fn++<Us||ye[0]!=null)&&ft--);G=ye[0]!=null,he[0]||he.splice(0,1)}if(P==c){for(B=1,ft=he[0];ft>=10;ft/=10,B++);ce(ge,F+(ge.e=B+U*u-1)+1,j,G)}else ge.e=U,ge.r=+G;return ge}})();function Ke(k,E,R,M){var D,F,j,P,N;if(R==null?R=te:C(R,0,8),!k.c)return k.toString();if(D=k.c[0],j=k.e,E==null)N=y(k.c),N=M==1||M==2&&(j<=Z||j>=De)?A(N,j):T(N,j,"0");else if(k=ce(new K(k),E,R),F=k.e,N=y(k.c),P=N.length,M==1||M==2&&(E<=F||F<=Z)){for(;P<E;N+="0",P++);N=A(N,F)}else if(E-=j+(M===2&&F>j),N=T(N,F,"0"),F+1>P){if(--E>0)for(N+=".";E--;N+="0");}else if(E+=F-P,E>0)for(F+1==P&&(N+=".");E--;N+="0");return k.s<0&&D?"-"+N:N}function Fe(k,E){for(var R,M,D=1,F=new K(k[0]);D<k.length;D++)M=new K(k[D]),(!M.s||(R=w(F,M))===E||R===0&&F.s===E)&&(F=M);return F}function Y(k,E,R){for(var M=1,D=E.length;!E[--D];E.pop());for(D=E[0];D>=10;D/=10,M++);return(R=M+R*u-1)>Te?k.c=k.e=null:R<qe?k.c=[k.e=0]:(k.e=R,k.c=E),k}$=(function(){var k=/^(-?)0([xbo])(?=\w[\w.]*$)/i,E=/^([^.]+)\.$/,R=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,D=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(F,j,P,N){var U,B=P?j:j.replace(D,"");if(M.test(B))F.s=isNaN(B)?null:B<0?-1:1;else{if(!P&&(B=B.replace(k,function(G,oe,ie){return U=(ie=ie.toLowerCase())=="x"?16:ie=="b"?2:8,!N||N==U?oe:G}),N&&(U=N,B=B.replace(E,"$1").replace(R,"0.$1")),j!=B))return new K(B,U);if(K.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+j);F.s=null}F.c=F.e=null}})();function ce(k,E,R,M){var D,F,j,P,N,U,B,G=k.c,oe=d;if(G){e:{for(D=1,P=G[0];P>=10;P/=10,D++);if(F=E-D,F<0)F+=u,j=E,N=G[U=0],B=o(N/oe[D-j-1]%10);else if(U=r((F+1)/u),U>=G.length)if(M){for(;G.length<=U;G.push(0));N=B=0,D=1,F%=u,j=F-u+1}else break e;else{for(N=P=G[U],D=1;P>=10;P/=10,D++);F%=u,j=F-u+D,B=j<0?0:o(N/oe[D-j-1]%10)}if(M=M||E<0||G[U+1]!=null||(j<0?N:N%oe[D-j-1]),M=R<4?(B||M)&&(R==0||R==(k.s<0?3:2)):B>5||B==5&&(R==4||M||R==6&&(F>0?j>0?N/oe[D-j]:0:G[U-1])%10&1||R==(k.s<0?8:7)),E<1||!G[0])return G.length=0,M?(E-=k.e+1,G[0]=oe[(u-E%u)%u],k.e=-E||0):G[0]=k.e=0,k;if(F==0?(G.length=U,P=1,U--):(G.length=U+1,P=oe[u-F],G[U]=j>0?o(N/oe[D-j]%oe[j])*P:0),M)for(;;)if(U==0){for(F=1,j=G[0];j>=10;j/=10,F++);for(j=G[0]+=P,P=1;j>=10;j/=10,P++);F!=P&&(k.e++,G[0]==c&&(G[0]=1));break}else{if(G[U]+=P,G[U]!=c)break;G[U--]=0,P=1}for(F=G.length;G[--F]===0;G.pop());}k.e>Te?k.c=k.e=null:k.e<qe&&(k.c=[k.e=0])}return k}function de(k){var E,R=k.e;return R===null?k.toString():(E=y(k.c),E=R<=Z||R>=De?A(E,R):T(E,R,"0"),k.s<0?"-"+E:E)}return H.absoluteValue=H.abs=function(){var k=new K(this);return k.s<0&&(k.s=1),k},H.comparedTo=function(k,E){return w(this,new K(k,E))},H.decimalPlaces=H.dp=function(k,E){var R,M,D,F=this;if(k!=null)return C(k,0,h),E==null?E=te:C(E,0,8),ce(new K(F),k+F.e+1,E);if(!(R=F.c))return null;if(M=((D=R.length-1)-b(this.e/u))*u,D=R[D])for(;D%10==0;D/=10,M--);return M<0&&(M=0),M},H.dividedBy=H.div=function(k,E){return O(this,new K(k,E),X,te)},H.dividedToIntegerBy=H.idiv=function(k,E){return O(this,new K(k,E),0,1)},H.exponentiatedBy=H.pow=function(k,E){var R,M,D,F,j,P,N,U,B,G=this;if(k=new K(k),k.c&&!k.isInteger())throw Error(s+"Exponent not an integer: "+de(k));if(E!=null&&(E=new K(E)),P=k.e>14,!G.c||!G.c[0]||G.c[0]==1&&!G.e&&G.c.length==1||!k.c||!k.c[0])return B=new K(Math.pow(+de(G),P?k.s*(2-v(k)):+de(k))),E?B.mod(E):B;if(N=k.s<0,E){if(E.c?!E.c[0]:!E.s)return new K(NaN);M=!N&&G.isInteger()&&E.isInteger(),M&&(G=G.mod(E))}else{if(k.e>9&&(G.e>0||G.e<-1||(G.e==0?G.c[0]>1||P&&G.c[1]>=24e7:G.c[0]<8e13||P&&G.c[0]<=9999975e7)))return F=G.s<0&&v(k)?-0:0,G.e>-1&&(F=1/F),new K(N?1/F:F);Q&&(F=r(Q/u+2))}for(P?(R=new K(.5),N&&(k.s=1),U=v(k)):(D=Math.abs(+de(k)),U=D%2),B=new K(ae);;){if(U){if(B=B.times(G),!B.c)break;F?B.c.length>F&&(B.c.length=F):M&&(B=B.mod(E))}if(D){if(D=o(D/2),D===0)break;U=D%2}else if(k=k.times(R),ce(k,k.e+1,1),k.e>14)U=v(k);else{if(D=+de(k),D===0)break;U=D%2}G=G.times(G),F?G.c&&G.c.length>F&&(G.c.length=F):M&&(G=G.mod(E))}return M?B:(N&&(B=ae.div(B)),E?B.mod(E):F?ce(B,Q,te,j):B)},H.integerValue=function(k){var E=new K(this);return k==null?k=te:C(k,0,8),ce(E,E.e+1,k)},H.isEqualTo=H.eq=function(k,E){return w(this,new K(k,E))===0},H.isFinite=function(){return!!this.c},H.isGreaterThan=H.gt=function(k,E){return w(this,new K(k,E))>0},H.isGreaterThanOrEqualTo=H.gte=function(k,E){return(E=w(this,new K(k,E)))===1||E===0},H.isInteger=function(){return!!this.c&&b(this.e/u)>this.c.length-2},H.isLessThan=H.lt=function(k,E){return w(this,new K(k,E))<0},H.isLessThanOrEqualTo=H.lte=function(k,E){return(E=w(this,new K(k,E)))===-1||E===0},H.isNaN=function(){return!this.s},H.isNegative=function(){return this.s<0},H.isPositive=function(){return this.s>0},H.isZero=function(){return!!this.c&&this.c[0]==0},H.minus=function(k,E){var R,M,D,F,j=this,P=j.s;if(k=new K(k,E),E=k.s,!P||!E)return new K(NaN);if(P!=E)return k.s=-E,j.plus(k);var N=j.e/u,U=k.e/u,B=j.c,G=k.c;if(!N||!U){if(!B||!G)return B?(k.s=-E,k):new K(G?j:NaN);if(!B[0]||!G[0])return G[0]?(k.s=-E,k):new K(B[0]?j:te==3?-0:0)}if(N=b(N),U=b(U),B=B.slice(),P=N-U){for((F=P<0)?(P=-P,D=B):(U=N,D=G),D.reverse(),E=P;E--;D.push(0));D.reverse()}else for(M=(F=(P=B.length)<(E=G.length))?P:E,P=E=0;E<M;E++)if(B[E]!=G[E]){F=B[E]<G[E];break}if(F&&(D=B,B=G,G=D,k.s=-k.s),E=(M=G.length)-(R=B.length),E>0)for(;E--;B[R++]=0);for(E=c-1;M>P;){if(B[--M]<G[M]){for(R=M;R&&!B[--R];B[R]=E);--B[R],B[M]+=c}B[M]-=G[M]}for(;B[0]==0;B.splice(0,1),--U);return B[0]?Y(k,B,U):(k.s=te==3?-1:1,k.c=[k.e=0],k)},H.modulo=H.mod=function(k,E){var R,M,D=this;return k=new K(k,E),!D.c||!k.s||k.c&&!k.c[0]?new K(NaN):!k.c||D.c&&!D.c[0]?new K(D):(ee==9?(M=k.s,k.s=1,R=O(D,k,0,3),k.s=M,R.s*=M):R=O(D,k,0,ee),k=D.minus(R.times(k)),!k.c[0]&&ee==1&&(k.s=D.s),k)},H.multipliedBy=H.times=function(k,E){var R,M,D,F,j,P,N,U,B,G,oe,ie,_e,ge,he,ye=this,xe=ye.c,Ye=(k=new K(k,E)).c;if(!xe||!Ye||!xe[0]||!Ye[0])return!ye.s||!k.s||xe&&!xe[0]&&!Ye||Ye&&!Ye[0]&&!xe?k.c=k.e=k.s=null:(k.s*=ye.s,!xe||!Ye?k.c=k.e=null:(k.c=[0],k.e=0)),k;for(M=b(ye.e/u)+b(k.e/u),k.s*=ye.s,N=xe.length,G=Ye.length,N<G&&(_e=xe,xe=Ye,Ye=_e,D=N,N=G,G=D),D=N+G,_e=[];D--;_e.push(0));for(ge=c,he=p,D=G;--D>=0;){for(R=0,oe=Ye[D]%he,ie=Ye[D]/he|0,j=N,F=D+j;F>D;)U=xe[--j]%he,B=xe[j]/he|0,P=ie*U+B*oe,U=oe*U+P%he*he+_e[F]+R,R=(U/ge|0)+(P/he|0)+ie*B,_e[F--]=U%ge;_e[F]=R}return R?++M:_e.splice(0,1),Y(k,_e,M)},H.negated=function(){var k=new K(this);return k.s=-k.s||null,k},H.plus=function(k,E){var R,M=this,D=M.s;if(k=new K(k,E),E=k.s,!D||!E)return new K(NaN);if(D!=E)return k.s=-E,M.minus(k);var F=M.e/u,j=k.e/u,P=M.c,N=k.c;if(!F||!j){if(!P||!N)return new K(D/0);if(!P[0]||!N[0])return N[0]?k:new K(P[0]?M:D*0)}if(F=b(F),j=b(j),P=P.slice(),D=F-j){for(D>0?(j=F,R=N):(D=-D,R=P),R.reverse();D--;R.push(0));R.reverse()}for(D=P.length,E=N.length,D-E<0&&(R=N,N=P,P=R,E=D),D=0;E;)D=(P[--E]=P[E]+N[E]+D)/c|0,P[E]=c===P[E]?0:P[E]%c;return D&&(P=[D].concat(P),++j),Y(k,P,j)},H.precision=H.sd=function(k,E){var R,M,D,F=this;if(k!=null&&k!==!!k)return C(k,1,h),E==null?E=te:C(E,0,8),ce(new K(F),k,E);if(!(R=F.c))return null;if(D=R.length-1,M=D*u+1,D=R[D]){for(;D%10==0;D/=10,M--);for(D=R[0];D>=10;D/=10,M++);}return k&&F.e+1>M&&(M=F.e+1),M},H.shiftedBy=function(k){return C(k,-f,f),this.times("1e"+k)},H.squareRoot=H.sqrt=function(){var k,E,R,M,D,F=this,j=F.c,P=F.s,N=F.e,U=X+4,B=new K("0.5");if(P!==1||!j||!j[0])return new K(!P||P<0&&(!j||j[0])?NaN:j?F:1/0);if(P=Math.sqrt(+de(F)),P==0||P==1/0?(E=y(j),(E.length+N)%2==0&&(E+="0"),P=Math.sqrt(+E),N=b((N+1)/2)-(N<0||N%2),P==1/0?E="5e"+N:(E=P.toExponential(),E=E.slice(0,E.indexOf("e")+1)+N),R=new K(E)):R=new K(P+""),R.c[0]){for(N=R.e,P=N+U,P<3&&(P=0);;)if(D=R,R=B.times(D.plus(O(F,D,U,1))),y(D.c).slice(0,P)===(E=y(R.c)).slice(0,P))if(R.e<N&&--P,E=E.slice(P-3,P+1),E=="9999"||!M&&E=="4999"){if(!M&&(ce(D,D.e+X+2,0),D.times(D).eq(F))){R=D;break}U+=4,P+=4,M=1}else{(!+E||!+E.slice(1)&&E.charAt(0)=="5")&&(ce(R,R.e+X+2,1),k=!R.times(R).eq(F));break}}return ce(R,R.e+X+1,te,k)},H.toExponential=function(k,E){return k!=null&&(C(k,0,h),k++),Ke(this,k,E,1)},H.toFixed=function(k,E){return k!=null&&(C(k,0,h),k=k+this.e+1),Ke(this,k,E)},H.toFormat=function(k,E,R){var M,D=this;if(R==null)k!=null&&E&&typeof E=="object"?(R=E,E=null):k&&typeof k=="object"?(R=k,k=E=null):R=se;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(M=D.toFixed(k,E),D.c){var F,j=M.split("."),P=+R.groupSize,N=+R.secondaryGroupSize,U=R.groupSeparator||"",B=j[0],G=j[1],oe=D.s<0,ie=oe?B.slice(1):B,_e=ie.length;if(N&&(F=P,P=N,N=F,_e-=F),P>0&&_e>0){for(F=_e%P||P,B=ie.substr(0,F);F<_e;F+=P)B+=U+ie.substr(F,P);N>0&&(B+=U+ie.slice(F)),oe&&(B="-"+B)}M=G?B+(R.decimalSeparator||"")+((N=+R.fractionGroupSize)?G.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):G):B}return(R.prefix||"")+M+(R.suffix||"")},H.toFraction=function(k){var E,R,M,D,F,j,P,N,U,B,G,oe,ie=this,_e=ie.c;if(k!=null&&(P=new K(k),!P.isInteger()&&(P.c||P.s!==1)||P.lt(ae)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+de(P));if(!_e)return new K(ie);for(E=new K(ae),U=R=new K(ae),M=N=new K(ae),oe=y(_e),F=E.e=oe.length-ie.e-1,E.c[0]=d[(j=F%u)<0?u+j:j],k=!k||P.comparedTo(E)>0?F>0?E:U:P,j=Te,Te=1/0,P=new K(oe),N.c[0]=0;B=O(P,E,0,1),D=R.plus(B.times(M)),D.comparedTo(k)!=1;)R=M,M=D,U=N.plus(B.times(D=U)),N=D,E=P.minus(B.times(D=E)),P=D;return D=O(k.minus(R),M,0,1),N=N.plus(D.times(U)),R=R.plus(D.times(M)),N.s=U.s=ie.s,F=F*2,G=O(U,M,F,te).minus(ie).abs().comparedTo(O(N,R,F,te).minus(ie).abs())<1?[U,M]:[N,R],Te=j,G},H.toNumber=function(){return+de(this)},H.toPrecision=function(k,E){return k!=null&&C(k,1,h),Ke(this,k,E,2)},H.toString=function(k){var E,R=this,M=R.s,D=R.e;return D===null?M?(E="Infinity",M<0&&(E="-"+E)):E="NaN":(k==null?E=D<=Z||D>=De?A(y(R.c),D):T(y(R.c),D,"0"):k===10&&be?(R=ce(new K(R),X+D+1,te),E=T(y(R.c),R.e,"0")):(C(k,2,le.length,"Base"),E=q(T(y(R.c),D,"0"),10,k,M,!0)),M<0&&R.c[0]&&(E="-"+E)),E},H.valueOf=H.toJSON=function(){return de(this)},H._isBigNumber=!0,x!=null&&K.set(x),K}function b(x){var O=x|0;return x>0||x===O?O:O-1}function y(x){for(var O,q,$=1,H=x.length,ae=x[0]+"";$<H;){for(O=x[$++]+"",q=u-O.length;q--;O="0"+O);ae+=O}for(H=ae.length;ae.charCodeAt(--H)===48;);return ae.slice(0,H+1||1)}function w(x,O){var q,$,H=x.c,ae=O.c,X=x.s,te=O.s,Z=x.e,De=O.e;if(!X||!te)return null;if(q=H&&!H[0],$=ae&&!ae[0],q||$)return q?$?0:-te:X;if(X!=te)return X;if(q=X<0,$=Z==De,!H||!ae)return $?0:!H^q?1:-1;if(!$)return Z>De^q?1:-1;for(te=(Z=H.length)<(De=ae.length)?Z:De,X=0;X<te;X++)if(H[X]!=ae[X])return H[X]>ae[X]^q?1:-1;return Z==De?0:Z>De^q?1:-1}function C(x,O,q,$){if(x<O||x>q||x!==o(x))throw Error(s+($||"Argument")+(typeof x=="number"?x<O||x>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(x))}function v(x){var O=x.c.length-1;return b(x.e/u)==O&&x.c[O]%2!=0}function A(x,O){return(x.length>1?x.charAt(0)+"."+x.slice(1):x)+(O<0?"e":"e+")+O}function T(x,O,q){var $,H;if(O<0){for(H=q+".";++O;H+=q);x=H+x}else if($=x.length,++O>$){for(H=q,O-=$;--O;H+=q);x+=H}else O<$&&(x=x.slice(0,O)+"."+x.slice(O));return x}e=_(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof uu<"u"&&uu.exports?uu.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(Jk)});var Xk=J((K$,Yk)=>{var Vk=nh(),Kk=Yk.exports;(function(){"use strict";function t(f){return f<10?"0"+f:f}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function c(f){return n.lastIndex=0,n.test(f)?'"'+f.replace(n,function(d){var p=s[d];return typeof p=="string"?p:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+f+'"'}function u(f,d){var p,h,_,b,y=r,w,C=d[f],v=C!=null&&(C instanceof Vk||Vk.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(f)),typeof i=="function"&&(C=i.call(d,f,C)),typeof C){case"string":return v?C:c(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(r+=o,w=[],Object.prototype.toString.apply(C)==="[object Array]"){for(b=C.length,p=0;p<b;p+=1)w[p]=u(p,C)||"null";return _=w.length===0?"[]":r?`[
73
+ `+r+w.join(`,
45
74
  `+r)+`
46
- `+w+"]":"["+b.join(",")+"]",r=w,S}if(a&&typeof a=="object")for(y=a.length,h=0;h<y;h+=1)typeof a[h]=="string"&&(m=a[h],S=l(m,_),S&&b.push(c(m)+(r?": ":":")+S));else Object.keys(_).forEach(function(k){var v=l(k,_);v&&b.push(c(k)+(r?": ":":")+v)});return S=b.length===0?"{}":r?`{
47
- `+r+b.join(`,
75
+ `+y+"]":"["+w.join(",")+"]",r=y,_}if(i&&typeof i=="object")for(b=i.length,p=0;p<b;p+=1)typeof i[p]=="string"&&(h=i[p],_=u(h,C),_&&w.push(c(h)+(r?": ":":")+_));else Object.keys(C).forEach(function(A){var T=u(A,C);T&&w.push(c(A)+(r?": ":":")+T)});return _=w.length===0?"{}":r?`{
76
+ `+r+w.join(`,
48
77
  `+r)+`
49
- `+w+"}":"{"+b.join(",")+"}",r=w,S}}typeof Zb.stringify!="function"&&(Zb.stringify=function(f,d,h){var m;if(r="",o="",typeof h=="number")for(m=0;m<h;m+=1)o+=" ";else typeof h=="string"&&(o=h);if(a=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return l("",{"":f})})})()});var rw=V((Dj,nw)=>{var kc=null,GT=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,JT=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,VT=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
- `,r:"\r",t:" "},s,a=function(w){throw{name:"SyntaxError",message:w,at:n,text:s}},c=function(w){return w&&w!==r&&a("Expected '"+w+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},l=function(){var w,b="";for(r==="-"&&(b="-",c("-"));r>="0"&&r<="9";)b+=r,c();if(r===".")for(b+=".";c()&&r>="0"&&r<="9";)b+=r;if(r==="e"||r==="E")for(b+=r,c(),(r==="-"||r==="+")&&(b+=r,c());r>="0"&&r<="9";)b+=r,c();if(w=+b,!isFinite(w))a("Bad number");else return kc==null&&(kc=qf()),b.length>15?e.storeAsString?b:e.useNativeBigInt?BigInt(b):new kc(b):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(w):new kc(w):w},f=function(){var w,b,_="",D;if(r==='"')for(var k=n;c();){if(r==='"')return n-1>k&&(_+=s.substring(k,n-1)),c(),_;if(r==="\\"){if(n-1>k&&(_+=s.substring(k,n-1)),c(),r==="u"){for(D=0,b=0;b<4&&(w=parseInt(c(),16),!!isFinite(w));b+=1)D=D*16+w;_+=String.fromCharCode(D)}else if(typeof o[r]=="string")_+=o[r];else break;k=n}}a("Bad string")},d=function(){for(;r&&r<=" ";)c()},h=function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}a("Unexpected '"+r+"'")},m,S=function(){var w=[];if(r==="["){if(c("["),d(),r==="]")return c("]"),w;for(;r;){if(w.push(m()),d(),r==="]")return c("]"),w;c(","),d()}}a("Bad array")},y=function(){var w,b=Object.create(null);if(r==="{"){if(c("{"),d(),r==="}")return c("}"),b;for(;r;){if(w=f(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(b,w)&&a('Duplicate key "'+w+'"'),GT.test(w)===!0?e.protoAction==="error"?a("Object contains forbidden prototype property"):e.protoAction==="ignore"?m():b[w]=m():JT.test(w)===!0?e.constructorAction==="error"?a("Object contains forbidden constructor property"):e.constructorAction==="ignore"?m():b[w]=m():b[w]=m(),d(),r==="}")return c("}"),b;c(","),d()}}a("Bad object")};return m=function(){switch(d(),r){case"{":return y();case"[":return S();case'"':return f();case"-":return l();default:return r>="0"&&r<="9"?l():h()}},function(w,b){var _;return s=w+"",n=0,r=" ",_=m(),d(),r&&a("Syntax error"),typeof b=="function"?(function D(k,v){var x,R,j=k[v];return j&&typeof j=="object"&&Object.keys(j).forEach(function(W){R=D(j,W),R!==void 0?j[W]=R:delete j[W]}),b.call(k,v,j)})({"":_},""):_}};nw.exports=VT});var iw=V((xj,Sc)=>{var ow=tw().stringify,sw=rw();Sc.exports=function(t){return{parse:sw(t),stringify:ow}};Sc.exports.parse=sw();Sc.exports.stringify=ow});var $f=V(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.GCE_LINUX_BIOS_PATHS=void 0;nn.isGoogleCloudServerless=uw;nn.isGoogleComputeEngineLinux=lw;nn.isGoogleComputeEngineMACAddress=dw;nn.isGoogleComputeEngine=fw;nn.detectGCPResidency=YT;var aw=require("fs"),cw=require("os");nn.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var KT=/^42:01/;function uw(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function lw(){if((0,cw.platform)()!=="linux")return!1;try{(0,aw.statSync)(nn.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,aw.readFileSync)(nn.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function dw(){let t=(0,cw.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(KT.test(n))return!0}return!1}function fw(){return lw()||dw()}function YT(){return uw()||fw()}});var hw=V(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.Colours=void 0;var lt=class t{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process==null?void 0:process.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};Ac.Colours=lt;lt.enabled=!1;lt.reset="";lt.bright="";lt.dim="";lt.red="";lt.green="";lt.yellow="";lt.blue="";lt.magenta="";lt.cyan="";lt.white="";lt.grey="";lt.refresh()});var yw=V(Ie=>{"use strict";var XT=Ie&&Ie.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),QT=Ie&&Ie.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pw=Ie&&Ie.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&XT(n,e,r[o]);return QT(n,e),n}})();Object.defineProperty(Ie,"__esModule",{value:!0});Ie.env=Ie.DebugLogBackendBase=Ie.placeholder=Ie.AdhocDebugLogger=Ie.LogSeverity=void 0;Ie.getNodeBackend=Hf;Ie.getDebugBackend=eR;Ie.getStructuredBackend=tR;Ie.setBackend=nR;Ie.log=mw;var ZT=require("events"),ii=pw(require("process")),gw=pw(require("util")),Tt=hw(),rn;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(rn||(Ie.LogSeverity=rn={}));var ai=class extends ZT.EventEmitter{constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(rn.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(rn.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(rn.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(rn.ERROR,...r),this.func.sublog=r=>mw(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Ie.AdhocDebugLogger=ai;Ie.placeholder=new ai("",()=>{}).func;var $o=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let n=(e=ii.env[Ie.env.nodeEnables])!==null&&e!==void 0?e:"*";n==="all"&&(n="*"),this.filters=n.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};Ie.DebugLogBackendBase=$o;var zf=class extends $o{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{var o;let s=`${Tt.Colours.green}${e}${Tt.Colours.reset}`,a=`${Tt.Colours.yellow}${ii.pid}${Tt.Colours.reset}`,c;switch(n.severity){case rn.ERROR:c=`${Tt.Colours.red}${n.severity}${Tt.Colours.reset}`;break;case rn.INFO:c=`${Tt.Colours.magenta}${n.severity}${Tt.Colours.reset}`;break;case rn.WARNING:c=`${Tt.Colours.yellow}${n.severity}${Tt.Colours.reset}`;break;default:c=(o=n.severity)!==null&&o!==void 0?o:rn.DEFAULT;break}let l=gw.formatWithOptions({colors:Tt.Colours.enabled},...r),f=Object.assign({},n);delete f.severity;let d=Object.getOwnPropertyNames(f).length?JSON.stringify(f):"",h=d?`${Tt.Colours.grey}${d}${Tt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",a,s,c,l,d?` ${h}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Hf(){return new zf}var Wf=class extends $o{constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){var e;let n=(e=ii.env.NODE_DEBUG)!==null&&e!==void 0?e:"";ii.env.NODE_DEBUG=`${n}${n?",":""}${this.filters.join(",")}`}};function eR(t){return new Wf(t)}var Gf=class extends $o{constructor(e){var n;super(),this.upstream=(n=e)!==null&&n!==void 0?n:void 0}makeLogger(e){var n;let r=(n=this.upstream)===null||n===void 0?void 0:n.makeLogger(e);return(o,...s)=>{var a;let c=(a=o.severity)!==null&&a!==void 0?a:rn.INFO,l=Object.assign({severity:c,message:gw.format(...s)},o),f=JSON.stringify(l);r?r(o,f):console.log("%s",f)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function tR(t){return new Gf(t)}Ie.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Jf=new Map,Rt;function nR(t){Rt=t,Jf.clear()}function mw(t,e){if(!Rt&&!ii.env[Ie.env.nodeEnables]||!t)return Ie.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Jf.get(t);if(n)return n.func;if(Rt===null)return Ie.placeholder;Rt===void 0&&(Rt=Hf());let r=(()=>{let o;return new ai(t,(a,...c)=>{if(o!==Rt){if(Rt===null)return;Rt===void 0&&(Rt=Hf()),o=Rt}Rt?.log(t,a,...c)})})();return Jf.set(t,r),r.func}});var Vf=V(to=>{"use strict";var rR=to&&to.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),oR=to&&to.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&rR(e,t,n)};Object.defineProperty(to,"__esModule",{value:!0});oR(yw(),to)});var ui=V(fe=>{"use strict";var bw=fe&&fe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),sR=fe&&fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iR=fe&&fe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&bw(n,e,r[o]);return sR(n,e),n}})(),aR=fe&&fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bw(e,t,n)};Object.defineProperty(fe,"__esModule",{value:!0});fe.gcpResidencyCache=fe.METADATA_SERVER_DETECTION=fe.HEADERS=fe.HEADER_VALUE=fe.HEADER_NAME=fe.SECONDARY_HOST_ADDRESS=fe.HOST_ADDRESS=fe.BASE_PATH=void 0;fe.instance=hR;fe.project=pR;fe.universe=gR;fe.bulk=mR;fe.isAvailable=_R;fe.resetIsAvailableCache=bR;fe.getGCPResidency=Xf;fe.setGCPResidency=ww;fe.requestTimeout=Cw;var Kf=ct(),cR=iw(),uR=$f(),lR=iR(Vf());fe.BASE_PATH="/computeMetadata/v1";fe.HOST_ADDRESS="http://169.254.169.254";fe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";fe.HEADER_NAME="Metadata-Flavor";fe.HEADER_VALUE="Google";fe.HEADERS=Object.freeze({[fe.HEADER_NAME]:fe.HEADER_VALUE});var _w=lR.log("gcp-metadata");fe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Yf(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||fe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(fe.BASE_PATH,t).href}function dR(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ci(t,e={},n=3,r=!1){let o=new Headers(fe.HEADERS),s="",a={};if(typeof t=="object"){let h=t;new Headers(h.headers).forEach((m,S)=>o.set(S,m)),s=h.metadataKey,a=h.params||a,n=h.noResponseRetries||n,r=h.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(dR(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((h,m)=>o.set(m,h)),a=e.params||a);let c=r?fR:Kf.request,l={url:`${Yf()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:a,responseType:"text",timeout:Cw()};_w.info("instance request %j",l);let f=await c(l);_w.info("instance metadata is %s",f.data);let d=f.headers.get(fe.HEADER_NAME);if(d!==fe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${fe.HEADER_NAME} header. Expected '${fe.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return cR.parse(f.data)}catch{}return f.data}async function fR(t){let e={...t,url:t.url?.toString().replace(Yf(),Yf(fe.SECONDARY_HOST_ADDRESS))},n=(0,Kf.request)(t),r=(0,Kf.request)(e);return Promise.any([n,r])}function hR(t){return ci("instance",t)}function pR(t){return ci("project",t)}function gR(t){return ci("universe",t)}async function mR(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ci(n),o=n.metadataKey;e[o]=r})())),e}function yR(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Ec;async function _R(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in fe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(fe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Xf();case"ping-only":}}try{return Ec===void 0&&(Ec=ci("instance",void 0,yR(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Ec,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function bR(){Ec=void 0}fe.gcpResidencyCache=null;function Xf(){return fe.gcpResidencyCache===null&&ww(),fe.gcpResidencyCache}function ww(t=null){fe.gcpResidencyCache=t!==null?t:(0,uR.detectGCPResidency)()}function Cw(){return Xf()?0:3e3}aR($f(),fe)});var Aw=V(vc=>{"use strict";vc.byteLength=CR;vc.toByteArray=SR;vc.fromByteArray=vR;var mn=[],zt=[],wR=typeof Uint8Array<"u"?Uint8Array:Array,Qf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(no=0,kw=Qf.length;no<kw;++no)mn[no]=Qf[no],zt[Qf.charCodeAt(no)]=no;var no,kw;zt[45]=62;zt[95]=63;function Sw(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function CR(t){var e=Sw(t),n=e[0],r=e[1];return(n+r)*3/4-r}function kR(t,e,n){return(e+n)*3/4-n}function SR(t){var e,n=Sw(t),r=n[0],o=n[1],s=new wR(kR(t,r,o)),a=0,c=o>0?r-4:r,l;for(l=0;l<c;l+=4)e=zt[t.charCodeAt(l)]<<18|zt[t.charCodeAt(l+1)]<<12|zt[t.charCodeAt(l+2)]<<6|zt[t.charCodeAt(l+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return o===2&&(e=zt[t.charCodeAt(l)]<<2|zt[t.charCodeAt(l+1)]>>4,s[a++]=e&255),o===1&&(e=zt[t.charCodeAt(l)]<<10|zt[t.charCodeAt(l+1)]<<4|zt[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function AR(t){return mn[t>>18&63]+mn[t>>12&63]+mn[t>>6&63]+mn[t&63]}function ER(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(AR(r));return o.join("")}function vR(t){for(var e,n=t.length,r=n%3,o=[],s=16383,a=0,c=n-r;a<c;a+=s)o.push(ER(t,a,a+s>c?c:a+s));return r===1?(e=t[n-1],o.push(mn[e>>2]+mn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(mn[e>>10]+mn[e>>4&63]+mn[e<<2&63]+"=")),o.join("")}});var eh=V(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});Zf.fromArrayBufferToHex=TR;function TR(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Ew=V(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.BrowserCrypto=void 0;var zo=Aw(),RR=eh(),th=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return zo.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),zo.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),a=zo.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,a,s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),a=await window.crypto.subtle.sign(r,s,o);return zo.fromByteArray(new Uint8Array(a))}decodeBase64StringUtf8(e){let n=zo.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return zo.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,RR.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};Tc.BrowserCrypto=th});var vw=V(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.NodeCrypto=void 0;var Ho=require("crypto"),nh=class{async sha256DigestBase64(e){return Ho.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Ho.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Ho.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Ho.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Ho.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:xR(e);return DR(Ho.createHmac("sha256",r).update(n).digest())}};Rc.NodeCrypto=nh;function DR(t){return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function xR(t){return Buffer.from(t)}});var li=V(zn=>{"use strict";var OR=zn&&zn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),FR=zn&&zn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&OR(e,t,n)};Object.defineProperty(zn,"__esModule",{value:!0});zn.createCrypto=NR;zn.hasBrowserCrypto=Tw;var PR=Ew(),IR=vw();FR(eh(),zn);function NR(){return Tw()?new PR.BrowserCrypto:new IR.NodeCrypto}function Tw(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Wo=V((rh,Dw)=>{var Dc=require("buffer"),yn=Dc.Buffer;function Rw(t,e){for(var n in t)e[n]=t[n]}yn.from&&yn.alloc&&yn.allocUnsafe&&yn.allocUnsafeSlow?Dw.exports=Dc:(Rw(Dc,rh),rh.Buffer=ro);function ro(t,e,n){return yn(t,e,n)}ro.prototype=Object.create(yn.prototype);Rw(yn,ro);ro.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return yn(t,e,n)};ro.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=yn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};ro.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return yn(t)};ro.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Dc.SlowBuffer(t)}});var Ow=V((qj,xw)=>{"use strict";function oh(t){var e=(t/8|0)+(t%8===0?0:1);return e}var BR={ES256:oh(256),ES384:oh(384),ES512:oh(521)};function jR(t){var e=BR[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}xw.exports=jR});var sh=V(($j,jw)=>{"use strict";var xc=Wo().Buffer,Pw=Ow(),Oc=128,Iw=0,MR=32,UR=16,LR=2,Nw=UR|MR|Iw<<6,Fc=LR|Iw<<6;function qR(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Bw(t){if(xc.isBuffer(t))return t;if(typeof t=="string")return xc.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function $R(t,e){t=Bw(t);var n=Pw(e),r=n+1,o=t.length,s=0;if(t[s++]!==Nw)throw new Error('Could not find expected "seq"');var a=t[s++];if(a===(Oc|1)&&(a=t[s++]),o-s<a)throw new Error('"seq" specified length of "'+a+'", only "'+(o-s)+'" remaining');if(t[s++]!==Fc)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var l=s;if(s+=c,t[s++]!==Fc)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(r<f)throw new Error('"s" specified length of "'+f+'", max of "'+r+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var h=n-c,m=n-f,S=xc.allocUnsafe(h+c+m+f);for(s=0;s<h;++s)S[s]=0;t.copy(S,s,l+Math.max(-h,0),l+c),s=n;for(var y=s;s<y+m;++s)S[s]=0;return t.copy(S,s,d+Math.max(-m,0),d+f),S=S.toString("base64"),S=qR(S),S}function Fw(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Oc;return o&&--r,r}function zR(t,e){t=Bw(t);var n=Pw(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Fw(t,0,n),s=Fw(t,n,t.length),a=n-o,c=n-s,l=2+a+1+1+c,f=l<Oc,d=xc.allocUnsafe((f?2:3)+l),h=0;return d[h++]=Nw,f?d[h++]=l:(d[h++]=Oc|1,d[h++]=l&255),d[h++]=Fc,d[h++]=a,o<0?(d[h++]=0,h+=t.copy(d,h,0,n)):h+=t.copy(d,h,o,n),d[h++]=Fc,d[h++]=c,s<0?(d[h++]=0,t.copy(d,h,n)):t.copy(d,h,n+s),d}jw.exports={derToJose:$R,joseToDer:zR}});var on=V(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.LRUCache=void 0;Hn.snakeToCamel=Uw;Hn.originalOrCamelOptions=JR;Hn.removeUndefinedValuesInObject=VR;Hn.isValidFile=KR;Hn.getWellKnownCertificateConfigFileLocation=YR;var HR=require("fs"),WR=require("os"),ih=require("path"),GR="certificate_config.json",Mw="gcloud";function Uw(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function JR(t){function e(n){let r=t||{};return r[n]??r[Uw(n)]}return{get:e}}var ah=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Hn.LRUCache=ah;function VR(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function KR(t){try{return(await HR.promises.lstat(t)).isFile()}catch{return!1}}function YR(){let t=process.env.CLOUDSDK_CONFIG||(XR()?ih.join(process.env.APPDATA||"",Mw):ih.join(process.env.HOME||"",".config",Mw));return ih.join(t,GR)}function XR(){return WR.platform().startsWith("win")}});var Lw=V((Hj,QR)=>{QR.exports={name:"google-auth-library",version:"10.4.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"5.8.2",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var ch=V(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.USER_AGENT=wr.PRODUCT_NAME=wr.pkg=void 0;var qw=Lw();wr.pkg=qw;var $w="google-api-nodejs-client";wr.PRODUCT_NAME=$w;var ZR=`${$w}/${qw.version}`;wr.USER_AGENT=ZR});var Dt=V(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.AuthClient=sn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=sn.DEFAULT_UNIVERSE=void 0;var eD=require("events"),uh=ct(),tD=on(),nD=Vf(),lh=ch();sn.DEFAULT_UNIVERSE="googleapis.com";sn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var dh=class t extends eD.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=sn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=sn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,tD.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??sn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new uh.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&uh.Gaxios.mergeHeaders(s,n.headers),r&&uh.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,nD.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${lh.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${lh.USER_AGENT}`):e.headers.set("User-Agent",lh.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let a={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,a):t.log.info("[%s] request %j",s,a)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};sn.AuthClient=dh});var hh=V(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.LoginTicket=void 0;var fh=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Pc.LoginTicket=fh});var oo=V(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.OAuth2Client=_n.ClientAuthentication=_n.CertificateFormat=_n.CodeChallengeMethod=void 0;var zw=ct(),rD=require("querystring"),oD=require("stream"),sD=sh(),Hw=on(),ph=li(),Go=Dt(),iD=hh(),Ww;(function(t){t.Plain="plain",t.S256="S256"})(Ww||(_n.CodeChallengeMethod=Ww={}));var Wn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Wn||(_n.CertificateFormat=Wn={}));var di;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(di||(_n.ClientAuthentication=di={}));var gh=class t extends Go.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Wn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||di.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+rD.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,ph.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===di.ClientSecretBasic){let l=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${l.toString("base64")}`)}this.clientAuthentication===di.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Hw.removeUndefinedValuesInObject)(o)),headers:r};Go.AuthClient.setMethodName(s,"getTokenAsync");let a=await this.transporter.request(s),c=a.data;return a.data&&a.data.expires_in&&(c.expiry_date=new Date().getTime()+a.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:a}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let a={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Hw.removeUndefinedValuesInObject)(r))};Go.AuthClient.setMethodName(a,"refreshTokenNoCache"),o=await this.transporter.request(a)}catch(a){throw a instanceof zw.GaxiosError&&a.message==="invalid_grant"&&a.response?.data&&/ReAuth/i.test(a.response.data.error_description)&&(a.message=JSON.stringify(a.response.data)),a}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let l=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(l)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(c){let l=c;throw l.response&&(l.response.status===403||l.response.status===404)&&(l.message=`Could not refresh access token: ${l.message}`),l}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let a=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(a),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Go.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=zw.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,a=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,l=o.config.data instanceof oD.Readable,f=s===401||s===403;if(!n&&f&&!l&&a)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&f&&!l&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,ph.hasBrowserCrypto)()?Wn.JWK:Wn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Wn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Wn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let f={...t.RETRY_CONFIG,url:o};Go.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),r=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=r?.headers.get("cache-control"),a=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(a=Number(f)*1e3)}let c={};switch(n){case Wn.PEM:c=r.data;break;case Wn.JWK:for(let f of r.data.keys)c[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${n}`)}let l=new Date;return this.certificateExpiry=a===-1?null:new Date(l.getTime()+a),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};Go.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let a=(0,ph.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let l=c[0]+"."+c[1],f=c[2],d,h;try{d=JSON.parse(a.decodeBase64StringUtf8(c[0]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token envelope: ${c[0]}': ${k.message}`),k}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{h=JSON.parse(a.decodeBase64StringUtf8(c[1]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token payload '${c[0]}`),k}if(!h)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let m=n[d.kid];if(d.alg==="ES256"&&(f=sD.joseToDer(f,"ES256").toString("base64")),!await a.verify(m,l,f))throw new Error("Invalid token signature: "+e);if(!h.iat)throw new Error("No issue time in token: "+JSON.stringify(h));if(!h.exp)throw new Error("No expiration time in token: "+JSON.stringify(h));let y=Number(h.iat);if(isNaN(y))throw new Error("iat field using invalid format");let w=Number(h.exp);if(isNaN(w))throw new Error("exp field using invalid format");let b=new Date().getTime()/1e3;if(w>=b+s)throw new Error("Expiration time too far in future: "+JSON.stringify(h));let _=y-t.CLOCK_SKEW_SECS_,D=w+t.CLOCK_SKEW_SECS_;if(b<_)throw new Error("Token used too early, "+b+" < "+_+": "+JSON.stringify(h));if(b>D)throw new Error("Token used too late, "+b+" > "+D+": "+JSON.stringify(h));if(o&&o.indexOf(h.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+h.iss);if(typeof r<"u"&&r!==null){let k=h.aud,v=!1;if(r.constructor===Array?v=r.indexOf(k)>-1:v=k===r,!v)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new iD.LoginTicket(d,h)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};_n.OAuth2Client=gh});var yh=V(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.Compute=void 0;var aD=ct(),Gw=ui(),cD=oo(),mh=class extends cD.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await Gw.instance(o)}catch(o){throw o instanceof aD.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await Gw.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Ic.Compute=mh});var bh=V(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.IdTokenClient=void 0;var uD=oo(),_h=class extends uD.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Nc.IdTokenClient=_h});var wh=V(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.GCPEnv=void 0;Jo.clear=lD;Jo.getEnv=dD;var Jw=ui(),bn;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(bn||(Jo.GCPEnv=bn={}));var fi;function lD(){fi=void 0}async function dD(){return fi||(fi=fD(),fi)}async function fD(){let t=bn.NONE;return hD()?t=bn.APP_ENGINE:pD()?t=bn.CLOUD_FUNCTIONS:await _D()?await yD()?t=bn.KUBERNETES_ENGINE:gD()?t=bn.CLOUD_RUN:mD()?t=bn.CLOUD_RUN_JOBS:t=bn.COMPUTE_ENGINE:t=bn.NONE,t}function hD(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function pD(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function gD(){return!!process.env.K_CONFIGURATION}function mD(){return!!process.env.CLOUD_RUN_JOB}async function yD(){try{return await Jw.instance("attributes/cluster-name"),!0}catch{return!1}}async function _D(){return Jw.isAvailable()}});var Ch=V((Qj,Vw)=>{var Bc=Wo().Buffer,bD=require("stream"),wD=require("util");function jc(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Bc.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Bc.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}wD.inherits(jc,bD);jc.prototype.write=function(e){this.buffer=Bc.concat([this.buffer,Bc.from(e)]),this.emit("data",e)};jc.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Vw.exports=jc});var Yw=V((Zj,Kw)=>{"use strict";var hi=require("buffer").Buffer,kh=require("buffer").SlowBuffer;Kw.exports=Mc;function Mc(t,e){if(!hi.isBuffer(t)||!hi.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Mc.install=function(){hi.prototype.equal=kh.prototype.equal=function(e){return Mc(this,e)}};var CD=hi.prototype.equal,kD=kh.prototype.equal;Mc.restore=function(){hi.prototype.equal=CD,kh.prototype.equal=kD}});var vh=V((eM,sC)=>{var Ko=Wo().Buffer,Ht=require("crypto"),Qw=sh(),Xw=require("util"),SD=`"%s" is not a valid algorithm.
78
+ `+y+"}":"{"+w.join(",")+"}",r=y,_}}typeof Kk.stringify!="function"&&(Kk.stringify=function(f,d,p){var h;if(r="",o="",typeof p=="number")for(h=0;h<p;h+=1)o+=" ";else typeof p=="string"&&(o=p);if(i=d,d&&typeof d!="function"&&(typeof d!="object"||typeof d.length!="number"))throw new Error("JSON.stringify");return u("",{"":f})})})()});var Zk=J((Y$,Qk)=>{var lu=null,k1=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,S1=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,E1=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
79
+ `,r:"\r",t:" "},s,i=function(y){throw{name:"SyntaxError",message:y,at:n,text:s}},c=function(y){return y&&y!==r&&i("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},u=function(){var y,w="";for(r==="-"&&(w="-",c("-"));r>="0"&&r<="9";)w+=r,c();if(r===".")for(w+=".";c()&&r>="0"&&r<="9";)w+=r;if(r==="e"||r==="E")for(w+=r,c(),(r==="-"||r==="+")&&(w+=r,c());r>="0"&&r<="9";)w+=r,c();if(y=+w,!isFinite(y))i("Bad number");else return lu==null&&(lu=nh()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new lu(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new lu(y):y},f=function(){var y,w,C="",v;if(r==='"')for(var A=n;c();){if(r==='"')return n-1>A&&(C+=s.substring(A,n-1)),c(),C;if(r==="\\"){if(n-1>A&&(C+=s.substring(A,n-1)),c(),r==="u"){for(v=0,w=0;w<4&&(y=parseInt(c(),16),!!isFinite(y));w+=1)v=v*16+y;C+=String.fromCharCode(v)}else if(typeof o[r]=="string")C+=o[r];else break;A=n}}i("Bad string")},d=function(){for(;r&&r<=" ";)c()},p=function(){switch(r){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}i("Unexpected '"+r+"'")},h,_=function(){var y=[];if(r==="["){if(c("["),d(),r==="]")return c("]"),y;for(;r;){if(y.push(h()),d(),r==="]")return c("]"),y;c(","),d()}}i("Bad array")},b=function(){var y,w=Object.create(null);if(r==="{"){if(c("{"),d(),r==="}")return c("}"),w;for(;r;){if(y=f(),d(),c(":"),e.strict===!0&&Object.hasOwnProperty.call(w,y)&&i('Duplicate key "'+y+'"'),k1.test(y)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():w[y]=h():S1.test(y)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():w[y]=h():w[y]=h(),d(),r==="}")return c("}"),w;c(","),d()}}i("Bad object")};return h=function(){switch(d(),r){case"{":return b();case"[":return _();case'"':return f();case"-":return u();default:return r>="0"&&r<="9"?u():p()}},function(y,w){var C;return s=y+"",n=0,r=" ",C=h(),d(),r&&i("Syntax error"),typeof w=="function"?(function v(A,T){var x,O,q=A[T];return q&&typeof q=="object"&&Object.keys(q).forEach(function($){O=v(q,$),O!==void 0?q[$]=O:delete q[$]}),w.call(A,T,q)})({"":C},""):C}};Qk.exports=E1});var nS=J((X$,du)=>{var eS=Xk().stringify,tS=Zk();du.exports=function(t){return{parse:tS(t),stringify:eS}};du.exports.parse=tS();du.exports.stringify=eS});var rh=J(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.GCE_LINUX_BIOS_PATHS=void 0;en.isGoogleCloudServerless=sS;en.isGoogleComputeEngineLinux=iS;en.isGoogleComputeEngineMACAddress=aS;en.isGoogleComputeEngine=cS;en.detectGCPResidency=A1;var rS=require("fs"),oS=require("os");en.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var v1=/^42:01/;function sS(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function iS(){if((0,oS.platform)()!=="linux")return!1;try{(0,rS.statSync)(en.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,rS.readFileSync)(en.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function aS(){let t=(0,oS.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(v1.test(n))return!0}return!1}function cS(){return iS()||aS()}function A1(){return sS()||cS()}});var uS=J(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.Colours=void 0;var fu=class t{static enabled=!1;static reset="";static bright="";static dim="";static red="";static green="";static yellow="";static blue="";static magenta="";static cyan="";static white="";static grey="";static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process?.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};pu.Colours=fu;fu.refresh()});var dS=J(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.LogSeverity=void 0;var lS;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(lS||(hu.LogSeverity=lS={}))});var mS=J(Ue=>{"use strict";var T1=Ue&&Ue.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),R1=Ue&&Ue.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fS=Ue&&Ue.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&T1(n,e,r[o]);return R1(n,e),n}})();Object.defineProperty(Ue,"__esModule",{value:!0});Ue.env=Ue.DebugLogBackendBase=Ue.placeholder=Ue.AdhocDebugLogger=void 0;Ue.getNodeBackend=sh;Ue.getDebugBackend=D1;Ue.getStructuredBackend=O1;Ue.setBackend=P1;Ue.log=hS;var x1=require("events"),Fi=fS(require("process")),pS=fS(require("util")),xt=uS(),Vn=dS(),Ni=class extends x1.EventEmitter{namespace;upstream;func;constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(Vn.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(Vn.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(Vn.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(Vn.LogSeverity.ERROR,...r),this.func.sublog=r=>hS(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};Ue.AdhocDebugLogger=Ni;Ue.placeholder=new Ni("",()=>{}).func;var os=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=Fi.env[Ue.env.nodeEnables]??"*";e==="all"&&(e="*"),this.filters=e.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};Ue.DebugLogBackendBase=os;var oh=class extends os{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${xt.Colours.green}${e}${xt.Colours.reset}`,s=`${xt.Colours.yellow}${Fi.pid}${xt.Colours.reset}`,i;switch(n.severity){case Vn.LogSeverity.ERROR:i=`${xt.Colours.red}${n.severity}${xt.Colours.reset}`;break;case Vn.LogSeverity.INFO:i=`${xt.Colours.magenta}${n.severity}${xt.Colours.reset}`;break;case Vn.LogSeverity.WARNING:i=`${xt.Colours.yellow}${n.severity}${xt.Colours.reset}`;break;default:i=n.severity??Vn.LogSeverity.DEFAULT;break}let c=pS.formatWithOptions({colors:xt.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let f=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",d=f?`${xt.Colours.grey}${f}${xt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,i,c,f?` ${d}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function sh(){return new oh}var ih=class extends os{debugPkg;constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){let e=Fi.env.NODE_DEBUG??"";Fi.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function D1(t){return new ih(t)}var ah=class extends os{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??Vn.LogSeverity.INFO,i=Object.assign({severity:s,message:pS.format(...o)},r),c=JSON.stringify(i);n?n(r,c):console.log("%s",c)}}setFilters(){this.upstream?.setFilters()}};function O1(t){return new ah(t)}Ue.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var ch=new Map,tn;function P1(t){tn=t,ch.clear()}function hS(t,e){if(!tn&&!Fi.env[Ue.env.nodeEnables]||!t)return Ue.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=ch.get(t);if(n)return n.func;if(tn===null)return Ue.placeholder;tn===void 0&&(tn=sh());let r=(()=>{let o;return new Ni(t,(i,...c)=>{if(o!==tn){if(tn===null)return;tn===void 0&&(tn=sh()),o=tn}tn?.log(t,i,...c)})})();return ch.set(t,r),r.func}});var uh=J(ho=>{"use strict";var I1=ho&&ho.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),F1=ho&&ho.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&I1(e,t,n)};Object.defineProperty(ho,"__esModule",{value:!0});F1(mS(),ho)});var Bi=J(pe=>{"use strict";var yS=pe&&pe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),N1=pe&&pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),M1=pe&&pe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&yS(n,e,r[o]);return N1(n,e),n}})(),B1=pe&&pe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yS(e,t,n)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=z1;pe.project=H1;pe.universe=W1;pe.bulk=G1;pe.isAvailable=V1;pe.resetIsAvailableCache=K1;pe.getGCPResidency=fh;pe.setGCPResidency=_S;pe.requestTimeout=bS;var lh=lt(),U1=nS(),j1=rh(),L1=M1(uh());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var gS=L1.log("gcp-metadata");pe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function dh(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function q1(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Mi(t,e={},n=3,r=!1){let o=new Headers(pe.HEADERS),s="",i={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,_)=>o.set(_,h)),s=p.metadataKey,i=p.params||i,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(q1(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let c=r?$1:lh.request,u={url:`${dh()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:bS()};gS.info("instance request %j",u);let f=await c(u);gS.info("instance metadata is %s",f.data);let d=f.headers.get(pe.HEADER_NAME);if(d!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof f.data=="string")try{return U1.parse(f.data)}catch{}return f.data}async function $1(t){let e={...t,url:t.url?.toString().replace(dh(),dh(pe.SECONDARY_HOST_ADDRESS))},n=(0,lh.request)(t),r=(0,lh.request)(e);return Promise.any([n,r])}function z1(t){return Mi("instance",t)}function H1(t){return Mi("project",t)}function W1(t){return Mi("universe",t)}async function G1(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await Mi(n),o=n.metadataKey;e[o]=r})())),e}function J1(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var mu;async function V1(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return fh();case"ping-only":}}try{return mu===void 0&&(mu=Mi("instance",void 0,J1(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await mu,!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let n="UNKNOWN";e.code&&(n=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${n}`,"MetadataLookupWarning")}return!1}}function K1(){mu=void 0}pe.gcpResidencyCache=null;function fh(){return pe.gcpResidencyCache===null&&_S(),pe.gcpResidencyCache}function _S(t=null){pe.gcpResidencyCache=t!==null?t:(0,j1.detectGCPResidency)()}function bS(){return fh()?0:3e3}B1(rh(),pe)});var kS=J(gu=>{"use strict";gu.byteLength=X1;gu.toByteArray=Z1;gu.fromByteArray=nP;var Cn=[],qt=[],Y1=typeof Uint8Array<"u"?Uint8Array:Array,ph="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(mo=0,CS=ph.length;mo<CS;++mo)Cn[mo]=ph[mo],qt[ph.charCodeAt(mo)]=mo;var mo,CS;qt[45]=62;qt[95]=63;function wS(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function X1(t){var e=wS(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Q1(t,e,n){return(e+n)*3/4-n}function Z1(t){var e,n=wS(t),r=n[0],o=n[1],s=new Y1(Q1(t,r,o)),i=0,c=o>0?r-4:r,u;for(u=0;u<c;u+=4)e=qt[t.charCodeAt(u)]<<18|qt[t.charCodeAt(u+1)]<<12|qt[t.charCodeAt(u+2)]<<6|qt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=qt[t.charCodeAt(u)]<<2|qt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=qt[t.charCodeAt(u)]<<10|qt[t.charCodeAt(u+1)]<<4|qt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function eP(t){return Cn[t>>18&63]+Cn[t>>12&63]+Cn[t>>6&63]+Cn[t&63]}function tP(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(eP(r));return o.join("")}function nP(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,c=n-r;i<c;i+=s)o.push(tP(t,i,i+s>c?c:i+s));return r===1?(e=t[n-1],o.push(Cn[e>>2]+Cn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Cn[e>>10]+Cn[e>>4&63]+Cn[e<<2&63]+"=")),o.join("")}});var mh=J(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});hh.fromArrayBufferToHex=rP;function rP(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var SS=J(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.BrowserCrypto=void 0;var ss=kS(),oP=mh(),gh=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return ss.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),ss.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),i=ss.toByteArray(t.padBase64(r)),c=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,c,Buffer.from(i),s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),i=await window.crypto.subtle.sign(r,s,o);return ss.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=ss.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return ss.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,oP.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};yu.BrowserCrypto=gh});var ES=J(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.NodeCrypto=void 0;var is=require("crypto"),yh=class{async sha256DigestBase64(e){return is.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return is.randomBytes(e).toString("base64")}async verify(e,n,r){let o=is.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=is.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return is.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:iP(e);return sP(is.createHmac("sha256",r).update(n).digest())}};_u.NodeCrypto=yh;function sP(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0;r<t.length;++r)n[r]=t[r];return e}function iP(t){return Buffer.from(t)}});var Ui=J(Kn=>{"use strict";var aP=Kn&&Kn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),cP=Kn&&Kn.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&aP(e,t,n)};Object.defineProperty(Kn,"__esModule",{value:!0});Kn.createCrypto=dP;Kn.hasBrowserCrypto=vS;var uP=SS(),lP=ES();cP(mh(),Kn);function dP(){return vS()?new uP.BrowserCrypto:new lP.NodeCrypto}function vS(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var as=J((_h,TS)=>{var bu=require("buffer"),wn=bu.Buffer;function AS(t,e){for(var n in t)e[n]=t[n]}wn.from&&wn.alloc&&wn.allocUnsafe&&wn.allocUnsafeSlow?TS.exports=bu:(AS(bu,_h),_h.Buffer=go);function go(t,e,n){return wn(t,e,n)}go.prototype=Object.create(wn.prototype);AS(wn,go);go.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return wn(t,e,n)};go.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=wn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};go.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return wn(t)};go.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return bu.SlowBuffer(t)}});var xS=J((uz,RS)=>{"use strict";function bh(t){var e=(t/8|0)+(t%8===0?0:1);return e}var fP={ES256:bh(256),ES384:bh(384),ES512:bh(521)};function pP(t){var e=fP[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}RS.exports=pP});var Ch=J((lz,NS)=>{"use strict";var Cu=as().Buffer,OS=xS(),wu=128,PS=0,hP=32,mP=16,gP=2,IS=mP|hP|PS<<6,ku=gP|PS<<6;function yP(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function FS(t){if(Cu.isBuffer(t))return t;if(typeof t=="string")return Cu.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function _P(t,e){t=FS(t);var n=OS(e),r=n+1,o=t.length,s=0;if(t[s++]!==IS)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(wu|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==ku)throw new Error('Could not find expected "int" for "r"');var c=t[s++];if(o-s-2<c)throw new Error('"r" specified length of "'+c+'", only "'+(o-s-2)+'" available');if(r<c)throw new Error('"r" specified length of "'+c+'", max of "'+r+'" is acceptable');var u=s;if(s+=c,t[s++]!==ku)throw new Error('Could not find expected "int" for "s"');var f=t[s++];if(o-s!==f)throw new Error('"s" specified length of "'+f+'", expected "'+(o-s)+'"');if(r<f)throw new Error('"s" specified length of "'+f+'", max of "'+r+'" is acceptable');var d=s;if(s+=f,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-c,h=n-f,_=Cu.allocUnsafe(p+c+h+f);for(s=0;s<p;++s)_[s]=0;t.copy(_,s,u+Math.max(-p,0),u+c),s=n;for(var b=s;s<b+h;++s)_[s]=0;return t.copy(_,s,d+Math.max(-h,0),d+f),_=_.toString("base64"),_=yP(_),_}function DS(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=wu;return o&&--r,r}function bP(t,e){t=FS(t);var n=OS(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=DS(t,0,n),s=DS(t,n,t.length),i=n-o,c=n-s,u=2+i+1+1+c,f=u<wu,d=Cu.allocUnsafe((f?2:3)+u),p=0;return d[p++]=IS,f?d[p++]=u:(d[p++]=wu|1,d[p++]=u&255),d[p++]=ku,d[p++]=i,o<0?(d[p++]=0,p+=t.copy(d,p,0,n)):p+=t.copy(d,p,o,n),d[p++]=ku,d[p++]=c,s<0?(d[p++]=0,t.copy(d,p,n)):t.copy(d,p,n+s),d}NS.exports={derToJose:_P,joseToDer:bP}});var nn=J(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.LRUCache=void 0;Yn.snakeToCamel=BS;Yn.originalOrCamelOptions=SP;Yn.removeUndefinedValuesInObject=EP;Yn.isValidFile=vP;Yn.getWellKnownCertificateConfigFileLocation=AP;var CP=require("fs"),wP=require("os"),wh=require("path"),kP="certificate_config.json",MS="gcloud";function BS(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function SP(t){function e(n){let r=t||{};return r[n]??r[BS(n)]}return{get:e}}var kh=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};Yn.LRUCache=kh;function EP(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function vP(t){try{return(await CP.promises.lstat(t)).isFile()}catch{return!1}}function AP(){let t=process.env.CLOUDSDK_CONFIG||(TP()?wh.join(process.env.APPDATA||"",MS):wh.join(process.env.HOME||"",".config",MS));return wh.join(t,kP)}function TP(){return wP.platform().startsWith("win")}});var US=J((fz,RP)=>{RP.exports={name:"google-auth-library",version:"11.0.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=22"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var Sh=J(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.USER_AGENT=xr.PRODUCT_NAME=xr.pkg=void 0;var jS=US();xr.pkg=jS;var LS="google-api-nodejs-client";xr.PRODUCT_NAME=LS;var xP=`${LS}/${jS.version}`;xr.USER_AGENT=xP});var Dt=J(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.AuthClient=rn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=rn.DEFAULT_UNIVERSE=void 0;var DP=require("events"),Eh=lt(),OP=nn(),PP=uh(),vh=Sh();rn.DEFAULT_UNIVERSE="googleapis.com";rn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Ah=class t extends DP.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=rn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=rn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,OP.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??rn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Eh.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Eh.Gaxios.mergeHeaders(s,n.headers),r&&Eh.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,PP.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${vh.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${vh.USER_AGENT}`):e.headers.set("User-Agent",vh.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,i):t.log.info("[%s] request %j",s,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};rn.AuthClient=Ah});var Rh=J(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.LoginTicket=void 0;var Th=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Su.LoginTicket=Th});var Dr=J(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.OAuth2Client=kn.ClientAuthentication=kn.CertificateFormat=kn.CodeChallengeMethod=void 0;var qS=lt(),IP=require("querystring"),FP=require("stream"),NP=Ch(),$S=nn(),xh=Ui(),cs=Dt(),MP=Rh(),zS;(function(t){t.Plain="plain",t.S256="S256"})(zS||(kn.CodeChallengeMethod=zS={}));var Xn;(function(t){t.PEM="PEM",t.JWK="JWK"})(Xn||(kn.CertificateFormat=Xn={}));var ji;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ji||(kn.ClientAuthentication=ji={}));var Dh=class t extends cs.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Xn.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||ji.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+IP.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,xh.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===ji.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===ji.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,$S.removeUndefinedValuesInObject)(o)),headers:r};cs.AuthClient.setMethodName(s,"getTokenAsync");let i=await this.transporter.request(s),c=i.data;return i.data&&i.data.expires_in&&(c.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete c.expires_in),this.emit("tokens",c),{tokens:c,res:i}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let i={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,$S.removeUndefinedValuesInObject)(r))};cs.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof qS.GaxiosError&&i.message==="invalid_grant"&&i.response?.data&&/ReAuth/i.test(i.response.data.error_description)&&(i.message=JSON.stringify(i.response.data)),i}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let c=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(c)}}if(this.refreshHandler){let c=await this.processAndValidateRefreshHandler();if(c?.access_token){this.setCredentials(c);let u=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(u)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(c){let u=c;throw u.response&&(u.response.status===403||u.response.status===404)&&(u.message=`Could not refresh access token: ${u.message}`),u}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let i=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(i),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(cs.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=qS.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),c=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,u=o.config.data instanceof FP.Readable,f=s===401||s===403;if(!n&&f&&!u&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&f&&!u&&c){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,xh.hasBrowserCrypto)()?Xn.JWK:Xn.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Xn.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Xn.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let f={...t.RETRY_CONFIG,url:o};cs.AuthClient.setMethodName(f,"getFederatedSignonCertsAsync"),r=await this.transporter.request(f)}catch(f){throw f instanceof Error&&(f.message=`Failed to retrieve verification certificates: ${f.message}`),f}let s=r?.headers.get("cache-control"),i=-1;if(s){let f=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;f&&(i=Number(f)*1e3)}let c={};switch(n){case Xn.PEM:c=r.data;break;case Xn.JWK:for(let f of r.data.keys)c[f.kid]=f;break;default:throw new Error(`Unsupported certificate format ${n}`)}let u=new Date;return this.certificateExpiry=i===-1?null:new Date(u.getTime()+i),this.certificateCache=c,this.certificateCacheFormat=n,{certs:c,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};cs.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let i=(0,xh.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let c=e.split(".");if(c.length!==3)throw new Error("Wrong number of segments in token: "+e);let u=c[0]+"."+c[1],f=c[2],d,p;try{d=JSON.parse(i.decodeBase64StringUtf8(c[0]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token envelope: ${c[0]}': ${A.message}`),A}if(!d)throw new Error("Can't parse token envelope: "+c[0]);try{p=JSON.parse(i.decodeBase64StringUtf8(c[1]))}catch(A){throw A instanceof Error&&(A.message=`Can't parse token payload '${c[0]}`),A}if(!p)throw new Error("Can't parse token payload: "+c[1]);if(!Object.prototype.hasOwnProperty.call(n,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let h=n[d.kid];if(d.alg==="ES256"&&(f=NP.joseToDer(f,"ES256").toString("base64")),!await i.verify(h,u,f))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let b=Number(p.iat);if(isNaN(b))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let w=new Date().getTime()/1e3;if(y>=w+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let C=b-t.CLOCK_SKEW_SECS_,v=y+t.CLOCK_SKEW_SECS_;if(w<C)throw new Error("Token used too early, "+w+" < "+C+": "+JSON.stringify(p));if(w>v)throw new Error("Token used too late, "+w+" > "+v+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let A=p.aud,T=!1;if(r.constructor===Array?T=r.indexOf(A)>-1:T=A===r,!T)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new MP.LoginTicket(d,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};kn.OAuth2Client=Dh});var Ph=J(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.Compute=void 0;var BP=lt(),HS=Bi(),UP=Dr(),Oh=class extends UP.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await HS.instance(o)}catch(o){throw o instanceof BP.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await HS.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Eu.Compute=Oh});var Fh=J(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.IdTokenClient=void 0;var jP=Dr(),Ih=class extends jP.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};vu.IdTokenClient=Ih});var Nh=J(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.GCPEnv=void 0;us.clear=LP;us.getEnv=qP;var WS=Bi(),Sn;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Sn||(us.GCPEnv=Sn={}));var Li;function LP(){Li=void 0}async function qP(){return Li||(Li=$P(),Li)}async function $P(){let t=Sn.NONE;return zP()?t=Sn.APP_ENGINE:HP()?t=Sn.CLOUD_FUNCTIONS:await VP()?await JP()?t=Sn.KUBERNETES_ENGINE:WP()?t=Sn.CLOUD_RUN:GP()?t=Sn.CLOUD_RUN_JOBS:t=Sn.COMPUTE_ENGINE:t=Sn.NONE,t}function zP(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function HP(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function WP(){return!!process.env.K_CONFIGURATION}function GP(){return!!process.env.CLOUD_RUN_JOB}async function JP(){try{return await WS.instance("attributes/cluster-name"),!0}catch{return!1}}async function VP(){return WS.isAvailable()}});var Mh=J((Cz,GS)=>{var Au=as().Buffer,KP=require("stream"),YP=require("util");function Tu(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Au.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Au.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}YP.inherits(Tu,KP);Tu.prototype.write=function(e){this.buffer=Au.concat([this.buffer,Au.from(e)]),this.emit("data",e)};Tu.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};GS.exports=Tu});var VS=J((wz,JS)=>{"use strict";var qi=require("buffer").Buffer,Bh=require("buffer").SlowBuffer;JS.exports=Ru;function Ru(t,e){if(!qi.isBuffer(t)||!qi.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Ru.install=function(){qi.prototype.equal=Bh.prototype.equal=function(e){return Ru(this,e)}};var XP=qi.prototype.equal,QP=Bh.prototype.equal;Ru.restore=function(){qi.prototype.equal=XP,Bh.prototype.equal=QP}});var qh=J((kz,rE)=>{var ds=as().Buffer,$t=require("crypto"),YS=Ch(),KS=require("util"),ZP=`"%s" is not a valid algorithm.
51
80
  Supported algorithms are:
52
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,pi="secret must be a string or buffer",Vo="key must be a string or a buffer",AD="key must be a string, a buffer or an object",Ah=typeof Ht.createPublicKey=="function";Ah&&(Vo+=" or a KeyObject",pi+="or a KeyObject");function Zw(t){if(!Ko.isBuffer(t)&&typeof t!="string"&&(!Ah||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw an(Vo)}function eC(t){if(!Ko.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw an(AD)}function ED(t){if(!Ko.isBuffer(t)){if(typeof t=="string")return t;if(!Ah||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw an(pi)}}function Eh(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function tC(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function an(t){var e=[].slice.call(arguments,1),n=Xw.format.bind(Xw,t).apply(null,e);return new TypeError(n)}function vD(t){return Ko.isBuffer(t)||typeof t=="string"}function gi(t){return vD(t)||(t=JSON.stringify(t)),t}function nC(t){return function(n,r){ED(r),n=gi(n);var o=Ht.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Eh(s)}}var Sh,TD="timingSafeEqual"in Ht?function(e,n){return e.byteLength!==n.byteLength?!1:Ht.timingSafeEqual(e,n)}:function(e,n){return Sh||(Sh=Yw()),Sh(e,n)};function RD(t){return function(n,r,o){var s=nC(t)(n,o);return TD(Ko.from(r),Ko.from(s))}}function rC(t){return function(n,r){eC(r),n=gi(n);var o=Ht.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Eh(s)}}function oC(t){return function(n,r,o){Zw(o),n=gi(n),r=tC(r);var s=Ht.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function DD(t){return function(n,r){eC(r),n=gi(n);var o=Ht.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Ht.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ht.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Eh(s)}}function xD(t){return function(n,r,o){Zw(o),n=gi(n),r=tC(r);var s=Ht.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Ht.constants.RSA_PKCS1_PSS_PADDING,saltLength:Ht.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function OD(t){var e=rC(t);return function(){var r=e.apply(null,arguments);return r=Qw.derToJose(r,"ES"+t),r}}function FD(t){var e=oC(t);return function(r,o,s){o=Qw.joseToDer(o,"ES"+t).toString("base64");var a=e(r,o,s);return a}}function PD(){return function(){return""}}function ID(){return function(e,n){return n===""}}sC.exports=function(e){var n={hs:nC,rs:rC,ps:DD,es:OD,none:PD},r={hs:RD,rs:oC,ps:xD,es:FD,none:ID},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw an(SD,e);var s=(o[1]||o[3]).toLowerCase(),a=o[2];return{sign:n[s](a),verify:r[s](a)}}});var Th=V((tM,iC)=>{var ND=require("buffer").Buffer;iC.exports=function(e){return typeof e=="string"?e:typeof e=="number"||ND.isBuffer(e)?e.toString():JSON.stringify(e)}});var fC=V((nM,dC)=>{var BD=Wo().Buffer,aC=Ch(),jD=vh(),MD=require("stream"),cC=Th(),Rh=require("util");function uC(t,e){return BD.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function UD(t,e,n){n=n||"utf8";var r=uC(cC(t),"binary"),o=uC(cC(e),n);return Rh.format("%s.%s",r,o)}function lC(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=jD(e.alg),a=UD(e,n,o),c=s.sign(a,r);return Rh.format("%s.%s",a,c)}function Uc(t){var e=t.secret||t.privateKey||t.key,n=new aC(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new aC(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Rh.inherits(Uc,MD);Uc.prototype.sign=function(){try{var e=lC({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Uc.sign=lC;dC.exports=Uc});var kC=V((rM,CC)=>{var pC=Wo().Buffer,hC=Ch(),LD=vh(),qD=require("stream"),gC=Th(),$D=require("util"),zD=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function HD(t){return Object.prototype.toString.call(t)==="[object Object]"}function WD(t){if(HD(t))return t;try{return JSON.parse(t)}catch{return}}function mC(t){var e=t.split(".",1)[0];return WD(pC.from(e,"base64").toString("binary"))}function GD(t){return t.split(".",2).join(".")}function yC(t){return t.split(".")[2]}function JD(t,e){e=e||"utf8";var n=t.split(".")[1];return pC.from(n,"base64").toString(e)}function _C(t){return zD.test(t)&&!!mC(t)}function bC(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=gC(t);var o=yC(t),s=GD(t),a=LD(e);return a.verify(s,o,n)}function wC(t,e){if(e=e||{},t=gC(t),!_C(t))return null;var n=mC(t);if(!n)return null;var r=JD(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:yC(t)}}function Yo(t){t=t||{};var e=t.secret||t.publicKey||t.key,n=new hC(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new hC(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}$D.inherits(Yo,qD);Yo.prototype.verify=function(){try{var e=bC(this.signature.buffer,this.algorithm,this.key.buffer),n=wC(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};Yo.decode=wC;Yo.isValid=_C;Yo.verify=bC;CC.exports=Yo});var Dh=V(Cr=>{var SC=fC(),Lc=kC(),VD=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Cr.ALGORITHMS=VD;Cr.sign=SC.sign;Cr.verify=Lc.verify;Cr.decode=Lc.decode;Cr.isValid=Lc.isValid;Cr.createSign=function(e){return new SC(e)};Cr.createVerify=function(e){return new Lc(e)}});var MC=V($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.GoogleToken=void 0;var AC=qc(require("fs")),KD=ct(),YD=qc(Dh()),XD=qc(require("path")),QD=require("util");function qc(t,e){if(typeof WeakMap=="function")var n=new WeakMap,r=new WeakMap;return(qc=function(s,a){if(!a&&s&&s.__esModule)return s;var c,l,f={__proto__:null,default:s};if(s===null||Gn(s)!="object"&&typeof s!="function")return f;if(c=a?r:n){if(c.has(s))return c.get(s);c.set(s,f)}for(var d in s)d!=="default"&&{}.hasOwnProperty.call(s,d)&&((l=(c=Object.defineProperty)&&Object.getOwnPropertyDescriptor(s,d))&&(l.get||l.set)?c(f,d,l):f[d]=s[d]);return f})(t,e)}function Gn(t){"@babel/helpers - typeof";return Gn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Gn(t)}function ZD(t,e){PC(t,e),e.add(t)}function ex(t,e,n){PC(t,e),e.set(t,n)}function PC(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function EC(t,e,n){return t.set(cn(t,e),n),n}function vC(t,e){return t.get(cn(t,e))}function cn(t,e,n){if(typeof t=="function"?t===e:t.has(e))return arguments.length<3?e:n;throw new TypeError("Private element is not present on this object")}function TC(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,BC(r.key),r)}}function IC(t,e,n){return e&&TC(t.prototype,e),n&&TC(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function NC(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function tx(t,e,n){return e=bi(e),nx(t,Nh()?Reflect.construct(e,n||[],bi(t).constructor):e.apply(t,n))}function nx(t,e){if(e&&(Gn(e)=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return rx(t)}function rx(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function ox(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_i(t,e)}function xh(t){var e=typeof Map=="function"?new Map:void 0;return xh=function(r){if(r===null||!ix(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(r))return e.get(r);e.set(r,o)}function o(){return sx(r,arguments,bi(this).constructor)}return o.prototype=Object.create(r.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),_i(o,r)},xh(t)}function sx(t,e,n){if(Nh())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var o=new(t.bind.apply(t,r));return n&&_i(o,n.prototype),o}function Nh(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Nh=function(){return!!t})()}function ix(t){try{return Function.toString.call(t).indexOf("[native code]")!==-1}catch{return typeof t=="function"}}function _i(t,e){return _i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},_i(t,e)}function bi(t){return bi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},bi(t)}function xt(t,e,n){return(e=BC(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function BC(t){var e=ax(t,"string");return Gn(e)=="symbol"?e:e+""}function ax(t,e){if(Gn(t)!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(Gn(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ft(){var t,e,n=typeof Symbol=="function"?Symbol:{},r=n.iterator||"@@iterator",o=n.toStringTag||"@@toStringTag";function s(S,y,w,b){var _=y&&y.prototype instanceof c?y:c,D=Object.create(_.prototype);return Ot(D,"_invoke",(function(k,v,x){var R,j,W,U=0,ue=x||[],Y=!1,ne={p:0,n:0,v:t,a:te,f:te.bind(t,4),d:function(K,se){return R=K,j=0,W=t,ne.n=se,a}};function te(re,K){for(j=re,W=K,e=0;!Y&&U&&!se&&e<ue.length;e++){var se,ie=ue[e],X=ne.p,Z=ie[2];re>3?(se=Z===K)&&(W=ie[(j=ie[4])?5:(j=3,3)],ie[4]=ie[5]=t):ie[0]<=X&&((se=re<2&&X<ie[1])?(j=0,ne.v=K,ne.n=ie[1]):X<Z&&(se=re<3||ie[0]>K||K>Z)&&(ie[4]=re,ie[5]=K,ne.n=Z,j=0))}if(se||re>1)return a;throw Y=!0,K}return function(re,K,se){if(U>1)throw TypeError("Generator is already running");for(Y&&K===1&&te(K,se),j=K,W=se;(e=j<2?t:W)||!Y;){R||(j?j<3?(j>1&&(ne.n=-1),te(j,W)):ne.n=W:ne.v=W);try{if(U=2,R){if(j||(re="next"),e=R[re]){if(!(e=e.call(R,W)))throw TypeError("iterator result is not an object");if(!e.done)return e;W=e.value,j<2&&(j=0)}else j===1&&(e=R.return)&&e.call(R),j<2&&(W=TypeError("The iterator does not provide a '"+re+"' method"),j=1);R=t}else if((e=(Y=ne.n<0)?W:k.call(v,ne))!==a)break}catch(ie){R=t,j=1,W=ie}finally{U=1}}return{value:e,done:Y}}})(S,w,b),!0),D}var a={};function c(){}function l(){}function f(){}e=Object.getPrototypeOf;var d=[][r]?e(e([][r]())):(Ot(e={},r,function(){return this}),e),h=f.prototype=c.prototype=Object.create(d);function m(S){return Object.setPrototypeOf?Object.setPrototypeOf(S,f):(S.__proto__=f,Ot(S,o,"GeneratorFunction")),S.prototype=Object.create(h),S}return l.prototype=f,Ot(h,"constructor",f),Ot(f,"constructor",l),l.displayName="GeneratorFunction",Ot(f,o,"GeneratorFunction"),Ot(h),Ot(h,o,"Generator"),Ot(h,r,function(){return this}),Ot(h,"toString",function(){return"[object Generator]"}),(Ft=function(){return{w:s,m}})()}function Ot(t,e,n,r){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}Ot=function(a,c,l,f){if(c)o?o(a,c,{value:l,enumerable:!f,configurable:!f,writable:!f}):a[c]=l;else{var d=function(m,S){Ot(a,m,function(y){return this._invoke(m,S,y)})};d("next",0),d("throw",1),d("return",2)}},Ot(t,e,n,r)}function RC(t,e,n,r,o,s,a){try{var c=t[s](a),l=c.value}catch(f){return void n(f)}c.done?e(l):Promise.resolve(l).then(r,o)}function Xo(t){return function(){var e=this,n=arguments;return new Promise(function(r,o){var s=t.apply(e,n);function a(l){RC(s,r,o,a,c,"next",l)}function c(l){RC(s,r,o,a,c,"throw",l)}a(void 0)})}}var DC=AC.readFile?(0,QD.promisify)(AC.readFile):Xo(Ft().m(function t(){return Ft().w(function(e){for(;;)switch(e.n){case 0:throw new yi("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},t)})),xC="https://oauth2.googleapis.com/token",cx="https://oauth2.googleapis.com/revoke?token=",yi=(function(t){function e(n,r){var o;return NC(this,e),o=tx(this,e,[n]),xt(o,"code",void 0),o.code=r,o}return ox(e,t),IC(e)})(xh(Error)),mi=new WeakMap,wn=new WeakSet,sM=$c.GoogleToken=(function(){function t(e){NC(this,t),ZD(this,wn),xt(this,"expiresAt",void 0),xt(this,"key",void 0),xt(this,"keyFile",void 0),xt(this,"iss",void 0),xt(this,"sub",void 0),xt(this,"scope",void 0),xt(this,"rawToken",void 0),xt(this,"tokenExpires",void 0),xt(this,"email",void 0),xt(this,"additionalClaims",void 0),xt(this,"eagerRefreshThresholdMillis",void 0),xt(this,"transporter",{request:function(r){return(0,KD.request)(r)}}),ex(this,mi,void 0),cn(wn,this,jC).call(this,e)}return IC(t,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var n=new Date().getTime();return this.rawToken&&this.expiresAt?n>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var n,r=new Date().getTime(),o=(n=this.eagerRefreshThresholdMillis)!==null&&n!==void 0?n:0;return this.rawToken&&this.expiresAt?this.expiresAt<=r+o:!0}},{key:"getToken",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Gn(n)==="object"&&(r=n,n=void 0),r=Object.assign({forceRefresh:!1},r),n){var o=n;cn(wn,this,OC).call(this,r).then(function(s){return o(null,s)},n);return}return cn(wn,this,OC).call(this,r)}},{key:"getCredentials",value:(function(){var e=Xo(Ft().m(function r(o){var s,a,c,l,f,d,h;return Ft().w(function(m){for(;;)switch(m.n){case 0:s=XD.extname(o),h=s,m.n=h===".json"?1:h===".der"||h===".crt"||h===".pem"?4:h===".p12"||h===".pfx"?6:7;break;case 1:return m.n=2,DC(o,"utf8");case 2:if(a=m.v,c=JSON.parse(a),l=c.private_key,f=c.client_email,!(!l||!f)){m.n=3;break}throw new yi("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return m.a(2,{privateKey:l,clientEmail:f});case 4:return m.n=5,DC(o,"utf8");case 5:return d=m.v,m.a(2,{privateKey:d});case 6:throw new yi("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new yi("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return m.a(2)}},r)}));function n(r){return e.apply(this,arguments)}return n})()},{key:"revokeToken",value:function(n){if(n){cn(wn,this,FC).call(this).then(function(){return n()},n);return}return cn(wn,this,FC).call(this)}}])})();function OC(t){return Oh.apply(this,arguments)}function Oh(){return Oh=Xo(Ft().m(function t(e){return Ft().w(function(n){for(;;)switch(n.n){case 0:if(!(vC(mi,this)&&!e.forceRefresh)){n.n=1;break}return n.a(2,vC(mi,this));case 1:return n.p=1,n.n=2,EC(mi,this,cn(wn,this,ux).call(this,e));case 2:return n.a(2,n.v);case 3:return n.p=3,EC(mi,this,void 0),n.f(3);case 4:return n.a(2)}},t,this,[[1,,3,4]])})),Oh.apply(this,arguments)}function ux(t){return Fh.apply(this,arguments)}function Fh(){return Fh=Xo(Ft().m(function t(e){var n;return Ft().w(function(r){for(;;)switch(r.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){r.n=1;break}return r.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){r.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){r.n=4;break}return r.n=3,this.getCredentials(this.keyFile);case 3:n=r.v,this.key=n.privateKey,this.iss=n.clientEmail||this.iss,n.clientEmail||cn(wn,this,lx).call(this);case 4:return r.a(2,cn(wn,this,dx).call(this))}},t,this)})),Fh.apply(this,arguments)}function lx(){if(!this.iss)throw new yi("email is required.","MISSING_CREDENTIALS")}function FC(){return Ph.apply(this,arguments)}function Ph(){return Ph=Xo(Ft().m(function t(){var e;return Ft().w(function(n){for(;;)switch(n.n){case 0:if(this.accessToken){n.n=1;break}throw new Error("No token to revoke.");case 1:return e=cx+this.accessToken,n.n=2,this.transporter.request({url:e,retry:!0});case 2:cn(wn,this,jC).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return n.a(2)}},t,this)})),Ph.apply(this,arguments)}function jC(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=t.keyFile,this.key=t.key,this.rawToken=void 0,this.iss=t.email||t.iss,this.sub=t.sub,this.additionalClaims=t.additionalClaims,Gn(t.scope)==="object"?this.scope=t.scope.join(" "):this.scope=t.scope,this.eagerRefreshThresholdMillis=t.eagerRefreshThresholdMillis,t.transporter&&(this.transporter=t.transporter)}function dx(){return Ih.apply(this,arguments)}function Ih(){return Ih=Xo(Ft().m(function t(){var e,n,r,o,s,a,c,l,f,d;return Ft().w(function(h){for(;;)switch(h.n){case 0:return e=Math.floor(new Date().getTime()/1e3),n=this.additionalClaims||{},r=Object.assign({iss:this.iss,scope:this.scope,aud:xC,exp:e+3600,iat:e,sub:this.sub},n),o=YD.sign({header:{alg:"RS256"},payload:r,secret:this.key}),h.p=1,h.n=2,this.transporter.request({method:"POST",url:xC,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return s=h.v,this.rawToken=s.data,this.expiresAt=s.data.expires_in===null||s.data.expires_in===void 0?void 0:(e+s.data.expires_in)*1e3,h.a(2,this.rawToken);case 3:throw h.p=3,d=h.v,this.rawToken=void 0,this.tokenExpires=void 0,l=d.response&&(a=d.response)!==null&&a!==void 0&&a.data?(c=d.response)===null||c===void 0?void 0:c.data:{},l.error&&(f=l.error_description?": ".concat(l.error_description):"",d.message="".concat(l.error).concat(f)),d;case 4:return h.a(2)}},t,this,[[1,3]])})),Ih.apply(this,arguments)}});var jh=V(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.JWTAccess=void 0;var fx=Dh(),hx=on(),UC={alg:"RS256",typ:"JWT"},Bh=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new hx.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),a=Date.now();if(s&&s.expiration-a>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1e3),l=t.getExpirationTime(c),f;if(Array.isArray(r)&&(r=r.join(" ")),r?f={iss:this.email,sub:this.email,scope:r,exp:l,iat:c}:f={iss:this.email,sub:this.email,aud:e,exp:l,iat:c},n){for(let y in f)if(n[y])throw new Error(`The '${y}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...UC,kid:this.keyId}:UC,h=Object.assign(f,n),m=fx.sign({header:d,payload:h,secret:this.key}),S=new Headers({authorization:`Bearer ${m}`});return this.cache.set(o,{expiration:l*1e3,headers:S}),S}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};zc.JWTAccess=Bh});var Uh=V(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.JWT=void 0;var LC=MC(),px=jh(),gx=oo(),Hc=Dt(),Mh=class t extends gx.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Hc.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Hc.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Hc.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new px.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Hc.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new LC.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new LC.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let n=await this.createGToken().getCredentials(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Wc.JWT=Mh});var qh=V(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.UserRefreshClient=Qo.USER_REFRESH_ACCOUNT_TYPE=void 0;var mx=oo(),yx=Dt();Qo.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Lh=class t extends mx.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let a=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(a),this._refreshToken=a.refreshToken,this.credentials.refresh_token=a.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return yx.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};Qo.UserRefreshClient=Lh});var zh=V(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.Impersonated=Zo.IMPERSONATED_ACCOUNT_TYPE=void 0;var qC=oo(),_x=ct(),bx=on();Zo.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var $h=class t extends qC.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),console.warn("The `Impersonated` constructor does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new qC.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,bx.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof _x.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Zo.Impersonated=$h});var Wh=V(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.OAuthClientAuthHandler=void 0;wi.getErrorFromOAuthErrorResponse=kx;var es=ct(),wx=li(),Cx=["PUT","POST","PATCH"],Hh=class{#e=(0,wx.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new es.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new es.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=es.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=es.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=es.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);es.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!Cx.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};wi.OAuthClientAuthHandler=Hh;function kx(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let a=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(l=>{l!=="message"&&Object.defineProperty(a,l,{value:e[l],writable:!1,enumerable:!0})})}return a}});var Jc=V(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.StsCredentials=void 0;var Sx=ct(),Ax=Dt(),$C=Wh(),Ex=on(),Gh=class t extends $C.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,Ex.removeUndefinedValuesInObject)(o))};Ax.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let a=await this.transporter.request(s),c=a.data;return c.res=a,c}catch(a){throw a instanceof Sx.GaxiosError&&a.response?(0,$C.getErrorFromOAuthErrorResponse)(a.response.data,a):a}}};Gc.StsCredentials=Gh});var kr=V(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.BaseExternalAccountClient=Wt.CLOUD_RESOURCE_MANAGER=Wt.EXTERNAL_ACCOUNT_TYPE=Wt.EXPIRATION_TIME_OFFSET=void 0;var vx=ct(),Tx=require("stream"),Jh=Dt(),Rx=Jc(),zC=on(),Dx=ch(),xx="urn:ietf:params:oauth:grant-type:token-exchange",Ox="urn:ietf:params:oauth:token-type:access_token",Vh="https://www.googleapis.com/auth/cloud-platform",Fx=3600;Wt.EXPIRATION_TIME_OFFSET=300*1e3;Wt.EXTERNAL_ACCOUNT_TYPE="external_account";Wt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Px="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Ix="https://sts.{universeDomain}/v1/token",Kh=class t extends Jh.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,zC.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Wt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Wt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??Ix.replace("{universeDomain}",this.universeDomain);let a=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),l=n.get("service_account_impersonation_url"),f=n.get("service_account_impersonation"),d=(0,zC.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new Rx.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Vh],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=a,this.workforcePoolUserProject=c;let h=new RegExp(Px);if(this.workforcePoolUserProject&&!this.audience.match(h))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=l,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Fx),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`};Jh.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=vx.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof Tx.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:xx,audience:this.audience,requestedTokenType:Ox,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Vh]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Jh.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Vh]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Dx.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Wt.BaseExternalAccountClient=Kh});var HC=V(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.FileSubjectTokenSupplier=void 0;var Xh=require("util"),Qh=require("fs"),Nx=(0,Xh.promisify)(Qh.readFile??(()=>{})),Bx=(0,Xh.promisify)(Qh.realpath??(()=>{})),jx=(0,Xh.promisify)(Qh.lstat??(()=>{})),Yh=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await Bx(e),!(await jx(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await Nx(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Vc.FileSubjectTokenSupplier=Yh});var WC=V(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.UrlSubjectTokenSupplier=void 0;var Mx=Dt(),Zh=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};Mx.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Kc.UrlSubjectTokenSupplier=Zh});var GC=V(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.CertificateSubjectTokenSupplier=Pt.InvalidConfigurationError=Pt.CertificateSourceUnavailableError=Pt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Yc=on(),Xc=require("fs"),Qc=require("crypto"),Ux=require("https");Pt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Cn=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Pt.CertificateSourceUnavailableError=Cn;var Gt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Pt.InvalidConfigurationError=Gt;var ep=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Gt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Gt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Gt("Cannot create mTLS Agent with missing certificate or key");return new Ux.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Yc.isValidFile)(e))return e;throw new Cn(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Pt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Yc.isValidFile)(n))return n;throw new Cn(`Path from environment variable "${Pt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Yc.getWellKnownCertificateConfigFileLocation)();if(await(0,Yc.isValidFile)(r))return r;throw new Cn(`Could not find certificate configuration file. Searched override path, the "${Pt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Xc.promises.readFile(e,"utf8")}catch{throw new Cn(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Gt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Gt?r:new Gt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Xc.promises.readFile(e),new Qc.X509Certificate(r)}catch(s){let a=s instanceof Error?s.message:String(s);throw new Cn(`Failed to read certificate file at ${e}: ${a}`)}try{o=await Xc.promises.readFile(n),(0,Qc.createPrivateKey)(o)}catch(s){let a=s instanceof Error?s.message:String(s);throw new Cn(`Failed to read private key file at ${n}: ${a}`)}return{cert:r,key:o}}async#r(e){let n=new Qc.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Xc.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((l,f)=>{try{return new Qc.X509Certificate(l)}catch(d){let h=d instanceof Error?d.message:String(d);throw new Gt(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${h}`)}}),a=s.findIndex(l=>n.raw.equals(l.raw)),c;if(a===-1)c=[n,...s];else if(a===0)c=s;else throw new Gt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${a}).`);return JSON.stringify(c.map(l=>l.raw.toString("base64")))}catch(r){if(r instanceof Gt)throw r;let o=r instanceof Error?r.message:String(r);throw new Cn(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Pt.CertificateSubjectTokenSupplier=ep});var rp=V(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.IdentityPoolClient=void 0;var Lx=kr(),tp=on(),qx=HC(),$x=WC(),JC=GC(),zx=Jc(),VC=ct(),np=class t extends Lx.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,tp.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,tp.originalOrCamelOptions)(r),a=(0,tp.originalOrCamelOptions)(s.get("format")),c=a.get("type")||"text",l=a.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!l)throw new Error("Missing subject_token_field_name for JSON credential_source format");let f=s.get("file"),d=s.get("url"),h=s.get("certificate"),m=s.get("headers");if(f&&d||d&&h||f&&h)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new qx.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:l});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new $x.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:l,headers:m,additionalGaxiosOptions:t.RETRY_CONFIG});else if(h){this.credentialSourceType="certificate";let S=new JC.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:h.use_default_certificate_config,certificateConfigLocation:h.certificate_config_location,trustChainPath:h.trust_chain_path});this.subjectTokenSupplier=S}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof JC.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new zx.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new VC.Gaxios({agent:n})}),this.transporter=new VC.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Zc.IdentityPoolClient=np});var sp=V(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.AwsRequestSigner=void 0;var eu=ct(),YC=li(),KC="AWS4-HMAC-SHA256",Hx="aws4_request",op=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,YC.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,a=e.headers,c=await this.getCredentials(),l=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await Gx({crypto:this.crypto,host:l.host,canonicalUri:l.pathname,canonicalQuerystring:l.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:a}),d=eu.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:l.host},a||{});c.token&&eu.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let h={url:r,method:o,headers:d};return s!==void 0&&(h.body=s),h}};tu.AwsRequestSigner=op;async function Ci(t,e,n){return await t.signWithHmacSha256(e,n)}async function Wx(t,e,n,r,o){let s=await Ci(t,`AWS4${e}`,n),a=await Ci(t,s,r),c=await Ci(t,a,o);return await Ci(t,c,"aws4_request")}async function Gx(t){let e=eu.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),a=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=eu.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),l="",f=[...c.keys()].sort();f.forEach(D=>{l+=`${D}:${c.get(D)}
53
- `});let d=f.join(";"),h=await t.crypto.sha256DigestHex(n),m=`${t.method.toUpperCase()}
81
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,$i="secret must be a string or buffer",ls="key must be a string or a buffer",eI="key must be a string, a buffer or an object",jh=typeof $t.createPublicKey=="function";jh&&(ls+=" or a KeyObject",$i+="or a KeyObject");function XS(t){if(!ds.isBuffer(t)&&typeof t!="string"&&(!jh||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw on(ls)}function QS(t){if(!ds.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw on(eI)}function tI(t){if(!ds.isBuffer(t)){if(typeof t=="string")return t;if(!jh||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw on($i)}}function Lh(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ZS(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function on(t){var e=[].slice.call(arguments,1),n=KS.format.bind(KS,t).apply(null,e);return new TypeError(n)}function nI(t){return ds.isBuffer(t)||typeof t=="string"}function zi(t){return nI(t)||(t=JSON.stringify(t)),t}function eE(t){return function(n,r){tI(r),n=zi(n);var o=$t.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Lh(s)}}var Uh,rI="timingSafeEqual"in $t?function(e,n){return e.byteLength!==n.byteLength?!1:$t.timingSafeEqual(e,n)}:function(e,n){return Uh||(Uh=VS()),Uh(e,n)};function oI(t){return function(n,r,o){var s=eE(t)(n,o);return rI(ds.from(r),ds.from(s))}}function tE(t){return function(n,r){QS(r),n=zi(n);var o=$t.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Lh(s)}}function nE(t){return function(n,r,o){XS(o),n=zi(n),r=ZS(r);var s=$t.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function sI(t){return function(n,r){QS(r),n=zi(n);var o=$t.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:$t.constants.RSA_PKCS1_PSS_PADDING,saltLength:$t.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Lh(s)}}function iI(t){return function(n,r,o){XS(o),n=zi(n),r=ZS(r);var s=$t.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:$t.constants.RSA_PKCS1_PSS_PADDING,saltLength:$t.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function aI(t){var e=tE(t);return function(){var r=e.apply(null,arguments);return r=YS.derToJose(r,"ES"+t),r}}function cI(t){var e=nE(t);return function(r,o,s){o=YS.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function uI(){return function(){return""}}function lI(){return function(e,n){return n===""}}rE.exports=function(e){var n={hs:eE,rs:tE,ps:sI,es:aI,none:uI},r={hs:oI,rs:nE,ps:iI,es:cI,none:lI},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw on(ZP,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var $h=J((Sz,oE)=>{var dI=require("buffer").Buffer;oE.exports=function(e){return typeof e=="string"?e:typeof e=="number"||dI.isBuffer(e)?e.toString():JSON.stringify(e)}});var lE=J((Ez,uE)=>{var fI=as().Buffer,sE=Mh(),pI=qh(),hI=require("stream"),iE=$h(),zh=require("util");function aE(t,e){return fI.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function mI(t,e,n){n=n||"utf8";var r=aE(iE(t),"binary"),o=aE(iE(e),n);return zh.format("%s.%s",r,o)}function cE(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=pI(e.alg),i=mI(e,n,o),c=s.sign(i,r);return zh.format("%s.%s",i,c)}function xu(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new sE(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new sE(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}zh.inherits(xu,hI);xu.prototype.sign=function(){try{var e=cE({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};xu.sign=cE;uE.exports=xu});var CE=J((vz,bE)=>{var fE=as().Buffer,dE=Mh(),gI=qh(),yI=require("stream"),pE=$h(),_I=require("util"),bI=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function CI(t){return Object.prototype.toString.call(t)==="[object Object]"}function wI(t){if(CI(t))return t;try{return JSON.parse(t)}catch{return}}function hE(t){var e=t.split(".",1)[0];return wI(fE.from(e,"base64").toString("binary"))}function kI(t){return t.split(".",2).join(".")}function mE(t){return t.split(".")[2]}function SI(t,e){e=e||"utf8";var n=t.split(".")[1];return fE.from(n,"base64").toString(e)}function gE(t){return bI.test(t)&&!!hE(t)}function yE(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=pE(t);var o=mE(t),s=kI(t),i=gI(e);return i.verify(s,o,n)}function _E(t,e){if(e=e||{},t=pE(t),!gE(t))return null;var n=hE(t);if(!n)return null;var r=SI(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:mE(t)}}function fs(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new dE(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new dE(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}_I.inherits(fs,yI);fs.prototype.verify=function(){try{var e=yE(this.signature.buffer,this.algorithm,this.key.buffer),n=_E(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};fs.decode=_E;fs.isValid=gE;fs.verify=yE;bE.exports=fs});var Hh=J(Or=>{var wE=lE(),Du=CE(),EI=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Or.ALGORITHMS=EI;Or.sign=wE.sign;Or.verify=Du.verify;Or.decode=Du.decode;Or.isValid=Du.isValid;Or.createSign=function(e){return new wE(e)};Or.createVerify=function(e){return new Du(e)}});var SE=J(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.buildPayloadForJwsSign=kE;Ou.getJwsSign=RI;var vI=Hh(),AI="RS256",TI="https://oauth2.googleapis.com/token";function kE(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:TI,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function RI(t){let e=kE(t);return(0,vI.sign)({header:{alg:AI},payload:e,secret:t.key})}});var EE=J(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});Wh.getToken=II;var xI=SE(),DI="https://oauth2.googleapis.com/token",OI="urn:ietf:params:oauth:grant-type:jwt-bearer",PI=t=>({method:"POST",url:DI,data:new URLSearchParams({grant_type:OI,assertion:(0,xI.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function II(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=PI(t);return(await t.transporter.request(e)).data}catch(e){let n=e,r=n.response?.data;throw r?.error&&(n.message=`${r.error}: ${r.error_description}`),n}}});var vE=J(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.ErrorWithCode=void 0;var Gh=class extends Error{code;constructor(e,n){super(e),this.code=n}};Pu.ErrorWithCode=Gh});var Qh=J(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});Xh.getCredentials=MI;var FI=require("path"),AE=require("fs"),NI=require("util"),Iu=vE(),TE=AE.readFile?(0,NI.promisify)(AE.readFile):async()=>{throw new Iu.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Pr;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Pr||(Pr={}));var Jh=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await TE(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let i=s;throw new Error(`Invalid JSON key file: ${i.message}`)}let r=n.private_key,o=n.client_email;if(!r||!o)throw new Iu.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},Vh=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await TE(this.keyFilePath,"utf8")}}},Kh=class{async getCredentials(){throw new Iu.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},Yh=class{static create(e){switch(FI.extname(e)){case Pr.JSON:return new Jh(e);case Pr.DER:case Pr.CRT:case Pr.PEM:return new Vh(e);case Pr.P12:case Pr.PFX:return new Kh;default:throw new Iu.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function MI(t){return Yh.create(t).getCredentials()}});var RE=J(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.TokenHandler=void 0;var BI=EE(),UI=Qh(),Zh=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,UI.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,BI.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};Fu.TokenHandler=Zh});var xE=J(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.revokeToken=qI;var jI="https://oauth2.googleapis.com/revoke?token=",LI=!0;async function qI(t,e){let n=jI+t;return await e.request({url:n,retry:LI})}});var nm=J(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.GoogleToken=void 0;var $I=lt(),DE=RE(),zI=xE(),tm=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,$I.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new DE.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let r;typeof e=="function"?r=e:typeof e=="object"&&(n=e);let o=this.tokenHandler.getToken(n.forceRefresh??!1);return r&&o.then(s=>r(null,s),r),o}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,zI.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new DE.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};Nu.GoogleToken=tm});var om=J(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.JWTAccess=void 0;var HI=Hh(),WI=nn(),OE={alg:"RS256",typ:"JWT"},rm=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new WI.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),i=Date.now();if(s&&s.expiration-i>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let c=Math.floor(Date.now()/1e3),u=t.getExpirationTime(c),f;if(Array.isArray(r)&&(r=r.join(" ")),r?f={iss:this.email,sub:this.email,scope:r,exp:u,iat:c}:f={iss:this.email,sub:this.email,aud:e,exp:u,iat:c},n){for(let b in f)if(n[b])throw new Error(`The '${b}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...OE,kid:this.keyId}:OE,p=Object.assign(f,n),h=HI.sign({header:d,payload:p,secret:this.key}),_=new Headers({authorization:`Bearer ${h}`});return this.cache.set(o,{expiration:u*1e3,headers:_}),_}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};Mu.JWTAccess=rm});var im=J(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});Uu.JWT=void 0;var PE=nm(),GI=Qh(),JI=om(),VI=Dr(),Bu=Dt(),sm=class t extends VI.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Bu.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Bu.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Bu.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new JI.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Bu.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new PE.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new PE.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,GI.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Uu.JWT=sm});var cm=J(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.UserRefreshClient=ps.USER_REFRESH_ACCOUNT_TYPE=void 0;var KI=Dr(),YI=Dt();ps.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var am=class t extends KI.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let i=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(i),this._refreshToken=i.refreshToken,this.credentials.refresh_token=i.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return YI.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};ps.UserRefreshClient=am});var lm=J(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.Impersonated=hs.IMPERSONATED_ACCOUNT_TYPE=void 0;var IE=Dr(),XI=lt(),QI=nn();hs.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var um=class t extends IE.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new IE.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,QI.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof XI.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};hs.Impersonated=um});var fm=J(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.OAuthClientAuthHandler=void 0;Hi.getErrorFromOAuthErrorResponse=tF;var ms=lt(),ZI=Ui(),eF=["PUT","POST","PATCH"],dm=class{#e=(0,ZI.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ms.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ms.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=ms.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=ms.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ms.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);ms.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!eF.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Hi.OAuthClientAuthHandler=dm;function tF(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let i=new Error(s);if(e){let c=Object.keys(e);e.stack&&c.push("stack"),c.forEach(u=>{u!=="message"&&Object.defineProperty(i,u,{value:e[u],writable:!1,enumerable:!0})})}return i}});var Lu=J(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});ju.StsCredentials=void 0;var nF=lt(),rF=Dt(),FE=fm(),oF=nn(),pm=class t extends FE.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,oF.removeUndefinedValuesInObject)(o)),responseType:"json"};rF.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let i=await this.transporter.request(s),c=i.data;return c.res=i,c}catch(i){throw i instanceof nF.GaxiosError&&i.response?(0,FE.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};ju.StsCredentials=pm});var Ir=J(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.BaseExternalAccountClient=zt.CLOUD_RESOURCE_MANAGER=zt.EXTERNAL_ACCOUNT_TYPE=zt.EXPIRATION_TIME_OFFSET=void 0;var sF=lt(),iF=require("stream"),hm=Dt(),aF=Lu(),NE=nn(),cF=Sh(),uF="urn:ietf:params:oauth:grant-type:token-exchange",lF="urn:ietf:params:oauth:token-type:access_token",mm="https://www.googleapis.com/auth/cloud-platform",dF=3600;zt.EXPIRATION_TIME_OFFSET=300*1e3;zt.EXTERNAL_ACCOUNT_TYPE="external_account";zt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var fF="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",pF="https://sts.{universeDomain}/v1/token",gm=class t extends hm.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,NE.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==zt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${zt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??pF.replace("{universeDomain}",this.universeDomain);let i=n.get("subject_token_type"),c=n.get("workforce_pool_user_project"),u=n.get("service_account_impersonation_url"),f=n.get("service_account_impersonation"),d=(0,NE.originalOrCamelOptions)(f).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new aF.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[mm],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=c;let p=new RegExp(fF);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=u,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=dF),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};hm.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=sF.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,c=s.config.data instanceof iF.Readable;if(!n&&(i===401||i===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:uF,audience:this.audience,requestedTokenType:lF,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[mm]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};hm.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[mm]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${cF.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};zt.BaseExternalAccountClient=gm});var ME=J(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.FileSubjectTokenSupplier=void 0;var _m=require("util"),bm=require("fs"),hF=(0,_m.promisify)(bm.readFile??(()=>{})),mF=(0,_m.promisify)(bm.realpath??(()=>{})),gF=(0,_m.promisify)(bm.lstat??(()=>{})),ym=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await mF(e),!(await gF(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await hF(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};qu.FileSubjectTokenSupplier=ym});var BE=J($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.UrlSubjectTokenSupplier=void 0;var yF=Dt(),Cm=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};yF.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};$u.UrlSubjectTokenSupplier=Cm});var UE=J(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.CertificateSubjectTokenSupplier=Ot.InvalidConfigurationError=Ot.CertificateSourceUnavailableError=Ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var zu=nn(),Hu=require("fs"),Wu=require("crypto"),_F=require("https");Ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var En=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Ot.CertificateSourceUnavailableError=En;var Ht=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Ot.InvalidConfigurationError=Ht;var wm=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Ht("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Ht("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Ht("Cannot create mTLS Agent with missing certificate or key");return new _F.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,zu.isValidFile)(e))return e;throw new En(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,zu.isValidFile)(n))return n;throw new En(`Path from environment variable "${Ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,zu.getWellKnownCertificateConfigFileLocation)();if(await(0,zu.isValidFile)(r))return r;throw new En(`Could not find certificate configuration file. Searched override path, the "${Ot.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Hu.promises.readFile(e,"utf8")}catch{throw new En(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Ht(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Ht?r:new Ht(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Hu.promises.readFile(e),new Wu.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new En(`Failed to read certificate file at ${e}: ${i}`)}try{o=await Hu.promises.readFile(n),(0,Wu.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new En(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new Wu.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Hu.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,f)=>{try{return new Wu.X509Certificate(u)}catch(d){let p=d instanceof Error?d.message:String(d);throw new Ht(`Failed to parse certificate at index ${f} in trust chain file ${this.trustChainPath}: ${p}`)}}),i=s.findIndex(u=>n.raw.equals(u.raw)),c;if(i===-1)c=[n,...s];else if(i===0)c=s;else throw new Ht(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(c.map(u=>u.raw.toString("base64")))}catch(r){if(r instanceof Ht)throw r;let o=r instanceof Error?r.message:String(r);throw new En(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Ot.CertificateSubjectTokenSupplier=wm});var Em=J(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});Gu.IdentityPoolClient=void 0;var bF=Ir(),km=nn(),CF=ME(),wF=BE(),jE=UE(),kF=Lu(),LE=lt(),Sm=class t extends bF.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,km.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,km.originalOrCamelOptions)(r),i=(0,km.originalOrCamelOptions)(s.get("format")),c=i.get("type")||"text",u=i.get("subject_token_field_name");if(c!=="json"&&c!=="text")throw new Error(`Invalid credential_source format "${c}"`);if(c==="json"&&!u)throw new Error("Missing subject_token_field_name for JSON credential_source format");let f=s.get("file"),d=s.get("url"),p=s.get("certificate"),h=s.get("headers");if(f&&d||d&&p||f&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(f)this.credentialSourceType="file",this.subjectTokenSupplier=new CF.FileSubjectTokenSupplier({filePath:f,formatType:c,subjectTokenFieldName:u});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new wF.UrlSubjectTokenSupplier({url:d,formatType:c,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let _=new jE.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=_}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof jE.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new kF.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new LE.Gaxios({agent:n})}),this.transporter=new LE.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Gu.IdentityPoolClient=Sm});var Am=J(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.AwsRequestSigner=void 0;var Ju=lt(),$E=Ui(),qE="AWS4-HMAC-SHA256",SF="aws4_request",vm=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,$E.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,i=e.headers,c=await this.getCredentials(),u=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let f=await vF({crypto:this.crypto,host:u.host,canonicalUri:u.pathname,canonicalQuerystring:u.search.slice(1),method:o,region:this.region,securityCredentials:c,requestPayload:s,additionalAmzHeaders:i}),d=Ju.Gaxios.mergeHeaders(f.amzDate?{"x-amz-date":f.amzDate}:{},{authorization:f.authorizationHeader,host:u.host},i||{});c.token&&Ju.Gaxios.mergeHeaders(d,{"x-amz-security-token":c.token});let p={url:r,method:o,headers:d};return s!==void 0&&(p.body=s),p}};Vu.AwsRequestSigner=vm;async function Wi(t,e,n){return await t.signWithHmacSha256(e,n)}async function EF(t,e,n,r,o){let s=await Wi(t,`AWS4${e}`,n),i=await Wi(t,s,r),c=await Wi(t,i,o);return await Wi(t,c,"aws4_request")}async function vF(t){let e=Ju.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),i=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let c=Ju.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),u="",f=[...c.keys()].sort();f.forEach(v=>{u+=`${v}:${c.get(v)}
82
+ `});let d=f.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
54
83
  ${t.canonicalUri}
55
84
  ${t.canonicalQuerystring}
56
- ${l}
85
+ ${u}
57
86
  ${d}
58
- ${h}`,S=`${a}/${t.region}/${r}/${Hx}`,y=`${KC}
87
+ ${p}`,_=`${i}/${t.region}/${r}/${SF}`,b=`${qE}
59
88
  ${s}
60
- ${S}
61
- `+await t.crypto.sha256DigestHex(m),w=await Wx(t.crypto,t.securityCredentials.secretAccessKey,a,t.region,r),b=await Ci(t.crypto,w,y),_=`${KC} Credential=${t.securityCredentials.accessKeyId}/${S}, SignedHeaders=${d}, Signature=${(0,YC.fromArrayBufferToHex)(b)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:_,canonicalQuerystring:t.canonicalQuerystring}}});var XC=V(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.DefaultAwsSecurityCredentialsSupplier=void 0;var nu=Dt(),ip=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:n};nu.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return nu.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return nu.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n};return nu.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};ru.DefaultAwsSecurityCredentialsSupplier=ip});var cp=V(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.AwsClient=void 0;var Jx=sp(),Vx=kr(),Kx=XC(),QC=on(),Yx=ct(),ap=class t extends Vx.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,QC.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,QC.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let a=s.get("region_url"),c=s.get("url"),l=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Kx.DefaultAwsSecurityCredentialsSupplier({regionUrl:a,securityCredentialsUrl:c,imdsV2SessionTokenUrl:l}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new Jx.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return Yx.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};ou.AwsClient=ap});var hp=V(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.InvalidSubjectTokenError=Ye.InvalidMessageFieldError=Ye.InvalidCodeFieldError=Ye.InvalidTokenTypeFieldError=Ye.InvalidExpirationTimeFieldError=Ye.InvalidSuccessFieldError=Ye.InvalidVersionFieldError=Ye.ExecutableResponseError=Ye.ExecutableResponse=void 0;var su="urn:ietf:params:oauth:token-type:saml2",up="urn:ietf:params:oauth:token-type:id_token",lp="urn:ietf:params:oauth:token-type:jwt",dp=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new iu("Executable response must contain a 'version' field.");if(e.success===void 0)throw new au("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==su&&this.tokenType!==up&&this.tokenType!==lp)throw new cu(`Executable response must contain a 'token_type' field when successful and it must be one of ${up}, ${lp}, or ${su}.`);if(this.tokenType===su){if(!e.saml_response)throw new ki(`Executable response must contain a 'saml_response' field when token_type=${su}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new ki(`Executable response must contain a 'id_token' field when token_type=${up} or ${lp}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new uu("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new lu("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Ye.ExecutableResponse=dp;var kn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Ye.ExecutableResponseError=kn;var iu=class extends kn{};Ye.InvalidVersionFieldError=iu;var au=class extends kn{};Ye.InvalidSuccessFieldError=au;var fp=class extends kn{};Ye.InvalidExpirationTimeFieldError=fp;var cu=class extends kn{};Ye.InvalidTokenTypeFieldError=cu;var uu=class extends kn{};Ye.InvalidCodeFieldError=uu;var lu=class extends kn{};Ye.InvalidMessageFieldError=lu;var ki=class extends kn{};Ye.InvalidSubjectTokenError=ki});var mp=V(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.PluggableAuthHandler=ts.ExecutableError=void 0;var so=hp(),Xx=require("child_process"),pp=require("fs"),du=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};ts.ExecutableError=du;var gp=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=Xx.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let a=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(a),c===0)try{let l=JSON.parse(s),f=new so.ExecutableResponse(l);return n(f)}catch(l){return l instanceof so.ExecutableResponseError?r(l):r(new so.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new du(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await pp.promises.realpath(this.outputFile)}catch{return}if(!(await pp.promises.lstat(e)).isFile())return;let n=await pp.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new so.ExecutableResponse(r).isValid()?new so.ExecutableResponse(r):void 0}catch(r){throw r instanceof so.ExecutableResponseError?r:new so.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};ts.PluggableAuthHandler=gp});var _p=V(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.PluggableAuthClient=ns.ExecutableError=void 0;var Qx=kr(),Zx=hp(),ZC=mp(),eO=mp();Object.defineProperty(ns,"ExecutableError",{enumerable:!0,get:function(){return eO.ExecutableError}});var tO=30*1e3,ek=5*1e3,tk=120*1e3,nO="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",nk=1,yp=class extends Qx.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=tO;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<ek||this.timeoutMillis>tk)throw new Error(`Timeout must be between ${ek} and ${tk} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new ZC.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[nO]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>nk)throw new Error(`Version of executable is not currently supported, maximum supported version is ${nk}.`);if(!e.success)throw new ZC.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Zx.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ns.PluggableAuthClient=yp});var wp=V(fu=>{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.ExternalAccountClient=void 0;var rO=kr(),oO=rp(),sO=cp(),iO=_p(),bp=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return console.warn("The `fromJSON` method does not validate the credential configuration. A security risk occurs when a credential configuration configured with malicious URLs is used. When the credential configuration is accepted from an untrusted source, you should validate it before using it with this method. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),e&&e.type===rO.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new sO.AwsClient(e):e.credential_source?.executable?new iO.PluggableAuthClient(e):new oO.IdentityPoolClient(e):null}};fu.ExternalAccountClient=bp});var ik=V(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.ExternalAccountAuthorizedUserClient=rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var ok=Dt(),rk=Wh(),sk=ct(),aO=require("stream"),cO=kr();rs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var uO="https://sts.{universeDomain}/v1/oauthtoken",Cp=class t extends rk.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};ok.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof sk.GaxiosError&&o.response?(0,rk.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},kp=class extends ok.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Cp({tokenRefreshEndpoint:e.token_url??uO.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=cO.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=sk.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof aO.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};rs.ExternalAccountAuthorizedUserClient=kp});var lk=V(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.GoogleAuth=un.GoogleAuthExceptionMessages=void 0;var lO=require("child_process"),Si=require("fs"),dO=ct(),Ai=ui(),fO=require("os"),Sp=require("path"),hO=li(),pO=yh(),gO=bh(),mO=wh(),os=Uh(),ak=qh(),ss=zh(),yO=wp(),Ei=kr(),Ap=Dt(),ck=ik(),uk=on();un.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
89
+ ${_}
90
+ `+await t.crypto.sha256DigestHex(h),y=await EF(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),w=await Wi(t.crypto,y,b),C=`${qE} Credential=${t.securityCredentials.accessKeyId}/${_}, SignedHeaders=${d}, Signature=${(0,$E.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:C,canonicalQuerystring:t.canonicalQuerystring}}});var zE=J(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.DefaultAwsSecurityCredentialsSupplier=void 0;var Ku=Dt(),Tm=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};Ku.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Ku.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return Ku.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return Ku.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Yu.DefaultAwsSecurityCredentialsSupplier=Tm});var xm=J(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});Xu.AwsClient=void 0;var AF=Am(),TF=Ir(),RF=zE(),HE=nn(),xF=lt(),Rm=class t extends TF.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,HE.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,HE.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let i=s.get("region_url"),c=s.get("url"),u=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new RF.DefaultAwsSecurityCredentialsSupplier({regionUrl:i,securityCredentialsUrl:c,imdsV2SessionTokenUrl:u}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new AF.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return xF.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};Xu.AwsClient=Rm});var Fm=J(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.InvalidSubjectTokenError=Xe.InvalidMessageFieldError=Xe.InvalidCodeFieldError=Xe.InvalidTokenTypeFieldError=Xe.InvalidExpirationTimeFieldError=Xe.InvalidSuccessFieldError=Xe.InvalidVersionFieldError=Xe.ExecutableResponseError=Xe.ExecutableResponse=void 0;var Qu="urn:ietf:params:oauth:token-type:saml2",Dm="urn:ietf:params:oauth:token-type:id_token",Om="urn:ietf:params:oauth:token-type:jwt",Pm=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Zu("Executable response must contain a 'version' field.");if(e.success===void 0)throw new el("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Qu&&this.tokenType!==Dm&&this.tokenType!==Om)throw new tl(`Executable response must contain a 'token_type' field when successful and it must be one of ${Dm}, ${Om}, or ${Qu}.`);if(this.tokenType===Qu){if(!e.saml_response)throw new Gi(`Executable response must contain a 'saml_response' field when token_type=${Qu}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Gi(`Executable response must contain a 'id_token' field when token_type=${Dm} or ${Om}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new nl("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new rl("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Xe.ExecutableResponse=Pm;var vn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Xe.ExecutableResponseError=vn;var Zu=class extends vn{};Xe.InvalidVersionFieldError=Zu;var el=class extends vn{};Xe.InvalidSuccessFieldError=el;var Im=class extends vn{};Xe.InvalidExpirationTimeFieldError=Im;var tl=class extends vn{};Xe.InvalidTokenTypeFieldError=tl;var nl=class extends vn{};Xe.InvalidCodeFieldError=nl;var rl=class extends vn{};Xe.InvalidMessageFieldError=rl;var Gi=class extends vn{};Xe.InvalidSubjectTokenError=Gi});var Bm=J(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.PluggableAuthHandler=gs.ExecutableError=void 0;var yo=Fm(),DF=require("child_process"),Nm=require("fs"),ol=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};gs.ExecutableError=ol;var Mm=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=DF.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",c=>{s+=c}),o.stderr.on("data",c=>{s+=c});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",c=>{if(clearTimeout(i),c===0)try{let u=JSON.parse(s),f=new yo.ExecutableResponse(u);return n(f)}catch(u){return u instanceof yo.ExecutableResponseError?r(u):r(new yo.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new ol(s,c.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Nm.promises.realpath(this.outputFile)}catch{return}if(!(await Nm.promises.lstat(e)).isFile())return;let n=await Nm.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new yo.ExecutableResponse(r).isValid()?new yo.ExecutableResponse(r):void 0}catch(r){throw r instanceof yo.ExecutableResponseError?r:new yo.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};gs.PluggableAuthHandler=Mm});var jm=J(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.PluggableAuthClient=ys.ExecutableError=void 0;var OF=Ir(),PF=Fm(),WE=Bm(),IF=Bm();Object.defineProperty(ys,"ExecutableError",{enumerable:!0,get:function(){return IF.ExecutableError}});var FF=30*1e3,GE=5*1e3,JE=120*1e3,NF="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",VE=1,Um=class extends OF.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=FF;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<GE||this.timeoutMillis>JE)throw new Error(`Timeout must be between ${GE} and ${JE} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new WE.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[NF]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>VE)throw new Error(`Version of executable is not currently supported, maximum supported version is ${VE}.`);if(!e.success)throw new WE.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new PF.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};ys.PluggableAuthClient=Um});var qm=J(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.ExternalAccountClient=void 0;var MF=Ir(),BF=Em(),UF=xm(),jF=jm(),Lm=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===MF.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new UF.AwsClient(e):e.credential_source?.executable?new jF.PluggableAuthClient(e):new BF.IdentityPoolClient(e):null}};sl.ExternalAccountClient=Lm});var Hm=J(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.ExternalAccountAuthorizedUserClient=_s.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var YE=Dt(),KE=fm(),XE=lt(),LF=require("stream"),qF=Ir();_s.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var $F="https://sts.{universeDomain}/v1/oauthtoken",$m=class t extends KE.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};YE.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof XE.GaxiosError&&o.response?(0,KE.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},zm=class extends YE.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new $m({tokenRefreshEndpoint:e.token_url??$F.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=qF.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=XE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,c=s.config.data instanceof LF.Readable;if(!n&&(i===401||i===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};_s.ExternalAccountAuthorizedUserClient=zm});var Gm=J(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.GdchClient=Fr.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var zF=require("crypto"),HF=require("fs"),WF=require("https"),GF=Dr(),JF=3600;Fr.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var Wm=class t extends GF.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||JF,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Fr.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Fr.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(r.agent=await this.getCaAgent());try{let o=await this.transporter.request(r),s=o.data;if(!s.access_token)throw new Error("Token response did not contain an access_token.");if(!s.expires_in)throw new Error("Token response did not contain an expires_in field.");let i={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1e3};return this.emit("tokens",i),{res:o,tokens:i}}catch(o){if(o&&o.config&&o.config.data)try{if(typeof o.config.data=="string"){let s=JSON.parse(o.config.data);s.subject_token&&(s.subject_token="***REDACTED***",o.config.data=JSON.stringify(s))}else typeof o.config.data=="object"&&o.config.data.subject_token&&(o.config.data.subject_token="***REDACTED***")}catch{}throw o instanceof Error&&(o.message=`Error getting access token for GDCH service account: ${o.message}, iss: ${this.serviceIdentityName}`),o}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1e3),o={iss:n,sub:n,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},s=this.base64UrlEncode(JSON.stringify(e)),i=this.base64UrlEncode(JSON.stringify(o)),c=`${s}.${i}`,u=zF.sign("sha256",Buffer.from(c),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),f=this.base64UrlEncode(u);return`${c}.${f}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();!r.includes("googleapis.com")&&!r.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let o=await HF.promises.readFile(r);return new WF.Agent({ca:o})}catch(o){throw this.cachedCaCertPath===r&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),o instanceof Error&&(o.message=`Error reading certificate file from CA cert path, value '${r}': ${o.message}`),o}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Fr.GdchClient=Wm});var tv=J(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.GoogleAuth=sn.GoogleAuthExceptionMessages=void 0;var VF=require("child_process"),Ji=require("fs"),KF=lt(),Vi=Bi(),YF=require("os"),il=require("path"),XF=Ui(),QF=Ph(),ZF=Fh(),eN=Nh(),bs=im(),QE=cm(),Cs=lm(),tN=qm(),Ki=Ir(),Jm=Dt(),ZE=Hm(),Vm=Gm(),ev=nn();sn.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
62
91
  To learn more about authentication and Google APIs, visit:
63
92
  https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
64
93
  To learn more about authentication and Google APIs, visit:
65
94
  https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
66
95
  To learn more about Universe Domain retrieval, visit:
67
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Ep=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.keyFilename&&console.warn("The `keyFilename` option is deprecated. Please use the `credentials` option instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.jsonContent&&console.warn("The `credentials` option is deprecated. Please use the `auth` object constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials."),this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(un.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===un.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(un.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Ai.universe("universe-domain"),e||=Ap.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ap.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,uk.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ap.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof os.JWT?n.scopes=this.scopes:n instanceof Ei.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof os.JWT?n.scopes=this.scopes:n instanceof Ei.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new pO.Compute(e));throw new Error(un.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Ai.getGCPResidency()||await Ai.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=null;if(this._isWindows())n=process.env.APPDATA;else{let o=process.env.HOME;o&&(n=Sp.join(o,".config"))}return n&&(n=Sp.join(n,"gcloud","application_default_credentials.json"),Si.existsSync(n)||(n=null)),n?await this._getApplicationCredentialsFromFilePath(n,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Si.realpathSync(e),!Si.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=Si.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==ss.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ss.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new ss.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){console.warn("The `fromJSON` method is deprecated. Please use the `JWT` constructor instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let r,o=(0,uk.originalOrCamelOptions)(n).get("universe_domain");return e.type===ak.USER_REFRESH_ACCOUNT_TYPE?(r=new ak.UserRefreshClient(n),r.fromJSON(e)):e.type===ss.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ei.EXTERNAL_ACCOUNT_TYPE?(r=yO.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===ck.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new ck.ExternalAccountAuthorizedUserClient({...e,...n}):(n.scopes=this.scopes,r=new os.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){console.warn("The `fromStream` method is deprecated. Please use the `JWT` constructor with a parsed stream instead. For more details, see https://cloud.google.com/docs/authentication/external/externally-sourced-credentials.");let o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",a=>s.push(a)).on("end",()=>{try{try{let a=JSON.parse(s.join("")),c=this._cacheClientFromJSON(a,n);return r(c)}catch(a){if(!this.keyFilename)throw a;let c=new os.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),r(c)}}catch(a){return o(a)}})})}fromAPIKey(e,n={}){return new os.JWT({...n,apiKey:e})}_isWindows(){let e=fO.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,lO.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Ei.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ai.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof ss.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ei.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([Ai.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(un.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{return await this.#e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Sp.resolve(this.keyFilename),n=Si.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new gO.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=dO.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,mO.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof ss.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,hO.createCrypto)();if(r instanceof os.JWT&&r.key)return await s.sign(r.key,e);let a=await this.getCredentials();if(!a.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,a.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};un.GoogleAuth=Ep});var dk=V(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.IAMAuth=void 0;var vp=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};hu.IAMAuth=vp});var fk=V(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.DownscopedClient=Sn.EXPIRATION_TIME_OFFSET=Sn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var _O=ct(),bO=require("stream"),Tp=Dt(),wO=Jc(),CO="urn:ietf:params:oauth:grant-type:token-exchange",kO="urn:ietf:params:oauth:token-type:access_token",SO="urn:ietf:params:oauth:token-type:access_token";Sn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Sn.EXPIRATION_TIME_OFFSET=300*1e3;var Rp=class extends Tp.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Tp.AuthClient?{}:e),e instanceof Tp.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Sn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Sn.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new wO.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=_O.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let a=s.status,c=s.config.data instanceof bO.Readable;if(!n&&(a===401||a===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:CO,requestedTokenType:kO,subjectToken:e,subjectTokenType:SO},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Sn.DownscopedClient=Rp});var hk=V(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.PassThroughClient=void 0;var AO=Dt(),Dp=class extends AO.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};pu.PassThroughClient=Dp});var gu=V(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GoogleAuth=le.auth=le.PassThroughClient=le.ExecutableError=le.PluggableAuthClient=le.DownscopedClient=le.BaseExternalAccountClient=le.ExternalAccountClient=le.IdentityPoolClient=le.AwsRequestSigner=le.AwsClient=le.UserRefreshClient=le.LoginTicket=le.ClientAuthentication=le.OAuth2Client=le.CodeChallengeMethod=le.Impersonated=le.JWT=le.JWTAccess=le.IdTokenClient=le.IAMAuth=le.GCPEnv=le.Compute=le.DEFAULT_UNIVERSE=le.AuthClient=le.gaxios=le.gcpMetadata=void 0;var pk=lk();Object.defineProperty(le,"GoogleAuth",{enumerable:!0,get:function(){return pk.GoogleAuth}});le.gcpMetadata=ui();le.gaxios=ct();var gk=Dt();Object.defineProperty(le,"AuthClient",{enumerable:!0,get:function(){return gk.AuthClient}});Object.defineProperty(le,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return gk.DEFAULT_UNIVERSE}});var EO=yh();Object.defineProperty(le,"Compute",{enumerable:!0,get:function(){return EO.Compute}});var vO=wh();Object.defineProperty(le,"GCPEnv",{enumerable:!0,get:function(){return vO.GCPEnv}});var TO=dk();Object.defineProperty(le,"IAMAuth",{enumerable:!0,get:function(){return TO.IAMAuth}});var RO=bh();Object.defineProperty(le,"IdTokenClient",{enumerable:!0,get:function(){return RO.IdTokenClient}});var DO=jh();Object.defineProperty(le,"JWTAccess",{enumerable:!0,get:function(){return DO.JWTAccess}});var xO=Uh();Object.defineProperty(le,"JWT",{enumerable:!0,get:function(){return xO.JWT}});var OO=zh();Object.defineProperty(le,"Impersonated",{enumerable:!0,get:function(){return OO.Impersonated}});var xp=oo();Object.defineProperty(le,"CodeChallengeMethod",{enumerable:!0,get:function(){return xp.CodeChallengeMethod}});Object.defineProperty(le,"OAuth2Client",{enumerable:!0,get:function(){return xp.OAuth2Client}});Object.defineProperty(le,"ClientAuthentication",{enumerable:!0,get:function(){return xp.ClientAuthentication}});var FO=hh();Object.defineProperty(le,"LoginTicket",{enumerable:!0,get:function(){return FO.LoginTicket}});var PO=qh();Object.defineProperty(le,"UserRefreshClient",{enumerable:!0,get:function(){return PO.UserRefreshClient}});var IO=cp();Object.defineProperty(le,"AwsClient",{enumerable:!0,get:function(){return IO.AwsClient}});var NO=sp();Object.defineProperty(le,"AwsRequestSigner",{enumerable:!0,get:function(){return NO.AwsRequestSigner}});var BO=rp();Object.defineProperty(le,"IdentityPoolClient",{enumerable:!0,get:function(){return BO.IdentityPoolClient}});var jO=wp();Object.defineProperty(le,"ExternalAccountClient",{enumerable:!0,get:function(){return jO.ExternalAccountClient}});var MO=kr();Object.defineProperty(le,"BaseExternalAccountClient",{enumerable:!0,get:function(){return MO.BaseExternalAccountClient}});var UO=fk();Object.defineProperty(le,"DownscopedClient",{enumerable:!0,get:function(){return UO.DownscopedClient}});var mk=_p();Object.defineProperty(le,"PluggableAuthClient",{enumerable:!0,get:function(){return mk.PluggableAuthClient}});Object.defineProperty(le,"ExecutableError",{enumerable:!0,get:function(){return mk.ExecutableError}});var LO=hk();Object.defineProperty(le,"PassThroughClient",{enumerable:!0,get:function(){return LO.PassThroughClient}});var qO=new pk.GoogleAuth;le.auth=qO});var EA=V((s$,xg)=>{"use strict";var eN=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,tN=/(\w*(\.\w*)*)\..*/;xg.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,AA(r.stack)}};function AA(t){let e=t.match(eN);return e?e[1].split(/[/\\]/).slice(-1)[0].match(tN)[1]:"anonymous"}xg.exports.extractPluginName=AA});var TA=V((i$,vA)=>{"use strict";vA.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var RA=V((a$,Fl)=>{"use strict";var nN=EA(),rN=TA(),oN=0;function Og(t,e={}){let n=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(n=!0,e.name=nN(t)+"-auto-"+oN++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let r=rN(e.name);return!n&&!t[r]&&(t[r]=t),t}Fl.exports=Og;Fl.exports.default=Og;Fl.exports.fastifyPlugin=Og});var zi,Fg=fr(()=>{"use strict";zi=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:a}=n||{},c="";if(o){let l=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${l}]${this.colors.reset} `:`[${l}] `}switch(s&&(c+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;case"text":default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return a&&Object.keys(a).length>0&&(c+=`
68
- `+(this.config.colors?`${this.colors.dim}`:""),c+="Metadata: "+JSON.stringify(a,null,2),this.config.colors&&(c+=this.colors.reset)),c}toMarkdown(e,n=0){let r=" ".repeat(n);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${r}-
96
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Km=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(sn.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===sn.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(sn.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Vi.universe("universe-domain"),e||=Jm.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Jm.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,ev.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Jm.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof bs.JWT?n.scopes=this.scopes:n instanceof Ki.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof bs.JWT?n.scopes=this.scopes:n instanceof Ki.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new QF.Compute(e));throw new Error(sn.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Vi.getGCPResidency()||await Vi.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=il.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=il.join(s,".config","gcloud"))}if(!n)return null;let r=il.join(n,"application_default_credentials.json");return Ji.existsSync(r)?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ji.realpathSync(e),!Ji.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=Ji.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Cs.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Cs.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new Cs.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,ev.originalOrCamelOptions)(n).get("universe_domain");return e.type===QE.USER_REFRESH_ACCOUNT_TYPE?(r=new QE.UserRefreshClient(n),r.fromJSON(e)):e.type===Cs.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ki.EXTERNAL_ACCOUNT_TYPE?(r=tN.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===ZE.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new ZE.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Vm.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Vm.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new bs.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){let o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",i=>s.push(i)).on("end",()=>{try{try{let i=JSON.parse(s.join("")),c=this._cacheClientFromJSON(i,n);return r(c)}catch(i){if(!this.keyFilename)throw i;let c=new bs.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=c,this.setGapicJWTValues(c),r(c)}}catch(i){return o(i)}})})}fromAPIKey(e,n={}){return new bs.JWT({...n,apiKey:e})}_isWindows(){let e=YF.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,VF.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Ki.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Vi.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Cs.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ki.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([Vi.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(sn.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Vm.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),i=e.createWithGdchAudience(s);return this.cachedCredential=i,i}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=il.resolve(this.keyFilename),n=Ji.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new ZF.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=KF.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,eN.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof Cs.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,XF.createCrypto)();if(r instanceof bs.JWT&&r.key)return await s.sign(r.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,i.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};sn.GoogleAuth=Km});var nv=J(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.IAMAuth=void 0;var Ym=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};al.IAMAuth=Ym});var rv=J(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.DownscopedClient=An.EXPIRATION_TIME_OFFSET=An.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var nN=lt(),rN=require("stream"),Xm=Dt(),oN=Lu(),sN="urn:ietf:params:oauth:grant-type:token-exchange",iN="urn:ietf:params:oauth:token-type:access_token",aN="urn:ietf:params:oauth:token-type:access_token";An.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;An.EXPIRATION_TIME_OFFSET=300*1e3;var Qm=class extends Xm.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Xm.AuthClient?{}:e),e instanceof Xm.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>An.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${An.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new oN.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=nN.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,c=s.config.data instanceof rN.Readable;if(!n&&(i===401||i===403)&&!c&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:sN,requestedTokenType:iN,subjectToken:e,subjectTokenType:aN},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};An.DownscopedClient=Qm});var ov=J(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.PassThroughClient=void 0;var cN=Dt(),Zm=class extends cN.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};cl.PassThroughClient=Zm});var ul=J(ne=>{"use strict";var uN=ne&&ne.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lN=ne&&ne.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&uN(e,t,n)};Object.defineProperty(ne,"__esModule",{value:!0});ne.GoogleAuth=ne.auth=ne.GDCH_SERVICE_ACCOUNT_TYPE=ne.GdchClient=ne.PassThroughClient=ne.ExternalAccountAuthorizedUserClient=ne.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=ne.ExecutableError=ne.PluggableAuthClient=ne.DownscopedClient=ne.BaseExternalAccountClient=ne.ExternalAccountClient=ne.IdentityPoolClient=ne.AwsRequestSigner=ne.AwsClient=ne.UserRefreshClient=ne.LoginTicket=ne.ClientAuthentication=ne.OAuth2Client=ne.CodeChallengeMethod=ne.Impersonated=ne.JWT=ne.JWTAccess=ne.IdTokenClient=ne.IAMAuth=ne.GCPEnv=ne.Compute=ne.DEFAULT_UNIVERSE=ne.AuthClient=ne.gaxios=ne.gcpMetadata=void 0;var sv=tv();Object.defineProperty(ne,"GoogleAuth",{enumerable:!0,get:function(){return sv.GoogleAuth}});ne.gcpMetadata=Bi();ne.gaxios=lt();var iv=Dt();Object.defineProperty(ne,"AuthClient",{enumerable:!0,get:function(){return iv.AuthClient}});Object.defineProperty(ne,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return iv.DEFAULT_UNIVERSE}});var dN=Ph();Object.defineProperty(ne,"Compute",{enumerable:!0,get:function(){return dN.Compute}});var fN=Nh();Object.defineProperty(ne,"GCPEnv",{enumerable:!0,get:function(){return fN.GCPEnv}});var pN=nv();Object.defineProperty(ne,"IAMAuth",{enumerable:!0,get:function(){return pN.IAMAuth}});var hN=Fh();Object.defineProperty(ne,"IdTokenClient",{enumerable:!0,get:function(){return hN.IdTokenClient}});var mN=om();Object.defineProperty(ne,"JWTAccess",{enumerable:!0,get:function(){return mN.JWTAccess}});var gN=im();Object.defineProperty(ne,"JWT",{enumerable:!0,get:function(){return gN.JWT}});var yN=lm();Object.defineProperty(ne,"Impersonated",{enumerable:!0,get:function(){return yN.Impersonated}});var eg=Dr();Object.defineProperty(ne,"CodeChallengeMethod",{enumerable:!0,get:function(){return eg.CodeChallengeMethod}});Object.defineProperty(ne,"OAuth2Client",{enumerable:!0,get:function(){return eg.OAuth2Client}});Object.defineProperty(ne,"ClientAuthentication",{enumerable:!0,get:function(){return eg.ClientAuthentication}});var _N=Rh();Object.defineProperty(ne,"LoginTicket",{enumerable:!0,get:function(){return _N.LoginTicket}});var bN=cm();Object.defineProperty(ne,"UserRefreshClient",{enumerable:!0,get:function(){return bN.UserRefreshClient}});var CN=xm();Object.defineProperty(ne,"AwsClient",{enumerable:!0,get:function(){return CN.AwsClient}});var wN=Am();Object.defineProperty(ne,"AwsRequestSigner",{enumerable:!0,get:function(){return wN.AwsRequestSigner}});var kN=Em();Object.defineProperty(ne,"IdentityPoolClient",{enumerable:!0,get:function(){return kN.IdentityPoolClient}});var SN=qm();Object.defineProperty(ne,"ExternalAccountClient",{enumerable:!0,get:function(){return SN.ExternalAccountClient}});var EN=Ir();Object.defineProperty(ne,"BaseExternalAccountClient",{enumerable:!0,get:function(){return EN.BaseExternalAccountClient}});var vN=rv();Object.defineProperty(ne,"DownscopedClient",{enumerable:!0,get:function(){return vN.DownscopedClient}});var av=jm();Object.defineProperty(ne,"PluggableAuthClient",{enumerable:!0,get:function(){return av.PluggableAuthClient}});Object.defineProperty(ne,"ExecutableError",{enumerable:!0,get:function(){return av.ExecutableError}});var cv=Hm();Object.defineProperty(ne,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return cv.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(ne,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return cv.ExternalAccountAuthorizedUserClient}});var AN=ov();Object.defineProperty(ne,"PassThroughClient",{enumerable:!0,get:function(){return AN.PassThroughClient}});var uv=Gm();Object.defineProperty(ne,"GdchClient",{enumerable:!0,get:function(){return uv.GdchClient}});Object.defineProperty(ne,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return uv.GDCH_SERVICE_ACCOUNT_TYPE}});lN(nm(),ne);var TN=new sv.GoogleAuth;ne.auth=TN});var $T=J((tW,wy)=>{"use strict";var AL=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,TL=/(\w*(\.\w*)*)\..*/;wy.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,qT(r.stack)}};function qT(t){let e=t.match(AL);return e?e[1].split(/[/\\]/).slice(-1)[0].match(TL)[1]:"anonymous"}wy.exports.extractPluginName=qT});var HT=J((nW,zT)=>{"use strict";zT.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var WT=J((rW,Sd)=>{"use strict";var RL=$T(),xL=HT(),DL=0;function ky(t,e={}){let n=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(n=!0,e.name=RL(t)+"-auto-"+DL++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let r=xL(e.name);return!n&&!t[r]&&(t[r]=t),t}Sd.exports=ky;Sd.exports.default=ky;Sd.exports.fastifyPlugin=ky});var da,Sy=_r(()=>{"use strict";da=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:i}=n||{},c="";if(o){let u=new Date().toISOString();c+=this.config.colors?`${this.colors.cyan}[${u}]${this.colors.reset} `:`[${u}] `}switch(s&&(c+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":c+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?c+=this.toMarkdown(e):c+=String(e);break;default:typeof e=="object"?c+=JSON.stringify(e,null,2):c+=String(e);break}return i&&Object.keys(i).length>0&&(c+=`
97
+ `+(this.config.colors?`${this.colors.dim}`:""),c+="Metadata: "+JSON.stringify(i,null,2),this.config.colors&&(c+=this.colors.reset)),c}toMarkdown(e,n=0){let r=" ".repeat(n);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${r}-
69
98
  ${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
70
99
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${r}${o}:
71
100
  ${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
72
- `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;case"log":default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var Hi,Pg=fr(()=>{"use strict";Hi=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{format:r="json",timestamp:o=!0,prefix:s,metadata:a}=n||{},c={data:e};return o&&(c.timestamp=new Date().toISOString()),s&&(c.prefix=s),a&&Object.keys(a).length>0&&(c.metadata=a),c}async sendRequest(e,n,r,o,s){let a=new AbortController,c=setTimeout(()=>a.abort(),s);try{let l=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:a.signal});if(clearTimeout(c),!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);return l}catch(l){throw clearTimeout(c),l}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,a){let c=null;for(let l=1;l<=a.maxAttempts;l++)try{return await this.sendRequest(e,n,r,o,s)}catch(f){if(c=f,l===a.maxAttempts)break;let d=a.backoffMs*Math.pow(2,l-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${l}/${a.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw c}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n),a=await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry);return!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`)}}}});var ms,Ig,DA,Wi,Ng=fr(()=>{"use strict";ms=require("fs"),Ig=require("path"),DA=require("os"),Wi=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,DA.tmpdir)();this.baseDir=(0,Ig.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,ms.existsSync)(this.baseDir)||(0,ms.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return(0,Ig.join)(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return(0,ms.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Bg,ys,xA=fr(()=>{"use strict";Fg();Pg();Ng();Bg=class{handlers=new Map;defaultOptions={};logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){(this.logger?.error??console.error)(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){let n;switch(e.type){case"console":n=new zi(e.config);break;case"webhook":n=new Hi(e.config);break;case"temp-file":n=new Wi(e.config);break;default:throw new Error(`Unknown output handler type: ${e.type}`)}return this.logger&&typeof n.setLogger=="function"&&n.setLogger(this.logger),n}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([a,c])=>{try{await c.output(e,r)?o.success.push(a):o.failed.push(a)}catch(l){(this.logger?.error??console.error)(`[OutputManager] Handler ${a} failed:`,l),o.failed.push(a)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},a=e.map(async c=>{let l=this.handlers.get(c);if(!l){(this.logger?.warn??console.warn)(`[OutputManager] Handler ${c} not found`),s.failed.push(c);return}try{await l.output(n,o)?s.success.push(c):s.failed.push(c)}catch(f){(this.logger?.error??console.error)(`[OutputManager] Handler ${c} failed:`,f),s.failed.push(c)}});return await Promise.all(a),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,a])=>a.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},ys=new Bg});var aN={};Bd(aN,{ANTIGRAVITY_CLIENT_ID:()=>ml,ANTIGRAVITY_CLIENT_SECRET:()=>yl,ANTIGRAVITY_REDIRECT_URI:()=>wg,ANTIGRAVITY_SCOPES:()=>IS,ConfigService:()=>Mr,ProviderService:()=>$r,SSEParserTransform:()=>Un,SSESerializerTransform:()=>zr,TokenizerService:()=>co,TransformerService:()=>ao,calculateTokenCount:()=>vg,default:()=>iN,diffHeadersForLog:()=>Yy,exchangeAuthorizationCode:()=>KS,fetchUserEmail:()=>VS,getGlobalTokenSpeedStats:()=>Ug,getTokenSpeedStats:()=>Mg,getValidAccessToken:()=>Ii,isClientAbortError:()=>tt,loadTokens:()=>Fi,pluginManager:()=>Dg,resolveProjectId:()=>bl,rewriteStream:()=>tf,router:()=>Ol,sanitizeHeadersForLog:()=>Ea,saveTokens:()=>_l,searchProjectBySession:()=>Tg,sessionUsageCache:()=>Tl,tokenSpeedPlugin:()=>Lg});module.exports=zA(aN);var PA=st(require("fastify"),1),IA=st(require("@fastify/cors"),1);var Hs=require("fs"),Gd=require("path"),Vy=require("dotenv"),Ky=st(Wd(),1),Mr=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,Gd.join)(process.cwd(),this.options.jsonPath);if((0,Hs.existsSync)(e))try{let n=(0,Hs.readFileSync)(e,"utf-8"),r=Ky.default.parse(n);this.config={...this.config,...r},(this.logger?.info??console.log)(`Loaded JSON config from: ${e}`)}catch(n){(this.logger?.warn??console.warn)(`Failed to load JSON config from ${e}:`,n)}else(this.logger?.warn??console.warn)(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Gd.join)(process.cwd(),this.options.envPath);if((0,Hs.existsSync)(e))try{let n=(0,Vy.config)({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){(this.logger?.warn??console.warn)(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};var QA="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function _t(t){return t.replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi,"[redacted-url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${QA})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"').replace(/\b(?:authorization|x-api-key|api-key|api_key|access_token|token)\s*[:=]\s*["']?[^\s,;"']+/gi,e=>`${e.split(/\s*[:=]/,1)[0]}=[redacted]`).replace(/\[[0-9a-f:]+\](?::\d+)?/gi,"[redacted-address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[redacted-address]").replace(/\b(connect(?:ing)?(?:\s+to)?|from|to)\s+(?:localhost|(?:[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.)+[a-z]{2,63})(?::\d+)?\b/gi,"$1 [redacted-address]").replace(/([?&](?:api_?key|key|token|access_token|auth)=)[^&\s]+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,240)}function ZA(t,e){return t.split(`
73
- `).map(n=>_t(n)).filter(Boolean).join(`
74
- `).slice(0,e)}function Ur(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:_t(n)||"Unknown error",code:typeof e?.code=="string"?e.code:void 0,name:typeof e?.name=="string"?e.name:void 0,statusCode:typeof e?.statusCode=="number"?e.statusCode:void 0,stack:typeof e?.stack=="string"?ZA(e.stack,4e3):void 0,cause:r?_t(r):void 0}}var eE=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function tE(t){return eE.test(t)}function nE(t){if(t==null)return;if(Array.isArray(t)){let n=t.filter(r=>r!=null&&String(r).length>0).map(r=>String(r));return n.length?n.join(", "):void 0}let e=String(t);return e.length?e:void 0}function Ea(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=nE(o);if(s!=null){if(tE(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function Yy(t,e){let n=Ea(t),r=Ea(e),o=new Map(Object.entries(n).map(([d,h])=>[d.toLowerCase(),{key:d,value:h}])),s=new Map(Object.entries(r).map(([d,h])=>[d.toLowerCase(),{key:d,value:h}])),a={},c={},l={},f=0;for(let[d,{key:h,value:m}]of o){let S=s.get(d);if(!S){a[h]=m;continue}S.value===m?f+=1:l[h]={from:m,to:S.value}}for(let[d,{key:h,value:m}]of s)o.has(d)||(c[h]=m);return{onlyInLeft:a,onlyInRight:c,changed:l,sameCount:f}}var bt="client disconnected";function Vd(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"})):new Promise((n,r)=>{let o=setTimeout(()=>{e&&e.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),r(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"}))};e&&e.addEventListener("abort",s,{once:!0})})}function Qy(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(c=bt)=>{n.signal.aborted||n.abort(c)},a=()=>{if(!o&&(o=!0,!!r)){if(Jd(r)){s(`${bt} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&Jd(r)&&s(`${bt} (response close)`)}),r.on("error",c=>{(c?.code==="EPIPE"||c?.code==="ECONNRESET"||c?.code==="ERR_STREAM_PREMATURE_CLOSE"||tt(c))&&s(`${bt} (response error)`)})}};return{signal:n.signal,arm:a}}function rE(t){let e=t?.trim();if(!e)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(n*1e3,6e4);let r=Date.parse(e);if(Number.isFinite(r))return Math.min(Math.max(0,r-Date.now()),6e4)}function oE(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function Kd(t,e){let n=rE(e);return n!==void 0&&n>0?n:oE(t)}function Zy(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var Xy=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CONNECT"]);function e_(t){let e=t;if(!e)return!1;if(e.name==="TimeoutError"||e.code==="TIMEOUT_ERR"||e.code===23||e.cause&&(e.cause.name==="TimeoutError"||e.cause.code==="TIMEOUT_ERR"||e.cause.code===23))return!0;let n=String(e.message||"");return/aborted due to timeout|operation was aborted due to timeout/i.test(n)}function pr(t=bt){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:bt;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function tt(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(bt)||/client.*(closed|disconnect)|socket hang up/i.test(t);let e=t;if(e_(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(bt)||typeof e.message=="string"&&e.message.startsWith(bt)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return/client.*(closed|disconnect)|socket hang up/i.test(r)}function Jd(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function t_(t){return Jd(t.raw)}function Ws(t){if(!t||tt(t))return!1;if(e_(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&Xy.has(e.code)||e.cause?.code&&Xy.has(String(e.cause.code)))return!0;let n=String(e.message||"");return/fetch failed|network|socket|ECONNRESET|ENOTFOUND|ETIMEDOUT|other side closed/i.test(n)}function n_(t){let e=t;return!e||tt(e)?!1:e.code==="provider_response_error"||e.code==="provider_network_error"||Ws(e)}function $e(t,e=500,n="internal_error",r="api_error",o){let s=new Error(_t(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function r_(t,e,n){if(tt(t)||n.raw.destroyed||n.sent)return e.log.debug(Ur(t),"request aborted or already closed"),!n.sent&&!n.raw.destroyed&&!n.raw.headersSent?(n.type("application/json"),n.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):void 0;e.log.error(Ur(t),"request error");let r=t.statusCode||500,o={error:{message:_t(t.message||"Internal error")||"Internal error",type:t.type||"api_error",code:t.code||"internal_error"}};return t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(o)}var f_=require("stream");var s_=require("undici");function sE(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function iE(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function o_(t){let e=t.split(".");if(e.length!==4)return null;let n=0;for(let r of e){let o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>255)return null;n=n<<8|o}return n>>>0}function aE(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=o_(t),a=o_(n);if(s===null||a===null)return!1;let c=o===0?0:-1<<32-o>>>0;return(s&c)===(a&c)}function cE(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=sE(e.hostname);if(n==="localhost"||n==="127.0.0.1"||n.startsWith("127.")||n==="0.0.0.0"||n==="::1"||n==="0:0:0:0:0:0:0:1")return!0;let r=process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;let o=r.split(",").map(s=>s.trim()).filter(Boolean);for(let s of o){let a=s.toLowerCase();if(a==="*")return!0;let c=uE(a);if(c.startsWith(".")){if(n.endsWith(c)||n===c.slice(1))return!0;continue}if(c.includes("/")&&iE(n)){if(aE(n,c))return!0;continue}if(n===c)return!0;if(c.startsWith("*.")){let l=c.slice(1);if(n.endsWith(l)||n===l.slice(1))return!0}}return!1}function uE(t){if(t.startsWith("[")&&t.includes("]"))return t.slice(1,t.indexOf("]"));if(t.split(":").length-1===1){let[n,r]=t.split(":");if(/^\d+$/.test(r))return n}return t}async function Eo(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([h,m])=>{m&&s.set(h,m)});let a=AbortSignal.timeout(n.TIMEOUT??60*1e3*60),c=n.signal?AbortSignal.any([n.signal,a]):a,l={method:"POST",headers:s,body:JSON.stringify(e),signal:c},f=typeof t=="string"?t:t.toString();!!n.httpsProxy&&!cE(f)&&(l.dispatcher=new s_.ProxyAgent(new URL(n.httpsProxy).toString()));try{return await fetch(f,l)}catch(h){if(tt(h))throw typeof h=="string"?pr(h):h;if(n.signal?.aborted&&tt(n.signal.reason??bt))throw pr(n.signal.reason??h);if(Ws(h)){let m=$e(h?.message||"Provider network error",502,"provider_network_error");throw m.cause=h,m}throw h}}var i_="1.0.57";var c_=require("crypto"),Yd={type:"ephemeral"};function Je(t){return t.map(e=>{let n={...e};return Array.isArray(n.content)&&(n.content=n.content.map(r=>{if(r.cache_control){let{cache_control:o,...s}=r;return s}return r})),n.cache_control&&delete n.cache_control,Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{let{cache_control:o,...s}=r;return s})),n})}function Ve(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function a_(t){return`ccr_${(0,c_.createHash)("sha256").update(t).digest("hex").slice(0,48)}`}function dE(t){if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}return t}function fE(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
75
- `):""}function Qt(t,e){let n=t?.req?.sessionId||dE(e?.metadata?.user_id);if(typeof n=="string"&&n)return a_(n);let r=(e.messages||[]).find(a=>a.role==="system"||a.role==="user"),o=r?fE(r.content):"",s=[e.model||"",o].join(`
76
- `);return s.trim()?a_(s):void 0}function Lr(t,e={}){let n=e.maxBreakpoints??4,r=JSON.parse(JSON.stringify(t)),o=[],s=f=>{f&&typeof f=="object"&&f.cache_control&&o.push(f)};(Array.isArray(r.tools)?r.tools:[]).forEach(s),Array.isArray(r.system)?r.system.forEach(s):s(r.system),(Array.isArray(r.messages)?r.messages:[]).forEach(f=>{s(f),Array.isArray(f?.content)&&f.content.forEach(s)});let a=!!r.cache_control,c=Math.max(0,n-(a?1:0));if(o.length>c)for(let f of o.slice(0,o.length-c))delete f.cache_control;let l=Math.min(o.length,c);if(!a&&l<n){let f=o[o.length-1]?.cache_control;r.cache_control=f?.ttl?{type:"ephemeral",ttl:f.ttl}:Yd}return r}function qr(t){let e=Je(t.messages||[]),n=Ve(t.tools);for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o.content=="string"&&o.content){o.content=[{type:"text",text:o.content,cache_control:Yd}];break}if(Array.isArray(o.content))for(let s=o.content.length-1;s>=0;s-=1){let a=o.content[s];if(a?.type==="text"&&a.text)return o.content[s]={...a,cache_control:Yd},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function va(t){let e=[];for(let n=0;n<t.length;n++){let r={...t[n]};if(r.role==="assistant"&&r.tool_calls){let o=[],s=[],a=[],c=n+1;for(;c<t.length&&t[c].role==="tool";)a.push(t[c]),c++;r.tool_calls.forEach(l=>{a.some(d=>d.tool_call_id===l.id)?o.push(l):s.push(l.id)}),o.length>0?r.tool_calls=o:delete r.tool_calls,(r.content||r.tool_calls)&&e.push(r)}else if(r.role==="tool"){let o=!1;if(n>0){let s=t[n-1];if(s.role==="assistant"&&s.tool_calls)o=s.tool_calls.some(a=>a.id===r.tool_call_id);else if(s.role==="tool"){for(let a=n-1;a>=0;a--)if(t[a].role!=="tool"){t[a].role==="assistant"&&t[a].tool_calls&&(o=t[a].tool_calls.some(c=>c.id===r.tool_call_id));break}}}o&&e.push(r)}else e.push(r)}return e}function u_(t){let n=(t||"").toLowerCase().match(/(?:^|\/)gpt-(\d+)(?:\.(\d+))?/);if(!n)return!1;let r=Number(n[1]),o=Number(n[2]||0);return r>5||r===5&&o>=6}function l_(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function hE(t){for(let e=t.length-1;e>=0;e-=1)if(l_(t[e]))return e;return-1}function Gs(t,e,n){let r={...t,messages:(t.messages||[]).map(s=>({...s,content:Array.isArray(s.content)?s.content.map(a=>({...a})):s.content})),tools:Array.isArray(t.tools)?t.tools.map(s=>({...s,function:{...s.function,parameters:{...s.function.parameters}}})):t.tools},o=Qt(n,t);if(o&&(r.prompt_cache_key=o),u_(r.model)){let s=[];r.messages.forEach((a,c)=>{if(a.cache_control){if(typeof a.content=="string"&&a.content)s.push({messageIndex:c});else if(Array.isArray(a.content)){let l=hE(a.content);l>=0&&s.push({messageIndex:c,contentIndex:l})}}Array.isArray(a.content)&&a.content.forEach((l,f)=>{l?.cache_control&&l_(l)&&s.push({messageIndex:c,contentIndex:f})})});for(let a of s.slice(-3)){let c=r.messages[a.messageIndex];typeof c.content=="string"?c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}]:Array.isArray(c.content)&&a.contentIndex!==void 0&&(c.content[a.contentIndex].prompt_cache_breakpoint={mode:"explicit"})}}return r.messages=Je(r.messages),r.tools=Ve(r.tools),r}function Ta(t,e){return u_(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function pE(t){return String(t?.name||"").trim().toLowerCase()}function gE(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function Xd(t,e){let n={...t,messages:Je(t.messages||[]),tools:Ve(t.tools)},r=Qt(e,t);return r&&(n.prompt_cache_key=r),n}function Ra(t,e,n){let r=pE(e),o=gE(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?Gs(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?qr(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?Xd(t,n):{...t,messages:Je(t.messages||[]),tools:Ve(t.tools)}}async function d_(t,e,n){let r=await t(e);if(r.status!==401||typeof n!="function")return r;let o=await n();if(!o)return r;try{await r.body?.cancel()}catch{}return Object.assign(e,o),t(e)}async function mE(t,e,n,r){let o=t.body,s=t.provider,a=n.providerService.getProvider(s),c=Qy(t,e),l=c.signal;if(c.arm(),!a)throw $e(`Provider '${s}' not found`,404,"provider_not_found");try{let{requestBody:f,config:d,bypass:h}=await h_(o,a,r,t.headers,{req:t,provider:a,signal:l}),m=await p_(f,d,a,n,h,r,{req:t,signal:l}),S=await g_(f,m,a,r,h,{req:t,signal:l});return await m_(S,e,o,l)}catch(f){if(tt(f))throw typeof f=="string"?pr(f):f;if(l.aborted)throw pr(l.reason??f);if(n_(f)){let d=await yE(t,e,n,r,f,l);if(d)return d;if(l.aborted)throw pr(l.reason??bt)}throw f}}async function yE(t,e,n,r,o,s){let a=t.scenarioType||"default",c=n.configService.get("fallback"),l=Zy(c,a);if(!l?.length||s?.aborted||tt(o))return null;t.log.warn({scenarioType:a,fallbackCount:l.length,error:Ur(o)},`Request failed for ${a}, trying ${l.length} fallback models`);let f=0,d=Kd(f,o?.headers?.["Retry-After"]??o?.headers?.["retry-after"]);if(f+=1,d>0){t.log.info(`Waiting ${d}ms before first fallback attempt`);try{await Vd(d,s)}catch(h){if(tt(h)||s?.aborted)return null;throw h}}for(let h=0;h<l.length;h+=1){if(s?.aborted)return null;let m=l[h];try{t.log.info(`Trying fallback model: ${m}`);let S={...t.body},[y,...w]=m.split(",");S.model=w.join(",");let b={...t,provider:y,body:S},_=n.providerService.getProvider(y);if(!_){t.log.warn(`Fallback provider '${y}' not found, skipping`);continue}let{requestBody:D,config:k,bypass:v}=await h_(S,_,r,t.headers,{req:b,provider:_,signal:s}),x=await p_(D,k,_,n,v,r,{req:b,signal:s}),R=await g_(D,x,_,r,v,{req:b,signal:s});return t.log.info(`Fallback model ${m} succeeded`),await m_(R,e,S,s)}catch(S){if(tt(S))throw S;if(s?.aborted)throw pr(s.reason??bt);if(t.log.warn({fallbackModel:m,error:Ur(S)},`Fallback model ${m} failed`),h<l.length-1){let w=Kd(f,S?.headers?.["Retry-After"]??S?.headers?.["retry-after"]);if(f+=1,w>0){t.log.info(`Waiting ${w}ms before next fallback attempt`);try{await Vd(w,s)}catch(b){if(tt(b)||s?.aborted)return null;throw b}}}continue}}return t.log.error(`All fallback models failed for ${a}`),null}async function h_(t,e,n,r,o){let s=t,a={},c=!1;c=_E(e,n,t);let l=c||e.transformer?.passthrough;if(c&&(r instanceof Headers?r.delete("content-length"):delete r["content-length"],a.headers=r),!l&&typeof n.transformRequestOut=="function"){let f=await n.transformRequestOut(s,o);f.body?(s=f.body,a=f.config||{}):s=f}if(!c&&e.transformer?.use?.length)for(let f of e.transformer.use){if(!f||typeof f.transformRequestIn!="function")continue;let d=await f.transformRequestIn(s,e,o);d.body?(s=d.body,a={...a,...d.config}):s=d}if(!c&&e.transformer?.[t.model]?.use?.length)for(let f of e.transformer[t.model].use){if(!f||typeof f.transformRequestIn!="function")continue;let d=await f.transformRequestIn(s,e,o);d.body?(s=d.body,a={...a,...d.config}):s=d}return!c&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=Ra(s,e,o)),{requestBody:s,config:a,bypass:c}}function _E(t,e,n){return t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[n.model]?.use.length||t.transformer?.[n.model]?.use.length===1&&t.transformer?.[n.model]?.use[0].name===e.name)}async function p_(t,e,n,r,o,s,a){if(e?.__providerResponse)return e.__providerResponse;let c=e.url||new URL(n.baseUrl);if((o||n.transformer?.passthrough)&&typeof s.auth=="function"){let S=await s.auth(t,n,a);if(S.body){t=S.body;let y=e.headers||{};S.config?.headers&&(y={...y,...S.config.headers},delete y.host,delete S.config.headers),e={...e,...S.config,headers:y}}else t=S}let l={Authorization:`Bearer ${n.apiKey}`,...e?.headers||{}};l["x-api-key"]&&delete l.Authorization;for(let S in l)(l[S]==="undefined"||["authorization","Authorization"].includes(S)&&l[S]?.includes("undefined"))&&delete l[S];let{__authRecovery:f,...d}=e||{},m=await d_(S=>Eo(c,t,{httpsProxy:r.configService.getHttpsProxy(),...d,headers:JSON.parse(JSON.stringify(S)),signal:a?.signal??d.signal},a,r.log),l,f);if(!m.ok){let S=await m.text(),y=_t(S)||S.slice(0,240),w,b=m.headers.get("retry-after");if(b)w={"Retry-After":b};else if(m.status===429)try{let _=JSON.parse(S),D=_?.error?.details||_?.details;if(Array.isArray(D)){let k=D.find(v=>v["@type"]==="type.googleapis.com/google.rpc.RetryInfo");if(k?.retryDelay){let v=parseInt(k.retryDelay,10);isNaN(v)||(w={"Retry-After":v.toString()})}}}catch{}try{let _=JSON.parse(S),D=_t(String(_?.error?.message||S))||y;r.log.error({status:m.status,provider:n.name,model:t.model,errorMessage:D},`[provider_response_error] ${n.name},${t.model}: ${D}`)}catch{r.log.error({status:m.status,provider:n.name,model:t.model,errorText:y},`[provider_response_error] ${n.name},${t.model}: ${y}`)}throw $e(`Error from provider(${n.name},${t.model}: ${m.status}): ${y}`,m.status,"provider_response_error","api_error",w)}return m}async function g_(t,e,n,r,o,s){let a=e,c=o||n.transformer?.passthrough,l={...s,provider:n};if(!o&&n.transformer?.use?.length)for(let f of Array.from(n.transformer.use).reverse())!f||typeof f.transformResponseOut!="function"||(a=await f.transformResponseOut(a,l));if(!o&&n.transformer?.[t.model]?.use?.length)for(let f of Array.from(n.transformer[t.model].use).reverse())!f||typeof f.transformResponseOut!="function"||(a=await f.transformResponseOut(a,l));return!c&&r.transformResponseIn&&(a=await r.transformResponseIn(a,s)),a}async function m_(t,e,n,r){if(t.ok||e.code(t.status),n.stream===!0&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let s=f_.Readable.fromWeb(t.body),a=!1,c=()=>{if(!a){a=!0;try{s.destroyed||s.destroy()}catch{}}},l=()=>{r&&r.removeEventListener("abort",c)};return t_(e)?(c(),!e.sent&&!e.raw.destroyed?(e.type("application/json"),e.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):e):(r?.aborted&&e.log?.warn?.({reason:String(r.reason??""),headersSent:e.raw.headersSent,writableEnded:e.raw.writableEnded},"disconnect signal fired but socket still open; continuing SSE"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&r.addEventListener("abort",c,{once:!0}),e.raw.on("error",d=>{(d?.code==="EPIPE"||d?.code==="ECONNRESET"||d?.code==="ERR_STREAM_PREMATURE_CLOSE"||tt(d))&&c()}),e.raw.on("close",()=>{e.raw.writableEnded||c()}),s.on("error",d=>{d?.code==="ERR_STREAM_PREMATURE_CLOSE"||d?.code==="ABORT_ERR"||tt(d)||e.log?.error?.(Ur(d),"upstream stream error")}),s.once("end",l),s.once("close",l),e.send(s))}if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),t.body&&typeof t.body.pipe=="function")return e.send(t.body);throw $e("Streaming response body is not a readable stream",502,"provider_response_error")}else{let s=await t.json();return e.send(s)}}var Qd=async t=>{t.get("/",async()=>({message:"LLMs API",version:i_})),t.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=t.transformerService.getTransformersWithEndpoint();for(let{transformer:n}of e)n.endPoint&&t.post(n.endPoint,async(r,o)=>mE(r,o,t,n));t.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(n,r)=>{let{name:o,baseUrl:s,apiKey:a,models:c}=n.body;if(!o?.trim())throw $e("Provider name is required",400,"invalid_request");if(!s||!bE(s))throw $e("Valid base URL is required",400,"invalid_request");if(!a?.trim())throw $e("API key is required",400,"invalid_request");if(!c||!Array.isArray(c)||c.length===0)throw $e("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(n.body.name))throw $e(`Provider with name '${n.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(n.body)}),t.get("/providers",async()=>t.providerService.getProviders()),t.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{let r=t.providerService.getProvider(n.params.id);if(!r)throw $e("Provider not found",404,"provider_not_found");return r}),t.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(n,r)=>{let o=t.providerService.updateProvider(n.params.id,n.body);if(!o)throw $e("Provider not found",404,"provider_not_found");return o}),t.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async n=>{if(!t.providerService.deleteProvider(n.params.id))throw $e("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(n,r)=>{if(!t.providerService.toggleProvider(n.params.id,n.body.enabled))throw $e("Provider not found",404,"provider_not_found");return{message:`Provider ${n.body.enabled?"enabled":"disabled"} successfully`}})};function bE(t){try{return new URL(t),!0}catch{return!1}}var $r=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return this.attachTransformerLogger(new a(s[1]))}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?this.attachTransformerLogger(new a):this.attachTransformerLogger(a)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let a=this.transformerService.getTransformer(s[0]);if(a)return this.attachTransformerLogger(new a(s[1]))}if(typeof s=="string"){let a=this.transformerService.getTransformer(s);return typeof a=="function"?this.attachTransformerLogger(new a):this.attachTransformerLogger(a)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let a=`${r.name},${s}`;this.modelRoutes.delete(a),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let a=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:a};this.modelRoutes.set(a,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var it=[];for(let t=0;t<256;++t)it.push((t+256).toString(16).slice(1));function y_(t,e=0){return(it[t[e+0]]+it[t[e+1]]+it[t[e+2]]+it[t[e+3]]+"-"+it[t[e+4]]+it[t[e+5]]+"-"+it[t[e+6]]+it[t[e+7]]+"-"+it[t[e+8]]+it[t[e+9]]+"-"+it[t[e+10]]+it[t[e+11]]+it[t[e+12]]+it[t[e+13]]+it[t[e+14]]+it[t[e+15]]).toLowerCase()}var __=require("crypto"),xa=new Uint8Array(256),Da=xa.length;function Zd(){return Da>xa.length-16&&((0,__.randomFillSync)(xa),Da=0),xa.slice(Da,Da+=16)}var b_=require("crypto"),ef={randomUUID:b_.randomUUID};function wE(t,e,n){if(ef.randomUUID&&!e&&!t)return ef.randomUUID();t=t||{};let r=t.random??t.rng?.()??Zd();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return y_(r)}var dn=wE;var w_=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);function Oa(t){let e=t?.prompt_tokens_details?.cached_tokens||0,n=t?.prompt_tokens_details?.cache_write_tokens||0;return{input_tokens:Math.max(0,(t?.prompt_tokens||0)-e-n),output_tokens:t?.completion_tokens||0,cache_creation_input_tokens:n,cache_read_input_tokens:e}}var vo=class{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n,r){let o={};return this.useBearer?(o.authorization=`Bearer ${n.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=n.apiKey,o.authorization=void 0),{body:Lr(e),config:{headers:o}}}async transformRequestOut(e,n){let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let c=e.system.filter(l=>l.type==="text"&&l.text).map(l=>({type:"text",text:l.text,cache_control:l.cache_control}));r.push({role:"system",content:c})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(c=>{if(c.role==="user"||c.role==="assistant"){if(typeof c.content=="string"){r.push({role:c.role,content:c.content});return}if(Array.isArray(c.content)){if(c.role==="user"){let l=c.content.filter(d=>d.type==="tool_result"&&d.tool_use_id);l.length&&l.forEach(d=>{let h={role:"tool",content:typeof d.content=="string"?d.content:Array.isArray(d.content)&&d.content.filter(m=>m.type==="text"&&m.text).map(m=>m.text).join(`
77
- `)||JSON.stringify(d.content),tool_call_id:d.tool_use_id,cache_control:d.cache_control};r.push(h)});let f=c.content.filter(d=>d.type==="text"&&d.text||d.type==="image"&&d.source);f.length&&r.push({role:"user",content:f.map(d=>d?.type==="image"?{type:"image_url",image_url:{url:d.source?.type==="base64"?w_(d.source.data,d.source.media_type):d.source.url},media_type:d.source.media_type,cache_control:d.cache_control}:d)})}else if(c.role==="assistant"){let l={role:"assistant",content:""},f=c.content.filter(m=>m.type==="text"&&m.text);f.length&&(l.content=f.some(m=>m.cache_control)?f.map(m=>({type:"text",text:m.text,cache_control:m.cache_control})):f.map(m=>m.text).join(`
78
- `));let d=c.content.filter(m=>m.type==="tool_use"&&m.id);d.length&&(l.tool_calls=d.map(m=>({id:m.id,type:"function",function:{name:m.name,arguments:JSON.stringify(m.input||{})},cache_control:m.cache_control})));let h=c.content.find(m=>m.type==="thinking"&&m.signature);h&&(l.thinking={content:h.thinking,signature:h.signature}),r.push(l)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice,...e.cache_control?{cache_control:e.cache_control}:{}};return e.thinking&&(s.reasoning={effort:e.output_config?.effort||e.effort,enabled:e.thinking.type==="enabled"||e.thinking.type==="adaptive",...typeof e.thinking.budget_tokens=="number"?{max_tokens:e.thinking.budget_tokens}:{}}),Array.isArray(n?.provider?.transformer?.use)&&n.provider.transformer.use.some(c=>c?.name==="claude-auth")&&(e.thinking&&(s.anthropic_thinking=e.thinking),e.output_config&&(s.anthropic_output_config=e.output_config),e.metadata&&(s.anthropic_metadata=e.metadata),e.stop_sequences&&(s.anthropic_stop_sequences=e.stop_sequences)),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:s.tool_choice=e.tool_choice.type),s}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}static buildAnthropicBody(e,n){let r;e.system&&(typeof e.system=="string"?r=e.system:Array.isArray(e.system)&&e.system.length&&(r=e.system.filter(l=>l.type==="text").map(l=>({type:"text",text:l.text,...l.cache_control?{cache_control:l.cache_control}:{}}))));let o=[];for(let l of e.messages){if(l.role==="system"){if(!r){if(typeof l.content=="string")r=l.content;else if(Array.isArray(l.content)){let f=l.content.filter(d=>d.type==="text"&&!!d.text);f.length===1&&!f[0].cache_control?r=f[0].text:f.length>0&&(r=f.map(d=>({type:"text",text:d.text,...d.cache_control?{cache_control:d.cache_control}:{}})))}}continue}if(l.role==="tool"){let f={type:"tool_result",tool_use_id:l.tool_call_id,content:typeof l.content=="string"?l.content:JSON.stringify(l.content),...l.cache_control?{cache_control:l.cache_control}:{}},d=o[o.length-1];d?.role==="user"&&Array.isArray(d.content)?d.content.push(f):o.push({role:"user",content:[f]});continue}if(l.role==="assistant"){let f=[];if(l.thinking&&f.push({type:"thinking",thinking:l.thinking.content,signature:l.thinking.signature}),typeof l.content=="string"&&l.content)f.push({type:"text",text:l.content});else if(Array.isArray(l.content))for(let d of l.content)d.type==="text"&&d.text&&f.push({type:"text",text:d.text,...d.cache_control?{cache_control:d.cache_control}:{}});if(l.tool_calls?.length)for(let d of l.tool_calls){let h={};try{h=JSON.parse(d.function.arguments||"{}")}catch(m){(n?.error??console.error)("Failed to parse tool_call arguments for tool '%s': %s",d.function.name,m)}f.push({type:"tool_use",id:d.id,name:d.function.name,input:h,...d.cache_control?{cache_control:d.cache_control}:{}})}f.length>0&&o.push({role:"assistant",content:f});continue}if(l.role==="user"){let f=[];if(typeof l.content=="string")f.push({type:"text",text:l.content});else if(Array.isArray(l.content)){for(let d of l.content)if(d.type==="text"&&d.text)f.push({type:"text",text:d.text,...d.cache_control?{cache_control:d.cache_control}:{}});else if(d.type==="image_url"&&d.image_url?.url){let h=d.image_url.url;if(h.startsWith("data:")){let[m,S]=h.split(","),y=m.split(":")[1]?.split(";")[0]??"image/jpeg";f.push({type:"image",source:{type:"base64",media_type:y,data:S},...d.cache_control?{cache_control:d.cache_control}:{}})}else f.push({type:"image",source:{type:"url",url:h},...d.cache_control?{cache_control:d.cache_control}:{}})}}f.length>0&&o.push({role:"user",content:f});continue}}let s;e.tools?.length&&(s=e.tools.map(l=>({name:l.function.name,description:l.function.description||"",input_schema:l.function.parameters,...l.cache_control?{cache_control:l.cache_control}:{}})));let a;if(e.tool_choice){let l=e.tool_choice;l==="auto"?a={type:"auto"}:l==="required"?a={type:"any"}:typeof l=="string"?a={type:"tool",name:l}:l.type==="function"&&(a={type:"tool",name:l.function?.name})}let c={model:e.model,max_tokens:e.max_tokens??8192,messages:o,stream:e.stream??!0};return r!==void 0&&(c.system=r),e.temperature!==void 0&&(c.temperature=e.temperature),e.tool_choice!=="none"&&s?.length&&(c.tools=s),e.tool_choice!=="none"&&a&&(c.tool_choice=a),e.anthropic_thinking&&(c.thinking=e.anthropic_thinking),e.anthropic_output_config&&(c.output_config=e.anthropic_output_config),e.anthropic_metadata&&(c.metadata=e.anthropic_metadata),e.anthropic_stop_sequences&&(c.stop_sequences=e.anthropic_stop_sequences),e.cache_control&&(c.cache_control=e.cache_control),Lr(c)}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema},...n.cache_control?{cache_control:n.cache_control}:{}}))}async convertOpenAIStreamToAnthropic(e,n){let r=null,o=null;return new ReadableStream({start:async a=>{let c=new TextEncoder,l=`msg_${Date.now()}`,f=null,d="unknown",h=!1,m=!1,S=!1,y=new Map,w=new Map,b=0,_=0,D=0,k=!1;o=()=>{k=!0};let v=!1,x=0,R=-1,j=0,W=()=>{let te=x;return x++,te},U=te=>{if(!k)try{a.enqueue(te);let re=new TextDecoder().decode(te);this.logger.debug({reqId:n.req.id,data:re,type:"send data"})}catch(re){if(re instanceof TypeError&&re.message.includes("Controller is already closed"))k=!0;else throw this.logger.debug({reqId:n.req.id,error:re instanceof Error?re.message:String(re),type:"send data error"}),re}},ue=()=>{if(!k)try{if(R>=0){let re={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
79
- data: ${JSON.stringify(re)}
80
-
81
- `)),R=-1}if(f)j>0&&(f.usage.server_tool_use={web_search_requests:j}),U(c.encode(`event: message_delta
82
- data: ${JSON.stringify(f)}
101
+ `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var fa,Ey=_r(()=>{"use strict";fa=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{timestamp:r=!0,prefix:o,metadata:s}=n||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),o&&(i.prefix=o),s&&Object.keys(s).length>0&&(i.metadata=s),i}async sendRequest(e,n,r,o,s){let i=new AbortController,c=setTimeout(()=>i.abort(),s);try{let u=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(c),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return u}catch(u){throw clearTimeout(c),u}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,i){let c=null;for(let u=1;u<=i.maxAttempts;u++)try{return await this.sendRequest(e,n,r,o,s)}catch(f){if(c=f,u===i.maxAttempts)break;let d=i.backoffMs*Math.pow(2,u-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${u}/${i.maxAttempts}), retrying in ${d}ms...`,f.message),await this.delay(d)}throw c}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n);return await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry),!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`,{cause:o})}}}});var Ms,vy,GT,pa,Ay=_r(()=>{"use strict";Ms=require("fs"),vy=require("path"),GT=require("os"),pa=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,GT.tmpdir)();this.baseDir=(0,vy.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Ms.existsSync)(this.baseDir)||(0,Ms.mkdirSync)(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return(0,vy.join)(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return(0,Ms.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var Ty,Bs,JT=_r(()=>{"use strict";Sy();Ey();Ay();Ty=class{handlers=new Map;defaultOptions={};logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){(this.logger?.error??console.error)(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){let n;switch(e.type){case"console":n=new da(e.config);break;case"webhook":n=new fa(e.config);break;case"temp-file":n=new pa(e.config);break;default:throw new Error(`Unknown output handler type: ${e.type}`)}return this.logger&&typeof n.setLogger=="function"&&n.setLogger(this.logger),n}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([i,c])=>{try{await c.output(e,r)?o.success.push(i):o.failed.push(i)}catch(u){(this.logger?.error??console.error)(`[OutputManager] Handler ${i} failed:`,u),o.failed.push(i)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},i=e.map(async c=>{let u=this.handlers.get(c);if(!u){(this.logger?.warn??console.warn)(`[OutputManager] Handler ${c} not found`),s.failed.push(c);return}try{await u.output(n,o)?s.success.push(c):s.failed.push(c)}catch(f){(this.logger?.error??console.error)(`[OutputManager] Handler ${c} failed:`,f),s.failed.push(c)}});return await Promise.all(i),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,i])=>i.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},Bs=new Ty});var IL={};Rf(IL,{ANTIGRAVITY_CLIENT_ID:()=>dd,ANTIGRAVITY_CLIENT_SECRET:()=>fd,ANTIGRAVITY_REDIRECT_URI:()=>hy,ANTIGRAVITY_SCOPES:()=>rT,ConfigService:()=>Kr,DEFAULT_LOG_BODY_MAX_BYTES:()=>Yf,ProviderService:()=>eo,SSEParserTransform:()=>Hn,SSESerializerTransform:()=>to,TokenizerService:()=>ko,TransformerService:()=>wo,calculateTokenCount:()=>cp,default:()=>PL,diffHeadersForLog:()=>ub,exchangeAuthorizationCode:()=>_T,fetchUserEmail:()=>yT,getGlobalTokenSpeedStats:()=>Dy,getTokenSpeedStats:()=>xy,getValidAccessToken:()=>oa,isClientAbortError:()=>Ge,isRoutedLlmPost:()=>xb,listClientRouteRegistrations:()=>lc,loadTokens:()=>na,matchClientProtocol:()=>wr,pluginManager:()=>Cy,protocolErrorBody:()=>Bo,resolveProjectId:()=>hd,rewriteStream:()=>pp,router:()=>hc,sanitizeBodyForLog:()=>cb,sanitizeHeadersForLog:()=>sc,saveTokens:()=>pd,searchProjectBySession:()=>up,sessionUsageCache:()=>fc,tokenSpeedPlugin:()=>Oy});module.exports=cR(IL);var YT=tt(require("fastify"),1),XT=tt(require("@fastify/cors"),1),QT=tt(K0(),1),ZT=require("@caeliq/ccr-shared");var pi=require("fs"),Vf=require("path"),ib=require("dotenv"),ab=tt(Jf(),1),Kr=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,Vf.join)(process.cwd(),this.options.jsonPath);if((0,pi.existsSync)(e))try{let n=(0,pi.readFileSync)(e,"utf-8"),r=ab.default.parse(n);this.config={...this.config,...r},(this.logger?.info??console.log)(`Loaded JSON config from: ${e}`)}catch(n){(this.logger?.warn??console.warn)(`Failed to load JSON config from ${e}:`,n)}else(this.logger?.warn??console.warn)(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Vf.join)(process.cwd(),this.options.envPath);if((0,pi.existsSync)(e))try{let n=(0,ib.config)({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){(this.logger?.warn??console.warn)(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};var Kf="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function et(t){return t.replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi,"[redacted-url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${Kf})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"').replace(/\b(?:authorization|x-api-key|api-key|api_key|access_token|token)\s*[:=]\s*["']?[^\s,;"']+/gi,e=>`${e.split(/\s*[:=]/,1)[0]}=[redacted]`).replace(/\[[0-9a-f:]+\](?::\d+)?/gi,"[redacted-address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[redacted-address]").replace(/\b(connect(?:ing)?(?:\s+to)?|from|to)\s+(?:localhost|(?:[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.)+[a-z]{2,63})(?::\d+)?\b/gi,"$1 [redacted-address]").replace(/([?&](?:api_?key|key|token|access_token|auth)=)[^&\s]+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,240)}var MR=new RegExp(`^(?:${Kf})$`,"i"),BR=6,UR=20;function oc(t,e=0){if(t==null)return t;if(!(e>BR)){if(typeof t=="string")return et(t);if(Array.isArray(t))return t.slice(0,UR).map(n=>oc(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=MR.test(r)?"[redacted]":oc(o,e+1);return n}return t}}var Yf=32768;function cb(t,e=Yf){let n=t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${Kf})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"'),r=Math.max(0,e);if(n.length<=r)return n;let o=n.length-r;return`${n.slice(0,r)}\u2026[truncated ${o} bytes]`}function jR(t,e){return t.split(`
102
+ `).map(n=>et(n)).filter(Boolean).join(`
103
+ `).slice(0,e)}function Cr(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:et(n)||"Unknown error",code:typeof e?.code=="string"?e.code:void 0,name:typeof e?.name=="string"?e.name:void 0,statusCode:typeof e?.statusCode=="number"?e.statusCode:void 0,stack:typeof e?.stack=="string"?jR(e.stack,4e3):void 0,cause:r?et(r):void 0}}var LR=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function qR(t){return LR.test(t)}function $R(t){if(t==null)return;if(Array.isArray(t)){let n=t.filter(r=>r!=null&&String(r).length>0).map(r=>String(r));return n.length?n.join(", "):void 0}let e=String(t);return e.length?e:void 0}function sc(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=$R(o);if(s!=null){if(qR(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function ub(t,e){let n=sc(t),r=sc(e),o=new Map(Object.entries(n).map(([d,p])=>[d.toLowerCase(),{key:d,value:p}])),s=new Map(Object.entries(r).map(([d,p])=>[d.toLowerCase(),{key:d,value:p}])),i={},c={},u={},f=0;for(let[d,{key:p,value:h}]of o){let _=s.get(d);if(!_){i[p]=h;continue}_.value===h?f+=1:u[p]={from:h,to:_.value}}for(let[d,{key:p,value:h}]of s)o.has(d)||(c[p]=h);return{onlyInLeft:i,onlyInRight:c,changed:u,sameCount:f}}var bt="client disconnected";function Qf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"})):new Promise((n,r)=>{let o=setTimeout(()=>{e&&e.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),r(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"}))};e&&e.addEventListener("abort",s,{once:!0})})}function fb(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(c=bt)=>{n.signal.aborted||n.abort(c)},i=()=>{if(!o&&(o=!0,!!r)){if(Xf(r)){s(`${bt} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&Xf(r)&&s(`${bt} (response close)`)}),r.on("error",c=>{(c?.code==="EPIPE"||c?.code==="ECONNRESET"||c?.code==="ERR_STREAM_PREMATURE_CLOSE"||Ge(c))&&s(`${bt} (response error)`)})}};return{signal:n.signal,arm:i}}function zR(t){let e=t?.trim();if(!e)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(n*1e3,6e4);let r=Date.parse(e);if(Number.isFinite(r))return Math.min(Math.max(0,r-Date.now()),6e4)}function HR(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function Zf(t,e){let n=zR(e);return n!==void 0&&n>0?n:HR(t)}function pb(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var lb=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CONNECT"]);function hb(t){let e=t;if(!e)return!1;if(e.name==="TimeoutError"||e.code==="TIMEOUT_ERR"||e.code===23||e.cause&&(e.cause.name==="TimeoutError"||e.cause.code==="TIMEOUT_ERR"||e.cause.code===23))return!0;let n=String(e.message||"");return/aborted due to timeout|operation was aborted due to timeout/i.test(n)}function hn(t=bt){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:bt;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function db(t){let e=t.toLowerCase();if(e.includes("socket hang up"))return!0;let n=e.indexOf("client");if(n===-1)return!1;let r=e.slice(n);return r.includes("closed")||r.includes("disconnect")}function Ge(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(bt)||db(t);let e=t;if(hb(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(bt)||typeof e.message=="string"&&e.message.startsWith(bt)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return db(r)}function Xf(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function mb(t){return Xf(t.raw)}function Yr(t){if(!t||Ge(t))return!1;if(hb(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&lb.has(e.code)||e.cause?.code&&lb.has(String(e.cause.code)))return!0;let n=String(e.message||"");return/fetch failed|network|socket|ECONNRESET|ENOTFOUND|ETIMEDOUT|other side closed/i.test(n)}function WR(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function ep(t){let e=t;if(!e||Ge(e))return!1;if(Yr(e))return!0;let n=typeof e.statusCode=="number"?e.statusCode:typeof e.upstream?.status=="number"?e.upstream.status:void 0;return n!==void 0?WR(n):e.code==="provider_response_error"}function Bo(t,e,n,r,o="invalid_request_error"){switch(t){case"openai_chat_completions":case"openai_responses":return{statusCode:n,body:{error:{message:e,type:o,param:null,code:r}}};default:return{statusCode:n,body:{error:{message:e,type:o==="invalid_request_error"?"invalid_request_error":o,code:r},type:"error"}}}}function W(t,e=500,n="internal_error",r="api_error",o){let s=new Error(et(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function gb(t,e,n){if(Ge(t)||n.raw.destroyed||n.sent)return e.log.debug(Cr(t),"request aborted or already closed"),!n.sent&&!n.raw.destroyed&&!n.raw.headersSent?(n.type("application/json"),n.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):void 0;e.log.error(Cr(t),"request error");let r=t.statusCode||500,o=et(t.message||"Internal error")||"Internal error",s=t.code||"internal_error",i=t.type||(r>=400&&r<500?"invalid_request_error":"api_error"),c=e.clientProtocol,u=t.protocolBody,f=t.upstream?.body;if(!u&&f&&typeof f=="object"){let d=f.error;(c==="anthropic_messages"||!c)&&f.type==="error"&&d&&typeof d=="object"?u={type:"error",error:{type:typeof d.type=="string"?d.type:i,message:typeof d.message=="string"?d.message:o,...typeof d.code=="string"?{code:d.code}:{}}}:(c==="openai_chat_completions"||c==="openai_responses")&&d&&typeof d=="object"&&(u={error:{message:typeof d.message=="string"?d.message:o,type:typeof d.type=="string"?d.type:i,param:d.param??null,code:typeof d.code=="string"?d.code:s}})}return u||(u=Bo(c,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}var sC=require("stream");var _b=require("undici");function GR(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function JR(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function yb(t){let e=t.split(".");if(e.length!==4)return null;let n=0;for(let r of e){let o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>255)return null;n=n<<8|o}return n>>>0}function VR(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=yb(t),i=yb(n);if(s===null||i===null)return!1;let c=o===0?0:-1<<32-o>>>0;return(s&c)===(i&c)}function KR(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=GR(e.hostname);if(n==="localhost"||n==="127.0.0.1"||n.startsWith("127.")||n==="0.0.0.0"||n==="::1"||n==="0:0:0:0:0:0:0:1")return!0;let r=process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;let o=r.split(",").map(s=>s.trim()).filter(Boolean);for(let s of o){let i=s.toLowerCase();if(i==="*")return!0;let c=YR(i);if(c.startsWith(".")){if(n.endsWith(c)||n===c.slice(1))return!0;continue}if(c.includes("/")&&JR(n)){if(VR(n,c))return!0;continue}if(n===c)return!0;if(c.startsWith("*.")){let u=c.slice(1);if(n.endsWith(u)||n===u.slice(1))return!0}}return!1}function YR(t){if(t.startsWith("[")&&t.includes("]"))return t.slice(1,t.indexOf("]"));if(t.split(":").length-1===1){let[n,r]=t.split(":");if(/^\d+$/.test(r))return n}return t}async function Uo(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([p,h])=>{h&&s.set(p,h)});let i=AbortSignal.timeout(n.TIMEOUT??60*1e3*60),c=n.signal?AbortSignal.any([n.signal,i]):i,u={method:"POST",headers:s,body:JSON.stringify(e),signal:c},f=typeof t=="string"?t:t.toString();n.httpsProxy&&!KR(f)&&(u.dispatcher=new _b.ProxyAgent(new URL(n.httpsProxy).toString()));try{return await fetch(f,u)}catch(p){if(Ge(p))throw typeof p=="string"?hn(p):p;if(n.signal?.aborted&&Ge(n.signal.reason??bt))throw hn(n.signal.reason??p);if(Yr(p)){let h=W(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var bb="1.0.59";var wb=require("crypto"),tp={type:"ephemeral"};function Je(t){return t.map(e=>{let n={...e};return Array.isArray(n.content)&&(n.content=n.content.map(r=>{if(r.cache_control){let{cache_control:o,...s}=r;return s}return r})),n.cache_control&&delete n.cache_control,Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{let{cache_control:o,...s}=r;return s})),n})}function Ve(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function Cb(t){return`ccr_${(0,wb.createHash)("sha256").update(t).digest("hex").slice(0,48)}`}function QR(t){if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}return t}function ZR(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
104
+ `):""}function Yt(t,e){let n=t?.req?.sessionId||QR(e?.metadata?.user_id);if(typeof n=="string"&&n)return Cb(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?ZR(r.content):"",s=[e.model||"",o].join(`
105
+ `);return s.trim()?Cb(s):void 0}function Xr(t,e={}){let n=e.maxBreakpoints??4,r=JSON.parse(JSON.stringify(t)),o=[],s=f=>{f&&typeof f=="object"&&f.cache_control&&o.push(f)};(Array.isArray(r.tools)?r.tools:[]).forEach(s),Array.isArray(r.system)?r.system.forEach(s):s(r.system),(Array.isArray(r.messages)?r.messages:[]).forEach(f=>{s(f),Array.isArray(f?.content)&&f.content.forEach(s)});let i=!!r.cache_control,c=Math.max(0,n-(i?1:0));if(o.length>c)for(let f of o.slice(0,o.length-c))delete f.cache_control;let u=Math.min(o.length,c);if(!i&&u<n){let f=o[o.length-1]?.cache_control;r.cache_control=f?.ttl?{type:"ephemeral",ttl:f.ttl}:tp}return r}function Qr(t){let e=Je(t.messages||[]),n=Ve(t.tools);for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o.content=="string"&&o.content){o.content=[{type:"text",text:o.content,cache_control:tp}];break}if(Array.isArray(o.content))for(let s=o.content.length-1;s>=0;s-=1){let i=o.content[s];if(i?.type==="text"&&i.text)return o.content[s]={...i,cache_control:tp},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function ic(t){let e=[];for(let n=0;n<t.length;n++){let r={...t[n]};if(r.role==="assistant"&&r.tool_calls){let o=[],s=[],i=[],c=n+1;for(;c<t.length&&t[c].role==="tool";)i.push(t[c]),c++;r.tool_calls.forEach(u=>{i.some(d=>d.tool_call_id===u.id)?o.push(u):s.push(u.id)}),o.length>0?r.tool_calls=o:delete r.tool_calls,(r.content||r.tool_calls)&&e.push(r)}else if(r.role==="tool"){let o=!1;if(n>0){let s=t[n-1];if(s.role==="assistant"&&s.tool_calls)o=s.tool_calls.some(i=>i.id===r.tool_call_id);else if(s.role==="tool"){for(let i=n-1;i>=0;i--)if(t[i].role!=="tool"){t[i].role==="assistant"&&t[i].tool_calls&&(o=t[i].tool_calls.some(c=>c.id===r.tool_call_id));break}}}o&&e.push(r)}else e.push(r)}return e}function kb(t){let n=(t||"").toLowerCase().match(/(?:^|\/)gpt-(\d+)(?:\.(\d+))?/);if(!n)return!1;let r=Number(n[1]),o=Number(n[2]||0);return r>5||r===5&&o>=6}function Sb(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function ex(t){for(let e=t.length-1;e>=0;e-=1)if(Sb(t[e]))return e;return-1}function hi(t,e,n){let r={...t,messages:(t.messages||[]).map(s=>({...s,content:Array.isArray(s.content)?s.content.map(i=>({...i})):s.content})),tools:Array.isArray(t.tools)?t.tools.map(s=>s?.function?{...s,function:{...s.function,parameters:{...s.function.parameters}}}:{...s}):t.tools},o=Yt(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),kb(r.model)){let s=[];r.messages.forEach((i,c)=>{if(i.cache_control){if(typeof i.content=="string"&&i.content)s.push({messageIndex:c});else if(Array.isArray(i.content)){let u=ex(i.content);u>=0&&s.push({messageIndex:c,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,f)=>{u?.cache_control&&Sb(u)&&s.push({messageIndex:c,contentIndex:f})})});for(let i of s.slice(-3)){let c=r.messages[i.messageIndex];typeof c.content=="string"?c.content=[{type:"text",text:c.content,prompt_cache_breakpoint:{mode:"explicit"}}]:Array.isArray(c.content)&&i.contentIndex!==void 0&&(c.content[i.contentIndex].prompt_cache_breakpoint={mode:"explicit"})}}return r.messages=Je(r.messages),r.tools=Ve(r.tools),r}function ac(t,e){return kb(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function tx(t){return String(t?.name||"").trim().toLowerCase()}function nx(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function np(t,e){let n={...t,messages:Je(t.messages||[]),tools:Ve(t.tools)},r=Yt(e,t);return r&&(n.prompt_cache_key=r),n}function cc(t,e,n){let r=tx(e),o=nx(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?hi(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?Qr(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?np(t,n):{...t,messages:Je(t.messages||[]),tools:Ve(t.tools)}}async function Eb(t,e,n){let r=await t(e);if(r.status!==401||typeof n!="function")return r;let o=await n();if(!o)return r;try{await r.body?.cancel()}catch{}return Object.assign(e,o),t(e)}function vb(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function uc(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=vb(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var rx=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function Ab(t){let e={};return t&&t.forEach((n,r)=>{rx.has(r.toLowerCase())||(e[r]=n)}),e}var ox=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),sx=["anthropic-ratelimit-","x-ratelimit-"];function rp(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){if(typeof o!="string"||!o)continue;let s=r.toLowerCase();!(ox.has(s)||sx.some(c=>s.startsWith(c)))||e[s]!==void 0||(e[s]=o)}return e}function Tb(t,e){let n={};for(let[r,o]of Object.entries(t||{})){if(o===void 0||o==="undefined")continue;let s=r.toLowerCase(),i=s==="authorization"?"Authorization":s==="x-api-key"?"x-api-key":s,c=vb(n,i);c&&delete n[c],n[i]=o}return n["x-api-key"]?delete n.Authorization:!n.Authorization&&e&&(n.Authorization=`Bearer ${e}`),Object.fromEntries(Object.entries(n).filter(r=>typeof r[1]=="string"))}var Zr=require("@caeliq/ccr-shared");var Rb=[{protocol:"anthropic_messages",canonicalPath:"/v1/messages",aliases:[],ownerTransformerName:"Anthropic"},{protocol:"openai_chat_completions",canonicalPath:"/v1/chat/completions",aliases:["/chat/completions"],ownerTransformerName:"OpenAI"},{protocol:"openai_responses",canonicalPath:"/v1/responses",aliases:["/responses"],ownerTransformerName:"openai-responses"}],ix=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],ax=/^\/preset\/[^/]+/;function cx(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function ux(t){let e=t.match(ax);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function lx(t){return ix.some(e=>t===e)}function dx(t){for(let e of Rb){let n=[e.canonicalPath,...e.aliases];for(let r of n)if(t===r)return{protocol:e.protocol,canonicalPath:e.canonicalPath,matchedPath:r,ownerTransformerName:e.ownerTransformerName,isAlias:r!==e.canonicalPath,stream:!!e.defaultStream}}return null}function wr(t,e){if(t.toUpperCase()!=="POST")return null;let n=cx(e),{suffix:r,presetPrefix:o}=ux(n);if(lx(r))return null;let s=dx(r);return s?{...s,presetPrefix:o}:null}function xb(t,e){return wr(t,e)!==null}function lc(){let t=[];for(let e of Rb){t.push({path:e.canonicalPath,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!0});for(let n of e.aliases)t.push({path:n,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!1})}return t}function Db(t,e){return{protocol:t.protocol,pathname:t.matchedPath,canonicalPath:t.canonicalPath,matchedPath:t.matchedPath,originalModel:e?.originalModel,stream:e?.stream??t.stream,scenarioType:e?.scenarioType,ownerTransformerName:t.ownerTransformerName}}var Ob=require("crypto"),Pb=/^[a-zA-Z0-9_-]+$/,Ib=/[^a-zA-Z0-9_-]+/g,Fb=256;function fx(t){return t.length>0&&t.length<=Fb&&Pb.test(t)}function op(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function $n(t){if(typeof t!="string"||t.length===0)return;if(fx(t))return t;let e=op(t.replace(Ib,"_").slice(0,Fb));return e.length?e:void 0}var Nb=64,Mb=20,px=Nb-Mb-1;function hx(t){return t.length>0&&t.length<=Nb&&Pb.test(t)}function Ct(t){if(typeof t!="string"||t.length===0)return;if(hx(t))return t;let e=op(t.replace(Ib,"_")),n=op(e.slice(0,px))||"call",r=(0,Ob.createHash)("sha256").update(t,"utf8").digest("base64url").slice(0,Mb);return`${n}_${r}`}function jo(){return{forward:new Map,reverse:new Map}}function mi(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=Ct(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=Ct(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=Ct(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function dc(t,e=jo()){if(!t||typeof t!="object")throw W("Invalid Responses body",400,"invalid_body");if(typeof t.model!="string"||!t.model.trim())throw W("Responses requires model",400,"invalid_body","invalid_request_error");if(mx(t),t.stream!==void 0&&typeof t.stream!="boolean")throw W("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.instructions!==void 0&&typeof t.instructions!="string")throw W("instructions must be a string",400,"invalid_instructions","invalid_request_error");if(t.max_tokens!==void 0)throw W("Responses uses max_output_tokens, not max_tokens",400,"unsupported_field","invalid_request_error");if(t.max_output_tokens!=null){let u=Number(t.max_output_tokens);if(!Number.isInteger(u)||u<=0)throw W("max_output_tokens must be a positive integer",400,"invalid_token_limit","invalid_request_error")}if(t.reasoning!==void 0&&(t.reasoning===null||typeof t.reasoning!="object"||Array.isArray(t.reasoning)))throw W("reasoning must be an object",400,"invalid_reasoning","invalid_request_error");if(t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw W("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");if(t.prompt_cache_key!==void 0&&typeof t.prompt_cache_key!="string")throw W("prompt_cache_key must be a string",400,"invalid_prompt_cache_key","invalid_request_error");if(t.text?.format&&t.text.format.type!=="text")throw W("Structured text formats are not supported without a verified mapping",400,"unsupported_response_format","invalid_request_error");for(let u of["metadata","max_tool_calls","service_tier","safety_identifier","top_logprobs","truncation"])if(t[u]!==void 0&&t[u]!==null)throw W(`Responses field '${u}' is not supported`,400,"unsupported_field","invalid_request_error");let n=[];typeof t.instructions=="string"&&t.instructions&&n.push({role:"system",content:t.instructions});let r=t.input;if(typeof r=="string")n.push({role:"user",content:r});else if(Array.isArray(r)){if(r.length===0)throw W("Responses input[] must not be empty",400,"invalid_input","invalid_request_error");for(let u of r)gx(n,u,e)}else throw W("Responses requires string input or input[]",400,"invalid_input","invalid_request_error");if(n.length===0)throw W("Responses input did not contain a supported item",400,"invalid_input","invalid_request_error");let o=_x(t.tools),s=bx(t.tool_choice),i=t.reasoning&&typeof t.reasoning=="object"?{enabled:!0,effort:t.reasoning.effort,summary:t.reasoning.summary}:void 0,c={model:t.model,messages:n,tools:o,tool_choice:s,stream:t.stream===!0,temperature:t.temperature,top_p:t.top_p,max_tokens:t.max_output_tokens??t.max_tokens,reasoning:i,parallel_tool_calls:t.parallel_tool_calls};return typeof t.prompt_cache_key=="string"&&(c.prompt_cache_key=t.prompt_cache_key),c}function mx(t){if(t.store===!0)throw W("store: true is not supported; CCR does not own Responses state",400,"unsupported_store","invalid_request_error");if(t.previous_response_id)throw W("previous_response_id is not supported",400,"unsupported_previous_response_id","invalid_request_error");if(t.conversation)throw W("conversation is not supported",400,"unsupported_conversation","invalid_request_error");if(t.background===!0)throw W("background: true is not supported",400,"unsupported_background","invalid_request_error");if(Array.isArray(t.tools))for(let e of t.tools){let n=e?.type;if(typeof n!="string"||!n)throw W("Responses tools require a type",400,"invalid_tool","invalid_request_error");if(n!=="function"&&n!=="web_search"&&n!=="web_search_preview")throw W(`Hosted tool type '${n}' is not supported on cross-protocol routes`,400,"unsupported_hosted_tool","invalid_request_error")}}function gx(t,e,n){if(!e||typeof e!="object")throw W("Invalid Responses input item",400,"invalid_input_item","invalid_request_error");if(e.type==="function_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw W("function_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:mi(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="function_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw W("function_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw W("function_call requires name",400,"invalid_function_call","invalid_request_error");t.push({role:"assistant",content:null,tool_calls:[{id:mi(n,r)??r,type:"function",function:{name:e.name,arguments:typeof e.arguments=="string"?e.arguments:JSON.stringify(e.arguments??{})}}]});return}if(e.type==="message"||e.role){let r=e.role==="assistant"?"assistant":e.role==="system"||e.role==="developer"?"system":e.role==="user"?"user":void 0;if(!r)throw W(`Unsupported Responses message role '${e.role}'`,400,"unsupported_role","invalid_request_error");if(typeof e.content!="string"&&!Array.isArray(e.content))throw W("Responses message items require string or array content",400,"invalid_content","invalid_request_error");t.push({role:r,content:yx(e.content)});return}if(e.type==="input_text"||e.type==="output_text"){t.push({role:e.type==="output_text"?"assistant":"user",content:String(e.text??"")});return}if(e.type==="input_image"){if(e.file_id)throw W("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=e.image_url||e.url;if(typeof r!="string"||!r)throw W("input_image requires image_url",400,"invalid_image","invalid_request_error");t.push({role:"user",content:[{type:"image_url",image_url:{url:r,...e.detail?{detail:e.detail}:{}}}]});return}throw W(`Unsupported Responses input item type '${e.type||"unknown"}'`,400,"unsupported_input_item","invalid_request_error")}function yx(t){if(typeof t=="string")return t;if(!Array.isArray(t))return t==null?"":JSON.stringify(t);let e=[];for(let n of t){if(typeof n=="string"){e.push({type:"text",text:n});continue}if(!(!n||typeof n!="object"))if(n.type==="input_text"||n.type==="output_text"||n.type==="text")e.push({type:"text",text:String(n.text??"")});else if(n.type==="input_image"||n.type==="image_url"){if(n.file_id)throw W("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=n.image_url?.url||n.image_url||n.url;if(typeof r!="string"||!r)throw W("input_image requires image_url",400,"invalid_image","invalid_request_error");e.push({type:"image_url",image_url:{url:r,...n.detail?{detail:n.detail}:{}}})}else throw W(`Unsupported Responses content part '${n.type||"unknown"}'`,400,"unsupported_content_part","invalid_request_error")}return e.length===1&&e[0].type==="text"?e[0].text:e.length>0?e:""}function _x(t){if(t!=null){if(!Array.isArray(t))throw W("Responses tools must be an array",400,"invalid_tools","invalid_request_error");return t.map(e=>{if(e?.type==="function"){let n=e.name||e.function?.name;if(typeof n!="string"||!n)throw W("Responses function tools require a name",400,"invalid_tool","invalid_request_error");return{type:"function",function:{name:n,description:e.description||e.function?.description,parameters:e.parameters||e.function?.parameters||{type:"object",properties:{}}}}}if(e?.type==="web_search"||e?.type==="web_search_preview")return{...e,type:"web_search"};throw W(`Unsupported Responses tool type '${e?.type||"unknown"}'`,400,"unsupported_hosted_tool","invalid_request_error")})}}function bx(t){if(t!=null){if(typeof t=="string"){if(["auto","none","required"].includes(t))return t;throw W(`Unsupported Responses tool_choice '${t}'`,400,"unsupported_tool_choice","invalid_request_error")}if(t?.type==="function"&&t?.name)return{type:"function",function:{name:t.name}};throw t?.type==="allowed_tools"?W("allowed_tools tool_choice is not supported",400,"unsupported_tool_choice","invalid_request_error"):W("Unsupported Responses tool_choice",400,"unsupported_tool_choice","invalid_request_error")}}function Bb(t,e){let n=e?.callIdMap??jo(),o=t?.choices?.[0]?.message||{},s=[],i=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.filter(u=>u?.type==="text").map(u=>u.text).join(""):"";if(i||!o.tool_calls?.length){let u=`msg_${t.id||Date.now()}`;s.push({type:"message",id:u,status:"completed",role:"assistant",content:[{type:"output_text",text:i||"",annotations:[],logprobs:o?.logprobs?.content||[]}]})}if(Array.isArray(o.tool_calls))for(let u of o.tool_calls){if(!u?.function)continue;let f=mi(n,u.id,"unified_to_client")??u.id;s.push({type:"function_call",id:f,call_id:f,name:u.function.name,arguments:typeof u.function.arguments=="string"?u.function.arguments:JSON.stringify(u.function.arguments??{}),status:"completed"})}let c=zb(t?.usage);return{id:t?.id||`resp_${Date.now()}`,object:"response",created_at:t?.created||Math.floor(Date.now()/1e3),status:"completed",model:e?.originalModel||t?.model,output:s,usage:c}}function Ub(t){let e=`resp_${Date.now()}`;return{responseId:e,model:t?.model,textItemId:`msg_${e}`,textStarted:!1,textContent:"",toolCalls:new Map,nextOutputIndex:0,finished:!1,created:!1,sequenceNumber:0,finishReasonSeen:!1,callIdMap:t?.callIdMap??jo()}}function jb(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function Lb(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:$b(t,"in_progress")}))}function qb(t,e){if(!t||typeof t!="object")return[];if(e.finished)return[];let n=[],r=t.choices?.[0],o=r?.delta||{};if(!e.model&&t.model&&(e.model=t.model),t.id&&(e.responseId=t.id.startsWith("resp_")?t.id:`resp_${t.id}`),t.usage&&(e.usage=t.usage),!e.textStarted&&e.toolCalls.size===0&&(typeof o.content=="string"||Array.isArray(o.tool_calls)||r?.finish_reason)&&Lb(e,n),typeof o.content=="string"&&o.content.length>0&&(e.textStarted||(e.textStarted=!0,e.textOutputIndex=e.nextOutputIndex++,n.push({type:"response.output_item.added",output_index:e.textOutputIndex,item:{type:"message",id:e.textItemId,status:"in_progress",role:"assistant",content:[]}}),n.push({type:"response.content_part.added",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,part:{type:"output_text",text:"",annotations:[]}})),e.textContent+=o.content,n.push({type:"response.output_text.delta",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,delta:o.content,logprobs:[]})),Array.isArray(o.tool_calls))for(let s of o.tool_calls){let i=typeof s.index=="number"?s.index:0,c=e.toolCalls.get(i);if(c||(c={id:mi(e.callIdMap,s.id||`call_${e.responseId}_${i}`,"unified_to_client")||`call_${i}`,name:s.function?.name||"",arguments:"",added:!1,outputIndex:e.nextOutputIndex++,emittedArgumentsLength:0},e.toolCalls.set(i,c)),s.id&&!c.added&&(c.id=mi(e.callIdMap,s.id,"unified_to_client")||c.id),s.function?.name&&(c.name=s.function.name),typeof s.function?.arguments=="string"&&(c.arguments+=s.function.arguments),!c.added&&c.name&&(c.added=!0,n.push({type:"response.output_item.added",output_index:c.outputIndex,item:{type:"function_call",id:c.id,call_id:c.id,name:c.name,arguments:"",status:"in_progress"}})),c.added&&c.arguments.length>c.emittedArgumentsLength){let u=c.arguments.slice(c.emittedArgumentsLength);c.emittedArgumentsLength=c.arguments.length,n.push({type:"response.function_call_arguments.delta",item_id:c.id,output_index:c.outputIndex,delta:u})}}return r?.finish_reason&&(e.finishReasonSeen=!0),jb(e,n)}function sp(t,e){if(t.finished)return[];t.finished=!0;let n=[];Lb(t,n),t.textStarted&&(n.push({type:"response.output_text.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,text:t.textContent,logprobs:[]}),n.push({type:"response.content_part.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,part:{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}}),n.push({type:"response.output_item.done",output_index:t.textOutputIndex,item:{type:"message",id:t.textItemId,status:"completed",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}}));for(let o of t.toolCalls.values())n.push({type:"response.function_call_arguments.done",item_id:o.id,output_index:o.outputIndex,name:o.name,arguments:o.arguments}),n.push({type:"response.output_item.done",output_index:o.outputIndex,item:{type:"function_call",id:o.id,call_id:o.id,name:o.name,arguments:o.arguments,status:"completed"}});let r=$b(t,"completed",e||t.usage);return n.push({type:"response.completed",response:r}),jb(t,n)}function $b(t,e,n){let r=[];(t.textStarted||t.textContent)&&r.push({index:t.textOutputIndex??0,item:{type:"message",id:t.textItemId,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}});for(let s of t.toolCalls.values())r.push({index:s.outputIndex,item:{type:"function_call",id:s.id,call_id:s.id,name:s.name,arguments:s.arguments,status:e==="completed"?"completed":"in_progress"}});let o=r.sort((s,i)=>s.index-i.index).map(({item:s})=>s);return{id:t.responseId,object:"response",created_at:Math.floor(Date.now()/1e3),status:e,model:t.model,output:o,usage:zb(n)}}function zb(t){if(!t||typeof t!="object")return;let e={input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0},n=t.prompt_tokens_details;return n&&typeof n=="object"&&(e.input_tokens_details={},n.cached_tokens!=null&&(e.input_tokens_details.cached_tokens=n.cached_tokens),n.cache_write_tokens!=null&&(e.input_tokens_details.cache_write_tokens=n.cache_write_tokens)),e}function gi(t,e){let n={type:"response.failed",response:{id:e?.responseId||`resp_${Date.now()}`,object:"response",status:"failed",error:{message:t,type:"api_error",code:"provider_response_error"},output:[]}};return e?{...n,sequence_number:e.sequenceNumber++}:n}function Hb(t,e,n){let r=e&&typeof e=="object"?Lo(e):{},o=t.stream,s=typeof r.model=="string"?r.model:void 0;(t.protocol==="openai_chat_completions"||t.protocol==="openai_responses"||t.protocol==="anthropic_messages")&&(o=r.stream===!0);let i=Db(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function Wb(t,e,n,r){if(typeof n.transformRequestOut=="function"){let o=await n.transformRequestOut(e,r);return o&&typeof o=="object"&&"body"in o&&o.body?o.body:o}if(t==="openai_chat_completions")return Cx(e);if(t==="openai_responses")return dc(e);throw t==="anthropic_messages"?W("Anthropic transformRequestOut is required",500,"transformer_misconfigured"):W(`Client protocol '${t}' normalization is not implemented yet`,501,"protocol_not_implemented")}function Cx(t){if(!t||typeof t!="object")throw W("Invalid Chat Completions body",400,"invalid_body");if(!Array.isArray(t.messages))throw W("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model)throw W("Chat Completions requires model",400,"invalid_body","invalid_request_error");return t}function Lo(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var wx=new Set(["accept","content-type","idempotency-key","anthropic-beta","anthropic-dangerous-direct-browser-access","anthropic-version","openai-beta","openai-organization","openai-project","user-agent","x-app","x-claude-code-session-id","x-client-request-id"]),kx=["x-stainless-"];function Gb(t){let e={};if(!t)return e;let n=t instanceof Headers?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=r.toLowerCase();if(!(wx.has(s)||kx.some(u=>s.startsWith(u))))continue;let c=Array.isArray(o)?o[0]:o;typeof c=="string"&&c&&(e[s]=c)}return e}function Jb(t,e,n,r){let o=t.transformer?.use;if(!Array.isArray(o)||o.length!==1||o[0]?.name!==e.name)return!1;let s=r?t.transformer?.[r]?.use:void 0;if(Array.isArray(s)&&s.length>0&&(s.length!==1||s[0]?.name!==e.name))return!1;let i={anthropic_messages:"Anthropic",openai_chat_completions:"OpenAI",openai_responses:"openai-responses"};return e.name===i[n]}var Yb=require("tiktoken");var ip=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},fc=new ip(100);var ap=require("fs/promises"),yi=require("fs/promises"),at=require("path"),qo=require("@caeliq/ccr-shared"),Xb=require("lru-cache"),Sx=(0,Yb.get_encoding)("cl100k_base"),zn=t=>Sx.encode(t,void 0,[]),Vb="<CCR-SUBAGENT-MODEL>",Kb="</CCR-SUBAGENT-MODEL>",_i="x-anthropic-billing-header",$o=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Qb(t){let e=t?.trim();if(!e)return;if(e.includes(","))return e;let n=e.indexOf("/");return n>0?`${e.slice(0,n)},${e.slice(n+1)}`:e}function Ex(t){let e=`${_i}:`;if(!t.startsWith(e))return!1;let n=t.slice(e.length).trim();if(!n)return!1;if(n.startsWith("{"))try{let o=JSON.parse(n);return $o(o)&&o.cc_is_subagent===!0}catch{return!1}let r=n.split(";").map(o=>o.trim()).filter(Boolean).flatMap(o=>{let s=o.indexOf("=");return s<0||o.slice(0,s).trim()!=="cc_is_subagent"?[]:[o.slice(s+1).trim()]});return r.length===1&&r[0]==="true"}function pc(t,e){let n=t.indexOf(Vb);if(n<0)return;let r=n+Vb.length,o=t.indexOf(Kb,r);if(o<0)return;let s=Qb(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Kb.length)}`),s}function Zb(t,e){if(typeof t=="string")return pc(t,e);if(!(!$o(t)||typeof t.text!="string"))return pc(t.text,e)}function vx(t){let e=t?.system;if(typeof e=="string")return pc(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=Zb(r,s=>{typeof r=="string"?e[n]=s:$o(r)&&(r.text=s)});if(o)return o}}function Ax(t){if(typeof t.content=="string")return pc(t.content,n=>{t.content=n});if(!Array.isArray(t.content))return;let e=t.content;for(let n=0;n<e.length;n+=1){let r=e[n],o=Zb(r,s=>{typeof r=="string"?e[n]=s:$o(r)&&(r.text=s)});if(o)return o}}function Tx(t){if(!Array.isArray(t?.messages))return;let e=Math.min(t.messages.length,2);for(let n=0;n<e;n+=1){let r=t.messages[n];if(!$o(r)||r.role!=="user")continue;let o=Ax(r);if(o)return o}}function eC(t){return vx(t)||Tx(t)}function tC(t){let e=t?.system;if(!Array.isArray(e)||e.length===0)return{present:!1,isSubagent:!1};let n=e[0],r=typeof n=="string"?n:$o(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(_i)?{present:!0,isSubagent:Ex(r)}:{present:!1,isSubagent:!1}}var cp=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=zn(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=zn(s.text).length:s.type==="tool_use"?r+=zn(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=zn(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=zn(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=zn(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=zn(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=zn(o.name+o.description).length),o.input_schema&&(r+=zn(JSON.stringify(o.input_schema)).length)}),r},Rx=async(t,e)=>{if(t.sessionId){let n=await up(t.sessionId);if(n){let r=(0,at.resolve)(qo.HOME_DIR),o=(0,at.resolve)(r,(0,at.basename)(n)),s=(0,at.relative)(r,o);if(!s||s.startsWith(".."))return;let i=`${(0,at.basename)(String(t.sessionId))}.json`,c=(0,at.join)(o,"config.json"),u=(0,at.join)(o,i);try{let f=JSON.parse(await(0,ap.readFile)(u,"utf8"));if(f&&f.Router)return f.Router}catch{}try{let f=JSON.parse(await(0,ap.readFile)(c,"utf8"));if(f&&f.Router)return f.Router}catch{}}}};function nC(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function xx(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function Dx(t){return Array.isArray(t)?t.some(e=>{if(!e||typeof e!="object")return!1;if(typeof e.type=="string"&&(e.type==="web_search"||e.type.startsWith("web_search")))return!0;let n=e.function?.name||e.name||e.function?.function?.name;return typeof n=="string"&&(n==="web_search"||n.toLowerCase()==="websearch")}):!1}function Ox(t){if(t?.thinking)return!0;let e=t?.reasoning;return!!(e&&typeof e=="object"&&(e.enabled===!0||typeof e.effort=="string"&&e.effort.trim().length>0))}var Px=async(t,e,n,r)=>{let o=await Rx(t,n),s=n.get("providers")||[],i=o||n.get("Router"),c=nC(t),u=typeof c?.model=="string"?c.model:String(c?.model??"");if(u.includes(",")){let[h,_]=u.split(","),b=s.find(w=>w.name.toLowerCase()===h.toLowerCase()),y=b?.models?.find(w=>w.toLowerCase()===_.toLowerCase());return b&&y?{model:`${b.name},${y}`,scenarioType:"default"}:{model:u,scenarioType:"default"}}let f=i?.longContextThreshold||6e4,d=r&&r.input_tokens>f&&e>2e4,p=e>f;if(xx(t)){let h=t.protocolContext?.taggedSubagentModel,_=t.protocolContext?.claudeCodeSubagent===!0;if(h)return t.log.info(`Using CCR subagent tag model: ${h}`),{model:h,scenarioType:"subagent"};if(_){let y=Qb(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(y)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${y}`),{model:y,scenarioType:"subagent"}}let b=n.get("Router");if(u?.includes("claude")&&u?.includes("haiku")&&b?.background)return t.log.info(`Using background model for ${u}`),{model:b.background,scenarioType:"background"}}return Dx(c?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:Ox(c)&&i?.think?(t.log.info("Using think model for reasoning/thinking request"),{model:i.think,scenarioType:"think"}):(d||p)&&i?.longContext?(t.log.info(`Using long context model due to token count: ${e}, threshold: ${f}`),{model:i.longContext,scenarioType:"longContext"}):{model:i?.default||u,scenarioType:"default"}},Ix=t=>{if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}},hc=async(t,e,n)=>{let{configService:r,event:o}=n,s=nC(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=Ix(i);let c=fc.get(t.sessionId),u=s.messages||[],f=s.system??[],d=s.tools||[];try{let p=typeof s.model=="string"?s.model:String(s.model??""),[h,_]=p.split(","),b=n.tokenizerService?.getTokenizerConfigForModel(h,_),y;n.tokenizerService?y=(await n.tokenizerService.countTokens({messages:u,system:f,tools:d},b)).tokenCount:y=cp(u,f,d),t.tokenCount=y;let w,C=r.get("CUSTOM_ROUTER_PATH");if(C)try{w=await require(C)(t,r.getAll(),{event:o})}catch(v){t.log.error(`failed to load custom router: ${v.message}`)}if(w)t.scenarioType="default";else{let v=await Px(t,y,r,c);w=v.model,t.scenarioType=v.scenarioType}s.model=w,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=w)}catch(p){t.log.error(`Error in router middleware: ${p.message}`);let _=r.get("Router")?.default||s.model;s.model=_,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=_),t.scenarioType="default"}},kr=new Xb.LRUCache({max:1e3}),up=async(t,e)=>{if(kr.has(t)){let n=kr.get(t);return!n||n===""?null:n}try{if(!(await(0,yi.stat)(qo.CLAUDE_PROJECTS_DIR)).isDirectory())return kr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(kr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),kr.set(t,""),null)}try{let n=await(0,yi.opendir)(qo.CLAUDE_PROJECTS_DIR),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=(0,at.resolve)(qo.CLAUDE_PROJECTS_DIR),s=`${(0,at.basename)(String(t))}.jsonl`,i=r.map(async u=>{let f=(0,at.resolve)(o,(0,at.basename)(u)),d=(0,at.relative)(o,f);if(!d||d.startsWith(".."))return null;let p=(0,at.join)(f,s);try{return(await(0,yi.stat)(p)).isFile()?u:null}catch{return null}}),c=await Promise.all(i);for(let u of c)if(u)return kr.set(t,u),u;return kr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),kr.set(t,""),null}};var rC=require("fs/promises");async function oC(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||wr(t.method,s)||wr("POST",o);if(!i)throw W(`No inbound protocol match for ${s}`,404,"protocol_not_found");t.protocolMatch=i,t.clientProtocol=i.protocol,i.ownerTransformerName!==r.name&&t.log?.warn?.({expected:i.ownerTransformerName,actual:r.name,path:s},"endpoint transformer name differs from protocol owner");let c=t.body,u=t.query||{},{normalizationInput:f,context:d}=Hb(i,c,u);i.protocol==="anthropic_messages"&&await Fx(f,d,n.configService);let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:d},h=await Wb(i.protocol,f,r,p),_=t;t.protocolContext=d,t.unifiedBody=h,t.originalClientBody=c;let b=n.configService.get("CUSTOM_ROUTER_PATH"),y=_.body;_.body=i.protocol==="anthropic_messages"&&b?c:h;try{await hc(_,e,{configService:n.configService,tokenizerService:n.tokenizerService})}finally{_.body=y??c}let w=typeof h.model=="string"?h.model:d.originalModel;h.model=w||"",d.scenarioType=_.scenarioType,d.originalModel=d.originalModel??(typeof c?.model=="string"?c.model:void 0),_.unifiedBody=h,_.protocolContext=d;let C=Nx(h.model,i.protocol);return n.providerService.getProvider(C.providerName)||mc(i.protocol,`Provider '${C.providerName}' not found`,404,"provider_not_found"),h.model=C.modelName,_.provider=C.providerName,_.model=C.modelName,d.stream=d.stream||h.stream===!0||c?.stream===!0,{match:i,protocolContext:d,originalBody:c,clientWireBody:f,unifiedBody:h,providerName:C.providerName,modelName:C.modelName}}async function Fx(t,e,n){let r=tC(t);e.claudeCodeSubagent=r.isSubagent,e.taggedSubagentModel=eC(t),e.anthropicCacheMode="preserve";let o=n.get("REWRITE_SYSTEM_PROMPT"),s=t?.system;if(o&&Array.isArray(s)&&s.length>1&&typeof s[1]?.text=="string"&&s[1].text.includes("<env>")){let i=await(0,rC.readFile)(o,"utf-8");s[1].text=`${i}<env>${s[1].text.split("<env>").pop()}`}}function Nx(t,e){let n=typeof t=="string"?t.trim():"";n||mc(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||mc(e,`Unresolved bare model '${n}'. Configure Router.default or send provider,model.`,400,"unresolved_model","invalid_request_error");let[r,...o]=n.split(","),s=o.join(",");return(!r||!s)&&mc(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function mc(t,e,n,r,o="api_error"){let s=Bo(t,e,n,r,o),i=W(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function gc(t,e,n,r){return n?Jb(t,e,n.protocol,r):t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r||""]?.use?.length||t.transformer?.[r||""]?.use.length===1&&t.transformer?.[r||""]?.use[0].name===e.name)}function bi(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}async function Mx(t,e,n,r,o){let s=fb(t,e),i=s.signal;s.arm();let c;try{c=await oC(t,e,n,r,o)}catch(f){throw Ge(f)||i.aborted?typeof f=="string"?hn(f):hn(i.reason??f):f}let u=n.providerService.getProvider(c.providerName);if(!u)throw W(`Provider '${c.providerName}' not found`,404,"provider_not_found");t._preparedInbound=c;try{let f=gc(u,r,c.protocolContext,c.modelName),d=bi(u,r,c.protocolContext),p=c.clientWireBody??c.originalBody,h=f||d?{...typeof p=="object"&&p?Lo(p):{},model:c.modelName}:Lo(c.unifiedBody),{requestBody:_,config:b,bypass:y}=await iC(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:c.protocolContext.protocol,protocolContext:c.protocolContext,skipClientNormalization:!0}),w=await aC(_,b,u,n,y,r,{req:t,signal:i,protocolContext:c.protocolContext}),C=await cC(_,w,u,r,y,{req:t,signal:i,protocolContext:c.protocolContext,skipClientNormalization:y});return await uC(C,e,c.originalBody,i,c.protocolContext.stream)}catch(f){if(Ge(f))throw typeof f=="string"?hn(f):f;if(i.aborted)throw hn(i.reason??f);if(ep(f)){let d=await Bx(t,e,n,r,f,i);if(d)return d;if(i.aborted)throw hn(i.reason??bt)}throw f}}async function Bx(t,e,n,r,o,s){let i=t.scenarioType||"default",c=n.configService.get("fallback"),u=pb(c,i);if(!u?.length||s?.aborted||Ge(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:Cr(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let f=0,d=Zf(f,o?.headers?.["Retry-After"]??o?.headers?.["retry-after"]);if(f+=1,d>0){t.log.info(`Waiting ${d}ms before first fallback attempt`);try{await Qf(d,s)}catch(p){if(Ge(p)||s?.aborted)return null;throw p}}for(let p=0;p<u.length;p+=1){if(s?.aborted)return null;let h=u[p];try{t.log.info(`Trying fallback model: ${h}`);let _=t._preparedInbound,[b,...y]=h.split(","),w=y.join(","),C={...Lo(_?.unifiedBody||t.unifiedBody||t.body),model:w},v={...t,provider:b,model:w,body:_?.originalBody??t.body,unifiedBody:C,protocolContext:_?.protocolContext,clientProtocol:_?.protocolContext?.protocol,scenarioType:i},A=n.providerService.getProvider(b);if(!A){t.log.warn(`Fallback provider '${b}' not found, skipping`);continue}let T=gc(A,r,_?.protocolContext,w),x=bi(A,r,_?.protocolContext),O=_?.clientWireBody??_?.originalBody,q=T||x?{...typeof O=="object"&&O?Lo(O):{},model:w}:C,{requestBody:$,config:H,bypass:ae}=await iC(q,A,r,t.headers,{req:v,provider:A,signal:s,clientProtocol:_?.protocolContext?.protocol,protocolContext:_?.protocolContext,skipClientNormalization:!0}),X=await aC($,H,A,n,ae,r,{req:v,signal:s,protocolContext:_?.protocolContext}),te=await cC($,X,A,r,ae,{req:v,signal:s,protocolContext:_?.protocolContext});return t.log.info(`Fallback model ${h} succeeded`),await uC(te,e,_?.originalBody??t.body,s,_?.protocolContext?.stream)}catch(_){if(Ge(_))throw _;if(s?.aborted)throw hn(s.reason??bt);if(!ep(_))throw t.log.warn({fallbackModel:h,error:Cr(_)},`Fallback model ${h} failed with a terminal error`),_;if(t.log.warn({fallbackModel:h,error:Cr(_)},`Fallback model ${h} failed`),p<u.length-1){let y=Zf(f,_?.headers?.["Retry-After"]??_?.headers?.["retry-after"]);if(f+=1,y>0){t.log.info(`Waiting ${y}ms before next fallback attempt`);try{await Qf(y,s)}catch(w){if(Ge(w)||s?.aborted)return null;throw w}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function iC(t,e,n,r,o){let s=t,i={},c=gc(e,n,o?.protocolContext,t?.model),u=bi(e,n,o?.protocolContext),f=c||e.transformer?.passthrough||o?.skipClientNormalization===!0;if(c&&(i.headers=Gb(r)),!c&&o?.protocolContext?.protocol==="openai_responses"&&!e.transformer?.use?.some(d=>d?.name==="openai-responses")&&delete s.prompt_cache_key,!f&&typeof n.transformRequestOut=="function"){let d=await n.transformRequestOut(s,o);d.body?(s=d.body,i=d.config||{}):s=d}if(!c&&e.transformer?.use?.length)for(let d of e.transformer.use){if(u&&d?.name===n.name||!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(s,e,o);if(p.body){s=p.body;let h=p.config||{};i={...i,...h,headers:uc(i.headers,h.headers)}}else s=p}if(!c&&e.transformer?.[t.model]?.use?.length)for(let d of e.transformer[t.model].use){if(u&&d?.name===n.name||!d||typeof d.transformRequestIn!="function")continue;let p=await d.transformRequestIn(s,e,o);if(p.body){s=p.body;let h=p.config||{};i={...i,...h,headers:uc(i.headers,h.headers)}}else s=p}return!c&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=cc(s,e,o)),{requestBody:s,config:i,bypass:c}}async function aC(t,e,n,r,o,s,i){if(e?.__providerResponse)return e.__providerResponse;if((o||n.transformer?.passthrough)&&typeof s.auth=="function"){let _=await s.auth(t,n,i);if(_.body){t=_.body;let b=e.headers||{};_.config?.headers&&(b=uc(b,_.config.headers),delete b.host,delete _.config.headers),e={...e,..._.config,headers:b}}else t=_}let c=e.url||new URL(n.baseUrl),u=Tb(e?.headers,n.apiKey),{__authRecovery:f,...d}=e||{},h=await Eb(_=>Uo(c,t,{httpsProxy:r.configService.getHttpsProxy(),...d,headers:JSON.parse(JSON.stringify(_)),signal:i?.signal??d.signal},i,r.log),u,f);if(!h.ok){let _=await h.text(),b=et(_)||_.slice(0,240),y;try{y=JSON.parse(_)}catch{y=void 0}let w=y&&typeof y=="object"?y.error:void 0,C=rp(h.headers),v=Object.keys(C).length>0?C:void 0;if(!v?.["retry-after"]&&h.status===429){let O=w?.details||y?.details;if(Array.isArray(O)){let q=O.find($=>$["@type"]==="type.googleapis.com/google.rpc.RetryInfo");if(q?.retryDelay){let $=parseInt(q.retryDelay,10);isNaN($)||(v={...v||{},"retry-after":$.toString()})}}}let A=typeof w?.message=="string"?w.message:void 0,T=et(A||_)||b;r.log.error({status:h.status,provider:n.name,model:t.model,errorMessage:T,upstreamType:typeof w?.type=="string"?w.type:void 0,upstreamCode:typeof w?.code=="string"?w.code:void 0},`[provider_response_error] ${n.name},${t.model}: ${T}`);let x=W(`Error from provider(${n.name},${t.model}: ${h.status}): ${T}`,h.status,typeof w?.code=="string"?w.code:"provider_response_error","api_error",v);throw x.upstream={status:h.status,statusText:h.statusText,headers:v??{},body:y!==void 0?oc(y):void 0,provider:n.name,model:t.model},x}return h}async function cC(t,e,n,r,o,s){let i=e,c=o||bi(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,u=bi(n,r,s?.protocolContext),f={...s,provider:n};if(!o&&n.transformer?.use?.length)for(let d of Array.from(n.transformer.use).reverse())u&&d?.name===r.name||!d||typeof d.transformResponseOut!="function"||(i=await d.transformResponseOut(i,f));if(!o&&n.transformer?.[t.model]?.use?.length)for(let d of Array.from(n.transformer[t.model].use).reverse())u&&d?.name===r.name||!d||typeof d.transformResponseOut!="function"||(i=await d.transformResponseOut(i,f));return!c&&r.transformResponseIn&&(i=await r.transformResponseIn(i,s)),i}async function uC(t,e,n,r,o){t.ok||e.code(t.status);let s=rp(t.headers);for(let[c,u]of Object.entries(s))e.header(c,u);if((typeof o=="boolean"?o:n?.stream===!0)&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let c=sC.Readable.fromWeb(t.body),u=!1,f=()=>{if(!u){u=!0;try{c.destroyed||c.destroy()}catch{}}},d=()=>{r&&r.removeEventListener("abort",f)};return mb(e)?(f(),!e.sent&&!e.raw.destroyed?(e.type("application/json"),e.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):e):(r?.aborted&&e.log?.warn?.({reason:String(r.reason??""),headersSent:e.raw.headersSent,writableEnded:e.raw.writableEnded},"disconnect signal fired but socket still open; continuing SSE"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&r.addEventListener("abort",f,{once:!0}),e.raw.on("error",h=>{(h?.code==="EPIPE"||h?.code==="ECONNRESET"||h?.code==="ERR_STREAM_PREMATURE_CLOSE"||Ge(h))&&f()}),e.raw.on("close",()=>{e.raw.writableEnded||f()}),c.on("error",h=>{h?.code==="ERR_STREAM_PREMATURE_CLOSE"||h?.code==="ABORT_ERR"||Ge(h)||e.log?.error?.(Cr(h),"upstream stream error")}),c.once("end",d),c.once("close",d),e.send(c))}if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),t.body&&typeof t.body.pipe=="function")return e.send(t.body);throw W("Streaming response body is not a readable stream",502,"provider_response_error")}else{let c=await t.json();return e.send(c)}}var lp=async t=>{let e={config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",c=wr(s.method,i);s.pathname=i,c&&(s.protocolMatch=c,s.clientProtocol=c.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:bb})),t.get("/health",e,async()=>({status:"ok",timestamp:new Date().toISOString()}));let n=t.transformerService.getAllTransformers(),r=s=>{let i=n.get(s);if(i){if(typeof i=="object")return i;try{let c=new i;return c&&typeof c=="object"&&(c.logger=t.log),c}catch{return}}},o=new Set;for(let s of lc()){let i=r(s.ownerTransformerName);if(!i){t.log.warn(`protocol route ${s.path}: owner transformer '${s.ownerTransformerName}' not found`);continue}for(let c of[s.path,`${s.path}/`])o.has(c)||(o.add(c),t.post(c,e,async(u,f)=>Mx(u,f,t,i,c)))}t.post("/providers",{config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}},schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(s,i)=>{let{name:c,baseUrl:u,apiKey:f,models:d}=s.body;if(!c?.trim())throw W("Provider name is required",400,"invalid_request");if(!u||!Ux(u))throw W("Valid base URL is required",400,"invalid_request");if(!f?.trim())throw W("API key is required",400,"invalid_request");if(!d||!Array.isArray(d)||d.length===0)throw W("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(s.body.name))throw W(`Provider with name '${s.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(s.body)}),t.get("/providers",e,async()=>t.providerService.getProviders()),t.get("/providers/:id",{config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{let i=t.providerService.getProvider(s.params.id);if(!i)throw W("Provider not found",404,"provider_not_found");return i}),t.put("/providers/:id",{config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(s,i)=>{let c=t.providerService.updateProvider(s.params.id,s.body);if(!c)throw W("Provider not found",404,"provider_not_found");return c}),t.delete("/providers/:id",{config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{if(!t.providerService.deleteProvider(s.params.id))throw W("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{config:{rateLimit:{...Zr.RATE_LIMIT_CONFIG}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(s,i)=>{if(!t.providerService.toggleProvider(s.params.id,s.body.enabled))throw W("Provider not found",404,"provider_not_found");return{message:`Provider ${s.body.enabled?"enabled":"disabled"} successfully`}})};function Ux(t){try{return new URL(t),!0}catch{return!1}}var eo=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}configService;transformerService;logger;providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let i=`${r.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let i=`${r.name},${s}`,c={provider:r.name,model:s,fullModel:i};this.modelRoutes.set(i,c),this.modelRoutes.has(s)||this.modelRoutes.set(s,c)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var ct=[];for(let t=0;t<256;++t)ct.push((t+256).toString(16).slice(1));function lC(t,e=0){return(ct[t[e+0]]+ct[t[e+1]]+ct[t[e+2]]+ct[t[e+3]]+"-"+ct[t[e+4]]+ct[t[e+5]]+"-"+ct[t[e+6]]+ct[t[e+7]]+"-"+ct[t[e+8]]+ct[t[e+9]]+"-"+ct[t[e+10]]+ct[t[e+11]]+ct[t[e+12]]+ct[t[e+13]]+ct[t[e+14]]+ct[t[e+15]]).toLowerCase()}var jx=new Uint8Array(16);function dp(){return crypto.getRandomValues(jx)}function Lx(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():qx(t,e,n)}function qx(t,e,n){t=t||{};let r=t.random??t.rng?.()??dp();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return lC(r)}var mn=Lx;var dC=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var fp=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function $x(t){if(typeof t!="string")return!1;let e=t.trim();return fp.some(n=>e===n)}function zx(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.filter(n=>n?.type==="text"&&typeof n.text=="string"&&n.text.length>0).map(n=>n.text).join(`
106
+ `);if(e)return e}return JSON.stringify(t)??""}function Hx(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function Wx(t){let e={source:"anthropic",trailingToolResults:[],interruption:"none",steering:"none"};if(!Array.isArray(t)||t.length===0)return e;let n=t[t.length-1];if(n?.role!=="user")return e;if(typeof n.content=="string")return n.content.trim()&&(e.steering="meaningful"),e;if(!Array.isArray(n.content))return e;let r=n.content.some(o=>o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0);for(let o of n.content){if(o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0){e.trailingToolResults.push({toolCallId:o.tool_use_id,content:zx(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&$x(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}Hx(o)&&(e.steering="meaningful")}return e}function Gx(t){let e=t&&typeof t=="object"&&typeof t.user_id=="string"?t.user_id:void 0;if(!e)return;try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}return e.split("_session_")[1]||e}function fC(t){return{source:"anthropic",sourceSessionIdentity:Gx(t.metadata),turnIntent:Wx(t.messages)}}var Hn=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
107
+ `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var to=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
108
+ `),e.id&&(r+=`id: ${e.id}
109
+ `),e.retry&&(r+=`retry: ${e.retry}
110
+ `),e.data&&(e.data.type==="done"?r+=`data: [DONE]
111
+ `:r+=`data: ${JSON.stringify(e.data)}
112
+ `),r+=`
113
+ `,n.enqueue(r)}})}};var pp=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let i=await e(s,r);i!==void 0&&r.enqueue(i)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};function Jx(t){if(Ge(t)||!Yr(t))return t;let e=t;if(e&&typeof e=="object"&&e.code==="provider_network_error")return e;let n=String(e?.cause?.message||e?.cause?.code||"").trim(),r=String(e?.message||"Upstream stream failed"),o=new Error(n&&!r.includes(n)?`Upstream stream terminated: ${r} (${n})`:`Upstream stream terminated: ${r}`);return Object.assign(o,{type:"api_error",code:"provider_network_error",cause:e})}function Ie(t,e,n){let r=new TextEncoder,o=!1,s=null,i=!1,c=new ReadableStream({async start(u){if(!t.body){u.close();return}let f={controller:u,encoder:r};try{let d=t.body.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).pipeThrough(new to).getReader();for(s=d;!i;){let{done:p,value:h}=await d.read();if(p)break;if(!h)continue;let _=h.split(`
114
+ `);for(let b of _)if(b.trim())try{e(b,f)}catch(y){(n?.logger?.error??console.error)("Error processing line:",b,y),u.enqueue(r.encode(b+`
115
+ `))}}}catch(d){if(!i){let p=Jx(d);(n?.logger?.error??console.error)("Stream error:",p);let h=!1;try{h=n?.onError?.(p,f)===!0}catch(_){(n?.logger?.error??console.error)("Stream error handler failed:",_)}o=!h,h||u.error(p)}}finally{s=null;try{n?.onComplete?.(f)}catch(d){(n?.logger?.error??console.error)("Stream completion error:",d),o||(o=!0,u.error(d))}o||u.close()}},cancel:async u=>{i=!0;let f=s;s=null,f&&await f.cancel(u).catch(()=>{})}});return new Response(c,{status:t.status,statusText:t.statusText,headers:{...Ab(t.headers),"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function Ee(t,e){return e.encode(`data: ${t}
83
116
 
84
- `)),f=null;else{let re={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0};j>0&&(re.server_tool_use={web_search_requests:j}),U(c.encode(`event: message_delta
85
- data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:re})}
117
+ `)}function Re(t,e){return e.encode(t+`
118
+ `)}var yc=tt(vC(),1),dD={STOP:"stop",MAX_TOKENS:"length",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter"},hp="\u26A0\uFE0F Upstream ended the turn without a reply";function Ci(t){return t?dD[t.toUpperCase()]||t.toLowerCase():null}function mp(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${hp} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var _c=class{constructor(e){this.emit=e}emit;_hasThinking=!1;_sigSent=!1;_contentSent=!1;_buffer="";processThinking(e,n){this._hasThinking=!0,this.emit.thinking(e,n)}processSignature(e,n){this.processSignatureWithMeta(e,n)}processSignatureWithMeta(e,n,r){if(!this._sigSent){if(this._contentSent){this._sigSent=!0;return}this._hasThinking||(this._hasThinking=!0,this.emit.thinking("(no content)",n)),this._sigSent=!0,this.emit.signature(e,n),r?.beforeFlush?.(),this.flushBufferedContent(r?.flushMeta)}}processContent(e,n,r){this._sigSent||!this._hasThinking?(this._contentSent=!0,this.emit.content(e,{chunk:n,candidate:r,mode:"direct"})):this._buffer+=e}emitContentPlaceholder(e,n){this._contentSent=!0,this.emit.content(e,{chunk:n?.chunk,candidate:n?.candidate,mode:"placeholder",finishReason:n?.finishReason})}bufferContent(e){this._buffer+=e}finalize(e,n,r){if(this._hasThinking&&!this._sigSent){this.processSignatureWithMeta(`ccr_${Date.now()}`,e,{beforeFlush:r?.beforeFlush,flushMeta:{chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Ci(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Ci(n?.finishReason)})}flushBufferedContent(e){this._buffer&&(this._contentSent=!0,this.emit.content(this._buffer,{chunk:e?.chunk,candidate:e?.candidate,mode:e?.mode||"buffered",finishReason:e?.finishReason}),this._buffer="")}shouldDeferContent(e,n){return this._hasThinking&&!this._sigSent&&!e&&!n}get hasBufferedContent(){return this._buffer.length>0}get hasThinkingContent(){return this._hasThinking}get signatureSent(){return this._sigSent}get contentSent(){return this._contentSent}get needsContentPlaceholder(){return this._sigSent&&!this._contentSent}acknowledgeSignature(){this._sigSent=!0}};function bc(t,e){return e[t]||t}function Cc(t){return!t||typeof t=="string"?[]:t.filter(e=>e.type==="image_url").map(e=>({url:e.image_url.url,mediaType:e.media_type||"image/jpeg",isBase64:e.image_url.url.startsWith("data:")}))}function wc(t,e){if(t.length===0)return[];let n=[];for(let r of t){let o=n[n.length-1];if(o&&o.role===r.role){let s=o[e],i=r[e];Array.isArray(s)&&Array.isArray(i)&&s.push(...i)}else n.push({...r})}return n}function zo(t){return t.function?.name?{name:t.function.name,description:t.function.description,parameters:t.function.parameters}:{name:t.name,description:t.description,parameters:t.input_schema}}function kc(t,e){if(e==="gemini")return t.isBase64?{inlineData:{mimeType:t.mediaType,data:t.url.split(",").pop()||t.url}}:{fileData:{mimeType:t.mediaType,fileUri:t.url}};if(e==="claude")return{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.url.startsWith("data:")&&t.url.split(",").pop()||t.url}};throw new Error(`Unsupported provider for image processing: ${e}`)}function wi(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof yc.default=="function"?yc.default:yc.default.default;if(typeof e!="function")return t;let n=/(\$\$?[\s\S]+?\$\$?|\\\(?:[\s\S]+?\\\)|\\\[[\s\S]+?\\\]|\\(?:[a-zA-Z]+))/g;return t.replace(n,r=>{let o=r,s;do s=o,o=e(o);while(o!==s);return o.replace(/\$([^$]+)\$/g,"$1")})}catch{return t}}function AC(t){if(!t)return"unnamed_function";let e=t.replace(/[^a-zA-Z0-9_.:-]/g,"_");return/^[^a-zA-Z_]/.test(e)&&(e="_"+e),e.substring(0,128)}function Er(t){let e=t?.input_tokens||0,n=t?.cache_read_input_tokens||0,r=t?.cache_creation_input_tokens||0,o=t?.output_tokens||0;return{completion_tokens:o,prompt_tokens:e+n+r,prompt_tokens_details:{cached_tokens:n,cache_write_tokens:r},total_tokens:e+n+r+o}}function gp(t){switch(t){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"stop_sequence":case"pause_turn":return"stop";default:return typeof t=="string"&&t?"stop":null}}function TC(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=bc(s.role,{assistant:"assistant"}),c=[];if(s.role==="tool"){let u=s.content;Array.isArray(u)?u=u.filter(f=>f.type==="text").map(f=>f.text).join(`
119
+ `):typeof u=="object"&&u!==null&&(u=JSON.stringify(u)),c.push({type:"tool_result",tool_use_id:s.tool_call_id,content:u,...s.cache_control?{cache_control:s.cache_control}:{}})}else typeof s.content=="string"?c.push({type:"text",text:s.content,...s.cache_control?{cache_control:s.cache_control}:{}}):Array.isArray(s.content)&&(s.content.forEach(f=>{f.type==="text"&&c.push({type:"text",text:f.text||"",...f.cache_control?{cache_control:f.cache_control}:{}})}),Cc(s.content).forEach(f=>{c.push(kc(f,"claude"))})),s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(u=>{c.push({type:"tool_use",id:u.id,name:u.function.name,input:JSON.parse(u.function.arguments||"{}")})});c.length>0&&e.push({role:i,content:c})}let r={anthropic_version:"vertex-2023-10-16",messages:wc(e,"content"),max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(o=>{let s=zo(o);return{name:s.name,description:s.description,input_schema:s.parameters,...o.cache_control?{cache_control:o.cache_control}:{}}})),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),Xr(r)}function RC(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(i=>i.type==="text"?{type:"text",text:i.text||""}:i.type==="image"&&i.source?{type:"image_url",image_url:{url:i.source.data},media_type:i.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function Sc(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o=Array.isArray(r.content)?r.content:[],s=o.filter(h=>h?.type==="text"&&typeof h.text=="string").map(h=>h.text),i=o.find(h=>h?.type==="thinking"&&typeof h.thinking=="string"),c,u=o.filter(h=>h?.type==="tool_use");u.length>0?c=u.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})):Array.isArray(r.tool_use)&&r.tool_use.length>0&&(c=r.tool_use.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})));let f=gp(r.stop_reason),d={role:"assistant",content:s.length>0?s.join(""):null,...c&&{tool_calls:c}};i&&(d.thinking={content:i.thinking,signature:i.signature});let p={id:r.id,choices:[{finish_reason:f,index:0,message:d}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:Er(r.usage)};return new Response(JSON.stringify(p),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r={},o="",s="",i=new Map;return Ie(t,(u,f)=>{let{controller:d,encoder:p}=f;if(u.startsWith("data: ")){let h=u.slice(6).trim();if(h){n?.debug({chunkStr:h},`${e} chunk:`);try{let _=JSON.parse(h);if(_.type==="message_start"){r=_.message?.usage||_.usage||{},o=_.message?.id||_.id||o,s=_.message?.model||_.model||s;let b={choices:[{delta:{role:"assistant"},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:o,model:s,object:"chat.completion.chunk"};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
86
120
 
87
- `))}let te={type:"message_stop"};U(c.encode(`event: message_stop
88
- data: ${JSON.stringify(te)}
121
+ `))}else if(_.type==="content_block_delta"&&_.delta?.type==="text_delta"){let b={choices:[{delta:{role:"assistant",content:_.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
89
122
 
90
- `)),a.close(),k=!0}catch(te){if(te instanceof TypeError&&te.message.includes("Controller is already closed"))k=!0;else throw te}},Y=te=>{if(!k)try{R>=0&&(U(c.encode(`event: content_block_stop
91
- data: ${JSON.stringify({type:"content_block_stop",index:R})}
123
+ `))}else if(_.type==="content_block_delta"&&_.delta?.type==="input_json_delta"){let b={choices:[{delta:{tool_calls:[{index:i.get(Number(_.index||0))??Number(_.index||0),function:{arguments:_.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
92
124
 
93
- `)),R=-1);let re=te&&typeof te=="object"?te:{},K=typeof re.type=="string"?re.type:"api_error",se=te instanceof Error?te.message:typeof re.message=="string"?re.message:String(te||"Upstream stream failed");U(c.encode(`event: error
94
- data: ${JSON.stringify({type:"error",error:{type:K,message:se}})}
125
+ `))}else if(_.type==="content_block_delta"&&_.delta?.type==="thinking_delta"){let b={choices:[{delta:{thinking:{content:_.delta.thinking||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
95
126
 
96
- `)),a.close(),k=!0}catch(re){try{a.error(re)}catch(K){this.logger?.error(K)}}},ne=null;try{ne=e.getReader(),r=ne;let te=new TextDecoder,re="";for(;!k;){let{done:K,value:se}=await ne.read();if(K)break;re+=te.decode(se,{stream:!0});let ie=re.split(`
97
- `);re=ie.pop()||"";for(let X of ie){if(k||S)break;if(!X.startsWith("data:"))continue;let Z=X.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:Z}),Z!=="[DONE]")try{let Q=JSON.parse(Z);if(b++,this.logger.debug({reqId:n.req.id,response:Q,tppe:"Original Response"}),Q.error){let he={type:"error",message:{type:"api_error",message:JSON.stringify(Q.error)}};U(c.encode(`event: error
98
- data: ${JSON.stringify(he)}
127
+ `))}else if(_.type==="content_block_delta"&&_.delta?.type==="signature_delta"){let b={choices:[{delta:{thinking:{signature:_.delta.signature||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
99
128
 
100
- `));continue}if(d=Q.model||d,!h&&!k&&!S){h=!0;let he={type:"message_start",message:{id:l,type:"message",role:"assistant",content:[],model:d,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}};U(c.encode(`event: message_start
101
- data: ${JSON.stringify(he)}
129
+ `))}else if(_.type==="content_block_start"&&_.content_block?.type==="tool_use"){let b=Number(_.index||0),y=i.size;i.set(b,y);let w={choices:[{delta:{tool_calls:[{index:y,id:_.content_block.id,type:"function",function:{name:_.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(w)}
102
130
 
103
- `))}let me=Q.choices?.[0];if(Q.usage&&(f?f.usage=Oa(Q.usage):f={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Oa(Q.usage)}),!me)continue;if(me?.delta?.thinking&&!k&&!S){if(R>=0&&!v){let he={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
104
- data: ${JSON.stringify(he)}
131
+ `))}else if(_.type==="message_delta"){let b={choices:[{delta:{},finish_reason:gp(_.delta?.stop_reason)||"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:Er({...r,..._.usage})};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
105
132
 
106
- `)),R=-1,m=!1}if(!v){let he=W(),z={type:"content_block_start",index:he,content_block:{type:"thinking",thinking:""}};U(c.encode(`event: content_block_start
107
- data: ${JSON.stringify(z)}
133
+ `))}else if(_.type==="message_stop")d.enqueue(p.encode(`data: [DONE]
108
134
 
109
- `)),R=he,v=!0}if(me.delta.thinking.signature){let he={type:"content_block_delta",index:R,delta:{type:"signature_delta",signature:me.delta.thinking.signature}};U(c.encode(`event: content_block_delta
110
- data: ${JSON.stringify(he)}
135
+ `));else{if(_.type==="content_block_start"||_.type==="content_block_stop"||_.type==="ping")return;{let b={choices:[{delta:{role:"assistant",content:_.content?.[0]?.text||""},finish_reason:gp(_.stop_reason),index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_.id||o,model:_.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",..._.usage?{usage:Er(_.usage)}:{}};d.enqueue(p.encode(`data: ${JSON.stringify(b)}
111
136
 
112
- `));let z={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
113
- data: ${JSON.stringify(z)}
137
+ `))}}}catch(_){n?.error(`Error parsing ${e} stream chunk`,h,_.message)}}}})}return t}var fD={"claude-3-5-haiku":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-haiku-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-3-5-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-3-7-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:32e3,upper:64e3},capabilities:[]},"claude-sonnet-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-sonnet-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management"]},"claude-opus-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-1":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-opus-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-opus-4-7":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"xhigh",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","context_management","fast_mode"]},"claude-opus-4-8":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt"]},"claude-opus-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt","refusal_fallback","opus_5_prompt_bundle"]},"claude-fable-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","rejects_disabled_thinking","mid_conv_system","context_management","lean_prompt","fable_5_mitigations","refusal_fallback"]},"claude-mythos-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},capabilities:[]}},yp=/\[1m\]/gi;function ki(t){let e=t||"",n=yp.test(e);return yp.lastIndex=0,{modelId:e.replace(yp,""),requestedOneMillion:n}}function pD(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=ki(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function _p(t){let e=pD(t);if(e)return fD[e]}function bp(t,e){return t?.capabilities.includes(e)??!1}function xC(t){return(t?.capabilities.length??0)>0}function DC(t){let e=new URL(t||"https://api.anthropic.com"),n=e.pathname.replace(/\/$/,"");return n.endsWith("/v1/messages")||(e.pathname=`${n}/v1/messages`.replace(/\/+/g,"/")),e.searchParams.set("beta","true"),e.toString()}function Ec(t){let e=t?.prompt_tokens_details?.cached_tokens||0,n=t?.prompt_tokens_details?.cache_write_tokens||0;return{input_tokens:Math.max(0,(t?.prompt_tokens||0)-e-n),output_tokens:t?.completion_tokens||0,cache_creation_input_tokens:n,cache_read_input_tokens:e}}var vc=class t{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}options;name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n,r){let o={};return this.useBearer?(o.Authorization=`Bearer ${n.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=n.apiKey,o.Authorization=void 0),{body:r?.protocolContext?.anthropicCacheMode==="preserve"?e:Xr(e),config:{url:DC(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,r);o.model=ki(o.model).modelId,r?.claudeAuthPostBuildHook?.(o);let s=DC(n?.baseUrl),i={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return!n?.transformer?.use?.some(u=>u?.name==="claude-auth")&&(this.useBearer?(i.Authorization=`Bearer ${n.apiKey}`,i["x-api-key"]=void 0):(i["x-api-key"]=n.apiKey,i.Authorization=void 0)),{body:o,config:{url:s,headers:i}}}async transformResponseOut(e,n){return Sc(e,this.name,this.logger)}async transformRequestOut(e,n){n&&(n.unifiedRequest=fC(e));let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let u=e.system.filter(f=>f.type==="text"&&f.text).map(f=>({type:"text",text:f.text,cache_control:f.cache_control}));r.push({role:"system",content:u})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(u=>{if(u.role==="user"||u.role==="assistant"){if(typeof u.content=="string"){r.push({role:u.role,content:u.content});return}if(Array.isArray(u.content)){if(u.role==="user"){let f=u.content.filter(p=>p.type==="tool_result"&&p.tool_use_id);f.length&&f.forEach(p=>{let h={role:"tool",content:typeof p.content=="string"?p.content:Array.isArray(p.content)&&p.content.filter(_=>_.type==="text"&&_.text).map(_=>_.text).join(`
138
+ `)||JSON.stringify(p.content),tool_call_id:$n(p.tool_use_id)??p.tool_use_id,cache_control:p.cache_control};r.push(h)});let d=u.content.filter(p=>p.type==="text"&&p.text||p.type==="image"&&p.source);d.length&&r.push({role:"user",content:d.map(p=>p?.type==="image"?{type:"image_url",image_url:{url:p.source?.type==="base64"?dC(p.source.data,p.source.media_type):p.source.url},media_type:p.source.media_type,cache_control:p.cache_control}:p)})}else if(u.role==="assistant"){let f={role:"assistant",content:""},d=u.content.filter(_=>_.type==="text"&&_.text);d.length&&(f.content=d.some(_=>_.cache_control)?d.map(_=>({type:"text",text:_.text,cache_control:_.cache_control})):d.map(_=>_.text).join(`
139
+ `));let p=u.content.filter(_=>_.type==="tool_use"&&_.id);p.length&&(f.tool_calls=p.map(_=>({id:$n(_.id)??_.id,type:"function",function:{name:_.name,arguments:JSON.stringify(_.input||{})},cache_control:_.cache_control})));let h=u.content.find(_=>_.type==="thinking"&&_.signature);h&&(f.thinking={content:h.thinking,signature:h.signature}),r.push(f)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice,...e.cache_control?{cache_control:e.cache_control}:{}};e.thinking&&(s.reasoning={effort:e.output_config?.effort||e.effort,enabled:e.thinking.type==="enabled"||e.thinking.type==="adaptive",...typeof e.thinking.budget_tokens=="number"?{max_tokens:e.thinking.budget_tokens}:{}});let i=n?.protocolContext;return i?.protocol==="anthropic_messages"&&(i.anthropicCacheMode="preserve",i.anthropicSource={...e.metadata?{metadata:JSON.parse(JSON.stringify(e.metadata))}:{},...e.thinking?{thinking:JSON.parse(JSON.stringify(e.thinking))}:{},...e.output_config?{outputConfig:JSON.parse(JSON.stringify(e.output_config))}:{},...e.stop_sequences?{stopSequences:[...e.stop_sequences]}:{}}),Array.isArray(n?.provider?.transformer?.use)&&n.provider.transformer.use.some(u=>u?.name==="claude-auth")&&(e.thinking&&(s.anthropic_thinking=e.thinking),e.output_config&&(s.anthropic_output_config=e.output_config),e.metadata&&(s.anthropic_metadata=e.metadata),e.stop_sequences&&(s.anthropic_stop_sequences=e.stop_sequences)),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:s.tool_choice=e.tool_choice.type),s}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}static buildAnthropicBody(e,n,r){let o=[],s=h=>{if(typeof h=="string"){h&&o.push({type:"text",text:h});return}if(Array.isArray(h))for(let _ of h)_?.type==="text"&&_.text&&o.push({type:"text",text:_.text,..._.cache_control?{cache_control:_.cache_control}:{}})};e.system&&s(e.system);let i=[];for(let h of e.messages){if(h.role==="system"||h.role==="developer"){s(h.content);continue}if(h.role==="tool"){let _={type:"tool_result",tool_use_id:$n(h.tool_call_id)??h.tool_call_id,content:typeof h.content=="string"?h.content:Array.isArray(h.content)?h.content.filter(y=>y?.type==="text").map(y=>({type:"text",text:y.text||"",...y.cache_control?{cache_control:y.cache_control}:{}})):JSON.stringify(h.content),...h.cache_control?{cache_control:h.cache_control}:{}},b=i[i.length-1];b?.role==="user"&&Array.isArray(b.content)?b.content.push(_):i.push({role:"user",content:[_]});continue}if(h.role==="assistant"){let _=[];if(h.thinking&&_.push({type:"thinking",thinking:h.thinking.content,signature:h.thinking.signature}),typeof h.content=="string"&&h.content)_.push({type:"text",text:h.content});else if(Array.isArray(h.content))for(let b of h.content)b.type==="text"&&b.text&&_.push({type:"text",text:b.text,...b.cache_control?{cache_control:b.cache_control}:{}});if(h.tool_calls?.length)for(let b of h.tool_calls){let y={};try{y=JSON.parse(b.function.arguments||"{}")}catch(w){(n?.error??console.error)("Failed to parse tool_call arguments for tool '%s': %s",b.function.name,w)}_.push({type:"tool_use",id:$n(b.id)??b.id,name:b.function.name,input:y,...b.cache_control?{cache_control:b.cache_control}:{}})}_.length>0&&i.push({role:"assistant",content:_});continue}if(h.role==="user"){let _=[];if(typeof h.content=="string")_.push({type:"text",text:h.content});else if(Array.isArray(h.content)){for(let b of h.content)if(b.type==="text"&&b.text)_.push({type:"text",text:b.text,...b.cache_control?{cache_control:b.cache_control}:{}});else if(b.type==="image_url"&&b.image_url?.url){let y=b.image_url.url;if(y.startsWith("data:")){let[w,C]=y.split(","),v=w.split(":")[1]?.split(";")[0]??"image/jpeg";_.push({type:"image",source:{type:"base64",media_type:v,data:C},...b.cache_control?{cache_control:b.cache_control}:{}})}else _.push({type:"image",source:{type:"url",url:y},...b.cache_control?{cache_control:b.cache_control}:{}})}}_.length>0&&i.push({role:"user",content:_});continue}}let c;if(e.tools?.length){let h=e.tools.find(_=>_?.type!=="function"||!_?.function);if(h)throw W(`Tool type '${h?.type||"unknown"}' cannot be represented by Anthropic Messages`,400,"unsupported_hosted_tool","invalid_request_error");c=e.tools.map(_=>({name:_.function.name,description:_.function.description||"",input_schema:_.function.parameters,..._.cache_control?{cache_control:_.cache_control}:{}}))}let u;if(e.tool_choice){let h=e.tool_choice;h==="auto"?u={type:"auto"}:h==="required"?u={type:"any"}:typeof h=="string"?u={type:"tool",name:h}:h.type==="function"&&(u={type:"tool",name:h.function?.name})}let f=o.length===1&&!o[0].cache_control?o[0].text:o.length>0?o:void 0,d={model:e.model,max_tokens:e.max_tokens??8192,messages:i,stream:e.stream??!0};f!==void 0&&(d.system=f),e.temperature!==void 0&&(d.temperature=e.temperature),e.top_p!==void 0&&(d.top_p=e.top_p),e.stop!==void 0&&(d.stop_sequences=Array.isArray(e.stop)?e.stop:[e.stop]),e.tool_choice!=="none"&&c?.length&&(d.tools=c),e.tool_choice!=="none"&&u&&(d.tool_choice=u);let p=r?.protocolContext?.anthropicSource;return p?.thinking?d.thinking=p.thinking:e.anthropic_thinking?d.thinking=e.anthropic_thinking:(e.reasoning?.enabled||e.reasoning?.effort)&&(d.thinking={type:"adaptive"}),p?.outputConfig?d.output_config=p.outputConfig:e.anthropic_output_config?d.output_config=e.anthropic_output_config:e.reasoning?.effort&&(d.output_config={effort:e.reasoning.effort}),p?.metadata?d.metadata=p.metadata:e.anthropic_metadata&&(d.metadata=e.anthropic_metadata),p?.stopSequences?d.stop_sequences=p.stopSequences:e.anthropic_stop_sequences&&(d.stop_sequences=e.anthropic_stop_sequences),e.cache_control&&(d.cache_control=e.cache_control),r?.protocolContext?.anthropicCacheMode==="preserve"?d:Xr(d)}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema},...n.cache_control?{cache_control:n.cache_control}:{}}))}async convertOpenAIStreamToAnthropic(e,n){let r=null,o=null;return new ReadableStream({start:async i=>{let c=new TextEncoder,u=`msg_${Date.now()}`,f=null,d="unknown",p=!1,h=!1,_=!1,b=new Map,y=new Map,w=0,C=0,v=!1;o=()=>{v=!0};let A=!1,T=0,x=-1,O=0,q=()=>{let te=T;return T++,te},$=te=>{if(!v)try{i.enqueue(te);let Z=new TextDecoder().decode(te);this.logger.debug({reqId:n.req.id,data:Z,type:"send data"})}catch(Z){if(Z instanceof TypeError&&Z.message.includes("Controller is already closed"))v=!0;else throw this.logger.debug({reqId:n.req.id,error:Z instanceof Error?Z.message:String(Z),type:"send data error"}),Z}},H=()=>{if(!v)try{if(x>=0){let Z={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
140
+ data: ${JSON.stringify(Z)}
114
141
 
115
- `)),R=-1,v=!1}else if(me.delta.thinking.content){let he={type:"content_block_delta",index:R,delta:{type:"thinking_delta",thinking:me.delta.thinking.content||""}};U(c.encode(`event: content_block_delta
116
- data: ${JSON.stringify(he)}
142
+ `)),x=-1}if(f)O>0&&(f.usage.server_tool_use={web_search_requests:O}),$(c.encode(`event: message_delta
143
+ data: ${JSON.stringify(f)}
117
144
 
118
- `))}}if(me?.delta?.content&&!k&&!S){if(_++,R>=0&&!m){let z={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
119
- data: ${JSON.stringify(z)}
145
+ `)),f=null;else{let Z={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0};O>0&&(Z.server_tool_use={web_search_requests:O}),$(c.encode(`event: message_delta
146
+ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Z})}
147
+
148
+ `))}let te={type:"message_stop"};$(c.encode(`event: message_stop
149
+ data: ${JSON.stringify(te)}
120
150
 
121
- `)),R=-1,v=!1}if(!m&&!S){m=!0;let he=W(),z={type:"content_block_start",index:he,content_block:{type:"text",text:""}};U(c.encode(`event: content_block_start
122
- data: ${JSON.stringify(z)}
151
+ `)),i.close(),v=!0}catch(te){if(te instanceof TypeError&&te.message.includes("Controller is already closed"))v=!0;else throw te}},ae=te=>{if(!v)try{x>=0&&($(c.encode(`event: content_block_stop
152
+ data: ${JSON.stringify({type:"content_block_stop",index:x})}
123
153
 
124
- `)),R=he}if(!k&&!S){let he={type:"content_block_delta",index:R,delta:{type:"text_delta",text:me.delta.content}};U(c.encode(`event: content_block_delta
125
- data: ${JSON.stringify(he)}
154
+ `)),x=-1);let Z=te&&typeof te=="object"?te:{},De=typeof Z.type=="string"?Z.type:"api_error",qe=te instanceof Error?te.message:typeof Z.message=="string"?Z.message:String(te||"Upstream stream failed");$(c.encode(`event: error
155
+ data: ${JSON.stringify({type:"error",error:{type:De,message:qe}})}
126
156
 
127
- `))}}if(me?.delta?.annotations?.length&&!k&&!S){if(j+=me.delta.annotations.length,R>=0&&m){let he={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
128
- data: ${JSON.stringify(he)}
157
+ `)),i.close(),v=!0}catch(Z){try{i.error(Z)}catch(De){this.logger?.error(De)}}},X=null;try{X=e.getReader(),r=X;let te=new TextDecoder,Z="";for(;!v;){let{done:De,value:qe}=await X.read();if(De)break;Z+=te.decode(qe,{stream:!0});let Te=Z.split(`
158
+ `);Z=Te.pop()||"";for(let We of Te){if(v||_)break;if(!We.startsWith("data:"))continue;let ee=We.slice(5).trim();if(this.logger.debug({reqId:n.req.id,type:"recieved data",data:ee}),ee!=="[DONE]")try{let Q=JSON.parse(ee);if(this.logger.debug({reqId:n.req.id,response:Q,tppe:"Original Response"}),Q.error){let le={type:"error",message:{type:"api_error",message:JSON.stringify(Q.error)}};$(c.encode(`event: error
159
+ data: ${JSON.stringify(le)}
129
160
 
130
- `)),R=-1,m=!1}me?.delta?.annotations.forEach(he=>{let z=W(),ge={type:"content_block_start",index:z,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${dn()}`,content:[{type:"web_search_result",title:he.url_citation.title,url:he.url_citation.url}]}};U(c.encode(`event: content_block_start
131
- data: ${JSON.stringify(ge)}
161
+ `));continue}if(d=Q.model||d,!p&&!v&&!_){p=!0;let le={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:d,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}};$(c.encode(`event: message_start
162
+ data: ${JSON.stringify(le)}
132
163
 
133
- `));let Fe={type:"content_block_stop",index:z};U(c.encode(`event: content_block_stop
134
- data: ${JSON.stringify(Fe)}
164
+ `))}let se=Q.choices?.[0];if(Q.usage&&(f?f.usage=Ec(Q.usage):f={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Ec(Q.usage)}),!se)continue;if(se?.delta?.thinking&&!v&&!_){if(x>=0&&!A){let le={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
165
+ data: ${JSON.stringify(le)}
135
166
 
136
- `)),R=-1})}if(me?.delta?.tool_calls&&!k&&!S){D++;let he=new Set;for(let z of me.delta.tool_calls){if(k)break;let ge=z.index??0;if(he.has(ge))continue;if(he.add(ge),!w.has(ge)){if(R>=0){let T={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
137
- data: ${JSON.stringify(T)}
167
+ `)),x=-1,h=!1}if(!A){let le=q(),be={type:"content_block_start",index:le,content_block:{type:"thinking",thinking:""}};$(c.encode(`event: content_block_start
168
+ data: ${JSON.stringify(be)}
138
169
 
139
- `)),R=-1}let xe=W();w.set(ge,xe);let ye=z.id||`call_${Date.now()}_${ge}`,be=z.function?.name||`tool_${ge}`,C={type:"content_block_start",index:xe,content_block:{type:"tool_use",id:ye,name:be,input:{}}};U(c.encode(`event: content_block_start
140
- data: ${JSON.stringify(C)}
170
+ `)),x=le,A=!0}if(se.delta.thinking.signature){let le={type:"content_block_delta",index:x,delta:{type:"signature_delta",signature:se.delta.thinking.signature}};$(c.encode(`event: content_block_delta
171
+ data: ${JSON.stringify(le)}
141
172
 
142
- `)),R=xe;let E={id:ye,name:be,arguments:"",contentBlockIndex:xe};y.set(ge,E)}else if(z.id&&z.function?.name){let xe=y.get(ge);xe.id.startsWith("call_")&&xe.name.startsWith("tool_")&&(xe.id=z.id,xe.name=z.function.name)}if(z.function?.arguments&&!k&&!S){let xe=w.get(ge);if(xe===void 0)continue;let ye=y.get(ge);ye&&(ye.arguments+=z.function.arguments);try{let be={type:"content_block_delta",index:xe,delta:{type:"input_json_delta",partial_json:z.function.arguments}};U(c.encode(`event: content_block_delta
173
+ `));let be={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
143
174
  data: ${JSON.stringify(be)}
144
175
 
145
- `))}catch{try{let be=z.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),C={type:"content_block_delta",index:xe,delta:{type:"input_json_delta",partial_json:be}};U(c.encode(`event: content_block_delta
146
- data: ${JSON.stringify(C)}
176
+ `)),x=-1,A=!1}else if(se.delta.thinking.content){let le={type:"content_block_delta",index:x,delta:{type:"thinking_delta",thinking:se.delta.thinking.content||""}};$(c.encode(`event: content_block_delta
177
+ data: ${JSON.stringify(le)}
147
178
 
148
- `))}catch(be){this.logger?.error(be)}}}}}if(me?.finish_reason&&!k&&!S){if(_===0&&D===0&&this.logger?.warn("No content in the stream response!"),R>=0){let he={type:"content_block_stop",index:R};U(c.encode(`event: content_block_stop
149
- data: ${JSON.stringify(he)}
179
+ `))}}if(se?.delta?.content&&!v&&!_){if(w++,x>=0&&!h){let be={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
180
+ data: ${JSON.stringify(be)}
150
181
 
151
- `)),R=-1}if(!k){let z={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[me.finish_reason]||"end_turn";w.size>0&&z==="end_turn"&&(z="tool_use"),f={type:"message_delta",delta:{stop_reason:z,stop_sequence:null},usage:Oa(Q.usage)}}break}}catch(Q){this.logger?.error(`parseError: ${Q.name} message: ${Q.message} stack: ${Q.stack} data: ${Z}`)}}}ue()}catch(te){Y(te)}finally{if(r===ne&&(r=null),ne)try{ne.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:a=>{o?.();let c=r;r=null,c&&c.cancel(a).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${a}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature}),r.message.annotations){let c=`srvtoolu_${dn()}`;o.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:c,content:r.message.annotations.map(l=>({type:"web_search_result",url:l.url_citation.url,title:l.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(c=>{if(!("function"in c)||!c.function)return;let l={};try{let f=c.function.arguments||"{}";typeof f=="object"?l=f:typeof f=="string"&&(l=JSON.parse(f))}catch{l={text:c.function.arguments||""}}o.push({type:"tool_use",id:c.id,name:c.function.name,input:l})});let s=String(r.finish_reason||""),a={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":s==="length"?"max_tokens":s==="tool_calls"?"tool_use":s==="content_filter"?"stop_sequence":s==="model_context_window_exceeded"?"model_context_window_exceeded":"end_turn",stop_sequence:null,usage:{...Oa(e.usage),...r.message.annotations?.length?{server_tool_use:{web_search_requests:r.message.annotations.length}}:{}}};return this.logger.debug({reqId:n.req.id,result:a},"Conversion complete, final Anthropic response"),a}catch{throw $e(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var CE=new Set(["type","format","title","description","nullable","enum","maxItems","minItems","properties","required","minProperties","maxProperties","minLength","maxLength","pattern","example","anyOf","propertyOrdering","default","items","minimum","maximum","additionalProperties","allOf","oneOf"]);function gr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>gr(r,e));let n={};for(let r in t){if(e!=="properties"&&!CE.has(r))continue;let o=t[r];if(!(r==="enum"&&t.type&&t.type!=="string")&&!(r==="format"&&t.type==="string"&&o&&!["enum","date-time"].includes(o))&&!(r==="format"&&o==="uri")&&r!=="$schema")if(r==="properties"&&typeof o=="object"&&!Array.isArray(o)){let s={};for(let a in o)s[a]=gr(o[a]);n[r]=s}else r==="items"?n[r]=gr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>gr(s,r)):n[r]=o}if(Array.isArray(n.required)&&n.properties){let r=new Set(Object.keys(n.properties));n.required=n.required.filter(o=>r.has(o)),n.required.length===0&&delete n.required}return n}function To(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(To);let e={};for(let m in t){let S=t[m];if(m==="properties"&&S&&typeof S=="object"){let y={};for(let w in S)y[w]=To(S[w]);e[m]=y}else m==="items"?e[m]=To(S):["anyOf","allOf","oneOf"].includes(m)&&Array.isArray(S)?e[m]=S.map(To):e[m]=S}let n=e.anyOf||e.oneOf;if(!Array.isArray(n)||e.type)return e;let r=n.filter(m=>m&&typeof m=="object"),o=r.find(m=>m.type)||r[0];if(!o)return e;let{anyOf:s,oneOf:a,description:c,...l}=e,f=[...new Set(r.filter(m=>m!==o).map(m=>String(m.description||m.type||"").split(" (alternatives:")[0]).filter(Boolean))],d={...o,...l},h=[c,o.description,...f].filter(Boolean);return h.length&&(d.description=f.length?`${h[0]} (alternatives: ${f.join("; ")})`:h[0]),d}function Fa(t){return!t||typeof t!="object"?t:gr(t)}var Js=["minimal","low","medium","high"];function kE(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function SE(t){let e=kE(t);return e?e.includes("-image")||e.includes("imagen")?{kind:"none"}:e.startsWith("claude")?{kind:"budget",min:1024,max:64e3,requireMin:!0}:/^gemini-3(\.\d+)?\b/.test(e)||e.startsWith("gemini-pro-agent")?/^gemini-3-pro\b/.test(e)?{kind:"level",levels:["low","high"]}:e.includes("flash")?{kind:"level",levels:Js}:{kind:"level",levels:["low","medium","high"]}:/^gemini-2\.5/.test(e)?e.includes("pro")?{kind:"budget",min:128,max:32768}:{kind:"budget",min:0,max:24576}:{kind:"includeOnly"}:{kind:"includeOnly"}}function AE(t,e){let n=t.toLowerCase(),r=Js.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max")return r[r.length-1];let o=Js.indexOf(n);return o<0?r[r.length-1]:r.find(s=>Js.indexOf(s)>=o)??r[r.length-1]}function EE(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function vE(t,e,n){return Math.min(Math.max(t,e),n)}function C_(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=SE(t.model);if(r.kind==="none")return;let o=e.effort?.toLowerCase(),s=o==="none"||e.enabled===!1;if(r.kind==="includeOnly")return s?void 0:{includeThoughts:!0};if(r.kind==="level"){let f=Js.filter(d=>r.levels.includes(d));return s?{includeThoughts:!1,thinkingLevel:f[0]}:o?{includeThoughts:!0,thinkingLevel:AE(o,r.levels)}:{includeThoughts:!0}}if(s)return r.min===0?{includeThoughts:!1,thinkingBudget:0}:void 0;let a=e.max_tokens,c=typeof a=="number"?a:o?EE(o,r.max):void 0;if(typeof c!="number")return{includeThoughts:!0};let l=vE(c,r.min,r.max);if(t.max_tokens&&l>=t.max_tokens&&(l=t.max_tokens-1),l<r.min){if(r.requireMin)return;l=r.min}return{includeThoughts:!0,thinkingBudget:l}}var Un=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
152
- `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};var zr=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
153
- `),e.id&&(r+=`id: ${e.id}
154
- `),e.retry&&(r+=`retry: ${e.retry}
155
- `),e.data&&(e.data.type==="done"?r+=`data: [DONE]
156
- `:r+=`data: ${JSON.stringify(e.data)}
157
- `),r+=`
158
- `,n.enqueue(r)}})}};var tf=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let a=await e(s,r);a!==void 0&&r.enqueue(a)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};function ze(t,e,n){let r=new TextEncoder,o=!1,s=new ReadableStream({async start(a){if(!t.body){a.close();return}let c={controller:a,encoder:r};try{let l=t.body.pipeThrough(new TextDecoderStream).pipeThrough(new Un).pipeThrough(new zr).getReader();for(;;){let{done:f,value:d}=await l.read();if(f)break;if(!d)continue;let h=d.split(`
159
- `);for(let m of h)if(m.trim())try{e(m,c)}catch(S){(n?.logger?.error??console.error)("Error processing line:",m,S),a.enqueue(r.encode(m+`
160
- `))}}}catch(l){(n?.logger?.error??console.error)("Stream error:",l),o=!0,a.error(l)}finally{try{n?.onComplete?.(c)}catch(l){(n?.logger?.error??console.error)("Stream completion error:",l),o||(o=!0,a.error(l))}o||a.close()}}});return new Response(s,{status:t.status,statusText:t.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function Be(t,e){return e.encode(`data: ${t}
182
+ `)),x=-1,A=!1}if(!h&&!_){h=!0;let le=q(),be={type:"content_block_start",index:le,content_block:{type:"text",text:""}};$(c.encode(`event: content_block_start
183
+ data: ${JSON.stringify(be)}
161
184
 
162
- `)}function Te(t,e){return e.encode(t+`
163
- `)}var Pa=st(I_(),1),HE={STOP:"stop",MAX_TOKENS:"length",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter"},nf="\u26A0\uFE0F Upstream ended the turn without a reply";function Vs(t){return t?HE[t.toUpperCase()]||t.toLowerCase():null}function rf(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${nf} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var Ia=class{constructor(e){this.emit=e}_hasThinking=!1;_sigSent=!1;_contentSent=!1;_buffer="";processThinking(e,n){this._hasThinking=!0,this.emit.thinking(e,n)}processSignature(e,n){this.processSignatureWithMeta(e,n)}processSignatureWithMeta(e,n,r){if(!this._sigSent){if(this._contentSent){this._sigSent=!0;return}this._hasThinking||(this._hasThinking=!0,this.emit.thinking("(no content)",n)),this._sigSent=!0,this.emit.signature(e,n),r?.beforeFlush?.(),this.flushBufferedContent(r?.flushMeta)}}processContent(e,n,r){this._sigSent||!this._hasThinking?(this._contentSent=!0,this.emit.content(e,{chunk:n,candidate:r,mode:"direct"})):this._buffer+=e}emitContentPlaceholder(e,n){this._contentSent=!0,this.emit.content(e,{chunk:n?.chunk,candidate:n?.candidate,mode:"placeholder",finishReason:n?.finishReason})}bufferContent(e){this._buffer+=e}finalize(e,n,r){if(this._hasThinking&&!this._sigSent){this.processSignatureWithMeta(`ccr_${Date.now()}`,e,{beforeFlush:r?.beforeFlush,flushMeta:{chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Vs(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Vs(n?.finishReason)})}flushBufferedContent(e){this._buffer&&(this._contentSent=!0,this.emit.content(this._buffer,{chunk:e?.chunk,candidate:e?.candidate,mode:e?.mode||"buffered",finishReason:e?.finishReason}),this._buffer="")}shouldDeferContent(e,n){return this._hasThinking&&!this._sigSent&&!e&&!n}get hasBufferedContent(){return this._buffer.length>0}get hasThinkingContent(){return this._hasThinking}get signatureSent(){return this._sigSent}get contentSent(){return this._contentSent}get needsContentPlaceholder(){return this._sigSent&&!this._contentSent}acknowledgeSignature(){this._sigSent=!0}};function Na(t,e){return e[t]||t}function Ba(t){return!t||typeof t=="string"?[]:t.filter(e=>e.type==="image_url").map(e=>({url:e.image_url.url,mediaType:e.media_type||"image/jpeg",isBase64:e.image_url.url.startsWith("data:")}))}function ja(t,e){if(t.length===0)return[];let n=[];for(let r of t){let o=n[n.length-1];if(o&&o.role===r.role){let s=o[e],a=r[e];Array.isArray(s)&&Array.isArray(a)&&s.push(...a)}else n.push({...r})}return n}function Ro(t){return t.function?.name?{name:t.function.name,description:t.function.description,parameters:t.function.parameters}:{name:t.name,description:t.description,parameters:t.input_schema}}function Ma(t,e){if(e==="gemini")return t.isBase64?{inlineData:{mimeType:t.mediaType,data:t.url.split(",").pop()||t.url}}:{fileData:{mimeType:t.mediaType,fileUri:t.url}};if(e==="claude")return{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.url.startsWith("data:")&&t.url.split(",").pop()||t.url}};throw new Error(`Unsupported provider for image processing: ${e}`)}function Ks(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof Pa.default=="function"?Pa.default:Pa.default.default;if(typeof e!="function")return t;let n=/(\$\$?[\s\S]+?\$\$?|\\\(?:[\s\S]+?\\\)|\\\[[\s\S]+?\\\]|\\(?:[a-zA-Z]+))/g;return t.replace(n,r=>{let o=r,s;do s=o,o=e(o);while(o!==s);return o.replace(/\$([^\$]+)\$/g,"$1")})}catch{return t}}function N_(t){if(!t)return"unnamed_function";let e=t.replace(/[^a-zA-Z0-9_.:\-]/g,"_");return/^[^a-zA-Z_]/.test(e)&&(e="_"+e),e.substring(0,128)}var Hr=new Map,B_=(t,e)=>`${t||"default"}${e}`;function j_(t,e,n){if(!e||!n)return;let r=B_(t,e);for(Hr.delete(r),Hr.set(r,{signature:n,expiresAt:Date.now()+216e5});Hr.size>4096;){let o=Hr.keys().next();if(o.done)break;Hr.delete(o.value)}}function M_(t,e){if(!e)return;let n=B_(t,e),r=Hr.get(n);if(r){if(r.expiresAt<=Date.now()){Hr.delete(n);return}return r.signature}}function WE(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var Do={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function GE(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(Do).includes(r)?r:Do.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Do).includes(o)?o:Do.TYPE_UNSPECIFIED})}}}function Ys(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&GE(t.type,e);for(let[a,c]of Object.entries(t))if(c!=null)if(a=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let l=String(c).toUpperCase();e.type=Object.values(Do).includes(l)?l:Do.TYPE_UNSPECIFIED}else if(n.includes(a))e[a]=Ys(c);else if(r.includes(a)){let l=[];for(let f of Array.isArray(c)?c:[]){if(f.type=="null"){e.nullable=!0;continue}l.push(Ys(f))}e[a]=l}else if(o.includes(a)){let l={};for(let[f,d]of Object.entries(c))l[f]=Ys(d);e[a]=l}else{if(a==="additionalProperties")continue;e[a]=c}if(e.type==="ARRAY"&&!e.items&&(e.items={type:"STRING"}),Array.isArray(e.required)&&e.properties){let a=new Set(Object.keys(e.properties));e.required=e.required.filter(c=>a.has(c)),e.required.length===0&&delete e.required}return e}function JE(t,e){let n=r=>e?.collapseUnions?To(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=gr(r.parameters);r.parameters=n(Ys(o))}if(r.response){let o=gr(r.response);r.response=n(Ys(o))}}return t}var L_="skip_thought_signature_validator";function Ua(t,e){let n=[],r=t.tools||[],o=r.filter(_=>Ro(_).name!=="web_search").map(_=>{let{name:D,description:k,parameters:v}=Ro(_);return{name:N_(D),description:k,parameters:v??{type:"object",properties:{}}}});o?.length&&n.push(JE({functionDeclarations:o},{collapseUnions:WE(t.model)})),r.find(_=>Ro(_).name==="web_search")&&n.push({googleSearch:{}});let a=[],c=t.messages||[],l=[],f=_=>{if(typeof _=="string")_&&l.push(_);else if(Array.isArray(_))for(let D of _)D?.type==="text"&&D.text?l.push(D.text):typeof D=="string"&&D&&l.push(D)};t.system&&f(t.system);for(let _ of c)_.role==="system"&&f(_.content);let d=c.filter(_=>_.role==="tool"),h=c.filter(_=>_.role!=="tool"&&_.role!=="system"),m=e?.thoughtSignatureFallback!=="none";h.forEach(_=>{let D=Na(_.role,{assistant:"model"}),k=[],v=_.thinking?.signature,x=v?.startsWith("ccr_")?void 0:v,R=W=>D==="model"&&(W==="(no content)"||W.startsWith(nf));if(x&&D==="model"&&k.push({thought:!0,text:_.thinking?.content||"",thoughtSignature:x}),typeof _.content=="string")_.content&&!R(_.content)&&k.push({text:_.content});else if(Array.isArray(_.content))_.content.forEach(U=>{if(U.type==="text"){let ue=U.text||"";ue&&!R(ue)&&k.push({text:ue})}}),Ba(_.content).forEach(U=>{k.push(Ma(U,"gemini"))});else if(_.content&&typeof _.content=="object")if(_.content.text){let W=_.content.text;R(W)||k.push({text:W})}else k.push({text:JSON.stringify(_.content)});let j=Array.isArray(_.tool_calls)?_.tool_calls.map((W,U)=>{let ue=W.id||`tool_${Math.random().toString(36).substring(2,15)}`,Y=W.thought_signature||M_(e?.signatureScope,ue);return!Y&&U===0&&(Y=x||(m?L_:void 0)),{toolCall:W,id:ue,signature:Y}}):[];if(j.length>0&&k.push(...j.map(({toolCall:W,id:U,signature:ue})=>({functionCall:{id:U,name:W.function.name,args:JSON.parse(W.function.arguments||"{}")},...ue&&{thoughtSignature:ue}}))),k.length===0&&k.push({text:""}),a.push({role:D,parts:k}),D==="model"&&j.length>0){let W=j.map(({toolCall:U,id:ue})=>{let ne=d.find(te=>te.tool_call_id===U.id)?.content;return Array.isArray(ne)?ne=ne.filter(te=>te.type==="text").map(te=>te.text).join(`
164
- `):typeof ne=="object"&&ne!==null&&(ne=JSON.stringify(ne)),{functionResponse:{id:ue,name:U?.function?.name,response:{result:ne}}}});a.push({role:"user",parts:W})}});let S=ja(a,"parts"),y={},w=C_(t);w&&(y.thinkingConfig=w),t.max_tokens&&(y.maxOutputTokens=t.max_tokens),t.temperature!==void 0&&(y.temperature=t.temperature);let b={contents:S.length?S:[{role:"user",parts:[{text:""}]}],tools:n.length?n:void 0,generationConfig:y};if(l.length&&(b.systemInstruction={parts:[{text:l.join(`
185
+ `)),x=le}if(!v&&!_){let le={type:"content_block_delta",index:x,delta:{type:"text_delta",text:se.delta.content}};$(c.encode(`event: content_block_delta
186
+ data: ${JSON.stringify(le)}
165
187
 
166
- `)}]}),t.tool_choice){let _={functionCallingConfig:{}};t.tool_choice==="auto"?_.functionCallingConfig.mode="auto":t.tool_choice==="none"?_.functionCallingConfig.mode="none":t.tool_choice==="required"?_.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(_.functionCallingConfig.mode="any",_.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),b.toolConfig=_}return b}function La(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,a=t.stream,c=t.tool_choice,l={messages:[],model:r,max_tokens:o,temperature:s,stream:a,tool_choice:c};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?l.messages.push({role:"user",content:f}):typeof f.text=="string"?l.messages.push({role:"user",content:f.text||null}):f.role==="user"?l.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&l.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(n)&&(l.tools=[],n.forEach(f=>{let d=f.functionDeclarations;Array.isArray(d)&&d.forEach(h=>{l.tools.push({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})})})),l}function U_(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===L_||r.startsWith("ccr_")||j_(t,n.id,r)})}async function qa(t,e,n,r){let o=r||e;if(t.headers.get("Content-Type")?.includes("application/json")){let s=await t.json();if(n?.debug({response:s},`${e} response:`),t.status>=400){let D=(s.error?.message||"").toLowerCase();if(["user input too long","input too long","prompt is too long","exceeds the token limit","request payload size exceeds","context_length_exceeded"].some(v=>D.includes(v))){let v={id:`ctxexceeded_${Date.now()}`,choices:[{finish_reason:"model_context_window_exceeded",index:0,message:{content:"",role:"assistant"}}],created:Math.floor(Date.now()/1e3),model:"",object:"chat.completion",usage:{completion_tokens:0,prompt_tokens:0,total_tokens:0}};return new Response(JSON.stringify(v),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}if(!s.candidates||s.candidates.length===0)return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers});let a="",c="",l=s.candidates[0]?.content?.parts||[],f=[];for(let _ of l)_.text&&_.thought===!0?a+=Ks(_.text):f.push(_);c=l.find(_=>_.thoughtSignature)?.thoughtSignature,a&&!c&&(c=`ccr_${+new Date}`);let d=f?.filter(_=>_.functionCall)?.map(_=>({id:_.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:_.functionCall?.name,arguments:JSON.stringify(_.functionCall?.args||{})},thought_signature:_.thoughtSignature||_.thought_signature||void 0}))||[];c&&d.length>0&&!d[0].thought_signature&&(d[0].thought_signature=c),U_(o,d);let h=f?.filter(_=>_.text)?.map(_=>Ks(_.text||""))?.join(`
167
- `)||"",m=s.candidates[0],S=h&&h!=="(no content)"?h:"",y=!S&&d.length===0?rf(m):null,w=Vs(m?.finishReason),b={id:s.responseId,choices:[{finish_reason:d.length>0?"tool_calls":w,index:0,message:{content:y||S,role:"assistant",tool_calls:d.length>0?d:void 0,...c&&a&&{thinking:{content:a,signature:c}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:s.modelVersion,object:"chat.completion",usage:{completion_tokens:s.usageMetadata?.candidatesTokenCount||0,prompt_tokens:s.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:s.usageMetadata?.cachedContentTokenCount||0},total_tokens:s.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:s.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(b),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let s=0,a=-1,c=null,l=null,f=null,d=(b,_)=>{b.controller.enqueue(b.encoder.encode(`data: ${JSON.stringify(_)}
188
+ `))}}if(se?.delta?.annotations?.length&&!v&&!_){if(O+=se.delta.annotations.length,x>=0&&h){let le={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
189
+ data: ${JSON.stringify(le)}
168
190
 
169
- `))},h=b=>({completion_tokens:b?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:b?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:b?.usageMetadata?.cachedContentTokenCount||0},total_tokens:b?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:b?.usageMetadata?.thoughtsTokenCount||0}}),m=b=>b?.groundingMetadata?.groundingChunks?.map((_,D)=>{let k=b?.groundingMetadata?.groundingSupports?.filter(v=>v.groundingChunkIndices?.includes(D));return{type:"url_citation",url_citation:{url:_?.web?.uri||"",title:_?.web?.title||"",content:k?.[0]?.segment?.text||"",start_index:k?.[0]?.segment?.startIndex||0,end_index:k?.[0]?.segment?.endIndex||0}}})||[],S=(b,_,D)=>{let k=D?.mode||"direct";k==="direct"&&s++;let v={choices:[{delta:{role:"assistant",content:_},finish_reason:D?.finishReason??(k==="direct"||k==="finish"?Vs(D?.candidate?.finishReason):null),index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:D?.chunk?.responseId||"",model:D?.chunk?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(k==="direct"||k==="finish"){v.usage=h(D?.chunk);let x=m(D?.candidate);x.length>0&&(v.choices[0].delta.annotations=x)}d(b,v)},y=new Ia({thinking:(b,_)=>{c&&d(c,{choices:[{delta:{role:"assistant",content:null,thinking:{content:b}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_?.responseId||"",model:_?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},signature:(b,_)=>{c&&d(c,{choices:[{delta:{role:"assistant",content:null,thinking:{signature:b}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:_?.responseId||"",model:_?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},content:(b,_)=>{c&&S(c,b,_)}});return ze(t,(b,_)=>{if(c=_,b.startsWith("data: ")){let D=b.slice(6).trim();if(D){n?.debug({chunkStr:D},`${e} chunk:`);try{let k=JSON.parse(D);if(!k.candidates||!k.candidates[0]){n?.debug({chunkStr:D},"Invalid chunk structure");return}let v=k.candidates[0];l=k,f=v;let x=v.content?.parts||[];x.filter(Y=>Y.text&&Y.thought===!0).forEach(Y=>{y.processThinking(Ks(Y.text),k)});let R=x.filter(Y=>Y.functionCall).map(Y=>({id:Y.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:Y.functionCall?.name,arguments:JSON.stringify(Y.functionCall?.args||{})},thought_signature:Y.thoughtSignature||Y.thought_signature||void 0})),j=x.filter(Y=>Y.text&&Y.thought!==!0).map(Y=>Ks(Y.text||"")).join(`
170
- `),W=x.find(Y=>Y.thoughtSignature)?.thoughtSignature;W&&R.length>0&&!R[0].thought_signature&&(R[0].thought_signature=W),U_(o,R);let U=!!(j&&j!=="(no content)")||R.length>0||!!v.finishReason;if(j&&j!=="(no content)"&&k.modelVersion?.includes("3")&&y.shouldDeferContent(!!v.finishReason,R.length>0))y.bufferContent(j);else if(j&&j!=="(no content)"){if(y.hasThinkingContent&&!y.signatureSent&&U&&!W){let Y=y.hasBufferedContent;y.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:Y?()=>{s++}:void 0,flushMeta:Y?{chunk:k,candidate:v,mode:"buffered",finishReason:null}:void 0})}y.processContent(j,k,v)}W&&(R.length>0&&!y.hasThinkingContent&&!j&&!y.contentSent?y.acknowledgeSignature():y.processSignatureWithMeta(W,k,{beforeFlush:()=>{s++},flushMeta:{chunk:k,candidate:v,mode:"buffered"}}));let ue=a<0&&R.length===0&&!j?rf(v):null;if(!j&&R.length===0&&a<0&&v.finishReason&&!ue&&y.needsContentPlaceholder&&y.emitContentPlaceholder("(no content)",{chunk:k,candidate:v}),!W&&!j&&y.hasThinkingContent&&!y.signatureSent&&U){let Y=y.hasBufferedContent;y.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:Y?()=>{s++}:void 0,flushMeta:Y?{chunk:k,candidate:v,mode:"buffered",finishReason:null}:void 0})}if(j&&k.modelVersion?.includes("3")&&y.hasBufferedContent&&!W&&R.length===0&&!v.finishReason)return;R.length>0&&R.forEach((Y,ne)=>{s++,a++;let te=v.finishReason!=null&&ne===R.length-1?"tool_calls":null,re={choices:[{delta:{role:"assistant",tool_calls:[{...Y,index:a}]},finish_reason:te,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:k.responseId||"",model:k.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:h(k)},K=m(v);K.length>0&&(re.choices[0].delta.annotations=K),d(_,re)}),v.finishReason&&(y.hasBufferedContent?y.finalize(k,v,{beforeFlush:()=>{y.signatureSent||s++}}):!j&&R.length===0&&(s++,S(_,ue||"",{chunk:k,candidate:v,mode:"finish",...a>=0?{finishReason:"tool_calls"}:{}})))}catch(k){n?.error(`Error parsing ${e} stream chunk`,D,k.message)}}}},{onComplete:b=>{c=b,(y.hasBufferedContent||y.hasThinkingContent&&!y.signatureSent)&&y.finalize(l||void 0,f||void 0,{beforeFlush:()=>{y.signatureSent||s++}})}})}return t}var z_=require("crypto"),VE=15e3,KE=256,Ln=new Map,of=new Map;function q_(t){return(0,z_.createHash)("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function YE(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function XE(t){return Math.floor(JSON.stringify(t).length/4)}function QE(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function $_(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function $a(t,e){let n=Date.now();for(let[r,o]of Ln)o.expiresAt<=n&&Ln.delete(r);for(Ln.delete(t),Ln.set(t,e);Ln.size>KE;){let r=Ln.keys().next().value;if(r===void 0)break;Ln.delete(r)}}async function za(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=QE(e);if(Object.keys(s).length===0||XE(s)<YE(n))return e;let a=q_(o),c=[String(r),a,n,q_(s)].join(":"),l=Date.now(),f=Ln.get(c);if(f&&f.expiresAt>l)return f.name?$_(e,f.name):e;f&&Ln.delete(c);let d=3600,h={model:n,...s,ttl:`${d}s`},m=of.get(c);m||(m=(async()=>{try{let y=await fetch(r,{method:"POST",headers:Object.fromEntries(Object.entries({"Content-Type":"application/json",...o}).filter(([,b])=>b!==void 0)),body:JSON.stringify(h),signal:AbortSignal.timeout(VE)});if(!y.ok){t.logger?.debug?.({status:y.status},"Gemini cached-content create failed; using implicit cache"),$a(c,{expiresAt:Date.now()+300*1e3});return}let w=await y.json();if(!w?.name){t.logger?.debug?.("Gemini cached-content response had no resource name; using implicit cache"),$a(c,{expiresAt:Date.now()+300*1e3});return}return $a(c,{name:w.name,expiresAt:Date.now()+(d-30)*1e3}),w.name}catch(y){t.logger?.debug?.({error:y?.message||String(y)},"Gemini cached-content create errored; using implicit cache"),$a(c,{expiresAt:Date.now()+300*1e3});return}finally{of.delete(c)}})(),of.set(c,m));let S=await m;return S?$_(e,S):e}var Ha=class{constructor(e){this.options=e;this.cachedContent=e?.cachedContent!==!1,this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}static TransformerName="gemini";logger;name="gemini";endPoint="/v1beta/models/:modelAndAction";cachedContent;thoughtSignatureFallback;async transformRequestIn(e,n,r){let o=e.model||(typeof r?.req?.model=="string"?r.req.model:Array.isArray(r?.req?.model)?r.req.model.join(","):"")||n.models?.[0]||"",s=Ua(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await za({body:s,modelResource:o.startsWith("models/")?o:`models/${o}`,createUrl:new URL("../cachedContents",n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0},logger:this.logger}):s,config:{url:new URL(`./${o}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}async transformRequestOut(e){return La(e)}async transformResponseOut(e,n){return qa(e,this.name,this.logger,n?.provider?.name||this.name)}};async function $O(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>st(gu(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
171
- 1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
172
- 2. Run "gcloud auth application-default login"
173
- 3. Use Google Cloud environment with default service account`)}}var mu=class{static TransformerName="vertex-gemini";logger;name="vertex-gemini";thoughtSignatureFallback;constructor(e){this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}async transformRequestIn(e,n,r){let o=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let m=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),S=JSON.parse(m);S&&S.project_id&&(o=S.project_id)}catch(h){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",h)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await $O(this.logger),c=e.model||n.models?.[0]||"",l=n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`,f=`projects/${o}/locations/${s}/publishers/google/models/${c}`;return{body:await za({body:Ua(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name}),modelResource:f,createUrl:new URL(`./v1beta1/projects/${o}/locations/${s}/cachedContents`,l),headers:{Authorization:`Bearer ${a}`,"x-goog-api-key":void 0},logger:this.logger}),config:{url:new URL(`./v1beta1/${f}:${e.stream?"streamGenerateContent":"generateContent"}`,l),headers:{Authorization:`Bearer ${a}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return La(e)}async transformResponseOut(e,n){return qa(e,this.name,this.logger,n?.provider?.name||this.name)}};function yu(){return{content:"",isComplete:!1,hasContent:!1}}function _u(t,e){t.content+=e,t.hasContent=!0}function bu(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Sr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function is(t){if(t.reasoning_content){let e=t.reasoning_content;return typeof e=="string"?e:typeof e?.text=="string"?e.text:null}if(t.reasoning){let e=t.reasoning;return typeof e=="string"?e:null}return null}function Ar(t){delete t.reasoning_content,delete t.reasoning}var bk=require("node:crypto"),yk=360*60*1e3,zO=4096,Op="__ccrDeepseekReasoning",Fp=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>yk){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,n),n.reasoning}}put(e,n){n&&(this.cache.delete(e),this.cache.set(e,{reasoning:n,createdAt:Date.now()}),this.prune())}prune(){for(let[e,n]of this.cache)Date.now()-n.createdAt>yk&&this.cache.delete(e);for(;this.cache.size>zO;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},wu=new Fp;function Pp(t){return Array.isArray(t)?t.map(Pp):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=Pp(t[n]),e),{}):t}function io(t){return JSON.stringify(Pp(t))}function Cu(t){return(0,bk.createHash)("sha256").update(t).digest("hex")}function wk(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):io(e)).join(""):io(t)}function Ip(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:io(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function Ck(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function kk(t){let e=Ip(t);return Cu(io({...e,id:void 0}))}function Sk(t){return Cu(io({content:wk(t.content),tool_calls:(t.tool_calls||[]).map(e=>Ip(e))}))}function HO(t){let e={role:t.role,content:wk(t.content)};return t.name&&(e.name=t.name),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.tool_calls?.length&&(e.tool_calls=t.tool_calls.map(n=>Ip(n))),e}function _k(t,e){let n=t.filter(r=>r.role!=="system").map(r=>HO(r));return Cu(io({namespace:e,messages:n}))}function WO(t){if(typeof t.reasoning_content=="string"&&t.reasoning_content.length>0)return t.reasoning_content;if(typeof t.thinking?.content=="string"&&t.thinking.content.length>0)return t.thinking.content}function Ak(t,e){if(t.role!=="assistant")return 0;let n=WO(t);if(!n)return 0;let r=[`scope:${e}:signature:${Sk(t)}`];return r.push(...Ck(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${kk(o)}`)),r.forEach(o=>wu.put(o,n)),r.length}function GO(t,e){let n=wu.get(`scope:${e}:signature:${Sk(t)}`);if(n)return n;for(let r of Ck(t)){let o=wu.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=wu.get(`scope:${e}:tool_call_signature:${kk(r)}`);if(o)return o}}function JO(t,e){if(t.tool_calls?.length)return!0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool")return!0;if(r.role==="user"||r.role==="system")return!1}return!1}function VO(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek"),a=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&a}function KO(t,e){return Cu(io({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function ku(t,e,n){if(!VO(t,e))return n?.req&&delete n.req[Op],{restoredFromCache:0,restoredFromThinking:0};let r=KO(t,e),o=[],s=0,a=0;for(let c of t.messages){if(c.role==="assistant"){let l=_k(o,r);if(JO(c,o)&&!(typeof c.reasoning_content=="string"&&c.reasoning_content.length>0?c.reasoning_content:void 0)){let h=typeof c.thinking?.content=="string"&&c.thinking.content.length>0?c.thinking.content:void 0;if(h)c.reasoning_content=h,a++;else{let m=GO(c,l);m&&(c.reasoning_content=m,s++)}}Ak(c,l)}o.push(c)}return n?.req&&(n.req[Op]={enabled:!0,namespace:r,requestScope:_k(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:a}}function Ek(t){return t?.req?.[Op]}function Su(t){return Ek(t)?.enabled===!0}function as(t,e){if(!t)return 0;let n=Ek(e);return n?Ak(t,n.requestScope):0}function Au(){return{content:"",reasoning:"",toolCalls:new Map}}function cs(t,e){e&&(typeof e.reasoning_content=="string"&&(t.reasoning+=e.reasoning_content),typeof e.content=="string"&&(t.content+=e.content),Array.isArray(e.tool_calls)&&e.tool_calls.forEach((n,r)=>{let o=typeof n.index=="number"?n.index:r,s=t.toolCalls.get(o)||{id:"",type:"function",function:{name:"",arguments:""}};typeof n.id=="string"&&n.id.length>0&&(s.id=n.id),typeof n.type=="string"&&n.type.length>0&&(s.type=n.type);let a=n.function||{};typeof a.name=="string"&&a.name.length>0&&(s.function.name+=a.name),typeof a.arguments=="string"&&a.arguments.length>0&&(s.function.arguments+=a.arguments),t.toolCalls.set(o,s)}))}function Eu(t){if(!t.reasoning)return null;let e=Array.from(t.toolCalls.entries()).sort(([n],[r])=>n-r).map(([,n])=>n).filter(n=>typeof n.id=="string"&&n.id.length>0&&typeof n.function?.name=="string"&&n.function.name.length>0);return!t.content&&e.length===0?null:{role:"assistant",content:t.content||null,tool_calls:e.length>0?e:void 0,reasoning_content:t.reasoning}}function vk(t){let e=t?.usage;!e||e.prompt_cache_hit_tokens===void 0||(e.prompt_tokens_details={...e.prompt_tokens_details||{},cached_tokens:e.prompt_cache_hit_tokens||0})}var vu=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Je(e.messages),e.tools=Ve(e.tools),ku(e,n,r),e}async transformResponseOut(e,n){let r=Su(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return vk(o),r&&as({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=yu(),s=r?Au():null;return ze(e,(a,c)=>{if(!a.trim()){c.controller.enqueue(Te(a,c.encoder));return}if(!a.startsWith("data:")||a.trim()==="data: [DONE]"){c.controller.enqueue(Te(a,c.encoder));return}try{let l=a.slice(5).trim(),f=JSON.parse(l);vk(f);let d=f.choices?.[0]?.delta;if(!d){c.controller.enqueue(Be(JSON.stringify(f),c.encoder));return}let h=is(d);if(h){s&&cs(s,d),_u(o,h);let m=Sr(f,{content:h});Ar(m.choices[0].delta),c.controller.enqueue(Be(JSON.stringify(m),c.encoder));return}if(s&&cs(s,d),d.content&&o.hasContent&&!o.isComplete){let{content:m,signature:S}=bu(o),y=Sr(f,{content:m,signature:S});Ar(y.choices[0].delta),y.choices[0].delta.content=null,c.controller.enqueue(Be(JSON.stringify(y),c.encoder))}d.reasoning_content&&delete d.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0&&(o.isComplete&&f.choices[0].index++,c.controller.enqueue(Be(JSON.stringify(f),c.encoder)))}catch{c.controller.enqueue(Te(a,c.encoder))}},{onComplete:()=>{s&&as(Eu(s),n)}})}return e}};var Tu=class{name="tooluse";async transformRequestIn(e,n,r){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice=e.tool_choice||"required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
174
- IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
175
- Examples:
176
- 1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
177
- 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=-1,s="";return ze(e,(c,l)=>{let{controller:f,encoder:d}=l;if(c.startsWith("data: ")&&c.trim()!=="data: [DONE]")try{let h=JSON.parse(c.slice(6));if(h.choices[0]?.delta?.tool_calls?.length){let m=h.choices[0].delta.tool_calls[0];if(m.function?.name==="ExitTool"){o=m.index;return}else if(o>-1&&m.index===o&&m.function.arguments){s+=m.function.arguments;try{let S=JSON.parse(s);h.choices=[{delta:{role:"assistant",content:S.response||""}}];let y=`data: ${JSON.stringify(h)}
178
-
179
- `;f.enqueue(d.encode(y))}catch{}return}}if(h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){let m=`data: ${JSON.stringify(h)}
180
-
181
- `;f.enqueue(d.encode(m))}}catch{f.enqueue(d.encode(c+`
182
- `))}else f.enqueue(d.encode(c+`
183
- `))})}return e}};var Ru=class{constructor(e){this.options=e}static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=Qt(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=Lr(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=Gs(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=qr(e):s.includes("gemini")?e=qr(e):e={...e,messages:Je(e.messages),tools:Ve(e.tools)},e.model.includes("claude")?e.messages.forEach(a=>{Array.isArray(a.content)&&a.content.forEach(c=>{c.type==="image_url"&&(c.image_url.url.startsWith("http")||(c.image_url.url=`data:${c.media_type};base64,${c.image_url.url}`),delete c.media_type)})}):e.messages.forEach(a=>{Array.isArray(a.content)&&a.content.forEach(c=>{c.type==="image_url"&&(c.image_url.url.startsWith("http")||(c.image_url.url=`${c.image_url.url}`),delete c.media_type)})}),Object.assign(e,this.options||{}),o&&(e.session_id=o,e.prompt_cache_key=o),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=yu(),r=!1,o=!1;return ze(e,(s,a)=>{if(!s.trim()){a.controller.enqueue(Te(s,a.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){a.controller.enqueue(Te(s,a.encoder));return}try{let c=s.slice(6),l=JSON.parse(c);l.usage&&(this.logger?.debug({usage:l.usage,hasToolCall:o},"usage"),l.choices[0].finish_reason=o?"tool_calls":"stop"),l.choices?.[0]?.finish_reason==="error"&&a.controller.enqueue(Be(JSON.stringify({error:l.choices?.[0]?.error}),a.encoder)),l.choices?.[0]?.delta?.content&&!r&&(r=!0);let f=l.choices?.[0]?.delta,d=f?is(f):null;if(d){_u(n,d);let h=Sr(l,{content:d});Ar(h.choices[0].delta),a.controller.enqueue(Be(JSON.stringify(h),a.encoder));return}if(f?.content&&n.hasContent&&!n.isComplete){let{content:h,signature:m}=bu(n),S=Sr(l,{content:h,signature:m});Ar(S.choices[0].delta),S.choices[0].delta.content=null,a.controller.enqueue(Be(JSON.stringify(S),a.encoder))}f?.reasoning&&delete f.reasoning,f?.tool_calls?.length&&!Number.isNaN(parseInt(f.tool_calls[0].id,10))&&f.tool_calls.forEach(h=>{h.id=`call_${dn()}`}),f?.tool_calls?.length&&!o&&(o=!0),f?.tool_calls?.length&&r&&(typeof l.choices[0].index=="number"?l.choices[0].index+=1:l.choices[0].index=1),a.controller.enqueue(Be(JSON.stringify(l),a.encoder))}catch{a.controller.enqueue(Te(s,a.encoder))}})}return e}};var Du=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var xu=class{name="groq";async transformRequestIn(e){return e.messages=Je(e.messages),e.tools=Ve(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=Fa(n.function.parameters))}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=!1;return ze(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Te(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Te(r,o.encoder));return}try{let s=r.slice(5).trim(),a=JSON.parse(s);if(a.error)throw new Error(JSON.stringify(a));a.choices?.[0]?.delta?.content&&!n&&(n=!0),a.choices?.[0]?.delta?.tool_calls?.length&&a.choices[0].delta.tool_calls.forEach(c=>{c.id=`call_${dn()}`}),a.choices?.[0]?.delta?.tool_calls?.length&&n&&(typeof a.choices[0].index=="number"?a.choices[0].index+=1:a.choices[0].index=1),o.controller.enqueue(Be(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Te(r,o.encoder))}})}return e}};var Ou=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{n.cache_control&&delete n.cache_control}),e}};var Ik=st(Wd());var Jn=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function Tk(t){return/^[0-9A-Fa-f]$/.test(t)}function vr(t){return t>="0"&&t<="9"}function Rk(t){return t>=" "}function vi(t){return`,:[]/{}()
184
- +`.includes(t)}function Np(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Bp(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var jp=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Mp=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Up(t){return`,[]/{}
185
- +`.includes(t)}function Lp(t){return Ti(t)||YO.test(t)}var YO=/^[[{\w-]$/;function Dk(t){return t===`
186
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Er(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function xk(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function Ok(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function Ti(t){return qp(t)||Fu(t)}function qp(t){return t==='"'||t==="\u201C"||t==="\u201D"}function $p(t){return t==='"'}function Fu(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function zp(t){return t==="'"}function us(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Jt(t,e){let n=t.length;if(!Er(t,n-1))return t+e;for(;Er(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function Fk(t,e,n){return t.substring(0,e)+t.substring(e+n)}function Pk(t){return/[,\n][ \t\r]*$/.test(t)}var XO={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},QO={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
187
- `,r:"\r",t:" "};function Hp(t){let e=0,n="";f(["```","[```","{```"]),s()||re(),f(["```","```]","```}"]);let o=h(",");for(o&&a(),Lp(t[e])&&Pk(n)?(o||(n=Jt(n,",")),_()):o&&(n=us(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;te();function s(){a();let X=w()||b()||D()||v()||x()||j(!1)||W();return a(),X}function a(){let X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,Q=c(X);do Q=l(),Q&&(Q=c(X));while(Q);return e>Z}function c(X){let Z=X?Er:xk,Q="";for(;;)if(Z(t,e))Q+=t[e],e++;else if(Ok(t,e))Q+=" ",e++;else break;return Q.length>0?(n+=Q,!0):!1}function l(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!ZO(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
188
- `;)e++;return!0}return!1}function f(X){if(d(X)){if(Np(t[e]))for(;e<t.length&&Bp(t[e]);)e++;return a(),!0}return!1}function d(X){c(!0);for(let Z of X){let Q=e+Z.length;if(t.slice(e,Q)===Z)return e=Q,!0}return!1}function h(X){return t[e]===X?(n+=t[e],e++,!0):!1}function m(X){return t[e]===X?(e++,!0):!1}function S(){return m("\\")}function y(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),m(","),!0):!1}function w(){if(t[e]==="{"){n+="{",e++,a(),m(",")&&a();let X=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(X?(Z=!0,X=!1):(Z=h(","),Z||(n=Jt(n,",")),a()),y(),!(D()||j(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=us(n,","):K();break}a();let me=h(":"),he=e>=t.length;me||(Lp(t[e])||he?n=Jt(n,":"):se()),s()||(me||he?n+="null":se())}return t[e]==="}"?(n+="}",e++):n=Jt(n,"}"),!0}return!1}function b(){if(t[e]==="["){n+="[",e++,a(),m(",")&&a();let X=!0;for(;e<t.length&&t[e]!=="]";)if(X?X=!1:h(",")||(n=Jt(n,",")),y(),!s()){n=us(n,",");break}return t[e]==="]"?(n+="]",e++):n=Jt(n,"]"),!0}return!1}function _(){let X=!0,Z=!0;for(;Z;)X?X=!1:h(",")||(n=Jt(n,",")),Z=s();Z||(n=us(n,",")),n=`[
189
- ${n}
190
- ]`}function D(){let X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,Q=t[e]==="\\";if(Q&&(e++,Q=!0),Ti(t[e])){let me=$p(t[e])?$p:zp(t[e])?zp:Fu(t[e])?Fu:qp,he=e,z=n.length,ge='"';for(e++;;){if(e>=t.length){let Fe=U(e-1);return!X&&vi(t.charAt(Fe))?(e=he,n=n.substring(0,z),D(!0)):(ge=Jt(ge,'"'),n+=ge,!0)}if(e===Z)return ge=Jt(ge,'"'),n+=ge,!0;if(me(t[e])){let Fe=e,xe=ge.length;if(ge+='"',e++,n+=ge,a(!1),X||e>=t.length||vi(t[e])||Ti(t[e])||vr(t[e]))return k(),!0;let ye=U(Fe-1),be=t.charAt(ye);if(be===",")return e=he,n=n.substring(0,z),D(!1,ye);if(vi(be))return e=he,n=n.substring(0,z),D(!0);n=n.substring(0,z),e=Fe+1,ge=`${ge.substring(0,xe)}\\${ge.substring(xe)}`}else if(X&&Up(t[e])){if(t[e-1]===":"&&jp.test(t.substring(he+1,e+2)))for(;e<t.length&&Mp.test(t[e]);)ge+=t[e],e++;return ge=Jt(ge,'"'),n+=ge,k(),!0}else if(t[e]==="\\"){let Fe=t.charAt(e+1);if(QO[Fe]!==void 0)ge+=t.slice(e,e+2),e+=2;else if(Fe==="u"){let ye=2;for(;ye<6&&Tk(t[e+ye]);)ye++;ye===6?(ge+=t.slice(e,e+6),e+=6):e+ye>=t.length?e=t.length:ie()}else ge+=Fe,e+=2}else{let Fe=t.charAt(e);Fe==='"'&&t[e-1]!=="\\"?(ge+=`\\${Fe}`,e++):Dk(Fe)?(ge+=XO[Fe],e++):(Rk(Fe)||ne(Fe),ge+=Fe,e++)}Q&&S()}}return!1}function k(){let X=!1;for(a();t[e]==="+";){X=!0,e++,a(),n=us(n,'"',!0);let Z=n.length;D()?n=Fk(n,Z,1):n=Jt(n,'"')}return X}function v(){let X=e;if(t[e]==="-"){if(e++,ue())return Y(X),!0;if(!vr(t[e]))return e=X,!1}for(;vr(t[e]);)e++;if(t[e]==="."){if(e++,ue())return Y(X),!0;if(!vr(t[e]))return e=X,!1;for(;vr(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,ue())return Y(X),!0;if(!vr(t[e]))return e=X,!1;for(;vr(t[e]);)e++}if(!ue())return e=X,!1;if(e>X){let Z=t.slice(X,e),Q=/^0\d/.test(Z);return n+=Q?`"${Z}"`:Z,!0}return!1}function x(){return R("true","true")||R("false","false")||R("null","null")||R("True","true")||R("False","false")||R("None","null")}function R(X,Z){return t.slice(e,e+X.length)===X?(n+=Z,e+=X.length,!0):!1}function j(X){let Z=e;if(Np(t[e])){for(;e<t.length&&Bp(t[e]);)e++;let Q=e;for(;Er(t,Q);)Q++;if(t[Q]==="(")return e=Q+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Up(t[e])&&!Ti(t[e])&&(!X||t[e]!==":");)e++;if(t[e-1]===":"&&jp.test(t.substring(Z,e+2)))for(;e<t.length&&Mp.test(t[e]);)e++;if(e>Z){for(;Er(t,e-1)&&e>0;)e--;let Q=t.slice(Z,e);return n+=Q==="undefined"?"null":JSON.stringify(Q),t[e]==='"'&&e++,!0}}function W(){if(t[e]==="/"){let X=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(X,e)}"`,!0}}function U(X){let Z=X;for(;Z>0&&Er(t,Z);)Z--;return Z}function ue(){return e>=t.length||vi(t[e])||Er(t,e)}function Y(X){n+=`${t.slice(X,e)}0`}function ne(X){throw new Jn(`Invalid character ${JSON.stringify(X)}`,e)}function te(){throw new Jn(`Unexpected character ${JSON.stringify(t[e])}`,e)}function re(){throw new Jn("Unexpected end of json string",t.length)}function K(){throw new Jn("Object key expected",e)}function se(){throw new Jn("Colon expected",e)}function ie(){let X=t.slice(e,e+6);throw new Jn(`Invalid unicode character "${X}"`,e)}}function ZO(t,e){return t[e]==="*"&&t[e+1]==="/"}function Wp(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=Ik.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Hp(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Pu=class{logger;name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Wp(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,a="",c=!1,l=!1,f="",d=new ReadableStream({start:async h=>{let m=e.body.getReader(),S=(b,_,D)=>{let k=b.split(`
191
- `);for(let v of k)v.trim()&&_.enqueue(D.encode(v+`
192
- `))},y=(b,_,D)=>{let k="";try{k=Wp(o.arguments||"",this.logger)}catch(j){this.logger?.error(`${j.message} ${j.stack} Tool call argument parsing failed: ${JSON.stringify(o)}`),k=o.arguments||""}let v={role:"assistant",tool_calls:[{function:{name:o.name,arguments:k},id:o.id,index:o.index,type:"function"}]},x={...b,choices:[{...b.choices[0],delta:v}]};x.choices[0].delta.content!==void 0&&delete x.choices[0].delta.content;let R=`data: ${JSON.stringify(x)}
191
+ `)),x=-1,h=!1}se?.delta?.annotations.forEach(le=>{let be=q(),K={type:"content_block_start",index:be,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${mn()}`,content:[{type:"web_search_result",title:le.url_citation.title,url:le.url_citation.url}]}};$(c.encode(`event: content_block_start
192
+ data: ${JSON.stringify(K)}
193
193
 
194
- `;_.enqueue(D.encode(R))},w=(b,_)=>{let{controller:D,encoder:k}=_;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let v=b.slice(6);try{let x=JSON.parse(v);if(x.choices?.[0]?.delta?.tool_calls?.length){let j=x.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:j.index,name:j.function?.name||"",id:j.id||"",arguments:j.function?.arguments||""},j.function?.arguments&&(j.function.arguments="");let W=`data: ${JSON.stringify(x)}
194
+ `));let Ke={type:"content_block_stop",index:be};$(c.encode(`event: content_block_stop
195
+ data: ${JSON.stringify(Ke)}
195
196
 
196
- `;D.enqueue(k.encode(W));return}else if(o.index===j.index){j.function?.arguments&&(o.arguments+=j.function.arguments);return}else{y(x,D,k),o={index:j.index,name:j.function?.name||"",id:j.id||"",arguments:j.function?.arguments||""};return}}if(x.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){y(x,D,k),o={};return}x.choices?.[0]?.delta?.tool_calls?.length&&_.hasTextContent()&&(typeof x.choices[0].index=="number"?x.choices[0].index+=1:x.choices[0].index=1);let R=`data: ${JSON.stringify(x)}
197
+ `))})}if(se?.delta?.tool_calls&&!v&&!_){C++;let le=new Set;for(let be of se.delta.tool_calls){if(v)break;let K=be.index??0;if(le.has(K))continue;if(le.add(K),!y.has(K)){if(x>=0){let E={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
198
+ data: ${JSON.stringify(E)}
197
199
 
198
- `;D.enqueue(k.encode(R))}catch{D.enqueue(k.encode(b+`
199
- `))}}else D.enqueue(k.encode(b+`
200
- `))};try{for(;;){let{done:b,value:_}=await m.read();if(b){f.trim()&&S(f,h,r);break}if(!_||_.length===0)continue;let D;try{D=n.decode(_,{stream:!0})}catch(v){this.logger?.warn("Failed to decode chunk",v);continue}if(D.length===0)continue;if(f+=D,f.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let v=f.split(`
201
- `);f=v.pop()||"";for(let x of v)if(x.trim())try{w(x,{controller:h,encoder:r,hasTextContent:()=>s,setHasTextContent:R=>s=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>c,setReasoningComplete:R=>c=R})}catch(R){this.logger?.error("Error processing line:",x,R),h.enqueue(r.encode(x+`
202
- `))}continue}let k=f.split(`
203
- `);f=k.pop()||"";for(let v of k)if(v.trim())try{w(v,{controller:h,encoder:r,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>a,appendReasoningContent:x=>a+=x,isReasoningComplete:()=>c,setReasoningComplete:x=>c=x})}catch(x){this.logger?.error("Error processing line:",v,x),h.enqueue(r.encode(v+`
204
- `))}}}catch(b){this.logger?.error("Stream error:",b),h.error(b)}finally{try{m.releaseLock()}catch(b){this.logger?.error("Error releasing reader lock:",b)}h.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Iu=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e,n,r){return this.enable?(e.reasoning?(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0):e.model&&String(e.model).startsWith("deepseek")&&(e.enable_thinking=!0),ku(e,n,r),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e,n){if(!this.enable)return e;let r=Su(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return o.choices[0]?.message.reasoning_content&&(o.thinking={content:o.choices[0]?.message.reasoning_content}),r&&as({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=new TextEncoder,s="",a=!1,c=r?Au():null;return ze(e,(f,d)=>{let{controller:h,encoder:m}=d;if(f.startsWith("data: ")&&f.trim()!=="data: [DONE]")try{let S=JSON.parse(f.slice(6)),y=S.choices?.[0]?.delta;if(!y){h.enqueue(m.encode(f+`
205
- `));return}if(y.reasoning_content){s+=typeof y.reasoning_content=="string"?y.reasoning_content:JSON.stringify(y.reasoning_content),c&&cs(c,y);let w={...S,choices:[{...S.choices[0],delta:{...y,thinking:{content:y.reasoning_content}}}]};delete w.choices[0].delta.reasoning_content;let b=`data: ${JSON.stringify(w)}
200
+ `)),x=-1}h=!1,A=!1;let Fe=q();y.set(K,Fe);let Y=$n(be.id)||`call_${Date.now()}_${K}`,ce=be.function?.name||`tool_${K}`,de={type:"content_block_start",index:Fe,content_block:{type:"tool_use",id:Y,name:ce,input:{}}};$(c.encode(`event: content_block_start
201
+ data: ${JSON.stringify(de)}
206
202
 
207
- `;h.enqueue(m.encode(b));return}if(c&&cs(c,y),(y.content||y.tool_calls)&&s&&!a){a=!0;let w=Date.now().toString(),b={...S,choices:[{...S.choices[0],delta:{...S.choices[0].delta,content:null,thinking:{content:s,signature:w}}}]};delete b.choices[0].delta.reasoning_content;let _=`data: ${JSON.stringify(b)}
203
+ `)),x=Fe;let k={id:Y,name:ce,arguments:"",contentBlockIndex:Fe};b.set(K,k)}else if(be.id&&be.function?.name){let Fe=b.get(K);Fe.id.startsWith("call_")&&Fe.name.startsWith("tool_")&&(Fe.id=be.id,Fe.name=be.function.name)}if(be.function?.arguments&&!v&&!_){let Fe=y.get(K);if(Fe===void 0)continue;let Y=b.get(K);Y&&(Y.arguments+=be.function.arguments);try{let ce={type:"content_block_delta",index:Fe,delta:{type:"input_json_delta",partial_json:be.function.arguments}};$(c.encode(`event: content_block_delta
204
+ data: ${JSON.stringify(ce)}
208
205
 
209
- `;h.enqueue(m.encode(_))}if(y.reasoning_content&&delete S.choices[0].delta.reasoning_content,S.choices?.[0]?.delta&&Object.keys(S.choices[0].delta).length>0){a&&S.choices[0].index++;let w=`data: ${JSON.stringify(S)}
206
+ `))}catch{try{let ce=be.function.arguments.replace(new RegExp("\\p{Cc}","gu"),"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),de={type:"content_block_delta",index:Fe,delta:{type:"input_json_delta",partial_json:ce}};$(c.encode(`event: content_block_delta
207
+ data: ${JSON.stringify(de)}
210
208
 
211
- `;h.enqueue(m.encode(w))}}catch{h.enqueue(m.encode(f+`
212
- `))}else h.enqueue(m.encode(f+`
213
- `))},{onComplete:()=>{c&&as(Eu(c),n)}})}return e}};var Nu=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Bu=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function Gp(t){let e=t?.input_tokens||0,n=t?.cache_read_input_tokens||0,r=t?.cache_creation_input_tokens||0,o=t?.output_tokens||0;return{completion_tokens:o,prompt_tokens:e+n+r,prompt_tokens_details:{cached_tokens:n,cache_write_tokens:r},total_tokens:e+n+r+o}}function Nk(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],a=Na(s.role,{assistant:"assistant"}),c=[];if(s.role==="tool"){let l=s.content;Array.isArray(l)?l=l.filter(f=>f.type==="text").map(f=>f.text).join(`
214
- `):typeof l=="object"&&l!==null&&(l=JSON.stringify(l)),c.push({type:"tool_result",tool_use_id:s.tool_call_id,content:l,...s.cache_control?{cache_control:s.cache_control}:{}})}else typeof s.content=="string"?c.push({type:"text",text:s.content,...s.cache_control?{cache_control:s.cache_control}:{}}):Array.isArray(s.content)&&(s.content.forEach(f=>{f.type==="text"&&c.push({type:"text",text:f.text||"",...f.cache_control?{cache_control:f.cache_control}:{}})}),Ba(s.content).forEach(f=>{c.push(Ma(f,"claude"))})),s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(l=>{c.push({type:"tool_use",id:l.id,name:l.function.name,input:JSON.parse(l.function.arguments||"{}")})});c.length>0&&e.push({role:a,content:c})}let r={anthropic_version:"vertex-2023-10-16",messages:ja(e,"content"),max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(o=>{let s=Ro(o);return{name:s.name,description:s.description,input_schema:s.parameters,...o.cache_control?{cache_control:o.cache_control}:{}}})),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),Lr(r)}function Bk(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"&&a.source?{type:"image_url",image_url:{url:a.source.data},media_type:a.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function ju(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o;r.tool_use&&r.tool_use.length>0&&(o=r.tool_use.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:JSON.stringify(a.input)}})));let s={id:r.id,choices:[{finish_reason:r.stop_reason||null,index:0,message:{content:r.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:Gp(r.usage)};return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r={};return ze(t,(s,a)=>{let{controller:c,encoder:l}=a;if(s.startsWith("data: ")){let f=s.slice(6).trim();if(f){n?.debug({chunkStr:f},`${e} chunk:`);try{let d=JSON.parse(f);if(d.type==="message_start"){r=d.message?.usage||d.usage||{};let h={choices:[],created:parseInt(new Date().getTime()/1e3+"",10),id:d.message?.id||d.id||"",model:d.message?.model||d.model||"",object:"chat.completion.chunk",usage:Gp(r)};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
209
+ `))}catch(ce){this.logger?.error(ce)}}}}}if(se?.finish_reason&&!v&&!_){if(w===0&&C===0&&this.logger?.warn("No content in the stream response!"),x>=0){let le={type:"content_block_stop",index:x};$(c.encode(`event: content_block_stop
210
+ data: ${JSON.stringify(le)}
215
211
 
216
- `))}else if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let h={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
212
+ `)),x=-1}if(!v){let be={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[se.finish_reason]||"end_turn";y.size>0&&be==="end_turn"&&(be="tool_use"),f={type:"message_delta",delta:{stop_reason:be,stop_sequence:null},usage:Ec(Q.usage)}}break}}catch(Q){this.logger?.error(`parseError: ${Q.name} message: ${Q.message} stack: ${Q.stack} data: ${ee}`)}}}H()}catch(te){ae(te)}finally{if(r===X&&(r=null),X)try{X.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:async i=>{o?.();let c=r;r=null,c&&await c.cancel(i).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${i}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[];if(r.message?.thinking?.content&&o.push({type:"thinking",thinking:r.message.thinking.content,signature:r.message.thinking.signature}),r.message.annotations){let c=`srvtoolu_${mn()}`;o.push({type:"server_tool_use",id:c,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:c,content:r.message.annotations.map(u=>({type:"web_search_result",url:u.url_citation.url,title:u.url_citation.title}))})}r.message.content&&o.push({type:"text",text:r.message.content}),r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(c=>{if(!("function"in c)||!c.function)return;let u={};try{let f=c.function.arguments||"{}";typeof f=="object"?u=f:typeof f=="string"&&(u=JSON.parse(f))}catch{u={text:c.function.arguments||""}}o.push({type:"tool_use",id:$n(c.id)??c.id,name:c.function.name,input:u})});let s=String(r.finish_reason||""),i={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":s==="length"?"max_tokens":s==="tool_calls"?"tool_use":s==="content_filter"?"stop_sequence":s==="model_context_window_exceeded"?"model_context_window_exceeded":"end_turn",stop_sequence:null,usage:{...Ec(e.usage),...r.message.annotations?.length?{server_tool_use:{web_search_requests:r.message.annotations.length}}:{}}};return this.logger.debug({reqId:n.req.id,result:i},"Conversion complete, final Anthropic response"),i}catch{throw W(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var hD=new Set(["type","format","title","description","nullable","enum","maxItems","minItems","properties","required","minProperties","maxProperties","minLength","maxLength","pattern","example","anyOf","propertyOrdering","default","items","minimum","maximum","additionalProperties","allOf","oneOf"]);function vr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>vr(r,e));let n={};for(let r in t){if(e!=="properties"&&!hD.has(r))continue;let o=t[r];if(!(r==="enum"&&t.type&&t.type!=="string")&&!(r==="format"&&t.type==="string"&&o&&!["enum","date-time"].includes(o))&&!(r==="format"&&o==="uri")&&r!=="$schema")if(r==="properties"&&typeof o=="object"&&!Array.isArray(o)){let s={};for(let i in o)s[i]=vr(o[i]);n[r]=s}else r==="items"?n[r]=vr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>vr(s,r)):n[r]=o}if(Array.isArray(n.required)&&n.properties){let r=new Set(Object.keys(n.properties));n.required=n.required.filter(o=>r.has(o)),n.required.length===0&&delete n.required}return n}function Ho(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ho);let e={};for(let h in t){let _=t[h];if(h==="properties"&&_&&typeof _=="object"){let b={};for(let y in _)b[y]=Ho(_[y]);e[h]=b}else h==="items"?e[h]=Ho(_):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(_)?e[h]=_.map(Ho):e[h]=_}let n=e.anyOf||e.oneOf;if(!Array.isArray(n)||e.type)return e;let r=n.filter(h=>h&&typeof h=="object"),o=r.find(h=>h.type)||r[0];if(!o)return e;let{anyOf:s,oneOf:i,description:c,...u}=e,f=[...new Set(r.filter(h=>h!==o).map(h=>String(h.description||h.type||"").split(" (alternatives:")[0]).filter(Boolean))],d={...o,...u},p=[c,o.description,...f].filter(Boolean);return p.length&&(d.description=f.length?`${p[0]} (alternatives: ${f.join("; ")})`:p[0]),d}function Ac(t){return!t||typeof t!="object"?t:vr(t)}var Si=["minimal","low","medium","high"];function mD(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function gD(t){let e=mD(t);return e?e.includes("-image")||e.includes("imagen")?{kind:"none"}:e.startsWith("claude")?{kind:"budget",min:1024,max:64e3,requireMin:!0}:/^gemini-3(\.\d+)?\b/.test(e)||e.startsWith("gemini-pro-agent")?/^gemini-3-pro\b/.test(e)?{kind:"level",levels:["low","high"]}:e.includes("flash")?{kind:"level",levels:Si}:{kind:"level",levels:["low","medium","high"]}:/^gemini-2\.5/.test(e)?e.includes("pro")?{kind:"budget",min:128,max:32768}:{kind:"budget",min:0,max:24576}:{kind:"includeOnly"}:{kind:"includeOnly"}}function yD(t,e){let n=t.toLowerCase(),r=Si.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max")return r[r.length-1];let o=Si.indexOf(n);return o<0?r[r.length-1]:r.find(s=>Si.indexOf(s)>=o)??r[r.length-1]}function _D(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function bD(t,e,n){return Math.min(Math.max(t,e),n)}function OC(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=gD(t.model);if(r.kind==="none")return;let o=e.effort?.toLowerCase(),s=o==="none"||e.enabled===!1;if(r.kind==="includeOnly")return s?void 0:{includeThoughts:!0};if(r.kind==="level"){let f=Si.filter(d=>r.levels.includes(d));return s?{includeThoughts:!1,thinkingLevel:f[0]}:o?{includeThoughts:!0,thinkingLevel:yD(o,r.levels)}:{includeThoughts:!0}}if(s)return r.min===0?{includeThoughts:!1,thinkingBudget:0}:void 0;let i=e.max_tokens,c=typeof i=="number"?i:o?_D(o,r.max):void 0;if(typeof c!="number")return{includeThoughts:!0};let u=bD(c,r.min,r.max);if(t.max_tokens&&u>=t.max_tokens&&(u=t.max_tokens-1),u<r.min){if(r.requireMin)return;u=r.min}return{includeThoughts:!0,thinkingBudget:u}}var no=new Map,PC=(t,e)=>`${t||"default"}${e}`;function IC(t,e,n){if(!e||!n)return;let r=PC(t,e);for(no.delete(r),no.set(r,{signature:n,expiresAt:Date.now()+216e5});no.size>4096;){let o=no.keys().next();if(o.done)break;no.delete(o.value)}}function FC(t,e){if(!e)return;let n=PC(t,e),r=no.get(n);if(r){if(r.expiresAt<=Date.now()){no.delete(n);return}return r.signature}}function CD(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var Wo={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function wD(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(Wo).includes(r)?r:Wo.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Wo).includes(o)?o:Wo.TYPE_UNSPECIFIED})}}}function Ei(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&wD(t.type,e);for(let[i,c]of Object.entries(t))if(c!=null)if(i=="type"){if(c==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(c))continue;let u=String(c).toUpperCase();e.type=Object.values(Wo).includes(u)?u:Wo.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=Ei(c);else if(r.includes(i)){let u=[];for(let f of Array.isArray(c)?c:[]){if(f.type=="null"){e.nullable=!0;continue}u.push(Ei(f))}e[i]=u}else if(o.includes(i)){let u={};for(let[f,d]of Object.entries(c))u[f]=Ei(d);e[i]=u}else{if(i==="additionalProperties")continue;e[i]=c}if(e.type==="ARRAY"&&!e.items&&(e.items={type:"STRING"}),Array.isArray(e.required)&&e.properties){let i=new Set(Object.keys(e.properties));e.required=e.required.filter(c=>i.has(c)),e.required.length===0&&delete e.required}return e}function kD(t,e){let n=r=>e?.collapseUnions?Ho(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=vr(r.parameters);r.parameters=n(Ei(o))}if(r.response){let o=vr(r.response);r.response=n(Ei(o))}}return t}var MC="skip_thought_signature_validator";function Tc(t,e){let n=[],r=t.tools||[],o=r.filter(C=>zo(C).name!=="web_search").map(C=>{let{name:v,description:A,parameters:T}=zo(C);return{name:AC(v),description:A,parameters:T??{type:"object",properties:{}}}});o?.length&&n.push(kD({functionDeclarations:o},{collapseUnions:CD(t.model)})),r.find(C=>zo(C).name==="web_search")&&n.push({googleSearch:{}});let i=[],c=t.messages||[],u=[],f=C=>{if(typeof C=="string")C&&u.push(C);else if(Array.isArray(C))for(let v of C)v?.type==="text"&&v.text?u.push(v.text):typeof v=="string"&&v&&u.push(v)};t.system&&f(t.system);for(let C of c)C.role==="system"&&f(C.content);let d=c.filter(C=>C.role==="tool"),p=c.filter(C=>C.role!=="tool"&&C.role!=="system"),h=e?.thoughtSignatureFallback!=="none";p.forEach(C=>{let v=bc(C.role,{assistant:"model"}),A=[],T=C.thinking?.signature,x=T?.startsWith("ccr_")?void 0:T,O=$=>v==="model"&&($==="(no content)"||$.startsWith(hp));if(x&&v==="model"&&A.push({thought:!0,text:C.thinking?.content||"",thoughtSignature:x}),typeof C.content=="string")C.content&&!O(C.content)&&A.push({text:C.content});else if(Array.isArray(C.content))C.content.forEach(H=>{if(H.type==="text"){let ae=H.text||"";ae&&!O(ae)&&A.push({text:ae})}}),Cc(C.content).forEach(H=>{A.push(kc(H,"gemini"))});else if(C.content&&typeof C.content=="object")if(C.content.text){let $=C.content.text;O($)||A.push({text:$})}else A.push({text:JSON.stringify(C.content)});let q=Array.isArray(C.tool_calls)?C.tool_calls.map(($,H)=>{let ae=$.id||`tool_${Math.random().toString(36).substring(2,15)}`,X=$.thought_signature||FC(e?.signatureScope,ae);return!X&&H===0&&(X=x||(h?MC:void 0)),{toolCall:$,id:ae,signature:X}}):[];if(q.length>0&&A.push(...q.map(({toolCall:$,id:H,signature:ae})=>({functionCall:{id:H,name:$.function.name,args:JSON.parse($.function.arguments||"{}")},...ae&&{thoughtSignature:ae}}))),A.length===0&&A.push({text:""}),i.push({role:v,parts:A}),v==="model"&&q.length>0){let $=q.map(({toolCall:H,id:ae})=>{let te=d.find(Z=>Z.tool_call_id===H.id)?.content;return Array.isArray(te)?te=te.filter(Z=>Z.type==="text").map(Z=>Z.text).join(`
213
+ `):typeof te=="object"&&te!==null&&(te=JSON.stringify(te)),{functionResponse:{id:ae,name:H?.function?.name,response:{result:te}}}});i.push({role:"user",parts:$})}});let _=wc(i,"parts"),b={},y=OC(t);y&&(b.thinkingConfig=y),t.max_tokens&&(b.maxOutputTokens=t.max_tokens),t.temperature!==void 0&&(b.temperature=t.temperature);let w={contents:_.length?_:[{role:"user",parts:[{text:""}]}],tools:n.length?n:void 0,generationConfig:b};if(u.length&&(w.systemInstruction={parts:[{text:u.join(`
217
214
 
218
- `))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let h={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
215
+ `)}]}),t.tool_choice){let C={functionCallingConfig:{}};t.tool_choice==="auto"?C.functionCallingConfig.mode="auto":t.tool_choice==="none"?C.functionCallingConfig.mode="none":t.tool_choice==="required"?C.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(C.functionCallingConfig.mode="any",C.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),w.toolConfig=C}return w}function Rc(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,i=t.stream,c=t.tool_choice,u={messages:[],model:r,max_tokens:o,temperature:s,stream:i,tool_choice:c};return Array.isArray(e)&&e.forEach(f=>{typeof f=="string"?u.messages.push({role:"user",content:f}):typeof f.text=="string"?u.messages.push({role:"user",content:f.text||null}):f.role==="user"?u.messages.push({role:"user",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):f.role==="model"&&u.messages.push({role:"assistant",content:f?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(n)&&(u.tools=[],n.forEach(f=>{let d=f.functionDeclarations;Array.isArray(d)&&d.forEach(p=>{u.tools.push({type:"function",function:{name:p.name,description:p.description,parameters:p.parameters}})})})),u}function NC(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===MC||r.startsWith("ccr_")||IC(t,n.id,r)})}async function xc(t,e,n,r){let o=r||e;if(t.headers.get("Content-Type")?.includes("application/json")){let s=await t.json();if(n?.debug({response:s},`${e} response:`),t.status>=400){let v=(s.error?.message||"").toLowerCase();if(["user input too long","input too long","prompt is too long","exceeds the token limit","request payload size exceeds","context_length_exceeded"].some(T=>v.includes(T))){let T={id:`ctxexceeded_${Date.now()}`,choices:[{finish_reason:"model_context_window_exceeded",index:0,message:{content:"",role:"assistant"}}],created:Math.floor(Date.now()/1e3),model:"",object:"chat.completion",usage:{completion_tokens:0,prompt_tokens:0,total_tokens:0}};return new Response(JSON.stringify(T),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}if(!s.candidates||s.candidates.length===0)return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers});let i="",c,u=s.candidates[0]?.content?.parts||[],f=[];for(let C of u)C.text&&C.thought===!0?i+=wi(C.text):f.push(C);c=u.find(C=>C.thoughtSignature)?.thoughtSignature,i&&!c&&(c=`ccr_${+new Date}`);let d=f?.filter(C=>C.functionCall)?.map(C=>({id:C.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})},thought_signature:C.thoughtSignature||C.thought_signature||void 0}))||[];c&&d.length>0&&!d[0].thought_signature&&(d[0].thought_signature=c),NC(o,d);let p=f?.filter(C=>C.text)?.map(C=>wi(C.text||""))?.join(`
216
+ `)||"",h=s.candidates[0],_=p&&p!=="(no content)"?p:"",b=!_&&d.length===0?mp(h):null,y=Ci(h?.finishReason),w={id:s.responseId,choices:[{finish_reason:d.length>0?"tool_calls":y,index:0,message:{content:b||_,role:"assistant",tool_calls:d.length>0?d:void 0,...c&&i&&{thinking:{content:i,signature:c}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:s.modelVersion,object:"chat.completion",usage:{completion_tokens:s.usageMetadata?.candidatesTokenCount||0,prompt_tokens:s.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:s.usageMetadata?.cachedContentTokenCount||0},total_tokens:s.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:s.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(w),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let s=0,i=-1,c=null,u=null,f=null,d=(w,C)=>{w.controller.enqueue(w.encoder.encode(`data: ${JSON.stringify(C)}
219
217
 
220
- `))}else if(d.type==="content_block_delta"&&d.delta?.type==="thinking_delta"){let h={choices:[{delta:{thinking:{content:d.delta.thinking||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
218
+ `))},p=w=>({completion_tokens:w?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w?.usageMetadata?.cachedContentTokenCount||0},total_tokens:w?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w?.usageMetadata?.thoughtsTokenCount||0}}),h=w=>w?.groundingMetadata?.groundingChunks?.map((C,v)=>{let A=w?.groundingMetadata?.groundingSupports?.filter(T=>T.groundingChunkIndices?.includes(v));return{type:"url_citation",url_citation:{url:C?.web?.uri||"",title:C?.web?.title||"",content:A?.[0]?.segment?.text||"",start_index:A?.[0]?.segment?.startIndex||0,end_index:A?.[0]?.segment?.endIndex||0}}})||[],_=(w,C,v)=>{let A=v?.mode||"direct";A==="direct"&&s++;let T={choices:[{delta:{role:"assistant",content:C},finish_reason:v?.finishReason??(A==="direct"||A==="finish"?Ci(v?.candidate?.finishReason):null),index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:v?.chunk?.responseId||"",model:v?.chunk?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(A==="direct"||A==="finish"){T.usage=p(v?.chunk);let x=h(v?.candidate);x.length>0&&(T.choices[0].delta.annotations=x)}d(w,T)},b=new _c({thinking:(w,C)=>{c&&d(c,{choices:[{delta:{role:"assistant",content:null,thinking:{content:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},signature:(w,C)=>{c&&d(c,{choices:[{delta:{role:"assistant",content:null,thinking:{signature:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},content:(w,C)=>{c&&_(c,w,C)}});return Ie(t,(w,C)=>{if(c=C,w.startsWith("data: ")){let v=w.slice(6).trim();if(v){n?.debug({chunkStr:v},`${e} chunk:`);try{let A=JSON.parse(v);if(!A.candidates||!A.candidates[0]){n?.debug({chunkStr:v},"Invalid chunk structure");return}let T=A.candidates[0];u=A,f=T;let x=T.content?.parts||[];x.filter(X=>X.text&&X.thought===!0).forEach(X=>{b.processThinking(wi(X.text),A)});let O=x.filter(X=>X.functionCall).map(X=>({id:X.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:X.functionCall?.name,arguments:JSON.stringify(X.functionCall?.args||{})},thought_signature:X.thoughtSignature||X.thought_signature||void 0})),q=x.filter(X=>X.text&&X.thought!==!0).map(X=>wi(X.text||"")).join(`
219
+ `),$=x.find(X=>X.thoughtSignature)?.thoughtSignature;$&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=$),NC(o,O);let H=!!(q&&q!=="(no content)")||O.length>0||!!T.finishReason;if(q&&q!=="(no content)"&&A.modelVersion?.includes("3")&&b.shouldDeferContent(!!T.finishReason,O.length>0))b.bufferContent(q);else if(q&&q!=="(no content)"){if(b.hasThinkingContent&&!b.signatureSent&&H&&!$){let X=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,A,{beforeFlush:X?()=>{s++}:void 0,flushMeta:X?{chunk:A,candidate:T,mode:"buffered",finishReason:null}:void 0})}b.processContent(q,A,T)}$&&(O.length>0&&!b.hasThinkingContent&&!q&&!b.contentSent?b.acknowledgeSignature():b.processSignatureWithMeta($,A,{beforeFlush:()=>{s++},flushMeta:{chunk:A,candidate:T,mode:"buffered"}}));let ae=i<0&&O.length===0&&!q?mp(T):null;if(!q&&O.length===0&&i<0&&T.finishReason&&!ae&&b.needsContentPlaceholder&&b.emitContentPlaceholder("(no content)",{chunk:A,candidate:T}),!$&&!q&&b.hasThinkingContent&&!b.signatureSent&&H){let X=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,A,{beforeFlush:X?()=>{s++}:void 0,flushMeta:X?{chunk:A,candidate:T,mode:"buffered",finishReason:null}:void 0})}if(q&&A.modelVersion?.includes("3")&&b.hasBufferedContent&&!$&&O.length===0&&!T.finishReason)return;O.length>0&&O.forEach((X,te)=>{s++,i++;let Z=T.finishReason!=null&&te===O.length-1?"tool_calls":null,De={choices:[{delta:{role:"assistant",tool_calls:[{...X,index:i}]},finish_reason:Z,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:A.responseId||"",model:A.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:p(A)},qe=h(T);qe.length>0&&(De.choices[0].delta.annotations=qe),d(C,De)}),T.finishReason&&(b.hasBufferedContent?b.finalize(A,T,{beforeFlush:()=>{b.signatureSent||s++}}):!q&&O.length===0&&(s++,_(C,ae||"",{chunk:A,candidate:T,mode:"finish",...i>=0?{finishReason:"tool_calls"}:{}})))}catch(A){n?.error(`Error parsing ${e} stream chunk`,v,A.message)}}}},{onComplete:w=>{c=w,(b.hasBufferedContent||b.hasThinkingContent&&!b.signatureSent)&&b.finalize(u||void 0,f||void 0,{beforeFlush:()=>{b.signatureSent||s++}})}})}return t}var jC=require("crypto"),SD=15e3,ED=256,Wn=new Map,Cp=new Map;function BC(t){return(0,jC.createHash)("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function vD(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function AD(t){return Math.floor(JSON.stringify(t).length/4)}function TD(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function UC(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function Dc(t,e){let n=Date.now();for(let[r,o]of Wn)o.expiresAt<=n&&Wn.delete(r);for(Wn.delete(t),Wn.set(t,e);Wn.size>ED;){let r=Wn.keys().next().value;if(r===void 0)break;Wn.delete(r)}}async function Oc(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=TD(e);if(Object.keys(s).length===0||AD(s)<vD(n))return e;let i=BC(o),c=[String(r),i,n,BC(s)].join(":"),u=Date.now(),f=Wn.get(c);if(f&&f.expiresAt>u)return f.name?UC(e,f.name):e;f&&Wn.delete(c);let d=3600,p={model:n,...s,ttl:`${d}s`},h=Cp.get(c);h||(h=(async()=>{try{let b=await fetch(r,{method:"POST",headers:Object.fromEntries(Object.entries({"Content-Type":"application/json",...o}).filter(([,w])=>w!==void 0)),body:JSON.stringify(p),signal:AbortSignal.timeout(SD)});if(!b.ok){t.logger?.debug?.({status:b.status},"Gemini cached-content create failed; using implicit cache"),Dc(c,{expiresAt:Date.now()+300*1e3});return}let y=await b.json();if(!y?.name){t.logger?.debug?.("Gemini cached-content response had no resource name; using implicit cache"),Dc(c,{expiresAt:Date.now()+300*1e3});return}return Dc(c,{name:y.name,expiresAt:Date.now()+(d-30)*1e3}),y.name}catch(b){t.logger?.debug?.({error:b?.message||String(b)},"Gemini cached-content create errored; using implicit cache"),Dc(c,{expiresAt:Date.now()+300*1e3});return}finally{Cp.delete(c)}})(),Cp.set(c,h));let _=await h;return _?UC(e,_):e}var Pc=class{constructor(e){this.options=e;this.cachedContent=e?.cachedContent!==!1,this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}options;static TransformerName="gemini";logger;name="gemini";endPoint="/v1beta/models/:modelAndAction";cachedContent;thoughtSignatureFallback;async transformRequestIn(e,n,r){let o=e.model||(typeof r?.req?.model=="string"?r.req.model:Array.isArray(r?.req?.model)?r.req.model.join(","):"")||n.models?.[0]||"",s=Tc(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await Oc({body:s,modelResource:o.startsWith("models/")?o:`models/${o}`,createUrl:new URL("../cachedContents",n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0},logger:this.logger}):s,config:{url:new URL(`./${o}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}async transformRequestOut(e){return Rc(e)}async transformResponseOut(e,n){return xc(e,this.name,this.logger,n?.provider?.name||this.name)}};async function RN(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>tt(ul(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
220
+ 1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
221
+ 2. Run "gcloud auth application-default login"
222
+ 3. Use Google Cloud environment with default service account`,{cause:e})}}var ll=class{static TransformerName="vertex-gemini";logger;name="vertex-gemini";thoughtSignatureFallback;constructor(e){this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}async transformRequestIn(e,n,r){let o=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let h=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),_=JSON.parse(h);_&&_.project_id&&(o=_.project_id)}catch(p){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",p)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await RN(this.logger),c=e.model||n.models?.[0]||"",u=n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`,f=`projects/${o}/locations/${s}/publishers/google/models/${c}`;return{body:await Oc({body:Tc(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name}),modelResource:f,createUrl:new URL(`./v1beta1/projects/${o}/locations/${s}/cachedContents`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0},logger:this.logger}),config:{url:new URL(`./v1beta1/${f}:${e.stream?"streamGenerateContent":"generateContent"}`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Rc(e)}async transformResponseOut(e,n){return xc(e,this.name,this.logger,n?.provider?.name||this.name)}};function dl(){return{content:"",isComplete:!1,hasContent:!1}}function fl(t,e){t.content+=e,t.hasContent=!0}function pl(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Nr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function ws(t){if(t.reasoning_content){let e=t.reasoning_content;return typeof e=="string"?e:typeof e?.text=="string"?e.text:null}if(t.reasoning){let e=t.reasoning;return typeof e=="string"?e:null}return null}function Mr(t){delete t.reasoning_content,delete t.reasoning}var fv=require("node:crypto"),lv=360*60*1e3,xN=4096,tg="__ccrDeepseekReasoning",ng=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>lv){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,n),n.reasoning}}put(e,n){n&&(this.cache.delete(e),this.cache.set(e,{reasoning:n,createdAt:Date.now()}),this.prune())}prune(){for(let[e,n]of this.cache)Date.now()-n.createdAt>lv&&this.cache.delete(e);for(;this.cache.size>xN;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},hl=new ng;function rg(t){return Array.isArray(t)?t.map(rg):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=rg(t[n]),e),{}):t}function _o(t){return JSON.stringify(rg(t))}function ml(t){return(0,fv.createHash)("sha256").update(t).digest("hex")}function pv(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):_o(e)).join(""):_o(t)}function og(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:_o(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function hv(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function mv(t){let e=og(t);return ml(_o({...e,id:void 0}))}function gv(t){return ml(_o({content:pv(t.content),tool_calls:(t.tool_calls||[]).map(e=>og(e))}))}function DN(t){let e={role:t.role,content:pv(t.content)};return t.name&&(e.name=t.name),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.tool_calls?.length&&(e.tool_calls=t.tool_calls.map(n=>og(n))),e}function dv(t,e){let n=t.filter(r=>r.role!=="system").map(r=>DN(r));return ml(_o({namespace:e,messages:n}))}function ON(t){if(typeof t.reasoning_content=="string"&&t.reasoning_content.length>0)return t.reasoning_content;if(typeof t.thinking?.content=="string"&&t.thinking.content.length>0)return t.thinking.content}function yv(t,e){if(t.role!=="assistant")return 0;let n=ON(t);if(!n)return 0;let r=[`scope:${e}:signature:${gv(t)}`];return r.push(...hv(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${mv(o)}`)),r.forEach(o=>hl.put(o,n)),r.length}function PN(t,e){let n=hl.get(`scope:${e}:signature:${gv(t)}`);if(n)return n;for(let r of hv(t)){let o=hl.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=hl.get(`scope:${e}:tool_call_signature:${mv(r)}`);if(o)return o}}function IN(t,e){if(t.tool_calls?.length)return!0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool")return!0;if(r.role==="user"||r.role==="system")return!1}return!1}function FN(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek"),i=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&i}function NN(t,e){return ml(_o({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function gl(t,e,n){if(!FN(t,e))return n?.req&&delete n.req[tg],{restoredFromCache:0,restoredFromThinking:0};let r=NN(t,e),o=[],s=0,i=0;for(let c of t.messages){if(c.role==="assistant"){let u=dv(o,r);if(IN(c,o)&&!(typeof c.reasoning_content=="string"&&c.reasoning_content.length>0?c.reasoning_content:void 0)){let p=typeof c.thinking?.content=="string"&&c.thinking.content.length>0?c.thinking.content:void 0;if(p)c.reasoning_content=p,i++;else{let h=PN(c,u);h&&(c.reasoning_content=h,s++)}}yv(c,u)}o.push(c)}return n?.req&&(n.req[tg]={enabled:!0,namespace:r,requestScope:dv(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function _v(t){return t?.req?.[tg]}function yl(t){return _v(t)?.enabled===!0}function ks(t,e){if(!t)return 0;let n=_v(e);return n?yv(t,n.requestScope):0}function _l(){return{content:"",reasoning:"",toolCalls:new Map}}function Ss(t,e){e&&(typeof e.reasoning_content=="string"&&(t.reasoning+=e.reasoning_content),typeof e.content=="string"&&(t.content+=e.content),Array.isArray(e.tool_calls)&&e.tool_calls.forEach((n,r)=>{let o=typeof n.index=="number"?n.index:r,s=t.toolCalls.get(o)||{id:"",type:"function",function:{name:"",arguments:""}};typeof n.id=="string"&&n.id.length>0&&(s.id=n.id),typeof n.type=="string"&&n.type.length>0&&(s.type=n.type);let i=n.function||{};typeof i.name=="string"&&i.name.length>0&&(s.function.name+=i.name),typeof i.arguments=="string"&&i.arguments.length>0&&(s.function.arguments+=i.arguments),t.toolCalls.set(o,s)}))}function bl(t){if(!t.reasoning)return null;let e=Array.from(t.toolCalls.entries()).sort(([n],[r])=>n-r).map(([,n])=>n).filter(n=>typeof n.id=="string"&&n.id.length>0&&typeof n.function?.name=="string"&&n.function.name.length>0);return!t.content&&e.length===0?null:{role:"assistant",content:t.content||null,tool_calls:e.length>0?e:void 0,reasoning_content:t.reasoning}}function bv(t){let e=t?.usage;!e||e.prompt_cache_hit_tokens===void 0||(e.prompt_tokens_details={...e.prompt_tokens_details||{},cached_tokens:e.prompt_cache_hit_tokens||0})}var Cl=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Je(e.messages),e.tools=Ve(e.tools),gl(e,n,r),e}async transformResponseOut(e,n){let r=yl(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return bv(o),r&&ks({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=dl(),s=r?_l():null;return Ie(e,(i,c)=>{if(!i.trim()){c.controller.enqueue(Re(i,c.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){c.controller.enqueue(Re(i,c.encoder));return}try{let u=i.slice(5).trim(),f=JSON.parse(u);bv(f);let d=f.choices?.[0]?.delta;if(!d){c.controller.enqueue(Ee(JSON.stringify(f),c.encoder));return}let p=ws(d);if(p){s&&Ss(s,d),fl(o,p);let h=Nr(f,{content:p});Mr(h.choices[0].delta),c.controller.enqueue(Ee(JSON.stringify(h),c.encoder));return}if(s&&Ss(s,d),d.content&&o.hasContent&&!o.isComplete){let{content:h,signature:_}=pl(o),b=Nr(f,{content:h,signature:_});Mr(b.choices[0].delta),b.choices[0].delta.content=null,c.controller.enqueue(Ee(JSON.stringify(b),c.encoder))}d.reasoning_content&&delete d.reasoning_content,f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0&&(o.isComplete&&f.choices[0].index++,c.controller.enqueue(Ee(JSON.stringify(f),c.encoder)))}catch{c.controller.enqueue(Re(i,c.encoder))}},{onComplete:()=>{s&&ks(bl(s),n)}})}return e}};var wl=class{name="tooluse";async transformRequestIn(e,n,r){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice=e.tool_choice||"required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
223
+ IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
224
+ Examples:
225
+ 1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
226
+ 2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message.tool_calls?.length&&n?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let r=n?.choices[0]?.message.tool_calls[0],o=JSON.parse(r.function.arguments||"{}");n.choices[0].message.content=o.response||"",delete n.choices[0].message.tool_calls}return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=-1,r="";return Ie(e,(s,i)=>{let{controller:c,encoder:u}=i;if(s.startsWith("data: ")&&s.trim()!=="data: [DONE]")try{let f=JSON.parse(s.slice(6));if(f.choices[0]?.delta?.tool_calls?.length){let d=f.choices[0].delta.tool_calls[0];if(d.function?.name==="ExitTool"){n=d.index;return}else if(n>-1&&d.index===n&&d.function.arguments){r+=d.function.arguments;try{let p=JSON.parse(r);f.choices=[{delta:{role:"assistant",content:p.response||""}}];let h=`data: ${JSON.stringify(f)}
227
+
228
+ `;c.enqueue(u.encode(h))}catch{}return}}if(f.choices?.[0]?.delta&&Object.keys(f.choices[0].delta).length>0){let d=`data: ${JSON.stringify(f)}
229
+
230
+ `;c.enqueue(u.encode(d))}}catch{c.enqueue(u.encode(s+`
231
+ `))}else c.enqueue(u.encode(s+`
232
+ `))})}return e}};var kl=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=Yt(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=Xr(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=hi(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=Qr(e):s.includes("gemini")?e=Qr(e):e={...e,messages:Je(e.messages),tools:Ve(e.tools)},e.model.includes("claude")?e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(c=>{c.type==="image_url"&&(c.image_url.url.startsWith("http")||(c.image_url.url=`data:${c.media_type};base64,${c.image_url.url}`),delete c.media_type)})}):e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(c=>{c.type==="image_url"&&(c.image_url.url.startsWith("http")||(c.image_url.url=`${c.image_url.url}`),delete c.media_type)})}),Object.assign(e,this.options||{}),o&&(e.session_id=o,e.prompt_cache_key=o),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=dl(),r=!1,o=!1;return Ie(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Re(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Re(s,i.encoder));return}try{let c=s.slice(6),u=JSON.parse(c);u.usage&&(this.logger?.debug({usage:u.usage,hasToolCall:o},"usage"),u.choices[0].finish_reason=o?"tool_calls":"stop"),u.choices?.[0]?.finish_reason==="error"&&i.controller.enqueue(Ee(JSON.stringify({error:u.choices?.[0]?.error}),i.encoder)),u.choices?.[0]?.delta?.content&&!r&&(r=!0);let f=u.choices?.[0]?.delta,d=f?ws(f):null;if(d){fl(n,d);let p=Nr(u,{content:d});Mr(p.choices[0].delta),i.controller.enqueue(Ee(JSON.stringify(p),i.encoder));return}if(f?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=pl(n),_=Nr(u,{content:p,signature:h});Mr(_.choices[0].delta),_.choices[0].delta.content=null,i.controller.enqueue(Ee(JSON.stringify(_),i.encoder))}f?.reasoning&&delete f.reasoning,f?.tool_calls?.length&&!Number.isNaN(parseInt(f.tool_calls[0].id,10))&&f.tool_calls.forEach(p=>{p.id=`call_${mn()}`}),f?.tool_calls?.length&&!o&&(o=!0),f?.tool_calls?.length&&r&&(typeof u.choices[0].index=="number"?u.choices[0].index+=1:u.choices[0].index=1),i.controller.enqueue(Ee(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Re(s,i.encoder))}})}return e}};var Sl=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}options;static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var El=class{name="groq";async transformRequestIn(e){return e.messages=Je(e.messages),e.tools=Ve(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=Ac(n.function.parameters))}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=!1;return Ie(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Re(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Re(r,o.encoder));return}try{let s=r.slice(5).trim(),i=JSON.parse(s);if(i.error)throw new Error(JSON.stringify(i));i.choices?.[0]?.delta?.content&&!n&&(n=!0),i.choices?.[0]?.delta?.tool_calls?.length&&i.choices[0].delta.tool_calls.forEach(c=>{c.id=`call_${mn()}`}),i.choices?.[0]?.delta?.tool_calls?.length&&n&&(typeof i.choices[0].index=="number"?i.choices[0].index+=1:i.choices[0].index=1),o.controller.enqueue(Ee(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Re(r,o.encoder))}})}return e}};var vl=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{n.cache_control&&delete n.cache_control}),e}};var Dv=tt(Jf());var Qn=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function Cv(t){return/^[0-9A-Fa-f]$/.test(t)}function er(t){return t>="0"&&t<="9"}function wv(t){return t>=" "}function vs(t){return`,:[]/{}()
233
+ +`.includes(t)}function sg(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Al(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var ig=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,ag=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function cg(t){return`,[]/{}
234
+ +`.includes(t)}function ug(t){return As(t)||MN.test(t)}var MN=/^[[{\w-]$/;function lg(t){return t===`
235
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Zn(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function kv(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function Sv(t,e){let n=t.charCodeAt(e);return n===160||n===6158||n>=8192&&n<=8203||n===8239||n===8287||n===12288||n===65279}function As(t){return dg(t)||Tl(t)}function dg(t){return t==='"'||t==="\u201C"||t==="\u201D"}function fg(t){return t==='"'}function Tl(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function pg(t){return t==="'"}function Ts(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Wt(t,e){let n=t.length;if(!Zn(t,n-1))return t+e;for(;Zn(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function Ev(t,e,n){return t.substring(0,e)+t.substring(e+n)}function vv(t){return/[,\n][ \t\r]*$/.test(t)}var BN={"&quot;":'"',"&amp;":"&","&lt;":"<","&gt;":">","&apos;":"'"},hg=12;function mg(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=BN[n];if(r!==void 0)return{char:r,length:n.length};if(t.charAt(1)==="#"){let o=t.substring(2,e),s=o.charAt(0)==="x"||o.charAt(0)==="X",i=s?o.substring(1):o;if(i.length>0){let c=Number.parseInt(i,s?16:10);if(!Number.isNaN(c)&&c>=0&&c<=1114111)return{char:String.fromCodePoint(c),length:n.length}}}return null}function Av(t){return t!==null&&t.char==='"'}function Tv(t){return t!==null&&t.char==="'"}function Es(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function Rv(t,e){switch(e){case")":return Es(t,"(")>Es(t,")");case"]":return Es(t,"[")>Es(t,"]");case"}":return Es(t,"{")>Es(t,"}");default:return!1}}var xv={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},UN={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
236
+ `,r:"\r",t:" "};function gg(t){let e=0,n="";f(["```","[```","{```"]),s()||De(),f(["```","```]","```}"]);let o=p(",");for(o&&i(),ug(t[e])&&vv(n)?(o||(n=Wt(n,",")),C()):o&&(n=Ts(n,","));t[e]==="}"||t[e]==="]";)e++,i();if(e>=t.length)return n;Z();function s(){i();let ee=y()||w()||v()||T()||x()||q(!1)||$();return i(),ee}function i(){let ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Q=e,se=c(ee);do se=u(),se&&(se=c(ee));while(se);return e>Q}function c(ee){let Q=ee?Zn:kv,se="";for(;;)if(Q(t,e))se+=t[e],e++;else if(Sv(t,e))se+=" ",e++;else break;return se.length>0?(n+=se,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!jN(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
237
+ `;)e++;return!0}return!1}function f(ee){if(d(ee)){if(sg(t[e]))for(;e<t.length&&Al(t[e]);)e++;return i(),!0}return!1}function d(ee){c(!0);for(let Q of ee){let se=e+Q.length;if(t.slice(e,se)===Q)return e=se,!0}return!1}function p(ee){return t[e]===ee?(n+=t[e],e++,!0):!1}function h(ee){return t[e]===ee?(e++,!0):!1}function _(){return h("\\")}function b(){return i(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,i(),h(","),!0):!1}function y(){if(t[e]==="{"){n+="{",e++,i(),h(",")&&i();let ee=!0;for(;e<t.length&&t[e]!=="}";){let Q;if(ee?Q=!0:(Q=p(","),Q||(n=Wt(n,",")),i()),b(),!(v()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ee||(n=Ts(n,",")):qe();break}i();let le=p(":"),be=e>=t.length;le||(ug(t[e])||be?n=Wt(n,":"):Te()),s()||(le||be?n+="null":Te()),ee=!1}return t[e]==="}"?(n+="}",e++):n=Wt(n,"}"),!0}return!1}function w(){if(t[e]==="["){n+="[",e++,i(),h(",")&&i();let ee=!0;for(;e<t.length&&t[e]!=="]";){if(ee||p(",")||(n=Wt(n,",")),b(),!s()){ee||(n=Ts(n,","));break}ee=!1}return t[e]==="]"?(n+="]",e++):n=Wt(n,"]"),!0}return!1}function C(){let ee=!0,Q=!0;for(;Q;)ee?ee=!1:p(",")||(n=Wt(n,",")),Q=s();Q||(n=Ts(n,",")),n=`[
238
+ ${n}
239
+ ]`}function v(){let ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,se=t[e]==="\\";se&&(e++,As(t[e])||Z());let le=t[e]==="&"?mg(t.slice(e,e+hg)):null,be=Av(le)||Tv(le);if(As(t[e])||be){let K=fg(t[e])?fg:pg(t[e])?pg:Tl(t[e])?Tl:dg,Ke=e,Fe=n.length,Y='"';for(e+=be&&le?le.length:1;;){if(e>=t.length){let k=H(e-1);return!ee&&vs(t.charAt(k))?(e=Ke,n=n.substring(0,Fe),v(!0)):(Y=Wt(Y,'"'),n+=Y,!0)}if(e===Q)return Y=Wt(Y,'"'),n+=Y,!0;let ce=be&&t[e]==="&"?mg(t.slice(e,e+hg)):null;if(ce&&le?ce.char===le.char:K(t[e])){let k=e,E=Y.length;if(Y+='"',e+=ce?ce.length:1,n+=Y,i(!1),ee||e>=t.length||vs(t[e])&&!Rv(Y,t[e])||As(t[e])&&!ae(e)||er(t[e]))return A(),!0;t[e]==="\\"&&Z();let R=H(k-1),M=t.charAt(R);if(M===",")return e=Ke,n=n.substring(0,Fe),v(!1,R);if(vs(M))return e=Ke,n=n.substring(0,Fe),v(!0);n=n.substring(0,Fe),e=k+(ce?ce.length:1),Y=`${Y.substring(0,E)}\\${Y.substring(E)}`}else if(ee&&cg(t[e])){if(t[e-1]===":"&&ig.test(t.substring(Ke+1,e+2)))for(;e<t.length&&ag.test(t[e]);)Y+=t[e],e++;return Y=Wt(Y,'"'),n+=Y,A(),!0}else if(ce){let k=ce.char;k==='"'?Y+='\\"':lg(k)?Y+=xv[k]:Y+=k,e+=ce.length}else if(t[e]==="\\"){let k=t.charAt(e+1);if(UN[k]!==void 0)Y+=t.slice(e,e+2),e+=2;else if(k==="u"){let R=2;for(;R<6&&Cv(t[e+R]);)R++;R===6?(Y+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:We()}else k===`
240
+ `?(Y+="\\n",e+=2):(Y+=k,e+=2)}else{let k=t.charAt(e);k==='"'&&t[e-1]!=="\\"?(Y+=`\\${k}`,e++):lg(k)?(Y+=xv[k],e++):(wv(k)||te(k),Y+=k,e++)}se&&_()}}return!1}function A(){let ee=!1;for(i();t[e]==="+";){ee=!0,e++,i(),n=Ts(n,'"',!0);let Q=n.length;v()?n=Ev(n,Q,1):n=Wt(n,'"')}return ee}function T(){let ee=e,Q="",se=!1;for(t[e]==="-"&&(Q+=t[e],e++,!er(t[e])&&X()&&(Q+="0")),t[e]==="0"&&er(t[e+1])&&(se=!0);er(t[e]);)Q+=t[e],e++;if(t[e]===".")for((Q===""||Q==="-")&&(Q+="0"),Q+=t[e],e++,er(t[e])||(Q+="0");er(t[e]);)Q+=t[e],e++;if(e>ee){if(t[e]==="e"||t[e]==="E")for(Q==="-"&&(se=!0),Q+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Q+=t[e],e++),er(t[e])||(Q+="0");er(t[e]);)Q+=t[e],e++;return X()?(n+=se?`"${t.substring(ee,e)}"`:Q,!0):(e=ee,!1)}return!1}function x(){return O("true","true")||O("false","false")||O("null","null")||O("True","true")||O("False","false")||O("None","null")}function O(ee,Q){return t.slice(e,e+ee.length)===ee&&!Al(t[e+ee.length])?(n+=Q,e+=ee.length,!0):!1}function q(ee){let Q=e;if(sg(t[e])){for(;e<t.length&&Al(t[e]);)e++;let se=e;for(;Zn(t,se);)se++;if(t[se]==="(")return e=se+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!cg(t[e])&&!As(t[e])&&(!ee||t[e]!==":");)e++;if(t[e-1]===":"&&ig.test(t.substring(Q,e+2)))for(;e<t.length&&ag.test(t[e]);)e++;if(e>Q){for(;Zn(t,e-1)&&e>0;)e--;let se=t.slice(Q,e);return n+=se==="undefined"?"null":JSON.stringify(se),t[e]==='"'&&e++,!0}}function $(){if(t[e]==="/"){let ee=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=JSON.stringify(t.substring(ee,e)),!0}}function H(ee){let Q=ee;for(;Q>0&&Zn(t,Q);)Q--;return Q}function ae(ee){let Q=ee+1;for(;Q<t.length&&Zn(t,Q);)Q++;return Q>=t.length||vs(t[Q])}function X(){return e>=t.length||vs(t[e])||Zn(t,e)}function te(ee){throw new Qn(`Invalid character ${JSON.stringify(ee)}`,e)}function Z(){throw new Qn(`Unexpected character ${JSON.stringify(t[e])}`,e)}function De(){throw new Qn("Unexpected end of json string",t.length)}function qe(){throw new Qn("Object key expected",e)}function Te(){throw new Qn("Colon expected",e)}function We(){let ee=t.slice(e,e+6);throw new Qn(`Invalid unicode character "${ee}"`,e)}}function jN(t,e){return t[e]==="*"&&t[e+1]==="/"}function yg(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=Dv.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=gg(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Rl=class{logger;name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=yg(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,i="",c=!1,u="",f=new ReadableStream({start:async d=>{let p=e.body.getReader(),h=(y,w,C)=>{let v=y.split(`
241
+ `);for(let A of v)A.trim()&&w.enqueue(C.encode(A+`
242
+ `))},_=(y,w,C)=>{let v;try{v=yg(o.arguments||"",this.logger)}catch(O){this.logger?.error(`${O.message} ${O.stack} Tool call argument parsing failed: ${JSON.stringify(o)}`),v=o.arguments||""}let A={role:"assistant",tool_calls:[{function:{name:o.name,arguments:v},id:o.id,index:o.index,type:"function"}]},T={...y,choices:[{...y.choices[0],delta:A}]};T.choices[0].delta.content!==void 0&&delete T.choices[0].delta.content;let x=`data: ${JSON.stringify(T)}
221
243
 
222
- `))}else if(d.type==="content_block_delta"&&d.delta?.type==="signature_delta"){let h={choices:[{delta:{thinking:{signature:d.delta.signature||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
244
+ `;w.enqueue(C.encode(x))},b=(y,w)=>{let{controller:C,encoder:v}=w;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let A=y.slice(6);try{let T=JSON.parse(A);if(T.choices?.[0]?.delta?.tool_calls?.length){let O=T.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""},O.function?.arguments&&(O.function.arguments="");let q=`data: ${JSON.stringify(T)}
223
245
 
224
- `))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let h={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
246
+ `;C.enqueue(v.encode(q));return}else if(o.index===O.index){O.function?.arguments&&(o.arguments+=O.function.arguments);return}else{_(T,C,v),o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""};return}}if(T.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){_(T,C,v),o={};return}T.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof T.choices[0].index=="number"?T.choices[0].index+=1:T.choices[0].index=1);let x=`data: ${JSON.stringify(T)}
225
247
 
226
- `))}else if(d.type==="message_delta"){let h={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:Gp({...r,...d.usage})};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
248
+ `;C.enqueue(v.encode(x))}catch{C.enqueue(v.encode(y+`
249
+ `))}}else C.enqueue(v.encode(y+`
250
+ `))};try{for(;;){let{done:y,value:w}=await p.read();if(y){u.trim()&&h(u,d,r);break}if(!w||w.length===0)continue;let C;try{C=n.decode(w,{stream:!0})}catch(A){this.logger?.warn("Failed to decode chunk",A);continue}if(C.length===0)continue;if(u+=C,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let A=u.split(`
251
+ `);u=A.pop()||"";for(let T of A)if(T.trim())try{b(T,{controller:d,encoder:r,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>i,appendReasoningContent:x=>i+=x,isReasoningComplete:()=>c,setReasoningComplete:x=>c=x})}catch(x){this.logger?.error("Error processing line:",T,x),d.enqueue(r.encode(T+`
252
+ `))}continue}let v=u.split(`
253
+ `);u=v.pop()||"";for(let A of v)if(A.trim())try{b(A,{controller:d,encoder:r,hasTextContent:()=>s,setHasTextContent:T=>s=T,reasoningContent:()=>i,appendReasoningContent:T=>i+=T,isReasoningComplete:()=>c,setReasoningComplete:T=>c=T})}catch(T){this.logger?.error("Error processing line:",A,T),d.enqueue(r.encode(A+`
254
+ `))}}}catch(y){this.logger?.error("Stream error:",y),d.error(y)}finally{try{p.releaseLock()}catch(y){this.logger?.error("Error releasing reader lock:",y)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var xl=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}options;static TransformerName="reasoning";enable;async transformRequestIn(e,n,r){return this.enable?(e.reasoning?(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0):e.model&&String(e.model).startsWith("deepseek")&&(e.enable_thinking=!0),gl(e,n,r),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e,n){if(!this.enable)return e;let r=yl(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return o.choices[0]?.message.reasoning_content&&(o.thinking={content:o.choices[0]?.message.reasoning_content}),r&&ks({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o="",s=!1,i=r?_l():null;return Ie(e,(u,f)=>{let{controller:d,encoder:p}=f;if(u.startsWith("data: ")&&u.trim()!=="data: [DONE]")try{let h=JSON.parse(u.slice(6)),_=h.choices?.[0]?.delta;if(!_){d.enqueue(p.encode(u+`
255
+ `));return}if(_.reasoning_content){o+=typeof _.reasoning_content=="string"?_.reasoning_content:JSON.stringify(_.reasoning_content),i&&Ss(i,_);let b={...h,choices:[{...h.choices[0],delta:{..._,thinking:{content:_.reasoning_content}}}]};delete b.choices[0].delta.reasoning_content;let y=`data: ${JSON.stringify(b)}
227
256
 
228
- `))}else if(d.type==="message_stop")c.enqueue(l.encode(`data: [DONE]
257
+ `;d.enqueue(p.encode(y));return}if(i&&Ss(i,_),(_.content||_.tool_calls)&&o&&!s){s=!0;let b=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:o,signature:b}}}]};delete y.choices[0].delta.reasoning_content;let w=`data: ${JSON.stringify(y)}
229
258
 
230
- `));else{let h={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};c.enqueue(l.encode(`data: ${JSON.stringify(h)}
259
+ `;d.enqueue(p.encode(w))}if(_.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){s&&h.choices[0].index++;let b=`data: ${JSON.stringify(h)}
231
260
 
232
- `))}}catch(d){n?.error(`Error parsing ${e} stream chunk`,f,d.message)}}}})}return t}async function e1(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>st(gu(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
261
+ `;d.enqueue(p.encode(b))}}catch{d.enqueue(p.encode(u+`
262
+ `))}else d.enqueue(p.encode(u+`
263
+ `))},{onComplete:()=>{i&&ks(bl(i),n)}})}return e}};var Dl=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}options;static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Ol=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};async function LN(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>tt(ul(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
233
264
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
234
265
  2. Run "gcloud auth application-default login"
235
- 3. Use Google Cloud environment with default service account`)}}var Mu=class{logger;name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),l=JSON.parse(c);l&&l.project_id&&(r=l.project_id)}catch(a){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",a)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await e1(this.logger);return{body:Nk(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Bk(e)}async transformResponseOut(e){return ju(e,this.name,this.logger)}};var jk=st(gu(),1);var Uu=class{static TransformerName="vertex-openai";client;client_email;private_key;constructor(e={}){this.client_email=e.client_email,this.private_key=e.private_key?.replace(/\\n/g,`
236
- `)}async getClient(){if(this.client)return this.client;if(!this.client_email||!this.private_key)throw new Error("vertex-openai requires client_email and private_key in transformer options");let e=new jk.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],credentials:{client_email:this.client_email,private_key:this.private_key}});return this.client=await e.getClient(),this.client}async transformRequestIn(e){let n=await this.getClient(),{token:r}=await n.getAccessToken();if(!r)throw new Error("Failed to get access token");return{body:{...e,messages:Je(e.messages),tools:Ve(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var Lu=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Je(o.messages),o.tools=Ve(o.tools);let s=Qt(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var qu=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var $u=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){return Ra(e,n,r)}};var zu=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var Hu=class{constructor(e){this.options=e}static TransformerName="vercel";logger;endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){e={...e,messages:Je(e.messages),tools:Ve(e.tools)},e.messages.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)})}),Object.assign(e,this.options||{});let o=e.providerOptions||{};return e.providerOptions={...o,gateway:{...o.gateway||{},caching:"auto"}},e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",a=!1,c=!1,l="",f=new ReadableStream({start:async d=>{let h=e.body.getReader(),m=(y,w,b)=>{let _=y.split(`
237
- `);for(let D of _)D.trim()&&w.enqueue(b.encode(D+`
238
- `))},S=(y,w)=>{let{controller:b,encoder:_}=w;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let D=y.slice(6);try{let k=JSON.parse(D);if(k.usage&&(this.logger?.debug({usage:k.usage,hasToolCall:c},"usage"),k.choices[0].finish_reason=c?"tool_calls":"stop"),k.choices?.[0]?.finish_reason==="error"&&b.enqueue(_.encode(`data: ${JSON.stringify({error:k.choices?.[0].error})}
266
+ 3. Use Google Cloud environment with default service account`,{cause:e})}}var Pl=class{logger;name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let c=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),u=JSON.parse(c);u&&u.project_id&&(r=u.project_id)}catch(i){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await LN(this.logger);return{body:TC(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return RC(e)}async transformResponseOut(e){return Sc(e,this.name,this.logger)}};var Ov=tt(ul(),1);var Il=class{static TransformerName="vertex-openai";client;client_email;private_key;constructor(e={}){this.client_email=e.client_email,this.private_key=e.private_key?.replace(/\\n/g,`
267
+ `)}async getClient(){if(this.client)return this.client;if(!this.client_email||!this.private_key)throw new Error("vertex-openai requires client_email and private_key in transformer options");let e=new Ov.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],credentials:{client_email:this.client_email,private_key:this.private_key}});return this.client=await e.getClient(),this.client}async transformRequestIn(e){let n=await this.getClient(),{token:r}=await n.getAccessToken();if(!r)throw new Error("Failed to get access token");return{body:{...e,messages:Je(e.messages),tools:Ve(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var Fl=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Je(o.messages),o.tools=Ve(o.tools);let s=Yt(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Nl=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Ml=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return qN(e)}async transformRequestIn(e,n,r){return cc(e,n,r)}async transformResponseIn(e,n){return(e.headers.get("Content-Type")||"").includes("text/event-stream")?HN(e):e}};function qN(t){if(!t||typeof t!="object")throw W("Invalid Chat Completions body",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model.trim())throw W("Chat Completions requires model",400,"invalid_body","invalid_request_error");if(!Array.isArray(t.messages))throw W("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(t.stream!==void 0&&typeof t.stream!="boolean")throw W("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.n!==void 0&&t.n!==1)throw W("n values other than 1 are not supported",400,"unsupported_n","invalid_request_error");if(t.logprobs===!0||t.top_logprobs!==void 0)throw W("logprobs/top_logprobs are not supported",400,"unsupported_logprobs","invalid_request_error");if(Array.isArray(t.modalities)&&t.modalities.filter(i=>i!=="text"&&i!==void 0).length>0)throw W("Non-text output modalities are not supported",400,"unsupported_modalities","invalid_request_error");if(t.audio!==void 0)throw W("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.store===!0||t.metadata!==void 0)throw W("Stored Chat Completions and metadata are not supported",400,"unsupported_state","invalid_request_error");for(let s of["prediction","web_search_options","moderation","service_tier","frequency_penalty","presence_penalty","seed","user","verbosity","safety_identifier","functions","function_call"])if(t[s]!==void 0&&t[s]!==null)throw W(`Chat Completions field '${s}' is not supported`,400,"unsupported_field","invalid_request_error");if(t.response_format!==void 0){let s=t.response_format,i=typeof s=="object"&&s?s.type:s;if(i&&i!=="text")throw W("response_format structured output is not supported without a verified provider mapping",400,"unsupported_response_format","invalid_request_error")}if(t.stream_options!=null&&t.stream!==!0)throw W("stream_options requires stream: true",400,"invalid_stream_options","invalid_request_error");if(t.stream_options!=null){if(typeof t.stream_options!="object"||Array.isArray(t.stream_options))throw W("stream_options must be an object",400,"invalid_stream_options","invalid_request_error");let s=Object.keys(t.stream_options).find(i=>i!=="include_usage");if(s)throw W(`Unsupported stream option '${s}'`,400,"invalid_stream_options","invalid_request_error");if(t.stream_options.include_usage!==void 0&&typeof t.stream_options.include_usage!="boolean")throw W("stream_options.include_usage must be a boolean",400,"invalid_stream_options","invalid_request_error")}let e=t.max_tokens!=null,n=t.max_completion_tokens!=null;if(e&&n&&Number(t.max_tokens)!==Number(t.max_completion_tokens))throw W("max_tokens and max_completion_tokens both present and differ",400,"conflicting_token_limits","invalid_request_error");for(let[s,i]of[["max_tokens",e],["max_completion_tokens",n]]){if(!i)continue;let c=Number(t[s]);if(!Number.isInteger(c)||c<=0)throw W(`${s} must be a positive integer`,400,"invalid_token_limit","invalid_request_error")}if(zN(t.tools,t.tool_choice),t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw W("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");let r=t.messages.map(s=>$N(s)),o={model:t.model,messages:r,stream:t.stream===!0};return t.stream_options&&(o.stream_options=t.stream_options),e&&(o.max_tokens=Number(t.max_tokens)),n&&(o.max_completion_tokens=Number(t.max_completion_tokens),e||(o.max_tokens=Number(t.max_completion_tokens))),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.stop!==void 0&&(o.stop=t.stop),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),t.parallel_tool_calls!==void 0&&(o.parallel_tool_calls=t.parallel_tool_calls),t.reasoning!==void 0&&(o.reasoning=t.reasoning),t.thinking!==void 0&&(o.thinking=t.thinking),o}function $N(t){if(!t||typeof t!="object")throw W("Invalid message in messages[]",400,"invalid_body","invalid_request_error");let e=t.role;if(!["developer","system","user","assistant","tool"].includes(e))throw W(`Unsupported message role '${e}'`,400,"unsupported_role","invalid_request_error");if(t.audio!==void 0)throw W("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.name!==void 0)throw W("Named messages are not supported by the cross-protocol compatibility tier",400,"unsupported_message_name","invalid_request_error");if(Array.isArray(t.content)){let n={developer:new Set(["text"]),system:new Set(["text"]),user:new Set(["text","image_url"]),assistant:new Set(["text","refusal"]),tool:new Set(["text"])};for(let r of t.content){if(!r||typeof r!="object")throw W(`Invalid content part for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if(r?.type==="input_audio"||r?.type==="audio")throw W("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(r?.type==="file")throw W("Provider-hosted file inputs are not supported",400,"unsupported_file","invalid_request_error");if(!n[e]?.has(r?.type))throw W(`Unsupported content part '${r?.type||"unknown"}' for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if((r.type==="text"||r.type==="refusal")&&typeof r.text!="string"&&typeof r.refusal!="string")throw W(`Content part '${r.type}' requires text`,400,"invalid_content_part","invalid_request_error");if(r.type==="image_url"&&(typeof r.image_url!="object"||typeof r.image_url?.url!="string"||!r.image_url.url))throw W("image_url content requires image_url.url",400,"invalid_image","invalid_request_error")}}else if(typeof t.content!="string"&&!(e==="assistant"&&t.content==null))throw W(`Message role '${e}' requires string or array content`,400,"invalid_message_content","invalid_request_error");if(e==="tool"){if(typeof t.tool_call_id!="string"||!t.tool_call_id)throw W("Tool messages require tool_call_id",400,"invalid_tool_call_id","invalid_request_error")}else if(t.tool_call_id!==void 0)throw W("tool_call_id is only valid on tool messages",400,"invalid_tool_call_id","invalid_request_error");if(t.tool_calls!==void 0){if(e!=="assistant"||!Array.isArray(t.tool_calls))throw W("tool_calls must be an array on assistant messages",400,"invalid_tool_calls","invalid_request_error");for(let n of t.tool_calls)if(n?.type!=="function"||typeof n?.id!="string"||!n.id||typeof n?.function?.name!="string"||!n.function.name||typeof n?.function?.arguments!="string")throw W("Invalid function call in assistant tool_calls",400,"invalid_tool_calls","invalid_request_error")}return e==="developer"?{...t,role:"system"}:t}function zN(t,e){if(t!==void 0&&!Array.isArray(t))throw W("tools must be an array",400,"invalid_tools","invalid_request_error");for(let n of t||[])if(n?.type!=="function"||typeof n?.function?.name!="string"||!n.function.name)throw W("Only function tools are supported by Chat Completions inbound routes",400,"unsupported_tool","invalid_request_error");if(e!=null&&!["auto","none","required"].includes(e)&&!(e?.type==="function"&&typeof e?.function?.name=="string"&&e.function.name))throw W("Unsupported tool_choice",400,"unsupported_tool_choice","invalid_request_error")}function HN(t){if(!t.body)return t;let e=t.body.getReader(),n=new TextDecoder,r=new TextEncoder,o="",s=!1,i=(u,f=!1)=>{o+=u;let d=o.split(/\r?\n/);o=f?"":d.pop()||"";for(let p of d)/^data:\s*\[DONE\]\s*$/.test(p)&&(s=!0);f&&/^data:\s*\[DONE\]\s*$/.test(o)&&(s=!0,o="")},c=new ReadableStream({async pull(u){try{let{done:f,value:d}=await e.read();if(f){i(n.decode(),!0),s||u.enqueue(r.encode(`data: [DONE]
239
268
 
240
- `)),k.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),k.choices?.[0]?.delta?.reasoning){w.appendReasoningContent(k.choices[0].delta.reasoning);let x={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,thinking:{content:k.choices[0].delta.reasoning}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let R=`data: ${JSON.stringify(x)}
269
+ `)),u.close();return}let p=n.decode(d,{stream:!0});i(p),u.enqueue(d)}catch{s||(u.enqueue(r.encode(`data: ${JSON.stringify({error:{message:"Upstream stream failed",type:"api_error",param:null,code:"provider_response_error"}})}
241
270
 
242
- `;b.enqueue(_.encode(R));return}if(k.choices?.[0]?.delta?.content&&w.reasoningContent()&&!w.isReasoningComplete()){w.setReasoningComplete(!0);let x=Date.now().toString(),R={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,content:null,thinking:{content:w.reasoningContent(),signature:x}}}]};R.choices?.[0]?.delta&&delete R.choices[0].delta.reasoning;let j=`data: ${JSON.stringify(R)}
271
+ `)),u.enqueue(r.encode(`data: [DONE]
243
272
 
244
- `;b.enqueue(_.encode(j))}k.choices?.[0]?.delta?.reasoning&&delete k.choices[0].delta.reasoning,k.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(k.choices?.[0]?.delta?.tool_calls[0].id,10))&&k.choices?.[0]?.delta?.tool_calls.forEach(x=>{x.id=`call_${dn()}`}),k.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),k.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof k.choices[0].index=="number"?k.choices[0].index+=1:k.choices[0].index=1);let v=`data: ${JSON.stringify(k)}
273
+ `))),u.close()}},cancel(u){return e.cancel(u)}});return new Response(c,{status:t.status,statusText:t.statusText,headers:t.headers})}var Bl=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var Ul=class{constructor(e){this.options=e}options;static TransformerName="vercel";logger;endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){e={...e,messages:Je(e.messages),tools:Ve(e.tools)},e.messages.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="image_url"&&(i.image_url.url.startsWith("http")||(i.image_url.url=`data:${i.media_type};base64,${i.image_url.url}`),delete i.media_type)})}),Object.assign(e,this.options||{});let o=e.providerOptions||{};return e.providerOptions={...o,gateway:{...o.gateway||{},caching:"auto"}},e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",i=!1,c=!1,u="",f=new ReadableStream({start:async d=>{let p=e.body.getReader(),h=(b,y,w)=>{let C=b.split(`
274
+ `);for(let v of C)v.trim()&&y.enqueue(w.encode(v+`
275
+ `))},_=(b,y)=>{let{controller:w,encoder:C}=y;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let v=b.slice(6);try{let A=JSON.parse(v);if(A.usage&&(this.logger?.debug({usage:A.usage,hasToolCall:c},"usage"),A.choices[0].finish_reason=c?"tool_calls":"stop"),A.choices?.[0]?.finish_reason==="error"&&w.enqueue(C.encode(`data: ${JSON.stringify({error:A.choices?.[0].error})}
245
276
 
246
- `;b.enqueue(_.encode(v))}catch{b.enqueue(_.encode(y+`
247
- `))}}else b.enqueue(_.encode(y+`
248
- `))};try{for(;;){let{done:y,value:w}=await h.read();if(y){l.trim()&&m(l,d,r);break}if(!w||w.length===0)continue;let b;try{b=n.decode(w,{stream:!0})}catch(D){this.logger?.warn("Failed to decode chunk",D);continue}if(b.length===0)continue;if(l+=b,l.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let D=l.split(`
249
- `);l=D.pop()||"";for(let k of D)if(k.trim())try{S(k,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:v=>o=v,reasoningContent:()=>s,appendReasoningContent:v=>s+=v,isReasoningComplete:()=>a,setReasoningComplete:v=>a=v})}catch(v){this.logger?.error("Error processing line:",k,v),d.enqueue(r.encode(k+`
250
- `))}continue}let _=l.split(`
251
- `);l=_.pop()||"";for(let D of _)if(D.trim())try{S(D,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>a,setReasoningComplete:k=>a=k})}catch(k){this.logger?.error("Error processing line:",D,k),d.enqueue(r.encode(D+`
252
- `))}}}catch(y){this.logger?.error("Stream error:",y),d.error(y)}finally{try{h.releaseLock()}catch(y){this.logger?.error("Error releasing reader lock:",y)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wu=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestIn(e,n,r){delete e.temperature,delete e.max_tokens,e.reasoning&&(e.reasoning={effort:e.reasoning.effort,summary:"detailed"});let o=e.model||"";e=Gs(e,n,r);let s=va(e.messages);e.messages=s;let a=[],c=!1,l=e.messages.filter(f=>f.role==="system");if(l.length>0){let f=l[0];Array.isArray(f.content)?f.content.forEach(d=>{let h="";typeof d=="string"?h=d:d&&typeof d=="object"&&"text"in d&&(h=d.text),a.push({role:"system",content:[{type:"input_text",text:h,...Ta(d,o)}]})}):e.instructions=f.content}if(e.messages.forEach(f=>{if(f.role!=="system"){if(Array.isArray(f.content)){let d=f.content.map(h=>this.normalizeRequestContent(h,f.role,o)).filter(h=>h!==null);d.length>0?f.content=d:delete f.content}if(f.role==="tool"){let d={...f};d.type="function_call_output",d.call_id=f.tool_call_id,d.output=f.content,delete d.cache_control,delete d.role,delete d.tool_call_id,delete d.content,a.push(d),c=!0;return}if(f.role==="assistant"&&Array.isArray(f.tool_calls)){let d=f.content&&(typeof f.content=="string"||Array.isArray(f.content)&&f.content.length>0);c=!1,f.tool_calls.forEach(h=>{a.push({type:"function_call",arguments:h.function.arguments,name:h.function.name,call_id:h.id})});return}c&&f.role==="user"&&a.push({role:"assistant",content:""}),c=!1,a.push(f)}}),e.input=a,delete e.messages,Array.isArray(e.tools)){let f=e.tools.find(d=>d.function.name==="web_search");e.tools=e.tools.filter(d=>d.function.name!=="web_search").map(d=>(d.function.name==="WebSearch"&&delete d.function.parameters.properties.allowed_domains,d.function.name==="Edit"?{type:d.type,name:d.function.name,description:d.function.description,parameters:{...d.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:d.type,name:d.function.name,description:d.function.description,parameters:d.function.parameters})),f&&e.tools.push({type:"web_search"})}return e.parallel_tool_calls=!1,e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=!1,o=-1,s="",a=l=>(l!==s&&(o++,s=l),o),c=this;return ze(e,(l,f)=>{if(l.trim()&&!l.startsWith("event: "))if(l.startsWith("data: ")){let d=l.slice(5).trim();if(d==="[DONE]"){r=!0,f.controller.enqueue(Be("[DONE]",f.encoder));return}try{let h=JSON.parse(d),m=c.convertStreamEvent(h,a);m&&f.controller.enqueue(Be(JSON.stringify(m),f.encoder))}catch{f.controller.enqueue(Te(l,f.encoder))}}else f.controller.enqueue(Te(l,f.encoder))})}return e}convertStreamEvent(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:0,id:e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:n(e.type),delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:n(e.type),delta:{tool_calls:[{index:0,function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:n(e.type),delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:n(e.type),delta:{thinking:{signature:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...Ta(e,r)};if(e.type==="image_url"){this.logger?.debug(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),{...o,...Ta(e,r)}}return null}convertResponseToChat(e){let n=e.output?.find(l=>l.type==="message"),r=e.output?.find(l=>l.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let l=[],f=[];if(n.content.forEach(d=>{if(d.type==="output_text")l.push(d.text||"");else if(d.type==="output_image"){let h=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});h&&f.push(h)}else if(d.type==="output_image_base64"){let h=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});h&&f.push(h)}}),f.length>0){let d=[];l.length>0&&d.push({type:"text",text:l.join("")}),d.push(...f),s=d}else s=l.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var zk=require("crypto"),Hk=require("child_process"),Vn=require("os");var He=require("fs"),Ju=require("path"),Mk=require("os"),t1=(0,Ju.join)((0,Mk.homedir)(),".claude-code-router","codex_auth.json"),n1=300,r1=11520*60,o1=2*6e4,s1=35e3,Uk={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Gu=null;function Yp(){return process.env.CCR_CODEX_AUTH_FILE||t1}function Vp(){return`${Yp()}.refresh.lock`}function i1(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||Uk.token_endpoint}function Xp(t){if(!t)return null;let e=t.split(".");if(e.length!==3||!e[1])return null;try{return JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"))}catch{return null}}function Vu(t){let e=t.account_id?.trim();return e||Xp(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function a1(t){return Xp(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function Lk(t){let e=Xp(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Ku(t){let e=Vu(t),n=Lk(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function Kp(){try{let t=Yp();if(!(0,He.existsSync)(t))return null;let e=JSON.parse((0,He.readFileSync)(t,"utf8"));return e.access_token?Ku(e):null}catch{return null}}function c1(t){let e=Yp();(0,He.mkdirSync)((0,Ju.dirname)(e),{recursive:!0});let n=Ku(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,He.writeFileSync)(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),(0,He.renameSync)(r,e)}finally{try{(0,He.existsSync)(r)&&(0,He.unlinkSync)(r)}catch{}}}function qk(t,e=n1){let n=Lk(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+r1)}function Jp(t,e){let n=Vu(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function u1(t){try{let e=JSON.parse(t),n=e?.error?.code||e?.error,r=e?.error?.message||e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function l1(t){if(!t.refresh_token)throw new Error("Codex OAuth token cannot be refreshed because no refresh token is available. Run `ccr codex-auth` again.");let e=await fetch(i1(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:Uk.client_id,grant_type:"refresh_token",refresh_token:t.refresh_token}),signal:AbortSignal.timeout(3e4)}),n=await e.text();if(!e.ok)throw new Error(`Codex OAuth token refresh failed (${e.status}): ${u1(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("Codex OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return Ku({...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:r.expires_at||o+(typeof r.expires_in=="number"?r.expires_in:3600),account_id:r.account_id||t.account_id,last_refresh:o})}function d1(){let t=Vp();try{return(0,He.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,He.statSync)(t).mtimeMs>o1&&(0,He.unlinkSync)(t)}catch{}return null}}async function f1(t){let e=Date.now()+s1,n=null;for(;n===null&&(n=d1(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh Codex OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=(0,He.fstatSync)(n).ino;(0,He.closeSync)(n);try{(0,He.statSync)(Vp()).ino===r&&(0,He.unlinkSync)(Vp())}catch{}}}async function h1(t,e){return f1(async()=>{let n=Kp();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");Jp(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!qk(n))return n;let o=await l1(n);Jp(e.expectedAccountId,o);let s=Kp();return s&&s.access_token!==n.access_token?(Jp(e.expectedAccountId,s),s):(c1(o),o)})}async function Qp(t={}){let e=Kp();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!qk(e)?e:(Gu||(Gu=h1(e,{...t,expectedAccountId:t.expectedAccountId||Vu(e)}).finally(()=>{Gu=null})),Gu)}function Zp(t){let e=Ku(t);return{mode:"oauth",token:e.access_token,accountId:Vu(e),isFedramp:a1(e)}}var p1=300*1e3,Yu=new Map,eg=new Map,Wk="0.145.0",Gk="codex_cli_rs",Jk="x-codex-turn-metadata",g1="x-codex-window-id",m1="x-codex-parent-thread-id",y1="session_id",_1="thread_id",b1="turn_id",w1="window_id";function C1(){switch((0,Vn.platform)()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return(0,Vn.platform)()||"unknown"}}function k1(){switch((0,Vn.arch)()){case"x64":return"x86_64";case"arm64":return"arm64";default:return(0,Vn.arch)()||"unknown"}}function S1(){if((0,Vn.platform)()==="darwin")try{return(0,Hk.execFileSync)("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return(0,Vn.release)()||"unknown"}function A1(){return`${Gk}/${Wk} (${C1()} ${S1()}; ${k1()})`}function $k(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",Wk),e.toString()}function E1(t){return{session_id:t,thread_id:t,turn_id:(0,zk.randomUUID)(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function v1(t){return{[y1]:t.session_id,[_1]:t.thread_id,[b1]:t.turn_id,[w1]:t.window_id,[Jk]:JSON.stringify(t)}}function T1(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function R1(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[g1]:t.window_id,[Jk]:JSON.stringify(t),[m1]:t.thread_id}}function D1(t){let e=t?.metadata?.user_id;if(typeof e!="string"||!e)return;let n=e.split("_session_");if(n.length>1&&n[1])return n[1];try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}}function x1(t,e){return t?.req?.sessionId||D1(e)}function O1(t,e,n){if(!n)return;let r=E1(n);t.client_metadata=T1(t.client_metadata,v1(r)),Object.assign(e,R1(r))}var Xu=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let a=e.reasoning?.effort||n?.reasoningEffort;if(a){let y={effort:a},w=["auto","detailed","none"],b=n?.reasoningSummary;b&&w.includes(b)?b!=="none"&&(y.summary=b):y.summary="detailed",e.reasoning=y}else delete e.reasoning;let c=["low","medium","high"];n?.verbosity&&c.includes(n.verbosity)&&(e.verbosity=n.verbosity),e=Xd(e,r);let l=va(e.messages);e.messages=l;let f=[],d=!1,h=e.messages.filter(y=>y.role==="system");if(h.length>0){let y=h[0],w="";Array.isArray(y.content)?w=y.content.map(b=>typeof b=="string"?b:b&&typeof b=="object"&&"text"in b?b.text:"").filter(Boolean).join(`
253
- `):w=y.content,w&&(e.instructions=w)}if(e.instructions||(e.instructions=""),e.messages.forEach(y=>{if(y.role!=="system"){if(Array.isArray(y.content)){let w=y.content.map(b=>this.normalizeRequestContent(b,y.role)).filter(b=>b!==null);w.length>0?y.content=w:delete y.content}if(y.role==="tool"){let w={...y};w.type="function_call_output",w.call_id=y.tool_call_id,w.output=y.content,delete w.cache_control,delete w.role,delete w.tool_call_id,delete w.content,f.push(w),d=!0;return}if(y.role==="assistant"&&Array.isArray(y.tool_calls)){d=!1,y.tool_calls.forEach(w=>{f.push({type:"function_call",arguments:w.function.arguments,name:w.function.name,call_id:w.id})});return}d&&y.role==="user"&&f.push({type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),d=!1,typeof y.content=="string"?f.push({type:"message",role:y.role,content:[{type:y.role==="assistant"?"output_text":"input_text",text:y.content}]}):f.push({type:"message",role:y.role,content:y.content})}}),e.input=f,delete e.messages,e.store=!1,Array.isArray(e.tools)){let y=e.tools.find(w=>w.function.name==="web_search");e.tools=e.tools.filter(w=>w.function.name!=="web_search").map(w=>(w.function.name==="WebSearch"&&delete w.function.parameters.properties.allowed_domains,w.function.name==="Edit"?{type:w.type,name:w.function.name,description:w.function.description,parameters:{...w.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:w.type,name:w.function.name,description:w.function.description,parameters:w.function.parameters})),y&&e.tools.push({type:"web_search"})}e.parallel_tool_calls=n?.parallelToolCalls===!0,e.stream=!0;let m=this.buildAuthHeaders(s);O1(e,m,e.prompt_cache_key||x1(r,e));let S=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:$k(`${S}/responses`),headers:m,__authRecovery:()=>this.recoverUnauthorizedAuth(n,s)}}}async auth(e,n){let r=await this.resolveAuth(n),o=this.buildAuthHeaders(r),s=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:$k(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=typeof e?.apiKey=="string"?e.apiKey.trim():e?.apiKey;return typeof n=="string"&&n.startsWith("at-")?this.resolvePatAuth(n):Zp(await Qp())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:Gk,"User-Agent":A1()};return e.accountId&&(n["ChatGPT-Account-ID"]=e.accountId),e.isFedramp&&(n["X-OpenAI-Fedramp"]="true"),n}async recoverUnauthorizedAuth(e,n){if(n.mode==="pat")return Yu.delete(n.token),null;let r=typeof e?.apiKey=="string"?e.apiKey.trim():e?.apiKey;if(typeof r=="string"&&r.startsWith("at-"))return null;let o=await Qp({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),s=Zp(o);if(n.accountId&&s.accountId&&n.accountId!==s.accountId)throw new Error("Codex OAuth account changed during unauthorized recovery.");return this.buildAuthHeaders(s)}async resolvePatAuth(e){let n=Yu.get(e);if(n&&n.expiresAt>Date.now())return n.value;Yu.delete(e);let r=eg.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{eg.delete(e)});return eg.set(e,o),o}async requestPatAuth(e){let n=(process.env.CODEX_AUTHAPI_BASE_URL||"https://auth.openai.com/api/accounts").replace(/\/+$/,""),r=await fetch(`${n}/v1/user-auth-credential/whoami`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new Error(`Codex PAT metadata request failed (${r.status}). Verify that the configured at- token is valid and has Codex access.`);let o=await r.json();if(!o.chatgpt_account_id||!o.chatgpt_user_id||!o.chatgpt_plan_type)throw new Error("Codex PAT metadata response is missing required account, user, or plan information.");let s={mode:"pat",token:e,accountId:o.chatgpt_account_id,isFedramp:o.chatgpt_account_is_fedramp===!0};return Yu.set(e,{value:s,expiresAt:Date.now()+p1}),s}async transformResponseOut(e,n){let r=e.headers.get("Content-Type")||"",o=this,s=n?.req?.id,a=s?this.streamIntent.get(s):void 0;try{return await this.transformResponseOutInner(e,r,o,s,a)}finally{s&&this.streamIntent.delete(s)}}async transformResponseOutInner(e,n,r,o,s){let a=o?s!==!1:!0,c,l=f=>f?(c=f,f):c;if(!n||n.includes("text/event-stream")){if(!e.body)return e;let f=await this.readBodyAndPeek(e.clone().body);if(f&&(f.firstChar==="{"||f.firstChar==="[")){let k;try{k=JSON.parse(f.text)}catch{return a?new Response(this.jsonToSseStream(f.text),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f.text,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let v=k?.object==="response"&&k.output?this.convertResponseToChat(k):k,x=JSON.stringify(v);return a?new Response(this.jsonToSseStream(x),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(x,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}if(!a)try{let k=await this.collectSseIntoChatCompletion(e,l);return new Response(JSON.stringify(k),{status:e.status,statusText:e.statusText,headers:{"Content-Type":"application/json"}})}catch(k){throw k}let d=!1,h=-1,m="",S=k=>(k!==m&&(h++,m=k),h),w=ze(e,(k,v)=>{if(k.trim()&&!k.startsWith("event: "))if(k.startsWith("data: ")){let x=k.slice(5).trim();if(x==="[DONE]"){d=!0,v.controller.enqueue(Be("[DONE]",v.encoder));return}try{let R=JSON.parse(x);R.response?.model&&(c=R.response.model);let j=r.convertStreamEvent(R,S,l);j&&v.controller.enqueue(Be(JSON.stringify(j),v.encoder))}catch{v.controller.enqueue(Te(k,v.encoder))}}else v.controller.enqueue(Te(k,v.encoder))}).body,b=!1,_=null,D=new ReadableStream({start(k){_=w.getReader();let v=W=>{if(!b)try{k.enqueue(W)}catch{b=!0}},x=()=>{if(!b)try{k.close()}catch{}},R=W=>{if(!b)try{k.error(W)}catch{}},j=()=>{b||!_||_.read().then(({done:W,value:U})=>{if(W){x();return}U&&v(U),j()}).catch(W=>{b||R(W)})};j()},cancel(){if(b=!0,_)try{_.cancel().catch(()=>{})}catch{}}});return new Response(D,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else if(n.includes("application/json")){let f=await e.json();if(Array.isArray(f)){let d=new TextEncoder,h=-1,m="",S=w=>(w!==m&&(h++,m=w),h),y=new ReadableStream({start(w){for(let b of f){b?.response?.model&&(c=b.response.model);let _=r.convertStreamEvent(b,S,l);_&&w.enqueue(d.encode(`data: ${JSON.stringify(_)}
277
+ `)),A.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),A.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(A.choices[0].delta.reasoning);let x={...A,choices:[{...A.choices?.[0],delta:{...A.choices[0].delta,thinking:{content:A.choices[0].delta.reasoning}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let O=`data: ${JSON.stringify(x)}
254
278
 
255
- `))}w.enqueue(d.encode(`data: [DONE]
279
+ `;w.enqueue(C.encode(O));return}if(A.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let x=Date.now().toString(),O={...A,choices:[{...A.choices?.[0],delta:{...A.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:x}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let q=`data: ${JSON.stringify(O)}
256
280
 
257
- `)),w.close()}});return new Response(y,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(f.object==="response"&&f.output){let d=this.convertResponseToChat(f);return new Response(JSON.stringify(d),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return new Response(JSON.stringify(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r){let o=a=>r?r(a):a,s=a=>a||o(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:0,id:e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let a=[];(e.item.content||[]).forEach(l=>{l.type==="output_text"&&a.push({type:"text",text:l.text||""})});let c={role:"assistant"};return a.length===1&&a[0].type==="text"?c.content=a[0].text:a.length>0&&(c.content=a),c.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:c,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{tool_calls:[{index:0,function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let a=e.response?.output?.some(l=>l.type==="function_call")?"tool_calls":"stop",c={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:0,delta:{},finish_reason:a}]};return e.response?.usage&&(c.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),c}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_text.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{signature:e.item_id}},finish_reason:null}]}:e.type==="response.output_text.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}:e.type==="response.output_item.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}:null}jsonToSseStream(e){let n=new TextEncoder,r;try{r=JSON.parse(e)}catch{r=null}let o=s=>n.encode(`data: ${JSON.stringify(s)}
281
+ `;w.enqueue(C.encode(q))}A.choices?.[0]?.delta?.reasoning&&delete A.choices[0].delta.reasoning,A.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(A.choices?.[0]?.delta?.tool_calls[0].id,10))&&A.choices?.[0]?.delta?.tool_calls.forEach(x=>{x.id=`call_${mn()}`}),A.choices?.[0]?.delta?.tool_calls?.length&&!c&&(c=!0),A.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof A.choices[0].index=="number"?A.choices[0].index+=1:A.choices[0].index=1);let T=`data: ${JSON.stringify(A)}
258
282
 
259
- `);return new ReadableStream({start(s){if(!r){s.close();return}let a={id:r.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:r.created||Math.floor(Date.now()/1e3),model:r.model||"unknown"},c=r.choices?.[0];if(c){let l=c.message||{};if(typeof l.content=="string"&&l.content&&s.enqueue(o({...a,choices:[{index:0,delta:{role:"assistant",content:l.content},finish_reason:null}]})),l.thinking?.content&&s.enqueue(o({...a,choices:[{index:0,delta:{thinking:{content:l.thinking.content}},finish_reason:null}]})),Array.isArray(l.tool_calls))for(let d of l.tool_calls)s.enqueue(o({...a,choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:0,id:d.id,type:"function",function:{name:d.function?.name||"",arguments:d.function?.arguments||""}}]},finish_reason:null}]}));let f={...a,choices:[{index:0,delta:{},finish_reason:c.finish_reason||"stop"}]};r.usage&&(f.usage={prompt_tokens:r.usage.prompt_tokens||0,completion_tokens:r.usage.completion_tokens||0,total_tokens:r.usage.total_tokens||0,...r.usage.prompt_tokens_details?{prompt_tokens_details:{...r.usage.prompt_tokens_details}}:{}}),s.enqueue(o(f))}s.enqueue(n.encode(`data: [DONE]
283
+ `;w.enqueue(C.encode(T))}catch{w.enqueue(C.encode(b+`
284
+ `))}}else w.enqueue(C.encode(b+`
285
+ `))};try{for(;;){let{done:b,value:y}=await p.read();if(b){u.trim()&&h(u,d,r);break}if(!y||y.length===0)continue;let w;try{w=n.decode(y,{stream:!0})}catch(v){this.logger?.warn("Failed to decode chunk",v);continue}if(w.length===0)continue;if(u+=w,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let v=u.split(`
286
+ `);u=v.pop()||"";for(let A of v)if(A.trim())try{_(A,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:T=>o=T,reasoningContent:()=>s,appendReasoningContent:T=>s+=T,isReasoningComplete:()=>i,setReasoningComplete:T=>i=T})}catch(T){this.logger?.error("Error processing line:",A,T),d.enqueue(r.encode(A+`
287
+ `))}continue}let C=u.split(`
288
+ `);u=C.pop()||"";for(let v of C)if(v.trim())try{_(v,{controller:d,encoder:r,hasTextContent:()=>o,setHasTextContent:A=>o=A,reasoningContent:()=>s,appendReasoningContent:A=>s+=A,isReasoningComplete:()=>i,setReasoningComplete:A=>i=A})}catch(A){this.logger?.error("Error processing line:",v,A),d.enqueue(r.encode(v+`
289
+ `))}}}catch(b){this.logger?.error("Stream error:",b),d.error(b)}finally{try{p.releaseLock()}catch(b){this.logger?.error("Error releasing reader lock:",b)}d.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var jl=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=jo();return n&&(n.responsesCallIdMap=r,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r)),dc(e,r)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||jo(),o=n?.protocolContext?.originalModel||n?.req?.protocolContext?.originalModel,s=e.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await e.json();if(i?.object==="response")return new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:e.headers});let c=Bb(i,{originalModel:o,callIdMap:r});return new Response(JSON.stringify(c),{status:e.status,statusText:e.statusText,headers:e.headers})}return s.includes("text/event-stream")?this.convertUnifiedStreamToResponses(e,{callIdMap:r,originalModel:o}):e}convertUnifiedStreamToResponses(e,n){if(!e.body)return e;let r=Ub({model:n.originalModel,callIdMap:n.callIdMap});return Ie(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let c=gi("Malformed upstream SSE event",r);s.controller.enqueue(Ee(JSON.stringify(c),s.encoder)),r.finished=!0}return}let i=o.slice(5).trim();if(i==="[DONE]"){if(!r.finished)for(let c of sp(r))s.controller.enqueue(Ee(JSON.stringify(c),s.encoder));return}try{let c=JSON.parse(i);if(typeof c?.type=="string"&&c.type.startsWith("response.")){s.controller.enqueue(Ee(JSON.stringify(c),s.encoder)),(c.type==="response.completed"||c.type==="response.failed")&&(r.finished=!0);return}if(c?.error&&!c?.choices){let f=gi(et(String(c.error.message||c.error))||"Upstream stream failed",r);s.controller.enqueue(Ee(JSON.stringify(f),s.encoder)),r.finished=!0;return}let u=qb(c,r);for(let f of u)s.controller.enqueue(Ee(JSON.stringify(f),s.encoder))}catch{let c=gi("Malformed JSON in upstream SSE event",r);s.controller.enqueue(Ee(JSON.stringify(c),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of sp(r))o.controller.enqueue(Ee(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),c=gi(et(i)||"Upstream stream failed",r);s.controller.enqueue(Ee(JSON.stringify(c),s.encoder)),r.finished=!0}return!0},logger:this.logger})}async transformRequestIn(e,n,r){e=structuredClone(e);let o=e.max_tokens??e.max_completion_tokens;if(o!=null&&(e.max_output_tokens=o),delete e.max_tokens,delete e.max_completion_tokens,e.reasoning&&(e.reasoning={...e.reasoning.effort?{effort:e.reasoning.effort}:{},...e.reasoning.summary?{summary:e.reasoning.summary}:{}}),e.stop!==void 0)throw W("stop cannot be represented by the Responses API provider adapter",400,"unsupported_stop","invalid_request_error");delete e.stream_options;let s=e.model||"";e=hi(e,n,r);let i=ic(e.messages);e.messages=i;let c=[],u=!1;if(e.messages.filter(d=>d.role==="system").forEach((d,p)=>{Array.isArray(d.content)?d.content.forEach(h=>{let _="";typeof h=="string"?_=h:h&&typeof h=="object"&&"text"in h&&(_=h.text),c.push({role:"system",content:[{type:"input_text",text:_,...ac(h,s)}]})}):p===0?e.instructions=d.content:c.push({role:"system",content:[{type:"input_text",text:String(d.content||"")}]})}),e.messages.forEach(d=>{if(d.role!=="system"){if(Array.isArray(d.content)){let p=d.content.map(h=>this.normalizeRequestContent(h,d.role,s)).filter(h=>h!==null);p.length>0?d.content=p:delete d.content}if(d.role==="tool"){let p={...d};p.type="function_call_output",p.call_id=Ct(d.tool_call_id)??d.tool_call_id,p.output=d.content,delete p.cache_control,delete p.role,delete p.tool_call_id,delete p.content,c.push(p),u=!0;return}if(d.role==="assistant"&&Array.isArray(d.tool_calls)){let p=d.content&&(typeof d.content=="string"||Array.isArray(d.content)&&d.content.length>0);if(u=!1,p){let h={...d};delete h.tool_calls,c.push(h)}d.tool_calls.forEach(h=>{c.push({type:"function_call",arguments:h.function.arguments,name:h.function.name,call_id:Ct(h.id)??h.id})});return}u&&d.role==="user"&&c.push({role:"assistant",content:""}),u=!1,c.push(d)}}),e.input=c,delete e.messages,Array.isArray(e.tools)){let d=e.tools.find(p=>p?.type==="web_search");e.tools=e.tools.filter(p=>p?.type!=="web_search").map(p=>(p.function.name==="WebSearch"&&p.function.parameters?.properties&&delete p.function.parameters.properties.allowed_domains,p.function.name==="Edit"?{type:p.type,name:p.function.name,description:p.function.description,parameters:{...p.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:p.type,name:p.function.name,description:p.function.description,parameters:p.function.parameters})),d&&e.tools.push({...d,type:"web_search"})}return e.tool_choice&&typeof e.tool_choice=="object"&&e.tool_choice.type==="function"&&(e.tool_choice={type:"function",name:e.tool_choice.function?.name}),e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new Map,o=0,s=!1,i=u=>{let f=u.item_id||u.item?.id||(typeof u.output_index=="number"?`output:${u.output_index}`:void 0);if(f!==void 0){let d=r.get(f);if(d!==void 0)return d;let p=o++;return r.set(f,p),p}return o++},c=()=>{s=!0,r.clear()};return Ie(e,(u,f)=>{if(!s&&u.trim()&&!u.startsWith("event: "))if(u.startsWith("data: ")){let d=u.slice(5).trim();if(d==="[DONE]"){f.controller.enqueue(Ee("[DONE]",f.encoder)),c();return}try{let p=JSON.parse(d);if(p.type==="response.failed"){c();let _=p.response?.error??{},b=et(String(_.message||"Upstream response failed"))||"Upstream response failed";f.controller.enqueue(Ee(JSON.stringify({error:{message:b,type:typeof _.type=="string"?_.type:"api_error",code:typeof _.code=="string"?_.code:null}}),f.encoder)),f.controller.enqueue(Ee("[DONE]",f.encoder));return}let h=this.convertStreamEvent(p,i);h&&f.controller.enqueue(Ee(JSON.stringify(h),f.encoder)),p.type==="response.completed"&&(f.controller.enqueue(Ee("[DONE]",f.encoder)),c())}catch{f.controller.enqueue(Re(u,f.encoder))}}else f.controller.enqueue(Re(u,f.encoder))})}return e}convertStreamEvent(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:n(e),id:Ct(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:0,delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{tool_calls:[{index:n(e),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{signature:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...ac(e,r)};if(e.type==="image_url"){this.logger?.debug(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),{...o,...ac(e,r)}}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=(e.output??[]).filter(u=>u.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger?.debug?.({data:o,type:"url_citation"});let s=null,i=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let u=[],f=[];if(n.content.forEach(d=>{if(d.type==="output_text")u.push(d.text||"");else if(d.type==="output_image"){let p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&f.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&f.push(p)}}),f.length>0){let d=[];u.length>0&&d.push({type:"text",text:u.join("")}),d.push(...f),s=d}else s=u.join("")}return r.length>0&&(i=r.map(u=>({id:Ct(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:c,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var Bv=require("crypto"),Uv=require("child_process"),tr=require("os"),Ag=require("@caeliq/ccr-shared");var $e=require("fs"),ql=require("path"),Pv=require("os"),WN=(0,ql.join)((0,Pv.homedir)(),".claude-code-router","codex_auth.json"),GN=300,JN=11520*60,VN=2*6e4,KN=35e3,Iv={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Ll=null;function wg(){return process.env.CCR_CODEX_AUTH_FILE||WN}function bg(){return`${wg()}.refresh.lock`}function YN(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||Iv.token_endpoint}function kg(t){if(!t)return null;let e=t.split(".");if(e.length!==3||!e[1])return null;try{return JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"))}catch{return null}}function $l(t){let e=t.account_id?.trim();return e||kg(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function XN(t){return kg(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function Fv(t){let e=kg(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function zl(t){let e=$l(t),n=Fv(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function Cg(){try{let t=wg();if(!(0,$e.existsSync)(t))return null;let e=JSON.parse((0,$e.readFileSync)(t,"utf8"));return e.access_token?zl(e):null}catch{return null}}function QN(t){let e=wg();(0,$e.mkdirSync)((0,ql.dirname)(e),{recursive:!0});let n=zl(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,$e.writeFileSync)(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),(0,$e.renameSync)(r,e)}finally{try{(0,$e.existsSync)(r)&&(0,$e.unlinkSync)(r)}catch{}}}function Nv(t,e=GN){let n=Fv(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+JN)}function _g(t,e){let n=$l(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function ZN(t){try{let e=JSON.parse(t),n=e?.error?.code||e?.error,r=e?.error?.message||e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function eM(t){if(!t.refresh_token)throw new Error("Codex OAuth token cannot be refreshed because no refresh token is available. Run `ccr codex-auth` again.");let e=await fetch(YN(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:Iv.client_id,grant_type:"refresh_token",refresh_token:t.refresh_token}),signal:AbortSignal.timeout(3e4)}),n=await e.text();if(!e.ok)throw new Error(`Codex OAuth token refresh failed (${e.status}): ${ZN(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("Codex OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return zl({...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:r.expires_at||o+(typeof r.expires_in=="number"?r.expires_in:3600),account_id:r.account_id||t.account_id,last_refresh:o})}function tM(){let t=bg();try{return(0,$e.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,$e.statSync)(t).mtimeMs>VN&&(0,$e.unlinkSync)(t)}catch{}return null}}async function nM(t){let e=Date.now()+KN,n=null;for(;n===null&&(n=tM(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh Codex OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=(0,$e.fstatSync)(n).ino;(0,$e.closeSync)(n);try{(0,$e.statSync)(bg()).ino===r&&(0,$e.unlinkSync)(bg())}catch{}}}async function rM(t,e){return nM(async()=>{let n=Cg();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");_g(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!Nv(n))return n;let o=await eM(n);_g(e.expectedAccountId,o);let s=Cg();return s&&s.access_token!==n.access_token?(_g(e.expectedAccountId,s),s):(QN(o),o)})}async function Sg(t={}){let e=Cg();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!Nv(e)?e:(Ll||(Ll=rM(e,{...t,expectedAccountId:t.expectedAccountId||$l(e)}).finally(()=>{Ll=null})),Ll)}function Eg(t){let e=zl(t);return{mode:"oauth",token:e.access_token,accountId:$l(e),isFedramp:XN(e)}}var oM=300*1e3,Hl=new Map,vg=new Map,jv="0.145.0",Lv="codex_cli_rs",qv="x-codex-turn-metadata",sM="x-codex-window-id",iM="x-codex-parent-thread-id",aM="session_id",cM="thread_id",uM="turn_id",lM="window_id";function dM(){switch((0,tr.platform)()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return(0,tr.platform)()||"unknown"}}function fM(){switch((0,tr.arch)()){case"x64":return"x86_64";case"arm64":return"arm64";default:return(0,tr.arch)()||"unknown"}}function pM(){if((0,tr.platform)()==="darwin")try{return(0,Uv.execFileSync)("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return(0,tr.release)()||"unknown"}function hM(){return`${Lv}/${jv} (${dM()} ${pM()}; ${fM()})`}function Mv(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",jv),e.toString()}function mM(t){return{session_id:t,thread_id:t,turn_id:(0,Bv.randomUUID)(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function gM(t){return{[aM]:t.session_id,[cM]:t.thread_id,[uM]:t.turn_id,[lM]:t.window_id,[qv]:JSON.stringify(t)}}function yM(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function _M(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[sM]:t.window_id,[qv]:JSON.stringify(t),[iM]:t.thread_id}}function bM(t){let e=t?.metadata?.user_id;if(typeof e!="string"||!e)return;let n=e.split("_session_");if(n.length>1&&n[1])return n[1];try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}}function CM(t,e){return t?.req?.sessionId||bM(e)}function wM(t,e,n){if(!n)return;let r=mM(n);t.client_metadata=yM(t.client_metadata,gM(r)),Object.assign(e,_M(r))}var Wl=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let i=e.reasoning?.effort||n?.reasoningEffort;if(i){let b={effort:i},y=["auto","detailed","none"],w=n?.reasoningSummary;w&&y.includes(w)?w!=="none"&&(b.summary=w):b.summary="detailed",e.reasoning=b}else delete e.reasoning;let c=["low","medium","high"];n?.verbosity&&c.includes(n.verbosity)&&(e.verbosity=n.verbosity),e=np(e,r);let u=ic(e.messages);e.messages=u;let f=[],d=!1,p=e.messages.filter(b=>b.role==="system");if(p.length>0){let b=p[0],y;Array.isArray(b.content)?y=b.content.map(w=>typeof w=="string"?w:w&&typeof w=="object"&&"text"in w?w.text:"").filter(Boolean).join(`
290
+ `):y=b.content,y&&(e.instructions=y)}if(e.instructions||(e.instructions=""),e.messages.forEach(b=>{if(b.role!=="system"){if(Array.isArray(b.content)){let y=b.content.map(w=>this.normalizeRequestContent(w,b.role)).filter(w=>w!==null);y.length>0?b.content=y:delete b.content}if(b.role==="tool"){let y={...b};y.type="function_call_output",y.call_id=Ct(b.tool_call_id)??b.tool_call_id,y.output=b.content,delete y.cache_control,delete y.role,delete y.tool_call_id,delete y.content,f.push(y),d=!0;return}if(b.role==="assistant"&&Array.isArray(b.tool_calls)){d=!1,b.tool_calls.forEach(y=>{f.push({type:"function_call",arguments:y.function.arguments,name:y.function.name,call_id:Ct(y.id)??y.id})});return}d&&b.role==="user"&&f.push({type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),d=!1,typeof b.content=="string"?f.push({type:"message",role:b.role,content:[{type:b.role==="assistant"?"output_text":"input_text",text:b.content}]}):f.push({type:"message",role:b.role,content:b.content})}}),e.input=f,delete e.messages,e.store=!1,Array.isArray(e.tools)){let b=e.tools.find(y=>y.function.name==="web_search");e.tools=e.tools.filter(y=>y.function.name!=="web_search").map(y=>(y.function.name==="WebSearch"&&delete y.function.parameters.properties.allowed_domains,y.function.name==="Edit"?{type:y.type,name:y.function.name,description:y.function.description,parameters:{...y.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:y.type,name:y.function.name,description:y.function.description,parameters:y.function.parameters})),b&&e.tools.push({type:"web_search"})}e.parallel_tool_calls=n?.parallelToolCalls===!0,e.stream=!0;let h=this.buildAuthHeaders(s);wM(e,h,e.prompt_cache_key||CM(r,e));let _=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:Mv(`${_}/responses`),headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(n,s)}}}async auth(e,n){let r=await this.resolveAuth(n),o=this.buildAuthHeaders(r),s=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:Mv(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=(0,Ag.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):Eg(await Sg())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:Lv,"User-Agent":hM()};return e.accountId&&(n["ChatGPT-Account-ID"]=e.accountId),e.isFedramp&&(n["X-OpenAI-Fedramp"]="true"),n}async recoverUnauthorizedAuth(e,n){if(n.mode==="pat")return Hl.delete(n.token),null;if((0,Ag.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Sg({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),o=Eg(r);if(n.accountId&&o.accountId&&n.accountId!==o.accountId)throw new Error("Codex OAuth account changed during unauthorized recovery.");return this.buildAuthHeaders(o)}async resolvePatAuth(e){let n=Hl.get(e);if(n&&n.expiresAt>Date.now())return n.value;Hl.delete(e);let r=vg.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{vg.delete(e)});return vg.set(e,o),o}async requestPatAuth(e){let n=(process.env.CODEX_AUTHAPI_BASE_URL||"https://auth.openai.com/api/accounts").replace(/\/+$/,""),r=await fetch(`${n}/v1/user-auth-credential/whoami`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new Error(`Codex PAT metadata request failed (${r.status}). Verify that the configured at- token is valid and has Codex access.`);let o=await r.json();if(!o.chatgpt_account_id||!o.chatgpt_user_id||!o.chatgpt_plan_type)throw new Error("Codex PAT metadata response is missing required account, user, or plan information.");let s={mode:"pat",token:e,accountId:o.chatgpt_account_id,isFedramp:o.chatgpt_account_is_fedramp===!0};return Hl.set(e,{value:s,expiresAt:Date.now()+oM}),s}async transformResponseOut(e,n){let r=e.headers.get("Content-Type")||"",o=n?.req?.id,s=o?this.streamIntent.get(o):void 0;try{return await this.transformResponseOutInner(e,r,this,o,s)}finally{o&&this.streamIntent.delete(o)}}async transformResponseOutInner(e,n,r,o,s){let i=o?s!==!1:!0,c,u=f=>f?(c=f,f):c;if(!n||n.includes("text/event-stream")){if(!e.body)return e;let f=await this.readBodyAndPeek(e.clone().body);if(f&&(f.firstChar==="{"||f.firstChar==="[")){let v;try{v=JSON.parse(f.text)}catch{return i?new Response(this.jsonToSseStream(f.text),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f.text,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let A=v?.object==="response"&&v.output?this.convertResponseToChat(v):v,T=JSON.stringify(A);return i?new Response(this.jsonToSseStream(T),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(T,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}if(!i){let v=await this.collectSseIntoChatCompletion(e,u);return new Response(JSON.stringify(v),{status:e.status,statusText:e.statusText,headers:{"Content-Type":"application/json"}})}let d=-1,p="",h=v=>(v!==p&&(d++,p=v),d),b=Ie(e,(v,A)=>{if(v.trim()&&!v.startsWith("event: "))if(v.startsWith("data: ")){let T=v.slice(5).trim();if(T==="[DONE]"){A.controller.enqueue(Ee("[DONE]",A.encoder));return}try{let x=JSON.parse(T);x.response?.model&&(c=x.response.model);let O=r.convertStreamEvent(x,h,u);O&&A.controller.enqueue(Ee(JSON.stringify(O),A.encoder))}catch{A.controller.enqueue(Re(v,A.encoder))}}else A.controller.enqueue(Re(v,A.encoder))}).body,y=!1,w=null,C=new ReadableStream({start(v){w=b.getReader();let A=q=>{if(!y)try{v.enqueue(q)}catch{y=!0}},T=()=>{if(!y)try{v.close()}catch{}},x=q=>{if(!y)try{v.error(q)}catch{}},O=()=>{y||!w||w.read().then(({done:q,value:$})=>{if(q){T();return}$&&A($),O()}).catch(q=>{y||x(q)})};O()},cancel(){if(y=!0,w)try{w.cancel().catch(()=>{})}catch{}}});return new Response(C,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else if(n.includes("application/json")){let f=await e.json();if(Array.isArray(f)){let d=new TextEncoder,p=-1,h="",_=y=>(y!==h&&(p++,h=y),p),b=new ReadableStream({start(y){for(let w of f){w?.response?.model&&(c=w.response.model);let C=r.convertStreamEvent(w,_,u);C&&y.enqueue(d.encode(`data: ${JSON.stringify(C)}
260
291
 
261
- `)),s.close()}})}async readBodyAndPeek(e){let n=e.getReader(),r=new TextDecoder,o=()=>{try{n.releaseLock()}catch{}},s;try{s=await n.read()}catch(d){throw o(),d}if(s.done)return o(),null;let a=r.decode(s.value,{stream:!0}),l=a.trimStart().charAt(0)||"";if(l!=="{"&&l!=="[")return o(),null;let f=a;try{for(;;){let d=await n.read();if(d.done)break;f+=r.decode(d.value,{stream:!0})}}finally{f+=r.decode(),o()}return{firstChar:l,text:f}}async collectSseIntoChatCompletion(e,n){let r=e.body.getReader(),o=new TextDecoder,s="",a="unknown",c="chatcmpl-"+Date.now(),l=Math.floor(Date.now()/1e3),f="",d="",h=[],m=new Map,S=null,y,w=-1,b="",_=v=>(v!==b&&(w++,b=v),w),D=()=>{let v={role:"assistant"};d&&(v.thinking={content:d,signature:""});let x=Array.from(m.values());x.length&&(v.tool_calls=x),h.length&&(v.annotations=h),f?v.content=f:x.length===0&&!d?v.content=null:v.content=f||null;let R={index:0,message:v,logprobs:null,finish_reason:x.length?"tool_calls":S||"stop"};return{id:c,object:"chat.completion",created:l,model:a||"unknown",choices:[R],usage:y||null}},k=v=>{if(!v)return;v.id&&(c=v.id),v.model&&(a=v.model),v.created&&(l=v.created),v.usage&&(y=v.usage);let x=v.choices?.[0];if(!x)return;x.finish_reason&&(S=x.finish_reason);let R=x.delta||{};if(R.role,typeof R.content=="string"&&R.content&&(f+=R.content),R.thinking?.content&&(d+=R.thinking.content),R.thinking?.signature,Array.isArray(R.annotations))for(let j of R.annotations)h.push(j);if(Array.isArray(R.tool_calls))for(let j of R.tool_calls){let W=j.index??0,U=m.get(W)||{index:W,id:j.id,type:"function",function:{name:j.function?.name||"",arguments:""}};j.id&&(U.id=j.id),j.function?.name&&(U.function.name=j.function.name),typeof j.function?.arguments=="string"&&(U.function.arguments=(U.function.arguments||"")+j.function.arguments),m.set(W,U)}};for(;;){let{done:v,value:x}=await r.read();if(v)break;s+=o.decode(x,{stream:!0});let R=s.split(`
262
- `);s=R.pop()||"";for(let j of R){if(!j.startsWith("data: "))continue;let W=j.slice(5).trim();if(!(!W||W==="[DONE]"))try{let U=JSON.parse(W);if(U.response?.model){let Y=n(U.response.model);Y&&(a=Y)}let ue=this.convertStreamEvent(U,_,n);k(ue)}catch{}}}return D()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(l=>l.type==="message"),r=e.output?.find(l=>l.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(l=>({type:"url_citation",url_citation:{url:l.url||"",title:l.title||"",content:"",start_index:l.start_index||0,end_index:l.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,a=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let l=[],f=[];if(n.content.forEach(d=>{if(d.type==="output_text")l.push(d.text||"");else if(d.type==="output_image"){let h=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});h&&f.push(h)}else if(d.type==="output_image_base64"){let h=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});h&&f.push(h)}}),f.length>0){let d=[];l.length>0&&d.push({type:"text",text:l.join("")}),d.push(...f),s=d}else s=l.join("")}return r&&(a=[{id:r.call_id||r.id,function:{name:r.name,arguments:r.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:a,thinking:c,annotations:o},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var Kn=require("fs"),ng=require("path"),rg=require("os"),tg=(0,ng.join)((0,rg.homedir)(),".claude-code-router","qwen_auth.json"),F1="https://qwen.aikit.club",P1=1e4,I1=120;function N1(){try{if(!(0,Kn.existsSync)(tg))return null;let t=JSON.parse((0,Kn.readFileSync)(tg,"utf-8"));return t.token?t:null}catch{return null}}function B1(t){let e=(0,ng.join)((0,rg.homedir)(),".claude-code-router");(0,Kn.existsSync)(e)||(0,Kn.mkdirSync)(e,{recursive:!0}),(0,Kn.writeFileSync)(tg,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function j1(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1],"base64url").toString());if(e.exp)return e.exp*1e3}catch{}return null}async function M1(t){try{let e=await fetch(`${F1}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(P1)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function Vk(){let t=N1();if(!t)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");if(t.expiresAt&&Date.now()+I1*1e3>=t.expiresAt){let e=await M1(t.token);if(!e)throw new Error("Qwen token expired and refresh failed. Run `ccr qwen-auth` to re-authenticate.");t={token:e,expiresAt:j1(e),updatedAt:Date.now()},B1(t)}return t}var U1="https://qwen.aikit.club",Kk=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Qu=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await Vk();return{url:e?.api_base_url||e?.baseUrl||U1,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:qr(e),config:await this.buildAuthConfig(n)}}async auth(e,n){return{config:await this.buildAuthConfig(n)}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?ze(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Te(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Te(r,o.encoder));return}let a=s.replace(Kk,"");o.controller.enqueue(Te(`data: ${a}`,o.encoder));return}o.controller.enqueue(Te(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(Kk,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var og=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
292
+ `))}y.enqueue(d.encode(`data: [DONE]
293
+
294
+ `)),y.close()}});return new Response(b,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(f.object==="response"&&f.output){let d=this.convertResponseToChat(f);return new Response(JSON.stringify(d),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return new Response(JSON.stringify(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r){let o=i=>r?r(i):i,s=i=>i||o(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:0,id:Ct(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let i=[];(e.item.content||[]).forEach(u=>{u.type==="output_text"&&i.push({type:"text",text:u.text||""})});let c={role:"assistant"};return i.length===1&&i[0].type==="text"?c.content=i[0].text:i.length>0&&(c.content=i),c.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:c,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{tool_calls:[{index:0,function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let i=e.response?.output?.some(u=>u.type==="function_call")?"tool_calls":"stop",c={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:0,delta:{},finish_reason:i}]};return e.response?.usage&&(c.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),c}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_text.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{signature:e.item_id}},finish_reason:null}]}:e.type==="response.output_text.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}:e.type==="response.output_item.done"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:s(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}:null}jsonToSseStream(e){let n=new TextEncoder,r;try{r=JSON.parse(e)}catch{r=null}let o=s=>n.encode(`data: ${JSON.stringify(s)}
295
+
296
+ `);return new ReadableStream({start(s){if(!r){s.close();return}let i={id:r.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:r.created||Math.floor(Date.now()/1e3),model:r.model||"unknown"},c=r.choices?.[0];if(c){let u=c.message||{};if(typeof u.content=="string"&&u.content&&s.enqueue(o({...i,choices:[{index:0,delta:{role:"assistant",content:u.content},finish_reason:null}]})),u.thinking?.content&&s.enqueue(o({...i,choices:[{index:0,delta:{thinking:{content:u.thinking.content}},finish_reason:null}]})),Array.isArray(u.tool_calls))for(let d of u.tool_calls)s.enqueue(o({...i,choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:0,id:d.id,type:"function",function:{name:d.function?.name||"",arguments:d.function?.arguments||""}}]},finish_reason:null}]}));let f={...i,choices:[{index:0,delta:{},finish_reason:c.finish_reason||"stop"}]};r.usage&&(f.usage={prompt_tokens:r.usage.prompt_tokens||0,completion_tokens:r.usage.completion_tokens||0,total_tokens:r.usage.total_tokens||0,...r.usage.prompt_tokens_details?{prompt_tokens_details:{...r.usage.prompt_tokens_details}}:{}}),s.enqueue(o(f))}s.enqueue(n.encode(`data: [DONE]
297
+
298
+ `)),s.close()}})}async readBodyAndPeek(e){let n=e.getReader(),r=new TextDecoder,o=()=>{try{n.releaseLock()}catch{}},s;try{s=await n.read()}catch(d){throw o(),d}if(s.done)return o(),null;let i=r.decode(s.value,{stream:!0}),u=i.trimStart().charAt(0)||"";if(u!=="{"&&u!=="[")return o(),null;let f=i;try{for(;;){let d=await n.read();if(d.done)break;f+=r.decode(d.value,{stream:!0})}}finally{f+=r.decode(),o()}return{firstChar:u,text:f}}async collectSseIntoChatCompletion(e,n){let r=e.body.getReader(),o=new TextDecoder,s="",i="unknown",c="chatcmpl-"+Date.now(),u=Math.floor(Date.now()/1e3),f="",d="",p=[],h=new Map,_=null,b,y=-1,w="",C=T=>(T!==w&&(y++,w=T),y),v=()=>{let T={role:"assistant"};d&&(T.thinking={content:d,signature:""});let x=Array.from(h.values());x.length&&(T.tool_calls=x),p.length&&(T.annotations=p),f?T.content=f:x.length===0&&!d?T.content=null:T.content=f||null;let O={index:0,message:T,logprobs:null,finish_reason:x.length?"tool_calls":_||"stop"};return{id:c,object:"chat.completion",created:u,model:i||"unknown",choices:[O],usage:b||null}},A=T=>{if(!T)return;T.id&&(c=T.id),T.model&&(i=T.model),T.created&&(u=T.created),T.usage&&(b=T.usage);let x=T.choices?.[0];if(!x)return;x.finish_reason&&(_=x.finish_reason);let O=x.delta||{};if(O.role,typeof O.content=="string"&&O.content&&(f+=O.content),O.thinking?.content&&(d+=O.thinking.content),O.thinking?.signature,Array.isArray(O.annotations))for(let q of O.annotations)p.push(q);if(Array.isArray(O.tool_calls))for(let q of O.tool_calls){let $=q.index??0,H=h.get($)||{index:$,id:q.id,type:"function",function:{name:q.function?.name||"",arguments:""}};q.id&&(H.id=q.id),q.function?.name&&(H.function.name=q.function.name),typeof q.function?.arguments=="string"&&(H.function.arguments=(H.function.arguments||"")+q.function.arguments),h.set($,H)}};for(;;){let{done:T,value:x}=await r.read();if(T)break;s+=o.decode(x,{stream:!0});let O=s.split(`
299
+ `);s=O.pop()||"";for(let q of O){if(!q.startsWith("data: "))continue;let $=q.slice(5).trim();if(!(!$||$==="[DONE]"))try{let H=JSON.parse($);if(H.response?.model){let X=n(H.response.model);X&&(i=X)}let ae=this.convertStreamEvent(H,C,n);A(ae)}catch{}}}return v()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=e.output?.find(u=>u.type==="function_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,i=null,c=null;if(n&&n.reasoning&&(c={content:n.reasoning}),n&&n.content){let u=[],f=[];if(n.content.forEach(d=>{if(d.type==="output_text")u.push(d.text||"");else if(d.type==="output_image"){let p=this.buildImageContent({url:d.image_url,mime_type:d.mime_type});p&&f.push(p)}else if(d.type==="output_image_base64"){let p=this.buildImageContent({b64_json:d.image_base64,mime_type:d.mime_type});p&&f.push(p)}}),f.length>0){let d=[];u.length>0&&d.push({type:"text",text:u.join("")}),d.push(...f),s=d}else s=u.join("")}return r&&(i=[{id:Ct(r.call_id||r.id)||r.call_id||r.id,function:{name:r.name,arguments:r.arguments},type:"function"}]),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:c,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};var nr=require("fs"),Rg=require("path"),xg=require("os"),Tg=(0,Rg.join)((0,xg.homedir)(),".claude-code-router","qwen_auth.json"),kM="https://qwen.aikit.club",SM=1e4,EM=120;function vM(){try{if(!(0,nr.existsSync)(Tg))return null;let t=JSON.parse((0,nr.readFileSync)(Tg,"utf-8"));return t.token?t:null}catch{return null}}function AM(t){let e=(0,Rg.join)((0,xg.homedir)(),".claude-code-router");(0,nr.existsSync)(e)||(0,nr.mkdirSync)(e,{recursive:!0}),(0,nr.writeFileSync)(Tg,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function TM(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1],"base64url").toString());if(e.exp)return e.exp*1e3}catch{}return null}async function RM(t){try{let e=await fetch(`${kM}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(SM)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function $v(){let t=vM();if(!t)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");if(t.expiresAt&&Date.now()+EM*1e3>=t.expiresAt){let e=await RM(t.token);if(!e)throw new Error("Qwen token expired and refresh failed. Run `ccr qwen-auth` to re-authenticate.");t={token:e,expiresAt:TM(e),updatedAt:Date.now()},AM(t)}return t}var xM="https://qwen.aikit.club",zv=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Gl=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await $v();return{url:e?.api_base_url||e?.baseUrl||xM,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:Qr(e),config:await this.buildAuthConfig(n)}}async auth(e,n){return{config:await this.buildAuthConfig(n)}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ie(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Re(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Re(r,o.encoder));return}let i=s.replace(zv,"");o.controller.enqueue(Re(`data: ${i}`,o.encoder));return}o.controller.enqueue(Re(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(zv,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var Dg=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
263
300
 
264
301
  Output format:
265
302
  <reasoning_content>
266
303
  Your detailed thinking process goes here
267
304
  </reasoning_content>
268
- Your final answer must follow after the closing tag above.`,L1=10,Zu=class{logger;name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<L1)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
269
- ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:og}):r.content=[{type:"text",text:og},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:og}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,a=o.choices[0]?.message.content.match(s);a&&a[1]&&(o.thinking={content:a[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,a=new TextEncoder,c=new ReadableStream({start:async l=>{let f=e.body.getReader(),d="",h="SEARCHING",m="",S="",y=(w,b)=>{if(typeof b!="string"){w.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0&&!w.choices[0].delta.content&&(w.choices[0].index=o,l.enqueue(a.encode(`data: ${JSON.stringify(w)}
305
+ Your final answer must follow after the closing tag above.`,DM=10,Jl=class{logger;name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<DM)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
306
+ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:Dg}):r.content=[{type:"text",text:Dg},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:Dg}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,i=o.choices[0]?.message.content.match(s);i&&i[1]&&(o.thinking={content:i[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,i=new TextEncoder,c=new ReadableStream({start:async u=>{let f=e.body.getReader(),d="",p="SEARCHING",h="",_="",b=(y,w)=>{if(typeof w!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=o,u.enqueue(i.encode(`data: ${JSON.stringify(y)}
307
+
308
+ `)));return}let C=h+w;for(h="";C.length>0;)if(p==="SEARCHING"){let v=C.indexOf(n);if(v!==-1)C=C.substring(v+n.length),p="REASONING";else{for(let A=n.length-1;A>0;A--)if(C.endsWith(n.substring(0,A))){h=C.substring(C.length-A);break}C=""}}else if(p==="REASONING"){let v=C.indexOf(r);if(v!==-1){let A=C.substring(0,v);if(A.length>0){let O={...y.choices[0].delta,thinking:{content:A}};delete O.content;let q={...y,choices:[{...y.choices[0],delta:O,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(q)}
309
+
310
+ `))}let T={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete T.content;let x={...y,choices:[{...y.choices[0],delta:T,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
270
311
 
271
- `)));return}let _=m+b;for(m="";_.length>0;)if(h==="SEARCHING"){let D=_.indexOf(n);if(D!==-1)_=_.substring(D+n.length),h="REASONING";else{for(let k=n.length-1;k>0;k--)if(_.endsWith(n.substring(0,k))){m=_.substring(_.length-k);break}_=""}}else if(h==="REASONING"){let D=_.indexOf(r);if(D!==-1){let k=_.substring(0,D);if(k.length>0){let R={...w.choices[0].delta,thinking:{content:k}};delete R.content;let j={...w,choices:[{...w.choices[0],delta:R,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(j)}
312
+ `)),o++,C=C.substring(v+r.length),p="FINAL"}else{let A=C;for(let T=r.length-1;T>0;T--)if(C.endsWith(r.substring(0,T))){h=C.substring(C.length-T),A=C.substring(0,C.length-T);break}if(A.length>0){let T={...y.choices[0].delta,thinking:{content:A}};delete T.content;let x={...y,choices:[{...y.choices[0],delta:T,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
272
313
 
273
- `))}let v={...w.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete v.content;let x={...w,choices:[{...w.choices[0],delta:v,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(x)}
314
+ `))}C=""}}else if(p==="FINAL"){if(C.length>0)if(/^\s*$/.test(C))_+=C;else{let A=_+C,T={...y.choices[0].delta,content:A};T.thinking&&delete T.thinking;let x={...y,choices:[{...y.choices[0],delta:T}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
274
315
 
275
- `)),o++,_=_.substring(D+r.length),h="FINAL"}else{let k=_;for(let v=r.length-1;v>0;v--)if(_.endsWith(r.substring(0,v))){m=_.substring(_.length-v),k=_.substring(0,_.length-v);break}if(k.length>0){let v={...w.choices[0].delta,thinking:{content:k}};delete v.content;let x={...w,choices:[{...w.choices[0],delta:v,index:o}]};l.enqueue(a.encode(`data: ${JSON.stringify(x)}
316
+ `)),_=""}o++,C=""}};try{for(;;){let{done:y,value:w}=await f.read();if(y)break;let C=s.decode(w,{stream:!0});d+=C;let v=d.split(`
317
+ `);d=v.pop()||"";for(let A of v)if(A.trim()){if(A.trim()==="data: [DONE]"){u.enqueue(i.encode(A+`
276
318
 
277
- `))}_=""}}else if(h==="FINAL"){if(_.length>0)if(/^\s*$/.test(_))S+=_;else{let k=S+_,v={...w.choices[0].delta,content:k};v.thinking&&delete v.thinking;let x={...w,choices:[{...w.choices[0],delta:v}]};l.enqueue(a.encode(`data: ${JSON.stringify(x)}
319
+ `));break}if(A.startsWith("data:"))try{let T=JSON.parse(A.slice(5));b(T,T.choices?.[0]?.delta?.content)}catch{u.enqueue(i.encode(A+`
320
+ `))}else u.enqueue(i.encode(A+`
321
+ `))}}}catch(y){this.logger?.error("Stream error:",y),u.error(y)}finally{try{f.releaseLock()}catch(y){this.logger?.error("Error releasing reader lock:",y)}if(p==="REASONING"){let w={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};u.enqueue(i.encode(`data: ${JSON.stringify(w)}
278
322
 
279
- `)),S=""}o++,_=""}};try{for(;;){let{done:w,value:b}=await f.read();if(w)break;let _=s.decode(b,{stream:!0});d+=_;let D=d.split(`
280
- `);d=D.pop()||"";for(let k of D)if(k.trim()){if(k.trim()==="data: [DONE]"){l.enqueue(a.encode(k+`
323
+ `))}u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Vl=class{name="extrathinktag";async transformRequestIn(e){return e}async transformResponseOut(e){let n="<think>",r="</think>";if(e.headers.get("Content-Type")?.includes("application/json"))try{let u=await e.json(),f=u?.choices?.[0]?.message?.content;if(typeof f=="string"){let d=f.match(/<think>([\s\S]*?)<\/think>/);d?.[1]&&(u.thinking={content:d[1]})}return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return e}if(!e.headers.get("Content-Type")?.includes("stream")||!e.body)return e;let o=new TextDecoder,s=new TextEncoder,i=0,c=new ReadableStream({async start(u){let f=e.body.getReader(),d="",p="SEARCHING",h="",_="",b=w=>{u.enqueue(s.encode(`data: ${JSON.stringify(w)}
281
324
 
282
- `));break}if(k.startsWith("data:"))try{let v=JSON.parse(k.slice(5));y(v,v.choices?.[0]?.delta?.content)}catch{l.enqueue(a.encode(k+`
283
- `))}else l.enqueue(a.encode(k+`
284
- `))}}}catch(w){this.logger?.error("Stream error:",w),l.error(w)}finally{try{f.releaseLock()}catch(w){this.logger?.error("Error releasing reader lock:",w)}if(h==="REASONING"){let b={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};l.enqueue(a.encode(`data: ${JSON.stringify(b)}
325
+ `))},y=(w,C)=>{if(typeof C!="string"&&w?.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0&&!w.choices[0].delta.content){w.choices[0].index=i,b(w);return}if(typeof C!="string")return;let v=h+C;for(h="";v.length>0;){if(p==="SEARCHING"){let A=v.indexOf(n);if(A!==-1){v=v.substring(A+n.length),p="THINKING";continue}for(let T=n.length-1;T>0;T--)if(v.endsWith(n.substring(0,T))){h=v.substring(v.length-T);break}v="";continue}if(p==="THINKING"){let A=v.indexOf(r);if(A!==-1){let x=v.substring(0,A);if(x.length>0){let q={...w.choices[0].delta,thinking:{content:x}};delete q.content,b({...w,choices:[{...w.choices[0],delta:q,index:i}]})}let O={...w.choices[0].delta,thinking:{signature:Date.now().toString()}};delete O.content,b({...w,choices:[{...w.choices[0],delta:O,index:i}]}),i++,v=v.substring(A+r.length),p="FINAL";continue}let T=v;for(let x=r.length-1;x>0;x--)if(v.endsWith(r.substring(0,x))){h=v.substring(v.length-x),T=v.substring(0,v.length-x);break}if(T.length>0){let x={...w.choices[0].delta,thinking:{content:T}};delete x.content,b({...w,choices:[{...w.choices[0],delta:x,index:i}]})}v="";continue}if(v.length>0)if(/^\s*$/.test(v))_+=v;else{let A=_+v,T={...w.choices[0].delta,content:A};T.thinking&&delete T.thinking,b({...w,choices:[{...w.choices[0],delta:T}]}),_=""}i++,v=""}};try{for(;;){let{done:w,value:C}=await f.read();if(w)break;d+=o.decode(C,{stream:!0});let v=d.split(`
326
+ `);d=v.pop()||"";for(let A of v)if(A.trim()){if(A.trim()==="data: [DONE]"){u.enqueue(s.encode(A+`
285
327
 
286
- `))}l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var el=class{name="extrathinktag";async transformRequestIn(e){return e}async transformResponseOut(e){let n="<think>",r="</think>";if(e.headers.get("Content-Type")?.includes("application/json"))try{let l=await e.json(),f=l?.choices?.[0]?.message?.content;if(typeof f=="string"){let d=f.match(/<think>([\s\S]*?)<\/think>/);d?.[1]&&(l.thinking={content:d[1]})}return new Response(JSON.stringify(l),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return e}if(!e.headers.get("Content-Type")?.includes("stream")||!e.body)return e;let o=new TextDecoder,s=new TextEncoder,a=0,c=new ReadableStream({async start(l){let f=e.body.getReader(),d="",h="SEARCHING",m="",S="",y=b=>{l.enqueue(s.encode(`data: ${JSON.stringify(b)}
328
+ `));continue}if(A.startsWith("data:"))try{let T=JSON.parse(A.slice(5));y(T,T?.choices?.[0]?.delta?.content)}catch{u.enqueue(s.encode(A+`
329
+ `))}else u.enqueue(s.encode(A+`
330
+ `))}}}catch(w){console.error("Stream error:",w),u.error(w)}finally{try{f.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}p==="THINKING"&&b({choices:[{delta:{thinking:{signature:Date.now().toString()}}}]}),u.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}};function OM(t){let e={...t};if(Array.isArray(e.content)){let n=e.content,r=n.some(s=>s.type==="image_url"),o=n.some(s=>s.type==="thinking");if(r||o)e.content=n.map(s=>{if(s.type==="text"){let{cache_control:i,...c}=s;return c}return s});else{let s=n.filter(i=>i.type==="text").map(i=>i.text).filter(i=>i&&i.length>0);e.content=s.join(`
331
+ `)}}return e.cache_control&&delete e.cache_control,e}function PM(t){return t==="auto"||t==="none"?t:t==="required"?"any":typeof t=="object"&&t.function?.name?{type:"function",function:{name:t.function.name}}:t}function IM(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="low"||e==="medium"||e==="high"?e:"high"}var Hv=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function Wv(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>OM(s))),r.stream===void 0&&(r.stream=!0);let o=Yt(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=PM(r.tool_choice)),Array.isArray(r.tools)&&(r.tools=r.tools.map(s=>{let{cache_control:i,...c}=s;return c?.function?.parameters?{...c,function:{...c.function,parameters:Ac(c.function.parameters)}}:c})),r.reasoning&&r.model){let s=r.model;(s.startsWith("magistral-")||s.startsWith("labs-leanstral-")||s==="mistral-vibe-cli-fast"||s.startsWith("mistral-small-")&&!Hv.has(s)||s.startsWith("mistral-medium-")&&!Hv.has(s))&&(r.reasoning_effort=IM(r.reasoning)),delete r.reasoning}return r}async function Gv(t,e,n){let r=t.headers.get("Content-Type")??"";if(r.includes("application/json")){let o=await t.json();n?.debug({response:o},`${e} response:`);let s=o.choices?.[0];if(s?.message){let i=s.message,c="";if(i.reasoning_content){let u=i.reasoning_content;c+=typeof u=="string"?u:typeof u?.text=="string"?u.text:JSON.stringify(u),delete i.reasoning_content}if(Array.isArray(i.content)){let u="";for(let f of i.content)if(f.type==="thinking"){let d=Array.isArray(f.thinking)?f.thinking:[f.thinking];c+=d.map(p=>typeof p=="string"?p:p&&typeof p.text=="string"?p.text:JSON.stringify(p)).join("")}else f.type==="text"&&(u+=typeof f.text=="string"?f.text:JSON.stringify(f.text??""));i.content=u}c&&(o.thinking={content:c})}return new Response(JSON.stringify(o),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(r.includes("stream"))return t.body?Ie(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Re(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Re(o,s.encoder));return}try{let i=o.slice(5).trim(),c=JSON.parse(i),u=c.choices?.[0]?.delta;if(!u){s.controller.enqueue(Re(o,s.encoder));return}let f=ws(u);if(f){let d=Nr(c,{content:f});Mr(d.choices[0].delta);let p=u.content;if(Array.isArray(p)){let h="",_=p.filter(b=>b.type==="text").map(b=>typeof b.text=="string"?b.text:JSON.stringify(b.text??"")).join("");for(let b of p)if(b.type==="thinking"){let y=Array.isArray(b.thinking)?b.thinking:[b.thinking];h+=y.map(w=>typeof w=="string"?w:w&&typeof w.text=="string"?w.text:JSON.stringify(w)).join("")}delete d.choices[0].delta.content,(h||f)&&(d.choices[0].delta.thinking={content:h||f}),_&&(d.choices[0].delta.content=_)}s.controller.enqueue(Ee(JSON.stringify(d),s.encoder));return}if(Array.isArray(u.content)){let d="",p=u.content.filter(h=>h.type==="text").map(h=>typeof h.text=="string"?h.text:JSON.stringify(h.text??"")).join("");for(let h of u.content)if(h.type==="thinking"){let _=Array.isArray(h.thinking)?h.thinking:[h.thinking];d+=_.map(b=>typeof b=="string"?b:b&&typeof b.text=="string"?b.text:JSON.stringify(b)).join("")}delete u.content,d&&(u.thinking={content:d}),p&&(u.content=p)}s.controller.enqueue(Ee(JSON.stringify(c),s.encoder))}catch{s.controller.enqueue(Re(o,s.encoder))}}):t;return t}var Kl=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:Wv(e,r,n),config:{url:new URL("/v1/chat/completions",n.baseUrl),headers:{Authorization:`Bearer ${n.apiKey}`}}}}transformRequestOut;async transformResponseOut(e,n){try{return await Gv(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var FM="http://127.0.0.1:3457",Yl=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||FM;r?.req?.body&&(r.req.body.stream=!0);let s=Yt(r,e);return{body:{...e,messages:Je(e.messages),tools:Ve(e.tools),stream:!0},config:{url:`${o}/v1/chat/completions`,headers:{"Content-Type":"application/json",...s?{"x-ccr-session-id":s}:{}}}}}async transformResponseOut(e){return(e.headers.get("Content-Type")||"").includes("text/event-stream")||!e.body,e}};var Ql=require("crypto");var NM="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Jv=3,Xl=class{name="opencode-headers";sessionCache=new Map;MAX_SESSIONS=100;lastTimestamp=0;counter=0;async transformRequestIn(e,n,r){let o=r?.req?.sessionId||this.fingerprintConversation(e,r),s=e.body||e,i=e.config||{},c=await this.sendWithSessionRetry(s,i,n,r,o);return{body:s,config:{...i,url:n?.baseUrl||n?.api_base_url,__providerResponse:c}}}async sendWithSessionRetry(e,n,r,o,s){let i=r?.baseUrl||r?.api_base_url,c=o?.req?.server?.configService?.getHttpsProxy?.(),u=o?.req?.log??o?.req?.server?.log,f=e?.model;for(let d=0;d<Jv;d++){let p=this.buildHeaders(n,r,s),h=await Uo(i,e,{httpsProxy:c,...n,headers:p,signal:o?.signal??n?.signal},o,u);if(h.ok)return h;let _=await h.text();if(!(d===Jv-1)&&this.isZenRoutingFailure(h.status,_)){this.invalidateSession(s),u?.warn?.({provider:r?.name,model:f,status:h.status,attempt:d+1},"opencode: Zen provider-routing failure \u2014 re-rolling session and retrying");continue}let y=et(_)||_.slice(0,240);throw W(`Error from provider(${r?.name},${f}: ${h.status}): ${y}`,h.status,"provider_response_error","api_error",this.retryAfterHeaders(h))}throw W(`Error from provider(${r?.name},${f}): Zen provider-routing retries exhausted`,503,"provider_response_error")}buildHeaders(e,n,r){let o=this.getOrCreateSessionId(r),s=this.generateId("msg");return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":o,"x-opencode-request":s,"x-opencode-client":"cli","user-agent":"opencode/1.18.4",authorization:void 0}}isZenRoutingFailure(e,n){if(e!==401&&e!==400)return!1;let r;try{r=JSON.parse(n)}catch{return!1}let o=String(r?.error?.message||"");return!!(e===401&&r?.error?.type==="ModelError"&&/no provider available/i.test(o)||e===400&&/upstream request failed/i.test(o))}retryAfterHeaders(e){let n=e.headers.get("retry-after");return n?{"Retry-After":n}:void 0}fingerprintConversation(e,n){let r=e.body||e,o=r.model||"",s=r.messages||[],i=JSON.stringify(s.slice(0,3)),c=n?.req?.headers?.["x-forwarded-for"]||n?.req?.ip||"",u=n?.req?.headers?.["user-agent"]||"";return(0,Ql.createHash)("sha256").update(`${o}|${c}|${u}|${i}`).digest("hex").slice(0,32)}getOrCreateSessionId(e){let n=this.sessionCache.get(e);if(n)return n;if(this.sessionCache.size>=this.MAX_SESSIONS){let o=this.sessionCache.keys().next().value;o!==void 0&&this.sessionCache.delete(o)}let r=this.generateId("ses");return this.sessionCache.set(e,r),r}invalidateSession(e){this.sessionCache.delete(e)}generateId(e){let n=Date.now();n!==this.lastTimestamp&&(this.lastTimestamp=n,this.counter=0),this.counter++;let r=BigInt(n)*BigInt(4096)+BigInt(this.counter),o=Buffer.alloc(6);for(let i=0;i<6;i++)o[i]=Number(r>>BigInt(40-8*i)&BigInt(255));let s="";for(;s.length<14;){let i=(0,Ql.randomBytes)(1)[0];i>=248||(s+=NM[i%62])}return`${e}_${o.toString("hex")}${s}`}};var qg=require("crypto");var Et=require("fs"),Rs=require("path"),Og=require("os"),Kv=require("crypto"),MM=(0,Rs.join)((0,Og.homedir)(),".claude-code-router","claude_auth.json"),BM=(0,Rs.join)((0,Og.homedir)(),".claude-code-router","claude_device.json"),UM=/^[0-9a-f]{64}$/;function Yv(){return process.env.CCR_CLAUDE_AUTH_FILE||MM}function jM(){return process.env.CCR_CLAUDE_DEVICE_FILE||BM}var Vv={client_id:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorization_endpoint:"https://claude.ai/oauth/authorize",token_endpoint:"https://platform.claude.com/v1/oauth/token",scope:"user:profile user:inference user:sessions:claude_code user:mcp_servers"};function Pg(){try{let t=Yv();if(!(0,Et.existsSync)(t))return null;let e=(0,Et.readFileSync)(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function Ig(t){let e=Yv(),n=(0,Rs.dirname)(e);(0,Et.existsSync)(n)||(0,Et.mkdirSync)(n,{recursive:!0}),(0,Et.writeFileSync)(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function LM(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function Fg(t){let e=await fetch(Vv.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:Vv.client_id,refresh_token:t})});if(!e.ok){let r=await e.text();throw new Error(`Token refresh failed (${e.status}): ${r}`)}let n=await e.json();return{access_token:n.access_token,refresh_token:n.refresh_token,id_token:n.id_token,token_type:n.token_type||"Bearer",scope:n.scope,expires_at:n.expires_at||Date.now()/1e3+(n.expires_in||3600),last_refresh:Date.now()/1e3}}async function Xv(){let t=Pg();if(!t)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(LM(t)){if(!t.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");t=await Fg(t.refresh_token),Ig(t)}return t}function Qv(){let t=jM();try{if((0,Et.existsSync)(t)){let r=JSON.parse((0,Et.readFileSync)(t,"utf-8"));if(typeof r.device_id=="string"&&UM.test(r.device_id))return r.device_id}}catch{}let e=(0,Kv.randomBytes)(32).toString("hex"),n=(0,Rs.dirname)(t);return(0,Et.existsSync)(n)||(0,Et.mkdirSync)(n,{recursive:!0}),(0,Et.writeFileSync)(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}var Zl=require("crypto");var qM="59cf53e54c78",Mg=process.env.ANTHROPIC_CLI_VERSION||"2.1.220",Bg=process.env.CLAUDE_CODE_ENTRYPOINT||"cli",xs="You are Claude Code, Anthropic's official CLI for Claude.";function $M(t){return typeof t=="string"?t:Array.isArray(t)?t.find(n=>n.type==="text")?.text??"":""}function zM(t){let e=t?.find(n=>n.role==="user");return e?$M(e.content):""}function HM(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return(0,Zl.createHash)("sha256").update(qM+n+e).digest("hex").slice(0,3)}var Ng;function WM(){return Ng||(Ng=(0,Zl.randomBytes)(3).toString("hex").slice(0,5)),Ng}function GM(t,e=Mg,n=Bg){let r=HM(zM(t),e);return`${_i}: cc_version=${e}.${r}; cc_entrypoint=${n}; cch=${WM()};`}function Zv(t){let e=[],n=r=>{if(typeof r=="string"){r&&e.push({type:"text",text:r});return}if(Array.isArray(r)){for(let o of r)if(o?.type==="text"&&o.text){let s={type:"text",text:o.text};o.cache_control!==void 0&&(s.cache_control=o.cache_control),e.push(s)}}};if((typeof t.system=="string"||Array.isArray(t.system))&&n(t.system),Array.isArray(t.messages)){let r=[];for(let o of t.messages)o.role==="system"||o.role==="developer"?n(o.content):r.push(o);t.messages=r}return t.system=e,e}function eA(t,e){for(let n=t.length-1;n>=0;n--)t[n].text.startsWith(_i)&&t.splice(n,1);t.unshift({type:"text",text:GM(e)})}function tA(t){let n=t[1];if(n?.text!==xs){if(n?.text.startsWith(xs)&&n.text.length>xs.length){let r={type:"text",text:n.text.slice(xs.length)};n.cache_control!==void 0&&(r.cache_control=n.cache_control),t.splice(1,1,{type:"text",text:xs},r);return}t.splice(1,0,{type:"text",text:xs})}}function nA(t,e){if(t.length<=2||!Array.isArray(e))return;let n=e.find(s=>s.role==="user");if(!n)return;let o=t.splice(2).map(s=>s.text).filter(s=>s.length>0).join(`
287
332
 
288
- `))},w=(b,_)=>{if(typeof _!="string"&&b?.choices?.[0]?.delta&&Object.keys(b.choices[0].delta).length>0&&!b.choices[0].delta.content){b.choices[0].index=a,y(b);return}if(typeof _!="string")return;let D=m+_;for(m="";D.length>0;){if(h==="SEARCHING"){let k=D.indexOf(n);if(k!==-1){D=D.substring(k+n.length),h="THINKING";continue}for(let v=n.length-1;v>0;v--)if(D.endsWith(n.substring(0,v))){m=D.substring(D.length-v);break}D="";continue}if(h==="THINKING"){let k=D.indexOf(r);if(k!==-1){let x=D.substring(0,k);if(x.length>0){let j={...b.choices[0].delta,thinking:{content:x}};delete j.content,y({...b,choices:[{...b.choices[0],delta:j,index:a}]})}let R={...b.choices[0].delta,thinking:{signature:Date.now().toString()}};delete R.content,y({...b,choices:[{...b.choices[0],delta:R,index:a}]}),a++,D=D.substring(k+r.length),h="FINAL";continue}let v=D;for(let x=r.length-1;x>0;x--)if(D.endsWith(r.substring(0,x))){m=D.substring(D.length-x),v=D.substring(0,D.length-x);break}if(v.length>0){let x={...b.choices[0].delta,thinking:{content:v}};delete x.content,y({...b,choices:[{...b.choices[0],delta:x,index:a}]})}D="";continue}if(D.length>0)if(/^\s*$/.test(D))S+=D;else{let k=S+D,v={...b.choices[0].delta,content:k};v.thinking&&delete v.thinking,y({...b,choices:[{...b.choices[0],delta:v}]}),S=""}a++,D=""}};try{for(;;){let{done:b,value:_}=await f.read();if(b)break;d+=o.decode(_,{stream:!0});let D=d.split(`
289
- `);d=D.pop()||"";for(let k of D)if(k.trim()){if(k.trim()==="data: [DONE]"){l.enqueue(s.encode(k+`
333
+ `);o&&(typeof n.content=="string"?n.content=n.content?`${o}
290
334
 
291
- `));continue}if(k.startsWith("data:"))try{let v=JSON.parse(k.slice(5));w(v,v?.choices?.[0]?.delta?.content)}catch{l.enqueue(s.encode(k+`
292
- `))}else l.enqueue(s.encode(k+`
293
- `))}}}catch(b){console.error("Stream error:",b),l.error(b)}finally{try{f.releaseLock()}catch(b){console.error("Error releasing reader lock:",b)}h==="THINKING"&&y({choices:[{delta:{thinking:{signature:Date.now().toString()}}}]}),l.close()}}});return new Response(c,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}};function q1(t){let e={...t};if(Array.isArray(e.content)){let n=e.content,r=n.some(s=>s.type==="image_url"),o=n.some(s=>s.type==="thinking");if(r||o)e.content=n.map(s=>{if(s.type==="text"){let{cache_control:a,...c}=s;return c}return s});else{let s=n.filter(a=>a.type==="text").map(a=>a.text).filter(a=>a&&a.length>0);e.content=s.join(`
294
- `)}}return e.cache_control&&delete e.cache_control,e}function $1(t){return t==="auto"||t==="none"?t:t==="required"?"any":typeof t=="object"&&t.function?.name?{type:"function",function:{name:t.function.name}}:t}function z1(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="low"||e==="medium"||e==="high"?e:"high"}var Yk=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function Xk(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>q1(s))),r.stream===void 0&&(r.stream=!0);let o=Qt(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=$1(r.tool_choice)),Array.isArray(r.tools)&&(r.tools=r.tools.map(s=>{let{cache_control:a,...c}=s;return c?.function?.parameters?{...c,function:{...c.function,parameters:Fa(c.function.parameters)}}:c})),r.reasoning&&r.model){let s=r.model;(s.startsWith("magistral-")||s.startsWith("labs-leanstral-")||s==="mistral-vibe-cli-fast"||s.startsWith("mistral-small-")&&!Yk.has(s)||s.startsWith("mistral-medium-")&&!Yk.has(s))&&(r.reasoning_effort=z1(r.reasoning)),delete r.reasoning}return r}async function Qk(t,e,n){let r=t.headers.get("Content-Type")??"";if(r.includes("application/json")){let o=await t.json();n?.debug({response:o},`${e} response:`);let s=o.choices?.[0];if(s?.message){let a=s.message,c="";if(a.reasoning_content){let l=a.reasoning_content;c+=typeof l=="string"?l:typeof l?.text=="string"?l.text:JSON.stringify(l),delete a.reasoning_content}if(Array.isArray(a.content)){let l="";for(let f of a.content)if(f.type==="thinking"){let d=Array.isArray(f.thinking)?f.thinking:[f.thinking];c+=d.map(h=>typeof h=="string"?h:h&&typeof h.text=="string"?h.text:JSON.stringify(h)).join("")}else f.type==="text"&&(l+=typeof f.text=="string"?f.text:JSON.stringify(f.text??""));a.content=l}c&&(o.thinking={content:c})}return new Response(JSON.stringify(o),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(r.includes("stream"))return t.body?ze(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Te(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Te(o,s.encoder));return}try{let a=o.slice(5).trim(),c=JSON.parse(a),l=c.choices?.[0]?.delta;if(!l){s.controller.enqueue(Te(o,s.encoder));return}let f=is(l);if(f){let d=Sr(c,{content:f});Ar(d.choices[0].delta);let h=l.content;if(Array.isArray(h)){let m="",S=h.filter(y=>y.type==="text").map(y=>typeof y.text=="string"?y.text:JSON.stringify(y.text??"")).join("");for(let y of h)if(y.type==="thinking"){let w=Array.isArray(y.thinking)?y.thinking:[y.thinking];m+=w.map(b=>typeof b=="string"?b:b&&typeof b.text=="string"?b.text:JSON.stringify(b)).join("")}delete d.choices[0].delta.content,(m||f)&&(d.choices[0].delta.thinking={content:m||f}),S&&(d.choices[0].delta.content=S)}s.controller.enqueue(Be(JSON.stringify(d),s.encoder));return}if(Array.isArray(l.content)){let d="",h=l.content.filter(m=>m.type==="text").map(m=>typeof m.text=="string"?m.text:JSON.stringify(m.text??"")).join("");for(let m of l.content)if(m.type==="thinking"){let S=Array.isArray(m.thinking)?m.thinking:[m.thinking];d+=S.map(y=>typeof y=="string"?y:y&&typeof y.text=="string"?y.text:JSON.stringify(y)).join("")}delete l.content,d&&(l.thinking={content:d}),h&&(l.content=h)}s.controller.enqueue(Be(JSON.stringify(c),s.encoder))}catch{s.controller.enqueue(Te(o,s.encoder))}}):t;return t}var tl=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:Xk(e,r,n),config:{url:new URL("/v1/chat/completions",n.baseUrl),headers:{Authorization:`Bearer ${n.apiKey}`}}}}transformRequestOut;async transformResponseOut(e,n){try{return await Qk(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var H1="http://127.0.0.1:3457",nl=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||H1;r?.req?.body&&(r.req.body.stream=!0);let s=Qt(r,e);return{body:{...e,messages:Je(e.messages),tools:Ve(e.tools),stream:!0},config:{url:`${o}/v1/chat/completions`,headers:{"Content-Type":"application/json",...s?{"x-ccr-session-id":s}:{}}}}}async transformResponseOut(e){return(e.headers.get("Content-Type")||"").includes("text/event-stream")||!e.body,e}};var ol=require("crypto");var W1="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Zk=3,rl=class{name="opencode-headers";sessionCache=new Map;MAX_SESSIONS=100;lastTimestamp=0;counter=0;async transformRequestIn(e,n,r){let o=r?.req?.sessionId||this.fingerprintConversation(e,r),s=e.body||e,a=e.config||{},c=await this.sendWithSessionRetry(s,a,n,r,o);return{body:s,config:{...a,url:n?.baseUrl||n?.api_base_url,__providerResponse:c}}}async sendWithSessionRetry(e,n,r,o,s){let a=r?.baseUrl||r?.api_base_url,c=o?.req?.server?.configService?.getHttpsProxy?.(),l=o?.req?.log??o?.req?.server?.log,f=e?.model;for(let d=0;d<Zk;d++){let h=this.buildHeaders(n,r,s),m=await Eo(a,e,{httpsProxy:c,...n,headers:h,signal:o?.signal??n?.signal},o,l);if(m.ok)return m;let S=await m.text();if(!(d===Zk-1)&&this.isZenRoutingFailure(m.status,S)){this.invalidateSession(s),l?.warn?.({provider:r?.name,model:f,status:m.status,attempt:d+1},"opencode: Zen provider-routing failure \u2014 re-rolling session and retrying");continue}let w=_t(S)||S.slice(0,240);throw $e(`Error from provider(${r?.name},${f}: ${m.status}): ${w}`,m.status,"provider_response_error","api_error",this.retryAfterHeaders(m))}throw $e(`Error from provider(${r?.name},${f}): Zen provider-routing retries exhausted`,503,"provider_response_error")}buildHeaders(e,n,r){let o=this.getOrCreateSessionId(r),s=this.generateId("msg");return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":o,"x-opencode-request":s,"x-opencode-client":"cli","user-agent":"opencode/1.18.4",authorization:void 0}}isZenRoutingFailure(e,n){if(e!==401&&e!==400)return!1;let r;try{r=JSON.parse(n)}catch{return!1}let o=String(r?.error?.message||"");return!!(e===401&&r?.error?.type==="ModelError"&&/no provider available/i.test(o)||e===400&&/upstream request failed/i.test(o))}retryAfterHeaders(e){let n=e.headers.get("retry-after");return n?{"Retry-After":n}:void 0}fingerprintConversation(e,n){let r=e.body||e,o=r.model||"",s=r.messages||[],a=JSON.stringify(s.slice(0,3)),c=n?.req?.headers?.["x-forwarded-for"]||n?.req?.ip||"",l=n?.req?.headers?.["user-agent"]||"";return(0,ol.createHash)("sha256").update(`${o}|${c}|${l}|${a}`).digest("hex").slice(0,32)}getOrCreateSessionId(e){let n=this.sessionCache.get(e);if(n)return n;if(this.sessionCache.size>=this.MAX_SESSIONS){let o=this.sessionCache.keys().next().value;o!==void 0&&this.sessionCache.delete(o)}let r=this.generateId("ses");return this.sessionCache.set(e,r),r}invalidateSession(e){this.sessionCache.delete(e)}generateId(e){let n=Date.now();n!==this.lastTimestamp&&(this.lastTimestamp=n,this.counter=0),this.counter++;let r=BigInt(n)*BigInt(4096)+BigInt(this.counter),o=Buffer.alloc(6);for(let c=0;c<6;c++)o[c]=Number(r>>BigInt(40-8*c)&BigInt(255));let s=(0,ol.randomBytes)(14),a="";for(let c=0;c<14;c++)a+=W1[s[c]%62];return`${e}_${o.toString("hex")}${a}`}};var Yn=require("fs"),ig=require("path"),ag=require("os"),sg=(0,ig.join)((0,ag.homedir)(),".claude-code-router","claude_auth.json"),eS={client_id:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorization_endpoint:"https://claude.ai/oauth/authorize",token_endpoint:"https://platform.claude.com/v1/oauth/token",scope:"user:profile user:inference user:sessions:claude_code user:mcp_servers"};function G1(){try{if(!(0,Yn.existsSync)(sg))return null;let t=(0,Yn.readFileSync)(sg,"utf-8"),e=JSON.parse(t);return e.access_token?e:null}catch{return null}}function J1(t){let e=(0,ig.join)((0,ag.homedir)(),".claude-code-router");(0,Yn.existsSync)(e)||(0,Yn.mkdirSync)(e,{recursive:!0}),(0,Yn.writeFileSync)(sg,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function V1(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function K1(t){let e=await fetch(eS.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:eS.client_id,refresh_token:t})});if(!e.ok){let r=await e.text();throw new Error(`Token refresh failed (${e.status}): ${r}`)}let n=await e.json();return{access_token:n.access_token,refresh_token:n.refresh_token,id_token:n.id_token,token_type:n.token_type||"Bearer",scope:n.scope,expires_at:n.expires_at||Date.now()/1e3+(n.expires_in||3600),last_refresh:Date.now()/1e3}}async function tS(){let t=G1();if(!t)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(V1(t)){if(!t.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");t=await K1(t.refresh_token),J1(t)}return t}var nS="oauth-2025-04-20";function Y1(...t){let e=new Set,n=[];for(let r of t)if(r)for(let o of r.split(",")){let s=o.trim();if(!s)continue;let a=s.toLowerCase();e.has(a)||(e.add(a),n.push(s))}return n.join(",")}function sl(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n)continue;if(o==null)return;if(Array.isArray(o)){let a=o.filter(c=>c!=null&&String(c).length>0);return a.length?a.map(String).join(", "):void 0}let s=String(o);return s.length?s:void 0}}function X1(t){return t.clientBeta?.trim()?Y1(t.clientBeta,nS):nS}var il=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await tS(),s=n?.api_base_url??n?.baseUrl??"https://api.anthropic.com",a=s.endsWith("/v1/messages")?s:`${s.replace(/\/$/,"")}/v1/messages`,c=new URL(a);c.searchParams.set("beta","true");let l=vo.buildAnthropicBody(e,this.logger),f=r?.req?.headers||{},d=sl(f,"user-agent"),h=d?.startsWith("claude-cli/")??!1,m=h?sl(f,"anthropic-beta"):void 0,S=X1({clientBeta:m}),y={Authorization:`Bearer ${o.access_token}`,"Content-Type":"application/json","anthropic-version":h&&sl(f,"anthropic-version")||"2023-06-01","anthropic-beta":S};if(h)for(let w of["user-agent","x-app","x-claude-code-session-id","anthropic-dangerous-direct-browser-access","x-anthropic-billing-header","x-client-request-id","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout"]){let b=sl(f,w);b&&(y[w]=b)}else d&&(y["User-Agent"]=d);return{body:l,config:{url:c.toString(),headers:y}}}async transformResponseOut(e){return ju(e,this.name,this.logger)}};var DS=require("@cursor/sdk");var Q1=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function rS(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!Q1.test(e)&&!e.includes("$CURSOR_API_KEY")&&!e.includes("${"))return e;let n=process.env.CURSOR_API_KEY?.trim();if(n)return n;throw Object.assign(new Error("Cursor API key not found. Set Providers[].api_key to a crsr_ key, or export CURSOR_API_KEY."),{statusCode:401,code:"provider_response_error",type:"api_error"})}var oS=require("crypto"),sS=require("os"),cg=require("path"),ug="cursor-sdk",al="bridge",Z1=(0,cg.join)((0,sS.homedir)(),".claude-code-router"),cl=(0,cg.join)(Z1,"cursor-sdk-workspaces"),iS=900*1e3,lg=32,aS=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],Ri="custom-user-tools";function cS(t){return(0,oS.createHash)("sha256").update(t.filter(Boolean).join(`
295
- `)).digest("hex").slice(0,32)}function ls(t){if(typeof t=="string")return t;if(t==null)return"";if(typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function uS(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function lS(t,e){let n=Math.floor(Date.now()/1e3),r=`chatcmpl-cursor-${Date.now()}`,o=()=>({id:r,object:"chat.completion.chunk",created:n,model:t});return{setId(s){s&&(r=s)},content(s){return{...o(),choices:[{index:0,delta:{role:"assistant",content:s},finish_reason:null}]}},thinking(s){return{...o(),choices:[{index:0,delta:{thinking:{content:ls(s)}},finish_reason:null}]}},thinkingSignature(s=`ccr_cursor_${Date.now()}`){return{...o(),choices:[{index:0,delta:{thinking:{signature:s}},finish_reason:null}]}},toolCall(s,a=0){return{...o(),choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:a,id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}]},finish_reason:null}]}},finish(s,a){let c=Number(a?.prompt_tokens)||0,l=Number(a?.completion_tokens)||0,f=Number(a?.total_tokens)||c+l;return{...o(),choices:[{index:0,delta:{},finish_reason:s}],usage:{prompt_tokens:c,completion_tokens:l,total_tokens:f,prompt_tokens_details:{cached_tokens:Number(a?.prompt_tokens_details?.cached_tokens)||0}}}},encode(s){return Be(JSON.stringify(s),e)},encodeDone(){return Be("[DONE]",e)}}}function dS(t,e){let n="",r="",o="",s=[],a="stop",c=null,l=`chatcmpl-cursor-${Date.now()}`,f=Math.floor(Date.now()/1e3);for(let h of e){typeof h.id=="string"&&(l=h.id);let m=h.choices?.[0];if(!m)continue;m.finish_reason&&(a=m.finish_reason);let S=m.delta||{};if(typeof S.content=="string"&&(n+=S.content),S.thinking?.content&&(r+=ls(S.thinking.content)),typeof S.thinking?.signature=="string"&&S.thinking.signature&&(o=S.thinking.signature),Array.isArray(S.tool_calls))for(let y of S.tool_calls){let w=y.index??s.length;s[w]||(s[w]={id:y.id,type:"function",function:{name:y.function?.name||"",arguments:""}}),y.id&&(s[w].id=y.id),y.function?.name&&(s[w].function.name=y.function.name),typeof y.function?.arguments=="string"&&(s[w].function.arguments+=y.function.arguments)}h.usage&&(c=h.usage)}let d={role:"assistant",content:n||null};return r&&(d.thinking={content:r,signature:o||`ccr_cursor_${f}`}),s.length&&(d.tool_calls=s.filter(Boolean),a="tool_calls"),{id:l,object:"chat.completion",created:f,model:t,choices:[{index:0,message:d,finish_reason:a}],usage:c}}function Di(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):"").filter(Boolean).join(`
296
- `):String(t)}function eF(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(!n||typeof n!="object")&&n.type==="image_url"&&n.image_url?.url){let r=String(n.image_url.url),o=r.match(/^data:([^;]+);base64,(.+)$/);o?e.push({data:o[2],mimeType:o[1]}):e.push({url:r})}return e}function tF(t){return!Array.isArray(t.tools)||t.tools.length===0?"(no host tools advertised on this request)":t.tools.map(e=>{let n=e.function?.name||"unknown",r=e.function?.description||"";return`- ${n}: ${r}`}).join(`
297
- `)}function nF(t,e){return["You are running inside the Claude Code Router Cursor SDK bridge.","Claude Code (the host) owns filesystem, shell, and project tools.","Cursor built-in tools are denied in this workspace \u2014 do not call them.",`Host tools are exposed via MCP server "${Ri}" using bare tool names.`,`Isolated agent cwd (do not treat as the user project): ${e}`,"Pass absolute paths into host tools when referring to the user's real project files.","A progress update such as 'Checking...', 'Inspecting...', or 'Let me look...' is not a final answer.","After progress narration, call a host tool in the same turn; if no tool is needed, provide the complete user-facing answer before finishing.","Never end a turn with progress narration alone.","Available host tools:",tF(t)].join(`
298
- `)}var rF=[/^(?:checking|inspecting|reviewing|examining|investigating|verifying|reading|searching)\s+(?:the|this|that|these|those|your|our|which|whether|for|how|why|what|where)\b/i,/^looking\s+(?:at|into|for|through|up)\b/i,/^(?:i(?:'ll| will)|let me)\s+(?:check|inspect|review|examine|investigate|verify|read|search|look)\b/i];function oF(t){let e=String(t||"").trim();if(!e||e.length>240||/\n\s*\n/.test(e))return!1;let n=e.replace(/\s+/g," ");return(n.match(/[.!?](?:\s|$)/g)?.length||0)>1?!1:rF.some(o=>o.test(n))}function fS(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&oF(t.assistantText)}function hS(){return{text:["Continue the same turn now.","Your previous assistant message was only progress narration and ended without a host tool call or a complete answer.","Do not repeat the progress update.","If evidence is still needed, call an available host tool immediately; otherwise provide the complete user-facing answer now.","Do not finish until the requested work or answer is complete."].join(" ")}}function pS(t,e){let n=t.messages||[],r=[];e.mode==="bridge"?(r.push(nF(t,e.workspaceDir)),r.push("")):e.mode==="plan"&&(r.push("You are a planning/chat assistant. Respond with text and reasoning only. Do not execute tools."),r.push(""));let o=n.filter(f=>f.role==="system");for(let f of o){let d=Di(f.content);d&&r.push(`[system]
299
- ${d}`)}let s=n.filter(f=>f.role!=="system"),a=e.followUpOnly?s.slice(-Math.max(1,sF(s)+1)):s,c=[];for(let f of a){if(f.role==="assistant"){let d=Di(f.content);if(d&&r.push(`[assistant]
300
- ${d}`),Array.isArray(f.tool_calls)&&f.tool_calls.length)for(let h of f.tool_calls)r.push(`[assistant tool_call id=${h.id} name=${h.function.name}]
301
- ${h.function.arguments||"{}"}`);continue}if(f.role==="tool"){r.push(`[tool_result id=${f.tool_call_id||"unknown"}]
302
- ${Di(f.content)}`);continue}if(f.role==="user"){let d=Di(f.content);c=[...c,...eF(f.content)],d&&r.push(`[user]
303
- ${d}`)}}let l=r.join(`
335
+ ${n.content}`:o:Array.isArray(n.content)?n.content.unshift({type:"text",text:o}):n.content=o)}function JM(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function VM(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function rA(t,e){let n=r=>{let o=JM(r);return e?.set(o,r),o};if(Array.isArray(t.tools))for(let r of t.tools)r?.function?.name&&(r.function.name=n(r.function.name));if(Array.isArray(t.messages))for(let r of t.messages)for(let o of r.tool_calls??[])o?.function?.name&&(o.function.name=n(o.function.name));typeof t.tool_choice=="string"?["auto","none","required"].includes(t.tool_choice)||(t.tool_choice=n(t.tool_choice)):t.tool_choice?.type==="function"&&t.tool_choice.function?.name&&(t.tool_choice.function.name=n(t.tool_choice.function.name))}function Ug(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??VM(o))};for(let r of t?.choices??[]){for(let o of r?.message?.tool_calls??[])n(o);for(let o of r?.delta?.tool_calls??[])n(o)}}var oA="oauth-2025-04-20";function KM(...t){let e=new Set,n=[];for(let r of t)if(r)for(let o of r.split(",")){let s=o.trim();if(!s)continue;let i=s.toLowerCase();e.has(i)||(e.add(i),n.push(s))}return n.join(",")}function jg(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n)continue;if(o==null)return;if(Array.isArray(o)){let i=o.filter(c=>c!=null&&String(c).length>0);return i.length?i.map(String).join(", "):void 0}let s=String(o);return s.length?s:void 0}}function YM(t){return t?.startsWith("claude-cli/")??!1}function XM(t){return t.clientBeta?.trim()?KM(t.clientBeta,oA):oA}function QM(t,e){let n=e?.envBeta??process.env.ANTHROPIC_BETA_FLAGS;if(n?.trim())return n.trim();let{requestedOneMillion:r}=ki(t),o=_p(t),s=c=>bp(o,c),i=["claude-code-20250219","oauth-2025-04-20"];return r&&i.push("context-1m-2025-08-07"),xC(o)&&i.push("interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13"),s("context_management")&&i.push("context-management-2025-06-27"),i.push("prompt-caching-scope-2026-01-05"),s("mid_conv_system")&&i.push("mid-conversation-system-2026-04-07"),i.push("advanced-tool-use-2025-11-20"),s("effort")&&i.push("effort-2025-11-24"),s("fast_mode")&&i.push("fallback-credit-2026-06-01"),i.join(",")}function ZM(t,e){let n=o=>bp(e,o),r=o=>{o&&typeof o=="object"&&!n("effort")&&delete o.effort};r(t.thinking),r(t.output_config),t.thinking&&typeof t.thinking=="object"&&t.thinking.type!=="disabled"&&(t.thinking=n("adaptive_thinking")?{type:"adaptive",display:"omitted"}:{type:"enabled",...t.thinking.budget_tokens!==void 0?{budget_tokens:t.thinking.budget_tokens}:{},display:"omitted"}),e&&typeof t.max_tokens=="number"&&(t.max_tokens=Math.min(t.max_tokens,e.maxOutputTokens.upper))}var eB="0.94.0";function tB(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function nB(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Lg;function sA(){return Lg||(Lg=(0,qg.randomUUID)()),Lg}function rB(){return{"User-Agent":process.env.ANTHROPIC_USER_AGENT||`claude-cli/${Mg} (external, ${Bg})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":sA(),"x-client-request-id":(0,qg.randomUUID)(),"x-stainless-arch":tB(),"x-stainless-lang":"js","x-stainless-os":nB(),"x-stainless-package-version":eB,"x-stainless-retry-count":"0","x-stainless-runtime":"node","x-stainless-runtime-version":process.version,"x-stainless-timeout":"600"}}var ed=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await Xv(),s=r?.req?.headers||{},i=jg(s,"user-agent"),c=YM(i);if(!c){let p=Zv(e);eA(p,e.messages),tA(p),nA(p,e.messages);let h=new Map;rA(e,h),r&&(r.claudeAuthToolNameMap=h,r.protocolContext&&(r.protocolContext.claudeAuthToolNameMap=h))}let u=c?jg(s,"anthropic-beta"):void 0,f=c?XM({clientBeta:u}):QM(e.model),d={Authorization:`Bearer ${o.access_token}`,"anthropic-beta":f};if(c)for(let p of["user-agent","x-app","x-claude-code-session-id","anthropic-dangerous-direct-browser-access","x-client-request-id","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout"]){let h=jg(s,p);h&&(d[p]=h)}else{Object.assign(d,rB());let p=_p(e.model);r&&(r.claudeAuthPostBuildHook=h=>{ZM(h,p);let _=Qv();h.metadata={...h.metadata||{},user_id:JSON.stringify({device_id:_,account_uuid:"",session_id:sA()})}})}return{body:e,config:{headers:d,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async transformResponseOut(e,n){let r=n?.claudeAuthToolNameMap??n?.protocolContext?.claudeAuthToolNameMap;if(r?.size&&e.ok){let s=e.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await e.json();return Ug(i,r),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:e.headers})}if(s.includes("text/event-stream")&&e.body)return Ie(e,(i,c)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){c.controller.enqueue(c.encoder.encode(i+`
336
+ `));return}try{let u=JSON.parse(i.slice(6));Ug(u,r),c.controller.enqueue(c.encoder.encode(`data: ${JSON.stringify(u)}
304
337
 
305
- `).trim()||"Continue.";return c.length?{text:l,images:c}:{text:l}}function sF(t){let e=0;for(let n=t.length-1;n>=0;n--){if(t[n].role==="tool"){e++;continue}break}return e}function gS(t){let e=[],n=t.messages||[];for(let r=n.length-1;r>=0;r--){let o=n[r];if(o.role!=="tool")break;e.unshift({toolCallId:String(o.tool_call_id||""),content:Di(o.content)})}return e}var ul=require("crypto"),fs=require("fs"),_S=require("path"),fg=require("@cursor/sdk");var Tr=require("fs"),ds=require("path");var iF=`#!/usr/bin/env node
338
+ `))}catch{c.controller.enqueue(c.encoder.encode(i+`
339
+ `))}},{logger:this.logger})}let o=e.headers.get("anthropic-ratelimit-unified-overage-in-use");return o&&this.logger?.debug?.({overageInUse:o,overageStatus:e.headers.get("anthropic-ratelimit-unified-overage-status")},"claude-auth: subscription overage in use for this request"),e}async recoverUnauthorizedAuth(e){let n=Pg();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await Fg(n.refresh_token);return Ig(r),{Authorization:`Bearer ${r.access_token}`}}};var QA=require("@cursor/sdk");var oB=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function iA(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!oB.test(e)&&!e.includes("$CURSOR_API_KEY")&&!e.includes("${"))return e;let n=process.env.CURSOR_API_KEY?.trim();if(n)return n;throw Object.assign(new Error("Cursor API key not found. Set Providers[].api_key to a crsr_ key, or export CURSOR_API_KEY."),{statusCode:401,code:"provider_response_error",type:"api_error"})}var aA=require("crypto"),cA=require("os"),bo=require("path"),$g="cursor-sdk",td="bridge",sB=(0,bo.join)((0,cA.homedir)(),".claude-code-router"),Tn=(0,bo.join)(sB,"cursor-sdk-workspaces"),uA=900*1e3,zg=32,lA=1440*60*1e3,dA=3600*1e3,iB=/^[0-9a-f]{32}$/;function Hg(t,e=Tn){let n=t.replace(/[\\/]+$/,"");return(0,bo.dirname)(n)!==e.replace(/[\\/]+$/,"")?!1:iB.test((0,bo.basename)(n))}var fA=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],Yi="custom-user-tools";function an(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):"").filter(Boolean).join(`
340
+ `):String(t)}function Ds(t){return(0,aA.createHash)("sha256").update(t.filter(Boolean).join(`
341
+ `)).digest("hex").slice(0,32)}function Os(t){if(typeof t=="string")return t;if(t==null)return"";if(typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Wg(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function pA(t,e){let n=Math.floor(Date.now()/1e3),r=`chatcmpl-cursor-${Date.now()}`,o=()=>({id:r,object:"chat.completion.chunk",created:n,model:t});return{setId(s){s&&(r=s)},content(s){return{...o(),choices:[{index:0,delta:{role:"assistant",content:s},finish_reason:null}]}},thinking(s){return{...o(),choices:[{index:0,delta:{thinking:{content:Os(s)}},finish_reason:null}]}},thinkingSignature(s=`ccr_cursor_${Date.now()}`){return{...o(),choices:[{index:0,delta:{thinking:{signature:s}},finish_reason:null}]}},toolCall(s,i=0){return{...o(),choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:i,id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}]},finish_reason:null}]}},finish(s,i){let c=Number(i?.prompt_tokens)||0,u=Number(i?.completion_tokens)||0,f=Number(i?.total_tokens)||c+u;return{...o(),choices:[{index:0,delta:{},finish_reason:s}],usage:{prompt_tokens:c,completion_tokens:u,total_tokens:f,prompt_tokens_details:{cached_tokens:Number(i?.prompt_tokens_details?.cached_tokens)||0}}}},encode(s){return Ee(JSON.stringify(s),e)},encodeDone(){return Ee("[DONE]",e)}}}function Gg(t,e){let n="",r="",o="",s=[],i="stop",c=null,u=`chatcmpl-cursor-${Date.now()}`,f=Math.floor(Date.now()/1e3);for(let p of e){typeof p.id=="string"&&(u=p.id);let h=p.choices?.[0];if(!h)continue;h.finish_reason&&(i=h.finish_reason);let _=h.delta||{};if(typeof _.content=="string"&&(n+=_.content),_.thinking?.content&&(r+=Os(_.thinking.content)),typeof _.thinking?.signature=="string"&&_.thinking.signature&&(o=_.thinking.signature),Array.isArray(_.tool_calls))for(let b of _.tool_calls){let y=b.index??s.length;s[y]||(s[y]={id:b.id,type:"function",function:{name:b.function?.name||"",arguments:""}}),b.id&&(s[y].id=b.id),b.function?.name&&(s[y].function.name=b.function.name),typeof b.function?.arguments=="string"&&(s[y].function.arguments+=b.function.arguments)}p.usage&&(c=p.usage)}let d={role:"assistant",content:n||null};return r&&(d.thinking={content:r,signature:o||`ccr_cursor_${f}`}),s.length&&(d.tool_calls=s.filter(Boolean),i="tool_calls"),{id:u,object:"chat.completion",created:f,model:t,choices:[{index:0,message:d,finish_reason:i}],usage:c}}var Br={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},hA=/<(env|environment|system-info|system_info)>([\s\S]*?)<\/\1>/gi,aB=/^\s*[-*]?\s*([A-Za-z][A-Za-z0-9 _/'-]{2,48}?)\s*:\s*(\S.*?)\s*$/,cB=/working director|workspace root|project root|platform|os version|operating system|git repo/i,mA=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],gA=[/^additional working director/i,/^additional director/i,/^extra working director/i],yA=[/^platform$/i,/^operating system$/i,/^os$/i],_A=[/^os version$/i,/^system version$/i],uB=[...mA,...gA,...yA,..._A],lB=2e5,dB=16,fB=400;function pB(t){let e=[],n=lB,r=!1;for(let o of t.messages||[]){if(o.role!=="system"&&o.role!=="user")continue;if(o.role==="user"&&r)break;o.role==="user"&&(r=!0);let s=an(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
342
+ `)}function hB(t){let e=[],n=new Set,r=i=>{if(e.length>=dB)return;let c=i.match(aB);if(!c)return;let u=c[1].trim(),f=c[2].trim().slice(0,fB);if(!u||!f)return;let d=u.toLowerCase();n.has(d)||(n.add(d),e.push({key:u,value:f}))},o=!1;hA.lastIndex=0;let s;for(;s=hA.exec(t);){o=!0;for(let i of s[2].split(/\r?\n/))r(i)}if(!o)for(let i of t.split(/\r?\n/))cB.test(i)&&r(i);return e}function nd(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function bA(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function mB(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>bA(e)):[]}function Xi(t){let e=hB(pB(t)),n=nd(e,mA),r=n&&bA(n)?n:void 0,o=mB(nd(e,gA)).filter(u=>u!==r),s=nd(e,yA),i=nd(e,_A),c=!!(r||s||i||e.length);return c?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:c,fingerprint:Ds([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:Br}function CA(t){let e=[];t.projectRoot&&e.push(`- Project root: ${t.projectRoot}`);for(let n of t.additionalRoots)e.push(`- Additional in-scope root: ${n}`);t.platform&&e.push(`- Platform: ${t.platform}`),t.osVersion&&e.push(`- OS version: ${t.osVersion}`);for(let n of t.facts)uB.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function Co(t){return t.projectRoot?`Every path you pass to a host tool must be an absolute path on the host, normally under ${t.projectRoot}.`:"Every path you pass to a host tool must be an absolute host path taken from this conversation \u2014 never invent one and never derive one from your local filesystem."}function gB(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(!n||typeof n!="object")&&n.type==="image_url"&&n.image_url?.url){let r=String(n.image_url.url),o=r.match(/^data:([^;]+);base64,(.+)$/);o?e.push({data:o[2],mimeType:o[1]}):e.push({url:r})}return e}function yB(t){return!Array.isArray(t.tools)||t.tools.length===0?"(no host tools advertised on this request)":t.tools.map(e=>{let n=e.function?.name||"unknown",r=e.function?.description||"";return`- ${n}: ${r}`}).join(`
343
+ `)}function kA(t,e){let n=["You are a remote reasoning agent driving Claude Code (the host).","Tools do not run where you are running: every tool call is executed by the host on the user's machine, and only the result is sent back to you.",`Your local environment is disposable scratch space: ${t}`,"It is empty and contains none of the user's files. Never read, list, search, or verify paths against it, and never prefix a host tool path with it.","Your own cwd, OS, and workspace root describe that scratch container only \u2014 they say nothing about the user's project, so never reason from them or report them to the user."],r=CA(e);return r.length&&(n.push("The user's project lives on the host machine, which is where every tool call lands:"),n.push(...r)),n.push(Co(e)),n.push(`Host tools are exposed via MCP server "${Yi}" using bare tool names.`,"Cursor built-in tools are denied here. That denial only routes tool use through the host \u2014 it is not a restriction on the user's project, which stays fully reachable through the host tools."),n}function _B(t,e,n=Xi(t)){return[...kA(e,n),"A progress update such as 'Checking...', 'Inspecting...', or 'Let me look...' is not a final answer.","After progress narration, call a host tool in the same turn; if no tool is needed, provide the complete user-facing answer before finishing.","Never end a turn with progress narration alone.","Available host tools:",yB(t)].join(`
344
+ `)}function bB(t,e){return["[bridge reminder]",`Tools run on the host machine, not here. ${t} is empty scratch space \u2014 never treat it as the project, and never build a tool path from it.`,Co(e)].join(`
345
+ `)}function SA(t,e){return["# Agent rules","",...kA(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
346
+ `)}function EA(t){return["Your local filesystem is empty scratch space on a different machine from the user's project.","The project is reachable only through the host tools, and it is not restricted.",Co(t)].join(" ")}var CB=[/^(?:checking|inspecting|reviewing|examining|investigating|verifying|reading|searching)\s+(?:the|this|that|these|those|your|our|which|whether|for|how|why|what|where)\b/i,/^looking\s+(?:at|into|for|through|up)\b/i,/^(?:i(?:'ll| will)|let me)\s+(?:check|inspect|review|examine|investigate|verify|read|search|look)\b/i];function wB(t){let e=String(t||"").trim();if(!e||e.length>240||/\n\s*\n/.test(e))return!1;let n=e.replace(/\s+/g," ");return(n.match(/[.!?](?:\s|$)/g)?.length||0)>1?!1:CB.some(o=>o.test(n))}function vA(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&wB(t.assistantText)}function AA(t){let e=["Continue the same turn now.","Your previous assistant message was only progress narration and ended without a host tool call or a complete answer.","Do not repeat the progress update.","If evidence is still needed, call an available host tool immediately; otherwise provide the complete user-facing answer now.","Do not finish until the requested work or answer is complete."];return t?.known&&e.push(Co(t)),{text:e.join(" ")}}function wA(t){let e=t.trim();return fp.some(n=>e===n)}function kB(t){if(!Array.isArray(t)){let e=an(t);return e.trim().length>0&&!wA(e)}return t.some(e=>{if(!e||typeof e!="object")return!1;if("text"in e){let n=String(e.text||"");return n.trim().length>0&&!wA(n)}return!0})}function TA(t,e){let n=t.messages||[],r=[],o=e.hostEnv||Xi(t);e.mode==="bridge"?(r.push(_B(t,e.workspaceDir,o)),r.push("")):e.mode==="plan"&&(r.push("You are a planning/chat assistant. Respond with text and reasoning only. Do not execute tools."),r.push(""));let s=n.filter(d=>d.role==="system");for(let d of s){let p=an(d.content);p&&r.push(`[system]
347
+ ${p}`)}let i=n.filter(d=>d.role!=="system"),c=e.followUpOnly?i.slice(-Math.max(1,SB(i,e.turnIntent)+1)):i,u=[];for(let d of c){if(d.role==="assistant"){let p=an(d.content);if(p&&r.push(`[assistant]
348
+ ${p}`),Array.isArray(d.tool_calls)&&d.tool_calls.length)for(let h of d.tool_calls)r.push(`[assistant tool_call id=${h.id} name=${h.function.name}]
349
+ ${h.function.arguments||"{}"}`);continue}if(d.role==="tool"){r.push(`[tool_result id=${d.tool_call_id||"unknown"}]
350
+ ${an(d.content)}`);continue}if(d.role==="user"){let p=an(d.content);u=[...u,...gB(d.content)],p&&r.push(`[user]
351
+ ${p}`)}}e.mode==="bridge"&&r.push(bB(e.workspaceDir,o));let f=r.join(`
352
+
353
+ `).trim()||"Continue.";return u.length?{text:f,images:u}:{text:f}}function SB(t,e){let n=t.length-1,r=0;e?.interruption==="synthetic_client_interrupt"&&e.steering==="none"&&t[n]?.role==="user"&&(r=1,n-=1);let o=0;for(;n>=0;n--){if(t[n].role==="tool"){o+=1;continue}break}return o>0?r+o:0}function RA(t,e){if(e)return{toolResults:e.trailingToolResults.map(i=>({toolCallId:i.toolCallId,content:i.content,isError:i.isError})),hasTrailingUserInput:e.steering==="meaningful"};let n=[],r=t.messages||[],o=r.length-1,s=!1;for(;o>=0&&r[o].role==="user";)s=s||kB(r[o].content),o-=1;for(;o>=0;o--){let i=r[o];if(i.role!=="tool")break;n.unshift({toolCallId:String(i.tool_call_id||""),content:an(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}var rd=require("crypto"),Gt=require("fs"),Yg=require("path"),Vg=require("@cursor/sdk");var Ur=require("fs"),Ps=require("path");function EB(t){return`#!/usr/bin/env node
306
354
  const chunks = [];
307
355
  process.stdin.on("data", (c) => chunks.push(c));
308
356
  process.stdin.on("end", () => {
@@ -326,15 +374,12 @@ process.stdin.on("end", () => {
326
374
  );
327
375
 
328
376
  // Always allow the SDK synthetic MCP host tools Claude Code bridges through.
329
- if (server.includes(${JSON.stringify(Ri)})) {
377
+ if (server.includes(${JSON.stringify(Yi)})) {
330
378
  process.stdout.write(JSON.stringify({ permission: "allow" }));
331
379
  return;
332
380
  }
333
381
 
334
- const denyMessage =
335
- "CCR Cursor SDK bridge: do not use Cursor built-in tools. " +
336
- "Call host tools via MCP server '${Ri}' " +
337
- "using the bare Claude Code tool names (Read, Bash, Edit, \u2026).";
382
+ const denyMessage = ${JSON.stringify(t)};
338
383
 
339
384
  process.stdout.write(
340
385
  JSON.stringify({
@@ -344,17 +389,28 @@ process.stdin.on("end", () => {
344
389
  })
345
390
  );
346
391
  });
347
- `;function dg(t){let e=(0,ds.join)(t,".cursor"),n=(0,ds.join)(e,"hooks");(0,Tr.mkdirSync)(n,{recursive:!0});let r=(0,ds.join)(n,"deny-builtin.cjs");(0,Tr.writeFileSync)(r,iF,{encoding:"utf-8",mode:448});try{(0,Tr.chmodSync)(r,448)}catch{}let o=aS.join("|"),s=`node "${r}"`,a={version:1,hooks:{preToolUse:[{matcher:o,command:s}],beforeShellExecution:[{command:s}],beforeReadFile:[{command:s}],beforeMCPExecution:[{command:s}]}};(0,Tr.writeFileSync)((0,ds.join)(e,"hooks.json"),JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),(0,Tr.writeFileSync)((0,ds.join)(t,"AGENTS.md"),"",{encoding:"utf-8",mode:384})}function hg(t,e){t.poisoned=!0,t.poisonReason=e}async function xi(t,e={}){let n={skipped:!1,hadRun:!!t.run,hadIterator:!!t.streamIterator,failed:!1,timedOut:!1};if(e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken)return{...n,skipped:!0};let r=t.run,o=t.streamIterator;if(t.run=void 0,t.streamIterator=void 0,t.activeRunToken=void 0,t.pendingEmit=[],t.pendingSdkMessages=[],t.notifyEmit(),t.notifySdkMessage?.(),e.rejectParked&&t.parked.length){let s=e.reason||"cursor-sdk run cancelled";for(let a of t.parked.splice(0,t.parked.length))try{a.reject(new Error(s))}catch{}}if(o&&typeof o.return=="function")try{await ll(o.return(void 0),e.timeoutMs??2e3,"cursor-sdk stream iterator return timed out")}catch(s){n.failed=!0,n.timedOut=n.timedOut||/timed out/i.test(String(s?.message||s))}if(!r||r.status!=="running")return n.failed&&e.poisonOnFailure&&hg(t,e.reason||"cursor-sdk run cancellation did not complete"),n;try{await ll(r.cancel(),e.timeoutMs??2e3,"cursor-sdk run cancel timed out")}catch(s){n.failed=!0,n.timedOut=n.timedOut||/timed out/i.test(String(s?.message||s))}return n.failed&&e.poisonOnFailure&&hg(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function ll(t,e,n){let r;try{return await Promise.race([t,new Promise((o,s)=>{r=setTimeout(()=>s(new Error(n)),e)})])}finally{r&&clearTimeout(r)}}async function gg(t,e){let n=t.sendChain,r,o=new Promise(s=>{r=s});t.sendChain=n.then(()=>o).catch(()=>o),await n.catch(()=>{});try{return await e()}finally{r()}}function mS(t){if(t===!1)return!1;let e=process.env.CCR_CURSOR_SANDBOX?.trim().toLowerCase();return!(e==="0"||e==="false"||e==="off"||!(t===!0||e==="1"||e==="true"||e==="on")||(0,fs.existsSync)("/.dockerenv")||process.env.container==="docker")}function aF(t){(0,fs.existsSync)(cl)||(0,fs.mkdirSync)(cl,{recursive:!0});let e=(0,_S.join)(cl,t);return(0,fs.mkdirSync)(e,{recursive:!0}),dg(e),e}function bS(t){if(t.headerSession)return(0,ul.createHash)("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?(0,ul.createHash)("sha256").update(e[1]).digest("hex").slice(0,32):(0,ul.createHash)("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return cS([t.model||"",t.systemAndFirstUser||""])}function yS(t){return!!(t.streamIterator||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function dl(t){t.lastActiveAt=Date.now()}var pg=class{constructor(e){this.logger=e;this.cleanupTimer=setInterval(()=>this.evictIdle(),6e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}sessions=new Map;cleanupTimer;setLogger(e){this.logger=e}get(e){let n=this.sessions.get(e);if(n?.poisoned){this.invalidate(n,n.poisonReason||"cursor-sdk session poisoned");return}return n&&dl(n),n}async getOrCreate(e){let n=this.get(e.key);if(n)return n;this.evictIfNeeded();let r=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:aF(e.key);e.mode==="bridge"&&dg(r);let o=e.mode==="plan"?"plan":"agent",s=mS(e.sandboxEnabled),a=await fg.Agent.create({apiKey:e.apiKey,model:e.model,name:`ccr-${e.key.slice(0,8)}`,mode:o,local:{cwd:r,settingSources:[],sandboxOptions:{enabled:s},enableAgentRetries:!0}}),c=this.createSessionRecord({key:e.key,agent:a,mode:e.mode,workspaceDir:r});return this.sessions.set(e.key,c),this.logger?.info?.({sessionKey:e.key,agentId:a.agentId,mode:e.mode,sandboxEnabled:s},"cursor-sdk session created"),c}async resume(e){let n=mS(e.sandboxEnabled),r=await fg.Agent.resume(e.agentId,{apiKey:e.apiKey,model:e.model,local:{cwd:e.workspaceDir,settingSources:[],sandboxOptions:{enabled:n}}}),o=this.createSessionRecord({key:e.key,agent:r,mode:e.mode,workspaceDir:e.workspaceDir});return this.sessions.set(e.key,o),o}resolveParkedTools(e,n){let r=0,o=[];for(let s of n){let a=-1;if(s.toolCallId?a=e.parked.findIndex(l=>l.id===s.toolCallId):n.length===1&&e.parked.length===1&&(a=0),a===-1){o.push(s.toolCallId||"(empty)");continue}let[c]=e.parked.splice(a,1);c.resolve(s.content),r++}return o.length&&this.logger?.warn?.({unmatched:o,parkedRemaining:e.parked.map(s=>s.id),resolved:r},"cursor-sdk tool results did not match parked tools"),dl(e),r}async dispose(e){let n=this.sessions.get(e);if(n){this.sessions.delete(e),await xi(n,{rejectParked:!0,reason:"cursor-sdk session disposed"});try{n.agent.close()}catch{}}}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(r){if(hg(r,n),r.run=void 0,r.streamIterator=void 0,r.activeRunToken=void 0,r.pendingEmit=[],r.pendingSdkMessages=[],r.parked.length)for(let o of r.parked.splice(0,r.parked.length))try{o.reject(new Error(n))}catch{}r.notifyEmit(),r.notifySdkMessage(),this.sessions.get(r.key)===r&&this.sessions.delete(r.key);try{r.agent.close()}catch{}this.logger?.warn?.({sessionKey:r.key,agentId:r.agentId,reason:n},"cursor-sdk session invalidated")}}createSessionRecord(e){let n={key:e.key,agent:e.agent,agentId:e.agent.agentId,mode:e.mode,workspaceDir:e.workspaceDir,parked:[],pendingEmit:[],emitWaiters:[],pendingSdkMessages:[],sdkMessageWaiters:[],sendChain:Promise.resolve(),hasSentPrompt:!1,lastActiveAt:Date.now(),metrics:{customToolCalls:0,builtinToolCallsSeen:0},parkHostTool:({id:r,name:o,args:s})=>{let a,c,l=new Promise((d,h)=>{a=d,c=h}),f=n.activeRunToken;return n.parked.push({id:r,name:o,args:s,runToken:f,resolve:a,reject:c,promise:l}),n.pendingEmit.push({id:r,name:o,args:s,runToken:f}),n.notifyEmit(),l},notifyEmit:()=>{let r=n.emitWaiters.splice(0,n.emitWaiters.length);for(let o of r)o()},waitForEmit:()=>new Promise(r=>{if(n.pendingEmit.length){r();return}n.emitWaiters.push(r)}),enqueueSdkMessage:(r,o=n.activeRunToken)=>{n.pendingSdkMessages.push({message:r,runToken:o,source:"delta"}),n.notifySdkMessage()},notifySdkMessage:()=>{let r=n.sdkMessageWaiters.splice(0,n.sdkMessageWaiters.length);for(let o of r)o()},waitForSdkMessage:()=>new Promise(r=>{if(n.pendingSdkMessages.length){r();return}n.sdkMessageWaiters.push(r)})};return n}evictIfNeeded(){for(;this.sessions.size>=lg;){let e,n=1/0;for(let[r,o]of this.sessions)yS(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:lg},"cursor-sdk session capacity reached with all sessions in-flight; deferring eviction");break}this.dispose(e)}}evictIdle(){let e=Date.now();for(let[n,r]of this.sessions)yS(r)||e-r.lastActiveAt>iS&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n))}},An=new pg;var cF="Cursor SDK agent.send timed out";function mg(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=typeof e.message=="string"?e.message:String(t);return n==="AgentBusyError"||e.status===409||/already has active run|active run|agent busy/i.test(r)}function yg(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=typeof e.message=="string"?e.message:String(t);return n==="AgentNotFoundError"||n==="NetworkError"||e.status===503||e.status===504||/agent not found|request aborted (?:before|during) send|agent\.send timed out|network/i.test(r)}function uF(t){return{...t,local:{...t.local||{},force:!0}}}function lF(t){if(!t)return;let e;return{promise:new Promise((r,o)=>{if(t.aborted){o(new Error("cursor-sdk request aborted before send"));return}e=()=>o(new Error("cursor-sdk request aborted during send")),t.addEventListener("abort",e,{once:!0})}),cleanup:()=>{e&&t.removeEventListener("abort",e)}}}async function wS(t,e,n,r){let o,s;try{if(r?.aborted)throw new Error("cursor-sdk request aborted before send");return o=t.agent.send(e,n),s=lF(r),await ll(s?Promise.race([o,s.promise]):o,15e3,cF)}catch(a){throw o&&o.then(c=>{try{c.cancel()}catch{}}).catch(()=>{}),a}finally{s?.cleanup()}}async function _g(t,e,n,r={}){try{return await wS(t,e,n,r.abortSignal)}catch(o){if(r.abortSignal?.aborted||!mg(o))throw o;return r.logger?.warn?.({err:o,sessionKey:t.key,agentId:t.agentId},"cursor-sdk agent busy; retrying send with local.force"),wS(t,e,uF(n),r.abortSignal)}}var CS=require("crypto");function dF(t){if(!t)return{type:"object",properties:{}};if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object")return e}catch{return{type:"object",properties:{}}}return typeof t=="object"?t:{type:"object",properties:{}}}function kS(t,e){let n={};if(!Array.isArray(t.tools))return n;for(let r of t.tools){let o=r.function?.name;!o||typeof o!="string"||(n[o]={description:r.function.description||`Claude Code host tool: ${o}`,inputSchema:dF(r.function.parameters),async execute(s,a){let c=a.toolCallId||(0,CS.randomUUID)();return e.metrics.customToolCalls+=1,e.parkHostTool({id:c,name:o,args:s||{}})}})}return n}function AS(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function SS(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function ES(t){let e=[];t.system&&e.push(SS(t.system));for(let n of t.messages||[])e.push(SS(n.content)),n.thinking?.content&&e.push(String(n.thinking.content)),n.reasoning_content&&e.push(String(n.reasoning_content)),n.tool_calls?.length&&e.push(JSON.stringify(n.tool_calls));return t.tools?.length&&e.push(JSON.stringify(t.tools)),AS(e.join(`
348
- `).length)}function vS(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=AS(e),s=Math.min(r,Math.max(0,Math.trunc(n)||0));return{prompt_tokens:r,completion_tokens:o,total_tokens:r+o,prompt_tokens_details:{cached_tokens:s}}}function fl(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function TS(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=fl(t.prompt_tokens),s=fl(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let a=fl(e?.prompt_tokens),c=fl(e?.prompt_tokens_details?.cached_tokens),l=o-a,f=s-c,d=l>0&&f>0?f/l:s/o,h=Math.min(1,Math.max(0,d));return Math.min(r,Math.floor(r*h))}function RS(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,a=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:a}}}var fF=900*1e3,Oi=null;function hF(t){return`${t.length}:${t.slice(0,8)}:${t.slice(-4)}`}async function pF(t){let e=hF(t);if(Oi&&Oi.apiKeyFingerprint===e&&Date.now()-Oi.fetchedAt<fF)return Oi.models;let n=await DS.Cursor.models.list({apiKey:t})||[];return Oi={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function gF(t,e,n){let r=[];try{r=await pF(t)}catch{return{id:e}}let o=r.find(a=>a.id===e||a.displayName===e||Array.isArray(a.aliases)&&a.aliases.includes(e));if(!o)return{id:e};if(n&&Array.isArray(o.variants)&&o.variants.length){let a=o.variants.find(c=>c.params?.some(l=>/effort|reasoning/i.test(l.id)&&String(l.value).toLowerCase()===String(n).toLowerCase()))||o.variants.find(c=>(c.displayName||"").toLowerCase().includes(String(n).toLowerCase()));if(a)return{id:o.id,params:a.params}}let s=o.variants?.find(a=>a.isDefault)||o.variants?.[0];return s?.params?.length?{id:o.id,params:s.params}:{id:o.id}}function mF(t){let e=[];for(let n of t.messages||[])if((n.role==="system"||n.role==="user")&&(typeof n.content=="string"?e.push(n.content):Array.isArray(n.content)&&e.push(n.content.map(r=>typeof r=="string"?r:r?.text||"").join("")),n.role==="user"))break;return e.join(`
349
- `)}async function*yF(t,e,n,r){let o=t.streamIterator;if(!o){yield{kind:"end"};return}let s=o.next(),a=t.waitForEmit().then(()=>"emit"),c=t.waitForSdkMessage().then(()=>"sdk_message"),l=()=>{let f=t.pendingSdkMessages.findIndex(h=>h.runToken===n);if(f===-1)return;let[d]=t.pendingSdkMessages.splice(f,1);return d};for(;;){if(r?.aborted||t.activeRunToken!==n){yield{kind:"end"};return}let f=l();if(f){yield{kind:"sdk",message:f.message,source:f.source};continue}let d=await Promise.race([c.then(S=>({type:S})),s.then(S=>({type:"msg",r:S})),a.then(S=>({type:S}))]);if(d.type==="emit"){for(;t.pendingEmit.length&&t.pendingEmit[0]?.runToken===n;)yield{kind:"host_tool",tool:t.pendingEmit.shift()};a=t.waitForEmit().then(()=>"emit");continue}if(d.type==="sdk_message"){for(;;){let S=l();if(!S)break;yield{kind:"sdk",message:S.message,source:S.source}}c=t.waitForSdkMessage().then(()=>"sdk_message");continue}let{r:h}=d;if(h.done){yield{kind:"end"};return}let m=h.value;if(r?.aborted||t.activeRunToken!==n){yield{kind:"end"};return}m?.type==="tool_call"&&e==="bridge"&&(t.metrics.builtinToolCallsSeen+=1),yield{kind:"sdk",message:m,source:"stream"},s=o.next()}}function _F(t,e){if(!e||e.type!=="thinking-delta")return;let n=ls(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function xS(t,e,n,r={}){let o=r.logger||e?.logger;o&&An.setLogger(o);let s=r.cursorMode||al,a=t.stream===!0,c=t.model||"composer-2",l;try{l=rS(e)}catch(K){throw Object.assign(K instanceof Error?K:new Error(String(K)),{statusCode:K?.statusCode||401,code:"provider_response_error",type:"api_error"})}let f=n?.req?.headers?.["x-ccr-cursor-session"]||n?.req?.headers?.["X-Ccr-Cursor-Session"],d=bS({headerSession:typeof f=="string"?f:void 0,metadataUserId:t?.metadata?.user_id,model:c,systemAndFirstUser:mF(t)}),h=uS(t),m=await gF(l,c,h),S={key:d,apiKey:l,model:m,mode:s,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled},y=await An.getOrCreate(S),w=gS(t),b=y.parked.length>0;w.length&&b&&An.resolveParkedTools(y,w);let _=!y.streamIterator||!b,D=y.hasSentPrompt,k=y.activeRunToken,v=(K,se)=>{K.pendingSdkMessages=K.pendingSdkMessages.filter(ie=>ie.runToken!==se),K.notifySdkMessage()},x=(K,se)=>{let ie=s==="bridge"?kS(t,K):void 0;return{model:m,mode:s==="plan"?"plan":"agent",local:ie?{customTools:ie}:void 0,onDelta:({update:X})=>{let Z=_F(K,X);Z&&K.enqueueSdkMessage(Z,se)}}},R=K=>Object.assign(new Error(`Cursor SDK error: ${K?.message||K}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),j=(K,se)=>se.hasSentPrompt&&!r.abortSignal?.aborted&&(K?.retryFreshCursorSession===!0||mg(K)||yg(K)),W=async(K,se)=>{let ie;if(await gg(K,async()=>{if((K.run||K.streamIterator)&&(await xi(K,{rejectParked:!0,reason:"cursor-sdk superseded by new prompt",timeoutMs:2e3,poisonOnFailure:!0})).failed)throw An.invalidate(K,"cursor-sdk active run did not finish cancellation before new prompt"),Object.assign(new Error("cursor-sdk active run did not finish cancellation"),{retryFreshCursorSession:!0});let X=pS(t,{mode:s,workspaceDir:K.workspaceDir,followUpOnly:se});ie=Symbol("cursor-sdk-run"),K.activeRunToken=ie;try{let Z=await _g(K,X,x(K,ie),{abortSignal:r.abortSignal,logger:o});K.run=Z,K.activeRunToken=ie,K.streamIterator=Z.stream()[Symbol.asyncIterator](),K.hasSentPrompt=!0}catch(Z){throw ie&&K.activeRunToken===ie&&(K.activeRunToken=void 0,v(K,ie)),(r.abortSignal?.aborted||yg(Z))&&An.invalidate(K,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),o?.error?.({err:Z},"cursor-sdk agent.send failed"),Z}}),!ie)throw new Error("cursor-sdk agent.send did not produce a run token");return ie};if(_){D&&w.length&&!y.streamIterator&&o?.warn?.({toolResultCount:w.length,hadParked:b},"cursor-sdk dead-run recovery: sending follow-up with tool results");try{k=await W(y,D)}catch(K){if(!j(K,y))throw R(K);o?.warn?.({err:K,sessionKey:y.key,agentId:y.agentId},"cursor-sdk retrying failed resumed send with fresh session"),An.invalidate(y,"cursor-sdk resumed send failed before streaming"),y=await An.getOrCreate(S);try{k=await W(y,!1)}catch(se){throw R(se)}}}k||(k=Symbol("cursor-sdk-run"),y.activeRunToken=k);let U=lS(c,new TextEncoder),ue=[],Y=ES(t),ne=0,te,re=new ReadableStream({async start(K){let se=Q=>{ue.push(Q),a&&K.enqueue(U.encode(Q))},ie=Q=>{typeof Q=="string"&&Q.length&&(ne+=Q.length)},X=()=>{let Q=TS(te,y.lastSdkUsageRaw,Y),me=vS(Y,ne,Q);return te&&(y.lastSdkUsageRaw=te),me},Z=Q=>{let me=X();o?.debug?.({reason:Q,promptTokens:me.prompt_tokens,completionTokens:me.completion_tokens,outputChars:ne,sdkUsageRaw:te,runUsage:y.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),se(U.finish(Q,me))};try{let Q=0,me=!1,he=!0,z=!1,ge=!1,Fe,xe="",ye=0,be=()=>{!z||ge||(se(U.thinkingSignature()),ge=!0,he=!1)};for(;;){let C=!1;for await(let E of yF(y,s,k,r.abortSignal)){if(dl(y),E.kind==="host_tool"){if(s!=="bridge")continue;for(be(),he=!1,ie(E.tool.name),ie(JSON.stringify(E.tool.args??{})),se(U.toolCall(E.tool,Q)),Q+=1;y.pendingEmit.length;){let I=y.pendingEmit.shift();ie(I.name),ie(JSON.stringify(I.args??{})),se(U.toolCall(I,Q)),Q+=1}Z("tool_calls"),a&&K.enqueue(U.encodeDone()),K.close();return}if(E.kind==="end"){if(y.activeRunToken===k&&(y.streamIterator=void 0,y.run=void 0,y.activeRunToken=void 0),fS({mode:s,assistantText:xe,emittedHostTools:Q,continuationAttempts:ye})){ye+=1,o?.warn?.({assistantText:xe,attempt:ye},"cursor-sdk continuing progress-only terminal turn");let I=Symbol("cursor-sdk-run");y.activeRunToken=I;let F;try{F=await gg(y,()=>_g(y,hS(),x(y,I),{abortSignal:r.abortSignal,logger:o}))}catch(B){throw y.activeRunToken===I&&(y.activeRunToken=void 0,v(y,I)),B}k=I,y.run=F,y.activeRunToken=k,y.streamIterator=F.stream()[Symbol.asyncIterator](),y.hasSentPrompt=!0,xe="",C=!0;break}be(),Z("stop"),a&&K.enqueue(U.encodeDone()),K.close();return}let T=E.message;if(T){if(T.type==="assistant")for(let I of T.message?.content||[])I.type==="text"&&I.text&&(be(),he=!1,me=!0,xe+=I.text,ie(I.text),se(U.content(I.text)));else if(T.type==="thinking"){if(!he)continue;let I=E.source||"stream";if(Fe&&Fe!==I)continue;Fe=I;let F=ls(T.text);F&&(z=!0,ie(F),se(U.thinking(F)))}else if(T.type==="usage")te=RS(T);else if(T.type==="status"){if(T.status==="ERROR"||T.status==="CANCELLED")throw Object.assign(new Error(T.message||`Cursor run ${T.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(T.type==="tool_call"&&s!=="bridge"&&s==="agent"&&T.name){be(),he=!1;let I=`
350
- [cursor tool ${T.status||"running"}: ${T.name}]
351
- `;ie(I),se(U.content(I))}}}if(!C)break}!me&&!Q&&(be(),Z("stop")),a&&K.enqueue(U.encodeDone()),K.close()}catch(Q){o?.error?.({err:Q,metrics:y.metrics},"cursor-sdk stream failed"),xi(y,{rejectParked:!0,reason:"cursor-sdk stream failed",timeoutMs:2e3,onlyRunToken:k,poisonOnFailure:!0}).then(me=>{me.skipped||An.invalidate(y,"cursor-sdk stream failed before terminal state")});try{K.error(Q)}catch{}}},cancel(){xi(y,{rejectParked:!0,reason:"cursor-sdk client cancelled stream",timeoutMs:2e3,onlyRunToken:k,poisonOnFailure:!0}).then(K=>{K.skipped||An.invalidate(y,"cursor-sdk client cancelled stream")})}});if(!a){let K=re.getReader();for(;;){let{done:ie}=await K.read();if(ie)break}let se=dS(c,ue);return new Response(JSON.stringify(se),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(re,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}var hl=class{static TransformerName=ug;name=ug;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let s={cursorMode:this.options.cursorMode||al,cursorCwd:this.options.cursorCwd,sandboxEnabled:this.options.sandboxEnabled,abortSignal:r?.signal,logger:this.logger},a={...e,messages:Je(e.messages),tools:Ve(e.tools)},c=await xS(a,n,r,s);return{body:a,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:c}}}async transformResponseOut(e){return e}};var QS=require("crypto");var It=require("fs"),gl=require("path"),FS=require("os"),PS=require("crypto"),ml="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",yl="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",wg="http://localhost:51121/oauth-callback",IS=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],Cg="https://daily-cloudcode-pa.sandbox.googleapis.com",NS="https://autopush-cloudcode-pa.sandbox.googleapis.com",BS="https://cloudcode-pa.googleapis.com",bF=[Cg,NS,BS],bg=[BS,Cg,NS],wF="1.18.3",CF=(0,gl.join)((0,FS.homedir)(),".claude-code-router","antigravity_auth.json"),kF=12e4,jS="https://oauth2.googleapis.com/token",SF="https://www.googleapis.com/oauth2/v2/userinfo",pl=null,MS=null;function US(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||CF}function Pi(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${wF} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,"X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})}}function Fi(){try{let t=US();if(!(0,It.existsSync)(t))return null;let e=JSON.parse((0,It.readFileSync)(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function _l(t){let e=US();(0,It.mkdirSync)((0,gl.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,It.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,It.renameSync)(n,e)}finally{try{(0,It.existsSync)(n)&&(0,It.unlinkSync)(n)}catch{}}}function AF(t){return Date.now()+kF>=t.expires_at}async function EF(t){let e=new URLSearchParams({client_id:ml,client_secret:yl,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(jS,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Antigravity token refresh failed (${n.status}). Run \`ccr antigravity-auth\` again. ${s.slice(0,200)}`)}let r=await n.json();if(!r.access_token)throw new Error("Antigravity token refresh returned no access_token. Run `ccr antigravity-auth` again.");let o={...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,expires_at:Date.now()+(r.expires_in||3600)*1e3};return _l(o),o}async function Ii(t){let e=Fi();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!AF(e)?e:(pl||(pl=EF(e).finally(()=>{pl=null})),pl)}function hs(t){let e=t?.cloudaicompanionProject;if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e.id=="string"&&e.id.trim())return e.id.trim()}function vF(t){let e=n=>{if(n){if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="object"&&typeof n.id=="string"&&n.id.trim())return n.id.trim()}};return e(t?.paidTier)||e(t?.currentTier)||e(t?.allowedTiers?.find(n=>n?.isDefault))||e(t?.allowedTiers?.[0])||void 0}function LS(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function OS(t){await new Promise(e=>setTimeout(e,t))}async function TF(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Pi()};for(let s=0;s<20;s++){try{let a=await fetch(r,{method:"GET",headers:o,signal:AbortSignal.timeout(15e3)});if(!a.ok){await OS(2e3);continue}let c=await a.json();if(c?.done===!0)return hs(c?.response)||hs(c)||void 0}catch{}await OS(2e3)}}async function RF(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Pi()},body:JSON.stringify({tierId:e,metadata:LS()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=hs(o?.response)||hs(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?TF(t,n,o.name.trim()):void 0}catch{return}}function DF(t){let e=vF(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function xF(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Pi()},n=JSON.stringify({metadata:LS()}),r;for(let o of bg)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let a=await s.json();r=a;let c=hs(a);if(c)return c}catch{}for(let o of DF(r))for(let s of bg){let a=await RF(t,o,s);if(a)return a}for(let o of bg)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let a=hs(await s.json());if(a)return a}catch{}}async function bl(t,e){let n=t?.project_id?.trim();if(n)return n;let r=Fi();if(r?.project_id?.trim())return r.project_id.trim();let o=await xF(e);if(o){let s=Fi();return s&&_l({...s,project_id:o}),o}}function Ni(){return MS||Cg}function qS(t){MS=t}var $S=new Set;function zS(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function HS(t){$S.add(t.replace(/\/$/,""))}function OF(t){return $S.has(t.replace(/\/$/,""))}function WS(t,e){return e?t===404||t===403||t>=500:!1}function GS(t){let e=t?.replace(/\/$/,"")||Ni(),n=[...new Set([e,...bF])],r=n.filter(o=>!OF(o));return r.length?r:n}function wl(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function JS(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:(0,PS.randomUUID)()}}async function VS(t){try{let e=await fetch(SF,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function KS(t,e){let n=new URLSearchParams({client_id:ml,client_secret:yl,code:t,grant_type:"authorization_code",redirect_uri:wg,code_verifier:e}),r=await fetch(jS,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Antigravity token exchange failed (${r.status}): ${s.slice(0,300)}`)}let o=await r.json();if(!o.access_token||!o.refresh_token)throw new Error("Antigravity token exchange did not return access_token and refresh_token. Re-auth with prompt=consent may be required.");return{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:Date.now()+(o.expires_in||3600)*1e3}}function YS(t){try{let e=JSON.parse(t),n=e?.error?.details||e?.details;if(!Array.isArray(n))return;for(let r of n){let o=r?.retryDelay||r?.retry_delay;if(typeof o=="string"){let s=o.match(/^([\d.]+)s$/);if(s)return Math.ceil(parseFloat(s[1])*1e3)}}}catch{}}function XS(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function FF(t,e){let n=t?.req?.body?.model;return typeof n=="string"&&n?n:typeof t?.req?.model=="string"&&t.req.model?t.req.model:e?.models?.[0]||""}function PF(t){return t?.req?.body?.stream===!0}function IF(t){return GS(t)}var Cl=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Ii({force:o?.forceRefresh}),a=await bl(n,s.access_token),c=FF(r,n),l=PF(r),f=JS({...a?{project:a}:{},model:c,request:e});return f.requestId=f.requestId||(0,QS.randomUUID)(),{body:f,accessToken:s.access_token,projectId:a,model:c,stream:l}}buildHeaders(e,n){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-goog-api-key":void 0,...Pi(),...n?{Accept:"text/event-stream"}:{}}}async sendWithFallback(e,n,r,o,s,a=!1){let c=s?.req?.server?.configService?.getHttpsProxy?.(),l=this.logger??s?.req?.log??s?.req?.server?.log,f=o?.baseUrl||o?.api_base_url||Ni(),d=IF(f),h;for(let m=0;m<d.length;m++){let S=d[m],y=wl(S,r),w=this.buildHeaders(n,r);try{let b=await Eo(y,e,{httpsProxy:c,headers:Object.fromEntries(Object.entries(w).filter(([,_])=>_!==void 0)),signal:s?.signal},s,l);if(b.status===401&&!a){let _=await Ii({force:!0});return this.sendWithFallback(e,_.access_token,r,o,s,!0)}if(b.status===429){let _=await b.clone().text().catch(()=>""),D=YS(_),k={};throw D!=null&&(k["Retry-After"]=String(Math.ceil(D/1e3))),$e(_t(_)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",k)}if(!b.ok){let _=await b.clone().text().catch(()=>"");if(b.status===403&&zS(_)&&(HS(S),l?.warn?.({endpoint:S},"Antigravity endpoint is not enabled for this project; skipping it")),WS(b.status,m<d.length-1)){h=$e(`Antigravity endpoint ${S} returned ${b.status}`,b.status,"provider_error");continue}throw $e(_t(_)||`Antigravity request failed with ${b.status}`,b.status,b.status===403?"permission_error":"provider_error")}return qS(S),b}catch(b){if(b?.statusCode===429||b?.status===429||!Ws(b))throw b;if(h=b,m<d.length-1)continue;throw b}}throw h||$e("All Antigravity endpoints failed",502,"provider_error")}async transformRequestIn(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r),s=await this.sendWithFallback(o.body,o.accessToken,o.stream,n,r);return{body:o.body,config:{url:wl(Ni(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream),__providerResponse:s}}}async auth(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r);return{config:{url:wl(n?.baseUrl||Ni(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?ze(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Te(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(Be("[DONE]",o.encoder));return}try{let a=JSON.parse(s),c=XS(a);o.controller.enqueue(Be(JSON.stringify(c),o.encoder))}catch{o.controller.enqueue(Te(r,o.encoder))}return}o.controller.enqueue(Te(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=XS(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};var ZS={AnthropicTransformer:vo,GeminiTransformer:Ha,VertexGeminiTransformer:mu,VertexClaudeTransformer:Mu,VertexOpenaiTransformer:Uu,DeepseekTransformer:vu,TooluseTransformer:Tu,OpenrouterTransformer:Ru,OpenAITransformer:$u,MaxTokenTransformer:Du,GroqTransformer:xu,CleancacheTransformer:Ou,EnhanceToolTransformer:Pu,ReasoningTransformer:Iu,SamplingTransformer:Nu,MaxCompletionTokens:Bu,CerebrasTransformer:Lu,StreamOptionsTransformer:qu,CustomParamsTransformer:zu,VercelTransformer:Hu,OpenAIResponsesTransformer:Wu,CodexTransformer:Xu,QwenAuthTransformer:Qu,ForceReasoningTransformer:Zu,ExtraThinkTagTransformer:el,MistralTransformer:tl,ChromeOnDeviceTransformer:nl,OpencodeHeadersTransformer:rl,ClaudeAuthTransformer:il,CursorSdkTransformer:hl,AntigravityAuthTransformer:Cl};var ao=class{constructor(e,n){this.configService=e;this.logger=n}transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let a=s.endPoint;if(!a)return;let c=n.get(a);if(c){this.logger?.debug?.(`transformer ${o} shares endpoint ${a} with ${c}; keeping ${c}`);return}n.set(a,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let a=new o;a&&typeof a=="object"&&(a.logger=this.logger),r(s,a)}catch(a){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${a?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=require(require.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
392
+ `}function vB(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${Yi}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,EA(t)].join(" ")}function Jg(t,e,n){try{if((0,Ur.readFileSync)(t,"utf-8")===e)return}catch{}(0,Ur.writeFileSync)(t,e,{encoding:"utf-8",mode:n})}function Qi(t,e=Br){let n=(0,Ps.join)(t,".cursor"),r=(0,Ps.join)(n,"hooks");(0,Ur.mkdirSync)(r,{recursive:!0});let o=(0,Ps.join)(r,"deny-builtin.cjs");Jg(o,EB(vB(e)),448);try{(0,Ur.chmodSync)(o,448)}catch{}let s=fA.join("|"),i=`node "${o}"`,c={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};Jg((0,Ps.join)(n,"hooks.json"),JSON.stringify(c,null,2),384),Jg((0,Ps.join)(t,"AGENTS.md"),SA(t,e),384)}var AB=2e3;function TB(t){let e=t;return e?.name==="AbortError"||String(e?.message||t).toLowerCase()==="this operation was aborted"}function Is(t,e){t.poisoned=!0,t.poisonReason=e}async function Xg(t,e={}){let n={skipped:!1,hadRun:!!t.run,hadIterator:!!t.streamIterator,runCancelFailed:!1,iteratorReturnFailed:!1,failed:!1,timedOut:!1};if(e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken)return{...n,skipped:!0};let r=t.run,o=t.streamIterator,s=t.streamNext;if(t.run=void 0,t.streamIterator=void 0,t.streamNext=void 0,t.streamNextRunToken=void 0,t.activeRunToken=void 0,t.pendingEmit=[],t.pendingSdkMessages=[],t.notifyEmit(),t.notifySdkMessage?.(),s?.catch(()=>{}),e.rejectParked&&t.parked.length){let u=e.reason||"cursor-sdk run cancelled";for(let f of t.parked.splice(0,t.parked.length))try{f.reject(new Error(u))}catch{}}let i=async(u,f,d)=>{try{await sd(Promise.resolve().then(u),e.timeoutMs??2e3,f)}catch(p){n.failed=!0,d==="run"&&(n.runCancelFailed=!0),d==="iterator"&&(n.iteratorReturnFailed=!0),n.timedOut=n.timedOut||String(p?.message||p).toLowerCase().includes("timed out")}},c=[];return r?.status==="running"&&c.push(i(()=>r.cancel(),"cursor-sdk run cancel timed out","run")),o&&typeof o.return=="function"&&c.push(i(()=>o.return(void 0),"cursor-sdk stream iterator return timed out","iterator")),await Promise.all(c),n.failed&&e.poisonOnFailure&&Is(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function sd(t,e,n){let r;try{return await Promise.race([t,new Promise((o,s)=>{r=setTimeout(()=>s(new Error(n)),e)})])}finally{r&&clearTimeout(r)}}async function id(t,e){let n=t.sendChain,r,o=new Promise(s=>{r=s});t.sendChain=n.then(()=>o).catch(()=>o),await n.catch(()=>{});try{return await e()}finally{r()}}function Zi(t){if(t===!1)return!1;let e=process.env.CCR_CURSOR_SANDBOX?.trim().toLowerCase();return!(e==="0"||e==="false"||e==="off"||!(t===!0||e==="1"||e==="true"||e==="on")||(0,Gt.existsSync)("/.dockerenv")||process.env.container==="docker")}function RB(t,e){(0,Gt.existsSync)(Tn)||(0,Gt.mkdirSync)(Tn,{recursive:!0});let n=(0,Yg.join)(Tn,t);return(0,Gt.mkdirSync)(n,{recursive:!0}),Qi(n,e),n}function Qg(t,e){if(!e.known&&t.hostEnv?.known)return!1;let n=t.guidanceFingerprint!==e.fingerprint;if(t.hostEnv=e,t.mode!=="bridge"||!n)return!1;try{return Qi(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function xA(t,e,n=Tn){if(!Hg(t,n))return!1;try{return(0,Gt.rmSync)(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function OA(t){if(t.headerSession)return(0,rd.createHash)("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?(0,rd.createHash)("sha256").update(e[1]).digest("hex").slice(0,32):(0,rd.createHash)("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return Ds([t.model||"",t.systemAndFirstUser||""])}function DA(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function od(t){t.lastActiveAt=Date.now()}var Kg=class{constructor(e){this.logger=e;this.cleanupTimer=setInterval(()=>this.evictIdle(),6e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}logger;sessions=new Map;retirements=new Map;creations=new Map;cleanupTimer;lastSweepAt=0;setLogger(e){this.logger=e}get(e){let n=this.sessions.get(e);if(n?.poisoned){let r=n.poisonReason||"cursor-sdk session poisoned";this.retireSession(n,r,async()=>(await this.invalidate(n,r),!0)).catch(o=>{this.logger?.warn?.({err:o,sessionKey:n.key,agentId:n.agentId,reason:r},"cursor-sdk poisoned session retirement failed")});return}return n&&od(n),n}async retireSession(e,n,r){Is(e,n),this.sessions.get(e.key)===e&&this.sessions.delete(e.key);let o=this.retirements.get(e.key);o||(o={tail:Promise.resolve(),pending:new Map},this.retirements.set(e.key,o));let s=o.pending.get(e);if(s)return await s.catch(()=>{}),!1;let i=o.pending.size>0,c=o.tail,u=async()=>(this.logger?.debug?.({sessionKey:e.key,agentId:e.agentId,reason:n},"cursor-sdk session retirement started"),r()),f=i?c.then(u):u();o.pending.set(e,f);let d=f.then(()=>{},()=>{});o.tail=d;try{return await f}finally{o.pending.get(e)===f&&o.pending.delete(e),this.retirements.get(e.key)===o&&o.tail===d&&o.pending.size===0&&this.retirements.delete(e.key)}}async getOrCreate(e){for(;;){let o=this.retirements.get(e.key);if(o){await o.tail;continue}let s=this.get(e.key);if(s)return s;let i=this.retirements.get(e.key);if(i){await i.tail;continue}let c=this.creations.get(e.key);if(!c)break;await c}let n,r=new Promise(o=>{n=o});this.creations.set(e.key,r);try{this.evictIfNeeded();let o=e.hostEnv||Br,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:RB(e.key,o);e.mode==="bridge"&&Qi(s,o);let i=e.mode==="plan"?"plan":"agent",c=Zi(e.sandboxEnabled),u=await Vg.Agent.create({apiKey:e.apiKey,model:e.model,name:`ccr-${e.key.slice(0,8)}`,mode:i,local:{cwd:s,settingSources:[],sandboxOptions:{enabled:c},enableAgentRetries:!0}}),f=this.createSessionRecord({key:e.key,agent:u,mode:e.mode,workspaceDir:s,hostEnv:o,guidanceFingerprint:o.fingerprint});return this.sessions.set(e.key,f),this.logger?.info?.({sessionKey:e.key,agentId:u.agentId,mode:e.mode,sandboxEnabled:c},"cursor-sdk session created"),f}finally{this.creations.get(e.key)===r&&this.creations.delete(e.key),n()}}async resume(e){let n=Zi(e.sandboxEnabled),r=e.hostEnv||Br;e.mode==="bridge"&&Qi(e.workspaceDir,r);let o=await Vg.Agent.resume(e.agentId,{apiKey:e.apiKey,model:e.model,local:{cwd:e.workspaceDir,settingSources:[],sandboxOptions:{enabled:n}}}),s=this.createSessionRecord({key:e.key,agent:o,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:r,guidanceFingerprint:r.fingerprint});return this.sessions.set(e.key,s),s}resolveParkedTools(e,n){let r=0,o=[],s=e.parked.map(i=>i.id).filter((i,c,u)=>i&&u.indexOf(i)!==c);s.length&&this.logger?.warn?.({sessionKey:e.key,duplicates:[...new Set(s)]},"cursor-sdk parked tools share an id; results may mispair");for(let i of n){let c=-1;if(i.toolCallId?c=e.parked.findIndex(f=>f.id===i.toolCallId):n.length===1&&e.parked.length===1&&(c=0),c===-1){o.push(i.toolCallId||"(empty)");continue}let[u]=e.parked.splice(c,1);u.resolve(i.content),r++}return o.length&&this.logger?.warn?.({unmatched:o,parkedRemaining:e.parked.map(i=>i.id),resolved:r},"cursor-sdk tool results did not match parked tools"),od(e),r}async dispose(e){let n=this.sessions.get(e);if(!n)return;let r="cursor-sdk session disposed";await this.retireSession(n,r,async()=>(await Xg(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),xA(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(Is(r,n),r.run=void 0,r.streamIterator=void 0,r.streamNext?.catch(()=>{}),r.streamNext=void 0,r.streamNextRunToken=void 0,r.activeRunToken=void 0,r.pendingEmit=[],r.pendingSdkMessages=[],r.parked.length)for(let o of r.parked.splice(0,r.parked.length))try{o.reject(new Error(n))}catch{}return r.notifyEmit(),r.notifySdkMessage(),this.sessions.get(r.key)===r&&this.sessions.delete(r.key),this.logger?.warn?.({sessionKey:r.key,agentId:r.agentId,reason:n},"cursor-sdk session invalidated"),this.disposeAgent(r,n)}async disposeAgent(e,n){try{let r=e.agent[Symbol.asyncDispose]();r.catch(()=>{}),await sd(r,AB,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};TB(r)?this.logger?.debug?.(o,"cursor-sdk agent disposal observed expected cancellation"):this.logger?.warn?.(o,"cursor-sdk agent disposal failed")}}createSessionRecord(e){let n={key:e.key,agent:e.agent,agentId:e.agent.agentId,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:e.hostEnv,parked:[],pendingEmit:[],emitWaiters:[],pendingSdkMessages:[],sdkMessageWaiters:[],sendChain:Promise.resolve(),hasSentPrompt:!1,guidanceFingerprint:e.guidanceFingerprint,lastActiveAt:Date.now(),metrics:{customToolCalls:0,builtinToolCallsSeen:0,scratchPathViolations:0,scratchPathCorrections:0},parkHostTool:({id:r,name:o,args:s})=>{let i,c,u=new Promise((d,p)=>{i=d,c=p}),f=n.activeRunToken;return n.parked.push({id:r,name:o,args:s,runToken:f,resolve:i,reject:c,promise:u}),n.pendingEmit.push({id:r,name:o,args:s,runToken:f}),n.notifyEmit(),u},notifyEmit:()=>{let r=n.emitWaiters.splice(0,n.emitWaiters.length);for(let o of r)o()},waitForEmit:()=>new Promise(r=>{if(n.pendingEmit.length){r();return}n.emitWaiters.push(r)}),enqueueSdkMessage:(r,o=n.activeRunToken)=>{n.pendingSdkMessages.push({message:r,runToken:o,source:"delta"}),n.notifySdkMessage()},notifySdkMessage:()=>{let r=n.sdkMessageWaiters.splice(0,n.sdkMessageWaiters.length);for(let o of r)o()},waitForSdkMessage:()=>new Promise(r=>{if(n.pendingSdkMessages.length){r();return}n.sdkMessageWaiters.push(r)})};return n}evictIfNeeded(){for(;this.sessions.size>=zg;){let e,n=1/0;for(let[r,o]of this.sessions)DA(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:zg},"cursor-sdk session capacity reached with all sessions in-flight; deferring eviction");break}this.dispose(e)}}evictIdle(){let e=Date.now();for(let[n,r]of this.sessions)DA(r)||e-r.lastActiveAt>uA&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=Tn){if(e-this.lastSweepAt<dA)return 0;this.lastSweepAt=e;let r;try{r=(0,Gt.readdirSync)(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let c=(0,Yg.join)(n,i);if(!(o.has(c)||!Hg(c,n))){try{let u=(0,Gt.statSync)(c);if(!u.isDirectory()||e-u.mtimeMs<=lA)continue}catch{continue}xA(c,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},jr=new Kg;var xB="Cursor SDK agent.send timed out";function Zg(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentBusyError"||e.status===409||r.includes("already has active run")||r.includes("agent busy")}function ey(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentNotFoundError"||n==="NetworkError"||e.status===503||e.status===504||r.includes("agent not found")||r.includes("request aborted before send")||r.includes("request aborted during send")||r.includes("agent.send timed out")||r.includes("network error")||r.includes("network request failed")||r.includes("network timeout")||r.includes("network connection")}function DB(t){if(!t)return;let e;return{promise:new Promise((r,o)=>{if(t.aborted){o(new Error("cursor-sdk request aborted before send"));return}e=()=>o(new Error("cursor-sdk request aborted during send")),t.addEventListener("abort",e,{once:!0})}),cleanup:()=>{e&&t.removeEventListener("abort",e)}}}async function OB(t,e,n,r){let o,s;try{if(r?.aborted)throw new Error("cursor-sdk request aborted before send");return o=t.agent.send(e,n),s=DB(r),await sd(s?Promise.race([o,s.promise]):o,15e3,xB)}catch(i){throw o&&o.then(c=>c.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function ty(t,e,n,r={}){return OB(t,e,n,r.abortSignal)}var NA=require("crypto");var PB=6,IB=512,FB=4;function NB(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function MB(t,e){return t.length<8?!1:t.includes(e)||t.includes(Tn)}function PA(t,e){let n=[],r=0,o=(s,i,c)=>{if(!(n.length>=FB||r>=IB||c>PB)){if(r++,typeof s=="string"){MB(s,e)&&n.push({argPath:i||"(argument)",value:NB(s)});return}if(Array.isArray(s)){s.forEach((u,f)=>o(u,`${i}.${f}`,c+1));return}if(s&&typeof s=="object")for(let[u,f]of Object.entries(s))o(f,i?`${i}.${u}`:u,c+1)}};return o(t,"",0),n}function IA(t){return t.projectRoot?!t.projectRoot.startsWith(Tn):!0}function FA(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
393
+ `);return[`Error: this ${e} call was not executed because it points at your local scratch container, not at the user's machine.`,"Offending arguments:",o,`${n} is disposable scratch space on the machine running the model bridge. It is empty and contains none of the user's files.`,"Host tools execute on the user's machine, where that path does not exist.",Co(r),"Retry the call with a host path."].join(`
394
+ `)}var BB=3;function UB(t){if(!t)return{type:"object",properties:{}};if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object")return e}catch{return{type:"object",properties:{}}}return typeof t=="object"?t:{type:"object",properties:{}}}function ny(){return{scratchViolations:0,scratchCorrections:0}}function MA(t,e,n,r=ny()){let o={};if(!Array.isArray(t.tools))return o;for(let s of t.tools){let i=s.function?.name;!i||typeof i!="string"||(o[i]={description:s.function.description||`Claude Code host tool: ${i}`,inputSchema:UB(s.function.parameters),async execute(c,u){let f=$n(u.toolCallId)||(0,NA.randomUUID)(),d=c||{},p=e.hostEnv||Br,h=IA(p)?PA(d,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let _=e.metrics.scratchPathCorrections<BB;if(n?.warn?.({sessionKey:e.key,tool:i,hits:h,corrected:_,violations:e.metrics.scratchPathViolations},"cursor-sdk host tool call referenced the scratch workspace"),_)return e.metrics.scratchPathCorrections+=1,r.scratchCorrections+=1,FA(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:f,name:i,args:d})}})}return o}function UA(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function BA(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function jA(t){let e=[];t.system&&e.push(BA(t.system));for(let n of t.messages||[])e.push(BA(n.content)),n.thinking?.content&&e.push(String(n.thinking.content)),n.reasoning_content&&e.push(String(n.reasoning_content)),n.tool_calls?.length&&e.push(JSON.stringify(n.tool_calls));return t.tools?.length&&e.push(JSON.stringify(t.tools)),UA(e.join(`
395
+ `).length)}function LA(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=UA(e),s=Math.min(r,Math.max(0,Math.trunc(n)||0));return{prompt_tokens:r,completion_tokens:o,total_tokens:r+o,prompt_tokens_details:{cached_tokens:s}}}function ad(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function qA(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=ad(t.prompt_tokens),s=ad(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=ad(e?.prompt_tokens),c=ad(e?.prompt_tokens_details?.cached_tokens),u=o-i,f=s-c,d=u>0&&f>0?f/u:s/o,p=Math.min(1,Math.max(0,d));return Math.min(r,Math.floor(r*p))}function $A(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,i=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:i}}}var zA=require("crypto"),jB=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Rn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="bigint")return String(t);if(Array.isArray(t))return t.map(n=>Rn(n)).filter(n=>n!==void 0);if(typeof t!="object")return;let e={};for(let n of Object.keys(t).sort()){if(n==="cache_control")continue;let r=Rn(t[n]);r!==void 0&&(e[n]=r)}return e}function oy(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Rn(t);return e===void 0?[]:[e]}return t.map(e=>{if(typeof e=="string")return{text:e,type:"text"};if(!e||typeof e!="object")return Rn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Rn(n)}).filter(e=>e!==void 0)}function LB(t){if(typeof t!="string")return Rn(t)??null;try{return Rn(JSON.parse(t))??null}catch{return t}}function sy(t){let e=t,n={content:oy(e.content),role:e.role};return e.reasoning_content&&(n.reasoning_content=e.reasoning_content),e.thinking?.content&&(n.thinking={content:e.thinking.content}),e.tool_call_id&&(n.tool_call_id=e.tool_call_id),e.is_error!==void 0&&(n.is_error=e.is_error),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(n.tool_calls=e.tool_calls.map(r=>({function:{arguments:LB(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function HA(t){return Array.isArray(t)?t.map(e=>Rn(e)).filter(e=>e!==void 0).sort((e,n)=>ry(e).localeCompare(ry(n))):[]}function ry(t){return JSON.stringify(t)}function iy(t){return(0,zA.createHash)("sha256").update(ry(t)).digest("hex")}function WA(t){return{system:oy(t.system),messages:(t.messages||[]).map(sy)}}function qB(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(jB.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(sy):r==="system"?o=oy(t.system):r==="tools"?o=HA(t.tools):o=Rn(e[r]),o!==void 0&&(n[r]=o)}return n}function GA(t,e={}){return iy({compatibilityStamp:e.compatibilityStamp||"",request:qB(t),turnIntent:e.turnIntent?{interruption:e.turnIntent.interruption,source:e.turnIntent.source,steering:e.turnIntent.steering,trailingToolResults:e.turnIntent.trailingToolResults.map(n=>({content:n.content,isError:n.isError,toolCallId:n.toolCallId}))}:null})}function ay(t){return iy({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Rn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:HA(t.tools),workspaceDir:t.workspaceDir})}function JA(t,e){return iy({messages:e,system:t})}function VA(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=WA(t);return e&&n.messages.push(sy(e)),Object.freeze({transcriptHash:JA(n.system,n.messages),messageCount:n.messages.length})}function KA(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=WA(e);if(!(n.messages.length<=t.messageCount)&&JA(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function $B(t,e){if(t.length===0||t.length!==e.length)return;let n=new Map;for(let s of e){let i=s.toolCallId;if(!i||n.has(i))return;n.set(i,s)}let r=new Set,o=[];for(let s of t){if(!s.id||r.has(s.id))return;r.add(s.id);let i=n.get(s.id);if(!i)return;o.push({parked:s,result:i})}return o}var rr=t=>({action:"retire-and-replay-full",reason:t});function YA(t){let{session:e,turn:n}=t;if(e.poisoned)return rr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:rr("inconsistent-unused-session");if(e.alignment==="unknown")return rr("unknown-context-alignment");if(e.alignment==="divergent")return rr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return rr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return rr("dead-parked-run");if(n.hasMeaningfulSteering)return rr("parked-turn-has-steering");let r=$B(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:rr("parked-tool-results-mismatch")}return n.toolResults.length>0?rr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function cn(t){let e=t instanceof Error?t.message:typeof t=="string"&&t?t:"Cursor turn subscriber aborted";return Object.assign(new Error(e),{name:"AbortError"})}async function cy(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var uy=class{constructor(e,n,r,o){this.sessionKey=e;this.fingerprint=n;this.responseKind=r;this.onTerminal=o;this.ready.catch(()=>{})}sessionKey;fingerprint;responseKind;onTerminal;abortController=new AbortController;phase="awaiting_response";responseMetadata;sourceReader;chunks=[];bufferedBytes=0;replayable=!0;readySettled=!1;completedAt;nextInterestId=1;nextSubscriberId=1;interests=new Set;subscribers=new Map;failure;readyResolve;readyReject;settledResolve;ready=new Promise((e,n)=>{this.readyResolve=e,this.readyReject=n});settled=new Promise(e=>{this.settledResolve=e});get canReplay(){return this.phase==="completed"&&this.replayable}get replayAgeMs(){return this.completedAt===void 0?Number.POSITIVE_INFINITY:Date.now()-this.completedAt}get isJoinable(){return this.replayable&&(this.phase==="awaiting_response"||this.phase==="streaming")}get isProducing(){return this.phase==="awaiting_response"||this.phase==="streaming"}reserve(e,n){let r=this.nextInterestId++;return this.interests.add(r),new ly(this,r,e,n)}releaseInterest(e){if(this.interests.delete(e))return this.abortIfUnobserved("Cursor turn has no remaining subscribers")}async attach(e,n,r){if(this.phase==="aborting"||this.phase==="failed"||this.abortController.signal.aborted){try{await e.body?.cancel(this.abortController.signal.reason)}catch{}this.finishFailed(cn(this.abortController.signal.reason??"Cursor turn superseded"));return}let o=[];e.headers.forEach((i,c)=>{o.push([c,i])}),this.responseMetadata={status:e.status,statusText:e.statusText,headers:o},this.phase="streaming";let s=this.interests.has(n)?this.responseForReadyInterest(n,r):void 0;return this.readySettled=!0,this.readyResolve(),e.body?(this.sourceReader=e.body.getReader(),s&&this.ensurePumpStarted(),s):(this.finishCompleted(),s)}fail(e){this.finishFailed(e instanceof Error?e:new Error(String(e)))}async supersede(e){if(this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"){await cy(this.settled,3e3);return}this.phase="aborting";let n=cn(e);this.readySettled||(this.readySettled=!0,this.readyReject(n)),this.abortController.abort(n),this.errorSubscribers(n);let r=this.sourceReader;if(r){let o=Promise.resolve(r.cancel(n)).catch(()=>{}).then(()=>{});await cy(o,3e3),this.finishFailed(n)}await cy(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw cn(n?.reason);if(!this.responseMetadata)throw this.failure||new Error("Cursor turn response metadata is missing");if(!this.replayable&&this.phase!=="streaming")throw this.releaseInterest(e),Object.assign(new Error("Cursor turn result exceeded the bounded replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});let r=this.responseForReadyInterest(e,n);return this.ensurePumpStarted(),r}responseForReadyInterest(e,n){let r=this.openStream(e,n);return new Response(r,{status:this.responseMetadata.status,statusText:this.responseMetadata.statusText,headers:this.responseMetadata.headers})}openStream(e,n){let r;return new ReadableStream({start:o=>{if(!this.interests.has(e)){o.error(cn(n?.reason));return}r=this.nextSubscriberId++;let s={controller:o};if(this.subscribers.set(r,s),this.interests.delete(e),n){let i=()=>{r!==void 0&&this.removeSubscriber(r,cn(n.reason))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0}),s.removeAbortListener=()=>n.removeEventListener("abort",i)}if(!this.replayable){this.removeSubscriber(r,Object.assign(new Error("Cursor turn cannot replay an oversized active result"),{statusCode:409,code:"cursor_turn_not_replayable"}));return}for(let i of this.chunks)o.enqueue(i);this.phase==="completed"?this.closeSubscriber(r):(this.phase==="failed"||this.phase==="aborting")&&this.removeSubscriber(r,this.failure||cn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,cn(o),!1):this.releaseInterest(e)})}pumpStarted=!1;ensurePumpStarted(){this.pumpStarted||!this.sourceReader||this.phase!=="streaming"||(this.pumpStarted=!0,this.pump())}async pump(){let e=this.sourceReader;if(e)try{for(;this.phase==="streaming";){let{done:n,value:r}=await e.read();if(n){this.finishCompleted();return}if(r){if(this.replayable)if(this.bufferedBytes+r.byteLength<=8388608){let o=r.slice();this.chunks.push(o),this.bufferedBytes+=o.byteLength}else this.replayable=!1,this.chunks=[];for(let o of this.subscribers.values())o.controller.enqueue(r)}}}catch(n){this.finishFailed(n instanceof Error?n:new Error(String(n)))}}abortIfUnobserved(e){if(!(this.interests.size>0||this.subscribers.size>0||this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"))return this.supersede(e)}removeSubscriber(e,n,r=!0){let o=this.subscribers.get(e);if(o){if(this.subscribers.delete(e),o.removeAbortListener?.(),r)try{o.controller.error(n)}catch{}return this.abortIfUnobserved(n.message)}}closeSubscriber(e){let n=this.subscribers.get(e);if(n){this.subscribers.delete(e),n.removeAbortListener?.();try{n.controller.close()}catch{}}}errorSubscribers(e){for(let n of[...this.subscribers.keys()])this.removeSubscriber(n,e)}releaseSourceReader(){let e=this.sourceReader;if(this.sourceReader=void 0,!!e)try{e.releaseLock()}catch{}}finishCompleted(){if(!(this.phase==="completed"||this.phase==="failed")){if(this.phase==="aborting"){this.finishFailed(cn(this.abortController.signal.reason));return}this.phase="completed",this.completedAt=Date.now(),this.releaseSourceReader();for(let e of[...this.subscribers.keys()])this.closeSubscriber(e);this.settledResolve(),this.onTerminal(this,"completed")}}finishFailed(e){this.phase==="completed"||this.phase==="failed"||(this.phase="failed",this.failure=e,this.releaseSourceReader(),this.readySettled||(this.readySettled=!0,this.readyReject(e)),this.errorSubscribers(e),this.interests.clear(),this.settledResolve(),this.onTerminal(this,"failed"))}},ly=class{constructor(e,n,r,o="join"){this.turn=e;this.interestId=n;this.signal=r;this.kind=o;if(r){let s=()=>{this.turn.releaseInterest(this.interestId)};r.aborted?s():(r.addEventListener("abort",s,{once:!0}),this.removeReservationAbortListener=()=>r.removeEventListener("abort",s))}}turn;interestId;signal;kind;attachedResponse;removeReservationAbortListener;get producerSignal(){return this.turn.abortController.signal}attach(e){if(this.kind!=="leader")throw new Error("Only the Cursor turn leader may attach a response");return this.turn.attach(e,this.interestId,this.signal).then(n=>{this.attachedResponse=n})}fail(e){this.kind==="leader"&&this.turn.fail(e),this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}async response(){try{if(this.attachedResponse){let e=this.attachedResponse;return this.attachedResponse=void 0,e}return await this.turn.responseFor(this.interestId,this.signal)}finally{this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}}},dy=class{sessions=new Map;admissionGates=new Map;forgetExpiredSuperseded(e,n,r=!0){let o=Date.now();for(let[s,i]of n.superseded)i<=o&&n.superseded.delete(s);r&&!n.active&&!n.completed&&n.superseded.size===0&&this.sessions.delete(e)}rememberSuperseded(e,n,r){for(n.superseded.delete(r),n.superseded.set(r,Date.now()+9e5);n.superseded.size>16;){let s=n.superseded.keys().next().value;if(typeof s!="string")break;n.superseded.delete(s)}let o=setTimeout(()=>{let s=this.sessions.get(e);s&&this.forgetExpiredSuperseded(e,s)},9e5);typeof o.unref=="function"&&o.unref()}async admit(e){if(e.signal?.aborted)throw cn(e.signal.reason);let n=this.admissionGates.get(e.sessionKey),r,o=new Promise(s=>{r=s});this.admissionGates.set(e.sessionKey,o),n&&await n;try{if(e.signal?.aborted)throw cn(e.signal.reason);for(;;){if(e.signal?.aborted)throw cn(e.signal.reason);let s=this.sessions.get(e.sessionKey)||{superseded:new Map};if(this.sessions.set(e.sessionKey,s),this.forgetExpiredSuperseded(e.sessionKey,s,!1),s.superseded.has(e.fingerprint))throw Object.assign(new Error("This Cursor turn was superseded by a newer request"),{statusCode:409,code:"cursor_turn_superseded"});let i=s.active;if(i){if(i.fingerprint===e.fingerprint){if(i.responseKind!==e.responseKind)throw Object.assign(new Error("An identical Cursor turn is already using a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});if(i.isJoinable)return i.reserve(e.signal,"join");if(i.isProducing)throw Object.assign(new Error("The active Cursor turn exceeded the bounded duplicate replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});await i.supersede("Waiting for the aborted Cursor turn to finish cleanup"),s.active===i&&(s.active=void 0);continue}this.rememberSuperseded(e.sessionKey,s,i.fingerprint),await i.supersede("Cursor turn superseded by a newer request"),s.active===i&&(s.active=void 0);continue}let c=s.completed;if(c&&c.replayAgeMs<=6e4&&c.fingerprint===e.fingerprint&&c.canReplay){if(c.responseKind!==e.responseKind)throw Object.assign(new Error("The cached Cursor turn uses a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});return c.reserve(e.signal,"replay")}c&&c.fingerprint!==e.fingerprint&&this.rememberSuperseded(e.sessionKey,s,c.fingerprint),s.completed=void 0;let u=new uy(e.sessionKey,e.fingerprint,e.responseKind,(f,d)=>{let p=this.sessions.get(e.sessionKey);if(p){if(p.active===f&&(p.active=void 0),d==="completed"&&f.canReplay){p.completed=f;let h=setTimeout(()=>{let _=this.sessions.get(e.sessionKey);_?.completed===f&&(_.completed=void 0,this.forgetExpiredSuperseded(e.sessionKey,_))},6e4);typeof h.unref=="function"&&h.unref()}!p.active&&!p.completed&&p.superseded.size===0&&this.sessions.delete(e.sessionKey)}});return s.active=u,s.completed=void 0,u.reserve(e.signal,"leader")}}finally{r(),this.admissionGates.get(e.sessionKey)===o&&this.admissionGates.delete(e.sessionKey)}}clear(){for(let e of this.sessions.values())e.active&&e.active.supersede("Cursor turn registry cleared");this.sessions.clear()}},XA=new dy;var zB=900*1e3,ea=null;function fy(t){return Ds([t])}async function HB(t){let e=fy(t);if(ea&&ea.apiKeyFingerprint===e&&Date.now()-ea.fetchedAt<zB)return ea.models;let n=await QA.Cursor.models.list({apiKey:t})||[];return ea={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function WB(t,e,n){let r;try{r=await HB(t)}catch{return{id:e}}let o=r.find(i=>i.id===e||i.displayName===e||Array.isArray(i.aliases)&&i.aliases.includes(e));if(!o)return{id:e};if(n&&Array.isArray(o.variants)&&o.variants.length){let i=o.variants.find(c=>c.params?.some(u=>/effort|reasoning/i.test(u.id)&&String(u.value).toLowerCase()===String(n).toLowerCase()))||o.variants.find(c=>(c.displayName||"").toLowerCase().includes(String(n).toLowerCase()));if(i)return{id:o.id,params:i.params}}let s=o.variants?.find(i=>i.isDefault)||o.variants?.[0];return s?.params?.length?{id:o.id,params:s.params}:{id:o.id}}function GB(t){let e=[];for(let n of t.messages||[])if((n.role==="system"||n.role==="user")&&(typeof n.content=="string"?e.push(n.content):Array.isArray(n.content)&&e.push(n.content.map(r=>typeof r=="string"?r:r?.text||"").join("")),n.role==="user"))break;return e.join(`
396
+ `)}function JB(t){return t.length===1&&t[0]?.role==="user"}function VB(t,e,n){if(e.hasTrailingUserInput)return!1;let r=n?.interruption==="synthetic_client_interrupt"&&n.steering==="none",o=e.toolResults.length+(r?1:0);if(t.length!==o)return!1;for(let s=0;s<e.toolResults.length;s+=1){let i=t[s],c=e.toolResults[s];if(i?.role!=="tool"||i.tool_call_id!==c.toolCallId||an(i.content)!==c.content)return!1}return!r||t[t.length-1]?.role==="user"}function un(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*KB(t,e,n,r){let o=t.streamIterator;if(!o){yield{kind:"end"};return}let s=d=>(d.catch(()=>{}),t.streamNext=d,t.streamNextRunToken=n,d),i=s(t.streamNextRunToken===n&&t.streamNext?t.streamNext:o.next()),c=t.waitForEmit().then(()=>"emit"),u=t.waitForSdkMessage().then(()=>"sdk_message"),f=()=>{let d=t.pendingSdkMessages.findIndex(h=>h.runToken===n);if(d===-1)return;let[p]=t.pendingSdkMessages.splice(d,1);return p};for(;;){if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}let d=f();if(d){yield{kind:"sdk",message:d.message,source:d.source};continue}let p=await Promise.race([u.then(b=>({type:b})),i.then(b=>({type:"msg",r:b})),c.then(b=>({type:b}))]);if(p.type==="emit"){for(;t.pendingEmit.length&&t.pendingEmit[0]?.runToken===n;)yield{kind:"host_tool",tool:t.pendingEmit.shift()};c=t.waitForEmit().then(()=>"emit");continue}if(p.type==="sdk_message"){for(;;){let b=f();if(!b)break;yield{kind:"sdk",message:b.message,source:b.source}}u=t.waitForSdkMessage().then(()=>"sdk_message");continue}let{r:h}=p;if(t.streamNext===i&&(t.streamNext=void 0,t.streamNextRunToken=void 0),h.done){yield{kind:"end"};return}let _=h.value;if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}_?.type==="tool_call"&&e==="bridge"&&(t.metrics.builtinToolCallsSeen+=1),yield{kind:"sdk",message:_,source:"stream"},i=s(o.next())}}function YB(t,e){if(!e||e.type!=="thinking-delta")return;let n=Os(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function ta(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:jr.retireSession(t,e.reason,()=>id(t,async()=>(await Xg(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await jr.invalidate(t,e.reason),!0)))}function XB(t,e,n,r){let o=r.cursorMode||td,s=t.model||"composer-2",i;try{i=iA(e)}catch(d){throw Object.assign(d instanceof Error?d:new Error(String(d)),{statusCode:d?.statusCode||401,code:"provider_response_error",type:"api_error"})}let c=n?.req?.headers?.["x-ccr-cursor-session"]||n?.req?.headers?.["X-Ccr-Cursor-Session"],u=r.sourceSessionIdentity||n?.unifiedRequest?.sourceSessionIdentity||t?.metadata?.user_id,f=OA({headerSession:typeof c=="string"?c:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:GB(t)});return{apiKey:i,hostEnv:Xi(t),mode:o,modelId:s,sessionKey:f,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function ZA(t,e,n,r={}){let o=XB(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=ay({credentialFingerprint:fy(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:Wg(t)||""},sandboxEnabled:Zi(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),c=GA(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await XA.admit({sessionKey:o.sessionKey,fingerprint:c,responseKind:t.stream===!0?"stream":"json",signal:r.abortSignal});if(u.kind!=="leader")return u.response();try{let f=await QB(t,e,n,{...r,abortSignal:u.producerSignal,turnIntent:o.turnIntent},o);await u.attach(f)}catch(f){throw u.fail(f),f}return u.response()}async function QB(t,e,n,r,o){un(r.abortSignal);let s=r.logger||e?.logger;s&&jr.setLogger(s);let i=o.mode,c=t.stream===!0,u=o.modelId,f=o.apiKey,d=o.sessionKey,p=Wg(t),h=await WB(f,u,p);un(r.abortSignal);let _=o.hostEnv,b={key:d,apiKey:f,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:_};un(r.abortSignal);let y=await jr.getOrCreate(b);un(r.abortSignal);let w=Y=>!_.known&&Y.hostEnv?.known?Y.hostEnv:_,C=Y=>ay({credentialFingerprint:fy(f),guidanceFingerprint:w(Y).fingerprint,mode:i,model:h,sandboxEnabled:Zi(r.sandboxEnabled),tools:t.tools,workspaceDir:Y.workspaceDir}),v=w(y),A=C(y),T=RA(t,r.turnIntent),x=T.toolResults,O=y.parked.length>0?{kind:"parked",live:!!(y.run&&y.streamIterator&&y.activeRunToken&&!y.poisoned),tools:y.parked}:y.run||y.streamIterator||y.streamNext||y.activeRunToken?{kind:"active-different-turn"}:{kind:"idle"},q=y.transcriptCommit&&y.compatibilityStamp===A?KA(y.transcriptCommit,t):void 0,$=q===void 0?!1:O.kind==="parked"?VB(q,T,r.turnIntent):O.kind==="idle"?JB(q):!0,H=!y.hasSentPrompt||!y.transcriptCommit?"unknown":$?"strict":"divergent",ae=YA({session:{alignment:H,hasSentPrompt:y.hasSentPrompt,poisoned:y.poisoned===!0,run:O},turn:{hasMeaningfulSteering:T.hasTrailingUserInput,toolResults:x}});if(ae.action==="retire-and-replay-full"&&(s?.info?.({sessionKey:y.key,agentId:y.agentId,alignment:H,lifecycleReason:ae.reason,toolResultCount:x.length},"cursor-sdk retiring session before full transcript replay"),await ta(y,{reason:`cursor-sdk lifecycle: ${ae.reason}`,onlyRunToken:y.activeRunToken}),un(r.abortSignal),y=await jr.getOrCreate(b),un(r.abortSignal),v=w(y),A=C(y),ae={action:"send-full",reason:"unused-session"}),un(r.abortSignal),Qg(y,v),ae.action==="resume-parked"&&(un(r.abortSignal),jr.resolveParkedTools(y,x)!==x.length||y.parked.length!==0))throw new Error("cursor-sdk lifecycle changed while resolving exact parked tools");let X=ae.action!=="resume-parked",te=ae.action==="send-incremental",Z=y.activeRunToken,De=(Y,ce)=>{Y.pendingSdkMessages=Y.pendingSdkMessages.filter(de=>de.runToken!==ce),Y.notifySdkMessage()},qe=(Y,ce)=>{let de=i==="bridge"?MA(t,Y,s,Te):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:de?{customTools:de}:void 0,onDelta:({update:k})=>{let E=YB(Y,k);E&&Y.enqueueSdkMessage(E,ce)}}},Te=ny(),We=Y=>Object.assign(new Error(`Cursor SDK error: ${Y?.message||Y}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ee=(Y,ce)=>ce.hasSentPrompt&&!r.abortSignal?.aborted&&(Y?.retryFreshCursorSession===!0||Zg(Y)||ey(Y)),Q=async(Y,ce)=>{let de;if(await id(Y,async()=>{if(Y.poisoned)throw Object.assign(new Error("cursor-sdk session is no longer safe for sends"),{retryFreshCursorSession:!0});if(Y.run||Y.streamIterator||Y.streamNext||Y.activeRunToken||Y.parked.length>0)throw Is(Y,"cursor-sdk session became active after lifecycle admission"),Object.assign(new Error("cursor-sdk session became active before prompt send"),{retryFreshCursorSession:!0});if(Y.poisoned)throw Object.assign(new Error("cursor-sdk session was retired during cancellation"),{retryFreshCursorSession:!0});let k=TA(t,{mode:i,workspaceDir:Y.workspaceDir,followUpOnly:ce,hostEnv:v,turnIntent:r.turnIntent});de=Symbol("cursor-sdk-run"),Y.activeRunToken=de;try{let E=await ty(Y,k,qe(Y,de),{abortSignal:r.abortSignal,logger:s});Y.run=E,Y.activeRunToken=de,Y.streamIterator=E.stream()[Symbol.asyncIterator](),Y.streamNext=void 0,Y.streamNextRunToken=void 0,Y.hasSentPrompt=!0,un(r.abortSignal)}catch(E){throw de&&Y.activeRunToken===de&&(Y.activeRunToken=void 0,De(Y,de)),(r.abortSignal?.aborted||ey(E)||Zg(E))&&Is(Y,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),s?.error?.({err:E},"cursor-sdk agent.send failed"),E}}),!de)throw new Error("cursor-sdk agent.send did not produce a run token");return de};if(X)try{Z=await Q(y,te)}catch(Y){let ce=ee(Y,y);if(await ta(y,{reason:"cursor-sdk prompt send failed before streaming"}),!ce)throw We(Y);un(r.abortSignal),s?.warn?.({err:Y,sessionKey:y.key,agentId:y.agentId},"cursor-sdk retrying failed resumed send with fresh session"),y=await jr.getOrCreate(b),un(r.abortSignal),v=w(y),A=C(y),Qg(y,v);try{Z=await Q(y,!1)}catch(de){throw await ta(y,{reason:"cursor-sdk fresh replay send failed before streaming"}),We(de)}}Z||(Z=Symbol("cursor-sdk-run"),y.activeRunToken=Z);let se=pA(u,new TextEncoder),le=[],be=jA(t),K=0,Ke,Fe=new ReadableStream({async start(Y){let ce=()=>{Te.scratchViolations<=0||s?.warn?.({sessionKey:y.key,model:u,scratchViolations:Te.scratchViolations,scratchCorrections:Te.scratchCorrections,metrics:y.metrics,hostProjectRoot:v.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},de=D=>{le.push(D),c&&Y.enqueue(se.encode(D))},k=D=>{typeof D=="string"&&D.length&&(K+=D.length)},E=()=>{let D=qA(Ke,y.lastSdkUsageRaw,be),F=LA(be,K,D);return Ke&&(y.lastSdkUsageRaw=Ke),F},R=()=>{if(y.activeRunToken!==Z)return;let F=Gg(u,le)?.choices?.[0]?.message;!F||F.role!=="assistant"||(y.transcriptCommit=VA(t,F),y.compatibilityStamp=A)},M=D=>{let F=E();s?.debug?.({reason:D,promptTokens:F.prompt_tokens,completionTokens:F.completion_tokens,outputChars:K,sdkUsageRaw:Ke,runUsage:y.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),de(se.finish(D,F)),R()};try{let D=0,F=!1,j=!0,P=!1,N=!1,U,B="",G=0,oe=()=>{!P||N||(de(se.thinkingSignature()),N=!0,j=!1)};for(;;){let ie=!1;for await(let _e of KB(y,i,Z,r.abortSignal)){if(od(y),_e.kind==="host_tool"){if(i!=="bridge")continue;for(oe(),j=!1,k(_e.tool.name),k(JSON.stringify(_e.tool.args??{})),de(se.toolCall(_e.tool,D)),D+=1;y.pendingEmit.length;){let he=y.pendingEmit.shift();k(he.name),k(JSON.stringify(he.args??{})),de(se.toolCall(he,D)),D+=1}M("tool_calls"),c&&Y.enqueue(se.encodeDone()),Y.close();return}if(_e.kind==="end"){if(_e.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(vA({mode:i,assistantText:B,emittedHostTools:D,continuationAttempts:G})){y.activeRunToken===Z&&(y.streamIterator=void 0,y.streamNext=void 0,y.streamNextRunToken=void 0,y.run=void 0,y.activeRunToken=void 0),G+=1,s?.warn?.({assistantText:B,attempt:G},"cursor-sdk continuing progress-only terminal turn");let he=Symbol("cursor-sdk-run");Z=he,y.activeRunToken=he,await id(y,async()=>{if(y.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let ye=await ty(y,AA(v),qe(y,he),{abortSignal:r.abortSignal,logger:s});if(y.run=ye,y.activeRunToken=he,y.streamIterator=ye.stream()[Symbol.asyncIterator](),y.streamNext=void 0,y.streamNextRunToken=void 0,y.hasSentPrompt=!0,y.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation retired during send")}),B="",ie=!0;break}oe(),M("stop"),y.activeRunToken===Z&&(y.streamIterator=void 0,y.streamNext=void 0,y.streamNextRunToken=void 0,y.run=void 0,y.activeRunToken=void 0),c&&Y.enqueue(se.encodeDone()),Y.close();return}let ge=_e.message;if(ge){if(ge.type==="assistant")for(let he of ge.message?.content||[])he.type==="text"&&he.text&&(oe(),j=!1,F=!0,B+=he.text,k(he.text),de(se.content(he.text)));else if(ge.type==="thinking"){if(!j)continue;let he=_e.source||"stream";if(U&&U!==he)continue;U=he;let ye=Os(ge.text);ye&&(P=!0,k(ye),de(se.thinking(ye)))}else if(ge.type==="usage")Ke=$A(ge);else if(ge.type==="status"){if(ge.status==="ERROR"||ge.status==="CANCELLED")throw Object.assign(new Error(ge.message||`Cursor run ${ge.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(ge.type==="tool_call"&&i!=="bridge"&&i==="agent"&&ge.name){oe(),j=!1;let he=`
397
+ [cursor tool ${ge.status||"running"}: ${ge.name}]
398
+ `;k(he),de(se.content(he))}}}if(!ie)break}!F&&!D&&(oe(),M("stop")),c&&Y.enqueue(se.encodeDone()),Y.close()}catch(D){s?.error?.({err:D,metrics:y.metrics},"cursor-sdk stream failed"),await ta(y,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Z});try{Y.error(D)}catch{}}finally{ce()}},async cancel(){await ta(y,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Z})}});if(!c){let Y=Fe.getReader();for(;;){let{done:de}=await Y.read();if(de)break}let ce=Gg(u,le);return new Response(JSON.stringify(ce),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(Fe,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function ZB(t,e,n){return{cursorMode:t.cursorMode||td,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var cd=class{static TransformerName=$g;name=$g;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=ZB(this.options,r,this.logger),s={...e,messages:Je(e.messages),tools:Ve(e.tools)},i=await ZA(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};var wT=require("crypto");var Pt=require("fs"),ld=require("path"),tT=require("os"),nT=require("crypto"),dd="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",fd="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",hy="http://localhost:51121/oauth-callback",rT=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],my="https://daily-cloudcode-pa.sandbox.googleapis.com",oT="https://autopush-cloudcode-pa.sandbox.googleapis.com",sT="https://cloudcode-pa.googleapis.com",eU=[my,oT,sT],py=[sT,my,oT],tU="1.18.3",nU=(0,ld.join)((0,tT.homedir)(),".claude-code-router","antigravity_auth.json"),rU=12e4,iT="https://oauth2.googleapis.com/token",oU="https://www.googleapis.com/oauth2/v2/userinfo",ud=null,aT=null;function cT(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||nU}function ra(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${tU} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,"X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})}}function na(){try{let t=cT();if(!(0,Pt.existsSync)(t))return null;let e=JSON.parse((0,Pt.readFileSync)(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function pd(t){let e=cT();(0,Pt.mkdirSync)((0,ld.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,Pt.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,Pt.renameSync)(n,e)}finally{try{(0,Pt.existsSync)(n)&&(0,Pt.unlinkSync)(n)}catch{}}}function sU(t){return Date.now()+rU>=t.expires_at}async function iU(t){let e=new URLSearchParams({client_id:dd,client_secret:fd,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(iT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Antigravity token refresh failed (${n.status}). Run \`ccr antigravity-auth\` again. ${s.slice(0,200)}`)}let r=await n.json();if(!r.access_token)throw new Error("Antigravity token refresh returned no access_token. Run `ccr antigravity-auth` again.");let o={...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,expires_at:Date.now()+(r.expires_in||3600)*1e3};return pd(o),o}async function oa(t){let e=na();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!sU(e)?e:(ud||(ud=iU(e).finally(()=>{ud=null})),ud)}function Fs(t){let e=t?.cloudaicompanionProject;if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e.id=="string"&&e.id.trim())return e.id.trim()}function aU(t){let e=n=>{if(n){if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="object"&&typeof n.id=="string"&&n.id.trim())return n.id.trim()}};return e(t?.paidTier)||e(t?.currentTier)||e(t?.allowedTiers?.find(n=>n?.isDefault))||e(t?.allowedTiers?.[0])||void 0}function uT(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function eT(t){await new Promise(e=>setTimeout(e,t))}async function cU(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...ra()};for(let s=0;s<20;s++){try{let i=await fetch(r,{method:"GET",headers:o,signal:AbortSignal.timeout(15e3)});if(!i.ok){await eT(2e3);continue}let c=await i.json();if(c?.done===!0)return Fs(c?.response)||Fs(c)||void 0}catch{}await eT(2e3)}}async function uU(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...ra()},body:JSON.stringify({tierId:e,metadata:uT()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=Fs(o?.response)||Fs(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?cU(t,n,o.name.trim()):void 0}catch{return}}function lU(t){let e=aU(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function dU(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...ra()},n=JSON.stringify({metadata:uT()}),r;for(let o of py)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=await s.json();r=i;let c=Fs(i);if(c)return c}catch{}for(let o of lU(r))for(let s of py){let i=await uU(t,o,s);if(i)return i}for(let o of py)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=Fs(await s.json());if(i)return i}catch{}}async function hd(t,e){let n=t?.project_id?.trim();if(n)return n;let r=na();if(r?.project_id?.trim())return r.project_id.trim();let o=await dU(e);if(o){let s=na();return s&&pd({...s,project_id:o}),o}}function sa(){return aT||my}function lT(t){aT=t}var dT=new Set;function fT(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function pT(t){dT.add(t.replace(/\/$/,""))}function fU(t){return dT.has(t.replace(/\/$/,""))}function hT(t,e){return e?t===404||t===403||t>=500:!1}function mT(t){let e=t?.replace(/\/$/,"")||sa(),n=[...new Set([e,...eU])],r=n.filter(o=>!fU(o));return r.length?r:n}function md(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function gT(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:(0,nT.randomUUID)()}}async function yT(t){try{let e=await fetch(oU,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function _T(t,e){let n=new URLSearchParams({client_id:dd,client_secret:fd,code:t,grant_type:"authorization_code",redirect_uri:hy,code_verifier:e}),r=await fetch(iT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Antigravity token exchange failed (${r.status}): ${s.slice(0,300)}`)}let o=await r.json();if(!o.access_token||!o.refresh_token)throw new Error("Antigravity token exchange did not return access_token and refresh_token. Re-auth with prompt=consent may be required.");return{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:Date.now()+(o.expires_in||3600)*1e3}}function bT(t){try{let e=JSON.parse(t),n=e?.error?.details||e?.details;if(!Array.isArray(n))return;for(let r of n){let o=r?.retryDelay||r?.retry_delay;if(typeof o=="string"){let s=o.match(/^([\d.]+)s$/);if(s)return Math.ceil(parseFloat(s[1])*1e3)}}}catch{}}function CT(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function pU(t,e){let n=t?.req?.body?.model;return typeof n=="string"&&n?n:typeof t?.req?.model=="string"&&t.req.model?t.req.model:e?.models?.[0]||""}function hU(t){return t?.req?.body?.stream===!0}function mU(t){return mT(t)}var gd=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await oa({force:o?.forceRefresh}),i=await hd(n,s.access_token),c=pU(r,n),u=hU(r),f=gT({...i?{project:i}:{},model:c,request:e});return f.requestId=f.requestId||(0,wT.randomUUID)(),{body:f,accessToken:s.access_token,projectId:i,model:c,stream:u}}buildHeaders(e,n){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-goog-api-key":void 0,...ra(),...n?{Accept:"text/event-stream"}:{}}}async sendWithFallback(e,n,r,o,s,i=!1){let c=s?.req?.server?.configService?.getHttpsProxy?.(),u=this.logger??s?.req?.log??s?.req?.server?.log,f=o?.baseUrl||o?.api_base_url||sa(),d=mU(f),p;for(let h=0;h<d.length;h++){let _=d[h],b=md(_,r),y=this.buildHeaders(n,r);try{let w=await Uo(b,e,{httpsProxy:c,headers:Object.fromEntries(Object.entries(y).filter(([,C])=>C!==void 0)),signal:s?.signal},s,u);if(w.status===401&&!i){let C=await oa({force:!0});return this.sendWithFallback(e,C.access_token,r,o,s,!0)}if(w.status===429){let C=await w.clone().text().catch(()=>""),v=bT(C),A={};throw v!=null&&(A["Retry-After"]=String(Math.ceil(v/1e3))),W(et(C)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",A)}if(!w.ok){let C=await w.clone().text().catch(()=>"");if(w.status===403&&fT(C)&&(pT(_),u?.warn?.({endpoint:_},"Antigravity endpoint is not enabled for this project; skipping it")),hT(w.status,h<d.length-1)){p=W(`Antigravity endpoint ${_} returned ${w.status}`,w.status,"provider_error");continue}throw W(et(C)||`Antigravity request failed with ${w.status}`,w.status,w.status===403?"permission_error":"provider_error")}return lT(_),w}catch(w){if(w?.statusCode===429||w?.status===429||!Yr(w))throw w;if(p=w,h<d.length-1)continue;throw w}}throw p||W("All Antigravity endpoints failed",502,"provider_error")}async transformRequestIn(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r),s=await this.sendWithFallback(o.body,o.accessToken,o.stream,n,r);return{body:o.body,config:{url:md(sa(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream),__providerResponse:s}}}async auth(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r);return{config:{url:md(n?.baseUrl||sa(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ie(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Re(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(Ee("[DONE]",o.encoder));return}try{let i=JSON.parse(s),c=CT(i);o.controller.enqueue(Ee(JSON.stringify(c),o.encoder))}catch{o.controller.enqueue(Re(r,o.encoder))}return}o.controller.enqueue(Re(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=CT(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};var kT={AnthropicTransformer:vc,GeminiTransformer:Pc,VertexGeminiTransformer:ll,VertexClaudeTransformer:Pl,VertexOpenaiTransformer:Il,DeepseekTransformer:Cl,TooluseTransformer:wl,OpenrouterTransformer:kl,OpenAITransformer:Ml,MaxTokenTransformer:Sl,GroqTransformer:El,CleancacheTransformer:vl,EnhanceToolTransformer:Rl,ReasoningTransformer:xl,SamplingTransformer:Dl,MaxCompletionTokens:Ol,CerebrasTransformer:Fl,StreamOptionsTransformer:Nl,CustomParamsTransformer:Bl,VercelTransformer:Ul,OpenAIResponsesTransformer:jl,CodexTransformer:Wl,QwenAuthTransformer:Gl,ForceReasoningTransformer:Jl,ExtraThinkTagTransformer:Vl,MistralTransformer:Kl,ChromeOnDeviceTransformer:Yl,OpencodeHeadersTransformer:Xl,ClaudeAuthTransformer:ed,CursorSdkTransformer:cd,AntigravityAuthTransformer:gd};var wo=class{constructor(e,n){this.configService=e;this.logger=n}configService;logger;transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let i=s.endPoint;if(!i)return;let c=n.get(i);if(c){this.logger?.debug?.(`transformer ${o} shares endpoint ${i} with ${c}; keeping ${c}`);return}n.set(i,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let i=new o;i&&typeof i=="object"&&(i.logger=this.logger),r(s,i)}catch(i){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${i?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=require(require.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
352
399
  error: ${n.message}
353
400
  stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
354
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(ZS).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};var eA=require("tiktoken"),Bi=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,eA.get_encoding)(e)}catch{throw new Error(`Failed to initialize tiktoken encoding: ${e}`)}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){if(!this.encoding)throw new Error("Encoding not initialized");let r=l=>this.encoding.encode(l,void 0,[]),o=0,{messages:s,system:a,tools:c}=e;return Array.isArray(s)&&s.forEach(l=>{typeof l.content=="string"?o+=r(l.content).length:Array.isArray(l.content)&&l.content.forEach(f=>{if(f.type==="text")o+=r(f.text).length;else if(f.type==="tool_use")o+=r(JSON.stringify(f.input)).length;else if(f.type==="tool_result"){let d=typeof f.content=="string"?f.content:JSON.stringify(f.content);o+=r(d).length}})}),typeof a=="string"?o+=r(a).length:Array.isArray(a)&&a.forEach(l=>{l.type==="text"&&(typeof l.text=="string"?o+=r(l.text).length:Array.isArray(l.text)&&l.text.forEach(f=>{o+=r(f||"").length}))}),c&&c.forEach(l=>{l.description&&(o+=r(l.name+l.description).length),l.input_schema&&(o+=r(JSON.stringify(l.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e,void 0,[]))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};var Li=require("path"),mA=require("os"),ps=require("fs"),qi=require("fs");var NF=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,a=null,c=o;for(;c<n&&(s=s[t[c]]);)s.end&&(a=s.end),++c;a?(o>r&&e.push(t.slice(r,o)),e.push(a),o+=a.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},BF=NF,jF=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??null}},MF=jF,aA=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),UF=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),LF=UF(aA),tA=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",qF=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${tA}])]+`,` ?[^\\s${tA}]+`]]),ji="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",H2=new RegExp(`^[${ji}]+$`,"gu"),Sg=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),kl=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");for(let[r,o]of qF)n=n.replaceAll(r,o);return new RegExp(n,"gu")}else if(t.String!==void 0){let n=$F(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},$F=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),zF=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},HF=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,WF=t=>Number.isInteger(t)||typeof t=="bigint",GF=t=>{let e=0;for(let n of t)++e;return e},JF=t=>cA(t.toLowerCase()),Vt=(...t)=>Array.prototype.concat.apply([],t),Ag=t=>new Map(Object.entries(t)),VF=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},cA=t=>t.replace(new RegExp("\\p{M}","gu"),""),nA=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},KF=t=>t.match(/\S+/g)||[],YF=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Mi=YF,XF=class extends Mi{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Xn=XF,QF=class extends Xn{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);HF(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
355
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},ZF=QF,eP=class extends Xn{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(e=>e.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},tP=eP,nP=class extends Xn{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>uA(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},rP=nP,oP=class extends Xn{normalize(t){let e=kl(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},sP=oP,iP=class extends Xn{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Sl=iP,aP=class extends Sl{constructor(){super(...arguments),this.form="NFC"}},cP=aP,uP=class extends Sl{constructor(){super(...arguments),this.form="NFD"}},lP=uP,dP=class extends Sl{constructor(){super(...arguments),this.form="NFKC"}},fP=dP,hP=class extends Sl{constructor(){super(...arguments),this.form="NFKD"}},pP=hP,gP=class extends Xn{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},mP=gP,yP=class extends Xn{normalize(t){return cA(t)}},_P=yP,bP=class extends Xn{normalize(t){return t.toLowerCase()}},wP=bP,CP=class extends Xn{normalize(t){return t=this.config.prepend+t,t}},kP=CP;function SP(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new ZF(t);case"Precompiled":return new tP(t);case"Sequence":return new rP(t);case"Replace":return new sP(t);case"NFC":return new cP(t);case"NFD":return new lP(t);case"NFKC":return new fP(t);case"NFKD":return new pP(t);case"Strip":return new mP(t);case"StripAccents":return new _P(t);case"Lowercase":return new wP(t);case"Prepend":return new kP(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var uA=SP,AP=class extends Mi{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},En=AP,EP=class extends En{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=aA,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(n=>Array.from(this.text_encoder.encode(n),r=>this.byte_encoder[r]).join(""))}},vP=EP,TP=class extends En{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},RP=TP,DP=class extends En{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},xP=DP,OP=class extends En{constructor(t){super(),this.config=t,this.pattern=kl(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):VF(t,this.pattern)}},FP=OP,PP=class extends En{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ji}]+|[${ji}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},IP=PP,NP=class extends En{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},BP=NP,jP=class extends En{constructor(){super(),this.pattern=new RegExp(`[^\\s${ji}]+|[${ji}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},MP=jP,UP=class extends En{constructor(t){super(),this.config=t,this.pattern=kl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},LP=UP,qP=class extends En{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>lA(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},$P=qP,zP=class extends En{pre_tokenize_text(t){return KF(t)}},HP=zP;function WP(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new MP;case"Sequence":return new $P(t);case"Whitespace":return new RP;case"WhitespaceSplit":return new HP;case"Metaspace":return new xP(t);case"ByteLevel":return new vP(t);case"Split":return new FP(t);case"Punctuation":return new IP(t);case"Digits":return new BP(t);case"Replace":return new LP(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var lA=WP,GP=class extends Mi{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=zF(e,this.tokens_to_ids,this.unk_token_id)),e}convert_tokens_to_ids(t){return t.map(e=>this.tokens_to_ids.get(e)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(e=>this.vocab[Number(e)]??this.unk_token)}},Al=GP,JP=class extends Al{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=Ag(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,a=[];for(;s<r.length;){let c=r.length,l=null;for(;s<c;){let f=r.slice(s,c).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){l=f;break}--c}if(l===null){o=!0;break}a.push(l),s=c}o?e.push(this.unk_token):e.push(...a)}return e}},rA=JP,oA=class dA{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new dA(!1,new Map)}},VP=class{constructor(){this.root=oA.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=oA.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},KP=VP,kg=class fA{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new fA(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},YP=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new kg(this.bos_token_id??0,0,0,0,0),o=new kg(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new kg(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let s of this.begin_nodes[e]){s.prev=null;let a=0,c=null;for(let l of this.end_nodes[e]){let f=l.backtrace_score+s.score;(c===null||f>a)&&(c=l.clone(),a=f)}if(c!==null)s.prev=c,s.backtrace_score=a;else return[]}++e}let n=[],r=this.begin_nodes[t][0].prev;if(r===null)return[];let o=r.clone();for(;o.prev!==null;)n.push(o.clone()),o=o.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},XP=YP;function QP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var ZP=class extends Al{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=QP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new KP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],a=e.slice(r).join(""),c=this.trie.common_prefix_search(a);for(let l of c){s.push(l);let f=this.tokens_to_ids.get(l),d=this.scores[f],h=GF(l);t.insert(r,h,d,f),!o&&h===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new XP(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},sA=ZP,eI=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},tI=eI,nI=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},rI=nI,oI=class extends Al{constructor(t){super(t),this.tokens_to_ids=Ag(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new rI(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new tI((c,l)=>c.score<l.score),s={token:n[0],bias:0,prev:null,next:null},a=s;for(let c=1;c<n.length;++c){let l={bias:c/n.length,token:n[c],prev:a,next:null};a.next=l,this.add_node(o,a),a=l}for(;!o.is_empty();){let c=o.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let f={...c.prev};c.prev.deleted=!0,c.prev=f,f.prev?f.prev.next=f:s=f}let l={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};l.prev?(l.prev.next=l,this.add_node(o,l.prev)):s=l,l.next&&(l.next.prev=l,this.add_node(o,l))}for(let c=s;c!==null;c=c.next)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(a=>this.tokens_to_ids.has(a))?e.push(...s):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},iA=oI,sI=class extends Al{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=Ag(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},iI=sI;function aI(t,e){switch(t.type){case"WordPiece":return new rA(t);case"Unigram":return new sA(t,e.eos_token);case"BPE":return new iA(t);default:if(t.vocab)return Array.isArray(t.vocab)?new sA(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new iA(t):new rA(t):new iI(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var cI=aI,uI=class extends Mi{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ui=uI,lI=class extends Ui{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let a of r)"SpecialToken"in a?n&&(o.push(a.SpecialToken.id),s.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(o=Vt(o,t),s=Vt(s,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(o=Vt(o,e),s=Vt(s,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},dI=lI,fI=class extends Ui{post_process(t,e=null){return{tokens:e?Vt(t,e):t}}},hI=fI,pI=class extends Ui{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Vt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=Vt(t,o,e,s),r=Vt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},gI=pI,mI=class extends Ui{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Vt([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=Vt(t,o,e,s),r=Vt(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},yI=mI,_I=class extends Ui{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>hA(e))}post_process(t,e=null,n=!0){let r={tokens:t};for(let o of this.processors)r=o.post_process(r.tokens,e,n);return r}},bI=_I;function wI(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new dI(t);case"ByteLevel":return new hI(t);case"BertProcessing":return new gI(t);case"RobertaProcessing":return new yI(t);case"Sequence":return new bI(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var hA=wI,CI=class extends Mi{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},vn=CI,kI=class extends vn{constructor(t){super(t),this.byte_decoder=LF,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},SI=kI,AI=class extends vn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=Sg(e)),e})}},EI=AI,vI=class extends vn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},TI=vI,RI=class extends vn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},DI=RI,xI=class extends vn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let r=1;r<t.length;++r)t[r]!==e.at(-1)&&e.push(t[r]);let n=e.filter(r=>r!==this.pad_token).join("");return this.cleanup&&(n=Sg(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(t){return[this.convert_tokens_to_string(t)]}},OI=xI,FI=class extends vn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>pA(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},PI=FI,II=class extends vn{decode_chain(t){let e=kl(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},NI=II,BI=class extends vn{decode_chain(t){return[t.join("")]}},jI=BI,MI=class extends vn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o)n=o+1;let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},UI=MI,LI=class extends vn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},qI=LI;function $I(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new SI(t);case"WordPiece":return new EI(t);case"Metaspace":return new TI(t);case"BPEDecoder":return new DI(t);case"CTC":return new OI(t);case"Sequence":return new PI(t);case"Replace":return new NI(t);case"Fuse":return new jI(t);case"Strip":return new UI(t);case"ByteFallback":return new qI(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var pA=$I,zI=class{constructor(t,e){let n=nA(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=nA(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=uA(this.tokenizer.normalizer),this.pre_tokenizer=lA(this.tokenizer.pre_tokenizer),this.model=cI(this.tokenizer.model,this.config),this.post_processor=hA(this.tokenizer.post_processor),this.decoder=pA(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[],this.tokenizer.added_tokens.forEach(o=>{let s=new MF(o);this.added_tokens.push(s),this.model.tokens_to_ids.set(s.content,s.id),this.model.vocab[s.id]=s.content,s.special&&(this.special_tokens.push(s.content),this.all_special_ids.push(s.id))}),(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new BF(this.added_tokens.map(o=>o.content)),this.added_tokens_map=new Map(this.added_tokens.map(o=>[o.content,o])),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),a=this.model.convert_tokens_to_ids(o),c={ids:a,tokens:o,attention_mask:new Array(a.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!WF(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=this.model.convert_ids_to_tokens(t);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Sg(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.added_tokens_splitter.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=JF(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.pre_tokenizer!==null?this.pre_tokenizer(n,{section_index:r}):[n];return this.model(o)})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:Vt(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}},gA=zI;var El=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,Li.join)((0,mA.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,Li.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,Li.join)(e,"tokenizer.json"),tokenizerConfig:(0,Li.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,ps.existsSync)(e)||(0,ps.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,ps.existsSync)(e.tokenizerJson)||!(0,ps.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([qi.promises.readFile(e.tokenizerJson,"utf-8"),qi.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,a]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,l]=await Promise.all([s.json(),a.ok?a.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([qi.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),qi.promises.writeFile(e.tokenizerConfig,JSON.stringify(l,null,2))]),{tokenizerJson:c,tokenizerConfig:l}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`);let e=this.getCachePaths();this.ensureDir(this.cacheDir);let n=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new gA(n.tokenizerJson,n.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`)}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let a of r)if(typeof a.content=="string")n.push(a.content);else if(Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let a of o)if(a.type==="text"){if(typeof a.text=="string")n.push(a.text);else if(Array.isArray(a.text))for(let c of a.text)c&&n.push(c)}}if(s)for(let a of s)a.name&&n.push(a.name),a.description&&n.push(a.description),a.input_schema&&n.push(JSON.stringify(a.input_schema));return n.join(" ")}};var vl=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch{throw new Error(`Invalid API URL: ${this.config.url}`)}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),a=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!a.ok)throw new Error(`API tokenizer request failed: ${a.status} ${a.statusText}`);let c=await a.json();return this.extractTokenCount(c)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out"):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`)}}};var co=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new Bi("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new Bi(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new El(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new vl(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var bA=require("tiktoken");var Eg=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Tl=new Eg(100);var Rl=require("fs/promises"),$i=require("fs/promises"),Dl=require("path"),uo=require("@caeliq/ccr-shared"),wA=require("lru-cache"),HI=(0,bA.get_encoding)("cl100k_base"),Qn=t=>HI.encode(t,void 0,[]),yA="<CCR-SUBAGENT-MODEL>",_A="</CCR-SUBAGENT-MODEL>",CA="x-anthropic-billing-header",gs=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function kA(t){let e=t?.trim();if(!e)return;if(e.includes(","))return e;let n=e.indexOf("/");return n>0?`${e.slice(0,n)},${e.slice(n+1)}`:e}function WI(t){let e=`${CA}:`;if(!t.startsWith(e))return!1;let n=t.slice(e.length).trim();if(!n)return!1;if(n.startsWith("{"))try{let o=JSON.parse(n);return gs(o)&&o.cc_is_subagent===!0}catch{return!1}let r=n.split(";").map(o=>o.trim()).filter(Boolean).flatMap(o=>{let s=o.indexOf("=");return s<0||o.slice(0,s).trim()!=="cc_is_subagent"?[]:[o.slice(s+1).trim()]});return r.length===1&&r[0]==="true"}function GI(t){let e=t?.system;if(!Array.isArray(e)||e.length===0)return!1;let n=e[0],r=typeof n=="string"?n:gs(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;if(!r?.startsWith(CA))return!1;let o=WI(r);return e.shift(),e.length===0&&delete t.system,o}function xl(t,e){let n=t.indexOf(yA);if(n<0)return;let r=n+yA.length,o=t.indexOf(_A,r);if(o<0)return;let s=kA(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+_A.length)}`),s}function SA(t,e){if(typeof t=="string")return xl(t,e);if(!(!gs(t)||typeof t.text!="string"))return xl(t.text,e)}function JI(t){let e=t?.system;if(typeof e=="string")return xl(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=SA(r,s=>{typeof r=="string"?e[n]=s:gs(r)&&(r.text=s)});if(o)return o}}function VI(t){if(typeof t.content=="string")return xl(t.content,n=>{t.content=n});if(!Array.isArray(t.content))return;let e=t.content;for(let n=0;n<e.length;n+=1){let r=e[n],o=SA(r,s=>{typeof r=="string"?e[n]=s:gs(r)&&(r.text=s)});if(o)return o}}function KI(t){if(!Array.isArray(t?.messages))return;let e=Math.min(t.messages.length,2);for(let n=0;n<e;n+=1){let r=t.messages[n];if(!gs(r)||r.role!=="user")continue;let o=VI(r);if(o)return o}}function YI(t){return JI(t)||KI(t)}var vg=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=Qn(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=Qn(s.text).length:s.type==="tool_use"?r+=Qn(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=Qn(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=Qn(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=Qn(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=Qn(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=Qn(o.name+o.description).length),o.input_schema&&(r+=Qn(JSON.stringify(o.input_schema)).length)}),r},XI=async(t,e)=>{if(t.sessionId){let n=await Tg(t.sessionId);if(n){let r=(0,Dl.join)(uo.HOME_DIR,n,"config.json"),o=(0,Dl.join)(uo.HOME_DIR,n,`${t.sessionId}.json`);try{let s=JSON.parse(await(0,Rl.readFile)(o,"utf8"));if(s&&s.Router)return s.Router}catch{}try{let s=JSON.parse(await(0,Rl.readFile)(r,"utf8"));if(s&&s.Router)return s.Router}catch{}}}},QI=async(t,e,n,r)=>{let o=await XI(t,n),s=n.get("providers")||[],a=o||n.get("Router");if(t.body.model.includes(",")){let[S,y]=t.body.model.split(","),w=s.find(_=>_.name.toLowerCase()===S),b=w?.models?.find(_=>_.toLowerCase()===y);return w&&b?{model:`${w.name},${b}`,scenarioType:"default"}:{model:t.body.model,scenarioType:"default"}}let c=a?.longContextThreshold||6e4,l=r&&r.input_tokens>c&&e>2e4,f=e>c;if((l||f)&&a?.longContext)return t.log.info(`Using long context model due to token count: ${e}, threshold: ${c}`),{model:a.longContext,scenarioType:"longContext"};let d=GI(t.body),h=YI(t.body);if(h)return t.log.info(`Using CCR subagent tag model: ${h}`),{model:h,scenarioType:"subagent"};if(d){let S=kA(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(S)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${S}`),{model:S,scenarioType:"subagent"}}let m=n.get("Router");return t.body.model?.includes("claude")&&t.body.model?.includes("haiku")&&m?.background?(t.log.info(`Using background model for ${t.body.model}`),{model:m.background,scenarioType:"background"}):Array.isArray(t.body.tools)&&t.body.tools.some(S=>S.type?.startsWith("web_search"))&&a?.webSearch?{model:a.webSearch,scenarioType:"webSearch"}:t.body.thinking&&a?.think?(t.log.info(`Using think model for ${t.body.thinking}`),{model:a.think,scenarioType:"think"}):{model:a?.default||t.body.model,scenarioType:"default"}},ZI=t=>{if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}},Ol=async(t,e,n)=>{let{configService:r,event:o}=n;t.sessionId=ZI(t.body.metadata?.user_id);let s=Tl.get(t.sessionId),{messages:a,system:c=[],tools:l}=t.body,f=r.get("REWRITE_SYSTEM_PROMPT");if(f&&c.length>1&&c[1]?.text?.includes("<env>")){let d=await(0,Rl.readFile)(f,"utf-8");c[1].text=`${d}<env>${c[1].text.split("<env>").pop()}`}try{let[d,h]=t.body.model.split(","),m=n.tokenizerService?.getTokenizerConfigForModel(d,h),S;n.tokenizerService?S=(await n.tokenizerService.countTokens({messages:a,system:c,tools:l},m)).tokenCount:S=vg(a,c,l);let y,w=r.get("CUSTOM_ROUTER_PATH");if(w)try{let b=require(w);t.tokenCount=S,y=await b(t,r.getAll(),{event:o})}catch(b){t.log.error(`failed to load custom router: ${b.message}`)}if(y)t.scenarioType="default";else{let b=await QI(t,S,r,s);y=b.model,t.scenarioType=b.scenarioType}t.body.model=y}catch(d){t.log.error(`Error in router middleware: ${d.message}`);let h=r.get("Router");t.body.model=h?.default||t.body.model,t.scenarioType="default"}},Rr=new wA.LRUCache({max:1e3}),Tg=async(t,e)=>{if(Rr.has(t)){let n=Rr.get(t);return!n||n===""?null:n}try{if(!(await(0,$i.stat)(uo.CLAUDE_PROJECTS_DIR)).isDirectory())return Rr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Rr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Rr.set(t,""),null)}try{let n=await(0,$i.opendir)(uo.CLAUDE_PROJECTS_DIR),r=[];for await(let a of n)a.isDirectory()&&r.push(a.name);let o=r.map(async a=>{let c=(0,Dl.join)(uo.CLAUDE_PROJECTS_DIR,a,`${t}.jsonl`);try{return(await(0,$i.stat)(c)).isFile()?a:null}catch{return null}}),s=await Promise.all(o);for(let a of s)if(a)return Rr.set(t,a),a;return Rr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Rr.set(t,""),null}};var Rg=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Dg=new Rg;var FA=st(RA(),1);Fg();Pg();Ng();xA();var lo=new Map;function Mg(t){let e=lo.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function Ug(){return Array.from(lo.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var jg=new Map,Lg={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,FA.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)ys.registerHandlers(n.outputHandlers);else{let s=[];for(let a of r)a==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):a==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):a==="webhook"&&t.log.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&ys.registerHandlers(s)}n.outputOptions&&ys.setDefaultOptions(n.outputOptions);let o=async s=>{let a=t.tokenizerService;if(!a)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,l=s.model,f=`${c}:${l}`;if(jg.has(f))return jg.get(f);let d=a.getTokenizerConfigForModel(c,l);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${l}, using fallback`),null;try{let h=await a.getTokenizer(d);return jg.set(f,h),t.log?.info(`Created tokenizer for ${c}:${l} - ${h.name}`),h}catch(h){return t.log?.warn(`Failed to create tokenizer for ${c}:${l}: ${h.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,a,c)=>{let l=s.requestStartTime;if(!l)return;let f=s.id||Date.now().toString(),d;try{let y=s.body?.metadata?.user_id;if(y&&typeof y=="string"){let w=y.match(/_session_([a-f0-9-]+)/i);d=w?w[1]:void 0}}catch{}if(!d)return;let h=await o(s);if(c instanceof ReadableStream){lo.set(f,{requestId:f,sessionId:d,startTime:l,lastTokenTime:l,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[y,w]=c.tee();return(async()=>{let _=null,D=async k=>{let v=lo.get(f);if(!v)return;let x=performance.now();if(k){let R=(v.lastTokenTime-v.startTime)/1e3;R>0&&(v.tokensPerSecond=Math.round(v.tokenCount/R))}else{let R=x-1e3;v.tokenTimestamps=v.tokenTimestamps.filter(j=>j>R),v.tokensPerSecond=v.tokenTimestamps.length}await OA(v,r,n.outputOptions,k,t.log).catch(R=>{t.log?.warn(`Failed to output streaming stats: ${R.message}`)})};try{let v=w.pipeThrough(new TextDecoderStream).pipeThrough(new Un).getReader();for(_=setInterval(async()=>{lo.get(f)&&await D(!1)},1e3);;){let{done:x,value:R}=await v.read();if(x)break;let j=R,W=lo.get(f);if(!W)continue;let U=performance.now();if(!W.firstTokenTime&&(j.event==="content_block_start"||j.event==="content_block_delta"||j.event==="text_block"||j.event==="content_block")&&(W.firstTokenTime=U,W.timeToFirstToken=Math.round(U-W.startTime)),j.event==="content_block_delta"&&j.data?.delta){let ue=j.data.delta.type,Y="";if(ue==="text_delta"?Y=j.data.delta.text||"":ue==="input_json_delta"?Y=j.data.delta.partial_json||"":ue==="thinking_delta"&&(Y=j.data.delta.thinking||""),Y){let ne=h&&h.encodeText?h.encodeText(Y).length:Gi(Y);W.tokenCount+=ne,W.lastTokenTime=U;for(let te=0;te<ne;te++)W.tokenTimestamps.push(U)}}j.event==="message_stop"&&(_&&(clearInterval(_),_=null),await D(!0),lo.delete(f))}}catch(k){_&&clearInterval(_),k.name!=="AbortError"&&k.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${k.message}`)}})().catch(_=>{t.log.error(_,"Background stats processing failed")}),y}let m=performance.now(),S=0;if(c&&typeof c=="string")try{let y=JSON.parse(c);if(y.usage?.output_tokens)S=y.usage.output_tokens;else{let w=y.content||y.message?.content||"";if(h)Array.isArray(w)?S=w.reduce((b,_)=>{if(_.type==="text"){let D=_.text||"";return b+(h.encodeText?h.encodeText(D).length:Gi(D))}return b},0):typeof w=="string"&&(S=h.encodeText?h.encodeText(w).length:Gi(w));else{let b=Array.isArray(w)?w.map(_=>_.text).join(""):w;S=Gi(b)}}}catch{}if(S>0){let y=(m-l)/1e3,w={requestId:f,sessionId:d,startTime:l,lastTokenTime:m,tokenCount:S,tokensPerSecond:y>0?Math.round(S/y):0,timeToFirstToken:Math.round(m-l),stream:!1,tokenTimestamps:[]};await OA(w,r,n.outputOptions,!0,t.log)}return c})})};function Gi(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function OA(t,e,n,r=!1,o){let s=r?"[Token Speed Final]":"[Token Speed]",a={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},c={prefix:s,metadata:{sessionId:t.sessionId},...n};for(let l of e)try{await ys.outputToType(l,a,c)}catch(f){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${l}:`,f)}}function sN(t={}){let e=(0,PA.default)({bodyLimit:52428800,...t});return e.setErrorHandler(r_),e.register(IA.default),e}var qg=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=sN({...r,logger:r.logger??!0}),this.configService=new Mr({...e,logger:this.app.log}),this.transformerService=new ao(this.configService,this.app.log),this.tokenizerService=new co(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new $r(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),c.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Ol(l,f,{configService:this.configService,tokenizerService:this.tokenizerService})}),await Qd(c)});return}if(!n)throw new Error("options is required");let r=new Mr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ao(r,this.app.log);await o.initialize();let s=new $r(r,o,this.app.log),a=new co(r,this.app.log);await a.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",a),c.addHook("preHandler",async(l,f)=>{new URL(`http://127.0.0.1${l.url}`).pathname.endsWith("/v1/messages")&&await Ol(l,f,{configService:r,tokenizerService:a})}),await Qd(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/"),this.app.addHook("preHandler",async(r,o)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body)try{let a=r.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[c,...l]=a.model.split(",");a.model=l.join(","),r.provider=c,r.model=l.join(",");return}catch(a){return r.log.error({error:a},"Error in modelProviderMiddleware:"),o.code(500).send({error:"Internal server error"})}});let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},iN=qg;0&&(module.exports={ANTIGRAVITY_CLIENT_ID,ANTIGRAVITY_CLIENT_SECRET,ANTIGRAVITY_REDIRECT_URI,ANTIGRAVITY_SCOPES,ConfigService,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,diffHeadersForLog,exchangeAuthorizationCode,fetchUserEmail,getGlobalTokenSpeedStats,getTokenSpeedStats,getValidAccessToken,isClientAbortError,loadTokens,pluginManager,resolveProjectId,rewriteStream,router,sanitizeHeadersForLog,saveTokens,searchProjectBySession,sessionUsageCache,tokenSpeedPlugin});
401
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(kT).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};var ST=require("tiktoken"),ia=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,ST.get_encoding)(e)}catch(n){throw new Error(`Failed to initialize tiktoken encoding: ${e}`,{cause:n})}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){if(!this.encoding)throw new Error("Encoding not initialized");let r=u=>this.encoding.encode(u,void 0,[]),o=0,{messages:s,system:i,tools:c}=e;return Array.isArray(s)&&s.forEach(u=>{typeof u.content=="string"?o+=r(u.content).length:Array.isArray(u.content)&&u.content.forEach(f=>{if(f.type==="text")o+=r(f.text).length;else if(f.type==="tool_use")o+=r(JSON.stringify(f.input)).length;else if(f.type==="tool_result"){let d=typeof f.content=="string"?f.content:JSON.stringify(f.content);o+=r(d).length}})}),typeof i=="string"?o+=r(i).length:Array.isArray(i)&&i.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?o+=r(u.text).length:Array.isArray(u.text)&&u.text.forEach(f=>{o+=r(f||"").length}))}),c&&c.forEach(u=>{u.description&&(o+=r(u.name+u.description).length),u.input_schema&&(o+=r(JSON.stringify(u.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e,void 0,[]))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};var ua=require("path"),LT=require("os"),Ns=require("fs"),la=require("fs");var gU=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,i=null,c=o;for(;c<n&&(s=s[t[c]]);)s.end&&(i=s.end),++c;i?(o>r&&e.push(t.slice(r,o)),e.push(i),o+=i.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},ET=gU,yU=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},_U=yU,OT=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),bU=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),CU=bU(OT),vT=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",wU=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${vT}])]+`,` ?[^\\s${vT}]+`]]),yd="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",yy=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),_d=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");n=n.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,o]of wU)n=n.replaceAll(r,o);try{return new RegExp(n,"gu")}catch(r){if(!(r instanceof SyntaxError)||!r.message.toLowerCase().includes("invalid property name"))throw r;let o=!1,s=n.replace(/(\\[pP])\{([^}=]+)\}/g,(i,c,u)=>{try{return new RegExp(`\\p{${u}}`,"u"),`${c}{${u}}`}catch{return o=!0,`${c}{Script=${u}}`}});if(!o)throw r;try{return new RegExp(s,"gu")}catch{throw r}}}else if(t.String!==void 0){let n=kU(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},kU=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),SU=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},EU=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,vU=t=>Number.isInteger(t)||typeof t=="bigint",AU=t=>{let e=0;for(let n of t)++e;return e},TU=t=>PT(t.toLowerCase()),ln=(...t)=>Array.prototype.concat.apply([],t),_y=t=>new Map(Object.entries(t)),RU=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},PT=t=>t.replace(new RegExp("\\p{M}","gu"),""),AT=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},xU=t=>t.match(/\S+/g)||[],DU=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},aa=DU,OU=class extends aa{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},or=OU,PU=class extends or{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);EU(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
402
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},IU=PU,FU=class extends or{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(n=>n.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},NU=FU,MU=class extends or{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>IT(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},BU=MU,UU=class extends or{normalize(t){let e=_d(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},jU=UU,LU=class extends or{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},bd=LU,qU=class extends bd{constructor(){super(...arguments),this.form="NFC"}},$U=qU,zU=class extends bd{constructor(){super(...arguments),this.form="NFD"}},HU=zU,WU=class extends bd{constructor(){super(...arguments),this.form="NFKC"}},GU=WU,JU=class extends bd{constructor(){super(...arguments),this.form="NFKD"}},VU=JU,KU=class extends or{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},YU=KU,XU=class extends or{normalize(t){return PT(t)}},QU=XU,ZU=class extends or{normalize(t){return t.toLowerCase()}},ej=ZU,tj=class extends or{normalize(t){return t=this.config.prepend+t,t}},nj=tj;function rj(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new IU(t);case"Precompiled":return new NU(t);case"Sequence":return new BU(t);case"Replace":return new jU(t);case"NFC":return new $U(t);case"NFD":return new HU(t);case"NFKC":return new GU(t);case"NFKD":return new VU(t);case"Strip":return new YU(t);case"StripAccents":return new QU(t);case"Lowercase":return new ej(t);case"Prepend":return new nj(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var IT=rj,oj=class extends aa{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},dn=oj,sj=class extends dn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=OT,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),o=>this.byte_encoder[o]).join(""))}},ij=sj,aj=class extends dn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},cj=aj,uj=class extends dn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},lj=uj,dj=class extends dn{constructor(t){super(),this.config=t,this.pattern=_d(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):RU(t,this.pattern)}},fj=dj,pj=class extends dn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${yd}]+|[${yd}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},hj=pj,mj=class extends dn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},gj=mj,yj=class extends dn{constructor(){super(),this.pattern=new RegExp(`[^\\s${yd}]+|[${yd}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},_j=yj,bj=class extends dn{constructor(t){super(),this.config=t,this.pattern=_d(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Cj=bj,wj=class extends dn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>FT(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},kj=wj,Sj=class extends dn{pre_tokenize_text(t){return xU(t)}},Ej=Sj,vj=class extends dn{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let n=0;n<t.length;n+=this._length)e.push(t.slice(n,n+this._length));return e}},Aj=vj;function Tj(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new _j;case"Sequence":return new kj(t);case"Whitespace":return new cj;case"WhitespaceSplit":return new Ej;case"Metaspace":return new lj(t);case"ByteLevel":return new ij(t);case"Split":return new fj(t);case"Punctuation":return new hj(t);case"Digits":return new gj(t);case"Replace":return new Cj(t);case"FixedLength":return new Aj(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var FT=Tj,Rj=class extends aa{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=SU(e,this.tokens_to_ids,this.unk_token_id)),e}},Cd=Rj,xj=class extends Cd{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=_y(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,i=[];for(;s<r.length;){let c=r.length,u=null;for(;s<c;){let f=r.slice(s,c).join("");if(s>0&&(f=this.config.continuing_subword_prefix+f),this.tokens_to_ids.has(f)){u=f;break}--c}if(u===null){o=!0;break}i.push(u),s=c}o?e.push(this.unk_token):e.push(...i)}return e}},TT=xj,RT=class NT{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new NT(!1,new Map)}},Dj=class{constructor(){this.root=RT.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=RT.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},Oj=Dj,gy=class MT{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new MT(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Pj=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new gy(this.bos_token_id??0,0,0,0,0),o=new gy(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new gy(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let c=0,u=null;for(let f of this.end_nodes[e]){let d=f.backtrace_score+i.score;(u===null||d>c)&&(u=f.clone(),c=d)}if(u!==null)i.prev=u,i.backtrace_score=c;else return[]}++e}let n=[],o=this.begin_nodes[t][0].prev;if(o===null)return[];let s=o.clone();for(;s.prev!==null;)n.push(s.clone()),s=s.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},Ij=Pj;function Fj(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var Nj=class extends Cd{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=Fj(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Oj,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],i=e.slice(r).join(""),c=this.trie.common_prefix_search(i);for(let u of c){s.push(u);let f=this.tokens_to_ids.get(u),d=this.scores[f],p=AU(u);t.insert(r,p,d,f),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new Ij(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},xT=Nj,Mj=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},Bj=Mj,Uj=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},jj=Uj,Lj=class extends Cd{constructor(t){super(t),this.tokens_to_ids=_y(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new jj(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new Bj((c,u)=>c.score<u.score),s={token:n[0],bias:0,prev:null,next:null},i=s;for(let c=1;c<n.length;++c){let u={bias:c/n.length,token:n[c],prev:i,next:null};i.next=u,this.add_node(o,i),i=u}for(;!o.is_empty();){let c=o.pop();if(c.deleted||!c.next||c.next.deleted)continue;if(c.deleted=!0,c.next.deleted=!0,c.prev){let f={...c.prev};c.prev.deleted=!0,c.prev=f,f.prev?f.prev.next=f:s=f}let u={token:c.token+c.next.token,bias:c.bias,prev:c.prev,next:c.next.next};u.prev?(u.prev.next=u,this.add_node(o,u.prev)):s=u,u.next&&(u.next.prev=u,this.add_node(o,u))}for(let c=s;c!==null;c=c.next)r.push(c.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(i=>`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(i=>this.tokens_to_ids.has(i))?e.push(...s):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},DT=Lj,qj=class extends Cd{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=_y(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},$j=qj;function zj(t,e){switch(t.type){case"WordPiece":return new TT(t);case"Unigram":return new xT(t,e.eos_token);case"BPE":return new DT(t);default:if(t.vocab)return Array.isArray(t.vocab)?new xT(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new DT(t):new TT(t):new $j(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var Hj=zj,Wj=class extends aa{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ca=Wj,Gj=class extends ca{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let i of r)"SpecialToken"in i?n&&(o.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(o=ln(o,t),s=ln(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=ln(o,e),s=ln(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},Jj=Gj,Vj=class extends ca{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},Kj=Vj,Yj=class extends ca{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=ln([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=ln(t,o,e,s),r=ln(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},Xj=Yj,Qj=class extends ca{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=ln([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=ln(t,o,e,s),r=ln(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},Zj=Qj,eL=class extends ca{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>BT(e))}post_process(t,e=null,n=!0){let r={tokens:t,tokens_pair:e};for(let o of this.processors)r=o.post_process(r.tokens,r.tokens_pair,n);return r}},tL=eL;function nL(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new Jj(t);case"ByteLevel":return new Kj(t);case"BertProcessing":return new Xj(t);case"RobertaProcessing":return new Zj(t);case"Sequence":return new tL(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var BT=nL,rL=class extends aa{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},xn=rL,oL=class extends xn{constructor(t){super(t),this.byte_decoder=CU,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},sL=oL,iL=class extends xn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=yy(e)),e})}},aL=iL,cL=class extends xn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},uL=cL,lL=class extends xn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},dL=lL,fL=class extends xn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let o=1;o<t.length;++o)t[o]!==e.at(-1)&&e.push(t[o]);let r=e.filter(o=>o!==this.pad_token).join("");return this.cleanup&&(r=yy(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},pL=fL,hL=class extends xn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>UT(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},mL=hL,gL=class extends xn{decode_chain(t){let e=_d(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},yL=gL,_L=class extends xn{decode_chain(t){return[t.join("")]}},bL=_L,CL=class extends xn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o){n=o+1;continue}let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},wL=CL,kL=class extends xn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},SL=kL;function EL(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new sL(t);case"WordPiece":return new aL(t);case"Metaspace":return new uL(t);case"BPEDecoder":return new dL(t);case"CTC":return new pL(t);case"Sequence":return new mL(t);case"Replace":return new yL(t);case"Fuse":return new bL(t);case"Strip":return new wL(t);case"ByteFallback":return new SL(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var UT=EL,vL=class{constructor(t,e){let n=AT(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=AT(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=IT(this.tokenizer.normalizer),this.pre_tokenizer=FT(this.tokenizer.pre_tokenizer),this.model=Hj(this.tokenizer.model,this.config),this.post_processor=BT(this.tokenizer.post_processor),this.decoder=UT(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let o=[],s=[];this.added_tokens_map=new Map;for(let i of this.tokenizer.added_tokens){let c=new _U(i);if(this.added_tokens.push(c),this.model.tokens_to_ids.set(c.content,c.id),this.model.vocab[c.id]=c.content,c.special&&(this.special_tokens.push(c.content),this.all_special_ids.push(c.id)),this.added_tokens_map.set(c.content,c),c.normalized&&this.normalizer!==null){let u=this.normalizer(c.content);s.push(u),this.added_tokens_map.set(u,c)}else o.push(c.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new ET(o),this.splitter_normalized=new ET(s),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),i=o.map(u=>this.added_tokens_map.get(u)?.id??this.model.tokens_to_ids.get(u)??this.model.unk_token_id),c={ids:i,tokens:o,attention_mask:new Array(i.length).fill(1)};return r&&s&&(c.token_type_ids=s),c}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!vU(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=t.map(o=>this.model.vocab[Number(o)]??this.model.unk_token);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=yy(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=TU(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.splitter_normalized.split(n);return o.forEach((s,i)=>{let c=this.added_tokens_map.get(s);c&&(c.lstrip&&i>0&&(o[i-1]=o[i-1].trimEnd()),c.rstrip&&i<o.length-1&&(o[i+1]=o[i+1].trimStart()))}),o.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:r}):[s];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:ln(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(t||!this.added_tokens_map.has(r))&&e.set(r,n)}return e}},jT=vL;var wd=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||(0,ua.join)((0,LT.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,ua.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,ua.join)(e,"tokenizer.json"),tokenizerConfig:(0,ua.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ns.existsSync)(e)||(0,Ns.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ns.existsSync)(e.tokenizerJson)||!(0,Ns.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([la.promises.readFile(e.tokenizerJson,"utf-8"),la.promises.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[c,u]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([la.promises.writeFile(e.tokenizerJson,JSON.stringify(c,null,2)),la.promises.writeFile(e.tokenizerConfig,JSON.stringify(u,null,2))]),{tokenizerJson:c,tokenizerConfig:u}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`),this.ensureDir(this.cacheDir);let e=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new jT(e.tokenizerJson,e.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`,{cause:e})}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let i of r)if(typeof i.content=="string")n.push(i.content);else if(Array.isArray(i.content))for(let c of i.content)c.type==="text"&&c.text?n.push(c.text):c.type==="tool_use"&&c.input?n.push(JSON.stringify(c.input)):c.type==="tool_result"&&n.push(typeof c.content=="string"?c.content:JSON.stringify(c.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let i of o)if(i.type==="text"){if(typeof i.text=="string")n.push(i.text);else if(Array.isArray(i.text))for(let c of i.text)c&&n.push(c)}}if(s)for(let i of s)i.name&&n.push(i.name),i.description&&n.push(i.description),i.input_schema&&n.push(JSON.stringify(i.input_schema));return n.join(" ")}};var kd=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch(e){throw new Error(`Invalid API URL: ${this.config.url}`,{cause:e})}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),i=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!i.ok)throw new Error(`API tokenizer request failed: ${i.status} ${i.statusText}`);let c=await i.json();return this.extractTokenCount(c)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out",{cause:n}):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`,{cause:n})}}};var ko=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new ia("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new ia(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new wd(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new kd(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var by=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},Cy=new by;var KT=tt(WT(),1);Sy();Ey();Ay();JT();var So=new Map;function xy(t){let e=So.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function Dy(){return Array.from(So.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var Ry=new Map,Oy={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,KT.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)Bs.registerHandlers(n.outputHandlers);else{let s=[];for(let i of r)i==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):i==="webhook"&&t.log.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&Bs.registerHandlers(s)}n.outputOptions&&Bs.setDefaultOptions(n.outputOptions);let o=async s=>{let i=t.tokenizerService;if(!i)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let c=s.provider,u=s.model,f=`${c}:${u}`;if(Ry.has(f))return Ry.get(f);let d=i.getTokenizerConfigForModel(c,u);if(!d)return t.log?.debug(`No tokenizer config for ${c}:${u}, using fallback`),null;try{let p=await i.getTokenizer(d);return Ry.set(f,p),t.log?.info(`Created tokenizer for ${c}:${u} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${c}:${u}: ${p.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,i,c)=>{let u=s.requestStartTime;if(!u)return;let f=s.id||Date.now().toString(),d;try{let b=s.body?.metadata?.user_id;if(b&&typeof b=="string"){let y=b.match(/_session_([a-f0-9-]+)/i);d=y?y[1]:void 0}}catch{}if(!d)return;let p=await o(s);if(c instanceof ReadableStream){So.set(f,{requestId:f,sessionId:d,startTime:u,lastTokenTime:u,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[b,y]=c.tee();return(async()=>{let C=null,v=async A=>{let T=So.get(f);if(!T)return;let x=performance.now();if(A){let O=(T.lastTokenTime-T.startTime)/1e3;O>0&&(T.tokensPerSecond=Math.round(T.tokenCount/O))}else{let O=x-1e3;T.tokenTimestamps=T.tokenTimestamps.filter(q=>q>O),T.tokensPerSecond=T.tokenTimestamps.length}await VT(T,r,n.outputOptions,A,t.log).catch(O=>{t.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let T=y.pipeThrough(new TextDecoderStream).pipeThrough(new Hn).getReader();for(C=setInterval(async()=>{So.get(f)&&await v(!1)},1e3);;){let{done:x,value:O}=await T.read();if(x)break;let q=O,$=So.get(f);if(!$)continue;let H=performance.now();if(!$.firstTokenTime&&(q.event==="content_block_start"||q.event==="content_block_delta"||q.event==="text_block"||q.event==="content_block")&&($.firstTokenTime=H,$.timeToFirstToken=Math.round(H-$.startTime)),q.event==="content_block_delta"&&q.data?.delta){let ae=q.data.delta.type,X="";if(ae==="text_delta"?X=q.data.delta.text||"":ae==="input_json_delta"?X=q.data.delta.partial_json||"":ae==="thinking_delta"&&(X=q.data.delta.thinking||""),X){let te=p&&p.encodeText?p.encodeText(X).length:ha(X);$.tokenCount+=te,$.lastTokenTime=H;for(let Z=0;Z<te;Z++)$.tokenTimestamps.push(H)}}q.event==="message_stop"&&(C&&(clearInterval(C),C=null),await v(!0),So.delete(f))}}catch(A){C&&clearInterval(C),A.name!=="AbortError"&&A.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${A.message}`)}})().catch(C=>{t.log.error(C,"Background stats processing failed")}),b}let h=performance.now(),_=0;if(c&&typeof c=="string")try{let b=JSON.parse(c);if(b.usage?.output_tokens)_=b.usage.output_tokens;else{let y=b.content||b.message?.content||"";if(p)Array.isArray(y)?_=y.reduce((w,C)=>{if(C.type==="text"){let v=C.text||"";return w+(p.encodeText?p.encodeText(v).length:ha(v))}return w},0):typeof y=="string"&&(_=p.encodeText?p.encodeText(y).length:ha(y));else{let w=Array.isArray(y)?y.map(C=>C.text).join(""):y;_=ha(w)}}}catch{}if(_>0){let b=(h-u)/1e3,y={requestId:f,sessionId:d,startTime:u,lastTokenTime:h,tokenCount:_,tokensPerSecond:b>0?Math.round(_/b):0,timeToFirstToken:Math.round(h-u),stream:!1,tokenTimestamps:[]};await VT(y,r,n.outputOptions,!0,t.log)}return c})})};function ha(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function VT(t,e,n,r=!1,o){let s=r?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},c={prefix:s,metadata:{sessionId:t.sessionId},...n};for(let u of e)try{await Bs.outputToType(u,i,c)}catch(f){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,f)}}function OL(t={}){let e=(0,YT.default)({bodyLimit:52428800,...t});return e.setErrorHandler(gb),e.register(XT.default),e.register(QT.default,{global:!0,...ZT.RATE_LIMIT_CONFIG}),e}var Py=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=OL({...r,logger:r.logger??!0}),this.configService=new Kr({...e,logger:this.app.log}),this.transformerService=new wo(this.configService,this.app.log),this.tokenizerService=new ko(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new eo(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async c=>{c.decorate("configService",this.configService),c.decorate("transformerService",this.transformerService),c.decorate("providerService",this.providerService),c.decorate("tokenizerService",this.tokenizerService),await lp(c)});return}if(!n)throw new Error("options is required");let r=new Kr({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new wo(r,this.app.log);await o.initialize();let s=new eo(r,o,this.app.log),i=new ko(r,this.app.log);await i.initialize(),await this.app.register(async c=>{c.decorate("configService",r),c.decorate("transformerService",o),c.decorate("providerService",s),c.decorate("tokenizerService",i),await lp(c)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{if(new URL(`http://127.0.0.1${r.url}`).pathname.endsWith("/v1/messages")&&r.body){let c=r.body;r.log.info({data:c,type:"request body"}),c.stream||(c.stream=!1)}s()}),await this.registerNamespace("/");let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},PL=Py;0&&(module.exports={ANTIGRAVITY_CLIENT_ID,ANTIGRAVITY_CLIENT_SECRET,ANTIGRAVITY_REDIRECT_URI,ANTIGRAVITY_SCOPES,ConfigService,DEFAULT_LOG_BODY_MAX_BYTES,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,diffHeadersForLog,exchangeAuthorizationCode,fetchUserEmail,getGlobalTokenSpeedStats,getTokenSpeedStats,getValidAccessToken,isClientAbortError,isRoutedLlmPost,listClientRouteRegistrations,loadTokens,matchClientProtocol,pluginManager,protocolErrorBody,resolveProjectId,rewriteStream,router,sanitizeBodyForLog,sanitizeHeadersForLog,saveTokens,searchProjectBySession,sessionUsageCache,tokenSpeedPlugin});
356
403
  /*! Bundled license information:
357
404
 
405
+ toad-cache/dist/toad-cache.cjs:
406
+ (**
407
+ * toad-cache
408
+ *
409
+ * @copyright 2026 Igor Savin <kibertoad@gmail.com>
410
+ * @license MIT
411
+ * @version 3.7.3
412
+ *)
413
+
358
414
  node-fetch-native/dist/node.mjs:
359
415
  (**
360
416
  * @license
@@ -369,8 +425,5 @@ node-fetch-native/dist/node.mjs:
369
425
 
370
426
  safe-buffer/index.js:
371
427
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
372
-
373
- gtoken/build/cjs/src/index.cjs:
374
- (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *)
375
428
  */
376
429
  //# sourceMappingURL=server.cjs.map