@regojs/erp-sdk 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rego Solution
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # ERP SDK
2
+ Rego Solution ERP SDK to integrate into javascript frameworks (Reactjs, Vuejs, etc..)
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ var y=new TextEncoder,z=new TextDecoder,be=new TextDecoder("utf-8",{fatal:!0});function G(...e){let t=e.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}var ge=/[^\x00-\x7f]/;function I(e){if(typeof e=="string"&&e.length>=128){if(ge.test(e))throw TypeError("non-ASCII string encountered in encode()");return y.encode(e)}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o>127)throw TypeError("non-ASCII string encountered in encode()");t[r]=o}return t}function X(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?"base64url":"base64",omitPadding:t});let r=32768,o=[];for(let i=0;i<e.length;i+=r)o.push(String.fromCharCode.apply(null,e.subarray(i,i+r)));let n=btoa(o.join(""));return t?n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"):n}function q(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?"base64url":"base64"});if(t){if(e.includes("+")||e.includes("/"))throw TypeError("Invalid base64url");e=e.replace(/-/g,"+").replace(/_/g,"/")}let r=atob(e),o=new Uint8Array(r.length);for(let n=0;n<r.length;n++)o[n]=r.charCodeAt(n);return o}class E extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class h extends E{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class p extends E{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class N extends E{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}var Ae="The input to be decoded is not correctly encoded.";function Y(e){try{return q(typeof e=="string"?e:z.decode(e),!0)}catch(t){throw TypeError(Ae,{cause:t})}}function A(e){return X(typeof e=="string"?y.encode(e):e,!0)}function T(e){if(typeof e!="object"||e===null||Object.prototype.toString.call(e)!=="[object Object]")return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Z(...e){let t=new Set;for(let r of e)if(r)for(let o of Object.keys(r)){if(t.has(o))return!1;t.add(o)}return!0}function Q(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}var ee={__proto__:null,b64:!0};function te(e,t){let{crit:r}=t??{};if(Array.isArray(r)&&new Set(r).size!==r.length)throw new e('"crit" (Critical) Header Parameter MUST NOT contain duplicate values')}function re(e,t,r,o,n){if(n.crit!==void 0&&o?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return[];if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some((s)=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i=r===void 0?t:{__proto__:null,...r,...t};for(let s of o.crit){if(!(s in i))throw new h(`Extension Header Parameter "${s}" is not recognized`);if(!Object.hasOwn(n,s)||n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i[s]&&(!Object.hasOwn(o,s)||o[s]===void 0))throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return o.crit}function oe(e,t){if(t.includes("b64")){let r=e.b64;if(typeof r!="boolean")throw new p('The "b64" (base64url-encode payload) Header Parameter must be a boolean');return r}return!0}function D(e,t){let r,o;try{r=JSON.stringify(t),o=JSON.parse(r)}catch(n){throw new e("JOSE Header is not valid JSON",{cause:n})}if(!T(o))throw new e("JOSE Header is not a JSON object");return[o,r]}var Te=(e)=>e[Symbol.toStringTag],_e=(e,t,r)=>{let{alg:o}=e;if(t.use!==void 0){let n=r==="sign"||r==="verify"?"sig":"enc";if(t.use!==n)throw TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==o)throw TypeError(`Invalid key for this operation, its "alg" must be "${o}" when present`);if(Array.isArray(t.key_ops)){let n=r==="encrypt"||r==="decrypt"?e.ops?.[r==="encrypt"?0:1]:r;if(n&&!t.key_ops.includes(n))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}};async function ie(e,t,r){let{alg:o,secret:n}=e,i=r==="decrypt"||r==="sign";if(n&&t instanceof Uint8Array)return t;let s,a;if(T(t)){if(s=Je(t),typeof s.kty!="string")throw ne(o,t,n);if(!(n?s.kty==="oct"&&typeof s.k=="string":s.kty!=="oct"&&(i?s.kty==="AKP"&&typeof s.priv=="string"||typeof s.d=="string":s.d===void 0&&s.priv===void 0)))throw TypeError(n?'JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present':`JSON Web Key for this operation must be a ${i?"private":"public"} JWK`);if(_e(e,s,r),s.kty==="oct")return Y(s.k);if(!Object.isFrozen(t)){let{key_ops:c}=t;Array.isArray(c)&&Object.freeze(c),Object.freeze(t)}}else{if(!Ee(t))throw ne(o,t,n);let c=n?"secret":i?"private":"public";if(t.type!==c&&(n||["secret","public","private"].includes(t.type)))throw TypeError(`${Te(t)} instances must be of type "${c}" for the ${o} algorithm`);if(se(t))return t;if(a=t,a.type==="secret")return a.export()}W||=new WeakMap;let g=t,d=W.get(g);if(d?.[o])return d[o];if(d||W.set(g,d={}),a&&typeof a.toCryptoKey=="function"){let c=a.type==="public",f=Se[a.asymmetricKeyDetails?.namedCurve],l=e.resolve?.({crv:f,asymmetricKeyType:a.asymmetricKeyType})??e.subtle;return d[o]=a.toCryptoKey(l,c,e.usages[c?0:1])}return s??=a.export({format:"jwk"}),s.alg=o,d[o]=await xe(e,s)}var W,Se={__proto__:null,prime256v1:"P-256",secp384r1:"P-384",secp521r1:"P-521"};var se=(e)=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ie=(e)=>e?.[Symbol.toStringTag]==="KeyObject",Ee=(e)=>se(e)||Ie(e);function Ce(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function ne(e,t,r){let o=["CryptoKey","KeyObject","JSON Web Key"];return r&&o.push("Uint8Array"),TypeError(Ce(`Key for the ${e} algorithm must be `,t,...o))}var C=(e,t="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function Re(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ae(e,t){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function ve(e,t,r){let o=e.algorithm;if(o.name!==t.name)throw C(t.name);if(t.hash&&o.hash?.name!==t.hash)throw C(t.hash,"algorithm.hash");if(t.namedCurve&&o.namedCurve!==t.namedCurve)throw C(t.namedCurve,"algorithm.namedCurve");if(t.length!==void 0&&o.length!==t.length)throw C(t.length,"algorithm.length");Re(e,r)}function Ke(e){return{__proto__:null,...e}}function Je(e){let t=Ke(e);if(t.ext!==void 0&&typeof t.ext!="boolean")throw TypeError('"ext" (Extractable) Parameter must be a boolean');if(t.key_ops!==void 0){let r=t.key_ops,o=Array.isArray(r)?[...r]:void 0;if(!o||o.some((n)=>typeof n!="string")||new Set(o).size!==o.length)throw TypeError('"key_ops" (Key Operations) Parameter must be an array of unique strings');t.key_ops=o}return t}async function xe(e,t,r){if(!e.kty.includes(t.kty))throw new h('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');let o=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,n=!!(t.d||t.priv),i={...t,ext:r??t.ext};return i.kty!=="AKP"&&delete i.alg,delete i.use,crypto.subtle.importKey("jwk",i,o,i.ext??!n,t.key_ops??e.usages[n?1:0])}async function ce(e,t,r,o=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey("raw",e,t,o,[r])),ve(e,t,r),e}function pe(e){let t={__proto__:null};for(let r in e)t[r]={...e[r],alg:r};return t}var _=[["verify"],["sign"]];function P(e){let t={name:"HMAC",hash:`SHA-${e}`};return{kty:["oct"],secret:!0,subtle:t,signing:t,usages:_}}function b(e,t){let r={name:t?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:`SHA-${e}`};return{kty:["RSA"],subtle:r,signing:t?{...r,saltLength:t}:r,usages:_,minRsaBits:2048}}function k(e,t){return{kty:["EC"],crv:e,subtle:{name:"ECDSA",namedCurve:e},signing:{name:"ECDSA",hash:`SHA-${t}`},usages:_}}function de(){let e={name:"Ed25519"};return{kty:["OKP"],crv:"Ed25519",subtle:e,signing:e,usages:_}}function j(e){let t={name:`ML-DSA-${e}`};return{kty:["AKP"],subtle:t,signing:t,usages:_}}var Oe=pe({HS256:P(256),HS384:P(384),HS512:P(512),RS256:b(256),RS384:b(384),RS512:b(512),PS256:b(256,32),PS384:b(384,48),PS512:b(512,64),ES256:k("P-256",256),ES384:k("P-384",384),ES512:k("P-521",512),EdDSA:de(),Ed25519:de(),"ML-DSA-44":j(44),"ML-DSA-65":j(65),"ML-DSA-87":j(87)});function me(e){let t=typeof e=="string"?Oe[e]:void 0;if(!t)throw new h(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}var R=(e)=>Math.floor(e.getTime()/1000),Ne={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},De=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function M(){throw TypeError("Invalid time period format")}function ue(e){typeof e!="string"&&M();let t=De.exec(e);(!t||t[4]&&t[1])&&M();let r=parseFloat(t[2]),o=Math.round(r*Ne[t[3][0].toLowerCase()]);return Number.isFinite(o)||M(),t[1]==="-"||t[4]==="ago"?-o:o}function H(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function L(e,t){if(typeof t!="string")throw TypeError(`"${e}" claim must be a string`)}function We(e){if(typeof e!="string"&&(!Array.isArray(e)||Array.from(e).some((t)=>typeof t!="string")))throw TypeError('"aud" claim must be a string or an array of strings')}function U(e,t){return typeof e=="number"?H(t,e):e instanceof Date?H(t,R(e)):R(new Date)+ue(e)}var fe;function u(e){return fe.get(e)}function le(e){let t=u(e);for(let r of["iat","nbf","exp"]){let o=t[r];if(typeof o=="number"&&!Number.isFinite(o))throw TypeError(`"${r}" claim must be a finite number`)}return y.encode(JSON.stringify(t))}class V{constructor(e={}){if(!T(e))throw TypeError("JWT Claims Set MUST be an object");(fe||=new WeakMap).set(this,structuredClone(e))}setIssuer(e){return L("iss",e),u(this).iss=e,this}setSubject(e){return L("sub",e),u(this).sub=e,this}setAudience(e){return We(e),u(this).aud=e,this}setJti(e){return L("jti",e),u(this).jti=e,this}setNotBefore(e){return u(this).nbf=U(e,"setNotBefore"),this}setExpirationTime(e){return u(this).exp=U(e,"setExpirationTime"),this}setIssuedAt(e){let t=u(this);return e===void 0?t.iat=R(new Date):typeof e=="string"?t.iat=H("setIssuedAt",R(new Date)+ue(e)):t.iat=U(e,"setIssuedAt"),this}}async function Pe(e,t,r){let[o,n,i,s]=e,a="";if(n!==void 0){let w=D(p,n);n=w[0],a=A(w[1])}if(i!==void 0&&(i=D(p,i)[0]),!n&&!i)throw new p("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Z(n,i))throw new p("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let g={...n,...i};te(p,n);let d=oe(n,re(p,ee,s,n,g));d||r?.();let{alg:c}=g;if(typeof c!="string"||!c)throw new p('JWS "alg" (Algorithm) Header Parameter missing or invalid');let f=me(c),l="",B=o,x;if(d){let w=e[4];w?(l=w[0]??=A(o),B=w[1]??=I(l)):(l=A(o),x=y.encode(`${a}.${l}`))}x??=G(I(a),I("."),B);let F=await ce(await ie(f,t,"sign"),f.subtle,"sign");f.minRsaBits&&ae(f.alg,F);let O={signature:A(new Uint8Array(await crypto.subtle.sign(f.signing,F,x))),payload:l};return n&&(O.protected=a),i&&(O.header=i),[O,d]}async function ye(e,t,r,o,n){let[i]=await Pe([e,t,void 0,r],o,n);return`${i.protected}.${i.payload}.${i.signature}`}var $e=V;class v extends $e{#e;setProtectedHeader(e){return Q(this.#e,"setProtectedHeader"),this.#e=e,this}async sign(e,t){return ye(le(this),this.#e,t?.crit,e,()=>{throw new N("JWTs MUST NOT use unencoded payload")})}}class m{params;appName="Rego ERP SDK";defaultVersion=1;token;constructor(e){this.params=e}async signToken(){let{params:{credential:{workspaceId:e,appId:t,secret:r},options:o}}=this;try{let n=new Uint8Array(Buffer.from(r,"base64")),i=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-512"},!1,["sign","verify"]),s=await new v({iss:e,aud:t}).setProtectedHeader({alg:"HS512"}).sign(i);return this.token=s,s}catch(n){if(o?.logs)console.error(`[${this.appName}] Sign token error:`,n);throw n}}}var je="https://api.regosolution.com";class S extends m{#e;constructor(e){super(e)}register(e){if(e?.blueprintId)this.#e=e.blueprintId;return this}async getRoutes(){let{params:{credential:{workspaceId:e,appId:t},options:r}}=this;try{if(!this.#e)throw Error("Missing blueprint ID!");let o=this.token||await this.signToken(),n=new Headers;n.append("X-Workspace-ID",e),n.append("X-App-ID",t),n.append("Authorization",`Bearer ${o}`),n.append("Content-Type","application/json");let i=await fetch(`${je}/cms/v${r?.version||this.defaultVersion}/blueprints/${this.#e}`,{method:"GET",headers:n});if(!i.ok)throw await i.json();let{data:s}=await i.json();return Object.freeze({hostname:s?.hostname||null,routes:s?.routes||null,data:s?.data})}catch(o){if(r?.logs)console.error("[CMS] get blueprint routes:",o);throw o}}}class K extends m{constructor(e){super(e)}}class J extends m{constructor(e){super(e)}}class we extends m{#e=new Map;constructor(e){super(e)}use(e){try{let t=this.#e.get(e);return{CMS:(()=>{let r=!t||!(t instanceof S)?new S(this.params):t;return this.#e.set(e,r),r})(),CRM:(()=>{let r=!t||!(t instanceof K)?new K(this.params):t;return this.#e.set(e,r),r})(),PIM:(()=>{let r=!t||!(t instanceof J)?new J(this.params):t;return this.#e.set(e,r),r})()}[e]}catch(t){if(this.params.options?.logs)console.error(`[${this.appName}] App init got problem:`,t);throw t}}}export{we as Client,S as CmsApp};
3
+
4
+ //# debugId=FB084FC1C1208C8264756E2164756E21
@@ -0,0 +1,25 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../node_modules/jose/dist/webapi/lib/buffer_utils.js", "../../node_modules/jose/dist/webapi/util/errors.js", "../../node_modules/jose/dist/webapi/util/base64url.js", "../../node_modules/jose/dist/webapi/lib/validate.js", "../../node_modules/jose/dist/webapi/lib/key.js", "../../node_modules/jose/dist/webapi/lib/key_descriptor.js", "../../node_modules/jose/dist/webapi/lib/jws_algorithms.js", "../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js", "../../node_modules/jose/dist/webapi/lib/jws_sign.js", "../../node_modules/jose/dist/webapi/jwt/sign.js", "../../src/server/providers/app.ts", "../../src/server/constants/variables.ts", "../../src/server/providers/cms.app.ts", "../../src/server/providers/crm.app.ts", "../../src/server/providers/pim.app.ts", "../../src/server/providers/client.ts"],
4
+ "sourcesContent": [
5
+ "const encoder = new TextEncoder(), decoder = new TextDecoder(), strictDecoder = new TextDecoder(\"utf-8\", { fatal: !0 }), MAX_INT32 = 2 ** 32;\nfunction concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0), buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers)\n buf.set(buffer, i), i += buffer.length;\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32)\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);\n}\nfunction uint64be(value) {\n const high = Math.floor(value / MAX_INT32), low = value % MAX_INT32, buf = new Uint8Array(8);\n return writeUInt32BE(buf, high, 0), writeUInt32BE(buf, low, 4), buf;\n}\nfunction uint32be(value) {\n const buf = new Uint8Array(4);\n return writeUInt32BE(buf, value), buf;\n}\nconst NON_ASCII = /[^\\x00-\\x7f]/;\nfunction encode(string) {\n if (typeof string == \"string\" && string.length >= 128) {\n if (NON_ASCII.test(string))\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n return encoder.encode(string);\n }\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127)\n throw new TypeError(\"non-ASCII string encountered in encode()\");\n bytes[i] = code;\n }\n return bytes;\n}\nfunction encodeBase64(input, url = !1) {\n if (Uint8Array.prototype.toBase64)\n return input.toBase64({ alphabet: url ? \"base64url\" : \"base64\", omitPadding: url });\n const CHUNK_SIZE = 32768, arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE)\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n const encoded = btoa(arr.join(\"\"));\n return url ? encoded.replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\") : encoded;\n}\nfunction decodeBase64(encoded, url = !1) {\n if (Uint8Array.fromBase64)\n return Uint8Array.fromBase64(encoded, { alphabet: url ? \"base64url\" : \"base64\" });\n if (url) {\n if (encoded.includes(\"+\") || encoded.includes(\"/\"))\n throw new TypeError(\"Invalid base64url\");\n encoded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\");\n }\n const binary = atob(encoded), bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\nasync function digest(algorithm, data) {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\nexport {\n concat,\n decodeBase64,\n decoder,\n digest,\n encode,\n encodeBase64,\n encoder,\n strictDecoder,\n uint32be,\n uint64be\n};\n",
6
+ "class JOSEError extends Error {\n static code = \"ERR_JOSE_GENERIC\";\n code = \"ERR_JOSE_GENERIC\";\n constructor(message, options) {\n super(message, options), this.name = this.constructor.name, Error.captureStackTrace?.(this, this.constructor);\n }\n}\nclass JWTClaimValidationFailed extends JOSEError {\n static code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n code = \"ERR_JWT_CLAIM_VALIDATION_FAILED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JWTExpired extends JOSEError {\n static code = \"ERR_JWT_EXPIRED\";\n code = \"ERR_JWT_EXPIRED\";\n claim;\n reason;\n payload;\n constructor(message, payload, claim = \"unspecified\", reason = \"unspecified\") {\n super(message, { cause: { claim, reason, payload } }), this.claim = claim, this.reason = reason, this.payload = payload;\n }\n}\nclass JOSEAlgNotAllowed extends JOSEError {\n static code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n code = \"ERR_JOSE_ALG_NOT_ALLOWED\";\n}\nclass JOSENotSupported extends JOSEError {\n static code = \"ERR_JOSE_NOT_SUPPORTED\";\n code = \"ERR_JOSE_NOT_SUPPORTED\";\n}\nclass JWEDecryptionFailed extends JOSEError {\n static code = \"ERR_JWE_DECRYPTION_FAILED\";\n code = \"ERR_JWE_DECRYPTION_FAILED\";\n constructor(message = \"decryption operation failed\", options) {\n super(message, options);\n }\n}\nclass JWEInvalid extends JOSEError {\n static code = \"ERR_JWE_INVALID\";\n code = \"ERR_JWE_INVALID\";\n}\nclass JWSInvalid extends JOSEError {\n static code = \"ERR_JWS_INVALID\";\n code = \"ERR_JWS_INVALID\";\n}\nclass JWTInvalid extends JOSEError {\n static code = \"ERR_JWT_INVALID\";\n code = \"ERR_JWT_INVALID\";\n}\nclass JWKInvalid extends JOSEError {\n static code = \"ERR_JWK_INVALID\";\n code = \"ERR_JWK_INVALID\";\n}\nclass JWKSInvalid extends JOSEError {\n static code = \"ERR_JWKS_INVALID\";\n code = \"ERR_JWKS_INVALID\";\n}\nclass JWKSNoMatchingKey extends JOSEError {\n static code = \"ERR_JWKS_NO_MATCHING_KEY\";\n code = \"ERR_JWKS_NO_MATCHING_KEY\";\n constructor(message = \"no applicable key found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator] = async function* () {\n };\n static code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n code = \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\";\n constructor(message = \"multiple matching keys found in the JSON Web Key Set\", options) {\n super(message, options);\n }\n}\nclass JWKSTimeout extends JOSEError {\n static code = \"ERR_JWKS_TIMEOUT\";\n code = \"ERR_JWKS_TIMEOUT\";\n constructor(message = \"request timed out\", options) {\n super(message, options);\n }\n}\nclass JWSSignatureVerificationFailed extends JOSEError {\n static code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n code = \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\";\n constructor(message = \"signature verification failed\", options) {\n super(message, options);\n }\n}\nexport {\n JOSEAlgNotAllowed,\n JOSEError,\n JOSENotSupported,\n JWEDecryptionFailed,\n JWEInvalid,\n JWKInvalid,\n JWKSInvalid,\n JWKSMultipleMatchingKeys,\n JWKSNoMatchingKey,\n JWKSTimeout,\n JWSInvalid,\n JWSSignatureVerificationFailed,\n JWTClaimValidationFailed,\n JWTExpired,\n JWTInvalid\n};\n",
7
+ "import { encoder, decoder, encodeBase64, decodeBase64 } from \"../lib/buffer_utils.js\";\nconst invalid = \"The input to be decoded is not correctly encoded.\";\nfunction decode(input) {\n try {\n return decodeBase64(typeof input == \"string\" ? input : decoder.decode(input), !0);\n } catch (cause) {\n throw new TypeError(invalid, { cause });\n }\n}\nfunction encode(input) {\n return encodeBase64(typeof input == \"string\" ? encoder.encode(input) : input, !0);\n}\nexport {\n decode,\n encode\n};\n",
8
+ "import { JOSENotSupported, JWSInvalid } from \"../util/errors.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { encode, strictDecoder } from \"./buffer_utils.js\";\nfunction assertUint8Array(input, label) {\n if (!(input instanceof Uint8Array))\n throw new TypeError(`${label} must be an instance of Uint8Array`);\n}\nfunction isObject(input) {\n if (typeof input != \"object\" || input === null || Object.prototype.toString.call(input) !== \"[object Object]\")\n return !1;\n const prototype = Object.getPrototypeOf(input);\n return prototype === null || Object.getPrototypeOf(prototype) === null;\n}\nfunction isJwkSet(input) {\n return isObject(input) && Array.isArray(input.keys) && Array.from(input.keys).every(isObject);\n}\nfunction isDisjoint(...headers) {\n const parameters = /* @__PURE__ */ new Set();\n for (const header of headers)\n if (header)\n for (const parameter of Object.keys(header)) {\n if (parameters.has(parameter))\n return !1;\n parameters.add(parameter);\n }\n return !0;\n}\nfunction assertNotSet(value, name) {\n if (value !== void 0)\n throw new TypeError(`${name} can only be called once`);\n}\nfunction decodeBase64url(value, label, ErrorClass) {\n try {\n return decode(value);\n } catch {\n throw new ErrorClass(`Failed to base64url decode the ${label}`);\n }\n}\nfunction encodeBase64url(value, label, ErrorClass) {\n try {\n return encode(value);\n } catch {\n throw new ErrorClass(`The ${label} is not a valid base64url string`);\n }\n}\nfunction parseJoseHeader(b64, ErrorClass, message) {\n let parsed;\n try {\n parsed = JSON.parse(strictDecoder.decode(decode(b64)));\n } catch {\n throw new ErrorClass(message);\n }\n if (!isObject(parsed))\n throw new ErrorClass(message);\n return parsed;\n}\nconst JWS_RECOGNIZED = { __proto__: null, b64: !0 }, JWE_RECOGNIZED = { __proto__: null };\nfunction validateAlgorithms(option, algorithms) {\n if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s != \"string\")))\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n return algorithms === void 0 ? void 0 : new Set(algorithms);\n}\nfunction validateCritDuplicates(Err, protectedHeader) {\n const { crit } = protectedHeader ?? {};\n if (Array.isArray(crit) && new Set(crit).size !== crit.length)\n throw new Err('\"crit\" (Critical) Header Parameter MUST NOT contain duplicate values');\n}\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0)\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n if (!protectedHeader || protectedHeader.crit === void 0)\n return [];\n if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input != \"string\" || input.length === 0))\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n const recognized = recognizedOption === void 0 ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };\n for (const parameter of protectedHeader.crit) {\n if (!(parameter in recognized))\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === void 0)\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === void 0))\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n return protectedHeader.crit;\n}\nfunction validateB64(protectedHeader, extensions) {\n if (extensions.includes(\"b64\")) {\n const b64 = protectedHeader.b64;\n if (typeof b64 != \"boolean\")\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n return b64;\n }\n return !0;\n}\nfunction serializeJoseHeader(Err, header) {\n let serialized, parsed;\n try {\n serialized = JSON.stringify(header), parsed = JSON.parse(serialized);\n } catch (cause) {\n throw new Err(\"JOSE Header is not valid JSON\", { cause });\n }\n if (!isObject(parsed))\n throw new Err(\"JOSE Header is not a JSON object\");\n return [parsed, serialized];\n}\nexport {\n JWE_RECOGNIZED,\n JWS_RECOGNIZED,\n assertNotSet,\n assertUint8Array,\n decodeBase64url,\n encodeBase64url,\n isDisjoint,\n isJwkSet,\n isObject,\n parseJoseHeader,\n serializeJoseHeader,\n validateAlgorithms,\n validateB64,\n validateCrit,\n validateCritDuplicates\n};\n",
9
+ "import { isObject } from \"./validate.js\";\nimport { decode } from \"../util/base64url.js\";\nimport { JOSENotSupported } from \"../util/errors.js\";\nconst tag = (key) => key[Symbol.toStringTag], jwkMatchesOp = (entry, key, usage) => {\n const { alg } = entry;\n if (key.use !== void 0) {\n const expected = usage === \"sign\" || usage === \"verify\" ? \"sig\" : \"enc\";\n if (key.use !== expected)\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n if (key.alg !== void 0 && key.alg !== alg)\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n if (Array.isArray(key.key_ops)) {\n const expectedKeyOp = usage === \"encrypt\" || usage === \"decrypt\" ? entry.ops?.[usage === \"encrypt\" ? 0 : 1] : usage;\n if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp))\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n};\nasync function prepareKey(entry, key, usage) {\n const { alg, secret } = entry, privateKey = usage === \"decrypt\" || usage === \"sign\";\n if (secret && key instanceof Uint8Array)\n return key;\n let normalized, keyObject;\n if (isObject(key)) {\n if (normalized = normalizeJwk(key), typeof normalized.kty != \"string\")\n throw invalidKeyType(alg, key, secret);\n if (!(secret ? normalized.kty === \"oct\" && typeof normalized.k == \"string\" : normalized.kty !== \"oct\" && (privateKey ? normalized.kty === \"AKP\" && typeof normalized.priv == \"string\" || typeof normalized.d == \"string\" : normalized.d === void 0 && normalized.priv === void 0)))\n throw new TypeError(secret ? 'JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present' : `JSON Web Key for this operation must be a ${privateKey ? \"private\" : \"public\"} JWK`);\n if (jwkMatchesOp(entry, normalized, usage), normalized.kty === \"oct\")\n return decode(normalized.k);\n if (!Object.isFrozen(key)) {\n const { key_ops } = key;\n Array.isArray(key_ops) && Object.freeze(key_ops), Object.freeze(key);\n }\n } else {\n if (!isKeyLike(key))\n throw invalidKeyType(alg, key, secret);\n const expectedType = secret ? \"secret\" : privateKey ? \"private\" : \"public\";\n if (key.type !== expectedType && (secret || [\"secret\", \"public\", \"private\"].includes(key.type)))\n throw new TypeError(`${tag(key)} instances must be of type \"${expectedType}\" for the ${alg} algorithm`);\n if (isCryptoKey(key))\n return key;\n if (keyObject = key, keyObject.type === \"secret\")\n return keyObject.export();\n }\n cache ||= /* @__PURE__ */ new WeakMap();\n const cacheKey = key;\n let cached = cache.get(cacheKey);\n if (cached?.[alg])\n return cached[alg];\n if (cached || cache.set(cacheKey, cached = {}), keyObject && typeof keyObject.toCryptoKey == \"function\") {\n const isPublic = keyObject.type === \"public\", crv = nist[keyObject.asymmetricKeyDetails?.namedCurve], params = entry.resolve?.({ crv, asymmetricKeyType: keyObject.asymmetricKeyType }) ?? entry.subtle;\n return cached[alg] = keyObject.toCryptoKey(params, isPublic, entry.usages[isPublic ? 0 : 1]);\n }\n return normalized ??= keyObject.export({ format: \"jwk\" }), normalized.alg = alg, cached[alg] = await jwkToKey(entry, normalized);\n}\nlet cache;\nconst nist = {\n __proto__: null,\n prime256v1: \"P-256\",\n secp384r1: \"P-384\",\n secp521r1: \"P-521\"\n};\nfunction assertCryptoKey(key) {\n if (!isCryptoKey(key))\n throw new Error(\"CryptoKey instance expected\");\n}\nconst isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === \"CryptoKey\")\n return !0;\n try {\n return key instanceof CryptoKey;\n } catch {\n return !1;\n }\n}, isKeyObject = (key) => key?.[Symbol.toStringTag] === \"KeyObject\", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\nfunction message(msg, actual, ...types) {\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(\", \")}, or ${last}.`;\n } else types.length === 2 ? msg += `one of type ${types[0]} or ${types[1]}.` : msg += `of type ${types[0]}.`;\n return actual == null ? msg += ` Received ${actual}` : typeof actual == \"function\" && actual.name ? msg += ` Received function ${actual.name}` : typeof actual == \"object\" && actual != null && actual.constructor?.name && (msg += ` Received an instance of ${actual.constructor.name}`), msg;\n}\nconst invalidKeyInput = (actual, ...types) => message(\"Key must be \", actual, ...types);\nfunction invalidKeyType(alg, actual, secret) {\n const types = [\"CryptoKey\", \"KeyObject\", \"JSON Web Key\"];\n return secret && types.push(\"Uint8Array\"), new TypeError(message(`Key for the ${alg} algorithm must be `, actual, ...types));\n}\nconst unusable = (name, prop = \"algorithm.name\") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage))\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n}\nfunction checkModulusLength(alg, key) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength != \"number\" || modulusLength < 2048)\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n}\nfunction checkCryptoKey(key, expected, usage) {\n const algorithm = key.algorithm;\n if (algorithm.name !== expected.name)\n throw unusable(expected.name);\n if (expected.hash && algorithm.hash?.name !== expected.hash)\n throw unusable(expected.hash, \"algorithm.hash\");\n if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve)\n throw unusable(expected.namedCurve, \"algorithm.namedCurve\");\n if (expected.length !== void 0 && algorithm.length !== expected.length)\n throw unusable(expected.length, \"algorithm.length\");\n checkUsage(key, usage);\n}\nfunction snapshotJwk(jwk) {\n return { __proto__: null, ...jwk };\n}\nfunction normalizeJwk(jwk) {\n const normalized = snapshotJwk(jwk);\n if (normalized.ext !== void 0 && typeof normalized.ext != \"boolean\")\n throw new TypeError('\"ext\" (Extractable) Parameter must be a boolean');\n if (normalized.key_ops !== void 0) {\n const value = normalized.key_ops, keyOps = Array.isArray(value) ? [...value] : void 0;\n if (!keyOps || keyOps.some((operation) => typeof operation != \"string\") || new Set(keyOps).size !== keyOps.length)\n throw new TypeError('\"key_ops\" (Key Operations) Parameter must be an array of unique strings');\n normalized.key_ops = keyOps;\n }\n return normalized;\n}\nfunction validateExtractableOption(extractable) {\n if (extractable !== void 0 && typeof extractable != \"boolean\")\n throw new TypeError('\"extractable\" option must be a boolean');\n return extractable;\n}\nasync function jwkToKey(entry, jwk, extractable) {\n if (!entry.kty.includes(jwk.kty))\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle, isPrivate = !!(jwk.d || jwk.priv), keyData = { ...jwk, ext: extractable ?? jwk.ext };\n return keyData.kty !== \"AKP\" && delete keyData.alg, delete keyData.use, crypto.subtle.importKey(\"jwk\", keyData, algorithm, keyData.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);\n}\nasync function rawKey(key, expected, usage, extractable = !1) {\n return key instanceof Uint8Array && (key = await crypto.subtle.importKey(\"raw\", key, expected, extractable, [usage])), checkCryptoKey(key, expected, usage), key;\n}\nexport {\n assertCryptoKey,\n checkCryptoKey,\n checkModulusLength,\n checkUsage,\n invalidKeyInput,\n isCryptoKey,\n isKeyLike,\n isKeyObject,\n jwkToKey,\n normalizeJwk,\n prepareKey,\n rawKey,\n snapshotJwk,\n validateExtractableOption\n};\n",
10
+ "function table(entries) {\n const out = { __proto__: null };\n for (const alg in entries)\n out[alg] = { ...entries[alg], alg };\n return out;\n}\nexport {\n table\n};\n",
11
+ "import { JOSENotSupported } from \"../util/errors.js\";\nimport { table } from \"./key_descriptor.js\";\nconst sig = [[\"verify\"], [\"sign\"]];\nfunction hmac(bits) {\n const subtle = { name: \"HMAC\", hash: `SHA-${bits}` };\n return { kty: [\"oct\"], secret: !0, subtle, signing: subtle, usages: sig };\n}\nfunction rsa(bits, saltLength) {\n const subtle = { name: saltLength ? \"RSA-PSS\" : \"RSASSA-PKCS1-v1_5\", hash: `SHA-${bits}` };\n return {\n kty: [\"RSA\"],\n subtle,\n signing: saltLength ? { ...subtle, saltLength } : subtle,\n usages: sig,\n minRsaBits: 2048\n };\n}\nfunction ecdsa(crv, bits) {\n return {\n kty: [\"EC\"],\n crv,\n subtle: { name: \"ECDSA\", namedCurve: crv },\n signing: { name: \"ECDSA\", hash: `SHA-${bits}` },\n usages: sig\n };\n}\nfunction eddsa() {\n const subtle = { name: \"Ed25519\" };\n return {\n kty: [\"OKP\"],\n crv: \"Ed25519\",\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nfunction mldsa(bits) {\n const subtle = { name: `ML-DSA-${bits}` };\n return {\n kty: [\"AKP\"],\n subtle,\n signing: subtle,\n usages: sig\n };\n}\nconst JWS = table({\n HS256: hmac(256),\n HS384: hmac(384),\n HS512: hmac(512),\n RS256: rsa(256),\n RS384: rsa(384),\n RS512: rsa(512),\n PS256: rsa(256, 32),\n PS384: rsa(384, 48),\n PS512: rsa(512, 64),\n ES256: ecdsa(\"P-256\", 256),\n ES384: ecdsa(\"P-384\", 384),\n ES512: ecdsa(\"P-521\", 512),\n EdDSA: eddsa(),\n Ed25519: eddsa(),\n \"ML-DSA-44\": mldsa(44),\n \"ML-DSA-65\": mldsa(65),\n \"ML-DSA-87\": mldsa(87)\n});\nfunction jwsAlgorithm(alg) {\n const entry = typeof alg == \"string\" ? JWS[alg] : void 0;\n if (!entry)\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n return entry;\n}\nexport {\n JWS,\n jwsAlgorithm\n};\n",
12
+ "import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from \"../util/errors.js\";\nimport { encoder, strictDecoder } from \"./buffer_utils.js\";\nimport { isObject } from \"./validate.js\";\nconst epoch = (date) => Math.floor(date.getTime() / 1e3), multipliers = {\n s: 1,\n m: 60,\n h: 3600,\n d: 86400,\n w: 604800,\n y: 31557600\n}, REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i, checkFailed = \"check_failed\";\nfunction invalidDuration() {\n throw new TypeError(\"Invalid time period format\");\n}\nfunction secs(str) {\n typeof str != \"string\" && invalidDuration();\n const matched = REGEX.exec(str);\n (!matched || matched[4] && matched[1]) && invalidDuration();\n const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);\n return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === \"-\" || matched[4] === \"ago\" ? -numericDate2 : numericDate2;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input))\n throw new TypeError(`Invalid ${label} input`);\n return input;\n}\nfunction validateStringClaim(claim, value) {\n if (typeof value != \"string\")\n throw new TypeError(`\"${claim}\" claim must be a string`);\n}\nfunction validateAudienceClaim(value) {\n if (typeof value != \"string\" && (!Array.isArray(value) || Array.from(value).some((member) => typeof member != \"string\")))\n throw new TypeError('\"aud\" claim must be a string or an array of strings');\n}\nfunction numericDate(value, label) {\n return typeof value == \"number\" ? validateInput(label, value) : value instanceof Date ? validateInput(label, epoch(value)) : epoch(/* @__PURE__ */ new Date()) + secs(value);\n}\nconst normalizeTyp = (value) => {\n const normalized = value.toLowerCase();\n return value.includes(\"/\") ? normalized : `application/${normalized}`;\n}, checkAudiencePresence = (audPayload, audOption) => typeof audPayload == \"string\" ? audOption.includes(audPayload) : Array.isArray(audPayload) ? audOption.some((aud) => audPayload.includes(aud)) : !1;\nfunction validateNumericDate(payload, claim, required = !1) {\n const value = payload[claim];\n if (!(value === void 0 && !required)) {\n if (typeof value != \"number\")\n throw new JWTClaimValidationFailed(`\"${claim}\" claim must be a number`, payload, claim, \"invalid\");\n return value;\n }\n}\nfunction unexpectedClaim(payload, claim) {\n throw new JWTClaimValidationFailed(`unexpected \"${claim}\" claim value`, payload, claim, checkFailed);\n}\nfunction validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(strictDecoder.decode(encodedPayload));\n } catch {\n }\n if (!isObject(payload))\n throw new JWTInvalid(\"JWT Claims Set must be a top-level JSON object\");\n const { typ } = options;\n if (typ !== void 0 && (typeof protectedHeader.typ != \"string\" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ)))\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, \"typ\", checkFailed);\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options, presenceCheck = [...requiredClaims];\n maxTokenAge !== void 0 && presenceCheck.push(\"iat\"), audience !== void 0 && presenceCheck.push(\"aud\"), subject !== void 0 && presenceCheck.push(\"sub\"), issuer !== void 0 && presenceCheck.push(\"iss\");\n for (const claim of new Set(presenceCheck.reverse()))\n if (!Object.hasOwn(payload, claim))\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, \"missing\");\n issuer !== void 0 && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss) && unexpectedClaim(payload, \"iss\"), subject !== void 0 && payload.sub !== subject && unexpectedClaim(payload, \"sub\"), audience !== void 0 && !checkAudiencePresence(payload.aud, typeof audience == \"string\" ? [audience] : audience) && unexpectedClaim(payload, \"aud\");\n const { clockTolerance } = options;\n let tolerance = 0;\n if (typeof clockTolerance == \"string\")\n tolerance = secs(clockTolerance);\n else if (clockTolerance !== void 0) {\n if (typeof clockTolerance != \"number\")\n throw new TypeError(\"Invalid clockTolerance option type\");\n tolerance = clockTolerance;\n }\n validateInput(\"clockTolerance option\", tolerance);\n const { currentDate } = options, now = validateInput(\"currentDate option\", epoch(currentDate === void 0 ? /* @__PURE__ */ new Date() : currentDate)), iat = validateNumericDate(payload, \"iat\", maxTokenAge !== void 0), nbf = validateNumericDate(payload, \"nbf\");\n if (nbf !== void 0 && nbf > now + tolerance)\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, \"nbf\", checkFailed);\n const exp = validateNumericDate(payload, \"exp\");\n if (exp !== void 0 && exp <= now - tolerance)\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, \"exp\", checkFailed);\n if (maxTokenAge !== void 0) {\n const age = now - iat, max = validateInput(\"maxTokenAge option\", typeof maxTokenAge == \"number\" ? maxTokenAge : secs(maxTokenAge));\n if (age - tolerance > max)\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, \"iat\", checkFailed);\n if (age < -tolerance)\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, \"iat\", checkFailed);\n }\n return payload;\n}\nlet producerPayloads;\nfunction producerPayload(producer) {\n return producerPayloads.get(producer);\n}\nfunction jwtData(producer) {\n const payload = producerPayload(producer);\n for (const claim of [\"iat\", \"nbf\", \"exp\"]) {\n const value = payload[claim];\n if (typeof value == \"number\" && !Number.isFinite(value))\n throw new TypeError(`\"${claim}\" claim must be a finite number`);\n }\n return encoder.encode(JSON.stringify(payload));\n}\nfunction jwtClaim(producer, claim) {\n return producerPayload(producer)[claim];\n}\nclass JWTClaimsBuilder {\n constructor(payload = {}) {\n if (!isObject(payload))\n throw new TypeError(\"JWT Claims Set MUST be an object\");\n (producerPayloads ||= /* @__PURE__ */ new WeakMap()).set(this, structuredClone(payload));\n }\n setIssuer(value) {\n return validateStringClaim(\"iss\", value), producerPayload(this).iss = value, this;\n }\n setSubject(value) {\n return validateStringClaim(\"sub\", value), producerPayload(this).sub = value, this;\n }\n setAudience(value) {\n return validateAudienceClaim(value), producerPayload(this).aud = value, this;\n }\n setJti(value) {\n return validateStringClaim(\"jti\", value), producerPayload(this).jti = value, this;\n }\n setNotBefore(value) {\n return producerPayload(this).nbf = numericDate(value, \"setNotBefore\"), this;\n }\n setExpirationTime(value) {\n return producerPayload(this).exp = numericDate(value, \"setExpirationTime\"), this;\n }\n setIssuedAt(value) {\n const payload = producerPayload(this);\n return value === void 0 ? payload.iat = epoch(/* @__PURE__ */ new Date()) : typeof value == \"string\" ? payload.iat = validateInput(\"setIssuedAt\", epoch(/* @__PURE__ */ new Date()) + secs(value)) : payload.iat = numericDate(value, \"setIssuedAt\"), this;\n }\n}\nexport {\n JWTClaimsBuilder,\n jwtClaim,\n jwtData,\n secs,\n validateClaimsSet\n};\n",
13
+ "import { encode as b64u } from \"../util/base64url.js\";\nimport { jwsAlgorithm } from \"./jws_algorithms.js\";\nimport { isDisjoint, serializeJoseHeader, validateB64, validateCrit, validateCritDuplicates, JWS_RECOGNIZED } from \"./validate.js\";\nimport { JWSInvalid } from \"../util/errors.js\";\nimport { concat, encode, encoder } from \"./buffer_utils.js\";\nimport { prepareKey, rawKey, checkModulusLength } from \"./key.js\";\nasync function createSignature(input, key, rejectUnencoded) {\n let [payload, protectedHeader, unprotectedHeader, crit] = input, protectedHeaderString = \"\";\n if (protectedHeader !== void 0) {\n const normalized = serializeJoseHeader(JWSInvalid, protectedHeader);\n protectedHeader = normalized[0], protectedHeaderString = b64u(normalized[1]);\n }\n if (unprotectedHeader !== void 0 && (unprotectedHeader = serializeJoseHeader(JWSInvalid, unprotectedHeader)[0]), !protectedHeader && !unprotectedHeader)\n throw new JWSInvalid(\"either setProtectedHeader or setUnprotectedHeader must be called before #sign()\");\n if (!isDisjoint(protectedHeader, unprotectedHeader))\n throw new JWSInvalid(\"JWS Protected and JWS Unprotected Header Parameter names must be disjoint\");\n const joseHeader = { ...protectedHeader, ...unprotectedHeader };\n validateCritDuplicates(JWSInvalid, protectedHeader);\n const b64 = validateB64(protectedHeader, validateCrit(JWSInvalid, JWS_RECOGNIZED, crit, protectedHeader, joseHeader));\n b64 || rejectUnencoded?.();\n const { alg } = joseHeader;\n if (typeof alg != \"string\" || !alg)\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n const entry = jwsAlgorithm(alg);\n let payloadS = \"\", payloadB = payload, data;\n if (b64) {\n const encoded = input[4];\n encoded ? (payloadS = encoded[0] ??= b64u(payload), payloadB = encoded[1] ??= encode(payloadS)) : (payloadS = b64u(payload), data = encoder.encode(`${protectedHeaderString}.${payloadS}`));\n }\n data ??= concat(encode(protectedHeaderString), encode(\".\"), payloadB);\n const k = await rawKey(await prepareKey(entry, key, \"sign\"), entry.subtle, \"sign\");\n entry.minRsaBits && checkModulusLength(entry.alg, k);\n const jws = {\n signature: b64u(new Uint8Array(await crypto.subtle.sign(entry.signing, k, data))),\n payload: payloadS\n };\n return protectedHeader && (jws.protected = protectedHeaderString), unprotectedHeader && (jws.header = unprotectedHeader), [jws, b64];\n}\nasync function createCompactSignature(payload, protectedHeader, crit, key, rejectUnencoded) {\n const [jws] = await createSignature([payload, protectedHeader, void 0, crit], key, rejectUnencoded);\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n}\nexport {\n createCompactSignature,\n createSignature\n};\n",
14
+ "import { createCompactSignature } from \"../lib/jws_sign.js\";\nimport { JWTInvalid } from \"../util/errors.js\";\nimport { JWTClaimsBuilder, jwtData } from \"../lib/jwt_claims_set.js\";\nimport { assertNotSet } from \"../lib/validate.js\";\nconst SignJWT_base = JWTClaimsBuilder;\nclass SignJWT extends SignJWT_base {\n #protectedHeader;\n setProtectedHeader(protectedHeader) {\n return assertNotSet(this.#protectedHeader, \"setProtectedHeader\"), this.#protectedHeader = protectedHeader, this;\n }\n async sign(key, options) {\n return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {\n throw new JWTInvalid(\"JWTs MUST NOT use unencoded payload\");\n });\n }\n}\nexport {\n SignJWT\n};\n",
15
+ "import type { IApp, TCredential, TOptions } from \"../types\";\n\nimport { SignJWT } from \"jose\";\n\nexport class App implements IApp {\n protected appName = \"Rego ERP SDK\";\n protected defaultVersion: number = 1;\n protected token?: string;\n\n /**\n * Initialize Rego ERP client instance\n * @param configs\n * @param options\n */\n constructor(\n protected readonly params: Readonly<{\n credential: TCredential;\n options?: TOptions;\n }>\n ) {}\n\n /**\n * Sign JWT token with Ed25519 algorithm\n * @returns\n */\n async signToken() {\n const {\n params: {\n credential: { workspaceId, appId, secret },\n options\n }\n } = this;\n\n try {\n const rawKey = new Uint8Array(Buffer.from(secret, \"base64\"));\n\n const privateKey = await crypto.subtle.importKey(\n \"raw\",\n rawKey,\n { name: \"HMAC\", hash: \"SHA-512\" },\n false,\n [\"sign\", \"verify\"]\n );\n\n const jwt = await new SignJWT({\n iss: workspaceId,\n aud: appId\n })\n .setProtectedHeader({ alg: \"HS512\" })\n .sign(privateKey);\n\n this.token = jwt;\n\n return jwt;\n } catch (error) {\n if (options?.logs) {\n console.error(`[${this.appName}] Sign token error:`, error);\n }\n\n throw error;\n }\n }\n}\n",
16
+ "export const baseUri = \"https://api.regosolution.com\";\n",
17
+ "import type { ICmsApp, TApiResponse, TCredential, TOptions } from \"../types\";\n\nimport { Variables } from \"../constants\";\nimport { App } from \"./app\";\n\nexport class CmsApp extends App implements ICmsApp {\n #blueprintId?: string;\n\n /**\n * Initialize Rego ERP CMS app instance\n * @param configs\n * @param options\n */\n constructor(\n params: Readonly<{\n credential: TCredential;\n options?: TOptions;\n }>\n ) {\n super(params);\n }\n\n register(\n payload: Parameters<ICmsApp[\"register\"]>[number]\n ): ReturnType<ICmsApp[\"register\"]> {\n if (payload?.blueprintId) {\n this.#blueprintId = payload.blueprintId;\n }\n\n return this;\n }\n\n async getRoutes(): ReturnType<ICmsApp[\"getRoutes\"]> {\n const {\n params: {\n credential: { workspaceId, appId },\n options\n }\n } = this;\n\n try {\n if (!this.#blueprintId) {\n throw new Error(\"Missing blueprint ID!\");\n }\n\n const authToken = this.token || (await this.signToken());\n const requestHeaders = new Headers();\n\n requestHeaders.append(\"X-Workspace-ID\", workspaceId);\n requestHeaders.append(\"X-App-ID\", appId);\n requestHeaders.append(\"Authorization\", `Bearer ${authToken}`);\n requestHeaders.append(\"Content-Type\", \"application/json\");\n\n const response = await fetch(\n `${Variables.baseUri}/cms/v${\n options?.version || this.defaultVersion\n }/blueprints/${this.#blueprintId}`,\n {\n method: \"GET\",\n headers: requestHeaders\n }\n );\n\n if (!response.ok) {\n throw await response.json();\n }\n\n const { data } = (await response.json()) as TApiResponse<\n ICmsApp[\"getRoutes\"]\n >;\n\n return Object.freeze({\n hostname: data?.hostname || null,\n routes: data?.routes || null,\n data: data?.data\n });\n } catch (error) {\n if (options?.logs) {\n console.error(\"[CMS] get blueprint routes:\", error);\n }\n\n throw error;\n }\n }\n}\n",
18
+ "import type { ICrmApp, TCredential, TOptions } from \"../types\";\n\nimport { App } from \"./app\";\n\nexport class CrmApp extends App implements ICrmApp {\n /**\n * Initialize Rego ERP PIM app instance\n * @param configs\n * @param options\n */\n constructor(\n params: Readonly<{\n credential: TCredential;\n options?: TOptions;\n }>\n ) {\n super(params);\n }\n}\n",
19
+ "import type { IPimApp, TCredential, TOptions } from \"../types\";\n\nimport { App } from \"./app\";\n\nexport class PimApp extends App implements IPimApp {\n /**\n * Initialize Rego ERP PIM app instance\n * @param configs\n * @param options\n */\n constructor(\n params: Readonly<{\n credential: TCredential;\n options?: TOptions;\n }>\n ) {\n super(params);\n }\n}\n",
20
+ "import type { IClient, TApps, TCredential, TOptions } from \"../types\";\n\nimport { App } from \"./app\";\nimport { CmsApp } from \"./cms.app\";\nimport { CrmApp } from \"./crm.app\";\nimport { PimApp } from \"./pim.app\";\n\nexport class Client extends App implements IClient {\n readonly #apps: Map<keyof TApps, TApps[keyof TApps]> = new Map();\n\n /**\n * Initialize Rego ERP client instance\n * @param configs\n * @param options\n */\n constructor(\n params: Readonly<{\n credential: TCredential;\n options?: TOptions;\n }>\n ) {\n super(params);\n }\n\n use<T extends keyof TApps = \"CMS\" | \"CRM\" | \"PIM\">(domain: T): TApps[T] {\n try {\n const app = this.#apps.get(domain);\n\n return {\n CMS: (() => {\n const tmpApp =\n !app || !(app instanceof CmsApp)\n ? new CmsApp(this.params)\n : app;\n\n this.#apps.set(domain, tmpApp);\n return tmpApp;\n })(),\n CRM: (() => {\n const tmpApp =\n !app || !(app instanceof CrmApp)\n ? new CrmApp(this.params)\n : app;\n\n this.#apps.set(domain, tmpApp);\n return tmpApp;\n })(),\n PIM: (() => {\n const tmpApp =\n !app || !(app instanceof PimApp)\n ? new PimApp(this.params)\n : app;\n\n this.#apps.set(domain, tmpApp);\n return tmpApp;\n })()\n }[domain];\n } catch (error) {\n if (this.params.options?.logs) {\n console.error(`[${this.appName}] App init got problem:`, error);\n }\n\n throw error;\n }\n }\n}\n"
21
+ ],
22
+ "mappings": ";AAAA,IAAM,EAAU,IAAI,YAAe,EAAU,IAAI,YAAe,GAAgB,IAAI,YAAY,QAAS,CAAE,MAAO,EAAG,CAAC,EACtH,SAAS,CAAM,IAAI,EA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M,IAAI,EAAQ,CAAM,EACtB,IACR,CACP,EAAE,GACJ,MAAO,EAAO,CACZ,GAAI,KAAK,OAAO,SAAS,KACrB,QAAQ,MAAM,IAAI,KAAK,iCAAkC,CAAK,EAGlE,MAAM,GAGlB",
23
+ "debugId": "FB084FC1C1208C8264756E2164756E21",
24
+ "names": []
25
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "author": "Trần Đức Tâm (Neo)",
3
+ "bugs": {
4
+ "url": "https://github.com/rego-solution/erp-sdk/issues"
5
+ },
6
+ "dependencies": {
7
+ "jose": "^6.2.12"
8
+ },
9
+ "devDependencies": {
10
+ "@types/bun": "^1.4.1",
11
+ "@types/node": "^26.5.0",
12
+ "prettier": "^3.9.6",
13
+ "typescript": "^7.0.2"
14
+ },
15
+ "files": [
16
+ "./dist",
17
+ "./src"
18
+ ],
19
+ "homepage": "https://github.com/rego-solution/erp-sdk#readme",
20
+ "keywords": [
21
+ "typescript",
22
+ "ts",
23
+ "bun",
24
+ "node",
25
+ "SDK"
26
+ ],
27
+ "license": "MIT",
28
+ "main": "./dist/index.js",
29
+ "name": "@regojs/erp-sdk",
30
+ "private": false,
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/rego-solution/erp-sdk"
37
+ },
38
+ "scripts": {
39
+ "build:browser": "tsc --noEmit && APP=\"browser\" bun run ./app.build.ts",
40
+ "build:server": "tsc --noEmit && APP=\"server\" bun run ./app.build.ts",
41
+ "format": "prettier \"./src/**/*.ts\" --write",
42
+ "test": "bun --hot run __test/index.ts"
43
+ },
44
+ "types": "./dist/index.d.ts",
45
+ "version": "1.0.0",
46
+ "exports": {
47
+ ".": {
48
+ "import": "./dist/index.js",
49
+ "require": "./dist/index.js",
50
+ "types": "./dist/index.d.ts"
51
+ },
52
+ "./browser": {
53
+ "import": "./dist/browser/index.js",
54
+ "require": "./dist/browser/index.js",
55
+ "types": "./dist/browser/index.d.ts"
56
+ },
57
+ "./server": {
58
+ "import": "./dist/server/index.js",
59
+ "require": "./dist/server/index.js",
60
+ "types": "./dist/server/index.d.ts"
61
+ }
62
+ }
63
+ }
File without changes
package/src/index.ts ADDED
File without changes
File without changes
@@ -0,0 +1,2 @@
1
+ export * as Enums from "./enums";
2
+ export * as Variables from "./variables";
@@ -0,0 +1 @@
1
+ export const baseUri = "https://api.regosolution.com";
@@ -0,0 +1,3 @@
1
+ export * from "./providers";
2
+
3
+ export type * from "./types";
@@ -0,0 +1,63 @@
1
+ import type { IApp, TCredential, TOptions } from "../types";
2
+
3
+ import { SignJWT } from "jose";
4
+
5
+ export class App implements IApp {
6
+ protected appName = "Rego ERP SDK";
7
+ protected defaultVersion: number = 1;
8
+ protected token?: string;
9
+
10
+ /**
11
+ * Initialize Rego ERP client instance
12
+ * @param configs
13
+ * @param options
14
+ */
15
+ constructor(
16
+ protected readonly params: Readonly<{
17
+ credential: TCredential;
18
+ options?: TOptions;
19
+ }>
20
+ ) {}
21
+
22
+ /**
23
+ * Sign JWT token with Ed25519 algorithm
24
+ * @returns
25
+ */
26
+ async signToken() {
27
+ const {
28
+ params: {
29
+ credential: { workspaceId, appId, secret },
30
+ options
31
+ }
32
+ } = this;
33
+
34
+ try {
35
+ const rawKey = new Uint8Array(Buffer.from(secret, "base64"));
36
+
37
+ const privateKey = await crypto.subtle.importKey(
38
+ "raw",
39
+ rawKey,
40
+ { name: "HMAC", hash: "SHA-512" },
41
+ false,
42
+ ["sign", "verify"]
43
+ );
44
+
45
+ const jwt = await new SignJWT({
46
+ iss: workspaceId,
47
+ aud: appId
48
+ })
49
+ .setProtectedHeader({ alg: "HS512" })
50
+ .sign(privateKey);
51
+
52
+ this.token = jwt;
53
+
54
+ return jwt;
55
+ } catch (error) {
56
+ if (options?.logs) {
57
+ console.error(`[${this.appName}] Sign token error:`, error);
58
+ }
59
+
60
+ throw error;
61
+ }
62
+ }
63
+ }
@@ -0,0 +1,66 @@
1
+ import type { IClient, TApps, TCredential, TOptions } from "../types";
2
+
3
+ import { App } from "./app";
4
+ import { CmsApp } from "./cms.app";
5
+ import { CrmApp } from "./crm.app";
6
+ import { PimApp } from "./pim.app";
7
+
8
+ export class Client extends App implements IClient {
9
+ readonly #apps: Map<keyof TApps, TApps[keyof TApps]> = new Map();
10
+
11
+ /**
12
+ * Initialize Rego ERP client instance
13
+ * @param configs
14
+ * @param options
15
+ */
16
+ constructor(
17
+ params: Readonly<{
18
+ credential: TCredential;
19
+ options?: TOptions;
20
+ }>
21
+ ) {
22
+ super(params);
23
+ }
24
+
25
+ use<T extends keyof TApps = "CMS" | "CRM" | "PIM">(domain: T): TApps[T] {
26
+ try {
27
+ const app = this.#apps.get(domain);
28
+
29
+ return {
30
+ CMS: (() => {
31
+ const tmpApp =
32
+ !app || !(app instanceof CmsApp)
33
+ ? new CmsApp(this.params)
34
+ : app;
35
+
36
+ this.#apps.set(domain, tmpApp);
37
+ return tmpApp;
38
+ })(),
39
+ CRM: (() => {
40
+ const tmpApp =
41
+ !app || !(app instanceof CrmApp)
42
+ ? new CrmApp(this.params)
43
+ : app;
44
+
45
+ this.#apps.set(domain, tmpApp);
46
+ return tmpApp;
47
+ })(),
48
+ PIM: (() => {
49
+ const tmpApp =
50
+ !app || !(app instanceof PimApp)
51
+ ? new PimApp(this.params)
52
+ : app;
53
+
54
+ this.#apps.set(domain, tmpApp);
55
+ return tmpApp;
56
+ })()
57
+ }[domain];
58
+ } catch (error) {
59
+ if (this.params.options?.logs) {
60
+ console.error(`[${this.appName}] App init got problem:`, error);
61
+ }
62
+
63
+ throw error;
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,85 @@
1
+ import type { ICmsApp, TApiResponse, TCredential, TOptions } from "../types";
2
+
3
+ import { Variables } from "../constants";
4
+ import { App } from "./app";
5
+
6
+ export class CmsApp extends App implements ICmsApp {
7
+ #blueprintId?: string;
8
+
9
+ /**
10
+ * Initialize Rego ERP CMS app instance
11
+ * @param configs
12
+ * @param options
13
+ */
14
+ constructor(
15
+ params: Readonly<{
16
+ credential: TCredential;
17
+ options?: TOptions;
18
+ }>
19
+ ) {
20
+ super(params);
21
+ }
22
+
23
+ register(
24
+ payload: Parameters<ICmsApp["register"]>[number]
25
+ ): ReturnType<ICmsApp["register"]> {
26
+ if (payload?.blueprintId) {
27
+ this.#blueprintId = payload.blueprintId;
28
+ }
29
+
30
+ return this;
31
+ }
32
+
33
+ async getRoutes(): ReturnType<ICmsApp["getRoutes"]> {
34
+ const {
35
+ params: {
36
+ credential: { workspaceId, appId },
37
+ options
38
+ }
39
+ } = this;
40
+
41
+ try {
42
+ if (!this.#blueprintId) {
43
+ throw new Error("Missing blueprint ID!");
44
+ }
45
+
46
+ const authToken = this.token || (await this.signToken());
47
+ const requestHeaders = new Headers();
48
+
49
+ requestHeaders.append("X-Workspace-ID", workspaceId);
50
+ requestHeaders.append("X-App-ID", appId);
51
+ requestHeaders.append("Authorization", `Bearer ${authToken}`);
52
+ requestHeaders.append("Content-Type", "application/json");
53
+
54
+ const response = await fetch(
55
+ `${Variables.baseUri}/cms/v${
56
+ options?.version || this.defaultVersion
57
+ }/blueprints/${this.#blueprintId}`,
58
+ {
59
+ method: "GET",
60
+ headers: requestHeaders
61
+ }
62
+ );
63
+
64
+ if (!response.ok) {
65
+ throw await response.json();
66
+ }
67
+
68
+ const { data } = (await response.json()) as TApiResponse<
69
+ ICmsApp["getRoutes"]
70
+ >;
71
+
72
+ return Object.freeze({
73
+ hostname: data?.hostname || null,
74
+ routes: data?.routes || null,
75
+ data: data?.data
76
+ });
77
+ } catch (error) {
78
+ if (options?.logs) {
79
+ console.error("[CMS] get blueprint routes:", error);
80
+ }
81
+
82
+ throw error;
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,19 @@
1
+ import type { ICrmApp, TCredential, TOptions } from "../types";
2
+
3
+ import { App } from "./app";
4
+
5
+ export class CrmApp extends App implements ICrmApp {
6
+ /**
7
+ * Initialize Rego ERP PIM app instance
8
+ * @param configs
9
+ * @param options
10
+ */
11
+ constructor(
12
+ params: Readonly<{
13
+ credential: TCredential;
14
+ options?: TOptions;
15
+ }>
16
+ ) {
17
+ super(params);
18
+ }
19
+ }
@@ -0,0 +1,2 @@
1
+ export { Client } from "./client";
2
+ export { CmsApp } from "./cms.app";
@@ -0,0 +1,19 @@
1
+ import type { IPimApp, TCredential, TOptions } from "../types";
2
+
3
+ import { App } from "./app";
4
+
5
+ export class PimApp extends App implements IPimApp {
6
+ /**
7
+ * Initialize Rego ERP PIM app instance
8
+ * @param configs
9
+ * @param options
10
+ */
11
+ constructor(
12
+ params: Readonly<{
13
+ credential: TCredential;
14
+ options?: TOptions;
15
+ }>
16
+ ) {
17
+ super(params);
18
+ }
19
+ }
@@ -0,0 +1,14 @@
1
+ export type TCredential = {
2
+ workspaceId: string;
3
+ appId: string;
4
+ secret: string;
5
+ };
6
+
7
+ export type TOptions = {
8
+ version?: number;
9
+ logs?: boolean;
10
+ };
11
+
12
+ export interface IApp {
13
+ signToken(): Promise<string>;
14
+ }
@@ -0,0 +1,16 @@
1
+ import type { IApp } from "./app";
2
+ import type { ICmsApp } from "./cms.app";
3
+ import type { ICrmApp } from "./crm.app";
4
+ import type { IPimApp } from "./pim.app";
5
+
6
+ export type TApps = {
7
+ CMS: ICmsApp;
8
+ CRM: ICrmApp;
9
+ PIM: IPimApp;
10
+ };
11
+
12
+ export type TDomains = "CMS" | "CRM" | "PIM";
13
+
14
+ export interface IClient extends IApp {
15
+ use<T extends keyof TApps = "CMS" | "CRM" | "PIM">(domain: T): TApps[T];
16
+ }
@@ -0,0 +1,19 @@
1
+ import type { IApp } from "./app";
2
+
3
+ export type TBlueprintRoute = {
4
+ path: string;
5
+ index?: boolean;
6
+ component?: string;
7
+ };
8
+
9
+ export interface ICmsApp extends IApp {
10
+ register(payload: { blueprintId?: string } = {}): ICmsApp;
11
+ getRoutes(): Promise<{
12
+ hostname?: string | null;
13
+ routes?: Array<TBlueprintRoute> | null;
14
+ data?: {
15
+ metadata?: Record<string, string> | null;
16
+ dynamicData?: unknown;
17
+ } | null;
18
+ } | null>;
19
+ }
@@ -0,0 +1,3 @@
1
+ import type { IApp } from "./app";
2
+
3
+ export interface ICrmApp extends IApp {}
@@ -0,0 +1,6 @@
1
+ export type * from "./app.d.ts";
2
+ export type * from "./client.d.ts";
3
+ export type * from "./cms.app";
4
+ export type * from "./crm.app";
5
+ export type * from "./pim.app";
6
+ export type * from "./response.d.ts";
@@ -0,0 +1,3 @@
1
+ import type { IApp } from "./app";
2
+
3
+ export interface IPimApp extends IApp {}
@@ -0,0 +1,7 @@
1
+ export type TApiResponse<T> = Readonly<{
2
+ data: Awaited<
3
+ ReturnType<
4
+ T extends (...args: any) => Promise<infer R> ? () => R : never
5
+ >
6
+ >;
7
+ }>;