shopar-plugin 1.1.0 → 1.1.1-alpha.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
|
@@ -15,6 +15,7 @@ Powered and developed by DeepAR.
|
|
|
15
15
|
- [Usage](#usage)
|
|
16
16
|
- [API](#api)
|
|
17
17
|
- [ShopAR.plugin.setup(options)](#shoparpluginsetupoptions)
|
|
18
|
+
- [SkuData](#skudata)
|
|
18
19
|
- [License](#license)
|
|
19
20
|
|
|
20
21
|
## Getting started
|
|
@@ -32,7 +33,7 @@ There are two distinct ways of integrating the plugin: via Script tag and via NP
|
|
|
32
33
|
Add the following script to your HTML.
|
|
33
34
|
|
|
34
35
|
```html
|
|
35
|
-
<script src="https://cdn.jsdelivr.net/npm/shopar-plugin@
|
|
36
|
+
<script src="https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist/shopar-plugin.js"></script>
|
|
36
37
|
```
|
|
37
38
|
|
|
38
39
|
It is possible to use a different CDN instead of [jsDelivr](https://www.jsdelivr.com/) (e.g. [cdnjs](https://cdnjs.com/), [unpkg](https://www.unpkg.com/)), or even a relative path if the plugin is distributed as a static asset to your app. Just make sure to set the `baseUrl` parameter accordingly (see [setup options](#shoparpluginsetupoptions) for more details).
|
|
@@ -194,13 +195,17 @@ Options used for the plugin setup:
|
|
|
194
195
|
- Type: `HTMLElement`
|
|
195
196
|
- The element to inflate with ShopAR UI.
|
|
196
197
|
- Its CSS position property must be either `static` or `relative`.
|
|
198
|
+
- `skuData` (optional)
|
|
199
|
+
- Type: `SkuData`
|
|
200
|
+
- If provided, the API call is skipped and this data is used instead. This is useful for providing product data directly without relying on the ShopAR Dashboard API.
|
|
201
|
+
- See [SkuData](#skudata) for the full type reference.
|
|
197
202
|
- `initialState` (optional)
|
|
198
203
|
- Type: `'AR' | '3D'`
|
|
199
204
|
- If provided, defines which preview type the plugin initializes to.
|
|
200
205
|
- `baseUrl` (optional)
|
|
201
206
|
- Type: `string`
|
|
202
207
|
- If provided, defines where the additional ShopAR plugin files are fetched from.
|
|
203
|
-
- Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@
|
|
208
|
+
- Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist`
|
|
204
209
|
- `defaultUI` (optional)
|
|
205
210
|
- Type: `boolean`
|
|
206
211
|
- If provided and set to `false`, disables the default UI (buttons and error UI).
|
|
@@ -258,6 +263,39 @@ Options used for the plugin setup:
|
|
|
258
263
|
- If provided, it will be called with the engagement duration on every (debounced) 3D engagement.
|
|
259
264
|
- 3D engagement is measured as the time spent by the user rotating, panning or zooming the product in 3D.
|
|
260
265
|
|
|
266
|
+
### SkuData
|
|
267
|
+
|
|
268
|
+
The `skuData` option allows you to provide product data directly, bypassing the ShopAR Dashboard API call. All properties are optional.
|
|
269
|
+
|
|
270
|
+
| Property | Type | Description |
|
|
271
|
+
| --- | --- | --- |
|
|
272
|
+
| `category` | `AssetCategory` | Product category. Supported values: `'Glasses'`, `'Shoes'`, `'Watches'`, `'Bracelets'`, `'Handbags'`, `'Rings'`, `'Bottles'`, `'Scarves'`, `'Hats'`, `'Necklaces'`, `'Earrings'`. |
|
|
273
|
+
| `arUrl` | `string` | URL to the AR model asset. |
|
|
274
|
+
| `arEnvUrl` | `string` | URL to the AR environment map. |
|
|
275
|
+
| `arDiamondEnvUrl` | `string` | URL to the AR diamond environment map. |
|
|
276
|
+
| `arToneMapping` | `ToneMapping` | Tone mapping mode for AR. Supported values: `'ACES'`, `'Linear'`, `'Neutral'`. |
|
|
277
|
+
| `arToneMappingExposure` | `number` | Tone mapping exposure for AR. |
|
|
278
|
+
| `arBloomEnabled` | `boolean` | Whether bloom is enabled in AR. |
|
|
279
|
+
| `arBloomStrength` | `number` | Bloom strength in AR. |
|
|
280
|
+
| `arBloomRadius` | `number` | Bloom radius in AR. |
|
|
281
|
+
| `arBloomThreshold` | `number` | Bloom threshold in AR. |
|
|
282
|
+
| `arKey` | `string` | License key for AR. |
|
|
283
|
+
| `arPromptEnabled` | `boolean` | Whether the AR prompt overlay is shown. |
|
|
284
|
+
| `arPromptText` | `string` | Custom text displayed in the AR prompt. |
|
|
285
|
+
| `arPromptImage` | `string` | URL to a custom AR prompt image. If not provided, a default bundled image is used. |
|
|
286
|
+
| `previewUrl` | `string` | URL to the 3D preview model asset. |
|
|
287
|
+
| `previewEnvUrl` | `string` | URL to the 3D preview environment map. |
|
|
288
|
+
| `previewDiamondEnvUrl` | `string` | URL to the 3D preview diamond environment map. |
|
|
289
|
+
| `previewToneMapping` | `ToneMapping` | Tone mapping mode for 3D preview. Supported values: `'ACES'`, `'Linear'`, `'Neutral'`. |
|
|
290
|
+
| `previewToneMappingExposure` | `number` | Tone mapping exposure for 3D preview. |
|
|
291
|
+
| `previewBloomEnabled` | `boolean` | Whether bloom is enabled in 3D preview. |
|
|
292
|
+
| `previewBloomStrength` | `number` | Bloom strength in 3D preview. |
|
|
293
|
+
| `previewBloomRadius` | `number` | Bloom radius in 3D preview. |
|
|
294
|
+
| `previewBloomThreshold` | `number` | Bloom threshold in 3D preview. |
|
|
295
|
+
| `previewPosterUrl` | `string` | URL to a poster image shown before 3D loads. |
|
|
296
|
+
| `cameraErrorText` | `string` | Custom text shown when camera access fails. |
|
|
297
|
+
| `qrPromptText` | `string` | Custom text shown on the QR code screen. |
|
|
298
|
+
|
|
261
299
|
## License
|
|
262
300
|
|
|
263
301
|
Please see: https://developer.deepar.ai/customer-agreement
|
|
Binary file
|
package/dist/shopar-analytics.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,n;var s=e(function(){if(n)return i;function t(t){return Number.isInteger(t)&&t>=0}function e(t){this.name="ArgumentError",this.message=t}return n=1,i=function(i,n){if(n=n||{},"function"!=typeof i)throw new e("fetch must be a function");if("object"!=typeof n)throw new e("defaults must be an object");if(void 0!==n.retries&&!t(n.retries))throw new e("retries must be a positive integer");if(void 0!==n.retryDelay&&!t(n.retryDelay)&&"function"!=typeof n.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==n.retryOn&&!Array.isArray(n.retryOn)&&"function"!=typeof n.retryOn)throw new e("retryOn property expects an array or function");return n=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},n),function(s,r){var o=n.retries,a=n.retryDelay,c=n.retryOn;if(r&&void 0!==r.retries){if(!t(r.retries))throw new e("retries must be a positive integer");o=r.retries}if(r&&void 0!==r.retryDelay){if(!t(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");a=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new e("retryOn property expects an array or function");c=r.retryOn}return new Promise(function(t,e){var n=function(n){var a="undefined"!=typeof Request&&s instanceof Request?s.clone():s;i(a,r).then(function(i){if(Array.isArray(c)&&-1===c.indexOf(i.status))t(i);else if("function"==typeof c)try{return Promise.resolve(c(n,null,i)).then(function(e){e?l(n,null,i):t(i)}).catch(e)}catch(t){e(t)}else n<o?l(n,null,i):t(i)}).catch(function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then(function(i){i?l(n,t,null):e(t)}).catch(function(t){e(t)})}catch(t){e(t)}else n<o?l(n,t,null):e(t)})};function l(t,e,i){var s="function"==typeof a?a(t,e,i):a;setTimeout(function(){n(++t)},s)}n(0)})}}}());var r,o;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(o||(o={}));class a{scope;type;value;remaining;reset;constructor(t=r.unknown,e=o.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){const o=new a,c=t.headers.get(e.toLowerCase())||r.unknown;o.scope=r[c];const l=t.headers.get(i.toLowerCase())||"",h=parseInt(l,10);isNaN(h)||(o.value=h);const u=t.headers.get(n.toLowerCase())||"",f=parseInt(u,10);isNaN(f)||(o.remaining=f);const p=t.headers.get(s.toLowerCase())||"",m=parseInt(p,10);return isNaN(m)||(o.reset=new Date(1e3*m)),o}class l{config;constructor(t){this.config=t}async doReq(t,e,i={},n={},r=this.config.timeout,a=!1){let l=a?t:`${this.config.baseUrl}${t}`;const u=this._prepareSearchParams(n);u&&(l+=`?${u.toString()}`);const f={...this.config.headers,...i.headers},p=await s(fetch)(l,{retries:1,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:f,method:e,body:i.body?i.body:void 0,signal:AbortSignal.timeout(r),cache:"no-store"});if(204===p.status)return p;if(429==p.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=o.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=o.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=o.api),e}(p);return Promise.reject(new h(t))}if(401===p.status)return Promise.reject(new Error("forbidden"));if(p.status>=400){const t=await p.json();return Promise.reject(new Error(t.message))}return await p.json()}post(t,e={},i={},n=this.config.timeout,s=!1){return this.doReq(t,"POST",e,i,n,s)}get(t,e={},i={},n=this.config.timeout){return this.doReq(t,"GET",e,i,n)}put(t,e={},i={},n=this.config.timeout){return this.doReq(t,"PUT",e,i,n)}delete(t,e={},i={},n=this.config.timeout){return this.doReq(t,"DELETE",e,i,n)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach(n=>{t[n]&&(e.append(n,t[n]),i=!0)}),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==o.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}const u="https://api.axiom.co";function f(t,e){return t.edgeUrl?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/ingest/${e}`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/ingest/${e}`}}(t.edgeUrl,e):t.edge?`https://${t.edge}/v1/ingest/${e}`:t.url?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/datasets/${e}/ingest`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/datasets/${e}/ingest`}}(t.url,e):`${u}/v1/datasets/${e}/ingest`}class p{client;clientOptions;constructor({orgId:t="",token:e,url:i,edge:n,edgeUrl:s,onError:r}){e||console.warn("Missing Axiom token"),this.clientOptions={orgId:t,token:e,url:i,edge:n,edgeUrl:s,onError:r};const o=i?i.replace(/\/+$/,""):u,a={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(a["User-Agent"]="axiom-js/1.4.0"),t&&(a["X-Axiom-Org-Id"]=t),this.client=new l({baseUrl:o,headers:a,timeout:2e4})}}var m,d,g,y,v,w,b,O;!function(t){t.TimestampField="_time";t.Service=class extends p{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=(t,e)=>{const i=new URLSearchParams;i.set("referrer",e?.referrer??"");const n=`/v2/datasets?${i.toString()}`;return this.client.post(n,{body:JSON.stringify(t)})};update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(m||(m={})),function(t){t.Service=class extends p{current=()=>this.client.get("/v1/user")}}(d||(d={}));class S{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout(()=>{},0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout(()=>{this.activeFlush=this.flush()},1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);let e=null;try{e=await this.ingestFn(this.id,t,this.options)}catch(t){throw t}finally{this.lastFlush=new Date}return e}}class x extends p{datasets;users;localPath="/v1";onError=console.error;constructor(t){t.token&&t.token.startsWith("xapt")&&console.warn("Using a personal token (`xapt-...`) is deprecated for security reasons. Please use an API token (`xaat-...`) instead. Support for personal tokens will be removed in a future release."),super(t),this.datasets=new m.Service(t),this.users=new d.Service(t),t.onError&&(this.onError=t.onError)}ingestRaw=async(t,e,i=g.JSON,n=y.Identity,s)=>{try{const r=f(this.clientOptions,t);return await this.client.post(r,{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter},void 0,!0)}catch(t){return this.onError(t),await Promise.resolve({ingested:0,failed:0,processedBytes:0,blocksCreated:0,walLength:0})}};queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache},12e4);query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:e?.format??"legacy",cursor:e?.cursor},12e4).then(t=>{if("tabular"!==e?.format)return t;const i=t;return{...t,tables:i.tables.map(t=>({...t,events:function*(){let t=0;if(this.columns)for(;t<=this.columns[0].length;){const e=Object.fromEntries(this.fields.map((e,i)=>[e.name,this.columns[i][t]]));if(t>=this.columns[0].length)return e;yield e,t++}}}))}})};aplQuery=(t,e)=>this.query(t,e)}class P extends x{batch={};ingest=(t,e,i)=>{const n=function(t,e){return`${t}:${e?.timestampField||"-"}:${e?.timestampFormat||"-"}:${e?.csvDelimiter||"-"}`}(t,i);return this.batch[n]||(this.batch[n]=new S((t,e,i)=>{const n=(Array.isArray(e)?e:[e]).map(t=>JSON.stringify(t)).join("\n");return this.ingestRaw(t,n,g.NDJSON,y.Identity,i)},t,i)),this.batch[n].ingest(e)};flush=async()=>{let t=[];for(const e in this.batch)t.push(this.batch[e].flush().catch(this.onError));await Promise.all(t).catch(this.onError)}}let N;BigInt.prototype.toJSON=function(){return this.toString()},function(t){t.JSON="application/json",t.NDJSON="application/x-ndjson",t.CSV="text/csv"}(g||(g={})),function(t){t.Identity="",t.GZIP="gzip"}(y||(y={})),function(t){t.Count="count",t.Distinct="distinct",t.Sum="sum",t.Avg="avg",t.Min="min",t.Max="max",t.Topk="topk",t.Percentiles="percentiles",t.Histogram="histogram",t.Variance="variance",t.Stdev="stdev",t.ArgMin="argmin",t.ArgMax="argmax",t.MakeSet="makeset",t.MakeSetIf="makesetif",t.CountIf="countif",t.CountDistinctIf="distinctif"}(v||(v={})),function(t){t.And="and",t.Or="or",t.Not="not",t.Equal="==",t.NotEqual="!=",t.Exists="exists",t.NotExists="not-exists",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.LessThan="<",t.LessThanOrEqualTo="<=",t.Gt="gt",t.Gte="gte",t.Lt="lt",t.Lte="lte",t.StartsWith="starts-with",t.NotStartsWith="not-starts-with",t.EndsWith="ends-with",t.NotEndsWith="not-ends-with",t.Contains="contains",t.NotContains="not-contains",t.Regexp="regexp",t.NotRegexp="not-regexp"}(w||(w={})),function(t){t.Service=class extends p{localPath="/v2/annotations";list=t=>this.client.get(this.localPath,{},t);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(b||(b={})),function(t){t.Service=class extends p{localPath="/v2/monitors";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(O||(O={})),t.initializeImpl=function(){N=new P({token:"xaat-f69a9dd7-3988-4fc2-849b-4a0978468c25"})},t.trackEventImpl=function(t,e){N.ingest("shopar-plugin",Object.assign({name:t},e))}});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,n;var s=e(function(){if(n)return i;function t(t){return Number.isInteger(t)&&t>=0}function e(t){this.name="ArgumentError",this.message=t}return n=1,i=function(i,n){if(n=n||{},"function"!=typeof i)throw new e("fetch must be a function");if("object"!=typeof n)throw new e("defaults must be an object");if(void 0!==n.retries&&!t(n.retries))throw new e("retries must be a positive integer");if(void 0!==n.retryDelay&&!t(n.retryDelay)&&"function"!=typeof n.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==n.retryOn&&!Array.isArray(n.retryOn)&&"function"!=typeof n.retryOn)throw new e("retryOn property expects an array or function");return n=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},n),function(s,r){var o=n.retries,a=n.retryDelay,c=n.retryOn;if(r&&void 0!==r.retries){if(!t(r.retries))throw new e("retries must be a positive integer");o=r.retries}if(r&&void 0!==r.retryDelay){if(!t(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");a=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new e("retryOn property expects an array or function");c=r.retryOn}return new Promise(function(t,e){var n=function(n){var a="undefined"!=typeof Request&&s instanceof Request?s.clone():s;i(a,r).then(function(i){if(Array.isArray(c)&&-1===c.indexOf(i.status))t(i);else if("function"==typeof c)try{return Promise.resolve(c(n,null,i)).then(function(e){e?l(n,null,i):t(i)}).catch(e)}catch(t){e(t)}else n<o?l(n,null,i):t(i)}).catch(function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then(function(i){i?l(n,t,null):e(t)}).catch(function(t){e(t)})}catch(t){e(t)}else n<o?l(n,t,null):e(t)})};function l(t,e,i){var s="function"==typeof a?a(t,e,i):a;setTimeout(function(){n(++t)},s)}n(0)})}}}());var r,o;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(o||(o={}));class a{scope;type;value;remaining;reset;constructor(t=r.unknown,e=o.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){const o=new a,c=t.headers.get(e.toLowerCase())||r.unknown;o.scope=r[c];const l=t.headers.get(i.toLowerCase())||"",h=parseInt(l,10);isNaN(h)||(o.value=h);const u=t.headers.get(n.toLowerCase())||"",f=parseInt(u,10);isNaN(f)||(o.remaining=f);const p=t.headers.get(s.toLowerCase())||"",m=parseInt(p,10);return isNaN(m)||(o.reset=new Date(1e3*m)),o}class l{config;constructor(t){this.config=t}async doReq(t,e,i={},n={},r=this.config.timeout,a=!1){let l=a?t:`${this.config.baseUrl}${t}`;const u=this._prepareSearchParams(n);u&&(l+=`?${u.toString()}`);const f={...this.config.headers,...i.headers},p=await s(fetch)(l,{retries:1,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:f,method:e,body:i.body?i.body:void 0,signal:AbortSignal.timeout(r),cache:"no-store"});if(204===p.status)return p;if(429==p.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=o.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=o.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=o.api),e}(p);return Promise.reject(new h(t))}if(401===p.status)return Promise.reject(new Error("forbidden"));if(p.status>=400){const t=await p.json();return Promise.reject(new Error(t.message))}return await p.json()}post(t,e={},i={},n=this.config.timeout,s=!1){return this.doReq(t,"POST",e,i,n,s)}get(t,e={},i={},n=this.config.timeout){return this.doReq(t,"GET",e,i,n)}put(t,e={},i={},n=this.config.timeout){return this.doReq(t,"PUT",e,i,n)}delete(t,e={},i={},n=this.config.timeout){return this.doReq(t,"DELETE",e,i,n)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach(n=>{t[n]&&(e.append(n,t[n]),i=!0)}),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==o.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}const u="https://api.axiom.co";function f(t,e){return t.edgeUrl?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/ingest/${e}`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/ingest/${e}`}}(t.edgeUrl,e):t.edge?`https://${t.edge}/v1/ingest/${e}`:t.url?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/datasets/${e}/ingest`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/datasets/${e}/ingest`}}(t.url,e):`${u}/v1/datasets/${e}/ingest`}class p{client;clientOptions;constructor({orgId:t="",token:e,url:i,edge:n,edgeUrl:s,onError:r}){e||console.warn("Missing Axiom token"),this.clientOptions={orgId:t,token:e,url:i,edge:n,edgeUrl:s,onError:r};const o=i?i.replace(/\/+$/,""):u,a={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(a["User-Agent"]="axiom-js/1.4.0"),t&&(a["X-Axiom-Org-Id"]=t),this.client=new l({baseUrl:o,headers:a,timeout:2e4})}}var m,d,g,y,v,w,b,O;!function(t){t.TimestampField="_time";t.Service=class extends p{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=(t,e)=>{const i=new URLSearchParams;i.set("referrer",e?.referrer??"");const n=`/v2/datasets?${i.toString()}`;return this.client.post(n,{body:JSON.stringify(t)})};update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(m||(m={})),function(t){t.Service=class extends p{current=()=>this.client.get("/v1/user")}}(d||(d={}));class S{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout(()=>{},0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout(()=>{this.activeFlush=this.flush()},1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);let e=null;try{e=await this.ingestFn(this.id,t,this.options)}catch(t){throw t}finally{this.lastFlush=new Date}return e}}class x extends p{datasets;users;localPath="/v1";onError=console.error;constructor(t){t.token&&t.token.startsWith("xapt")&&console.warn("Using a personal token (`xapt-...`) is deprecated for security reasons. Please use an API token (`xaat-...`) instead. Support for personal tokens will be removed in a future release."),super(t),this.datasets=new m.Service(t),this.users=new d.Service(t),t.onError&&(this.onError=t.onError)}ingestRaw=async(t,e,i=g.JSON,n=y.Identity,s)=>{try{const r=f(this.clientOptions,t);return await this.client.post(r,{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter},void 0,!0)}catch(t){return this.onError(t),await Promise.resolve({ingested:0,failed:0,processedBytes:0,blocksCreated:0,walLength:0})}};queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache},12e4);query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:e?.format??"legacy",cursor:e?.cursor},12e4).then(t=>{if("tabular"!==e?.format)return t;const i=t;return{...t,tables:i.tables.map(t=>({...t,events:function*(){let t=0;if(this.columns)for(;t<=this.columns[0].length;){const e=Object.fromEntries(this.fields.map((e,i)=>[e.name,this.columns[i][t]]));if(t>=this.columns[0].length)return e;yield e,t++}}}))}})};aplQuery=(t,e)=>this.query(t,e)}class P extends x{batch={};ingest=(t,e,i)=>{const n=function(t,e){return`${t}:${e?.timestampField||"-"}:${e?.timestampFormat||"-"}:${e?.csvDelimiter||"-"}`}(t,i);return this.batch[n]||(this.batch[n]=new S((t,e,i)=>{const n=(Array.isArray(e)?e:[e]).map(t=>JSON.stringify(t)).join("\n");return this.ingestRaw(t,n,g.NDJSON,y.Identity,i)},t,i)),this.batch[n].ingest(e)};flush=async()=>{let t=[];for(const e in this.batch)t.push(this.batch[e].flush().catch(this.onError));await Promise.all(t).catch(this.onError)}}let N;BigInt.prototype.toJSON=function(){return this.toString()},function(t){t.JSON="application/json",t.NDJSON="application/x-ndjson",t.CSV="text/csv"}(g||(g={})),function(t){t.Identity="",t.GZIP="gzip"}(y||(y={})),function(t){t.Count="count",t.Distinct="distinct",t.Sum="sum",t.Avg="avg",t.Min="min",t.Max="max",t.Topk="topk",t.Percentiles="percentiles",t.Histogram="histogram",t.Variance="variance",t.Stdev="stdev",t.ArgMin="argmin",t.ArgMax="argmax",t.MakeSet="makeset",t.MakeSetIf="makesetif",t.CountIf="countif",t.CountDistinctIf="distinctif"}(v||(v={})),function(t){t.And="and",t.Or="or",t.Not="not",t.Equal="==",t.NotEqual="!=",t.Exists="exists",t.NotExists="not-exists",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.LessThan="<",t.LessThanOrEqualTo="<=",t.Gt="gt",t.Gte="gte",t.Lt="lt",t.Lte="lte",t.StartsWith="starts-with",t.NotStartsWith="not-starts-with",t.EndsWith="ends-with",t.NotEndsWith="not-ends-with",t.Contains="contains",t.NotContains="not-contains",t.Regexp="regexp",t.NotRegexp="not-regexp"}(w||(w={})),function(t){t.Service=class extends p{localPath="/v2/annotations";list=t=>this.client.get(this.localPath,{},t);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(b||(b={})),function(t){t.Service=class extends p{localPath="/v2/monitors";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(O||(O={})),t.initializeImpl=function(){N=new P({token:"xaat-16d05fdd-4ab9-4990-acba-7cee24974bfb"})},t.trackEventImpl=function(t,e){N.ingest("shopar-plugin-alpha",Object.assign({name:t},e))}});
|
package/dist/shopar-plugin.d.ts
CHANGED