@ax-hub/admin-sdk 2.1.0 → 2.1.1
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.cjs +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var ulid=require('ulid'),crypto=require('crypto');var d=class extends Error{code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return _t(this)}};function _t(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(r=>`${r.name}:${r.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}var l=class extends d{},x=class extends d{},v=class extends d{},h=class extends d{},u=class extends d{},$=class extends d{},A=class extends d{},R=class extends d{},E=class extends d{},M=class extends u{},F=class extends u{},H=class extends u{},j=class extends x{},z=class extends x{},K=class extends x{},N=class extends v{},G=class extends v{},W=class extends h{},V=class extends h{},Me=class extends h{},Y=class extends u{},J=class extends u{},X=class extends u{},Q=class extends u{},Z=class extends u{},ee=class extends u{},te=class extends u{},re=class extends u{},ne=class extends u{},se=class extends u{},ie=class extends u{},oe=class extends u{},ae=class extends l{},Fe=class extends l{},de=class extends l{},ue=class extends l{},ce=class extends l{},le=class extends v{},pe=class extends v{},ge=class extends E{},ye=class extends d{},me=class extends d{},_=class extends d{},T=class extends d{},at=class extends d{},He=class extends d{},dt=class extends d{},ut=class extends d{},je=class extends d{},fe=class extends x{},ct=class extends l{},lt=class extends h{},pt=class extends R{},S=class extends l{},k=class extends l{},he=class extends je{},gt=class extends R{},c=class extends d{description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},be=class extends c{},w=class extends c{},xe=class extends c{},ve=class extends c{},C=class extends c{},yt=class extends w{},mt=class extends C{},Te=class extends c{},Ie=class extends c{},Ae=class extends c{},Re=class extends c{},Ee=class extends c{},_e=class extends c{},Se=class extends c{},ke=class extends c{},we=class extends c{};var St={slug_taken:M,already_member:F,already_deleted:H,already_revoked:Y,already_settled:J,already_active:X,already_inactive:Q,already_accessed:Z,not_deleted:ee,last_admin:te,pending_exists:re,invalid_state_transition:ne,schema_name_taken:se,domain_taken:ie,duplicate:oe,token_missing:j,token_expired:z,token_invalid:K,pool_stale:fe,not_admin:N,forbidden:G,not_member:le,not_allowed:pe,permanently_deleted:W,invitation_expired:V,link_invalid:Me,invalid_value:ae,invalid_expiry:Fe,required:de,empty:ue,bad_request:ce,app_unavailable:ge},kt={validation:l,unauthenticated:x,permission_denied:v,not_found:h,conflict:u,precondition_failed:$,rate_limited:A,internal:R,unavailable:E},wt={invalid_grant:be,access_denied:w,authorization_pending:xe,slow_down:ve,expired_token:C,invalid_target:Te,invalid_client:Ie,invalid_request:Ae,invalid_scope:Re,invalid_token:Ee,unauthorized_client:_e,unsupported_grant_type:Se,server_error:ke,temporarily_unavailable:we},Ct={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Vt(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let r=e;return typeof r.code=="string"&&typeof r.category=="string"&&typeof r.retryable=="boolean"}function Yt(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}function Ot(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}function ft(t){return Ot(t.path)&&Yt(t.body)?Xt(t):Vt(t.body)?Jt(t):new _({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}function Jt(t){let r=t.body.error,n=r.retry?{afterMs:r.retry.after_ms}:void 0,s={message:r.message,code:r.code,category:r.category,httpStatus:t.status,retryable:r.retryable,requestId:r.request_id||t.fallbackRequestId,resource:r.resource,fields:r.fields,retry:n,docUrl:r.doc_url},a=St[r.code];if(a)return new a(s);let p=kt[r.category]??d;return new p(s)}function Xt(t){let e=t.body,r=wt[e.error]??c,n=Ct[e.error]??false;return new r({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:n,requestId:t.fallbackRequestId})}function Qt(t){return t}function Zt(t){return t}function er(t){return t}function tr(t){return t}function rr(t){return t}function nr(t){return t}function sr(t){return t}function ir(t){return t}var or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qt=/^[a-z][a-z0-9-]{0,62}$/;function ze(t,e,r){return new l({message:t,code:r,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:r}]})}function f(t,e){if(t.trim()==="")throw ze(`${e} must be non-empty`,e,"empty");if(!or.test(t))throw ze(`${e} must be a UUID`,e,"invalid_uuid")}function Pt(t,e){if(t.trim()==="")throw ze(`${e} must be non-empty`,e,"empty");if(!qt.test(t))throw ze(`${e} must match ${qt.source}`,e,"invalid_slug")}var ar={tenant(t){return f(t,"tenantId"),t},tenantSlug(t){return Pt(t,"tenantSlug"),t},app(t){return f(t,"appId"),t},appSlug(t){return Pt(t,"appSlug"),t},user(t){return f(t,"userId"),t},deployment(t){return f(t,"deploymentId"),t},pat(t){return f(t,"patId"),t},resource(t){return f(t,"resourceId"),t},connector(t){return f(t,"connectorId"),t},subject(t){return f(t,"subjectId"),t},grant(t){return f(t,"grantId"),t},tag(t){return f(t,"tagId"),t},auditEvent(t){return f(t,"auditEventId"),t},table(t){return f(t,"tableId"),t}};var Ce=class{token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},Oe=class{headersFor(e){return {}}async onUnauthorized(){return false}};var Ke={debug(){},info(){},warn(){},error(){}};function ht(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let r=Number(e);if(Number.isFinite(r))return r>=0?Math.floor(r*1e3):6e4;let n=Date.parse(e);return Number.isNaN(n)?6e4:Math.max(0,n-Date.now())}var dr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),ur="***REDACTED***";function Dt(t){let e={},r=(n,s)=>{e[n]=dr.has(n.toLowerCase())?ur:s;};if(typeof Headers<"u"&&t instanceof Headers)t.forEach((n,s)=>r(s,n));else for(let[n,s]of Object.entries(t))r(n,s);return e}var xt={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function cr(t){return t instanceof d?t.retryable:t instanceof TypeError}async function Lt(t,e=xt,r){let n;for(let s=0;s<e.maxAttempts;s++){if(r?.aborted)throw bt("aborted before attempt",r.reason);try{return await t(s)}catch(a){if(n=a,!cr(a)||s===e.maxAttempts-1)throw a;let p=Math.min(e.capMs,e.baseMs*2**s)*e.jitter();await vt(p,r);}}throw n}function vt(t,e){return new Promise((r,n)=>{if(e?.aborted){n(bt("aborted before sleep",e.reason));return}let s=setTimeout(()=>{e?.removeEventListener("abort",a),r();},t),a=()=>{clearTimeout(s),n(bt("aborted during sleep",e?.reason));};e?.addEventListener("abort",a,{once:true});})}function bt(t,e){return new T({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}var lr=new Set(["GET","HEAD","OPTIONS"]),Ne=class{baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??Ke,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid.ulid},this.retryPolicy=e.retryPolicy??xt,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,r,n){let s=lr.has(e.toUpperCase()),a=this.withStableIdempotencyKey(n);return s||n.idempotent?Lt(()=>this.requestOnce(e,r,a),this.retryPolicy,a.signal):this.requestOnce(e,r,a)}async requestOnce(e,r,n){let s=this.buildUrl(r,n.query),a=ulid.ulid(),p=this.buildHeaders(a,n);if(n.body!==void 0&&n.form!==void 0)throw new d({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:a});let b=n.form!==void 0?this.formBody(n.form):n.body!==void 0?JSON.stringify(n.body):void 0;b!==void 0&&(p["Content-Type"]=n.form!==void 0?"application/x-www-form-urlencoded":"application/json");let g=new AbortController,$e=()=>g.abort(n.signal?.reason);n.signal?.addEventListener("abort",$e,{once:true});let Et=n.timeoutMs??this.timeoutMs,Gt=setTimeout(()=>g.abort(new Error("timeout")),Et),y;try{this.logRequest(e,s,p,a),y=await this.fetch(s,{method:e,headers:p,body:b,redirect:"manual",signal:g.signal});}catch(I){throw n.signal?.aborted?new T({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:a,cause:I}):g.signal.aborted?new me({message:`Request timed out after ${Et}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:a,cause:I}):new ye({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:a,cause:I})}finally{clearTimeout(Gt),n.signal?.removeEventListener("abort",$e);}if(y.status>=300&&y.status<400)return {status:y.status,location:y.headers.get("Location")??y.headers.get("location")};if(n.rawResponse&&y.ok)return {response:y,requestId:a};if(y.ok)return this.parseSuccess(y,n,a);let ot=await this.safeParseJson(y);if(y.status===401&&n.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,r,n);if(y.status===429){let I=ht(y.headers.get("Retry-After")),Wt=new A({message:pr(ot)??"Rate limited",code:gr(ot)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:a,retry:{afterMs:I}});if(this.rateLimitStrategy==="sleep")return await vt(I,n.signal),this.requestOnce(e,r,n);throw Wt}throw ft({path:r,status:y.status,body:ot,fallbackRequestId:a})}async parseSuccess(e,r,n){if(e.status===204||r.parseBody===false)return;let s=await e.text();if(s!=="")try{return JSON.parse(s)}catch{return s}}async safeParseJson(e){try{let r=await e.text();return r===""?void 0:JSON.parse(r)}catch{return}}buildUrl(e,r){let n=e.startsWith("/")?e:`/${e}`,s=this.baseUrl+n;if(!r)return s;let a=new URLSearchParams;for(let[b,g]of Object.entries(r))if(g!==void 0)if(Array.isArray(g))for(let $e of g)a.append(b,String($e));else a.set(b,String(g));let p=a.toString();return p?`${s}?${p}`:s}buildHeaders(e,r){let n=this.resolveIdempotencyKey(r);return {"X-Request-Id":e,Accept:"application/json",...r.ring!=="public"?this.auth.headersFor(r.ring):{},...n?{"Idempotency-Key":n}:{},...r.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new d({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let r=new URLSearchParams;for(let[n,s]of Object.entries(e))s!==void 0&&r.set(n,String(s));return r.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,r,n,s){this.debug&&this.logger.debug({method:e,url:r,headers:Dt(n),requestId:s},"http.request");}};function pr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.message;if(typeof r=="string")return r}if(typeof e=="string")return e}function gr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.code;if(typeof r=="string")return r}}var Bt=4096,$t=false;function Mt(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}function yr(t){if(t.length>Bt)throw new S({message:`Cursor token exceeds maximum size (${Bt} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new k({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new k({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!br(e))throw new Error("invalid cursor shape");return e}catch(e){throw new S({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}function mr(t,e){let r=typeof t=="string"?t.split(",").map(n=>{let s=n.trim();return s.startsWith("-")?{field:s.slice(1),dir:"desc"}:s.startsWith("+")?{field:s.slice(1),dir:"asc"}:{field:s,dir:"asc"}}).filter(n=>n.field.length>0):[...t??[]].map(n=>({field:n.field,dir:n.dir??"asc"}));return r.length>0&&!r.some(n=>n.field==="id")&&(e?.warnOnTiebreaker&&!$t&&($t=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),r.push({field:"id",dir:"asc"})),r}function fr(t){return JSON.stringify(Ft(t))}function hr(t,e){if(!t)return null;let r=Ft(e?.orderBy,{warnOnTiebreaker:true}),n={};for(let b of r){let g=t[b.field];(g===null||typeof g=="string"||typeof g=="number"||typeof g=="boolean")&&(n[b.field]=g);}let s=t.id,a={values:n,direction:e?.direction??"forward",orderBy:r,orderByFingerprint:JSON.stringify(r)};(typeof s=="string"||typeof s=="number")&&(a.tiebreaker={field:"id",value:s});let p=e?.page;return typeof p=="number"&&Number.isInteger(p)&&p>0&&(a.page=p),e?.contextFingerprint&&(a.contextFingerprint=e.contextFingerprint),Mt(a)}function Ft(t,e){let r=mr(t,e);return r.length>0?r:[{field:"id",dir:"asc"}]}function br(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}function Tt(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}function vr(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}function Tr(t,e,r){let n=r?Buffer.concat([Buffer.from(`${r}.`),Tt(t)]):Tt(t);return `sha256=${crypto.createHmac("sha256",e).update(n).digest("hex")}`}function Ir(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=vr(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let r=Math.floor((t.now?.()??Date.now())/1e3),n=Tt(t.rawBody);if(t.timestamp!==void 0){let a=Number(t.timestamp);if(!Number.isFinite(a))return {ok:false,reason:"timestamp_skew"};let p=t.tolerance??300;if(Math.abs(r-a)>p)return {ok:false,reason:"timestamp_skew"};let b=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(b))return {ok:false,reason:"replay"};n=Buffer.concat([Buffer.from(`${t.timestamp}.`),n]);}let s=crypto.createHmac("sha256",t.secret).update(n).digest();return e.byteLength!==s.byteLength?{ok:false,reason:"signature_mismatch"}:crypto.timingSafeEqual(e,s)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}function o(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}function O(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}function q(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}function m(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}function i(t){return encodeURIComponent(t)}function Ge(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}function Ar(t){return {id:String(t.id),role:String(t.role),...t,userId:t.user_id??t.userId}}function It(t){return {id:String(t.id),email:String(t.email),role:String(t.role),status:String(t.status),...t}}function jt(t){return {...t,domain:String(t.domain??t.email_domain),verified:t.verified}}var P=class{constructor(e,r){this.http=e;this.mockStore=r;}http;mockStore;scoped(e){return new We(this.http,e)}async create(e,r){if(this.mockStore)return this.mockStore.createTenant(e);let n=await this.http.request("POST","/api/v1/tenants",o({ring:"admin",body:m(e),idempotent:false},r));return Ge(n)}async get(e,r){if(this.mockStore)return this.mockStore.getTenant(e);let n=await this.http.request("GET",`/api/v1/tenants/${i(e)}`,o({ring:"admin"},r));return Ge(n)}async list(e){if(this.mockStore)return this.mockStore.listTenants();let r=await this.http.request("GET","/api/v1/tenants",o({ring:"admin",query:O(e)},e));return q(r,Ge)}async update(e,r,n){if(this.mockStore)return this.mockStore.updateTenant(e,r);let s=await this.http.request("PATCH",`/api/v1/tenants/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n));return Ge(s)}async delete(e,r){if(this.mockStore)return this.mockStore.deleteTenant(e);await this.http.request("DELETE",`/api/v1/tenants/${i(e)}`,o({ring:"admin",idempotent:true},r));}async signIconUploadURL(e,r,n){let s=await this.http.request("POST",`/api/v1/tenants/${i(e)}/icon/upload-url`,o({ring:"admin",body:{content_type:r.contentType},idempotent:false},n));return {uploadUrl:s.upload_url??s.put_url??"",getUrl:s.get_url??s.public_url??"",expiresAt:s.expires_at}}get members(){return new Ve(this.http)}get invitations(){return new Ye(this.http)}get emailDomains(){return new Je(this.http)}},We=class{members;invitations;emailDomains;constructor(e,r){this.members=new qe(e,r),this.invitations=new Pe(e,r),this.emailDomains=new De(e,r);}},Ve=class{constructor(e){this.http=e;}http;forTenant(e){return new qe(this.http,e)}},qe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/members`,o({ring:"admin",query:O(e)},e));return q(r,Ar)}async update(e,r,n){await this.http.request("PATCH",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n));}async deactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}/deactivate`,o({ring:"admin",body:{},idempotent:false},r));}async reactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}/reactivate`,o({ring:"admin",body:{},idempotent:false},r));}},Ye=class{constructor(e){this.http=e;}http;forTenant(e){return new Pe(this.http,e)}},Pe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/invitations`,o({ring:"admin",query:O(e)},e));return q(r,It)}async create(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/invitations`,o({ring:"admin",body:m(e),idempotent:false},r));return It(n)}async bulkCreate(e,r){if(e.length>200)throw new l({message:"bulk invitations are capped at 200",code:"too_many_items",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"invitations",code:"max_200"}]});let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/invitations/bulk`,o({ring:"admin",body:{items:e},idempotent:false},r));return {accepted:(n.succeeded??[]).map(It),rejected:(n.failed??[]).map(s=>({email:s.email,reason:s.reason,message:s.message}))}}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${i(this.tenant)}/invitations/${i(e)}`,o({ring:"admin",idempotent:true},r));}},Je=class{constructor(e){this.http=e;}http;forTenant(e){return new De(this.http,e)}},De=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){return (await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/email-domains`,o({ring:"admin"},e))).items.map(jt)}async create(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/email-domains`,o({ring:"admin",body:{email_domain:e.domain},idempotent:false},r));return jt(n)}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${i(this.tenant)}/email-domains/${i(e)}`,o({ring:"admin",idempotent:true},r));}};var D=class{constructor(e){this.http=e;}http;scoped(e){return new Xe(this.http,e)}},Xe=class{tags;subjects;grants;constructor(e,r){let n=`/api/v1/tenants/${i(r)}`;this.tags=new Qe(e,`${n}/tags`),this.subjects=new Ze(e,`${n}/subjects`),this.grants=new et(e,`${n}/grants`);}},Qe=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,o({ring:"admin",body:m(e),idempotent:false},r))}update(e,r,n){return this.http.request("PATCH",`${this.base}/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n))}delete(e,r){return this.http.request("DELETE",`${this.base}/${i(e)}`,o({ring:"admin",idempotent:true},r))}},Ze=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,o({ring:"admin",body:m(e),idempotent:false},r))}update(e,r,n){return this.http.request("PATCH",`${this.base}/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n))}delete(e,r){return this.http.request("DELETE",`${this.base}/${i(e)}`,o({ring:"admin",idempotent:true},r))}},et=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}};function Le(t){return {id:String(t.id),...t,actorId:t.actor_id??t.actorId,prevHash:t.prev_hash??t.prevHash,createdAt:t.created_at??t.createdAt}}function Rr(t){let e={ok:!!t.ok,checked:Number(t.checked??0)};return t.first_bad_seq!==void 0&&t.first_bad_seq!==null&&(e.firstBadSeq=Number(t.first_bad_seq)),t.reason!==void 0&&(e.reason=t.reason),e}var L=class{constructor(e){this.http=e;this.events=new rt(e),this.server=new nt(e);}http;events;server;scoped(e){return new tt(this.http,e)}integrityCheck(e,r){return this.scoped(e).integrityCheck(r)}anonymize(e,r,n){return this.scoped(e).anonymize(r,n)}},tt=class{constructor(e,r){this.http=e;this.tenantSlug=r;this.events=new Ue(e,r),this.server=new Be(e,r);}http;tenantSlug;events;server;async integrityCheck(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/integrity-check`,o({ring:"admin"},e));return Rr(r)}async anonymize(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/anonymize`,o({ring:"admin",body:{tenant_id:this.tenantSlug,actor_id:e.actorId??e.subjectId,anonymized_id:e.anonymizedId},idempotent:false},r));return n===void 0?void 0:Le(n)}},rt=class{constructor(e){this.http=e;}http;forTenant(e){return new Ue(this.http,e)}},Ue=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events`,o({ring:"admin",query:{...O(e),...e?.type?{type:e.type}:{}}},e));return Array.isArray(r)?{items:r.map(Le),nextCursor:null,total:r.length}:q({items:r.items??[],next_cursor:r.next_cursor??null,total:r.total??r.items?.length??0},Le)}async get(e,r){let n=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/${i(e)}`,o({ring:"admin"},r));return Le(n)}},nt=class{constructor(e){this.http=e;}http;forTenant(e){return new Be(this.http,e)}},Be=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;async emit(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/server`,o({ring:"admin",body:{type:e.type,actor_id:e.actorId,resource:e.resource,payload:e.payload},idempotent:false},r));return Le(n)}};var U=class{constructor(e){this.http=e;}http;list(e,r){return this.http.request("GET",`/api/v1/tenants/${i(e)}/identity-providers`,o({ring:"admin"},r))}create(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers`,o({ring:"admin",body:r,idempotent:false},n))}enable(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers/${i(r)}/enable`,o({ring:"admin",body:{},idempotent:false},n))}disable(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers/${i(r)}/disable`,o({ring:"admin",body:{},idempotent:false},n))}};var B=class{constructor(e){this.http=e;}http;create(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/categories`,o({ring:"admin",body:m(r),idempotent:false},n))}update(e,r,n,s){return this.http.request("PATCH",`/api/v1/tenants/${i(e)}/categories/${i(r)}`,o({ring:"admin",body:m(n),idempotent:false},s))}delete(e,r,n){return this.http.request("DELETE",`/api/v1/tenants/${i(e)}/categories/${i(r)}`,o({ring:"admin",idempotent:true},n))}};var Er=new Set(["1","true","yes","on"]);function _r(t){return t?.trim().toLowerCase()==="production"}function Sr(t){return t===void 0?false:Er.has(t.trim().toLowerCase())}function zt(){if(_r(process.env.NODE_ENV)){if(Sr(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/admin-sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new he({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}function At(t){return new h({message:`Mock tenant not found: ${t}`,code:"tenant_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`tenants/${t}`})}var st=class{tenants=new Map;nextId=1;constructor(e){for(let r of e?.tenants??[]){let n=String(r.id);this.tenants.set(n,{...r,id:n});}}createTenant(e){let r=`tenant_${this.nextId++}`,n=new Date().toISOString(),s={id:r,slug:e.slug,name:e.name,...e.plan!==void 0?{plan:e.plan}:{},createdAt:n,updatedAt:n};return this.tenants.set(r,s),{...s}}getTenant(e){let r=this.tenants.get(e);if(!r)throw At(e);return {...r}}listTenants(){let e=[...this.tenants.values()].map(r=>({...r}));return {items:e,nextCursor:null,total:e.length}}updateTenant(e,r){let n=this.tenants.get(e);if(!n)throw At(e);let s={...n,...r,id:e,updatedAt:new Date().toISOString()};return this.tenants.set(e,s),{...s}}deleteTenant(e){if(!this.tenants.has(e))throw At(e);this.tenants.delete(e);}};function Kt(t){if(t.mode==="mock")return zt(),new st(t.fixtures)}var Nt="https://api.axhub.ai";function kr(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}var Rt=class{http;logger;mock;r;n;s;i;o;constructor(e){if(kr(e)){this.http=e.__sharedHttp,this.logger=e.logger;return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AdminClient requires tokenType when token is set ("pat" | "jwt")');let r=e.token!==void 0&&e.tokenType!==void 0?new Ce({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new Oe;this.http=new Ne({baseUrl:e.baseUrl??Nt,auth:r,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.logger=e.logger??Ke,this.mock=Kt(e);}get tenants(){return this.r||(this.r=new P(this.http,this.mock)),this.r}get authz(){return this.n||(this.n=new D(this.http)),this.n}get audit(){return this.s||(this.s=new L(this.http)),this.s}get identityProviders(){return this.i||(this.i=new U(this.http)),this.i}get categories(){return this.o||(this.o=new B(this.http)),this.o}tenant(e){return new it(e,this.http)}},it=class{constructor(e,r){this.tenant=e;this.http=r;}tenant;http;get tenants(){return new P(this.http).scoped(this.tenant)}get authz(){return new D(this.http).scoped(this.tenant)}get audit(){return new L(this.http).scoped(this.tenant)}get identityProviders(){return new U(this.http)}get categories(){return new B(this.http)}};
|
|
2
|
-
exports.AbortError=
|
|
1
|
+
'use strict';var ulid=require('ulid'),crypto=require('crypto');var Yt=Object.defineProperty;var n=(t,e)=>Yt(t,"name",{value:e,configurable:true});var u=class extends Error{static{n(this,"AxHubError");}code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return St(this)}};function St(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(r=>`${r.name}:${r.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}n(St,"formatErrorMessage");var p=class extends u{static{n(this,"ValidationError");}},v=class extends u{static{n(this,"UnauthenticatedError");}},T=class extends u{static{n(this,"PermissionDeniedError");}},b=class extends u{static{n(this,"NotFoundError");}},c=class extends u{static{n(this,"ConflictError");}},M=class extends u{static{n(this,"PreconditionFailedError");}},R=class extends u{static{n(this,"RateLimitedError");}},E=class extends u{static{n(this,"InternalServerError");}},_=class extends u{static{n(this,"UnavailableError");}},F=class extends c{static{n(this,"SlugTakenError");}},H=class extends c{static{n(this,"AlreadyMemberError");}},j=class extends c{static{n(this,"AlreadyDeletedError");}},z=class extends v{static{n(this,"TokenMissingError");}},K=class extends v{static{n(this,"TokenExpiredError");}},N=class extends v{static{n(this,"TokenInvalidError");}},G=class extends T{static{n(this,"NotAdminError");}},W=class extends T{static{n(this,"ForbiddenError");}},V=class extends b{static{n(this,"PermanentlyDeletedError");}},Y=class extends b{static{n(this,"InvitationExpiredError");}},Fe=class extends b{static{n(this,"LinkInvalidError");}},J=class extends c{static{n(this,"AlreadyRevokedError");}},X=class extends c{static{n(this,"AlreadySettledError");}},Q=class extends c{static{n(this,"AlreadyActiveError");}},Z=class extends c{static{n(this,"AlreadyInactiveError");}},ee=class extends c{static{n(this,"AlreadyAccessedError");}},te=class extends c{static{n(this,"NotDeletedError");}},re=class extends c{static{n(this,"LastAdminError");}},ne=class extends c{static{n(this,"PendingExistsError");}},se=class extends c{static{n(this,"InvalidStateTransitionError");}},ie=class extends c{static{n(this,"SchemaNameTakenError");}},oe=class extends c{static{n(this,"DomainTakenError");}},ae=class extends c{static{n(this,"DuplicateError");}},de=class extends p{static{n(this,"InvalidValueError");}},He=class extends p{static{n(this,"InvalidExpiryError");}},ue=class extends p{static{n(this,"RequiredError");}},ce=class extends p{static{n(this,"EmptyError");}},le=class extends p{static{n(this,"BadRequestError");}},pe=class extends T{static{n(this,"NotMemberError");}},ge=class extends T{static{n(this,"NotAllowedError");}},ye=class extends _{static{n(this,"AppUnavailableError");}},me=class extends u{static{n(this,"NetworkError");}},fe=class extends u{static{n(this,"TimeoutError");}},S=class extends u{static{n(this,"DecodeError");}},I=class extends u{static{n(this,"AbortError");}},dt=class extends u{static{n(this,"InvalidPathError");}},je=class extends u{static{n(this,"StreamConsumedError");}},ut=class extends u{static{n(this,"TenantSlugRequiredError");}},ct=class extends u{static{n(this,"TenantIdRequiredError");}},ze=class extends u{static{n(this,"ConfigurationError");}},he=class extends v{static{n(this,"PoolStaleError");}},lt=class extends p{static{n(this,"WebhookVerificationError");}},pt=class extends b{static{n(this,"TableNotFoundError");}},gt=class extends E{static{n(this,"IntrospectFailedError");}},k=class extends p{static{n(this,"InvalidCursorError");}},w=class extends p{static{n(this,"LegacyCursorError");}},be=class extends ze{static{n(this,"MockInProductionError");}},yt=class extends E{static{n(this,"ScanLimitExceededError");}},l=class extends u{static{n(this,"OAuthError");}description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},xe=class extends l{static{n(this,"InvalidGrantError");}},C=class extends l{static{n(this,"AccessDeniedError");}},ve=class extends l{static{n(this,"AuthorizationPendingError");}},Te=class extends l{static{n(this,"SlowDownError");}},O=class extends l{static{n(this,"ExpiredTokenError");}},mt=class extends C{static{n(this,"DeviceFlowDeniedError");}},ft=class extends O{static{n(this,"DeviceFlowTimeoutError");}},Ie=class extends l{static{n(this,"InvalidTargetError");}},Ae=class extends l{static{n(this,"InvalidClientError");}},Re=class extends l{static{n(this,"InvalidRequestError");}},Ee=class extends l{static{n(this,"InvalidScopeError");}},_e=class extends l{static{n(this,"InvalidTokenError");}},Se=class extends l{static{n(this,"UnauthorizedClientError");}},ke=class extends l{static{n(this,"UnsupportedGrantTypeError");}},we=class extends l{static{n(this,"OAuthServerError");}},Ce=class extends l{static{n(this,"TemporarilyUnavailableError");}};var kt={slug_taken:F,already_member:H,already_deleted:j,already_revoked:J,already_settled:X,already_active:Q,already_inactive:Z,already_accessed:ee,not_deleted:te,last_admin:re,pending_exists:ne,invalid_state_transition:se,schema_name_taken:ie,domain_taken:oe,duplicate:ae,token_missing:z,token_expired:K,token_invalid:N,pool_stale:he,not_admin:G,forbidden:W,not_member:pe,not_allowed:ge,permanently_deleted:V,invitation_expired:Y,link_invalid:Fe,invalid_value:de,invalid_expiry:He,required:ue,empty:ce,bad_request:le,app_unavailable:ye},wt={validation:p,unauthenticated:v,permission_denied:T,not_found:b,conflict:c,precondition_failed:M,rate_limited:R,internal:E,unavailable:_},Ct={invalid_grant:xe,access_denied:C,authorization_pending:ve,slow_down:Te,expired_token:O,invalid_target:Ie,invalid_client:Ae,invalid_request:Re,invalid_scope:Ee,invalid_token:_e,unauthorized_client:Se,unsupported_grant_type:ke,server_error:we,temporarily_unavailable:Ce},Ot={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Jt(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let r=e;return typeof r.code=="string"&&typeof r.category=="string"&&typeof r.retryable=="boolean"}n(Jt,"isWrappedEnvelope");function Xt(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}n(Xt,"isOAuthErrorBody");function qt(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}n(qt,"isOAuthPath");function ht(t){return qt(t.path)&&Xt(t.body)?Zt(t):Jt(t.body)?Qt(t):new S({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}n(ht,"dispatch");function Qt(t){let r=t.body.error,s=r.retry?{afterMs:r.retry.after_ms}:void 0,i={message:r.message,code:r.code,category:r.category,httpStatus:t.status,retryable:r.retryable,requestId:r.request_id||t.fallbackRequestId,resource:r.resource,fields:r.fields,retry:s,docUrl:r.doc_url},d=kt[r.code];if(d)return new d(i);let g=wt[r.category]??u;return new g(i)}n(Qt,"dispatchWrapped");function Zt(t){let e=t.body,r=Ct[e.error]??l,s=Ot[e.error]??false;return new r({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:s,requestId:t.fallbackRequestId})}n(Zt,"dispatchOAuth");function er(t){return t}n(er,"asAppId");function tr(t){return t}n(tr,"asDeploymentId");function rr(t){return t}n(rr,"asTenantId");function nr(t){return t}n(nr,"asTenantSlug");function sr(t){return t}n(sr,"asAppSlug");function ir(t){return t}n(ir,"asPatId");function or(t){return t}n(or,"asUserId");function ar(t){return t}n(ar,"asRequestId");var dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pt=/^[a-z][a-z0-9-]{0,62}$/;function Ke(t,e,r){return new p({message:t,code:r,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:r}]})}n(Ke,"validation");function h(t,e){if(t.trim()==="")throw Ke(`${e} must be non-empty`,e,"empty");if(!dr.test(t))throw Ke(`${e} must be a UUID`,e,"invalid_uuid")}n(h,"requireUuid");function Dt(t,e){if(t.trim()==="")throw Ke(`${e} must be non-empty`,e,"empty");if(!Pt.test(t))throw Ke(`${e} must match ${Pt.source}`,e,"invalid_slug")}n(Dt,"requireSlug");var ur={tenant(t){return h(t,"tenantId"),t},tenantSlug(t){return Dt(t,"tenantSlug"),t},app(t){return h(t,"appId"),t},appSlug(t){return Dt(t,"appSlug"),t},user(t){return h(t,"userId"),t},deployment(t){return h(t,"deploymentId"),t},pat(t){return h(t,"patId"),t},resource(t){return h(t,"resourceId"),t},connector(t){return h(t,"connectorId"),t},subject(t){return h(t,"subjectId"),t},grant(t){return h(t,"grantId"),t},tag(t){return h(t,"tagId"),t},auditEvent(t){return h(t,"auditEventId"),t},table(t){return h(t,"tableId"),t}};var Oe=class{static{n(this,"StaticTokenAuth");}token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},qe=class{static{n(this,"NoAuth");}headersFor(e){return {}}async onUnauthorized(){return false}};var Ne={debug(){},info(){},warn(){},error(){}};function bt(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let r=Number(e);if(Number.isFinite(r))return r>=0?Math.floor(r*1e3):6e4;let s=Date.parse(e);return Number.isNaN(s)?6e4:Math.max(0,s-Date.now())}n(bt,"parseRetryAfter");var cr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),lr="***REDACTED***";function Lt(t){let e={},r=n((s,i)=>{e[s]=cr.has(s.toLowerCase())?lr:i;},"visit");if(typeof Headers<"u"&&t instanceof Headers)t.forEach((s,i)=>r(i,s));else for(let[s,i]of Object.entries(t))r(s,i);return e}n(Lt,"redactHeaders");var vt={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function pr(t){return t instanceof u?t.retryable:t instanceof TypeError}n(pr,"isRetriable");async function Ut(t,e=vt,r){let s;for(let i=0;i<e.maxAttempts;i++){if(r?.aborted)throw xt("aborted before attempt",r.reason);try{return await t(i)}catch(d){if(s=d,!pr(d)||i===e.maxAttempts-1)throw d;let g=Math.min(e.capMs,e.baseMs*2**i)*e.jitter();await Tt(g,r);}}throw s}n(Ut,"withRetry");function Tt(t,e){return new Promise((r,s)=>{if(e?.aborted){s(xt("aborted before sleep",e.reason));return}let i=setTimeout(()=>{e?.removeEventListener("abort",d),r();},t),d=n(()=>{clearTimeout(i),s(xt("aborted during sleep",e?.reason));},"onAbort");e?.addEventListener("abort",d,{once:true});})}n(Tt,"abortableSleep");function xt(t,e){return new I({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}n(xt,"aborted");var gr=new Set(["GET","HEAD","OPTIONS"]),Ge=class{static{n(this,"HttpClient");}baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??Ne,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid.ulid},this.retryPolicy=e.retryPolicy??vt,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,r,s){let i=gr.has(e.toUpperCase()),d=this.withStableIdempotencyKey(s);return i||s.idempotent?Ut(()=>this.requestOnce(e,r,d),this.retryPolicy,d.signal):this.requestOnce(e,r,d)}async requestOnce(e,r,s){let i=this.buildUrl(r,s.query),d=ulid.ulid(),g=this.buildHeaders(d,s);if(s.body!==void 0&&s.form!==void 0)throw new u({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:d});let x=s.form!==void 0?this.formBody(s.form):s.body!==void 0?JSON.stringify(s.body):void 0;x!==void 0&&(g["Content-Type"]=s.form!==void 0?"application/x-www-form-urlencoded":"application/json");let y=new AbortController,Me=n(()=>y.abort(s.signal?.reason),"externalAbort");s.signal?.addEventListener("abort",Me,{once:true});let _t=s.timeoutMs??this.timeoutMs,Wt=setTimeout(()=>y.abort(new Error("timeout")),_t),m;try{this.logRequest(e,i,g,d),m=await this.fetch(i,{method:e,headers:g,body:x,redirect:"manual",signal:y.signal});}catch(A){throw s.signal?.aborted?new I({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:d,cause:A}):y.signal.aborted?new fe({message:`Request timed out after ${_t}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:d,cause:A}):new me({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:d,cause:A})}finally{clearTimeout(Wt),s.signal?.removeEventListener("abort",Me);}if(m.status>=300&&m.status<400)return {status:m.status,location:m.headers.get("Location")??m.headers.get("location")};if(s.rawResponse&&m.ok)return {response:m,requestId:d};if(m.ok)return this.parseSuccess(m,s,d);let at=await this.safeParseJson(m);if(m.status===401&&s.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,r,s);if(m.status===429){let A=bt(m.headers.get("Retry-After")),Vt=new R({message:yr(at)??"Rate limited",code:mr(at)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:d,retry:{afterMs:A}});if(this.rateLimitStrategy==="sleep")return await Tt(A,s.signal),this.requestOnce(e,r,s);throw Vt}throw ht({path:r,status:m.status,body:at,fallbackRequestId:d})}async parseSuccess(e,r,s){if(e.status===204||r.parseBody===false)return;let i=await e.text();if(i!=="")try{return JSON.parse(i)}catch{return i}}async safeParseJson(e){try{let r=await e.text();return r===""?void 0:JSON.parse(r)}catch{return}}buildUrl(e,r){let s=e.startsWith("/")?e:`/${e}`,i=this.baseUrl+s;if(!r)return i;let d=new URLSearchParams;for(let[x,y]of Object.entries(r))if(y!==void 0)if(Array.isArray(y))for(let Me of y)d.append(x,String(Me));else d.set(x,String(y));let g=d.toString();return g?`${i}?${g}`:i}buildHeaders(e,r){let s=this.resolveIdempotencyKey(r);return {"X-Request-Id":e,Accept:"application/json",...r.ring!=="public"?this.auth.headersFor(r.ring):{},...s?{"Idempotency-Key":s}:{},...r.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new u({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let r=new URLSearchParams;for(let[s,i]of Object.entries(e))i!==void 0&&r.set(s,String(i));return r.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,r,s,i){this.debug&&this.logger.debug({method:e,url:r,headers:Lt(s),requestId:i},"http.request");}};function yr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.message;if(typeof r=="string")return r}if(typeof e=="string")return e}n(yr,"getMessage");function mr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.code;if(typeof r=="string")return r}}n(mr,"extractCode");var $t=4096,Mt=false;function Ft(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}n(Ft,"encodeCursor");function fr(t){if(t.length>$t)throw new k({message:`Cursor token exceeds maximum size (${$t} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new w({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new w({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!vr(e))throw new Error("invalid cursor shape");return e}catch(e){throw new k({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}n(fr,"decodeCursor");function hr(t,e){let r=typeof t=="string"?t.split(",").map(s=>{let i=s.trim();return i.startsWith("-")?{field:i.slice(1),dir:"desc"}:i.startsWith("+")?{field:i.slice(1),dir:"asc"}:{field:i,dir:"asc"}}).filter(s=>s.field.length>0):[...t??[]].map(s=>({field:s.field,dir:s.dir??"asc"}));return r.length>0&&!r.some(s=>s.field==="id")&&(e?.warnOnTiebreaker&&!Mt&&(Mt=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),r.push({field:"id",dir:"asc"})),r}n(hr,"normalizeOrderBy");function br(t){return JSON.stringify(Ht(t))}n(br,"orderByFingerprint");function xr(t,e){if(!t)return null;let r=Ht(e?.orderBy,{warnOnTiebreaker:true}),s={};for(let x of r){let y=t[x.field];(y===null||typeof y=="string"||typeof y=="number"||typeof y=="boolean")&&(s[x.field]=y);}let i=t.id,d={values:s,direction:e?.direction??"forward",orderBy:r,orderByFingerprint:JSON.stringify(r)};(typeof i=="string"||typeof i=="number")&&(d.tiebreaker={field:"id",value:i});let g=e?.page;return typeof g=="number"&&Number.isInteger(g)&&g>0&&(d.page=g),e?.contextFingerprint&&(d.contextFingerprint=e.contextFingerprint),Ft(d)}n(xr,"cursorFromRow");function Ht(t,e){let r=hr(t,e);return r.length>0?r:[{field:"id",dir:"asc"}]}n(Ht,"effectiveCursorOrderBy");function vr(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}n(vr,"isKeysetCursor");function It(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}n(It,"bodyBytes");function Ir(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}n(Ir,"parseSignature");function Ar(t,e,r){let s=r?Buffer.concat([Buffer.from(`${r}.`),It(t)]):It(t);return `sha256=${crypto.createHmac("sha256",e).update(s).digest("hex")}`}n(Ar,"signWebhook");function Rr(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=Ir(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let r=Math.floor((t.now?.()??Date.now())/1e3),s=It(t.rawBody);if(t.timestamp!==void 0){let d=Number(t.timestamp);if(!Number.isFinite(d))return {ok:false,reason:"timestamp_skew"};let g=t.tolerance??300;if(Math.abs(r-d)>g)return {ok:false,reason:"timestamp_skew"};let x=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(x))return {ok:false,reason:"replay"};s=Buffer.concat([Buffer.from(`${t.timestamp}.`),s]);}let i=crypto.createHmac("sha256",t.secret).update(s).digest();return e.byteLength!==i.byteLength?{ok:false,reason:"signature_mismatch"}:crypto.timingSafeEqual(e,i)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}n(Rr,"verifyWebhook");function a(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}n(a,"withRequestOptions");function q(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}n(q,"pageQuery");function P(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}n(P,"toPaginatedList");function f(t){let e={};for(let[r,s]of Object.entries(t))s!==void 0&&(e[r]=s);return e}n(f,"compactBody");function o(t){return encodeURIComponent(t)}n(o,"encodePath");function We(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}n(We,"toTenant");function Er(t){return {id:String(t.id),role:String(t.role),...t,userId:t.user_id??t.userId}}n(Er,"toMember");function At(t){return {id:String(t.id),email:String(t.email),role:String(t.role),status:String(t.status),...t}}n(At,"toInvitation");function zt(t){return {...t,domain:String(t.domain??t.email_domain),verified:t.verified}}n(zt,"toEmailDomain");var D=class{constructor(e,r){this.http=e;this.mockStore=r;}http;mockStore;static{n(this,"TenantsAdminClient");}scoped(e){return new Ve(this.http,e)}async create(e,r){if(this.mockStore)return this.mockStore.createTenant(e);let s=await this.http.request("POST","/api/v1/tenants",a({ring:"admin",body:f(e),idempotent:false},r));return We(s)}async get(e,r){if(this.mockStore)return this.mockStore.getTenant(e);let s=await this.http.request("GET",`/api/v1/tenants/${o(e)}`,a({ring:"admin"},r));return We(s)}async list(e){if(this.mockStore)return this.mockStore.listTenants();let r=await this.http.request("GET","/api/v1/tenants",a({ring:"admin",query:q(e)},e));return P(r,We)}async update(e,r,s){if(this.mockStore)return this.mockStore.updateTenant(e,r);let i=await this.http.request("PATCH",`/api/v1/tenants/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s));return We(i)}async delete(e,r){if(this.mockStore)return this.mockStore.deleteTenant(e);await this.http.request("DELETE",`/api/v1/tenants/${o(e)}`,a({ring:"admin",idempotent:true},r));}async signIconUploadURL(e,r,s){let i=await this.http.request("POST",`/api/v1/tenants/${o(e)}/icon/upload-url`,a({ring:"admin",body:{content_type:r.contentType},idempotent:false},s));return {uploadUrl:i.upload_url??i.put_url??"",getUrl:i.get_url??i.public_url??"",expiresAt:i.expires_at}}get members(){return new Ye(this.http)}get invitations(){return new Je(this.http)}get emailDomains(){return new Xe(this.http)}},Ve=class{static{n(this,"TenantScopedTenantsAdminClient");}members;invitations;emailDomains;constructor(e,r){this.members=new Pe(e,r),this.invitations=new De(e,r),this.emailDomains=new Le(e,r);}},Ye=class{constructor(e){this.http=e;}http;static{n(this,"TenantMembersClient");}forTenant(e){return new Pe(this.http,e)}},Pe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantMembersForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/members`,a({ring:"admin",query:q(e)},e));return P(r,Er)}async update(e,r,s){await this.http.request("PATCH",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s));}async deactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}/deactivate`,a({ring:"admin",body:{},idempotent:false},r));}async reactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}/reactivate`,a({ring:"admin",body:{},idempotent:false},r));}},Je=class{constructor(e){this.http=e;}http;static{n(this,"TenantInvitationsClient");}forTenant(e){return new De(this.http,e)}},De=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantInvitationsForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/invitations`,a({ring:"admin",query:q(e)},e));return P(r,At)}async create(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/invitations`,a({ring:"admin",body:f(e),idempotent:false},r));return At(s)}async bulkCreate(e,r){if(e.length>200)throw new p({message:"bulk invitations are capped at 200",code:"too_many_items",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"invitations",code:"max_200"}]});let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/invitations/bulk`,a({ring:"admin",body:{items:e},idempotent:false},r));return {accepted:(s.succeeded??[]).map(At),rejected:(s.failed??[]).map(i=>({email:i.email,reason:i.reason,message:i.message}))}}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${o(this.tenant)}/invitations/${o(e)}`,a({ring:"admin",idempotent:true},r));}},Xe=class{constructor(e){this.http=e;}http;static{n(this,"TenantEmailDomainsClient");}forTenant(e){return new Le(this.http,e)}},Le=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantEmailDomainsForTenantClient");}async list(e){return (await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/email-domains`,a({ring:"admin"},e))).items.map(zt)}async create(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/email-domains`,a({ring:"admin",body:{email_domain:e.domain},idempotent:false},r));return zt(s)}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${o(this.tenant)}/email-domains/${o(e)}`,a({ring:"admin",idempotent:true},r));}};var L=class{constructor(e){this.http=e;}http;static{n(this,"AuthzClient");}scoped(e){return new Qe(this.http,e)}},Qe=class{static{n(this,"TenantAuthzClient");}tags;subjects;grants;constructor(e,r){let s=`/api/v1/tenants/${o(r)}`;this.tags=new Ze(e,`${s}/tags`),this.subjects=new et(e,`${s}/subjects`),this.grants=new tt(e,`${s}/grants`);}},Ze=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzTagsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,a({ring:"admin",body:f(e),idempotent:false},r))}update(e,r,s){return this.http.request("PATCH",`${this.base}/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s))}delete(e,r){return this.http.request("DELETE",`${this.base}/${o(e)}`,a({ring:"admin",idempotent:true},r))}},et=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzSubjectsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,a({ring:"admin",body:f(e),idempotent:false},r))}update(e,r,s){return this.http.request("PATCH",`${this.base}/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s))}delete(e,r){return this.http.request("DELETE",`${this.base}/${o(e)}`,a({ring:"admin",idempotent:true},r))}},tt=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzGrantsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}};function Ue(t){return {id:String(t.id),...t,actorId:t.actor_id??t.actorId,prevHash:t.prev_hash??t.prevHash,createdAt:t.created_at??t.createdAt}}n(Ue,"toEvent");function _r(t){let e={ok:!!t.ok,checked:Number(t.checked??0)};return t.first_bad_seq!==void 0&&t.first_bad_seq!==null&&(e.firstBadSeq=Number(t.first_bad_seq)),t.reason!==void 0&&(e.reason=t.reason),e}n(_r,"toIntegrityCheck");var U=class{constructor(e){this.http=e;this.events=new nt(e),this.server=new st(e);}http;static{n(this,"AuditClient");}events;server;scoped(e){return new rt(this.http,e)}integrityCheck(e,r){return this.scoped(e).integrityCheck(r)}anonymize(e,r,s){return this.scoped(e).anonymize(r,s)}},rt=class{constructor(e,r){this.http=e;this.tenantSlug=r;this.events=new Be(e,r),this.server=new $e(e,r);}http;tenantSlug;static{n(this,"TenantAuditClient");}events;server;async integrityCheck(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/integrity-check`,a({ring:"admin"},e));return _r(r)}async anonymize(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/anonymize`,a({ring:"admin",body:{tenant_id:this.tenantSlug,actor_id:e.actorId??e.subjectId,anonymized_id:e.anonymizedId},idempotent:false},r));return s===void 0?void 0:Ue(s)}},nt=class{constructor(e){this.http=e;}http;static{n(this,"AuditEventsClient");}forTenant(e){return new Be(this.http,e)}},Be=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;static{n(this,"AuditEventsForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events`,a({ring:"admin",query:{...q(e),...e?.type?{type:e.type}:{}}},e));return Array.isArray(r)?{items:r.map(Ue),nextCursor:null,total:r.length}:P({items:r.items??[],next_cursor:r.next_cursor??null,total:r.total??r.items?.length??0},Ue)}async get(e,r){let s=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/${o(e)}`,a({ring:"admin"},r));return Ue(s)}},st=class{constructor(e){this.http=e;}http;static{n(this,"AuditServerClient");}forTenant(e){return new $e(this.http,e)}},$e=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;static{n(this,"AuditServerForTenantClient");}async emit(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/server`,a({ring:"admin",body:{type:e.type,actor_id:e.actorId,resource:e.resource,payload:e.payload},idempotent:false},r));return Ue(s)}};var B=class{constructor(e){this.http=e;}http;static{n(this,"IdentityProviderClient");}list(e,r){return this.http.request("GET",`/api/v1/tenants/${o(e)}/identity-providers`,a({ring:"admin"},r))}create(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers`,a({ring:"admin",body:r,idempotent:false},s))}enable(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers/${o(r)}/enable`,a({ring:"admin",body:{},idempotent:false},s))}disable(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers/${o(r)}/disable`,a({ring:"admin",body:{},idempotent:false},s))}};var $=class{constructor(e){this.http=e;}http;static{n(this,"CategoriesAdminClient");}create(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/categories`,a({ring:"admin",body:f(r),idempotent:false},s))}update(e,r,s,i){return this.http.request("PATCH",`/api/v1/tenants/${o(e)}/categories/${o(r)}`,a({ring:"admin",body:f(s),idempotent:false},i))}delete(e,r,s){return this.http.request("DELETE",`/api/v1/tenants/${o(e)}/categories/${o(r)}`,a({ring:"admin",idempotent:true},s))}};var Sr=new Set(["1","true","yes","on"]);function kr(t){return t?.trim().toLowerCase()==="production"}n(kr,"isProductionEnv");function wr(t){return t===void 0?false:Sr.has(t.trim().toLowerCase())}n(wr,"isTruthyOptIn");function Kt(){if(kr(process.env.NODE_ENV)){if(wr(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/admin-sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new be({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}n(Kt,"assertMockModeAllowed");function Rt(t){return new b({message:`Mock tenant not found: ${t}`,code:"tenant_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`tenants/${t}`})}n(Rt,"tenantNotFound");var it=class{static{n(this,"AdminMockStore");}tenants=new Map;nextId=1;constructor(e){for(let r of e?.tenants??[]){let s=String(r.id);this.tenants.set(s,{...r,id:s});}}createTenant(e){let r=`tenant_${this.nextId++}`,s=new Date().toISOString(),i={id:r,slug:e.slug,name:e.name,...e.plan!==void 0?{plan:e.plan}:{},createdAt:s,updatedAt:s};return this.tenants.set(r,i),{...i}}getTenant(e){let r=this.tenants.get(e);if(!r)throw Rt(e);return {...r}}listTenants(){let e=[...this.tenants.values()].map(r=>({...r}));return {items:e,nextCursor:null,total:e.length}}updateTenant(e,r){let s=this.tenants.get(e);if(!s)throw Rt(e);let i={...s,...r,id:e,updatedAt:new Date().toISOString()};return this.tenants.set(e,i),{...i}}deleteTenant(e){if(!this.tenants.has(e))throw Rt(e);this.tenants.delete(e);}};function Nt(t){if(t.mode==="mock")return Kt(),new it(t.fixtures)}n(Nt,"createAdminMockStore");var Gt="https://api.axhub.ai";function Cr(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}n(Cr,"isInternal");var Et=class{static{n(this,"AdminClient");}http;logger;mock;r;n;s;i;o;constructor(e){if(Cr(e)){this.http=e.__sharedHttp,this.logger=e.logger;return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AdminClient requires tokenType when token is set ("pat" | "jwt")');let r=e.token!==void 0&&e.tokenType!==void 0?new Oe({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new qe;this.http=new Ge({baseUrl:e.baseUrl??Gt,auth:r,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.logger=e.logger??Ne,this.mock=Nt(e);}get tenants(){return this.r||(this.r=new D(this.http,this.mock)),this.r}get authz(){return this.n||(this.n=new L(this.http)),this.n}get audit(){return this.s||(this.s=new U(this.http)),this.s}get identityProviders(){return this.i||(this.i=new B(this.http)),this.i}get categories(){return this.o||(this.o=new $(this.http)),this.o}tenant(e){return new ot(e,this.http)}},ot=class{constructor(e,r){this.tenant=e;this.http=r;}tenant;http;static{n(this,"TenantScopedAdminClient");}get tenants(){return new D(this.http).scoped(this.tenant)}get authz(){return new L(this.http).scoped(this.tenant)}get audit(){return new U(this.http).scoped(this.tenant)}get identityProviders(){return new B(this.http)}get categories(){return new $(this.http)}};
|
|
2
|
+
exports.AbortError=I;exports.AccessDeniedError=C;exports.AdminClient=Et;exports.AlreadyAccessedError=ee;exports.AlreadyActiveError=Q;exports.AlreadyDeletedError=j;exports.AlreadyInactiveError=Z;exports.AlreadyMemberError=H;exports.AlreadyRevokedError=J;exports.AlreadySettledError=X;exports.AppUnavailableError=ye;exports.AuditClient=U;exports.AuditEventsClient=nt;exports.AuditEventsForTenantClient=Be;exports.AuditServerClient=st;exports.AuditServerForTenantClient=$e;exports.AuthorizationPendingError=ve;exports.AuthzClient=L;exports.AuthzGrantsClient=tt;exports.AuthzSubjectsClient=et;exports.AuthzTagsClient=Ze;exports.AxHubError=u;exports.BadRequestError=le;exports.CategoriesAdminClient=$;exports.ConfigurationError=ze;exports.ConflictError=c;exports.DEFAULT_BASE_URL=Gt;exports.DecodeError=S;exports.DeviceFlowDeniedError=mt;exports.DeviceFlowTimeoutError=ft;exports.DomainTakenError=oe;exports.DuplicateError=ae;exports.EmptyError=ce;exports.ExpiredTokenError=O;exports.ForbiddenError=W;exports.IdentityProviderClient=B;exports.InternalServerError=E;exports.IntrospectFailedError=gt;exports.InvalidClientError=Ae;exports.InvalidCursorError=k;exports.InvalidGrantError=xe;exports.InvalidPathError=dt;exports.InvalidRequestError=Re;exports.InvalidScopeError=Ee;exports.InvalidStateTransitionError=se;exports.InvalidTargetError=Ie;exports.InvalidTokenError=_e;exports.InvalidValueError=de;exports.InvitationExpiredError=Y;exports.LastAdminError=re;exports.LegacyCursorError=w;exports.MockInProductionError=be;exports.NetworkError=me;exports.NoAuth=qe;exports.NotAdminError=G;exports.NotAllowedError=ge;exports.NotDeletedError=te;exports.NotFoundError=b;exports.NotMemberError=pe;exports.OAuthError=l;exports.OAuthServerError=we;exports.PendingExistsError=ne;exports.PermanentlyDeletedError=V;exports.PermissionDeniedError=T;exports.PoolStaleError=he;exports.PreconditionFailedError=M;exports.RateLimitedError=R;exports.RequiredError=ue;exports.ScanLimitExceededError=yt;exports.SchemaNameTakenError=ie;exports.SlowDownError=Te;exports.SlugTakenError=F;exports.StaticTokenAuth=Oe;exports.StreamConsumedError=je;exports.TableNotFoundError=pt;exports.TemporarilyUnavailableError=Ce;exports.TenantAuditClient=rt;exports.TenantAuthzClient=Qe;exports.TenantEmailDomainsClient=Xe;exports.TenantEmailDomainsForTenantClient=Le;exports.TenantIdRequiredError=ct;exports.TenantInvitationsClient=Je;exports.TenantInvitationsForTenantClient=De;exports.TenantMembersClient=Ye;exports.TenantMembersForTenantClient=Pe;exports.TenantScopedAdminClient=ot;exports.TenantScopedTenantsAdminClient=Ve;exports.TenantSlugRequiredError=ut;exports.TenantsAdminClient=D;exports.TimeoutError=fe;exports.TokenExpiredError=K;exports.TokenInvalidError=N;exports.TokenMissingError=z;exports.UnauthenticatedError=v;exports.UnauthorizedClientError=Se;exports.UnavailableError=_;exports.UnsupportedGrantTypeError=ke;exports.ValidationError=p;exports.WebhookVerificationError=lt;exports.asAppId=er;exports.asAppSlug=sr;exports.asDeploymentId=tr;exports.asPatId=ir;exports.asRequestId=ar;exports.asTenantId=rr;exports.asTenantSlug=nr;exports.asUserId=or;exports.cursorFromRow=xr;exports.decodeCursor=fr;exports.encodeCursor=Ft;exports.formatErrorMessage=St;exports.id=ur;exports.orderByFingerprint=br;exports.parseRetryAfter=bt;exports.signWebhook=Ar;exports.verifyWebhook=Rr;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {ulid}from'ulid';import {createHmac,timingSafeEqual}from'crypto';var d=class extends Error{code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return _t(this)}};function _t(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(r=>`${r.name}:${r.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}var l=class extends d{},x=class extends d{},v=class extends d{},h=class extends d{},u=class extends d{},$=class extends d{},A=class extends d{},R=class extends d{},E=class extends d{},M=class extends u{},F=class extends u{},H=class extends u{},j=class extends x{},z=class extends x{},K=class extends x{},N=class extends v{},G=class extends v{},W=class extends h{},V=class extends h{},Me=class extends h{},Y=class extends u{},J=class extends u{},X=class extends u{},Q=class extends u{},Z=class extends u{},ee=class extends u{},te=class extends u{},re=class extends u{},ne=class extends u{},se=class extends u{},ie=class extends u{},oe=class extends u{},ae=class extends l{},Fe=class extends l{},de=class extends l{},ue=class extends l{},ce=class extends l{},le=class extends v{},pe=class extends v{},ge=class extends E{},ye=class extends d{},me=class extends d{},_=class extends d{},T=class extends d{},at=class extends d{},He=class extends d{},dt=class extends d{},ut=class extends d{},je=class extends d{},fe=class extends x{},ct=class extends l{},lt=class extends h{},pt=class extends R{},S=class extends l{},k=class extends l{},he=class extends je{},gt=class extends R{},c=class extends d{description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},be=class extends c{},w=class extends c{},xe=class extends c{},ve=class extends c{},C=class extends c{},yt=class extends w{},mt=class extends C{},Te=class extends c{},Ie=class extends c{},Ae=class extends c{},Re=class extends c{},Ee=class extends c{},_e=class extends c{},Se=class extends c{},ke=class extends c{},we=class extends c{};var St={slug_taken:M,already_member:F,already_deleted:H,already_revoked:Y,already_settled:J,already_active:X,already_inactive:Q,already_accessed:Z,not_deleted:ee,last_admin:te,pending_exists:re,invalid_state_transition:ne,schema_name_taken:se,domain_taken:ie,duplicate:oe,token_missing:j,token_expired:z,token_invalid:K,pool_stale:fe,not_admin:N,forbidden:G,not_member:le,not_allowed:pe,permanently_deleted:W,invitation_expired:V,link_invalid:Me,invalid_value:ae,invalid_expiry:Fe,required:de,empty:ue,bad_request:ce,app_unavailable:ge},kt={validation:l,unauthenticated:x,permission_denied:v,not_found:h,conflict:u,precondition_failed:$,rate_limited:A,internal:R,unavailable:E},wt={invalid_grant:be,access_denied:w,authorization_pending:xe,slow_down:ve,expired_token:C,invalid_target:Te,invalid_client:Ie,invalid_request:Ae,invalid_scope:Re,invalid_token:Ee,unauthorized_client:_e,unsupported_grant_type:Se,server_error:ke,temporarily_unavailable:we},Ct={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Vt(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let r=e;return typeof r.code=="string"&&typeof r.category=="string"&&typeof r.retryable=="boolean"}function Yt(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}function Ot(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}function ft(t){return Ot(t.path)&&Yt(t.body)?Xt(t):Vt(t.body)?Jt(t):new _({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}function Jt(t){let r=t.body.error,n=r.retry?{afterMs:r.retry.after_ms}:void 0,s={message:r.message,code:r.code,category:r.category,httpStatus:t.status,retryable:r.retryable,requestId:r.request_id||t.fallbackRequestId,resource:r.resource,fields:r.fields,retry:n,docUrl:r.doc_url},a=St[r.code];if(a)return new a(s);let p=kt[r.category]??d;return new p(s)}function Xt(t){let e=t.body,r=wt[e.error]??c,n=Ct[e.error]??false;return new r({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:n,requestId:t.fallbackRequestId})}function Qt(t){return t}function Zt(t){return t}function er(t){return t}function tr(t){return t}function rr(t){return t}function nr(t){return t}function sr(t){return t}function ir(t){return t}var or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qt=/^[a-z][a-z0-9-]{0,62}$/;function ze(t,e,r){return new l({message:t,code:r,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:r}]})}function f(t,e){if(t.trim()==="")throw ze(`${e} must be non-empty`,e,"empty");if(!or.test(t))throw ze(`${e} must be a UUID`,e,"invalid_uuid")}function Pt(t,e){if(t.trim()==="")throw ze(`${e} must be non-empty`,e,"empty");if(!qt.test(t))throw ze(`${e} must match ${qt.source}`,e,"invalid_slug")}var ar={tenant(t){return f(t,"tenantId"),t},tenantSlug(t){return Pt(t,"tenantSlug"),t},app(t){return f(t,"appId"),t},appSlug(t){return Pt(t,"appSlug"),t},user(t){return f(t,"userId"),t},deployment(t){return f(t,"deploymentId"),t},pat(t){return f(t,"patId"),t},resource(t){return f(t,"resourceId"),t},connector(t){return f(t,"connectorId"),t},subject(t){return f(t,"subjectId"),t},grant(t){return f(t,"grantId"),t},tag(t){return f(t,"tagId"),t},auditEvent(t){return f(t,"auditEventId"),t},table(t){return f(t,"tableId"),t}};var Ce=class{token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},Oe=class{headersFor(e){return {}}async onUnauthorized(){return false}};var Ke={debug(){},info(){},warn(){},error(){}};function ht(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let r=Number(e);if(Number.isFinite(r))return r>=0?Math.floor(r*1e3):6e4;let n=Date.parse(e);return Number.isNaN(n)?6e4:Math.max(0,n-Date.now())}var dr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),ur="***REDACTED***";function Dt(t){let e={},r=(n,s)=>{e[n]=dr.has(n.toLowerCase())?ur:s;};if(typeof Headers<"u"&&t instanceof Headers)t.forEach((n,s)=>r(s,n));else for(let[n,s]of Object.entries(t))r(n,s);return e}var xt={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function cr(t){return t instanceof d?t.retryable:t instanceof TypeError}async function Lt(t,e=xt,r){let n;for(let s=0;s<e.maxAttempts;s++){if(r?.aborted)throw bt("aborted before attempt",r.reason);try{return await t(s)}catch(a){if(n=a,!cr(a)||s===e.maxAttempts-1)throw a;let p=Math.min(e.capMs,e.baseMs*2**s)*e.jitter();await vt(p,r);}}throw n}function vt(t,e){return new Promise((r,n)=>{if(e?.aborted){n(bt("aborted before sleep",e.reason));return}let s=setTimeout(()=>{e?.removeEventListener("abort",a),r();},t),a=()=>{clearTimeout(s),n(bt("aborted during sleep",e?.reason));};e?.addEventListener("abort",a,{once:true});})}function bt(t,e){return new T({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}var lr=new Set(["GET","HEAD","OPTIONS"]),Ne=class{baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??Ke,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid},this.retryPolicy=e.retryPolicy??xt,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,r,n){let s=lr.has(e.toUpperCase()),a=this.withStableIdempotencyKey(n);return s||n.idempotent?Lt(()=>this.requestOnce(e,r,a),this.retryPolicy,a.signal):this.requestOnce(e,r,a)}async requestOnce(e,r,n){let s=this.buildUrl(r,n.query),a=ulid(),p=this.buildHeaders(a,n);if(n.body!==void 0&&n.form!==void 0)throw new d({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:a});let b=n.form!==void 0?this.formBody(n.form):n.body!==void 0?JSON.stringify(n.body):void 0;b!==void 0&&(p["Content-Type"]=n.form!==void 0?"application/x-www-form-urlencoded":"application/json");let g=new AbortController,$e=()=>g.abort(n.signal?.reason);n.signal?.addEventListener("abort",$e,{once:true});let Et=n.timeoutMs??this.timeoutMs,Gt=setTimeout(()=>g.abort(new Error("timeout")),Et),y;try{this.logRequest(e,s,p,a),y=await this.fetch(s,{method:e,headers:p,body:b,redirect:"manual",signal:g.signal});}catch(I){throw n.signal?.aborted?new T({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:a,cause:I}):g.signal.aborted?new me({message:`Request timed out after ${Et}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:a,cause:I}):new ye({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:a,cause:I})}finally{clearTimeout(Gt),n.signal?.removeEventListener("abort",$e);}if(y.status>=300&&y.status<400)return {status:y.status,location:y.headers.get("Location")??y.headers.get("location")};if(n.rawResponse&&y.ok)return {response:y,requestId:a};if(y.ok)return this.parseSuccess(y,n,a);let ot=await this.safeParseJson(y);if(y.status===401&&n.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,r,n);if(y.status===429){let I=ht(y.headers.get("Retry-After")),Wt=new A({message:pr(ot)??"Rate limited",code:gr(ot)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:a,retry:{afterMs:I}});if(this.rateLimitStrategy==="sleep")return await vt(I,n.signal),this.requestOnce(e,r,n);throw Wt}throw ft({path:r,status:y.status,body:ot,fallbackRequestId:a})}async parseSuccess(e,r,n){if(e.status===204||r.parseBody===false)return;let s=await e.text();if(s!=="")try{return JSON.parse(s)}catch{return s}}async safeParseJson(e){try{let r=await e.text();return r===""?void 0:JSON.parse(r)}catch{return}}buildUrl(e,r){let n=e.startsWith("/")?e:`/${e}`,s=this.baseUrl+n;if(!r)return s;let a=new URLSearchParams;for(let[b,g]of Object.entries(r))if(g!==void 0)if(Array.isArray(g))for(let $e of g)a.append(b,String($e));else a.set(b,String(g));let p=a.toString();return p?`${s}?${p}`:s}buildHeaders(e,r){let n=this.resolveIdempotencyKey(r);return {"X-Request-Id":e,Accept:"application/json",...r.ring!=="public"?this.auth.headersFor(r.ring):{},...n?{"Idempotency-Key":n}:{},...r.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new d({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let r=new URLSearchParams;for(let[n,s]of Object.entries(e))s!==void 0&&r.set(n,String(s));return r.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,r,n,s){this.debug&&this.logger.debug({method:e,url:r,headers:Dt(n),requestId:s},"http.request");}};function pr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.message;if(typeof r=="string")return r}if(typeof e=="string")return e}function gr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.code;if(typeof r=="string")return r}}var Bt=4096,$t=false;function Mt(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}function yr(t){if(t.length>Bt)throw new S({message:`Cursor token exceeds maximum size (${Bt} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new k({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new k({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!br(e))throw new Error("invalid cursor shape");return e}catch(e){throw new S({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}function mr(t,e){let r=typeof t=="string"?t.split(",").map(n=>{let s=n.trim();return s.startsWith("-")?{field:s.slice(1),dir:"desc"}:s.startsWith("+")?{field:s.slice(1),dir:"asc"}:{field:s,dir:"asc"}}).filter(n=>n.field.length>0):[...t??[]].map(n=>({field:n.field,dir:n.dir??"asc"}));return r.length>0&&!r.some(n=>n.field==="id")&&(e?.warnOnTiebreaker&&!$t&&($t=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),r.push({field:"id",dir:"asc"})),r}function fr(t){return JSON.stringify(Ft(t))}function hr(t,e){if(!t)return null;let r=Ft(e?.orderBy,{warnOnTiebreaker:true}),n={};for(let b of r){let g=t[b.field];(g===null||typeof g=="string"||typeof g=="number"||typeof g=="boolean")&&(n[b.field]=g);}let s=t.id,a={values:n,direction:e?.direction??"forward",orderBy:r,orderByFingerprint:JSON.stringify(r)};(typeof s=="string"||typeof s=="number")&&(a.tiebreaker={field:"id",value:s});let p=e?.page;return typeof p=="number"&&Number.isInteger(p)&&p>0&&(a.page=p),e?.contextFingerprint&&(a.contextFingerprint=e.contextFingerprint),Mt(a)}function Ft(t,e){let r=mr(t,e);return r.length>0?r:[{field:"id",dir:"asc"}]}function br(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}function Tt(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}function vr(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}function Tr(t,e,r){let n=r?Buffer.concat([Buffer.from(`${r}.`),Tt(t)]):Tt(t);return `sha256=${createHmac("sha256",e).update(n).digest("hex")}`}function Ir(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=vr(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let r=Math.floor((t.now?.()??Date.now())/1e3),n=Tt(t.rawBody);if(t.timestamp!==void 0){let a=Number(t.timestamp);if(!Number.isFinite(a))return {ok:false,reason:"timestamp_skew"};let p=t.tolerance??300;if(Math.abs(r-a)>p)return {ok:false,reason:"timestamp_skew"};let b=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(b))return {ok:false,reason:"replay"};n=Buffer.concat([Buffer.from(`${t.timestamp}.`),n]);}let s=createHmac("sha256",t.secret).update(n).digest();return e.byteLength!==s.byteLength?{ok:false,reason:"signature_mismatch"}:timingSafeEqual(e,s)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}function o(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}function O(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}function q(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}function m(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}function i(t){return encodeURIComponent(t)}function Ge(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}function Ar(t){return {id:String(t.id),role:String(t.role),...t,userId:t.user_id??t.userId}}function It(t){return {id:String(t.id),email:String(t.email),role:String(t.role),status:String(t.status),...t}}function jt(t){return {...t,domain:String(t.domain??t.email_domain),verified:t.verified}}var P=class{constructor(e,r){this.http=e;this.mockStore=r;}http;mockStore;scoped(e){return new We(this.http,e)}async create(e,r){if(this.mockStore)return this.mockStore.createTenant(e);let n=await this.http.request("POST","/api/v1/tenants",o({ring:"admin",body:m(e),idempotent:false},r));return Ge(n)}async get(e,r){if(this.mockStore)return this.mockStore.getTenant(e);let n=await this.http.request("GET",`/api/v1/tenants/${i(e)}`,o({ring:"admin"},r));return Ge(n)}async list(e){if(this.mockStore)return this.mockStore.listTenants();let r=await this.http.request("GET","/api/v1/tenants",o({ring:"admin",query:O(e)},e));return q(r,Ge)}async update(e,r,n){if(this.mockStore)return this.mockStore.updateTenant(e,r);let s=await this.http.request("PATCH",`/api/v1/tenants/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n));return Ge(s)}async delete(e,r){if(this.mockStore)return this.mockStore.deleteTenant(e);await this.http.request("DELETE",`/api/v1/tenants/${i(e)}`,o({ring:"admin",idempotent:true},r));}async signIconUploadURL(e,r,n){let s=await this.http.request("POST",`/api/v1/tenants/${i(e)}/icon/upload-url`,o({ring:"admin",body:{content_type:r.contentType},idempotent:false},n));return {uploadUrl:s.upload_url??s.put_url??"",getUrl:s.get_url??s.public_url??"",expiresAt:s.expires_at}}get members(){return new Ve(this.http)}get invitations(){return new Ye(this.http)}get emailDomains(){return new Je(this.http)}},We=class{members;invitations;emailDomains;constructor(e,r){this.members=new qe(e,r),this.invitations=new Pe(e,r),this.emailDomains=new De(e,r);}},Ve=class{constructor(e){this.http=e;}http;forTenant(e){return new qe(this.http,e)}},qe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/members`,o({ring:"admin",query:O(e)},e));return q(r,Ar)}async update(e,r,n){await this.http.request("PATCH",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n));}async deactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}/deactivate`,o({ring:"admin",body:{},idempotent:false},r));}async reactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/members/${i(e)}/reactivate`,o({ring:"admin",body:{},idempotent:false},r));}},Ye=class{constructor(e){this.http=e;}http;forTenant(e){return new Pe(this.http,e)}},Pe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/invitations`,o({ring:"admin",query:O(e)},e));return q(r,It)}async create(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/invitations`,o({ring:"admin",body:m(e),idempotent:false},r));return It(n)}async bulkCreate(e,r){if(e.length>200)throw new l({message:"bulk invitations are capped at 200",code:"too_many_items",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"invitations",code:"max_200"}]});let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/invitations/bulk`,o({ring:"admin",body:{items:e},idempotent:false},r));return {accepted:(n.succeeded??[]).map(It),rejected:(n.failed??[]).map(s=>({email:s.email,reason:s.reason,message:s.message}))}}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${i(this.tenant)}/invitations/${i(e)}`,o({ring:"admin",idempotent:true},r));}},Je=class{constructor(e){this.http=e;}http;forTenant(e){return new De(this.http,e)}},De=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;async list(e){return (await this.http.request("GET",`/api/v1/tenants/${i(this.tenant)}/email-domains`,o({ring:"admin"},e))).items.map(jt)}async create(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenant)}/email-domains`,o({ring:"admin",body:{email_domain:e.domain},idempotent:false},r));return jt(n)}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${i(this.tenant)}/email-domains/${i(e)}`,o({ring:"admin",idempotent:true},r));}};var D=class{constructor(e){this.http=e;}http;scoped(e){return new Xe(this.http,e)}},Xe=class{tags;subjects;grants;constructor(e,r){let n=`/api/v1/tenants/${i(r)}`;this.tags=new Qe(e,`${n}/tags`),this.subjects=new Ze(e,`${n}/subjects`),this.grants=new et(e,`${n}/grants`);}},Qe=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,o({ring:"admin",body:m(e),idempotent:false},r))}update(e,r,n){return this.http.request("PATCH",`${this.base}/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n))}delete(e,r){return this.http.request("DELETE",`${this.base}/${i(e)}`,o({ring:"admin",idempotent:true},r))}},Ze=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,o({ring:"admin",body:m(e),idempotent:false},r))}update(e,r,n){return this.http.request("PATCH",`${this.base}/${i(e)}`,o({ring:"admin",body:m(r),idempotent:false},n))}delete(e,r){return this.http.request("DELETE",`${this.base}/${i(e)}`,o({ring:"admin",idempotent:true},r))}},et=class{constructor(e,r){this.http=e;this.base=r;}http;base;list(e){return this.http.request("GET",this.base,o({ring:"admin"},e))}};function Le(t){return {id:String(t.id),...t,actorId:t.actor_id??t.actorId,prevHash:t.prev_hash??t.prevHash,createdAt:t.created_at??t.createdAt}}function Rr(t){let e={ok:!!t.ok,checked:Number(t.checked??0)};return t.first_bad_seq!==void 0&&t.first_bad_seq!==null&&(e.firstBadSeq=Number(t.first_bad_seq)),t.reason!==void 0&&(e.reason=t.reason),e}var L=class{constructor(e){this.http=e;this.events=new rt(e),this.server=new nt(e);}http;events;server;scoped(e){return new tt(this.http,e)}integrityCheck(e,r){return this.scoped(e).integrityCheck(r)}anonymize(e,r,n){return this.scoped(e).anonymize(r,n)}},tt=class{constructor(e,r){this.http=e;this.tenantSlug=r;this.events=new Ue(e,r),this.server=new Be(e,r);}http;tenantSlug;events;server;async integrityCheck(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/integrity-check`,o({ring:"admin"},e));return Rr(r)}async anonymize(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/anonymize`,o({ring:"admin",body:{tenant_id:this.tenantSlug,actor_id:e.actorId??e.subjectId,anonymized_id:e.anonymizedId},idempotent:false},r));return n===void 0?void 0:Le(n)}},rt=class{constructor(e){this.http=e;}http;forTenant(e){return new Ue(this.http,e)}},Ue=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events`,o({ring:"admin",query:{...O(e),...e?.type?{type:e.type}:{}}},e));return Array.isArray(r)?{items:r.map(Le),nextCursor:null,total:r.length}:q({items:r.items??[],next_cursor:r.next_cursor??null,total:r.total??r.items?.length??0},Le)}async get(e,r){let n=await this.http.request("GET",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/${i(e)}`,o({ring:"admin"},r));return Le(n)}},nt=class{constructor(e){this.http=e;}http;forTenant(e){return new Be(this.http,e)}},Be=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;async emit(e,r){let n=await this.http.request("POST",`/api/v1/tenants/${i(this.tenantSlug)}/audit-events/server`,o({ring:"admin",body:{type:e.type,actor_id:e.actorId,resource:e.resource,payload:e.payload},idempotent:false},r));return Le(n)}};var U=class{constructor(e){this.http=e;}http;list(e,r){return this.http.request("GET",`/api/v1/tenants/${i(e)}/identity-providers`,o({ring:"admin"},r))}create(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers`,o({ring:"admin",body:r,idempotent:false},n))}enable(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers/${i(r)}/enable`,o({ring:"admin",body:{},idempotent:false},n))}disable(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/identity-providers/${i(r)}/disable`,o({ring:"admin",body:{},idempotent:false},n))}};var B=class{constructor(e){this.http=e;}http;create(e,r,n){return this.http.request("POST",`/api/v1/tenants/${i(e)}/categories`,o({ring:"admin",body:m(r),idempotent:false},n))}update(e,r,n,s){return this.http.request("PATCH",`/api/v1/tenants/${i(e)}/categories/${i(r)}`,o({ring:"admin",body:m(n),idempotent:false},s))}delete(e,r,n){return this.http.request("DELETE",`/api/v1/tenants/${i(e)}/categories/${i(r)}`,o({ring:"admin",idempotent:true},n))}};var Er=new Set(["1","true","yes","on"]);function _r(t){return t?.trim().toLowerCase()==="production"}function Sr(t){return t===void 0?false:Er.has(t.trim().toLowerCase())}function zt(){if(_r(process.env.NODE_ENV)){if(Sr(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/admin-sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new he({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}function At(t){return new h({message:`Mock tenant not found: ${t}`,code:"tenant_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`tenants/${t}`})}var st=class{tenants=new Map;nextId=1;constructor(e){for(let r of e?.tenants??[]){let n=String(r.id);this.tenants.set(n,{...r,id:n});}}createTenant(e){let r=`tenant_${this.nextId++}`,n=new Date().toISOString(),s={id:r,slug:e.slug,name:e.name,...e.plan!==void 0?{plan:e.plan}:{},createdAt:n,updatedAt:n};return this.tenants.set(r,s),{...s}}getTenant(e){let r=this.tenants.get(e);if(!r)throw At(e);return {...r}}listTenants(){let e=[...this.tenants.values()].map(r=>({...r}));return {items:e,nextCursor:null,total:e.length}}updateTenant(e,r){let n=this.tenants.get(e);if(!n)throw At(e);let s={...n,...r,id:e,updatedAt:new Date().toISOString()};return this.tenants.set(e,s),{...s}}deleteTenant(e){if(!this.tenants.has(e))throw At(e);this.tenants.delete(e);}};function Kt(t){if(t.mode==="mock")return zt(),new st(t.fixtures)}var Nt="https://api.axhub.ai";function kr(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}var Rt=class{http;logger;mock;r;n;s;i;o;constructor(e){if(kr(e)){this.http=e.__sharedHttp,this.logger=e.logger;return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AdminClient requires tokenType when token is set ("pat" | "jwt")');let r=e.token!==void 0&&e.tokenType!==void 0?new Ce({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new Oe;this.http=new Ne({baseUrl:e.baseUrl??Nt,auth:r,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.logger=e.logger??Ke,this.mock=Kt(e);}get tenants(){return this.r||(this.r=new P(this.http,this.mock)),this.r}get authz(){return this.n||(this.n=new D(this.http)),this.n}get audit(){return this.s||(this.s=new L(this.http)),this.s}get identityProviders(){return this.i||(this.i=new U(this.http)),this.i}get categories(){return this.o||(this.o=new B(this.http)),this.o}tenant(e){return new it(e,this.http)}},it=class{constructor(e,r){this.tenant=e;this.http=r;}tenant;http;get tenants(){return new P(this.http).scoped(this.tenant)}get authz(){return new D(this.http).scoped(this.tenant)}get audit(){return new L(this.http).scoped(this.tenant)}get identityProviders(){return new U(this.http)}get categories(){return new B(this.http)}};
|
|
2
|
-
export{
|
|
1
|
+
import {ulid}from'ulid';import {createHmac,timingSafeEqual}from'crypto';var Yt=Object.defineProperty;var n=(t,e)=>Yt(t,"name",{value:e,configurable:true});var u=class extends Error{static{n(this,"AxHubError");}code;category;httpStatus;retryable;requestId;resource;fields;retry;docUrl;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.name=this.constructor.name,this.code=e.code,this.category=e.category,this.httpStatus=e.httpStatus,this.retryable=e.retryable,this.requestId=e.requestId,e.resource!==void 0&&(this.resource=e.resource),e.fields!==void 0&&(this.fields=e.fields),e.retry!==void 0&&(this.retry=e.retry),e.docUrl!==void 0&&(this.docUrl=e.docUrl);}toJSON(){return {name:this.name,message:this.message,code:this.code,category:this.category,httpStatus:this.httpStatus,retryable:this.retryable,requestId:this.requestId,resource:this.resource,fields:this.fields,retry:this.retry,docUrl:this.docUrl}}toString(){return St(this)}};function St(t){let e=[`${t.name}[${t.code}]`];return t.requestId&&e.push(`req=${t.requestId}`),e.push(`problem=${t.message}`),t.fields?.length&&e.push(`cause=${t.fields.map(r=>`${r.name}:${r.code}`).join(",")}`),t.retry?.afterMs!==void 0?e.push(`fix=retry_after_${t.retry.afterMs}ms`):t.retryable?e.push("fix=retry_with_backoff"):e.push("fix=inspect_input_or_permissions"),t.docUrl&&e.push(`docs=${t.docUrl}`),e.join(" ")}n(St,"formatErrorMessage");var p=class extends u{static{n(this,"ValidationError");}},v=class extends u{static{n(this,"UnauthenticatedError");}},T=class extends u{static{n(this,"PermissionDeniedError");}},b=class extends u{static{n(this,"NotFoundError");}},c=class extends u{static{n(this,"ConflictError");}},M=class extends u{static{n(this,"PreconditionFailedError");}},R=class extends u{static{n(this,"RateLimitedError");}},E=class extends u{static{n(this,"InternalServerError");}},_=class extends u{static{n(this,"UnavailableError");}},F=class extends c{static{n(this,"SlugTakenError");}},H=class extends c{static{n(this,"AlreadyMemberError");}},j=class extends c{static{n(this,"AlreadyDeletedError");}},z=class extends v{static{n(this,"TokenMissingError");}},K=class extends v{static{n(this,"TokenExpiredError");}},N=class extends v{static{n(this,"TokenInvalidError");}},G=class extends T{static{n(this,"NotAdminError");}},W=class extends T{static{n(this,"ForbiddenError");}},V=class extends b{static{n(this,"PermanentlyDeletedError");}},Y=class extends b{static{n(this,"InvitationExpiredError");}},Fe=class extends b{static{n(this,"LinkInvalidError");}},J=class extends c{static{n(this,"AlreadyRevokedError");}},X=class extends c{static{n(this,"AlreadySettledError");}},Q=class extends c{static{n(this,"AlreadyActiveError");}},Z=class extends c{static{n(this,"AlreadyInactiveError");}},ee=class extends c{static{n(this,"AlreadyAccessedError");}},te=class extends c{static{n(this,"NotDeletedError");}},re=class extends c{static{n(this,"LastAdminError");}},ne=class extends c{static{n(this,"PendingExistsError");}},se=class extends c{static{n(this,"InvalidStateTransitionError");}},ie=class extends c{static{n(this,"SchemaNameTakenError");}},oe=class extends c{static{n(this,"DomainTakenError");}},ae=class extends c{static{n(this,"DuplicateError");}},de=class extends p{static{n(this,"InvalidValueError");}},He=class extends p{static{n(this,"InvalidExpiryError");}},ue=class extends p{static{n(this,"RequiredError");}},ce=class extends p{static{n(this,"EmptyError");}},le=class extends p{static{n(this,"BadRequestError");}},pe=class extends T{static{n(this,"NotMemberError");}},ge=class extends T{static{n(this,"NotAllowedError");}},ye=class extends _{static{n(this,"AppUnavailableError");}},me=class extends u{static{n(this,"NetworkError");}},fe=class extends u{static{n(this,"TimeoutError");}},S=class extends u{static{n(this,"DecodeError");}},I=class extends u{static{n(this,"AbortError");}},dt=class extends u{static{n(this,"InvalidPathError");}},je=class extends u{static{n(this,"StreamConsumedError");}},ut=class extends u{static{n(this,"TenantSlugRequiredError");}},ct=class extends u{static{n(this,"TenantIdRequiredError");}},ze=class extends u{static{n(this,"ConfigurationError");}},he=class extends v{static{n(this,"PoolStaleError");}},lt=class extends p{static{n(this,"WebhookVerificationError");}},pt=class extends b{static{n(this,"TableNotFoundError");}},gt=class extends E{static{n(this,"IntrospectFailedError");}},k=class extends p{static{n(this,"InvalidCursorError");}},w=class extends p{static{n(this,"LegacyCursorError");}},be=class extends ze{static{n(this,"MockInProductionError");}},yt=class extends E{static{n(this,"ScanLimitExceededError");}},l=class extends u{static{n(this,"OAuthError");}description;uri;constructor(e){super({message:e.description??e.code,code:e.code,category:"oauth",httpStatus:e.httpStatus,retryable:e.retryable,requestId:e.requestId}),e.description!==void 0&&(this.description=e.description),e.uri!==void 0&&(this.uri=e.uri);}},xe=class extends l{static{n(this,"InvalidGrantError");}},C=class extends l{static{n(this,"AccessDeniedError");}},ve=class extends l{static{n(this,"AuthorizationPendingError");}},Te=class extends l{static{n(this,"SlowDownError");}},O=class extends l{static{n(this,"ExpiredTokenError");}},mt=class extends C{static{n(this,"DeviceFlowDeniedError");}},ft=class extends O{static{n(this,"DeviceFlowTimeoutError");}},Ie=class extends l{static{n(this,"InvalidTargetError");}},Ae=class extends l{static{n(this,"InvalidClientError");}},Re=class extends l{static{n(this,"InvalidRequestError");}},Ee=class extends l{static{n(this,"InvalidScopeError");}},_e=class extends l{static{n(this,"InvalidTokenError");}},Se=class extends l{static{n(this,"UnauthorizedClientError");}},ke=class extends l{static{n(this,"UnsupportedGrantTypeError");}},we=class extends l{static{n(this,"OAuthServerError");}},Ce=class extends l{static{n(this,"TemporarilyUnavailableError");}};var kt={slug_taken:F,already_member:H,already_deleted:j,already_revoked:J,already_settled:X,already_active:Q,already_inactive:Z,already_accessed:ee,not_deleted:te,last_admin:re,pending_exists:ne,invalid_state_transition:se,schema_name_taken:ie,domain_taken:oe,duplicate:ae,token_missing:z,token_expired:K,token_invalid:N,pool_stale:he,not_admin:G,forbidden:W,not_member:pe,not_allowed:ge,permanently_deleted:V,invitation_expired:Y,link_invalid:Fe,invalid_value:de,invalid_expiry:He,required:ue,empty:ce,bad_request:le,app_unavailable:ye},wt={validation:p,unauthenticated:v,permission_denied:T,not_found:b,conflict:c,precondition_failed:M,rate_limited:R,internal:E,unavailable:_},Ct={invalid_grant:xe,access_denied:C,authorization_pending:ve,slow_down:Te,expired_token:O,invalid_target:Ie,invalid_client:Ae,invalid_request:Re,invalid_scope:Ee,invalid_token:_e,unauthorized_client:Se,unsupported_grant_type:ke,server_error:we,temporarily_unavailable:Ce},Ot={authorization_pending:true,slow_down:true,access_denied:false,invalid_grant:false,expired_token:false,server_error:true,temporarily_unavailable:true};function Jt(t){if(typeof t!="object"||t===null)return false;let e=t.error;if(typeof e!="object"||e===null)return false;let r=e;return typeof r.code=="string"&&typeof r.category=="string"&&typeof r.retryable=="boolean"}n(Jt,"isWrappedEnvelope");function Xt(t){return typeof t!="object"||t===null?false:typeof t.error=="string"}n(Xt,"isOAuthErrorBody");function qt(t){return t.startsWith("/oauth/")||t.startsWith("/auth/")}n(qt,"isOAuthPath");function ht(t){return qt(t.path)&&Xt(t.body)?Zt(t):Jt(t.body)?Qt(t):new S({message:"Unexpected error response shape",code:"decode_failed",category:"decode",httpStatus:t.status,retryable:false,requestId:t.fallbackRequestId})}n(ht,"dispatch");function Qt(t){let r=t.body.error,s=r.retry?{afterMs:r.retry.after_ms}:void 0,i={message:r.message,code:r.code,category:r.category,httpStatus:t.status,retryable:r.retryable,requestId:r.request_id||t.fallbackRequestId,resource:r.resource,fields:r.fields,retry:s,docUrl:r.doc_url},d=kt[r.code];if(d)return new d(i);let g=wt[r.category]??u;return new g(i)}n(Qt,"dispatchWrapped");function Zt(t){let e=t.body,r=Ct[e.error]??l,s=Ot[e.error]??false;return new r({code:e.error,description:e.error_description,uri:e.error_uri,httpStatus:t.status,retryable:s,requestId:t.fallbackRequestId})}n(Zt,"dispatchOAuth");function er(t){return t}n(er,"asAppId");function tr(t){return t}n(tr,"asDeploymentId");function rr(t){return t}n(rr,"asTenantId");function nr(t){return t}n(nr,"asTenantSlug");function sr(t){return t}n(sr,"asAppSlug");function ir(t){return t}n(ir,"asPatId");function or(t){return t}n(or,"asUserId");function ar(t){return t}n(ar,"asRequestId");var dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pt=/^[a-z][a-z0-9-]{0,62}$/;function Ke(t,e,r){return new p({message:t,code:r,category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:e,code:r}]})}n(Ke,"validation");function h(t,e){if(t.trim()==="")throw Ke(`${e} must be non-empty`,e,"empty");if(!dr.test(t))throw Ke(`${e} must be a UUID`,e,"invalid_uuid")}n(h,"requireUuid");function Dt(t,e){if(t.trim()==="")throw Ke(`${e} must be non-empty`,e,"empty");if(!Pt.test(t))throw Ke(`${e} must match ${Pt.source}`,e,"invalid_slug")}n(Dt,"requireSlug");var ur={tenant(t){return h(t,"tenantId"),t},tenantSlug(t){return Dt(t,"tenantSlug"),t},app(t){return h(t,"appId"),t},appSlug(t){return Dt(t,"appSlug"),t},user(t){return h(t,"userId"),t},deployment(t){return h(t,"deploymentId"),t},pat(t){return h(t,"patId"),t},resource(t){return h(t,"resourceId"),t},connector(t){return h(t,"connectorId"),t},subject(t){return h(t,"subjectId"),t},grant(t){return h(t,"grantId"),t},tag(t){return h(t,"tagId"),t},auditEvent(t){return h(t,"auditEventId"),t},table(t){return h(t,"tableId"),t}};var Oe=class{static{n(this,"StaticTokenAuth");}token;tokenType;onRefresh;refreshing=null;constructor(e){this.token=e.token,this.tokenType=e.tokenType,this.onRefresh=e.onRefresh;}currentToken(){return this.token}headersFor(e){return e==="public"?{}:this.tokenType==="pat"?{"X-Api-Key":this.token}:{Authorization:`Bearer ${this.token}`}}async onUnauthorized(){return this.tokenType!=="jwt"||!this.onRefresh?false:this.refreshing?this.refreshing:(this.refreshing=(async()=>{try{let e=await this.onRefresh();return this.token=e,!0}catch{return false}finally{this.refreshing=null;}})(),this.refreshing)}},qe=class{static{n(this,"NoAuth");}headersFor(e){return {}}async onUnauthorized(){return false}};var Ne={debug(){},info(){},warn(){},error(){}};function bt(t){if(!t)return 6e4;let e=t.trim();if(e==="")return 6e4;let r=Number(e);if(Number.isFinite(r))return r>=0?Math.floor(r*1e3):6e4;let s=Date.parse(e);return Number.isNaN(s)?6e4:Math.max(0,s-Date.now())}n(bt,"parseRetryAfter");var cr=new Set(["authorization","x-api-key","cookie","set-cookie","proxy-authorization"]),lr="***REDACTED***";function Lt(t){let e={},r=n((s,i)=>{e[s]=cr.has(s.toLowerCase())?lr:i;},"visit");if(typeof Headers<"u"&&t instanceof Headers)t.forEach((s,i)=>r(i,s));else for(let[s,i]of Object.entries(t))r(s,i);return e}n(Lt,"redactHeaders");var vt={maxAttempts:3,baseMs:200,capMs:5e3,jitter:Math.random};function pr(t){return t instanceof u?t.retryable:t instanceof TypeError}n(pr,"isRetriable");async function Ut(t,e=vt,r){let s;for(let i=0;i<e.maxAttempts;i++){if(r?.aborted)throw xt("aborted before attempt",r.reason);try{return await t(i)}catch(d){if(s=d,!pr(d)||i===e.maxAttempts-1)throw d;let g=Math.min(e.capMs,e.baseMs*2**i)*e.jitter();await Tt(g,r);}}throw s}n(Ut,"withRetry");function Tt(t,e){return new Promise((r,s)=>{if(e?.aborted){s(xt("aborted before sleep",e.reason));return}let i=setTimeout(()=>{e?.removeEventListener("abort",d),r();},t),d=n(()=>{clearTimeout(i),s(xt("aborted during sleep",e?.reason));},"onAbort");e?.addEventListener("abort",d,{once:true});})}n(Tt,"abortableSleep");function xt(t,e){return new I({message:t,code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:"",cause:e})}n(xt,"aborted");var gr=new Set(["GET","HEAD","OPTIONS"]),Ge=class{static{n(this,"HttpClient");}baseUrl;auth;fetch;logger;debug;timeoutMs;idempotencyKey;retryPolicy;rateLimitStrategy;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.auth=e.auth,this.fetch=e.fetch??globalThis.fetch,this.logger=e.logger??Ne,this.debug=e.debug??false,this.timeoutMs=e.timeoutMs??3e4,this.idempotencyKey={autoGenerate:e.idempotencyKey?.autoGenerate??true,generator:e.idempotencyKey?.generator??ulid},this.retryPolicy=e.retryPolicy??vt,this.rateLimitStrategy=e.rateLimitStrategy??"sleep";}async request(e,r,s){let i=gr.has(e.toUpperCase()),d=this.withStableIdempotencyKey(s);return i||s.idempotent?Ut(()=>this.requestOnce(e,r,d),this.retryPolicy,d.signal):this.requestOnce(e,r,d)}async requestOnce(e,r,s){let i=this.buildUrl(r,s.query),d=ulid(),g=this.buildHeaders(d,s);if(s.body!==void 0&&s.form!==void 0)throw new u({message:"body and form are mutually exclusive",code:"invalid_request_body",category:"validation",httpStatus:0,retryable:false,requestId:d});let x=s.form!==void 0?this.formBody(s.form):s.body!==void 0?JSON.stringify(s.body):void 0;x!==void 0&&(g["Content-Type"]=s.form!==void 0?"application/x-www-form-urlencoded":"application/json");let y=new AbortController,Me=n(()=>y.abort(s.signal?.reason),"externalAbort");s.signal?.addEventListener("abort",Me,{once:true});let _t=s.timeoutMs??this.timeoutMs,Wt=setTimeout(()=>y.abort(new Error("timeout")),_t),m;try{this.logRequest(e,i,g,d),m=await this.fetch(i,{method:e,headers:g,body:x,redirect:"manual",signal:y.signal});}catch(A){throw s.signal?.aborted?new I({message:"Request aborted",code:"aborted",category:"abort",httpStatus:0,retryable:false,requestId:d,cause:A}):y.signal.aborted?new fe({message:`Request timed out after ${_t}ms`,code:"timeout",category:"timeout",httpStatus:0,retryable:true,requestId:d,cause:A}):new me({message:"Network error",code:"network",category:"network",httpStatus:0,retryable:true,requestId:d,cause:A})}finally{clearTimeout(Wt),s.signal?.removeEventListener("abort",Me);}if(m.status>=300&&m.status<400)return {status:m.status,location:m.headers.get("Location")??m.headers.get("location")};if(s.rawResponse&&m.ok)return {response:m,requestId:d};if(m.ok)return this.parseSuccess(m,s,d);let at=await this.safeParseJson(m);if(m.status===401&&s.ring==="admin"&&await this.auth.onUnauthorized())return this.requestOnce(e,r,s);if(m.status===429){let A=bt(m.headers.get("Retry-After")),Vt=new R({message:yr(at)??"Rate limited",code:mr(at)??"rate_limited",category:"rate_limited",httpStatus:429,retryable:true,requestId:d,retry:{afterMs:A}});if(this.rateLimitStrategy==="sleep")return await Tt(A,s.signal),this.requestOnce(e,r,s);throw Vt}throw ht({path:r,status:m.status,body:at,fallbackRequestId:d})}async parseSuccess(e,r,s){if(e.status===204||r.parseBody===false)return;let i=await e.text();if(i!=="")try{return JSON.parse(i)}catch{return i}}async safeParseJson(e){try{let r=await e.text();return r===""?void 0:JSON.parse(r)}catch{return}}buildUrl(e,r){let s=e.startsWith("/")?e:`/${e}`,i=this.baseUrl+s;if(!r)return i;let d=new URLSearchParams;for(let[x,y]of Object.entries(r))if(y!==void 0)if(Array.isArray(y))for(let Me of y)d.append(x,String(Me));else d.set(x,String(y));let g=d.toString();return g?`${i}?${g}`:i}buildHeaders(e,r){let s=this.resolveIdempotencyKey(r);return {"X-Request-Id":e,Accept:"application/json",...r.ring!=="public"?this.auth.headersFor(r.ring):{},...s?{"Idempotency-Key":s}:{},...r.headers??{}}}resolveIdempotencyKey(e){if(e.idempotencyKey!==false){if(typeof e.idempotencyKey=="string"){if(e.idempotencyKey.trim()==="")throw new u({message:"idempotencyKey must be non-empty",code:"invalid_idempotency_key",category:"validation",httpStatus:0,retryable:false,requestId:""});return e.idempotencyKey}if(!(!e.idempotent||!this.idempotencyKey.autoGenerate))return this.idempotencyKey.generator()}}formBody(e){let r=new URLSearchParams;for(let[s,i]of Object.entries(e))i!==void 0&&r.set(s,String(i));return r.toString()}withStableIdempotencyKey(e){return e.idempotencyKey!==void 0||!e.idempotent||!this.idempotencyKey.autoGenerate?e:{...e,idempotencyKey:this.idempotencyKey.generator()}}logRequest(e,r,s,i){this.debug&&this.logger.debug({method:e,url:r,headers:Lt(s),requestId:i},"http.request");}};function yr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.message;if(typeof r=="string")return r}if(typeof e=="string")return e}n(yr,"getMessage");function mr(t){if(typeof t!="object"||t===null)return;let e=t.error;if(typeof e=="object"&&e!==null){let r=e.code;if(typeof r=="string")return r}}n(mr,"extractCode");var $t=4096,Mt=false;function Ft(t){return `v2:${Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}`}n(Ft,"encodeCursor");function fr(t){if(t.length>$t)throw new k({message:`Cursor token exceeds maximum size (${$t} chars)`,code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"});if(t.startsWith("v1:"))throw new w({message:"Legacy v1: cursor token is not compatible with keyset pagination; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});if(!t.startsWith("v2:"))throw new w({message:"Cursor token is missing the v2: keyset prefix; restart pagination without cursor",code:"legacy_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/validation/legacy-cursor"});try{let e=JSON.parse(Buffer.from(t.slice(3),"base64url").toString("utf8"));if(!vr(e))throw new Error("invalid cursor shape");return e}catch(e){throw new k({message:"Malformed keyset cursor token",code:"invalid_cursor",category:"validation",httpStatus:0,retryable:false,requestId:"",cause:e,docUrl:"https://docs.axhub.dev/errors/validation/invalid-cursor"})}}n(fr,"decodeCursor");function hr(t,e){let r=typeof t=="string"?t.split(",").map(s=>{let i=s.trim();return i.startsWith("-")?{field:i.slice(1),dir:"desc"}:i.startsWith("+")?{field:i.slice(1),dir:"asc"}:{field:i,dir:"asc"}}).filter(s=>s.field.length>0):[...t??[]].map(s=>({field:s.field,dir:s.dir??"asc"}));return r.length>0&&!r.some(s=>s.field==="id")&&(e?.warnOnTiebreaker&&!Mt&&(Mt=true,console.warn("AX Hub SDK: orderBy is not unique; appending id ASC as keyset cursor tiebreaker")),r.push({field:"id",dir:"asc"})),r}n(hr,"normalizeOrderBy");function br(t){return JSON.stringify(Ht(t))}n(br,"orderByFingerprint");function xr(t,e){if(!t)return null;let r=Ht(e?.orderBy,{warnOnTiebreaker:true}),s={};for(let x of r){let y=t[x.field];(y===null||typeof y=="string"||typeof y=="number"||typeof y=="boolean")&&(s[x.field]=y);}let i=t.id,d={values:s,direction:e?.direction??"forward",orderBy:r,orderByFingerprint:JSON.stringify(r)};(typeof i=="string"||typeof i=="number")&&(d.tiebreaker={field:"id",value:i});let g=e?.page;return typeof g=="number"&&Number.isInteger(g)&&g>0&&(d.page=g),e?.contextFingerprint&&(d.contextFingerprint=e.contextFingerprint),Ft(d)}n(xr,"cursorFromRow");function Ht(t,e){let r=hr(t,e);return r.length>0?r:[{field:"id",dir:"asc"}]}n(Ht,"effectiveCursorOrderBy");function vr(t){return typeof t=="object"&&t!==null&&typeof t.values=="object"&&(t.direction==="forward"||t.direction==="backward")&&Array.isArray(t.orderBy)&&typeof t.orderByFingerprint=="string"}n(vr,"isKeysetCursor");function It(t){return Buffer.isBuffer(t)?t:Buffer.from(t)}n(It,"bodyBytes");function Ir(t){let e=t.startsWith("sha256=")?t.slice(7):t;return /^[0-9a-f]{64}$/i.test(e)?Buffer.from(e,"hex"):null}n(Ir,"parseSignature");function Ar(t,e,r){let s=r?Buffer.concat([Buffer.from(`${r}.`),It(t)]):It(t);return `sha256=${createHmac("sha256",e).update(s).digest("hex")}`}n(Ar,"signWebhook");function Rr(t){if(!t.secret)return {ok:false,reason:"missing_secret"};let e=Ir(t.signature);if(!e)return {ok:false,reason:"malformed_signature"};let r=Math.floor((t.now?.()??Date.now())/1e3),s=It(t.rawBody);if(t.timestamp!==void 0){let d=Number(t.timestamp);if(!Number.isFinite(d))return {ok:false,reason:"timestamp_skew"};let g=t.tolerance??300;if(Math.abs(r-d)>g)return {ok:false,reason:"timestamp_skew"};let x=`${t.timestamp}:${t.signature}`;if(t.replayCache?.has(x))return {ok:false,reason:"replay"};s=Buffer.concat([Buffer.from(`${t.timestamp}.`),s]);}let i=createHmac("sha256",t.secret).update(s).digest();return e.byteLength!==i.byteLength?{ok:false,reason:"signature_mismatch"}:timingSafeEqual(e,i)?(t.timestamp!==void 0&&t.replayCache?.add(`${t.timestamp}:${t.signature}`),{ok:true}):{ok:false,reason:"signature_mismatch"}}n(Rr,"verifyWebhook");function a(t,e){return {...t,signal:e?.signal,timeoutMs:e?.timeoutMs,idempotencyKey:e?.idempotencyKey}}n(a,"withRequestOptions");function q(t){let e={};return t?.pageSize!==void 0&&(e.limit=t.pageSize),t?.cursor!==void 0&&(e.cursor=t.cursor),e}n(q,"pageQuery");function P(t,e){return {items:t.items.map(e),nextCursor:t.next_cursor,total:t.total}}n(P,"toPaginatedList");function f(t){let e={};for(let[r,s]of Object.entries(t))s!==void 0&&(e[r]=s);return e}n(f,"compactBody");function o(t){return encodeURIComponent(t)}n(o,"encodePath");function We(t){return {...t,id:String(t.id),slug:String(t.slug),name:String(t.name),createdAt:t.created_at??t.createdAt,updatedAt:t.updated_at??t.updatedAt}}n(We,"toTenant");function Er(t){return {id:String(t.id),role:String(t.role),...t,userId:t.user_id??t.userId}}n(Er,"toMember");function At(t){return {id:String(t.id),email:String(t.email),role:String(t.role),status:String(t.status),...t}}n(At,"toInvitation");function zt(t){return {...t,domain:String(t.domain??t.email_domain),verified:t.verified}}n(zt,"toEmailDomain");var D=class{constructor(e,r){this.http=e;this.mockStore=r;}http;mockStore;static{n(this,"TenantsAdminClient");}scoped(e){return new Ve(this.http,e)}async create(e,r){if(this.mockStore)return this.mockStore.createTenant(e);let s=await this.http.request("POST","/api/v1/tenants",a({ring:"admin",body:f(e),idempotent:false},r));return We(s)}async get(e,r){if(this.mockStore)return this.mockStore.getTenant(e);let s=await this.http.request("GET",`/api/v1/tenants/${o(e)}`,a({ring:"admin"},r));return We(s)}async list(e){if(this.mockStore)return this.mockStore.listTenants();let r=await this.http.request("GET","/api/v1/tenants",a({ring:"admin",query:q(e)},e));return P(r,We)}async update(e,r,s){if(this.mockStore)return this.mockStore.updateTenant(e,r);let i=await this.http.request("PATCH",`/api/v1/tenants/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s));return We(i)}async delete(e,r){if(this.mockStore)return this.mockStore.deleteTenant(e);await this.http.request("DELETE",`/api/v1/tenants/${o(e)}`,a({ring:"admin",idempotent:true},r));}async signIconUploadURL(e,r,s){let i=await this.http.request("POST",`/api/v1/tenants/${o(e)}/icon/upload-url`,a({ring:"admin",body:{content_type:r.contentType},idempotent:false},s));return {uploadUrl:i.upload_url??i.put_url??"",getUrl:i.get_url??i.public_url??"",expiresAt:i.expires_at}}get members(){return new Ye(this.http)}get invitations(){return new Je(this.http)}get emailDomains(){return new Xe(this.http)}},Ve=class{static{n(this,"TenantScopedTenantsAdminClient");}members;invitations;emailDomains;constructor(e,r){this.members=new Pe(e,r),this.invitations=new De(e,r),this.emailDomains=new Le(e,r);}},Ye=class{constructor(e){this.http=e;}http;static{n(this,"TenantMembersClient");}forTenant(e){return new Pe(this.http,e)}},Pe=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantMembersForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/members`,a({ring:"admin",query:q(e)},e));return P(r,Er)}async update(e,r,s){await this.http.request("PATCH",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s));}async deactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}/deactivate`,a({ring:"admin",body:{},idempotent:false},r));}async reactivate(e,r){await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/members/${o(e)}/reactivate`,a({ring:"admin",body:{},idempotent:false},r));}},Je=class{constructor(e){this.http=e;}http;static{n(this,"TenantInvitationsClient");}forTenant(e){return new De(this.http,e)}},De=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantInvitationsForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/invitations`,a({ring:"admin",query:q(e)},e));return P(r,At)}async create(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/invitations`,a({ring:"admin",body:f(e),idempotent:false},r));return At(s)}async bulkCreate(e,r){if(e.length>200)throw new p({message:"bulk invitations are capped at 200",code:"too_many_items",category:"validation",httpStatus:0,retryable:false,requestId:"",fields:[{name:"invitations",code:"max_200"}]});let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/invitations/bulk`,a({ring:"admin",body:{items:e},idempotent:false},r));return {accepted:(s.succeeded??[]).map(At),rejected:(s.failed??[]).map(i=>({email:i.email,reason:i.reason,message:i.message}))}}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${o(this.tenant)}/invitations/${o(e)}`,a({ring:"admin",idempotent:true},r));}},Xe=class{constructor(e){this.http=e;}http;static{n(this,"TenantEmailDomainsClient");}forTenant(e){return new Le(this.http,e)}},Le=class{constructor(e,r){this.http=e;this.tenant=r;}http;tenant;static{n(this,"TenantEmailDomainsForTenantClient");}async list(e){return (await this.http.request("GET",`/api/v1/tenants/${o(this.tenant)}/email-domains`,a({ring:"admin"},e))).items.map(zt)}async create(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenant)}/email-domains`,a({ring:"admin",body:{email_domain:e.domain},idempotent:false},r));return zt(s)}async delete(e,r){await this.http.request("DELETE",`/api/v1/tenants/${o(this.tenant)}/email-domains/${o(e)}`,a({ring:"admin",idempotent:true},r));}};var L=class{constructor(e){this.http=e;}http;static{n(this,"AuthzClient");}scoped(e){return new Qe(this.http,e)}},Qe=class{static{n(this,"TenantAuthzClient");}tags;subjects;grants;constructor(e,r){let s=`/api/v1/tenants/${o(r)}`;this.tags=new Ze(e,`${s}/tags`),this.subjects=new et(e,`${s}/subjects`),this.grants=new tt(e,`${s}/grants`);}},Ze=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzTagsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,a({ring:"admin",body:f(e),idempotent:false},r))}update(e,r,s){return this.http.request("PATCH",`${this.base}/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s))}delete(e,r){return this.http.request("DELETE",`${this.base}/${o(e)}`,a({ring:"admin",idempotent:true},r))}},et=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzSubjectsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}create(e,r){return this.http.request("POST",this.base,a({ring:"admin",body:f(e),idempotent:false},r))}update(e,r,s){return this.http.request("PATCH",`${this.base}/${o(e)}`,a({ring:"admin",body:f(r),idempotent:false},s))}delete(e,r){return this.http.request("DELETE",`${this.base}/${o(e)}`,a({ring:"admin",idempotent:true},r))}},tt=class{constructor(e,r){this.http=e;this.base=r;}http;base;static{n(this,"AuthzGrantsClient");}list(e){return this.http.request("GET",this.base,a({ring:"admin"},e))}};function Ue(t){return {id:String(t.id),...t,actorId:t.actor_id??t.actorId,prevHash:t.prev_hash??t.prevHash,createdAt:t.created_at??t.createdAt}}n(Ue,"toEvent");function _r(t){let e={ok:!!t.ok,checked:Number(t.checked??0)};return t.first_bad_seq!==void 0&&t.first_bad_seq!==null&&(e.firstBadSeq=Number(t.first_bad_seq)),t.reason!==void 0&&(e.reason=t.reason),e}n(_r,"toIntegrityCheck");var U=class{constructor(e){this.http=e;this.events=new nt(e),this.server=new st(e);}http;static{n(this,"AuditClient");}events;server;scoped(e){return new rt(this.http,e)}integrityCheck(e,r){return this.scoped(e).integrityCheck(r)}anonymize(e,r,s){return this.scoped(e).anonymize(r,s)}},rt=class{constructor(e,r){this.http=e;this.tenantSlug=r;this.events=new Be(e,r),this.server=new $e(e,r);}http;tenantSlug;static{n(this,"TenantAuditClient");}events;server;async integrityCheck(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/integrity-check`,a({ring:"admin"},e));return _r(r)}async anonymize(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/anonymize`,a({ring:"admin",body:{tenant_id:this.tenantSlug,actor_id:e.actorId??e.subjectId,anonymized_id:e.anonymizedId},idempotent:false},r));return s===void 0?void 0:Ue(s)}},nt=class{constructor(e){this.http=e;}http;static{n(this,"AuditEventsClient");}forTenant(e){return new Be(this.http,e)}},Be=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;static{n(this,"AuditEventsForTenantClient");}async list(e){let r=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events`,a({ring:"admin",query:{...q(e),...e?.type?{type:e.type}:{}}},e));return Array.isArray(r)?{items:r.map(Ue),nextCursor:null,total:r.length}:P({items:r.items??[],next_cursor:r.next_cursor??null,total:r.total??r.items?.length??0},Ue)}async get(e,r){let s=await this.http.request("GET",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/${o(e)}`,a({ring:"admin"},r));return Ue(s)}},st=class{constructor(e){this.http=e;}http;static{n(this,"AuditServerClient");}forTenant(e){return new $e(this.http,e)}},$e=class{constructor(e,r){this.http=e;this.tenantSlug=r;}http;tenantSlug;static{n(this,"AuditServerForTenantClient");}async emit(e,r){let s=await this.http.request("POST",`/api/v1/tenants/${o(this.tenantSlug)}/audit-events/server`,a({ring:"admin",body:{type:e.type,actor_id:e.actorId,resource:e.resource,payload:e.payload},idempotent:false},r));return Ue(s)}};var B=class{constructor(e){this.http=e;}http;static{n(this,"IdentityProviderClient");}list(e,r){return this.http.request("GET",`/api/v1/tenants/${o(e)}/identity-providers`,a({ring:"admin"},r))}create(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers`,a({ring:"admin",body:r,idempotent:false},s))}enable(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers/${o(r)}/enable`,a({ring:"admin",body:{},idempotent:false},s))}disable(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/identity-providers/${o(r)}/disable`,a({ring:"admin",body:{},idempotent:false},s))}};var $=class{constructor(e){this.http=e;}http;static{n(this,"CategoriesAdminClient");}create(e,r,s){return this.http.request("POST",`/api/v1/tenants/${o(e)}/categories`,a({ring:"admin",body:f(r),idempotent:false},s))}update(e,r,s,i){return this.http.request("PATCH",`/api/v1/tenants/${o(e)}/categories/${o(r)}`,a({ring:"admin",body:f(s),idempotent:false},i))}delete(e,r,s){return this.http.request("DELETE",`/api/v1/tenants/${o(e)}/categories/${o(r)}`,a({ring:"admin",idempotent:true},s))}};var Sr=new Set(["1","true","yes","on"]);function kr(t){return t?.trim().toLowerCase()==="production"}n(kr,"isProductionEnv");function wr(t){return t===void 0?false:Sr.has(t.trim().toLowerCase())}n(wr,"isTruthyOptIn");function Kt(){if(kr(process.env.NODE_ENV)){if(wr(process.env.AX_HUB_ALLOW_MOCK_IN_PROD)){console.warn("[@ax-hub/admin-sdk] WARNING: mock mode active in production (AX_HUB_ALLOW_MOCK_IN_PROD opt-in).");return}throw new be({message:"Mock mode active in production without explicit opt-in",code:"mock_in_production",category:"configuration",httpStatus:0,retryable:false,requestId:"",docUrl:"https://docs.axhub.dev/errors/mock-in-production"})}}n(Kt,"assertMockModeAllowed");function Rt(t){return new b({message:`Mock tenant not found: ${t}`,code:"tenant_not_found",category:"not_found",httpStatus:404,retryable:false,requestId:"",resource:`tenants/${t}`})}n(Rt,"tenantNotFound");var it=class{static{n(this,"AdminMockStore");}tenants=new Map;nextId=1;constructor(e){for(let r of e?.tenants??[]){let s=String(r.id);this.tenants.set(s,{...r,id:s});}}createTenant(e){let r=`tenant_${this.nextId++}`,s=new Date().toISOString(),i={id:r,slug:e.slug,name:e.name,...e.plan!==void 0?{plan:e.plan}:{},createdAt:s,updatedAt:s};return this.tenants.set(r,i),{...i}}getTenant(e){let r=this.tenants.get(e);if(!r)throw Rt(e);return {...r}}listTenants(){let e=[...this.tenants.values()].map(r=>({...r}));return {items:e,nextCursor:null,total:e.length}}updateTenant(e,r){let s=this.tenants.get(e);if(!s)throw Rt(e);let i={...s,...r,id:e,updatedAt:new Date().toISOString()};return this.tenants.set(e,i),{...i}}deleteTenant(e){if(!this.tenants.has(e))throw Rt(e);this.tenants.delete(e);}};function Nt(t){if(t.mode==="mock")return Kt(),new it(t.fixtures)}n(Nt,"createAdminMockStore");var Gt="https://api.axhub.ai";function Cr(t){return typeof t=="object"&&t!==null&&"__sharedHttp"in t}n(Cr,"isInternal");var Et=class{static{n(this,"AdminClient");}http;logger;mock;r;n;s;i;o;constructor(e){if(Cr(e)){this.http=e.__sharedHttp,this.logger=e.logger;return}if(e.token!==void 0&&e.tokenType===void 0)throw new TypeError('AdminClient requires tokenType when token is set ("pat" | "jwt")');let r=e.token!==void 0&&e.tokenType!==void 0?new Oe({token:e.token,tokenType:e.tokenType,onRefresh:e.onRefresh}):new qe;this.http=new Ge({baseUrl:e.baseUrl??Gt,auth:r,fetch:e.fetch,logger:e.logger,debug:e.debug,timeoutMs:e.timeoutMs,idempotencyKey:e.idempotencyKey,retryPolicy:e.retryPolicy,rateLimitStrategy:e.rateLimitStrategy}),this.logger=e.logger??Ne,this.mock=Nt(e);}get tenants(){return this.r||(this.r=new D(this.http,this.mock)),this.r}get authz(){return this.n||(this.n=new L(this.http)),this.n}get audit(){return this.s||(this.s=new U(this.http)),this.s}get identityProviders(){return this.i||(this.i=new B(this.http)),this.i}get categories(){return this.o||(this.o=new $(this.http)),this.o}tenant(e){return new ot(e,this.http)}},ot=class{constructor(e,r){this.tenant=e;this.http=r;}tenant;http;static{n(this,"TenantScopedAdminClient");}get tenants(){return new D(this.http).scoped(this.tenant)}get authz(){return new L(this.http).scoped(this.tenant)}get audit(){return new U(this.http).scoped(this.tenant)}get identityProviders(){return new B(this.http)}get categories(){return new $(this.http)}};
|
|
2
|
+
export{I as AbortError,C as AccessDeniedError,Et as AdminClient,ee as AlreadyAccessedError,Q as AlreadyActiveError,j as AlreadyDeletedError,Z as AlreadyInactiveError,H as AlreadyMemberError,J as AlreadyRevokedError,X as AlreadySettledError,ye as AppUnavailableError,U as AuditClient,nt as AuditEventsClient,Be as AuditEventsForTenantClient,st as AuditServerClient,$e as AuditServerForTenantClient,ve as AuthorizationPendingError,L as AuthzClient,tt as AuthzGrantsClient,et as AuthzSubjectsClient,Ze as AuthzTagsClient,u as AxHubError,le as BadRequestError,$ as CategoriesAdminClient,ze as ConfigurationError,c as ConflictError,Gt as DEFAULT_BASE_URL,S as DecodeError,mt as DeviceFlowDeniedError,ft as DeviceFlowTimeoutError,oe as DomainTakenError,ae as DuplicateError,ce as EmptyError,O as ExpiredTokenError,W as ForbiddenError,B as IdentityProviderClient,E as InternalServerError,gt as IntrospectFailedError,Ae as InvalidClientError,k as InvalidCursorError,xe as InvalidGrantError,dt as InvalidPathError,Re as InvalidRequestError,Ee as InvalidScopeError,se as InvalidStateTransitionError,Ie as InvalidTargetError,_e as InvalidTokenError,de as InvalidValueError,Y as InvitationExpiredError,re as LastAdminError,w as LegacyCursorError,be as MockInProductionError,me as NetworkError,qe as NoAuth,G as NotAdminError,ge as NotAllowedError,te as NotDeletedError,b as NotFoundError,pe as NotMemberError,l as OAuthError,we as OAuthServerError,ne as PendingExistsError,V as PermanentlyDeletedError,T as PermissionDeniedError,he as PoolStaleError,M as PreconditionFailedError,R as RateLimitedError,ue as RequiredError,yt as ScanLimitExceededError,ie as SchemaNameTakenError,Te as SlowDownError,F as SlugTakenError,Oe as StaticTokenAuth,je as StreamConsumedError,pt as TableNotFoundError,Ce as TemporarilyUnavailableError,rt as TenantAuditClient,Qe as TenantAuthzClient,Xe as TenantEmailDomainsClient,Le as TenantEmailDomainsForTenantClient,ct as TenantIdRequiredError,Je as TenantInvitationsClient,De as TenantInvitationsForTenantClient,Ye as TenantMembersClient,Pe as TenantMembersForTenantClient,ot as TenantScopedAdminClient,Ve as TenantScopedTenantsAdminClient,ut as TenantSlugRequiredError,D as TenantsAdminClient,fe as TimeoutError,K as TokenExpiredError,N as TokenInvalidError,z as TokenMissingError,v as UnauthenticatedError,Se as UnauthorizedClientError,_ as UnavailableError,ke as UnsupportedGrantTypeError,p as ValidationError,lt as WebhookVerificationError,er as asAppId,sr as asAppSlug,tr as asDeploymentId,ir as asPatId,ar as asRequestId,rr as asTenantId,nr as asTenantSlug,or as asUserId,xr as cursorFromRow,fr as decodeCursor,Ft as encodeCursor,St as formatErrorMessage,ur as id,br as orderByFingerprint,bt as parseRetryAfter,Ar as signWebhook,Rr as verifyWebhook};
|