eth-graph-query 2.0.15 → 2.0.21

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,146 +1,135 @@
1
- <h1>
2
- eth-graph-query
3
- </h1>
1
+ # eth-graph-query
4
2
 
5
- Simple package for creating query to [the GraphQL](https://thegraph.com/).
3
+ A lightweight and flexible library for building [The Graph (GraphQL)](https://thegraph.com/) queries using simple JSON objects. Eliminate the need for complex string concatenation and maintain type-safe queries.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/eth-graph-query.svg)](https://www.npmjs.com/package/eth-graph-query)
6
+ [![license](https://img.shields.io/npm/l/eth-graph-query.svg)](https://github.com/phamhongphuc1999/eth-graph-query/blob/main/LICENSE)
6
7
 
7
8
  ---
8
9
 
9
- ### Installation
10
+ ## 🚀 Features
10
11
 
11
- ```shell
12
- npm install eth-graph-query
12
+ - **JSON to GraphQL**: Convert nested JSON structures into valid GraphQL query strings.
13
+ - **Multiple Collections**: Query multiple collections in a single HTTP request.
14
+ - **Deep Nesting**: Support for nested collection queries and entity relationships.
15
+ - **Advanced Filtering**: Full support for The Graph's operators (`_gt`, `_in`, `_contains`, etc.) via `$` prefix.
16
+ - **Inline Fragments**: Support for GraphQL inline fragments (`... on Type`).
17
+ - **TypeScript First**: Full type definitions for parameters, filters, and metadata.
18
+ - **Metadata Support**: Easily fetch subgraph metadata (`_meta`).
13
19
 
14
- ```
20
+ ---
15
21
 
16
- - Or if you use `yarn`
22
+ ## 📦 Installation
17
23
 
18
24
  ```shell
25
+ # npm
26
+ npm install eth-graph-query
27
+
28
+ # yarn
19
29
  yarn add eth-graph-query
30
+
31
+ # bun
32
+ bun install eth-graph-query
20
33
  ```
21
34
 
22
35
  ---
23
36
 
24
- ### Usage
37
+ ## 💡 Usage
25
38
 
26
- - The first thing you have to do is to create a query instance
39
+ ### 1. Initialize the Client
27
40
 
28
- ```js
29
- const query = new EthGraphQuery(root);
30
- ```
31
-
32
- - This package has three query options. Simply, you can create a direct string query
41
+ ```typescript
42
+ import { EthGraphQuery } from 'eth-graph-query';
33
43
 
34
- ```js
35
- result = await query.stringQuery(`query query {
36
- collection1(first: 10) {
37
- element1
38
- element2
39
- }
40
- }`);
44
+ const rootUrl = 'https://api.thegraph.com/subgraphs/name/username/subgraph-name';
45
+ const client = new EthGraphQuery(rootUrl);
41
46
  ```
42
47
 
43
- - More readable, you can create a single json query
48
+ ### 2. Single Collection Query
44
49
 
45
- ```js
46
- const result = await query.query({
47
- collection: 'collection1',
50
+ ```typescript
51
+ const result = await client.query({
52
+ collection: 'users',
48
53
  params: {
49
- elements: ['element1', 'element2'],
54
+ elements: ['id', 'name', 'balance'],
55
+ where: { balance: { $gt: '1000' } },
50
56
  first: 10,
57
+ orderBy: 'balance',
58
+ orderDirection: 'desc',
51
59
  },
52
60
  });
53
61
  ```
54
62
 
55
- - You can create a multiple json queries
63
+ ### 3. Multiple Collections Query
56
64
 
57
- ```js
58
- const result = await query.multipleQuery([
65
+ Fetch data from multiple collections in a single round-trip.
66
+
67
+ ```typescript
68
+ const result = await client.multipleQuery([
59
69
  {
60
- collection: 'collection1',
61
- params: {
62
- elements: ['element11', 'element12'],
63
- },
70
+ collection: 'tokens',
71
+ params: { elements: ['id', 'symbol'], first: 5 },
64
72
  },
65
73
  {
66
- collection: 'collection2',
67
- params: {
68
- elements: ['element21', 'element22'],
69
- },
74
+ collection: 'factories',
75
+ params: { elements: ['id', 'poolCount'] },
70
76
  },
71
77
  ]);
72
78
  ```
73
79
 
74
- - You can create a complex query
80
+ ### 4. Advanced Nested Query & Filters
75
81
 
76
- ```js
77
- const result = await query.multipleQuery([
78
- {
79
- collection: 'collection1',
80
- params: {
81
- elements: ['element11', 'element12'],
82
- where: { element11: 'abc' },
83
- },
84
- },
85
- {
86
- collection: 'collection2',
87
- params: {
88
- elements: [
89
- 'element21',
90
- {
91
- collection: 'collection3',
92
- params: {
93
- elements: ['element31'],
94
- where: {
95
- id: { $in: ['123'] },
96
- token_: { setId: { $in: ['1', 2, true] } },
97
- element31: 'element31',
98
- },
99
- first: 50,
82
+ Build complex queries with nested collections and operators.
83
+
84
+ ```typescript
85
+ const result = await client.query({
86
+ collection: 'pools',
87
+ params: {
88
+ elements: [
89
+ 'id',
90
+ 'token0',
91
+ {
92
+ collection: 'swaps',
93
+ params: {
94
+ elements: ['amount0', 'amount1', 'timestamp'],
95
+ where: {
96
+ amount0: { $gt: 0 },
97
+ timestamp: { $gte: 1672531200 },
100
98
  },
99
+ first: 50,
101
100
  },
102
- ],
103
- where: {
104
- element21: '123',
105
- collection3: { element31: '123' },
106
101
  },
107
- inlineFragments: [
108
- {
109
- collection: 'BridgeDepositTransaction',
110
- params: { elements: ['id', 'l1Token'] },
111
- },
112
- {
113
- collection: 'NameSignalTransaction',
114
- params: { elements: ['id', 'timestamp'] },
115
- },
116
- ],
102
+ ],
103
+ where: {
104
+ id: { $in: ['0x123...', '0x456...'] },
117
105
  },
118
106
  },
119
- ]);
107
+ });
120
108
  ```
121
109
 
122
110
  ---
123
111
 
124
- ### API
112
+ ## 📘 API Reference
125
113
 
126
- Read the [API Docs](https://github.com/phamhongphuc1999/eth-graph-query/blob/main/documents/api.md), you also read my [examples](https://github.com/phamhongphuc1999/eth-graph-query/blob/main/examples)
114
+ Documentation for all functions and types can be found in the [API Docs](https://github.com/phamhongphuc1999/eth-graph-query/blob/main/documents/api.md).
127
115
 
128
116
  ---
129
117
 
130
- ### For developer
118
+ ## 🛠 For Developers
131
119
 
132
- - Run example
120
+ ### Run Tests
133
121
 
134
122
  ```shell
135
- npm run example example/file-name
123
+ npm run test
136
124
  ```
137
125
 
138
- - Run test
126
+ ---
139
127
 
140
- ```shell
141
- npm run test
142
- ```
128
+ ## 📜 License
129
+
130
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
143
131
 
144
- ### Reference
132
+ ## 🔗 References
145
133
 
146
- - https://spec.graphql.org
134
+ - [The Graph Documentation](https://thegraph.com/docs/)
135
+ - [GraphQL Specification](https://spec.graphql.org)
package/dist/index.cjs CHANGED
@@ -1,6 +1 @@
1
- "use strict";var qe=Object.defineProperty;var Qe=(e,t,n)=>t in e?qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var D=(e,t,n)=>(Qe(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Ee(e,t){return function(){return e.apply(t,arguments)}}const{toString:Je}=Object.prototype,{getPrototypeOf:te}=Object,M=(e=>t=>{const n=Je.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),R=e=>(e=e.toLowerCase(),t=>M(t)===e),q=e=>t=>typeof t===e,{isArray:F}=Array,C=q("undefined");function ze(e){return e!==null&&!C(e)&&e.constructor!==null&&!C(e.constructor)&&g(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Se=R("ArrayBuffer");function Ve(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Se(e.buffer),t}const We=q("string"),g=q("function"),ge=q("number"),Q=e=>e!==null&&typeof e=="object",Ke=e=>e===!0||e===!1,L=e=>{if(M(e)!=="object")return!1;const t=te(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Ge=R("Date"),ve=R("File"),Xe=R("Blob"),Ze=R("FileList"),Ye=e=>Q(e)&&g(e.pipe),et=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||g(e.append)&&((t=M(e))==="formdata"||t==="object"&&g(e.toString)&&e.toString()==="[object FormData]"))},tt=R("URLSearchParams"),nt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function B(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),F(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(r=0;r<i;r++)c=o[r],t.call(null,e[c],c,e)}}function Oe(e,t){t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const Re=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ae=e=>!C(e)&&e!==Re;function v(){const{caseless:e}=Ae(this)&&this||{},t={},n=(r,s)=>{const o=e&&Oe(t,s)||s;L(t[o])&&L(r)?t[o]=v(t[o],r):L(r)?t[o]=v({},r):F(r)?t[o]=r.slice():t[o]=r};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&B(arguments[r],n);return t}const rt=(e,t,n,{allOwnKeys:r}={})=>(B(t,(s,o)=>{n&&g(s)?e[o]=Ee(s,n):e[o]=s},{allOwnKeys:r}),e),st=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ot=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},it=(e,t,n,r)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!r||r(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&te(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},at=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},ct=e=>{if(!e)return null;if(F(e))return e;let t=e.length;if(!ge(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},lt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&te(Uint8Array)),ut=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},ft=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},dt=R("HTMLFormElement"),ht=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),ae=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),pt=R("RegExp"),Te=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};B(n,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(r[o]=i||s)}),Object.defineProperties(e,r)},mt=e=>{Te(e,(t,n)=>{if(g(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(g(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},yt=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return F(e)?r(e):r(String(e).split(t)),n},bt=()=>{},wt=(e,t)=>(e=+e,Number.isFinite(e)?e:t),V="abcdefghijklmnopqrstuvwxyz",ce="0123456789",_e={DIGIT:ce,ALPHA:V,ALPHA_DIGIT:V+V.toUpperCase()+ce},Et=(e=16,t=_e.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function St(e){return!!(e&&g(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const gt=e=>{const t=new Array(10),n=(r,s)=>{if(Q(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[s]=r;const o=F(r)?[]:{};return B(r,(i,c)=>{const d=n(i,s+1);!C(d)&&(o[c]=d)}),t[s]=void 0,o}}return r};return n(e,0)},Ot=R("AsyncFunction"),Rt=e=>e&&(Q(e)||g(e))&&g(e.then)&&g(e.catch),a={isArray:F,isArrayBuffer:Se,isBuffer:ze,isFormData:et,isArrayBufferView:Ve,isString:We,isNumber:ge,isBoolean:Ke,isObject:Q,isPlainObject:L,isUndefined:C,isDate:Ge,isFile:ve,isBlob:Xe,isRegExp:pt,isFunction:g,isStream:Ye,isURLSearchParams:tt,isTypedArray:lt,isFileList:Ze,forEach:B,merge:v,extend:rt,trim:nt,stripBOM:st,inherits:ot,toFlatObject:it,kindOf:M,kindOfTest:R,endsWith:at,toArray:ct,forEachEntry:ut,matchAll:ft,isHTMLForm:dt,hasOwnProperty:ae,hasOwnProp:ae,reduceDescriptors:Te,freezeMethods:mt,toObjectSet:yt,toCamelCase:ht,noop:bt,toFiniteNumber:wt,findKey:Oe,global:Re,isContextDefined:Ae,ALPHABET:_e,generateString:Et,isSpecCompliantForm:St,toJSONObject:gt,isAsyncFn:Ot,isThenable:Rt};function m(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s)}a.inherits(m,Error,{toJSON:function(){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:a.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const Ne=m.prototype,xe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{xe[e]={value:e}});Object.defineProperties(m,xe);Object.defineProperty(Ne,"isAxiosError",{value:!0});m.from=(e,t,n,r,s,o)=>{const i=Object.create(Ne);return a.toFlatObject(e,i,function(d){return d!==Error.prototype},c=>c!=="isAxiosError"),m.call(i,e.message,t,n,r,s),i.cause=e,i.name=e.name,o&&Object.assign(i,o),i};const At=null;function X(e){return a.isPlainObject(e)||a.isArray(e)}function Fe(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function le(e,t,n){return e?e.concat(t).map(function(s,o){return s=Fe(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function Tt(e){return a.isArray(e)&&!e.some(X)}const _t=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function J(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(p,w){return!a.isUndefined(w[p])});const r=n.metaTokens,s=n.visitor||u,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function f(h){if(h===null)return"";if(a.isDate(h))return h.toISOString();if(!d&&a.isBlob(h))throw new m("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(h)||a.isTypedArray(h)?d&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function u(h,p,w){let E=h;if(h&&!w&&typeof h=="object"){if(a.endsWith(p,"{}"))p=r?p:p.slice(0,-2),h=JSON.stringify(h);else if(a.isArray(h)&&Tt(h)||(a.isFileList(h)||a.endsWith(p,"[]"))&&(E=a.toArray(h)))return p=Fe(p),E.forEach(function(_,Me){!(a.isUndefined(_)||_===null)&&t.append(i===!0?le([p],Me,o):i===null?p:p+"[]",f(_))}),!1}return X(h)?!0:(t.append(le(w,p,o),f(h)),!1)}const l=[],b=Object.assign(_t,{defaultVisitor:u,convertValue:f,isVisitable:X});function S(h,p){if(!a.isUndefined(h)){if(l.indexOf(h)!==-1)throw Error("Circular reference detected in "+p.join("."));l.push(h),a.forEach(h,function(E,T){(!(a.isUndefined(E)||E===null)&&s.call(t,E,a.isString(T)?T.trim():T,p,b))===!0&&S(E,p?p.concat(T):[T])}),l.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return S(e),t}function ue(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function ne(e,t){this._pairs=[],e&&J(e,this,t)}const Pe=ne.prototype;Pe.append=function(t,n){this._pairs.push([t,n])};Pe.toString=function(t){const n=t?function(r){return t.call(this,r,ue)}:ue;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Nt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ke(e,t,n){if(!t)return e;const r=n&&n.encode||Nt,s=n&&n.serialize;let o;if(s?o=s(t,n):o=a.isURLSearchParams(t)?t.toString():new ne(t,n).toString(r),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class fe{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Ce={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},xt=typeof URLSearchParams<"u"?URLSearchParams:ne,Ft=typeof FormData<"u"?FormData:null,Pt=typeof Blob<"u"?Blob:null,kt={isBrowser:!0,classes:{URLSearchParams:xt,FormData:Ft,Blob:Pt},protocols:["http","https","file","blob","url","data"]},Be=typeof window<"u"&&typeof document<"u",Ct=(e=>Be&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),Bt=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",jt=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Be,hasStandardBrowserEnv:Ct,hasStandardBrowserWebWorkerEnv:Bt},Symbol.toStringTag,{value:"Module"})),O={...jt,...kt};function Dt(e,t){return J(e,new O.classes.URLSearchParams,Object.assign({visitor:function(n,r,s,o){return O.isNode&&a.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}function $t(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Lt(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],t[o]=e[o];return t}function je(e){function t(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(s)?s.length:i,d?(a.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(n,r,s[i],o)&&a.isArray(s[i])&&(s[i]=Lt(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t($t(r),s,n,0)}),n}return null}function Ut(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const re={transitional:Ce,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(je(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Dt(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return J(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Ut(t)):t}],transformResponse:[function(t){const n=this.transitional||re.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(t&&a.isString(t)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t)}catch(c){if(i)throw c.name==="SyntaxError"?m.from(c,m.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:O.classes.FormData,Blob:O.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{re.headers[e]={}});const se=re,Ht=a.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"]),It=e=>{const t={};let n,r,s;return e&&e.split(`
2
- `).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||t[n]&&Ht[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},de=Symbol("internals");function P(e){return e&&String(e).trim().toLowerCase()}function U(e){return e===!1||e==null?e:a.isArray(e)?e.map(U):String(e)}function Mt(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const qt=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function W(e,t,n,r,s){if(a.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!a.isString(t)){if(a.isString(r))return t.indexOf(r)!==-1;if(a.isRegExp(r))return r.test(t)}}function Qt(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Jt(e,t){const n=a.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,i){return this[r].call(this,t,s,o,i)},configurable:!0})})}class z{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(c,d,f){const u=P(d);if(!u)throw new Error("header name must be a non-empty string");const l=a.findKey(s,u);(!l||s[l]===void 0||f===!0||f===void 0&&s[l]!==!1)&&(s[l||d]=U(c))}const i=(c,d)=>a.forEach(c,(f,u)=>o(f,u,d));return a.isPlainObject(t)||t instanceof this.constructor?i(t,n):a.isString(t)&&(t=t.trim())&&!qt(t)?i(It(t),n):t!=null&&o(n,t,r),this}get(t,n){if(t=P(t),t){const r=a.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return Mt(s);if(a.isFunction(n))return n.call(this,s,r);if(a.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=P(t),t){const r=a.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||W(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(i){if(i=P(i),i){const c=a.findKey(r,i);c&&(!n||W(r,r[c],c,n))&&(delete r[c],s=!0)}}return a.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||W(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return a.forEach(this,(s,o)=>{const i=a.findKey(r,o);if(i){n[i]=U(s),delete n[o];return}const c=t?Qt(o):String(o).trim();c!==o&&delete n[o],n[c]=U(s),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return a.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&a.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
3
- `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[de]=this[de]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=P(i);r[c]||(Jt(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}}z.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(z.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(z);const A=z;function K(e,t){const n=this||se,r=t||n,s=A.from(r.headers);let o=r.data;return a.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function De(e){return!!(e&&e.__CANCEL__)}function j(e,t,n){m.call(this,e??"canceled",m.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(j,m,{__CANCEL__:!0});function zt(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new m("Request failed with status code "+n.status,[m.ERR_BAD_REQUEST,m.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Vt=O.hasStandardBrowserEnv?{write(e,t,n,r,s,o){const i=[e+"="+encodeURIComponent(t)];a.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),a.isString(r)&&i.push("path="+r),a.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Wt(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Kt(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function $e(e,t){return e&&!Wt(t)?Kt(e,t):t}const Gt=O.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function s(o){let i=o;return t&&(n.setAttribute("href",i),i=n.href),n.setAttribute("href",i),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=s(window.location.href),function(i){const c=a.isString(i)?s(i):i;return c.protocol===r.protocol&&c.host===r.host}}():function(){return function(){return!0}}();function vt(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Xt(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const f=Date.now(),u=r[o];i||(i=f),n[s]=d,r[s]=f;let l=o,b=0;for(;l!==s;)b+=n[l++],l=l%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),f-i<t)return;const S=u&&f-u;return S?Math.round(b*1e3/S):void 0}}function he(e,t){let n=0;const r=Xt(50,250);return s=>{const o=s.loaded,i=s.lengthComputable?s.total:void 0,c=o-n,d=r(c),f=o<=i;n=o;const u={loaded:o,total:i,progress:i?o/i:void 0,bytes:c,rate:d||void 0,estimated:d&&i&&f?(i-o)/d:void 0,event:s};u[t?"download":"upload"]=!0,e(u)}}const Zt=typeof XMLHttpRequest<"u",Yt=Zt&&function(e){return new Promise(function(n,r){let s=e.data;const o=A.from(e.headers).normalize();let{responseType:i,withXSRFToken:c}=e,d;function f(){e.cancelToken&&e.cancelToken.unsubscribe(d),e.signal&&e.signal.removeEventListener("abort",d)}let u;if(a.isFormData(s)){if(O.hasStandardBrowserEnv||O.hasStandardBrowserWebWorkerEnv)o.setContentType(!1);else if((u=o.getContentType())!==!1){const[p,...w]=u?u.split(";").map(E=>E.trim()).filter(Boolean):[];o.setContentType([p||"multipart/form-data",...w].join("; "))}}let l=new XMLHttpRequest;if(e.auth){const p=e.auth.username||"",w=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.set("Authorization","Basic "+btoa(p+":"+w))}const b=$e(e.baseURL,e.url);l.open(e.method.toUpperCase(),ke(b,e.params,e.paramsSerializer),!0),l.timeout=e.timeout;function S(){if(!l)return;const p=A.from("getAllResponseHeaders"in l&&l.getAllResponseHeaders()),E={data:!i||i==="text"||i==="json"?l.responseText:l.response,status:l.status,statusText:l.statusText,headers:p,config:e,request:l};zt(function(_){n(_),f()},function(_){r(_),f()},E),l=null}if("onloadend"in l?l.onloadend=S:l.onreadystatechange=function(){!l||l.readyState!==4||l.status===0&&!(l.responseURL&&l.responseURL.indexOf("file:")===0)||setTimeout(S)},l.onabort=function(){l&&(r(new m("Request aborted",m.ECONNABORTED,e,l)),l=null)},l.onerror=function(){r(new m("Network Error",m.ERR_NETWORK,e,l)),l=null},l.ontimeout=function(){let w=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const E=e.transitional||Ce;e.timeoutErrorMessage&&(w=e.timeoutErrorMessage),r(new m(w,E.clarifyTimeoutError?m.ETIMEDOUT:m.ECONNABORTED,e,l)),l=null},O.hasStandardBrowserEnv&&(c&&a.isFunction(c)&&(c=c(e)),c||c!==!1&&Gt(b))){const p=e.xsrfHeaderName&&e.xsrfCookieName&&Vt.read(e.xsrfCookieName);p&&o.set(e.xsrfHeaderName,p)}s===void 0&&o.setContentType(null),"setRequestHeader"in l&&a.forEach(o.toJSON(),function(w,E){l.setRequestHeader(E,w)}),a.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),i&&i!=="json"&&(l.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&l.addEventListener("progress",he(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&l.upload&&l.upload.addEventListener("progress",he(e.onUploadProgress)),(e.cancelToken||e.signal)&&(d=p=>{l&&(r(!p||p.type?new j(null,e,l):p),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(d),e.signal&&(e.signal.aborted?d():e.signal.addEventListener("abort",d)));const h=vt(b);if(h&&O.protocols.indexOf(h)===-1){r(new m("Unsupported protocol "+h+":",m.ERR_BAD_REQUEST,e));return}l.send(s||null)})},Z={http:At,xhr:Yt};a.forEach(Z,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const pe=e=>`- ${e}`,en=e=>a.isFunction(e)||e===null||e===!1,Le={getAdapter:e=>{e=a.isArray(e)?e:[e];const{length:t}=e;let n,r;const s={};for(let o=0;o<t;o++){n=e[o];let i;if(r=n,!en(n)&&(r=Z[(i=String(n)).toLowerCase()],r===void 0))throw new m(`Unknown adapter '${i}'`);if(r)break;s[i||"#"+o]=r}if(!r){const o=Object.entries(s).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let i=t?o.length>1?`since :
4
- `+o.map(pe).join(`
5
- `):" "+pe(o[0]):"as no adapter specified";throw new m("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return r},adapters:Z};function G(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new j(null,e)}function me(e){return G(e),e.headers=A.from(e.headers),e.data=K.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Le.getAdapter(e.adapter||se.adapter)(e).then(function(r){return G(e),r.data=K.call(e,e.transformResponse,r),r.headers=A.from(r.headers),r},function(r){return De(r)||(G(e),r&&r.response&&(r.response.data=K.call(e,e.transformResponse,r.response),r.response.headers=A.from(r.response.headers))),Promise.reject(r)})}const ye=e=>e instanceof A?{...e}:e;function x(e,t){t=t||{};const n={};function r(f,u,l){return a.isPlainObject(f)&&a.isPlainObject(u)?a.merge.call({caseless:l},f,u):a.isPlainObject(u)?a.merge({},u):a.isArray(u)?u.slice():u}function s(f,u,l){if(a.isUndefined(u)){if(!a.isUndefined(f))return r(void 0,f,l)}else return r(f,u,l)}function o(f,u){if(!a.isUndefined(u))return r(void 0,u)}function i(f,u){if(a.isUndefined(u)){if(!a.isUndefined(f))return r(void 0,f)}else return r(void 0,u)}function c(f,u,l){if(l in t)return r(f,u);if(l in e)return r(void 0,f)}const d={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(f,u)=>s(ye(f),ye(u),!0)};return a.forEach(Object.keys(Object.assign({},e,t)),function(u){const l=d[u]||s,b=l(e[u],t[u],u);a.isUndefined(b)&&l!==c||(n[u]=b)}),n}const Ue="1.6.8",oe={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{oe[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const be={};oe.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Ue+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,c)=>{if(t===!1)throw new m(s(i," has been removed"+(n?" in "+n:"")),m.ERR_DEPRECATED);return n&&!be[i]&&(be[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,i,c):!0}};function tn(e,t,n){if(typeof e!="object")throw new m("options must be an object",m.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],i=t[o];if(i){const c=e[o],d=c===void 0||i(c,o,e);if(d!==!0)throw new m("option "+o+" must be "+d,m.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new m("Unknown option "+o,m.ERR_BAD_OPTION)}}const Y={assertOptions:tn,validators:oe},N=Y.validators;class I{constructor(t){this.defaults=t,this.interceptors={request:new fe,response:new fe}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s;Error.captureStackTrace?Error.captureStackTrace(s={}):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
6
- `+o):r.stack=o}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=x(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Y.assertOptions(r,{silentJSONParsing:N.transitional(N.boolean),forcedJSONParsing:N.transitional(N.boolean),clarifyTimeoutError:N.transitional(N.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:Y.assertOptions(s,{encode:N.function,serialize:N.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],h=>{delete o[h]}),n.headers=A.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(n)===!1||(d=d&&p.synchronous,c.unshift(p.fulfilled,p.rejected))});const f=[];this.interceptors.response.forEach(function(p){f.push(p.fulfilled,p.rejected)});let u,l=0,b;if(!d){const h=[me.bind(this),void 0];for(h.unshift.apply(h,c),h.push.apply(h,f),b=h.length,u=Promise.resolve(n);l<b;)u=u.then(h[l++],h[l++]);return u}b=c.length;let S=n;for(l=0;l<b;){const h=c[l++],p=c[l++];try{S=h(S)}catch(w){p.call(this,w);break}}try{u=me.call(this,S)}catch(h){return Promise.reject(h)}for(l=0,b=f.length;l<b;)u=u.then(f[l++],f[l++]);return u}getUri(t){t=x(this.defaults,t);const n=$e(t.baseURL,t.url);return ke(n,t.params,t.paramsSerializer)}}a.forEach(["delete","get","head","options"],function(t){I.prototype[t]=function(n,r){return this.request(x(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(x(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}I.prototype[t]=n(),I.prototype[t+"Form"]=n(!0)});const H=I;class ie{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new j(o,i,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ie(function(s){t=s}),cancel:t}}}const nn=ie;function rn(e){return function(n){return e.apply(null,n)}}function sn(e){return a.isObject(e)&&e.isAxiosError===!0}const ee={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};Object.entries(ee).forEach(([e,t])=>{ee[t]=e});const on=ee;function He(e){const t=new H(e),n=Ee(H.prototype.request,t);return a.extend(n,H.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return He(x(e,s))},n}const y=He(se);y.Axios=H;y.CanceledError=j;y.CancelToken=nn;y.isCancel=De;y.VERSION=Ue;y.toFormData=J;y.AxiosError=m;y.Cancel=y.CanceledError;y.all=function(t){return Promise.all(t)};y.spread=rn;y.isAxiosError=sn;y.mergeConfig=x;y.AxiosHeaders=A;y.formToJSON=e=>je(a.isHTMLForm(e)?new FormData(e):e);y.getAdapter=Le.getAdapter;y.HttpStatusCode=on;y.default=y;const we={Accept:"application/json","Content-Type":"application/json"};function $(e){return e.data}class an{constructor(t,n){D(this,"root");D(this,"config");var r;this.root=t,n?(this.config=n,(r=this.config)!=null&&r.headers||(this.config.headers={}),this.config.headers={...this.config.headers,...we}):this.config={headers:we}}async get(t,n){return await y.get(`${this.root}${t}`,{...n,...this.config}).then($)}async post(t,n,r){return await y.post(`${this.root}${t}`,n,{...r,...this.config}).then($)}async put(t,n,r){return await y.put(`${this.root}${t}`,n,{...r,...this.config}).then($)}async del(t,n){return await y.delete(`${this.root}${t}`,{...n,...this.config}).then($)}}const Ie=["contains","contains_nocase","ends_with","end_with_nocase","starts_with","starts_with_nocase","not_contains","not_contains_nocase","not_ends_with","not_ends_with_nocase","not_starts_with","not_starts_with_nocase","gt","gte","lt","lte","not","in","not_in"];class k{static buildJsonQuery(t){const n=[];for(const r in t)if(t[r]!==void 0)if(t[r]===null&&n.push(`${r}: null`),Array.isArray(t[r])){const s=t[r];n.push(`${r}: [${s.map(o=>`"${o}"`).join(", ")}]`)}else if(typeof t[r]=="string")n.push(`${r}: "${t[r]}"`);else if(typeof t[r]=="object"){const s={},o={},i=t[r];for(const c in i){const d=i[c];if(c.length==1)s[c]=d;else if(c[0]=="$"){const f=c.slice(1);Ie.includes(f)&&(o[`${r}_${f}`]=d)}else s[c]=d}Object.keys(s).length>0&&n.push(`${r}: {${this.buildJsonQuery(s)}}`),Object.keys(o).length>0&&n.push(this.buildJsonQuery(o))}else n.push(`${r}: ${t[r]}`);return n.join(", ")}static buildElements(t){const n=[];for(const r of t)if(typeof r=="string")n.push(r);else{const s=r;n.push(this.buildQuery({collection:s.collection,params:s.params}))}return n}static buildMetadata(t){let n="";const r=[];t.blockQuery&&(t.blockQuery.hash&&r.push(`hash: "${t.blockQuery.hash}"`),t.blockQuery.number&&r.push(`number: ${t.blockQuery.number}`),t.blockQuery.number_gte&&r.push(`number_gte: ${t.blockQuery.number_gte}`));const s=r.join(", ");s.length>0&&(n+=`(block: {${s}})`);const o=[],i=[];if(t.elements){for(const f of t.elements)if(f=="deployment"||f=="hasIndexingErrors"){const u=f.toString();o.includes(u)||o.push(u)}else{const u=f.toString();i.includes(u)||i.push(u)}const c=i.join(" ");c.length>0&&o.push(`block{${c}}`);const d=o.join(" ");d.length>0&&(n+=`{${d}}`)}return n.length>0?`_meta${n}`:""}static _buildInlineFragment(t){var r;let n=["id"];return(r=t.params)!=null&&r.elements&&(n=this.buildElements(t.params.elements)),`... on ${t.collection}{${n.join(" ")}}`}static buildInlineFragments(t){const n=[];for(const r of t)n.push(this._buildInlineFragment(r));return n.join(" ")}static buildQuery(t,n){const r=t.collection,s=t.params,o=[];if((s==null?void 0:s.id)!=null&&o.push(`id: ${s.id}`),s!=null&&s.orderBy&&o.push(`orderBy: ${s.orderBy}`),s!=null&&s.orderDirection&&o.push(`orderDirection: ${s.orderDirection}`),(s==null?void 0:s.first)!=null&&(s.first<0?s.first=0:s.first>1e3&&(s.first=1e3),o.push(`first: ${s.first}`)),(s==null?void 0:s.skip)!=null&&(s.skip<0?s.skip=0:s.skip>5e3&&(s.skip=5e3),o.push(`skip: ${s.skip}`)),s!=null&&s.where){const l=this.buildJsonQuery(s.where);l.length>0&&o.push(`where: {${l}}`)}if(s!=null&&s.block){const l=this.buildJsonQuery(s.block);l.length>0&&o.push(`block: {${l}}`)}const i=o.join(", ");let c=["id"];s!=null&&s.elements&&s.elements.length>0&&(c=this.buildElements(s.elements));let d="";s!=null&&s.inlineFragments&&s.inlineFragments.length>0&&(d=this.buildInlineFragments(s.inlineFragments));let f="";const u=d.length>0?`${c.join(" ")} ${d}`:c.join(" ");if(i.length>0?f=`${r}(${i}) {${u}}`:f=`${r} {${u}}`,n){const l=this.buildMetadata(n);return l.length>0?`${l} ${f}`:f}return f}static buildMultipleQuery(t,n){const r=[];for(const o of t)r.push(this.buildQuery({collection:o.collection,params:o.params}));const s=r.join(" ");if(n){const o=this.buildMetadata(n);return o.length>0?`${o} ${s}`:s}return s}static makeFullQuery(t,n="query"){return`query ${n} {${t}}`}}class cn extends an{constructor(n,r){super(n,r);D(this,"queryName");this.queryName="query"}async stringQuery(n){const r=await this.post("",{query:n});if(r.errors){const s=r;throw new Error(s.errors[0].message)}return r}async query(n,r){const s=n,o=k.buildQuery({collection:s.collection,params:s.params},r);return await this.stringQuery(k.makeFullQuery(o,this.queryName))}async multipleQuery(n,r){const s=k.buildMultipleQuery(n,r);return await this.stringQuery(k.makeFullQuery(s,this.queryName))}}exports.EthGraphQuery=cn;exports.OptionKeys=Ie;exports.QueryBuilder=k;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("axios"),f={Accept:"application/json","Content-Type":"application/json"};function d(h){return h.data}class b{root;config;constructor(t,e={}){this.root=t,this.config={...e,headers:{...f,...e.headers||{}}}}async request(t,e,r,s){const n=`${this.root}${e}`,i={...this.config,...s},c=await(t==="get"||t==="delete"?y[t](n,i):y[t](n,r,i));return d(c)}async get(t,e){return this.request("get",t,void 0,e)}async post(t,e,r){return this.request("post",t,e,r)}async put(t,e,r){return this.request("put",t,e,r)}async del(t,e){return this.request("delete",t,void 0,e)}}const p=["contains","contains_nocase","ends_with","end_with_nocase","starts_with","starts_with_nocase","not_contains","not_contains_nocase","not_ends_with","not_ends_with_nocase","not_starts_with","not_starts_with_nocase","gt","gte","lt","lte","not","in","not_in"],$=1e3,g=5e3;class a{static buildJsonQuery(t){const e=[];for(const r in t){const s=t[r];if(s!==void 0)if(s===null)e.push(`${r}: null`);else if(Array.isArray(s)){const n=s;e.push(`${r}: [${n.map(i=>typeof i=="string"?`"${i}"`:i).join(", ")}]`)}else if(typeof s=="string")e.push(`${r}: "${s}"`);else if(typeof s=="object"){const n={},i={},c=s;for(const l in c){const u=c[l];if(l.startsWith("$")){const o=l.slice(1);p.includes(o)?i[`${r}_${o}`]=u:n[l]=u}else n[l]=u}Object.keys(n).length>0&&e.push(`${r}: {${this.buildJsonQuery(n)}}`),Object.keys(i).length>0&&e.push(this.buildJsonQuery(i))}else e.push(`${r}: ${s}`)}return e.join(", ")}static buildElements(t){return t.map(e=>{if(typeof e=="string")return e;const r=e;return this.buildQuery({collection:r.collection,params:r.params})})}static buildMetadata(t){let e="";const r=[];t.blockQuery&&(t.blockQuery.hash&&r.push(`hash: "${t.blockQuery.hash}"`),t.blockQuery.number!==void 0&&r.push(`number: ${t.blockQuery.number}`),t.blockQuery.number_gte!==void 0&&r.push(`number_gte: ${t.blockQuery.number_gte}`));const s=r.join(", ");s.length>0&&(e+=`(block: {${s}})`);const n=[],i=[];if(t.elements){for(const u of t.elements)u==="deployment"||u==="hasIndexingErrors"?n.includes(u)||n.push(u):i.includes(u)||i.push(u);const c=i.join(" ");c.length>0&&n.push(`block{${c}}`);const l=n.join(" ");l.length>0&&(e+=`{${l}}`)}return e.length>0?`_meta${e}`:""}static _buildInlineFragment(t){const e=t.params?.elements?.length?this.buildElements(t.params.elements):["id"];return`... on ${t.collection}{${e.join(" ")}}`}static buildInlineFragments(t){return t.map(e=>this._buildInlineFragment(e)).join(" ")}static buildQuery(t,e){const{collection:r,params:s}=t,n=[];if(s?.id!==void 0&&n.push(`id: ${s.id}`),s?.orderBy&&n.push(`orderBy: ${s.orderBy}`),s?.orderDirection&&n.push(`orderDirection: ${s.orderDirection}`),s?.first!==void 0){const o=Math.max(0,Math.min(s.first,$));n.push(`first: ${o}`)}if(s?.skip!==void 0){const o=Math.max(0,Math.min(s.skip,g));n.push(`skip: ${o}`)}if(s?.where){const o=this.buildJsonQuery(s.where);o.length>0&&n.push(`where: {${o}}`)}if(s?.block){const o=this.buildJsonQuery(s.block);o.length>0&&n.push(`block: {${o}}`)}const i=n.length>0?`(${n.join(", ")})`:"";let c=["id"];s?.elements&&s.elements.length>0&&(c=this.buildElements(s.elements));let l="";s?.inlineFragments&&s.inlineFragments.length>0&&(l=` ${this.buildInlineFragments(s.inlineFragments)}`);const u=`${r}${i} {${c.join(" ")}${l}}`;if(e){const o=this.buildMetadata(e);return o?`${o} ${u}`:u}return u}static buildMultipleQuery(t,e){const s=t.map(n=>this.buildQuery({collection:n.collection,params:n.params})).join(" ");if(e){const n=this.buildMetadata(e);return n?`${n} ${s}`:s}return s}static makeFullQuery(t,e="query"){return`query ${e} {${t}}`}}class Q extends b{queryName;constructor(t,e){super(t,e),this.queryName="query"}async stringQuery(t){const e=await this.post("",{query:t});if(e&&typeof e=="object"&&"errors"in e){const s=e.errors.map(n=>n.message).join("; ");throw new Error(`GraphQL Error: ${s}`)}return e.data}async query(t,e){const r=a.buildQuery(t,e);return this.stringQuery(a.makeFullQuery(r,this.queryName))}async multipleQuery(t,e){const r=a.buildMultipleQuery(t,e);return this.stringQuery(a.makeFullQuery(r,this.queryName))}}exports.EthGraphQuery=Q;exports.OptionKeys=p;exports.QueryBuilder=a;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,324 @@
1
- export { EthGraphQuery } from './eth-graph-query.js';
2
- export { QueryBuilder } from './query-builder';
3
- export * from './type';
1
+ import { AxiosRequestConfig } from 'axios';
2
+
3
+ /**
4
+ * Base class for handling API requests using axios.
5
+ * Provides protected methods for common HTTP verbs.
6
+ */
7
+ declare class ApiQuery {
8
+ /** The root URL for all API requests. */
9
+ root: string;
10
+ /** Axios configuration used for all requests. */
11
+ config: AxiosRequestConfig;
12
+ /**
13
+ * Initializes a new instance of the ApiQuery class.
14
+ * @param rootUrl - The base URL for the API.
15
+ * @param config - Optional axios configuration.
16
+ */
17
+ constructor(rootUrl: string, config?: AxiosRequestConfig);
18
+ /**
19
+ * Performs an API request.
20
+ * @template T - The expected response type.
21
+ * @param method - The HTTP method to use.
22
+ * @param url - The relative URL for the request.
23
+ * @param data - The request payload (for POST, PUT).
24
+ * @param config - Optional axios configuration to override defaults.
25
+ * @returns A promise that resolves to the response data.
26
+ */
27
+ private request;
28
+ /**
29
+ * Performs a GET request.
30
+ * @template T - The expected response type.
31
+ * @param url - The relative URL for the request.
32
+ * @param config - Optional axios configuration to override defaults.
33
+ * @returns A promise that resolves to the response data.
34
+ */
35
+ protected get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
36
+ /**
37
+ * Performs a POST request.
38
+ * @template B - The request body type.
39
+ * @template T - The expected response type.
40
+ * @param url - The relative URL for the request.
41
+ * @param data - The request payload.
42
+ * @param config - Optional axios configuration to override defaults.
43
+ * @returns A promise that resolves to the response data.
44
+ */
45
+ protected post<B = any, T = any>(url: string, data?: B, config?: AxiosRequestConfig): Promise<T>;
46
+ /**
47
+ * Performs a PUT request.
48
+ * @template B - The request body type.
49
+ * @template T - The expected response type.
50
+ * @param url - The relative URL for the request.
51
+ * @param data - The request payload.
52
+ * @param config - Optional axios configuration to override defaults.
53
+ * @returns A promise that resolves to the response data.
54
+ */
55
+ protected put<B = any, T = any>(url: string, data?: B, config?: AxiosRequestConfig): Promise<T>;
56
+ /**
57
+ * Performs a DELETE request.
58
+ * @template T - The expected response type.
59
+ * @param url - The relative URL for the request.
60
+ * @param config - Optional axios configuration to override defaults.
61
+ * @returns A promise that resolves to the response data.
62
+ */
63
+ protected del<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
64
+ }
65
+
66
+ /**
67
+ * Base types that can be used in query filters.
68
+ */
69
+ export declare type BaseQueryType = string | number | boolean | Array<string | number | boolean> | null | undefined;
70
+
71
+ /**
72
+ * Filter for querying data at a specific block.
73
+ */
74
+ export declare type BlockQuery = {
75
+ /** Filter by block hash. */
76
+ hash?: string;
77
+ /** Filter by exact block number. */
78
+ number?: number;
79
+ /** Filter by blocks with number greater than or equal to. */
80
+ number_gte?: number;
81
+ };
82
+
83
+ /**
84
+ * Common filter options for all field types.
85
+ */
86
+ export declare type CommonWhereOptions = {
87
+ /** Greater than. */
88
+ $gt?: BaseQueryType;
89
+ /** Greater than or equal to. */
90
+ $gte?: BaseQueryType;
91
+ /** Less than. */
92
+ $lt?: BaseQueryType;
93
+ /** Less than or equal to. */
94
+ $lte?: BaseQueryType;
95
+ /** Not equal to. */
96
+ $not?: BaseQueryType;
97
+ /** Included in the provided array. */
98
+ $in?: BaseQueryType;
99
+ /** Not included in the provided array. */
100
+ $not_in?: BaseQueryType;
101
+ };
102
+
103
+ /**
104
+ * Represents a field in a query. Can be a simple string (field name)
105
+ * or a GraphObject for nested collection queries.
106
+ */
107
+ export declare type ElementType = string | GraphObject;
108
+
109
+ /**
110
+ * Error structure returned by The Graph API.
111
+ */
112
+ export declare type ErrorObject = {
113
+ /** List of errors encountered during query execution. */
114
+ errors: Array<{
115
+ message: string;
116
+ locations: Array<unknown>;
117
+ }>;
118
+ };
119
+
120
+ /**
121
+ * Main class for performing queries against The Graph protocols.
122
+ * Extends ApiQuery to handle HTTP communication.
123
+ */
124
+ export declare class EthGraphQuery extends ApiQuery {
125
+ /** The name of the GraphQL query, used in makeFullQuery. */
126
+ queryName: string;
127
+ /**
128
+ * Initializes a new EthGraphQuery instance.
129
+ * @param rootUrl - The endpoint URL of the subgraph.
130
+ * @param config - Optional axios configuration for custom headers or timeouts.
131
+ */
132
+ constructor(rootUrl: string, config?: AxiosRequestConfig);
133
+ /**
134
+ * Executes a raw GraphQL query string.
135
+ * @template T - The expected return type of the data.
136
+ * @param data - The raw GraphQL query string.
137
+ * @returns A promise resolving to the query result.
138
+ * @throws Error if the response contains any GraphQL errors.
139
+ */
140
+ stringQuery<T = any>(data: string): Promise<T>;
141
+ /**
142
+ * Executes a single collection query using a JSON configuration.
143
+ * @template T - The expected return type of the data.
144
+ * @param data - The configuration for the collection query.
145
+ * @param metadata - Optional metadata fields to include in the query.
146
+ * @returns A promise resolving to the fetched data.
147
+ */
148
+ query<T = any>(data: GraphObject, metadata?: Metadata): Promise<T>;
149
+ /**
150
+ * Executes multiple collection queries in a single request using JSON configurations.
151
+ * @template T - The expected return type of the data.
152
+ * @param data - An array of query configurations.
153
+ * @param metadata - Optional metadata fields to include in the query.
154
+ * @returns A promise resolving to the merged results of all queries.
155
+ */
156
+ multipleQuery<T = any>(data: Array<GraphObject>, metadata?: Metadata): Promise<T>;
157
+ }
158
+
159
+ /**
160
+ * Configuration for a query against a specific collection.
161
+ */
162
+ export declare interface GraphObject {
163
+ /** The name of the collection to query (e.g., 'users'). */
164
+ collection: string;
165
+ /** Optional parameters for filtering, sorting, and pagination. */
166
+ params?: GraphParams;
167
+ }
168
+
169
+ /**
170
+ * Parameters for a collection query.
171
+ */
172
+ export declare interface GraphParams {
173
+ /** Fields to select from the collection. */
174
+ elements?: Array<ElementType>;
175
+ /** Inline fragments for selecting fields on specific types. */
176
+ inlineFragments?: Array<InlineFragmentType>;
177
+ /** Filter conditions for the query. */
178
+ where?: QueryJson;
179
+ /** Filter by specific entity ID (shortcut for where: { id: ... }). */
180
+ id?: string;
181
+ /** Number of items to return (max 1000). */
182
+ first?: number;
183
+ /** Field to sort the results by. */
184
+ orderBy?: string;
185
+ /** Direction of the sort (asc or desc). */
186
+ orderDirection?: 'asc' | 'desc';
187
+ /** Number of items to skip (max 5000). */
188
+ skip?: number;
189
+ /** Re-run the query even if the subgraph has indexing errors. */
190
+ subgraphError?: 'allow' | 'deny';
191
+ /** Query the collection state at a specific block. */
192
+ block?: BlockQuery;
193
+ }
194
+
195
+ /**
196
+ * Represents an inline fragment for polymorphic types.
197
+ */
198
+ export declare type InlineFragmentType = {
199
+ /** The collection name for the fragment (e.g., 'User'). */
200
+ collection: string;
201
+ /** Fields to select within the fragment. */
202
+ params?: Pick<GraphParams, 'elements'>;
203
+ };
204
+
205
+ /**
206
+ * Metadata fields to query from the subgraph (_meta).
207
+ */
208
+ export declare type Metadata = {
209
+ /** Specific metadata elements to fetch. */
210
+ elements?: Array<'deployment' | 'hasIndexingErrors' | 'hash' | 'number' | 'timestamp'>;
211
+ /** Query metadata for a specific block. */
212
+ blockQuery?: BlockQuery;
213
+ };
214
+
215
+ /**
216
+ * Type representing the valid operator keys.
217
+ */
218
+ export declare type OptionKey = (typeof OptionKeys)[number];
219
+
220
+ /**
221
+ * Valid operator suffixes for The Graph queries (e.g., _gt, _in, _contains).
222
+ */
223
+ export declare const OptionKeys: readonly ["contains", "contains_nocase", "ends_with", "end_with_nocase", "starts_with", "starts_with_nocase", "not_contains", "not_contains_nocase", "not_ends_with", "not_ends_with_nocase", "not_starts_with", "not_starts_with_nocase", "gt", "gte", "lt", "lte", "not", "in", "not_in"];
224
+
225
+ export declare class QueryBuilder {
226
+ /**
227
+ * Converts a JSON query object into a GraphQL-compatible string.
228
+ * Handles nested objects and operator mapping (e.g., $gt -> _gt).
229
+ * @param query - The JSON filter object to build.
230
+ * @returns A string representing the GraphQL 'where' or 'block' filter.
231
+ */
232
+ static buildJsonQuery(query: QueryJson): string;
233
+ /**
234
+ * Builds the fields/elements part of a GraphQL query from an array of strings or objects.
235
+ * @param elements - An array of fields to query. Can include nested collections as GraphObject.
236
+ * @returns An array of strings representing the selected fields.
237
+ */
238
+ static buildElements(elements: Array<ElementType>): Array<string>;
239
+ /**
240
+ * Builds the metadata (_meta) fragment of a GraphQL query.
241
+ * @param metadata - The metadata configuration.
242
+ * @returns A string representing the _meta query fragment.
243
+ */
244
+ static buildMetadata(metadata: Metadata): string;
245
+ /**
246
+ * Builds an inline fragment (... on Collection { ... }) for a query.
247
+ * @param fragment - The inline fragment configuration.
248
+ * @returns A string representing the inline fragment.
249
+ * @private
250
+ */
251
+ private static _buildInlineFragment;
252
+ /**
253
+ * Builds multiple inline fragments from an array of fragment configurations.
254
+ * @param fragments - An array of inline fragments.
255
+ * @returns A string containing all built inline fragments.
256
+ */
257
+ static buildInlineFragments(fragments: Array<InlineFragmentType>): string;
258
+ /**
259
+ * Builds a complete GraphQL query for a single collection.
260
+ * @param data - The collection and parameters for the query.
261
+ * @param metadata - Optional metadata configuration.
262
+ * @returns A string containing the GraphQL query for the collection.
263
+ */
264
+ static buildQuery(data: GraphObject, metadata?: Metadata): string;
265
+ /**
266
+ * Builds a query that targets multiple collections simultaneously.
267
+ * @param data - An array of collection queries and their parameters.
268
+ * @param metadata - Optional metadata configuration that applies to the entire query.
269
+ * @returns A string containing the merged GraphQL query for multiple collections.
270
+ */
271
+ static buildMultipleQuery(data: Array<GraphObject>, metadata?: Metadata): string;
272
+ /**
273
+ * Wraps a query fragment into a full GraphQL 'query' block.
274
+ * @param query - The query fragment to wrap.
275
+ * @param queryName - An optional name for the GraphQL query (defaults to 'query').
276
+ * @returns The full GraphQL query string.
277
+ */
278
+ static makeFullQuery(query: string, queryName?: string): string;
279
+ }
280
+
281
+ /**
282
+ * JSON structure representing the 'where' filter in a query.
283
+ * Keys are field names, and values can be primitive values or WhereOptions.
284
+ */
285
+ export declare type QueryJson = {
286
+ [key: string]: QueryJson | WhereOptions | BaseQueryType;
287
+ };
288
+
289
+ /**
290
+ * Filter options for text-based fields.
291
+ */
292
+ export declare type TextWhereOptions = {
293
+ /** Matches values containing the substring. */
294
+ $contains?: BaseQueryType;
295
+ /** Case-insensitive contains. */
296
+ $contains_nocase?: BaseQueryType;
297
+ /** Matches values ending with the substring. */
298
+ $ends_with?: BaseQueryType;
299
+ /** Case-insensitive ends_with. */
300
+ $end_with_nocase?: BaseQueryType;
301
+ /** Matches values starting with the substring. */
302
+ $starts_with?: BaseQueryType;
303
+ /** Case-insensitive starts_with. */
304
+ $starts_with_nocase?: BaseQueryType;
305
+ /** Matches values NOT containing the substring. */
306
+ $not_contains?: BaseQueryType;
307
+ /** Case-insensitive not_contains. */
308
+ $not_contains_nocase?: BaseQueryType;
309
+ /** Matches values NOT ending with the substring. */
310
+ $not_ends_with?: BaseQueryType;
311
+ /** Case-insensitive not_ends_with. */
312
+ $not_ends_with_nocase?: BaseQueryType;
313
+ /** Matches values NOT starting with the substring. */
314
+ $not_starts_with?: BaseQueryType;
315
+ /** Case-insensitive not_starts_with. */
316
+ $not_starts_with_nocase?: BaseQueryType;
317
+ };
318
+
319
+ /**
320
+ * Combined filter options for a field.
321
+ */
322
+ export declare type WhereOptions = TextWhereOptions & CommonWhereOptions;
323
+
324
+ export { }