canada-api 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,15 @@
1
+ ([Français](#canada-api-fr))
2
+
1
3
  # canada-api
2
4
 
3
5
  [![NPM Version](https://img.shields.io/npm/v/canada-api?branch=main)](https://www.npmjs.com/package/canada-api) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/dnd-mdn/canada-api/blob/main/LICENSE.md)
4
6
 
5
7
  Cross platform API for fetching public data from [canada.ca](https://www.canada.ca).
6
8
 
7
-
8
9
  ## Browser
10
+
9
11
  ```html
10
- <script src="https://cdn.jsdelivr.net/npm/canada-api@5.0.0"></script>
12
+ <script src="https://cdn.jsdelivr.net/npm/canada-api@5.1.0"></script>
11
13
  ```
12
14
 
13
15
  ## Node 18+
@@ -32,7 +34,7 @@ npm test
32
34
 
33
35
  Tests use the built-in Node.js test runner (`node:test`) and require Node 18 or later.
34
36
 
35
- ## Core API
37
+ ## API
36
38
 
37
39
  ### `ca.normalize(url)`
38
40
 
@@ -44,30 +46,10 @@ Validates and normalizes a canada.ca URL. Strips the `/content/canadasite` prefi
44
46
  Throws {TypeError} if `url` is not a string or URL object.
45
47
  Throws {Error} if the URL is not on canada.ca or the path does not start with `/en/` or `/fr/`.
46
48
 
47
- ### `ca.request(url)`
48
-
49
- - `url` {string|URL} - Relative or absolute URL on [canada.ca](https://www.canada.ca)
50
- - Returns: {Promise} Fulfills with an axios response object
51
-
52
- Raw HTTP client for canada.ca. No URL transformation is applied.
53
-
54
- ```json
55
- {
56
- "data": {},
57
- "status": 200,
58
- "statusText": "OK",
59
- "headers": {},
60
- "config": {},
61
- "request": {}
62
- }
63
- ```
64
-
65
- ## Basic API
66
-
67
49
  ### `ca.children(url)`
68
50
 
69
51
  - `url` {string|URL} - Absolute or relative URL
70
- - Returns: {Promise} Fulfills with an axios response whose `data` is an array of sitemap entries
52
+ - Returns: {Promise} Fulfills with a response whose `data` is an array of sitemap entries
71
53
 
72
54
  Fetches and parses the sitemap for the given page, returning its child pages. Entries without a `<loc>` element are skipped.
73
55
 
@@ -78,27 +60,29 @@ Fetches and parses the sitemap for the given page, returning its child pages. En
78
60
  "path": "/en/department-national-defence/maple-leaf",
79
61
  "lastmod": "2022-09-20T00:00:00.000Z"
80
62
  }
81
- ]
63
+ ],
64
+ "status": 200
82
65
  }
83
66
  ```
84
67
 
85
68
  ### `ca.content(url)`
86
69
 
87
70
  - `url` {string|URL} - Absolute or relative URL
88
- - Returns: {Promise} Fulfills with an axios response whose `data` is the raw HTML string
71
+ - Returns: {Promise} Fulfills with a response whose `data` is the raw HTML string
89
72
 
90
73
  Retrieves the HTML content of the page.
91
74
 
92
75
  ```json
93
76
  {
94
- "data": "<!DOCTYPE html>\r\n...."
77
+ "data": "<!DOCTYPE html>\r\n....",
78
+ "status": 200
95
79
  }
96
80
  ```
97
81
 
98
82
  ### `ca.meta(url)`
99
83
 
100
84
  - `url` {string|URL} - Absolute or relative URL
101
- - Returns: {Promise} Fulfills with an axios response whose `data` is a formatted metadata object
85
+ - Returns: {Promise} Fulfills with a response whose `data` is a formatted metadata object
102
86
 
103
87
  Fetches JCR metadata for the given page. The following transformations are applied:
104
88
 
@@ -115,6 +99,94 @@ Fetches JCR metadata for the given page. The following transformations are appli
115
99
  "cq:lastModified": "2022-10-25T19:16:28.000Z",
116
100
  "fluidWidth": false,
117
101
  "peer": "/fr/ministere-defense-nationale/feuille-erable"
118
- }
102
+ },
103
+ "status": 200
119
104
  }
120
105
  ```
106
+
107
+ ### `ca.request`
108
+
109
+ Raw HTTP client with `https://www.canada.ca` as the base URL. Use this for any requests not covered by the methods above. No URL transformation is applied.
110
+
111
+ ```js
112
+ const response = await ca.request('/en/sr/srb/srvs/t-srvc-eng.html');
113
+ ```
114
+
115
+ ---
116
+
117
+ ([English](#canada-api))
118
+
119
+ <a name="canada-api-fr"></a>
120
+ # canada-api
121
+
122
+ [![NPM Version](https://img.shields.io/npm/v/canada-api?branch=main)](https://www.npmjs.com/package/canada-api) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/dnd-mdn/canada-api/blob/main/LICENSE.md)
123
+
124
+ API multiplateforme pour récupérer des données publiques de [canada.ca](https://www.canada.ca).
125
+
126
+ ## Navigateur
127
+
128
+ ```html
129
+ <script src="https://cdn.jsdelivr.net/npm/canada-api@5.1.0"></script>
130
+ ```
131
+
132
+ ## Node 18+
133
+
134
+ ### Installation
135
+
136
+ ```shell
137
+ npm install canada-api
138
+ ```
139
+
140
+ ### Utilisation
141
+
142
+ ```js
143
+ import ca from 'canada-api'
144
+ ```
145
+
146
+ ## API
147
+
148
+ ### `ca.normalize(url)`
149
+
150
+ - `url` {string|URL} - URL complète ou chemin relatif (p. ex. `'/fr/page'` ou `'https://www.canada.ca/fr/page'`)
151
+ - Retourne: {URL} Objet URL normalisé avec un chemin nettoyé
152
+
153
+ Valide et normalise une URL de canada.ca. Supprime le préfixe `/content/canadasite`, les extensions de fichier et les barres obliques finales.
154
+
155
+ Lève {TypeError} si `url` n'est pas une chaîne ou un objet URL.
156
+ Lève {Error} si l'URL n'est pas sur canada.ca ou si le chemin ne commence pas par `/en/` ou `/fr/`.
157
+
158
+ ### `ca.children(url)`
159
+
160
+ - `url` {string|URL} - URL absolue ou relative
161
+ - Retourne: {Promise} Résout avec une réponse dont `data` est un tableau d'entrées du plan de site
162
+
163
+ Récupère et analyse le plan de site de la page donnée, retournant ses pages enfants. Les entrées sans élément `<loc>` sont ignorées.
164
+
165
+ ### `ca.content(url)`
166
+
167
+ - `url` {string|URL} - URL absolue ou relative
168
+ - Retourne: {Promise} Résout avec une réponse dont `data` est la chaîne HTML brute
169
+
170
+ Récupère le contenu HTML de la page.
171
+
172
+ ### `ca.meta(url)`
173
+
174
+ - `url` {string|URL} - URL absolue ou relative
175
+ - Retourne: {Promise} Résout avec une réponse dont `data` est un objet de métadonnées formaté
176
+
177
+ Récupère les métadonnées JCR de la page donnée. Les transformations suivantes sont appliquées :
178
+
179
+ - Les valeurs `"true"` / `"false"` sont converties en booléens
180
+ - Les propriétés `@TypeHint` sont supprimées
181
+ - Les tableaux vides sont supprimés
182
+ - Les chaînes de date sont converties en ISO 8601
183
+ - Les clés sont triées alphabétiquement
184
+ - Un champ `peer` normalisé est ajouté lorsque `gcAltLanguagePeer` est présent
185
+
186
+ ### `ca.request`
187
+
188
+ Client HTTP brut avec `https://www.canada.ca` comme URL de base. Utilisez-le pour toute requête non couverte par les méthodes ci-dessus. Aucune transformation d'URL n'est appliquée.
189
+
190
+ ```js
191
+ const response = await ca.request.get('/fr/sr/srb/srvs/t-srvc-fra.html');
192
+ ```
package/dist/ca.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("ca",[],e):"object"==typeof exports?exports.ca=e():t.ca=e()}(Object("undefined"!=typeof self?self:this),()=>(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),t.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var e={};t.r(e),t.d(e,{default:()=>Wn});var n={};t.r(n),t.d(n,{hasBrowserEnv:()=>pt,hasStandardBrowserEnv:()=>mt,hasStandardBrowserWebWorkerEnv:()=>bt,navigator:()=>gt,origin:()=>yt});const r="https://www.canada.ca",i=t=>{if("string"==typeof t)t=new URL(t,r);else if(!(t instanceof URL))throw new TypeError("string or URL object expected");if(t.origin!==r)throw new Error("URL must start with "+r);if(t.pathname=t.pathname.replace(/^\/content\/canadasite/,""),t.pathname=t.pathname.replace(/\.[^/]*$/,"").replace(/\/+$/,""),!t.pathname.startsWith("/en/")&&!t.pathname.startsWith("/fr/"))throw new Error(`Invalid path: "${t.pathname}" must start with /en/ or /fr/`);return t};function s(t,e){return function(){return t.apply(e,arguments)}}const{toString:o}=Object.prototype,{getPrototypeOf:a}=Object,{iterator:l,toStringTag:c}=Symbol,u=(h=Object.create(null),t=>{const e=o.call(t);return h[e]||(h[e]=e.slice(8,-1).toLowerCase())});var h;const d=t=>(t=t.toLowerCase(),e=>u(e)===t),f=t=>e=>typeof e===t,{isArray:p}=Array,g=f("undefined");function m(t){return null!==t&&!g(t)&&null!==t.constructor&&!g(t.constructor)&&E(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const b=d("ArrayBuffer"),y=f("string"),E=f("function"),w=f("number"),x=t=>null!==t&&"object"==typeof t,N=t=>{if("object"!==u(t))return!1;const e=a(t);return!(null!==e&&e!==Object.prototype&&null!==Object.getPrototypeOf(e)||c in t||l in t)},S=d("Date"),v=d("File"),T=d("Blob"),O=d("FileList"),R="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==t.g?t.g:{},A=void 0!==R.FormData?R.FormData:void 0,C=d("URLSearchParams"),[P,_,j,I]=["ReadableStream","Request","Response","Headers"].map(d);function D(t,e,{allOwnKeys:n=!1}={}){if(null==t)return;let r,i;if("object"!=typeof t&&(t=[t]),p(t))for(r=0,i=t.length;r<i;r++)e.call(null,t[r],r,t);else{if(m(t))return;const i=n?Object.getOwnPropertyNames(t):Object.keys(t),s=i.length;let o;for(r=0;r<s;r++)o=i[r],e.call(null,t[o],o,t)}}function U(t,e){if(m(t))return null;e=e.toLowerCase();const n=Object.keys(t);let r,i=n.length;for(;i-- >0;)if(r=n[i],e===r.toLowerCase())return r;return null}const k="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:t.g,F=t=>!g(t)&&t!==k,L=($="undefined"!=typeof Uint8Array&&a(Uint8Array),t=>$&&t instanceof $);var $;const B=d("HTMLFormElement"),M=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),V=d("RegExp"),q=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};D(n,(n,i)=>{let s;!1!==(s=e(n,i,t))&&(r[i]=s||n)}),Object.defineProperties(t,r)},z=d("AsyncFunction"),W=(J="function"==typeof setImmediate,H=E(k.postMessage),J?setImmediate:H?(K=`axios@${Math.random()}`,X=[],k.addEventListener("message",({source:t,data:e})=>{t===k&&e===K&&X.length&&X.shift()()},!1),t=>{X.push(t),k.postMessage(K,"*")}):t=>setTimeout(t));var J,H,K,X;const Y="undefined"!=typeof queueMicrotask?queueMicrotask.bind(k):"undefined"!=typeof process&&process.nextTick||W,G={isArray:p,isArrayBuffer:b,isBuffer:m,isFormData:t=>{let e;return t&&(A&&t instanceof A||E(t.append)&&("formdata"===(e=u(t))||"object"===e&&E(t.toString)&&"[object FormData]"===t.toString()))},isArrayBufferView:function(t){let e;return e="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&b(t.buffer),e},isString:y,isNumber:w,isBoolean:t=>!0===t||!1===t,isObject:x,isPlainObject:N,isEmptyObject:t=>{if(!x(t)||m(t))return!1;try{return 0===Object.keys(t).length&&Object.getPrototypeOf(t)===Object.prototype}catch(t){return!1}},isReadableStream:P,isRequest:_,isResponse:j,isHeaders:I,isUndefined:g,isDate:S,isFile:v,isReactNativeBlob:t=>!(!t||void 0===t.uri),isReactNative:t=>t&&void 0!==t.getParts,isBlob:T,isRegExp:V,isFunction:E,isStream:t=>x(t)&&E(t.pipe),isURLSearchParams:C,isTypedArray:L,isFileList:O,forEach:D,merge:function t(){const{caseless:e,skipUndefined:n}=F(this)&&this||{},r={},i=(i,s)=>{if("__proto__"===s||"constructor"===s||"prototype"===s)return;const o=e&&U(r,s)||s;N(r[o])&&N(i)?r[o]=t(r[o],i):N(i)?r[o]=t({},i):p(i)?r[o]=i.slice():n&&g(i)||(r[o]=i)};for(let t=0,e=arguments.length;t<e;t++)arguments[t]&&D(arguments[t],i);return r},extend:(t,e,n,{allOwnKeys:r}={})=>(D(e,(e,r)=>{n&&E(e)?Object.defineProperty(t,r,{value:s(e,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(t,r,{value:e,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),t),trim:t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:t=>(65279===t.charCodeAt(0)&&(t=t.slice(1)),t),inherits:(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),Object.defineProperty(t.prototype,"constructor",{value:t,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},toFlatObject:(t,e,n,r)=>{let i,s,o;const l={};if(e=e||{},null==t)return e;do{for(i=Object.getOwnPropertyNames(t),s=i.length;s-- >0;)o=i[s],r&&!r(o,t,e)||l[o]||(e[o]=t[o],l[o]=!0);t=!1!==n&&a(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},kindOf:u,kindOfTest:d,endsWith:(t,e,n)=>{t=String(t),(void 0===n||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return-1!==r&&r===n},toArray:t=>{if(!t)return null;if(p(t))return t;let e=t.length;if(!w(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},forEachEntry:(t,e)=>{const n=(t&&t[l]).call(t);let r;for(;(r=n.next())&&!r.done;){const n=r.value;e.call(t,n[0],n[1])}},matchAll:(t,e)=>{let n;const r=[];for(;null!==(n=t.exec(e));)r.push(n);return r},isHTMLForm:B,hasOwnProperty:M,hasOwnProp:M,reduceDescriptors:q,freezeMethods:t=>{q(t,(e,n)=>{if(E(t)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=t[n];E(r)&&(e.enumerable=!1,"writable"in e?e.writable=!1:e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(t,e)=>{const n={},r=t=>{t.forEach(t=>{n[t]=!0})};return p(t)?r(t):r(String(t).split(e)),n},toCamelCase:t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,e,n){return e.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(t,e)=>null!=t&&Number.isFinite(t=+t)?t:e,findKey:U,global:k,isContextDefined:F,isSpecCompliantForm:function(t){return!!(t&&E(t.append)&&"FormData"===t[c]&&t[l])},toJSONObject:t=>{const e=new Array(10),n=(t,r)=>{if(x(t)){if(e.indexOf(t)>=0)return;if(m(t))return t;if(!("toJSON"in t)){e[r]=t;const i=p(t)?[]:{};return D(t,(t,e)=>{const s=n(t,r+1);!g(s)&&(i[e]=s)}),e[r]=void 0,i}}return t};return n(t,0)},isAsyncFn:z,isThenable:t=>t&&(x(t)||E(t))&&E(t.then)&&E(t.catch),setImmediate:W,asap:Y,isIterable:t=>null!=t&&E(t[l])};class Z extends Error{static from(t,e,n,r,i,s){const o=new Z(t.message,e||t.code,n,r,i);return o.cause=t,o.name=t.name,null!=t.status&&null==o.status&&(o.status=t.status),s&&Object.assign(o,s),o}constructor(t,e,n,r,i){super(t),Object.defineProperty(this,"message",{value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:G.toJSONObject(this.config),code:this.code,status:this.status}}}Z.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Z.ERR_BAD_OPTION="ERR_BAD_OPTION",Z.ECONNABORTED="ECONNABORTED",Z.ETIMEDOUT="ETIMEDOUT",Z.ERR_NETWORK="ERR_NETWORK",Z.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Z.ERR_DEPRECATED="ERR_DEPRECATED",Z.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Z.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Z.ERR_CANCELED="ERR_CANCELED",Z.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Z.ERR_INVALID_URL="ERR_INVALID_URL";const Q=Z;function tt(t){return G.isPlainObject(t)||G.isArray(t)}function et(t){return G.endsWith(t,"[]")?t.slice(0,-2):t}function nt(t,e,n){return t?t.concat(e).map(function(t,e){return t=et(t),!n&&e?"["+t+"]":t}).join(n?".":""):e}const rt=G.toFlatObject(G,{},null,function(t){return/^is[A-Z]/.test(t)}),it=function(t,e,n){if(!G.isObject(t))throw new TypeError("target must be an object");e=e||new FormData;const r=(n=G.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(t,e){return!G.isUndefined(e[t])})).metaTokens,i=n.visitor||c,s=n.dots,o=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&G.isSpecCompliantForm(e);if(!G.isFunction(i))throw new TypeError("visitor must be a function");function l(t){if(null===t)return"";if(G.isDate(t))return t.toISOString();if(G.isBoolean(t))return t.toString();if(!a&&G.isBlob(t))throw new Q("Blob is not supported. Use a Buffer instead.");return G.isArrayBuffer(t)||G.isTypedArray(t)?a&&"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}function c(t,n,i){let a=t;if(G.isReactNative(e)&&G.isReactNativeBlob(t))return e.append(nt(i,n,s),l(t)),!1;if(t&&!i&&"object"==typeof t)if(G.endsWith(n,"{}"))n=r?n:n.slice(0,-2),t=JSON.stringify(t);else if(G.isArray(t)&&function(t){return G.isArray(t)&&!t.some(tt)}(t)||(G.isFileList(t)||G.endsWith(n,"[]"))&&(a=G.toArray(t)))return n=et(n),a.forEach(function(t,r){!G.isUndefined(t)&&null!==t&&e.append(!0===o?nt([n],r,s):null===o?n:n+"[]",l(t))}),!1;return!!tt(t)||(e.append(nt(i,n,s),l(t)),!1)}const u=[],h=Object.assign(rt,{defaultVisitor:c,convertValue:l,isVisitable:tt});if(!G.isObject(t))throw new TypeError("data must be an object");return function t(n,r){if(!G.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+r.join("."));u.push(n),G.forEach(n,function(n,s){!0===(!(G.isUndefined(n)||null===n)&&i.call(e,n,G.isString(s)?s.trim():s,r,h))&&t(n,r?r.concat(s):[s])}),u.pop()}}(t),e};function st(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(t){return e[t]})}function ot(t,e){this._pairs=[],t&&it(t,this,e)}const at=ot.prototype;at.append=function(t,e){this._pairs.push([t,e])},at.toString=function(t){const e=t?function(e){return t.call(this,e,st)}:st;return this._pairs.map(function(t){return e(t[0])+"="+e(t[1])},"").join("&")};const lt=ot;function ct(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ut(t,e,n){if(!e)return t;const r=n&&n.encode||ct,i=G.isFunction(n)?{serialize:n}:n,s=i&&i.serialize;let o;if(o=s?s(e,i):G.isURLSearchParams(e)?e.toString():new lt(e,i).toString(r),o){const e=t.indexOf("#");-1!==e&&(t=t.slice(0,e)),t+=(-1===t.indexOf("?")?"?":"&")+o}return t}const ht=class{constructor(){this.handlers=[]}use(t,e,n){return this.handlers.push({fulfilled:t,rejected:e,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){G.forEach(this.handlers,function(e){null!==e&&t(e)})}},dt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},ft={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:lt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},pt="undefined"!=typeof window&&"undefined"!=typeof document,gt="object"==typeof navigator&&navigator||void 0,mt=pt&&(!gt||["ReactNative","NativeScript","NS"].indexOf(gt.product)<0),bt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,yt=pt&&window.location.href||"http://localhost",Et={...n,...ft},wt=function(t){function e(t,n,r,i){let s=t[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=t.length;return s=!s&&G.isArray(r)?r.length:s,a?(G.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!o):(r[s]&&G.isObject(r[s])||(r[s]=[]),e(t,n,r[s],i)&&G.isArray(r[s])&&(r[s]=function(t){const e={},n=Object.keys(t);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],e[s]=t[s];return e}(r[s])),!o)}if(G.isFormData(t)&&G.isFunction(t.entries)){const n={};return G.forEachEntry(t,(t,r)=>{e(function(t){return G.matchAll(/\w+|\[(\w*)]/g,t).map(t=>"[]"===t[0]?"":t[1]||t[0])}(t),r,n,0)}),n}return null},xt={transitional:dt,adapter:["xhr","http","fetch"],transformRequest:[function(t,e){const n=e.getContentType()||"",r=n.indexOf("application/json")>-1,i=G.isObject(t);if(i&&G.isHTMLForm(t)&&(t=new FormData(t)),G.isFormData(t))return r?JSON.stringify(wt(t)):t;if(G.isArrayBuffer(t)||G.isBuffer(t)||G.isStream(t)||G.isFile(t)||G.isBlob(t)||G.isReadableStream(t))return t;if(G.isArrayBufferView(t))return t.buffer;if(G.isURLSearchParams(t))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(t,e){return it(t,new Et.classes.URLSearchParams,{visitor:function(t,e,n,r){return Et.isNode&&G.isBuffer(t)?(this.append(e,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...e})}(t,this.formSerializer).toString();if((s=G.isFileList(t))||n.indexOf("multipart/form-data")>-1){const e=this.env&&this.env.FormData;return it(s?{"files[]":t}:t,e&&new e,this.formSerializer)}}return i||r?(e.setContentType("application/json",!1),function(t){if(G.isString(t))try{return(0,JSON.parse)(t),G.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(0,JSON.stringify)(t)}(t)):t}],transformResponse:[function(t){const e=this.transitional||xt.transitional,n=e&&e.forcedJSONParsing,r="json"===this.responseType;if(G.isResponse(t)||G.isReadableStream(t))return t;if(t&&G.isString(t)&&(n&&!this.responseType||r)){const n=!(e&&e.silentJSONParsing)&&r;try{return JSON.parse(t,this.parseReviver)}catch(t){if(n){if("SyntaxError"===t.name)throw Q.from(t,Q.ERR_BAD_RESPONSE,this,null,this.response);throw t}}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Et.classes.FormData,Blob:Et.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};G.forEach(["delete","get","head","post","put","patch"],t=>{xt.headers[t]={}});const Nt=xt,St=G.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),vt=Symbol("internals");function Tt(t){return t&&String(t).trim().toLowerCase()}function Ot(t){return!1===t||null==t?t:G.isArray(t)?t.map(Ot):String(t)}function Rt(t,e,n,r,i){return G.isFunction(r)?r.call(this,e,n):(i&&(e=n),G.isString(e)?G.isString(r)?-1!==e.indexOf(r):G.isRegExp(r)?r.test(e):void 0:void 0)}class At{constructor(t){t&&this.set(t)}set(t,e,n){const r=this;function i(t,e,n){const i=Tt(e);if(!i)throw new Error("header name must be a non-empty string");const s=G.findKey(r,i);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||e]=Ot(t))}const s=(t,e)=>G.forEach(t,(t,n)=>i(t,n,e));if(G.isPlainObject(t)||t instanceof this.constructor)s(t,e);else if(G.isString(t)&&(t=t.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim()))s((t=>{const e={};let n,r,i;return t&&t.split("\n").forEach(function(t){i=t.indexOf(":"),n=t.substring(0,i).trim().toLowerCase(),r=t.substring(i+1).trim(),!n||e[n]&&St[n]||("set-cookie"===n?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e})(t),e);else if(G.isObject(t)&&G.isIterable(t)){let n,r,i={};for(const e of t){if(!G.isArray(e))throw TypeError("Object iterator must return a key-value pair");i[r=e[0]]=(n=i[r])?G.isArray(n)?[...n,e[1]]:[n,e[1]]:e[1]}s(i,e)}else null!=t&&i(e,t,n);return this}get(t,e){if(t=Tt(t)){const n=G.findKey(this,t);if(n){const t=this[n];if(!e)return t;if(!0===e)return function(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}(t);if(G.isFunction(e))return e.call(this,t,n);if(G.isRegExp(e))return e.exec(t);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,e){if(t=Tt(t)){const n=G.findKey(this,t);return!(!n||void 0===this[n]||e&&!Rt(0,this[n],n,e))}return!1}delete(t,e){const n=this;let r=!1;function i(t){if(t=Tt(t)){const i=G.findKey(n,t);!i||e&&!Rt(0,n[i],i,e)||(delete n[i],r=!0)}}return G.isArray(t)?t.forEach(i):i(t),r}clear(t){const e=Object.keys(this);let n=e.length,r=!1;for(;n--;){const i=e[n];t&&!Rt(0,this[i],i,t,!0)||(delete this[i],r=!0)}return r}normalize(t){const e=this,n={};return G.forEach(this,(r,i)=>{const s=G.findKey(n,i);if(s)return e[s]=Ot(r),void delete e[i];const o=t?function(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,e,n)=>e.toUpperCase()+n)}(i):String(i).trim();o!==i&&delete e[i],e[o]=Ot(r),n[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const e=Object.create(null);return G.forEach(this,(n,r)=>{null!=n&&!1!==n&&(e[r]=t&&G.isArray(n)?n.join(", "):n)}),e}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,e])=>t+": "+e).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...e){const n=new this(t);return e.forEach(t=>n.set(t)),n}static accessor(t){const e=(this[vt]=this[vt]={accessors:{}}).accessors,n=this.prototype;function r(t){const r=Tt(t);e[r]||(function(t,e){const n=G.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(t,n,i){return this[r].call(this,e,t,n,i)},configurable:!0})})}(n,t),e[r]=!0)}return G.isArray(t)?t.forEach(r):r(t),this}}At.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),G.reduceDescriptors(At.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(t){this[n]=t}}}),G.freezeMethods(At);const Ct=At;function Pt(t,e){const n=this||Nt,r=e||n,i=Ct.from(r.headers);let s=r.data;return G.forEach(t,function(t){s=t.call(n,s,i.normalize(),e?e.status:void 0)}),i.normalize(),s}function _t(t){return!(!t||!t.__CANCEL__)}const jt=class extends Q{constructor(t,e,n){super(null==t?"canceled":t,Q.ERR_CANCELED,e,n),this.name="CanceledError",this.__CANCEL__=!0}};function It(t,e,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?e(new Q("Request failed with status code "+n.status,[Q.ERR_BAD_REQUEST,Q.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):t(n)}const Dt=(t,e,n=3)=>{let r=0;const i=function(t,e){t=t||10;const n=new Array(t),r=new Array(t);let i,s=0,o=0;return e=void 0!==e?e:1e3,function(a){const l=Date.now(),c=r[o];i||(i=l),n[s]=a,r[s]=l;let u=o,h=0;for(;u!==s;)h+=n[u++],u%=t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),l-i<e)return;const d=c&&l-c;return d?Math.round(1e3*h/d):void 0}}(50,250);return function(t,e){let n,r,i=0,s=1e3/e;const o=(e,s=Date.now())=>{i=s,n=null,r&&(clearTimeout(r),r=null),t(...e)};return[(...t)=>{const e=Date.now(),a=e-i;a>=s?o(t,e):(n=t,r||(r=setTimeout(()=>{r=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,l=i(a);r=s,t({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:l||void 0,estimated:l&&o&&s<=o?(o-s)/l:void 0,event:n,lengthComputable:null!=o,[e?"download":"upload"]:!0})},n)},Ut=(t,e)=>{const n=null!=t;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},kt=t=>(...e)=>G.asap(()=>t(...e)),Ft=Et.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,Et.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(Et.origin),Et.navigator&&/(msie|trident)/i.test(Et.navigator.userAgent)):()=>!0,Lt=Et.hasStandardBrowserEnv?{write(t,e,n,r,i,s,o){if("undefined"==typeof document)return;const a=[`${t}=${encodeURIComponent(e)}`];G.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),G.isString(r)&&a.push(`path=${r}`),G.isString(i)&&a.push(`domain=${i}`),!0===s&&a.push("secure"),G.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.join("; ")},read(t){if("undefined"==typeof document)return null;const e=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return e?decodeURIComponent(e[1]):null},remove(t){this.write(t,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function $t(t,e,n){let r=!("string"==typeof(i=e)&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(i));var i;return t&&(r||0==n)?function(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}(t,e):e}const Bt=t=>t instanceof Ct?{...t}:t;function Mt(t,e){e=e||{};const n={};function r(t,e,n,r){return G.isPlainObject(t)&&G.isPlainObject(e)?G.merge.call({caseless:r},t,e):G.isPlainObject(e)?G.merge({},e):G.isArray(e)?e.slice():e}function i(t,e,n,i){return G.isUndefined(e)?G.isUndefined(t)?void 0:r(void 0,t,0,i):r(t,e,0,i)}function s(t,e){if(!G.isUndefined(e))return r(void 0,e)}function o(t,e){return G.isUndefined(e)?G.isUndefined(t)?void 0:r(void 0,t):r(void 0,e)}function a(n,i,s){return s in e?r(n,i):s in t?r(void 0,n):void 0}const l={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(t,e,n)=>i(Bt(t),Bt(e),0,!0)};return G.forEach(Object.keys({...t,...e}),function(r){if("__proto__"===r||"constructor"===r||"prototype"===r)return;const s=G.hasOwnProp(l,r)?l[r]:i,o=s(t[r],e[r],r);G.isUndefined(o)&&s!==a||(n[r]=o)}),n}const Vt=t=>{const e=Mt({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=e;if(e.headers=o=Ct.from(o),e.url=ut($t(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),G.isFormData(n))if(Et.hasStandardBrowserEnv||Et.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(G.isFunction(n.getHeaders)){const t=n.getHeaders(),e=["content-type","content-length"];Object.entries(t).forEach(([t,n])=>{e.includes(t.toLowerCase())&&o.set(t,n)})}if(Et.hasStandardBrowserEnv&&(r&&G.isFunction(r)&&(r=r(e)),r||!1!==r&&Ft(e.url))){const t=i&&s&&Lt.read(s);t&&o.set(i,t)}return e},qt="undefined"!=typeof XMLHttpRequest&&function(t){return new Promise(function(e,n){const r=Vt(t);let i=r.data;const s=Ct.from(r.headers).normalize();let o,a,l,c,u,{responseType:h,onUploadProgress:d,onDownloadProgress:f}=r;function p(){c&&c(),u&&u(),r.cancelToken&&r.cancelToken.unsubscribe(o),r.signal&&r.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const r=Ct.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());It(function(t){e(t),p()},function(t){n(t),p()},{data:h&&"text"!==h&&"json"!==h?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:r,config:t,request:g}),g=null}g.open(r.method.toUpperCase(),r.url,!0),g.timeout=r.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new Q("Request aborted",Q.ECONNABORTED,t,g)),g=null)},g.onerror=function(e){const r=e&&e.message?e.message:"Network Error",i=new Q(r,Q.ERR_NETWORK,t,g);i.event=e||null,n(i),g=null},g.ontimeout=function(){let e=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||dt;r.timeoutErrorMessage&&(e=r.timeoutErrorMessage),n(new Q(e,i.clarifyTimeoutError?Q.ETIMEDOUT:Q.ECONNABORTED,t,g)),g=null},void 0===i&&s.setContentType(null),"setRequestHeader"in g&&G.forEach(s.toJSON(),function(t,e){g.setRequestHeader(e,t)}),G.isUndefined(r.withCredentials)||(g.withCredentials=!!r.withCredentials),h&&"json"!==h&&(g.responseType=r.responseType),f&&([l,u]=Dt(f,!0),g.addEventListener("progress",l)),d&&g.upload&&([a,c]=Dt(d),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",c)),(r.cancelToken||r.signal)&&(o=e=>{g&&(n(!e||e.type?new jt(null,t,g):e),g.abort(),g=null)},r.cancelToken&&r.cancelToken.subscribe(o),r.signal&&(r.signal.aborted?o():r.signal.addEventListener("abort",o)));const b=function(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}(r.url);b&&-1===Et.protocols.indexOf(b)?n(new Q("Unsupported protocol "+b+":",Q.ERR_BAD_REQUEST,t)):g.send(i||null)})},zt=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let n,r=new AbortController;const i=function(t){if(!n){n=!0,o();const e=t instanceof Error?t:this.reason;r.abort(e instanceof Q?e:new jt(e instanceof Error?e.message:e))}};let s=e&&setTimeout(()=>{s=null,i(new Q(`timeout of ${e}ms exceeded`,Q.ETIMEDOUT))},e);const o=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(t=>{t.unsubscribe?t.unsubscribe(i):t.removeEventListener("abort",i)}),t=null)};t.forEach(t=>t.addEventListener("abort",i));const{signal:a}=r;return a.unsubscribe=()=>G.asap(o),a}},Wt=function*(t,e){let n=t.byteLength;if(!e||n<e)return void(yield t);let r,i=0;for(;i<n;)r=i+e,yield t.slice(i,r),i=r},Jt=(t,e,n,r)=>{const i=async function*(t,e){for await(const n of async function*(t){if(t[Symbol.asyncIterator])return void(yield*t);const e=t.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}}(t))yield*Wt(n,e)}(t,e);let s,o=0,a=t=>{s||(s=!0,r&&r(t))};return new ReadableStream({async pull(t){try{const{done:e,value:r}=await i.next();if(e)return a(),void t.close();let s=r.byteLength;if(n){let t=o+=s;n(t)}t.enqueue(new Uint8Array(r))}catch(t){throw a(t),t}},cancel:t=>(a(t),i.return())},{highWaterMark:2})},{isFunction:Ht}=G,Kt=(({Request:t,Response:e})=>({Request:t,Response:e}))(G.global),{ReadableStream:Xt,TextEncoder:Yt}=G.global,Gt=(t,...e)=>{try{return!!t(...e)}catch(t){return!1}},Zt=t=>{t=G.merge.call({skipUndefined:!0},Kt,t);const{fetch:e,Request:n,Response:r}=t,i=e?Ht(e):"function"==typeof fetch,s=Ht(n),o=Ht(r);if(!i)return!1;const a=i&&Ht(Xt),l=i&&("function"==typeof Yt?(c=new Yt,t=>c.encode(t)):async t=>new Uint8Array(await new n(t).arrayBuffer()));var c;const u=s&&a&&Gt(()=>{let t=!1;const e=new n(Et.origin,{body:new Xt,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),h=o&&a&&Gt(()=>G.isReadableStream(new r("").body)),d={stream:h&&(t=>t.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!d[t]&&(d[t]=(e,n)=>{let r=e&&e[t];if(r)return r.call(e);throw new Q(`Response type '${t}' is not supported`,Q.ERR_NOT_SUPPORT,n)})});return async t=>{let{url:i,method:o,data:a,signal:c,cancelToken:f,timeout:p,onDownloadProgress:g,onUploadProgress:m,responseType:b,headers:y,withCredentials:E="same-origin",fetchOptions:w}=Vt(t),x=e||fetch;b=b?(b+"").toLowerCase():"text";let N=zt([c,f&&f.toAbortSignal()],p),S=null;const v=N&&N.unsubscribe&&(()=>{N.unsubscribe()});let T;try{if(m&&u&&"get"!==o&&"head"!==o&&0!==(T=await(async(t,e)=>{const r=G.toFiniteNumber(t.getContentLength());return null==r?(async t=>{if(null==t)return 0;if(G.isBlob(t))return t.size;if(G.isSpecCompliantForm(t)){const e=new n(Et.origin,{method:"POST",body:t});return(await e.arrayBuffer()).byteLength}return G.isArrayBufferView(t)||G.isArrayBuffer(t)?t.byteLength:(G.isURLSearchParams(t)&&(t+=""),G.isString(t)?(await l(t)).byteLength:void 0)})(e):r})(y,a))){let t,e=new n(i,{method:"POST",body:a,duplex:"half"});if(G.isFormData(a)&&(t=e.headers.get("content-type"))&&y.setContentType(t),e.body){const[t,n]=Ut(T,Dt(kt(m)));a=Jt(e.body,65536,t,n)}}G.isString(E)||(E=E?"include":"omit");const e=s&&"credentials"in n.prototype,c={...w,signal:N,method:o.toUpperCase(),headers:y.normalize().toJSON(),body:a,duplex:"half",credentials:e?E:void 0};S=s&&new n(i,c);let f=await(s?x(S,w):x(i,c));const p=h&&("stream"===b||"response"===b);if(h&&(g||p&&v)){const t={};["status","statusText","headers"].forEach(e=>{t[e]=f[e]});const e=G.toFiniteNumber(f.headers.get("content-length")),[n,i]=g&&Ut(e,Dt(kt(g),!0))||[];f=new r(Jt(f.body,65536,n,()=>{i&&i(),v&&v()}),t)}b=b||"text";let O=await d[G.findKey(d,b)||"text"](f,t);return!p&&v&&v(),await new Promise((e,n)=>{It(e,n,{data:O,headers:Ct.from(f.headers),status:f.status,statusText:f.statusText,config:t,request:S})})}catch(e){if(v&&v(),e&&"TypeError"===e.name&&/Load failed|fetch/i.test(e.message))throw Object.assign(new Q("Network Error",Q.ERR_NETWORK,t,S,e&&e.response),{cause:e.cause||e});throw Q.from(e,e&&e.code,t,S,e&&e.response)}}},Qt=new Map,te=t=>{let e=t&&t.env||{};const{fetch:n,Request:r,Response:i}=e,s=[r,i,n];let o,a,l=s.length,c=Qt;for(;l--;)o=s[l],a=c.get(o),void 0===a&&c.set(o,a=l?new Map:Zt(e)),c=a;return a},ee=(te(),{http:null,xhr:qt,fetch:{get:te}});G.forEach(ee,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(t){}Object.defineProperty(t,"adapterName",{value:e})}});const ne=t=>`- ${t}`,re=t=>G.isFunction(t)||null===t||!1===t,ie=function(t,e){t=G.isArray(t)?t:[t];const{length:n}=t;let r,i;const s={};for(let o=0;o<n;o++){let n;if(r=t[o],i=r,!re(r)&&(i=ee[(n=String(r)).toLowerCase()],void 0===i))throw new Q(`Unknown adapter '${n}'`);if(i&&(G.isFunction(i)||(i=i.get(e))))break;s[n||"#"+o]=i}if(!i){const t=Object.entries(s).map(([t,e])=>`adapter ${t} `+(!1===e?"is not supported by the environment":"is not available in the build"));let e=n?t.length>1?"since :\n"+t.map(ne).join("\n"):" "+ne(t[0]):"as no adapter specified";throw new Q("There is no suitable adapter to dispatch the request "+e,"ERR_NOT_SUPPORT")}return i};function se(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new jt(null,t)}function oe(t){return se(t),t.headers=Ct.from(t.headers),t.data=Pt.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1),ie(t.adapter||Nt.adapter,t)(t).then(function(e){return se(t),e.data=Pt.call(t,t.transformResponse,e),e.headers=Ct.from(e.headers),e},function(e){return _t(e)||(se(t),e&&e.response&&(e.response.data=Pt.call(t,t.transformResponse,e.response),e.response.headers=Ct.from(e.response.headers))),Promise.reject(e)})}const ae="1.13.6",le={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{le[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const ce={};le.transitional=function(t,e,n){function r(t,e){return"[Axios v"+ae+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return(n,i,s)=>{if(!1===t)throw new Q(r(i," has been removed"+(e?" in "+e:"")),Q.ERR_DEPRECATED);return e&&!ce[i]&&(ce[i]=!0,console.warn(r(i," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,i,s)}},le.spelling=function(t){return(e,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};const ue={assertOptions:function(t,e,n){if("object"!=typeof t)throw new Q("options must be an object",Q.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let i=r.length;for(;i-- >0;){const s=r[i],o=e[s];if(o){const e=t[s],n=void 0===e||o(e,s,t);if(!0!==n)throw new Q("option "+s+" must be "+n,Q.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Q("Unknown option "+s,Q.ERR_BAD_OPTION)}},validators:le},he=ue.validators;class de{constructor(t){this.defaults=t||{},this.interceptors={request:new ht,response:new ht}}async request(t,e){try{return await this._request(t,e)}catch(t){if(t instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const n=e.stack?e.stack.replace(/^.+\n/,""):"";try{t.stack?n&&!String(t.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(t.stack+="\n"+n):t.stack=n}catch(t){}}throw t}}_request(t,e){"string"==typeof t?(e=e||{}).url=t:e=t||{},e=Mt(this.defaults,e);const{transitional:n,paramsSerializer:r,headers:i}=e;void 0!==n&&ue.assertOptions(n,{silentJSONParsing:he.transitional(he.boolean),forcedJSONParsing:he.transitional(he.boolean),clarifyTimeoutError:he.transitional(he.boolean),legacyInterceptorReqResOrdering:he.transitional(he.boolean)},!1),null!=r&&(G.isFunction(r)?e.paramsSerializer={serialize:r}:ue.assertOptions(r,{encode:he.function,serialize:he.function},!0)),void 0!==e.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),ue.assertOptions(e,{baseUrl:he.spelling("baseURL"),withXsrfToken:he.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let s=i&&G.merge(i.common,i[e.method]);i&&G.forEach(["delete","get","head","post","put","patch","common"],t=>{delete i[t]}),e.headers=Ct.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(t){if("function"==typeof t.runWhen&&!1===t.runWhen(e))return;a=a&&t.synchronous;const n=e.transitional||dt;n&&n.legacyInterceptorReqResOrdering?o.unshift(t.fulfilled,t.rejected):o.push(t.fulfilled,t.rejected)});const l=[];let c;this.interceptors.response.forEach(function(t){l.push(t.fulfilled,t.rejected)});let u,h=0;if(!a){const t=[oe.bind(this),void 0];for(t.unshift(...o),t.push(...l),u=t.length,c=Promise.resolve(e);h<u;)c=c.then(t[h++],t[h++]);return c}u=o.length;let d=e;for(;h<u;){const t=o[h++],e=o[h++];try{d=t(d)}catch(t){e.call(this,t);break}}try{c=oe.call(this,d)}catch(t){return Promise.reject(t)}for(h=0,u=l.length;h<u;)c=c.then(l[h++],l[h++]);return c}getUri(t){return ut($t((t=Mt(this.defaults,t)).baseURL,t.url,t.allowAbsoluteUrls),t.params,t.paramsSerializer)}}G.forEach(["delete","get","head","options"],function(t){de.prototype[t]=function(e,n){return this.request(Mt(n||{},{method:t,url:e,data:(n||{}).data}))}}),G.forEach(["post","put","patch"],function(t){function e(e){return function(n,r,i){return this.request(Mt(i||{},{method:t,headers:e?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}de.prototype[t]=e(),de.prototype[t+"Form"]=e(!0)});const fe=de;class pe{constructor(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");let e;this.promise=new Promise(function(t){e=t});const n=this;this.promise.then(t=>{if(!n._listeners)return;let e=n._listeners.length;for(;e-- >0;)n._listeners[e](t);n._listeners=null}),this.promise.then=t=>{let e;const r=new Promise(t=>{n.subscribe(t),e=t}).then(t);return r.cancel=function(){n.unsubscribe(e)},r},t(function(t,r,i){n.reason||(n.reason=new jt(t,r,i),e(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){this.reason?t(this.reason):this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1)}toAbortSignal(){const t=new AbortController,e=e=>{t.abort(e)};return this.subscribe(e),t.signal.unsubscribe=()=>this.unsubscribe(e),t.signal}static source(){let t;return{token:new pe(function(e){t=e}),cancel:t}}}const ge=pe,me={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(me).forEach(([t,e])=>{me[e]=t});const be=me,ye=function t(e){const n=new fe(e),r=s(fe.prototype.request,n);return G.extend(r,fe.prototype,n,{allOwnKeys:!0}),G.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return t(Mt(e,n))},r}(Nt);ye.Axios=fe,ye.CanceledError=jt,ye.CancelToken=ge,ye.isCancel=_t,ye.VERSION=ae,ye.toFormData=it,ye.AxiosError=Q,ye.Cancel=ye.CanceledError,ye.all=function(t){return Promise.all(t)},ye.spread=function(t){return function(e){return t.apply(null,e)}},ye.isAxiosError=function(t){return G.isObject(t)&&!0===t.isAxiosError},ye.mergeConfig=Mt,ye.AxiosHeaders=Ct,ye.formToJSON=t=>wt(G.isHTMLForm(t)?new FormData(t):t),ye.getAdapter=ie,ye.HttpStatusCode=be,ye.default=ye;const Ee=ye,we=Ee.create({baseURL:r,timeout:3e4}),xe=":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",Ne=new RegExp("^["+xe+"]["+xe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function Se(t,e){const n=[];let r=e.exec(t);for(;r;){const i=[];i.startIndex=e.lastIndex-r[0].length;const s=r.length;for(let t=0;t<s;t++)i.push(r[t]);n.push(i),r=e.exec(t)}return n}const ve=function(t){return!(null==Ne.exec(t))},Te=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],Oe=["__proto__","constructor","prototype"],Re={allowBooleanAttributes:!1,unpairedTags:[]};function Ae(t,e){e=Object.assign({},Re,e);const n=[];let r=!1,i=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let s=0;s<t.length;s++)if("<"===t[s]&&"?"===t[s+1]){if(s+=2,s=Pe(t,s),s.err)return s}else{if("<"!==t[s]){if(Ce(t[s]))continue;return Le("InvalidChar","char '"+t[s]+"' is not expected.",Me(t,s))}{let o=s;if(s++,"!"===t[s]){s=_e(t,s);continue}{let a=!1;"/"===t[s]&&(a=!0,s++);let l="";for(;s<t.length&&">"!==t[s]&&" "!==t[s]&&"\t"!==t[s]&&"\n"!==t[s]&&"\r"!==t[s];s++)l+=t[s];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),s--),!Be(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Le("InvalidTag",e,Me(t,s))}const c=De(t,s);if(!1===c)return Le("InvalidAttr","Attributes for '"+l+"' have open quote.",Me(t,s));let u=c.value;if(s=c.index,"/"===u[u.length-1]){const n=s-u.length;u=u.substring(0,u.length-1);const i=ke(u,e);if(!0!==i)return Le(i.err.code,i.err.msg,Me(t,n+i.err.line));r=!0}else if(a){if(!c.tagClosed)return Le("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Me(t,s));if(u.trim().length>0)return Le("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Me(t,o));if(0===n.length)return Le("InvalidTag","Closing tag '"+l+"' has not been opened.",Me(t,o));{const e=n.pop();if(l!==e.tagName){let n=Me(t,e.tagStartPos);return Le("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+l+"'.",Me(t,o))}0==n.length&&(i=!0)}}else{const a=ke(u,e);if(!0!==a)return Le(a.err.code,a.err.msg,Me(t,s-u.length+a.err.line));if(!0===i)return Le("InvalidXml","Multiple possible root nodes found.",Me(t,s));-1!==e.unpairedTags.indexOf(l)||n.push({tagName:l,tagStartPos:o}),r=!0}for(s++;s<t.length;s++)if("<"===t[s]){if("!"===t[s+1]){s++,s=_e(t,s);continue}if("?"!==t[s+1])break;if(s=Pe(t,++s),s.err)return s}else if("&"===t[s]){const e=Fe(t,s);if(-1==e)return Le("InvalidChar","char '&' is not expected.",Me(t,s));s=e}else if(!0===i&&!Ce(t[s]))return Le("InvalidXml","Extra text at the end",Me(t,s));"<"===t[s]&&s--}}}return r?1==n.length?Le("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",Me(t,n[0].tagStartPos)):!(n.length>0)||Le("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Le("InvalidXml","Start tag expected.",1)}function Ce(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Pe(t,e){const n=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const r=t.substr(n,e-n);if(e>5&&"xml"===r)return Le("InvalidXml","XML declaration allowed only at the start of the document.",Me(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function _e(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e<t.length;e++)if("<"===t[e])n++;else if(">"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const je='"',Ie="'";function De(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===je||t[e]===Ie)""===r?r=t[e]:r!==t[e]||(r="");else if(">"===t[e]&&""===r){i=!0;break}n+=t[e]}return""===r&&{value:n,index:e,tagClosed:i}}const Ue=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function ke(t,e){const n=Se(t,Ue),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return Le("InvalidAttr","Attribute '"+n[t][2]+"' has no space in starting.",Ve(n[t]));if(void 0!==n[t][3]&&void 0===n[t][4])return Le("InvalidAttr","Attribute '"+n[t][2]+"' is without value.",Ve(n[t]));if(void 0===n[t][3]&&!e.allowBooleanAttributes)return Le("InvalidAttr","boolean attribute '"+n[t][2]+"' is not allowed.",Ve(n[t]));const i=n[t][2];if(!$e(i))return Le("InvalidAttr","Attribute '"+i+"' is an invalid name.",Ve(n[t]));if(Object.prototype.hasOwnProperty.call(r,i))return Le("InvalidAttr","Attribute '"+i+"' is repeated.",Ve(n[t]));r[i]=1}return!0}function Fe(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let n=/\d/;for("x"===t[e]&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(n))break}return-1}(t,++e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(";"===t[e])break;return-1}return e}function Le(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function $e(t){return ve(t)}function Be(t){return ve(t)}function Me(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Ve(t){return t.startIndex+t[1].length}const qe={validate:Ae},ze=t=>Te.includes(t)?"__"+t:t,We={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:ze};function Je(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(Te.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(Oe.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function He(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,maxEntityCount:100,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:t.maxEntitySize??1e4,maxExpansionDepth:t.maxExpansionDepth??10,maxTotalExpansions:t.maxTotalExpansions??1e3,maxExpandedLength:t.maxExpandedLength??1e5,maxEntityCount:t.maxEntityCount??100,allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:He(!0)}const Ke=function(t){const e=Object.assign({},We,t),n=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of n)t&&Je(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=ze),e.processEntities=He(e.processEntities),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let Xe;Xe="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class Ye{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][Xe]={startIndex:e})}static getMetaDataSymbol(){return Xe}}class Ge{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const n=Object.create(null);let r=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,o=!1,a="";for(;e<t.length;e++)if("<"!==t[e]||o)if(">"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:a+=t[e];else{if(s&&Qe(t,"!ENTITY",e)){let i,s;if(e+=7,[i,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){if(!1!==this.options.enabled&&this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw new Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);const t=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n[i]={regx:RegExp(`&${t};`,"g"),val:s},r++}}else if(s&&Qe(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(s&&Qe(t,"!ATTLIST",e))e+=8;else if(s&&Qe(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!Qe(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}i++,a=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){e=Ze(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)n+=t[e],e++;if(tn(n),e=Ze(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let r="";if([e,r]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&r.length>this.options.maxEntitySize)throw new Error(`Entity "${n}" size (${r.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,r,--e]}readNotationExp(t,e){e=Ze(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;!this.suppressValidationErr&&tn(n),e=Ze(t,e);const r=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==r&&"PUBLIC"!==r)throw new Error(`Expected SYSTEM or PUBLIC, found "${r}"`);e+=r.length,e=Ze(t,e);let i=null,s=null;if("PUBLIC"===r)[e,i]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=Ze(t,e)]&&"'"!==t[e]||([e,s]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===r&&([e,s]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!s))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:i,systemIdentifier:s,index:--e}}readIdentifierVal(t,e,n){let r="";const i=t[e];if('"'!==i&&"'"!==i)throw new Error(`Expected quoted string, found "${i}"`);for(e++;e<t.length&&t[e]!==i;)r+=t[e],e++;if(t[e]!==i)throw new Error(`Unterminated ${n} value`);return[++e,r]}readElementExp(t,e){e=Ze(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!this.suppressValidationErr&&!ve(n))throw new Error(`Invalid element name: "${n}"`);let r="";if("E"===t[e=Ze(t,e)]&&Qe(t,"MPTY",e))e+=4;else if("A"===t[e]&&Qe(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)r+=t[e],e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:r.trim(),index:e}}readAttlistExp(t,e){e=Ze(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;tn(n),e=Ze(t,e);let r="";for(;e<t.length&&!/\s/.test(t[e]);)r+=t[e],e++;if(!tn(r))throw new Error(`Invalid attribute name: "${r}"`);e=Ze(t,e);let i="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(i="NOTATION","("!==t[e=Ze(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let n=[];for(;e<t.length&&")"!==t[e];){let r="";for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)r+=t[e],e++;if(r=r.trim(),!tn(r))throw new Error(`Invalid notation name: "${r}"`);n.push(r),"|"===t[e]&&(e++,e=Ze(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,i+=" ("+n.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;const n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(i.toUpperCase()))throw new Error(`Invalid attribute type: "${i}"`)}e=Ze(t,e);let s="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(s="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(s="#IMPLIED",e+=7):[e,s]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:r,attributeType:i,defaultValue:s,index:e}}}const Ze=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function Qe(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function tn(t){if(ve(t))return t;throw new Error(`Invalid entity name ${t}`)}const en=/^[-+]?0x[a-fA-F0-9]+$/,nn=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,rn={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};const sn=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class on{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[]}push(t,e=null,n=null){this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const i=this.siblingStacks[r],s=n?`${n}:${t}`:t,o=i.get(s)||0;let a=0;for(const t of i.values())a+=t;i.set(s,o+1);const l={tag:t,position:a,counter:o};null!=n&&(l.namespace=n),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0===this.path.length)return;const e=this.path[this.path.length-1];return e.values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const n=t||this.separator;return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++){const n=t[e],r=this.path[e],i=e===this.path.length-1;if(!this._matchSegment(n,r,i))return!1}return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,n=t.length-1;for(;n>=0&&e>=0;){const r=t[n];if("deep-wildcard"===r.type){if(n--,n<0)return!0;const r=t[n];let i=!1;for(let t=e;t>=0;t--){const s=t===this.path.length-1;if(this._matchSegment(r,this.path[t],s)){e=t-1,n--,i=!0;break}}if(!i)return!1}else{const t=e===this.path.length-1;if(!this._matchSegment(r,this.path[e],t))return!1;e--,n--}}return n<0}_matchSegment(t,e,n){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!n)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue){const n=e.values[t.attrName];if(String(n)!==String(t.attrValue))return!1}}if(void 0!==t.position){if(!n)return!1;const r=e.counter??0;if("first"===t.position&&0!==r)return!1;if("odd"===t.position&&r%2!=1)return!1;if("even"===t.position&&r%2!=0)return!1;if("nth"===t.position&&r!==t.positionValue)return!1}return!0}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}}class an{constructor(t,e={}){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let n=0,r="";for(;n<t.length;)t[n]===this.separator?n+1<t.length&&t[n+1]===this.separator?(r.trim()&&(e.push(this._parseSegment(r.trim())),r=""),e.push({type:"deep-wildcard"}),n+=2):(r.trim()&&e.push(this._parseSegment(r.trim())),r="",n++):(r+=t[n],n++);return r.trim()&&e.push(this._parseSegment(r.trim())),e}_parseSegment(t){const e={type:"tag"};let n=null,r=t;const i=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(i&&(r=i[1]+i[3],i[2])){const t=i[2].slice(1,-1);t&&(n=t)}let s,o,a=r;if(r.includes("::")){const e=r.indexOf("::");if(s=r.substring(0,e).trim(),a=r.substring(e+2).trim(),!s)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(a.includes(":")){const t=a.lastIndexOf(":"),e=a.substring(0,t).trim(),n=a.substring(t+1).trim();["first","last","odd","even"].includes(n)||/^nth\(\d+\)$/.test(n)?(o=e,l=n):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=o,s&&(e.namespace=s),n)if(n.includes("=")){const t=n.indexOf("=");e.attrName=n.substring(0,t).trim(),e.attrValue=n.substring(t+1).trim()}else e.attrName=n.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}function ln(t,e){if(!t)return{};const n=e.attributesGroupName?t[e.attributesGroupName]:t;if(!n)return{};const r={};for(const t in n)t.startsWith(e.attributeNamePrefix)?r[t.substring(e.attributeNamePrefix.length)]=n[t]:r[t]=n[t];return r}function cn(t){if(!t||"string"!=typeof t)return;const e=t.indexOf(":");if(-1!==e&&e>0){const n=t.substring(0,e);if("xmlns"!==n)return n}}class un{constructor(t){var e;if(this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>Tn(e,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>Tn(e,16,"&#x")}},this.addExternalEntities=hn,this.parseXml=mn,this.parseTextData=dn,this.resolveNameSpace=fn,this.buildAttributesMap=gn,this.isItStopNode=wn,this.replaceEntitiesValue=yn,this.readStopNodeData=Sn,this.saveTextToParentTag=En,this.addChild=bn,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const n of e){if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0,this.matcher=new on,this.isCurrentNodeStopNode=!1,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodeExpressions=[];for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e?this.stopNodeExpressions.push(new an(e)):e instanceof an&&this.stopNodeExpressions.push(e)}}}}function hn(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n],i=r.replace(/[.\-+*:]/g,"\\.");this.lastEntities[r]={regex:new RegExp("&"+i+";","g"),val:t[r]}}}function dn(t,e,n,r,i,s,o){if(void 0!==t&&(this.options.trimValues&&!r&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,n));const r=this.options.jPath?n.toString():n,a=this.options.tagValueProcessor(e,t,r,i,s);return null==a?t:typeof a!=typeof t||a!==t?a:this.options.trimValues||t.trim()===t?vn(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function fn(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const pn=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function gn(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const r=Se(t,pn),i=r.length,s={},o={};for(let t=0;t<i;t++){const i=this.resolveNameSpace(r[t][1]),s=r[t][4];if(i.length&&void 0!==s){let t=s;this.options.trimValues&&(t=t.trim()),t=this.replaceEntitiesValue(t,n,e),o[i]=t}}Object.keys(o).length>0&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(o);for(let t=0;t<i;t++){const i=this.resolveNameSpace(r[t][1]),o=this.options.jPath?e.toString():e;if(this.ignoreAttributesFn(i,o))continue;let a=r[t][4],l=this.options.attributeNamePrefix+i;if(i.length)if(this.options.transformAttributeName&&(l=this.options.transformAttributeName(l)),l=Rn(l,this.options),void 0!==a){this.options.trimValues&&(a=a.trim()),a=this.replaceEntitiesValue(a,n,e);const t=this.options.jPath?e.toString():e,r=this.options.attributeValueProcessor(i,a,t);s[l]=null==r?a:typeof r!=typeof a||r!==a?r:vn(a,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(s[l]=!0)}if(!Object.keys(s).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=s,t}return s}}const mn=function(t){t=t.replace(/\r\n?/g,"\n");const e=new Ye("!xml");let n=e,r="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const i=new Ge(this.options.processEntities);for(let s=0;s<t.length;s++)if("<"===t[s])if("/"===t[s+1]){const e=xn(t,">",s,"Closing Tag is not closed.");let i=t.substring(s+2,e).trim();if(this.options.removeNSPrefix){const t=i.indexOf(":");-1!==t&&(i=i.substr(t+1))}i=On(this.options.transformTagName,i,"",this.options).tagName,n&&(r=this.saveTextToParentTag(r,n,this.matcher));const o=this.matcher.getCurrentTag();if(i&&-1!==this.options.unpairedTags.indexOf(i))throw new Error(`Unpaired tag can not be used as closing tag: </${i}>`);o&&-1!==this.options.unpairedTags.indexOf(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,n=this.tagsNodeStack.pop(),r="",s=e}else if("?"===t[s+1]){let e=Nn(t,s,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(r=this.saveTextToParentTag(r,n,this.matcher),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new Ye(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName)),this.addChild(n,t,this.matcher,s)}s=e.closeIndex+1}else if("!--"===t.substr(s+1,3)){const e=xn(t,"--\x3e",s+4,"Comment is not closed.");if(this.options.commentPropName){const i=t.substring(s+4,e-2);r=this.saveTextToParentTag(r,n,this.matcher),n.add(this.options.commentPropName,[{[this.options.textNodeName]:i}])}s=e}else if("!D"===t.substr(s+1,2)){const e=i.readDocType(t,s);this.docTypeEntities=e.entities,s=e.i}else if("!["===t.substr(s+1,2)){const e=xn(t,"]]>",s,"CDATA is not closed.")-2,i=t.substring(s+9,e);r=this.saveTextToParentTag(r,n,this.matcher);let o=this.parseTextData(i,n.tagname,this.matcher,!0,!1,!0,!0);null==o&&(o=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:i}]):n.add(this.options.textNodeName,o),s=e+2}else{let i=Nn(t,s,this.options.removeNSPrefix);if(!i){const e=t.substring(Math.max(0,s-50),Math.min(t.length,s+50));throw new Error(`readTagExp returned undefined at position ${s}. Context: "${e}"`)}let o=i.tagName;const a=i.rawTagName;let l=i.tagExp,c=i.attrExpPresent,u=i.closeIndex;if(({tagName:o,tagExp:l}=On(this.options.transformTagName,o,l,this.options)),this.options.strictReservedNames&&(o===this.options.commentPropName||o===this.options.cdataPropName))throw new Error(`Invalid tag name: ${o}`);n&&r&&"!xml"!==n.tagname&&(r=this.saveTextToParentTag(r,n,this.matcher,!1));const h=n;h&&-1!==this.options.unpairedTags.indexOf(h.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let d=!1;l.length>0&&l.lastIndexOf("/")===l.length-1&&(d=!0,"/"===o[o.length-1]?(o=o.substr(0,o.length-1),l=o):l=l.substr(0,l.length-1),c=o!==l);let f,p=null,g={};f=cn(a),o!==e.tagname&&this.matcher.push(o,{},f),o!==l&&c&&(p=this.buildAttributesMap(l,this.matcher,o),p&&(g=ln(p,this.options))),o!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode(this.stopNodeExpressions,this.matcher));const m=s;if(this.isCurrentNodeStopNode){let e="";if(d)s=i.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(o))s=i.closeIndex;else{const n=this.readStopNodeData(t,a,u+1);if(!n)throw new Error(`Unexpected end of ${a}`);s=n.i,e=n.tagContent}const r=new Ye(o);p&&(r[":@"]=p),r.add(this.options.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,r,this.matcher,m)}else{if(d){({tagName:o,tagExp:l}=On(this.options.transformTagName,o,l,this.options));const t=new Ye(o);p&&(t[":@"]=p),this.addChild(n,t,this.matcher,m),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(-1!==this.options.unpairedTags.indexOf(o)){const t=new Ye(o);p&&(t[":@"]=p),this.addChild(n,t,this.matcher,m),this.matcher.pop(),this.isCurrentNodeStopNode=!1,s=i.closeIndex;continue}{const t=new Ye(o);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),p&&(t[":@"]=p),this.addChild(n,t,this.matcher,m),n=t}}r="",s=u}}else r+=t[s];return e.child};function bn(t,e,n,r){this.options.captureMetaData||(r=void 0);const i=this.options.jPath?n.toString():n,s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,r)):t.addChild(e,r))}function yn(t,e,n){const r=this.options.processEntities;if(!r||!r.enabled)return t;if(r.allowedTags){const i=this.options.jPath?n.toString():n;if(!(Array.isArray(r.allowedTags)?r.allowedTags.includes(e):r.allowedTags(e,i)))return t}if(r.tagFilter){const i=this.options.jPath?n.toString():n;if(!r.tagFilter(e,i))return t}for(const e of Object.keys(this.docTypeEntities)){const n=this.docTypeEntities[e],i=t.match(n.regx);if(i){if(this.entityExpansionCount+=i.length,r.maxTotalExpansions&&this.entityExpansionCount>r.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${r.maxTotalExpansions}`);const e=t.length;if(t=t.replace(n.regx,n.val),r.maxExpandedLength&&(this.currentExpandedLength+=t.length-e,this.currentExpandedLength>r.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${r.maxExpandedLength}`)}}for(const e of Object.keys(this.lastEntities)){const n=this.lastEntities[e],i=t.match(n.regex);if(i&&(this.entityExpansionCount+=i.length,r.maxTotalExpansions&&this.entityExpansionCount>r.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${r.maxTotalExpansions}`);t=t.replace(n.regex,n.val)}if(-1===t.indexOf("&"))return t;if(this.options.htmlEntities)for(const e of Object.keys(this.htmlEntities)){const n=this.htmlEntities[e],i=t.match(n.regex);if(i&&(this.entityExpansionCount+=i.length,r.maxTotalExpansions&&this.entityExpansionCount>r.maxTotalExpansions))throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${r.maxTotalExpansions}`);t=t.replace(n.regex,n.val)}return t.replace(this.ampEntity.regex,this.ampEntity.val)}function En(t,e,n,r){return t&&(void 0===r&&(r=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,r))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function wn(t,e){if(!t||0===t.length)return!1;for(let n=0;n<t.length;n++)if(e.matches(t[n]))return!0;return!1}function xn(t,e,n,r){const i=t.indexOf(e,n);if(-1===i)throw new Error(r);return i+e.length-1}function Nn(t,e,n,r=">"){const i=function(t,e,n=">"){let r,i="";for(let s=e;s<t.length;s++){let e=t[s];if(r)e===r&&(r="");else if('"'===e||"'"===e)r=e;else if(e===n[0]){if(!n[1])return{data:i,index:s};if(t[s+1]===n[1])return{data:i,index:s}}else"\t"===e&&(e=" ");i+=e}}(t,e+1,r);if(!i)return;let s=i.data;const o=i.index,a=s.search(/\s/);let l=s,c=!0;-1!==a&&(l=s.substring(0,a),s=s.substring(a+1).trimStart());const u=l;if(n){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),c=l!==i.data.substr(t+1))}return{tagName:l,tagExp:s,closeIndex:o,attrExpPresent:c,rawTagName:u}}function Sn(t,e,n){const r=n;let i=1;for(;n<t.length;n++)if("<"===t[n])if("/"===t[n+1]){const s=xn(t,">",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(i--,0===i))return{tagContent:t.substring(r,n),i:s};n=s}else if("?"===t[n+1])n=xn(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=xn(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=xn(t,"]]>",n,"StopNode is not closed.")-2;else{const r=Nn(t,n,">");r&&((r&&r.tagName)===e&&"/"!==r.tagExp[r.tagExp.length-1]&&i++,n=r.closeIndex)}}function vn(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},rn,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&en.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const r=e.match(sn);if(r){let i=r[1]||"";const s=-1===r[3].indexOf("e")?"E":"e",o=r[2],a=i?t[o.length+1]===s:t[o.length]===s;return o.length>1&&a?t:1!==o.length||!r[3].startsWith(`.${s}`)&&r[3][0]!==s?n.leadingZeros&&!a?(e=(r[1]||"")+r[3],Number(e)):t:Number(e)}return t}(t,n,e);{const i=nn.exec(n);if(i){const s=i[1]||"",o=i[2];let a=(r=i[3])&&-1!==r.indexOf(".")?("."===(r=r.replace(/0+$/,""))?r="0":"."===r[0]?r="0"+r:"."===r[r.length-1]&&(r=r.substring(0,r.length-1)),r):r;const l=s?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const r=Number(n),i=String(r);if(0===r)return r;if(-1!==i.search(/[eE]/))return e.eNotation?r:t;if(-1!==n.indexOf("."))return"0"===i||i===a||i===`${s}${a}`?r:t;let l=o?a:n;return o?l===i||s+l===i?r:t:l===i||l===s+i?r:t}}return t}}var r;return function(t,e,n){const r=e===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return r?"Infinity":"-Infinity";default:return t}}(t,Number(n),e)}(t,n)}return void 0!==t?t:""}function Tn(t,e,n){const r=Number.parseInt(t,e);return r>=0&&r<=1114111?String.fromCodePoint(r):n+t+";"}function On(t,e,n,r){if(t){const r=t(e);n===e&&(n=r),e=r}return{tagName:e=Rn(e,r),tagExp:n}}function Rn(t,e){if(Oe.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return Te.includes(t)?e.onDangerousProperty(t):t}const An=Ye.getMetaDataSymbol();function Cn(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const n={};for(const r in t)r.startsWith(e)?n[r.substring(e.length)]=t[r]:n[r]=t[r];return n}function Pn(t,e,n){return _n(t,e,n)}function _n(t,e,n){let r;const i={};for(let s=0;s<t.length;s++){const o=t[s],a=jn(o);if(void 0!==a&&a!==e.textNodeName){const t=Cn(o[":@"]||{},e.attributeNamePrefix);n.push(a,t)}if(a===e.textNodeName)void 0===r?r=o[a]:r+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=_n(o[a],e,n);const r=Dn(t,e);if(o[":@"]?In(t,o[":@"],n,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==o[An]&&"object"==typeof t&&null!==t&&(t[An]=o[An]),void 0!==i[a]&&Object.prototype.hasOwnProperty.call(i,a))Array.isArray(i[a])||(i[a]=[i[a]]),i[a].push(t);else{const s=e.jPath?n.toString():n;e.isArray(a,s,r)?i[a]=[t]:i[a]=t}void 0!==a&&a!==e.textNodeName&&n.pop()}}}return"string"==typeof r?r.length>0&&(i[e.textNodeName]=r):void 0!==r&&(i[e.textNodeName]=r),i}function jn(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const n=e[t];if(":@"!==n)return n}}function In(t,e,n,r){if(e){const i=Object.keys(e),s=i.length;for(let o=0;o<s;o++){const s=i[o],a=s.startsWith(r.attributeNamePrefix)?s.substring(r.attributeNamePrefix.length):s,l=r.jPath?n.toString()+"."+a:n;r.isArray(s,l,!0,!0)?t[s]=[e[s]]:t[s]=e[s]}}}function Dn(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return 0===r||!(1!==r||!t[n]&&"boolean"!=typeof t[n]&&0!==t[n])}class Un{constructor(t){this.externalEntities={},this.options=Ke(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const n=Ae(t,e);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new un(this.options);n.addExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||void 0===r?r:Pn(r,this.options,n.matcher)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return Ye.getMetaDataSymbol()}}const kn=Ee.create({baseURL:r,timeout:3e4,maxRedirects:0});kn.interceptors.request.use(t=>{const e=i(t.url);return e.pathname=e.pathname+".sitemap.xml",e.searchParams.set("_",Date.now()),t.url=e.toString(),t},t=>Promise.reject(t)),kn.interceptors.response.use(t=>(t.data=Fn(t.data),t),t=>Promise.reject(t));const Fn=t=>{const e=qe.validate(t);if(!0!==e)throw new Error(e.err.msg);const n=(new Un).parse(t),r=n.urlset?.url||[];return(Array.isArray(r)?r:[r]).filter(t=>t.loc).map(t=>({path:i(t.loc).pathname,lastmod:t.lastmod?new Date(t.lastmod).toISOString():null}))},Ln=kn,$n=Ee.create({baseURL:r,timeout:5e3,maxRedirects:0});$n.interceptors.request.use(t=>{const e=i(t.url);return e.pathname=e.pathname+".html",e.searchParams.set("_",Date.now()),t.url=e.toString(),t},t=>Promise.reject(t));const Bn=$n,Mn=Ee.create({baseURL:r,timeout:5e3,maxRedirects:0});Mn.interceptors.request.use(t=>{const e=i(t.url);return e.pathname=e.pathname+"/_jcr_content.json",e.searchParams.set("_",Date.now()),t.url=e.toString(),t},t=>Promise.reject(t)),Mn.interceptors.response.use(t=>(t.data=zn(t.data),t),t=>Promise.reject(t));const Vn={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"};function qn(t){if(/^\d{4}-\d{2}-\d{2}$/.test(t))return new Date(t).toISOString();let e=/^\w{3} (\w{3}) (\d{2}) (\d{4}) ([\d:]{8}) GMT([\-+]\d{4})$/.exec(t);return e?new Date(`${e[3]}-${Vn[e[1]]}-${e[2]}T${e[4]}${e[5]}`).toISOString():t}const zn=t=>{const e={};for(const[n,r]of Object.entries(t))n.endsWith("@TypeHint")||Array.isArray(r)&&0===r.length||("true"===r?e[n]=!0:"false"===r?e[n]=!1:"gcAltLanguagePeer"===n?(e[n]=r,e.peer=i(r).pathname):e[n]="string"==typeof r?qn(r.trim()):r);return Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{})},Wn={normalize:i,request:we,children:Ln,content:Bn,meta:Mn};return e})());
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("ca",[],e):"object"==typeof exports?exports.ca=e():t.ca=e()}(Object("undefined"!=typeof self?self:this),()=>(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{default:()=>Lt});const n="https://www.canada.ca",r=t=>{if("string"==typeof t)t=new URL(t,n);else{if(!(t instanceof URL))throw new TypeError("string or URL object expected");t=new URL(t.href)}if(t.origin!==n)throw new Error("URL must start with "+n);if(t.pathname=t.pathname.replace(/^\/content\/canadasite/,""),t.pathname=t.pathname.replace(/\.[^/]*$/,"").replace(/\/+$/,""),!t.pathname.startsWith("/en/")&&!t.pathname.startsWith("/fr/"))throw new Error(`Invalid path: "${t.pathname}" must start with /en/ or /fr/`);return t},s=":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",i=new RegExp("^["+s+"]["+s+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function a(t,e){const n=[];let r=e.exec(t);for(;r;){const s=[];s.startIndex=e.lastIndex-r[0].length;const i=r.length;for(let t=0;t<i;t++)s.push(r[t]);n.push(s),r=e.exec(t)}return n}const o=function(t){return!(null==i.exec(t))},l=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],h=["__proto__","constructor","prototype"],u=t=>l.includes(t)?"__"+t:t,c={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:u};function p(t,e){if("string"!=typeof t)return;const n=t.toLowerCase();if(l.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(h.some(t=>n===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function d(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,maxEntityCount:100,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:d(!0)}const g=function(t){const e=Object.assign({},c,t),n=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of n)t&&p(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=u),e.processEntities=d(e.processEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map(t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t)),e};let f;f="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class m{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][f]={startIndex:e})}static getMetaDataSymbol(){return f}}class x{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const n=Object.create(null);let r=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,i=!1,a=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||a)if(">"===t[e]){if(a?"-"===t[e-1]&&"-"===t[e-2]&&(a=!1,s--):s--,0===s)break}else"["===t[e]?i=!0:o+=t[e];else{if(i&&y(t,"!ENTITY",e)){let s,i;if(e+=7,[s,i,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===i.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&r>=this.options.maxEntityCount)throw new Error(`Entity count (${r+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);const t=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n[s]={regx:RegExp(`&${t};`,"g"),val:i},r++}}else if(i&&y(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(i&&y(t,"!ATTLIST",e))e+=8;else if(i&&y(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!y(t,"!--",e))throw new Error("Invalid DOCTYPE");a=!0}s++,o=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){const n=e=E(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let r=t.substring(n,e);if(b(r),e=E(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let s="";if([e,s]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&s.length>this.options.maxEntitySize)throw new Error(`Entity "${r}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[r,s,--e]}readNotationExp(t,e){const n=e=E(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);!this.suppressValidationErr&&b(r),e=E(t,e);const s=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);e+=s.length,e=E(t,e);let i=null,a=null;if("PUBLIC"===s)[e,i]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=E(t,e)]&&"'"!==t[e]||([e,a]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===s&&([e,a]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!a))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:r,publicIdentifier:i,systemIdentifier:a,index:--e}}readIdentifierVal(t,e,n){let r="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);const i=++e;for(;e<t.length&&t[e]!==s;)e++;if(r=t.substring(i,e),t[e]!==s)throw new Error(`Unterminated ${n} value`);return[++e,r]}readElementExp(t,e){const n=e=E(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);if(!this.suppressValidationErr&&!o(r))throw new Error(`Invalid element name: "${r}"`);let s="";if("E"===t[e=E(t,e)]&&y(t,"MPTY",e))e+=4;else if("A"===t[e]&&y(t,"NY",e))e+=2;else if("("===t[e]){const n=++e;for(;e<t.length&&")"!==t[e];)e++;if(s=t.substring(n,e),")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:r,contentModel:s.trim(),index:e}}readAttlistExp(t,e){let n=e=E(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let r=t.substring(n,e);for(b(r),n=e=E(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let s=t.substring(n,e);if(!b(s))throw new Error(`Invalid attribute name: "${s}"`);e=E(t,e);let i="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(i="NOTATION","("!==t[e=E(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let n=[];for(;e<t.length&&")"!==t[e];){const r=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;let s=t.substring(r,e);if(s=s.trim(),!b(s))throw new Error(`Invalid notation name: "${s}"`);n.push(s),"|"===t[e]&&(e++,e=E(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,i+=" ("+n.join("|")+")"}else{const n=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;i+=t.substring(n,e);const r=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!r.includes(i.toUpperCase()))throw new Error(`Invalid attribute type: "${i}"`)}e=E(t,e);let a="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(a="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(a="#IMPLIED",e+=7):[e,a]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:r,attributeName:s,attributeType:i,defaultValue:a,index:e}}}const E=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function y(t,e,n){for(let r=0;r<e.length;r++)if(e[r]!==t[n+r+1])return!1;return!0}function b(t){if(o(t))return t;throw new Error(`Invalid entity name ${t}`)}const w=/^[-+]?0x[a-fA-F0-9]+$/,_=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,v={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};const N=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class S{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){const e=this._matcher.path;if(0!==e.length)return e[e.length-1].values?.[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const n=e[e.length-1];return void 0!==n.values&&t in n.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map(t=>t.tag)}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class T{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new S(this)}push(t,e=null,n=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const r=this.path.length;this.siblingStacks[r]||(this.siblingStacks[r]=new Map);const s=this.siblingStacks[r],i=n?`${n}:${t}`:t,a=s.get(i)||0;let o=0;for(const t of s.values())o+=t;s.set(i,a+1);const l={tag:t,position:o,counter:a};null!=n&&(l.namespace=n),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){if(0!==this.path.length)return this.path[this.path.length-1].values?.[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const n=t||this.separator;if(n===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map(t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n);return this._pathStringCache=t,t}return this.path.map(t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag).join(n)}toArray(){return this.path.map(t=>t.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,n=t.length-1;for(;n>=0&&e>=0;){const r=t[n];if("deep-wildcard"===r.type){if(n--,n<0)return!0;const r=t[n];let s=!1;for(let t=e;t>=0;t--)if(this._matchSegment(r,this.path[t],t===this.path.length-1)){e=t-1,n--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(r,this.path[e],e===this.path.length-1))return!1;e--,n--}}return n<0}_matchSegment(t,e,n){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!n)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!n)return!1;const r=e.counter??0;if("first"===t.position&&0!==r)return!1;if("odd"===t.position&&r%2!=1)return!1;if("even"===t.position&&r%2!=0)return!1;if("nth"===t.position&&r!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map(t=>({...t})),siblingStacks:this.siblingStacks.map(t=>new Map(t))}}restore(t){this._pathStringCache=null,this.path=t.path.map(t=>({...t})),this.siblingStacks=t.siblingStacks.map(t=>new Map(t))}readOnly(){return this._view}}class A{constructor(t,e={},n){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=n,this._hasDeepWildcard=this.segments.some(t=>"deep-wildcard"===t.type),this._hasAttributeCondition=this.segments.some(t=>void 0!==t.attrName),this._hasPositionSelector=this.segments.some(t=>void 0!==t.position)}_parse(t){const e=[];let n=0,r="";for(;n<t.length;)t[n]===this.separator?n+1<t.length&&t[n+1]===this.separator?(r.trim()&&(e.push(this._parseSegment(r.trim())),r=""),e.push({type:"deep-wildcard"}),n+=2):(r.trim()&&e.push(this._parseSegment(r.trim())),r="",n++):(r+=t[n],n++);return r.trim()&&e.push(this._parseSegment(r.trim())),e}_parseSegment(t){const e={type:"tag"};let n=null,r=t;const s=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(r=s[1]+s[3],s[2])){const t=s[2].slice(1,-1);t&&(n=t)}let i,a,o=r;if(r.includes("::")){const e=r.indexOf("::");if(i=r.substring(0,e).trim(),o=r.substring(e+2).trim(),!i)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(o.includes(":")){const t=o.lastIndexOf(":"),e=o.substring(0,t).trim(),n=o.substring(t+1).trim();["first","last","odd","even"].includes(n)||/^nth\(\d+\)$/.test(n)?(a=e,l=n):a=o}else a=o;if(!a)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=a,i&&(e.namespace=i),n)if(n.includes("=")){const t=n.indexOf("=");e.attrName=n.substring(0,t).trim(),e.attrValue=n.substring(t+1).trim()}else e.attrName=n.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class C{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,n=t.segments[t.segments.length-1],r=n?.tag;if(r&&"*"!==r){const n=`${e}:${r}`;this._byDepthAndTag.has(n)||this._byDepthAndTag.set(n,[]),this._byDepthAndTag.get(n).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),n=`${e}:${t.getCurrentTag()}`,r=this._byDepthAndTag.get(n);if(r)for(let e=0;e<r.length;e++)if(t.matches(r[e]))return r[e];const s=this._wildcardByDepth.get(e);if(s)for(let e=0;e<s.length;e++)if(t.matches(s[e]))return s[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}const I={apos:{regex:/&(apos|#0*39|#x0*27);/g,val:"'"},gt:{regex:/&(gt|#0*62|#x0*3[Ee]);/g,val:">"},lt:{regex:/&(lt|#0*60|#x0*3[Cc]);/g,val:"<"},quot:{regex:/&(quot|#0*34|#x0*22);/g,val:'"'}},P=/&(amp|#0*38|#x0*26);/g,$=new Set("!?\\\\/[]$%{}^&*()<>|+");function O(t){for(const e of t)if($.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function D(t){return t.replace(/[.\-+*:]/g,"\\$&")}function M(t,e,n=!1){return!1===t||null===t?null:!0===t?e:void 0===t?n?e:null:"object"==typeof t?t:null}function L(t){const e=[];for(const n of Object.keys(t)){const r=t[n];if("object"==typeof r&&null!==r&&void 0!==r.val)e.push([n,{regex:r.regex??r.regx,val:r.val}]);else if("string"==typeof r){if(-1!==r.indexOf("&"))continue;O(n),e.push([n,{regex:new RegExp("&"+D(n)+";","g"),val:r}])}}return e}class k{constructor(t={}){var e;this._defaultTable=M(t.default,I,!0),this._systemTable=M(t.system,null,!1),this._ampEnabled=!1!==t.amp&&null!==t.amp,this._maxTotalExpansions=t.maxTotalExpansions||0,this._maxExpandedLength=t.maxExpandedLength||0,this._applyLimitsTo="all"===(e=t.applyLimitsTo??"external")?"all":"string"==typeof e?new Set([e]):Array.isArray(e)?new Set(e):new Set(["external"]),this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitExternal="all"===this._applyLimitsTo||this._applyLimitsTo instanceof Set&&this._applyLimitsTo.has("external"),this._limitSystem="all"===this._applyLimitsTo||this._applyLimitsTo instanceof Set&&this._applyLimitsTo.has("system"),this._limitDefault="all"===this._applyLimitsTo||this._applyLimitsTo instanceof Set&&this._applyLimitsTo.has("default"),this._defaultEntries=this._defaultTable?Object.entries(this._defaultTable):[],this._systemEntries=this._systemTable?Object.entries(this._systemTable):[],this._persistentEntries=[],this._inputEntries=[],this._totalExpansions=0,this._expandedLength=0}setExternalEntities(t){this._persistentEntries=L(t)}addExternalEntity(t,e){O(t),"string"==typeof e&&-1===e.indexOf("&")&&this._persistentEntries.push([t,{regex:new RegExp("&"+D(t)+";","g"),val:e}])}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputEntries=L(t)}reset(){this._inputEntries=[],this._totalExpansions=0,this._expandedLength=0}replace(t){if("string"!=typeof t||0===t.length)return t;if(-1===t.indexOf("&"))return t;const e=t;return this._persistentEntries.length>0&&(t=this._applyEntries(t,this._persistentEntries,this._limitExternal)),this._inputEntries.length>0&&-1!==t.indexOf("&")&&(t=this._applyEntries(t,this._inputEntries,this._limitExternal)),this._defaultEntries.length>0&&-1!==t.indexOf("&")&&(t=this._applyEntries(t,this._defaultEntries,this._limitDefault)),this._systemEntries.length>0&&-1!==t.indexOf("&")&&(t=this._applyEntries(t,this._systemEntries,this._limitSystem)),this._ampEnabled&&-1!==t.indexOf("&")&&(t=t.replace(P,"&")),this._postCheck(t,e)}parse(t){return this.replace(t)}_applyEntries(t,e,n){const r=n&&this._maxTotalExpansions>0,s=n&&this._maxExpandedLength>0,i=r||s;for(let n=0;n<e.length&&-1!==t.indexOf("&");n++){const a=e[n][1];if(i)if(r&&!s){let e=0;if(t=t.replace(a.regex,(...t)=>(e++,"function"==typeof a.val?a.val(...t):a.val)),e>0&&(this._totalExpansions+=e,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`)}else if(s&&!r){const e=t.length,n=(t=t.replace(a.regex,a.val)).length-e;if(n>0&&(this._expandedLength+=n,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}else{const e=t.length;let n=0;if(t=t.replace(a.regex,(...t)=>(n++,"function"==typeof a.val?a.val(...t):a.val)),n>0&&(this._totalExpansions+=n,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);const r=t.length-e;if(r>0&&(this._expandedLength+=r,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}else t=t.replace(a.regex,a.val)}return t}}const j={nbsp:{regex:/&(nbsp|#0*160|#x0*[Aa]0);/g,val:" "},copy:{regex:/&(copy|#0*169|#x0*[Aa]9);/g,val:"©"},reg:{regex:/&(reg|#0*174|#x0*[Aa][Ee]);/g,val:"®"},trade:{regex:/&(trade|#0*8482|#x0*2122);/g,val:"™"},mdash:{regex:/&(mdash|#0*8212|#x0*2014);/g,val:"—"},ndash:{regex:/&(ndash|#0*8211|#x0*2013);/g,val:"–"},hellip:{regex:/&(hellip|#0*8230|#x0*2026);/g,val:"…"},laquo:{regex:/&(laquo|#0*171|#x0*[Aa][Bb]);/g,val:"«"},raquo:{regex:/&(raquo|#0*187|#x0*[Bb][Bb]);/g,val:"»"},lsquo:{regex:/&(lsquo|#0*8216|#x0*2018);/g,val:"‘"},rsquo:{regex:/&(rsquo|#0*8217|#x0*2019);/g,val:"’"},ldquo:{regex:/&(ldquo|#0*8220|#x0*201[Cc]);/g,val:"“"},rdquo:{regex:/&(rdquo|#0*8221|#x0*201[Dd]);/g,val:"”"},bull:{regex:/&(bull|#0*8226|#x0*2022);/g,val:"•"},para:{regex:/&(para|#0*182|#x0*[Bb]6);/g,val:"¶"},sect:{regex:/&(sect|#0*167|#x0*[Aa]7);/g,val:"§"},deg:{regex:/&(deg|#0*176|#x0*[Bb]0);/g,val:"°"},frac12:{regex:/&(frac12|#0*189|#x0*[Bb][Dd]);/g,val:"½"},frac14:{regex:/&(frac14|#0*188|#x0*[Bb][Cc]);/g,val:"¼"},frac34:{regex:/&(frac34|#0*190|#x0*[Bb][Ee]);/g,val:"¾"},inr:{regex:/&(inr|#0*8377);/g,val:"₹"}},V={cent:{regex:/&(cent|#0*162|#x0*[Aa]2);/g,val:"¢"},pound:{regex:/&(pound|#0*163|#x0*[Aa]3);/g,val:"£"},yen:{regex:/&(yen|#0*165|#x0*[Aa]5);/g,val:"¥"},euro:{regex:/&(euro|#0*8364|#x0*20[Aa][Cc]);/g,val:"€"},inr:{regex:/&(inr|#0*8377|#x0*20[Bb]9);/g,val:"₹"},curren:{regex:/&(curren|#0*164|#x0*[Aa]4);/g,val:"¤"},fnof:{regex:/&(fnof|#0*402|#x0*192);/g,val:"ƒ"}},F={num_dec:{regex:/&#0*([0-9]{1,7});/g,val:(t,e)=>R(e,10,"&#")},num_hex:{regex:/&#x0*([0-9a-fA-F]{1,6});/g,val:(t,e)=>R(e,16,"&#x")}};function R(t,e,n){const r=Number.parseInt(t,e);return r>=0&&r<=1114111?String.fromCodePoint(r):n+t+";"}function U(t,e){if(!t)return{};const n=e.attributesGroupName?t[e.attributesGroupName]:t;if(!n)return{};const r={};for(const t in n)t.startsWith(e.attributeNamePrefix)?r[t.substring(e.attributeNamePrefix.length)]=n[t]:r[t]=n[t];return r}function B(t){if(!t||"string"!=typeof t)return;const e=t.indexOf(":");if(-1!==e&&e>0){const n=t.substring(0,e);if("xmlns"!==n)return n}}class W{constructor(t){var e;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=X,this.parseTextData=q,this.resolveNameSpace=Y,this.buildAttributesMap=G,this.isItStopNode=Q,this.replaceEntitiesValue=Z,this.readStopNodeData=nt,this.saveTextToParentTag=K,this.addChild=J,this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const n of e){if("string"==typeof n&&t===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0,this.entityReplacer=new k({default:!0,system:this.options.htmlEntities?{...j,...F,...V}:{},maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:"all"}),this.matcher=new T,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new C;const n=this.options.stopNodes;if(n&&n.length>0){for(let t=0;t<n.length;t++){const e=n[t];"string"==typeof e?this.stopNodeExpressionsSet.add(new A(e)):e instanceof A&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function q(t,e,n,r,s,i,a){const o=this.options;if(void 0!==t&&(o.trimValues&&!r&&(t=t.trim()),t.length>0)){a||(t=this.replaceEntitiesValue(t,e,n));const r=o.jPath?n.toString():n,l=o.tagValueProcessor(e,t,r,s,i);return null==l?t:typeof l!=typeof t||l!==t?l:o.trimValues||t.trim()===t?rt(t,o.parseTagValue,o.numberParseOptions):t}}function Y(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const z=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function G(t,e,n){const r=this.options;if(!0!==r.ignoreAttributes&&"string"==typeof t){const s=a(t,z),i=s.length,o={},l=new Array(i);let h=!1;const u={};for(let t=0;t<i;t++){const e=this.resolveNameSpace(s[t][1]),i=s[t][4];if(e.length&&void 0!==i){let s=i;r.trimValues&&(s=s.trim()),s=this.replaceEntitiesValue(s,n,this.readonlyMatcher),l[t]=s,u[e]=s,h=!0}}h&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(u);const c=r.jPath?e.toString():this.readonlyMatcher;let p=!1;for(let t=0;t<i;t++){const e=this.resolveNameSpace(s[t][1]);if(this.ignoreAttributesFn(e,c))continue;let n=r.attributeNamePrefix+e;if(e.length)if(r.transformAttributeName&&(n=r.transformAttributeName(n)),n=it(n,r),void 0!==s[t][4]){const s=l[t],i=r.attributeValueProcessor(e,s,c);o[n]=null==i?s:typeof i!=typeof s||i!==s?i:rt(s,r.parseAttributeValue,r.numberParseOptions),p=!0}else r.allowBooleanAttributes&&(o[n]=!0,p=!0)}if(!p)return;if(r.attributesGroupName){const t={};return t[r.attributesGroupName]=o,t}return o}}const X=function(t){t=t.replace(/\r\n?/g,"\n");const e=new m("!xml");let n=e,r="";this.matcher.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,i=new x(s.processEntities),a=t.length;for(let o=0;o<a;o++)if("<"===t[o]){const l=t.charCodeAt(o+1);if(47===l){const e=H(t,">",o,"Closing Tag is not closed.");let i=t.substring(o+2,e).trim();if(s.removeNSPrefix){const t=i.indexOf(":");-1!==t&&(i=i.substr(t+1))}i=st(s.transformTagName,i,"",s).tagName,n&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher));const a=this.matcher.getCurrentTag();if(i&&s.unpairedTagsSet.has(i))throw new Error(`Unpaired tag can not be used as closing tag: </${i}>`);a&&s.unpairedTagsSet.has(a)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,n=this.tagsNodeStack.pop(),r="",o=e}else if(63===l){let e=et(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(r=this.saveTextToParentTag(r,n,this.readonlyMatcher),s.ignoreDeclaration&&"?xml"===e.tagName||s.ignorePiTags);else{const t=new m(e.tagName);t.add(s.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName)),this.addChild(n,t,this.readonlyMatcher,o)}o=e.closeIndex+1}else if(33===l&&45===t.charCodeAt(o+2)&&45===t.charCodeAt(o+3)){const e=H(t,"--\x3e",o+4,"Comment is not closed.");if(s.commentPropName){const i=t.substring(o+4,e-2);r=this.saveTextToParentTag(r,n,this.readonlyMatcher),n.add(s.commentPropName,[{[s.textNodeName]:i}])}o=e}else if(33===l&&68===t.charCodeAt(o+2)){const e=i.readDocType(t,o);this.entityReplacer.addInputEntities(e.entities),o=e.i}else if(33===l&&91===t.charCodeAt(o+2)){const e=H(t,"]]>",o,"CDATA is not closed.")-2,i=t.substring(o+9,e);r=this.saveTextToParentTag(r,n,this.readonlyMatcher);let a=this.parseTextData(i,n.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==a&&(a=""),s.cdataPropName?n.add(s.cdataPropName,[{[s.textNodeName]:i}]):n.add(s.textNodeName,a),o=e+2}else{let i=et(t,o,s.removeNSPrefix);if(!i){const e=t.substring(Math.max(0,o-50),Math.min(a,o+50));throw new Error(`readTagExp returned undefined at position ${o}. Context: "${e}"`)}let l=i.tagName;const h=i.rawTagName;let u=i.tagExp,c=i.attrExpPresent,p=i.closeIndex;if(({tagName:l,tagExp:u}=st(s.transformTagName,l,u,s)),s.strictReservedNames&&(l===s.commentPropName||l===s.cdataPropName||l===s.textNodeName||l===s.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);n&&r&&"!xml"!==n.tagname&&(r=this.saveTextToParentTag(r,n,this.readonlyMatcher,!1));const d=n;d&&s.unpairedTagsSet.has(d.tagname)&&(n=this.tagsNodeStack.pop(),this.matcher.pop());let g=!1;u.length>0&&u.lastIndexOf("/")===u.length-1&&(g=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),u=l):u=u.substr(0,u.length-1),c=l!==u);let f,x=null,E={};f=B(h),l!==e.tagname&&this.matcher.push(l,{},f),l!==u&&c&&(x=this.buildAttributesMap(u,this.matcher,l),x&&(E=U(x,s))),l!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const y=o;if(this.isCurrentNodeStopNode){let e="";if(g)o=i.closeIndex;else if(s.unpairedTagsSet.has(l))o=i.closeIndex;else{const n=this.readStopNodeData(t,h,p+1);if(!n)throw new Error(`Unexpected end of ${h}`);o=n.i,e=n.tagContent}const r=new m(l);x&&(r[":@"]=x),r.add(s.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(n,r,this.readonlyMatcher,y)}else{if(g){({tagName:l,tagExp:u}=st(s.transformTagName,l,u,s));const t=new m(l);x&&(t[":@"]=x),this.addChild(n,t,this.readonlyMatcher,y),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(l)){const t=new m(l);x&&(t[":@"]=x),this.addChild(n,t,this.readonlyMatcher,y),this.matcher.pop(),this.isCurrentNodeStopNode=!1,o=i.closeIndex;continue}{const t=new m(l);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),x&&(t[":@"]=x),this.addChild(n,t,this.readonlyMatcher,y),n=t}}r="",o=p}}}else r+=t[o];return e.child};function J(t,e,n,r){this.options.captureMetaData||(r=void 0);const s=this.options.jPath?n.toString():n,i=this.options.updateTag(e.tagname,s,e[":@"]);!1===i||("string"==typeof i?(e.tagname=i,t.addChild(e,r)):t.addChild(e,r))}function Z(t,e,n){const r=this.options.processEntities;if(!r||!r.enabled)return t;if(r.allowedTags){const s=this.options.jPath?n.toString():n;if(!(Array.isArray(r.allowedTags)?r.allowedTags.includes(e):r.allowedTags(e,s)))return t}if(r.tagFilter){const s=this.options.jPath?n.toString():n;if(!r.tagFilter(e,s))return t}return this.entityReplacer.replace(t)}function K(t,e,n,r){return t&&(void 0===r&&(r=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,r))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Q(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function H(t,e,n,r){const s=t.indexOf(e,n);if(-1===s)throw new Error(r);return s+e.length-1}function tt(t,e,n,r){const s=t.indexOf(e,n);if(-1===s)throw new Error(r);return s}function et(t,e,n,r=">"){const s=function(t,e,n=">"){let r=0;const s=[],i=t.length,a=n.charCodeAt(0),o=n.length>1?n.charCodeAt(1):-1;for(let n=e;n<i;n++){const e=t.charCodeAt(n);if(r)e===r&&(r=0);else if(34===e||39===e)r=e;else if(e===a){if(-1===o)return{data:String.fromCharCode(...s),index:n};if(t.charCodeAt(n+1)===o)return{data:String.fromCharCode(...s),index:n}}else if(9===e){s.push(32);continue}s.push(e)}}(t,e+1,r);if(!s)return;let i=s.data;const a=s.index,o=i.search(/\s/);let l=i,h=!0;-1!==o&&(l=i.substring(0,o),i=i.substring(o+1).trimStart());const u=l;if(n){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),h=l!==s.data.substr(t+1))}return{tagName:l,tagExp:i,closeIndex:a,attrExpPresent:h,rawTagName:u}}function nt(t,e,n){const r=n;let s=1;const i=t.length;for(;n<i;n++)if("<"===t[n]){const i=t.charCodeAt(n+1);if(47===i){const i=tt(t,">",n,`${e} is not closed`);if(t.substring(n+2,i).trim()===e&&(s--,0===s))return{tagContent:t.substring(r,n),i};n=i}else if(63===i)n=H(t,"?>",n+1,"StopNode is not closed.");else if(33===i&&45===t.charCodeAt(n+2)&&45===t.charCodeAt(n+3))n=H(t,"--\x3e",n+3,"StopNode is not closed.");else if(33===i&&91===t.charCodeAt(n+2))n=H(t,"]]>",n,"StopNode is not closed.")-2;else{const r=et(t,n,">");r&&((r&&r.tagName)===e&&"/"!==r.tagExp[r.tagExp.length-1]&&s++,n=r.closeIndex)}}}function rt(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},v,e),!t||"string"!=typeof t)return t;let n=t.trim();if(0===n.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===n)return 0;if(e.hex&&w.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(isFinite(n)){if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const r=e.match(N);if(r){let s=r[1]||"";const i=-1===r[3].indexOf("e")?"E":"e",a=r[2],o=s?t[a.length+1]===i:t[a.length]===i;return a.length>1&&o?t:(1!==a.length||!r[3].startsWith(`.${i}`)&&r[3][0]!==i)&&a.length>0?n.leadingZeros&&!o?(e=(r[1]||"")+r[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=_.exec(n);if(s){const i=s[1]||"",a=s[2];let o=(r=s[3])&&-1!==r.indexOf(".")?("."===(r=r.replace(/0+$/,""))?r="0":"."===r[0]?r="0"+r:"."===r[r.length-1]&&(r=r.substring(0,r.length-1)),r):r;const l=i?"."===t[a.length+1]:"."===t[a.length];if(!e.leadingZeros&&(a.length>1||1===a.length&&!l))return t;{const r=Number(n),s=String(r);if(0===r)return r;if(-1!==s.search(/[eE]/))return e.eNotation?r:t;if(-1!==n.indexOf("."))return"0"===s||s===o||s===`${i}${o}`?r:t;let l=a?o:n;return a?l===s||i+l===s?r:t:l===s||l===i+s?r:t}}return t}}var r;return function(t,e,n){const r=e===1/0;switch(n.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return r?"Infinity":"-Infinity";default:return t}}(t,Number(n),e)}(t,n)}return void 0!==t?t:""}function st(t,e,n,r){if(t){const r=t(e);n===e&&(n=r),e=r}return{tagName:e=it(e,r),tagExp:n}}function it(t,e){if(h.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return l.includes(t)?e.onDangerousProperty(t):t}const at=m.getMetaDataSymbol();function ot(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const n={};for(const r in t)r.startsWith(e)?n[r.substring(e.length)]=t[r]:n[r]=t[r];return n}function lt(t,e,n,r){return ht(t,e,n,r)}function ht(t,e,n,r){let s;const i={};for(let a=0;a<t.length;a++){const o=t[a],l=ut(o);if(void 0!==l&&l!==e.textNodeName){const t=ot(o[":@"]||{},e.attributeNamePrefix);n.push(l,t)}if(l===e.textNodeName)void 0===s?s=o[l]:s+=""+o[l];else{if(void 0===l)continue;if(o[l]){let t=ht(o[l],e,n,r);const s=pt(t,e);if(o[":@"]?ct(t,o[":@"],r,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==o[at]&&"object"==typeof t&&null!==t&&(t[at]=o[at]),void 0!==i[l]&&Object.prototype.hasOwnProperty.call(i,l))Array.isArray(i[l])||(i[l]=[i[l]]),i[l].push(t);else{const n=e.jPath?r.toString():r;e.isArray(l,n,s)?i[l]=[t]:i[l]=t}void 0!==l&&l!==e.textNodeName&&n.pop()}}}return"string"==typeof s?s.length>0&&(i[e.textNodeName]=s):void 0!==s&&(i[e.textNodeName]=s),i}function ut(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const n=e[t];if(":@"!==n)return n}}function ct(t,e,n,r){if(e){const s=Object.keys(e),i=s.length;for(let a=0;a<i;a++){const i=s[a],o=i.startsWith(r.attributeNamePrefix)?i.substring(r.attributeNamePrefix.length):i,l=r.jPath?n.toString()+"."+o:n;r.isArray(i,l,!0,!0)?t[i]=[e[i]]:t[i]=e[i]}}}function pt(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return 0===r||!(1!==r||!t[n]&&"boolean"!=typeof t[n]&&0!==t[n])}const dt={allowBooleanAttributes:!1,unpairedTags:[]};function gt(t,e){e=Object.assign({},dt,e);const n=[];let r=!1,s=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let i=0;i<t.length;i++)if("<"===t[i]&&"?"===t[i+1]){if(i+=2,i=mt(t,i),i.err)return i}else{if("<"!==t[i]){if(ft(t[i]))continue;return Nt("InvalidChar","char '"+t[i]+"' is not expected.",At(t,i))}{let a=i;if(i++,"!"===t[i]){i=xt(t,i);continue}{let o=!1;"/"===t[i]&&(o=!0,i++);let l="";for(;i<t.length&&">"!==t[i]&&" "!==t[i]&&"\t"!==t[i]&&"\n"!==t[i]&&"\r"!==t[i];i++)l+=t[i];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),i--),!Tt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Nt("InvalidTag",e,At(t,i))}const h=bt(t,i);if(!1===h)return Nt("InvalidAttr","Attributes for '"+l+"' have open quote.",At(t,i));let u=h.value;if(i=h.index,"/"===u[u.length-1]){const n=i-u.length;u=u.substring(0,u.length-1);const s=_t(u,e);if(!0!==s)return Nt(s.err.code,s.err.msg,At(t,n+s.err.line));r=!0}else if(o){if(!h.tagClosed)return Nt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",At(t,i));if(u.trim().length>0)return Nt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",At(t,a));if(0===n.length)return Nt("InvalidTag","Closing tag '"+l+"' has not been opened.",At(t,a));{const e=n.pop();if(l!==e.tagName){let n=At(t,e.tagStartPos);return Nt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+l+"'.",At(t,a))}0==n.length&&(s=!0)}}else{const o=_t(u,e);if(!0!==o)return Nt(o.err.code,o.err.msg,At(t,i-u.length+o.err.line));if(!0===s)return Nt("InvalidXml","Multiple possible root nodes found.",At(t,i));-1!==e.unpairedTags.indexOf(l)||n.push({tagName:l,tagStartPos:a}),r=!0}for(i++;i<t.length;i++)if("<"===t[i]){if("!"===t[i+1]){i++,i=xt(t,i);continue}if("?"!==t[i+1])break;if(i=mt(t,++i),i.err)return i}else if("&"===t[i]){const e=vt(t,i);if(-1==e)return Nt("InvalidChar","char '&' is not expected.",At(t,i));i=e}else if(!0===s&&!ft(t[i]))return Nt("InvalidXml","Extra text at the end",At(t,i));"<"===t[i]&&i--}}}return r?1==n.length?Nt("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",At(t,n[0].tagStartPos)):!(n.length>0)||Nt("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Nt("InvalidXml","Start tag expected.",1)}function ft(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function mt(t,e){const n=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const r=t.substr(n,e-n);if(e>5&&"xml"===r)return Nt("InvalidXml","XML declaration allowed only at the start of the document.",At(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function xt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e<t.length;e++)if("<"===t[e])n++;else if(">"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const Et='"',yt="'";function bt(t,e){let n="",r="",s=!1;for(;e<t.length;e++){if(t[e]===Et||t[e]===yt)""===r?r=t[e]:r!==t[e]||(r="");else if(">"===t[e]&&""===r){s=!0;break}n+=t[e]}return""===r&&{value:n,index:e,tagClosed:s}}const wt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function _t(t,e){const n=a(t,wt),r={};for(let t=0;t<n.length;t++){if(0===n[t][1].length)return Nt("InvalidAttr","Attribute '"+n[t][2]+"' has no space in starting.",Ct(n[t]));if(void 0!==n[t][3]&&void 0===n[t][4])return Nt("InvalidAttr","Attribute '"+n[t][2]+"' is without value.",Ct(n[t]));if(void 0===n[t][3]&&!e.allowBooleanAttributes)return Nt("InvalidAttr","boolean attribute '"+n[t][2]+"' is not allowed.",Ct(n[t]));const s=n[t][2];if(!St(s))return Nt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Ct(n[t]));if(Object.prototype.hasOwnProperty.call(r,s))return Nt("InvalidAttr","Attribute '"+s+"' is repeated.",Ct(n[t]));r[s]=1}return!0}function vt(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let n=/\d/;for("x"===t[e]&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(n))break}return-1}(t,++e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(";"===t[e])break;return-1}return e}function Nt(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function St(t){return o(t)}function Tt(t){return o(t)}function At(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function Ct(t){return t.startIndex+t[1].length}const It={validate:gt},Pt=new class{constructor(t){this.externalEntities={},this.options=g(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const n=gt(t,e);if(!0!==n)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}const n=new W(this.options);n.entityReplacer.setExternalEntities(this.externalEntities);const r=n.parseXml(t);return this.options.preserveOrder||void 0===r?r:lt(r,this.options,n.matcher,n.readonlyMatcher)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return m.getMetaDataSymbol()}},$t=t=>{const e=It.validate(t);if(!0!==e)throw new Error(e.err.msg);const n=Pt.parse(t),s=n.urlset?.url||[];return(Array.isArray(s)?s:[s]).filter(t=>t.loc).map(t=>({path:r(t.loc).pathname,lastmod:t.lastmod?new Date(t.lastmod).toISOString():null}))},Ot={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"};function Dt(t){if(/^\d{4}-\d{2}-\d{2}$/.test(t))return new Date(t).toISOString();let e=/^\w{3} (\w{3}) (\d{2}) (\d{4}) ([\d:]{8}) GMT([\-+]\d{4})$/.exec(t);return e?new Date(`${e[3]}-${Ot[e[1]]}-${e[2]}T${e[4]}${e[5]}`).toISOString():t}const Mt=t=>{const e={};for(const[n,s]of Object.entries(t))n.endsWith("@TypeHint")||Array.isArray(s)&&0===s.length||("true"===s?e[n]=!0:"false"===s?e[n]=!1:"gcAltLanguagePeer"===n?(e[n]=s,e.peer=r(s).pathname):e[n]="string"==typeof s?Dt(s.trim()):s);return Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{})},Lt={normalize:r,request:async(t,e={})=>{const r=await fetch(new URL(t,n),{signal:AbortSignal.timeout(3e4),...e});if(!r.ok){const t=new Error(`${r.status} ${r.statusText}`);throw t.status=r.status,t}return{data:await r.text(),status:r.status,statusText:r.statusText,headers:r.headers}},children:async t=>{const e=r(t);e.pathname+=".sitemap.xml",e.searchParams.set("_",Date.now());const n=await fetch(e,{signal:AbortSignal.timeout(3e4),redirect:"error"});if(!n.ok){const t=new Error(`${n.status} ${n.statusText}`);throw t.status=n.status,t}const s=await n.text();return{data:$t(s),status:n.status,statusText:n.statusText,headers:n.headers}},content:async t=>{const e=r(t);e.pathname+=".html",e.searchParams.set("_",Date.now());const n=await fetch(e,{signal:AbortSignal.timeout(1e4),redirect:"error"});if(!n.ok){const t=new Error(`${n.status} ${n.statusText}`);throw t.status=n.status,t}return{data:await n.text(),status:n.status,statusText:n.statusText,headers:n.headers}},meta:async t=>{const e=r(t);e.pathname+="/_jcr_content.json",e.searchParams.set("_",Date.now());const n=await fetch(e,{signal:AbortSignal.timeout(1e4),redirect:"error"});if(!n.ok){const t=new Error(`${n.status} ${n.statusText}`);throw t.status=n.status,t}const s=await n.json();return{data:Mt(s),status:n.status,statusText:n.statusText,headers:n.headers}}};return e})());
package/package.json CHANGED
@@ -1,37 +1,46 @@
1
- {
2
- "name": "canada-api",
3
- "version": "5.0.0",
4
- "description": "Cross platform API to fetch data from canada.ca",
5
- "browser": "dist/ca.js",
6
- "main": "src/index.mjs",
7
- "scripts": {
8
- "test": "node --test tests/**/*.test.mjs",
9
- "build": "webpack",
10
- "dev": "webpack --mode development"
11
- },
12
- "repository": {
13
- "type": "git",
14
- "url": "https://github.com/dnd-mdn/canada-api.git"
15
- },
16
- "keywords": [
17
- "canada",
18
- "api",
19
- "fetch"
20
- ],
21
- "author": "National Defence",
22
- "license": "MIT",
23
- "homepage": "https://github.com/dnd-mdn/canada-api#readme",
24
- "bugs": "https://github.com/dnd-mdn/canada-api/issues",
25
- "files": [
26
- "src",
27
- "dist"
28
- ],
29
- "devDependencies": {
30
- "webpack": "^5.105.4",
31
- "webpack-cli": "^7.0.2"
32
- },
33
- "dependencies": {
34
- "axios": "^1.13.6",
35
- "fast-xml-parser": "^5.5.6"
36
- }
37
- }
1
+ {
2
+ "name": "canada-api",
3
+ "version": "5.1.0",
4
+ "description": "Cross platform API to fetch data from canada.ca",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "browser": "dist/ca.js",
8
+ "exports": {
9
+ ".": {
10
+ "browser": "./dist/ca.js",
11
+ "default": "./src/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "src",
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test tests/**/*.test.js",
20
+ "build": "webpack",
21
+ "dev": "webpack --mode development"
22
+ },
23
+ "author": "National Defence",
24
+ "license": "MIT",
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "keywords": [
29
+ "canada",
30
+ "api",
31
+ "fetch"
32
+ ],
33
+ "homepage": "https://github.com/dnd-mdn/canada-api#readme",
34
+ "bugs": "https://github.com/dnd-mdn/canada-api/issues",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/dnd-mdn/canada-api.git"
38
+ },
39
+ "dependencies": {
40
+ "fast-xml-parser": "^5.6.0"
41
+ },
42
+ "devDependencies": {
43
+ "webpack": "^5.105.4",
44
+ "webpack-cli": "^7.0.2"
45
+ }
46
+ }
@@ -0,0 +1,64 @@
1
+ import { XMLParser, XMLValidator } from "fast-xml-parser";
2
+ import normalize from "./normalize.js";
3
+
4
+ const parser = new XMLParser();
5
+
6
+ /**
7
+ * Represents a single URL entry from a sitemap
8
+ * @typedef {object} SitemapEntry
9
+ * @property {string} path - The normalized URL path (e.g., '/en/page')
10
+ * @property {string|null} lastmod - ISO 8601 timestamp or null if not present
11
+ */
12
+
13
+ /**
14
+ * Parse XML sitemap data into structured URL entries
15
+ * @param {string} data - Raw XML sitemap content
16
+ * @returns {SitemapEntry[]} Array of sitemap entries with path and lastmod. Entries missing a `<loc>` element are skipped.
17
+ * @throws {Error} If the XML is malformed or invalid
18
+ */
19
+ export const parseSitemap = (data) => {
20
+ const validation = XMLValidator.validate(data);
21
+ if (validation !== true) throw new Error(validation.err.msg);
22
+
23
+ const result = parser.parse(data);
24
+
25
+ const urls = result.urlset?.url || [];
26
+ return (Array.isArray(urls) ? urls : [urls]).filter(item => item.loc).map(item => ({
27
+ path: normalize(item.loc).pathname,
28
+ lastmod: item.lastmod ? new Date(item.lastmod).toISOString() : null
29
+ }));
30
+ };
31
+
32
+ /**
33
+ * Fetch and parse sitemap children for a canada.ca page
34
+ * @param {string|URL} url - Absolute or relative URL
35
+ * @returns {Promise<{data: SitemapEntry[], status: number, statusText: string, headers: Headers}>}
36
+ * @throws {Error} If the request fails or returns a non-2xx status
37
+ */
38
+ const children = async (url) => {
39
+ const target = normalize(url);
40
+ target.pathname += '.sitemap.xml';
41
+ target.searchParams.set('_', Date.now());
42
+
43
+ const response = await fetch(target, {
44
+ signal: AbortSignal.timeout(30000),
45
+ redirect: 'error'
46
+ });
47
+
48
+ if (!response.ok) {
49
+ const error = new Error(`${response.status} ${response.statusText}`);
50
+ error.status = response.status;
51
+ throw error;
52
+ }
53
+
54
+ const text = await response.text();
55
+
56
+ return {
57
+ data: parseSitemap(text),
58
+ status: response.status,
59
+ statusText: response.statusText,
60
+ headers: response.headers
61
+ };
62
+ };
63
+
64
+ export default children;
package/src/content.js ADDED
@@ -0,0 +1,35 @@
1
+ import normalize from "./normalize.js";
2
+
3
+ /**
4
+ * Fetch HTML content for a canada.ca page
5
+ * @param {string|URL} url - Absolute or relative URL
6
+ * @returns {Promise<{data: string, status: number, statusText: string, headers: Headers}>}
7
+ * @throws {Error} If the request fails or returns a non-2xx status
8
+ */
9
+ const content = async (url) => {
10
+ const target = normalize(url);
11
+ target.pathname += '.html';
12
+ target.searchParams.set('_', Date.now());
13
+
14
+ const response = await fetch(target, {
15
+ signal: AbortSignal.timeout(10000),
16
+ redirect: 'error'
17
+ });
18
+
19
+ if (!response.ok) {
20
+ const error = new Error(`${response.status} ${response.statusText}`);
21
+ error.status = response.status;
22
+ throw error;
23
+ }
24
+
25
+ const data = await response.text();
26
+
27
+ return {
28
+ data,
29
+ status: response.status,
30
+ statusText: response.statusText,
31
+ headers: response.headers
32
+ };
33
+ };
34
+
35
+ export default content;
package/src/index.js ADDED
@@ -0,0 +1,25 @@
1
+ import normalize from "./normalize.js";
2
+ import request from "./request.js";
3
+ import children from "./children.js";
4
+ import content from "./content.js";
5
+ import meta from "./meta.js";
6
+
7
+ /**
8
+ * @typedef {object} CanadaAPI
9
+ * @property {function} normalize - Normalize and validate canada.ca URLs
10
+ * @property {function} request - Raw HTTP client for canada.ca requests
11
+ * @property {function} children - Fetch and parse sitemap hierarchies
12
+ * @property {function} content - Fetch HTML content pages
13
+ * @property {function} meta - Fetch and format JCR metadata
14
+ */
15
+
16
+ /** @type {CanadaAPI} */
17
+ const ca = {
18
+ normalize,
19
+ request,
20
+ children,
21
+ content,
22
+ meta
23
+ }
24
+
25
+ export default ca
@@ -1,117 +1,114 @@
1
- import axios from "axios";
2
- import normalize from "./normalize.mjs";
3
- import { BASE_URL } from "./config.mjs";
4
-
5
- /**
6
- * Axios instance configured for fetching JCR metadata
7
- * @type {import('axios').AxiosInstance}
8
- * @description Returns formatted metadata
9
- */
10
- const meta = axios.create({
11
- baseURL: BASE_URL,
12
- timeout: 5000,
13
- maxRedirects: 0
14
- });
15
-
16
- // Transform URL
17
- meta.interceptors.request.use(config => {
18
- const url = normalize(config.url);
19
-
20
- url.pathname = url.pathname + '/_jcr_content.json';
21
- url.searchParams.set('_', Date.now());
22
-
23
- config.url = url.toString();
24
- return config;
25
- }, error => {
26
- return Promise.reject(error);
27
- });
28
-
29
- // Process response data
30
- meta.interceptors.response.use(response => {
31
- response.data = formatMeta(response.data);
32
-
33
- return response;
34
- }, error => {
35
- return Promise.reject(error);
36
- });
37
-
38
- /**
39
- * Month name to number mapping
40
- * @const {Record<string, string>}
41
- * @private
42
- */
43
- const months = {
44
- 'Jan': '01',
45
- 'Feb': '02',
46
- 'Mar': '03',
47
- 'Apr': '04',
48
- 'May': '05',
49
- 'Jun': '06',
50
- 'Jul': '07',
51
- 'Aug': '08',
52
- 'Sep': '09',
53
- 'Oct': '10',
54
- 'Nov': '11',
55
- 'Dec': '12'
56
- }
57
-
58
- /**
59
- * Try to parse and format date strings from JCR into ISO 8601
60
- * @param {string} text - Potential date string to format
61
- * @returns {string} ISO 8601 timestamp or original text if not a recognized date
62
- * @description Supports YYYY-MM-DD and JCR date format (e.g. "Wed Nov 20 2019 13:17:13 GMT-0500").
63
- * Uses explicit parsing to ensure consistent output across Node.js and browsers.
64
- * @private
65
- */
66
- function formatDate(text) {
67
- // Simple YYYY-MM-DD format
68
- if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
69
- return new Date(text).toISOString()
70
- }
71
-
72
- // RFC1123 format
73
- let m = /^\w{3} (\w{3}) (\d{2}) (\d{4}) ([\d:]{8}) GMT([\-+]\d{4})$/.exec(text)
74
- if (m) {
75
- return new Date(`${m[3]}-${months[m[1]]}-${m[2]}T${m[4]}${m[5]}`).toISOString()
76
- }
77
-
78
- return text
79
- }
80
-
81
- /**
82
- * Format and normalize metadata object
83
- * @param {Record<string, any>} data - Raw metadata object from JCR
84
- * @returns {Record<string, any>} Formatted metadata with normalized types and sorted keys
85
- * @description Converts string booleans to native booleans, formats dates to ISO 8601,
86
- * removes @TypeHint properties and empty arrays, sorts keys alphabetically, and adds a
87
- * normalized `peer` field when `gcAltLanguagePeer` is present.
88
- */
89
- export const formatMeta = (data) => {
90
- const result = {}
91
-
92
- for (const [key, value] of Object.entries(data)) {
93
- if (key.endsWith('@TypeHint')) continue
94
- if (Array.isArray(value) && value.length === 0) continue
95
-
96
- if (value === 'true') {
97
- result[key] = true
98
- } else if (value === 'false') {
99
- result[key] = false
100
- } else if (key === 'gcAltLanguagePeer') {
101
- result[key] = value
102
- result['peer'] = normalize(value).pathname
103
- } else if (typeof value === 'string') {
104
- result[key] = formatDate(value.trim())
105
- } else {
106
- result[key] = value
107
- }
108
- }
109
-
110
- // Sort object keys alphabetically for readability
111
- return Object.keys(result).sort().reduce((obj, key) => {
112
- obj[key] = result[key]
113
- return obj
114
- }, {})
115
- }
116
-
117
- export default meta;
1
+ import normalize from "./normalize.js";
2
+
3
+ /**
4
+ * Month name to number mapping
5
+ * @const {Record<string, string>}
6
+ * @private
7
+ */
8
+ const months = {
9
+ 'Jan': '01',
10
+ 'Feb': '02',
11
+ 'Mar': '03',
12
+ 'Apr': '04',
13
+ 'May': '05',
14
+ 'Jun': '06',
15
+ 'Jul': '07',
16
+ 'Aug': '08',
17
+ 'Sep': '09',
18
+ 'Oct': '10',
19
+ 'Nov': '11',
20
+ 'Dec': '12'
21
+ }
22
+
23
+ /**
24
+ * Try to parse and format date strings from JCR into ISO 8601
25
+ * @param {string} text - Potential date string to format
26
+ * @returns {string} ISO 8601 timestamp or original text if not a recognized date
27
+ * @description Supports YYYY-MM-DD and JCR date format (e.g. "Wed Nov 20 2019 13:17:13 GMT-0500").
28
+ * Uses explicit parsing to ensure consistent output across Node.js and browsers.
29
+ * @private
30
+ */
31
+ function formatDate(text) {
32
+ // Simple YYYY-MM-DD format
33
+ if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
34
+ return new Date(text).toISOString()
35
+ }
36
+
37
+ // RFC1123 format
38
+ let m = /^\w{3} (\w{3}) (\d{2}) (\d{4}) ([\d:]{8}) GMT([\-+]\d{4})$/.exec(text)
39
+ if (m) {
40
+ return new Date(`${m[3]}-${months[m[1]]}-${m[2]}T${m[4]}${m[5]}`).toISOString()
41
+ }
42
+
43
+ return text
44
+ }
45
+
46
+ /**
47
+ * Format and normalize metadata object
48
+ * @param {Record<string, any>} data - Raw metadata object from JCR
49
+ * @returns {Record<string, any>} Formatted metadata with normalized types and sorted keys
50
+ * @description Converts string booleans to native booleans, formats dates to ISO 8601,
51
+ * removes @TypeHint properties and empty arrays, sorts keys alphabetically, and adds a
52
+ * normalized `peer` field when `gcAltLanguagePeer` is present.
53
+ */
54
+ export const formatMeta = (data) => {
55
+ const result = {}
56
+
57
+ for (const [key, value] of Object.entries(data)) {
58
+ if (key.endsWith('@TypeHint')) continue
59
+ if (Array.isArray(value) && value.length === 0) continue
60
+
61
+ if (value === 'true') {
62
+ result[key] = true
63
+ } else if (value === 'false') {
64
+ result[key] = false
65
+ } else if (key === 'gcAltLanguagePeer') {
66
+ result[key] = value
67
+ result['peer'] = normalize(value).pathname
68
+ } else if (typeof value === 'string') {
69
+ result[key] = formatDate(value.trim())
70
+ } else {
71
+ result[key] = value
72
+ }
73
+ }
74
+
75
+ // Sort object keys alphabetically for readability
76
+ return Object.keys(result).sort().reduce((obj, key) => {
77
+ obj[key] = result[key]
78
+ return obj
79
+ }, {})
80
+ }
81
+
82
+ /**
83
+ * Fetch and format JCR metadata for a canada.ca page
84
+ * @param {string|URL} url - Absolute or relative URL
85
+ * @returns {Promise<{data: Record<string, any>, status: number, statusText: string, headers: Headers}>}
86
+ * @throws {Error} If the request fails or returns a non-2xx status
87
+ */
88
+ const meta = async (url) => {
89
+ const target = normalize(url);
90
+ target.pathname += '/_jcr_content.json';
91
+ target.searchParams.set('_', Date.now());
92
+
93
+ const response = await fetch(target, {
94
+ signal: AbortSignal.timeout(10000),
95
+ redirect: 'error'
96
+ });
97
+
98
+ if (!response.ok) {
99
+ const error = new Error(`${response.status} ${response.statusText}`);
100
+ error.status = response.status;
101
+ throw error;
102
+ }
103
+
104
+ const data = await response.json();
105
+
106
+ return {
107
+ data: formatMeta(data),
108
+ status: response.status,
109
+ statusText: response.statusText,
110
+ headers: response.headers
111
+ };
112
+ };
113
+
114
+ export default meta;
@@ -1,37 +1,39 @@
1
-
2
- import { BASE_URL } from './config.mjs';
3
-
4
- /**
5
- * Normalize a canada.ca URL to a clean pathname
6
- * @param {string|URL} url - A full URL or relative path (e.g., 'https://www.canada.ca/en/page' or '/en/page')
7
- * @returns {URL} Normalized URL object with cleaned pathname
8
- * @throws {TypeError} If url is not a string or URL object
9
- * @throws {Error} If URL is not from canada.ca or path doesn't start with /en/ or /fr/
10
- */
11
- const normalize = (url) => {
12
-
13
- if (typeof url === 'string') {
14
- url = new URL(url, BASE_URL)
15
- } else if (!(url instanceof URL)) {
16
- throw new TypeError('string or URL object expected')
17
- }
18
-
19
- // Verify domain
20
- if (url.origin !== BASE_URL) {
21
- throw new Error('URL must start with ' + BASE_URL)
22
- }
23
-
24
- url.pathname = url.pathname.replace(/^\/content\/canadasite/, '');
25
-
26
- // Remove file extensions (like .html, .xml) and trailing slashes
27
- url.pathname = url.pathname.replace(/\.[^/]*$/, '').replace(/\/+$/, '');
28
-
29
- // Verify root language
30
- if (!url.pathname.startsWith('/en/') && !url.pathname.startsWith('/fr/')) {
31
- throw new Error(`Invalid path: "${url.pathname}" must start with /en/ or /fr/`)
32
- }
33
-
34
- return url
35
- }
36
-
1
+
2
+ import { BASE_URL } from './config.js';
3
+
4
+ /**
5
+ * Normalize a canada.ca URL to a clean pathname
6
+ * @param {string|URL} url - A full URL or relative path (e.g., 'https://www.canada.ca/en/page' or '/en/page')
7
+ * @returns {URL} Normalized URL object with cleaned pathname
8
+ * @throws {TypeError} If url is not a string or URL object
9
+ * @throws {Error} If URL is not from canada.ca or path doesn't start with /en/ or /fr/
10
+ */
11
+ const normalize = (url) => {
12
+
13
+ if (typeof url === 'string') {
14
+ url = new URL(url, BASE_URL)
15
+ } else if (url instanceof URL) {
16
+ url = new URL(url.href)
17
+ } else {
18
+ throw new TypeError('string or URL object expected')
19
+ }
20
+
21
+ // Verify domain
22
+ if (url.origin !== BASE_URL) {
23
+ throw new Error('URL must start with ' + BASE_URL)
24
+ }
25
+
26
+ url.pathname = url.pathname.replace(/^\/content\/canadasite/, '');
27
+
28
+ // Remove file extensions (like .html, .xml) and trailing slashes
29
+ url.pathname = url.pathname.replace(/\.[^/]*$/, '').replace(/\/+$/, '');
30
+
31
+ // Verify root language
32
+ if (!url.pathname.startsWith('/en/') && !url.pathname.startsWith('/fr/')) {
33
+ throw new Error(`Invalid path: "${url.pathname}" must start with /en/ or /fr/`)
34
+ }
35
+
36
+ return url
37
+ }
38
+
37
39
  export default normalize;
package/src/request.js ADDED
@@ -0,0 +1,32 @@
1
+ import { BASE_URL } from "./config.js";
2
+
3
+ /**
4
+ * Raw HTTP client for canada.ca
5
+ * @param {string|URL} url - Relative or absolute URL on canada.ca
6
+ * @param {RequestInit} [options] - Fetch options
7
+ * @returns {Promise<{data: string, status: number, statusText: string, headers: Headers}>}
8
+ * @throws {Error} If the request fails or returns a non-2xx status
9
+ */
10
+ const request = async (url, options = {}) => {
11
+ const response = await fetch(new URL(url, BASE_URL), {
12
+ signal: AbortSignal.timeout(30000),
13
+ ...options
14
+ });
15
+
16
+ if (!response.ok) {
17
+ const error = new Error(`${response.status} ${response.statusText}`);
18
+ error.status = response.status;
19
+ throw error;
20
+ }
21
+
22
+ const data = await response.text();
23
+
24
+ return {
25
+ data,
26
+ status: response.status,
27
+ statusText: response.statusText,
28
+ headers: response.headers
29
+ };
30
+ };
31
+
32
+ export default request;
package/src/children.mjs DELETED
@@ -1,68 +0,0 @@
1
- import axios from "axios";
2
- import { XMLParser, XMLValidator } from "fast-xml-parser";
3
- import normalize from "./normalize.mjs";
4
- import { BASE_URL } from "./config.mjs";
5
-
6
- /**
7
- * Axios instance configured for fetching sitemap URLs
8
- * @type {import('axios').AxiosInstance}
9
- * @description Returns normalized node list of sitemap children
10
- */
11
- const children = axios.create({
12
- baseURL: BASE_URL,
13
- timeout: 30000,
14
- maxRedirects: 0
15
- });
16
-
17
- // Transform URL
18
- children.interceptors.request.use(config => {
19
- const url = normalize(config.url);
20
-
21
- url.pathname = url.pathname + '.sitemap.xml';
22
- url.searchParams.set('_', Date.now());
23
-
24
- config.url = url.toString();
25
- return config;
26
- }, error => {
27
- return Promise.reject(error);
28
- });
29
-
30
- // Process response data
31
- children.interceptors.response.use(response => {
32
- response.data = parseSitemap(response.data);
33
-
34
- return response;
35
- }, error => {
36
- return Promise.reject(error);
37
- });
38
-
39
- /**
40
- * Represents a single URL entry from a sitemap
41
- * @typedef {object} SitemapEntry
42
- * @property {string} path - The normalized URL path (e.g., '/en/page')
43
- * @property {string|null} lastmod - ISO 8601 timestamp or null if not present
44
- */
45
-
46
- /**
47
- * Parse XML sitemap data into structured URL entries
48
- * @param {string} data - Raw XML sitemap content
49
- * @returns {SitemapEntry[]} Array of sitemap entries with path and lastmod
50
- * @throws {Error} If the XML is malformed or invalid
51
- * @description Parses XML sitemap format and returns normalized entries with ISO timestamps.
52
- * Entries missing a `<loc>` element are silently skipped.
53
- */
54
- export const parseSitemap = (data) => {
55
- const validation = XMLValidator.validate(data);
56
- if (validation !== true) throw new Error(validation.err.msg);
57
-
58
- const parser = new XMLParser();
59
- const result = parser.parse(data);
60
-
61
- const urls = result.urlset?.url || [];
62
- return (Array.isArray(urls) ? urls : [urls]).filter(item => item.loc).map(item => ({
63
- path: normalize(item.loc).pathname,
64
- lastmod: item.lastmod ? new Date(item.lastmod).toISOString() : null
65
- }));
66
- };
67
-
68
- export default children;
package/src/content.mjs DELETED
@@ -1,29 +0,0 @@
1
- import axios from "axios";
2
- import normalize from "./normalize.mjs";
3
- import { BASE_URL } from "./config.mjs";
4
-
5
- /**
6
- * Axios instance configured for fetching HTML content
7
- * @type {import('axios').AxiosInstance}
8
- * @description Returns raw HTML content
9
- */
10
- const content = axios.create({
11
- baseURL: BASE_URL,
12
- timeout: 5000,
13
- maxRedirects: 0
14
- });
15
-
16
- // Transform URL
17
- content.interceptors.request.use(config => {
18
- const url = normalize(config.url);
19
-
20
- url.pathname = url.pathname + '.html';
21
- url.searchParams.set('_', Date.now());
22
-
23
- config.url = url.toString();
24
- return config;
25
- }, error => {
26
- return Promise.reject(error);
27
- });
28
-
29
- export default content;
package/src/index.mjs DELETED
@@ -1,25 +0,0 @@
1
- import normalize from "./normalize.mjs";
2
- import request from "./request.mjs";
3
- import children from "./children.mjs";
4
- import content from "./content.mjs";
5
- import meta from "./meta.mjs";
6
-
7
- /**
8
- * Canada API - Cross-platform client for fetching and parsing canada.ca data
9
- *
10
- * @typedef {object} CanadaAPI
11
- * @property {function} normalize - Normalize and validate canada.ca URLs
12
- * @property {import('axios').AxiosInstance} request - Raw HTTP client for canada.ca requests
13
- * @property {import('axios').AxiosInstance} children - Fetch and parse sitemap hierarchies
14
- * @property {import('axios').AxiosInstance} content - Fetch HTML content pages
15
- * @property {import('axios').AxiosInstance} meta - Fetch and format JCR metadata
16
- */
17
- const ca = {
18
- normalize,
19
- request,
20
- children,
21
- content,
22
- meta
23
- }
24
-
25
- export default ca
package/src/request.mjs DELETED
@@ -1,14 +0,0 @@
1
- import axios from "axios";
2
- import { BASE_URL } from "./config.mjs";
3
-
4
- /**
5
- * Axios instance configured for raw requests to canada.ca
6
- * @type {import('axios').AxiosInstance}
7
- * @description Base HTTP client for making raw requests.
8
- */
9
- const request = axios.create({
10
- baseURL: BASE_URL,
11
- timeout: 30000
12
- });
13
-
14
- export default request;
File without changes