@matheusdev20/hc-lib 0.1.5 → 0.1.7
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/dist/index.d.mts +8 -1
- package/dist/index.d.ts +8 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
type ExpiringItem<T> = {
|
|
2
|
+
value: T;
|
|
3
|
+
expiry: number;
|
|
4
|
+
};
|
|
5
|
+
declare function setWithExpiry(key: string, value: string, ttlSeconds: number): void;
|
|
6
|
+
declare function getWithExpiry(key: string): string | null;
|
|
7
|
+
|
|
1
8
|
declare function ready(fn: () => void): void;
|
|
2
9
|
|
|
3
10
|
declare function timeout(ms: number): Promise<never>;
|
|
@@ -10,4 +17,4 @@ type APIDependencies = 'articles';
|
|
|
10
17
|
|
|
11
18
|
declare function create(version: HCVersion, apiDependencies?: APIDependencies[]): HCInstance;
|
|
12
19
|
|
|
13
|
-
export { type HCInstance, type HCVersion, create, ready, timeout };
|
|
20
|
+
export { type ExpiringItem, type HCInstance, type HCVersion, create, getWithExpiry, ready, setWithExpiry, timeout };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
type ExpiringItem<T> = {
|
|
2
|
+
value: T;
|
|
3
|
+
expiry: number;
|
|
4
|
+
};
|
|
5
|
+
declare function setWithExpiry(key: string, value: string, ttlSeconds: number): void;
|
|
6
|
+
declare function getWithExpiry(key: string): string | null;
|
|
7
|
+
|
|
1
8
|
declare function ready(fn: () => void): void;
|
|
2
9
|
|
|
3
10
|
declare function timeout(ms: number): Promise<never>;
|
|
@@ -10,4 +17,4 @@ type APIDependencies = 'articles';
|
|
|
10
17
|
|
|
11
18
|
declare function create(version: HCVersion, apiDependencies?: APIDependencies[]): HCInstance;
|
|
12
19
|
|
|
13
|
-
export { type HCInstance, type HCVersion, create, ready, timeout };
|
|
20
|
+
export { type ExpiringItem, type HCInstance, type HCVersion, create, getWithExpiry, ready, setWithExpiry, timeout };
|
package/dist/index.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var AktieHC=(()=>{var
|
|
1
|
+
"use strict";var AktieHC=(()=>{var m=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var g=(t,e)=>{for(var r in e)m(t,r,{get:e[r],enumerable:!0})},_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!S.call(t,o)&&o!==r&&m(t,o,{get:()=>e[o],enumerable:!(n=P(e,o))||n.enumerable});return t};var b=t=>_(m({},"__esModule",{value:!0}),t);var $={};g($,{create:()=>v,getWithExpiry:()=>h,ready:()=>w,setWithExpiry:()=>f,timeout:()=>C});var c={};g(c,{getWithExpiry:()=>h,ready:()=>w,setWithExpiry:()=>f});function f(t,e,r){let n=Date.now(),o={value:e,expiry:n+r*1e3};localStorage.setItem(t,JSON.stringify(o))}function h(t){let e=localStorage.getItem(t);if(!e)return null;let r;try{r=JSON.parse(e)}catch(o){return localStorage.removeItem(t),null}return typeof(r==null?void 0:r.value)!="string"||typeof(r==null?void 0:r.expiry)!="number"||Date.now()>r.expiry?(localStorage.removeItem(t),null):r.value}function w(t){document.readyState!=="loading"?t():document.addEventListener("DOMContentLoaded",t)}function C(t){return new Promise((e,r)=>setTimeout(()=>r(new Error("Request timeout")),t))}var p=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}};var y={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async getAuthorizationToken(){return fetch("/hc/api/internal/csrf_token.json").then(t=>t.json()).then(t=>t.current_session.csrf_token).catch(t=>{console.error(new Error(t))})}};var x={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},general:{perPage:"100",include:"categories,sections"},async getAll(t=1){let e=`${this.web.subdomain}-articles-p${t}`;if(sessionStorage.getItem(e))return JSON.parse(sessionStorage.getItem(e));let n=await(await fetch(`/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`)).json();for(;n.next_page;){let s=await(await fetch(n.next_page)).json();n.categories.push(...s.categories.filter(i=>n.categories.findIndex(a=>a.id===i.id)===-1)),n.sections.push(...s.sections.filter(i=>n.sections.findIndex(a=>a.id===i.id)===-1)),n.articles=n.articles.concat(s.articles),n.next_page=s.next_page}return sessionStorage.setItem(e,JSON.stringify(n)),n},async searchArticle(t){let n=(o,s={})=>Promise.race([fetch(o,s),new Promise((i,a)=>setTimeout(()=>a(new Error("Request timeout")),8e3))]);try{if(!t||typeof t!="string")return{results:[],count:0};let s=`/api/v2/help_center/articles/search.json?query=${encodeURIComponent(t)}`,i={results:[],next_page:s},a=0;for(;i.next_page&&!(a>50);){let d=await n(i.next_page);if(!d.ok)break;let u=await d.json();if(!Array.isArray(u.results))break;i.results=i.results.concat(u.results),i.next_page=u.next_page,a++}return i}catch(o){return{results:[],error:o.message}}},async vote({articleId:t,vote:e}){var n;let r=JSON.parse((n=sessionStorage.getItem("cur-votes"))!=null?n:"")||{};if(!["up","down"].includes(e))throw new Error(`Tipo de voto "${e}" inv\xE1lido`);try{let o=`/api/v2/help_center/pt-br/articles/${t}/${e}`,s=await fetch(o,{method:"POST",headers:{"content-type":"application/json","x-csrf-token":await y.getAuthorizationToken(),"x-requested-with":"XMLHttpRequest"}});if(!s.ok)throw{message:"A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe atrav\xE9s de uma solicita\xE7\xE3o",code:s.status};return r[t]=e,sessionStorage.setItem("cur-votes",JSON.stringify(r)),s.json()}catch(o){return{error:!0,message:`Ocorreu um erro ao votar no artigo de ID "${t}"`,originalError:`${o.code} - ${o.message}`}}}};var A={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async me(){return await fetch("/api/v2/users/me.json")}};var I={articles:x,users:A};var l=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}searchForArticle(e){return this.use("articles").searchArticle(e)}};function v(t,e=[]){let r=null;if(e.length>0){let n={};for(let o of e)n[o]=I[o];r=n}switch(t){case"v3":return new p(r);case"v4":return new l(r);default:throw new Error(`Unsupported HC version: ${t}`)}}return b($);})();
|
|
2
2
|
//# sourceMappingURL=index.global.js.map
|
package/dist/index.global.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/dom/index.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["export * from \"./dom\";\nexport * from \"./utils\";\nexport * from \"./hc\";\n","export function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Unsupported HC version: ${version}`);\n }\n}\n"],"mappings":"2bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,UAAAC,EAAA,YAAAC,ICAO,SAASC,EAAMC,EAAsB,CACtC,SAAS,aAAe,UAC1BA,EAAG,EAEH,SAAS,iBAAiB,mBAAoBA,CAAE,CAEpD,CCLO,SAASC,EAAQC,EAA4B,CAClD,OAAO,IAAI,QAAQ,CAACC,EAAGC,IAAW,WAAW,IAAMA,EAAO,IAAI,MAAM,iBAAiB,CAAC,EAAGF,CAAE,CAAC,CAC9F,CCEO,IAAMG,EAAN,KAAiC,CAItC,YAAYC,EAAwB,CAClC,KAAK,IAAMA,GAAA,KAAAA,EAAW,CAA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B,OAAO,CACzB,CAEA,iBAAiBC,EAA6B,CAE5C,OADiB,KAAK,IAAI,UAAU,EACpB,cAAcA,CAAK,CACrC,CACF,EC3BO,SAASC,EAAOC,EAAoBC,EAAqC,CAAC,EAAe,CAC9F,IAAIC,EAAoD,KAExD,GAAID,EAAgB,OAAS,EAAG,CAC9B,IAAME,EAAgD,CAAC,EACvD,QAAWC,KAAOH,EAAiBE,EAAOC,CAAG,EAAIC,EAAKD,CAAG,EACzDF,EAAMC,CACR,CAEA,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["index_exports","__export","create","ready","timeout","ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/dom/index.ts","../src/dom/storage.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["export * from \"./dom\";\nexport * from \"./utils\";\nexport * from \"./hc\";\n","\nexport * from \"./storage\"\n\nexport function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","export type ExpiringItem<T> = {\n value: T;\n expiry: number;\n};\n\nexport function setWithExpiry(key: string, value: string, ttlSeconds: number): void {\n const now = Date.now();\n const item: ExpiringItem<string> = {\n value,\n expiry: now + ttlSeconds * 1000,\n };\n localStorage.setItem(key, JSON.stringify(item));\n}\n\nexport function getWithExpiry(key: string): string | null {\n const itemStr = localStorage.getItem(key);\n if (!itemStr) return null;\n\n let item: ExpiringItem<string>;\n try {\n item = JSON.parse(itemStr) as ExpiringItem<string>;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n\n if (typeof item?.value !== \"string\" || typeof item?.expiry !== \"number\") {\n localStorage.removeItem(key);\n return null;\n }\n\n const now = Date.now();\n if (now > item.expiry) {\n localStorage.removeItem(key);\n return null;\n }\n\n return item.value;\n}","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Unsupported HC version: ${version}`);\n }\n}\n"],"mappings":"2bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,kBAAAC,EAAA,UAAAC,EAAA,kBAAAC,EAAA,YAAAC,ICAA,IAAAC,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,UAAAC,EAAA,kBAAAC,ICKO,SAASC,EAAcC,EAAaC,EAAeC,EAA0B,CAClF,IAAMC,EAAM,KAAK,IAAI,EACfC,EAA6B,CACjC,MAAAH,EACA,OAAQE,EAAMD,EAAa,GAC7B,EACA,aAAa,QAAQF,EAAK,KAAK,UAAUI,CAAI,CAAC,CAChD,CAEO,SAASC,EAAcL,EAA4B,CACxD,IAAMM,EAAU,aAAa,QAAQN,CAAG,EACxC,GAAI,CAACM,EAAS,OAAO,KAErB,IAAIF,EACJ,GAAI,CACFA,EAAO,KAAK,MAAME,CAAO,CAC3B,OAAQC,EAAA,CACN,oBAAa,WAAWP,CAAG,EACpB,IACT,CAQA,OANI,OAAOI,GAAA,YAAAA,EAAM,QAAU,UAAY,OAAOA,GAAA,YAAAA,EAAM,SAAW,UAKnD,KAAK,IAAI,EACXA,EAAK,QACb,aAAa,WAAWJ,CAAG,EACpB,MAGFI,EAAK,KACd,CDnCO,SAASI,EAAMC,EAAsB,CACtC,SAAS,aAAe,UAC1BA,EAAG,EAEH,SAAS,iBAAiB,mBAAoBA,CAAE,CAEpD,CERO,SAASC,EAAQC,EAA4B,CAClD,OAAO,IAAI,QAAQ,CAACC,E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C,CACzB,CAEQ,IAA+BE,EAA0B,CAC/D,IAAMC,EAAS,KAAK,IAAID,CAAG,EAC3B,GAAI,CAACC,EACH,MAAM,IAAI,MACR,UAAUD,CAAG,0FAA0FA,CAAG,KAC5G,EAGF,OAAOC,CACT,CAEA,gBAA+B,CAE7B,OADiB,KAAK,IAAI,UAAU,EACpB,OAAO,CACzB,CAEA,iBAAiBC,EAA6B,CAE5C,OADiB,KAAK,IAAI,UAAU,EACpB,cAAcA,CAAK,CACrC,CACF,EC7BO,SAASC,EAAOC,EAAoBC,EAAqC,CAAC,EAAe,CAC9F,IAAIC,EAAoD,KAExD,GAAID,EAAgB,OAAS,EAAG,CAC9B,IAAME,EAAgD,CAAC,EACvD,QAAWC,KAAOH,EAAiBE,EAAOC,CAAG,EAAIC,EAAKD,CAAG,EACzDF,EAAMC,CACR,CAEA,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["index_exports","__export","create","getWithExpiry","ready","setWithExpiry","timeout","dom_exports","__export","getWithExpiry","ready","setWithExpiry","setWithExpiry","key","value","ttlSeconds","now","item","getWithExpiry","itemStr","e","ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dom_exports","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dom_exports","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var S=Object.prototype.hasOwnProperty;var g=(t,e)=>{for(var r in e)m(t,r,{get:e[r],enumerable:!0})},_=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!S.call(t,o)&&o!==r&&m(t,o,{get:()=>e[o],enumerable:!(n=P(e,o))||n.enumerable});return t};var b=t=>_(m({},"__esModule",{value:!0}),t);var $={};g($,{create:()=>v,getWithExpiry:()=>h,ready:()=>w,setWithExpiry:()=>f,timeout:()=>C});module.exports=b($);var c={};g(c,{getWithExpiry:()=>h,ready:()=>w,setWithExpiry:()=>f});function f(t,e,r){let n=Date.now(),o={value:e,expiry:n+r*1e3};localStorage.setItem(t,JSON.stringify(o))}function h(t){let e=localStorage.getItem(t);if(!e)return null;let r;try{r=JSON.parse(e)}catch(o){return localStorage.removeItem(t),null}return typeof(r==null?void 0:r.value)!="string"||typeof(r==null?void 0:r.expiry)!="number"||Date.now()>r.expiry?(localStorage.removeItem(t),null):r.value}function w(t){document.readyState!=="loading"?t():document.addEventListener("DOMContentLoaded",t)}function C(t){return new Promise((e,r)=>setTimeout(()=>r(new Error("Request timeout")),t))}var p=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}};var y={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async getAuthorizationToken(){return fetch("/hc/api/internal/csrf_token.json").then(t=>t.json()).then(t=>t.current_session.csrf_token).catch(t=>{console.error(new Error(t))})}};var x={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},general:{perPage:"100",include:"categories,sections"},async getAll(t=1){let e=`${this.web.subdomain}-articles-p${t}`;if(sessionStorage.getItem(e))return JSON.parse(sessionStorage.getItem(e));let n=await(await fetch(`/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`)).json();for(;n.next_page;){let s=await(await fetch(n.next_page)).json();n.categories.push(...s.categories.filter(i=>n.categories.findIndex(a=>a.id===i.id)===-1)),n.sections.push(...s.sections.filter(i=>n.sections.findIndex(a=>a.id===i.id)===-1)),n.articles=n.articles.concat(s.articles),n.next_page=s.next_page}return sessionStorage.setItem(e,JSON.stringify(n)),n},async searchArticle(t){let n=(o,s={})=>Promise.race([fetch(o,s),new Promise((i,a)=>setTimeout(()=>a(new Error("Request timeout")),8e3))]);try{if(!t||typeof t!="string")return{results:[],count:0};let s=`/api/v2/help_center/articles/search.json?query=${encodeURIComponent(t)}`,i={results:[],next_page:s},a=0;for(;i.next_page&&!(a>50);){let d=await n(i.next_page);if(!d.ok)break;let u=await d.json();if(!Array.isArray(u.results))break;i.results=i.results.concat(u.results),i.next_page=u.next_page,a++}return i}catch(o){return{results:[],error:o.message}}},async vote({articleId:t,vote:e}){var n;let r=JSON.parse((n=sessionStorage.getItem("cur-votes"))!=null?n:"")||{};if(!["up","down"].includes(e))throw new Error(`Tipo de voto "${e}" inv\xE1lido`);try{let o=`/api/v2/help_center/pt-br/articles/${t}/${e}`,s=await fetch(o,{method:"POST",headers:{"content-type":"application/json","x-csrf-token":await y.getAuthorizationToken(),"x-requested-with":"XMLHttpRequest"}});if(!s.ok)throw{message:"A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe atrav\xE9s de uma solicita\xE7\xE3o",code:s.status};return r[t]=e,sessionStorage.setItem("cur-votes",JSON.stringify(r)),s.json()}catch(o){return{error:!0,message:`Ocorreu um erro ao votar no artigo de ID "${t}"`,originalError:`${o.code} - ${o.message}`}}}};var A={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async me(){return await fetch("/api/v2/users/me.json")}};var I={articles:x,users:A};var l=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}searchForArticle(e){return this.use("articles").searchArticle(e)}};function v(t,e=[]){let r=null;if(e.length>0){let n={};for(let o of e)n[o]=I[o];r=n}switch(t){case"v3":return new p(r);case"v4":return new l(r);default:throw new Error(`Unsupported HC version: ${t}`)}}0&&(module.exports={create,getWithExpiry,ready,setWithExpiry,timeout});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/dom/index.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["export * from \"./dom\";\nexport * from \"./utils\";\nexport * from \"./hc\";\n","export function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Unsupported HC version: ${version}`);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,UAAAC,EAAA,YAAAC,IAAA,eAAAC,EAAAL,GCAO,SAASM,EAAMC,EAAsB,CACtC,SAAS,aAAe,UAC1BA,EAAG,EAEH,SAAS,iBAAiB,mBAAoBA,CAAE,CAEpD,CCLO,SAASC,EAAQC,EAA4B,CAClD,OAAO,IAAI,QAAQ,CAACC,EAAGC,IAAW,WAAW,IAAMA,EAAO,IAAI,MAAM,iBAAiB,CAAC,EAAGF,CAAE,CAAC,CAC9F,CCEO,IAAMG,EAAN,KAAiC,CAItC,YAAYC,EAAwB,CAClC,KAAK,IAAMA,GAAA,KAAAA,EAAW,CAAC,CACzB,CAEQ,IAA+BC,EAA0B,CAC/D,IAAMC,EAAS,KAAK,IAAID,CAAG,EAC3B,GAAI,CAACC,EACH,MAAM,IAAI,MACR,UAAUD,CAAG,0FAA0FA,CAAG,KAC5G,EAGF,OAAOC,CACT,CAGA,gBAA+B,CAE7B,OADiB,KAAK,IAAI,UAAU,EACpB,OAAO,CACzB,CACF,EC7BO,IAAMC,EAAY,CACvB,IAAK,CACH,UAAW,OAAO,SAAS,KAC3B,OAAQ,OAAO,SA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A,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["index_exports","__export","create","ready","timeout","__toCommonJS","ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/dom/index.ts","../src/dom/storage.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["export * from \"./dom\";\nexport * from \"./utils\";\nexport * from \"./hc\";\n","\nexport * from \"./storage\"\n\nexport function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","export type ExpiringItem<T> = {\n value: T;\n expiry: number;\n};\n\nexport function setWithExpiry(key: string, value: string, ttlSeconds: number): void {\n const now = Date.now();\n const item: ExpiringItem<string> = {\n value,\n expiry: now + ttlSeconds * 1000,\n };\n localStorage.setItem(key, JSON.stringify(item));\n}\n\nexport function getWithExpiry(key: string): string | null {\n const itemStr = localStorage.getItem(key);\n if (!itemStr) return null;\n\n let item: ExpiringItem<string>;\n try {\n item = JSON.parse(itemStr) as ExpiringItem<string>;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n\n if (typeof item?.value !== \"string\" || typeof item?.expiry !== \"number\") {\n localStorage.removeItem(key);\n return null;\n }\n\n const now = Date.now();\n if (now > item.expiry) {\n localStorage.removeItem(key);\n return null;\n }\n\n return item.value;\n}","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Uns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U,EACpB,cAAcA,CAAK,CACrC,CACF,EC7BO,SAASC,EAAOC,EAAoBC,EAAqC,CAAC,EAAe,CAC9F,IAAIC,EAAoD,KAExD,GAAID,EAAgB,OAAS,EAAG,CAC9B,IAAME,EAAgD,CAAC,EACvD,QAAWC,KAAOH,EAAiBE,EAAOC,CAAG,EAAIC,EAAKD,CAAG,EACzDF,EAAMC,CACR,CAEA,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["index_exports","__export","create","getWithExpiry","ready","setWithExpiry","timeout","__toCommonJS","dom_exports","__export","getWithExpiry","ready","setWithExpiry","setWithExpiry","key","value","ttlSeconds","now","item","getWithExpiry","itemStr","e","ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dom_exports","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dom_exports","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
var w=Object.defineProperty;var y=(t,e)=>{for(var r in e)w(t,r,{get:e[r],enumerable:!0})};var c={};y(c,{getWithExpiry:()=>A,ready:()=>I,setWithExpiry:()=>x});function x(t,e,r){let n=Date.now(),o={value:e,expiry:n+r*1e3};localStorage.setItem(t,JSON.stringify(o))}function A(t){let e=localStorage.getItem(t);if(!e)return null;let r;try{r=JSON.parse(e)}catch(o){return localStorage.removeItem(t),null}return typeof(r==null?void 0:r.value)!="string"||typeof(r==null?void 0:r.expiry)!="number"||Date.now()>r.expiry?(localStorage.removeItem(t),null):r.value}function I(t){document.readyState!=="loading"?t():document.addEventListener("DOMContentLoaded",t)}function _(t){return new Promise((e,r)=>setTimeout(()=>r(new Error("Request timeout")),t))}var p=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}};var d={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async getAuthorizationToken(){return fetch("/hc/api/internal/csrf_token.json").then(t=>t.json()).then(t=>t.current_session.csrf_token).catch(t=>{console.error(new Error(t))})}};var g={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},general:{perPage:"100",include:"categories,sections"},async getAll(t=1){let e=`${this.web.subdomain}-articles-p${t}`;if(sessionStorage.getItem(e))return JSON.parse(sessionStorage.getItem(e));let n=await(await fetch(`/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`)).json();for(;n.next_page;){let s=await(await fetch(n.next_page)).json();n.categories.push(...s.categories.filter(i=>n.categories.findIndex(a=>a.id===i.id)===-1)),n.sections.push(...s.sections.filter(i=>n.sections.findIndex(a=>a.id===i.id)===-1)),n.articles=n.articles.concat(s.articles),n.next_page=s.next_page}return sessionStorage.setItem(e,JSON.stringify(n)),n},async searchArticle(t){let n=(o,s={})=>Promise.race([fetch(o,s),new Promise((i,a)=>setTimeout(()=>a(new Error("Request timeout")),8e3))]);try{if(!t||typeof t!="string")return{results:[],count:0};let s=`/api/v2/help_center/articles/search.json?query=${encodeURIComponent(t)}`,i={results:[],next_page:s},a=0;for(;i.next_page&&!(a>50);){let m=await n(i.next_page);if(!m.ok)break;let u=await m.json();if(!Array.isArray(u.results))break;i.results=i.results.concat(u.results),i.next_page=u.next_page,a++}return i}catch(o){return{results:[],error:o.message}}},async vote({articleId:t,vote:e}){var n;let r=JSON.parse((n=sessionStorage.getItem("cur-votes"))!=null?n:"")||{};if(!["up","down"].includes(e))throw new Error(`Tipo de voto "${e}" inv\xE1lido`);try{let o=`/api/v2/help_center/pt-br/articles/${t}/${e}`,s=await fetch(o,{method:"POST",headers:{"content-type":"application/json","x-csrf-token":await d.getAuthorizationToken(),"x-requested-with":"XMLHttpRequest"}});if(!s.ok)throw{message:"A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe atrav\xE9s de uma solicita\xE7\xE3o",code:s.status};return r[t]=e,sessionStorage.setItem("cur-votes",JSON.stringify(r)),s.json()}catch(o){return{error:!0,message:`Ocorreu um erro ao votar no artigo de ID "${t}"`,originalError:`${o.code} - ${o.message}`}}}};var f={web:{subdomain:window.location.host,locale:window.location.pathname.split("/")[2]},async me(){return await fetch("/api/v2/users/me.json")}};var h={articles:g,users:f};var l=class{constructor(e){this.dom=c;this.api=e!=null?e:{}}use(e){let r=this.api[e];if(!r)throw new Error(`HCv4: "${e}" was not provided as a dependency. Pass it when creating the instance: create("v4", ["${e}"])`);return r}getAllArticles(){return this.use("articles").getAll()}searchForArticle(e){return this.use("articles").searchArticle(e)}};function v(t,e=[]){let r=null;if(e.length>0){let n={};for(let o of e)n[o]=h[o];r=n}switch(t){case"v3":return new p(r);case"v4":return new l(r);default:throw new Error(`Unsupported HC version: ${t}`)}}export{v as create,A as getWithExpiry,I as ready,x as setWithExpiry,_ as timeout};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dom/index.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["export function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Unsupported HC version: ${version}`);\n }\n}\n"],"mappings":"AAAO,SAASA,EAAMC,EAAsB,CACtC,SAAS,aAAe,UAC1BA,EAAG,EAEH,SAAS,iBAAiB,mBAAoBA,CAAE,CAEpD,CCLO,SAASC,EAAQC,EAA4B,CAClD,OAAO,I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C,EAA0B,CAC/D,IAAMC,EAAS,KAAK,IAAID,CAAG,EAC3B,GAAI,CAACC,EACH,MAAM,IAAI,MACR,UAAUD,CAAG,0FAA0FA,CAAG,KAC5G,EAGF,OAAOC,CACT,CAEA,gBAA+B,CAE7B,OADiB,KAAK,IAAI,UAAU,EACpB,OAAO,CACzB,CAEA,iBAAiBC,EAA6B,CAE5C,OADiB,KAAK,IAAI,UAAU,EACpB,cAAcA,CAAK,CACrC,CACF,EC3BO,SAASC,EAAOC,EAAoBC,EAAqC,CAAC,EAAe,CAC9F,IAAIC,EAAoD,KAExD,GAAID,EAAgB,OAAS,EAAG,CAC9B,IAAME,EAAgD,CAAC,EACvD,QAAWC,KAAOH,EAAiBE,EAAOC,CAAG,EAAIC,EAAKD,CAAG,EACzDF,EAAMC,CACR,CAEA,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
|
1
|
+
{"version":3,"sources":["../src/dom/index.ts","../src/dom/storage.ts","../src/utils/index.ts","../src/v3/index.ts","../src/api/internal/index.ts","../src/api/articles/index.ts","../src/api/users/index.ts","../src/api/index.ts","../src/v4/index.ts","../src/hc/factory.ts"],"sourcesContent":["\nexport * from \"./storage\"\n\nexport function ready(fn: () => void): void {\n if (document.readyState !== \"loading\") {\n fn();\n } else {\n document.addEventListener(\"DOMContentLoaded\", fn);\n }\n}\n","export type ExpiringItem<T> = {\n value: T;\n expiry: number;\n};\n\nexport function setWithExpiry(key: string, value: string, ttlSeconds: number): void {\n const now = Date.now();\n const item: ExpiringItem<string> = {\n value,\n expiry: now + ttlSeconds * 1000,\n };\n localStorage.setItem(key, JSON.stringify(item));\n}\n\nexport function getWithExpiry(key: string): string | null {\n const itemStr = localStorage.getItem(key);\n if (!itemStr) return null;\n\n let item: ExpiringItem<string>;\n try {\n item = JSON.parse(itemStr) as ExpiringItem<string>;\n } catch {\n localStorage.removeItem(key);\n return null;\n }\n\n if (typeof item?.value !== \"string\" || typeof item?.expiry !== \"number\") {\n localStorage.removeItem(key);\n return null;\n }\n\n const now = Date.now();\n if (now > item.expiry) {\n localStorage.removeItem(key);\n return null;\n }\n\n return item.value;\n}","\nexport function timeout(ms: number): Promise<never> {\n return new Promise((_, reject) => setTimeout(() => reject(new Error(\"Request timeout\")), ms));\n}\n","import type { APIDependencies, HCInstance } from \"../hc/types\";\n\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\nexport class HCv3 implements HCInstance {\n\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n}\n","export const internals = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async getAuthorizationToken() {\n return fetch('/hc/api/internal/csrf_token.json')\n .then((response) => response.json())\n .then((response) => response.current_session.csrf_token)\n .catch((response) => {\n console.error(new Error(response));\n });\n }\n}","import { ArticleVoteParams } from \"../../shared/types\";\nimport { internals } from \"../internal\"\n\nexport const articles = {\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n general: {\n perPage: \"100\",\n include: \"categories,sections\"\n },\n\n async getAll(page: number = 1) {\n const storageName = `${this.web.subdomain}-articles-p${page}`;\n if (sessionStorage.getItem(storageName)) { return JSON.parse(sessionStorage.getItem(storageName) as string); }\n\n const response = await fetch(\n `/api/v2/help_center/${this.web.locale}/articles?per_page=${this.general.perPage}&include=${this.general.include}`,\n );\n\n const json = await response.json();\n\n while (json.next_page) {\n const nextResult = await fetch(json.next_page);\n const nextJson = await nextResult.json();\n\n json.categories.push(...nextJson.categories\n .filter((nextCategory: any) =>\n json.categories\n .findIndex((category: any) => category.id === nextCategory.id) === -1\n )\n );\n json.sections.push(...nextJson.sections\n .filter((nextSection: any) =>\n json.sections\n .findIndex((section: any) => section.id === nextSection.id) === -1\n )\n );\n json.articles = json.articles.concat(nextJson.articles);\n json.next_page = nextJson.next_page;\n }\n\n sessionStorage.setItem(storageName, JSON.stringify(json));\n return json\n },\n\n async searchArticle(query: string) {\n const MAX_PAGES = 50;\n const REQUEST_TIMEOUT = 8000;\n const fetchWithTimeout = (url: string, options = {}) => {\n return Promise.race([\n fetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => reject(new Error(\"Request timeout\")), REQUEST_TIMEOUT)\n )\n ]);\n };\n\n try {\n if (!query || typeof query !== \"string\") {\n return { results: [], count: 0 };\n }\n const encoded = encodeURIComponent(query);\n let url = `/api/v2/help_center/articles/search.json?query=${encoded}`;\n let json = {\n results: [],\n next_page: url\n };\n\n let pageCount = 0;\n\n while (json.next_page) {\n if (pageCount > MAX_PAGES) {\n break;\n }\n\n const response = await fetchWithTimeout(json.next_page) as Response;\n\n if (!response.ok) break;\n\n\n const data = await response.json();\n if (!Array.isArray(data.results)) {\n break;\n }\n json.results = json.results.concat(data.results);\n json.next_page = data.next_page;\n\n pageCount++;\n }\n\n return json;\n\n } catch (error: any) {\n return { results: [], error: error.message };\n }\n },\n\n async vote({ articleId, vote }: ArticleVoteParams) {\n const sessionVotes = JSON.parse(sessionStorage.getItem('cur-votes') ?? '') || {};\n if (!['up', 'down'].includes(vote)) throw new Error(`Tipo de voto \"${vote}\" inválido`);\n try {\n const baseURL = `/api/v2/help_center/pt-br/articles/${articleId}/${vote}`;\n const response = await fetch(\n baseURL,\n {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-csrf-token': await internals.getAuthorizationToken(),\n 'x-requested-with': 'XMLHttpRequest',\n },\n\n }\n );\n\n if (!response.ok) {\n throw {\n message: 'A API do Zendesk retornou um erro inesperado, tente novamente. Caso o erro persista, nos informe através de uma solicitação',\n code: response.status\n }\n };\n\n sessionVotes[articleId] = vote;\n sessionStorage.setItem('cur-votes', JSON.stringify(sessionVotes));\n\n return response.json();\n } catch (error: any) {\n return {\n error: true,\n message: `Ocorreu um erro ao votar no artigo de ID \"${articleId}\"`,\n originalError: `${error.code} - ${error.message}`\n }\n }\n }\n}","export const users = {\n\n web: {\n subdomain: window.location.host,\n locale: window.location.pathname.split(\"/\")[2]\n },\n\n async me() {\n const json = await fetch('/api/v2/users/me.json')\n return json;\n }\n}","import { articles } from \"./articles\";\nimport { users } from \"./users\";\n\nexport const deps = {\n articles,\n users\n};","import type { APIDependencies, HCInstance } from \"../hc/types\";\nimport type { deps } from \"../api\";\nimport * as dom from \"../dom\";\n\ntype ApiMap = Partial<{ [K in APIDependencies]: (typeof deps)[K] }>;\n\nexport class HCv4 implements HCInstance {\n private api: ApiMap;\n readonly dom = dom;\n\n constructor(apiDeps: ApiMap | null) {\n this.api = apiDeps ?? {};\n }\n\n private use<K extends APIDependencies>(dep: K): (typeof deps)[K] {\n const module = this.api[dep];\n if (!module) {\n throw new Error(\n `HCv4: \"${dep}\" was not provided as a dependency. Pass it when creating the instance: create(\"v4\", [\"${dep}\"])`\n );\n }\n\n return module as (typeof deps)[K];\n }\n\n getAllArticles(): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.getAll();\n }\n\n searchForArticle(query: string): Promise<any> {\n const articles = this.use(\"articles\");\n return articles.searchArticle(query);\n }\n}\n","import type { APIDependencies, HCInstance, HCVersion } from \"./types\";\nimport { HCv3 } from \"../v3\";\nimport { deps } from \"../api/index\"\nimport { HCv4 } from \"../v4\";\n\nexport function create(version: HCVersion, apiDependencies: APIDependencies[] = []): HCInstance {\n let api: Partial<Record<APIDependencies, any>> | null = null\n\n if (apiDependencies.length > 0) {\n const result: Partial<Record<APIDependencies, any>> = {}\n for (const dep of apiDependencies) result[dep] = deps[dep]\n api = result\n }\n\n switch (version) {\n case \"v3\":\n return new HCv3(api);\n case \"v4\":\n return new HCv4(api);\n default:\n throw new Error(`Unsupported HC version: ${version}`);\n }\n}\n"],"mappings":"0FAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,EAAA,UAAAC,EAAA,kBAAAC,ICKO,SAASC,EAAcC,EAAaC,EAAeC,EAA0B,CAClF,IAAMC,EAAM,KAAK,IAAI,EACfC,EAA6B,CACjC,MAAAH,EACA,OAAQE,EAAMD,EAAa,GAC7B,EACA,aAAa,QAAQF,EAAK,KAAK,UAAUI,CAAI,CAAC,CAChD,CAEO,SAASC,EAAcL,EAA4B,CACxD,IAAMM,EAAU,aAAa,QAAQN,CAAG,EACxC,GAAI,CAACM,EAAS,OAAO,KAErB,IAAIF,EACJ,GAAI,CACFA,EAAO,KAAK,MAAME,CAAO,CAC3B,OAAQC,EAAA,CACN,oBAAa,WAAWP,CAAG,EACpB,IACT,CAQA,OANI,OAAOI,GAAA,YAAAA,EAAM,QAAU,UAAY,OAAOA,GAAA,YAAAA,EAAM,SAAW,UAKnD,KAAK,IAAI,EACXA,EAAK,QACb,aAAa,WAAWJ,CAAG,EACpB,MAGFI,EAAK,KACd,CDnCO,SAASI,EAAMC,EAAsB,CACtC,SAAS,aAAe,UAC1BA,EAAG,EAEH,SAAS,iBAAiB,mBAAoBA,CAAE,CAEpD,CERO,SAASC,EAAQC,EAA4B,CAClD,OAAO,IAAI,Q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AA,EAAW,CAAC,CACzB,CAEQ,IAA+BE,EAA0B,CAC/D,IAAMC,EAAS,KAAK,IAAID,CAAG,EAC3B,GAAI,CAACC,EACH,MAAM,IAAI,MACR,UAAUD,CAAG,0FAA0FA,CAAG,KAC5G,EAGF,OAAOC,CACT,CAEA,gBAA+B,CAE7B,OADiB,KAAK,IAAI,UAAU,EACpB,OAAO,CACzB,CAEA,iBAAiBC,EAA6B,CAE5C,OADiB,KAAK,IAAI,UAAU,EACpB,cAAcA,CAAK,CACrC,CACF,EC7BO,SAASC,EAAOC,EAAoBC,EAAqC,CAAC,EAAe,CAC9F,IAAIC,EAAoD,KAExD,GAAID,EAAgB,OAAS,EAAG,CAC9B,IAAME,EAAgD,CAAC,EACvD,QAAWC,KAAOH,EAAiBE,EAAOC,CAAG,EAAIC,EAAKD,CAAG,EACzDF,EAAMC,CACR,CAEA,OAAQH,EAAS,CACf,IAAK,KACH,OAAO,IAAIM,EAAKJ,CAAG,EACrB,IAAK,KACH,OAAO,IAAIK,EAAKL,CAAG,EACrB,QACE,MAAM,IAAI,MAAM,2BAA2BF,CAAO,EAAE,CACxD,CACF","names":["dom_exports","__export","getWithExpiry","ready","setWithExpiry","setWithExpiry","key","value","ttlSeconds","now","item","getWithExpiry","itemStr","e","ready","fn","timeout","ms","_","reject","HCv3","apiDeps","dom_exports","dep","module","internals","response","articles","page","storageName","json","nextJson","nextCategory","category","nextSection","section","query","fetchWithTimeout","url","options","_","reject","pageCount","response","data","error","articleId","vote","_a","sessionVotes","baseURL","internals","users","deps","articles","users","HCv4","apiDeps","dom_exports","dep","module","query","create","version","apiDependencies","api","result","dep","deps","HCv3","HCv4"]}
|
package/package.json
CHANGED