diff --git a/.ado/azure-pipelines.publish.yml b/.ado/azure-pipelines.publish.yml index 2917ec1f6e..d23674f50b 100644 --- a/.ado/azure-pipelines.publish.yml +++ b/.ado/azure-pipelines.publish.yml @@ -20,6 +20,20 @@ variables: - group: InfoSec-SecurityResults - name: tags value: production,externalfacing + # Use the private registry mirror due to network restrictions (this is added to .npmrc in a step below) + - name: REGISTRY_URL + value: https://pkgs.dev.azure.com/office/_packaging/Office/npm/registry/ + - name: YARN_NPM_REGISTRY_SERVER + value: $(REGISTRY_URL) + - name: YARN_NPM_ALWAYS_AUTH + value: 1 + # Enable yarn-plugin-npmrc + - name: YARN_NPMRC_AUTH_ENABLED + value: 1 + - name: packagesArtifactName + value: packed-tarballs + - name: releaseToolArtifactName + value: release-api-tool resources: repositories: @@ -35,6 +49,8 @@ extends: name: Azure-Pipelines-1ESPT-ExDShared image: windows-latest os: windows + settings: + networkIsolationPolicy: AzureActiveDirectory,AzureKeyVault,AzureResourceManager,AzureStorage,GitHub sdl: eslint: configuration: 'recommended' @@ -54,19 +70,36 @@ extends: name: Azure-Pipelines-1ESPT-ExDShared image: ubuntu-latest os: linux + variables: + # set in lage.config.mjs under BUILD_STAGINGDIRECTORY + packagesArtifactPath: $(Build.StagingDirectory)/_packed + releaseToolArtifactPath: $(Build.StagingDirectory)/${{ variables.releaseToolArtifactName }} templateContext: + # run SDL tasks once on this directory for all outputs + outputParentDirectory: $(Build.StagingDirectory) outputs: - output: pipelineArtifact - targetPath: $(System.DefaultWorkingDirectory)/_packed - artifactName: packed-tarballs + targetPath: $(packagesArtifactPath) + artifactName: ${{ variables.packagesArtifactName }} + - output: pipelineArtifact + targetPath: $(releaseToolArtifactPath) + artifactName: ${{ variables.releaseToolArtifactName }} steps: - task: UseNode@1 inputs: version: '22.x' displayName: 'Use Node.js 22.x' + - script: echo 'registry=$(REGISTRY_URL)' >> .npmrc + displayName: 'Configure npm registry' + + - task: npmAuthenticate@0 + inputs: + workingFile: $(Build.SourcesDirectory)/.npmrc + displayName: 'npm authenticate' + - script: | - yarn + yarn --immutable displayName: 'yarn install' - script: | @@ -75,16 +108,22 @@ extends: - script: | yarn lage pack --verbose --grouped - displayName: 'Pack all public packages' + displayName: 'Pack public packages (new versions only)' - script: | - ls -la $(System.DefaultWorkingDirectory)/_packed/ + ls -laR '$(packagesArtifactPath)' displayName: 'List packed tarballs' + - script: | + mkdir -p '$(releaseToolArtifactPath)' + cp scripts/esrp-npm-release-temp/index.mjs '$(releaseToolArtifactPath)' + displayName: 'Copy ESRP release tool' + - stage: Publish displayName: Publish to NPM dependsOn: Build - condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'), ne('${{ parameters.skipNpmPublish }}', 'true')) + # TODO uncomment + # condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'), ne('${{ parameters.skipNpmPublish }}', 'true')) jobs: - job: PublishPackages displayName: Publish NPM Packages @@ -92,58 +131,74 @@ extends: name: Azure-Pipelines-1ESPT-ExDShared image: ubuntu-latest os: linux + variables: + packagesArtifactPath: $(Agent.BuildDirectory)/${{ variables.packagesArtifactName }} + releaseToolArtifactPath: $(Agent.BuildDirectory)/${{ variables.releaseToolArtifactName }} + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + artifactName: ${{ variables.packagesArtifactName }} + targetPath: $(packagesArtifactPath) + - input: pipelineArtifact + artifactName: ${{ variables.releaseToolArtifactName }} + targetPath: $(releaseToolArtifactPath) steps: - task: UseNode@1 inputs: version: '22.x' displayName: 'Use Node.js 22.x' - - task: DownloadPipelineArtifact@2 - inputs: - artifactName: packed-tarballs - targetPath: $(System.DefaultWorkingDirectory)/_packed - displayName: 'Download packed tarballs' - - script: | echo "Downloaded tarballs:" - ls -la $(System.DefaultWorkingDirectory)/_packed/ - if ls $(System.DefaultWorkingDirectory)/_packed/*.tgz > /dev/null 2>&1; then - echo "##vso[task.setvariable variable=hasTarballs]true" + ls -laR '$(packagesArtifactPath)' + if ls "$(packagesArtifactPath)/*/*.tgz" > /dev/null 2>&1; then + echo "##vso[task.setvariable variable=hasTarballs]yes" else echo "No tarballs found — nothing to publish." - echo "##vso[task.setvariable variable=hasTarballs]false" + echo "##vso[task.setvariable variable=hasTarballs]no" fi displayName: 'Check downloaded tarballs' - - script: | - yarn - displayName: 'yarn install' - condition: eq(variables['hasTarballs'], 'true') - - - script: | - yarn config set npmPublishAccess public - yarn config set npmPublishRegistry "https://registry.npmjs.org" - yarn config set npmAuthToken $(npmAuth) - npm config set //registry.npmjs.org/:_authToken $(npmAuth) - displayName: 'Configure npm publishing auth' - condition: eq(variables['hasTarballs'], 'true') - - - script: | - # https://github.com/changesets/changesets/issues/432 - # We can't use `changeset publish` because it doesn't support workspaces, so we have to publish each package individually - yarn lage publish --verbose --grouped --reporter azureDevops - displayName: 'Publish NPM Packages' - condition: eq(variables['hasTarballs'], 'true') - - - script: | - yarn config unset npmPublishAccess - yarn config unset npmAuthToken - yarn config unset npmPublishRegistry - npm config delete //registry.npmjs.org/:_authToken - displayName: 'Cleanup npm publishing auth' - condition: always() - - - script: | - git clean -dfx - displayName: 'Clean up working directory' - condition: always() + - task: AzureCLI@2 + displayName: 'Get credentials for staging blob storage' + condition: eq(variables['hasTarballs'], 'yes') + inputs: + azureSubscription: ogx-esrp-infra-bot + scriptType: bash + scriptLocation: inlineScript + addSpnToEnvironment: true + inlineScript: | + echo "##vso[task.setvariable variable=STAGING_TENANT_ID]$tenantId" + echo "##vso[task.setvariable variable=STAGING_CLIENT_ID]$servicePrincipalId" + echo "##vso[task.setvariable variable=STAGING_ID_TOKEN;issecret=true]$idToken" + + - task: AzureKeyVault@2 + displayName: 'Get ESRP certificates from Key Vault' + condition: eq(variables['hasTarballs'], 'yes') + inputs: + azureSubscription: ESRP-JSHost3 + KeyVaultName: OGX-JSHost-KV + SecretsFilter: OGX-JSHost-Auth4,OGX-JSHost-Sign3 + + # TODO uncomment + # - script: node '$(releaseToolArtifactPath)/index.mjs' + # displayName: 'Publish packages using ESRP Release API' + # condition: eq(variables['hasTarballs'], 'yes') + # retryCountOnTaskFailure: 3 + # env: + # PACKED_PACKAGES_PATH: $(packagesArtifactPath) + # ESRP_PRODUCT_NAME: fluentui-react-native + # ESRP_NPM_TAG: latest + # # TODO should be somebody else + # ESRP_USER: elcraig@microsoft.com + # ESRP_APPROVERS: dannyvv@microsoft.com + # ESRP_TENANT_ID: cdc5aeea-15c5-4db6-b079-fcadd2505dc2 + # ESRP_CLIENT_ID: 0a35e01f-eadf-420a-a2bf-def002ba898d + # ESRP_AUTH_CERT: $(OGX-JSHost-Auth4) + # ESRP_REQUEST_SIGNING_CERT: $(OGX-JSHost-Sign3) + # STAGING_STORAGE_ACCOUNT_NAME: ogxesrptempstorage + # STAGING_CLIENT_ID: $(STAGING_CLIENT_ID) + # STAGING_TENANT_ID: $(STAGING_TENANT_ID) + # STAGING_ID_TOKEN: $(STAGING_ID_TOKEN) diff --git a/.changeset/two-buttons-joke.md b/.changeset/two-buttons-joke.md new file mode 100644 index 0000000000..8f4b2abff1 --- /dev/null +++ b/.changeset/two-buttons-joke.md @@ -0,0 +1,5 @@ +--- +'@fluentui-react-native/dependency-profiles': patch +--- + +Update `workspace-tools` to `^0.42.0` diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 48897110a1..4c4478d4e4 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -334,8 +334,8 @@ jobs: - name: List packed tarballs id: check run: | - ls -la _packed/ - if ls _packed/*.tgz > /dev/null 2>&1; then + ls -laR _packed/ + if ls _packed/*/*.tgz > /dev/null 2>&1; then echo "has-tarballs=true" >> $GITHUB_OUTPUT else echo "has-tarballs=false" >> $GITHUB_OUTPUT @@ -348,33 +348,6 @@ jobs: name: packed-tarballs-dry-run path: _packed/ - publish-dry-run: - name: NPM Publish Dry Run — Publish - runs-on: ubuntu-latest - timeout-minutes: 60 - needs: publish-dry-run-pack - if: needs.publish-dry-run-pack.outputs.has-tarballs == 'true' - steps: - - name: Checkout - uses: actions/checkout@v6 - - - name: Set up toolchain - uses: microsoft/react-native-test-app/.github/actions/setup-toolchain@5.2.3 - with: - node-version: 22 - - - name: Install dependencies - run: yarn - - - name: Download packed tarballs - uses: actions/download-artifact@v8 - with: - name: packed-tarballs-dry-run - path: _packed/ - - - name: Simulate publish - run: yarn lage publish:dry-run --verbose --grouped - test-links: name: Test repo links runs-on: ubuntu-latest @@ -407,7 +380,6 @@ jobs: - win32 - check-changesets - publish-dry-run-pack - - publish-dry-run - test-links steps: - name: Check for failures or cancellations diff --git a/.gitignore b/.gitignore index 9bc051322b..56c3e3d478 100644 --- a/.gitignore +++ b/.gitignore @@ -117,6 +117,9 @@ apps/*/.vscode/.react/ !**/.yarn/sdks !**/.yarn/versions +# May contain credentials +.npmrc + # Ccache .ccache diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 03a7f7302b..c600e485c6 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -11,6 +11,7 @@ "**/lib-commonjs/**", "**/dist/**", "packages/components/Callout/windows/FRNCallout/codegen/**", + "**/esrp-npm-release-temp/**", "**/CHANGELOG.*", "**/CODE_OF_CONDUCT.md", "**/SECURITY.md", diff --git a/.vscode/settings.json b/.vscode/settings.json index 61777f53c4..b139822e2b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -40,20 +40,19 @@ "**/lib-amd": true }, - "javascript.preferences.quoteStyle": "single", - "json.format.enable": false, - "typescript.preferences.quoteStyle": "single", - "typescript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": false, - "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false, + "js/ts.preferences.quoteStyle": "single", + "js/ts.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": false, + "js/ts.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false, // Points at the workspace's typescript package (7.0.2, native tsc). The // TypeScript 7 (native-preview) extension detects that this tsdk has no // tsserver.js and automatically runs it as a native LSP server. - "typescript.tsdk": "./node_modules/typescript/lib", + "js/ts.tsdk.path": "./node_modules/typescript/lib", "search.exclude": { "**/node_modules": true, + "**/.yarn": true, "**/lib": true, "**/lib-amd": true, "**/lib-commonjs": true, diff --git a/.yarn/plugins/@yarnpkg/plugin-npmrc.cjs b/.yarn/plugins/@yarnpkg/plugin-npmrc.cjs new file mode 100644 index 0000000000..bfb8e71e93 --- /dev/null +++ b/.yarn/plugins/@yarnpkg/plugin-npmrc.cjs @@ -0,0 +1,13 @@ +/* eslint-disable */ +//prettier-ignore +module.exports = { +name: "@yarnpkg/plugin-npmrc", +factory: function (require) { +"use strict";var plugin=(()=>{var Bt=Object.create;var M=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Ut=Object.prototype.hasOwnProperty;var E=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xe=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var A=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Ee=(e,t)=>{for(var r in t)M(e,r,{get:t[r],enumerable:!0})},ve=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of It(t))!Ut.call(e,o)&&o!==r&&M(e,o,{get:()=>t[o],enumerable:!(n=Vt(t,o))||n.enumerable});return e};var J=(e,t,r)=>(r=e!=null?Bt(Ft(e)):{},ve(t||!e||!e.__esModule?M(r,"default",{value:e,enumerable:!0}):r,e)),Wt=e=>ve(M({},"__esModule",{value:!0}),e);function k(e){throw new R.ReportError(R.MessageName.UNNAMED,`[${X}] ${e.message||e}`)}function je(e){let t=new Set,r=((n,o)=>{!e||o&&t.has(n)||(o&&t.add(n),console.log(`[${X}] ${n}`))});return r.verbose=e,r}function Ae(e,t){console[e](`[${X}] ${t}`)}var R,X,H=xe(()=>{"use strict";R=E("@yarnpkg/core"),X="yarn-plugin-npmrc"});var Ce=A((Jr,$e)=>{var{hasOwnProperty:Y}=Object.prototype,Q=(e,t={})=>{typeof t=="string"&&(t={section:t}),t.align=t.align===!0,t.newline=t.newline===!0,t.sort=t.sort===!0,t.whitespace=t.whitespace===!0||t.align===!0,t.platform=t.platform||typeof process<"u"&&process.platform,t.bracketedArray=t.bracketedArray!==!1;let r=t.platform==="win32"?`\r +`:` +`,n=t.whitespace?" = ":"=",o=[],i=t.sort?Object.keys(e).sort():Object.keys(e),f=0;t.align&&(f=C(i.filter(s=>e[s]===null||Array.isArray(e[s])||typeof e[s]!="object").map(s=>Array.isArray(e[s])?`${s}[]`:s).concat([""]).reduce((s,l)=>C(s).length>=C(l).length?s:l)).length);let a="",c=t.bracketedArray?"[]":"";for(let s of i){let l=e[s];if(l&&Array.isArray(l))for(let u of l)a+=C(`${s}${c}`).padEnd(f," ")+n+C(u)+r;else l&&typeof l=="object"?o.push(s):a+=C(s).padEnd(f," ")+n+C(l)+r}t.section&&a.length&&(a="["+C(t.section)+"]"+(t.newline?r+r:r)+a);for(let s of o){let l=Ne(s,".").join("\\."),u=(t.section?t.section+".":"")+l,d=Q(e[s],{...t,section:u});a.length&&d.length&&(a+=r),a+=d}return a};function Ne(e,t){var r=0,n=0,o=0,i=[];do if(o=e.indexOf(t,r),o!==-1){if(r=o+t.length,o>0&&e[o-1]==="\\")continue;i.push(e.slice(n,o)),n=o+t.length}while(o!==-1);return i.push(e.slice(n)),i}var Pe=(e,t={})=>{t.bracketedArray=t.bracketedArray!==!1;let r=Object.create(null),n=r,o=null,i=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,f=e.split(/[\r\n]+/g),a={};for(let s of f){if(!s||s.match(/^\s*[;#]/)||s.match(/^\s*$/))continue;let l=s.match(i);if(!l)continue;if(l[1]!==void 0){if(o=B(l[1]),o==="__proto__"){n=Object.create(null);continue}n=r[o]=r[o]||Object.create(null);continue}let u=B(l[2]),d;t.bracketedArray?d=u.length>2&&u.slice(-2)==="[]":(a[u]=(a?.[u]||0)+1,d=a[u]>1);let p=d&&u.endsWith("[]")?u.slice(0,-2):u;if(p==="__proto__")continue;let y=l[3]?B(l[4]):!0,w=y==="true"||y==="false"||y==="null"?JSON.parse(y):y;d&&(Y.call(n,p)?Array.isArray(n[p])||(n[p]=[n[p]]):n[p]=[]),Array.isArray(n[p])?n[p].push(w):n[p]=w}let c=[];for(let s of Object.keys(r)){if(!Y.call(r,s)||typeof r[s]!="object"||Array.isArray(r[s]))continue;let l=Ne(s,".");n=r;let u=l.pop(),d=u.replace(/\\\./g,".");for(let p of l)p!=="__proto__"&&((!Y.call(n,p)||typeof n[p]!="object")&&(n[p]=Object.create(null)),n=n[p]);n===r&&d===u||(n[d]=r[s],c.push(s))}for(let s of c)delete r[s];return r},Se=e=>e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"),C=e=>typeof e!="string"||e.match(/[=\r\n]/)||e.match(/^\[/)||e.length>1&&Se(e)||e!==e.trim()?JSON.stringify(e):e.split(";").join("\\;").split("#").join("\\#"),B=e=>{if(e=(e||"").trim(),Se(e)){e.charAt(0)==="'"&&(e=e.slice(1,-1));try{e=JSON.parse(e)}catch{}}else{let t=!1,r="";for(let n=0,o=e.length;n{_e.exports=Kt;function Kt(...e){let t=e;e.length===1&&(Array.isArray(e[0])||typeof e[0]=="string")&&(t=[].concat(e[0]));for(let o=0,i=t.length;ot?1:-1}});var z=A((Yr,Te)=>{Te.exports=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?(...e)=>console.error(...e):()=>{}});var ee=A((Qr,Me)=>{var ke=E("url"),Z=E("path"),qe=E("stream").Stream,Jt=E("os"),De=z();function Xt(e,t,r){e[t]=String(r)}function Yt(e,t,r){if(r===!0)return!1;if(r===null)return!0;r=String(r);let o=process.platform==="win32"?/^~(\/|\\)/:/^~\//,i=Jt.homedir();return i&&r.match(o)?e[t]=Z.resolve(i,r.slice(2)):e[t]=Z.resolve(r),!0}function Qt(e,t,r){if(De("validate Number %j %j %j",t,r,isNaN(r)),isNaN(r))return!1;e[t]=+r}function zt(e,t,r){let n=Date.parse(r);if(De("validate Date %j %j %j",t,r,n),isNaN(n))return!1;e[t]=new Date(r)}function Zt(e,t,r){typeof r=="string"?isNaN(r)?r==="null"||r==="false"?r=!1:r=!0:r=!!+r:r=!!r,e[t]=r}function er(e,t,r){if(r=ke.parse(String(r)),!r.host)return!1;e[t]=r.href}function tr(e,t,r){if(!(r instanceof qe))return!1;e[t]=r}Me.exports={String:{type:String,validate:Xt},Boolean:{type:Boolean,validate:Zt},url:{type:ke,validate:er},Number:{type:Number,validate:Qt},path:{type:Z,validate:Yt},Stream:{type:qe,validate:tr},Date:{type:Date,validate:zt},Array:{type:Array}}});var We=A((zr,Ue)=>{var V=Le(),b=z(),rr=ee(),He=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Be=(e,{types:t,dynamicTypes:r})=>{let n=He(t,e),o=t[e];if(!n&&typeof r=="function"){let i=r(e);i!==void 0&&(o=i,n=!0)}return[n,o]},T=(e,t)=>t&&e===t,$=(e,t)=>t&&e.indexOf(t)!==-1,nr=(e,t)=>t&&!$(e,t);function or(e,{types:t,shorthands:r,typeDefs:n,invalidHandler:o,unknownHandler:i,abbrevHandler:f,typeDefault:a,dynamicTypes:c}={}){b(t,r,e,n);let s={},l={remain:[],cooked:e,original:e.slice(0)};return Ie(e,s,l.remain,{typeDefs:n,types:t,dynamicTypes:c,shorthands:r,unknownHandler:i,abbrevHandler:f}),Ve(s,{types:t,dynamicTypes:c,typeDefs:n,invalidHandler:o,typeDefault:a}),s.argv=l,Object.defineProperty(s.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:!1}),s}function Ve(e,{types:t={},typeDefs:r={},dynamicTypes:n,invalidHandler:o,typeDefault:i}={}){let f=r.String?.type,a=r.Number?.type,c=r.Array?.type,s=r.Boolean?.type,l=r.Date?.type,u=typeof i<"u";u||(i=[!1,!0,null],f&&i.push(f),c&&i.push(c));let d={};Object.keys(e).forEach(p=>{if(p==="argv")return;let y=e[p];b("val=%j",y);let w=Array.isArray(y),[h,O]=Be(p,{types:t,dynamicTypes:n}),x=O;w||(y=[y]),x||(x=i),T(x,c)&&(x=i.concat(c)),Array.isArray(x)||(x=[x]),b("val=%j",y),b("types=",x),y=y.map(g=>{if(typeof g=="string"&&(b("string %j",g),g=g.trim(),g==="null"&&~x.indexOf(null)||g==="true"&&(~x.indexOf(!0)||$(x,s))||g==="false"&&(~x.indexOf(!1)||$(x,s))?(g=JSON.parse(g),b("jsonable %j",g)):$(x,a)&&!isNaN(g)?(b("convert to number",g),g=+g):$(x,l)&&!isNaN(Date.parse(g))&&(b("convert to date",g),g=new Date(g))),!h){if(!u)return g;O=i}g===!1&&~x.indexOf(null)&&!(~x.indexOf(!1)||$(x,s))&&(g=null);let S={};return S[p]=g,b("prevalidated val",S,g,O),te(S,p,g,O,{typeDefs:r})?(b("validated v",S,g,O),S[p]):(o?o(p,g,O,e):o!==!1&&b("invalid: "+p+"="+g,O),d)}).filter(g=>g!==d),!y.length&&nr(x,c)?(b("VAL HAS NO LENGTH, DELETE IT",y,p,x.indexOf(c)),delete e[p]):w?(b(w,e[p],y),e[p]=y):e[p]=y[0],b("k=%s val=%j",p,y,e[p])})}function te(e,t,r,n,{typeDefs:o}={}){let i=o?.Array?.type;if(Array.isArray(n)){for(let c=0,s=n.length;c1){let x=h.indexOf("=");if(x>-1){O=!0;let D=h.slice(x+1);h=h.slice(0,x),e.splice(w,1,h,D)}let g=Fe(h,y,p,{shorthands:i,abbrevHandler:c});if(b("arg=%j shRes=%j",h,g),g&&(e.splice.apply(e,[w,1].concat(g)),h!==g[0])){w--;continue}h=h.replace(/^-+/,"");let S=null;for(;h.toLowerCase().indexOf("no-")===0;)S=!S,h=h.slice(3);p[h]&&p[h]!==h&&(c?c(h,p[h]):c!==!1&&b(`abbrev: ${h} -> ${p[h]}`),h=p[h]);let[Rt,j]=Be(h,{types:n,dynamicTypes:f}),L=Array.isArray(j);L&&j.length===1&&(L=!1,j=j[0]);let G=T(j,u)||L&&$(j,u);!Rt&&He(t,h)&&(Array.isArray(t[h])||(t[h]=[t[h]]),G=!0);let P,m=e[w+1],Ht=typeof S=="boolean"||T(j,d)||L&&$(j,d)||typeof j>"u"&&!O||m==="false"&&(j===null||L&&~j.indexOf(null));if(typeof j>"u"){let D=!O&&m&&!m?.startsWith("-")&&!["true","false"].includes(m);a?D?a(h,m):a(h):a!==!1&&(b(`unknown: ${h}`),D&&b(`unknown: ${m} parsed as normal opt`))}if(Ht){P=!S,(m==="true"||m==="false")&&(P=JSON.parse(m),m=null,S&&(P=!P),w++),L&&m&&(~j.indexOf(m)?(P=m,w++):m==="null"&&~j.indexOf(null)?(P=null,w++):!m.match(/^-{2,}[^-]/)&&!isNaN(m)&&$(j,l)?(P=+m,w++):!m.match(/^-[^-]/)&&$(j,s)&&(P=m,w++)),G?(t[h]=t[h]||[]).push(P):t[h]=P;continue}T(j,s)&&(m===void 0?m="":m.match(/^-{1,2}[^-]+/)&&(m="",w--)),m&&m.match(/^-{2,}$/)&&(m=void 0,w--),P=m===void 0?!0:m,G?(t[h]=t[h]||[]).push(P):t[h]=P,w++;continue}r.push(h)}}var Re=Symbol("singles"),sr=(e,t)=>{let r=t[Re];r||(r=Object.keys(t).filter(o=>o.length===1).reduce((o,i)=>(o[i]=!0,o),{}),t[Re]=r,b("shorthand singles",r));let n=e.split("").filter(o=>r[o]);return n.join("")===e?n:null};function Fe(e,...t){let{abbrevHandler:r,types:n={},shorthands:o={}}=t.length?t.pop():{},i=t[0]??V(Object.keys(o)),f=t[1]??V(Object.keys(n));if(e=e.replace(/^-+/,""),f[e]===e)return null;if(o[e])return o[e]&&!Array.isArray(o[e])&&(o[e]=o[e].split(/\s+/)),o[e];let a=sr(e,o);return a?a.map(c=>o[c]).reduce((c,s)=>c.concat(s),[]):f[e]&&!o[e]?null:(i[e]&&(r?r(e,i[e]):r!==!1&&b(`abbrev: ${e} -> ${i[e]}`),e=i[e]),o[e]&&!Array.isArray(o[e])&&(o[e]=o[e].split(/\s+/)),o[e])}Ue.exports={nopt:or,clean:Ve,parse:Ie,validate:te,resolveShort:Fe,typeDefs:rr}});var ne=A((N,Ke)=>{var re=We(),ir=ee();Ke.exports=N=ar;N.clean=cr;N.typeDefs=ir;N.lib=re;function ar(e,t,r=process.argv,n=2){return re.nopt(r.slice(n),{types:e||{},shorthands:t||{},typeDefs:N.typeDefs,invalidHandler:N.invalidHandler,unknownHandler:N.unknownHandler,abbrevHandler:N.abbrevHandler})}function cr(e,t,r=N.typeDefs){return re.clean(e,{types:t||{},typeDefs:r,invalidHandler:N.invalidHandler,unknownHandler:N.unknownHandler,abbrevHandler:N.abbrevHandler})}});var Je=A((Zr,Ge)=>{var lr=Symbol("proc-log.meta");Ge.exports={META:lr,output:{LEVELS:["standard","error","buffer","flush"],KEYS:{standard:"standard",error:"error",buffer:"buffer",flush:"flush"},standard:function(...e){return process.emit("output","standard",...e)},error:function(...e){return process.emit("output","error",...e)},buffer:function(...e){return process.emit("output","buffer",...e)},flush:function(...e){return process.emit("output","flush",...e)}},log:{LEVELS:["notice","error","warn","info","verbose","http","silly","timing","pause","resume"],KEYS:{notice:"notice",error:"error",warn:"warn",info:"info",verbose:"verbose",http:"http",silly:"silly",timing:"timing",pause:"pause",resume:"resume"},error:function(...e){return process.emit("log","error",...e)},notice:function(...e){return process.emit("log","notice",...e)},warn:function(...e){return process.emit("log","warn",...e)},info:function(...e){return process.emit("log","info",...e)},verbose:function(...e){return process.emit("log","verbose",...e)},http:function(...e){return process.emit("log","http",...e)},silly:function(...e){return process.emit("log","silly",...e)},timing:function(...e){return process.emit("log","timing",...e)},pause:function(){return process.emit("log","pause")},resume:function(){return process.emit("log","resume")}},time:{LEVELS:["start","end"],KEYS:{start:"start",end:"end"},start:function(e,t){process.emit("time","start",e);function r(){return process.emit("time","end",e)}if(typeof t=="function"){let n=t();return n&&n.finally?n.finally(r):(r(),n)}return r},end:function(e){return process.emit("time","end",e)}},input:{LEVELS:["start","end","read"],KEYS:{start:"start",end:"end",read:"read"},start:function(...e){let t;typeof e[0]=="function"&&(t=e.shift()),process.emit("input","start",...e);function r(){return process.emit("input","end",...e)}if(typeof t=="function"){let n=t();return n&&n.finally?n.finally(r):(r(),n)}return r},end:function(...e){return process.emit("input","end",...e)},read:function(...e){let t,r,n=new Promise((o,i)=>{t=o,r=i});return process.emit("input","read",t,r,...e),n}}}});var F=A((en,oe)=>{var I=ne(),fr=I.typeDefs.path.validate,ur=(e,t,r)=>typeof r!="string"?!1:fr(e,t,r);oe.exports={...I.typeDefs,path:{...I.typeDefs.path,validate:ur}};I.typeDefs=oe.exports});var Qe=A((tn,Ye)=>{var{URL:Xe}=E("node:url");Ye.exports=e=>{let t=new Xe(e),r=`${t.protocol}//${t.host}${t.pathname}`,n=new Xe(".",r);return`//${n.host}${n.pathname}`}});var se=A((rn,ze)=>{var pr=/(?e.replace(pr,(r,n,o,i)=>{let f=i==="?"?"":`\${${o}}`,a=t[o]!==void 0?t[o]:f;return n.length%2?r.slice((n.length+1)/2):n.slice(n.length/2)+a})});var tt=A((nn,et)=>{var U=F(),hr=se(),{resolve:Ze}=E("node:path"),ie=(e,t,r,n=!1)=>{if(typeof e!="string"&&!Array.isArray(e))return e;let{platform:o,types:i,home:f,env:a}=r,c=new Set([].concat(i[t])),s=c.has(U.path.type),l=c.has(U.Boolean.type),u=s||c.has(U.String.type),d=c.has(U.Number.type),p=!n&&c.has(Array);if(Array.isArray(e))return p?e.map(y=>ie(y,t,r,!0)):e;if(e=e.trim(),p)return ie(e.split(` + +`),t,r);if(l&&!u&&e==="")return!0;if(!u&&!s&&!d)switch(e){case"true":return!0;case"false":return!1;case"null":return null;case"undefined":return}return e=hr(e,a),s&&((o==="win32"?/^~(\/|\\)/:/^~\//).test(e)&&f?e=Ze(f,e.slice(2)):e=Ze(e)),d&&!isNaN(e)&&(e=+e),e};et.exports=ie});var nt=A((on,rt)=>{var _=class{constructor(t,r){this.key=t,this.type=r.type,this.default=r.default}},{url:{type:dr},path:{type:ae}}=F(),gr={_auth:new _("_auth",{default:null,type:[null,String]}),global:new _("global",{default:!1,type:Boolean}),globalconfig:new _("globalconfig",{type:ae,default:""}),location:new _("location",{default:"user",type:["global","user","project"]}),prefix:new _("prefix",{type:ae,default:""}),registry:new _("registry",{default:"https://registry.npmjs.org/",type:dr}),userconfig:new _("userconfig",{default:"~/.npmrc",type:ae})};rt.exports=gr});var it=A((sn,st)=>{var ot=nt(),yr=(e,t={})=>{for(let[r,n]of Object.entries(e)){let o=ot[r];o&&o.flatten?o.flatten(r,e,t):(/@.*:registry$/i.test(r)||/^\/\//.test(r))&&(t[r]=n)}return t};st.exports={definitions:ot,flatten:yr}});var ct=A((an,at)=>{"use strict";var ce=class extends Error{constructor(t){let r="Invalid auth configuration found: ";r+=t.map(n=>{if(n.action==="delete")return`\`${n.key}\` is not allowed in ${n.where} config`;if(n.action==="rename")return`\`${n.from}\` must be renamed to \`${n.to}\` in ${n.where} config`}).join(", "),r+="\nPlease run `npm config fix` to repair your configuration.`",super(r),this.code="ERR_INVALID_AUTH",this.problems=t}};at.exports={ErrInvalidAuth:ce}});var pt=A((ln,ut)=>{var mr=Ce(),le=ne(),{log:W}=Je(),{resolve:fe,dirname:ue,join:lt}=E("node:path"),{homedir:br}=E("node:os"),{readFile:wr,stat:cn}=E("node:fs/promises"),pe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),xr=F(),ft=Qe(),Er=se(),vr=tt(),{definitions:jr}=it(),Ar=new Set(["global","user","project"]),he=new Set(["default","builtin",...Ar,"env"]),Or="env",de=class{#t=!1;#r="";constructor({npmPath:t,projectRoot:r,env:n=process.env,platform:o=process.platform,execPath:i=process.execPath,cwd:f=process.cwd()}){if(!r)throw new Error("must provide projectRoot option");this.#r=r;let a={},c={};for(let[u,d]of Object.entries(jr))c[u]=d.default,a[u]=d.type;this.types=a,this.defaults=c,this.npmPath=t,this.env=n,this.execPath=i,this.platform=o,this.cwd=f,this.globalPrefix=null,this.localPrefix=null,this.home=null;let s=[...he];this.data=new Map;let l=null;for(let u of s)this.data.set(u,l=new ge(l));this.data.set=()=>{throw new Error("cannot change internal config data structure")},this.data.delete=()=>{throw new Error("cannot change internal config data structure")},this.sources=new Map([]);for(let{data:u}of this.data.values())this.list.unshift(u);this.#t=!1}get list(){let t=[];for(let{data:r}of this.data.values())t.unshift(r);return t}get loaded(){return this.#t}get prefix(){return this.#e("global")?this.globalPrefix:this.localPrefix}get(t,r){if(!this.loaded)throw new Error("call config.load() before reading values");return this.#e(t,r)}#e(t,r=null){if(r!==null&&!he.has(r))throw new Error("invalid config location param: "+r);let{data:n}=this.data.get(r||Or);return r===null||pe(n,t)?n[t]:void 0}async load(){if(this.loaded)throw new Error("attempting to load npm config multiple times");this.loadDefaults(),await this.loadBuiltinConfig(),this.loadEnv(),await this.loadProjectConfig(),await this.loadUserConfig(),await this.loadGlobalConfig(),this.#t=!0,this.globalPrefix=this.get("prefix")}loadDefaults(){this.loadGlobalPrefix(),this.loadHome();let t={...this.defaults,prefix:this.globalPrefix};try{t["npm-version"]=E(lt(this.npmPath,"package.json")).version}catch{}this.#n(t,"default","default values");let{data:r}=this.data.get("default");Object.defineProperty(r,"globalconfig",{get:()=>fe(this.#e("prefix"),"etc/npmrc"),set(n){Object.defineProperty(r,"globalconfig",{value:n,configurable:!0,writable:!0,enumerable:!0})},configurable:!0,enumerable:!0})}loadHome(){this.home=this.env.HOME||br()}loadGlobalPrefix(){if(this.globalPrefix)throw new Error("cannot load default global prefix more than once");this.env.PREFIX?this.globalPrefix=this.env.PREFIX:this.platform==="win32"?this.globalPrefix=ue(this.execPath):(this.globalPrefix=ue(ue(this.execPath)),this.env.DESTDIR&&(this.globalPrefix=lt(this.env.DESTDIR,this.globalPrefix)))}loadEnv(){let t=Object.create(null);for(let[r,n]of Object.entries(this.env)){if(!/^npm_config_/i.test(r)||n==="")continue;let o=r.slice(11);o.startsWith("//")||(o=o.replace(/(?!^)_/g,"-").toLowerCase()),t[o]=n}this.#n(t,"env","environment")}get valid(){for(let[t,{valid:r}]of this.data.entries())if(r===!1||r===null&&!this.validate(t))return!1;return!0}validate(t){if(t){let r=this.data.get(t);return r[q]=!0,le.invalidHandler=(n,o,i)=>this.invalidHandler(n,o,i,r.source,t),le.clean(r.data,this.types,xr),le.invalidHandler=null,r[q]}else{let r=!0,n=[];for(let o of this.data.keys()){if(o==="default"||o==="builtin")continue;let i=this.validate(o);if(r=r&&i,["global","user","project"].includes(o)){for(let a of["_authtoken","-authtoken"])this.get(a,o)&&n.push({action:"delete",key:a,where:o});let f=ft(this.get("registry"));for(let a of["_auth","_authToken","username","_password"])this.get(a,o)&&(a==="username"&&!this.get("_password",o)?n.push({action:"delete",key:a,where:o}):a==="_password"&&!this.get("username",o)?n.push({action:"delete",key:a,where:o}):n.push({action:"rename",from:a,to:`${f}:${a}`,where:o}))}}if(n.length){let{ErrInvalidAuth:o}=ct();throw new o(n)}return r}}isDefault(t){let[r,...n]=[...he],o=this.data.get(r).data;return pe(o,t)&&n.every(i=>{let f=this.data.get(i).data;return!pe(f,t)})}invalidHandler(t,r,n,o,i){W.warn("invalid config",t+"="+JSON.stringify(r),`set in ${o}`),this.data.get(i)[q]=!1}#n(t,r,n,o=null){let i=this.data.get(r);if(i.source){let f=`double-loading "${r}" configs from ${n}, previously loaded from ${i.source}`;throw new Error(f)}if(this.sources.has(n)){let f=`double-loading config "${n}" as "${r}", previously loaded as "${this.sources.get(n)}"`;throw new Error(f)}if(i.source=n,this.sources.set(n,r),o)i.loadError=o,o.code!=="ENOENT"&&W.verbose("config",`error loading ${r} config`,o);else{i.raw=t;for(let[f,a]of Object.entries(t)){let c=Er(f,this.env),s=this.parseField(a,c);i.data[c]=s}}}parseField(t,r,n=!1){return vr(t,r,this,n)}async#o(t,r){W.silly("config",`load:file:${t}`),await wr(t,"utf8").then(n=>{let o=mr.parse(n);return r==="project"&&o.prefix&&W.error("config",`prefix cannot be changed from project config: ${t}.`),this.#n(o,r,t)},n=>this.#n(null,r,t,n))}loadBuiltinConfig(){return this.#o(fe(this.npmPath,"npmrc"),"builtin")}async loadProjectConfig(){if(await this.loadLocalPrefix(),this.#e("global")===!0||this.#e("location")==="global"){this.data.get("project").source="(global mode enabled, ignored)",this.sources.set(this.data.get("project").source,"project");return}let t=fe(this.localPrefix,".npmrc");if(t!==this.#e("userconfig"))return this.#o(t,"project");this.data.get("project").source='(same as "user" config, ignored)',this.sources.set(this.data.get("project").source,"project")}async loadLocalPrefix(){this.localPrefix=this.#r}loadUserConfig(){return this.#o(this.#e("userconfig"),"user")}loadGlobalConfig(){return this.#o(this.#e("globalconfig"),"global")}getCredentialsByURI(t){let r=ft(t),n={},o=this.get(`${r}:certfile`),i=this.get(`${r}:keyfile`);o&&i&&(n.certfile=o,n.keyfile=i);let f=this.get(`${r}:_authToken`);if(f)return n.token=f,n;let a=this.get(`${r}:username`),c=this.get(`${r}:_password`);if(a&&c){n.username=a,n.password=Buffer.from(c,"base64").toString("utf8");let l=`${n.username}:${n.password}`;return n.auth=Buffer.from(l,"utf8").toString("base64"),n}let s=this.get(`${r}:_auth`);if(s){let u=Buffer.from(s,"base64").toString("utf8").split(":");return n.username=u.shift(),n.password=u.join(":"),n.auth=s,n}return n}},K=Symbol("loadError"),q=Symbol("valid"),ge=class{#t;#r=null;#e={};constructor(t){this.#t=Object.create(t&&t.data),this[q]=!0}get data(){return this.#t}get valid(){return this[q]}set source(t){if(this.#r)throw new Error("cannot set ConfigData source more than once");this.#r=t}get source(){return this.#r}set loadError(t){if(this[K]||Object.keys(this.#e).length)throw new Error("cannot set ConfigData loadError after load");this[K]=t}get loadError(){return this[K]}set raw(t){if(Object.keys(this.#e).length||this[K])throw new Error("cannot set ConfigData raw after load");this.#e=t}get raw(){return this.#e}};ut.exports=de});var bt=A(v=>{"use strict";var ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Pr=ye(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sync=e.isexe=void 0;var t=E("node:fs"),r=E("node:fs/promises"),n=async(a,c={})=>{let{ignoreErrors:s=!1}=c;try{return i(await(0,r.stat)(a),c)}catch(l){let u=l;if(s||u.code==="EACCES")return!1;throw u}};e.isexe=n;var o=(a,c={})=>{let{ignoreErrors:s=!1}=c;try{return i((0,t.statSync)(a),c)}catch(l){let u=l;if(s||u.code==="EACCES")return!1;throw u}};e.sync=o;var i=(a,c)=>a.isFile()&&f(a,c),f=(a,c)=>{let s=c.uid??process.getuid?.(),l=c.groups??process.getgroups?.()??[],u=c.gid??process.getgid?.()??l[0];if(s===void 0||u===void 0)throw new Error("cannot get uid or gid");let d=new Set([u,...l]),p=a.mode,y=a.uid,w=a.gid,h=parseInt("100",8),O=parseInt("010",8),x=parseInt("001",8),g=h|O;return!!(p&x||p&O&&d.has(w)||p&h&&y===s||p&g&&s===0)}}),Nr=ye(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sync=e.isexe=void 0;var t=E("node:fs"),r=E("node:fs/promises"),n=E("node:path"),o=async(c,s={})=>{let{ignoreErrors:l=!1}=s;try{return a(await(0,r.stat)(c),c,s)}catch(u){let d=u;if(l||d.code==="EACCES")return!1;throw d}};e.isexe=o;var i=(c,s={})=>{let{ignoreErrors:l=!1}=s;try{return a((0,t.statSync)(c),c,s)}catch(u){let d=u;if(l||d.code==="EACCES")return!1;throw d}};e.sync=i;var f=(c,s)=>{let{pathExt:l=process.env.PATHEXT||""}=s,u=l.split(n.delimiter);if(u.indexOf("")!==-1)return!0;for(let d of u){let p=d.toLowerCase(),y=c.substring(c.length-p.length).toLowerCase();if(p&&y===p)return!0}return!1},a=(c,s,l)=>c.isFile()&&f(s,l)}),Sr=ye(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})}),ht=v&&v.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),$r=v&&v.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),dt=v&&v.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),o=0;o{var{isexe:Lr,sync:Tr}=bt(),{join:kr,delimiter:qr,sep:wt,posix:xt}=E("path"),Et=process.platform==="win32",vt=new RegExp(`[${xt.sep}${wt===xt.sep?"":wt}]`.replace(/(\\)/g,"\\$1")),Dr=new RegExp(`^\\.${vt.source}`),jt=e=>Object.assign(new Error(`not found: ${e}`),{code:"ENOENT"}),At=(e,{path:t=process.env.PATH,pathExt:r=process.env.PATHEXT,delimiter:n=qr})=>{let o=e.match(vt)?[""]:[...Et?[process.cwd()]:[],...(t||"").split(n)];if(Et){let i=r||[".EXE",".CMD",".BAT",".COM"].join(n),f=i.split(n).flatMap(a=>[a,a.toLowerCase()]);return e.includes(".")&&f[0]!==""&&f.unshift(""),{pathEnv:o,pathExt:f,pathExtExe:i}}return{pathEnv:o,pathExt:[""]}},Ot=(e,t)=>{let r=/^".*"$/.test(e)?e.slice(1,-1):e;return(!r&&Dr.test(t)?t.slice(0,2):"")+kr(r,t)},Pt=async(e,t={})=>{let{pathEnv:r,pathExt:n,pathExtExe:o}=At(e,t),i=[];for(let f of r){let a=Ot(f,e);for(let c of n){let s=a+c;if(await Lr(s,{pathExt:o,ignoreErrors:!0})){if(!t.all)return s;i.push(s)}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw jt(e)},Mr=(e,t={})=>{let{pathEnv:r,pathExt:n,pathExtExe:o}=At(e,t),i=[];for(let f of r){let a=Ot(f,e);for(let c of n){let s=a+c;if(Tr(s,{pathExt:o,ignoreErrors:!0})){if(!t.all)return s;i.push(s)}}}if(t.all&&i.length)return i;if(t.nothrow)return null;throw jt(e)};Nt.exports=Pt;Pt.sync=Mr});var Lt={};Ee(Lt,{loadNpmrc:()=>Rr});async function Rr(e){let{verboseLog:t,...r}=e,n=r.npmPath;try{n??=Ct.default.realpathSync(_t.default.sync("npm"))}catch{k(`Couldn't find "npm" executable to help read the config`)}let o=["silly","verbose","info","notice","warn","error"],i=o.indexOf(t.verbose?"silly":"warn"),f=(a,...c)=>{o.indexOf(a)>=i&&Ae(a==="error"||a==="warn"?a:"log",[`[${a}]`,...c].join(" "))};process.on("log",f);try{let a=new $t.default({...r,npmPath:n});if(await a.load(),a.validate(),t.verbose){t("Loaded npm config successfully. Config sources:");for(let[s,l]of a.sources.entries())t(` ${l}: ${s}`);let c=Object.keys(a.data.get("env")?.raw||{}).sort();if(c.length){t("Config loaded from environment variables:");for(let s of c)t(` ${s}`)}}return a}catch(a){k(a)}finally{process.off("log",f)}}var $t,Ct,_t,Tt=xe(()=>{"use strict";$t=J(pt()),Ct=J(E("node:fs")),_t=J(St());H()});var Fr={};Ee(Fr,{default:()=>Ir});var we=E("@yarnpkg/core");var qt=E("@yarnpkg/fslib");H();function Oe(e){let{npmrc:t,verboseLog:r,registry:n}=e;r(`Looking up credentials for registry ${n}`);let o=t.getCredentialsByURI(n);if(Object.keys(o).length===0&&!n.endsWith("/")&&(o=t.getCredentialsByURI(`${n}/`)),(o.certfile||o.keyfile)&&k(`This plugin does not support certfile or keyfile auth (for registry "${n}")`),"token"in o)return r("Using npm _authToken"),`Bearer ${o.token}`;if("auth"in o)return r("Using npm _password or _auth"),`Basic ${o.auth}`;r("No matching npm credentials found; using yarn's auth header")}var me=new Map,kt;async function Dt(e){let{currentHeader:t,registry:r,verboseLog:n}=e;if(!e.projectCwd)return n("No projectCwd; skipping .npmrc auth header",!0),t;kt??=(async()=>{let f=qt.npath.fromPortablePath(e.projectCwd);n(`Loading .npmrc for projectRoot=${f}`);let{loadNpmrc:a}=await Promise.resolve().then(()=>(Tt(),Lt));return await a({projectRoot:f,verboseLog:n})})();let o=await kt;if(me.has(r))return me.get(r)??t;let i=Oe({npmrc:o,verboseLog:n,registry:r});return me.set(r,i),i??t}H();var Hr={npmrcAuthEnabled:{description:"Attempt to read auth info from .npmrc for all registry requests",type:we.SettingsType.BOOLEAN,default:!1},npmrcAuthVerbose:{description:"Enable verbose logging",type:we.SettingsType.BOOLEAN,default:!1}},be;function Mt(e,t){return e.get(t)}var Br=async(e,t,{configuration:r})=>(be??=je(Mt(r,"npmrcAuthVerbose")),Mt(r,"npmrcAuthEnabled")?await Dt({currentHeader:e,registry:t,projectCwd:r.projectCwd,verboseLog:be}):(be("npmrcAuthEnabled is false/unset; skipping .npmrc auth header",!0),e)),Vr={hooks:{getNpmAuthenticationHeader:Br},configuration:Hr},Ir=Vr;return Wt(Fr);})(); +return plugin; +} +}; diff --git a/.yarnrc.yml b/.yarnrc.yml index ef20159f95..6155d8ac8d 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -1,6 +1,3 @@ -approvedGitRepositories: - - "**" - catalog: "@babel/core": ^7.20.0 "@babel/plugin-proposal-private-property-in-object": ^7.21.11 @@ -271,6 +268,9 @@ nodeLinker: pnpm npmMinimalAgeGate: 7d +npmPreapprovedPackages: + - "@microsoft/esrp-npm-release" + packageExtensions: "@svgr/core@*": dependencies: @@ -321,6 +321,9 @@ packageExtensions: react-native-svg@*: dependencies: buffer: "*" + zx@*: + dependencies: + "@types/fs-extra": "*" plugins: - path: .yarn/plugins/@yarnpkg/plugin-compat.cjs @@ -331,5 +334,8 @@ plugins: - checksum: 8d8252c376e41a67ca509b2778f3fb92164aa91828459ae8a6aa0e13f1b6f9843586d0983ba9a200f6d813d37efc171474c8dbc85b0dff01df56c0d476c238ce path: .yarn/plugins/@rnx-kit/yarn-plugin-ignore.cjs spec: "https://raw.githubusercontent.com/microsoft/rnx-kit/main/incubator/yarn-plugin-ignore/dist/yarn-plugin-ignore.cjs" + - checksum: 5ea21341a477907c298afb531f4a0b30f4347e893a3dc9b72c74645a38bb99e760ba8eca5bf1f13cc36d0cdf4ee208df7d96229e54bf604222b3151e5b2b0565 + path: .yarn/plugins/@yarnpkg/plugin-npmrc.cjs + spec: "https://raw.githubusercontent.com/microsoft/beachball/yarn-plugin-npmrc_v0.5.1/yarn-plugins/npmrc/dist/plugin.js" yarnPath: .yarn/releases/yarn-4.18.0.cjs diff --git a/AGENTS.md b/AGENTS.md index 3255934c46..31e85e437a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -283,7 +283,7 @@ Components require `ThemeProvider` from `@fluentui-react-native/design/theming` - Changesets config in `.changeset/config.json` - Major versions are disallowed (validated in CI via `.github/scripts/validate-changesets.mts`) - Version bump PRs are created automatically by GitHub Actions; `yarn changeset:version` applies version bumps -- Publishing happens in Azure Pipelines using `changeset publish` +- Publishing happens in Azure Pipelines using `.ado/azure-pipelines.publish.yml` ## Important Notes diff --git a/lage.config.mjs b/lage.config.mjs index 827c8caae6..8a6bcd5932 100644 --- a/lage.config.mjs +++ b/lage.config.mjs @@ -1,3 +1,5 @@ +import path from 'node:path'; + /** @type {import('lage').ConfigOptions} */ const config = { npmClient: 'yarn', @@ -79,26 +81,7 @@ const config = { type: 'worker', options: { worker: 'scripts/src/worker/pack.mts', - outputDir: '_packed', - }, - cache: false, - }, - publish: { - dependsOn: ['^publish'], - type: 'worker', - options: { - worker: 'scripts/src/worker/publish.mts', - outputDir: '_packed', - }, - cache: false, - }, - 'publish:dry-run': { - dependsOn: ['^publish:dry-run'], - type: 'worker', - options: { - worker: 'scripts/src/worker/publish.mts', - outputDir: '_packed', - dryRun: true, + outputDir: path.join(process.env.BUILD_STAGINGDIRECTORY || import.meta.dirname, '_packed'), }, cache: false, }, diff --git a/packages/components/Callout/NuGet.config b/packages/components/Callout/NuGet.config index fe459fedd6..cea979d2bd 100644 --- a/packages/components/Callout/NuGet.config +++ b/packages/components/Callout/NuGet.config @@ -3,9 +3,8 @@ - - + diff --git a/packages/dependency-profiles/package.json b/packages/dependency-profiles/package.json index a96a034c66..d9da53574f 100644 --- a/packages/dependency-profiles/package.json +++ b/packages/dependency-profiles/package.json @@ -25,7 +25,7 @@ "react-native-svg": ">=15.4.0 <15.13.0", "react-native-windows": "^0.81.0", "semver": "^7.7.3", - "workspace-tools": "^0.26.3" + "workspace-tools": "^0.42.0" }, "peerDependencies": { "@fluentui-react-native/adapters": "*", diff --git a/scripts/esrp-npm-release-temp/index.mjs b/scripts/esrp-npm-release-temp/index.mjs new file mode 100644 index 0000000000..25677dd852 --- /dev/null +++ b/scripts/esrp-npm-release-temp/index.mjs @@ -0,0 +1,56467 @@ +/** @noprettier - generated file (requires checkIgnorePragma option) */ +// @ts-nocheck +/* eslint-disable */ +import { createRequire as esbuildNodeHelpersCreateRequire } from 'node:module'; +var require = esbuildNodeHelpersCreateRequire(import.meta.url); +var __filename = import.meta.filename; +var __dirname = import.meta.dirname; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); +var __commonJS = (cb, mod) => function __require2() { + try { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + } catch (e) { + throw mod = 0, e; + } +}; +var __export = (target, all) => { + for (var name3 in all) + __defProp(target, name3, { get: all[name3], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// ../../node_modules/ms/index.js +var require_ms = __commonJS({ + "../../node_modules/ms/index.js"(exports2, module) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse2(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse2(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + __name(parse2, "parse"); + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + __name(fmtShort, "fmtShort"); + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + __name(fmtLong, "fmtLong"); + function plural(ms, msAbs, n, name3) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name3 + (isPlural ? "s" : ""); + } + __name(plural, "plural"); + } +}); + +// ../../node_modules/debug/src/common.js +var require_common = __commonJS({ + "../../node_modules/debug/src/common.js"(exports2, module) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable2; + createDebug.enable = enable2; + createDebug.enabled = enabled2; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy2; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + __name(selectColor, "selectColor"); + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match = formatter.call(self2, val); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + __name(debug, "debug"); + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend2; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: /* @__PURE__ */ __name(() => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, "get"), + set: /* @__PURE__ */ __name((v) => { + enableOverride = v; + }, "set") + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + __name(createDebug, "createDebug"); + function extend2(namespace, delimiter2) { + const newDebug = createDebug(this.namespace + (typeof delimiter2 === "undefined" ? ":" : delimiter2) + namespace); + newDebug.log = this.log; + return newDebug; + } + __name(extend2, "extend"); + function enable2(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + __name(enable2, "enable"); + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + __name(matchesTemplate, "matchesTemplate"); + function disable2() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + __name(disable2, "disable"); + function enabled2(name3) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name3, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name3, ns)) { + return true; + } + } + return false; + } + __name(enabled2, "enabled"); + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + __name(coerce, "coerce"); + function destroy2() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + __name(destroy2, "destroy"); + createDebug.enable(createDebug.load()); + return createDebug; + } + __name(setup, "setup"); + module.exports = setup; + } +}); + +// ../../node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "../../node_modules/debug/src/browser.js"(exports2, module) { + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.storage = localstorage(); + exports2.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports2.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 useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + __name(useColors, "useColors"); + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + __name(formatArgs, "formatArgs"); + exports2.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports2.storage.setItem("debug", namespaces); + } else { + exports2.storage.removeItem("debug"); + } + } catch (error) { + } + } + __name(save, "save"); + function load() { + let r; + try { + r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + __name(load, "load"); + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + __name(localstorage, "localstorage"); + module.exports = require_common()(exports2); + var { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + } +}); + +// ../../node_modules/has-flag/index.js +var require_has_flag = __commonJS({ + "../../node_modules/has-flag/index.js"(exports2, module) { + "use strict"; + module.exports = (flag, argv = process.argv) => { + const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix2 + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; + } +}); + +// ../../node_modules/supports-color/index.js +var require_supports_color = __commonJS({ + "../../node_modules/supports-color/index.js"(exports2, module) { + "use strict"; + var os2 = __require("os"); + var tty = __require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var forceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + forceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + forceColor = 1; + } + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + forceColor = 1; + } else if (env.FORCE_COLOR === "false") { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + __name(translateLevel, "translateLevel"); + function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os2.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version4 = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version4 >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + __name(supportsColor, "supportsColor"); + function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); + } + __name(getSupportLevel, "getSupportLevel"); + module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) + }; + } +}); + +// ../../node_modules/debug/src/node.js +var require_node = __commonJS({ + "../../node_modules/debug/src/node.js"(exports2, module) { + var tty = __require("tty"); + var util3 = __require("util"); + exports2.init = init; + exports2.log = log2; + exports2.formatArgs = formatArgs; + exports2.save = save; + exports2.load = load; + exports2.useColors = useColors; + exports2.destroy = util3.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports2.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports2.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 (error) { + } + exports2.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + __name(useColors, "useColors"); + function formatArgs(args) { + const { namespace: name3, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix2 = ` ${colorCode};1m${name3} \x1B[0m`; + args[0] = prefix2 + args[0].split("\n").join("\n" + prefix2); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name3 + " " + args[0]; + } + } + __name(formatArgs, "formatArgs"); + function getDate() { + if (exports2.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + __name(getDate, "getDate"); + function log2(...args) { + return process.stderr.write(util3.formatWithOptions(exports2.inspectOpts, ...args) + "\n"); + } + __name(log2, "log"); + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + __name(save, "save"); + function load() { + return process.env.DEBUG; + } + __name(load, "load"); + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports2.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]]; + } + } + __name(init, "init"); + module.exports = require_common()(exports2); + var { formatters } = module.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts); + }; + } +}); + +// ../../node_modules/debug/src/index.js +var require_src = __commonJS({ + "../../node_modules/debug/src/index.js"(exports2, module) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module.exports = require_browser(); + } else { + module.exports = require_node(); + } + } +}); + +// ../../node_modules/agent-base/dist/helpers.js +var require_helpers = __commonJS({ + "../../node_modules/agent-base/dist/helpers.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: /* @__PURE__ */ __name(function() { + return m[k]; + }, "get") }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.req = exports2.json = exports2.toBuffer = void 0; + var http2 = __importStar(__require("http")); + var https2 = __importStar(__require("https")); + async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + __name(toBuffer, "toBuffer"); + exports2.toBuffer = toBuffer; + async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString("utf8"); + try { + return JSON.parse(str); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } + } + __name(json, "json"); + exports2.json = json; + function req(url2, opts = {}) { + const href = typeof url2 === "string" ? url2 : url2.href; + const req2 = (href.startsWith("https:") ? https2 : http2).request(url2, opts); + const promise = new Promise((resolve, reject) => { + req2.once("response", resolve).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; + } + __name(req, "req"); + exports2.req = req; + } +}); + +// ../../node_modules/agent-base/dist/index.js +var require_dist = __commonJS({ + "../../node_modules/agent-base/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: /* @__PURE__ */ __name(function() { + return m[k]; + }, "get") }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Agent = void 0; + var net = __importStar(__require("net")); + var http2 = __importStar(__require("http")); + var https_1 = __require("https"); + __exportStar(require_helpers(), exports2); + var INTERNAL = /* @__PURE__ */ Symbol("AgentBaseInternalState"); + var Agent = class extends http2.Agent { + static { + __name(this, "Agent"); + } + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; + } + } + const { stack } = new Error(); + if (typeof stack !== "string") + return false; + return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name3) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name3]) { + this.sockets[name3] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name3].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name3, socket) { + if (!this.sockets[name3] || socket === null) { + return; + } + const sockets = this.sockets[name3]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name3]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name3 = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name3); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name3, fakeSocket); + if (socket instanceof http2.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name3, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = void 0; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); + } + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } + }; + exports2.Agent = Agent; + } +}); + +// ../../node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS({ + "../../node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) { + "use strict"; + var __importDefault = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.parseProxyResponse = void 0; + var debug_1 = __importDefault(require_src()); + var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + let buffersLength = 0; + const buffers = []; + function read2() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read2); + } + __name(read2, "read"); + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read2); + } + __name(cleanup, "cleanup"); + function onend() { + cleanup(); + debug("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + __name(onend, "onend"); + function onerror(err) { + cleanup(); + debug("onerror %o", err); + reject(err); + } + __name(onerror, "onerror"); + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf("\r\n\r\n"); + if (endOfHeaders === -1) { + debug("have not received end of HTTP headers yet..."); + read2(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n"); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + __name(ondata, "ondata"); + socket.on("error", onerror); + socket.on("end", onend); + read2(); + }); + } + __name(parseProxyResponse, "parseProxyResponse"); + exports2.parseProxyResponse = parseProxyResponse; + } +}); + +// ../../node_modules/https-proxy-agent/dist/index.js +var require_dist2 = __commonJS({ + "../../node_modules/https-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: /* @__PURE__ */ __name(function() { + return m[k]; + }, "get") }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + var __importDefault = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpsProxyAgent = void 0; + var net = __importStar(__require("net")); + var tls = __importStar(__require("tls")); + var assert_1 = __importDefault(__require("assert")); + var debug_1 = __importDefault(require_src()); + var agent_base_1 = require_dist(); + var url_1 = __require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = /* @__PURE__ */ __name((options) => { + if (options.servername === void 0 && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; + } + return options; + }, "setServernameFromNonIpHost"); + var HttpsProxyAgent2 = class extends agent_base_1.Agent { + static { + __name(this, "HttpsProxyAgent"); + } + constructor(proxy, opts) { + super(opts); + this.options = { path: void 0 }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + */ + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); + } + let socket; + if (proxy.protocol === "https:") { + debug("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name3 of Object.keys(headers)) { + payload += `${name3}: ${headers[name3]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; + } + }; + HttpsProxyAgent2.protocols = ["http", "https"]; + exports2.HttpsProxyAgent = HttpsProxyAgent2; + function resume(socket) { + socket.resume(); + } + __name(resume, "resume"); + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + __name(omit, "omit"); + } +}); + +// ../../node_modules/http-proxy-agent/dist/index.js +var require_dist3 = __commonJS({ + "../../node_modules/http-proxy-agent/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: /* @__PURE__ */ __name(function() { + return m[k]; + }, "get") }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }); + var __importStar = exports2 && exports2.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; + }; + var __importDefault = exports2 && exports2.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.HttpProxyAgent = void 0; + var net = __importStar(__require("net")); + var tls = __importStar(__require("tls")); + var debug_1 = __importDefault(require_src()); + var events_1 = __require("events"); + var agent_base_1 = require_dist(); + var url_1 = __require("url"); + var debug = (0, debug_1.default)("http-proxy-agent"); + var HttpProxyAgent2 = class extends agent_base_1.Agent { + static { + __name(this, "HttpProxyAgent"); + } + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug("Creating new HttpProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ...opts ? omit(opts, "headers") : null, + host, + port + }; + } + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? "https:" : "http:"; + const hostname = req.getHeader("host") || "localhost"; + const base = `${protocol}//${hostname}`; + const url2 = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url2.port = String(opts.port); + } + req.path = String(url2); + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name3 of Object.keys(headers)) { + const value = headers[name3]; + if (value) { + req.setHeader(name3, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes("://")) { + this.setRequestProps(req, opts); + } + let first; + let endOfHeaders; + debug("Regenerating stored HTTP header string for request"); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug("Patching connection write() output buffer with updated header"); + first = req.outputData[0].data; + endOfHeaders = first.indexOf("\r\n\r\n") + 4; + req.outputData[0].data = req._header + first.substring(endOfHeaders); + debug("Output buffer: %o", req.outputData[0].data); + } + let socket; + if (this.proxy.protocol === "https:") { + debug("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(this.connectOpts); + } else { + debug("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + await (0, events_1.once)(socket, "connect"); + return socket; + } + }; + HttpProxyAgent2.protocols = ["http", "https"]; + exports2.HttpProxyAgent = HttpProxyAgent2; + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + __name(omit, "omit"); + } +}); + +// ../../node_modules/@azure/core-tracing/dist/commonjs/state-cjs.js +var require_state_cjs = __commonJS({ + "../../node_modules/@azure/core-tracing/dist/commonjs/state-cjs.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + instrumenterImplementation: void 0 + }; + } +}); + +// ../../node_modules/@azure/core-client/dist/commonjs/state-cjs.js +var require_state_cjs2 = __commonJS({ + "../../node_modules/@azure/core-client/dist/commonjs/state-cjs.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.state = void 0; + exports2.state = { + operationRequestMap: /* @__PURE__ */ new WeakMap() + }; + } +}); + +// ../../node_modules/buffer-crc32/dist/index.cjs +var require_dist4 = __commonJS({ + "../../node_modules/buffer-crc32/dist/index.cjs"(exports2, module) { + "use strict"; + function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; + } + __name(getDefaultExportFromCjs, "getDefaultExportFromCjs"); + var CRC_TABLE = new Int32Array([ + 0, + 1996959894, + 3993919788, + 2567524794, + 124634137, + 1886057615, + 3915621685, + 2657392035, + 249268274, + 2044508324, + 3772115230, + 2547177864, + 162941995, + 2125561021, + 3887607047, + 2428444049, + 498536548, + 1789927666, + 4089016648, + 2227061214, + 450548861, + 1843258603, + 4107580753, + 2211677639, + 325883990, + 1684777152, + 4251122042, + 2321926636, + 335633487, + 1661365465, + 4195302755, + 2366115317, + 997073096, + 1281953886, + 3579855332, + 2724688242, + 1006888145, + 1258607687, + 3524101629, + 2768942443, + 901097722, + 1119000684, + 3686517206, + 2898065728, + 853044451, + 1172266101, + 3705015759, + 2882616665, + 651767980, + 1373503546, + 3369554304, + 3218104598, + 565507253, + 1454621731, + 3485111705, + 3099436303, + 671266974, + 1594198024, + 3322730930, + 2970347812, + 795835527, + 1483230225, + 3244367275, + 3060149565, + 1994146192, + 31158534, + 2563907772, + 4023717930, + 1907459465, + 112637215, + 2680153253, + 3904427059, + 2013776290, + 251722036, + 2517215374, + 3775830040, + 2137656763, + 141376813, + 2439277719, + 3865271297, + 1802195444, + 476864866, + 2238001368, + 4066508878, + 1812370925, + 453092731, + 2181625025, + 4111451223, + 1706088902, + 314042704, + 2344532202, + 4240017532, + 1658658271, + 366619977, + 2362670323, + 4224994405, + 1303535960, + 984961486, + 2747007092, + 3569037538, + 1256170817, + 1037604311, + 2765210733, + 3554079995, + 1131014506, + 879679996, + 2909243462, + 3663771856, + 1141124467, + 855842277, + 2852801631, + 3708648649, + 1342533948, + 654459306, + 3188396048, + 3373015174, + 1466479909, + 544179635, + 3110523913, + 3462522015, + 1591671054, + 702138776, + 2966460450, + 3352799412, + 1504918807, + 783551873, + 3082640443, + 3233442989, + 3988292384, + 2596254646, + 62317068, + 1957810842, + 3939845945, + 2647816111, + 81470997, + 1943803523, + 3814918930, + 2489596804, + 225274430, + 2053790376, + 3826175755, + 2466906013, + 167816743, + 2097651377, + 4027552580, + 2265490386, + 503444072, + 1762050814, + 4150417245, + 2154129355, + 426522225, + 1852507879, + 4275313526, + 2312317920, + 282753626, + 1742555852, + 4189708143, + 2394877945, + 397917763, + 1622183637, + 3604390888, + 2714866558, + 953729732, + 1340076626, + 3518719985, + 2797360999, + 1068828381, + 1219638859, + 3624741850, + 2936675148, + 906185462, + 1090812512, + 3747672003, + 2825379669, + 829329135, + 1181335161, + 3412177804, + 3160834842, + 628085408, + 1382605366, + 3423369109, + 3138078467, + 570562233, + 1426400815, + 3317316542, + 2998733608, + 733239954, + 1555261956, + 3268935591, + 3050360625, + 752459403, + 1541320221, + 2607071920, + 3965973030, + 1969922972, + 40735498, + 2617837225, + 3943577151, + 1913087877, + 83908371, + 2512341634, + 3803740692, + 2075208622, + 213261112, + 2463272603, + 3855990285, + 2094854071, + 198958881, + 2262029012, + 4057260610, + 1759359992, + 534414190, + 2176718541, + 4139329115, + 1873836001, + 414664567, + 2282248934, + 4279200368, + 1711684554, + 285281116, + 2405801727, + 4167216745, + 1634467795, + 376229701, + 2685067896, + 3608007406, + 1308918612, + 956543938, + 2808555105, + 3495958263, + 1231636301, + 1047427035, + 2932959818, + 3654703836, + 1088359270, + 936918e3, + 2847714899, + 3736837829, + 1202900863, + 817233897, + 3183342108, + 3401237130, + 1404277552, + 615818150, + 3134207493, + 3453421203, + 1423857449, + 601450431, + 3009837614, + 3294710456, + 1567103746, + 711928724, + 3020668471, + 3272380065, + 1510334235, + 755167117 + ]); + function ensureBuffer(input) { + if (Buffer.isBuffer(input)) { + return input; + } + if (typeof input === "number") { + return Buffer.alloc(input); + } else if (typeof input === "string") { + return Buffer.from(input); + } else { + throw new Error("input must be buffer, number, or string, received " + typeof input); + } + } + __name(ensureBuffer, "ensureBuffer"); + function bufferizeInt(num) { + const tmp = ensureBuffer(4); + tmp.writeInt32BE(num, 0); + return tmp; + } + __name(bufferizeInt, "bufferizeInt"); + function _crc32(buf, previous) { + buf = ensureBuffer(buf); + if (Buffer.isBuffer(previous)) { + previous = previous.readUInt32BE(0); + } + let crc = ~~previous ^ -1; + for (var n = 0; n < buf.length; n++) { + crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8; + } + return crc ^ -1; + } + __name(_crc32, "_crc32"); + function crc32() { + return bufferizeInt(_crc32.apply(null, arguments)); + } + __name(crc32, "crc32"); + crc32.signed = function() { + return _crc32.apply(null, arguments); + }; + crc32.unsigned = function() { + return _crc32.apply(null, arguments) >>> 0; + }; + var bufferCrc32 = crc32; + var index = /* @__PURE__ */ getDefaultExportFromCjs(bufferCrc32); + module.exports = index; + } +}); + +// ../../node_modules/yazl/index.js +var require_yazl = __commonJS({ + "../../node_modules/yazl/index.js"(exports2) { + var fs6 = __require("fs"); + var Transform2 = __require("stream").Transform; + var PassThrough = __require("stream").PassThrough; + var zlib2 = __require("zlib"); + var util3 = __require("util"); + var EventEmitter3 = __require("events").EventEmitter; + var errorMonitor = __require("events").errorMonitor; + var crc32 = require_dist4(); + exports2.ZipFile = ZipFile; + exports2.dateToDosDateTime = dateToDosDateTime; + util3.inherits(ZipFile, EventEmitter3); + function ZipFile() { + this.outputStream = new PassThrough(); + this.entries = []; + this.outputStreamCursor = 0; + this.ended = false; + this.allDone = false; + this.forceZip64Eocd = false; + this.errored = false; + this.on(errorMonitor, function() { + this.errored = true; + }); + } + __name(ZipFile, "ZipFile"); + ZipFile.prototype.addFile = function(realPath, metadataPath, options) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, false); + if (options == null) options = {}; + if (shouldIgnoreAdding(self2)) return; + var entry = new Entry(metadataPath, false, options); + self2.entries.push(entry); + fs6.stat(realPath, function(err, stats) { + if (err) return self2.emit("error", err); + if (!stats.isFile()) return self2.emit("error", new Error("not a file: " + realPath)); + entry.uncompressedSize = stats.size; + if (options.mtime == null) entry.setLastModDate(stats.mtime); + if (options.mode == null) entry.setFileAttributesMode(stats.mode); + entry.setFileDataPumpFunction(function() { + var readStream = fs6.createReadStream(realPath); + entry.state = Entry.FILE_DATA_IN_PROGRESS; + readStream.on("error", function(err2) { + self2.emit("error", err2); + }); + pumpFileDataReadStream(self2, entry, readStream); + }); + pumpEntries(self2); + }); + }; + ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) { + this.addReadStreamLazy(metadataPath, options, function(cb) { + cb(null, readStream); + }); + }; + ZipFile.prototype.addReadStreamLazy = function(metadataPath, options, getReadStreamFunction) { + var self2 = this; + if (typeof options === "function") { + getReadStreamFunction = options; + options = null; + } + if (options == null) options = {}; + metadataPath = validateMetadataPath(metadataPath, false); + if (shouldIgnoreAdding(self2)) return; + var entry = new Entry(metadataPath, false, options); + self2.entries.push(entry); + entry.setFileDataPumpFunction(function() { + entry.state = Entry.FILE_DATA_IN_PROGRESS; + getReadStreamFunction(function(err, readStream) { + if (err) return self2.emit("error", err); + pumpFileDataReadStream(self2, entry, readStream); + }); + }); + pumpEntries(self2); + }; + ZipFile.prototype.addBuffer = function(buffer2, metadataPath, options) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, false); + if (buffer2.length > 1073741823) throw new Error("buffer too large: " + buffer2.length + " > 1073741823"); + if (options == null) options = {}; + if (options.size != null) throw new Error("options.size not allowed"); + if (shouldIgnoreAdding(self2)) return; + var entry = new Entry(metadataPath, false, options); + entry.uncompressedSize = buffer2.length; + entry.crc32 = crc32.unsigned(buffer2); + entry.crcAndFileSizeKnown = true; + self2.entries.push(entry); + if (entry.compressionLevel === 0) { + setCompressedBuffer(buffer2); + } else { + zlib2.deflateRaw(buffer2, { level: entry.compressionLevel }, function(err, compressedBuffer) { + setCompressedBuffer(compressedBuffer); + }); + } + function setCompressedBuffer(compressedBuffer) { + entry.compressedSize = compressedBuffer.length; + entry.setFileDataPumpFunction(function() { + writeToOutputStream(self2, compressedBuffer); + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + setImmediate(function() { + pumpEntries(self2); + }); + }); + pumpEntries(self2); + } + __name(setCompressedBuffer, "setCompressedBuffer"); + }; + ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) { + var self2 = this; + metadataPath = validateMetadataPath(metadataPath, true); + if (options == null) options = {}; + if (options.size != null) throw new Error("options.size not allowed"); + if (options.compress != null) throw new Error("options.compress not allowed"); + if (options.compressionLevel != null) throw new Error("options.compressionLevel not allowed"); + if (shouldIgnoreAdding(self2)) return; + var entry = new Entry(metadataPath, true, options); + self2.entries.push(entry); + entry.setFileDataPumpFunction(function() { + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + pumpEntries(self2); + }); + pumpEntries(self2); + }; + var eocdrSignatureBuffer = bufferFrom([80, 75, 5, 6]); + ZipFile.prototype.end = function(options, calculatedTotalSizeCallback) { + if (typeof options === "function") { + calculatedTotalSizeCallback = options; + options = null; + } + if (options == null) options = {}; + if (this.ended) return; + this.ended = true; + if (this.errored) return; + this.calculatedTotalSizeCallback = calculatedTotalSizeCallback; + this.forceZip64Eocd = !!options.forceZip64Format; + if (options.comment) { + if (typeof options.comment === "string") { + this.comment = encodeCp437(options.comment); + } else { + this.comment = options.comment; + } + if (this.comment.length > 65535) throw new Error("comment is too large"); + if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature"); + } else { + this.comment = EMPTY_BUFFER; + } + pumpEntries(this); + }; + function writeToOutputStream(self2, buffer2) { + self2.outputStream.write(buffer2); + self2.outputStreamCursor += buffer2.length; + } + __name(writeToOutputStream, "writeToOutputStream"); + function pumpFileDataReadStream(self2, entry, readStream) { + var crc32Watcher = new Crc32Watcher(); + var uncompressedSizeCounter = new ByteCounter(); + var compressor = entry.compressionLevel !== 0 ? new zlib2.DeflateRaw({ level: entry.compressionLevel }) : new PassThrough(); + var compressedSizeCounter = new ByteCounter(); + readStream.pipe(crc32Watcher).pipe(uncompressedSizeCounter).pipe(compressor).pipe(compressedSizeCounter).pipe(self2.outputStream, { end: false }); + compressedSizeCounter.on("end", function() { + entry.crc32 = crc32Watcher.crc32; + if (entry.uncompressedSize == null) { + entry.uncompressedSize = uncompressedSizeCounter.byteCount; + } else { + if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self2.emit("error", new Error("file data stream has unexpected number of bytes")); + } + entry.compressedSize = compressedSizeCounter.byteCount; + self2.outputStreamCursor += entry.compressedSize; + writeToOutputStream(self2, entry.getDataDescriptor()); + entry.state = Entry.FILE_DATA_DONE; + pumpEntries(self2); + }); + } + __name(pumpFileDataReadStream, "pumpFileDataReadStream"); + function determineCompressionLevel(options) { + if (options.compress != null && options.compressionLevel != null) { + if (!!options.compress !== !!options.compressionLevel) throw new Error("conflicting settings for compress and compressionLevel"); + } + if (options.compressionLevel != null) return options.compressionLevel; + if (options.compress === false) return 0; + return 6; + } + __name(determineCompressionLevel, "determineCompressionLevel"); + function pumpEntries(self2) { + if (self2.allDone || self2.errored) return; + if (self2.ended && self2.calculatedTotalSizeCallback != null) { + var calculatedTotalSize = calculateTotalSize(self2); + if (calculatedTotalSize != null) { + self2.calculatedTotalSizeCallback(calculatedTotalSize); + self2.calculatedTotalSizeCallback = null; + } + } + var entry = getFirstNotDoneEntry(); + function getFirstNotDoneEntry() { + for (var i = 0; i < self2.entries.length; i++) { + var entry2 = self2.entries[i]; + if (entry2.state < Entry.FILE_DATA_DONE) return entry2; + } + return null; + } + __name(getFirstNotDoneEntry, "getFirstNotDoneEntry"); + if (entry != null) { + if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; + if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; + entry.relativeOffsetOfLocalHeader = self2.outputStreamCursor; + var localFileHeader = entry.getLocalFileHeader(); + writeToOutputStream(self2, localFileHeader); + entry.doFileDataPump(); + } else { + if (self2.ended) { + self2.offsetOfStartOfCentralDirectory = self2.outputStreamCursor; + self2.entries.forEach(function(entry2) { + var centralDirectoryRecord = entry2.getCentralDirectoryRecord(); + writeToOutputStream(self2, centralDirectoryRecord); + }); + writeToOutputStream(self2, getEndOfCentralDirectoryRecord(self2)); + self2.outputStream.end(); + self2.allDone = true; + } + } + } + __name(pumpEntries, "pumpEntries"); + function calculateTotalSize(self2) { + var pretendOutputCursor = 0; + var centralDirectorySize = 0; + for (var i = 0; i < self2.entries.length; i++) { + var entry = self2.entries[i]; + if (entry.compressionLevel !== 0) return -1; + if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) { + if (entry.uncompressedSize == null) return -1; + } else { + if (entry.uncompressedSize == null) return null; + } + entry.relativeOffsetOfLocalHeader = pretendOutputCursor; + var useZip64Format = entry.useZip64Format(); + pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length; + pretendOutputCursor += entry.uncompressedSize; + if (!entry.crcAndFileSizeKnown) { + if (useZip64Format) { + pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE; + } else { + pretendOutputCursor += DATA_DESCRIPTOR_SIZE; + } + } + centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length; + if (!entry.forceDosTimestamp) { + centralDirectorySize += INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE; + } + if (useZip64Format) { + centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE; + } + } + var endOfCentralDirectorySize = 0; + if (self2.forceZip64Eocd || self2.entries.length >= 65535 || centralDirectorySize >= 65535 || pretendOutputCursor >= 4294967295) { + endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE; + } + endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self2.comment.length; + return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize; + } + __name(calculateTotalSize, "calculateTotalSize"); + function shouldIgnoreAdding(self2) { + if (self2.ended) throw new Error("cannot add entries after calling end()"); + if (self2.errored) return true; + return false; + } + __name(shouldIgnoreAdding, "shouldIgnoreAdding"); + var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56; + var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20; + var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22; + function getEndOfCentralDirectoryRecord(self2, actuallyJustTellMeHowLongItWouldBe) { + var needZip64Format = false; + var normalEntriesLength = self2.entries.length; + if (self2.forceZip64Eocd || self2.entries.length >= 65535) { + normalEntriesLength = 65535; + needZip64Format = true; + } + var sizeOfCentralDirectory = self2.outputStreamCursor - self2.offsetOfStartOfCentralDirectory; + var normalSizeOfCentralDirectory = sizeOfCentralDirectory; + if (self2.forceZip64Eocd || sizeOfCentralDirectory >= 4294967295) { + normalSizeOfCentralDirectory = 4294967295; + needZip64Format = true; + } + var normalOffsetOfStartOfCentralDirectory = self2.offsetOfStartOfCentralDirectory; + if (self2.forceZip64Eocd || self2.offsetOfStartOfCentralDirectory >= 4294967295) { + normalOffsetOfStartOfCentralDirectory = 4294967295; + needZip64Format = true; + } + if (actuallyJustTellMeHowLongItWouldBe) { + if (needZip64Format) { + return ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE + END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; + } else { + return END_OF_CENTRAL_DIRECTORY_RECORD_SIZE; + } + } + var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self2.comment.length); + eocdrBuffer.writeUInt32LE(101010256, 0); + eocdrBuffer.writeUInt16LE(0, 4); + eocdrBuffer.writeUInt16LE(0, 6); + eocdrBuffer.writeUInt16LE(normalEntriesLength, 8); + eocdrBuffer.writeUInt16LE(normalEntriesLength, 10); + eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12); + eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16); + eocdrBuffer.writeUInt16LE(self2.comment.length, 20); + self2.comment.copy(eocdrBuffer, 22); + if (!needZip64Format) return eocdrBuffer; + var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE); + zip64EocdrBuffer.writeUInt32LE(101075792, 0); + writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4); + zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12); + zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14); + zip64EocdrBuffer.writeUInt32LE(0, 16); + zip64EocdrBuffer.writeUInt32LE(0, 20); + writeUInt64LE(zip64EocdrBuffer, self2.entries.length, 24); + writeUInt64LE(zip64EocdrBuffer, self2.entries.length, 32); + writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40); + writeUInt64LE(zip64EocdrBuffer, self2.offsetOfStartOfCentralDirectory, 48); + var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE); + zip64EocdlBuffer.writeUInt32LE(117853008, 0); + zip64EocdlBuffer.writeUInt32LE(0, 4); + writeUInt64LE(zip64EocdlBuffer, self2.outputStreamCursor, 8); + zip64EocdlBuffer.writeUInt32LE(1, 16); + return Buffer.concat([ + zip64EocdrBuffer, + zip64EocdlBuffer, + eocdrBuffer + ]); + } + __name(getEndOfCentralDirectoryRecord, "getEndOfCentralDirectoryRecord"); + function validateMetadataPath(metadataPath, isDirectory) { + if (metadataPath === "") throw new Error("empty metadataPath"); + metadataPath = metadataPath.replace(/\\/g, "/"); + if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath); + if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath); + var looksLikeDirectory = /\/$/.test(metadataPath); + if (isDirectory) { + if (!looksLikeDirectory) metadataPath += "/"; + } else { + if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath); + } + return metadataPath; + } + __name(validateMetadataPath, "validateMetadataPath"); + var EMPTY_BUFFER = bufferAlloc(0); + function Entry(metadataPath, isDirectory, options) { + this.utf8FileName = bufferFrom(metadataPath); + if (this.utf8FileName.length > 65535) throw new Error("utf8 file name too long. " + utf8FileName.length + " > 65535"); + this.isDirectory = isDirectory; + this.state = Entry.WAITING_FOR_METADATA; + this.setLastModDate(options.mtime != null ? options.mtime : /* @__PURE__ */ new Date()); + this.forceDosTimestamp = !!options.forceDosTimestamp; + if (options.mode != null) { + this.setFileAttributesMode(options.mode); + } else { + this.setFileAttributesMode(isDirectory ? 16893 : 33204); + } + if (isDirectory) { + this.crcAndFileSizeKnown = true; + this.crc32 = 0; + this.uncompressedSize = 0; + this.compressedSize = 0; + } else { + this.crcAndFileSizeKnown = false; + this.crc32 = null; + this.uncompressedSize = null; + this.compressedSize = null; + if (options.size != null) this.uncompressedSize = options.size; + } + if (isDirectory) { + this.compressionLevel = 0; + } else { + this.compressionLevel = determineCompressionLevel(options); + } + this.forceZip64Format = !!options.forceZip64Format; + if (options.fileComment) { + if (typeof options.fileComment === "string") { + this.fileComment = bufferFrom(options.fileComment, "utf-8"); + } else { + this.fileComment = options.fileComment; + } + if (this.fileComment.length > 65535) throw new Error("fileComment is too large"); + } else { + this.fileComment = EMPTY_BUFFER; + } + } + __name(Entry, "Entry"); + Entry.WAITING_FOR_METADATA = 0; + Entry.READY_TO_PUMP_FILE_DATA = 1; + Entry.FILE_DATA_IN_PROGRESS = 2; + Entry.FILE_DATA_DONE = 3; + Entry.prototype.setLastModDate = function(date) { + this.mtime = date; + var dosDateTime = dateToDosDateTime(date); + this.lastModFileTime = dosDateTime.time; + this.lastModFileDate = dosDateTime.date; + }; + Entry.prototype.setFileAttributesMode = function(mode) { + if ((mode & 65535) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= 65535"); + this.externalFileAttributes = mode << 16 >>> 0; + }; + Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) { + this.doFileDataPump = doFileDataPump; + this.state = Entry.READY_TO_PUMP_FILE_DATA; + }; + Entry.prototype.useZip64Format = function() { + return this.forceZip64Format || this.uncompressedSize != null && this.uncompressedSize > 4294967294 || this.compressedSize != null && this.compressedSize > 4294967294 || this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 4294967294; + }; + var LOCAL_FILE_HEADER_FIXED_SIZE = 30; + var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20; + var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45; + var VERSION_MADE_BY = 3 << 8 | 63; + var FILE_NAME_IS_UTF8 = 1 << 11; + var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3; + Entry.prototype.getLocalFileHeader = function() { + var crc322 = 0; + var compressedSize = 0; + var uncompressedSize = 0; + if (this.crcAndFileSizeKnown) { + crc322 = this.crc32; + compressedSize = this.compressedSize; + uncompressedSize = this.uncompressedSize; + } + var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE); + var generalPurposeBitFlag = FILE_NAME_IS_UTF8; + if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; + fixedSizeStuff.writeUInt32LE(67324752, 0); + fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4); + fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6); + fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8); + fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10); + fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12); + fixedSizeStuff.writeUInt32LE(crc322, 14); + fixedSizeStuff.writeUInt32LE(compressedSize, 18); + fixedSizeStuff.writeUInt32LE(uncompressedSize, 22); + fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26); + fixedSizeStuff.writeUInt16LE(0, 28); + return Buffer.concat([ + fixedSizeStuff, + // file name (variable size) + this.utf8FileName + // extra field (variable size) + // no extra fields + ]); + }; + var DATA_DESCRIPTOR_SIZE = 16; + var ZIP64_DATA_DESCRIPTOR_SIZE = 24; + Entry.prototype.getDataDescriptor = function() { + if (this.crcAndFileSizeKnown) { + return EMPTY_BUFFER; + } + if (!this.useZip64Format()) { + var buffer2 = bufferAlloc(DATA_DESCRIPTOR_SIZE); + buffer2.writeUInt32LE(134695760, 0); + buffer2.writeUInt32LE(this.crc32, 4); + buffer2.writeUInt32LE(this.compressedSize, 8); + buffer2.writeUInt32LE(this.uncompressedSize, 12); + return buffer2; + } else { + var buffer2 = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE); + buffer2.writeUInt32LE(134695760, 0); + buffer2.writeUInt32LE(this.crc32, 4); + writeUInt64LE(buffer2, this.compressedSize, 8); + writeUInt64LE(buffer2, this.uncompressedSize, 16); + return buffer2; + } + }; + var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46; + var INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE = 9; + var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28; + Entry.prototype.getCentralDirectoryRecord = function() { + var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE); + var generalPurposeBitFlag = FILE_NAME_IS_UTF8; + if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES; + var izutefBuffer = EMPTY_BUFFER; + if (!this.forceDosTimestamp) { + izutefBuffer = bufferAlloc(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE); + izutefBuffer.writeUInt16LE(21589, 0); + izutefBuffer.writeUInt16LE(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE - 4, 2); + var EB_UT_FL_MTIME = 1 << 0; + var EB_UT_FL_ATIME = 1 << 1; + izutefBuffer.writeUInt8(EB_UT_FL_MTIME | EB_UT_FL_ATIME, 4); + var timestamp = Math.floor(this.mtime.getTime() / 1e3); + if (timestamp < -2147483648) timestamp = -2147483648; + if (timestamp > 2147483647) timestamp = 2147483647; + izutefBuffer.writeUInt32LE(timestamp, 5); + } + var normalCompressedSize = this.compressedSize; + var normalUncompressedSize = this.uncompressedSize; + var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader; + var versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8; + var zeiefBuffer = EMPTY_BUFFER; + if (this.useZip64Format()) { + normalCompressedSize = 4294967295; + normalUncompressedSize = 4294967295; + normalRelativeOffsetOfLocalHeader = 4294967295; + versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64; + zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE); + zeiefBuffer.writeUInt16LE(1, 0); + zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2); + writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4); + writeUInt64LE(zeiefBuffer, this.compressedSize, 12); + writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20); + } + fixedSizeStuff.writeUInt32LE(33639248, 0); + fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4); + fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6); + fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8); + fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10); + fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12); + fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14); + fixedSizeStuff.writeUInt32LE(this.crc32, 16); + fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20); + fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24); + fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28); + fixedSizeStuff.writeUInt16LE(izutefBuffer.length + zeiefBuffer.length, 30); + fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32); + fixedSizeStuff.writeUInt16LE(0, 34); + fixedSizeStuff.writeUInt16LE(0, 36); + fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38); + fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42); + return Buffer.concat([ + fixedSizeStuff, + // file name (variable size) + this.utf8FileName, + // extra field (variable size) + izutefBuffer, + zeiefBuffer, + // file comment (variable size) + this.fileComment + ]); + }; + Entry.prototype.getCompressionMethod = function() { + var NO_COMPRESSION = 0; + var DEFLATE_COMPRESSION = 8; + return this.compressionLevel === 0 ? NO_COMPRESSION : DEFLATE_COMPRESSION; + }; + var minDosDate = new Date(1980, 0, 1); + var maxDosDate = new Date(2107, 11, 31, 23, 59, 58); + function dateToDosDateTime(jsDate) { + if (jsDate < minDosDate) jsDate = minDosDate; + else if (jsDate > maxDosDate) jsDate = maxDosDate; + var date = 0; + date |= jsDate.getDate() & 31; + date |= (jsDate.getMonth() + 1 & 15) << 5; + date |= (jsDate.getFullYear() - 1980 & 127) << 9; + var time = 0; + time |= Math.floor(jsDate.getSeconds() / 2); + time |= (jsDate.getMinutes() & 63) << 5; + time |= (jsDate.getHours() & 31) << 11; + return { date, time }; + } + __name(dateToDosDateTime, "dateToDosDateTime"); + function writeUInt64LE(buffer2, n, offset) { + var high = Math.floor(n / 4294967296); + var low = n % 4294967296; + buffer2.writeUInt32LE(low, offset); + buffer2.writeUInt32LE(high, offset + 4); + } + __name(writeUInt64LE, "writeUInt64LE"); + util3.inherits(ByteCounter, Transform2); + function ByteCounter(options) { + Transform2.call(this, options); + this.byteCount = 0; + } + __name(ByteCounter, "ByteCounter"); + ByteCounter.prototype._transform = function(chunk, encoding, cb) { + this.byteCount += chunk.length; + cb(null, chunk); + }; + util3.inherits(Crc32Watcher, Transform2); + function Crc32Watcher(options) { + Transform2.call(this, options); + this.crc32 = 0; + } + __name(Crc32Watcher, "Crc32Watcher"); + Crc32Watcher.prototype._transform = function(chunk, encoding, cb) { + this.crc32 = crc32.unsigned(chunk, this.crc32); + cb(null, chunk); + }; + var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"; + if (cp437.length !== 256) throw new Error("assertion failure"); + var reverseCp437 = null; + function encodeCp437(string) { + if (/^[\x20-\x7e]*$/.test(string)) { + return bufferFrom(string, "utf-8"); + } + if (reverseCp437 == null) { + reverseCp437 = {}; + for (var i = 0; i < cp437.length; i++) { + reverseCp437[cp437[i]] = i; + } + } + var result = bufferAlloc(string.length); + for (var i = 0; i < string.length; i++) { + var b = reverseCp437[string[i]]; + if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string[i])); + result[i] = b; + } + return result; + } + __name(encodeCp437, "encodeCp437"); + function bufferAlloc(size) { + bufferAlloc = modern; + try { + return bufferAlloc(size); + } catch (e) { + bufferAlloc = legacy; + return bufferAlloc(size); + } + function modern(size2) { + return Buffer.allocUnsafe(size2); + } + __name(modern, "modern"); + function legacy(size2) { + return new Buffer(size2); + } + __name(legacy, "legacy"); + } + __name(bufferAlloc, "bufferAlloc"); + function bufferFrom(something, encoding) { + bufferFrom = modern; + try { + return bufferFrom(something, encoding); + } catch (e) { + bufferFrom = legacy; + return bufferFrom(something, encoding); + } + function modern(something2, encoding2) { + return Buffer.from(something2, encoding2); + } + __name(modern, "modern"); + function legacy(something2, encoding2) { + return new Buffer(something2, encoding2); + } + __name(legacy, "legacy"); + } + __name(bufferFrom, "bufferFrom"); + function bufferIncludes(buffer2, content) { + bufferIncludes = modern; + try { + return bufferIncludes(buffer2, content); + } catch (e) { + bufferIncludes = legacy; + return bufferIncludes(buffer2, content); + } + function modern(buffer3, content2) { + return buffer3.includes(content2); + } + __name(modern, "modern"); + function legacy(buffer3, content2) { + for (var i = 0; i <= buffer3.length - content2.length; i++) { + for (var j = 0; ; j++) { + if (j === content2.length) return true; + if (buffer3[i + j] !== content2[j]) break; + } + } + return false; + } + __name(legacy, "legacy"); + } + __name(bufferIncludes, "bufferIncludes"); + } +}); + +// ../../node_modules/safe-buffer/index.js +var require_safe_buffer = __commonJS({ + "../../node_modules/safe-buffer/index.js"(exports2, module) { + var buffer2 = __require("buffer"); + var Buffer3 = buffer2.Buffer; + function copyProps(src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + __name(copyProps, "copyProps"); + if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) { + module.exports = buffer2; + } else { + copyProps(buffer2, exports2); + exports2.Buffer = SafeBuffer; + } + function SafeBuffer(arg, encodingOrOffset, length) { + return Buffer3(arg, encodingOrOffset, length); + } + __name(SafeBuffer, "SafeBuffer"); + SafeBuffer.prototype = Object.create(Buffer3.prototype); + copyProps(Buffer3, SafeBuffer); + SafeBuffer.from = function(arg, encodingOrOffset, length) { + if (typeof arg === "number") { + throw new TypeError("Argument must not be a number"); + } + return Buffer3(arg, encodingOrOffset, length); + }; + SafeBuffer.alloc = function(size, fill, encoding) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + var buf = Buffer3(size); + if (fill !== void 0) { + if (typeof encoding === "string") { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf; + }; + SafeBuffer.allocUnsafe = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return Buffer3(size); + }; + SafeBuffer.allocUnsafeSlow = function(size) { + if (typeof size !== "number") { + throw new TypeError("Argument must be a number"); + } + return buffer2.SlowBuffer(size); + }; + } +}); + +// ../../node_modules/jsonwebtoken/node_modules/jws/lib/data-stream.js +var require_data_stream = __commonJS({ + "../../node_modules/jsonwebtoken/node_modules/jws/lib/data-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var Stream2 = __require("stream"); + var util3 = __require("util"); + function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + if (!data) { + this.buffer = Buffer3.alloc(0); + return this; + } + if (typeof data.pipe === "function") { + this.buffer = Buffer3.alloc(0); + data.pipe(this); + return this; + } + if (data.length || typeof data === "object") { + this.buffer = data; + this.writable = false; + process.nextTick(function() { + this.emit("end", data); + this.readable = false; + this.emit("close"); + }.bind(this)); + return this; + } + throw new TypeError("Unexpected data type (" + typeof data + ")"); + } + __name(DataStream, "DataStream"); + util3.inherits(DataStream, Stream2); + DataStream.prototype.write = /* @__PURE__ */ __name(function write(data) { + this.buffer = Buffer3.concat([this.buffer, Buffer3.from(data)]); + this.emit("data", data); + }, "write"); + DataStream.prototype.end = /* @__PURE__ */ __name(function end(data) { + if (data) + this.write(data); + this.emit("end", data); + this.emit("close"); + this.writable = false; + this.readable = false; + }, "end"); + module.exports = DataStream; + } +}); + +// ../../node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js +var require_param_bytes_for_alg = __commonJS({ + "../../node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(exports2, module) { + "use strict"; + function getParamSize(keySize) { + var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; + } + __name(getParamSize, "getParamSize"); + var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) + }; + function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + throw new Error('Unknown algorithm "' + alg + '"'); + } + __name(getParamBytesForAlg, "getParamBytesForAlg"); + module.exports = getParamBytesForAlg; + } +}); + +// ../../node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js +var require_ecdsa_sig_formatter = __commonJS({ + "../../node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(exports2, module) { + "use strict"; + var Buffer3 = require_safe_buffer().Buffer; + var getParamBytesForAlg = require_param_bytes_for_alg(); + var MAX_OCTET = 128; + var CLASS_UNIVERSAL = 0; + var PRIMITIVE_BIT = 32; + var TAG_SEQ = 16; + var TAG_INT = 2; + var ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6; + var ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6; + function base64Url(base64) { + return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + } + __name(base64Url, "base64Url"); + function signatureAsBuffer(signature) { + if (Buffer3.isBuffer(signature)) { + return signature; + } else if ("string" === typeof signature) { + return Buffer3.from(signature, "base64"); + } + throw new TypeError("ECDSA signature must be a Base64 string or a Buffer"); + } + __name(signatureAsBuffer, "signatureAsBuffer"); + function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + var maxEncodedParamLength = paramBytes + 1; + var inputLength = signature.length; + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + var rLength = signature[offset++]; + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + var rOffset = offset; + offset += rLength; + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + var sLength = signature[offset++]; + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + var sOffset = offset; + offset += sLength; + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength; + var dst = Buffer3.allocUnsafe(rPadding + rLength + sPadding + sLength); + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + offset = paramBytes; + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + dst = dst.toString("base64"); + dst = base64Url(dst); + return dst; + } + __name(derToJose, "derToJose"); + function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + return padding; + } + __name(countPadding, "countPadding"); + function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + var shortLength = rsBytes < MAX_OCTET; + var dst = Buffer3.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + dst[offset++] = rsBytes; + } else { + dst[offset++] = MAX_OCTET | 1; + dst[offset++] = rsBytes & 255; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + return dst; + } + __name(joseToDer, "joseToDer"); + module.exports = { + derToJose, + joseToDer + }; + } +}); + +// ../../node_modules/buffer-equal-constant-time/index.js +var require_buffer_equal_constant_time = __commonJS({ + "../../node_modules/buffer-equal-constant-time/index.js"(exports2, module) { + "use strict"; + var Buffer3 = __require("buffer").Buffer; + var SlowBuffer = __require("buffer").SlowBuffer; + module.exports = bufferEq; + function bufferEq(a, b) { + if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + var c = 0; + for (var i = 0; i < a.length; i++) { + c |= a[i] ^ b[i]; + } + return c === 0; + } + __name(bufferEq, "bufferEq"); + bufferEq.install = function() { + Buffer3.prototype.equal = SlowBuffer.prototype.equal = /* @__PURE__ */ __name(function equal(that) { + return bufferEq(this, that); + }, "equal"); + }; + var origBufEqual = Buffer3.prototype.equal; + var origSlowBufEqual = SlowBuffer.prototype.equal; + bufferEq.restore = function() { + Buffer3.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; + }; + } +}); + +// ../../node_modules/jwa/index.js +var require_jwa = __commonJS({ + "../../node_modules/jwa/index.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var crypto5 = __require("crypto"); + var formatEcdsa = require_ecdsa_sig_formatter(); + var util3 = __require("util"); + var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".'; + var MSG_INVALID_SECRET = "secret must be a string or buffer"; + var MSG_INVALID_VERIFIER_KEY = "key must be a string or a buffer"; + var MSG_INVALID_SIGNER_KEY = "key must be a string, a buffer or an object"; + var supportsKeyObjects = typeof crypto5.createPublicKey === "function"; + if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += " or a KeyObject"; + MSG_INVALID_SECRET += "or a KeyObject"; + } + function checkIsPublicKey(key) { + if (Buffer3.isBuffer(key)) { + return; + } + if (typeof key === "string") { + return; + } + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + if (typeof key !== "object") { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + if (typeof key.type !== "string") { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + if (typeof key.asymmetricKeyType !== "string") { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + if (typeof key.export !== "function") { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + } + __name(checkIsPublicKey, "checkIsPublicKey"); + function checkIsPrivateKey(key) { + if (Buffer3.isBuffer(key)) { + return; + } + if (typeof key === "string") { + return; + } + if (typeof key === "object") { + return; + } + throw typeError(MSG_INVALID_SIGNER_KEY); + } + __name(checkIsPrivateKey, "checkIsPrivateKey"); + function checkIsSecretKey(key) { + if (Buffer3.isBuffer(key)) { + return; + } + if (typeof key === "string") { + return key; + } + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + if (typeof key !== "object") { + throw typeError(MSG_INVALID_SECRET); + } + if (key.type !== "secret") { + throw typeError(MSG_INVALID_SECRET); + } + if (typeof key.export !== "function") { + throw typeError(MSG_INVALID_SECRET); + } + } + __name(checkIsSecretKey, "checkIsSecretKey"); + function fromBase64(base64) { + return base64.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + } + __name(fromBase64, "fromBase64"); + function toBase64(base64url) { + base64url = base64url.toString(); + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += "="; + } + } + return base64url.replace(/\-/g, "+").replace(/_/g, "/"); + } + __name(toBase64, "toBase64"); + function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util3.format.bind(util3, template).apply(null, args); + return new TypeError(errMsg); + } + __name(typeError, "typeError"); + function bufferOrString(obj) { + return Buffer3.isBuffer(obj) || typeof obj === "string"; + } + __name(bufferOrString, "bufferOrString"); + function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; + } + __name(normalizeInput, "normalizeInput"); + function createHmacSigner(bits) { + return /* @__PURE__ */ __name(function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto5.createHmac("sha" + bits, secret); + var sig = (hmac.update(thing), hmac.digest("base64")); + return fromBase64(sig); + }, "sign"); + } + __name(createHmacSigner, "createHmacSigner"); + var bufferEqual; + var timingSafeEqual = "timingSafeEqual" in crypto5 ? /* @__PURE__ */ __name(function timingSafeEqual2(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + return crypto5.timingSafeEqual(a, b); + }, "timingSafeEqual") : /* @__PURE__ */ __name(function timingSafeEqual2(a, b) { + if (!bufferEqual) { + bufferEqual = require_buffer_equal_constant_time(); + } + return bufferEqual(a, b); + }, "timingSafeEqual"); + function createHmacVerifier(bits) { + return /* @__PURE__ */ __name(function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return timingSafeEqual(Buffer3.from(signature), Buffer3.from(computedSig)); + }, "verify"); + } + __name(createHmacVerifier, "createHmacVerifier"); + function createKeySigner(bits) { + return /* @__PURE__ */ __name(function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto5.createSign("RSA-SHA" + bits); + var sig = (signer.update(thing), signer.sign(privateKey, "base64")); + return fromBase64(sig); + }, "sign"); + } + __name(createKeySigner, "createKeySigner"); + function createKeyVerifier(bits) { + return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto5.createVerify("RSA-SHA" + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, "base64"); + }, "verify"); + } + __name(createKeyVerifier, "createKeyVerifier"); + function createPSSKeySigner(bits) { + return /* @__PURE__ */ __name(function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto5.createSign("RSA-SHA" + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto5.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto5.constants.RSA_PSS_SALTLEN_DIGEST + }, "base64")); + return fromBase64(sig); + }, "sign"); + } + __name(createPSSKeySigner, "createPSSKeySigner"); + function createPSSKeyVerifier(bits) { + return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto5.createVerify("RSA-SHA" + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto5.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto5.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, "base64"); + }, "verify"); + } + __name(createPSSKeyVerifier, "createPSSKeyVerifier"); + function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return /* @__PURE__ */ __name(function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, "ES" + bits); + return signature; + }, "sign"); + } + __name(createECDSASigner, "createECDSASigner"); + function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return /* @__PURE__ */ __name(function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, "ES" + bits).toString("base64"); + var result = inner(thing, signature, publicKey); + return result; + }, "verify"); + } + __name(createECDSAVerifer, "createECDSAVerifer"); + function createNoneSigner() { + return /* @__PURE__ */ __name(function sign() { + return ""; + }, "sign"); + } + __name(createNoneSigner, "createNoneSigner"); + function createNoneVerifier() { + return /* @__PURE__ */ __name(function verify(thing, signature) { + return signature === ""; + }, "verify"); + } + __name(createNoneVerifier, "createNoneVerifier"); + module.exports = /* @__PURE__ */ __name(function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner + }; + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier + }; + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits) + }; + }, "jwa"); + } +}); + +// ../../node_modules/jsonwebtoken/node_modules/jws/lib/tostring.js +var require_tostring = __commonJS({ + "../../node_modules/jsonwebtoken/node_modules/jws/lib/tostring.js"(exports2, module) { + var Buffer3 = __require("buffer").Buffer; + module.exports = /* @__PURE__ */ __name(function toString3(obj) { + if (typeof obj === "string") + return obj; + if (typeof obj === "number" || Buffer3.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); + }, "toString"); + } +}); + +// ../../node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js +var require_sign_stream = __commonJS({ + "../../node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var DataStream = require_data_stream(); + var jwa = require_jwa(); + var Stream2 = __require("stream"); + var toString3 = require_tostring(); + var util3 = __require("util"); + function base64url(string, encoding) { + return Buffer3.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + } + __name(base64url, "base64url"); + function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || "utf8"; + var encodedHeader = base64url(toString3(header), "binary"); + var encodedPayload = base64url(toString3(payload), encoding); + return util3.format("%s.%s", encodedHeader, encodedPayload); + } + __name(jwsSecuredInput, "jwsSecuredInput"); + function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util3.format("%s.%s", securedInput, signature); + } + __name(jwsSign, "jwsSign"); + function SignStream(opts) { + var secret = opts.secret; + secret = secret == null ? opts.privateKey : secret; + secret = secret == null ? opts.key : secret; + if (/^hs/i.test(opts.header.alg) === true && secret == null) { + throw new TypeError("secret must be a string or buffer or a KeyObject"); + } + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once("close", function() { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + this.payload.once("close", function() { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); + } + __name(SignStream, "SignStream"); + util3.inherits(SignStream, Stream2); + SignStream.prototype.sign = /* @__PURE__ */ __name(function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit("done", signature); + this.emit("data", signature); + this.emit("end"); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit("error", e); + this.emit("close"); + } + }, "sign"); + SignStream.sign = jwsSign; + module.exports = SignStream; + } +}); + +// ../../node_modules/jsonwebtoken/node_modules/jws/lib/verify-stream.js +var require_verify_stream = __commonJS({ + "../../node_modules/jsonwebtoken/node_modules/jws/lib/verify-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var DataStream = require_data_stream(); + var jwa = require_jwa(); + var Stream2 = __require("stream"); + var toString3 = require_tostring(); + var util3 = __require("util"); + var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + function isObject2(thing) { + return Object.prototype.toString.call(thing) === "[object Object]"; + } + __name(isObject2, "isObject"); + function safeJsonParse(thing) { + if (isObject2(thing)) + return thing; + try { + return JSON.parse(thing); + } catch (e) { + return void 0; + } + } + __name(safeJsonParse, "safeJsonParse"); + function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split(".", 1)[0]; + return safeJsonParse(Buffer3.from(encodedHeader, "base64").toString("binary")); + } + __name(headerFromJWS, "headerFromJWS"); + function securedInputFromJWS(jwsSig) { + return jwsSig.split(".", 2).join("."); + } + __name(securedInputFromJWS, "securedInputFromJWS"); + function signatureFromJWS(jwsSig) { + return jwsSig.split(".")[2]; + } + __name(signatureFromJWS, "signatureFromJWS"); + function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || "utf8"; + var payload = jwsSig.split(".")[1]; + return Buffer3.from(payload, "base64").toString(encoding); + } + __name(payloadFromJWS, "payloadFromJWS"); + function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); + } + __name(isValidJws, "isValidJws"); + function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString3(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); + } + __name(jwsVerify, "jwsVerify"); + function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString3(jwsSig); + if (!isValidJws(jwsSig)) + return null; + var header = headerFromJWS(jwsSig); + if (!header) + return null; + var payload = payloadFromJWS(jwsSig); + if (header.typ === "JWT" || opts.json) + payload = JSON.parse(payload, opts.encoding); + return { + header, + payload, + signature: signatureFromJWS(jwsSig) + }; + } + __name(jwsDecode, "jwsDecode"); + function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret; + secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey; + secretOrKey = secretOrKey == null ? opts.key : secretOrKey; + if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) { + throw new TypeError("secret must be a string or buffer or a KeyObject"); + } + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once("close", function() { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + this.signature.once("close", function() { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); + } + __name(VerifyStream, "VerifyStream"); + util3.inherits(VerifyStream, Stream2); + VerifyStream.prototype.verify = /* @__PURE__ */ __name(function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit("done", valid, obj); + this.emit("data", valid); + this.emit("end"); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit("error", e); + this.emit("close"); + } + }, "verify"); + VerifyStream.decode = jwsDecode; + VerifyStream.isValid = isValidJws; + VerifyStream.verify = jwsVerify; + module.exports = VerifyStream; + } +}); + +// ../../node_modules/jsonwebtoken/node_modules/jws/index.js +var require_jws = __commonJS({ + "../../node_modules/jsonwebtoken/node_modules/jws/index.js"(exports2) { + var SignStream = require_sign_stream(); + var VerifyStream = require_verify_stream(); + var ALGORITHMS = [ + "HS256", + "HS384", + "HS512", + "RS256", + "RS384", + "RS512", + "PS256", + "PS384", + "PS512", + "ES256", + "ES384", + "ES512" + ]; + exports2.ALGORITHMS = ALGORITHMS; + exports2.sign = SignStream.sign; + exports2.verify = VerifyStream.verify; + exports2.decode = VerifyStream.decode; + exports2.isValid = VerifyStream.isValid; + exports2.createSign = /* @__PURE__ */ __name(function createSign(opts) { + return new SignStream(opts); + }, "createSign"); + exports2.createVerify = /* @__PURE__ */ __name(function createVerify(opts) { + return new VerifyStream(opts); + }, "createVerify"); + } +}); + +// ../../node_modules/jsonwebtoken/decode.js +var require_decode = __commonJS({ + "../../node_modules/jsonwebtoken/decode.js"(exports2, module) { + var jws2 = require_jws(); + module.exports = function(jwt2, options) { + options = options || {}; + var decoded = jws2.decode(jwt2, options); + if (!decoded) { + return null; + } + var payload = decoded.payload; + if (typeof payload === "string") { + try { + var obj = JSON.parse(payload); + if (obj !== null && typeof obj === "object") { + payload = obj; + } + } catch (e) { + } + } + if (options.complete === true) { + return { + header: decoded.header, + payload, + signature: decoded.signature + }; + } + return payload; + }; + } +}); + +// ../../node_modules/jsonwebtoken/lib/JsonWebTokenError.js +var require_JsonWebTokenError = __commonJS({ + "../../node_modules/jsonwebtoken/lib/JsonWebTokenError.js"(exports2, module) { + var JsonWebTokenError = /* @__PURE__ */ __name(function(message, error) { + Error.call(this, message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "JsonWebTokenError"; + this.message = message; + if (error) this.inner = error; + }, "JsonWebTokenError"); + JsonWebTokenError.prototype = Object.create(Error.prototype); + JsonWebTokenError.prototype.constructor = JsonWebTokenError; + module.exports = JsonWebTokenError; + } +}); + +// ../../node_modules/jsonwebtoken/lib/NotBeforeError.js +var require_NotBeforeError = __commonJS({ + "../../node_modules/jsonwebtoken/lib/NotBeforeError.js"(exports2, module) { + var JsonWebTokenError = require_JsonWebTokenError(); + var NotBeforeError = /* @__PURE__ */ __name(function(message, date) { + JsonWebTokenError.call(this, message); + this.name = "NotBeforeError"; + this.date = date; + }, "NotBeforeError"); + NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); + NotBeforeError.prototype.constructor = NotBeforeError; + module.exports = NotBeforeError; + } +}); + +// ../../node_modules/jsonwebtoken/lib/TokenExpiredError.js +var require_TokenExpiredError = __commonJS({ + "../../node_modules/jsonwebtoken/lib/TokenExpiredError.js"(exports2, module) { + var JsonWebTokenError = require_JsonWebTokenError(); + var TokenExpiredError = /* @__PURE__ */ __name(function(message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = "TokenExpiredError"; + this.expiredAt = expiredAt; + }, "TokenExpiredError"); + TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + TokenExpiredError.prototype.constructor = TokenExpiredError; + module.exports = TokenExpiredError; + } +}); + +// ../../node_modules/jsonwebtoken/lib/timespan.js +var require_timespan = __commonJS({ + "../../node_modules/jsonwebtoken/lib/timespan.js"(exports2, module) { + var ms = require_ms(); + module.exports = function(time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1e3); + if (typeof time === "string") { + var milliseconds = ms(time); + if (typeof milliseconds === "undefined") { + return; + } + return Math.floor(timestamp + milliseconds / 1e3); + } else if (typeof time === "number") { + return timestamp + time; + } else { + return; + } + }; + } +}); + +// ../../node_modules/semver/internal/constants.js +var require_constants = __commonJS({ + "../../node_modules/semver/internal/constants.js"(exports2, module) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } +}); + +// ../../node_modules/semver/internal/debug.js +var require_debug = __commonJS({ + "../../node_modules/semver/internal/debug.js"(exports2, module) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module.exports = debug; + } +}); + +// ../../node_modules/semver/internal/re.js +var require_re = __commonJS({ + "../../node_modules/semver/internal/re.js"(exports2, module) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants(); + var debug = require_debug(); + exports2 = module.exports = {}; + var re = exports2.re = []; + var safeRe = exports2.safeRe = []; + var src = exports2.src = []; + var safeSrc = exports2.safeSrc = []; + var t = exports2.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = /* @__PURE__ */ __name((value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }, "makeSafeRegex"); + var createToken = /* @__PURE__ */ __name((name3, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index = R++; + debug(name3, index, value); + t[name3] = index; + src[index] = value; + safeSrc[index] = safe; + re[index] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0); + }, "createToken"); + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken("FULL", `^${src[t.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t.COERCE], true); + createToken("COERCERTLFULL", src[t.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports2.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports2.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports2.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } +}); + +// ../../node_modules/semver/internal/parse-options.js +var require_parse_options = __commonJS({ + "../../node_modules/semver/internal/parse-options.js"(exports2, module) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions = /* @__PURE__ */ __name((options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }, "parseOptions"); + module.exports = parseOptions; + } +}); + +// ../../node_modules/semver/internal/identifiers.js +var require_identifiers = __commonJS({ + "../../node_modules/semver/internal/identifiers.js"(exports2, module) { + "use strict"; + var numeric = /^[0-9]+$/; + var compareIdentifiers = /* @__PURE__ */ __name((a, b) => { + if (typeof a === "number" && typeof b === "number") { + return a === b ? 0 : a < b ? -1 : 1; + } + const anum = numeric.test(a); + const bnum = numeric.test(b); + if (anum && bnum) { + a = +a; + b = +b; + } + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }, "compareIdentifiers"); + var rcompareIdentifiers = /* @__PURE__ */ __name((a, b) => compareIdentifiers(b, a), "rcompareIdentifiers"); + module.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } +}); + +// ../../node_modules/semver/classes/semver.js +var require_semver = __commonJS({ + "../../node_modules/semver/classes/semver.js"(exports2, module) { + "use strict"; + var debug = require_debug(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); + var { safeRe: re, t } = require_re(); + var parseOptions = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var isPrereleaseIdentifier = /* @__PURE__ */ __name((prerelease, identifier) => { + const identifiers = identifier.split("."); + if (identifiers.length > prerelease.length) { + return false; + } + for (let i = 0; i < identifiers.length; i++) { + if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { + return false; + } + } + return true; + }, "isPrereleaseIdentifier"); + var SemVer = class _SemVer { + static { + __name(this, "SemVer"); + } + constructor(version4, options) { + options = parseOptions(options); + if (version4 instanceof _SemVer) { + if (version4.loose === !!options.loose && version4.includePrerelease === !!options.includePrerelease) { + return version4; + } else { + version4 = version4.version; + } + } else if (typeof version4 !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version4}".`); + } + if (version4.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version4, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version4.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + if (!m) { + throw new TypeError(`Invalid Version: ${version4}`); + } + this.raw = version4; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split(".").map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m[5] ? m[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.major < other.major) { + return -1; + } + if (this.major > other.major) { + return 1; + } + if (this.minor < other.minor) { + return -1; + } + if (this.minor > other.minor) { + return 1; + } + if (this.patch < other.patch) { + return -1; + } + if (this.patch > other.patch) { + return 1; + } + return 0; + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i = 0; + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug("prerelease compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i = 0; + do { + const a = this.build[i]; + const b = other.build[i]; + debug("build compare", i, a, b); + if (a === void 0 && b === void 0) { + return 0; + } else if (b === void 0) { + return 1; + } else if (a === void 0) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === "number") { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (isPrereleaseIdentifier(this.prerelease, identifier)) { + const prereleaseBase = this.prerelease[identifier.split(".").length]; + if (isNaN(prereleaseBase)) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module.exports = SemVer; + } +}); + +// ../../node_modules/semver/functions/parse.js +var require_parse = __commonJS({ + "../../node_modules/semver/functions/parse.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var parse2 = /* @__PURE__ */ __name((version4, options, throwErrors = false) => { + if (version4 instanceof SemVer) { + return version4; + } + try { + return new SemVer(version4, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }, "parse"); + module.exports = parse2; + } +}); + +// ../../node_modules/semver/functions/valid.js +var require_valid = __commonJS({ + "../../node_modules/semver/functions/valid.js"(exports2, module) { + "use strict"; + var parse2 = require_parse(); + var valid = /* @__PURE__ */ __name((version4, options) => { + const v = parse2(version4, options); + return v ? v.version : null; + }, "valid"); + module.exports = valid; + } +}); + +// ../../node_modules/semver/functions/clean.js +var require_clean = __commonJS({ + "../../node_modules/semver/functions/clean.js"(exports2, module) { + "use strict"; + var parse2 = require_parse(); + var clean = /* @__PURE__ */ __name((version4, options) => { + const s = parse2(version4.trim().replace(/^[=v]+/, ""), options); + return s ? s.version : null; + }, "clean"); + module.exports = clean; + } +}); + +// ../../node_modules/semver/functions/inc.js +var require_inc = __commonJS({ + "../../node_modules/semver/functions/inc.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var inc = /* @__PURE__ */ __name((version4, release, options, identifier, identifierBase) => { + if (typeof options === "string") { + identifierBase = identifier; + identifier = options; + options = void 0; + } + try { + return new SemVer( + version4 instanceof SemVer ? version4.version : version4, + options + ).inc(release, identifier, identifierBase).version; + } catch (er) { + return null; + } + }, "inc"); + module.exports = inc; + } +}); + +// ../../node_modules/semver/functions/diff.js +var require_diff = __commonJS({ + "../../node_modules/semver/functions/diff.js"(exports2, module) { + "use strict"; + var parse2 = require_parse(); + var diff = /* @__PURE__ */ __name((version1, version22) => { + const v1 = parse2(version1, null, true); + const v2 = parse2(version22, null, true); + const comparison = v1.compare(v2); + if (comparison === 0) { + return null; + } + const v1Higher = comparison > 0; + const highVersion = v1Higher ? v1 : v2; + const lowVersion = v1Higher ? v2 : v1; + const highHasPre = !!highVersion.prerelease.length; + const lowHasPre = !!lowVersion.prerelease.length; + if (lowHasPre && !highHasPre) { + if (!lowVersion.patch && !lowVersion.minor) { + return "major"; + } + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return "minor"; + } + return "patch"; + } + } + const prefix2 = highHasPre ? "pre" : ""; + if (v1.major !== v2.major) { + return prefix2 + "major"; + } + if (v1.minor !== v2.minor) { + return prefix2 + "minor"; + } + if (v1.patch !== v2.patch) { + return prefix2 + "patch"; + } + return "prerelease"; + }, "diff"); + module.exports = diff; + } +}); + +// ../../node_modules/semver/functions/major.js +var require_major = __commonJS({ + "../../node_modules/semver/functions/major.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var major = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).major, "major"); + module.exports = major; + } +}); + +// ../../node_modules/semver/functions/minor.js +var require_minor = __commonJS({ + "../../node_modules/semver/functions/minor.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var minor = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).minor, "minor"); + module.exports = minor; + } +}); + +// ../../node_modules/semver/functions/patch.js +var require_patch = __commonJS({ + "../../node_modules/semver/functions/patch.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var patch = /* @__PURE__ */ __name((a, loose) => new SemVer(a, loose).patch, "patch"); + module.exports = patch; + } +}); + +// ../../node_modules/semver/functions/prerelease.js +var require_prerelease = __commonJS({ + "../../node_modules/semver/functions/prerelease.js"(exports2, module) { + "use strict"; + var parse2 = require_parse(); + var prerelease = /* @__PURE__ */ __name((version4, options) => { + const parsed = parse2(version4, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + }, "prerelease"); + module.exports = prerelease; + } +}); + +// ../../node_modules/semver/functions/compare.js +var require_compare = __commonJS({ + "../../node_modules/semver/functions/compare.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var compare = /* @__PURE__ */ __name((a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)), "compare"); + module.exports = compare; + } +}); + +// ../../node_modules/semver/functions/rcompare.js +var require_rcompare = __commonJS({ + "../../node_modules/semver/functions/rcompare.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var rcompare = /* @__PURE__ */ __name((a, b, loose) => compare(b, a, loose), "rcompare"); + module.exports = rcompare; + } +}); + +// ../../node_modules/semver/functions/compare-loose.js +var require_compare_loose = __commonJS({ + "../../node_modules/semver/functions/compare-loose.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var compareLoose = /* @__PURE__ */ __name((a, b) => compare(a, b, true), "compareLoose"); + module.exports = compareLoose; + } +}); + +// ../../node_modules/semver/functions/compare-build.js +var require_compare_build = __commonJS({ + "../../node_modules/semver/functions/compare-build.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var compareBuild = /* @__PURE__ */ __name((a, b, loose) => { + const versionA = new SemVer(a, loose); + const versionB = new SemVer(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + }, "compareBuild"); + module.exports = compareBuild; + } +}); + +// ../../node_modules/semver/functions/sort.js +var require_sort = __commonJS({ + "../../node_modules/semver/functions/sort.js"(exports2, module) { + "use strict"; + var compareBuild = require_compare_build(); + var sort = /* @__PURE__ */ __name((list, loose) => list.sort((a, b) => compareBuild(a, b, loose)), "sort"); + module.exports = sort; + } +}); + +// ../../node_modules/semver/functions/rsort.js +var require_rsort = __commonJS({ + "../../node_modules/semver/functions/rsort.js"(exports2, module) { + "use strict"; + var compareBuild = require_compare_build(); + var rsort = /* @__PURE__ */ __name((list, loose) => list.sort((a, b) => compareBuild(b, a, loose)), "rsort"); + module.exports = rsort; + } +}); + +// ../../node_modules/semver/functions/gt.js +var require_gt = __commonJS({ + "../../node_modules/semver/functions/gt.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var gt = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) > 0, "gt"); + module.exports = gt; + } +}); + +// ../../node_modules/semver/functions/lt.js +var require_lt = __commonJS({ + "../../node_modules/semver/functions/lt.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var lt = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) < 0, "lt"); + module.exports = lt; + } +}); + +// ../../node_modules/semver/functions/eq.js +var require_eq = __commonJS({ + "../../node_modules/semver/functions/eq.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var eq = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) === 0, "eq"); + module.exports = eq; + } +}); + +// ../../node_modules/semver/functions/neq.js +var require_neq = __commonJS({ + "../../node_modules/semver/functions/neq.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var neq = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) !== 0, "neq"); + module.exports = neq; + } +}); + +// ../../node_modules/semver/functions/gte.js +var require_gte = __commonJS({ + "../../node_modules/semver/functions/gte.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var gte = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) >= 0, "gte"); + module.exports = gte; + } +}); + +// ../../node_modules/semver/functions/lte.js +var require_lte = __commonJS({ + "../../node_modules/semver/functions/lte.js"(exports2, module) { + "use strict"; + var compare = require_compare(); + var lte = /* @__PURE__ */ __name((a, b, loose) => compare(a, b, loose) <= 0, "lte"); + module.exports = lte; + } +}); + +// ../../node_modules/semver/functions/cmp.js +var require_cmp = __commonJS({ + "../../node_modules/semver/functions/cmp.js"(exports2, module) { + "use strict"; + var eq = require_eq(); + var neq = require_neq(); + var gt = require_gt(); + var gte = require_gte(); + var lt = require_lt(); + var lte = require_lte(); + var cmp = /* @__PURE__ */ __name((a, op, b, loose) => { + switch (op) { + case "===": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a === b; + case "!==": + if (typeof a === "object") { + a = a.version; + } + if (typeof b === "object") { + b = b.version; + } + return a !== b; + case "": + case "=": + case "==": + return eq(a, b, loose); + case "!=": + return neq(a, b, loose); + case ">": + return gt(a, b, loose); + case ">=": + return gte(a, b, loose); + case "<": + return lt(a, b, loose); + case "<=": + return lte(a, b, loose); + default: + throw new TypeError(`Invalid operator: ${op}`); + } + }, "cmp"); + module.exports = cmp; + } +}); + +// ../../node_modules/semver/functions/coerce.js +var require_coerce = __commonJS({ + "../../node_modules/semver/functions/coerce.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var parse2 = require_parse(); + var { safeRe: re, t } = require_re(); + var coerce = /* @__PURE__ */ __name((version4, options) => { + if (version4 instanceof SemVer) { + return version4; + } + if (typeof version4 === "number") { + version4 = String(version4); + } + if (typeof version4 !== "string") { + return null; + } + options = options || {}; + let match = null; + if (!options.rtl) { + match = version4.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]); + } else { + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]; + let next; + while ((next = coerceRtlRegex.exec(version4)) && (!match || match.index + match[0].length !== version4.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; + } + coerceRtlRegex.lastIndex = -1; + } + if (match === null) { + return null; + } + const major = match[2]; + const minor = match[3] || "0"; + const patch = match[4] || "0"; + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; + const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; + return parse2(`${major}.${minor}.${patch}${prerelease}${build}`, options); + }, "coerce"); + module.exports = coerce; + } +}); + +// ../../node_modules/semver/functions/truncate.js +var require_truncate = __commonJS({ + "../../node_modules/semver/functions/truncate.js"(exports2, module) { + "use strict"; + var parse2 = require_parse(); + var constants = require_constants(); + var SemVer = require_semver(); + var truncate = /* @__PURE__ */ __name((version4, truncation, options) => { + if (!constants.RELEASE_TYPES.includes(truncation)) { + return null; + } + const clonedVersion = cloneInputVersion(version4, options); + return clonedVersion && doTruncation(clonedVersion, truncation); + }, "truncate"); + var cloneInputVersion = /* @__PURE__ */ __name((version4, options) => { + const versionStringToParse = version4 instanceof SemVer ? version4.version : version4; + return parse2(versionStringToParse, options); + }, "cloneInputVersion"); + var doTruncation = /* @__PURE__ */ __name((version4, truncation) => { + if (isPrerelease(truncation)) { + return version4.version; + } + version4.prerelease = []; + switch (truncation) { + case "major": + version4.minor = 0; + version4.patch = 0; + break; + case "minor": + version4.patch = 0; + break; + } + return version4.format(); + }, "doTruncation"); + var isPrerelease = /* @__PURE__ */ __name((type) => { + return type.startsWith("pre"); + }, "isPrerelease"); + module.exports = truncate; + } +}); + +// ../../node_modules/semver/internal/lrucache.js +var require_lrucache = __commonJS({ + "../../node_modules/semver/internal/lrucache.js"(exports2, module) { + "use strict"; + var LRUCache = class { + static { + __name(this, "LRUCache"); + } + constructor() { + this.max = 1e3; + this.map = /* @__PURE__ */ new Map(); + } + get(key) { + const value = this.map.get(key); + if (value === void 0) { + return void 0; + } else { + this.map.delete(key); + this.map.set(key, value); + return value; + } + } + delete(key) { + return this.map.delete(key); + } + set(key, value) { + const deleted = this.delete(key); + if (!deleted && value !== void 0) { + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value; + this.delete(firstKey); + } + this.map.set(key, value); + } + return this; + } + }; + module.exports = LRUCache; + } +}); + +// ../../node_modules/semver/classes/range.js +var require_range = __commonJS({ + "../../node_modules/semver/classes/range.js"(exports2, module) { + "use strict"; + var SPACE_CHARACTERS = /\s+/g; + var Range = class _Range { + static { + __name(this, "Range"); + } + constructor(range2, options) { + options = parseOptions(options); + if (range2 instanceof _Range) { + if (range2.loose === !!options.loose && range2.includePrerelease === !!options.includePrerelease) { + return range2; + } else { + return new _Range(range2.raw, options); + } + } + if (range2 instanceof Comparator) { + this.raw = range2.value; + this.set = [[range2]]; + this.formatted = void 0; + return this; + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range2.trim().replace(SPACE_CHARACTERS, " "); + this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`); + } + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter((c) => !isNullSet(c[0])); + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + this.formatted = void 0; + } + get range() { + if (this.formatted === void 0) { + this.formatted = ""; + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += "||"; + } + const comps = this.set[i]; + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += " "; + } + this.formatted += comps[k].toString().trim(); + } + } + } + return this.formatted; + } + format() { + return this.range; + } + toString() { + return this.range; + } + parseRange(range2) { + range2 = range2.replace(BUILDSTRIPRE, ""); + const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); + const memoKey = memoOpts + ":" + range2; + const cached = cache.get(memoKey); + if (cached) { + return cached; + } + const loose = this.options.loose; + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; + range2 = range2.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug("hyphen replace", range2); + range2 = range2.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); + debug("comparator trim", range2); + range2 = range2.replace(re[t.TILDETRIM], tildeTrimReplace); + debug("tilde trim", range2); + range2 = range2.replace(re[t.CARETTRIM], caretTrimReplace); + debug("caret trim", range2); + let rangeList = range2.split(" ").map((comp26) => parseComparator(comp26, this.options)).join(" ").split(/\s+/).map((comp26) => replaceGTE0(comp26, this.options)); + if (loose) { + rangeList = rangeList.filter((comp26) => { + debug("loose invalid filter", comp26, this.options); + return !!comp26.match(re[t.COMPARATORLOOSE]); + }); + } + debug("range list", rangeList); + const rangeMap = /* @__PURE__ */ new Map(); + const comparators = rangeList.map((comp26) => new Comparator(comp26, this.options)); + for (const comp26 of comparators) { + if (isNullSet(comp26)) { + return [comp26]; + } + rangeMap.set(comp26.value, comp26); + } + if (rangeMap.size > 1 && rangeMap.has("")) { + rangeMap.delete(""); + } + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result; + } + intersects(range2, options) { + if (!(range2 instanceof _Range)) { + throw new TypeError("a Range is required"); + } + return this.set.some((thisComparators) => { + return isSatisfiable(thisComparators, options) && range2.set.some((rangeComparators) => { + return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + // if ANY of the sets match ALL of its comparators, then pass + test(version4) { + if (!version4) { + return false; + } + if (typeof version4 === "string") { + try { + version4 = new SemVer(version4, this.options); + } catch (er) { + return false; + } + } + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version4, this.options)) { + return true; + } + } + return false; + } + }; + module.exports = Range; + var LRU = require_lrucache(); + var cache = new LRU(); + var parseOptions = require_parse_options(); + var Comparator = require_comparator(); + var debug = require_debug(); + var SemVer = require_semver(); + var { + safeRe: re, + src, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = require_re(); + var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); + var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g"); + var isNullSet = /* @__PURE__ */ __name((c) => c.value === "<0.0.0-0", "isNullSet"); + var isAny = /* @__PURE__ */ __name((c) => c.value === "", "isAny"); + var isSatisfiable = /* @__PURE__ */ __name((comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + }, "isSatisfiable"); + var parseComparator = /* @__PURE__ */ __name((comp26, options) => { + comp26 = comp26.replace(re[t.BUILD], ""); + debug("comp", comp26, options); + comp26 = replaceCarets(comp26, options); + debug("caret", comp26); + comp26 = replaceTildes(comp26, options); + debug("tildes", comp26); + comp26 = replaceXRanges(comp26, options); + debug("xrange", comp26); + comp26 = replaceStars(comp26, options); + debug("stars", comp26); + return comp26; + }, "parseComparator"); + var isX = /* @__PURE__ */ __name((id) => !id || id.toLowerCase() === "x" || id === "*", "isX"); + var invalidXRangeOrder = /* @__PURE__ */ __name((M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p), "invalidXRangeOrder"); + var replaceTildes = /* @__PURE__ */ __name((comp26, options) => { + return comp26.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" "); + }, "replaceTildes"); + var replaceTilde = /* @__PURE__ */ __name((comp26, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + const z = options.includePrerelease ? "-0" : ""; + return comp26.replace(r, (_, M, m, p, pr) => { + debug("tilde", comp26, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug("replaceTilde pr", pr); + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + debug("tilde return", ret); + return ret; + }); + }, "replaceTilde"); + var replaceCarets = /* @__PURE__ */ __name((comp26, options) => { + return comp26.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); + }, "replaceCarets"); + var replaceCaret = /* @__PURE__ */ __name((comp26, options) => { + debug("caret", comp26, options); + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + const z = options.includePrerelease ? "-0" : ""; + return comp26.replace(r, (_, M, m, p, pr) => { + debug("caret", comp26, _, M, m, p, pr); + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug("replaceCaret pr", pr); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug("no pr"); + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + debug("caret return", ret); + return ret; + }); + }, "replaceCaret"); + var replaceXRanges = /* @__PURE__ */ __name((comp26, options) => { + debug("replaceXRanges", comp26, options); + return comp26.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); + }, "replaceXRanges"); + var replaceXRange = /* @__PURE__ */ __name((comp26, options) => { + comp26 = comp26.trim(); + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp26.replace(r, (ret, gtlt, M, m, p, pr) => { + debug("xRange", comp26, ret, gtlt, M, m, p, pr); + if (invalidXRangeOrder(M, m, p)) { + return comp26; + } + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + debug("xRange return", ret); + return ret; + }); + }, "replaceXRange"); + var replaceStars = /* @__PURE__ */ __name((comp26, options) => { + debug("replaceStars", comp26, options); + return comp26.trim().replace(re[t.STAR], ""); + }, "replaceStars"); + var replaceGTE0 = /* @__PURE__ */ __name((comp26, options) => { + debug("replaceGTE0", comp26, options); + return comp26.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); + }, "replaceGTE0"); + var hyphenReplace = /* @__PURE__ */ __name((incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }, "hyphenReplace"); + var testSet = /* @__PURE__ */ __name((set, version4, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version4)) { + return false; + } + } + if (version4.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === Comparator.ANY) { + continue; + } + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + if (allowed.major === version4.major && allowed.minor === version4.minor && allowed.patch === version4.patch) { + return true; + } + } + } + return false; + } + return true; + }, "testSet"); + } +}); + +// ../../node_modules/semver/classes/comparator.js +var require_comparator = __commonJS({ + "../../node_modules/semver/classes/comparator.js"(exports2, module) { + "use strict"; + var ANY = /* @__PURE__ */ Symbol("SemVer ANY"); + var Comparator = class _Comparator { + static { + __name(this, "Comparator"); + } + static get ANY() { + return ANY; + } + constructor(comp26, options) { + options = parseOptions(options); + if (comp26 instanceof _Comparator) { + if (comp26.loose === !!options.loose) { + return comp26; + } else { + comp26 = comp26.value; + } + } + comp26 = comp26.trim().split(/\s+/).join(" "); + debug("comparator", comp26, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp26); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug("comp", this); + } + parse(comp26) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp26.match(r); + if (!m) { + throw new TypeError(`Invalid comparator: ${comp26}`); + } + this.operator = m[1] !== void 0 ? m[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + toString() { + return this.value; + } + test(version4) { + debug("Comparator.test", version4, this.options.loose); + if (this.semver === ANY || version4 === ANY) { + return true; + } + if (typeof version4 === "string") { + try { + version4 = new SemVer(version4, this.options); + } catch (er) { + return false; + } + } + return cmp(version4, this.operator, this.semver, this.options); + } + intersects(comp26, options) { + if (!(comp26 instanceof _Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (this.operator === "") { + if (this.value === "") { + return true; + } + return new Range(comp26.value, options).test(this.value); + } else if (comp26.operator === "") { + if (comp26.value === "") { + return true; + } + return new Range(this.value, options).test(comp26.semver); + } + options = parseOptions(options); + if (options.includePrerelease && (this.value === "<0.0.0-0" || comp26.value === "<0.0.0-0")) { + return false; + } + if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp26.value.startsWith("<0.0.0"))) { + return false; + } + if (this.operator.startsWith(">") && comp26.operator.startsWith(">")) { + return true; + } + if (this.operator.startsWith("<") && comp26.operator.startsWith("<")) { + return true; + } + if (this.semver.version === comp26.semver.version && this.operator.includes("=") && comp26.operator.includes("=")) { + return true; + } + if (cmp(this.semver, "<", comp26.semver, options) && this.operator.startsWith(">") && comp26.operator.startsWith("<")) { + return true; + } + if (cmp(this.semver, ">", comp26.semver, options) && this.operator.startsWith("<") && comp26.operator.startsWith(">")) { + return true; + } + return false; + } + }; + module.exports = Comparator; + var parseOptions = require_parse_options(); + var { safeRe: re, t } = require_re(); + var cmp = require_cmp(); + var debug = require_debug(); + var SemVer = require_semver(); + var Range = require_range(); + } +}); + +// ../../node_modules/semver/functions/satisfies.js +var require_satisfies = __commonJS({ + "../../node_modules/semver/functions/satisfies.js"(exports2, module) { + "use strict"; + var Range = require_range(); + var satisfies = /* @__PURE__ */ __name((version4, range2, options) => { + try { + range2 = new Range(range2, options); + } catch (er) { + return false; + } + return range2.test(version4); + }, "satisfies"); + module.exports = satisfies; + } +}); + +// ../../node_modules/semver/ranges/to-comparators.js +var require_to_comparators = __commonJS({ + "../../node_modules/semver/ranges/to-comparators.js"(exports2, module) { + "use strict"; + var Range = require_range(); + var toComparators = /* @__PURE__ */ __name((range2, options) => new Range(range2, options).set.map((comp26) => comp26.map((c) => c.value).join(" ").trim().split(" ")), "toComparators"); + module.exports = toComparators; + } +}); + +// ../../node_modules/semver/ranges/max-satisfying.js +var require_max_satisfying = __commonJS({ + "../../node_modules/semver/ranges/max-satisfying.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var maxSatisfying = /* @__PURE__ */ __name((versions, range2, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range2, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; + }, "maxSatisfying"); + module.exports = maxSatisfying; + } +}); + +// ../../node_modules/semver/ranges/min-satisfying.js +var require_min_satisfying = __commonJS({ + "../../node_modules/semver/ranges/min-satisfying.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var minSatisfying = /* @__PURE__ */ __name((versions, range2, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range2, options); + } catch (er) { + return null; + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; + }, "minSatisfying"); + module.exports = minSatisfying; + } +}); + +// ../../node_modules/semver/ranges/min-version.js +var require_min_version = __commonJS({ + "../../node_modules/semver/ranges/min-version.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var gt = require_gt(); + var minVersion = /* @__PURE__ */ __name((range2, loose) => { + range2 = new Range(range2, loose); + let minver = new SemVer("0.0.0"); + if (range2.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range2.test(minver)) { + return minver; + } + minver = null; + for (let i = 0; i < range2.set.length; ++i) { + const comparators = range2.set[i]; + let setMin = null; + comparators.forEach((comparator) => { + const compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!setMin || gt(compver, setMin)) { + setMin = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin; + } + } + if (minver && range2.test(minver)) { + return minver; + } + return null; + }, "minVersion"); + module.exports = minVersion; + } +}); + +// ../../node_modules/semver/ranges/valid.js +var require_valid2 = __commonJS({ + "../../node_modules/semver/ranges/valid.js"(exports2, module) { + "use strict"; + var Range = require_range(); + var validRange = /* @__PURE__ */ __name((range2, options) => { + try { + return new Range(range2, options).range || "*"; + } catch (er) { + return null; + } + }, "validRange"); + module.exports = validRange; + } +}); + +// ../../node_modules/semver/ranges/outside.js +var require_outside = __commonJS({ + "../../node_modules/semver/ranges/outside.js"(exports2, module) { + "use strict"; + var SemVer = require_semver(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var Range = require_range(); + var satisfies = require_satisfies(); + var gt = require_gt(); + var lt = require_lt(); + var lte = require_lte(); + var gte = require_gte(); + var outside = /* @__PURE__ */ __name((version4, range2, hilo, options) => { + version4 = new SemVer(version4, options); + range2 = new Range(range2, options); + let gtfn, ltefn, ltfn, comp26, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp26 = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp26 = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies(version4, range2, options)) { + return false; + } + for (let i = 0; i < range2.set.length; ++i) { + const comparators = range2.set[i]; + let high = null; + let low = null; + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp26 || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp26) && ltefn(version4, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version4, low.semver)) { + return false; + } + } + return true; + }, "outside"); + module.exports = outside; + } +}); + +// ../../node_modules/semver/ranges/gtr.js +var require_gtr = __commonJS({ + "../../node_modules/semver/ranges/gtr.js"(exports2, module) { + "use strict"; + var outside = require_outside(); + var gtr = /* @__PURE__ */ __name((version4, range2, options) => outside(version4, range2, ">", options), "gtr"); + module.exports = gtr; + } +}); + +// ../../node_modules/semver/ranges/ltr.js +var require_ltr = __commonJS({ + "../../node_modules/semver/ranges/ltr.js"(exports2, module) { + "use strict"; + var outside = require_outside(); + var ltr = /* @__PURE__ */ __name((version4, range2, options) => outside(version4, range2, "<", options), "ltr"); + module.exports = ltr; + } +}); + +// ../../node_modules/semver/ranges/intersects.js +var require_intersects = __commonJS({ + "../../node_modules/semver/ranges/intersects.js"(exports2, module) { + "use strict"; + var Range = require_range(); + var intersects = /* @__PURE__ */ __name((r1, r2, options) => { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2, options); + }, "intersects"); + module.exports = intersects; + } +}); + +// ../../node_modules/semver/ranges/simplify.js +var require_simplify = __commonJS({ + "../../node_modules/semver/ranges/simplify.js"(exports2, module) { + "use strict"; + var satisfies = require_satisfies(); + var compare = require_compare(); + module.exports = (versions, range2, options) => { + const set = []; + let first = null; + let prev = null; + const v = versions.sort((a, b) => compare(a, b, options)); + for (const version4 of v) { + const included = satisfies(version4, range2, options); + if (included) { + prev = version4; + if (!first) { + first = version4; + } + } else { + if (prev) { + set.push([first, prev]); + } + prev = null; + first = null; + } + } + if (first) { + set.push([first, null]); + } + const ranges = []; + for (const [min, max] of set) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v[0]) { + ranges.push("*"); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + const simplified = ranges.join(" || "); + const original = typeof range2.raw === "string" ? range2.raw : String(range2); + return simplified.length < original.length ? simplified : range2; + }; + } +}); + +// ../../node_modules/semver/ranges/subset.js +var require_subset = __commonJS({ + "../../node_modules/semver/ranges/subset.js"(exports2, module) { + "use strict"; + var Range = require_range(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var satisfies = require_satisfies(); + var compare = require_compare(); + var subset = /* @__PURE__ */ __name((sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) { + continue OUTER; + } + } + if (sawNonNull) { + return false; + } + } + return true; + }, "subset"); + var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; + var minimumVersion = [new Comparator(">=0.0.0")]; + var simpleSubset = /* @__PURE__ */ __name((sub, dom, options) => { + if (sub === dom) { + return true; + } + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease; + } else { + sub = minimumVersion; + } + } + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = minimumVersion; + } + } + const eqSet = /* @__PURE__ */ new Set(); + let gt, lt; + for (const c of sub) { + if (c.operator === ">" || c.operator === ">=") { + gt = higherGT(gt, c, options); + } else if (c.operator === "<" || c.operator === "<=") { + lt = lowerLT(lt, c, options); + } else { + eqSet.add(c.semver); + } + } + if (eqSet.size > 1) { + return null; + } + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { + return null; + } + } + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null; + } + if (lt && !satisfies(eq, String(lt), options)) { + return null; + } + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false; + } + } + return true; + } + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">="; + hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<="; + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c.operator === ">" || c.operator === ">=") { + higher = higherGT(gt, c, options); + if (higher === c && higher !== gt) { + return false; + } + } else if (gt.operator === ">=" && !c.test(gt.semver)) { + return false; + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c.operator === "<" || c.operator === "<=") { + lower = lowerLT(lt, c, options); + if (lower === c && lower !== lt) { + return false; + } + } else if (lt.operator === "<=" && !c.test(lt.semver)) { + return false; + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false; + } + } + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false; + } + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false; + } + if (needDomGTPre || needDomLTPre) { + return false; + } + return true; + }, "simpleSubset"); + var higherGT = /* @__PURE__ */ __name((a, b, options) => { + if (!a) { + return b; + } + const comp26 = compare(a.semver, b.semver, options); + return comp26 > 0 ? a : comp26 < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a; + }, "higherGT"); + var lowerLT = /* @__PURE__ */ __name((a, b, options) => { + if (!a) { + return b; + } + const comp26 = compare(a.semver, b.semver, options); + return comp26 < 0 ? a : comp26 > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a; + }, "lowerLT"); + module.exports = subset; + } +}); + +// ../../node_modules/semver/index.js +var require_semver2 = __commonJS({ + "../../node_modules/semver/index.js"(exports2, module) { + "use strict"; + var internalRe = require_re(); + var constants = require_constants(); + var SemVer = require_semver(); + var identifiers = require_identifiers(); + var parse2 = require_parse(); + var valid = require_valid(); + var clean = require_clean(); + var inc = require_inc(); + var diff = require_diff(); + var major = require_major(); + var minor = require_minor(); + var patch = require_patch(); + var prerelease = require_prerelease(); + var compare = require_compare(); + var rcompare = require_rcompare(); + var compareLoose = require_compare_loose(); + var compareBuild = require_compare_build(); + var sort = require_sort(); + var rsort = require_rsort(); + var gt = require_gt(); + var lt = require_lt(); + var eq = require_eq(); + var neq = require_neq(); + var gte = require_gte(); + var lte = require_lte(); + var cmp = require_cmp(); + var coerce = require_coerce(); + var truncate = require_truncate(); + var Comparator = require_comparator(); + var Range = require_range(); + var satisfies = require_satisfies(); + var toComparators = require_to_comparators(); + var maxSatisfying = require_max_satisfying(); + var minSatisfying = require_min_satisfying(); + var minVersion = require_min_version(); + var validRange = require_valid2(); + var outside = require_outside(); + var gtr = require_gtr(); + var ltr = require_ltr(); + var intersects = require_intersects(); + var simplifyRange = require_simplify(); + var subset = require_subset(); + module.exports = { + parse: parse2, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + truncate, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers + }; + } +}); + +// ../../node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js +var require_asymmetricKeyDetailsSupported = __commonJS({ + "../../node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js"(exports2, module) { + var semver = require_semver2(); + module.exports = semver.satisfies(process.version, ">=15.7.0"); + } +}); + +// ../../node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js +var require_rsaPssKeyDetailsSupported = __commonJS({ + "../../node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js"(exports2, module) { + var semver = require_semver2(); + module.exports = semver.satisfies(process.version, ">=16.9.0"); + } +}); + +// ../../node_modules/jsonwebtoken/lib/validateAsymmetricKey.js +var require_validateAsymmetricKey = __commonJS({ + "../../node_modules/jsonwebtoken/lib/validateAsymmetricKey.js"(exports2, module) { + var ASYMMETRIC_KEY_DETAILS_SUPPORTED = require_asymmetricKeyDetailsSupported(); + var RSA_PSS_KEY_DETAILS_SUPPORTED = require_rsaPssKeyDetailsSupported(); + var allowedAlgorithmsForKeys = { + "ec": ["ES256", "ES384", "ES512"], + "rsa": ["RS256", "PS256", "RS384", "PS384", "RS512", "PS512"], + "rsa-pss": ["PS256", "PS384", "PS512"] + }; + var allowedCurves = { + ES256: "prime256v1", + ES384: "secp384r1", + ES512: "secp521r1" + }; + module.exports = function(algorithm, key) { + if (!algorithm || !key) return; + const keyType = key.asymmetricKeyType; + if (!keyType) return; + const allowedAlgorithms = allowedAlgorithmsForKeys[keyType]; + if (!allowedAlgorithms) { + throw new Error(`Unknown key type "${keyType}".`); + } + if (!allowedAlgorithms.includes(algorithm)) { + throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(", ")}.`); + } + if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) { + switch (keyType) { + case "ec": + const keyCurve = key.asymmetricKeyDetails.namedCurve; + const allowedCurve = allowedCurves[algorithm]; + if (keyCurve !== allowedCurve) { + throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`); + } + break; + case "rsa-pss": + if (RSA_PSS_KEY_DETAILS_SUPPORTED) { + const length = parseInt(algorithm.slice(-3), 10); + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; + if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`); + } + if (saltLength !== void 0 && saltLength > length >> 3) { + throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`); + } + } + break; + } + } + }; + } +}); + +// ../../node_modules/jsonwebtoken/lib/psSupported.js +var require_psSupported = __commonJS({ + "../../node_modules/jsonwebtoken/lib/psSupported.js"(exports2, module) { + var semver = require_semver2(); + module.exports = semver.satisfies(process.version, "^6.12.0 || >=8.0.0"); + } +}); + +// ../../node_modules/jsonwebtoken/verify.js +var require_verify = __commonJS({ + "../../node_modules/jsonwebtoken/verify.js"(exports2, module) { + var JsonWebTokenError = require_JsonWebTokenError(); + var NotBeforeError = require_NotBeforeError(); + var TokenExpiredError = require_TokenExpiredError(); + var decode = require_decode(); + var timespan = require_timespan(); + var validateAsymmetricKey = require_validateAsymmetricKey(); + var PS_SUPPORTED = require_psSupported(); + var jws2 = require_jws(); + var { KeyObject, createSecretKey, createPublicKey } = __require("crypto"); + var PUB_KEY_ALGS = ["RS256", "RS384", "RS512"]; + var EC_KEY_ALGS = ["ES256", "ES384", "ES512"]; + var RSA_KEY_ALGS = ["RS256", "RS384", "RS512"]; + var HS_ALGS = ["HS256", "HS384", "HS512"]; + if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, "PS256", "PS384", "PS512"); + RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, "PS256", "PS384", "PS512"); + } + module.exports = function(jwtString, secretOrPublicKey, options, callback) { + if (typeof options === "function" && !callback) { + callback = options; + options = {}; + } + if (!options) { + options = {}; + } + options = Object.assign({}, options); + let done; + if (callback) { + done = callback; + } else { + done = /* @__PURE__ */ __name(function(err, data) { + if (err) throw err; + return data; + }, "done"); + } + if (options.clockTimestamp && typeof options.clockTimestamp !== "number") { + return done(new JsonWebTokenError("clockTimestamp must be a number")); + } + if (options.nonce !== void 0 && (typeof options.nonce !== "string" || options.nonce.trim() === "")) { + return done(new JsonWebTokenError("nonce must be a non-empty string")); + } + if (options.allowInvalidAsymmetricKeyTypes !== void 0 && typeof options.allowInvalidAsymmetricKeyTypes !== "boolean") { + return done(new JsonWebTokenError("allowInvalidAsymmetricKeyTypes must be a boolean")); + } + const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1e3); + if (!jwtString) { + return done(new JsonWebTokenError("jwt must be provided")); + } + if (typeof jwtString !== "string") { + return done(new JsonWebTokenError("jwt must be a string")); + } + const parts = jwtString.split("."); + if (parts.length !== 3) { + return done(new JsonWebTokenError("jwt malformed")); + } + let decodedToken; + try { + decodedToken = decode(jwtString, { complete: true }); + } catch (err) { + return done(err); + } + if (!decodedToken) { + return done(new JsonWebTokenError("invalid token")); + } + const header = decodedToken.header; + let getSecret; + if (typeof secretOrPublicKey === "function") { + if (!callback) { + return done(new JsonWebTokenError("verify must be called asynchronous if secret or public key is provided as a callback")); + } + getSecret = secretOrPublicKey; + } else { + getSecret = /* @__PURE__ */ __name(function(header2, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }, "getSecret"); + } + return getSecret(header, function(err, secretOrPublicKey2) { + if (err) { + return done(new JsonWebTokenError("error in secret or public key callback: " + err.message)); + } + const hasSignature = parts[2].trim() !== ""; + if (!hasSignature && secretOrPublicKey2) { + return done(new JsonWebTokenError("jwt signature is required")); + } + if (hasSignature && !secretOrPublicKey2) { + return done(new JsonWebTokenError("secret or public key must be provided")); + } + if (!hasSignature && !options.algorithms) { + return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens')); + } + if (secretOrPublicKey2 != null && !(secretOrPublicKey2 instanceof KeyObject)) { + try { + secretOrPublicKey2 = createPublicKey(secretOrPublicKey2); + } catch (_) { + try { + secretOrPublicKey2 = createSecretKey(typeof secretOrPublicKey2 === "string" ? Buffer.from(secretOrPublicKey2) : secretOrPublicKey2); + } catch (_2) { + return done(new JsonWebTokenError("secretOrPublicKey is not valid key material")); + } + } + } + if (!options.algorithms) { + if (secretOrPublicKey2.type === "secret") { + options.algorithms = HS_ALGS; + } else if (["rsa", "rsa-pss"].includes(secretOrPublicKey2.asymmetricKeyType)) { + options.algorithms = RSA_KEY_ALGS; + } else if (secretOrPublicKey2.asymmetricKeyType === "ec") { + options.algorithms = EC_KEY_ALGS; + } else { + options.algorithms = PUB_KEY_ALGS; + } + } + if (options.algorithms.indexOf(decodedToken.header.alg) === -1) { + return done(new JsonWebTokenError("invalid algorithm")); + } + if (header.alg.startsWith("HS") && secretOrPublicKey2.type !== "secret") { + return done(new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${header.alg}`)); + } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey2.type !== "public") { + return done(new JsonWebTokenError(`secretOrPublicKey must be an asymmetric key when using ${header.alg}`)); + } + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPublicKey2); + } catch (e) { + return done(e); + } + } + let valid; + try { + valid = jws2.verify(jwtString, decodedToken.header.alg, secretOrPublicKey2); + } catch (e) { + return done(e); + } + if (!valid) { + return done(new JsonWebTokenError("invalid signature")); + } + const payload = decodedToken.payload; + if (typeof payload.nbf !== "undefined" && !options.ignoreNotBefore) { + if (typeof payload.nbf !== "number") { + return done(new JsonWebTokenError("invalid nbf value")); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError("jwt not active", new Date(payload.nbf * 1e3))); + } + } + if (typeof payload.exp !== "undefined" && !options.ignoreExpiration) { + if (typeof payload.exp !== "number") { + return done(new JsonWebTokenError("invalid exp value")); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError("jwt expired", new Date(payload.exp * 1e3))); + } + } + if (options.audience) { + const audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + const match = target.some(function(targetAudience) { + return audiences.some(function(audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + if (!match) { + return done(new JsonWebTokenError("jwt audience invalid. expected: " + audiences.join(" or "))); + } + } + if (options.issuer) { + const invalid_issuer = typeof options.issuer === "string" && payload.iss !== options.issuer || Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1; + if (invalid_issuer) { + return done(new JsonWebTokenError("jwt issuer invalid. expected: " + options.issuer)); + } + } + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError("jwt subject invalid. expected: " + options.subject)); + } + } + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError("jwt jwtid invalid. expected: " + options.jwtid)); + } + } + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError("jwt nonce invalid. expected: " + options.nonce)); + } + } + if (options.maxAge) { + if (typeof payload.iat !== "number") { + return done(new JsonWebTokenError("iat required when maxAge is specified")); + } + const maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === "undefined") { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError("maxAge exceeded", new Date(maxAgeTimestamp * 1e3))); + } + } + if (options.complete === true) { + const signature = decodedToken.signature; + return done(null, { + header, + payload, + signature + }); + } + return done(null, payload); + }); + }; + } +}); + +// ../../node_modules/lodash.includes/index.js +var require_lodash = __commonJS({ + "../../node_modules/lodash.includes/index.js"(exports2, module) { + var INFINITY = 1 / 0; + var MAX_SAFE_INTEGER = 9007199254740991; + var MAX_INTEGER = 17976931348623157e292; + var NAN = 0 / 0; + var argsTag = "[object Arguments]"; + var funcTag = "[object Function]"; + var genTag = "[object GeneratorFunction]"; + var stringTag = "[object String]"; + var symbolTag = "[object Symbol]"; + var reTrim = /^\s+|\s+$/g; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsOctal = /^0o[0-7]+$/i; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var freeParseInt = parseInt; + function arrayMap(array, iteratee) { + var index = -1, length = array ? array.length : 0, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + __name(arrayMap, "arrayMap"); + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + __name(baseFindIndex, "baseFindIndex"); + function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + __name(baseIndexOf, "baseIndexOf"); + function baseIsNaN(value) { + return value !== value; + } + __name(baseIsNaN, "baseIsNaN"); + function baseTimes(n, iteratee) { + var index = -1, result = Array(n); + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + __name(baseTimes, "baseTimes"); + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + __name(baseValues, "baseValues"); + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + __name(overArg, "overArg"); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + var objectToString = objectProto.toString; + var propertyIsEnumerable = objectProto.propertyIsEnumerable; + var nativeKeys = overArg(Object.keys, Object); + var nativeMax = Math.max; + function arrayLikeKeys(value, inherited) { + var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : []; + var length = result.length, skipIndexes = !!length; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) { + result.push(key); + } + } + return result; + } + __name(arrayLikeKeys, "arrayLikeKeys"); + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != "constructor") { + result.push(key); + } + } + return result; + } + __name(baseKeys, "baseKeys"); + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); + } + __name(isIndex, "isIndex"); + function isPrototype(value) { + var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value === proto; + } + __name(isPrototype, "isPrototype"); + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; + } + __name(includes, "includes"); + function isArguments(value) { + return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag); + } + __name(isArguments, "isArguments"); + var isArray = Array.isArray; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + __name(isArrayLike, "isArrayLike"); + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + __name(isArrayLikeObject, "isArrayLikeObject"); + function isFunction(value) { + var tag = isObject2(value) ? objectToString.call(value) : ""; + return tag == funcTag || tag == genTag; + } + __name(isFunction, "isFunction"); + function isLength(value) { + return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + __name(isLength, "isLength"); + function isObject2(value) { + var type = typeof value; + return !!value && (type == "object" || type == "function"); + } + __name(isObject2, "isObject"); + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isString(value) { + return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + } + __name(isString, "isString"); + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + __name(isSymbol, "isSymbol"); + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber2(value); + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + __name(toFinite, "toFinite"); + function toInteger(value) { + var result = toFinite(value), remainder = result % 1; + return result === result ? remainder ? result - remainder : result : 0; + } + __name(toInteger, "toInteger"); + function toNumber2(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject2(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject2(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ""); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + } + __name(toNumber2, "toNumber"); + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + __name(keys, "keys"); + function values(object) { + return object ? baseValues(object, keys(object)) : []; + } + __name(values, "values"); + module.exports = includes; + } +}); + +// ../../node_modules/lodash.isboolean/index.js +var require_lodash2 = __commonJS({ + "../../node_modules/lodash.isboolean/index.js"(exports2, module) { + var boolTag = "[object Boolean]"; + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + function isBoolean(value) { + return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag; + } + __name(isBoolean, "isBoolean"); + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + module.exports = isBoolean; + } +}); + +// ../../node_modules/lodash.isinteger/index.js +var require_lodash3 = __commonJS({ + "../../node_modules/lodash.isinteger/index.js"(exports2, module) { + var INFINITY = 1 / 0; + var MAX_INTEGER = 17976931348623157e292; + var NAN = 0 / 0; + var symbolTag = "[object Symbol]"; + var reTrim = /^\s+|\s+$/g; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsOctal = /^0o[0-7]+$/i; + var freeParseInt = parseInt; + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + function isInteger(value) { + return typeof value == "number" && value == toInteger(value); + } + __name(isInteger, "isInteger"); + function isObject2(value) { + var type = typeof value; + return !!value && (type == "object" || type == "function"); + } + __name(isObject2, "isObject"); + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + __name(isSymbol, "isSymbol"); + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber2(value); + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + __name(toFinite, "toFinite"); + function toInteger(value) { + var result = toFinite(value), remainder = result % 1; + return result === result ? remainder ? result - remainder : result : 0; + } + __name(toInteger, "toInteger"); + function toNumber2(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject2(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject2(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ""); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + } + __name(toNumber2, "toNumber"); + module.exports = isInteger; + } +}); + +// ../../node_modules/lodash.isnumber/index.js +var require_lodash4 = __commonJS({ + "../../node_modules/lodash.isnumber/index.js"(exports2, module) { + var numberTag = "[object Number]"; + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isNumber(value) { + return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag; + } + __name(isNumber, "isNumber"); + module.exports = isNumber; + } +}); + +// ../../node_modules/lodash.isplainobject/index.js +var require_lodash5 = __commonJS({ + "../../node_modules/lodash.isplainobject/index.js"(exports2, module) { + var objectTag = "[object Object]"; + function isHostObject(value) { + var result = false; + if (value != null && typeof value.toString != "function") { + try { + result = !!(value + ""); + } catch (e) { + } + } + return result; + } + __name(isHostObject, "isHostObject"); + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + __name(overArg, "overArg"); + var funcProto = Function.prototype; + var objectProto = Object.prototype; + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var objectCtorString = funcToString.call(Object); + var objectToString = objectProto.toString; + var getPrototype = overArg(Object.getPrototypeOf, Object); + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isPlainObject(value) { + if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; + } + __name(isPlainObject, "isPlainObject"); + module.exports = isPlainObject; + } +}); + +// ../../node_modules/lodash.isstring/index.js +var require_lodash6 = __commonJS({ + "../../node_modules/lodash.isstring/index.js"(exports2, module) { + var stringTag = "[object String]"; + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + var isArray = Array.isArray; + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isString(value) { + return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag; + } + __name(isString, "isString"); + module.exports = isString; + } +}); + +// ../../node_modules/lodash.once/index.js +var require_lodash7 = __commonJS({ + "../../node_modules/lodash.once/index.js"(exports2, module) { + var FUNC_ERROR_TEXT = "Expected a function"; + var INFINITY = 1 / 0; + var MAX_INTEGER = 17976931348623157e292; + var NAN = 0 / 0; + var symbolTag = "[object Symbol]"; + var reTrim = /^\s+|\s+$/g; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsOctal = /^0o[0-7]+$/i; + var freeParseInt = parseInt; + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + function before(n, func) { + var result; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = void 0; + } + return result; + }; + } + __name(before, "before"); + function once3(func) { + return before(2, func); + } + __name(once3, "once"); + function isObject2(value) { + var type = typeof value; + return !!value && (type == "object" || type == "function"); + } + __name(isObject2, "isObject"); + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + __name(isSymbol, "isSymbol"); + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber2(value); + if (value === INFINITY || value === -INFINITY) { + var sign = value < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + __name(toFinite, "toFinite"); + function toInteger(value) { + var result = toFinite(value), remainder = result % 1; + return result === result ? remainder ? result - remainder : result : 0; + } + __name(toInteger, "toInteger"); + function toNumber2(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject2(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject2(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ""); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + } + __name(toNumber2, "toNumber"); + module.exports = once3; + } +}); + +// ../../node_modules/jsonwebtoken/sign.js +var require_sign = __commonJS({ + "../../node_modules/jsonwebtoken/sign.js"(exports2, module) { + var timespan = require_timespan(); + var PS_SUPPORTED = require_psSupported(); + var validateAsymmetricKey = require_validateAsymmetricKey(); + var jws2 = require_jws(); + var includes = require_lodash(); + var isBoolean = require_lodash2(); + var isInteger = require_lodash3(); + var isNumber = require_lodash4(); + var isPlainObject = require_lodash5(); + var isString = require_lodash6(); + var once3 = require_lodash7(); + var { KeyObject, createSecretKey, createPrivateKey } = __require("crypto"); + var SUPPORTED_ALGS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512", "none"]; + if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, "PS256", "PS384", "PS512"); + } + var sign_options_schema = { + expiresIn: { isValid: /* @__PURE__ */ __name(function(value) { + return isInteger(value) || isString(value) && value; + }, "isValid"), message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: /* @__PURE__ */ __name(function(value) { + return isInteger(value) || isString(value) && value; + }, "isValid"), message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: /* @__PURE__ */ __name(function(value) { + return isString(value) || Array.isArray(value); + }, "isValid"), message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' }, + allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean' }, + allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean' } + }; + var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } + }; + function validate2(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object).forEach(function(key) { + const validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); + } + __name(validate2, "validate"); + function validateOptions(options) { + return validate2(sign_options_schema, false, options, "options"); + } + __name(validateOptions, "validateOptions"); + function validatePayload(payload) { + return validate2(registered_claims_schema, true, payload, "payload"); + } + __name(validatePayload, "validatePayload"); + var options_to_payload = { + "audience": "aud", + "issuer": "iss", + "subject": "sub", + "jwtid": "jti" + }; + var options_for_objects = [ + "expiresIn", + "notBefore", + "noTimestamp", + "audience", + "issuer", + "subject", + "jwtid" + ]; + module.exports = function(payload, secretOrPrivateKey, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else { + options = options || {}; + } + const isObjectPayload = typeof payload === "object" && !Buffer.isBuffer(payload); + const header = Object.assign({ + alg: options.algorithm || "HS256", + typ: isObjectPayload ? "JWT" : void 0, + kid: options.keyid + }, options.header); + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } + __name(failure, "failure"); + if (!secretOrPrivateKey && options.algorithm !== "none") { + return failure(new Error("secretOrPrivateKey must have a value")); + } + if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) { + try { + secretOrPrivateKey = createPrivateKey(secretOrPrivateKey); + } catch (_) { + try { + secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === "string" ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey); + } catch (_2) { + return failure(new Error("secretOrPrivateKey is not valid key material")); + } + } + } + if (header.alg.startsWith("HS") && secretOrPrivateKey.type !== "secret") { + return failure(new Error(`secretOrPrivateKey must be a symmetric key when using ${header.alg}`)); + } else if (/^(?:RS|PS|ES)/.test(header.alg)) { + if (secretOrPrivateKey.type !== "private") { + return failure(new Error(`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`)); + } + if (!options.allowInsecureKeySizes && !header.alg.startsWith("ES") && secretOrPrivateKey.asymmetricKeyDetails !== void 0 && //KeyObject.asymmetricKeyDetails is supported in Node 15+ + secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) { + return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)); + } + } + if (typeof payload === "undefined") { + return failure(new Error("payload is required")); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({}, payload); + } + } else { + const invalid_options = options_for_objects.filter(function(opt) { + return typeof options[opt] !== "undefined"; + }); + if (invalid_options.length > 0) { + return failure(new Error("invalid " + invalid_options.join(",") + " option for " + typeof payload + " payload")); + } + } + if (typeof payload.exp !== "undefined" && typeof options.expiresIn !== "undefined") { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } + if (typeof payload.nbf !== "undefined" && typeof options.notBefore !== "undefined") { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } + try { + validateOptions(options); + } catch (error) { + return failure(error); + } + if (!options.allowInvalidAsymmetricKeyTypes) { + try { + validateAsymmetricKey(header.alg, secretOrPrivateKey); + } catch (error) { + return failure(error); + } + } + const timestamp = payload.iat || Math.floor(Date.now() / 1e3); + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } + if (typeof options.notBefore !== "undefined") { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } catch (err) { + return failure(err); + } + if (typeof payload.nbf === "undefined") { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + if (typeof options.expiresIn !== "undefined" && typeof payload === "object") { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } catch (err) { + return failure(err); + } + if (typeof payload.exp === "undefined") { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } + Object.keys(options_to_payload).forEach(function(key) { + const claim = options_to_payload[key]; + if (typeof options[key] !== "undefined") { + if (typeof payload[claim] !== "undefined") { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); + const encoding = options.encoding || "utf8"; + if (typeof callback === "function") { + callback = callback && once3(callback); + jws2.createSign({ + header, + privateKey: secretOrPrivateKey, + payload, + encoding + }).once("error", callback).once("done", function(signature) { + if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`)); + } + callback(null, signature); + }); + } else { + let signature = jws2.sign({ header, payload, secret: secretOrPrivateKey, encoding }); + if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) { + throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`); + } + return signature; + } + }; + } +}); + +// ../../node_modules/jsonwebtoken/index.js +var require_jsonwebtoken = __commonJS({ + "../../node_modules/jsonwebtoken/index.js"(exports2, module) { + module.exports = { + decode: require_decode(), + verify: require_verify(), + sign: require_sign(), + JsonWebTokenError: require_JsonWebTokenError(), + NotBeforeError: require_NotBeforeError(), + TokenExpiredError: require_TokenExpiredError() + }; + } +}); + +// ../../node_modules/jws/lib/data-stream.js +var require_data_stream2 = __commonJS({ + "../../node_modules/jws/lib/data-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var Stream2 = __require("stream"); + var util3 = __require("util"); + function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + if (!data) { + this.buffer = Buffer3.alloc(0); + return this; + } + if (typeof data.pipe === "function") { + this.buffer = Buffer3.alloc(0); + data.pipe(this); + return this; + } + if (data.length || typeof data === "object") { + this.buffer = data; + this.writable = false; + process.nextTick(function() { + this.emit("end", data); + this.readable = false; + this.emit("close"); + }.bind(this)); + return this; + } + throw new TypeError("Unexpected data type (" + typeof data + ")"); + } + __name(DataStream, "DataStream"); + util3.inherits(DataStream, Stream2); + DataStream.prototype.write = /* @__PURE__ */ __name(function write(data) { + this.buffer = Buffer3.concat([this.buffer, Buffer3.from(data)]); + this.emit("data", data); + }, "write"); + DataStream.prototype.end = /* @__PURE__ */ __name(function end(data) { + if (data) + this.write(data); + this.emit("end", data); + this.emit("close"); + this.writable = false; + this.readable = false; + }, "end"); + module.exports = DataStream; + } +}); + +// ../../node_modules/jws/lib/tostring.js +var require_tostring2 = __commonJS({ + "../../node_modules/jws/lib/tostring.js"(exports2, module) { + var Buffer3 = __require("buffer").Buffer; + module.exports = /* @__PURE__ */ __name(function toString3(obj) { + if (typeof obj === "string") + return obj; + if (typeof obj === "number" || typeof obj === "bigint" || Buffer3.isBuffer(obj)) + return obj.toString(); + const marker2 = "__BIGINT_" + Math.random().toString(36).slice(2) + "__"; + const json = JSON.stringify( + obj, + (_k, v) => typeof v === "bigint" ? marker2 + v.toString() + marker2 : v + ); + return json.replace(new RegExp('"' + marker2 + "(-?\\d+)" + marker2 + '"', "g"), "$1"); + }, "toString"); + } +}); + +// ../../node_modules/jws/lib/sign-stream.js +var require_sign_stream2 = __commonJS({ + "../../node_modules/jws/lib/sign-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var DataStream = require_data_stream2(); + var jwa = require_jwa(); + var Stream2 = __require("stream"); + var toString3 = require_tostring2(); + var util3 = __require("util"); + function base64url(string, encoding) { + return Buffer3.from(string, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); + } + __name(base64url, "base64url"); + function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || "utf8"; + var encodedHeader = base64url(toString3(header), "binary"); + var encodedPayload = base64url(toString3(payload), encoding); + return util3.format("%s.%s", encodedHeader, encodedPayload); + } + __name(jwsSecuredInput, "jwsSecuredInput"); + function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util3.format("%s.%s", securedInput, signature); + } + __name(jwsSign, "jwsSign"); + function SignStream(opts) { + var secret = opts.secret; + secret = secret == null ? opts.privateKey : secret; + secret = secret == null ? opts.key : secret; + if (/^hs/i.test(opts.header.alg) === true && secret == null) { + throw new TypeError("secret must be a string or buffer or a KeyObject"); + } + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once("close", function() { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + this.payload.once("close", function() { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); + } + __name(SignStream, "SignStream"); + util3.inherits(SignStream, Stream2); + SignStream.prototype.sign = /* @__PURE__ */ __name(function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit("done", signature); + this.emit("data", signature); + this.emit("end"); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit("error", e); + this.emit("close"); + } + }, "sign"); + SignStream.sign = jwsSign; + module.exports = SignStream; + } +}); + +// ../../node_modules/jws/lib/verify-stream.js +var require_verify_stream2 = __commonJS({ + "../../node_modules/jws/lib/verify-stream.js"(exports2, module) { + var Buffer3 = require_safe_buffer().Buffer; + var DataStream = require_data_stream2(); + var jwa = require_jwa(); + var Stream2 = __require("stream"); + var toString3 = require_tostring2(); + var util3 = __require("util"); + var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + function isObject2(thing) { + return Object.prototype.toString.call(thing) === "[object Object]"; + } + __name(isObject2, "isObject"); + function safeJsonParse(thing) { + if (isObject2(thing)) + return thing; + try { + return JSON.parse(thing); + } catch (e) { + return void 0; + } + } + __name(safeJsonParse, "safeJsonParse"); + function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split(".", 1)[0]; + return safeJsonParse(Buffer3.from(encodedHeader, "base64").toString("binary")); + } + __name(headerFromJWS, "headerFromJWS"); + function securedInputFromJWS(jwsSig) { + return jwsSig.split(".", 2).join("."); + } + __name(securedInputFromJWS, "securedInputFromJWS"); + function signatureFromJWS(jwsSig) { + return jwsSig.split(".")[2]; + } + __name(signatureFromJWS, "signatureFromJWS"); + function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || "utf8"; + var payload = jwsSig.split(".")[1]; + return Buffer3.from(payload, "base64").toString(encoding); + } + __name(payloadFromJWS, "payloadFromJWS"); + function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); + } + __name(isValidJws, "isValidJws"); + function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString3(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); + } + __name(jwsVerify, "jwsVerify"); + function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString3(jwsSig); + if (!isValidJws(jwsSig)) + return null; + var header = headerFromJWS(jwsSig); + if (!header) + return null; + var payload = payloadFromJWS(jwsSig); + if (header.typ === "JWT" || opts.json) + payload = JSON.parse(payload, opts.encoding); + return { + header, + payload, + signature: signatureFromJWS(jwsSig) + }; + } + __name(jwsDecode, "jwsDecode"); + function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret; + secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey; + secretOrKey = secretOrKey == null ? opts.key : secretOrKey; + if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) { + throw new TypeError("secret must be a string or buffer or a KeyObject"); + } + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once("close", function() { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + this.signature.once("close", function() { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); + } + __name(VerifyStream, "VerifyStream"); + util3.inherits(VerifyStream, Stream2); + VerifyStream.prototype.verify = /* @__PURE__ */ __name(function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit("done", valid, obj); + this.emit("data", valid); + this.emit("end"); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit("error", e); + this.emit("close"); + } + }, "verify"); + VerifyStream.decode = jwsDecode; + VerifyStream.isValid = isValidJws; + VerifyStream.verify = jwsVerify; + module.exports = VerifyStream; + } +}); + +// ../../node_modules/jws/index.js +var require_jws2 = __commonJS({ + "../../node_modules/jws/index.js"(exports2) { + var SignStream = require_sign_stream2(); + var VerifyStream = require_verify_stream2(); + var ALGORITHMS = [ + "HS256", + "HS384", + "HS512", + "RS256", + "RS384", + "RS512", + "PS256", + "PS384", + "PS512", + "ES256", + "ES384", + "ES512" + ]; + exports2.ALGORITHMS = ALGORITHMS; + exports2.sign = SignStream.sign; + exports2.verify = VerifyStream.verify; + exports2.decode = VerifyStream.decode; + exports2.isValid = VerifyStream.isValid; + exports2.createSign = /* @__PURE__ */ __name(function createSign(opts) { + return new SignStream(opts); + }, "createSign"); + exports2.createVerify = /* @__PURE__ */ __name(function createVerify(opts) { + return new VerifyStream(opts); + }, "createVerify"); + } +}); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js +var AbortError = class extends Error { + static { + __name(this, "AbortError"); + } + constructor(message) { + super(message); + this.name = "AbortError"; + } +}; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js +import { EOL } from "node:os"; +import util from "node:util"; +import process2 from "node:process"; +function log(message, ...args) { + process2.stderr.write(`${util.format(message, ...args)}${EOL}`); +} +__name(log, "log"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/env.js +import process3 from "node:process"; +function getEnvironmentVariable(name3) { + return process3.env[name3]; +} +__name(getEnvironmentVariable, "getEnvironmentVariable"); +var isDeno = typeof process3.versions.deno === "string" && process3.versions.deno.length > 0; +var isBun = typeof process3.versions.bun === "string" && process3.versions.bun.length > 0; +var isNodeLike = true; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js +var debugEnvVariable = getEnvironmentVariable("DEBUG"); +var enabledString; +var enabledNamespaces = []; +var skippedNamespaces = []; +var debuggers = []; +if (debugEnvVariable) { + enable(debugEnvVariable); +} +var debugObj = Object.assign((namespace) => { + return createDebugger(namespace); +}, { + enable, + enabled, + disable, + log +}); +function enable(namespaces) { + enabledString = namespaces; + enabledNamespaces = []; + skippedNamespaces = []; + const namespaceList = namespaces.split(",").map((ns) => ns.trim()); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(ns.substring(1)); + } else { + enabledNamespaces.push(ns); + } + } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); + } +} +__name(enable, "enable"); +function enabled(namespace) { + if (namespace.endsWith("*")) { + return true; + } + for (const skipped of skippedNamespaces) { + if (namespaceMatches(namespace, skipped)) { + return false; + } + } + for (const enabledNamespace of enabledNamespaces) { + if (namespaceMatches(namespace, enabledNamespace)) { + return true; + } + } + return false; +} +__name(enabled, "enabled"); +function namespaceMatches(namespace, patternToMatch) { + if (patternToMatch.indexOf("*") === -1) { + return namespace === patternToMatch; + } + let pattern = patternToMatch; + if (patternToMatch.indexOf("**") !== -1) { + const patternParts = []; + let lastCharacter = ""; + for (const character of patternToMatch) { + if (character === "*" && lastCharacter === "*") { + continue; + } else { + lastCharacter = character; + patternParts.push(character); + } + } + pattern = patternParts.join(""); + } + let namespaceIndex = 0; + let patternIndex = 0; + const patternLength = pattern.length; + const namespaceLength = namespace.length; + let lastWildcard = -1; + let lastWildcardNamespace = -1; + while (namespaceIndex < namespaceLength && patternIndex < patternLength) { + if (pattern[patternIndex] === "*") { + lastWildcard = patternIndex; + patternIndex++; + if (patternIndex === patternLength) { + return true; + } + while (namespace[namespaceIndex] !== pattern[patternIndex]) { + namespaceIndex++; + if (namespaceIndex === namespaceLength) { + return false; + } + } + lastWildcardNamespace = namespaceIndex; + namespaceIndex++; + patternIndex++; + continue; + } else if (pattern[patternIndex] === namespace[namespaceIndex]) { + patternIndex++; + namespaceIndex++; + } else if (lastWildcard >= 0) { + patternIndex = lastWildcard + 1; + namespaceIndex = lastWildcardNamespace + 1; + if (namespaceIndex === namespaceLength) { + return false; + } + while (namespace[namespaceIndex] !== pattern[patternIndex]) { + namespaceIndex++; + if (namespaceIndex === namespaceLength) { + return false; + } + } + lastWildcardNamespace = namespaceIndex; + namespaceIndex++; + patternIndex++; + continue; + } else { + return false; + } + } + const namespaceDone = namespaceIndex === namespace.length; + const patternDone = patternIndex === pattern.length; + const trailingWildCard = patternIndex === pattern.length - 1 && pattern[patternIndex] === "*"; + return namespaceDone && (patternDone || trailingWildCard); +} +__name(namespaceMatches, "namespaceMatches"); +function disable() { + const result = enabledString || ""; + enable(""); + return result; +} +__name(disable, "disable"); +function createDebugger(namespace) { + const newDebugger = Object.assign(debug, { + enabled: enabled(namespace), + destroy, + log: debugObj.log, + namespace, + extend + }); + function debug(...args) { + if (!newDebugger.enabled) { + return; + } + if (args.length > 0) { + args[0] = `${namespace} ${args[0]}`; + } + newDebugger.log(...args); + } + __name(debug, "debug"); + debuggers.push(newDebugger); + return newDebugger; +} +__name(createDebugger, "createDebugger"); +function destroy() { + const index = debuggers.indexOf(this); + if (index >= 0) { + debuggers.splice(index, 1); + return true; + } + return false; +} +__name(destroy, "destroy"); +function extend(namespace) { + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); + newDebugger.log = this.log; + return newDebugger; +} +__name(extend, "extend"); +var debug_default = debugObj; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js +var TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +var levelMap = { + verbose: 400, + info: 300, + warning: 200, + error: 100 +}; +function patchLogMethod(parent, child) { + child.log = (...args) => { + parent.log(...args); + }; +} +__name(patchLogMethod, "patchLogMethod"); +function isTypeSpecRuntimeLogLevel(level) { + return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level); +} +__name(isTypeSpecRuntimeLogLevel, "isTypeSpecRuntimeLogLevel"); +function createLoggerContext(options) { + const registeredLoggers = /* @__PURE__ */ new Set(); + const logLevelFromEnv = getEnvironmentVariable(options.logLevelEnvVarName); + let logLevel; + const clientLogger = debug_default(options.namespace); + clientLogger.log = (...args) => { + debug_default.log(...args); + }; + function contextSetLogLevel(level) { + if (level && !isTypeSpecRuntimeLogLevel(level)) { + throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`); + } + logLevel = level; + const enabledNamespaces2 = []; + for (const logger8 of registeredLoggers) { + if (shouldEnable(logger8)) { + enabledNamespaces2.push(logger8.namespace); + } + } + debug_default.enable(enabledNamespaces2.join(",")); + } + __name(contextSetLogLevel, "contextSetLogLevel"); + if (logLevelFromEnv) { + if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) { + contextSetLogLevel(logLevelFromEnv); + } else { + console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`); + } + } + function shouldEnable(logger8) { + return Boolean(logLevel && levelMap[logger8.level] <= levelMap[logLevel]); + } + __name(shouldEnable, "shouldEnable"); + function createLogger(parent, level) { + const logger8 = Object.assign(parent.extend(level), { + level + }); + patchLogMethod(parent, logger8); + if (shouldEnable(logger8)) { + const enabledNamespaces2 = debug_default.disable(); + debug_default.enable(enabledNamespaces2 + "," + logger8.namespace); + } + registeredLoggers.add(logger8); + return logger8; + } + __name(createLogger, "createLogger"); + function contextGetLogLevel() { + return logLevel; + } + __name(contextGetLogLevel, "contextGetLogLevel"); + function contextCreateClientLogger(namespace) { + const clientRootLogger = clientLogger.extend(namespace); + patchLogMethod(clientLogger, clientRootLogger); + return { + error: createLogger(clientRootLogger, "error"), + warning: createLogger(clientRootLogger, "warning"), + info: createLogger(clientRootLogger, "info"), + verbose: createLogger(clientRootLogger, "verbose") + }; + } + __name(contextCreateClientLogger, "contextCreateClientLogger"); + return { + setLogLevel: contextSetLogLevel, + getLogLevel: contextGetLogLevel, + createClientLogger: contextCreateClientLogger, + logger: clientLogger + }; +} +__name(createLoggerContext, "createLoggerContext"); +var context = createLoggerContext({ + logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL", + namespace: "typeSpecRuntime" +}); +var TypeSpecRuntimeLogger = context.logger; +function createClientLogger(namespace) { + return context.createClientLogger(namespace); +} +__name(createClientLogger, "createClientLogger"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js +function normalizeName(name3) { + return name3.toLowerCase(); +} +__name(normalizeName, "normalizeName"); +function normalizeValue(value) { + return String(value).trim().replace(/[\r\n]/g, ""); +} +__name(normalizeValue, "normalizeValue"); +function* headerIterator(map) { + for (const entry of map.values()) { + yield [entry.name, entry.value]; + } +} +__name(headerIterator, "headerIterator"); +var HttpHeadersImpl = class { + static { + __name(this, "HttpHeadersImpl"); + } + _headersMap; + constructor(rawHeaders) { + this._headersMap = /* @__PURE__ */ new Map(); + if (rawHeaders) { + for (const headerName of Object.keys(rawHeaders)) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param name - The name of the header to set. This value is case-insensitive. + * @param value - The value of the header to set. + */ + set(name3, value) { + this._headersMap.set(normalizeName(name3), { name: name3, value: normalizeValue(value) }); + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param name - The name of the header. This value is case-insensitive. + */ + get(name3) { + return this._headersMap.get(normalizeName(name3))?.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + * @param name - The name of the header to set. This value is case-insensitive. + */ + has(name3) { + return this._headersMap.has(normalizeName(name3)); + } + /** + * Remove the header with the provided headerName. + * @param name - The name of the header to remove. + */ + delete(name3) { + this._headersMap.delete(normalizeName(name3)); + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJSON(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const entry of this._headersMap.values()) { + result[entry.name] = entry.value; + } + } else { + for (const [normalizedName, entry] of this._headersMap) { + result[normalizedName] = entry.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJSON({ preserveCase: true })); + } + /** + * Iterate over tuples of header [name, value] pairs. + */ + [Symbol.iterator]() { + return headerIterator(this._headersMap); + } +}; +function createHttpHeaders(rawHeaders) { + return new HttpHeadersImpl(rawHeaders); +} +__name(createHttpHeaders, "createHttpHeaders"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js +function randomUUID() { + return globalThis.crypto.randomUUID(); +} +__name(randomUUID, "randomUUID"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js +var PipelineRequestImpl = class { + static { + __name(this, "PipelineRequestImpl"); + } + url; + method; + headers; + timeout; + withCredentials; + body; + multipartBody; + formData; + streamResponseStatusCodes; + enableBrowserStreams; + proxySettings; + disableKeepAlive; + abortSignal; + requestId; + allowInsecureConnection; + onUploadProgress; + onDownloadProgress; + requestOverrides; + authSchemes; + constructor(options) { + this.url = options.url; + this.body = options.body; + this.headers = options.headers ?? createHttpHeaders(); + this.method = options.method ?? "GET"; + this.timeout = options.timeout ?? 0; + this.multipartBody = options.multipartBody; + this.formData = options.formData; + this.disableKeepAlive = options.disableKeepAlive ?? false; + this.proxySettings = options.proxySettings; + this.streamResponseStatusCodes = options.streamResponseStatusCodes; + this.withCredentials = options.withCredentials ?? false; + this.abortSignal = options.abortSignal; + this.onUploadProgress = options.onUploadProgress; + this.onDownloadProgress = options.onDownloadProgress; + this.requestId = options.requestId || randomUUID(); + this.allowInsecureConnection = options.allowInsecureConnection ?? false; + this.enableBrowserStreams = options.enableBrowserStreams ?? false; + this.requestOverrides = options.requestOverrides; + this.authSchemes = options.authSchemes; + } +}; +function createPipelineRequest(options) { + return new PipelineRequestImpl(options); +} +__name(createPipelineRequest, "createPipelineRequest"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js +var ValidPhaseNames = /* @__PURE__ */ new Set(["Deserialize", "Serialize", "Retry", "Sign"]); +var HttpPipeline = class _HttpPipeline { + static { + __name(this, "HttpPipeline"); + } + _policies = []; + _orderedPolicies; + constructor(policies) { + this._policies = policies?.slice(0) ?? []; + this._orderedPolicies = void 0; + } + addPolicy(policy, options = {}) { + if (options.phase && options.afterPhase) { + throw new Error("Policies inside a phase cannot specify afterPhase."); + } + if (options.phase && !ValidPhaseNames.has(options.phase)) { + throw new Error(`Invalid phase name: ${options.phase}`); + } + if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { + throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); + } + this._policies.push({ + policy, + options + }); + this._orderedPolicies = void 0; + } + removePolicy(options) { + const removedPolicies = []; + this._policies = this._policies.filter((policyDescriptor) => { + if (options.name && policyDescriptor.policy.name === options.name || options.phase && policyDescriptor.options.phase === options.phase) { + removedPolicies.push(policyDescriptor.policy); + return false; + } else { + return true; + } + }); + this._orderedPolicies = void 0; + return removedPolicies; + } + sendRequest(httpClient, request) { + const policies = this.getOrderedPolicies(); + const pipeline2 = policies.reduceRight((next, policy) => { + return (req) => { + return policy.sendRequest(req, next); + }; + }, (req) => httpClient.sendRequest(req)); + return pipeline2(request); + } + getOrderedPolicies() { + if (!this._orderedPolicies) { + this._orderedPolicies = this.orderPolicies(); + } + return this._orderedPolicies; + } + clone() { + return new _HttpPipeline(this._policies); + } + static create() { + return new _HttpPipeline(); + } + orderPolicies() { + const result = []; + const policyMap = /* @__PURE__ */ new Map(); + function createPhase(name3) { + return { + name: name3, + policies: /* @__PURE__ */ new Set(), + hasRun: false, + hasAfterPolicies: false + }; + } + __name(createPhase, "createPhase"); + const serializePhase = createPhase("Serialize"); + const noPhase = createPhase("None"); + const deserializePhase = createPhase("Deserialize"); + const retryPhase = createPhase("Retry"); + const signPhase = createPhase("Sign"); + const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; + function getPhase(phase) { + if (phase === "Retry") { + return retryPhase; + } else if (phase === "Serialize") { + return serializePhase; + } else if (phase === "Deserialize") { + return deserializePhase; + } else if (phase === "Sign") { + return signPhase; + } else { + return noPhase; + } + } + __name(getPhase, "getPhase"); + for (const descriptor of this._policies) { + const policy = descriptor.policy; + const options = descriptor.options; + const policyName = policy.name; + if (policyMap.has(policyName)) { + throw new Error("Duplicate policy names not allowed in pipeline"); + } + const node = { + policy, + dependsOn: /* @__PURE__ */ new Set(), + dependants: /* @__PURE__ */ new Set() + }; + if (options.afterPhase) { + node.afterPhase = getPhase(options.afterPhase); + node.afterPhase.hasAfterPolicies = true; + } + policyMap.set(policyName, node); + const phase = getPhase(options.phase); + phase.policies.add(node); + } + for (const descriptor of this._policies) { + const { policy, options } = descriptor; + const policyName = policy.name; + const node = policyMap.get(policyName); + if (!node) { + throw new Error(`Missing node for policy ${policyName}`); + } + if (options.afterPolicies) { + for (const afterPolicyName of options.afterPolicies) { + const afterNode = policyMap.get(afterPolicyName); + if (afterNode) { + node.dependsOn.add(afterNode); + afterNode.dependants.add(node); + } + } + } + if (options.beforePolicies) { + for (const beforePolicyName of options.beforePolicies) { + const beforeNode = policyMap.get(beforePolicyName); + if (beforeNode) { + beforeNode.dependsOn.add(node); + node.dependants.add(beforeNode); + } + } + } + } + function walkPhase(phase) { + phase.hasRun = true; + for (const node of phase.policies) { + if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { + continue; + } + if (node.dependsOn.size === 0) { + result.push(node.policy); + for (const dependant of node.dependants) { + dependant.dependsOn.delete(node); + } + policyMap.delete(node.policy.name); + phase.policies.delete(node); + } + } + } + __name(walkPhase, "walkPhase"); + function walkPhases() { + for (const phase of orderedPhases) { + walkPhase(phase); + if (phase.policies.size > 0 && phase !== noPhase) { + if (!noPhase.hasRun) { + walkPhase(noPhase); + } + return; + } + if (phase.hasAfterPolicies) { + walkPhase(noPhase); + } + } + } + __name(walkPhases, "walkPhases"); + let iteration = 0; + while (policyMap.size > 0) { + iteration++; + const initialResultLength = result.length; + walkPhases(); + if (result.length <= initialResultLength && iteration > 1) { + throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); + } + } + return result; + } +}; +function createEmptyPipeline() { + return HttpPipeline.create(); +} +__name(createEmptyPipeline, "createEmptyPipeline"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js +function isObject(input) { + return typeof input === "object" && input !== null && !Array.isArray(input) && !(input instanceof RegExp) && !(input instanceof Date); +} +__name(isObject, "isObject"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js +function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +__name(isError, "isError"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js +import { inspect } from "node:util"; +var custom = inspect.custom; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js +var RedactedString = "REDACTED"; +var defaultAllowedHeaderNames = [ + "x-ms-client-request-id", + "x-ms-return-client-request-id", + "x-ms-useragent", + "x-ms-correlation-request-id", + "x-ms-request-id", + "client-request-id", + "ms-cv", + "return-client-request-id", + "traceparent", + "Access-Control-Allow-Credentials", + "Access-Control-Allow-Headers", + "Access-Control-Allow-Methods", + "Access-Control-Allow-Origin", + "Access-Control-Expose-Headers", + "Access-Control-Max-Age", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Origin", + "Accept", + "Accept-Encoding", + "Cache-Control", + "Connection", + "Content-Length", + "Content-Type", + "Date", + "ETag", + "Expires", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Unmodified-Since", + "Last-Modified", + "Pragma", + "Request-Id", + "Retry-After", + "Server", + "Transfer-Encoding", + "User-Agent", + "WWW-Authenticate" +]; +var defaultAllowedQueryParameters = ["api-version"]; +var Sanitizer = class { + static { + __name(this, "Sanitizer"); + } + allowedHeaderNames; + allowedQueryParameters; + constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [] } = {}) { + allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); + allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); + } + /** + * Sanitizes an object for logging. + * @param obj - The object to sanitize + * @returns - The sanitized object as a string + */ + sanitize(obj) { + const seen = /* @__PURE__ */ new Set(); + return JSON.stringify(obj, (key, value) => { + if (value instanceof Error) { + return { + ...value, + name: value.name, + message: value.message + }; + } + if (key === "headers" && isObject(value)) { + return this.sanitizeHeaders(value); + } else if (key === "url" && typeof value === "string") { + return this.sanitizeUrl(value); + } else if (key === "query" && isObject(value)) { + return this.sanitizeQuery(value); + } else if (key === "body") { + return void 0; + } else if (key === "response") { + return void 0; + } else if (key === "operationSpec") { + return void 0; + } else if (Array.isArray(value) || isObject(value)) { + if (seen.has(value)) { + return "[Circular]"; + } + seen.add(value); + } + return value; + }, 2); + } + /** + * Sanitizes a URL for logging. + * @param value - The URL to sanitize + * @returns - The sanitized URL as a string + */ + sanitizeUrl(value) { + if (typeof value !== "string" || value === null || value === "") { + return value; + } + const url2 = new URL(value); + if (!url2.search) { + return value; + } + for (const [key] of url2.searchParams) { + if (!this.allowedQueryParameters.has(key.toLowerCase())) { + url2.searchParams.set(key, RedactedString); + } + } + return url2.toString(); + } + sanitizeHeaders(obj) { + const sanitized = {}; + for (const key of Object.keys(obj)) { + if (this.allowedHeaderNames.has(key.toLowerCase())) { + sanitized[key] = obj[key]; + } else { + sanitized[key] = RedactedString; + } + } + return sanitized; + } + sanitizeQuery(value) { + if (typeof value !== "object" || value === null) { + return value; + } + const sanitized = {}; + for (const k of Object.keys(value)) { + if (this.allowedQueryParameters.has(k.toLowerCase())) { + sanitized[k] = value[k]; + } else { + sanitized[k] = RedactedString; + } + } + return sanitized; + } +}; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/restError.js +var errorSanitizer = new Sanitizer(); +var RestError = class _RestError extends Error { + static { + __name(this, "RestError"); + } + /** + * Something went wrong when making the request. + * This means the actual request failed for some reason, + * such as a DNS issue or the connection being lost. + */ + static REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; + /** + * This means that parsing the response from the server failed. + * It may have been malformed. + */ + static PARSE_ERROR = "PARSE_ERROR"; + /** + * The code of the error itself (use statics on RestError if possible.) + */ + code; + /** + * The HTTP status code of the request (if applicable.) + */ + statusCode; + /** + * The request that was made. + * This property is non-enumerable. + */ + request; + /** + * The response received (if any.) + * This property is non-enumerable. + */ + response; + /** + * Bonus property set by the throw site. + */ + details; + constructor(message, options = {}) { + super(message); + this.name = "RestError"; + this.code = options.code; + this.statusCode = options.statusCode; + Object.defineProperty(this, "request", { value: options.request, enumerable: false }); + Object.defineProperty(this, "response", { value: options.response, enumerable: false }); + const agent = this.request?.agent ? { + maxFreeSockets: this.request.agent.maxFreeSockets, + maxSockets: this.request.agent.maxSockets + } : void 0; + Object.defineProperty(this, custom, { + value: /* @__PURE__ */ __name(() => { + return `RestError: ${this.message} + ${errorSanitizer.sanitize({ + ...this, + request: { ...this.request, agent }, + response: this.response + })}`; + }, "value"), + enumerable: false + }); + Object.setPrototypeOf(this, _RestError.prototype); + } +}; +function isRestError(e) { + if (e instanceof RestError) { + return true; + } + return isError(e) && e.name === "RestError"; +} +__name(isRestError, "isRestError"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js +function uint8ArrayToString(bytes, format) { + return Buffer.from(bytes).toString(format); +} +__name(uint8ArrayToString, "uint8ArrayToString"); +function stringToUint8Array(value, format) { + return Buffer.from(value, format); +} +__name(stringToUint8Array, "stringToUint8Array"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js +import http from "node:http"; +import https from "node:https"; +import zlib from "node:zlib"; +import { Transform } from "node:stream"; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/log.js +var logger = createClientLogger("ts-http-runtime"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js +var DEFAULT_TLS_SETTINGS = {}; +function isReadableStream(body2) { + return body2 && typeof body2.pipe === "function"; +} +__name(isReadableStream, "isReadableStream"); +function isStreamComplete(stream) { + if (stream.readable === false) { + return Promise.resolve(); + } + return new Promise((resolve) => { + const handler = /* @__PURE__ */ __name(() => { + resolve(); + stream.removeListener("close", handler); + stream.removeListener("end", handler); + stream.removeListener("error", handler); + }, "handler"); + stream.on("close", handler); + stream.on("end", handler); + stream.on("error", handler); + }); +} +__name(isStreamComplete, "isStreamComplete"); +function isArrayBuffer(body2) { + return body2 && typeof body2.byteLength === "number"; +} +__name(isArrayBuffer, "isArrayBuffer"); +var ReportTransform = class extends Transform { + static { + __name(this, "ReportTransform"); + } + loadedBytes = 0; + progressCallback; + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + _transform(chunk, _encoding, callback) { + this.push(chunk); + this.loadedBytes += chunk.length; + try { + this.progressCallback({ loadedBytes: this.loadedBytes }); + callback(); + } catch (e) { + callback(e); + } + } + constructor(progressCallback) { + super(); + this.progressCallback = progressCallback; + } +}; +var NodeHttpClient = class { + static { + __name(this, "NodeHttpClient"); + } + cachedHttpAgent; + cachedHttpsAgents = /* @__PURE__ */ new WeakMap(); + /** + * Makes a request over an underlying transport layer and returns the response. + * @param request - The request to be made. + */ + async sendRequest(request) { + const abortController = new AbortController(); + let abortListener; + if (request.abortSignal) { + if (request.abortSignal.aborted) { + throw new AbortError("The operation was aborted. Request has already been canceled."); + } + abortListener = /* @__PURE__ */ __name((event) => { + if (event.type === "abort") { + abortController.abort(); + } + }, "abortListener"); + request.abortSignal.addEventListener("abort", abortListener); + } + let timeoutId; + if (request.timeout > 0) { + timeoutId = setTimeout(() => { + const sanitizer = new Sanitizer(); + logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`); + abortController.abort(); + }, request.timeout); + } + const acceptEncoding = request.headers.get("Accept-Encoding"); + const shouldDecompress = acceptEncoding?.includes("gzip") || acceptEncoding?.includes("deflate"); + let body2 = typeof request.body === "function" ? request.body() : request.body; + if (body2 && !request.headers.has("Content-Length")) { + const bodyLength = getBodyLength(body2); + if (bodyLength !== null) { + request.headers.set("Content-Length", bodyLength); + } + } + let responseStream; + try { + if (body2 && request.onUploadProgress) { + const onUploadProgress = request.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + uploadReportStream.on("error", (e) => { + logger.error("Error in upload progress", e); + }); + if (isReadableStream(body2)) { + body2.pipe(uploadReportStream); + } else { + uploadReportStream.end(body2); + } + body2 = uploadReportStream; + } + const res = await this.makeRequest(request, abortController, body2); + if (timeoutId !== void 0) { + clearTimeout(timeoutId); + } + const headers = getResponseHeaders(res); + const status = res.statusCode ?? 0; + const response = { + status, + headers, + request + }; + if (request.method === "HEAD") { + res.resume(); + return response; + } + responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; + const onDownloadProgress = request.onDownloadProgress; + if (onDownloadProgress) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + downloadReportStream.on("error", (e) => { + logger.error("Error in download progress", e); + }); + responseStream.pipe(downloadReportStream); + responseStream = downloadReportStream; + } + if ( + // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code + request.streamResponseStatusCodes?.has(Number.POSITIVE_INFINITY) || request.streamResponseStatusCodes?.has(response.status) + ) { + response.readableStreamBody = responseStream; + } else { + response.bodyAsText = await streamToText(responseStream); + } + return response; + } finally { + if (request.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body2)) { + uploadStreamDone = isStreamComplete(body2); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(responseStream)) { + downloadStreamDone = isStreamComplete(responseStream); + } + Promise.all([uploadStreamDone, downloadStreamDone]).then(() => { + if (abortListener) { + request.abortSignal?.removeEventListener("abort", abortListener); + } + }).catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } + makeRequest(request, abortController, body2) { + const url2 = new URL(request.url); + const isInsecure = url2.protocol !== "https:"; + if (isInsecure && !request.allowInsecureConnection) { + throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); + } + const agent = request.agent ?? this.getOrCreateAgent(request, isInsecure); + const options = { + agent, + hostname: url2.hostname, + path: `${url2.pathname}${url2.search}`, + port: url2.port, + method: request.method, + headers: request.headers.toJSON({ preserveCase: true }), + ...request.requestOverrides + }; + return new Promise((resolve, reject) => { + const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve); + req.once("error", (err) => { + reject(new RestError(err.message, { code: err.code ?? RestError.REQUEST_SEND_ERROR, request })); + }); + abortController.signal.addEventListener("abort", () => { + const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request."); + req.destroy(abortError); + reject(abortError); + }); + if (body2 && isReadableStream(body2)) { + body2.pipe(req); + } else if (body2) { + if (typeof body2 === "string" || Buffer.isBuffer(body2)) { + req.end(body2); + } else if (isArrayBuffer(body2)) { + req.end(ArrayBuffer.isView(body2) ? Buffer.from(body2.buffer, body2.byteOffset, body2.byteLength) : Buffer.from(body2)); + } else { + logger.error("Unrecognized body type", body2); + reject(new RestError("Unrecognized body type")); + } + } else { + req.end(); + } + }); + } + getOrCreateAgent(request, isInsecure) { + const disableKeepAlive = request.disableKeepAlive; + if (isInsecure) { + if (disableKeepAlive) { + return http.globalAgent; + } + if (!this.cachedHttpAgent) { + this.cachedHttpAgent = new http.Agent({ keepAlive: true }); + } + return this.cachedHttpAgent; + } else { + if (disableKeepAlive && !request.tlsSettings) { + return https.globalAgent; + } + const tlsSettings = request.tlsSettings ?? DEFAULT_TLS_SETTINGS; + let agent = this.cachedHttpsAgents.get(tlsSettings); + if (agent && agent.options.keepAlive === !disableKeepAlive) { + return agent; + } + logger.info("No cached TLS Agent exist, creating a new Agent"); + agent = new https.Agent({ + // keepAlive is true if disableKeepAlive is false. + keepAlive: !disableKeepAlive, + // Since we are spreading, if no tslSettings were provided, nothing is added to the agent options. + ...tlsSettings + }); + this.cachedHttpsAgents.set(tlsSettings, agent); + return agent; + } + } +}; +function getResponseHeaders(res) { + const headers = createHttpHeaders(); + for (const header of Object.keys(res.headers)) { + const value = res.headers[header]; + if (Array.isArray(value)) { + if (value.length > 0) { + headers.set(header, value[0]); + } + } else if (value) { + headers.set(header, value); + } + } + return headers; +} +__name(getResponseHeaders, "getResponseHeaders"); +function getDecodedResponseStream(stream, headers) { + const contentEncoding = headers.get("Content-Encoding"); + if (contentEncoding === "gzip") { + const unzip = zlib.createGunzip(); + stream.pipe(unzip); + return unzip; + } else if (contentEncoding === "deflate") { + const inflate = zlib.createInflate(); + stream.pipe(inflate); + return inflate; + } + return stream; +} +__name(getDecodedResponseStream, "getDecodedResponseStream"); +function streamToText(stream) { + return new Promise((resolve, reject) => { + const buffer2 = []; + stream.on("data", (chunk) => { + if (Buffer.isBuffer(chunk)) { + buffer2.push(chunk); + } else { + buffer2.push(Buffer.from(chunk)); + } + }); + stream.on("end", () => { + resolve(Buffer.concat(buffer2).toString("utf8")); + }); + stream.on("error", (e) => { + if (e && e?.name === "AbortError") { + reject(e); + } else { + reject(new RestError(`Error reading response as text: ${e.message}`, { + code: RestError.PARSE_ERROR + })); + } + }); + }); +} +__name(streamToText, "streamToText"); +function getBodyLength(body2) { + if (!body2) { + return 0; + } else if (Buffer.isBuffer(body2)) { + return body2.length; + } else if (isReadableStream(body2)) { + return null; + } else if (isArrayBuffer(body2)) { + return body2.byteLength; + } else if (typeof body2 === "string") { + return Buffer.from(body2).length; + } else { + return null; + } +} +__name(getBodyLength, "getBodyLength"); +function createNodeHttpClient() { + return new NodeHttpClient(); +} +__name(createNodeHttpClient, "createNodeHttpClient"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js +function createDefaultHttpClient() { + return createNodeHttpClient(); +} +__name(createDefaultHttpClient, "createDefaultHttpClient"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js +var logPolicyName = "logPolicy"; +function logPolicy(options = {}) { + const logger8 = options.logger ?? logger.info; + const sanitizer = new Sanitizer({ + additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + return { + name: logPolicyName, + async sendRequest(request, next) { + if (!logger8.enabled) { + return next(request); + } + logger8(`Request: ${sanitizer.sanitize(request)}`); + const response = await next(request); + logger8(`Response status code: ${response.status}`); + logger8(`Headers: ${sanitizer.sanitize({ headers: response.headers })}`); + return response; + } + }; +} +__name(logPolicy, "logPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgentPlatform.js +function getHeaderName() { + return "User-Agent"; +} +__name(getHeaderName, "getHeaderName"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/constants.js +var DEFAULT_RETRY_POLICY_COUNT = 3; + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/userAgent.js +function getUserAgentHeaderName() { + return getHeaderName(); +} +__name(getUserAgentHeaderName, "getUserAgentHeaderName"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/userAgentPolicy.js +var UserAgentHeaderName = getUserAgentHeaderName(); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js +function getRandomIntegerInclusive(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} +__name(getRandomIntegerInclusive, "getRandomIntegerInclusive"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js +function calculateRetryDelay(retryAttempt, config) { + const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); + const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); + const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2); + return { retryAfterInMs }; +} +__name(calculateRetryDelay, "calculateRetryDelay"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js +var StandardAbortMessage = "The operation was aborted."; +function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = void 0; + let onAborted = void 0; + const rejectOnAbort = /* @__PURE__ */ __name(() => { + return reject(new AbortError(options?.abortErrorMsg ? options?.abortErrorMsg : StandardAbortMessage)); + }, "rejectOnAbort"); + const removeListeners = /* @__PURE__ */ __name(() => { + if (options?.abortSignal && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }, "removeListeners"); + onAborted = /* @__PURE__ */ __name(() => { + if (timer) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }, "onAborted"); + if (options?.abortSignal && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options?.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); +} +__name(delay, "delay"); +function parseHeaderValueAsNumber(response, headerName) { + const value = response.headers.get(headerName); + if (!value) + return; + const valueAsNum = Number(value); + if (Number.isNaN(valueAsNum)) + return; + return valueAsNum; +} +__name(parseHeaderValueAsNumber, "parseHeaderValueAsNumber"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js +var RetryAfterHeader = "Retry-After"; +var AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; +function getRetryAfterInMs(response) { + if (!(response && [429, 503].includes(response.status))) + return void 0; + try { + for (const header of AllRetryAfterHeaders) { + const retryAfterValue = parseHeaderValueAsNumber(response, header); + if (retryAfterValue === 0 || retryAfterValue) { + const multiplyingFactor = header === RetryAfterHeader ? 1e3 : 1; + return retryAfterValue * multiplyingFactor; + } + } + const retryAfterHeader = response.headers.get(RetryAfterHeader); + if (!retryAfterHeader) + return; + const date = Date.parse(retryAfterHeader); + const diff = date - Date.now(); + return Number.isFinite(diff) ? Math.max(0, diff) : void 0; + } catch { + return void 0; + } +} +__name(getRetryAfterInMs, "getRetryAfterInMs"); +function isThrottlingRetryResponse(response) { + return Number.isFinite(getRetryAfterInMs(response)); +} +__name(isThrottlingRetryResponse, "isThrottlingRetryResponse"); +function throttlingRetryStrategy() { + return { + name: "throttlingRetryStrategy", + retry({ response }) { + const retryAfterInMs = getRetryAfterInMs(response); + if (!Number.isFinite(retryAfterInMs)) { + return { skipStrategy: true }; + } + return { + retryAfterInMs + }; + } + }; +} +__name(throttlingRetryStrategy, "throttlingRetryStrategy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js +var DEFAULT_CLIENT_RETRY_INTERVAL = 1e3; +var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1e3 * 64; +function exponentialRetryStrategy(options = {}) { + const retryInterval = options.retryDelayInMs ?? DEFAULT_CLIENT_RETRY_INTERVAL; + const maxRetryInterval = options.maxRetryDelayInMs ?? DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + return { + name: "exponentialRetryStrategy", + retry({ retryCount, response, responseError }) { + const matchedSystemError = isSystemError(responseError); + const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; + const isExponential = isExponentialRetryResponse(response); + const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; + const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential); + if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { + return { skipStrategy: true }; + } + if (responseError && !matchedSystemError && !isExponential) { + return { errorToThrow: responseError }; + } + return calculateRetryDelay(retryCount, { + retryDelayInMs: retryInterval, + maxRetryDelayInMs: maxRetryInterval + }); + } + }; +} +__name(exponentialRetryStrategy, "exponentialRetryStrategy"); +function isExponentialRetryResponse(response) { + return Boolean(response && response.status !== void 0 && (response.status >= 500 || response.status === 408) && response.status !== 501 && response.status !== 505); +} +__name(isExponentialRetryResponse, "isExponentialRetryResponse"); +function isSystemError(err) { + if (!err) { + return false; + } + return err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || err.code === "ECONNRESET" || err.code === "ENOENT" || err.code === "ENOTFOUND"; +} +__name(isSystemError, "isSystemError"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js +var retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy"); +var retryPolicyName = "retryPolicy"; +function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) { + const logger8 = options.logger || retryPolicyLogger; + return { + name: retryPolicyName, + async sendRequest(request, next) { + let response; + let responseError; + let retryCount = -1; + retryRequest: while (true) { + retryCount += 1; + response = void 0; + responseError = void 0; + try { + logger8.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); + response = await next(request); + logger8.info(`Retry ${retryCount}: Received a response from request`, request.requestId); + } catch (e) { + logger8.error(`Retry ${retryCount}: Received an error from request`, request.requestId); + if (!isRestError(e)) { + throw e; + } + responseError = e; + response = e.response; + } + if (request.abortSignal?.aborted) { + logger8.error(`Retry ${retryCount}: Request aborted.`); + const abortError = new AbortError(); + throw abortError; + } + if (retryCount >= (options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT)) { + logger8.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + if (responseError) { + throw responseError; + } else if (response) { + return response; + } else { + throw new Error("Maximum retries reached with no response or error to throw"); + } + } + logger8.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + strategiesLoop: for (const strategy of strategies) { + const strategyLogger = strategy.logger || logger8; + strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); + const modifiers = strategy.retry({ + retryCount, + response, + responseError + }); + if (modifiers.skipStrategy) { + strategyLogger.info(`Retry ${retryCount}: Skipped.`); + continue strategiesLoop; + } + const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; + if (errorToThrow) { + strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); + throw errorToThrow; + } + if (retryAfterInMs || retryAfterInMs === 0) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); + await delay(retryAfterInMs, void 0, { abortSignal: request.abortSignal }); + continue retryRequest; + } + if (redirectTo) { + strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); + request.url = redirectTo; + continue retryRequest; + } + } + if (responseError) { + logger8.info(`None of the retry strategies could work with the received error. Throwing it.`); + throw responseError; + } + if (response) { + logger8.info(`None of the retry strategies could work with the received response. Returning it.`); + return response; + } + } + } + }; +} +__name(retryPolicy, "retryPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js +var defaultRetryPolicyName = "defaultRetryPolicy"; +function defaultRetryPolicy(options = {}) { + return { + name: defaultRetryPolicyName, + sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], { + maxRetries: options.maxRetries ?? DEFAULT_RETRY_POLICY_COUNT + }).sendRequest + }; +} +__name(defaultRetryPolicy, "defaultRetryPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/formData.js +function convertBodyToFormDataMap(body2) { + if (typeof FormData !== "undefined" && body2 instanceof FormData) { + const formDataMap = {}; + for (const [key, value] of body2.entries()) { + const existing = formDataMap[key]; + if (Array.isArray(existing)) { + existing.push(value); + } else { + formDataMap[key] = existing !== void 0 ? [existing, value] : [value]; + } + } + return formDataMap; + } + return void 0; +} +__name(convertBodyToFormDataMap, "convertBodyToFormDataMap"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js +var formDataPolicyName = "formDataPolicy"; +function formDataPolicy() { + return { + name: formDataPolicyName, + async sendRequest(request, next) { + const converted = convertBodyToFormDataMap(request.body); + if (converted) { + request.formData = converted; + request.body = void 0; + } + if (request.formData) { + const contentType2 = request.headers.get("Content-Type"); + if (contentType2 && contentType2.indexOf("application/x-www-form-urlencoded") !== -1) { + request.body = wwwFormUrlEncode(request.formData); + } else { + await prepareFormData(request.formData, request); + } + request.formData = void 0; + } + return next(request); + } + }; +} +__name(formDataPolicy, "formDataPolicy"); +function wwwFormUrlEncode(formData) { + const urlSearchParams = new URLSearchParams(); + for (const [key, value] of Object.entries(formData)) { + if (Array.isArray(value)) { + for (const subValue of value) { + urlSearchParams.append(key, subValue.toString()); + } + } else { + urlSearchParams.append(key, value.toString()); + } + } + return urlSearchParams.toString(); +} +__name(wwwFormUrlEncode, "wwwFormUrlEncode"); +async function prepareFormData(formData, request) { + const contentType2 = request.headers.get("Content-Type"); + if (contentType2 && !contentType2.startsWith("multipart/form-data")) { + return; + } + request.headers.set("Content-Type", contentType2 ?? "multipart/form-data"); + const parts = []; + for (const [fieldName, values] of Object.entries(formData)) { + for (const value of Array.isArray(values) ? values : [values]) { + if (typeof value === "string") { + parts.push({ + headers: createHttpHeaders({ + "Content-Disposition": `form-data; name="${fieldName}"` + }), + body: stringToUint8Array(value, "utf-8") + }); + } else if (value === void 0 || value === null || typeof value !== "object") { + throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); + } else { + const fileName = value.name || "blob"; + const headers = createHttpHeaders(); + headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); + headers.set("Content-Type", value.type || "application/octet-stream"); + parts.push({ + headers, + body: value + }); + } + } + } + request.multipartBody = { parts }; +} +__name(prepareFormData, "prepareFormData"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js +var agentPolicyName = "agentPolicy"; +function agentPolicy(agent) { + return { + name: agentPolicyName, + sendRequest: /* @__PURE__ */ __name(async (req, next) => { + if (!req.agent) { + req.agent = agent; + } + return next(req); + }, "sendRequest") + }; +} +__name(agentPolicy, "agentPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js +var tlsPolicyName = "tlsPolicy"; +function tlsPolicy(tlsSettings) { + return { + name: tlsPolicyName, + sendRequest: /* @__PURE__ */ __name(async (req, next) => { + if (!req.tlsSettings) { + req.tlsSettings = tlsSettings; + } + return next(req); + }, "sendRequest") + }; +} +__name(tlsPolicy, "tlsPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js +var import_https_proxy_agent = __toESM(require_dist2(), 1); +var import_http_proxy_agent = __toESM(require_dist3(), 1); +var HTTPS_PROXY = "HTTPS_PROXY"; +var HTTP_PROXY = "HTTP_PROXY"; +var ALL_PROXY = "ALL_PROXY"; +var NO_PROXY = "NO_PROXY"; +var proxyPolicyName = "proxyPolicy"; +var globalNoProxyList = []; +var noProxyListLoaded = false; +var globalBypassedMap = /* @__PURE__ */ new Map(); +function getEnvironmentValue(name3) { + if (process.env[name3]) { + return process.env[name3]; + } else if (process.env[name3.toLowerCase()]) { + return process.env[name3.toLowerCase()]; + } + return void 0; +} +__name(getEnvironmentValue, "getEnvironmentValue"); +function loadEnvironmentProxyValue() { + if (!process) { + return void 0; + } + const httpsProxy = getEnvironmentValue(HTTPS_PROXY); + const allProxy = getEnvironmentValue(ALL_PROXY); + const httpProxy = getEnvironmentValue(HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +__name(loadEnvironmentProxyValue, "loadEnvironmentProxyValue"); +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = new URL(uri).hostname; + if (bypassedMap?.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } + } else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap?.set(host, isBypassedFlag); + return isBypassedFlag; +} +__name(isBypassed, "isBypassed"); +function loadNoProxy() { + const noProxy = getEnvironmentValue(NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy.split(",").map((item) => item.trim()).filter((item) => item.length); + } + return []; +} +__name(loadNoProxy, "loadNoProxy"); +function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return void 0; + } + } + const parsedUrl = new URL(proxyUrl); + const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; + return { + host: schema + parsedUrl.hostname, + port: Number.parseInt(parsedUrl.port || "80"), + username: parsedUrl.username, + password: parsedUrl.password + }; +} +__name(getDefaultProxySettings, "getDefaultProxySettings"); +function getDefaultProxySettingsInternal() { + const envProxy = loadEnvironmentProxyValue(); + return envProxy ? new URL(envProxy) : void 0; +} +__name(getDefaultProxySettingsInternal, "getDefaultProxySettingsInternal"); +function getUrlFromProxySettings(settings) { + let parsedProxyUrl; + try { + parsedProxyUrl = new URL(settings.host); + } catch { + throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); + } + parsedProxyUrl.port = String(settings.port); + if (settings.username) { + parsedProxyUrl.username = settings.username; + } + if (settings.password) { + parsedProxyUrl.password = settings.password; + } + return parsedProxyUrl; +} +__name(getUrlFromProxySettings, "getUrlFromProxySettings"); +function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { + if (request.agent) { + return; + } + const url2 = new URL(request.url); + const isInsecure = url2.protocol !== "https:"; + if (request.tlsSettings) { + logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); + } + if (isInsecure) { + if (!cachedAgents.httpProxyAgent) { + cachedAgents.httpProxyAgent = new import_http_proxy_agent.HttpProxyAgent(proxyUrl); + } + request.agent = cachedAgents.httpProxyAgent; + } else { + if (!cachedAgents.httpsProxyAgent) { + cachedAgents.httpsProxyAgent = new import_https_proxy_agent.HttpsProxyAgent(proxyUrl); + } + request.agent = cachedAgents.httpsProxyAgent; + } +} +__name(setProxyAgentOnRequest, "setProxyAgentOnRequest"); +function proxyPolicy(proxySettings, options) { + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); + } + const defaultProxy = proxySettings ? getUrlFromProxySettings(proxySettings) : getDefaultProxySettingsInternal(); + const cachedAgents = {}; + return { + name: proxyPolicyName, + async sendRequest(request, next) { + if (!request.proxySettings && defaultProxy && !isBypassed(request.url, options?.customNoProxyList ?? globalNoProxyList, options?.customNoProxyList ? void 0 : globalBypassedMap)) { + setProxyAgentOnRequest(request, cachedAgents, defaultProxy); + } else if (request.proxySettings) { + setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); + } + return next(request); + } + }; +} +__name(proxyPolicy, "proxyPolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js +var decompressResponsePolicyName = "decompressResponsePolicy"; +function decompressResponsePolicy() { + return { + name: decompressResponsePolicyName, + async sendRequest(request, next) { + if (request.method !== "HEAD") { + request.headers.set("Accept-Encoding", "gzip,deflate"); + } + return next(request); + } + }; +} +__name(decompressResponsePolicy, "decompressResponsePolicy"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js +var redirectPolicyName = "redirectPolicy"; +var allowedRedirect = ["GET", "HEAD"]; +function redirectPolicy(options = {}) { + const { maxRetries = 20, allowCrossOriginRedirects = false } = options; + return { + name: redirectPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return handleRedirect(next, response, maxRetries, allowCrossOriginRedirects); + } + }; +} +__name(redirectPolicy, "redirectPolicy"); +async function handleRedirect(next, response, maxRetries, allowCrossOriginRedirects, currentRetries = 0) { + const { request, status, headers } = response; + const locationHeader = headers.get("location"); + if (locationHeader && (status === 300 || status === 301 && allowedRedirect.includes(request.method) || status === 302 && allowedRedirect.includes(request.method) || status === 303 && request.method === "POST" || status === 307) && currentRetries < maxRetries) { + const url2 = new URL(locationHeader, request.url); + if (!allowCrossOriginRedirects) { + const originalUrl = new URL(request.url); + if (url2.origin !== originalUrl.origin) { + logger.verbose(`Skipping cross-origin redirect from ${originalUrl.origin} to ${url2.origin}.`); + return response; + } + } + request.url = url2.toString(); + if (status === 303) { + request.method = "GET"; + request.headers.delete("Content-Length"); + delete request.body; + } + request.headers.delete("Authorization"); + const res = await next(request); + return handleRedirect(next, res, maxRetries, allowCrossOriginRedirects, currentRetries + 1); + } + return response; +} +__name(handleRedirect, "handleRedirect"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js +function isBlob(x) { + return x instanceof Blob; +} +__name(isBlob, "isBlob"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js +import { Readable } from "stream"; +async function* streamAsyncIterator() { + const reader = this.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) { + return; + } + yield value; + } + } finally { + reader.releaseLock(); + } +} +__name(streamAsyncIterator, "streamAsyncIterator"); +function makeAsyncIterable(webStream) { + if (!webStream[Symbol.asyncIterator]) { + webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); + } + if (!webStream.values) { + webStream.values = streamAsyncIterator.bind(webStream); + } +} +__name(makeAsyncIterable, "makeAsyncIterable"); +function ensureNodeStream(stream) { + if (stream instanceof ReadableStream) { + makeAsyncIterable(stream); + return Readable.fromWeb(stream); + } else { + return stream; + } +} +__name(ensureNodeStream, "ensureNodeStream"); +function toStream(source) { + if (source instanceof Uint8Array) { + return Readable.from(Buffer.from(source)); + } else if (isBlob(source)) { + return ensureNodeStream(source.stream()); + } else { + return ensureNodeStream(source); + } +} +__name(toStream, "toStream"); +async function concat(sources) { + return function() { + const streams = sources.map((x) => typeof x === "function" ? x() : x).map(toStream); + return Readable.from((async function* () { + for (const stream of streams) { + for await (const chunk of stream) { + yield chunk; + } + } + })()); + }; +} +__name(concat, "concat"); + +// ../../node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js +function generateBoundary() { + return `----AzSDKFormBoundary${randomUUID()}`; +} +__name(generateBoundary, "generateBoundary"); +function encodeHeaders(headers) { + let result = ""; + for (const [key, value] of headers) { + result += `${key}: ${value}\r +`; + } + return result; +} +__name(encodeHeaders, "encodeHeaders"); +function getLength(source) { + if (source instanceof Uint8Array) { + return source.byteLength; + } else if (isBlob(source)) { + return source.size === -1 ? void 0 : source.size; + } else { + return void 0; + } +} +__name(getLength, "getLength"); +function getTotalLength(sources) { + let total = 0; + for (const source of sources) { + const partLength = getLength(source); + if (partLength === void 0) { + return void 0; + } else { + total += partLength; + } + } + return total; +} +__name(getTotalLength, "getTotalLength"); +async function buildRequestBody(request, parts, boundary) { + const sources = [ + stringToUint8Array(`--${boundary}`, "utf-8"), + ...parts.flatMap((part) => [ + stringToUint8Array("\r\n", "utf-8"), + stringToUint8Array(encodeHeaders(part.headers), "utf-8"), + stringToUint8Array("\r\n", "utf-8"), + part.body, + stringToUint8Array(`\r +--${boundary}`, "utf-8") + ]), + stringToUint8Array("--\r\n\r\n", "utf-8") + ]; + const contentLength2 = getTotalLength(sources); + if (contentLength2) { + request.headers.set("Content-Length", contentLength2); + } + request.body = await concat(sources); +} +__name(buildRequestBody, "buildRequestBody"); +var multipartPolicyName = "multipartPolicy"; +var maxBoundaryLength = 70; +var validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); +function assertValidBoundary(boundary) { + if (boundary.length > maxBoundaryLength) { + throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); + } + if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { + throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); + } +} +__name(assertValidBoundary, "assertValidBoundary"); +function multipartPolicy() { + return { + name: multipartPolicyName, + async sendRequest(request, next) { + if (!request.multipartBody) { + return next(request); + } + if (request.body) { + throw new Error("multipartBody and regular body cannot be set at the same time"); + } + let boundary = request.multipartBody.boundary; + const contentTypeHeader = request.headers.get("Content-Type") ?? "multipart/mixed"; + const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); + if (!parsedHeader) { + throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); + } + const [, contentType2, parsedBoundary] = parsedHeader; + if (parsedBoundary && boundary && parsedBoundary !== boundary) { + throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); + } + boundary ??= parsedBoundary; + if (boundary) { + assertValidBoundary(boundary); + } else { + boundary = generateBoundary(); + } + request.headers.set("Content-Type", `${contentType2}; boundary=${boundary}`); + await buildRequestBody(request, request.multipartBody.parts, boundary); + request.multipartBody = void 0; + return next(request); + } + }; +} +__name(multipartPolicy, "multipartPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js +function createEmptyPipeline2() { + return createEmptyPipeline(); +} +__name(createEmptyPipeline2, "createEmptyPipeline"); + +// ../../node_modules/@azure/logger/dist/esm/index.js +var context2 = createLoggerContext({ + logLevelEnvVarName: "AZURE_LOG_LEVEL", + namespace: "azure" +}); +var AzureLogger = context2.logger; +function createClientLogger2(namespace) { + return context2.createClientLogger(namespace); +} +__name(createClientLogger2, "createClientLogger"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/log.js +var logger2 = createClientLogger2("core-rest-pipeline"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js +function logPolicy2(options = {}) { + return logPolicy({ + logger: logger2.info, + ...options + }); +} +__name(logPolicy2, "logPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js +var redirectPolicyName2 = redirectPolicyName; +function redirectPolicy2(options = {}) { + return redirectPolicy(options); +} +__name(redirectPolicy2, "redirectPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js +import os from "node:os"; +import process4 from "node:process"; +function getHeaderName2() { + return "User-Agent"; +} +__name(getHeaderName2, "getHeaderName"); +async function setPlatformSpecificData2(map) { + if (process4 && process4.versions) { + const osInfo = `${os.type()} ${os.release()}; ${os.arch()}`; + if (process4.versions.bun) { + map.set("Bun", `${process4.versions.bun} (${osInfo})`); + } else if (process4.versions.deno) { + map.set("Deno", `${process4.versions.deno} (${osInfo})`); + } else if (process4.versions.node) { + map.set("Node", `${process4.versions.node} (${osInfo})`); + } + } +} +__name(setPlatformSpecificData2, "setPlatformSpecificData"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/constants.js +var SDK_VERSION2 = "1.25.0"; + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js +function getUserAgentString(telemetryInfo) { + const parts = []; + for (const [key, value] of telemetryInfo) { + const token = value ? `${key}/${value}` : key; + parts.push(token); + } + return parts.join(" "); +} +__name(getUserAgentString, "getUserAgentString"); +function getUserAgentHeaderName2() { + return getHeaderName2(); +} +__name(getUserAgentHeaderName2, "getUserAgentHeaderName"); +async function getUserAgentValue2(prefix2) { + const runtimeInfo = /* @__PURE__ */ new Map(); + runtimeInfo.set("core-rest-pipeline", SDK_VERSION2); + await setPlatformSpecificData2(runtimeInfo); + const defaultAgent = getUserAgentString(runtimeInfo); + const userAgentValue = prefix2 ? `${prefix2} ${defaultAgent}` : defaultAgent; + return userAgentValue; +} +__name(getUserAgentValue2, "getUserAgentValue"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js +var UserAgentHeaderName2 = getUserAgentHeaderName2(); +var userAgentPolicyName2 = "userAgentPolicy"; +function userAgentPolicy2(options = {}) { + const userAgentValue = getUserAgentValue2(options.userAgentPrefix); + return { + name: userAgentPolicyName2, + async sendRequest(request, next) { + if (!request.headers.has(UserAgentHeaderName2)) { + request.headers.set(UserAgentHeaderName2, await userAgentValue); + } + return next(request); + } + }; +} +__name(userAgentPolicy2, "userAgentPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js +var rawContent = /* @__PURE__ */ Symbol("rawContent"); +function hasRawContent(x) { + return typeof x[rawContent] === "function"; +} +__name(hasRawContent, "hasRawContent"); +function getRawContent(blob) { + if (hasRawContent(blob)) { + return blob[rawContent](); + } else { + return blob; + } +} +__name(getRawContent, "getRawContent"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js +var multipartPolicyName2 = multipartPolicyName; +function multipartPolicy2() { + const tspPolicy = multipartPolicy(); + return { + name: multipartPolicyName2, + sendRequest: /* @__PURE__ */ __name(async (request, next) => { + if (request.multipartBody) { + for (const part of request.multipartBody.parts) { + if (hasRawContent(part.body)) { + part.body = getRawContent(part.body); + } + } + } + return tspPolicy.sendRequest(request, next); + }, "sendRequest") + }; +} +__name(multipartPolicy2, "multipartPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js +var decompressResponsePolicyName2 = decompressResponsePolicyName; +function decompressResponsePolicy2() { + return decompressResponsePolicy(); +} +__name(decompressResponsePolicy2, "decompressResponsePolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js +function defaultRetryPolicy2(options = {}) { + return defaultRetryPolicy(options); +} +__name(defaultRetryPolicy2, "defaultRetryPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js +function formDataPolicy2() { + return formDataPolicy(); +} +__name(formDataPolicy2, "formDataPolicy"); + +// ../../node_modules/@azure/abort-controller/dist/esm/AbortError.js +var AbortError2 = class extends Error { + static { + __name(this, "AbortError"); + } + constructor(message) { + super(message); + this.name = "AbortError"; + } +}; + +// ../../node_modules/@azure/core-util/dist/esm/createAbortablePromise.js +function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options ?? {}; + return new Promise((resolve, reject) => { + function rejectOnAbort() { + reject(new AbortError2(abortErrorMsg ?? "The operation was aborted.")); + } + __name(rejectOnAbort, "rejectOnAbort"); + function removeListeners() { + abortSignal?.removeEventListener("abort", onAbort); + } + __name(removeListeners, "removeListeners"); + function onAbort() { + cleanupBeforeAbort?.(); + removeListeners(); + rejectOnAbort(); + } + __name(onAbort, "onAbort"); + if (abortSignal?.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } catch (err) { + reject(err); + } + abortSignal?.addEventListener("abort", onAbort); + }); +} +__name(createAbortablePromise, "createAbortablePromise"); + +// ../../node_modules/@azure/core-util/dist/esm/delay.js +var StandardAbortMessage2 = "The delay was aborted."; +function delay2(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options ?? {}; + return createAbortablePromise((resolve) => { + token = setTimeout(resolve, timeInMs); + }, { + cleanupBeforeAbort: /* @__PURE__ */ __name(() => clearTimeout(token), "cleanupBeforeAbort"), + abortSignal, + abortErrorMsg: abortErrorMsg ?? StandardAbortMessage2 + }); +} +__name(delay2, "delay"); + +// ../../node_modules/@azure/core-util/dist/esm/error.js +function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } else { + stringified = String(e); + } + } catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} +__name(getErrorMessage, "getErrorMessage"); + +// ../../node_modules/@azure/core-util/dist/esm/index.js +function isError2(e) { + return isError(e); +} +__name(isError2, "isError"); +function randomUUID2() { + return randomUUID(); +} +__name(randomUUID2, "randomUUID"); +var isNodeLike2 = isNodeLike; +function uint8ArrayToString2(bytes, format) { + return uint8ArrayToString(bytes, format); +} +__name(uint8ArrayToString2, "uint8ArrayToString"); +function stringToUint8Array2(value, format) { + return stringToUint8Array(value, format); +} +__name(stringToUint8Array2, "stringToUint8Array"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js +function getDefaultProxySettings2(proxyUrl) { + return getDefaultProxySettings(proxyUrl); +} +__name(getDefaultProxySettings2, "getDefaultProxySettings"); +function proxyPolicy2(proxySettings, options) { + return proxyPolicy(proxySettings, options); +} +__name(proxyPolicy2, "proxyPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js +var setClientRequestIdPolicyName = "setClientRequestIdPolicy"; +function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { + return { + name: setClientRequestIdPolicyName, + async sendRequest(request, next) { + if (!request.headers.has(requestIdHeaderName)) { + request.headers.set(requestIdHeaderName, request.requestId); + } + return next(request); + } + }; +} +__name(setClientRequestIdPolicy, "setClientRequestIdPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js +function agentPolicy2(agent) { + return agentPolicy(agent); +} +__name(agentPolicy2, "agentPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js +function tlsPolicy2(tlsSettings) { + return tlsPolicy(tlsSettings); +} +__name(tlsPolicy2, "tlsPolicy"); + +// ../../node_modules/@azure/core-tracing/dist/esm/tracingContext.js +var knownContextKeys = { + span: /* @__PURE__ */ Symbol.for("@azure/core-tracing span"), + namespace: /* @__PURE__ */ Symbol.for("@azure/core-tracing namespace") +}; +function createTracingContext(options = {}) { + let context3 = new TracingContextImpl(options.parentContext); + if (options.span) { + context3 = context3.setValue(knownContextKeys.span, options.span); + } + if (options.namespace) { + context3 = context3.setValue(knownContextKeys.namespace, options.namespace); + } + return context3; +} +__name(createTracingContext, "createTracingContext"); +var TracingContextImpl = class _TracingContextImpl { + static { + __name(this, "TracingContextImpl"); + } + _contextMap; + constructor(initialContext) { + this._contextMap = initialContext instanceof _TracingContextImpl ? new Map(initialContext._contextMap) : /* @__PURE__ */ new Map(); + } + setValue(key, value) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.set(key, value); + return newContext; + } + getValue(key) { + return this._contextMap.get(key); + } + deleteValue(key) { + const newContext = new _TracingContextImpl(this); + newContext._contextMap.delete(key); + return newContext; + } +}; + +// ../../node_modules/@azure/core-tracing/dist/esm/state.js +var import_state_cjs = __toESM(require_state_cjs(), 1); +var state = import_state_cjs.state; + +// ../../node_modules/@azure/core-tracing/dist/esm/instrumenter.js +function createDefaultTracingSpan() { + return { + end: /* @__PURE__ */ __name(() => { + }, "end"), + isRecording: /* @__PURE__ */ __name(() => false, "isRecording"), + recordException: /* @__PURE__ */ __name(() => { + }, "recordException"), + setAttribute: /* @__PURE__ */ __name(() => { + }, "setAttribute"), + setStatus: /* @__PURE__ */ __name(() => { + }, "setStatus"), + addEvent: /* @__PURE__ */ __name(() => { + }, "addEvent") + }; +} +__name(createDefaultTracingSpan, "createDefaultTracingSpan"); +function createDefaultInstrumenter() { + return { + createRequestHeaders: /* @__PURE__ */ __name(() => { + return {}; + }, "createRequestHeaders"), + parseTraceparentHeader: /* @__PURE__ */ __name(() => { + return void 0; + }, "parseTraceparentHeader"), + startSpan: /* @__PURE__ */ __name((_name, spanOptions) => { + return { + span: createDefaultTracingSpan(), + tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }) + }; + }, "startSpan"), + withContext(_context, callback, ...callbackArgs) { + return callback(...callbackArgs); + } + }; +} +__name(createDefaultInstrumenter, "createDefaultInstrumenter"); +function getInstrumenter() { + if (!state.instrumenterImplementation) { + state.instrumenterImplementation = createDefaultInstrumenter(); + } + return state.instrumenterImplementation; +} +__name(getInstrumenter, "getInstrumenter"); + +// ../../node_modules/@azure/core-tracing/dist/esm/tracingClient.js +function createTracingClient(options) { + const { namespace, packageName, packageVersion } = options; + function startSpan(name3, operationOptions, spanOptions) { + const startSpanResult = getInstrumenter().startSpan(name3, { + ...spanOptions, + packageName, + packageVersion, + tracingContext: operationOptions?.tracingOptions?.tracingContext + }); + let tracingContext = startSpanResult.tracingContext; + const span = startSpanResult.span; + if (!tracingContext.getValue(knownContextKeys.namespace)) { + tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace); + } + span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace)); + const updatedOptions = Object.assign({}, operationOptions, { + tracingOptions: { ...operationOptions?.tracingOptions, tracingContext } + }); + return { + span, + updatedOptions + }; + } + __name(startSpan, "startSpan"); + async function withSpan(name3, operationOptions, callback, spanOptions) { + const { span, updatedOptions } = startSpan(name3, operationOptions, spanOptions); + try { + const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => callback(updatedOptions, span)); + span.setStatus({ status: "success" }); + return result; + } catch (err) { + span.setStatus({ status: "error", error: err }); + throw err; + } finally { + span.end(); + } + } + __name(withSpan, "withSpan"); + function withContext(context3, callback, ...callbackArgs) { + return getInstrumenter().withContext(context3, callback, ...callbackArgs); + } + __name(withContext, "withContext"); + function parseTraceparentHeader(traceparentHeader) { + return getInstrumenter().parseTraceparentHeader(traceparentHeader); + } + __name(parseTraceparentHeader, "parseTraceparentHeader"); + function createRequestHeaders(tracingContext) { + return getInstrumenter().createRequestHeaders(tracingContext); + } + __name(createRequestHeaders, "createRequestHeaders"); + return { + startSpan, + withSpan, + withContext, + parseTraceparentHeader, + createRequestHeaders + }; +} +__name(createTracingClient, "createTracingClient"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/restError.js +var RestError2 = RestError; +function isRestError2(e) { + return isRestError(e); +} +__name(isRestError2, "isRestError"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js +var tracingPolicyName = "tracingPolicy"; +function tracingPolicy(options = {}) { + const userAgentPromise = getUserAgentValue2(options.userAgentPrefix); + const sanitizer = new Sanitizer({ + additionalAllowedQueryParameters: options.additionalAllowedQueryParameters + }); + const tracingClient2 = tryCreateTracingClient(); + return { + name: tracingPolicyName, + async sendRequest(request, next) { + if (!tracingClient2) { + return next(request); + } + const userAgent = await userAgentPromise; + const spanAttributes = { + "http.url": sanitizer.sanitizeUrl(request.url), + "http.method": request.method, + "http.user_agent": userAgent, + requestId: request.requestId + }; + if (userAgent) { + spanAttributes["http.user_agent"] = userAgent; + } + const { span, tracingContext } = tryCreateSpan(tracingClient2, request, spanAttributes) ?? {}; + if (!span || !tracingContext) { + return next(request); + } + try { + const response = await tracingClient2.withContext(tracingContext, next, request); + tryProcessResponse(span, response); + return response; + } catch (err) { + tryProcessError(span, err); + throw err; + } + } + }; +} +__name(tracingPolicy, "tracingPolicy"); +function tryCreateTracingClient() { + try { + return createTracingClient({ + namespace: "", + packageName: "@azure/core-rest-pipeline", + packageVersion: SDK_VERSION2 + }); + } catch (e) { + logger2.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`); + return void 0; + } +} +__name(tryCreateTracingClient, "tryCreateTracingClient"); +function tryCreateSpan(tracingClient2, request, spanAttributes) { + try { + const { span, updatedOptions } = tracingClient2.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { + spanKind: "client", + spanAttributes + }); + if (!span.isRecording()) { + span.end(); + return void 0; + } + const headers = tracingClient2.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); + for (const [key, value] of Object.entries(headers)) { + request.headers.set(key, value); + } + return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; + } catch (e) { + logger2.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`); + return void 0; + } +} +__name(tryCreateSpan, "tryCreateSpan"); +function tryProcessError(span, error) { + try { + span.setStatus({ + status: "error", + error: isError2(error) ? error : void 0 + }); + if (isRestError2(error) && error.statusCode) { + span.setAttribute("http.status_code", error.statusCode); + } + span.end(); + } catch (e) { + logger2.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); + } +} +__name(tryProcessError, "tryProcessError"); +function tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + if (response.status >= 400) { + span.setStatus({ + status: "error" + }); + } + span.end(); + } catch (e) { + logger2.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); + } +} +__name(tryProcessResponse, "tryProcessResponse"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js +function wrapAbortSignalLike(abortSignalLike) { + if (abortSignalLike instanceof AbortSignal) { + return { abortSignal: abortSignalLike }; + } + if (abortSignalLike.aborted) { + return { + abortSignal: AbortSignal.abort("reason" in abortSignalLike ? abortSignalLike.reason : void 0) + }; + } + const controller = new AbortController(); + let needsCleanup = true; + function cleanup() { + if (needsCleanup) { + abortSignalLike.removeEventListener("abort", listener); + needsCleanup = false; + } + } + __name(cleanup, "cleanup"); + function listener() { + controller.abort("reason" in abortSignalLike ? abortSignalLike.reason : void 0); + cleanup(); + } + __name(listener, "listener"); + abortSignalLike.addEventListener("abort", listener); + return { abortSignal: controller.signal, cleanup }; +} +__name(wrapAbortSignalLike, "wrapAbortSignalLike"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js +var wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy"; +function wrapAbortSignalLikePolicy() { + return { + name: wrapAbortSignalLikePolicyName, + sendRequest: /* @__PURE__ */ __name(async (request, next) => { + if (!request.abortSignal) { + return next(request); + } + const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal); + request.abortSignal = abortSignal; + try { + return await next(request); + } finally { + cleanup?.(); + } + }, "sendRequest") + }; +} +__name(wrapAbortSignalLikePolicy, "wrapAbortSignalLikePolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js +function createPipelineFromOptions2(options) { + const pipeline2 = createEmptyPipeline2(); + if (isNodeLike2) { + if (options.agent) { + pipeline2.addPolicy(agentPolicy2(options.agent)); + } + if (options.tlsOptions) { + pipeline2.addPolicy(tlsPolicy2(options.tlsOptions)); + } + pipeline2.addPolicy(proxyPolicy2(options.proxyOptions)); + pipeline2.addPolicy(decompressResponsePolicy2()); + } + pipeline2.addPolicy(wrapAbortSignalLikePolicy()); + pipeline2.addPolicy(formDataPolicy2(), { beforePolicies: [multipartPolicyName2] }); + pipeline2.addPolicy(userAgentPolicy2(options.userAgentOptions)); + pipeline2.addPolicy(setClientRequestIdPolicy(options.telemetryOptions?.clientRequestIdHeaderName)); + pipeline2.addPolicy(multipartPolicy2(), { afterPhase: "Deserialize" }); + pipeline2.addPolicy(defaultRetryPolicy2(options.retryOptions), { phase: "Retry" }); + pipeline2.addPolicy(tracingPolicy({ ...options.userAgentOptions, ...options.loggingOptions }), { + afterPhase: "Retry" + }); + if (isNodeLike2) { + pipeline2.addPolicy(redirectPolicy2(options.redirectOptions), { afterPhase: "Retry" }); + } + pipeline2.addPolicy(logPolicy2(options.loggingOptions), { afterPhase: "Sign" }); + return pipeline2; +} +__name(createPipelineFromOptions2, "createPipelineFromOptions"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js +function createDefaultHttpClient2() { + const client = createDefaultHttpClient(); + return { + async sendRequest(request) { + const { abortSignal, cleanup } = request.abortSignal ? wrapAbortSignalLike(request.abortSignal) : {}; + try { + request.abortSignal = abortSignal; + return await client.sendRequest(request); + } finally { + cleanup?.(); + } + } + }; +} +__name(createDefaultHttpClient2, "createDefaultHttpClient"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js +function createHttpHeaders2(rawHeaders) { + return createHttpHeaders(rawHeaders); +} +__name(createHttpHeaders2, "createHttpHeaders"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js +function createPipelineRequest2(options) { + return createPipelineRequest(options); +} +__name(createPipelineRequest2, "createPipelineRequest"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js +var retryPolicyLogger2 = createClientLogger2("core-rest-pipeline retryPolicy"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js +var DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1e3, + // Force waiting for a refresh 1s before the token expires + retryIntervalInMs: 3e3, + // Allow refresh attempts every 3s + refreshWindowInMs: 1e3 * 60 * 2 + // Start refreshing 2m before expiry +}; +async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { + async function tryGetAccessToken() { + if (Date.now() < refreshTimeout) { + try { + return await getAccessToken(); + } catch { + return null; + } + } else { + const finalToken = await getAccessToken(); + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + __name(tryGetAccessToken, "tryGetAccessToken"); + let token = await tryGetAccessToken(); + while (token === null) { + await delay2(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; +} +__name(beginRefresh, "beginRefresh"); +function createTokenCycler(credential, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + let tenantId; + const options = { + ...DEFAULT_CYCLER_OPTIONS, + ...tokenCyclerOptions + }; + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + if (token === null) { + return true; + } + if (cycler.isRefreshing) { + return false; + } + if (token.refreshAfterTimestamp && token.refreshAfterTimestamp < Date.now()) { + return true; + } + return token.expiresOnTimestamp - options.refreshWindowInMs < Date.now(); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now(); + } + }; + function refresh(scopes, getTokenOptions) { + if (!cycler.isRefreshing) { + const tryGetAccessToken = /* @__PURE__ */ __name(() => credential.getToken(scopes, getTokenOptions), "tryGetAccessToken"); + refreshWorker = beginRefresh( + tryGetAccessToken, + options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + token?.expiresOnTimestamp ?? Date.now() + ).then((_token) => { + refreshWorker = null; + token = _token; + tenantId = getTokenOptions.tenantId; + return token; + }).catch((reason) => { + refreshWorker = null; + token = null; + tenantId = void 0; + throw reason; + }); + } + return refreshWorker; + } + __name(refresh, "refresh"); + return async (scopes, tokenOptions) => { + const hasClaimChallenge = Boolean(tokenOptions.claims); + const tenantIdChanged = tenantId !== tokenOptions.tenantId; + if (hasClaimChallenge) { + token = null; + } + const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; + if (mustRefresh) { + return refresh(scopes, tokenOptions); + } + if (cycler.shouldRefresh) { + refresh(scopes, tokenOptions); + } + return token; + }; +} +__name(createTokenCycler, "createTokenCycler"); + +// ../../node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js +var bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; +async function trySendRequest(request, next) { + try { + return [await next(request), void 0]; + } catch (e) { + if (isRestError2(e) && e.response) { + return [e.response, e]; + } else { + throw e; + } + } +} +__name(trySendRequest, "trySendRequest"); +async function defaultAuthorizeRequest(options) { + const { scopes, getAccessToken, request } = options; + const getTokenOptions = { + abortSignal: request.abortSignal, + tracingOptions: request.tracingOptions, + enableCae: true + }; + const accessToken = await getAccessToken(scopes, getTokenOptions); + if (accessToken) { + options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); + } +} +__name(defaultAuthorizeRequest, "defaultAuthorizeRequest"); +function isChallengeResponse(response) { + return response.status === 401 && response.headers.has("WWW-Authenticate"); +} +__name(isChallengeResponse, "isChallengeResponse"); +async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) { + const { scopes } = onChallengeOptions; + const accessToken = await onChallengeOptions.getAccessToken(scopes, { + enableCae: true, + claims: caeClaims + }); + if (!accessToken) { + return false; + } + onChallengeOptions.request.headers.set("Authorization", `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + return true; +} +__name(authorizeRequestOnCaeChallenge, "authorizeRequestOnCaeChallenge"); +function bearerTokenAuthenticationPolicy(options) { + const { credential, scopes, challengeCallbacks } = options; + const logger8 = options.logger || logger2; + const callbacks = { + authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest, + authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks) + }; + const getAccessToken = credential ? createTokenCycler( + credential + /* , options */ + ) : () => Promise.resolve(null); + return { + name: bearerTokenAuthenticationPolicyName, + /** + * If there's no challenge parameter: + * - It will try to retrieve the token using the cache, or the credential's getToken. + * - Then it will try the next policy with or without the retrieved token. + * + * It uses the challenge parameters to: + * - Skip a first attempt to get the token from the credential if there's no cached token, + * since it expects the token to be retrievable only after the challenge. + * - Prepare the outgoing request if the `prepareRequest` method has been provided. + * - Send an initial request to receive the challenge if it fails. + * - Process a challenge if the response contains it. + * - Retrieve a token with the challenge information, then re-send the request. + */ + async sendRequest(request, next) { + if (!request.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + await callbacks.authorizeRequest({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + getAccessToken, + logger: logger8 + }); + let response; + let error; + let shouldSendRequest; + [response, error] = await trySendRequest(request, next); + if (isChallengeResponse(response)) { + let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate")); + if (claims) { + let parsedClaim; + try { + parsedClaim = atob(claims); + } catch (e) { + logger8.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + return response; + } + shouldSendRequest = await authorizeRequestOnCaeChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + response, + request, + getAccessToken, + logger: logger8 + }, parsedClaim); + if (shouldSendRequest) { + [response, error] = await trySendRequest(request, next); + } + } else if (callbacks.authorizeRequestOnChallenge) { + shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + request, + response, + getAccessToken, + logger: logger8 + }); + if (shouldSendRequest) { + [response, error] = await trySendRequest(request, next); + } + if (isChallengeResponse(response)) { + claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate") ?? ""); + if (claims) { + let parsedClaim; + try { + parsedClaim = atob(claims); + } catch (e) { + logger8.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + return response; + } + shouldSendRequest = await authorizeRequestOnCaeChallenge({ + scopes: Array.isArray(scopes) ? scopes : [scopes], + response, + request, + getAccessToken, + logger: logger8 + }, parsedClaim); + if (shouldSendRequest) { + [response, error] = await trySendRequest(request, next); + } + } + } + } + } + if (error) { + throw error; + } else { + return response; + } + } + }; +} +__name(bearerTokenAuthenticationPolicy, "bearerTokenAuthenticationPolicy"); +function parseChallenges(challenges) { + const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g; + const paramRegex = /(\w+)="([^"]*)"/g; + const parsedChallenges = []; + let match; + while ((match = challengeRegex.exec(challenges)) !== null) { + const scheme = match[1]; + const paramsString = match[2]; + const params = {}; + let paramMatch; + while ((paramMatch = paramRegex.exec(paramsString)) !== null) { + params[paramMatch[1]] = paramMatch[2]; + } + parsedChallenges.push({ scheme, params }); + } + return parsedChallenges; +} +__name(parseChallenges, "parseChallenges"); +function getCaeChallengeClaims(challenges) { + if (!challenges) { + return; + } + const parsedChallenges = parseChallenges(challenges); + return parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")?.params.claims; +} +__name(getCaeChallengeClaims, "getCaeChallengeClaims"); + +// ../../node_modules/@azure/core-auth/dist/esm/tokenCredential.js +function isTokenCredential(credential) { + const castCredential = credential; + return castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === void 0 || castCredential.getToken.length > 0); +} +__name(isTokenCredential, "isTokenCredential"); + +// ../../node_modules/@azure/core-http-compat/dist/esm/policies/disableKeepAlivePolicy.js +var disableKeepAlivePolicyName = "DisableKeepAlivePolicy"; +function createDisableKeepAlivePolicy() { + return { + name: disableKeepAlivePolicyName, + sendRequest(request, next) { + request.disableKeepAlive = true; + return next(request); + } + }; +} +__name(createDisableKeepAlivePolicy, "createDisableKeepAlivePolicy"); +function pipelineContainsDisableKeepAlivePolicy(pipeline2) { + return pipeline2.getOrderedPolicies().some((policy) => policy.name === disableKeepAlivePolicyName); +} +__name(pipelineContainsDisableKeepAlivePolicy, "pipelineContainsDisableKeepAlivePolicy"); + +// ../../node_modules/@azure/core-client/dist/esm/base64.js +function encodeByteArray(value) { + return uint8ArrayToString2(value, "base64"); +} +__name(encodeByteArray, "encodeByteArray"); +function decodeString(value) { + return stringToUint8Array2(value, "base64"); +} +__name(decodeString, "decodeString"); + +// ../../node_modules/@azure/core-client/dist/esm/interfaces.js +var XML_ATTRKEY = "$"; +var XML_CHARKEY = "_"; + +// ../../node_modules/@azure/core-client/dist/esm/utils.js +function isPrimitiveBody(value, mapperTypeName) { + return mapperTypeName !== "Composite" && mapperTypeName !== "Dictionary" && (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || mapperTypeName?.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i) !== null || value === void 0 || value === null); +} +__name(isPrimitiveBody, "isPrimitiveBody"); +var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; +function isDuration(value) { + return validateISODuration.test(value); +} +__name(isDuration, "isDuration"); +var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; +function isValidUuid(uuid) { + return validUuidRegex.test(uuid); +} +__name(isValidUuid, "isValidUuid"); +function handleNullableResponseAndWrappableBody(responseObject) { + const combinedHeadersAndBody = { + ...responseObject.headers, + ...responseObject.body + }; + if (responseObject.hasNullableType && Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { + return responseObject.shouldWrapBody ? { body: null } : null; + } else { + return responseObject.shouldWrapBody ? { + ...responseObject.headers, + body: responseObject.body + } : combinedHeadersAndBody; + } +} +__name(handleNullableResponseAndWrappableBody, "handleNullableResponseAndWrappableBody"); +function flattenResponse(fullResponse, responseSpec) { + const parsedHeaders = fullResponse.parsedHeaders; + if (fullResponse.request.method === "HEAD") { + return { + ...parsedHeaders, + body: fullResponse.parsedBody + }; + } + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const isNullable = Boolean(bodyMapper?.nullable); + const expectedBodyTypeName = bodyMapper?.type.name; + if (expectedBodyTypeName === "Stream") { + return { + ...parsedHeaders, + blobBody: fullResponse.blobBody, + readableStreamBody: fullResponse.readableStreamBody + }; + } + const modelProperties = expectedBodyTypeName === "Composite" && bodyMapper.type.modelProperties || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); + if (expectedBodyTypeName === "Sequence" || isPageableResponse) { + const arrayResponse = fullResponse.parsedBody ?? []; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { + arrayResponse[key] = fullResponse.parsedBody?.[key]; + } + } + if (parsedHeaders) { + for (const key of Object.keys(parsedHeaders)) { + arrayResponse[key] = parsedHeaders[key]; + } + } + return isNullable && !fullResponse.parsedBody && !parsedHeaders && Object.getOwnPropertyNames(modelProperties).length === 0 ? null : arrayResponse; + } + return handleNullableResponseAndWrappableBody({ + body: fullResponse.parsedBody, + headers: parsedHeaders, + hasNullableType: isNullable, + shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName) + }); +} +__name(flattenResponse, "flattenResponse"); + +// ../../node_modules/@azure/core-client/dist/esm/serializer.js +var SerializerImpl = class { + static { + __name(this, "SerializerImpl"); + } + modelMappers; + isXML; + constructor(modelMappers = {}, isXML = false) { + this.modelMappers = modelMappers; + this.isXML = isXML; + } + /** + * @deprecated Removing the constraints validation on client side. + */ + validateConstraints(mapper, value, objectName) { + const failValidation = /* @__PURE__ */ __name((constraintName, constraintValue) => { + throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); + }, "failValidation"); + if (mapper.constraints && value !== void 0 && value !== null) { + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; + if (ExclusiveMaximum !== void 0 && value >= ExclusiveMaximum) { + failValidation("ExclusiveMaximum", ExclusiveMaximum); + } + if (ExclusiveMinimum !== void 0 && value <= ExclusiveMinimum) { + failValidation("ExclusiveMinimum", ExclusiveMinimum); + } + if (InclusiveMaximum !== void 0 && value > InclusiveMaximum) { + failValidation("InclusiveMaximum", InclusiveMaximum); + } + if (InclusiveMinimum !== void 0 && value < InclusiveMinimum) { + failValidation("InclusiveMinimum", InclusiveMinimum); + } + if (MaxItems !== void 0 && value.length > MaxItems) { + failValidation("MaxItems", MaxItems); + } + if (MaxLength !== void 0 && value.length > MaxLength) { + failValidation("MaxLength", MaxLength); + } + if (MinItems !== void 0 && value.length < MinItems) { + failValidation("MinItems", MinItems); + } + if (MinLength !== void 0 && value.length < MinLength) { + failValidation("MinLength", MinLength); + } + if (MultipleOf !== void 0 && value % MultipleOf !== 0) { + failValidation("MultipleOf", MultipleOf); + } + if (Pattern) { + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + if (typeof value !== "string" || value.match(pattern) === null) { + failValidation("Pattern", Pattern); + } + } + if (UniqueItems && value.some((item, i, ar) => ar.indexOf(item) !== i)) { + failValidation("UniqueItems", UniqueItems); + } + } + } + /** + * Serialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param object - A valid Javascript object to be serialized + * + * @param objectName - Name of the serialized object + * + * @param options - additional options to serialization + * + * @returns A valid serialized Javascript object + */ + serialize(mapper, object, objectName, options = { xml: {} }) { + const updatedOptions = { + xml: { + rootName: options.xml.rootName ?? "", + includeRoot: options.xml.includeRoot ?? false, + xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY + } + }; + let payload = {}; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Sequence$/i) !== null) { + payload = []; + } + if (mapper.isConstant) { + object = mapper.defaultValue; + } + const { required, nullable } = mapper; + if (required && nullable && object === void 0) { + throw new Error(`${objectName} cannot be undefined.`); + } + if (required && !nullable && (object === void 0 || object === null)) { + throw new Error(`${objectName} cannot be null or undefined.`); + } + if (!required && nullable === false && object === null) { + throw new Error(`${objectName} cannot be null.`); + } + if (object === void 0 || object === null) { + payload = object; + } else { + if (mapperType.match(/^any$/i) !== null) { + payload = object; + } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { + payload = serializeBasicTypes(mapperType, objectName, object); + } else if (mapperType.match(/^Enum$/i) !== null) { + const enumMapper = mapper; + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { + payload = serializeDateTypes(mapperType, object, objectName); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = serializeByteArrayType(objectName, object); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = serializeBase64UrlType(objectName, object); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } else if (mapperType.match(/^Composite$/i) !== null) { + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + } + } + return payload; + } + /** + * Deserialize the given object based on its metadata defined in the mapper + * + * @param mapper - The mapper which defines the metadata of the serializable object + * + * @param responseBody - A valid Javascript entity to be deserialized + * + * @param objectName - Name of the deserialized object + * + * @param options - Controls behavior of XML parser and builder. + * + * @returns A valid deserialized Javascript object + */ + deserialize(mapper, responseBody, objectName, options = { xml: {} }) { + const updatedOptions = { + xml: { + rootName: options.xml.rootName ?? "", + includeRoot: options.xml.includeRoot ?? false, + xmlCharKey: options.xml.xmlCharKey ?? XML_CHARKEY + }, + ignoreUnknownProperties: options.ignoreUnknownProperties ?? false + }; + if (responseBody === void 0 || responseBody === null) { + if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { + responseBody = []; + } + if (mapper.defaultValue !== void 0) { + responseBody = mapper.defaultValue; + } + return responseBody; + } + let payload; + const mapperType = mapper.type.name; + if (!objectName) { + objectName = mapper.serializedName; + } + if (mapperType.match(/^Composite$/i) !== null) { + payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + } else { + if (this.isXML) { + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (responseBody[XML_ATTRKEY] !== void 0 && responseBody[xmlCharKey] !== void 0) { + responseBody = responseBody[xmlCharKey]; + } + } + if (mapperType.match(/^Number$/i) !== null) { + payload = parseFloat(responseBody); + if (isNaN(payload)) { + payload = responseBody; + } + } else if (mapperType.match(/^Boolean$/i) !== null) { + if (responseBody === "true") { + payload = true; + } else if (responseBody === "false") { + payload = false; + } else { + payload = responseBody; + } + } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { + payload = responseBody; + } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { + payload = new Date(responseBody); + } else if (mapperType.match(/^UnixTime$/i) !== null) { + payload = unixTimeToDate(responseBody); + } else if (mapperType.match(/^ByteArray$/i) !== null) { + payload = decodeString(responseBody); + } else if (mapperType.match(/^Base64Url$/i) !== null) { + payload = base64UrlToByteArray(responseBody); + } else if (mapperType.match(/^Sequence$/i) !== null) { + payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + } else if (mapperType.match(/^Dictionary$/i) !== null) { + payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + } + } + if (mapper.isConstant) { + payload = mapper.defaultValue; + } + return payload; + } +}; +function createSerializer(modelMappers = {}, isXML = false) { + return new SerializerImpl(modelMappers, isXML); +} +__name(createSerializer, "createSerializer"); +function trimEnd(str, ch) { + let len = str.length; + while (len - 1 >= 0 && str[len - 1] === ch) { + --len; + } + return str.substr(0, len); +} +__name(trimEnd, "trimEnd"); +function bufferToBase64Url(buffer2) { + if (!buffer2) { + return void 0; + } + if (!(buffer2 instanceof Uint8Array)) { + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); + } + const str = encodeByteArray(buffer2); + return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); +} +__name(bufferToBase64Url, "bufferToBase64Url"); +function base64UrlToByteArray(str) { + if (!str) { + return void 0; + } + if (str && typeof str.valueOf() !== "string") { + throw new Error("Please provide an input of type string for converting to Uint8Array"); + } + str = str.replace(/-/g, "+").replace(/_/g, "/"); + return decodeString(str); +} +__name(base64UrlToByteArray, "base64UrlToByteArray"); +function splitSerializeName(prop) { + const classes = []; + let partialclass = ""; + if (prop) { + const subwords = prop.split("."); + for (const item of subwords) { + if (item.charAt(item.length - 1) === "\\") { + partialclass += item.substr(0, item.length - 1) + "."; + } else { + partialclass += item; + classes.push(partialclass); + partialclass = ""; + } + } + } + return classes; +} +__name(splitSerializeName, "splitSerializeName"); +function dateToUnixTime(d) { + if (!d) { + return void 0; + } + if (typeof d.valueOf() === "string") { + d = new Date(d); + } + return Math.floor(d.getTime() / 1e3); +} +__name(dateToUnixTime, "dateToUnixTime"); +function unixTimeToDate(n) { + if (!n) { + return void 0; + } + return new Date(n * 1e3); +} +__name(unixTimeToDate, "unixTimeToDate"); +function serializeBasicTypes(typeName, objectName, value) { + if (value !== null && value !== void 0) { + if (typeName.match(/^Number$/i) !== null) { + if (typeof value !== "number") { + throw new Error(`${objectName} with value ${value} must be of type number.`); + } + } else if (typeName.match(/^String$/i) !== null) { + if (typeof value.valueOf() !== "string") { + throw new Error(`${objectName} with value "${value}" must be of type string.`); + } + } else if (typeName.match(/^Uuid$/i) !== null) { + if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + } + } else if (typeName.match(/^Boolean$/i) !== null) { + if (typeof value !== "boolean") { + throw new Error(`${objectName} with value ${value} must be of type boolean.`); + } + } else if (typeName.match(/^Stream$/i) !== null) { + const objectType = typeof value; + if (objectType !== "string" && typeof value.pipe !== "function" && // NodeJS.ReadableStream + typeof value.tee !== "function" && // browser ReadableStream + !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && // File objects count as a type of Blob, so we want to use instanceof explicitly + !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && objectType !== "function") { + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); + } + } + } + return value; +} +__name(serializeBasicTypes, "serializeBasicTypes"); +function serializeEnumType(objectName, allowedValues, value) { + if (!allowedValues) { + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); + } + const isPresent = allowedValues.some((item) => { + if (typeof item.valueOf() === "string") { + return item.toLowerCase() === value.toLowerCase(); + } + return item === value; + }); + if (!isPresent) { + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + } + return value; +} +__name(serializeEnumType, "serializeEnumType"); +function serializeByteArrayType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = encodeByteArray(value); + } + return value; +} +__name(serializeByteArrayType, "serializeByteArrayType"); +function serializeBase64UrlType(objectName, value) { + if (value !== void 0 && value !== null) { + if (!(value instanceof Uint8Array)) { + throw new Error(`${objectName} must be of type Uint8Array.`); + } + value = bufferToBase64Url(value); + } + return value; +} +__name(serializeBase64UrlType, "serializeBase64UrlType"); +function serializeDateTypes(typeName, value, objectName) { + if (value !== void 0 && value !== null) { + if (typeName.match(/^Date$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); + } else if (typeName.match(/^DateTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); + } + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); + } + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } else if (typeName.match(/^UnixTime$/i) !== null) { + if (!(value instanceof Date || typeof value.valueOf() === "string" && !isNaN(Date.parse(value)))) { + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format for it to be serialized in UnixTime/Epoch format.`); + } + value = dateToUnixTime(value); + } else if (typeName.match(/^TimeSpan$/i) !== null) { + if (!isDuration(value)) { + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); + } + } + } + return value; +} +__name(serializeDateTypes, "serializeDateTypes"); +function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { + if (!Array.isArray(object)) { + throw new Error(`${objectName} must be of type Array.`); + } + let elementType = mapper.type.element; + if (!elementType || typeof elementType !== "object") { + throw new Error(`"element" metadata for an Array must be defined in the mapper and it must be of type "object" in ${objectName}.`); + } + if (elementType.type.name === "Composite" && elementType.type.className) { + elementType = serializer.modelMappers[elementType.type.className] ?? elementType; + } + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + if (isXml && elementType.xmlNamespace) { + const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; + if (elementType.type.name === "Composite") { + tempArray[i] = { ...serializedValue }; + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } else { + tempArray[i] = {}; + tempArray[i][options.xml.xmlCharKey] = serializedValue; + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; + } + } else { + tempArray[i] = serializedValue; + } + } + return tempArray; +} +__name(serializeSequenceType, "serializeSequenceType"); +function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { + if (typeof object !== "object") { + throw new Error(`${objectName} must be of type object.`); + } + const valueType = mapper.type.value; + if (!valueType || typeof valueType !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`); + } + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + } + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; + return result; + } + return tempDictionary; +} +__name(serializeDictionaryType, "serializeDictionaryType"); +function resolveAdditionalProperties(serializer, mapper, objectName) { + const additionalProperties = mapper.type.additionalProperties; + if (!additionalProperties && mapper.type.className) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + return modelMapper?.type.additionalProperties; + } + return additionalProperties; +} +__name(resolveAdditionalProperties, "resolveAdditionalProperties"); +function resolveReferencedMapper(serializer, mapper, objectName) { + const className = mapper.type.className; + if (!className) { + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, void 0, 2)}".`); + } + return serializer.modelMappers[className]; +} +__name(resolveReferencedMapper, "resolveReferencedMapper"); +function resolveModelProperties(serializer, mapper, objectName) { + let modelProps = mapper.type.modelProperties; + if (!modelProps) { + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + if (!modelMapper) { + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); + } + modelProps = modelMapper?.type.modelProperties; + if (!modelProps) { + throw new Error(`modelProperties cannot be null or undefined in the mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); + } + } + return modelProps; +} +__name(resolveModelProperties, "resolveModelProperties"); +function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); + } + if (object !== void 0 && object !== null) { + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + if (propertyMapper.readOnly) { + continue; + } + let propName3; + let parentObject = payload; + if (serializer.isXML) { + if (propertyMapper.xmlIsWrapped) { + propName3 = propertyMapper.xmlName; + } else { + propName3 = propertyMapper.xmlElementName || propertyMapper.xmlName; + } + } else { + const paths = splitSerializeName(propertyMapper.serializedName); + propName3 = paths.pop(); + for (const pathName of paths) { + const childObject = parentObject[pathName]; + if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) { + parentObject[pathName] = {}; + } + parentObject = parentObject[pathName]; + } + } + if (parentObject !== void 0 && parentObject !== null) { + if (isXml && mapper.xmlNamespace) { + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + parentObject[XML_ATTRKEY] = { + ...parentObject[XML_ATTRKEY], + [xmlnsKey]: mapper.xmlNamespace + }; + } + const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) { + toSerialize = mapper.serializedName; + } + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + if (serializedValue !== void 0 && propName3 !== void 0 && propName3 !== null) { + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + if (isXml && propertyMapper.xmlIsAttribute) { + parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; + parentObject[XML_ATTRKEY][propName3] = serializedValue; + } else if (isXml && propertyMapper.xmlIsWrapped) { + parentObject[propName3] = { [propertyMapper.xmlElementName]: value }; + } else { + parentObject[propName3] = value; + } + } + } + } + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + if (additionalPropertiesMapper) { + const propNames = Object.keys(modelProps); + for (const clientPropName of Object.keys(object)) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); + if (isAdditionalProperty) { + Object.defineProperty(payload, clientPropName, { + value: serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options), + enumerable: true, + configurable: true, + writable: true + }); + } + } + } + return payload; + } + return object; +} +__name(serializeCompositeType, "serializeCompositeType"); +function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { + if (!isXml || !propertyMapper.xmlNamespace) { + return serializedValue; + } + const xmlnsKey = propertyMapper.xmlNamespacePrefix ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; + if (["Composite"].includes(propertyMapper.type.name)) { + if (serializedValue[XML_ATTRKEY]) { + return serializedValue; + } else { + const result2 = { ...serializedValue }; + result2[XML_ATTRKEY] = xmlNamespace; + return result2; + } + } + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = xmlNamespace; + return result; +} +__name(getXmlObjectValue, "getXmlObjectValue"); +function isSpecialXmlProperty(propertyName, options) { + return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); +} +__name(isSpecialXmlProperty, "isSpecialXmlProperty"); +function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { + const xmlCharKey = options.xml.xmlCharKey ?? XML_CHARKEY; + if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { + mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); + } + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); + handledPropertyNames.push(paths[0]); + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; + if (serializedName !== "" && serializedName !== void 0) { + propertyObjectName = objectName + "." + serializedName; + } + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { + if (headerKey.startsWith(headerCollectionPrefix)) { + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + } + handledPropertyNames.push(headerKey); + } + instance[key] = dictionary; + } else if (serializer.isXML) { + if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { + instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + } else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== void 0) { + instance[key] = responseBody[xmlCharKey]; + } else if (typeof responseBody === "string") { + instance[key] = responseBody; + } + } else { + const propertyName = xmlElementName || xmlName || serializedName; + if (propertyMapper.xmlIsWrapped) { + const wrapped = responseBody[xmlName]; + const elementList = wrapped?.[xmlElementName] ?? []; + Object.defineProperty(instance, key, { + value: serializer.deserialize(propertyMapper, elementList, propertyObjectName, options), + enumerable: true, + configurable: true, + writable: true + }); + handledPropertyNames.push(xmlName); + } else { + const property = responseBody[propertyName]; + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + handledPropertyNames.push(propertyName); + } + } + } else { + let propertyInstance; + let res = responseBody; + let steps = 0; + for (const item of paths) { + if (!res) + break; + steps++; + res = res[item]; + } + if (res === null && steps < paths.length) { + res = void 0; + } + propertyInstance = res; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && (propertyInstance === void 0 || propertyInstance === null)) { + propertyInstance = mapper.serializedName; + } + let serializedValue; + if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { + propertyInstance = responseBody[key]; + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + for (const [k, v] of Object.entries(instance)) { + if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { + arrayInstance[k] = v; + } + } + instance = arrayInstance; + } else if (propertyInstance !== void 0 || propertyMapper.defaultValue !== void 0) { + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance[key] = serializedValue; + } + } + } + const additionalPropertiesMapper = mapper.type.additionalProperties; + if (additionalPropertiesMapper) { + const isAdditionalProperty = /* @__PURE__ */ __name((responsePropName) => { + for (const clientPropName of Object.keys(modelProps)) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); + if (paths[0] === responsePropName) { + return false; + } + } + return true; + }, "isAdditionalProperty"); + for (const responsePropName of Object.keys(responseBody)) { + if (isAdditionalProperty(responsePropName)) { + const deserializedValue = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + Object.defineProperty(instance, responsePropName, { + value: deserializedValue, + enumerable: true, + configurable: true, + writable: true + }); + } + } + } else if (responseBody && !options.ignoreUnknownProperties) { + for (const key of Object.keys(responseBody)) { + if (instance[key] === void 0 && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { + Object.defineProperty(instance, key, { + value: responseBody[key], + enumerable: true, + configurable: true, + writable: true + }); + } + } + } + return instance; +} +__name(deserializeCompositeType, "deserializeCompositeType"); +function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { + const value = mapper.type.value; + if (!value || typeof value !== "object") { + throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}`); + } + if (responseBody) { + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + } + return tempDictionary; + } + return responseBody; +} +__name(deserializeDictionaryType, "deserializeDictionaryType"); +function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { + let element = mapper.type.element; + if (!element || typeof element !== "object") { + throw new Error(`"element" metadata for an Array must be defined in the mapper and it must be of type "object" in ${objectName}`); + } + if (responseBody) { + if (!Array.isArray(responseBody)) { + responseBody = [responseBody]; + } + if (element.type.name === "Composite" && element.type.className) { + element = serializer.modelMappers[element.type.className] ?? element; + } + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); + } + return tempArray; + } + return responseBody; +} +__name(deserializeSequenceType, "deserializeSequenceType"); +function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { + const typeNamesToCheck = [typeName]; + while (typeNamesToCheck.length) { + const currentName = typeNamesToCheck.shift(); + const indexDiscriminator = discriminatorValue === currentName ? discriminatorValue : currentName + "." + discriminatorValue; + if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { + return discriminators[indexDiscriminator]; + } else { + for (const [name3, mapper] of Object.entries(discriminators)) { + if (name3.startsWith(currentName + ".") && mapper.type.uberParent === currentName && mapper.type.className) { + typeNamesToCheck.push(mapper.type.className); + } + } + } + } + return void 0; +} +__name(getIndexDiscriminator, "getIndexDiscriminator"); +function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + if (polymorphicDiscriminator) { + let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + if (discriminatorName) { + if (polymorphicPropertyName === "serializedName") { + discriminatorName = discriminatorName.replace(/\\/gi, ""); + } + const discriminatorValue = object[discriminatorName]; + const typeName = mapper.type.uberParent ?? mapper.type.className; + if (typeof discriminatorValue === "string" && typeName) { + const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); + if (polymorphicMapper) { + mapper = polymorphicMapper; + } + } + } + } + return mapper; +} +__name(getPolymorphicMapper, "getPolymorphicMapper"); +function getPolymorphicDiscriminatorRecursively(serializer, mapper) { + return mapper.type.polymorphicDiscriminator || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); +} +__name(getPolymorphicDiscriminatorRecursively, "getPolymorphicDiscriminatorRecursively"); +function getPolymorphicDiscriminatorSafely(serializer, typeName) { + return typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator; +} +__name(getPolymorphicDiscriminatorSafely, "getPolymorphicDiscriminatorSafely"); +var MapperTypeNames = { + Base64Url: "Base64Url", + Boolean: "Boolean", + ByteArray: "ByteArray", + Composite: "Composite", + Date: "Date", + DateTime: "DateTime", + DateTimeRfc1123: "DateTimeRfc1123", + Dictionary: "Dictionary", + Enum: "Enum", + Number: "Number", + Object: "Object", + Sequence: "Sequence", + String: "String", + Stream: "Stream", + TimeSpan: "TimeSpan", + UnixTime: "UnixTime" +}; + +// ../../node_modules/@azure/core-client/dist/esm/state.js +var import_state_cjs2 = __toESM(require_state_cjs2(), 1); +var state2 = import_state_cjs2.state; + +// ../../node_modules/@azure/core-client/dist/esm/operationHelpers.js +function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { + let parameterPath = parameter.parameterPath; + const parameterMapper = parameter.mapper; + let value; + if (typeof parameterPath === "string") { + parameterPath = [parameterPath]; + } + if (Array.isArray(parameterPath)) { + if (parameterPath.length > 0) { + if (parameterMapper.isConstant) { + value = parameterMapper.defaultValue; + } else { + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + if (!propertySearchResult.propertyFound && fallbackObject) { + propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); + } + let useDefaultValue = false; + if (!propertySearchResult.propertyFound) { + useDefaultValue = parameterMapper.required || parameterPath[0] === "options" && parameterPath.length === 2; + } + value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; + } + } + } else { + if (parameterMapper.required) { + value = {}; + } + for (const [propertyName, propertyPath] of Object.entries(parameterPath)) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { + parameterPath: propertyPath, + mapper: propertyMapper + }, fallbackObject); + if (propertyValue !== void 0) { + if (!value) { + value = {}; + } + Object.defineProperty(value, propertyName, { + value: propertyValue, + enumerable: true, + configurable: true, + writable: true + }); + } + } + } + return value; +} +__name(getOperationArgumentValueFromParameter, "getOperationArgumentValueFromParameter"); +function getPropertyFromParameterPath(parent, parameterPath) { + const result = { propertyFound: false }; + let i = 0; + for (; i < parameterPath.length; ++i) { + const parameterPathPart = parameterPath[i]; + if (parent && parameterPathPart in parent) { + parent = parent[parameterPathPart]; + } else { + break; + } + } + if (i === parameterPath.length) { + result.propertyValue = parent; + result.propertyFound = true; + } + return result; +} +__name(getPropertyFromParameterPath, "getPropertyFromParameterPath"); +var originalRequestSymbol = /* @__PURE__ */ Symbol.for("@azure/core-client original request"); +function hasOriginalRequest(request) { + return originalRequestSymbol in request; +} +__name(hasOriginalRequest, "hasOriginalRequest"); +function getOperationRequestInfo(request) { + if (hasOriginalRequest(request)) { + return getOperationRequestInfo(request[originalRequestSymbol]); + } + let info = state2.operationRequestMap.get(request); + if (!info) { + info = {}; + state2.operationRequestMap.set(request, info); + } + return info; +} +__name(getOperationRequestInfo, "getOperationRequestInfo"); + +// ../../node_modules/@azure/core-client/dist/esm/deserializationPolicy.js +var defaultJsonContentTypes = ["application/json", "text/json"]; +var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +var deserializationPolicyName = "deserializationPolicy"; +function deserializationPolicy(options = {}) { + const jsonContentTypes = options.expectedContentTypes?.json ?? defaultJsonContentTypes; + const xmlContentTypes = options.expectedContentTypes?.xml ?? defaultXmlContentTypes; + const parseXML2 = options.parseXML; + const serializerOptions = options.serializerOptions; + const updatedOptions = { + xml: { + rootName: serializerOptions?.xml.rootName ?? "", + includeRoot: serializerOptions?.xml.includeRoot ?? false, + xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY + } + }; + return { + name: deserializationPolicyName, + async sendRequest(request, next) { + const response = await next(request); + return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML2); + } + }; +} +__name(deserializationPolicy, "deserializationPolicy"); +function getOperationResponseMap(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationInfo = getOperationRequestInfo(request); + const operationSpec = operationInfo?.operationSpec; + if (operationSpec) { + if (!operationInfo?.operationResponseGetter) { + result = operationSpec.responses[parsedResponse.status]; + } else { + result = operationInfo?.operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; +} +__name(getOperationResponseMap, "getOperationResponseMap"); +function shouldDeserializeResponse(parsedResponse) { + const request = parsedResponse.request; + const operationInfo = getOperationRequestInfo(request); + const shouldDeserialize = operationInfo?.shouldDeserialize; + let result; + if (shouldDeserialize === void 0) { + result = true; + } else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } else { + result = shouldDeserialize(parsedResponse); + } + return result; +} +__name(shouldDeserializeResponse, "shouldDeserializeResponse"); +async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML2) { + const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML2); + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationInfo = getOperationRequestInfo(parsedResponse.request); + const operationSpec = operationInfo?.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponseMap(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); + if (error) { + throw error; + } else if (shouldReturnResponse) { + return parsedResponse; + } + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) { + valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } catch (deserializeError) { + const restError = new RestError2(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + throw restError; + } + } else if (operationSpec.httpMethod === "HEAD") { + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); + } + } + return parsedResponse; +} +__name(deserializeResponseBody, "deserializeResponseBody"); +function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return expectedStatusCodes.length === 0 || expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"; +} +__name(isOperationSpecEmpty, "isOperationSpecEmpty"); +function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec ?? operationSpec.responses.default; + const initialErrorMessage = parsedResponse.request.streamResponseStatusCodes?.has(parsedResponse.status) ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; + const error = new RestError2(initialErrorMessage, { + statusCode: parsedResponse.status, + request: parsedResponse.request, + response: parsedResponse + }); + if (!errorResponseSpec && !(parsedResponse.parsedBody?.error?.code && parsedResponse.parsedBody?.error?.message)) { + throw error; + } + const defaultBodyMapper = errorResponseSpec?.bodyMapper; + const defaultHeadersMapper = errorResponseSpec?.headersMapper; + try { + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let deserializedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) { + valueToDeserialize = []; + const elementName = defaultBodyMapper.xmlElementName; + if (typeof parsedBody === "object" && elementName) { + valueToDeserialize = parsedBody[elementName]; + } + } + deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); + } + const internalError = parsedBody.error || deserializedError || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + error.response.parsedBody = deserializedError; + } + } + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); + } + } catch (defaultError) { + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error, shouldReturnResponse: false }; +} +__name(handleErrorResponse, "handleErrorResponse"); +async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML2) { + if (!operationResponse.request.streamResponseStatusCodes?.has(operationResponse.status) && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType2 = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType2 ? [] : contentType2.split(";").map((component) => component.toLowerCase()); + try { + if (contentComponents.length === 0 || contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + operationResponse.parsedBody = JSON.parse(text); + return operationResponse; + } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + if (!parseXML2) { + throw new Error("Parsing XML not supported."); + } + const body2 = await parseXML2(text, opts.xml); + operationResponse.parsedBody = body2; + return operationResponse; + } + } catch (err) { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError2.PARSE_ERROR; + const e = new RestError2(msg, { + code: errCode, + statusCode: operationResponse.status, + request: operationResponse.request, + response: operationResponse + }); + throw e; + } + } + return operationResponse; +} +__name(parse, "parse"); + +// ../../node_modules/@azure/core-client/dist/esm/interfaceHelpers.js +function getStreamingResponseStatusCodes(operationSpec) { + const result = /* @__PURE__ */ new Set(); + for (const [statusCode, operationResponse] of Object.entries(operationSpec.responses)) { + if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) { + result.add(Number(statusCode)); + } + } + return result; +} +__name(getStreamingResponseStatusCodes, "getStreamingResponseStatusCodes"); +function getPathStringFromParameter(parameter) { + const { parameterPath, mapper } = parameter; + let result; + if (typeof parameterPath === "string") { + result = parameterPath; + } else if (Array.isArray(parameterPath)) { + result = parameterPath.join("."); + } else { + result = mapper.serializedName; + } + return result; +} +__name(getPathStringFromParameter, "getPathStringFromParameter"); + +// ../../node_modules/@azure/core-client/dist/esm/serializationPolicy.js +var serializationPolicyName = "serializationPolicy"; +function serializationPolicy(options = {}) { + const stringifyXML2 = options.stringifyXML; + return { + name: serializationPolicyName, + sendRequest(request, next) { + const operationInfo = getOperationRequestInfo(request); + const operationSpec = operationInfo?.operationSpec; + const operationArguments = operationInfo?.operationArguments; + if (operationSpec && operationArguments) { + serializeHeaders(request, operationArguments, operationSpec); + serializeRequestBody(request, operationArguments, operationSpec, stringifyXML2); + } + return next(request); + } + }; +} +__name(serializationPolicy, "serializationPolicy"); +function serializeHeaders(request, operationArguments, operationSpec) { + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter); + if (headerValue !== null && headerValue !== void 0 || headerParameter.mapper.required) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); + const headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + request.headers.set(headerCollectionPrefix + key, headerValue[key]); + } + } else { + request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); + } + } + } + } + const customHeaders = operationArguments.options?.requestOptions?.customHeaders; + if (customHeaders) { + for (const customHeaderName of Object.keys(customHeaders)) { + request.headers.set(customHeaderName, customHeaders[customHeaderName]); + } + } +} +__name(serializeHeaders, "serializeHeaders"); +function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML2 = function() { + throw new Error("XML serialization unsupported!"); +}) { + const serializerOptions = operationArguments.options?.serializerOptions; + const updatedOptions = { + xml: { + rootName: serializerOptions?.xml.rootName ?? "", + includeRoot: serializerOptions?.xml.includeRoot ?? false, + xmlCharKey: serializerOptions?.xml.xmlCharKey ?? XML_CHARKEY + } + }; + const xmlCharKey = updatedOptions.xml.xmlCharKey; + if (operationSpec.requestBody && operationSpec.requestBody.mapper) { + request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody); + const bodyMapper = operationSpec.requestBody.mapper; + const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable } = bodyMapper; + const typeName = bodyMapper.type.name; + try { + if (request.body !== void 0 && request.body !== null || nullable && request.body === null || required) { + const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); + request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); + const isStream = typeName === MapperTypeNames.Stream; + if (operationSpec.isXML) { + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); + if (typeName === MapperTypeNames.Sequence) { + request.body = stringifyXML2(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); + } else if (!isStream) { + request.body = stringifyXML2(value, { + rootName: xmlName || serializedName, + xmlCharKey + }); + } + } else if (typeName === MapperTypeNames.String && (operationSpec.contentType?.match("text/plain") || operationSpec.mediaType === "text")) { + return; + } else if (!isStream) { + request.body = JSON.stringify(request.body); + } + } + } catch (error) { + throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, void 0, " ")}.`); + } + } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { + request.formData = {}; + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter); + if (formDataParameterValue !== void 0 && formDataParameterValue !== null) { + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); + } + } + } +} +__name(serializeRequestBody, "serializeRequestBody"); +function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { + if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { + const result = {}; + result[options.xml.xmlCharKey] = serializedValue; + result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; + return result; + } + return serializedValue; +} +__name(getXmlValueWithNamespace, "getXmlValueWithNamespace"); +function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { + if (!Array.isArray(obj)) { + obj = [obj]; + } + if (!xmlNamespaceKey || !xmlNamespace) { + return { [elementName]: obj }; + } + const result = { [elementName]: obj }; + result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; + return result; +} +__name(prepareXMLRootList, "prepareXMLRootList"); + +// ../../node_modules/@azure/core-client/dist/esm/pipeline.js +function createClientPipeline(options = {}) { + const pipeline2 = createPipelineFromOptions2(options ?? {}); + if (options.credentialOptions) { + pipeline2.addPolicy(bearerTokenAuthenticationPolicy({ + credential: options.credentialOptions.credential, + scopes: options.credentialOptions.credentialScopes + })); + } + pipeline2.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" }); + pipeline2.addPolicy(deserializationPolicy(options.deserializationOptions), { + phase: "Deserialize" + }); + return pipeline2; +} +__name(createClientPipeline, "createClientPipeline"); + +// ../../node_modules/@azure/core-client/dist/esm/httpClientCache.js +var cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = createDefaultHttpClient2(); + } + return cachedHttpClient; +} +__name(getCachedDefaultHttpClient, "getCachedDefaultHttpClient"); + +// ../../node_modules/@azure/core-client/dist/esm/urlHelpers.js +var CollectionFormatToDelimiterMap = { + CSV: ",", + SSV: " ", + Multi: "Multi", + TSV: " ", + Pipes: "|" +}; +function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { + const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); + let isAbsolutePath = false; + let requestUrl = replaceAll(baseUri, urlReplacements); + if (operationSpec.path) { + let path5 = replaceAll(operationSpec.path, urlReplacements); + if (operationSpec.path === "/{nextLink}" && path5.startsWith("/")) { + path5 = path5.substring(1); + } + if (isAbsoluteUrl(path5)) { + requestUrl = path5; + isAbsolutePath = true; + } else { + requestUrl = appendPath(requestUrl, path5); + } + } + const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); + requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); + return requestUrl; +} +__name(getRequestUrl, "getRequestUrl"); +function replaceAll(input, replacements) { + let result = input; + for (const [searchValue, replaceValue] of replacements) { + result = result.split(searchValue).join(replaceValue); + } + return result; +} +__name(replaceAll, "replaceAll"); +function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { + const result = /* @__PURE__ */ new Map(); + if (operationSpec.urlParameters?.length) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject); + const parameterPathString = getPathStringFromParameter(urlParameter); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); + } + } + return result; +} +__name(calculateUrlReplacements, "calculateUrlReplacements"); +function isAbsoluteUrl(url2) { + return url2.includes("://"); +} +__name(isAbsoluteUrl, "isAbsoluteUrl"); +function appendPath(url2, pathToAppend) { + if (!pathToAppend) { + return url2; + } + const parsedUrl = new URL(url2); + let newPath = parsedUrl.pathname; + if (!newPath.endsWith("/")) { + newPath = `${newPath}/`; + } + if (pathToAppend.startsWith("/")) { + pathToAppend = pathToAppend.substring(1); + } + const searchStart = pathToAppend.indexOf("?"); + if (searchStart !== -1) { + const path5 = pathToAppend.substring(0, searchStart); + const search = pathToAppend.substring(searchStart + 1); + newPath = newPath + path5; + if (search) { + parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; + } + } else { + newPath = newPath + pathToAppend; + } + Object.assign(parsedUrl, { pathname: newPath }); + return parsedUrl.toString(); +} +__name(appendPath, "appendPath"); +function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { + const result = /* @__PURE__ */ new Map(); + const sequenceParams = /* @__PURE__ */ new Set(); + if (operationSpec.queryParameters?.length) { + for (const queryParameter of operationSpec.queryParameters) { + if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { + sequenceParams.add(queryParameter.mapper.serializedName); + } + let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject); + if (queryParameterValue !== void 0 && queryParameterValue !== null || queryParameter.mapper.required) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); + const delimiter2 = queryParameter.collectionFormat ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] : ""; + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + if (item === null || item === void 0) { + return ""; + } + return item; + }); + } + if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { + continue; + } else if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { + queryParameterValue = queryParameterValue.join(delimiter2); + } + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + queryParameterValue = queryParameterValue.map((item) => { + return encodeURIComponent(item); + }); + } else { + queryParameterValue = encodeURIComponent(queryParameterValue); + } + } + if (Array.isArray(queryParameterValue) && (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { + queryParameterValue = queryParameterValue.join(delimiter2); + } + result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + } + } + } + return { + queryParams: result, + sequenceParams + }; +} +__name(calculateQueryParameters, "calculateQueryParameters"); +function simpleParseQueryParams(queryString) { + const result = /* @__PURE__ */ new Map(); + if (!queryString || queryString[0] !== "?") { + return result; + } + queryString = queryString.slice(1); + const pairs = queryString.split("&"); + for (const pair of pairs) { + const [name3, value] = pair.split("=", 2); + const existingValue = result.get(name3); + if (existingValue) { + if (Array.isArray(existingValue)) { + existingValue.push(value); + } else { + result.set(name3, [existingValue, value]); + } + } else { + result.set(name3, value); + } + } + return result; +} +__name(simpleParseQueryParams, "simpleParseQueryParams"); +function appendQueryParams(url2, queryParams, sequenceParams, noOverwrite = false) { + if (queryParams.size === 0) { + return url2; + } + const parsedUrl = new URL(url2); + const combinedParams = simpleParseQueryParams(parsedUrl.search); + for (const [name3, value] of queryParams) { + const existingValue = combinedParams.get(name3); + if (Array.isArray(existingValue)) { + if (Array.isArray(value)) { + existingValue.push(...value); + const valueSet = new Set(existingValue); + combinedParams.set(name3, Array.from(valueSet)); + } else { + existingValue.push(value); + } + } else if (existingValue) { + if (Array.isArray(value)) { + value.unshift(existingValue); + } else if (sequenceParams.has(name3)) { + combinedParams.set(name3, [existingValue, value]); + } + if (!noOverwrite) { + combinedParams.set(name3, value); + } + } else { + combinedParams.set(name3, value); + } + } + const searchPieces = []; + for (const [name3, value] of combinedParams) { + if (typeof value === "string") { + searchPieces.push(`${name3}=${value}`); + } else if (Array.isArray(value)) { + for (const subValue of value) { + searchPieces.push(`${name3}=${subValue}`); + } + } else { + searchPieces.push(`${name3}=${value}`); + } + } + parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; + return parsedUrl.toString(); +} +__name(appendQueryParams, "appendQueryParams"); + +// ../../node_modules/@azure/core-client/dist/esm/log.js +var logger3 = createClientLogger2("core-client"); + +// ../../node_modules/@azure/core-client/dist/esm/serviceClient.js +var ServiceClient = class { + static { + __name(this, "ServiceClient"); + } + /** + * If specified, this is the base URI that requests will be made against for this ServiceClient. + * If it is not specified, then all OperationSpecs must contain a baseUrl property. + */ + _endpoint; + /** + * The default request content type for the service. + * Used if no requestContentType is present on an OperationSpec. + */ + _requestContentType; + /** + * Set to true if the request is sent over HTTP instead of HTTPS + */ + _allowInsecureConnection; + /** + * The HTTP client that will be used to send requests. + */ + _httpClient; + /** + * The pipeline used by this client to make requests + */ + pipeline; + /** + * The ServiceClient constructor + * @param options - The service client options that govern the behavior of the client. + */ + constructor(options = {}) { + this._requestContentType = options.requestContentType; + this._endpoint = options.endpoint ?? options.baseUri; + if (options.baseUri) { + logger3.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); + } + this._allowInsecureConnection = options.allowInsecureConnection; + this._httpClient = options.httpClient || getCachedDefaultHttpClient(); + this.pipeline = options.pipeline || createDefaultPipeline2(options); + if (options.additionalPolicies?.length) { + for (const { policy, position } of options.additionalPolicies) { + const afterPhase = position === "perRetry" ? "Sign" : void 0; + this.pipeline.addPolicy(policy, { + afterPhase + }); + } + } + } + /** + * Send the provided httpRequest. + */ + sendRequest(request) { + return this.pipeline.sendRequest(this._httpClient, request); + } + /** + * Send an HTTP request that is populated using the provided OperationSpec. + * @typeParam T - The typed result of the request, based on the OperationSpec. + * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. + * @param operationSpec - The OperationSpec to use to populate the httpRequest. + */ + async sendOperationRequest(operationArguments, operationSpec) { + const endpoint = operationSpec.baseUrl || this._endpoint; + if (!endpoint) { + throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); + } + const url2 = getRequestUrl(endpoint, operationSpec, operationArguments, this); + const request = createPipelineRequest2({ + url: url2 + }); + request.method = operationSpec.httpMethod; + const operationInfo = getOperationRequestInfo(request); + operationInfo.operationSpec = operationSpec; + operationInfo.operationArguments = operationArguments; + const contentType2 = operationSpec.contentType || this._requestContentType; + if (contentType2 && operationSpec.requestBody) { + request.headers.set("Content-Type", contentType2); + } + const options = operationArguments.options; + if (options) { + const requestOptions = options.requestOptions; + if (requestOptions) { + if (requestOptions.timeout) { + request.timeout = requestOptions.timeout; + } + if (requestOptions.onUploadProgress) { + request.onUploadProgress = requestOptions.onUploadProgress; + } + if (requestOptions.onDownloadProgress) { + request.onDownloadProgress = requestOptions.onDownloadProgress; + } + if (requestOptions.shouldDeserialize !== void 0) { + operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; + } + if (requestOptions.allowInsecureConnection) { + request.allowInsecureConnection = true; + } + } + if (options.abortSignal) { + request.abortSignal = options.abortSignal; + } + if (options.tracingOptions) { + request.tracingOptions = options.tracingOptions; + } + } + if (this._allowInsecureConnection) { + request.allowInsecureConnection = true; + } + if (request.streamResponseStatusCodes === void 0) { + request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec); + } + try { + const rawResponse = await this.sendRequest(request); + const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]); + if (options?.onResponse) { + options.onResponse(rawResponse, flatResponse); + } + return flatResponse; + } catch (error) { + if (typeof error === "object" && error?.response) { + const rawResponse = error.response; + const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]); + error.details = flatResponse; + if (options?.onResponse) { + options.onResponse(rawResponse, flatResponse, error); + } + } + throw error; + } + } +}; +function createDefaultPipeline2(options) { + const credentialScopes = getCredentialScopes(options); + const credentialOptions = options.credential && credentialScopes ? { credentialScopes, credential: options.credential } : void 0; + return createClientPipeline({ + ...options, + credentialOptions + }); +} +__name(createDefaultPipeline2, "createDefaultPipeline"); +function getCredentialScopes(options) { + if (options.credentialScopes) { + return options.credentialScopes; + } + if (options.endpoint) { + return `${options.endpoint}/.default`; + } + if (options.baseUri) { + return `${options.baseUri}/.default`; + } + if (options.credential) { + throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); + } + return void 0; +} +__name(getCredentialScopes, "getCredentialScopes"); + +// ../../node_modules/@azure/core-client/dist/esm/authorizeRequestOnTenantChallenge.js +var Constants = { + DefaultScope: "/.default", + /** + * Defines constants for use with HTTP headers. + */ + HeaderConstants: { + /** + * The Authorization header. + */ + AUTHORIZATION: "authorization" + } +}; +function isUuid(text) { + return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text); +} +__name(isUuid, "isUuid"); +var authorizeRequestOnTenantChallenge = /* @__PURE__ */ __name(async (challengeOptions) => { + const requestOptions = requestToOptions(challengeOptions.request); + const challenge = getChallenge(challengeOptions.response); + if (challenge) { + const challengeInfo = parseChallenge(challenge); + const challengeScopes = buildScopes(challengeOptions, challengeInfo); + const tenantId = extractTenantId(challengeInfo); + if (!tenantId) { + return false; + } + const accessToken = await challengeOptions.getAccessToken(challengeScopes, { + ...requestOptions, + tenantId + }); + if (!accessToken) { + return false; + } + challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `${accessToken.tokenType ?? "Bearer"} ${accessToken.token}`); + return true; + } + return false; +}, "authorizeRequestOnTenantChallenge"); +function extractTenantId(challengeInfo) { + const parsedAuthUri = new URL(challengeInfo.authorization_uri); + const pathSegments = parsedAuthUri.pathname.split("/"); + const tenantId = pathSegments[1]; + if (tenantId && isUuid(tenantId)) { + return tenantId; + } + return void 0; +} +__name(extractTenantId, "extractTenantId"); +function buildScopes(challengeOptions, challengeInfo) { + if (!challengeInfo.resource_id) { + return challengeOptions.scopes; + } + const challengeScopes = new URL(challengeInfo.resource_id); + let scope = new URL(Constants.DefaultScope, challengeScopes.origin).toString(); + if (scope === "https://disk.azure.com/.default") { + scope = "https://disk.azure.com//.default"; + } + return [scope]; +} +__name(buildScopes, "buildScopes"); +function getChallenge(response) { + const challenge = response.headers.get("WWW-Authenticate"); + if (response.status === 401 && challenge) { + return challenge; + } + return; +} +__name(getChallenge, "getChallenge"); +function parseChallenge(challenge) { + const bearerChallenge = challenge.slice("Bearer ".length); + const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x); + const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("="))); + return keyValuePairs.reduce((a, b) => ({ ...a, ...b }), {}); +} +__name(parseChallenge, "parseChallenge"); +function requestToOptions(request) { + return { + abortSignal: request.abortSignal, + requestOptions: { + timeout: request.timeout + }, + tracingOptions: request.tracingOptions + }; +} +__name(requestToOptions, "requestToOptions"); + +// ../../node_modules/@azure/core-http-compat/dist/esm/util.js +var originalRequestSymbol2 = /* @__PURE__ */ Symbol("Original PipelineRequest"); +var originalClientRequestSymbol = /* @__PURE__ */ Symbol.for("@azure/core-client original request"); +var passThroughProps = /* @__PURE__ */ new Set([ + "url", + "method", + "withCredentials", + "timeout", + "requestId", + "abortSignal", + "body", + "formData", + "onDownloadProgress", + "onUploadProgress", + "proxySettings", + "streamResponseStatusCodes", + "agent", + "requestOverrides" +]); +function toPipelineRequest(webResource, options = {}) { + const compatWebResource = webResource; + const request = compatWebResource[originalRequestSymbol2]; + const headers = createHttpHeaders2(webResource.headers.toJson({ preserveCase: true })); + if (request) { + request.headers = headers; + return request; + } else { + const newRequest = createPipelineRequest2({ + url: webResource.url, + method: webResource.method, + headers, + withCredentials: webResource.withCredentials, + timeout: webResource.timeout, + requestId: webResource.requestId, + abortSignal: webResource.abortSignal, + body: webResource.body, + formData: webResource.formData, + disableKeepAlive: !!webResource.keepAlive, + onDownloadProgress: webResource.onDownloadProgress, + onUploadProgress: webResource.onUploadProgress, + proxySettings: webResource.proxySettings, + streamResponseStatusCodes: webResource.streamResponseStatusCodes, + agent: webResource.agent, + requestOverrides: webResource.requestOverrides + }); + if (options.originalRequest) { + newRequest[originalClientRequestSymbol] = options.originalRequest; + } + return newRequest; + } +} +__name(toPipelineRequest, "toPipelineRequest"); +function toWebResourceLike(request, options) { + const originalRequest = options?.originalRequest ?? request; + const webResource = { + url: request.url, + method: request.method, + headers: toHttpHeadersLike(request.headers), + withCredentials: request.withCredentials, + timeout: request.timeout, + requestId: request.headers.get("x-ms-client-request-id") || request.requestId, + abortSignal: request.abortSignal, + body: request.body, + formData: request.formData, + keepAlive: !!request.disableKeepAlive, + onDownloadProgress: request.onDownloadProgress, + onUploadProgress: request.onUploadProgress, + proxySettings: request.proxySettings, + streamResponseStatusCodes: request.streamResponseStatusCodes, + agent: request.agent, + requestOverrides: request.requestOverrides, + clone() { + throw new Error("Cannot clone a non-proxied WebResourceLike"); + }, + prepare() { + throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat"); + }, + validateRequestProperties() { + } + }; + if (options?.createProxy) { + return new Proxy(webResource, { + get(target, prop, receiver) { + if (prop === originalRequestSymbol2) { + return request; + } else if (prop === "clone") { + return () => { + return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), { + createProxy: true, + originalRequest + }); + }; + } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "keepAlive") { + request.disableKeepAlive = !value; + } + if (typeof prop === "string" && passThroughProps.has(prop)) { + request[prop] = value; + } + return Reflect.set(target, prop, value, receiver); + } + }); + } else { + return webResource; + } +} +__name(toWebResourceLike, "toWebResourceLike"); +function toHttpHeadersLike(headers) { + return new HttpHeaders(headers.toJSON({ preserveCase: true })); +} +__name(toHttpHeadersLike, "toHttpHeadersLike"); +function getHeaderKey(headerName) { + return headerName.toLowerCase(); +} +__name(getHeaderKey, "getHeaderKey"); +var HttpHeaders = class _HttpHeaders { + static { + __name(this, "HttpHeaders"); + } + _headersMap; + constructor(rawHeaders) { + this._headersMap = {}; + if (rawHeaders) { + for (const headerName in rawHeaders) { + this.set(headerName, rawHeaders[headerName]); + } + } + } + /** + * Set a header in this collection with the provided name and value. The name is + * case-insensitive. + * @param headerName - The name of the header to set. This value is case-insensitive. + * @param headerValue - The value of the header to set. + */ + set(headerName, headerValue) { + this._headersMap[getHeaderKey(headerName)] = { + name: headerName, + value: headerValue.toString() + }; + } + /** + * Get the header value for the provided header name, or undefined if no header exists in this + * collection with the provided name. + * @param headerName - The name of the header. + */ + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; + return !header ? void 0 : header.value; + } + /** + * Get whether or not this header collection contains a header entry for the provided header name. + */ + contains(headerName) { + return !!this._headersMap[getHeaderKey(headerName)]; + } + /** + * Remove the header with the provided headerName. Return whether or not the header existed and + * was removed. + * @param headerName - The name of the header to remove. + */ + remove(headerName) { + const result = this.contains(headerName); + delete this._headersMap[getHeaderKey(headerName)]; + return result; + } + /** + * Get the headers that are contained this collection as an object. + */ + rawHeaders() { + return this.toJson({ preserveCase: true }); + } + /** + * Get the headers that are contained in this collection as an array. + */ + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { + headers.push(this._headersMap[headerKey]); + } + return headers; + } + /** + * Get the header names that are contained in this collection. + */ + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerNames.push(headers[i].name); + } + return headerNames; + } + /** + * Get the header values that are contained in this collection. + */ + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { + headerValues.push(headers[i].value); + } + return headerValues; + } + /** + * Get the JSON object representation of this HTTP header collection. + */ + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } + } + return result; + } + /** + * Get the string representation of this HTTP header collection. + */ + toString() { + return JSON.stringify(this.toJson({ preserveCase: true })); + } + /** + * Create a deep clone/copy of this HttpHeaders collection. + */ + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new _HttpHeaders(resultPreservingCasing); + } +}; + +// ../../node_modules/@azure/core-http-compat/dist/esm/response.js +var originalResponse = /* @__PURE__ */ Symbol("Original FullOperationResponse"); +function toCompatResponse(response, options) { + let request = toWebResourceLike(response.request); + let headers = toHttpHeadersLike(response.headers); + if (options?.createProxy) { + return new Proxy(response, { + get(target, prop, receiver) { + if (prop === "headers") { + return headers; + } else if (prop === "request") { + return request; + } else if (prop === originalResponse) { + return response; + } + return Reflect.get(target, prop, receiver); + }, + set(target, prop, value, receiver) { + if (prop === "headers") { + headers = value; + } else if (prop === "request") { + request = value; + } + return Reflect.set(target, prop, value, receiver); + } + }); + } else { + return { + ...response, + request, + headers + }; + } +} +__name(toCompatResponse, "toCompatResponse"); +function toPipelineResponse(compatResponse) { + const extendedCompatResponse = compatResponse; + const response = extendedCompatResponse[originalResponse]; + const headers = createHttpHeaders2(compatResponse.headers.toJson({ preserveCase: true })); + if (response) { + response.headers = headers; + return response; + } else { + return { + ...compatResponse, + headers, + request: toPipelineRequest(compatResponse.request) + }; + } +} +__name(toPipelineResponse, "toPipelineResponse"); + +// ../../node_modules/@azure/core-http-compat/dist/esm/extendedClient.js +var ExtendedServiceClient = class extends ServiceClient { + static { + __name(this, "ExtendedServiceClient"); + } + constructor(options) { + super(options); + if (options.keepAliveOptions?.enable === false && !pipelineContainsDisableKeepAlivePolicy(this.pipeline)) { + this.pipeline.addPolicy(createDisableKeepAlivePolicy()); + } + if (options.redirectOptions?.handleRedirects === false) { + this.pipeline.removePolicy({ + name: redirectPolicyName2 + }); + } + } + /** + * Compatible send operation request function. + * + * @param operationArguments - Operation arguments + * @param operationSpec - Operation Spec + * @returns + */ + async sendOperationRequest(operationArguments, operationSpec) { + const userProvidedCallBack = operationArguments?.options?.onResponse; + let lastResponse; + function onResponse(rawResponse, flatResponse, error) { + lastResponse = rawResponse; + if (userProvidedCallBack) { + userProvidedCallBack(rawResponse, flatResponse, error); + } + } + __name(onResponse, "onResponse"); + operationArguments.options = { + ...operationArguments.options, + onResponse + }; + const result = await super.sendOperationRequest(operationArguments, operationSpec); + if (lastResponse) { + Object.defineProperty(result, "_response", { + value: toCompatResponse(lastResponse) + }); + } + return result; + } +}; + +// ../../node_modules/@azure/core-http-compat/dist/esm/policies/requestPolicyFactoryPolicy.js +var HttpPipelineLogLevel; +(function(HttpPipelineLogLevel2) { + HttpPipelineLogLevel2[HttpPipelineLogLevel2["ERROR"] = 1] = "ERROR"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["INFO"] = 3] = "INFO"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["OFF"] = 0] = "OFF"; + HttpPipelineLogLevel2[HttpPipelineLogLevel2["WARNING"] = 2] = "WARNING"; +})(HttpPipelineLogLevel || (HttpPipelineLogLevel = {})); +var mockRequestPolicyOptions = { + log(_logLevel, _message) { + }, + shouldLog(_logLevel) { + return false; + } +}; +var requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy"; +function createRequestPolicyFactoryPolicy(factories) { + const orderedFactories = factories.slice().reverse(); + return { + name: requestPolicyFactoryPolicyName, + async sendRequest(request, next) { + let httpPipeline = { + async sendRequest(httpRequest) { + const response2 = await next(toPipelineRequest(httpRequest)); + return toCompatResponse(response2, { createProxy: true }); + } + }; + for (const factory of orderedFactories) { + httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions); + } + const webResourceLike = toWebResourceLike(request, { createProxy: true }); + const response = await httpPipeline.sendRequest(webResourceLike); + return toPipelineResponse(response); + } + }; +} +__name(createRequestPolicyFactoryPolicy, "createRequestPolicyFactoryPolicy"); + +// ../../node_modules/@azure/core-http-compat/dist/esm/httpClientAdapter.js +function convertHttpClient(requestPolicyClient) { + return { + sendRequest: /* @__PURE__ */ __name(async (request) => { + const response = await requestPolicyClient.sendRequest(toWebResourceLike(request, { createProxy: true })); + return toPipelineResponse(response); + }, "sendRequest") + }; +} +__name(convertHttpClient, "convertHttpClient"); + +// ../../node_modules/fast-xml-parser/src/util.js +var nameStartChar = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*"; +var regexName = new RegExp("^" + nameRegexp + "$"); +function getAllMatches(string, regex) { + const matches = []; + let match = regex.exec(string); + while (match) { + const allmatches = []; + allmatches.startIndex = regex.lastIndex - match[0].length; + const len = match.length; + for (let index = 0; index < len; index++) { + allmatches.push(match[index]); + } + matches.push(allmatches); + match = regex.exec(string); + } + return matches; +} +__name(getAllMatches, "getAllMatches"); +var isName = /* @__PURE__ */ __name(function(string) { + const match = regexName.exec(string); + return !(match === null || typeof match === "undefined"); +}, "isName"); +function isExist(v) { + return typeof v !== "undefined"; +} +__name(isExist, "isExist"); +var DANGEROUS_PROPERTY_NAMES = [ + // '__proto__', + // 'constructor', + // 'prototype', + "hasOwnProperty", + "toString", + "valueOf", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__" +]; +var criticalProperties = ["__proto__", "constructor", "prototype"]; + +// ../../node_modules/fast-xml-parser/src/validator.js +var defaultOptions = { + allowBooleanAttributes: false, + //A tag can have attributes without any value + unpairedTags: [] +}; +function validate(xmlData, options) { + options = Object.assign({}, defaultOptions, options); + const tags2 = []; + let tagFound = false; + let reachedRoot = false; + if (xmlData[0] === "\uFEFF") { + xmlData = xmlData.substr(1); + } + for (let i = 0; i < xmlData.length; i++) { + if (xmlData[i] === "<" && xmlData[i + 1] === "?") { + i += 2; + i = readPI(xmlData, i); + if (i.err) return i; + } else if (xmlData[i] === "<") { + let tagStartPos = i; + i++; + if (xmlData[i] === "!") { + i = readCommentAndCDATA(xmlData, i); + continue; + } else { + let closingTag = false; + if (xmlData[i] === "/") { + closingTag = true; + i++; + } + let tagName = ""; + for (; i < xmlData.length && xmlData[i] !== ">" && xmlData[i] !== " " && xmlData[i] !== " " && xmlData[i] !== "\n" && xmlData[i] !== "\r"; i++) { + tagName += xmlData[i]; + } + tagName = tagName.trim(); + if (tagName[tagName.length - 1] === "/") { + tagName = tagName.substring(0, tagName.length - 1); + i--; + } + if (!validateTagName(tagName)) { + let msg; + if (tagName.trim().length === 0) { + msg = "Invalid space after '<'."; + } else { + msg = "Tag '" + tagName + "' is an invalid name."; + } + return getErrorObject("InvalidTag", msg, getLineNumberForPosition(xmlData, i)); + } + const result = readAttributeStr(xmlData, i); + if (result === false) { + return getErrorObject("InvalidAttr", "Attributes for '" + tagName + "' have open quote.", getLineNumberForPosition(xmlData, i)); + } + let attrStr = result.value; + i = result.index; + if (attrStr[attrStr.length - 1] === "/") { + const attrStrStart = i - attrStr.length; + attrStr = attrStr.substring(0, attrStr.length - 1); + const isValid = validateAttributeString(attrStr, options); + if (isValid === true) { + tagFound = true; + } else { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line)); + } + } else if (closingTag) { + if (!result.tagClosed) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' doesn't have proper closing.", getLineNumberForPosition(xmlData, i)); + } else if (attrStr.trim().length > 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos)); + } else if (tags2.length === 0) { + return getErrorObject("InvalidTag", "Closing tag '" + tagName + "' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos)); + } else { + const otg = tags2.pop(); + if (tagName !== otg.tagName) { + let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos); + return getErrorObject( + "InvalidTag", + "Expected closing tag '" + otg.tagName + "' (opened in line " + openPos.line + ", col " + openPos.col + ") instead of closing tag '" + tagName + "'.", + getLineNumberForPosition(xmlData, tagStartPos) + ); + } + if (tags2.length == 0) { + reachedRoot = true; + } + } + } else { + const isValid = validateAttributeString(attrStr, options); + if (isValid !== true) { + return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line)); + } + if (reachedRoot === true) { + return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(xmlData, i)); + } else if (options.unpairedTags.indexOf(tagName) !== -1) { + } else { + tags2.push({ tagName, tagStartPos }); + } + tagFound = true; + } + for (i++; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + if (xmlData[i + 1] === "!") { + i++; + i = readCommentAndCDATA(xmlData, i); + continue; + } else if (xmlData[i + 1] === "?") { + i = readPI(xmlData, ++i); + if (i.err) return i; + } else { + break; + } + } else if (xmlData[i] === "&") { + const afterAmp = validateAmpersand(xmlData, i); + if (afterAmp == -1) + return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(xmlData, i)); + i = afterAmp; + } else { + if (reachedRoot === true && !isWhiteSpace(xmlData[i])) { + return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(xmlData, i)); + } + } + } + if (xmlData[i] === "<") { + i--; + } + } + } else { + if (isWhiteSpace(xmlData[i])) { + continue; + } + return getErrorObject("InvalidChar", "char '" + xmlData[i] + "' is not expected.", getLineNumberForPosition(xmlData, i)); + } + } + if (!tagFound) { + return getErrorObject("InvalidXml", "Start tag expected.", 1); + } else if (tags2.length == 1) { + return getErrorObject("InvalidTag", "Unclosed tag '" + tags2[0].tagName + "'.", getLineNumberForPosition(xmlData, tags2[0].tagStartPos)); + } else if (tags2.length > 0) { + return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(tags2.map((t) => t.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }); + } + return true; +} +__name(validate, "validate"); +function isWhiteSpace(char) { + return char === " " || char === " " || char === "\n" || char === "\r"; +} +__name(isWhiteSpace, "isWhiteSpace"); +function readPI(xmlData, i) { + const start = i; + for (; i < xmlData.length; i++) { + if (xmlData[i] == "?" || xmlData[i] == " ") { + const tagname = xmlData.substr(start, i - start); + if (i > 5 && tagname === "xml") { + return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(xmlData, i)); + } else if (xmlData[i] == "?" && xmlData[i + 1] == ">") { + i++; + break; + } else { + continue; + } + } + } + return i; +} +__name(readPI, "readPI"); +function readCommentAndCDATA(xmlData, i) { + if (xmlData.length > i + 5 && xmlData[i + 1] === "-" && xmlData[i + 2] === "-") { + for (i += 3; i < xmlData.length; i++) { + if (xmlData[i] === "-" && xmlData[i + 1] === "-" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } else if (xmlData.length > i + 8 && xmlData[i + 1] === "D" && xmlData[i + 2] === "O" && xmlData[i + 3] === "C" && xmlData[i + 4] === "T" && xmlData[i + 5] === "Y" && xmlData[i + 6] === "P" && xmlData[i + 7] === "E") { + let angleBracketsCount = 1; + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "<") { + angleBracketsCount++; + } else if (xmlData[i] === ">") { + angleBracketsCount--; + if (angleBracketsCount === 0) { + break; + } + } + } + } else if (xmlData.length > i + 9 && xmlData[i + 1] === "[" && xmlData[i + 2] === "C" && xmlData[i + 3] === "D" && xmlData[i + 4] === "A" && xmlData[i + 5] === "T" && xmlData[i + 6] === "A" && xmlData[i + 7] === "[") { + for (i += 8; i < xmlData.length; i++) { + if (xmlData[i] === "]" && xmlData[i + 1] === "]" && xmlData[i + 2] === ">") { + i += 2; + break; + } + } + } + return i; +} +__name(readCommentAndCDATA, "readCommentAndCDATA"); +var doubleQuote = '"'; +var singleQuote = "'"; +function readAttributeStr(xmlData, i) { + let attrStr = ""; + let startChar = ""; + let tagClosed = false; + for (; i < xmlData.length; i++) { + if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) { + if (startChar === "") { + startChar = xmlData[i]; + } else if (startChar !== xmlData[i]) { + } else { + startChar = ""; + } + } else if (xmlData[i] === ">") { + if (startChar === "") { + tagClosed = true; + break; + } + } + attrStr += xmlData[i]; + } + if (startChar !== "") { + return false; + } + return { + value: attrStr, + index: i, + tagClosed + }; +} +__name(readAttributeStr, "readAttributeStr"); +var validAttrStrRegxp = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); +function validateAttributeString(attrStr, options) { + const matches = getAllMatches(attrStr, validAttrStrRegxp); + const attrNames = {}; + for (let i = 0; i < matches.length; i++) { + if (matches[i][1].length === 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' has no space in starting.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] !== void 0 && matches[i][4] === void 0) { + return getErrorObject("InvalidAttr", "Attribute '" + matches[i][2] + "' is without value.", getPositionFromMatch(matches[i])); + } else if (matches[i][3] === void 0 && !options.allowBooleanAttributes) { + return getErrorObject("InvalidAttr", "boolean attribute '" + matches[i][2] + "' is not allowed.", getPositionFromMatch(matches[i])); + } + const attrName = matches[i][2]; + if (!validateAttrName(attrName)) { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches[i])); + } + if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) { + attrNames[attrName] = 1; + } else { + return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches[i])); + } + } + return true; +} +__name(validateAttributeString, "validateAttributeString"); +function validateNumberAmpersand(xmlData, i) { + let re = /\d/; + if (xmlData[i] === "x") { + i++; + re = /[\da-fA-F]/; + } + for (; i < xmlData.length; i++) { + if (xmlData[i] === ";") + return i; + if (!xmlData[i].match(re)) + break; + } + return -1; +} +__name(validateNumberAmpersand, "validateNumberAmpersand"); +function validateAmpersand(xmlData, i) { + i++; + if (xmlData[i] === ";") + return -1; + if (xmlData[i] === "#") { + i++; + return validateNumberAmpersand(xmlData, i); + } + let count = 0; + for (; i < xmlData.length; i++, count++) { + if (xmlData[i].match(/\w/) && count < 20) + continue; + if (xmlData[i] === ";") + break; + return -1; + } + return i; +} +__name(validateAmpersand, "validateAmpersand"); +function getErrorObject(code, message, lineNumber) { + return { + err: { + code, + msg: message, + line: lineNumber.line || lineNumber, + col: lineNumber.col + } + }; +} +__name(getErrorObject, "getErrorObject"); +function validateAttrName(attrName) { + return isName(attrName); +} +__name(validateAttrName, "validateAttrName"); +function validateTagName(tagname) { + return isName(tagname); +} +__name(validateTagName, "validateTagName"); +function getLineNumberForPosition(xmlData, index) { + const lines = xmlData.substring(0, index).split(/\r?\n/); + return { + line: lines.length, + // column number is last line's length + 1, because column numbering starts at 1: + col: lines[lines.length - 1].length + 1 + }; +} +__name(getLineNumberForPosition, "getLineNumberForPosition"); +function getPositionFromMatch(match) { + return match.startIndex + match[1].length; +} +__name(getPositionFromMatch, "getPositionFromMatch"); + +// ../../node_modules/@nodable/entities/src/entities.js +var CURRENCY = { + cent: "\xA2", + pound: "\xA3", + curren: "\xA4", + yen: "\xA5", + euro: "\u20AC", + dollar: "$", + fnof: "\u0192", + inr: "\u20B9", + af: "\u060B", + birr: "\u1265\u122D", + peso: "\u20B1", + rub: "\u20BD", + won: "\u20A9", + yuan: "\xA5", + cedil: "\xB8" +}; +var XML = { + amp: "&", + apos: "'", + gt: ">", + lt: "<", + quot: '"' +}; +var COMMON_HTML = { + nbsp: "\xA0", + copy: "\xA9", + reg: "\xAE", + trade: "\u2122", + mdash: "\u2014", + ndash: "\u2013", + hellip: "\u2026", + laquo: "\xAB", + raquo: "\xBB", + lsquo: "\u2018", + rsquo: "\u2019", + ldquo: "\u201C", + rdquo: "\u201D", + bull: "\u2022", + para: "\xB6", + sect: "\xA7", + deg: "\xB0", + frac12: "\xBD", + frac14: "\xBC", + frac34: "\xBE" +}; + +// ../../node_modules/@nodable/entities/src/EntityDecoder.js +var ENTITY_ACTION = Object.freeze({ + /** Resolve and expand the entity normally. */ + ALLOW: "allow", + /** Silently skip this entity — it will not be registered. */ + BLOCK: "block", + /** Throw an error, aborting entity registration entirely. */ + THROW: "throw" +}); +var SPECIAL_CHARS = new Set("!?\\\\/[]$%{}^&*()<>|+"); +function validateEntityName(name3) { + if (name3[0] === "#") { + throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${name3}"`); + } + for (const ch of name3) { + if (SPECIAL_CHARS.has(ch)) { + throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: "${name3}"`); + } + } + return name3; +} +__name(validateEntityName, "validateEntityName"); +function mergeEntityMaps(...maps) { + const out = /* @__PURE__ */ Object.create(null); + for (const map of maps) { + if (!map) continue; + for (const key of Object.keys(map)) { + const raw = map[key]; + if (typeof raw === "string") { + out[key] = raw; + } else if (raw && typeof raw === "object" && raw.val !== void 0) { + const val = raw.val; + if (typeof val === "string") { + out[key] = val; + } + } + } + } + return out; +} +__name(mergeEntityMaps, "mergeEntityMaps"); +var LIMIT_TIER_EXTERNAL = "external"; +var LIMIT_TIER_BASE = "base"; +var LIMIT_TIER_ALL = "all"; +function parseLimitTiers(raw) { + if (!raw || raw === LIMIT_TIER_EXTERNAL) return /* @__PURE__ */ new Set([LIMIT_TIER_EXTERNAL]); + if (raw === LIMIT_TIER_ALL) return /* @__PURE__ */ new Set([LIMIT_TIER_ALL]); + if (raw === LIMIT_TIER_BASE) return /* @__PURE__ */ new Set([LIMIT_TIER_BASE]); + if (Array.isArray(raw)) return new Set(raw); + return /* @__PURE__ */ new Set([LIMIT_TIER_EXTERNAL]); +} +__name(parseLimitTiers, "parseLimitTiers"); +var NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 }); +var XML10_ALLOWED_C0 = /* @__PURE__ */ new Set([9, 10, 13]); +function parseNCRConfig(ncr) { + if (!ncr) { + return { xmlVersion: 1, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove }; + } + const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1; + const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow; + const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove; + const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove); + return { xmlVersion, onLevel, nullLevel: clampedNull }; +} +__name(parseNCRConfig, "parseNCRConfig"); +var EntityDecoder = class { + static { + __name(this, "EntityDecoder"); + } + /** + * @param {object} [options] + * @param {object|null} [options.namedEntities] — extra named entities merged into base map + * @param {object} [options.limit] — security limits + * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited + * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited + * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external'] + * Which entity tiers count against the security limits: + * - 'external' (default) — only input/runtime + persistent external entities + * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities + * - 'all' — every entity regardless of tier + * - string[] — explicit combination, e.g. ['external', 'base'] + * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null] + * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string) + * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output) + * @param {object} [options.ncr] — Numeric Character Reference controls + * @param {1.0|1.1} [options.ncr.xmlVersion=1.0] + * XML version governing which codepoint ranges are restricted: + * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited + * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is + * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow'] + * Base action for numeric references. Severity order: allow < leave < remove < throw. + * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove), + * the effective action is max(onNCR, rangeMinimum). + * @param {'remove'|'throw'} [options.ncr.nullNCR='remove'] + * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onExternalEntity=null] + * Hook called when an external entity is registered via `setExternalEntities()` or + * `addExternalEntity()`. Return `ENTITY_ACTION.ALLOW` to accept the entity, + * `ENTITY_ACTION.BLOCK` to silently skip it, or `ENTITY_ACTION.THROW` to abort with an error. + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} [options.onInputEntity=null] + * Hook called when an input entity is registered via `addInputEntities()`. Return + * `ENTITY_ACTION.ALLOW` to accept, `ENTITY_ACTION.BLOCK` to silently skip, or + * `ENTITY_ACTION.THROW` to abort with an error. + */ + constructor(options = {}) { + this._limit = options.limit || {}; + this._maxTotalExpansions = this._limit.maxTotalExpansions || 0; + this._maxExpandedLength = this._limit.maxExpandedLength || 0; + this._postCheck = typeof options.postCheck === "function" ? options.postCheck : (r) => r; + this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL); + this._numericAllowed = options.numericAllowed ?? true; + this._baseMap = mergeEntityMaps(XML, options.namedEntities || null); + this._externalMap = /* @__PURE__ */ Object.create(null); + this._inputMap = /* @__PURE__ */ Object.create(null); + this._totalExpansions = 0; + this._expandedLength = 0; + this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []); + this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []); + const ncrCfg = parseNCRConfig(options.ncr); + this._ncrXmlVersion = ncrCfg.xmlVersion; + this._ncrOnLevel = ncrCfg.onLevel; + this._ncrNullLevel = ncrCfg.nullLevel; + this._onExternalEntity = typeof options.onExternalEntity === "function" ? options.onExternalEntity : null; + this._onInputEntity = typeof options.onInputEntity === "function" ? options.onInputEntity : null; + } + // ------------------------------------------------------------------------- + // Private: registration hook dispatch + // ------------------------------------------------------------------------- + /** + * Invoke a registration hook for a single entity name/value pair. + * Returns true when the entity should be accepted, false when it should be + * silently skipped (BLOCK), and throws when the hook returns THROW. + * + * @param {((name: string, value: string) => 'allow'|'block'|'throw')|null} hook + * @param {string} name + * @param {string} value + * @param {string} context — used in error messages ('external' | 'input') + * @returns {boolean} true = accept, false = skip + */ + _applyRegistrationHook(hook, name3, value, context3) { + if (!hook) return true; + const action5 = hook(name3, value); + if (action5 === ENTITY_ACTION.BLOCK) return false; + if (action5 === ENTITY_ACTION.THROW) { + throw new Error( + `[EntityDecoder] Registration of ${context3} entity "&${name3};" was rejected by hook` + ); + } + return true; + } + // ------------------------------------------------------------------------- + // Persistent external entity registration + // ------------------------------------------------------------------------- + /** + * Replace the full set of persistent external entities. + * All keys are validated — throws on invalid characters. + * If `onExternalEntity` is set, it is called once per entry; entries that + * return `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` + * aborts the whole call. + * @param {Record} map + */ + setExternalEntities(map) { + if (map) { + for (const key of Object.keys(map)) { + validateEntityName(key); + } + } + if (!this._onExternalEntity) { + this._externalMap = mergeEntityMaps(map); + return; + } + const flat = mergeEntityMaps(map); + const filtered = /* @__PURE__ */ Object.create(null); + for (const [name3, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onExternalEntity, name3, value, "external")) { + filtered[name3] = value; + } + } + this._externalMap = filtered; + } + /** + * Add a single persistent external entity. + * If `onExternalEntity` is set it is called before the entity is stored; + * `ENTITY_ACTION.BLOCK` silently skips storage, `ENTITY_ACTION.THROW` raises. + * @param {string} key + * @param {string} value + */ + addExternalEntity(key, value) { + validateEntityName(key); + if (typeof value === "string" && value.indexOf("&") === -1) { + if (this._applyRegistrationHook(this._onExternalEntity, key, value, "external")) { + this._externalMap[key] = value; + } + } + } + // ------------------------------------------------------------------------- + // Input / runtime entity registration (per document) + // ------------------------------------------------------------------------- + /** + * Inject DOCTYPE entities for the current document. + * Also resets per-document expansion counters. + * If `onInputEntity` is set it is called once per entry; entries returning + * `ENTITY_ACTION.BLOCK` are silently omitted, `ENTITY_ACTION.THROW` aborts. + * @param {Record} map + */ + addInputEntities(map) { + this._totalExpansions = 0; + this._expandedLength = 0; + if (!this._onInputEntity) { + this._inputMap = mergeEntityMaps(map); + return; + } + const flat = mergeEntityMaps(map); + const filtered = /* @__PURE__ */ Object.create(null); + for (const [name3, value] of Object.entries(flat)) { + if (this._applyRegistrationHook(this._onInputEntity, name3, value, "input")) { + filtered[name3] = value; + } + } + this._inputMap = filtered; + } + // ------------------------------------------------------------------------- + // Per-document reset + // ------------------------------------------------------------------------- + /** + * Wipe input/runtime entities and reset counters. + * Call this before processing each new document. + * @returns {this} + */ + reset() { + this._inputMap = /* @__PURE__ */ Object.create(null); + this._totalExpansions = 0; + this._expandedLength = 0; + return this; + } + // ------------------------------------------------------------------------- + // XML version (can be set after construction, e.g. once parser reads ) + // ------------------------------------------------------------------------- + /** + * Update the XML version used for NCR classification. + * Call this as soon as the document's `` declaration is parsed. + * @param {1.0|1.1|number} version + */ + setXmlVersion(version4) { + this._ncrXmlVersion = version4 === 1.1 ? 1.1 : 1; + } + // ------------------------------------------------------------------------- + // Primary API + // ------------------------------------------------------------------------- + /** + * Replace all entity references in `str` in a single pass. + * + * @param {string} str + * @returns {string} + */ + decode(str) { + if (typeof str !== "string" || str.length === 0) return str; + if (str.indexOf("&") === -1) return str; + const original = str; + const chunks = []; + const len = str.length; + let last = 0; + let i = 0; + const limitExpansions = this._maxTotalExpansions > 0; + const limitLength = this._maxExpandedLength > 0; + const checkLimits = limitExpansions || limitLength; + while (i < len) { + if (str.charCodeAt(i) !== 38) { + i++; + continue; + } + let j = i + 1; + while (j < len && str.charCodeAt(j) !== 59 && j - i <= 32) j++; + if (j >= len || str.charCodeAt(j) !== 59) { + i++; + continue; + } + const token = str.slice(i + 1, j); + if (token.length === 0) { + i++; + continue; + } + let replacement; + let tier2; + if (this._removeSet.has(token)) { + replacement = ""; + if (tier2 === void 0) { + tier2 = LIMIT_TIER_EXTERNAL; + } + } else if (this._leaveSet.has(token)) { + i++; + continue; + } else if (token.charCodeAt(0) === 35) { + const ncrResult = this._resolveNCR(token); + if (ncrResult === void 0) { + i++; + continue; + } + replacement = ncrResult; + tier2 = LIMIT_TIER_BASE; + } else { + const resolved = this._resolveName(token); + replacement = resolved?.value; + tier2 = resolved?.tier; + } + if (replacement === void 0) { + i++; + continue; + } + if (i > last) chunks.push(str.slice(last, i)); + chunks.push(replacement); + last = j + 1; + i = last; + if (checkLimits && this._tierCounts(tier2)) { + if (limitExpansions) { + this._totalExpansions++; + if (this._totalExpansions > this._maxTotalExpansions) { + throw new Error( + `[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}` + ); + } + } + if (limitLength) { + const delta = replacement.length - (token.length + 2); + if (delta > 0) { + this._expandedLength += delta; + if (this._expandedLength > this._maxExpandedLength) { + throw new Error( + `[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}` + ); + } + } + } + } + } + if (last < len) chunks.push(str.slice(last)); + const result = chunks.length === 0 ? str : chunks.join(""); + return this._postCheck(result, original); + } + // ------------------------------------------------------------------------- + // Private: limit tier check + // ------------------------------------------------------------------------- + /** + * Returns true if a resolved entity of the given tier should count + * against the expansion/length limits. + * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE + * @returns {boolean} + */ + _tierCounts(tier2) { + if (this._limitTiers.has(LIMIT_TIER_ALL)) return true; + return this._limitTiers.has(tier2); + } + // ------------------------------------------------------------------------- + // Private: entity resolution + // ------------------------------------------------------------------------- + /** + * Resolve a named entity token (without & and ;). + * Priority: inputMap > externalMap > baseMap + * Returns the resolved value tagged with its limit tier. + * + * @param {string} name + * @returns {{ value: string, tier: string }|undefined} + */ + _resolveName(name3) { + if (name3 in this._inputMap) return { value: this._inputMap[name3], tier: LIMIT_TIER_EXTERNAL }; + if (name3 in this._externalMap) return { value: this._externalMap[name3], tier: LIMIT_TIER_EXTERNAL }; + if (name3 in this._baseMap) return { value: this._baseMap[name3], tier: LIMIT_TIER_BASE }; + return void 0; + } + /** + * Classify a codepoint and return the minimum action level that must be applied. + * Returns -1 when no minimum is imposed (normal allow path). + * + * Ranges checked (in priority order): + * 1. U+0000 — null, governed by nullNCR (always ≥ remove) + * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove) + * 3. U+0001–U+001F \ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove) + * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs) + * + * @param {number} cp — codepoint + * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction + */ + _classifyNCR(cp) { + if (cp === 0) return this._ncrNullLevel; + if (cp >= 55296 && cp <= 57343) return NCR_LEVEL.remove; + if (this._ncrXmlVersion === 1) { + if (cp >= 1 && cp <= 31 && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove; + } + return -1; + } + /** + * Execute a resolved NCR action. + * + * @param {number} action — NCR_LEVEL value + * @param {string} token — raw token (e.g. '#38') for error messages + * @param {number} cp — codepoint, used only for error messages + * @returns {string|undefined} + * - decoded character string → 'allow' + * - '' → 'remove' + * - undefined → 'leave' (caller must skip past '&' only) + * - throws Error → 'throw' + */ + _applyNCRAction(action5, token, cp) { + switch (action5) { + case NCR_LEVEL.allow: + return String.fromCodePoint(cp); + case NCR_LEVEL.remove: + return ""; + case NCR_LEVEL.leave: + return void 0; + // signal: keep literal + case NCR_LEVEL.throw: + throw new Error( + `[EntityDecoder] Prohibited numeric character reference &${token}; (U+${cp.toString(16).toUpperCase().padStart(4, "0")})` + ); + default: + return String.fromCodePoint(cp); + } + } + /** + * Full NCR resolution pipeline for a numeric token. + * + * Steps: + * 1. Parse the codepoint (decimal or hex). + * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF). + * 3. If numericAllowed is false and no minimum restriction applies → leave as-is. + * 4. Classify the codepoint to find the minimum required action level. + * 5. Resolve effective action = max(onNCR, minimum). + * 6. Apply and return. + * + * @param {string} token — e.g. '#38', '#x26', '#X26' + * @returns {string|undefined} + * - string (incl. '') — replacement ('' = remove) + * - undefined — leave original &token; as-is + */ + _resolveNCR(token) { + const second = token.charCodeAt(1); + let cp; + if (second === 120 || second === 88) { + cp = parseInt(token.slice(2), 16); + } else { + cp = parseInt(token.slice(1), 10); + } + if (Number.isNaN(cp) || cp < 0 || cp > 1114111) return void 0; + const minimum = this._classifyNCR(cp); + if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return void 0; + const effective = minimum === -1 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, minimum); + return this._applyNCRAction(effective, token, cp); + } +}; + +// ../../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js +var defaultOnDangerousProperty = /* @__PURE__ */ __name((name3) => { + if (DANGEROUS_PROPERTY_NAMES.includes(name3)) { + return "__" + name3; + } + return name3; +}, "defaultOnDangerousProperty"); +var defaultOptions2 = { + preserveOrder: false, + attributeNamePrefix: "@_", + attributesGroupName: false, + textNodeName: "#text", + ignoreAttributes: true, + removeNSPrefix: false, + // remove NS from tag name or attribute name if true + allowBooleanAttributes: false, + //a tag can have attributes without any value + //ignoreRootElement : false, + parseTagValue: true, + parseAttributeValue: false, + trimValues: true, + //Trim string values of tag and attributes + cdataPropName: false, + numberParseOptions: { + hex: true, + leadingZeros: true, + eNotation: true, + unicode: false + }, + tagValueProcessor: /* @__PURE__ */ __name(function(tagName, val) { + return val; + }, "tagValueProcessor"), + attributeValueProcessor: /* @__PURE__ */ __name(function(attrName, val) { + return val; + }, "attributeValueProcessor"), + stopNodes: [], + //nested tags will not be parsed even for errors + alwaysCreateTextNode: false, + isArray: /* @__PURE__ */ __name(() => false, "isArray"), + commentPropName: false, + unpairedTags: [], + processEntities: true, + htmlEntities: false, + entityDecoder: null, + ignoreDeclaration: false, + ignorePiTags: false, + transformTagName: false, + transformAttributeName: false, + updateTag: /* @__PURE__ */ __name(function(tagName, jPath, attrs) { + return tagName; + }, "updateTag"), + // skipEmptyListItem: false + captureMetaData: false, + maxNestedTags: 100, + strictReservedNames: true, + jPath: true, + // if true, pass jPath string to callbacks; if false, pass matcher instance + onDangerousProperty: defaultOnDangerousProperty +}; +function validatePropertyName(propertyName, optionName) { + if (typeof propertyName !== "string") { + return; + } + const normalized = propertyName.toLowerCase(); + if (DANGEROUS_PROPERTY_NAMES.some((dangerous) => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } + if (criticalProperties.some((dangerous) => normalized === dangerous.toLowerCase())) { + throw new Error( + `[SECURITY] Invalid ${optionName}: "${propertyName}" is a reserved JavaScript keyword that could cause prototype pollution` + ); + } +} +__name(validatePropertyName, "validatePropertyName"); +function normalizeProcessEntities(value, htmlEntities) { + if (typeof value === "boolean") { + return { + enabled: value, + // true or false + maxEntitySize: 1e4, + maxExpansionDepth: 1e4, + maxTotalExpansions: Infinity, + maxExpandedLength: 1e5, + maxEntityCount: 1e3, + allowedTags: null, + tagFilter: null, + appliesTo: "all" + }; + } + if (typeof value === "object" && value !== null) { + return { + enabled: value.enabled !== false, + maxEntitySize: Math.max(1, value.maxEntitySize ?? 1e4), + maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 1e4), + maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity), + maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 1e5), + maxEntityCount: Math.max(1, value.maxEntityCount ?? 1e3), + allowedTags: value.allowedTags ?? null, + tagFilter: value.tagFilter ?? null, + appliesTo: value.appliesTo ?? "all" + }; + } + return normalizeProcessEntities(true); +} +__name(normalizeProcessEntities, "normalizeProcessEntities"); +var buildOptions = /* @__PURE__ */ __name(function(options) { + const built = Object.assign({}, defaultOptions2, options); + const propertyNameOptions = [ + { value: built.attributeNamePrefix, name: "attributeNamePrefix" }, + { value: built.attributesGroupName, name: "attributesGroupName" }, + { value: built.textNodeName, name: "textNodeName" }, + { value: built.cdataPropName, name: "cdataPropName" }, + { value: built.commentPropName, name: "commentPropName" } + ]; + for (const { value, name: name3 } of propertyNameOptions) { + if (value) { + validatePropertyName(value, name3); + } + } + if (built.onDangerousProperty === null) { + built.onDangerousProperty = defaultOnDangerousProperty; + } + built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities); + built.unpairedTagsSet = new Set(built.unpairedTags); + if (built.stopNodes && Array.isArray(built.stopNodes)) { + built.stopNodes = built.stopNodes.map((node) => { + if (typeof node === "string" && node.startsWith("*.")) { + return ".." + node.substring(2); + } + return node; + }); + } + return built; +}, "buildOptions"); + +// ../../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js +var METADATA_SYMBOL; +if (typeof Symbol !== "function") { + METADATA_SYMBOL = "@@xmlMetadata"; +} else { + METADATA_SYMBOL = /* @__PURE__ */ Symbol("XML Node Metadata"); +} +var XmlNode = class { + static { + __name(this, "XmlNode"); + } + constructor(tagname) { + this.tagname = tagname; + this.child = []; + this[":@"] = /* @__PURE__ */ Object.create(null); + } + add(key, val) { + if (key === "__proto__") key = "#__proto__"; + this.child.push({ [key]: val }); + } + addChild(node, startIndex) { + if (node.tagname === "__proto__") node.tagname = "#__proto__"; + if (node[":@"] && Object.keys(node[":@"]).length > 0) { + this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); + } else { + this.child.push({ [node.tagname]: node.child }); + } + if (startIndex !== void 0) { + this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex }; + } + } + /** symbol used for metadata */ + static getMetaDataSymbol() { + return METADATA_SYMBOL; + } +}; + +// ../../node_modules/xml-naming/src/index.js +var nameStartChar10 = ":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; +var nameChar10 = nameStartChar10 + "\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040"; +var nameStartChar11 = ":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}"; +var nameChar11 = nameStartChar11 + "\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040"; +var buildRegexes = /* @__PURE__ */ __name((startChar, char, flags = "") => { + const ncStart = startChar.replace(":", ""); + const ncChar = char.replace(":", ""); + const ncNamePat = `[${ncStart}][${ncChar}]*`; + return { + name: new RegExp(`^[${startChar}][${char}]*$`, flags), + ncName: new RegExp(`^${ncNamePat}$`, flags), + qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags), + nmToken: new RegExp(`^[${char}]+$`, flags), + nmTokens: new RegExp(`^[${char}]+(?:\\s+[${char}]+)*$`, flags) + }; +}, "buildRegexes"); +var regexes10 = buildRegexes(nameStartChar10, nameChar10); +var regexes11 = buildRegexes(nameStartChar11, nameChar11, "u"); +var nameStartCharAscii = ":A-Za-z_"; +var nameCharAscii = nameStartCharAscii + "\\-\\.\\d"; +var regexesAscii = buildRegexes(nameStartCharAscii, nameCharAscii); +var getRegexes = /* @__PURE__ */ __name((xmlVersion = "1.0", asciiOnly = false) => { + if (asciiOnly) return regexesAscii; + return xmlVersion === "1.1" ? regexes11 : regexes10; +}, "getRegexes"); +var qName = /* @__PURE__ */ __name((str, { xmlVersion = "1.0", asciiOnly = false } = {}) => getRegexes(xmlVersion, asciiOnly).qName.test(str), "qName"); +var PRODUCTIONS = ["name", "ncName", "qName", "nmToken", "nmTokens"]; +var createValidator = /* @__PURE__ */ __name((production, { xmlVersion = "1.0", asciiOnly = false, maxCacheSize = 2048 } = {}) => { + if (!PRODUCTIONS.includes(production)) { + throw new TypeError( + `Unknown production "${production}". Must be one of: ${PRODUCTIONS.join(", ")}` + ); + } + const regex = getRegexes(xmlVersion, asciiOnly)[production]; + let cache = /* @__PURE__ */ new Map(); + const validator = /* @__PURE__ */ __name((str) => { + const cached = cache.get(str); + if (cached !== void 0) return cached; + const result = regex.test(str); + if (cache.size < maxCacheSize) cache.set(str, result); + return result; + }, "validator"); + validator.reset = () => { + cache = /* @__PURE__ */ new Map(); + }; + return validator; +}, "createValidator"); + +// ../../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js +var DocTypeReader = class { + static { + __name(this, "DocTypeReader"); + } + constructor(options, xmlVersion) { + this.suppressValidationErr = !options; + this.options = options; + this.xmlVersion = xmlVersion || 1; + } + setXmlVersion(xmlVersion = 1) { + this.xmlVersion = xmlVersion; + } + readDocType(xmlData, i) { + const entities = /* @__PURE__ */ Object.create(null); + let entityCount = 0; + if (xmlData[i + 3] === "O" && xmlData[i + 4] === "C" && xmlData[i + 5] === "T" && xmlData[i + 6] === "Y" && xmlData[i + 7] === "P" && xmlData[i + 8] === "E") { + i = i + 9; + let angleBracketsCount = 1; + let hasBody = false, comment = false; + let exp = ""; + for (; i < xmlData.length; i++) { + if (xmlData[i] === "<" && !comment) { + if (hasBody && hasSeq(xmlData, "!ENTITY", i)) { + i += 7; + let entityName, val; + [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr); + if (val.indexOf("&") === -1) { + if (this.options.enabled !== false && this.options.maxEntityCount != null && entityCount >= this.options.maxEntityCount) { + throw new Error( + `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})` + ); + } + entities[entityName] = val; + entityCount++; + } + } else if (hasBody && hasSeq(xmlData, "!ELEMENT", i)) { + i += 8; + const { index } = this.readElementExp(xmlData, i + 1); + i = index; + } else if (hasBody && hasSeq(xmlData, "!ATTLIST", i)) { + i += 8; + } else if (hasBody && hasSeq(xmlData, "!NOTATION", i)) { + i += 9; + const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr); + i = index; + } else if (hasSeq(xmlData, "!--", i)) comment = true; + else throw new Error(`Invalid DOCTYPE`); + angleBracketsCount++; + exp = ""; + } else if (xmlData[i] === ">") { + if (comment) { + if (xmlData[i - 1] === "-" && xmlData[i - 2] === "-") { + comment = false; + angleBracketsCount--; + } + } else { + angleBracketsCount--; + } + if (angleBracketsCount === 0) { + break; + } + } else if (xmlData[i] === "[") { + hasBody = true; + } else { + exp += xmlData[i]; + } + } + if (angleBracketsCount !== 0) { + throw new Error(`Unclosed DOCTYPE`); + } + } else { + throw new Error(`Invalid Tag instead of DOCTYPE`); + } + return { entities, i }; + } + readEntityExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i]) && xmlData[i] !== '"' && xmlData[i] !== "'") { + i++; + } + let entityName = xmlData.substring(startIndex, i); + validateEntityName2(entityName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + if (!this.suppressValidationErr) { + if (xmlData.substring(i, i + 6).toUpperCase() === "SYSTEM") { + throw new Error("External entities are not supported"); + } else if (xmlData[i] === "%") { + throw new Error("Parameter entities are not supported"); + } + } + let entityValue = ""; + [i, entityValue] = this.readIdentifierVal(xmlData, i, "entity"); + if (this.options.enabled !== false && this.options.maxEntitySize != null && entityValue.length > this.options.maxEntitySize) { + throw new Error( + `Entity "${entityName}" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})` + ); + } + i--; + return [entityName, entityValue, i]; + } + readNotationExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let notationName = xmlData.substring(startIndex, i); + !this.suppressValidationErr && validateEntityName2(notationName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + const identifierType = xmlData.substring(i, i + 6).toUpperCase(); + if (!this.suppressValidationErr && identifierType !== "SYSTEM" && identifierType !== "PUBLIC") { + throw new Error(`Expected SYSTEM or PUBLIC, found "${identifierType}"`); + } + i += identifierType.length; + i = skipWhitespace(xmlData, i); + let publicIdentifier = null; + let systemIdentifier = null; + if (identifierType === "PUBLIC") { + [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, "publicIdentifier"); + i = skipWhitespace(xmlData, i); + if (xmlData[i] === '"' || xmlData[i] === "'") { + [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier"); + } + } else if (identifierType === "SYSTEM") { + [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, "systemIdentifier"); + if (!this.suppressValidationErr && !systemIdentifier) { + throw new Error("Missing mandatory system identifier for SYSTEM notation"); + } + } + return { notationName, publicIdentifier, systemIdentifier, index: --i }; + } + readIdentifierVal(xmlData, i, type) { + let identifierVal = ""; + const startChar = xmlData[i]; + if (startChar !== '"' && startChar !== "'") { + throw new Error(`Expected quoted string, found "${startChar}"`); + } + i++; + const startIndex = i; + while (i < xmlData.length && xmlData[i] !== startChar) { + i++; + } + identifierVal = xmlData.substring(startIndex, i); + if (xmlData[i] !== startChar) { + throw new Error(`Unterminated ${type} value`); + } + i++; + return [i, identifierVal]; + } + readElementExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + const startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let elementName = xmlData.substring(startIndex, i); + if (!this.suppressValidationErr && !qName(elementName, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid element name: "${elementName}"`); + } + i = skipWhitespace(xmlData, i); + let contentModel = ""; + if (xmlData[i] === "E" && hasSeq(xmlData, "MPTY", i)) i += 4; + else if (xmlData[i] === "A" && hasSeq(xmlData, "NY", i)) i += 2; + else if (xmlData[i] === "(") { + i++; + const startIndex2 = i; + while (i < xmlData.length && xmlData[i] !== ")") { + i++; + } + contentModel = xmlData.substring(startIndex2, i); + if (xmlData[i] !== ")") { + throw new Error("Unterminated content model"); + } + } else if (!this.suppressValidationErr) { + throw new Error(`Invalid Element Expression, found "${xmlData[i]}"`); + } + return { + elementName, + contentModel: contentModel.trim(), + index: i + }; + } + readAttlistExp(xmlData, i) { + i = skipWhitespace(xmlData, i); + let startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let elementName = xmlData.substring(startIndex, i); + validateEntityName2(elementName, { xmlVersion: this.xmlVersion }); + i = skipWhitespace(xmlData, i); + startIndex = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + let attributeName = xmlData.substring(startIndex, i); + if (!validateEntityName2(attributeName, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid attribute name: "${attributeName}"`); + } + i = skipWhitespace(xmlData, i); + let attributeType = ""; + if (xmlData.substring(i, i + 8).toUpperCase() === "NOTATION") { + attributeType = "NOTATION"; + i += 8; + i = skipWhitespace(xmlData, i); + if (xmlData[i] !== "(") { + throw new Error(`Expected '(', found "${xmlData[i]}"`); + } + i++; + let allowedNotations = []; + while (i < xmlData.length && xmlData[i] !== ")") { + const startIndex2 = i; + while (i < xmlData.length && xmlData[i] !== "|" && xmlData[i] !== ")") { + i++; + } + let notation = xmlData.substring(startIndex2, i); + notation = notation.trim(); + if (!validateEntityName2(notation, { xmlVersion: this.xmlVersion })) { + throw new Error(`Invalid notation name: "${notation}"`); + } + allowedNotations.push(notation); + if (xmlData[i] === "|") { + i++; + i = skipWhitespace(xmlData, i); + } + } + if (xmlData[i] !== ")") { + throw new Error("Unterminated list of notations"); + } + i++; + attributeType += " (" + allowedNotations.join("|") + ")"; + } else { + const startIndex2 = i; + while (i < xmlData.length && !/\s/.test(xmlData[i])) { + i++; + } + attributeType += xmlData.substring(startIndex2, i); + const validTypes = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; + if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) { + throw new Error(`Invalid attribute type: "${attributeType}"`); + } + } + i = skipWhitespace(xmlData, i); + let defaultValue = ""; + if (xmlData.substring(i, i + 8).toUpperCase() === "#REQUIRED") { + defaultValue = "#REQUIRED"; + i += 8; + } else if (xmlData.substring(i, i + 7).toUpperCase() === "#IMPLIED") { + defaultValue = "#IMPLIED"; + i += 7; + } else { + [i, defaultValue] = this.readIdentifierVal(xmlData, i, "ATTLIST"); + } + return { + elementName, + attributeName, + attributeType, + defaultValue, + index: i + }; + } +}; +var skipWhitespace = /* @__PURE__ */ __name((data, index) => { + while (index < data.length && /\s/.test(data[index])) { + index++; + } + return index; +}, "skipWhitespace"); +function hasSeq(data, seq, i) { + for (let j = 0; j < seq.length; j++) { + if (seq[j] !== data[i + j + 1]) return false; + } + return true; +} +__name(hasSeq, "hasSeq"); +function validateEntityName2(name3, xmlVersion) { + if (qName(name3, { xmlVersion })) + return name3; + else + throw new Error(`Invalid entity name ${name3}`); +} +__name(validateEntityName2, "validateEntityName"); + +// ../../node_modules/anynum/digitTable.js +var SCRIPT_ZEROS = [ + // Basic Latin (ASCII) — included for completeness / pass-through + 48, + // 0-9 + // Arabic scripts + 1632, + // Arabic-Indic ٠١٢٣٤٥٦٧٨٩ + 1776, + // Extended Arabic-Indic (Urdu/Persian/Sindhi) ۰۱۲۳ + // Indic scripts + 2406, + // Devanagari ०१२३४५६७८९ + 2534, + // Bengali ০১২৩৪৫৬৭৮৯ + 2662, + // Gurmukhi ੦੧੨੩੪੫੬੭੮੯ + 2790, + // Gujarati ૦૧૨૩૪૫૬૭૮૯ + 2918, + // Odia ୦୧୨୩୪୫୬୭୮୯ + 3046, + // Tamil ௦௧௨௩௪௫௬௭௮௯ + 3174, + // Telugu ౦౧౨౩౪౫౬౭౮౯ + 3302, + // Kannada ೦೧೨೩೪೫೬೭೮೯ + 3430, + // Malayalam ൦൧൨൩൪൫൬൭൮൯ + 3558, + // Sinhala Archaic ෦෧෨෩෪෫෬෭෮෯ + // Southeast Asian scripts + 3664, + // Thai ๐๑๒๓๔๕๖๗๘๙ + 3792, + // Lao ໐໑໒໓໔໕໖໗໘໙ + 3872, + // Tibetan ༠༡༢༣༤༥༦༧༨༩ + 4160, + // Myanmar ၀၁၂၃၄၅၆၇၈၉ + 4240, + // Myanmar Shan ႐႑႒႓႔႕႖႗႘႙ + 6112, + // Khmer ០១២៣៤៥៦៧៨៩ + 6160, + // Mongolian ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ + 6470, + // Limbu ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ + 6608, + // New Tai Lue ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ + 6784, + // Tai Tham Hora ᪀᪁᪂᪃᪄᪅᪆᪇᪈᪉ + 6800, + // Tai Tham Tham ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ + 6992, + // Balinese ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ + 7088, + // Sundanese ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ + 7232, + // Lepcha ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ + 7248, + // Ol Chiki ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ + // Fullwidth (CJK context) + 65296, + // Fullwidth 0123456789 + // Mathematical digit variants (Unicode math block) + 120782, + // Mathematical Bold + 120792, + // Mathematical Double-Struck + 120802, + // Mathematical Sans-Serif + 120812, + // Mathematical Sans-Serif Bold + 120822, + // Mathematical Monospace + // Other scripts + 66720, + // Osmanya 𐒠𐒡𐒢𐒣𐒤𐒥𐒦𐒧𐒨𐒩 + 68912, + // Hanifi Rohingya 𐴰𐴱𐴲𐴳𐴴𐴵𐴶𐴷𐴸𐴹 + 69734, + // Brahmi 𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯 + 69872, + // Sora Sompeng 𑃰𑃱𑃲𑃳𑃴𑃵𑃶𑃷𑃸𑃹 + 69942, + // Chakma 𑄶𑄷𑄸𑄹𑄺𑄻𑄼𑄽𑄾𑄿 + 70096, + // Sharada 𑇐𑇑𑇒𑇓𑇔𑇕𑇖𑇗𑇘𑇙 + 70384, + // Khudawadi 𑋰𑋱𑋲𑋳𑋴𑋵𑋶𑋷𑋸𑋹 + 70736, + // Newa 𑑐𑑑𑑒𑑓𑑔𑑕𑑖𑑗𑑘𑑙 + 70864, + // Tirhuta 𑓐𑓑𑓒𑓓𑓔𑓕𑓖𑓗𑓘𑓙 + 71248, + // Modi 𑙐𑙑𑙒𑙓𑙔𑙕𑙖𑙗𑙘𑙙 + 71360, + // Takri 𑛀𑛁𑛂𑛃𑛄𑛅𑛆𑛇𑛈𑛉 + 71472, + // Ahom 𑜰𑜱𑜲𑜳𑜴𑜵𑜶𑜷𑜸𑜹 + 71904, + // Warang Citi 𑣠𑣡𑣢𑣣𑣤𑣥𑣦𑣧𑣨𑣩 + 72016, + // Dives Akuru 𑥐𑥑𑥒𑥓𑥔𑥕𑥖𑥗𑥘𑥙 + 72688, + // Khitan Small Script 𑯰𑯱𑯲𑯳𑯴𑯵𑯶𑯷𑯸𑯹 + 72784, + // Bhaiksuki 𑱐𑱑𑱒𑱓𑱔𑱕𑱖𑱗𑱘𑱙 + 73040, + // Masaram Gondi 𑵐𑵑𑵒𑵓𑵔𑵕𑵖𑵗𑵘𑵙 + 73120, + // Gunjala Gondi 𑶠𑶡𑶢𑶣𑶤𑶥𑶦𑶧𑶨𑶩 + 73552, + // Kawi 𑽐𑽑𑽒𑽓𑽔𑽕𑽖𑽗𑽘𑽙 + 92768, + // Mro 𖩠𖩡𖩢𖩣𖩤𖩥𖩦𖩧𖩨𖩩 + 92864, + // Tangsa 𖫀𖫁𖫂𖫃𖫄𖫅𖫆𖫇𖫈𖫉 + 93008, + // Pahawh Hmong 𖭐𖭑𖭒𖭓𖭔𖭕𖭖𖭗𖭘𖭙 + 123200, + // Nyiakeng Puachue Hmong 𞅀𞅁𞅂𞅃𞅄𞅅𞅆𞅇𞅈𞅉 + 123632, + // Wancho 𞋰𞋱𞋲𞋳𞋴𞋵𞋶𞋷𞋸𞋹 + 124144, + // Nag Mundari 𞓰𞓱𞓲𞓳𞓴𞓵𞓶𞓷𞓸𞓹 + 125264, + // Adlam 𞥐𞥑𞥒𞥓𞥔𞥕𞥖𞥗𞥘𞥙 + 130032 + // Segmented digit symbols 🯰🯱🯲🯳🯴🯵🯶🯷🯸🯹 +]; +var NOT_DIGIT = 255; +var HIGH_MAP = /* @__PURE__ */ new Map(); +var LOW_MAX = 65535; +var LOW_MIN = 1632; +var TABLE_OFFSET = LOW_MIN; +var TABLE_SIZE = LOW_MAX - LOW_MIN + 1; +var TABLE = new Uint8Array(TABLE_SIZE).fill(NOT_DIGIT); +for (const zero of SCRIPT_ZEROS) { + for (let d = 0; d < 10; d++) { + const cp = zero + d; + if (cp <= LOW_MAX) { + TABLE[cp - TABLE_OFFSET] = d; + } else { + HIGH_MAP.set(cp, d); + } + } +} + +// ../../node_modules/anynum/anynum.js +var CHAR_0 = 48; +var CHAR_9 = 57; +var CHAR_MINUS = 45; +var MINUS_SET = /* @__PURE__ */ new Set([8722, 65293, 65123]); +function anynum(str) { + if (typeof str !== "string") return str; + const len = str.length; + if (len === 0) return str; + let firstHit = -1; + for (let i = 0; i < len; i++) { + const cc = str.charCodeAt(i); + if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) continue; + if (cc < TABLE_OFFSET) { + if (MINUS_SET.has(cc)) { + firstHit = i; + break; + } + continue; + } + if (cc >= 55296 && cc <= 56319) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + const cp = 65536 + (cc - 55296 << 10) + (low - 56320); + if (HIGH_MAP.has(cp)) { + firstHit = i; + break; + } + } + } + continue; + } + if (TABLE[cc - TABLE_OFFSET] !== NOT_DIGIT || MINUS_SET.has(cc)) { + firstHit = i; + break; + } + } + if (firstHit === -1) return str; + const chars = []; + if (firstHit > 0) chars.push(str.slice(0, firstHit)); + for (let i = firstHit; i < len; i++) { + const cc = str.charCodeAt(i); + if (cc >= CHAR_0 && cc <= CHAR_9 || cc === CHAR_MINUS) { + chars.push(str[i]); + continue; + } + if (cc < TABLE_OFFSET) { + chars.push(MINUS_SET.has(cc) ? "-" : str[i]); + continue; + } + if (cc >= 55296 && cc <= 56319) { + if (i + 1 < len) { + const low = str.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + const cp = 65536 + (cc - 55296 << 10) + (low - 56320); + const d2 = HIGH_MAP.get(cp); + if (d2 !== void 0) { + chars.push(String.fromCharCode(d2 + 48)); + i++; + continue; + } + } + } + chars.push(str[i]); + continue; + } + if (MINUS_SET.has(cc)) { + chars.push("-"); + continue; + } + const d = TABLE[cc - TABLE_OFFSET]; + chars.push(d !== NOT_DIGIT ? String.fromCharCode(d + 48) : str[i]); + } + return chars.join(""); +} +__name(anynum, "anynum"); +var anynum_default = anynum; + +// ../../node_modules/strnum/strnum.js +var hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; +var binRegex = /^0b[01]+$/; +var octRegex = /^0o[0-7]+$/; +var numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; +var consider = { + hex: true, + binary: false, + octal: false, + leadingZeros: true, + decimalPoint: ".", + eNotation: true, + //skipLike: /regex/, + infinity: "original", + // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) + unicode: false +}; +function toNumber(str, options = {}) { + options = Object.assign({}, consider, options); + if (!str || typeof str !== "string") return str; + let trimmedStr = str.trim(); + if (trimmedStr.length === 0) return str; + else if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str; + else if (trimmedStr === "0") return 0; + if (options.unicode) { + trimmedStr = anynum_default(trimmedStr); + if (trimmedStr === "0") return 0; + } + if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + } else if (options.binary && binRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 2); + } else if (options.octal && octRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 8); + } else if (!isFinite(trimmedStr)) { + return handleInfinity(str, Number(trimmedStr), options); + } else if (trimmedStr.includes("e") || trimmedStr.includes("E")) { + return resolveEnotation(str, trimmedStr, options); + } else { + const match = numRegex.exec(trimmedStr); + if (match) { + const sign = match[1] || ""; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); + const decimalAdjacentToLeadingZeros = sign ? ( + // 0., -00., 000. + str[leadingZeros.length + 1] === "." + ) : str[leadingZeros.length] === "."; + if (!options.leadingZeros && (leadingZeros.length > 1 || leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros)) { + return str; + } else { + const num = Number(trimmedStr); + const parsedStr = String(num); + if (num === 0) return num; + if (parsedStr.search(/[eE]/) !== -1) { + if (options.eNotation) return num; + else return str; + } else if (trimmedStr.indexOf(".") !== -1) { + if (parsedStr === "0") return num; + else if (parsedStr === numTrimmedByZeros) return num; + else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num; + else return str; + } + let n = leadingZeros ? numTrimmedByZeros : trimmedStr; + if (leadingZeros) { + return n === parsedStr || sign + n === parsedStr ? num : str; + } else { + return n === parsedStr || n === sign + parsedStr ? num : str; + } + } + } else { + return str; + } + } +} +__name(toNumber, "toNumber"); +var eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; +function resolveEnotation(str, trimmedStr, options) { + if (!options.eNotation) return str; + const notation = trimmedStr.match(eNotationRegx); + if (notation) { + let sign = notation[1] || ""; + const eChar = notation[3].indexOf("e") === -1 ? "E" : "e"; + const leadingZeros = notation[2]; + const eAdjacentToLeadingZeros = sign ? ( + // 0E. + str[leadingZeros.length + 1] === eChar + ) : str[leadingZeros.length] === eChar; + if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str; + else if (leadingZeros.length === 1 && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) { + return Number(trimmedStr); + } else if (leadingZeros.length > 0) { + if (options.leadingZeros && !eAdjacentToLeadingZeros) { + trimmedStr = (notation[1] || "") + notation[3]; + return Number(trimmedStr); + } else return str; + } else { + return Number(trimmedStr); + } + } else { + return str; + } +} +__name(resolveEnotation, "resolveEnotation"); +function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) { + numStr = numStr.replace(/0+$/, ""); + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1); + return numStr; + } + return numStr; +} +__name(trimZeros, "trimZeros"); +function parse_int(numStr, base) { + const str = numStr.trim(); + if (base === 2 || base === 8) numStr = str.substring(2); + if (parseInt) return parseInt(numStr, base); + else if (Number.parseInt) return Number.parseInt(numStr, base); + else if (window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); +} +__name(parse_int, "parse_int"); +function handleInfinity(str, num, options) { + const isPositive = num === Infinity; + switch (options.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return num; + // Return Infinity or -Infinity + case "string": + return isPositive ? "Infinity" : "-Infinity"; + case "original": + default: + return str; + } +} +__name(handleInfinity, "handleInfinity"); + +// ../../node_modules/fast-xml-parser/src/ignoreAttributes.js +function getIgnoreAttributesFn(ignoreAttributes) { + if (typeof ignoreAttributes === "function") { + return ignoreAttributes; + } + if (Array.isArray(ignoreAttributes)) { + return (attrName) => { + for (const pattern of ignoreAttributes) { + if (typeof pattern === "string" && attrName === pattern) { + return true; + } + if (pattern instanceof RegExp && pattern.test(attrName)) { + return true; + } + } + }; + } + return () => false; +} +__name(getIgnoreAttributesFn, "getIgnoreAttributesFn"); + +// ../../node_modules/path-expression-matcher/src/Expression.js +var Expression = class { + static { + __name(this, "Expression"); + } + /** + * Create a new Expression + * @param {string} pattern - Pattern string (e.g., "root.users.user", "..user[id]") + * @param {Object} options - Configuration options + * @param {string} options.separator - Path separator (default: '.') + */ + constructor(pattern, options = {}, data) { + this.pattern = pattern; + this.separator = options.separator || "."; + this.segments = this._parse(pattern); + this.data = data; + this._hasDeepWildcard = this.segments.some((seg) => seg.type === "deep-wildcard"); + this._hasAttributeCondition = this.segments.some((seg) => seg.attrName !== void 0); + this._hasPositionSelector = this.segments.some((seg) => seg.position !== void 0); + } + /** + * Parse pattern string into segments + * @private + * @param {string} pattern - Pattern to parse + * @returns {Array} Array of segment objects + */ + _parse(pattern) { + const segments = []; + let i = 0; + let currentPart = ""; + while (i < pattern.length) { + if (pattern[i] === this.separator) { + if (i + 1 < pattern.length && pattern[i + 1] === this.separator) { + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + currentPart = ""; + } + segments.push({ type: "deep-wildcard" }); + i += 2; + } else { + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + currentPart = ""; + i++; + } + } else { + currentPart += pattern[i]; + i++; + } + } + if (currentPart.trim()) { + segments.push(this._parseSegment(currentPart.trim())); + } + return segments; + } + /** + * Parse a single segment + * @private + * @param {string} part - Segment string (e.g., "user", "ns::user", "user[id]", "ns::user:first") + * @returns {Object} Segment object + */ + _parseSegment(part) { + const segment = { type: "tag" }; + let bracketContent = null; + let withoutBrackets = part; + const bracketMatch = part.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); + if (bracketMatch) { + withoutBrackets = bracketMatch[1] + bracketMatch[3]; + if (bracketMatch[2]) { + const content = bracketMatch[2].slice(1, -1); + if (content) { + bracketContent = content; + } + } + } + let namespace = void 0; + let tagAndPosition = withoutBrackets; + if (withoutBrackets.includes("::")) { + const nsIndex = withoutBrackets.indexOf("::"); + namespace = withoutBrackets.substring(0, nsIndex).trim(); + tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); + if (!namespace) { + throw new Error(`Invalid namespace in pattern: ${part}`); + } + } + let tag = void 0; + let positionMatch = null; + if (tagAndPosition.includes(":")) { + const colonIndex = tagAndPosition.lastIndexOf(":"); + const tagPart = tagAndPosition.substring(0, colonIndex).trim(); + const posPart = tagAndPosition.substring(colonIndex + 1).trim(); + const isPositionKeyword = ["first", "last", "odd", "even"].includes(posPart) || /^nth\(\d+\)$/.test(posPart); + if (isPositionKeyword) { + tag = tagPart; + positionMatch = posPart; + } else { + tag = tagAndPosition; + } + } else { + tag = tagAndPosition; + } + if (!tag) { + throw new Error(`Invalid segment pattern: ${part}`); + } + segment.tag = tag; + if (namespace) { + segment.namespace = namespace; + } + if (bracketContent) { + if (bracketContent.includes("=")) { + const eqIndex = bracketContent.indexOf("="); + segment.attrName = bracketContent.substring(0, eqIndex).trim(); + segment.attrValue = bracketContent.substring(eqIndex + 1).trim(); + } else { + segment.attrName = bracketContent.trim(); + } + } + if (positionMatch) { + const nthMatch = positionMatch.match(/^nth\((\d+)\)$/); + if (nthMatch) { + segment.position = "nth"; + segment.positionValue = parseInt(nthMatch[1], 10); + } else { + segment.position = positionMatch; + } + } + return segment; + } + /** + * Get the number of segments + * @returns {number} + */ + get length() { + return this.segments.length; + } + /** + * Check if expression contains deep wildcard + * @returns {boolean} + */ + hasDeepWildcard() { + return this._hasDeepWildcard; + } + /** + * Check if expression has attribute conditions + * @returns {boolean} + */ + hasAttributeCondition() { + return this._hasAttributeCondition; + } + /** + * Check if expression has position selectors + * @returns {boolean} + */ + hasPositionSelector() { + return this._hasPositionSelector; + } + /** + * Get string representation + * @returns {string} + */ + toString() { + return this.pattern; + } +}; + +// ../../node_modules/path-expression-matcher/src/ExpressionSet.js +var ExpressionSet = class { + static { + __name(this, "ExpressionSet"); + } + constructor() { + this._byDepthAndTag = /* @__PURE__ */ new Map(); + this._wildcardByDepth = /* @__PURE__ */ new Map(); + this._deepWildcards = []; + this._deepByTerminalTag = /* @__PURE__ */ new Map(); + this._patterns = /* @__PURE__ */ new Set(); + this._sealed = false; + } + /** + * Add an Expression to the set. + * Duplicate patterns (same pattern string) are silently ignored. + * + * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance + * @returns {this} for chaining + * @throws {TypeError} if called after seal() + * + * @example + * set.add(new Expression('root.users.user')); + * set.add(new Expression('..script')); + */ + add(expression) { + if (this._sealed) { + throw new TypeError( + "ExpressionSet is sealed. Create a new ExpressionSet to add more expressions." + ); + } + if (this._patterns.has(expression.pattern)) return this; + this._patterns.add(expression.pattern); + if (expression.hasDeepWildcard()) { + const lastSeg2 = expression.segments[expression.segments.length - 1]; + if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") { + const tag2 = lastSeg2.tag; + if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []); + this._deepByTerminalTag.get(tag2).push(expression); + } else { + this._deepWildcards.push(expression); + } + return this; + } + const depth = expression.length; + const lastSeg = expression.segments[expression.segments.length - 1]; + const tag = lastSeg?.tag; + if (!tag || tag === "*") { + if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []); + this._wildcardByDepth.get(depth).push(expression); + } else { + const key = `${depth}:${tag}`; + if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []); + this._byDepthAndTag.get(key).push(expression); + } + return this; + } + /** + * Add multiple expressions at once. + * + * @param {import('./Expression.js').default[]} expressions - Array of Expression instances + * @returns {this} for chaining + * + * @example + * set.addAll([ + * new Expression('root.users.user'), + * new Expression('root.config.setting'), + * ]); + */ + addAll(expressions) { + for (const expr of expressions) this.add(expr); + return this; + } + /** + * Check whether a pattern string is already present in the set. + * + * @param {import('./Expression.js').default} expression + * @returns {boolean} + */ + has(expression) { + return this._patterns.has(expression.pattern); + } + /** + * Number of expressions in the set. + * @type {number} + */ + get size() { + return this._patterns.size; + } + /** + * Seal the set against further modifications. + * Useful to prevent accidental mutations after config is built. + * Calling add() or addAll() on a sealed set throws a TypeError. + * + * @returns {this} + */ + seal() { + this._sealed = true; + return this; + } + /** + * Whether the set has been sealed. + * @type {boolean} + */ + get isSealed() { + return this._sealed; + } + /** + * Test whether the matcher's current path matches any expression in the set. + * + * Evaluation order (cheapest → most expensive): + * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions + * 2. Depth-only wildcard bucket — O(1) lookup, rare + * 3. Deep-wildcard list — always checked, but usually small + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {boolean} true if any expression matches the current path + * + * @example + * if (stopNodes.matchesAny(matcher)) { + * // handle stop node + * } + */ + matchesAny(matcher) { + return this.findMatch(matcher) !== null; + } + /** + * Find and return the first Expression that matches the matcher's current path. + * + * Uses the same evaluation order as matchesAny (cheapest → most expensive): + * 1. Exact depth + tag bucket + * 2. Depth-only wildcard bucket + * 3. Deep-wildcard list + * + * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view) + * @returns {import('./Expression.js').default | null} the first matching Expression, or null + * + * @example + * const expr = stopNodes.findMatch(matcher); + * if (expr) { + * // access expr.config, expr.pattern, etc. + * } + */ + findMatch(matcher) { + const depth = matcher.getDepth(); + const tag = matcher.getCurrentTag(); + const exactKey = `${depth}:${tag}`; + const exactBucket = this._byDepthAndTag.get(exactKey); + if (exactBucket) { + for (let i = 0; i < exactBucket.length; i++) { + if (matcher.matches(exactBucket[i])) return exactBucket[i]; + } + } + const wildcardBucket = this._wildcardByDepth.get(depth); + if (wildcardBucket) { + for (let i = 0; i < wildcardBucket.length; i++) { + if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i]; + } + } + const deepBucket = this._deepByTerminalTag.get(tag); + if (deepBucket) { + for (let i = 0; i < deepBucket.length; i++) { + if (matcher.matches(deepBucket[i])) return deepBucket[i]; + } + } + for (let i = 0; i < this._deepWildcards.length; i++) { + if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i]; + } + return null; + } +}; + +// ../../node_modules/path-expression-matcher/src/Matcher.js +var MatcherView = class { + static { + __name(this, "MatcherView"); + } + /** + * @param {Matcher} matcher - The parent Matcher instance to read from. + */ + constructor(matcher) { + this._matcher = matcher; + } + /** + * Get the path separator used by the parent matcher. + * @returns {string} + */ + get separator() { + return this._matcher.separator; + } + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + const path5 = this._matcher.path; + return path5.length > 0 ? path5[path5.length - 1].tag : void 0; + } + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + const path5 = this._matcher.path; + return path5.length > 0 ? path5[path5.length - 1].namespace : void 0; + } + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + const path5 = this._matcher.path; + if (path5.length === 0) return void 0; + return path5[path5.length - 1].values?.[attrName]; + } + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + const path5 = this._matcher.path; + if (path5.length === 0) return false; + const current = path5[path5.length - 1]; + return current.values !== void 0 && attrName in current.values; + } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {*} + */ + getAnyParentAttr(attrName) { + return this._matcher.getAnyParentAttr(attrName); + } + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + return this._matcher.hasAnyParentAttr(attrName); + } + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + const path5 = this._matcher.path; + if (path5.length === 0) return -1; + return path5[path5.length - 1].position ?? 0; + } + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + const path5 = this._matcher.path; + if (path5.length === 0) return -1; + return path5[path5.length - 1].counter ?? 0; + } + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this._matcher.path.length; + } + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + return this._matcher.toString(separator, includeNamespace); + } + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this._matcher.path.map((n) => n.tag); + } + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + return this._matcher.matches(expression); + } + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this._matcher); + } +}; +var Matcher = class { + static { + __name(this, "Matcher"); + } + /** + * Create a new Matcher. + * @param {Object} [options={}] + * @param {string} [options.separator='.'] - Default path separator + */ + constructor(options = {}) { + this.separator = options.separator || "."; + this.path = []; + this.siblingStacks = []; + this._pathStringCache = null; + this._view = new MatcherView(this); + this._keptAttrs = []; + } + /** + * Push a new tag onto the path. + * @param {string} tagName + * @param {Object|null} [attrValues=null] + * @param {string|null} [namespace=null] + * @param {Object|null} [options=null] + * @param {string[]} [options.keep] - Names of attributes (from attrValues) + */ + push(tagName, attrValues = null, namespace = null, options = null) { + this._pathStringCache = null; + if (this.path.length > 0) { + this.path[this.path.length - 1].values = void 0; + } + const currentLevel = this.path.length; + let level = this.siblingStacks[currentLevel]; + if (!level) { + level = { counts: /* @__PURE__ */ new Map(), total: 0 }; + this.siblingStacks[currentLevel] = level; + } + const siblingKey = namespace ? `${namespace}:${tagName}` : tagName; + const counter = level.counts.get(siblingKey) || 0; + const position = level.total; + level.counts.set(siblingKey, counter + 1); + level.total++; + const node = { + tag: tagName, + position, + counter + }; + if (namespace !== null && namespace !== void 0) { + node.namespace = namespace; + } + if (attrValues !== null && attrValues !== void 0) { + node.values = attrValues; + } + this.path.push(node); + const depth = this.path.length; + const keep = options !== null ? options.keep : null; + if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) { + for (let i = 0; i < keep.length; i++) { + const name3 = keep[i]; + if (attrValues[name3] !== void 0) { + this._keptAttrs.push({ depth, name: name3, value: attrValues[name3] }); + } + } + } + } + /** + * Pop the last tag from the path. + * @returns {Object|undefined} The popped node + */ + pop() { + if (this.path.length === 0) return void 0; + this._pathStringCache = null; + const node = this.path.pop(); + if (this.siblingStacks.length > this.path.length + 1) { + this.siblingStacks.length = this.path.length + 1; + } + const poppedDepth = this.path.length + 1; + while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) { + this._keptAttrs.pop(); + } + return node; + } + /** + * Update current node's attribute values. + * Useful when attributes are parsed after push. + * @param {Object} attrValues + */ + updateCurrent(attrValues) { + if (this.path.length > 0) { + const current = this.path[this.path.length - 1]; + if (attrValues !== null && attrValues !== void 0) { + current.values = attrValues; + } + } + } + /** + * Get current tag name. + * @returns {string|undefined} + */ + getCurrentTag() { + return this.path.length > 0 ? this.path[this.path.length - 1].tag : void 0; + } + /** + * Get current namespace. + * @returns {string|undefined} + */ + getCurrentNamespace() { + return this.path.length > 0 ? this.path[this.path.length - 1].namespace : void 0; + } + /** + * Get current node's attribute value. + * @param {string} attrName + * @returns {*} + */ + getAttrValue(attrName) { + if (this.path.length === 0) return void 0; + return this.path[this.path.length - 1].values?.[attrName]; + } + /** + * Check if current node has an attribute. + * @param {string} attrName + * @returns {boolean} + */ + hasAttr(attrName) { + if (this.path.length === 0) return false; + const current = this.path[this.path.length - 1]; + return current.values !== void 0 && attrName in current.values; + } + /** + * Get the value of a "kept" attribute from the nearest ancestor (or + * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`. + * Unlike getAttrValue(), this works regardless of how deep the path has + * gone since the attribute was pushed — but only for attribute names that + * were explicitly marked with `keep` at push time. Cost is proportional to + * the number of currently-kept attributes (typically 0-3), not path depth. + * @param {string} attrName + * @returns {*} the value, or undefined if no ancestor kept this attribute + */ + getAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return kept[i].value; + } + return void 0; + } + /** + * Check whether any ancestor (or the current node) kept the given + * attribute via `push(tag, attrs, ns, { keep: [...] })`. + * @param {string} attrName + * @returns {boolean} + */ + hasAnyParentAttr(attrName) { + const kept = this._keptAttrs; + for (let i = kept.length - 1; i >= 0; i--) { + if (kept[i].name === attrName) return true; + } + return false; + } + /** + * Get current node's sibling position (child index in parent). + * @returns {number} + */ + getPosition() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].position ?? 0; + } + /** + * Get current node's repeat counter (occurrence count of this tag name). + * @returns {number} + */ + getCounter() { + if (this.path.length === 0) return -1; + return this.path[this.path.length - 1].counter ?? 0; + } + /** + * Get current node's sibling index (alias for getPosition). + * @returns {number} + * @deprecated Use getPosition() or getCounter() instead + */ + getIndex() { + return this.getPosition(); + } + /** + * Get current path depth. + * @returns {number} + */ + getDepth() { + return this.path.length; + } + /** + * Get path as string. + * @param {string} [separator] - Optional separator (uses default if not provided) + * @param {boolean} [includeNamespace=true] + * @returns {string} + */ + toString(separator, includeNamespace = true) { + const sep2 = separator || this.separator; + const isDefault = sep2 === this.separator && includeNamespace === true; + if (isDefault) { + if (this._pathStringCache !== null) { + return this._pathStringCache; + } + const result = this.path.map( + (n) => n.namespace ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep2); + this._pathStringCache = result; + return result; + } + return this.path.map( + (n) => includeNamespace && n.namespace ? `${n.namespace}:${n.tag}` : n.tag + ).join(sep2); + } + /** + * Get path as array of tag names. + * @returns {string[]} + */ + toArray() { + return this.path.map((n) => n.tag); + } + /** + * Reset the path to empty. + */ + reset() { + this._pathStringCache = null; + this.path = []; + this.siblingStacks = []; + this._keptAttrs = []; + } + /** + * Match current path against an Expression. + * @param {Expression} expression + * @returns {boolean} + */ + matches(expression) { + const segments = expression.segments; + if (segments.length === 0) { + return false; + } + if (expression.hasDeepWildcard()) { + return this._matchWithDeepWildcard(segments); + } + return this._matchSimple(segments); + } + /** + * @private + */ + _matchSimple(segments) { + if (this.path.length !== segments.length) { + return false; + } + for (let i = 0; i < segments.length; i++) { + if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) { + return false; + } + } + return true; + } + /** + * @private + */ + _matchWithDeepWildcard(segments) { + let pathIdx = this.path.length - 1; + let segIdx = segments.length - 1; + while (segIdx >= 0 && pathIdx >= 0) { + const segment = segments[segIdx]; + if (segment.type === "deep-wildcard") { + segIdx--; + if (segIdx < 0) { + return true; + } + const nextSeg = segments[segIdx]; + let found = false; + for (let i = pathIdx; i >= 0; i--) { + if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) { + pathIdx = i - 1; + segIdx--; + found = true; + break; + } + } + if (!found) { + return false; + } + } else { + if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) { + return false; + } + pathIdx--; + segIdx--; + } + } + return segIdx < 0; + } + /** + * @private + */ + _matchSegment(segment, node, isCurrentNode) { + if (segment.tag !== "*" && segment.tag !== node.tag) { + return false; + } + if (segment.namespace !== void 0) { + if (segment.namespace !== "*" && segment.namespace !== node.namespace) { + return false; + } + } + if (segment.attrName !== void 0) { + if (!isCurrentNode) { + return false; + } + if (!node.values || !(segment.attrName in node.values)) { + return false; + } + if (segment.attrValue !== void 0) { + if (String(node.values[segment.attrName]) !== String(segment.attrValue)) { + return false; + } + } + } + if (segment.position !== void 0) { + if (!isCurrentNode) { + return false; + } + const counter = node.counter ?? 0; + if (segment.position === "first" && counter !== 0) { + return false; + } else if (segment.position === "odd" && counter % 2 !== 1) { + return false; + } else if (segment.position === "even" && counter % 2 !== 0) { + return false; + } else if (segment.position === "nth" && counter !== segment.positionValue) { + return false; + } + } + return true; + } + /** + * Match any expression in the given set against the current path. + * @param {ExpressionSet} exprSet + * @returns {boolean} + */ + matchesAny(exprSet) { + return exprSet.matchesAny(this); + } + /** + * Create a snapshot of current state. + * @returns {Object} + */ + snapshot() { + return { + path: this.path.map((node) => ({ ...node })), + siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level), + keptAttrs: this._keptAttrs.map((entry) => ({ ...entry })) + }; + } + /** + * Restore state from snapshot. + * @param {Object} snapshot + */ + restore(snapshot2) { + this._pathStringCache = null; + this.path = snapshot2.path.map((node) => ({ ...node })); + this.siblingStacks = snapshot2.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level); + this._keptAttrs = (snapshot2.keptAttrs || []).map((entry) => ({ ...entry })); + } + /** + * Return the read-only {@link MatcherView} for this matcher. + * + * The same instance is returned on every call — no allocation occurs. + * It always reflects the current parser state and is safe to pass to + * user callbacks without risk of accidental mutation. + * + * @returns {MatcherView} + * + * @example + * const view = matcher.readOnly(); + * // pass view to callbacks — it stays in sync automatically + * view.matches(expr); // ✓ + * view.getCurrentTag(); // ✓ + * // view.push(...) // ✗ method does not exist — caught by TypeScript + */ + readOnly() { + return this._view; + } +}; + +// ../../node_modules/is-unsafe/src/contexts/html.js +var HTML_PATTERNS = [ + { + id: "html-script-open", + description: "]/i + }, + { + id: "html-javascript-protocol", + description: "javascript: URI scheme (with optional whitespace/encoding)", + // Handles javascript:, j\u0061vascript:, and whitespace variants + pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i + }, + { + id: "html-vbscript-protocol", + description: "vbscript: URI scheme", + pattern: /vbscript[\t\n\r ]*:/i + }, + { + id: "html-data-html", + description: "data:text/html URI \u2014 can execute scripts in browsers", + pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i + }, + { + id: "html-data-xhtml", + description: "data:application/xhtml+xml URI", + pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i + }, + { + id: "html-data-svg", + description: "data:image/svg+xml URI \u2014 can execute scripts", + pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i + }, + { + id: "html-inline-event-handler", + description: "Inline event handler attributes: onclick=, onerror=, onload=, etc.", + // \bon ensures we match a word boundary so "phonetic=" is not caught + pattern: /\bon\w{1,30}\s*=/i + }, + { + id: "html-entity-obfuscated-script", + description: "HTML-entity-encoded