quickbase-js 2.0.0-alpha.3 → 2.0.0-alpha.5
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/client/request.d.ts.map +1 -1
- package/dist/client/request.js +12 -3
- package/dist/client/request.js.map +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/config.js.map +1 -1
- package/dist/quickbase.esm.js +2 -2
- package/dist/quickbase.esm.js.map +3 -3
- package/dist/quickbase.min.js +2 -2
- package/dist/quickbase.min.js.map +3 -3
- package/package.json +1 -1
package/dist/quickbase.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* QuickBase JS SDK v2.0.0-alpha.
|
|
2
|
+
* QuickBase JS SDK v2.0.0-alpha.5
|
|
3
3
|
* https://github.com/DrewBradfordXYZ/quickbase-js#readme
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var QuickBase=(()=>{var q=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ae=(t,r,e)=>r in t?q(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e;var ie=(t,r)=>{for(var e in r)q(t,e,{get:r[e],enumerable:!0})},ue=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of ne(r))!se.call(t,n)&&n!==e&&q(t,n,{get:()=>r[n],enumerable:!(o=oe(r,n))||o.enumerable});return t};var pe=t=>ue(q({},"__esModule",{value:!0}),t);var i=(t,r,e)=>ae(t,typeof r!="symbol"?r+"":r,e);var be={};ie(be,{AuthenticationError:()=>R,AuthorizationError:()=>w,NoOpThrottle:()=>v,NotFoundError:()=>I,QuickbaseError:()=>h,RateLimitError:()=>f,ServerError:()=>k,SlidingWindowThrottle:()=>D,SsoTokenStrategy:()=>S,TempTokenStrategy:()=>E,TimeoutError:()=>T,UserTokenStrategy:()=>P,ValidationError:()=>C,createApiMethods:()=>j,createAuthStrategy:()=>L,createClient:()=>re,default:()=>Te});var l={baseUrl:"https://api.quickbase.com/v1",timeout:3e4,debug:!1,retry:{maxAttempts:3,initialDelayMs:1e3,maxDelayMs:3e4,multiplier:2},proactiveThrottle:{enabled:!1,requestsPer10Seconds:100},tempTokenLifespanMs:29e4,autoPaginate:!1,convertDates:!0};var h=class t extends Error{constructor(e,o,n){super(e,{cause:n?.cause});i(this,"statusCode");i(this,"description");i(this,"rayId");this.name="QuickbaseError",this.statusCode=o,this.description=n?.description,this.rayId=n?.rayId,Error.captureStackTrace&&Error.captureStackTrace(this,t)}toJSON(){return{name:this.name,message:this.message,statusCode:this.statusCode,description:this.description,rayId:this.rayId}}},f=class extends h{constructor(e,o){super(o||`Rate limited. Retry after ${e.retryAfter??"unknown"} seconds`,429,{rayId:e.qbApiRay||e.cfRay});i(this,"retryAfter");i(this,"rateLimitInfo");this.name="RateLimitError",this.retryAfter=e.retryAfter,this.rateLimitInfo=e}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter,rateLimitInfo:this.rateLimitInfo}}},R=class extends h{constructor(r,e){super(r,401,e),this.name="AuthenticationError"}},w=class extends h{constructor(r,e){super(r,403,e),this.name="AuthorizationError"}},I=class extends h{constructor(r,e){super(r,404,e),this.name="NotFoundError"}},C=class extends h{constructor(e,o){super(e,400,o);i(this,"errors");this.name="ValidationError",this.errors=o?.errors}toJSON(){return{...super.toJSON(),errors:this.errors}}},T=class extends h{constructor(e,o){super(`Request timed out after ${e}ms`,0,o);i(this,"timeoutMs");this.name="TimeoutError",this.timeoutMs=e}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}},k=class extends h{constructor(r,e,o){super(e,r,o),this.name="ServerError"}};async function Q(t,r){let e=t.headers.get("qb-api-ray")||t.headers.get("cf-ray")||void 0,o=null;try{o=await t.json()}catch{}let n=o?.message||t.statusText||"Unknown error",a=o?.description;switch(t.status){case 400:return new C(n,{description:a,rayId:e,errors:o?.errors});case 401:return new R(n,{rayId:e});case 403:return new w(n,{rayId:e});case 404:return new I(n,{rayId:e});case 429:{let s=t.headers.get("Retry-After"),u={timestamp:new Date,requestUrl:r,httpStatus:429,retryAfter:s?parseInt(s,10):void 0,cfRay:t.headers.get("cf-ray")||void 0,tid:t.headers.get("tid")||void 0,qbApiRay:t.headers.get("qb-api-ray")||void 0,attempt:1};return new f(u,n)}default:return t.status>=500?new k(t.status,n,{description:a,rayId:e}):new h(n,t.status,{description:a,rayId:e})}}function F(t){return t instanceof f||t instanceof k||t instanceof T}var M=class{constructor(r=!1,e="quickbase-js"){i(this,"enabled");i(this,"prefix");this.enabled=r,this.prefix=e}formatMessage(r,e){return`[${new Date().toISOString()}] [${this.prefix}] [${r}] ${e}`}debug(r,e){this.enabled&&(e!==void 0?console.log(this.formatMessage("DEBUG",r),e):console.log(this.formatMessage("DEBUG",r)))}info(r,e){this.enabled&&(e!==void 0?console.info(this.formatMessage("INFO",r),e):console.info(this.formatMessage("INFO",r)))}warn(r,e){e!==void 0?console.warn(this.formatMessage("WARN",r),e):console.warn(this.formatMessage("WARN",r))}error(r,e){e!==void 0?console.error(this.formatMessage("ERROR",r),e):console.error(this.formatMessage("ERROR",r))}rateLimit(r){this.enabled&&this.debug(`Rate limited (attempt ${r.attempt}): ${r.url} - Status ${r.status}, Retry-After: ${r.retryAfter??"not specified"}s`+(r.rayId?`, Ray: ${r.rayId}`:""))}timing(r,e,o){this.enabled&&this.debug(`${r} ${e} completed in ${o}ms`)}retry(r,e,o,n){this.enabled&&this.debug(`Retry ${r}/${e} in ${o}ms: ${n}`)}token(r,e){if(this.enabled){let o=e?` for dbid: ${e}`:"";this.debug(`Token ${r}${o}`)}}};function N(t){return new M(t)}function _(t){de(t);let r={maxAttempts:t.rateLimit?.retry?.maxAttempts??l.retry.maxAttempts,initialDelayMs:t.rateLimit?.retry?.initialDelayMs??l.retry.initialDelayMs,maxDelayMs:t.rateLimit?.retry?.maxDelayMs??l.retry.maxDelayMs,multiplier:t.rateLimit?.retry?.multiplier??l.retry.multiplier},e={enabled:t.rateLimit?.proactiveThrottle?.enabled??l.proactiveThrottle.enabled,requestsPer10Seconds:t.rateLimit?.proactiveThrottle?.requestsPer10Seconds??l.proactiveThrottle.requestsPer10Seconds};return{realm:t.realm,baseUrl:t.baseUrl??l.baseUrl,timeout:t.timeout??l.timeout,debug:t.debug??l.debug,fetchApi:t.fetchApi??globalThis.fetch,auth:t.auth,retry:r,proactiveThrottle:e,onRateLimit:t.rateLimit?.onRateLimit,autoPaginate:t.autoPaginate??l.autoPaginate,convertDates:t.convertDates??l.convertDates}}function de(t){if(!t.realm)throw new Error("QuickBase realm is required");if(typeof t.realm!="string")throw new Error("QuickBase realm must be a string");if(t.realm.includes("."))throw new Error('Realm should be just the subdomain (e.g., "mycompany" not "mycompany.quickbase.com")');if(!t.auth)throw new Error("Authentication configuration is required");if(le(t.auth),t.timeout!==void 0&&(typeof t.timeout!="number"||t.timeout<=0))throw new Error("Timeout must be a positive number");t.rateLimit?.retry&&me(t.rateLimit.retry),t.rateLimit?.proactiveThrottle&&ce(t.rateLimit.proactiveThrottle)}function le(t){switch(t.type){case"user-token":if(!t.userToken)throw new Error("User token is required for user-token auth");break;case"temp-token":break;case"sso":if(!t.samlToken)throw new Error("SAML token is required for SSO auth");break;default:throw new Error(`Unknown auth type: ${t.type}`)}}function me(t){if(t.maxAttempts!==void 0&&(typeof t.maxAttempts!="number"||t.maxAttempts<0))throw new Error("maxAttempts must be a non-negative number");if(t.initialDelayMs!==void 0&&(typeof t.initialDelayMs!="number"||t.initialDelayMs<0))throw new Error("initialDelayMs must be a non-negative number");if(t.maxDelayMs!==void 0&&(typeof t.maxDelayMs!="number"||t.maxDelayMs<0))throw new Error("maxDelayMs must be a non-negative number");if(t.multiplier!==void 0&&(typeof t.multiplier!="number"||t.multiplier<1))throw new Error("multiplier must be a number >= 1")}function ce(t){if(t.requestsPer10Seconds!==void 0&&(typeof t.requestsPer10Seconds!="number"||t.requestsPer10Seconds<=0))throw new Error("requestsPer10Seconds must be a positive number")}function B(t){return`${t}.quickbase.com`}var he=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})?)?$/;function J(t){return he.test(t)}function G(t,r){if(!r||t===null||t===void 0||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>G(o,r));if(t instanceof Date)return t;let e={};for(let[o,n]of Object.entries(t))typeof n=="string"&&J(n)?e[o]=new Date(n):n instanceof Date?e[o]=n:typeof n=="object"&&n!==null?e[o]=G(n,r):e[o]=n;return e}var P=class{constructor(r,e){i(this,"userToken");i(this,"logger");this.userToken=r,this.logger=e.logger}async getToken(r){return this.userToken}getAuthorizationHeader(r){return`QB-USER-TOKEN ${r}`}async handleAuthError(r){return this.logger.debug("Auth error with user token - cannot refresh"),!1}invalidate(r){}};var A=class{constructor(r){i(this,"cache",new Map);i(this,"defaultLifespanMs");this.defaultLifespanMs=r}get(r){let e=this.cache.get(r);return e?Date.now()>=e.expiresAt-1e4?(this.cache.delete(r),null):e.token:null}set(r,e,o){let n=Date.now()+(o??this.defaultLifespanMs);this.cache.set(r,{token:e,expiresAt:n})}delete(r){return this.cache.delete(r)}clear(){this.cache.clear()}has(r){return this.get(r)!==null}getTimeToExpiry(r){let e=this.cache.get(r);if(!e)return null;let o=e.expiresAt-Date.now();return o>0?o:null}get size(){return this.cleanup(),this.cache.size}cleanup(){let r=Date.now();for(let[e,o]of this.cache)r>=o.expiresAt&&this.cache.delete(e)}};var E=class{constructor(r,e,o){i(this,"userToken");i(this,"appToken");i(this,"realm");i(this,"baseUrl");i(this,"fetchApi");i(this,"logger");i(this,"cache");i(this,"pendingFetches",new Map);this.userToken=r,this.appToken=o?.appToken,this.realm=e.realm,this.baseUrl=e.baseUrl,this.fetchApi=e.fetchApi,this.logger=e.logger,this.cache=new A(o?.tokenLifespanMs??l.tempTokenLifespanMs)}async getToken(r){if(!r)throw new Error("Database ID (dbid) is required for temporary token authentication");let e=this.cache.get(r);if(e)return this.logger.token("cache-hit",r),e;this.logger.token("cache-miss",r);let o=this.pendingFetches.get(r);if(o)return this.logger.debug(`Waiting for existing token fetch for dbid: ${r}`),o;let n=this.fetchToken(r);this.pendingFetches.set(r,n);try{return await n}finally{this.pendingFetches.delete(r)}}async fetchToken(r){this.logger.token("fetch",r);let e=`${this.baseUrl}/auth/temporary/${r}`,o={"QB-Realm-Hostname":`${this.realm}.quickbase.com`,Authorization:`QB-USER-TOKEN ${this.userToken}`,"Content-Type":"application/json"};this.appToken&&(o["QB-App-Token"]=this.appToken);let n=await this.fetchApi(e,{method:"GET",headers:o});if(!n.ok){let u=await n.text();throw new R(`Failed to fetch temporary token for ${r}: ${n.status} ${u}`,{rayId:n.headers.get("qb-api-ray")||void 0})}let s=(await n.json()).temporaryAuthorization;if(!s)throw new R(`No temporary token in response for ${r}`);return this.cache.set(r,s),this.logger.debug(`Cached new token for dbid: ${r}`),s}getAuthorizationHeader(r){return`QB-TEMP-TOKEN ${r}`}async handleAuthError(r){if(!r)return this.logger.debug("Auth error without dbid - cannot refresh temp token"),!1;this.invalidate(r);try{return this.logger.token("refresh",r),await this.getToken(r),!0}catch(e){return this.logger.error(`Failed to refresh temp token for ${r}`,e),!1}}invalidate(r){r?(this.logger.token("expire",r),this.cache.delete(r)):this.cache.clear()}};var S=class{constructor(r,e,o){i(this,"samlToken");i(this,"realm");i(this,"baseUrl");i(this,"fetchApi");i(this,"logger");i(this,"cache");i(this,"pendingExchange",null);this.samlToken=r,this.realm=e.realm,this.baseUrl=e.baseUrl,this.fetchApi=e.fetchApi,this.logger=e.logger,this.cache=new A(o?.tokenLifespanMs??l.tempTokenLifespanMs)}get cacheKey(){return"__sso__"}async getToken(r){let e=this.cache.get(this.cacheKey);if(e)return this.logger.token("cache-hit"),e;if(this.logger.token("cache-miss"),this.pendingExchange)return this.logger.debug("Waiting for existing SSO token exchange"),this.pendingExchange;let o=this.exchangeToken();this.pendingExchange=o;try{return await o}finally{this.pendingExchange=null}}async exchangeToken(){this.logger.token("fetch");let r=`${this.baseUrl}/auth/oauth/token`,e=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",requested_token_type:"urn:quickbase:params:oauth:token-type:temp_token",subject_token:this.samlToken,subject_token_type:"urn:ietf:params:oauth:token-type:saml2"}),o=await this.fetchApi(r,{method:"POST",headers:{"QB-Realm-Hostname":`${this.realm}.quickbase.com`,"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!o.ok){let s=await o.text();throw new R(`SSO token exchange failed: ${o.status} ${s}`,{rayId:o.headers.get("qb-api-ray")||void 0})}let a=(await o.json()).access_token;if(!a)throw new R("No access_token in SSO exchange response");return this.cache.set(this.cacheKey,a),this.logger.debug("Cached new SSO token"),a}getAuthorizationHeader(r){return`QB-TEMP-TOKEN ${r}`}async handleAuthError(r){this.invalidate();try{return this.logger.token("refresh"),await this.getToken(),!0}catch(e){return this.logger.error("Failed to refresh SSO token",e),!1}}invalidate(r){this.logger.token("expire"),this.cache.clear()}};function L(t,r){switch(t.type){case"user-token":return new P(t.userToken,r);case"temp-token":return new E(t.userToken,r,{appToken:t.appToken,tokenLifespanMs:t.tokenLifespanMs});case"sso":return new S(t.samlToken,r);default:throw new Error(`Unknown auth type: ${t.type}`)}}function z(t,r,e){let o=t.headers.get("Retry-After");return{timestamp:new Date,requestUrl:r,httpStatus:t.status,retryAfter:o?parseInt(o,10):void 0,cfRay:t.headers.get("cf-ray")||void 0,tid:t.headers.get("tid")||void 0,qbApiRay:t.headers.get("qb-api-ray")||void 0,attempt:e}}function H(t){return new Promise(r=>setTimeout(r,t))}function ge(t){if(t.dbid)return t.dbid;if(t.query?.tableId)return String(t.query.tableId);let r=t.path.match(/\/tables\/([^/?]+)/);if(r)return r[1];if(t.body&&typeof t.body=="object"){let e=t.body;if(typeof e.from=="string")return e.from;if(typeof e.to=="string")return e.to}}function V(t,r,e){let o=t.endsWith("/")?t:`${t}/`,n=r.startsWith("/")?r.slice(1):r,a=new URL(n,o);if(e)for(let[s,u]of Object.entries(e))u!==void 0&&a.searchParams.set(s,String(u));return a.toString()}async function Re(t,r,e,o){let n=await t.getToken(e),a=t.getAuthorizationHeader(n);return{"Content-Type":"application/json","QB-Realm-Hostname":r,Authorization:a,...o}}async function fe(t,r,e){let{config:o,auth:n,throttle:a,logger:s}=r,u=V(o.baseUrl,t.path,t.query),m=B(o.realm),d=await Re(n,m,e.dbid,t.headers);await a.acquire();let p={method:t.method,headers:d};t.body!==void 0&&(p.body=JSON.stringify(t.body));let c=new AbortController,g=setTimeout(()=>c.abort(),o.timeout);p.signal=c.signal;let b=Date.now();try{let y=await o.fetchApi(u,p),U=Date.now()-b;return s.timing(t.method,t.path,U),y}catch(y){throw y instanceof Error&&y.name==="AbortError"?new T(o.timeout):y}finally{clearTimeout(g)}}async function ye(t,r,e,o){let{config:n,logger:a}=o;if(t.ok)return t;if(t.status===429){let s=z(t,r,e.attempt);throw a.rateLimit({url:r,status:429,retryAfter:s.retryAfter,attempt:e.attempt,rayId:s.qbApiRay||s.cfRay}),n.onRateLimit&&n.onRateLimit(s),new f(s)}throw await Q(t,r)}async function Z(t,r){let{config:e,auth:o,logger:n}=r,a=e.retry.maxAttempts,s=ge(t),u={methodName:`${t.method} ${t.path}`,attempt:1,maxAttempts:a,dbid:s,startTime:Date.now()},m=null;for(let d=1;d<=a;d++){u.attempt=d;try{let p=await fe(t,r,u),c=V(e.baseUrl,t.path,t.query);await ye(p,c,u,r);let g=await p.json();return G(g,e.convertDates)}catch(p){if(m=p,!F(p)||d>=a)throw p;if(p instanceof h&&p.statusCode===401){if(!await o.handleAuthError(s))throw p;n.debug("Token refreshed, retrying request");continue}let c,g;p instanceof f?(c=p.retryAfter?p.retryAfter*1e3:$(d,e.retry),g="Rate limited (429)"):p instanceof T?(c=$(d,e.retry),g="Timeout"):p instanceof h&&p.statusCode>=500?(c=$(d,e.retry),g=`Server error (${p.statusCode})`):(c=$(d,e.retry),g="Retryable error"),n.retry(d,a,c,g),await H(c)}}throw m||new Error("Request failed")}function $(t,r){let e=r.initialDelayMs*Math.pow(r.multiplier,t-1),o=e*.1*(Math.random()*2-1);return Math.min(e+o,r.maxDelayMs)}function W(t){return{execute:r=>Z(r,t)}}var D=class{constructor(r=100){i(this,"requestsPer10Seconds");i(this,"timestamps",[]);this.requestsPer10Seconds=r}async acquire(){let r=Date.now(),e=r-1e4;for(;this.timestamps.length>0&&this.timestamps[0]<e;)this.timestamps.shift();if(this.timestamps.length>=this.requestsPer10Seconds){let n=this.timestamps[0]+1e4-r;if(n>0)return await this.sleep(n),this.acquire()}this.timestamps.push(Date.now())}getWindowCount(){let r=Date.now()-1e4;return this.timestamps.filter(e=>e>=r).length}getRemaining(){return Math.max(0,this.requestsPer10Seconds-this.getWindowCount())}reset(){this.timestamps.length=0}sleep(r){return new Promise(e=>setTimeout(e,r))}},v=class{async acquire(){}getWindowCount(){return 0}getRemaining(){return 1/0}reset(){}};function K(t){return t.enabled?new D(t.requestsPer10Seconds):new v}function X(t){return t.totalRecords!==void 0&&t.skip!==void 0?"skip":t.nextPageToken!==void 0||t.nextToken!==void 0?"token":"none"}function Y(t,r,e){let{metadata:o}=t;if(r==="skip")return o.totalRecords!==void 0&&e<o.totalRecords;if(r==="token"){let n=o.nextPageToken??o.nextToken;return n!==void 0&&n!==""}return!1}function ee(t){for(let r of Object.keys(t))if(Array.isArray(t[r]))return r;return"data"}function te(t){if(!t||typeof t!="object")return!1;let r=t;if(!r.metadata||typeof r.metadata!="object"||!Object.values(r).some(Array.isArray))return!1;let o=r.metadata;return o.totalRecords!==void 0||o.numRecords!==void 0||o.nextPageToken!==void 0||o.nextToken!==void 0}var O=class{constructor(r,e){i(this,"executor");i(this,"paginatedExecutor");i(this,"defaultAutoPaginate");this.executor=r,this.paginatedExecutor=e?.paginatedExecutor,this.defaultAutoPaginate=e?.autoPaginate??!1}then(r,e){return(this.defaultAutoPaginate?this.all():this.executor()).then(r,e)}async all(){return this.paginate({})}async paginate(r={}){if(!this.paginatedExecutor)return this.executor();let{limit:e,skip:o=0}=r,n=[],a=null,s="none",u=o,m,d=await this.paginatedExecutor({skip:o});if(!te(d))return d;a=d,s=X(d.metadata);let p=ee(d),c=d[p]||[];for(e!==void 0&&c.length>e?n=c.slice(0,e):n=[...c],s==="skip"?u=o+c.length:s==="token"&&(m=d.metadata.nextPageToken??d.metadata.nextToken);Y(a,s,n.length)&&!(e!==void 0&&n.length>=e);){let b;if(s==="skip")b=await this.paginatedExecutor({skip:u});else if(s==="token"&&m){let U=a.metadata.nextPageToken!==void 0?"nextPageToken":"nextToken";b=await this.paginatedExecutor({[U]:m})}else break;a=b;let y=b[p]||[];if(y.length===0)break;if(e!==void 0){let U=e-n.length;n=n.concat(y.slice(0,U))}else n=n.concat(y);if(s==="skip")u+=y.length;else if(s==="token"&&(m=b.metadata.nextPageToken??b.metadata.nextToken,!m))break}let g={...a,[p]:n,metadata:{...a.metadata,numRecords:n.length,skip:o}};return s==="token"&&(delete g.metadata.nextPageToken,delete g.metadata.nextToken),g}async noPaginate(){return this.executor()}toPromise(){return this.then()}};function x(t,r){return new O(t,r)}function j(t,r=!1){return{createApp(e){return t({method:"POST",path:"/apps",body:e})},getApp(e){return t({method:"GET",path:`/apps/${e.appId}`})},updateApp(e,o){return t({method:"POST",path:`/apps/${e.appId}`,body:o})},deleteApp(e,o){return t({method:"DELETE",path:`/apps/${e.appId}`,body:o})},getAppEvents(e){return t({method:"GET",path:`/apps/${e.appId}/events`})},copyApp(e,o){return t({method:"POST",path:`/apps/${e.appId}/copy`,body:o})},getAppTables(e){return t({method:"GET",path:"/tables",query:{appId:e.appId}})},createTable(e,o){return t({method:"POST",path:"/tables",query:{appId:e.appId},body:o})},getTable(e){return t({method:"GET",path:`/tables/${e.tableId}`,query:{appId:e.appId}})},updateTable(e,o){return t({method:"POST",path:`/tables/${e.tableId}`,query:{appId:e.appId},body:o})},deleteTable(e){return t({method:"DELETE",path:`/tables/${e.tableId}`,query:{appId:e.appId}})},getRelationships(e){return x(()=>t({method:"GET",path:`/tables/${e.tableId}/relationships`,query:{skip:e.skip}}),{paginatedExecutor:a=>t({method:"GET",path:`/tables/${e.tableId}/relationships`,query:{skip:e.skip,...a}}),autoPaginate:r})},createRelationship(e,o){return t({method:"POST",path:`/tables/${e.tableId}/relationship`,body:o})},updateRelationship(e,o){return t({method:"POST",path:`/tables/${e.tableId}/relationship/${e.relationshipId}`,body:o})},deleteRelationship(e){return t({method:"DELETE",path:`/tables/${e.tableId}/relationship/${e.relationshipId}`})},getTableReports(e){return t({method:"GET",path:"/reports",query:{tableId:e.tableId}})},getReport(e){return t({method:"GET",path:`/reports/${e.reportId}`,query:{tableId:e.tableId}})},runReport(e,o){return x(()=>t({method:"POST",path:`/reports/${e.reportId}/run`,query:{tableId:e.tableId,skip:e.skip,top:e.top},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:`/reports/${e.reportId}/run`,query:{tableId:e.tableId,skip:e.skip,top:e.top},body:m})},autoPaginate:r})},getFields(e){return t({method:"GET",path:"/fields",query:{tableId:e.tableId,includeFieldPerms:e.includeFieldPerms}})},createField(e,o){return t({method:"POST",path:"/fields",query:{tableId:e.tableId},body:o})},deleteFields(e,o){return t({method:"DELETE",path:"/fields",query:{tableId:e.tableId},body:o})},getField(e){return t({method:"GET",path:`/fields/${e.fieldId}`,query:{tableId:e.tableId,includeFieldPerms:e.includeFieldPerms}})},updateField(e,o){return t({method:"POST",path:`/fields/${e.fieldId}`,query:{tableId:e.tableId},body:o})},getFieldsUsage(e){return t({method:"GET",path:"/fields/usage",query:{tableId:e.tableId,skip:e.skip,top:e.top}})},getFieldUsage(e){return t({method:"GET",path:`/fields/usage/${e.fieldId}`,query:{tableId:e.tableId}})},runFormula(e){return t({method:"POST",path:"/formula/run",body:e})},upsert(e){return x(()=>t({method:"POST",path:"/records",body:e}),{paginatedExecutor:a=>{let s=e,u=a.skip!==void 0||a.nextPageToken||a.nextToken?{...s||{},options:{...s?.options||{},...a.skip!==void 0?{skip:a.skip}:{}},...a.nextPageToken?{nextPageToken:a.nextPageToken}:{},...a.nextToken?{nextToken:a.nextToken}:{}}:e;return t({method:"POST",path:"/records",body:u})},autoPaginate:r})},deleteRecords(e){return t({method:"DELETE",path:"/records",body:e})},runQuery(e){return x(()=>t({method:"POST",path:"/records/query",body:e}),{paginatedExecutor:a=>{let s=e,u=a.skip!==void 0||a.nextPageToken||a.nextToken?{...s||{},options:{...s?.options||{},...a.skip!==void 0?{skip:a.skip}:{}},...a.nextPageToken?{nextPageToken:a.nextPageToken}:{},...a.nextToken?{nextToken:a.nextToken}:{}}:e;return t({method:"POST",path:"/records/query",body:u})},autoPaginate:r})},getTempTokenDBID(e){return t({method:"GET",path:`/auth/temporary/${e.dbid}`})},exchangeSsoToken(e){return t({method:"POST",path:"/auth/oauth/token",body:e})},cloneUserToken(e){return t({method:"POST",path:"/usertoken/clone",body:e})},transferUserToken(e){return t({method:"POST",path:"/usertoken/transfer",body:e})},deactivateUserToken(){return t({method:"POST",path:"/usertoken/deactivate"})},deleteUserToken(){return t({method:"DELETE",path:"/usertoken"})},downloadFile(e){return t({method:"GET",path:`/files/${e.tableId}/${e.recordId}/${e.fieldId}/${e.versionNumber}`})},deleteFile(e){return t({method:"DELETE",path:`/files/${e.tableId}/${e.recordId}/${e.fieldId}/${e.versionNumber}`})},getUsers(e,o){return x(()=>t({method:"POST",path:"/users",query:{accountId:e.accountId},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:"/users",query:{accountId:e.accountId},body:m})},autoPaginate:r})},denyUsers(e,o){return t({method:"PUT",path:"/users/deny",query:{accountId:e.accountId},body:o})},denyUsersAndGroups(e,o){return t({method:"PUT",path:`/users/deny/${e.shouldDeleteFromGroups}`,query:{accountId:e.accountId},body:o})},undenyUsers(e,o){return t({method:"PUT",path:"/users/undeny",query:{accountId:e.accountId},body:o})},addMembersToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/members`,body:o})},removeMembersFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/members`,body:o})},addManagersToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/managers`,body:o})},removeManagersFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/managers`,body:o})},addSubgroupsToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/subgroups`,body:o})},removeSubgroupsFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/subgroups`,body:o})},audit(e){return t({method:"POST",path:"/audit",body:e})},platformAnalyticReads(e){return t({method:"GET",path:"/analytics/reads",query:{day:e.day}})},platformAnalyticEventSummaries(e,o){return x(()=>t({method:"POST",path:"/analytics/events/summaries",query:{accountId:e.accountId},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:"/analytics/events/summaries",query:{accountId:e.accountId},body:m})},autoPaginate:r})},exportSolution(e){return t({method:"GET",path:`/solutions/${e.solutionId}`})},updateSolution(e,o){return t({method:"PUT",path:`/solutions/${e.solutionId}`,body:o})},createSolution(e){return t({method:"POST",path:"/solutions",body:e})},exportSolutionToRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/torecord`,query:{tableId:e.tableId,fieldId:e.fieldId}})},createSolutionFromRecord(e){return t({method:"GET",path:"/solutions/fromrecord",query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},updateSolutionToRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/fromrecord`,query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},changesetSolution(e,o){return t({method:"PUT",path:`/solutions/${e.solutionId}/changeset`,body:o})},changesetSolutionFromRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/changeset/fromrecord`,query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},generateDocument(e){return t({method:"GET",path:`/docTemplates/${e.templateId}/generate`,query:{tableId:e.tableId,recordId:e.recordId,filename:e.filename,format:e.format,margin:e.margin,unit:e.unit,pageSize:e.pageSize,orientation:e.orientation,realm:e.realm}})}}}function re(t){let r=_(t),e=N(r.debug),o={realm:r.realm,baseUrl:r.baseUrl,fetchApi:r.fetchApi,logger:e},n=L(r.auth,o),a=K(r.proactiveThrottle),s=W({config:r,auth:n,throttle:a,logger:e});return{...j(s.execute,r.autoPaginate),request:s.execute,getConfig:()=>r}}var Te=re;return pe(be);})();
|
|
6
|
+
"use strict";var QuickBase=(()=>{var q=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var ae=(t,r,e)=>r in t?q(t,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[r]=e;var ie=(t,r)=>{for(var e in r)q(t,e,{get:r[e],enumerable:!0})},ue=(t,r,e,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of ne(r))!se.call(t,n)&&n!==e&&q(t,n,{get:()=>r[n],enumerable:!(o=oe(r,n))||o.enumerable});return t};var pe=t=>ue(q({},"__esModule",{value:!0}),t);var i=(t,r,e)=>ae(t,typeof r!="symbol"?r+"":r,e);var be={};ie(be,{AuthenticationError:()=>R,AuthorizationError:()=>w,NoOpThrottle:()=>v,NotFoundError:()=>I,QuickbaseError:()=>h,RateLimitError:()=>f,ServerError:()=>k,SlidingWindowThrottle:()=>D,SsoTokenStrategy:()=>S,TempTokenStrategy:()=>E,TimeoutError:()=>T,UserTokenStrategy:()=>P,ValidationError:()=>C,createApiMethods:()=>j,createAuthStrategy:()=>L,createClient:()=>re,default:()=>Te});var l={baseUrl:"https://api.quickbase.com/v1",timeout:3e4,debug:!1,retry:{maxAttempts:3,initialDelayMs:1e3,maxDelayMs:3e4,multiplier:2},proactiveThrottle:{enabled:!1,requestsPer10Seconds:100},tempTokenLifespanMs:29e4,autoPaginate:!1,convertDates:!0};var h=class t extends Error{constructor(e,o,n){super(e,{cause:n?.cause});i(this,"statusCode");i(this,"description");i(this,"rayId");this.name="QuickbaseError",this.statusCode=o,this.description=n?.description,this.rayId=n?.rayId,Error.captureStackTrace&&Error.captureStackTrace(this,t)}toJSON(){return{name:this.name,message:this.message,statusCode:this.statusCode,description:this.description,rayId:this.rayId}}},f=class extends h{constructor(e,o){super(o||`Rate limited. Retry after ${e.retryAfter??"unknown"} seconds`,429,{rayId:e.qbApiRay||e.cfRay});i(this,"retryAfter");i(this,"rateLimitInfo");this.name="RateLimitError",this.retryAfter=e.retryAfter,this.rateLimitInfo=e}toJSON(){return{...super.toJSON(),retryAfter:this.retryAfter,rateLimitInfo:this.rateLimitInfo}}},R=class extends h{constructor(r,e){super(r,401,e),this.name="AuthenticationError"}},w=class extends h{constructor(r,e){super(r,403,e),this.name="AuthorizationError"}},I=class extends h{constructor(r,e){super(r,404,e),this.name="NotFoundError"}},C=class extends h{constructor(e,o){super(e,400,o);i(this,"errors");this.name="ValidationError",this.errors=o?.errors}toJSON(){return{...super.toJSON(),errors:this.errors}}},T=class extends h{constructor(e,o){super(`Request timed out after ${e}ms`,0,o);i(this,"timeoutMs");this.name="TimeoutError",this.timeoutMs=e}toJSON(){return{...super.toJSON(),timeoutMs:this.timeoutMs}}},k=class extends h{constructor(r,e,o){super(e,r,o),this.name="ServerError"}};async function Q(t,r){let e=t.headers.get("qb-api-ray")||t.headers.get("cf-ray")||void 0,o=null;try{o=await t.json()}catch{}let n=o?.message||t.statusText||"Unknown error",a=o?.description;switch(t.status){case 400:return new C(n,{description:a,rayId:e,errors:o?.errors});case 401:return new R(n,{rayId:e});case 403:return new w(n,{rayId:e});case 404:return new I(n,{rayId:e});case 429:{let s=t.headers.get("Retry-After"),u={timestamp:new Date,requestUrl:r,httpStatus:429,retryAfter:s?parseInt(s,10):void 0,cfRay:t.headers.get("cf-ray")||void 0,tid:t.headers.get("tid")||void 0,qbApiRay:t.headers.get("qb-api-ray")||void 0,attempt:1};return new f(u,n)}default:return t.status>=500?new k(t.status,n,{description:a,rayId:e}):new h(n,t.status,{description:a,rayId:e})}}function F(t){return t instanceof f||t instanceof k||t instanceof T}var M=class{constructor(r=!1,e="quickbase-js"){i(this,"enabled");i(this,"prefix");this.enabled=r,this.prefix=e}formatMessage(r,e){return`[${new Date().toISOString()}] [${this.prefix}] [${r}] ${e}`}debug(r,e){this.enabled&&(e!==void 0?console.log(this.formatMessage("DEBUG",r),e):console.log(this.formatMessage("DEBUG",r)))}info(r,e){this.enabled&&(e!==void 0?console.info(this.formatMessage("INFO",r),e):console.info(this.formatMessage("INFO",r)))}warn(r,e){e!==void 0?console.warn(this.formatMessage("WARN",r),e):console.warn(this.formatMessage("WARN",r))}error(r,e){e!==void 0?console.error(this.formatMessage("ERROR",r),e):console.error(this.formatMessage("ERROR",r))}rateLimit(r){this.enabled&&this.debug(`Rate limited (attempt ${r.attempt}): ${r.url} - Status ${r.status}, Retry-After: ${r.retryAfter??"not specified"}s`+(r.rayId?`, Ray: ${r.rayId}`:""))}timing(r,e,o){this.enabled&&this.debug(`${r} ${e} completed in ${o}ms`)}retry(r,e,o,n){this.enabled&&this.debug(`Retry ${r}/${e} in ${o}ms: ${n}`)}token(r,e){if(this.enabled){let o=e?` for dbid: ${e}`:"";this.debug(`Token ${r}${o}`)}}};function N(t){return new M(t)}function _(t){de(t);let r={maxAttempts:t.rateLimit?.retry?.maxAttempts??l.retry.maxAttempts,initialDelayMs:t.rateLimit?.retry?.initialDelayMs??l.retry.initialDelayMs,maxDelayMs:t.rateLimit?.retry?.maxDelayMs??l.retry.maxDelayMs,multiplier:t.rateLimit?.retry?.multiplier??l.retry.multiplier},e={enabled:t.rateLimit?.proactiveThrottle?.enabled??l.proactiveThrottle.enabled,requestsPer10Seconds:t.rateLimit?.proactiveThrottle?.requestsPer10Seconds??l.proactiveThrottle.requestsPer10Seconds};return{realm:t.realm,baseUrl:t.baseUrl??l.baseUrl,timeout:t.timeout??l.timeout,debug:t.debug??l.debug,fetchApi:t.fetchApi??globalThis.fetch.bind(globalThis),auth:t.auth,retry:r,proactiveThrottle:e,onRateLimit:t.rateLimit?.onRateLimit,autoPaginate:t.autoPaginate??l.autoPaginate,convertDates:t.convertDates??l.convertDates}}function de(t){if(!t.realm)throw new Error("QuickBase realm is required");if(typeof t.realm!="string")throw new Error("QuickBase realm must be a string");if(t.realm.includes("."))throw new Error('Realm should be just the subdomain (e.g., "mycompany" not "mycompany.quickbase.com")');if(!t.auth)throw new Error("Authentication configuration is required");if(le(t.auth),t.timeout!==void 0&&(typeof t.timeout!="number"||t.timeout<=0))throw new Error("Timeout must be a positive number");t.rateLimit?.retry&&me(t.rateLimit.retry),t.rateLimit?.proactiveThrottle&&ce(t.rateLimit.proactiveThrottle)}function le(t){switch(t.type){case"user-token":if(!t.userToken)throw new Error("User token is required for user-token auth");break;case"temp-token":break;case"sso":if(!t.samlToken)throw new Error("SAML token is required for SSO auth");break;default:throw new Error(`Unknown auth type: ${t.type}`)}}function me(t){if(t.maxAttempts!==void 0&&(typeof t.maxAttempts!="number"||t.maxAttempts<0))throw new Error("maxAttempts must be a non-negative number");if(t.initialDelayMs!==void 0&&(typeof t.initialDelayMs!="number"||t.initialDelayMs<0))throw new Error("initialDelayMs must be a non-negative number");if(t.maxDelayMs!==void 0&&(typeof t.maxDelayMs!="number"||t.maxDelayMs<0))throw new Error("maxDelayMs must be a non-negative number");if(t.multiplier!==void 0&&(typeof t.multiplier!="number"||t.multiplier<1))throw new Error("multiplier must be a number >= 1")}function ce(t){if(t.requestsPer10Seconds!==void 0&&(typeof t.requestsPer10Seconds!="number"||t.requestsPer10Seconds<=0))throw new Error("requestsPer10Seconds must be a positive number")}function B(t){return`${t}.quickbase.com`}var he=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})?)?$/;function J(t){return he.test(t)}function G(t,r){if(!r||t===null||t===void 0||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>G(o,r));if(t instanceof Date)return t;let e={};for(let[o,n]of Object.entries(t))typeof n=="string"&&J(n)?e[o]=new Date(n):n instanceof Date?e[o]=n:typeof n=="object"&&n!==null?e[o]=G(n,r):e[o]=n;return e}var P=class{constructor(r,e){i(this,"userToken");i(this,"logger");this.userToken=r,this.logger=e.logger}async getToken(r){return this.userToken}getAuthorizationHeader(r){return`QB-USER-TOKEN ${r}`}async handleAuthError(r){return this.logger.debug("Auth error with user token - cannot refresh"),!1}invalidate(r){}};var A=class{constructor(r){i(this,"cache",new Map);i(this,"defaultLifespanMs");this.defaultLifespanMs=r}get(r){let e=this.cache.get(r);return e?Date.now()>=e.expiresAt-1e4?(this.cache.delete(r),null):e.token:null}set(r,e,o){let n=Date.now()+(o??this.defaultLifespanMs);this.cache.set(r,{token:e,expiresAt:n})}delete(r){return this.cache.delete(r)}clear(){this.cache.clear()}has(r){return this.get(r)!==null}getTimeToExpiry(r){let e=this.cache.get(r);if(!e)return null;let o=e.expiresAt-Date.now();return o>0?o:null}get size(){return this.cleanup(),this.cache.size}cleanup(){let r=Date.now();for(let[e,o]of this.cache)r>=o.expiresAt&&this.cache.delete(e)}};var E=class{constructor(r,e,o){i(this,"userToken");i(this,"appToken");i(this,"realm");i(this,"baseUrl");i(this,"fetchApi");i(this,"logger");i(this,"cache");i(this,"pendingFetches",new Map);this.userToken=r,this.appToken=o?.appToken,this.realm=e.realm,this.baseUrl=e.baseUrl,this.fetchApi=e.fetchApi,this.logger=e.logger,this.cache=new A(o?.tokenLifespanMs??l.tempTokenLifespanMs)}async getToken(r){if(!r)throw new Error("Database ID (dbid) is required for temporary token authentication");let e=this.cache.get(r);if(e)return this.logger.token("cache-hit",r),e;this.logger.token("cache-miss",r);let o=this.pendingFetches.get(r);if(o)return this.logger.debug(`Waiting for existing token fetch for dbid: ${r}`),o;let n=this.fetchToken(r);this.pendingFetches.set(r,n);try{return await n}finally{this.pendingFetches.delete(r)}}async fetchToken(r){this.logger.token("fetch",r);let e=`${this.baseUrl}/auth/temporary/${r}`,o={"QB-Realm-Hostname":`${this.realm}.quickbase.com`,Authorization:`QB-USER-TOKEN ${this.userToken}`,"Content-Type":"application/json"};this.appToken&&(o["QB-App-Token"]=this.appToken);let n=await this.fetchApi(e,{method:"GET",headers:o});if(!n.ok){let u=await n.text();throw new R(`Failed to fetch temporary token for ${r}: ${n.status} ${u}`,{rayId:n.headers.get("qb-api-ray")||void 0})}let s=(await n.json()).temporaryAuthorization;if(!s)throw new R(`No temporary token in response for ${r}`);return this.cache.set(r,s),this.logger.debug(`Cached new token for dbid: ${r}`),s}getAuthorizationHeader(r){return`QB-TEMP-TOKEN ${r}`}async handleAuthError(r){if(!r)return this.logger.debug("Auth error without dbid - cannot refresh temp token"),!1;this.invalidate(r);try{return this.logger.token("refresh",r),await this.getToken(r),!0}catch(e){return this.logger.error(`Failed to refresh temp token for ${r}`,e),!1}}invalidate(r){r?(this.logger.token("expire",r),this.cache.delete(r)):this.cache.clear()}};var S=class{constructor(r,e,o){i(this,"samlToken");i(this,"realm");i(this,"baseUrl");i(this,"fetchApi");i(this,"logger");i(this,"cache");i(this,"pendingExchange",null);this.samlToken=r,this.realm=e.realm,this.baseUrl=e.baseUrl,this.fetchApi=e.fetchApi,this.logger=e.logger,this.cache=new A(o?.tokenLifespanMs??l.tempTokenLifespanMs)}get cacheKey(){return"__sso__"}async getToken(r){let e=this.cache.get(this.cacheKey);if(e)return this.logger.token("cache-hit"),e;if(this.logger.token("cache-miss"),this.pendingExchange)return this.logger.debug("Waiting for existing SSO token exchange"),this.pendingExchange;let o=this.exchangeToken();this.pendingExchange=o;try{return await o}finally{this.pendingExchange=null}}async exchangeToken(){this.logger.token("fetch");let r=`${this.baseUrl}/auth/oauth/token`,e=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",requested_token_type:"urn:quickbase:params:oauth:token-type:temp_token",subject_token:this.samlToken,subject_token_type:"urn:ietf:params:oauth:token-type:saml2"}),o=await this.fetchApi(r,{method:"POST",headers:{"QB-Realm-Hostname":`${this.realm}.quickbase.com`,"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!o.ok){let s=await o.text();throw new R(`SSO token exchange failed: ${o.status} ${s}`,{rayId:o.headers.get("qb-api-ray")||void 0})}let a=(await o.json()).access_token;if(!a)throw new R("No access_token in SSO exchange response");return this.cache.set(this.cacheKey,a),this.logger.debug("Cached new SSO token"),a}getAuthorizationHeader(r){return`QB-TEMP-TOKEN ${r}`}async handleAuthError(r){this.invalidate();try{return this.logger.token("refresh"),await this.getToken(),!0}catch(e){return this.logger.error("Failed to refresh SSO token",e),!1}}invalidate(r){this.logger.token("expire"),this.cache.clear()}};function L(t,r){switch(t.type){case"user-token":return new P(t.userToken,r);case"temp-token":return new E(t.userToken,r,{appToken:t.appToken,tokenLifespanMs:t.tokenLifespanMs});case"sso":return new S(t.samlToken,r);default:throw new Error(`Unknown auth type: ${t.type}`)}}function z(t,r,e){let o=t.headers.get("Retry-After");return{timestamp:new Date,requestUrl:r,httpStatus:t.status,retryAfter:o?parseInt(o,10):void 0,cfRay:t.headers.get("cf-ray")||void 0,tid:t.headers.get("tid")||void 0,qbApiRay:t.headers.get("qb-api-ray")||void 0,attempt:e}}function H(t){return new Promise(r=>setTimeout(r,t))}function ge(t){if(t.dbid)return t.dbid;if(t.query?.tableId)return String(t.query.tableId);if(t.query?.appId)return String(t.query.appId);let r=t.path.match(/\/tables\/([^/?]+)/);if(r)return r[1];let e=t.path.match(/\/apps\/([^/?]+)/);if(e)return e[1];if(t.body&&typeof t.body=="object"){let o=t.body;if(typeof o.from=="string")return o.from;if(typeof o.to=="string")return o.to}}function V(t,r,e){let o=t.endsWith("/")?t:`${t}/`,n=r.startsWith("/")?r.slice(1):r,a=new URL(n,o);if(e)for(let[s,u]of Object.entries(e))u!==void 0&&a.searchParams.set(s,String(u));return a.toString()}async function Re(t,r,e,o){let n=await t.getToken(e),a=t.getAuthorizationHeader(n);return{"Content-Type":"application/json","QB-Realm-Hostname":r,Authorization:a,...o}}async function fe(t,r,e){let{config:o,auth:n,throttle:a,logger:s}=r,u=V(o.baseUrl,t.path,t.query),m=B(o.realm),d=await Re(n,m,e.dbid,t.headers);await a.acquire();let p={method:t.method,headers:d};t.body!==void 0&&(p.body=JSON.stringify(t.body));let c=new AbortController,g=setTimeout(()=>c.abort(),o.timeout);p.signal=c.signal;let b=Date.now();try{let y=await o.fetchApi(u,p),U=Date.now()-b;return s.timing(t.method,t.path,U),y}catch(y){throw y instanceof Error&&y.name==="AbortError"?new T(o.timeout):y}finally{clearTimeout(g)}}async function ye(t,r,e,o){let{config:n,logger:a}=o;if(t.ok)return t;if(t.status===429){let s=z(t,r,e.attempt);throw a.rateLimit({url:r,status:429,retryAfter:s.retryAfter,attempt:e.attempt,rayId:s.qbApiRay||s.cfRay}),n.onRateLimit&&n.onRateLimit(s),new f(s)}throw await Q(t,r)}async function Z(t,r){let{config:e,auth:o,logger:n}=r,a=e.retry.maxAttempts,s=ge(t),u={methodName:`${t.method} ${t.path}`,attempt:1,maxAttempts:a,dbid:s,startTime:Date.now()},m=null;for(let d=1;d<=a;d++){u.attempt=d;try{let p=await fe(t,r,u),c=V(e.baseUrl,t.path,t.query);await ye(p,c,u,r);let g=await p.json();return G(g,e.convertDates)}catch(p){if(m=p,!F(p)||d>=a)throw p;if(p instanceof h&&p.statusCode===401){if(!await o.handleAuthError(s))throw p;n.debug("Token refreshed, retrying request");continue}let c,g;p instanceof f?(c=p.retryAfter?p.retryAfter*1e3:$(d,e.retry),g="Rate limited (429)"):p instanceof T?(c=$(d,e.retry),g="Timeout"):p instanceof h&&p.statusCode>=500?(c=$(d,e.retry),g=`Server error (${p.statusCode})`):(c=$(d,e.retry),g="Retryable error"),n.retry(d,a,c,g),await H(c)}}throw m||new Error("Request failed")}function $(t,r){let e=r.initialDelayMs*Math.pow(r.multiplier,t-1),o=e*.1*(Math.random()*2-1);return Math.min(e+o,r.maxDelayMs)}function W(t){return{execute:r=>Z(r,t)}}var D=class{constructor(r=100){i(this,"requestsPer10Seconds");i(this,"timestamps",[]);this.requestsPer10Seconds=r}async acquire(){let r=Date.now(),e=r-1e4;for(;this.timestamps.length>0&&this.timestamps[0]<e;)this.timestamps.shift();if(this.timestamps.length>=this.requestsPer10Seconds){let n=this.timestamps[0]+1e4-r;if(n>0)return await this.sleep(n),this.acquire()}this.timestamps.push(Date.now())}getWindowCount(){let r=Date.now()-1e4;return this.timestamps.filter(e=>e>=r).length}getRemaining(){return Math.max(0,this.requestsPer10Seconds-this.getWindowCount())}reset(){this.timestamps.length=0}sleep(r){return new Promise(e=>setTimeout(e,r))}},v=class{async acquire(){}getWindowCount(){return 0}getRemaining(){return 1/0}reset(){}};function K(t){return t.enabled?new D(t.requestsPer10Seconds):new v}function X(t){return t.totalRecords!==void 0&&t.skip!==void 0?"skip":t.nextPageToken!==void 0||t.nextToken!==void 0?"token":"none"}function Y(t,r,e){let{metadata:o}=t;if(r==="skip")return o.totalRecords!==void 0&&e<o.totalRecords;if(r==="token"){let n=o.nextPageToken??o.nextToken;return n!==void 0&&n!==""}return!1}function ee(t){for(let r of Object.keys(t))if(Array.isArray(t[r]))return r;return"data"}function te(t){if(!t||typeof t!="object")return!1;let r=t;if(!r.metadata||typeof r.metadata!="object"||!Object.values(r).some(Array.isArray))return!1;let o=r.metadata;return o.totalRecords!==void 0||o.numRecords!==void 0||o.nextPageToken!==void 0||o.nextToken!==void 0}var O=class{constructor(r,e){i(this,"executor");i(this,"paginatedExecutor");i(this,"defaultAutoPaginate");this.executor=r,this.paginatedExecutor=e?.paginatedExecutor,this.defaultAutoPaginate=e?.autoPaginate??!1}then(r,e){return(this.defaultAutoPaginate?this.all():this.executor()).then(r,e)}async all(){return this.paginate({})}async paginate(r={}){if(!this.paginatedExecutor)return this.executor();let{limit:e,skip:o=0}=r,n=[],a=null,s="none",u=o,m,d=await this.paginatedExecutor({skip:o});if(!te(d))return d;a=d,s=X(d.metadata);let p=ee(d),c=d[p]||[];for(e!==void 0&&c.length>e?n=c.slice(0,e):n=[...c],s==="skip"?u=o+c.length:s==="token"&&(m=d.metadata.nextPageToken??d.metadata.nextToken);Y(a,s,n.length)&&!(e!==void 0&&n.length>=e);){let b;if(s==="skip")b=await this.paginatedExecutor({skip:u});else if(s==="token"&&m){let U=a.metadata.nextPageToken!==void 0?"nextPageToken":"nextToken";b=await this.paginatedExecutor({[U]:m})}else break;a=b;let y=b[p]||[];if(y.length===0)break;if(e!==void 0){let U=e-n.length;n=n.concat(y.slice(0,U))}else n=n.concat(y);if(s==="skip")u+=y.length;else if(s==="token"&&(m=b.metadata.nextPageToken??b.metadata.nextToken,!m))break}let g={...a,[p]:n,metadata:{...a.metadata,numRecords:n.length,skip:o}};return s==="token"&&(delete g.metadata.nextPageToken,delete g.metadata.nextToken),g}async noPaginate(){return this.executor()}toPromise(){return this.then()}};function x(t,r){return new O(t,r)}function j(t,r=!1){return{createApp(e){return t({method:"POST",path:"/apps",body:e})},getApp(e){return t({method:"GET",path:`/apps/${e.appId}`})},updateApp(e,o){return t({method:"POST",path:`/apps/${e.appId}`,body:o})},deleteApp(e,o){return t({method:"DELETE",path:`/apps/${e.appId}`,body:o})},getAppEvents(e){return t({method:"GET",path:`/apps/${e.appId}/events`})},copyApp(e,o){return t({method:"POST",path:`/apps/${e.appId}/copy`,body:o})},getAppTables(e){return t({method:"GET",path:"/tables",query:{appId:e.appId}})},createTable(e,o){return t({method:"POST",path:"/tables",query:{appId:e.appId},body:o})},getTable(e){return t({method:"GET",path:`/tables/${e.tableId}`,query:{appId:e.appId}})},updateTable(e,o){return t({method:"POST",path:`/tables/${e.tableId}`,query:{appId:e.appId},body:o})},deleteTable(e){return t({method:"DELETE",path:`/tables/${e.tableId}`,query:{appId:e.appId}})},getRelationships(e){return x(()=>t({method:"GET",path:`/tables/${e.tableId}/relationships`,query:{skip:e.skip}}),{paginatedExecutor:a=>t({method:"GET",path:`/tables/${e.tableId}/relationships`,query:{skip:e.skip,...a}}),autoPaginate:r})},createRelationship(e,o){return t({method:"POST",path:`/tables/${e.tableId}/relationship`,body:o})},updateRelationship(e,o){return t({method:"POST",path:`/tables/${e.tableId}/relationship/${e.relationshipId}`,body:o})},deleteRelationship(e){return t({method:"DELETE",path:`/tables/${e.tableId}/relationship/${e.relationshipId}`})},getTableReports(e){return t({method:"GET",path:"/reports",query:{tableId:e.tableId}})},getReport(e){return t({method:"GET",path:`/reports/${e.reportId}`,query:{tableId:e.tableId}})},runReport(e,o){return x(()=>t({method:"POST",path:`/reports/${e.reportId}/run`,query:{tableId:e.tableId,skip:e.skip,top:e.top},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:`/reports/${e.reportId}/run`,query:{tableId:e.tableId,skip:e.skip,top:e.top},body:m})},autoPaginate:r})},getFields(e){return t({method:"GET",path:"/fields",query:{tableId:e.tableId,includeFieldPerms:e.includeFieldPerms}})},createField(e,o){return t({method:"POST",path:"/fields",query:{tableId:e.tableId},body:o})},deleteFields(e,o){return t({method:"DELETE",path:"/fields",query:{tableId:e.tableId},body:o})},getField(e){return t({method:"GET",path:`/fields/${e.fieldId}`,query:{tableId:e.tableId,includeFieldPerms:e.includeFieldPerms}})},updateField(e,o){return t({method:"POST",path:`/fields/${e.fieldId}`,query:{tableId:e.tableId},body:o})},getFieldsUsage(e){return t({method:"GET",path:"/fields/usage",query:{tableId:e.tableId,skip:e.skip,top:e.top}})},getFieldUsage(e){return t({method:"GET",path:`/fields/usage/${e.fieldId}`,query:{tableId:e.tableId}})},runFormula(e){return t({method:"POST",path:"/formula/run",body:e})},upsert(e){return x(()=>t({method:"POST",path:"/records",body:e}),{paginatedExecutor:a=>{let s=e,u=a.skip!==void 0||a.nextPageToken||a.nextToken?{...s||{},options:{...s?.options||{},...a.skip!==void 0?{skip:a.skip}:{}},...a.nextPageToken?{nextPageToken:a.nextPageToken}:{},...a.nextToken?{nextToken:a.nextToken}:{}}:e;return t({method:"POST",path:"/records",body:u})},autoPaginate:r})},deleteRecords(e){return t({method:"DELETE",path:"/records",body:e})},runQuery(e){return x(()=>t({method:"POST",path:"/records/query",body:e}),{paginatedExecutor:a=>{let s=e,u=a.skip!==void 0||a.nextPageToken||a.nextToken?{...s||{},options:{...s?.options||{},...a.skip!==void 0?{skip:a.skip}:{}},...a.nextPageToken?{nextPageToken:a.nextPageToken}:{},...a.nextToken?{nextToken:a.nextToken}:{}}:e;return t({method:"POST",path:"/records/query",body:u})},autoPaginate:r})},getTempTokenDBID(e){return t({method:"GET",path:`/auth/temporary/${e.dbid}`})},exchangeSsoToken(e){return t({method:"POST",path:"/auth/oauth/token",body:e})},cloneUserToken(e){return t({method:"POST",path:"/usertoken/clone",body:e})},transferUserToken(e){return t({method:"POST",path:"/usertoken/transfer",body:e})},deactivateUserToken(){return t({method:"POST",path:"/usertoken/deactivate"})},deleteUserToken(){return t({method:"DELETE",path:"/usertoken"})},downloadFile(e){return t({method:"GET",path:`/files/${e.tableId}/${e.recordId}/${e.fieldId}/${e.versionNumber}`})},deleteFile(e){return t({method:"DELETE",path:`/files/${e.tableId}/${e.recordId}/${e.fieldId}/${e.versionNumber}`})},getUsers(e,o){return x(()=>t({method:"POST",path:"/users",query:{accountId:e.accountId},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:"/users",query:{accountId:e.accountId},body:m})},autoPaginate:r})},denyUsers(e,o){return t({method:"PUT",path:"/users/deny",query:{accountId:e.accountId},body:o})},denyUsersAndGroups(e,o){return t({method:"PUT",path:`/users/deny/${e.shouldDeleteFromGroups}`,query:{accountId:e.accountId},body:o})},undenyUsers(e,o){return t({method:"PUT",path:"/users/undeny",query:{accountId:e.accountId},body:o})},addMembersToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/members`,body:o})},removeMembersFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/members`,body:o})},addManagersToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/managers`,body:o})},removeManagersFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/managers`,body:o})},addSubgroupsToGroup(e,o){return t({method:"POST",path:`/groups/${e.gid}/subgroups`,body:o})},removeSubgroupsFromGroup(e,o){return t({method:"DELETE",path:`/groups/${e.gid}/subgroups`,body:o})},audit(e){return t({method:"POST",path:"/audit",body:e})},platformAnalyticReads(e){return t({method:"GET",path:"/analytics/reads",query:{day:e.day}})},platformAnalyticEventSummaries(e,o){return x(()=>t({method:"POST",path:"/analytics/events/summaries",query:{accountId:e.accountId},body:o}),{paginatedExecutor:s=>{let u=o,m=s.skip!==void 0||s.nextPageToken||s.nextToken?{...u||{},options:{...u?.options||{},...s.skip!==void 0?{skip:s.skip}:{}},...s.nextPageToken?{nextPageToken:s.nextPageToken}:{},...s.nextToken?{nextToken:s.nextToken}:{}}:o;return t({method:"POST",path:"/analytics/events/summaries",query:{accountId:e.accountId},body:m})},autoPaginate:r})},exportSolution(e){return t({method:"GET",path:`/solutions/${e.solutionId}`})},updateSolution(e,o){return t({method:"PUT",path:`/solutions/${e.solutionId}`,body:o})},createSolution(e){return t({method:"POST",path:"/solutions",body:e})},exportSolutionToRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/torecord`,query:{tableId:e.tableId,fieldId:e.fieldId}})},createSolutionFromRecord(e){return t({method:"GET",path:"/solutions/fromrecord",query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},updateSolutionToRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/fromrecord`,query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},changesetSolution(e,o){return t({method:"PUT",path:`/solutions/${e.solutionId}/changeset`,body:o})},changesetSolutionFromRecord(e){return t({method:"GET",path:`/solutions/${e.solutionId}/changeset/fromrecord`,query:{tableId:e.tableId,fieldId:e.fieldId,recordId:e.recordId}})},generateDocument(e){return t({method:"GET",path:`/docTemplates/${e.templateId}/generate`,query:{tableId:e.tableId,recordId:e.recordId,filename:e.filename,format:e.format,margin:e.margin,unit:e.unit,pageSize:e.pageSize,orientation:e.orientation,realm:e.realm}})}}}function re(t){let r=_(t),e=N(r.debug),o={realm:r.realm,baseUrl:r.baseUrl,fetchApi:r.fetchApi,logger:e},n=L(r.auth,o),a=K(r.proactiveThrottle),s=W({config:r,auth:n,throttle:a,logger:e});return{...j(s.execute,r.autoPaginate),request:s.execute,getConfig:()=>r}}var Te=re;return pe(be);})();
|
|
7
7
|
//# sourceMappingURL=quickbase.min.js.map
|