@carddb/browser 0.4.1 → 0.4.2

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.
@@ -551,7 +551,7 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
551
551
  warnings {
552
552
  ${R}
553
553
  }
554
- `,_=`
554
+ `,V=`
555
555
  deck {
556
556
  ${u}
557
557
  }
@@ -613,7 +613,7 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
613
613
  message
614
614
  details
615
615
  }
616
- `,_e=`
616
+ `,Ve=`
617
617
  total
618
618
  inserted
619
619
  updated
@@ -634,7 +634,7 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
634
634
  ${le}
635
635
  }
636
636
  stats {
637
- ${_e}
637
+ ${Ve}
638
638
  }
639
639
  `,ge=`
640
640
  fileId
@@ -685,7 +685,7 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
685
685
  imagesPending
686
686
  imagesCompleted
687
687
  imagesFailed
688
- `,Ve=`
688
+ `,_e=`
689
689
  id
690
690
  importJobId
691
691
  level
@@ -708,7 +708,7 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
708
708
  identifier
709
709
  status
710
710
  message
711
- `,V=`
711
+ `,_=`
712
712
  id
713
713
  publisherId
714
714
  publisher {
@@ -962,7 +962,14 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
962
962
  completedJobs
963
963
  failedJobs
964
964
  failureRate
965
+ noMatchCount
966
+ noMatchRate
965
967
  averageShortlistSize
968
+ vectorQueryCount
969
+ vectorFallbackCount
970
+ averageVectorCandidates
971
+ averageVectorQueryMs
972
+ averageEmbeddingMs
966
973
  confidenceDistribution
967
974
  feedback {
968
975
  total
@@ -976,8 +983,14 @@ var y=class ne extends Error{response;constructor(t,r){super(t),this.name="CardD
976
983
  jobCount
977
984
  completedJobs
978
985
  failedJobs
986
+ noMatchCount
979
987
  averageConfidence
980
988
  averageShortlistSize
989
+ vectorQueryCount
990
+ vectorFallbackCount
991
+ averageVectorCandidates
992
+ averageVectorQueryMs
993
+ averageEmbeddingMs
981
994
  feedbackCount
982
995
  correctFeedback
983
996
  correctedFeedback
@@ -1220,19 +1233,19 @@ ${ie}`:n;return {query:`
1220
1233
  `}},deleteDatasetRecords(){return {query:`
1221
1234
  mutation DatasetRecordsDelete($input: DatasetRecordsDeleteInput!) {
1222
1235
  datasetRecordsDelete(input: $input) {
1223
- ${V}
1236
+ ${_}
1224
1237
  }
1225
1238
  }
1226
1239
  `}},datasetRecordDeleteJob(){return {query:`
1227
1240
  query DatasetRecordDeleteJob($id: UUID!) {
1228
1241
  datasetRecordDeleteJob(id: $id) {
1229
- ${V}
1242
+ ${_}
1230
1243
  }
1231
1244
  }
1232
1245
  `}},datasetRecordDeleteJobs(e){let t={publisherId:e.publisherId},r=["publisherId: $publisherId"],s=["$publisherId: UUID!"];return e.datasetId!==void 0&&(s.push("$datasetId: UUID"),r.push("datasetId: $datasetId"),t.datasetId=e.datasetId),e.status!==void 0&&(s.push("$status: DatasetRecordDeleteJobStatus"),r.push("status: $status"),t.status=e.status),e.first!==void 0&&(s.push("$first: Int"),r.push("first: $first"),t.first=e.first),e.after!==void 0&&(s.push("$after: String"),r.push("after: $after"),t.after=e.after),{query:`
1233
1246
  query DatasetRecordDeleteJobs(${s.join(", ")}) {
1234
1247
  datasetRecordDeleteJobs(${r.join(", ")}) {
1235
- ${d(V)}
1248
+ ${d(_)}
1236
1249
  }
1237
1250
  }
1238
1251
  `,variables:t}},datasetImportPreview(){return {query:`
@@ -1287,7 +1300,7 @@ ${ie}`:n;return {query:`
1287
1300
  query ImportJobLogs(${i.join(", ")}) {
1288
1301
  importJob(${r.join(", ")}) {
1289
1302
  logs${n} {
1290
- ${d(Ve)}
1303
+ ${d(_e)}
1291
1304
  }
1292
1305
  }
1293
1306
  }
@@ -1714,19 +1727,19 @@ ${ie}`:n;return {query:`
1714
1727
  `}},addDeckEntry(){return {query:`
1715
1728
  mutation DeckEntryAdd($input: DeckEntryAddInput!) {
1716
1729
  deckEntryAdd(input: $input) {
1717
- ${_}
1730
+ ${V}
1718
1731
  }
1719
1732
  }
1720
1733
  `}},updateDeckEntry(){return {query:`
1721
1734
  mutation DeckEntryUpdate($id: UUID!, $input: DeckEntryUpdateInput!) {
1722
1735
  deckEntryUpdate(id: $id, input: $input) {
1723
- ${_}
1736
+ ${V}
1724
1737
  }
1725
1738
  }
1726
1739
  `}},removeDeckEntry(){return {query:`
1727
1740
  mutation DeckEntryRemove($id: UUID!, $expectedDraftRevision: Int!) {
1728
1741
  deckEntryRemove(id: $id, expectedDraftRevision: $expectedDraftRevision) {
1729
- ${_}
1742
+ ${V}
1730
1743
  }
1731
1744
  }
1732
1745
  `}},reorderDeckEntries(){return {query:`
@@ -1928,6 +1941,6 @@ ${ie}`:n;return {query:`
1928
1941
  }
1929
1942
  }
1930
1943
  }
1931
- `}}},l=class{totalCount;pageInfo;items;nextPageLoader;constructor(e,t={}){this.totalCount=e.totalCount,this.pageInfo=e.pageInfo,this.items=e.edges.map(r=>t.itemTransformer?t.itemTransformer(r.node):r.node),this.nextPageLoader=t.nextPageLoader;}get hasNextPage(){return this.pageInfo.hasNextPage}get hasPreviousPage(){return this.pageInfo.hasPreviousPage}get endCursor(){return this.pageInfo.endCursor}get startCursor(){return this.pageInfo.startCursor}get length(){return this.items.length}get isEmpty(){return this.items.length===0}get first(){return this.items[0]}get last(){return this.items[this.items.length-1]}async nextPage(){if(!this.hasNextPage)return null;if(!this.nextPageLoader)throw new Error("No next page loader configured");return this.endCursor?this.nextPageLoader(this.endCursor):null}async*[Symbol.asyncIterator](){let e=this;for(;e;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage();}}async forEach(e){let t=0;for await(let r of this)await e(r,t++);}async map(e){let t=[],r=0;for await(let s of this)t.push(await e(s,r++));return t}async filter(e){let t=[],r=0;for await(let s of this)await e(s,r++)&&t.push(s);return t}async find(e){let t=0;for await(let r of this)if(await e(r,t++))return r}async take(e){let t=[];for await(let r of this){if(t.length>=e)break;t.push(r);}return t}async toArray(){let e=[];for await(let t of this)e.push(t);return e}async*batches(){let e=this;for(;e&&(e.items.length>0&&(yield e.items),!!e.hasNextPage);)e=await e.nextPage();}each(){return this}};var Qe="https://carddb.dev/query",Ze=3e4,et=1e4,tt=300,rt=3,st=2,it=1e3,at=3e4,nt=class Ie{apiKey;publishableKey;secretKey;accessToken;legacyApiKey;environment;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.legacyApiKey=t.apiKey,this.publishableKey=t.publishableKey,this.secretKey=t.secretKey,this.accessToken=t.accessToken,this.apiKey=t.apiKey??t.publishableKey??t.secretKey,this.environment=t.environment,this.endpoint=t.endpoint??Qe,this.timeout=t.timeout??Ze,this.openTimeout=t.openTimeout??et,this.defaultPublisher=t.defaultPublisher,this.defaultGame=t.defaultGame,this.allowedPublishers=t.allowedPublishers,this.allowedGames=t.allowedGames,this.logger=t.logger,this.logLevel=t.logLevel??"info",this.retryOnRateLimit=t.retryOnRateLimit??false,this.maxRetries=t.maxRetries??rt,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??st,this.retryBaseDelay=t.retryBaseDelay??it,this.retryMaxDelay=t.retryMaxDelay??at,this.cache=t.cache,this.cacheTtl=t.cacheTtl??tt,this.cacheTtls=t.cacheTtls??{};}calculateRetryDelay(t){let r=this.retryBaseDelay*Math.pow(2,t),s=Math.min(r,this.retryMaxDelay),i=s*.25*(Math.random()*2-1);return Math.round(s+i)}cacheTtlFor(t){return this.cacheTtls[t]??this.cacheTtl}resolvePublisher(t){return t??this.defaultPublisher}resolveGame(t){return t??this.defaultGame}validatePublisher(t){if(this.allowedPublishers&&!this.allowedPublishers.includes(t))throw new $(`Publisher '${t}' is not in the allowed publishers list`)}validateGame(t,r){if(!this.allowedGames)return;let s=this.allowedGames[t];if(s&&!s.includes(r))throw new $(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}requireSecretCredential(t){if(!(!this.accessToken&&(this.legacyApiKey||this.secretKey&&!this.publishableKey)))throw new $(`${t} requires a server-side secretKey or legacy apiKey credential`)}requestApiKey(){return this.legacyApiKey??this.publishableKey??this.secretKey}configApiKey(){return this.legacyApiKey}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new Ie({apiKey:t.apiKey??this.legacyApiKey,publishableKey:t.publishableKey??this.publishableKey,secretKey:t.secretKey??this.secretKey,accessToken:t.accessToken??this.accessToken,environment:t.environment??this.environment,endpoint:t.endpoint??this.endpoint,timeout:t.timeout??this.timeout,openTimeout:t.openTimeout??this.openTimeout,defaultPublisher:t.defaultPublisher??this.defaultPublisher,defaultGame:t.defaultGame??this.defaultGame,allowedPublishers:t.allowedPublishers??this.allowedPublishers,allowedGames:t.allowedGames??this.allowedGames,logger:t.logger??this.logger,logLevel:t.logLevel??this.logLevel,retryOnRateLimit:t.retryOnRateLimit??this.retryOnRateLimit,maxRetries:t.maxRetries??this.maxRetries,retryOnNetworkError:t.retryOnNetworkError??this.retryOnNetworkError,maxNetworkRetries:t.maxNetworkRetries??this.maxNetworkRetries,retryBaseDelay:t.retryBaseDelay??this.retryBaseDelay,retryMaxDelay:t.retryMaxDelay??this.retryMaxDelay,cache:t.cache??this.cache,cacheTtl:t.cacheTtl??this.cacheTtl,cacheTtls:t.cacheTtls??this.cacheTtls})}},be="0.4.1";function ct(){if(typeof globalThis<"u"&&"Bun"in globalThis){let e=globalThis.Bun&&typeof globalThis.Bun=="object"&&globalThis.Bun.version;return {name:"bun",version:typeof e=="string"?e:"unknown"}}if(typeof globalThis<"u"&&"Deno"in globalThis){let e=globalThis.Deno&&typeof globalThis.Deno=="object"&&globalThis.Deno.version&&typeof globalThis.Deno.version=="object"&&globalThis.Deno.version.deno;return {name:"deno",version:typeof e=="string"?e:"unknown"}}return typeof process<"u"&&process.versions&&process.versions.node?{name:"node",version:process.versions.node}:typeof navigator<"u"&&navigator.userAgent?ot(navigator.userAgent):{name:"unknown",version:"unknown"}}function ot(e){let t=e.match(/Edg\/(\d+(?:\.\d+)*)/);if(t)return {name:"edge",version:t[1]};let r=e.match(/Chrome\/(\d+(?:\.\d+)*)/);if(r&&!e.includes("Edg/"))return {name:"chrome",version:r[1]};let s=e.match(/Firefox\/(\d+(?:\.\d+)*)/);if(s)return {name:"firefox",version:s[1]};let i=e.match(/Version\/(\d+(?:\.\d+)*).*Safari/);return i?{name:"safari",version:i[1]}:{name:"browser",version:"unknown"}}function ut(){let e=ct();return `CardDB-SDK/js/${be} (${e.name}/${e.version})`}function fr(){return be}var $e=null;function lt(){return $e}var dt=class{config;constructor(e){this.config=e;}async execute(e,t={}){let r=this.extractOperationName(e),s=0,i=0;for(;;)try{let n=Date.now();this.logRequest(r,t);let c=await this.fetch(e,t),o=Date.now()-n,h=await this.handleResponse(c);return this.logResponse(r,o),h}catch(n){if(n instanceof K&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let c=n.retryAfter??60;this.logRateLimitRetry(r,s,c),await this.sleep(c*1e3);continue}if(this.isRetryableNetworkError(n)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let c=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,c,n),i++,await this.sleep(c);continue}if(n instanceof O&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let c=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,c,n),i++,await this.sleep(c);continue}throw n}}isRetryableNetworkError(e){return e instanceof x||e instanceof G}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout),i=this.config.requestApiKey();try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":ut(),...this.config.accessToken?{Authorization:`Bearer ${this.config.accessToken}`}:{},...!this.config.accessToken&&i?{"X-API-Key":i}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(n){throw n instanceof Error?n.name==="AbortError"?(this.logError("Request timed out"),new G("Request timed out")):(this.logError(`Connection failed: ${n.message}`),new x(`Connection failed: ${n.message}`)):new x("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new M("Invalid or missing API key");case 429:return this.handleRateLimitResponse(e);default:if(e.status>=400&&e.status<500)return this.handleClientError(e);if(e.status>=500){let t=await this.parseBody(e);throw new O(`Server error (${e.status})`,{status:e.status,response:t})}throw new y(`Unexpected response status: ${e.status}`)}}async handleSuccessResponse(e){let t=await this.parseBody(e);return t.errors&&t.errors.length>0&&this.handleGraphQLErrors(t.errors,t),t.data??{}}handleGraphQLErrors(e,t){let r=e[0],s=r.message||"GraphQL error";switch(r.extensions?.code){case "UNAUTHENTICATED":throw new M(s,t);case "RATE_LIMITED":throw new K(s,{response:t});case "NOT_FOUND":throw new y(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new J(s,{errors:e,response:t});default:throw new ce(s,{errors:e,response:t})}}async handleRateLimitResponse(e){let t=parseInt(e.headers.get("Retry-After")??"60",10),r=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,i=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null,n=i?new Date(i*1e3):null,c=await this.parseBody(e);throw new K("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:n,response:c})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new J(r,{response:t})}async parseBody(e){try{return await e.json()}catch{return {raw:await e.text()}}}extractRateLimitInfo(e){let t=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,r=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null;$e={limit:t,remaining:r,reset:s};}extractOperationName(e){let t=e.match(/(?:query|mutation)\s+(\w+)/);return t?t[1]:"Unknown"}sleep(e){return new Promise(t=>setTimeout(t,e))}logRequest(e,t){!this.config.logger||!this.config.shouldLog("debug")||this.config.logger.debug(`[CardDB] Executing ${e}`,{variables:t});}logResponse(e,t){!this.config.logger||!this.config.shouldLog("info")||this.config.logger.info(`[CardDB] ${e} completed in ${t}ms`);}logRateLimitRetry(e,t,r){!this.config.logger||!this.config.shouldLog("warn")||this.config.logger.warn(`[CardDB] Rate limited on ${e}, retry ${t}/${this.config.maxRetries} after ${r}s`);}logNetworkRetry(e,t,r,s){if(!this.config.logger||!this.config.shouldLog("warn"))return;let i=s instanceof Error?s.name:"Unknown";this.config.logger.warn(`[CardDB] ${i} on ${e}, retry ${t}/${this.config.maxNetworkRetries} after ${r}ms`);}logError(e){!this.config.logger||!this.config.shouldLog("error")||this.config.logger.error(`[CardDB] ${e}`);}};function ht(e,t,r){let s=Object.entries(r).filter(([,i])=>i!==void 0).sort(([i],[n])=>i.localeCompare(n)).map(([i,n])=>`${i}=${JSON.stringify(n)}`).join("&");return `carddb:${e}:${t}:${s}`}async function yt(e,t){let r=e.get(t);return r}async function ft(e,t,r,s){let i=e.set(t,r,s);i instanceof Promise&&await i;}var f=class{connection;config;constructor(e,t){this.connection=e,this.config=t;}resolvePublisher(e){let t=this.config.resolvePublisher(e);if(!t)throw new Error("publisher_slug is required (no default configured)");return t}resolveGame(e){let t=this.config.resolveGame(e);if(!t)throw new Error("game_key is required (no default configured)");return t}validateAccess(e,t){this.config.validateAccess(e,t);}async withCache(e,t,r,s){let i=r.cache??!!this.config.cache,n=this.config.cache;if(!i||!n)return s();let c=await yt(n,e);if(c!==null)return c;let o=await s();if(o!=null){let h=this.config.cacheTtlFor(t);await ft(n,e,o,h);}return o}cacheKey(e,t,r){return ht(e,t,r)}},pt=class extends f{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=a.searchPublishers({search:e.search,first:e.first,after:e.after}),s=this.cacheKey("publishers","search",r),i=await this.withCache(s,"publishers",e,async()=>(await this.connection.execute(t,r)).searchPublishers);return new l(i,{nextPageLoader:async n=>this.search({...e,after:n})})}async get(e,t={}){let r=this.isUUID(e),s=this.cacheKey("publishers","get",{[r?"id":"slug"]:e});return this.withCache(s,"publishers",t,async()=>{if(r){let{query:i}=a.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=a.fetchPublisherBySlug();return (await this.connection.execute(i,{slug:e})).fetchPublisher??null}})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("publishers","getMany",{slugs:e});return this.withCache(r,"publishers",t,async()=>{let{query:s}=a.fetchPublishers();return (await this.connection.execute(s,{slugs:e})).fetchPublishers??[]})}isUUID(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},mt=class extends f{constructor(e,t){super(e,t);}async list(e,t={}){let{query:r,variables:s}=a.listGames({publisherId:e,first:t.first,after:t.after,includeArchived:t.includeArchived}),i=this.cacheKey("games","list",s),n=await this.withCache(i,"games",t,async()=>(await this.connection.execute(r,s)).games);return new l(n,{nextPageLoader:async c=>this.list(e,{...t,after:c})})}async getByKey(e){let t=this.cacheKey("games","getByKey",{publisherId:e.publisherId,publisherSlug:e.publisherSlug,gameKey:e.gameKey});return this.withCache(t,"games",e,async()=>{let{query:r,variables:s}=a.game(e);return (await this.connection.execute(r,s)).game??null})}async getBySlug(e){let t=this.cacheKey("games","getBySlug",{publisherId:e.publisherId,publisherSlug:e.publisherSlug,gameSlug:e.gameSlug});return this.withCache(t,"games",e,async()=>{let{query:r,variables:s}=a.game(e);return (await this.connection.execute(r,s)).game??null})}async create(e){this.config.requireSecretCredential("games.create");let{query:t}=a.createGame();return (await this.connection.execute(t,a.gameCreateVariables(e))).gameCreate}async update(e,t){this.config.requireSecretCredential("games.update");let{query:r}=a.updateGame();return (await this.connection.execute(r,a.gameUpdateVariables(e,t))).gameUpdate}async getRegions(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=a.gameScanRegionsVariables(t,r,e.includeInactive),i=this.cacheKey("games","getRegions",s);return this.withCache(i,"games",e,async()=>{let{query:n}=a.gameScanRegions();return (await this.connection.execute(n,s)).gameScanRegions??[]})}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=a.searchGames({publisherSlug:t,search:e.search,first:e.first,after:e.after}),i=this.cacheKey("games","search",s),n=await this.withCache(i,"games",e,async()=>(await this.connection.execute(r,s)).searchGames);return new l(n,{nextPageLoader:async c=>this.search({...e,after:c})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,n=r??{};this.validateAccess(s,i);let c=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(c,"games",n,async()=>{let{query:o}=a.fetchGameByKeys();return (await this.connection.execute(o,{publisherSlug:s,gameKey:i})).fetchGame??null})}else {let s=e,i=t??{},n=this.cacheKey("games","get",{id:s});return this.withCache(n,"games",i,async()=>{let{query:c}=a.fetchGameById();return (await this.connection.execute(c,{id:s})).fetchGame??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("games","getMany",{ids:e});return this.withCache(r,"games",t,async()=>{let{query:s}=a.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},gt=class extends f{constructor(e,t){super(e,t);}async list(e,t={}){let{query:r,variables:s}=a.listDatasets({publisherId:e,gameId:t.gameId,includeArchived:t.includeArchived,purpose:t.purpose,first:t.first,after:t.after}),i=this.cacheKey("datasets","list",s),n=await this.withCache(i,"datasets",t,async()=>(await this.connection.execute(r,s)).datasets);return new l(n,{nextPageLoader:async c=>this.list(e,{...t,after:c})})}async getByKey(e){let t=this.cacheKey("datasets","getByKey",{publisherId:e.publisherId,gameId:e.gameId,datasetKey:e.datasetKey});return this.withCache(t,"datasets",e,async()=>{let{query:r,variables:s}=a.dataset(e);return (await this.connection.execute(r,s)).dataset??null})}async getSchema(e){return (typeof e=="string"?await this.withCache(this.cacheKey("datasets","getSchema",{id:e}),"datasets",{},async()=>{let{query:r,variables:s}=a.dataset({id:e});return (await this.connection.execute(r,s)).dataset??null}):await this.getByKey(e))?.schema??null}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug),r=this.config.resolveGame(e.gameKey);t&&this.validateAccess(t,r);let{query:s,variables:i}=a.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),n=this.cacheKey("datasets","search",i),c=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(c,{nextPageLoader:async o=>this.search({...e,after:o})})}async get(e,t,r,s){if(typeof t=="string"&&typeof r=="string"){let i=e,n=t,c=s??{};this.validateAccess(i,n);let o=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:n,datasetKey:r});return this.withCache(o,"datasets",c,async()=>{let{query:h}=a.fetchDatasetByKeys();return (await this.connection.execute(h,{publisherSlug:i,gameKey:n,datasetKey:r})).fetchDataset??null})}else {let i=e,n=t??{},c=this.cacheKey("datasets","get",{id:i});return this.withCache(c,"datasets",n,async()=>{let{query:o}=a.fetchDatasetById();return (await this.connection.execute(o,{id:i})).fetchDataset??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("datasets","getMany",{ids:e});return this.withCache(r,"datasets",t,async()=>{let{query:s}=a.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},kt=class extends f{constructor(e,t){super(e,t);}async fetch(e,t={}){let r=this.cacheKey("decks","fetch",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async get(e,t={}){let r=this.cacheKey("decks","get",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckById();return (await this.connection.execute(s,{id:e})).deck??null})}async fetchMine(e,t={}){let r=this.cacheKey("decks","fetchMine",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.myDeck();return (await this.connection.execute(s,{id:e})).myDeck??null})}async fetchBySlug(e,t,r,s={}){let i=this.cacheKey("decks","fetchBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:n}=a.fetchDeckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).fetchDeckBySlug??null})}async getBySlug(e,t,r,s={}){let i=this.cacheKey("decks","getBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:n}=a.deckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).deckBySlug??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async getByExternalRef(e,t={}){let r=this.cacheKey("decks","getByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).deckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=a.listMyDecks({first:e.first,after:e.after,includeArchived:e.includeArchived}),s=this.cacheKey("decks","listMine",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).myDecks);return new l(i,{nextPageLoader:async n=>this.listMine({...e,after:n})})}async listViewer(e={}){let{query:t,variables:r}=a.viewerDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listViewer",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).viewerDecks);return new l(i,{nextPageLoader:async n=>this.listViewer({...e,after:n})})}async listApp(e={}){this.config.requireSecretCredential("decks.listApp");let{query:t,variables:r}=a.appDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listApp",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).appDecks);return new l(i,{nextPageLoader:async n=>this.listApp({...e,after:n})})}async listPublic(e={}){let{query:t,variables:r}=a.publicDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listPublic",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).publicDecks);return new l(i,{nextPageLoader:async n=>this.listPublic({...e,after:n})})}async fetchVersion(e,t={}){let r=this.cacheKey("decks","fetchVersion",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckVersion();return (await this.connection.execute(s,{id:e})).deckVersion??null})}async listVersions(e,t={}){let{query:r,variables:s}=a.deckVersions({first:t.first,after:t.after}),i={deckId:e,...s},n=this.cacheKey("decks","listVersions",i),c=await this.withCache(n,"decks",t,async()=>(await this.connection.execute(r,i)).deckVersions);return new l(c,{nextPageLoader:async o=>this.listVersions(e,{...t,after:o})})}async preview(e,t={}){let r=this.cacheKey("decks","preview",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckPreview();return (await this.connection.execute(s,{token:e})).deckPreview??null})}async embed(e,t={}){let r=this.cacheKey("decks","embed",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckEmbed();return (await this.connection.execute(s,{token:e})).deckEmbed??null})}async access(e,t={}){let r=this.cacheKey("decks","access",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckAccess();return (await this.connection.execute(s,{token:e})).deckAccess??null})}async draftDiff(e,t={}){let r=this.cacheKey("decks","draftDiff",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckDraftDiff();return (await this.connection.execute(s,{id:e})).deckDraftDiff})}async versionDiff(e,t,r={}){let s=a.deckVersionDiffVariables(e,t),i=this.cacheKey("decks","versionDiff",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckVersionDiff();return (await this.connection.execute(n,s)).deckVersionDiff})}async validate(e,t,r={}){let s=a.deckValidateVariables(e,t),i=this.cacheKey("decks","validate",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckValidate();return (await this.connection.execute(n,s)).deckValidate})}async hydrateDeckEntries(e,t={}){let r=a.deckHydrateEntriesVariables(e),s=this.cacheKey("decks","hydrateDeckEntries",r);return this.withCache(s,"decks",t,async()=>{let{query:i}=a.deckHydrateEntries();return (await this.connection.execute(i,r)).deckHydrateEntries})}async exportDeck(e,t="SIMPLE_TEXT",r={}){let s=a.deckExportVariables(e,t),i=this.cacheKey("decks","exportDeck",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckExport();return (await this.connection.execute(n,s)).deckExport})}async sectionDefinitions(e={}){let{query:t,variables:r}=a.deckSectionDefinitions({publisherSlug:e.publisherSlug,gameKey:e.gameKey,gameId:e.gameId,rulesetKey:e.rulesetKey,rulesetVersionId:e.rulesetVersionId}),s=this.cacheKey("decks","sectionDefinitions",r);return this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).deckSectionDefinitions)}async listCollaborators(e,t={}){let r=this.cacheKey("decks","listCollaborators",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckCollaborators();return (await this.connection.execute(s,{deckId:e})).deckCollaborators})}async listPreviewTokens(e,t={}){let r=this.cacheKey("decks","listPreviewTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckPreviewTokens();return (await this.connection.execute(s,{deckId:e})).deckPreviewTokens})}async listEmbedTokens(e,t={}){let r=this.cacheKey("decks","listEmbedTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckEmbedTokens();return (await this.connection.execute(s,{deckId:e})).deckEmbedTokens})}async listAccessTokenIssuers(e,t={}){let r=this.cacheKey("decks","listAccessTokenIssuers",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckAccessTokenIssuers();return (await this.connection.execute(s,{deckId:e})).deckAccessTokenIssuers})}async listApiApplicationAccesses(e,t={}){let r=a.deckApiApplicationAccessesVariables(e,t.includeRevoked),s=this.cacheKey("decks","listApiApplicationAccesses",r);return this.withCache(s,"decks",t,async()=>{let{query:i}=a.deckApiApplicationAccesses();return (await this.connection.execute(i,r)).deckApiApplicationAccesses})}async listMyApiApplicationAccesses(e={}){let t=a.myDeckApiApplicationAccessesVariables(e.applicationId),r=this.cacheKey("decks","listMyApiApplicationAccesses",t);return this.withCache(r,"decks",e,async()=>{let{query:s}=a.myDeckApiApplicationAccesses();return (await this.connection.execute(s,t)).myDeckApiApplicationAccesses})}async create(e){let{query:t}=a.createDeck(),r=a.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=a.updateDeck(),s=a.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async updateMetadata(e,t){return this.update(e,t)}async upsertByExternalRef(e){this.config.requireSecretCredential("decks.upsertByExternalRef");let{query:t}=a.upsertDeckByExternalRef(),r=a.deckUpsertByExternalRefVariables(e);return (await this.connection.execute(t,r)).deckUpsertByExternalRef}async claim(e,t){let{query:r}=a.claimDeck(),s=a.deckClaimVariables(e,t);return (await this.connection.execute(r,s)).deckClaim}async transferOwnership(e,t){let{query:r}=a.transferDeckOwnership(),s=a.deckTransferOwnershipVariables(e,t);return (await this.connection.execute(r,s)).deckTransferOwnership}async copy(e,t){let{query:r}=a.copyDeck(),s=a.deckCopyVariables(e,t);return (await this.connection.execute(r,s)).deckCopy}async addEntry(e){let{query:t}=a.addDeckEntry(),r=a.deckEntryAddVariables(e);return (await this.connection.execute(t,r)).deckEntryAdd}async updateEntry(e,t){let{query:r}=a.updateDeckEntry(),s=a.deckEntryUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckEntryUpdate}async removeEntry(e,t){let{query:r}=a.removeDeckEntry(),s=a.deckEntryRemoveVariables(e,t);return (await this.connection.execute(r,s)).deckEntryRemove}async reorderEntries(e,t){let{query:r}=a.reorderDeckEntries(),s=a.deckEntryReorderVariables(e,t);return (await this.connection.execute(r,s)).deckEntryReorder}async replaceEntries(e,t){let{query:r}=a.replaceDeckEntries(),s=a.deckEntriesReplaceVariables(e,t);return (await this.connection.execute(r,s)).deckEntriesReplace}async importDeck(e){let{query:t}=a.importDeck(),r=a.deckImportVariables(e);return (await this.connection.execute(t,r)).deckImport}async listImportFormats(e,t={}){let{query:r,variables:s}=a.deckImportFormats({gameId:e,includeArchived:t.includeArchived,first:t.first,after:t.after}),i=this.cacheKey("decks","listImportFormats",s),n=await this.withCache(i,"decks",t,async()=>(await this.connection.execute(r,s)).deckImportFormats);return new l(n,{nextPageLoader:async c=>this.listImportFormats(e,{...t,after:c})})}async fetchImportFormat(e,t={}){let r=this.cacheKey("decks","fetchImportFormat",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckImportFormat();return (await this.connection.execute(s,{id:e})).deckImportFormat??null})}async testImportFormat(e){let{query:t}=a.deckImportFormatTest(),r=a.deckImportFormatTestVariables(e);return (await this.connection.execute(t,r)).deckImportFormatTest}async createImportFormat(e){let{query:t}=a.createDeckImportFormat(),r=a.deckImportFormatCreateVariables(e);return (await this.connection.execute(t,r)).deckImportFormatCreate}async updateImportFormat(e,t){let{query:r}=a.updateDeckImportFormat(),s=a.deckImportFormatUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckImportFormatUpdate}async archiveImportFormat(e){let{query:t}=a.archiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatArchive}async unarchiveImportFormat(e){let{query:t}=a.unarchiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatUnarchive}async delete(e){let{query:t}=a.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}async archive(e){let{query:t}=a.archiveDeck();return (await this.connection.execute(t,{id:e})).deckArchive}async restore(e){let{query:t}=a.restoreDeck();return (await this.connection.execute(t,{id:e})).deckRestore}async unpublish(e){let{query:t}=a.unpublishDeck();return (await this.connection.execute(t,{id:e})).deckUnpublish}async publish(e,t){let{query:r}=a.publishDeck(),s=a.deckPublishVariables(e,t);return (await this.connection.execute(r,s)).deckPublish}async removeInvalidEntries(e,t){let{query:r}=a.removeInvalidDeckEntries(),s=a.deckRemoveInvalidEntriesVariables(e,t);return (await this.connection.execute(r,s)).deckRemoveInvalidEntries}async upsertCollaborator(e,t,r){let{query:s}=a.upsertDeckCollaborator(),i=a.deckCollaboratorVariables(e,t,r);return (await this.connection.execute(s,i)).deckCollaboratorUpsert}async removeCollaborator(e,t){let{query:r}=a.removeDeckCollaborator(),s=a.deckCollaboratorVariables(e,t);return !!(await this.connection.execute(r,s)).deckCollaboratorRemove}async createPreviewToken(e){let{query:t}=a.createDeckPreviewToken(),r=a.deckPreviewTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckPreviewTokenCreate}async revokePreviewToken(e){let{query:t}=a.revokeDeckPreviewToken();return !!(await this.connection.execute(t,{id:e})).deckPreviewTokenRevoke}async createEmbedToken(e){let{query:t}=a.createDeckEmbedToken(),r=a.deckEmbedTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckEmbedTokenCreate}async revokeEmbedToken(e){let{query:t}=a.revokeDeckEmbedToken();return !!(await this.connection.execute(t,{id:e})).deckEmbedTokenRevoke}async createAccessTokenIssuer(e){let{query:t}=a.createDeckAccessTokenIssuer(),r=a.deckAccessTokenIssuerCreateVariables(e);return (await this.connection.execute(t,r)).deckAccessTokenIssuerCreate}async revokeAccessTokenIssuer(e){let{query:t}=a.revokeDeckAccessTokenIssuer();return !!(await this.connection.execute(t,{id:e})).deckAccessTokenIssuerRevoke}async revokeAccessTokenIssuerSigningKey(e){let{query:t}=a.revokeDeckAccessTokenIssuerSigningKey();return (await this.connection.execute(t,{id:e})).deckAccessTokenIssuerSigningKeyRevoke}async grantApiApplicationAccess(e){let{query:t}=a.grantDeckApiApplicationAccess(),r=a.deckApiApplicationAccessGrantVariables(e);return (await this.connection.execute(t,r)).deckApiApplicationAccessGrant}async revokeApiApplicationAccess(e,t){let{query:r}=a.revokeDeckApiApplicationAccess(),s=a.deckApiApplicationAccessRevokeVariables(e,t);return !!(await this.connection.execute(r,s)).deckApiApplicationAccessRevoke}async exchangeAccessToken(e){this.config.requireSecretCredential("decks.exchangeAccessToken");let{query:t}=a.exchangeDeckAccessToken(),r=a.deckAccessTokenExchangeVariables(e);return (await this.connection.execute(t,r)).deckAccessTokenExchange}async exchangeSessionToken(e){this.config.requireSecretCredential("decks.exchangeSessionToken");let{query:t}=a.exchangeDeckSessionToken(),r=a.deckSessionTokenExchangeVariables(e);return (await this.connection.execute(t,r)).deckSessionTokenExchange}async revokeAccessToken(e){this.config.requireSecretCredential("decks.revokeAccessToken");let{query:t}=a.revokeDeckAccessToken();return !!(await this.connection.execute(t,{id:e})).deckAccessTokenRevoke}async hydrateEntries(e){if(e.entries.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=e.entries.map(o=>o.identifier),i=this.cacheKey("decks","hydrateEntries",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s}),n=await this.withCache(i,"decks",e,async()=>{let{query:o}=a.fetchRecordsByIdentifier();return (await this.connection.execute(o,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),c=It(n,s,e.identifierField);return e.entries.map(o=>({...o,record:c.get(o.identifier)??null}))}};function It(e,t,r){let s=new Set(t),i=new Map;for(let n of e){let c=r?n.data[r]:Object.values(n.data).find(h=>s.has(String(h)));if(c==null)continue;let o=String(c);s.has(o)&&(i.set(o,n),s.delete(o));}return i}var bt=class extends f{constructor(e,t){super(e,t);}async list(e){let t=U(e.filter),{query:r,variables:s}=a.listDatasetRecords({datasetId:e.datasetId,filter:t,orderBy:e.orderBy,first:e.first,after:e.after,last:e.last,before:e.before,validateSchema:e.validateSchema}),i=this.cacheKey("records","list",s),n=await this.withCache(i,"records",e,async()=>(await this.connection.execute(r,s)).datasetRecords);return new l(n,{nextPageLoader:async c=>this.list({...e,after:c})})}async getByDatasetIdentifier(e){let t=this.cacheKey("records","getByDatasetIdentifier",{datasetId:e.datasetId,identifier:e.identifier,includePricing:e.includePricing??false});return this.withCache(t,"records",e,async()=>{let{query:r,variables:s}=a.datasetRecord({datasetId:e.datasetId,identifier:e.identifier,includePricing:e.includePricing});return (await this.connection.execute(r,s)).datasetRecord??null})}async upsertBatch(e){this.config.requireSecretCredential("records.upsertBatch");let{query:t}=a.upsertDatasetRecords();return (await this.connection.execute(t,a.datasetRecordsUpsertVariables(e))).datasetRecordsUpsert}async deleteBatch(e){this.config.requireSecretCredential("records.deleteBatch");let{query:t}=a.deleteDatasetRecords();return (await this.connection.execute(t,a.datasetRecordsDeleteVariables(e))).datasetRecordsDelete}async getDeleteJob(e,t={}){let r=this.cacheKey("records","getDeleteJob",{id:e});return this.withCache(r,"records",t,async()=>{let{query:s}=a.datasetRecordDeleteJob();return (await this.connection.execute(s,{id:e})).datasetRecordDeleteJob??null})}async listDeleteJobs(e,t={}){let{query:r,variables:s}=a.datasetRecordDeleteJobs({publisherId:e,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("records","listDeleteJobs",s),n=await this.withCache(i,"records",t,async()=>(await this.connection.execute(r,s)).datasetRecordDeleteJobs);return new l(n,{nextPageLoader:async c=>this.listDeleteJobs(e,{...t,after:c})})}async waitForDeleteJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getDeleteJob(e,{cache:false});if(!n)throw new Error(`Delete job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for delete job '${e}'`);await new Promise(c=>setTimeout(c,r));}}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=U(e.filter),{query:i,variables:n}=a.searchRecords({publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,filter:s,search:e.search,orderBy:e.orderBy,resolveLinks:e.resolveLinks,first:e.first,after:e.after,validateSchema:e.validateSchema,includePricing:e.includePricing}),c=this.cacheKey("records","search",{...n,includePricing:e.includePricing??false}),o=await this.withCache(c,"records",e,async()=>(await this.connection.execute(i,n)).searchRecords);return new l(o,{nextPageLoader:async h=>this.search({...e,after:h})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=a.fetchRecordById({includePricing:t.includePricing});return (await this.connection.execute(s,{id:e})).fetchRecord??null})}async getByIdentifier(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=a.fetchRecordByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier})).fetchRecordByIdentifier??null})}async getManyByIdentifier(e){if(e.identifiers.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getManyByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=a.fetchRecordsByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers})).fetchRecordsByIdentifier??[]})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("records","getMany",{ids:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=a.fetchRecords({includePricing:t.includePricing});return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},$t=class extends f{constructor(e,t){super(e,t);}async datasets(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let{query:s,variables:i}=a.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),n=this.cacheKey("rules","datasets",i),c=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(c,{nextPageLoader:async o=>this.datasets({...e,after:o})})}async list(e={}){return this.searchRuleRecords("rules",e)}async formats(e={}){return this.searchRuleRecords(e.datasetKey??"formats",e)}async searchRuleRecords(e,t){let r=this.resolvePublisher(t.publisherSlug),s=this.resolveGame(t.gameKey),i=t.datasetKey??e;this.validateAccess(r,s);let n=U(t.filter),{query:c,variables:o}=a.searchRecords({publisherSlug:r,gameKey:s,datasetKey:i,filter:n,search:t.search,orderBy:t.orderBy,resolveLinks:t.resolveLinks,first:t.first,after:t.after,validateSchema:t.validateSchema}),h=this.cacheKey("rules","records",o),w=await this.withCache(h,"records",t,async()=>(await this.connection.execute(c,o)).searchRecords);return new l(w,{nextPageLoader:async X=>this.searchRuleRecords(e,{...t,after:X})})}},vt=class extends f{constructor(e,t){super(e,t);}async list(e){let{query:t,variables:r}=a.deckImportFormats({publisherId:e.publisherId,gameId:e.gameId,includeArchived:e.includeArchived,first:e.first,after:e.after}),s=this.cacheKey("importFormats","list",r),i=await this.withCache(s,"importFormats",e,async()=>(await this.connection.execute(t,r)).deckImportFormats);return new l(i,{nextPageLoader:async n=>this.list({...e,after:n})})}async get(e,t={}){let r=this.cacheKey("importFormats","get",{id:e});return this.withCache(r,"importFormats",t,async()=>{let{query:s}=a.deckImportFormat();return (await this.connection.execute(s,{id:e})).deckImportFormat??null})}async getByKey(e){let t=this.cacheKey("importFormats","getByKey",{gameId:e.gameId,formatKey:e.key});return this.withCache(t,"importFormats",e,async()=>{let{query:r}=a.deckImportFormat();return (await this.connection.execute(r,{gameId:e.gameId,key:e.key})).deckImportFormat??null})}async test(e){let{query:t}=a.deckImportFormatTest();return (await this.connection.execute(t,a.deckImportFormatTestVariables(e))).deckImportFormatTest}async create(e){this.config.requireSecretCredential("importFormats.create");let{query:t}=a.createDeckImportFormat();return (await this.connection.execute(t,a.deckImportFormatCreateVariables(e))).deckImportFormatCreate}async update(e,t){this.config.requireSecretCredential("importFormats.update");let{query:r}=a.updateDeckImportFormat();return (await this.connection.execute(r,a.deckImportFormatUpdateVariables(e,t))).deckImportFormatUpdate}async archive(e){this.config.requireSecretCredential("importFormats.archive");let{query:t}=a.archiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatArchive}async unarchive(e){this.config.requireSecretCredential("importFormats.unarchive");let{query:t}=a.unarchiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatUnarchive}},Dt=class extends f{constructor(e,t){super(e,t);}async preview(e){let{query:t}=a.datasetImportPreview();return (await this.connection.execute(t,a.datasetImportPreviewVariables(e))).datasetImportPreview}async validate(e){let{query:t}=a.datasetImportValidate();return (await this.connection.execute(t,a.datasetImportValidateVariables(e))).datasetImportValidate}async run(e){if(this.config.requireSecretCredential("imports.run"),"fileId"in e&&e.fileId){let{query:s}=a.datasetImportFromFile();return (await this.connection.execute(s,a.datasetImportFromFileVariables(e))).datasetImportFromFile}if("sourceUrl"in e&&e.sourceUrl){let{query:s}=a.datasetImportFromUrl();return (await this.connection.execute(s,a.datasetImportFromUrlVariables(e))).datasetImportFromUrl}let{query:t}=a.datasetImportFromPayload();return (await this.connection.execute(t,a.datasetImportFromPayloadVariables(e))).datasetImportFromPayload}async getJob(e,t={}){let r=this.cacheKey("imports","getJob",{id:e});return this.withCache(r,"imports",t,async()=>{let{query:s}=a.importJob();return (await this.connection.execute(s,{id:e})).importJob??null})}async listJobs(e,t={}){let{query:r,variables:s}=a.importJobs({publisherId:e,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("imports","listJobs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).importJobs);return new l(n,{nextPageLoader:async c=>this.listJobs(e,{...t,after:c})})}async cancelJob(e){this.config.requireSecretCredential("imports.cancelJob");let{query:t}=a.importJobCancel();return (await this.connection.execute(t,{id:e})).importJobCancel}async listJobLogs(e,t={}){let{query:r,variables:s}=a.importJobLogs({importJobId:e,level:t.level,datasetKey:t.datasetKey,first:t.first,after:t.after}),i=this.cacheKey("imports","listJobLogs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).importJob?.logs??wt());return new l(n,{nextPageLoader:async c=>this.listJobLogs(e,{...t,after:c})})}async waitForJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getJob(e,{cache:false});if(!n)throw new Error(`Import job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for import job '${e}'`);await new Promise(c=>setTimeout(c,r));}}async previewGame(e){let{query:t}=a.gameImportPreview();return (await this.connection.execute(t,a.gameImportPreviewVariables(e))).gameImportPreview}async runGame(e){if(this.config.requireSecretCredential("imports.runGame"),"fileId"in e&&e.fileId){let{query:s}=a.gameImportFromFile();return (await this.connection.execute(s,a.gameImportFromFileVariables(e))).gameImportFromFile}if("sourceUrl"in e&&e.sourceUrl){let{query:s}=a.gameImportFromUrl();return (await this.connection.execute(s,a.gameImportFromUrlVariables(e))).gameImportFromUrl}let{query:t}=a.gameImportFromPayload();return (await this.connection.execute(t,a.gameImportFromPayloadVariables(e))).gameImportFromPayload}async getGameJob(e,t={}){let r=this.cacheKey("imports","getGameJob",{id:e});return this.withCache(r,"imports",t,async()=>{let{query:s}=a.gameImportJob();return (await this.connection.execute(s,{id:e})).gameImportJob??null})}async listGameJobs(e,t={}){let{query:r,variables:s}=a.gameImportJobs({gameId:e,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("imports","listGameJobs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).gameImportJobs);return new l(n,{nextPageLoader:async c=>this.listGameJobs(e,{...t,after:c})})}async cancelGameJob(e){this.config.requireSecretCredential("imports.cancelGameJob");let{query:t}=a.gameImportJobCancel();return (await this.connection.execute(t,{id:e})).gameImportJobCancel}async waitForGameJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getGameJob(e,{cache:false});if(!n)throw new Error(`Game import job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for game import job '${e}'`);await new Promise(c=>setTimeout(c,r));}}};function wt(){return {totalCount:0,pageInfo:{hasNextPage:false,hasPreviousPage:false,startCursor:null,endCursor:null},edges:[]}}var St=class extends f{constructor(e,t){super(e,t);}async run(e){this.config.requireSecretCredential("exports.run");let{query:t}=a.datasetExport();return (await this.connection.execute(t,a.datasetExportVariables(e))).datasetExport}async create(e){return this.run(e)}async getJob(e,t={}){let r=this.cacheKey("exports","getJob",{id:e});return this.withCache(r,"exports",t,async()=>{let{query:s}=a.exportJob();return (await this.connection.execute(s,{id:e})).exportJob??null})}async listJobs(e,t={}){let{query:r,variables:s}=a.exportJobs({publisherId:e,gameId:t.gameId,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("exports","listJobs",s),n=await this.withCache(i,"exports",t,async()=>(await this.connection.execute(r,s)).exportJobs);return new l(n,{nextPageLoader:async c=>this.listJobs(e,{...t,after:c})})}async refreshUrl(e){let{query:t}=a.exportJobRefreshUrl();return (await this.connection.execute(t,{id:e})).exportJobRefreshUrl}async cancel(e){this.config.requireSecretCredential("exports.cancel");let{query:t}=a.exportJobCancel();return (await this.connection.execute(t,{id:e})).exportJobCancel}async waitForJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getJob(e,{cache:false});if(!n)throw new Error(`Export job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for export job '${e}'`);await new Promise(c=>setTimeout(c,r));}}},At=class extends f{constructor(e,t){super(e,t);}async get(e,t={}){let r=this.cacheKey("files","get",{id:e});return this.withCache(r,"files",t,async()=>{let{query:s}=a.file();return (await this.connection.execute(s,{id:e})).file??null})}async requestUpload(e){this.config.requireSecretCredential("files.requestUpload");let{query:t}=a.fileUploadRequest();return (await this.connection.execute(t,a.fileUploadRequestVariables(e))).fileUploadRequest}async confirmUpload(e){this.config.requireSecretCredential("files.confirmUpload");let{query:t}=a.fileUploadConfirm();return (await this.connection.execute(t,{id:e})).fileUploadConfirm}async upload(e){let t=e.size??xt(e.body);if(!t||t<=0)throw new Error("files.upload requires a positive size or a body with an inferable size");let r=await this.requestUpload({filename:e.filename,contentType:e.contentType,size:t,isPublic:e.isPublic??false,entityType:e.entityType??Tt(e.purpose),entityId:e.entityId,publisherId:e.publisherId,datasetId:e.datasetId});return await Et(r.uploadUrl,e.contentType,e.body),this.confirmUpload(r.file.id)}async delete(e){this.config.requireSecretCredential("files.delete");let{query:t}=a.fileDelete();return !!(await this.connection.execute(t,{id:e})).fileDelete}};async function Et(e,t,r){let s=globalThis.fetch;if(!s)throw new Error("files.upload requires a runtime with fetch support");let i=await s(e,{method:"PUT",headers:{"Content-Type":t},body:r});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`File upload failed with ${i.status} ${i.statusText}${n?`: ${n}`:""}`)}}function xt(e){if(typeof e=="string")return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;let t=e;if(typeof t?.size=="number")return t.size;if(typeof t?.byteLength=="number")return t.byteLength;if(typeof t?.length=="number")return t.length}function Tt(e){if(!(!e||e==="scan_image"))return e==="import"?"import":e==="scan_template_example"?"scan_template_example":e}var qt=class extends f{constructor(e,t){super(e,t);}async createUploadSession(e){let t=this.resolveCreateUploadSessionInput(e),{query:r}=a.createScanUploadSession();return (await this.connection.execute(r,a.createScanUploadSessionVariables(t))).createScanUploadSession}async confirmUpload(e){let t=this.resolveConfirmUploadInput(e),{query:r}=a.confirmScanUpload();return (await this.connection.execute(r,a.confirmScanUploadVariables(t))).confirmScanUpload}async createJob(e){let t=this.resolveCreateJobInput(e),{query:r}=a.createScanJob();return (await this.connection.execute(r,a.createScanJobVariables(t))).createScanJob}async getJob(e,t={}){let r=this.cacheKey("scans","getJob",{id:e});return this.withCache(r,"scans",t,async()=>{let{query:s}=a.scanJob();return (await this.connection.execute(s,{id:e})).scanJob??null})}async pollJob(e,t={}){let r=t.timeoutMs??3e5,s=Math.max(t.backoffFactor??1.5,1),i=t.maxIntervalMs??1e4,n=Date.now(),c=Math.max(t.intervalMs??1e3,1);for(;;){Kt(t.signal);let o=await this.getJob(e,{cache:false});if(!o)throw new Error(`Scan job '${e}' was not found`);if(Rt(o.status))return o;let h=Date.now()-n,w=r-h;if(w<=0)throw new Error(`Timed out waiting for scan job '${e}'`);await Ct(Math.min(c,w)),c=Math.min(Math.ceil(c*s),i);}}async submitFeedback(e){let{query:t}=a.submitScanFeedback();return (await this.connection.execute(t,a.submitScanFeedbackVariables(e))).submitScanFeedback}async metrics(e){let t=this.resolveMetricsInput(e),{query:r}=a.scanMetrics();return (await this.connection.execute(r,a.scanMetricsVariables(t))).scanMetrics}async verifyWebhookSignature(e){let t=Ut(),r=await t.importKey("raw",ve(e.secret),{name:"HMAC",hash:"SHA-256"},false,["sign"]),s=await t.sign("HMAC",r,Ft(e.body)),i=`sha256=${Pt(new Uint8Array(s))}`;return Lt(e.signature.trim().toLowerCase(),i)}resolveCreateJobInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveCreateUploadSessionInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveConfirmUploadInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveMetricsInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}};function Rt(e){let t=e.toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}async function Ct(e){return new Promise(t=>setTimeout(t,e))}function Kt(e){if(e&&(e.throwIfAborted&&e.throwIfAborted(),e.aborted))throw new Error("Scan job polling aborted")}function Ut(){let t=globalThis.crypto?.subtle;if(!t)throw new Error("Web Crypto HMAC support is not available in this runtime");return t}function Ft(e){return typeof e=="string"?ve(e):e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function ve(e){return new TextEncoder().encode(e)}function Pt(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Lt(e,t){let r=Math.max(e.length,t.length),s=e.length^t.length;for(let i=0;i<r;i++)s|=(e.charCodeAt(i)||0)^(t.charCodeAt(i)||0);return s===0}var _t=class extends f{constructor(e,t){super(e,t);}async resolve(e){let t=this.resolveTemplateScope(e),r=this.cacheKey("scanTemplates","resolve",{...t});return this.withCache(r,"scanTemplates",e,async()=>{let{query:s}=a.resolveScanTemplate();return (await this.connection.execute(s,a.resolveScanTemplateVariables(t))).resolveScanTemplate})}async list(e){let t=this.resolveListScope(e),r=this.cacheKey("scanTemplates","list",{...t});return this.withCache(r,"scanTemplates",e,async()=>{let{query:s}=a.scanTemplates();return (await this.connection.execute(s,a.scanTemplatesVariables(t))).scanTemplates?.templates??[]})}async create(e){this.config.requireSecretCredential("scanTemplates.create");let t=this.resolveSaveInput(e),{query:r}=a.createScanTemplate();return (await this.connection.execute(r,a.createScanTemplateVariables(t))).createScanTemplate}async update(e,t){this.config.requireSecretCredential("scanTemplates.update");let r=typeof e=="string"?e:e.id,s=typeof e=="string"?t:Vt(e);if(!s)throw new Error("scan template input is required");let i=this.resolveSaveInput(s),{query:n}=a.updateScanTemplate();return (await this.connection.execute(n,a.updateScanTemplateVariables(r,i))).updateScanTemplate}async preview(e){let t=this.resolvePreviewInput(e),{query:r}=a.previewScanTemplate();return (await this.connection.execute(r,a.previewScanTemplateVariables(t))).previewScanTemplate}resolveTemplateScope(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,templateId:e.templateId}}resolveListScope(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,includeArchived:e.includeArchived}}resolveSaveInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolvePreviewInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}};function Vt(e){let t={...e};return delete t.id,t}var De=class we{config;connection;publishers;games;datasets;records;decks;rules;importFormats;imports;exports;files;scans;scanTemplates;constructor(t={}){this.config=new nt(t),this.connection=new dt(this.config),this.publishers=new pt(this.connection,this.config),this.games=new mt(this.connection,this.config),this.datasets=new gt(this.connection,this.config),this.records=new bt(this.connection,this.config),this.decks=new kt(this.connection,this.config),this.rules=new $t(this.connection,this.config),this.importFormats=new vt(this.connection,this.config),this.imports=new Dt(this.connection,this.config),this.exports=new St(this.connection,this.config),this.files=new At(this.connection,this.config),this.scans=new qt(this.connection,this.config),this.scanTemplates=new _t(this.connection,this.config);}async me(){let{query:t}=a.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return lt()}withConfig(t){let r=this.config.merge(t);return new we({apiKey:r.configApiKey(),publishableKey:r.publishableKey,secretKey:r.secretKey,accessToken:r.accessToken,environment:r.environment,endpoint:r.endpoint,timeout:r.timeout,openTimeout:r.openTimeout,defaultPublisher:r.defaultPublisher,defaultGame:r.defaultGame,allowedPublishers:r.allowedPublishers,allowedGames:r.allowedGames,logger:r.logger,logLevel:r.logLevel,retryOnRateLimit:r.retryOnRateLimit,maxRetries:r.maxRetries,retryOnNetworkError:r.retryOnNetworkError,maxNetworkRetries:r.maxNetworkRetries,retryBaseDelay:r.retryBaseDelay,retryMaxDelay:r.retryMaxDelay,cache:r.cache,cacheTtl:r.cacheTtl,cacheTtls:r.cacheTtls})}};var W=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";this.storage=r==="sessionStorage"?globalThis.sessionStorage:globalThis.localStorage,this.prefix=t.prefix??"carddb:";}get(t){try{let r=this.storage.getItem(this.prefix+t);if(!r)return null;let s=JSON.parse(r);return s.expiresAt!==null&&Date.now()>s.expiresAt?(this.storage.removeItem(this.prefix+t),null):s.value}catch{return this.storage.removeItem(this.prefix+t),null}}set(t,r,s){try{let i={value:r,expiresAt:s!==void 0?Date.now()+s*1e3:null};this.storage.setItem(this.prefix+t,JSON.stringify(i));}catch(i){console.warn("[CardDB] Failed to write to cache:",i);}}delete(t){this.storage.removeItem(this.prefix+t);}clear(){let t=[];for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t.push(s);}for(let r of t)this.storage.removeItem(r);}has(t){return this.get(t)!==null}get size(){let t=0;for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t++;}return t}cleanup(){let t=Date.now(),r=[];for(let s=0;s<this.storage.length;s++){let i=this.storage.key(s);if(i&&i.startsWith(this.prefix))try{let n=this.storage.getItem(i);if(n){let c=JSON.parse(n);c.expiresAt!==null&&t>c.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var Se=class extends De{constructor(t={}){if("apiKey"in t&&t.apiKey!==void 0)throw new $("apiKey is not accepted in browsers; use publishableKey or accessToken");if("secretKey"in t&&t.secretKey!==void 0)throw new $("secretKey is server-only; use publishableKey or accessToken in browsers");super(t);}};
1932
- export{M as AuthenticationError,f as BaseResource,W as BrowserCache,Se as CardDBClient,y as CardDBError,l as Collection,nt as Configuration,dt as Connection,x as ConnectionError,tt as DEFAULT_CACHE_TTL,Qe as DEFAULT_ENDPOINT,st as DEFAULT_MAX_NETWORK_RETRIES,rt as DEFAULT_MAX_RETRIES,et as DEFAULT_OPEN_TIMEOUT,it as DEFAULT_RETRY_BASE_DELAY,at as DEFAULT_RETRY_MAX_DELAY,Ze as DEFAULT_TIMEOUT,gt as DatasetsResource,kt as DecksResource,St as ExportsResource,At as FilesResource,Ae as FilterBuilder,mt as GamesResource,ce as GraphQLError,vt as ImportFormatsResource,Dt as ImportsResource,Mt as LinkResolutionError,Bt as NotFoundError,pt as PublishersResource,a as QueryBuilder,K as RateLimitError,bt as RecordsResource,$ as RestrictedError,$t as RulesResource,_t as ScanTemplatesResource,qt as ScansResource,O as ServerError,G as TimeoutError,J as ValidationError,ht as cacheKey,Wt as contains,Jt as eq,lt as getRateLimitInfo,fr as getSDKVersion,ut as getUserAgent,Ot as gt,Nt as gte,Qt as ilike,er as isNotNull,Zt as isNull,Xt as like,jt as lt,Ht as lte,Gt as neq,zt as notWithin,yt as readCache,U as resolveFilter,Yt as within,ft as writeCache};//# sourceMappingURL=index.js.map
1944
+ `}}},l=class{totalCount;pageInfo;items;nextPageLoader;constructor(e,t={}){this.totalCount=e.totalCount,this.pageInfo=e.pageInfo,this.items=e.edges.map(r=>t.itemTransformer?t.itemTransformer(r.node):r.node),this.nextPageLoader=t.nextPageLoader;}get hasNextPage(){return this.pageInfo.hasNextPage}get hasPreviousPage(){return this.pageInfo.hasPreviousPage}get endCursor(){return this.pageInfo.endCursor}get startCursor(){return this.pageInfo.startCursor}get length(){return this.items.length}get isEmpty(){return this.items.length===0}get first(){return this.items[0]}get last(){return this.items[this.items.length-1]}async nextPage(){if(!this.hasNextPage)return null;if(!this.nextPageLoader)throw new Error("No next page loader configured");return this.endCursor?this.nextPageLoader(this.endCursor):null}async*[Symbol.asyncIterator](){let e=this;for(;e;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage();}}async forEach(e){let t=0;for await(let r of this)await e(r,t++);}async map(e){let t=[],r=0;for await(let s of this)t.push(await e(s,r++));return t}async filter(e){let t=[],r=0;for await(let s of this)await e(s,r++)&&t.push(s);return t}async find(e){let t=0;for await(let r of this)if(await e(r,t++))return r}async take(e){let t=[];for await(let r of this){if(t.length>=e)break;t.push(r);}return t}async toArray(){let e=[];for await(let t of this)e.push(t);return e}async*batches(){let e=this;for(;e&&(e.items.length>0&&(yield e.items),!!e.hasNextPage);)e=await e.nextPage();}each(){return this}};var Qe="https://carddb.dev/query",Ze=3e4,et=1e4,tt=300,rt=3,st=2,it=1e3,at=3e4,nt=class Ie{apiKey;publishableKey;secretKey;accessToken;legacyApiKey;environment;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.legacyApiKey=t.apiKey,this.publishableKey=t.publishableKey,this.secretKey=t.secretKey,this.accessToken=t.accessToken,this.apiKey=t.apiKey??t.publishableKey??t.secretKey,this.environment=t.environment,this.endpoint=t.endpoint??Qe,this.timeout=t.timeout??Ze,this.openTimeout=t.openTimeout??et,this.defaultPublisher=t.defaultPublisher,this.defaultGame=t.defaultGame,this.allowedPublishers=t.allowedPublishers,this.allowedGames=t.allowedGames,this.logger=t.logger,this.logLevel=t.logLevel??"info",this.retryOnRateLimit=t.retryOnRateLimit??false,this.maxRetries=t.maxRetries??rt,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??st,this.retryBaseDelay=t.retryBaseDelay??it,this.retryMaxDelay=t.retryMaxDelay??at,this.cache=t.cache,this.cacheTtl=t.cacheTtl??tt,this.cacheTtls=t.cacheTtls??{};}calculateRetryDelay(t){let r=this.retryBaseDelay*Math.pow(2,t),s=Math.min(r,this.retryMaxDelay),i=s*.25*(Math.random()*2-1);return Math.round(s+i)}cacheTtlFor(t){return this.cacheTtls[t]??this.cacheTtl}resolvePublisher(t){return t??this.defaultPublisher}resolveGame(t){return t??this.defaultGame}validatePublisher(t){if(this.allowedPublishers&&!this.allowedPublishers.includes(t))throw new $(`Publisher '${t}' is not in the allowed publishers list`)}validateGame(t,r){if(!this.allowedGames)return;let s=this.allowedGames[t];if(s&&!s.includes(r))throw new $(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}requireSecretCredential(t){if(!(!this.accessToken&&(this.legacyApiKey||this.secretKey&&!this.publishableKey)))throw new $(`${t} requires a server-side secretKey or legacy apiKey credential`)}requestApiKey(){return this.legacyApiKey??this.publishableKey??this.secretKey}configApiKey(){return this.legacyApiKey}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new Ie({apiKey:t.apiKey??this.legacyApiKey,publishableKey:t.publishableKey??this.publishableKey,secretKey:t.secretKey??this.secretKey,accessToken:t.accessToken??this.accessToken,environment:t.environment??this.environment,endpoint:t.endpoint??this.endpoint,timeout:t.timeout??this.timeout,openTimeout:t.openTimeout??this.openTimeout,defaultPublisher:t.defaultPublisher??this.defaultPublisher,defaultGame:t.defaultGame??this.defaultGame,allowedPublishers:t.allowedPublishers??this.allowedPublishers,allowedGames:t.allowedGames??this.allowedGames,logger:t.logger??this.logger,logLevel:t.logLevel??this.logLevel,retryOnRateLimit:t.retryOnRateLimit??this.retryOnRateLimit,maxRetries:t.maxRetries??this.maxRetries,retryOnNetworkError:t.retryOnNetworkError??this.retryOnNetworkError,maxNetworkRetries:t.maxNetworkRetries??this.maxNetworkRetries,retryBaseDelay:t.retryBaseDelay??this.retryBaseDelay,retryMaxDelay:t.retryMaxDelay??this.retryMaxDelay,cache:t.cache??this.cache,cacheTtl:t.cacheTtl??this.cacheTtl,cacheTtls:t.cacheTtls??this.cacheTtls})}},be="0.4.1";function ct(){if(typeof globalThis<"u"&&"Bun"in globalThis){let e=globalThis.Bun&&typeof globalThis.Bun=="object"&&globalThis.Bun.version;return {name:"bun",version:typeof e=="string"?e:"unknown"}}if(typeof globalThis<"u"&&"Deno"in globalThis){let e=globalThis.Deno&&typeof globalThis.Deno=="object"&&globalThis.Deno.version&&typeof globalThis.Deno.version=="object"&&globalThis.Deno.version.deno;return {name:"deno",version:typeof e=="string"?e:"unknown"}}return typeof process<"u"&&process.versions&&process.versions.node?{name:"node",version:process.versions.node}:typeof navigator<"u"&&navigator.userAgent?ot(navigator.userAgent):{name:"unknown",version:"unknown"}}function ot(e){let t=e.match(/Edg\/(\d+(?:\.\d+)*)/);if(t)return {name:"edge",version:t[1]};let r=e.match(/Chrome\/(\d+(?:\.\d+)*)/);if(r&&!e.includes("Edg/"))return {name:"chrome",version:r[1]};let s=e.match(/Firefox\/(\d+(?:\.\d+)*)/);if(s)return {name:"firefox",version:s[1]};let i=e.match(/Version\/(\d+(?:\.\d+)*).*Safari/);return i?{name:"safari",version:i[1]}:{name:"browser",version:"unknown"}}function ut(){let e=ct();return `CardDB-SDK/js/${be} (${e.name}/${e.version})`}function fr(){return be}var $e=null;function lt(){return $e}var dt=class{config;constructor(e){this.config=e;}async execute(e,t={}){let r=this.extractOperationName(e),s=0,i=0;for(;;)try{let n=Date.now();this.logRequest(r,t);let c=await this.fetch(e,t),o=Date.now()-n,h=await this.handleResponse(c);return this.logResponse(r,o),h}catch(n){if(n instanceof K&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let c=n.retryAfter??60;this.logRateLimitRetry(r,s,c),await this.sleep(c*1e3);continue}if(this.isRetryableNetworkError(n)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let c=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,c,n),i++,await this.sleep(c);continue}if(n instanceof O&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let c=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,c,n),i++,await this.sleep(c);continue}throw n}}isRetryableNetworkError(e){return e instanceof x||e instanceof G}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout),i=this.config.requestApiKey();try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":ut(),...this.config.accessToken?{Authorization:`Bearer ${this.config.accessToken}`}:{},...!this.config.accessToken&&i?{"X-API-Key":i}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(n){throw n instanceof Error?n.name==="AbortError"?(this.logError("Request timed out"),new G("Request timed out")):(this.logError(`Connection failed: ${n.message}`),new x(`Connection failed: ${n.message}`)):new x("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new M("Invalid or missing API key");case 429:return this.handleRateLimitResponse(e);default:if(e.status>=400&&e.status<500)return this.handleClientError(e);if(e.status>=500){let t=await this.parseBody(e);throw new O(`Server error (${e.status})`,{status:e.status,response:t})}throw new y(`Unexpected response status: ${e.status}`)}}async handleSuccessResponse(e){let t=await this.parseBody(e);return t.errors&&t.errors.length>0&&this.handleGraphQLErrors(t.errors,t),t.data??{}}handleGraphQLErrors(e,t){let r=e[0],s=r.message||"GraphQL error";switch(r.extensions?.code){case "UNAUTHENTICATED":throw new M(s,t);case "RATE_LIMITED":throw new K(s,{response:t});case "NOT_FOUND":throw new y(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new J(s,{errors:e,response:t});default:throw new ce(s,{errors:e,response:t})}}async handleRateLimitResponse(e){let t=parseInt(e.headers.get("Retry-After")??"60",10),r=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,i=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null,n=i?new Date(i*1e3):null,c=await this.parseBody(e);throw new K("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:n,response:c})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new J(r,{response:t})}async parseBody(e){try{return await e.json()}catch{return {raw:await e.text()}}}extractRateLimitInfo(e){let t=parseInt(e.headers.get("X-RateLimit-Limit")??"",10)||null,r=parseInt(e.headers.get("X-RateLimit-Remaining")??"",10)||null,s=parseInt(e.headers.get("X-RateLimit-Reset")??"",10)||null;$e={limit:t,remaining:r,reset:s};}extractOperationName(e){let t=e.match(/(?:query|mutation)\s+(\w+)/);return t?t[1]:"Unknown"}sleep(e){return new Promise(t=>setTimeout(t,e))}logRequest(e,t){!this.config.logger||!this.config.shouldLog("debug")||this.config.logger.debug(`[CardDB] Executing ${e}`,{variables:t});}logResponse(e,t){!this.config.logger||!this.config.shouldLog("info")||this.config.logger.info(`[CardDB] ${e} completed in ${t}ms`);}logRateLimitRetry(e,t,r){!this.config.logger||!this.config.shouldLog("warn")||this.config.logger.warn(`[CardDB] Rate limited on ${e}, retry ${t}/${this.config.maxRetries} after ${r}s`);}logNetworkRetry(e,t,r,s){if(!this.config.logger||!this.config.shouldLog("warn"))return;let i=s instanceof Error?s.name:"Unknown";this.config.logger.warn(`[CardDB] ${i} on ${e}, retry ${t}/${this.config.maxNetworkRetries} after ${r}ms`);}logError(e){!this.config.logger||!this.config.shouldLog("error")||this.config.logger.error(`[CardDB] ${e}`);}};function ht(e,t,r){let s=Object.entries(r).filter(([,i])=>i!==void 0).sort(([i],[n])=>i.localeCompare(n)).map(([i,n])=>`${i}=${JSON.stringify(n)}`).join("&");return `carddb:${e}:${t}:${s}`}async function yt(e,t){let r=e.get(t);return r}async function ft(e,t,r,s){let i=e.set(t,r,s);i instanceof Promise&&await i;}var f=class{connection;config;constructor(e,t){this.connection=e,this.config=t;}resolvePublisher(e){let t=this.config.resolvePublisher(e);if(!t)throw new Error("publisher_slug is required (no default configured)");return t}resolveGame(e){let t=this.config.resolveGame(e);if(!t)throw new Error("game_key is required (no default configured)");return t}validateAccess(e,t){this.config.validateAccess(e,t);}async withCache(e,t,r,s){let i=r.cache??!!this.config.cache,n=this.config.cache;if(!i||!n)return s();let c=await yt(n,e);if(c!==null)return c;let o=await s();if(o!=null){let h=this.config.cacheTtlFor(t);await ft(n,e,o,h);}return o}cacheKey(e,t,r){return ht(e,t,r)}},pt=class extends f{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=a.searchPublishers({search:e.search,first:e.first,after:e.after}),s=this.cacheKey("publishers","search",r),i=await this.withCache(s,"publishers",e,async()=>(await this.connection.execute(t,r)).searchPublishers);return new l(i,{nextPageLoader:async n=>this.search({...e,after:n})})}async get(e,t={}){let r=this.isUUID(e),s=this.cacheKey("publishers","get",{[r?"id":"slug"]:e});return this.withCache(s,"publishers",t,async()=>{if(r){let{query:i}=a.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=a.fetchPublisherBySlug();return (await this.connection.execute(i,{slug:e})).fetchPublisher??null}})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("publishers","getMany",{slugs:e});return this.withCache(r,"publishers",t,async()=>{let{query:s}=a.fetchPublishers();return (await this.connection.execute(s,{slugs:e})).fetchPublishers??[]})}isUUID(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},mt=class extends f{constructor(e,t){super(e,t);}async list(e,t={}){let{query:r,variables:s}=a.listGames({publisherId:e,first:t.first,after:t.after,includeArchived:t.includeArchived}),i=this.cacheKey("games","list",s),n=await this.withCache(i,"games",t,async()=>(await this.connection.execute(r,s)).games);return new l(n,{nextPageLoader:async c=>this.list(e,{...t,after:c})})}async getByKey(e){let t=this.cacheKey("games","getByKey",{publisherId:e.publisherId,publisherSlug:e.publisherSlug,gameKey:e.gameKey});return this.withCache(t,"games",e,async()=>{let{query:r,variables:s}=a.game(e);return (await this.connection.execute(r,s)).game??null})}async getBySlug(e){let t=this.cacheKey("games","getBySlug",{publisherId:e.publisherId,publisherSlug:e.publisherSlug,gameSlug:e.gameSlug});return this.withCache(t,"games",e,async()=>{let{query:r,variables:s}=a.game(e);return (await this.connection.execute(r,s)).game??null})}async create(e){this.config.requireSecretCredential("games.create");let{query:t}=a.createGame();return (await this.connection.execute(t,a.gameCreateVariables(e))).gameCreate}async update(e,t){this.config.requireSecretCredential("games.update");let{query:r}=a.updateGame();return (await this.connection.execute(r,a.gameUpdateVariables(e,t))).gameUpdate}async getRegions(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=a.gameScanRegionsVariables(t,r,e.includeInactive),i=this.cacheKey("games","getRegions",s);return this.withCache(i,"games",e,async()=>{let{query:n}=a.gameScanRegions();return (await this.connection.execute(n,s)).gameScanRegions??[]})}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=a.searchGames({publisherSlug:t,search:e.search,first:e.first,after:e.after}),i=this.cacheKey("games","search",s),n=await this.withCache(i,"games",e,async()=>(await this.connection.execute(r,s)).searchGames);return new l(n,{nextPageLoader:async c=>this.search({...e,after:c})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,n=r??{};this.validateAccess(s,i);let c=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(c,"games",n,async()=>{let{query:o}=a.fetchGameByKeys();return (await this.connection.execute(o,{publisherSlug:s,gameKey:i})).fetchGame??null})}else {let s=e,i=t??{},n=this.cacheKey("games","get",{id:s});return this.withCache(n,"games",i,async()=>{let{query:c}=a.fetchGameById();return (await this.connection.execute(c,{id:s})).fetchGame??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("games","getMany",{ids:e});return this.withCache(r,"games",t,async()=>{let{query:s}=a.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},gt=class extends f{constructor(e,t){super(e,t);}async list(e,t={}){let{query:r,variables:s}=a.listDatasets({publisherId:e,gameId:t.gameId,includeArchived:t.includeArchived,purpose:t.purpose,first:t.first,after:t.after}),i=this.cacheKey("datasets","list",s),n=await this.withCache(i,"datasets",t,async()=>(await this.connection.execute(r,s)).datasets);return new l(n,{nextPageLoader:async c=>this.list(e,{...t,after:c})})}async getByKey(e){let t=this.cacheKey("datasets","getByKey",{publisherId:e.publisherId,gameId:e.gameId,datasetKey:e.datasetKey});return this.withCache(t,"datasets",e,async()=>{let{query:r,variables:s}=a.dataset(e);return (await this.connection.execute(r,s)).dataset??null})}async getSchema(e){return (typeof e=="string"?await this.withCache(this.cacheKey("datasets","getSchema",{id:e}),"datasets",{},async()=>{let{query:r,variables:s}=a.dataset({id:e});return (await this.connection.execute(r,s)).dataset??null}):await this.getByKey(e))?.schema??null}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug),r=this.config.resolveGame(e.gameKey);t&&this.validateAccess(t,r);let{query:s,variables:i}=a.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),n=this.cacheKey("datasets","search",i),c=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(c,{nextPageLoader:async o=>this.search({...e,after:o})})}async get(e,t,r,s){if(typeof t=="string"&&typeof r=="string"){let i=e,n=t,c=s??{};this.validateAccess(i,n);let o=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:n,datasetKey:r});return this.withCache(o,"datasets",c,async()=>{let{query:h}=a.fetchDatasetByKeys();return (await this.connection.execute(h,{publisherSlug:i,gameKey:n,datasetKey:r})).fetchDataset??null})}else {let i=e,n=t??{},c=this.cacheKey("datasets","get",{id:i});return this.withCache(c,"datasets",n,async()=>{let{query:o}=a.fetchDatasetById();return (await this.connection.execute(o,{id:i})).fetchDataset??null})}}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("datasets","getMany",{ids:e});return this.withCache(r,"datasets",t,async()=>{let{query:s}=a.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},kt=class extends f{constructor(e,t){super(e,t);}async fetch(e,t={}){let r=this.cacheKey("decks","fetch",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async get(e,t={}){let r=this.cacheKey("decks","get",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckById();return (await this.connection.execute(s,{id:e})).deck??null})}async fetchMine(e,t={}){let r=this.cacheKey("decks","fetchMine",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.myDeck();return (await this.connection.execute(s,{id:e})).myDeck??null})}async fetchBySlug(e,t,r,s={}){let i=this.cacheKey("decks","fetchBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:n}=a.fetchDeckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).fetchDeckBySlug??null})}async getBySlug(e,t,r,s={}){let i=this.cacheKey("decks","getBySlug",{publisherSlug:e,gameKey:t,slug:r});return this.withCache(i,"decks",s,async()=>{let{query:n}=a.deckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).deckBySlug??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async getByExternalRef(e,t={}){let r=this.cacheKey("decks","getByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).deckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=a.listMyDecks({first:e.first,after:e.after,includeArchived:e.includeArchived}),s=this.cacheKey("decks","listMine",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).myDecks);return new l(i,{nextPageLoader:async n=>this.listMine({...e,after:n})})}async listViewer(e={}){let{query:t,variables:r}=a.viewerDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listViewer",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).viewerDecks);return new l(i,{nextPageLoader:async n=>this.listViewer({...e,after:n})})}async listApp(e={}){this.config.requireSecretCredential("decks.listApp");let{query:t,variables:r}=a.appDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listApp",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).appDecks);return new l(i,{nextPageLoader:async n=>this.listApp({...e,after:n})})}async listPublic(e={}){let{query:t,variables:r}=a.publicDecks({filter:e.filter,first:e.first,after:e.after}),s=this.cacheKey("decks","listPublic",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).publicDecks);return new l(i,{nextPageLoader:async n=>this.listPublic({...e,after:n})})}async fetchVersion(e,t={}){let r=this.cacheKey("decks","fetchVersion",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckVersion();return (await this.connection.execute(s,{id:e})).deckVersion??null})}async listVersions(e,t={}){let{query:r,variables:s}=a.deckVersions({first:t.first,after:t.after}),i={deckId:e,...s},n=this.cacheKey("decks","listVersions",i),c=await this.withCache(n,"decks",t,async()=>(await this.connection.execute(r,i)).deckVersions);return new l(c,{nextPageLoader:async o=>this.listVersions(e,{...t,after:o})})}async preview(e,t={}){let r=this.cacheKey("decks","preview",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckPreview();return (await this.connection.execute(s,{token:e})).deckPreview??null})}async embed(e,t={}){let r=this.cacheKey("decks","embed",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckEmbed();return (await this.connection.execute(s,{token:e})).deckEmbed??null})}async access(e,t={}){let r=this.cacheKey("decks","access",{token:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckAccess();return (await this.connection.execute(s,{token:e})).deckAccess??null})}async draftDiff(e,t={}){let r=this.cacheKey("decks","draftDiff",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckDraftDiff();return (await this.connection.execute(s,{id:e})).deckDraftDiff})}async versionDiff(e,t,r={}){let s=a.deckVersionDiffVariables(e,t),i=this.cacheKey("decks","versionDiff",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckVersionDiff();return (await this.connection.execute(n,s)).deckVersionDiff})}async validate(e,t,r={}){let s=a.deckValidateVariables(e,t),i=this.cacheKey("decks","validate",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckValidate();return (await this.connection.execute(n,s)).deckValidate})}async hydrateDeckEntries(e,t={}){let r=a.deckHydrateEntriesVariables(e),s=this.cacheKey("decks","hydrateDeckEntries",r);return this.withCache(s,"decks",t,async()=>{let{query:i}=a.deckHydrateEntries();return (await this.connection.execute(i,r)).deckHydrateEntries})}async exportDeck(e,t="SIMPLE_TEXT",r={}){let s=a.deckExportVariables(e,t),i=this.cacheKey("decks","exportDeck",s);return this.withCache(i,"decks",r,async()=>{let{query:n}=a.deckExport();return (await this.connection.execute(n,s)).deckExport})}async sectionDefinitions(e={}){let{query:t,variables:r}=a.deckSectionDefinitions({publisherSlug:e.publisherSlug,gameKey:e.gameKey,gameId:e.gameId,rulesetKey:e.rulesetKey,rulesetVersionId:e.rulesetVersionId}),s=this.cacheKey("decks","sectionDefinitions",r);return this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).deckSectionDefinitions)}async listCollaborators(e,t={}){let r=this.cacheKey("decks","listCollaborators",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckCollaborators();return (await this.connection.execute(s,{deckId:e})).deckCollaborators})}async listPreviewTokens(e,t={}){let r=this.cacheKey("decks","listPreviewTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckPreviewTokens();return (await this.connection.execute(s,{deckId:e})).deckPreviewTokens})}async listEmbedTokens(e,t={}){let r=this.cacheKey("decks","listEmbedTokens",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckEmbedTokens();return (await this.connection.execute(s,{deckId:e})).deckEmbedTokens})}async listAccessTokenIssuers(e,t={}){let r=this.cacheKey("decks","listAccessTokenIssuers",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckAccessTokenIssuers();return (await this.connection.execute(s,{deckId:e})).deckAccessTokenIssuers})}async listApiApplicationAccesses(e,t={}){let r=a.deckApiApplicationAccessesVariables(e,t.includeRevoked),s=this.cacheKey("decks","listApiApplicationAccesses",r);return this.withCache(s,"decks",t,async()=>{let{query:i}=a.deckApiApplicationAccesses();return (await this.connection.execute(i,r)).deckApiApplicationAccesses})}async listMyApiApplicationAccesses(e={}){let t=a.myDeckApiApplicationAccessesVariables(e.applicationId),r=this.cacheKey("decks","listMyApiApplicationAccesses",t);return this.withCache(r,"decks",e,async()=>{let{query:s}=a.myDeckApiApplicationAccesses();return (await this.connection.execute(s,t)).myDeckApiApplicationAccesses})}async create(e){let{query:t}=a.createDeck(),r=a.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=a.updateDeck(),s=a.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async updateMetadata(e,t){return this.update(e,t)}async upsertByExternalRef(e){this.config.requireSecretCredential("decks.upsertByExternalRef");let{query:t}=a.upsertDeckByExternalRef(),r=a.deckUpsertByExternalRefVariables(e);return (await this.connection.execute(t,r)).deckUpsertByExternalRef}async claim(e,t){let{query:r}=a.claimDeck(),s=a.deckClaimVariables(e,t);return (await this.connection.execute(r,s)).deckClaim}async transferOwnership(e,t){let{query:r}=a.transferDeckOwnership(),s=a.deckTransferOwnershipVariables(e,t);return (await this.connection.execute(r,s)).deckTransferOwnership}async copy(e,t){let{query:r}=a.copyDeck(),s=a.deckCopyVariables(e,t);return (await this.connection.execute(r,s)).deckCopy}async addEntry(e){let{query:t}=a.addDeckEntry(),r=a.deckEntryAddVariables(e);return (await this.connection.execute(t,r)).deckEntryAdd}async updateEntry(e,t){let{query:r}=a.updateDeckEntry(),s=a.deckEntryUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckEntryUpdate}async removeEntry(e,t){let{query:r}=a.removeDeckEntry(),s=a.deckEntryRemoveVariables(e,t);return (await this.connection.execute(r,s)).deckEntryRemove}async reorderEntries(e,t){let{query:r}=a.reorderDeckEntries(),s=a.deckEntryReorderVariables(e,t);return (await this.connection.execute(r,s)).deckEntryReorder}async replaceEntries(e,t){let{query:r}=a.replaceDeckEntries(),s=a.deckEntriesReplaceVariables(e,t);return (await this.connection.execute(r,s)).deckEntriesReplace}async importDeck(e){let{query:t}=a.importDeck(),r=a.deckImportVariables(e);return (await this.connection.execute(t,r)).deckImport}async listImportFormats(e,t={}){let{query:r,variables:s}=a.deckImportFormats({gameId:e,includeArchived:t.includeArchived,first:t.first,after:t.after}),i=this.cacheKey("decks","listImportFormats",s),n=await this.withCache(i,"decks",t,async()=>(await this.connection.execute(r,s)).deckImportFormats);return new l(n,{nextPageLoader:async c=>this.listImportFormats(e,{...t,after:c})})}async fetchImportFormat(e,t={}){let r=this.cacheKey("decks","fetchImportFormat",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=a.deckImportFormat();return (await this.connection.execute(s,{id:e})).deckImportFormat??null})}async testImportFormat(e){let{query:t}=a.deckImportFormatTest(),r=a.deckImportFormatTestVariables(e);return (await this.connection.execute(t,r)).deckImportFormatTest}async createImportFormat(e){let{query:t}=a.createDeckImportFormat(),r=a.deckImportFormatCreateVariables(e);return (await this.connection.execute(t,r)).deckImportFormatCreate}async updateImportFormat(e,t){let{query:r}=a.updateDeckImportFormat(),s=a.deckImportFormatUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckImportFormatUpdate}async archiveImportFormat(e){let{query:t}=a.archiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatArchive}async unarchiveImportFormat(e){let{query:t}=a.unarchiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatUnarchive}async delete(e){let{query:t}=a.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}async archive(e){let{query:t}=a.archiveDeck();return (await this.connection.execute(t,{id:e})).deckArchive}async restore(e){let{query:t}=a.restoreDeck();return (await this.connection.execute(t,{id:e})).deckRestore}async unpublish(e){let{query:t}=a.unpublishDeck();return (await this.connection.execute(t,{id:e})).deckUnpublish}async publish(e,t){let{query:r}=a.publishDeck(),s=a.deckPublishVariables(e,t);return (await this.connection.execute(r,s)).deckPublish}async removeInvalidEntries(e,t){let{query:r}=a.removeInvalidDeckEntries(),s=a.deckRemoveInvalidEntriesVariables(e,t);return (await this.connection.execute(r,s)).deckRemoveInvalidEntries}async upsertCollaborator(e,t,r){let{query:s}=a.upsertDeckCollaborator(),i=a.deckCollaboratorVariables(e,t,r);return (await this.connection.execute(s,i)).deckCollaboratorUpsert}async removeCollaborator(e,t){let{query:r}=a.removeDeckCollaborator(),s=a.deckCollaboratorVariables(e,t);return !!(await this.connection.execute(r,s)).deckCollaboratorRemove}async createPreviewToken(e){let{query:t}=a.createDeckPreviewToken(),r=a.deckPreviewTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckPreviewTokenCreate}async revokePreviewToken(e){let{query:t}=a.revokeDeckPreviewToken();return !!(await this.connection.execute(t,{id:e})).deckPreviewTokenRevoke}async createEmbedToken(e){let{query:t}=a.createDeckEmbedToken(),r=a.deckEmbedTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckEmbedTokenCreate}async revokeEmbedToken(e){let{query:t}=a.revokeDeckEmbedToken();return !!(await this.connection.execute(t,{id:e})).deckEmbedTokenRevoke}async createAccessTokenIssuer(e){let{query:t}=a.createDeckAccessTokenIssuer(),r=a.deckAccessTokenIssuerCreateVariables(e);return (await this.connection.execute(t,r)).deckAccessTokenIssuerCreate}async revokeAccessTokenIssuer(e){let{query:t}=a.revokeDeckAccessTokenIssuer();return !!(await this.connection.execute(t,{id:e})).deckAccessTokenIssuerRevoke}async revokeAccessTokenIssuerSigningKey(e){let{query:t}=a.revokeDeckAccessTokenIssuerSigningKey();return (await this.connection.execute(t,{id:e})).deckAccessTokenIssuerSigningKeyRevoke}async grantApiApplicationAccess(e){let{query:t}=a.grantDeckApiApplicationAccess(),r=a.deckApiApplicationAccessGrantVariables(e);return (await this.connection.execute(t,r)).deckApiApplicationAccessGrant}async revokeApiApplicationAccess(e,t){let{query:r}=a.revokeDeckApiApplicationAccess(),s=a.deckApiApplicationAccessRevokeVariables(e,t);return !!(await this.connection.execute(r,s)).deckApiApplicationAccessRevoke}async exchangeAccessToken(e){this.config.requireSecretCredential("decks.exchangeAccessToken");let{query:t}=a.exchangeDeckAccessToken(),r=a.deckAccessTokenExchangeVariables(e);return (await this.connection.execute(t,r)).deckAccessTokenExchange}async exchangeSessionToken(e){this.config.requireSecretCredential("decks.exchangeSessionToken");let{query:t}=a.exchangeDeckSessionToken(),r=a.deckSessionTokenExchangeVariables(e);return (await this.connection.execute(t,r)).deckSessionTokenExchange}async revokeAccessToken(e){this.config.requireSecretCredential("decks.revokeAccessToken");let{query:t}=a.revokeDeckAccessToken();return !!(await this.connection.execute(t,{id:e})).deckAccessTokenRevoke}async hydrateEntries(e){if(e.entries.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=e.entries.map(o=>o.identifier),i=this.cacheKey("decks","hydrateEntries",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s}),n=await this.withCache(i,"decks",e,async()=>{let{query:o}=a.fetchRecordsByIdentifier();return (await this.connection.execute(o,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),c=It(n,s,e.identifierField);return e.entries.map(o=>({...o,record:c.get(o.identifier)??null}))}};function It(e,t,r){let s=new Set(t),i=new Map;for(let n of e){let c=r?n.data[r]:Object.values(n.data).find(h=>s.has(String(h)));if(c==null)continue;let o=String(c);s.has(o)&&(i.set(o,n),s.delete(o));}return i}var bt=class extends f{constructor(e,t){super(e,t);}async list(e){let t=U(e.filter),{query:r,variables:s}=a.listDatasetRecords({datasetId:e.datasetId,filter:t,orderBy:e.orderBy,first:e.first,after:e.after,last:e.last,before:e.before,validateSchema:e.validateSchema}),i=this.cacheKey("records","list",s),n=await this.withCache(i,"records",e,async()=>(await this.connection.execute(r,s)).datasetRecords);return new l(n,{nextPageLoader:async c=>this.list({...e,after:c})})}async getByDatasetIdentifier(e){let t=this.cacheKey("records","getByDatasetIdentifier",{datasetId:e.datasetId,identifier:e.identifier,includePricing:e.includePricing??false});return this.withCache(t,"records",e,async()=>{let{query:r,variables:s}=a.datasetRecord({datasetId:e.datasetId,identifier:e.identifier,includePricing:e.includePricing});return (await this.connection.execute(r,s)).datasetRecord??null})}async upsertBatch(e){this.config.requireSecretCredential("records.upsertBatch");let{query:t}=a.upsertDatasetRecords();return (await this.connection.execute(t,a.datasetRecordsUpsertVariables(e))).datasetRecordsUpsert}async deleteBatch(e){this.config.requireSecretCredential("records.deleteBatch");let{query:t}=a.deleteDatasetRecords();return (await this.connection.execute(t,a.datasetRecordsDeleteVariables(e))).datasetRecordsDelete}async getDeleteJob(e,t={}){let r=this.cacheKey("records","getDeleteJob",{id:e});return this.withCache(r,"records",t,async()=>{let{query:s}=a.datasetRecordDeleteJob();return (await this.connection.execute(s,{id:e})).datasetRecordDeleteJob??null})}async listDeleteJobs(e,t={}){let{query:r,variables:s}=a.datasetRecordDeleteJobs({publisherId:e,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("records","listDeleteJobs",s),n=await this.withCache(i,"records",t,async()=>(await this.connection.execute(r,s)).datasetRecordDeleteJobs);return new l(n,{nextPageLoader:async c=>this.listDeleteJobs(e,{...t,after:c})})}async waitForDeleteJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getDeleteJob(e,{cache:false});if(!n)throw new Error(`Delete job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for delete job '${e}'`);await new Promise(c=>setTimeout(c,r));}}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=U(e.filter),{query:i,variables:n}=a.searchRecords({publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,filter:s,search:e.search,orderBy:e.orderBy,resolveLinks:e.resolveLinks,first:e.first,after:e.after,validateSchema:e.validateSchema,includePricing:e.includePricing}),c=this.cacheKey("records","search",{...n,includePricing:e.includePricing??false}),o=await this.withCache(c,"records",e,async()=>(await this.connection.execute(i,n)).searchRecords);return new l(o,{nextPageLoader:async h=>this.search({...e,after:h})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=a.fetchRecordById({includePricing:t.includePricing});return (await this.connection.execute(s,{id:e})).fetchRecord??null})}async getByIdentifier(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=a.fetchRecordByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifier:e.identifier})).fetchRecordByIdentifier??null})}async getManyByIdentifier(e){if(e.identifiers.length===0)return [];let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=this.cacheKey("records","getManyByIdentifier",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers,includePricing:e.includePricing??false});return this.withCache(s,"records",e,async()=>{let{query:i}=a.fetchRecordsByIdentifier({includePricing:e.includePricing});return (await this.connection.execute(i,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:e.identifiers})).fetchRecordsByIdentifier??[]})}async getMany(e,t={}){if(e.length===0)return [];let r=this.cacheKey("records","getMany",{ids:e,includePricing:t.includePricing??false});return this.withCache(r,"records",t,async()=>{let{query:s}=a.fetchRecords({includePricing:t.includePricing});return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},$t=class extends f{constructor(e,t){super(e,t);}async datasets(e={}){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let{query:s,variables:i}=a.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),n=this.cacheKey("rules","datasets",i),c=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(c,{nextPageLoader:async o=>this.datasets({...e,after:o})})}async list(e={}){return this.searchRuleRecords("rules",e)}async formats(e={}){return this.searchRuleRecords(e.datasetKey??"formats",e)}async searchRuleRecords(e,t){let r=this.resolvePublisher(t.publisherSlug),s=this.resolveGame(t.gameKey),i=t.datasetKey??e;this.validateAccess(r,s);let n=U(t.filter),{query:c,variables:o}=a.searchRecords({publisherSlug:r,gameKey:s,datasetKey:i,filter:n,search:t.search,orderBy:t.orderBy,resolveLinks:t.resolveLinks,first:t.first,after:t.after,validateSchema:t.validateSchema}),h=this.cacheKey("rules","records",o),w=await this.withCache(h,"records",t,async()=>(await this.connection.execute(c,o)).searchRecords);return new l(w,{nextPageLoader:async X=>this.searchRuleRecords(e,{...t,after:X})})}},vt=class extends f{constructor(e,t){super(e,t);}async list(e){let{query:t,variables:r}=a.deckImportFormats({publisherId:e.publisherId,gameId:e.gameId,includeArchived:e.includeArchived,first:e.first,after:e.after}),s=this.cacheKey("importFormats","list",r),i=await this.withCache(s,"importFormats",e,async()=>(await this.connection.execute(t,r)).deckImportFormats);return new l(i,{nextPageLoader:async n=>this.list({...e,after:n})})}async get(e,t={}){let r=this.cacheKey("importFormats","get",{id:e});return this.withCache(r,"importFormats",t,async()=>{let{query:s}=a.deckImportFormat();return (await this.connection.execute(s,{id:e})).deckImportFormat??null})}async getByKey(e){let t=this.cacheKey("importFormats","getByKey",{gameId:e.gameId,formatKey:e.key});return this.withCache(t,"importFormats",e,async()=>{let{query:r}=a.deckImportFormat();return (await this.connection.execute(r,{gameId:e.gameId,key:e.key})).deckImportFormat??null})}async test(e){let{query:t}=a.deckImportFormatTest();return (await this.connection.execute(t,a.deckImportFormatTestVariables(e))).deckImportFormatTest}async create(e){this.config.requireSecretCredential("importFormats.create");let{query:t}=a.createDeckImportFormat();return (await this.connection.execute(t,a.deckImportFormatCreateVariables(e))).deckImportFormatCreate}async update(e,t){this.config.requireSecretCredential("importFormats.update");let{query:r}=a.updateDeckImportFormat();return (await this.connection.execute(r,a.deckImportFormatUpdateVariables(e,t))).deckImportFormatUpdate}async archive(e){this.config.requireSecretCredential("importFormats.archive");let{query:t}=a.archiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatArchive}async unarchive(e){this.config.requireSecretCredential("importFormats.unarchive");let{query:t}=a.unarchiveDeckImportFormat();return (await this.connection.execute(t,{id:e})).deckImportFormatUnarchive}},Dt=class extends f{constructor(e,t){super(e,t);}async preview(e){let{query:t}=a.datasetImportPreview();return (await this.connection.execute(t,a.datasetImportPreviewVariables(e))).datasetImportPreview}async validate(e){let{query:t}=a.datasetImportValidate();return (await this.connection.execute(t,a.datasetImportValidateVariables(e))).datasetImportValidate}async run(e){if(this.config.requireSecretCredential("imports.run"),"fileId"in e&&e.fileId){let{query:s}=a.datasetImportFromFile();return (await this.connection.execute(s,a.datasetImportFromFileVariables(e))).datasetImportFromFile}if("sourceUrl"in e&&e.sourceUrl){let{query:s}=a.datasetImportFromUrl();return (await this.connection.execute(s,a.datasetImportFromUrlVariables(e))).datasetImportFromUrl}let{query:t}=a.datasetImportFromPayload();return (await this.connection.execute(t,a.datasetImportFromPayloadVariables(e))).datasetImportFromPayload}async getJob(e,t={}){let r=this.cacheKey("imports","getJob",{id:e});return this.withCache(r,"imports",t,async()=>{let{query:s}=a.importJob();return (await this.connection.execute(s,{id:e})).importJob??null})}async listJobs(e,t={}){let{query:r,variables:s}=a.importJobs({publisherId:e,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("imports","listJobs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).importJobs);return new l(n,{nextPageLoader:async c=>this.listJobs(e,{...t,after:c})})}async cancelJob(e){this.config.requireSecretCredential("imports.cancelJob");let{query:t}=a.importJobCancel();return (await this.connection.execute(t,{id:e})).importJobCancel}async listJobLogs(e,t={}){let{query:r,variables:s}=a.importJobLogs({importJobId:e,level:t.level,datasetKey:t.datasetKey,first:t.first,after:t.after}),i=this.cacheKey("imports","listJobLogs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).importJob?.logs??wt());return new l(n,{nextPageLoader:async c=>this.listJobLogs(e,{...t,after:c})})}async waitForJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getJob(e,{cache:false});if(!n)throw new Error(`Import job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for import job '${e}'`);await new Promise(c=>setTimeout(c,r));}}async previewGame(e){let{query:t}=a.gameImportPreview();return (await this.connection.execute(t,a.gameImportPreviewVariables(e))).gameImportPreview}async runGame(e){if(this.config.requireSecretCredential("imports.runGame"),"fileId"in e&&e.fileId){let{query:s}=a.gameImportFromFile();return (await this.connection.execute(s,a.gameImportFromFileVariables(e))).gameImportFromFile}if("sourceUrl"in e&&e.sourceUrl){let{query:s}=a.gameImportFromUrl();return (await this.connection.execute(s,a.gameImportFromUrlVariables(e))).gameImportFromUrl}let{query:t}=a.gameImportFromPayload();return (await this.connection.execute(t,a.gameImportFromPayloadVariables(e))).gameImportFromPayload}async getGameJob(e,t={}){let r=this.cacheKey("imports","getGameJob",{id:e});return this.withCache(r,"imports",t,async()=>{let{query:s}=a.gameImportJob();return (await this.connection.execute(s,{id:e})).gameImportJob??null})}async listGameJobs(e,t={}){let{query:r,variables:s}=a.gameImportJobs({gameId:e,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("imports","listGameJobs",s),n=await this.withCache(i,"imports",t,async()=>(await this.connection.execute(r,s)).gameImportJobs);return new l(n,{nextPageLoader:async c=>this.listGameJobs(e,{...t,after:c})})}async cancelGameJob(e){this.config.requireSecretCredential("imports.cancelGameJob");let{query:t}=a.gameImportJobCancel();return (await this.connection.execute(t,{id:e})).gameImportJobCancel}async waitForGameJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getGameJob(e,{cache:false});if(!n)throw new Error(`Game import job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for game import job '${e}'`);await new Promise(c=>setTimeout(c,r));}}};function wt(){return {totalCount:0,pageInfo:{hasNextPage:false,hasPreviousPage:false,startCursor:null,endCursor:null},edges:[]}}var St=class extends f{constructor(e,t){super(e,t);}async run(e){this.config.requireSecretCredential("exports.run");let{query:t}=a.datasetExport();return (await this.connection.execute(t,a.datasetExportVariables(e))).datasetExport}async create(e){return this.run(e)}async getJob(e,t={}){let r=this.cacheKey("exports","getJob",{id:e});return this.withCache(r,"exports",t,async()=>{let{query:s}=a.exportJob();return (await this.connection.execute(s,{id:e})).exportJob??null})}async listJobs(e,t={}){let{query:r,variables:s}=a.exportJobs({publisherId:e,gameId:t.gameId,datasetId:t.datasetId,status:t.status,first:t.first,after:t.after}),i=this.cacheKey("exports","listJobs",s),n=await this.withCache(i,"exports",t,async()=>(await this.connection.execute(r,s)).exportJobs);return new l(n,{nextPageLoader:async c=>this.listJobs(e,{...t,after:c})})}async refreshUrl(e){let{query:t}=a.exportJobRefreshUrl();return (await this.connection.execute(t,{id:e})).exportJobRefreshUrl}async cancel(e){this.config.requireSecretCredential("exports.cancel");let{query:t}=a.exportJobCancel();return (await this.connection.execute(t,{id:e})).exportJobCancel}async waitForJob(e,t={}){let r=t.intervalMs??1e3,s=t.timeoutMs??3e5,i=Date.now();for(;;){let n=await this.getJob(e,{cache:false});if(!n)throw new Error(`Export job '${e}' was not found`);if(n.status==="COMPLETED"||n.status==="FAILED")return n;if(Date.now()-i>=s)throw new Error(`Timed out waiting for export job '${e}'`);await new Promise(c=>setTimeout(c,r));}}},At=class extends f{constructor(e,t){super(e,t);}async get(e,t={}){let r=this.cacheKey("files","get",{id:e});return this.withCache(r,"files",t,async()=>{let{query:s}=a.file();return (await this.connection.execute(s,{id:e})).file??null})}async requestUpload(e){this.config.requireSecretCredential("files.requestUpload");let{query:t}=a.fileUploadRequest();return (await this.connection.execute(t,a.fileUploadRequestVariables(e))).fileUploadRequest}async confirmUpload(e){this.config.requireSecretCredential("files.confirmUpload");let{query:t}=a.fileUploadConfirm();return (await this.connection.execute(t,{id:e})).fileUploadConfirm}async upload(e){let t=e.size??xt(e.body);if(!t||t<=0)throw new Error("files.upload requires a positive size or a body with an inferable size");let r=await this.requestUpload({filename:e.filename,contentType:e.contentType,size:t,isPublic:e.isPublic??false,entityType:e.entityType??Tt(e.purpose),entityId:e.entityId,publisherId:e.publisherId,datasetId:e.datasetId});return await Et(r.uploadUrl,e.contentType,e.body),this.confirmUpload(r.file.id)}async delete(e){this.config.requireSecretCredential("files.delete");let{query:t}=a.fileDelete();return !!(await this.connection.execute(t,{id:e})).fileDelete}};async function Et(e,t,r){let s=globalThis.fetch;if(!s)throw new Error("files.upload requires a runtime with fetch support");let i=await s(e,{method:"PUT",headers:{"Content-Type":t},body:r});if(!i.ok){let n=await i.text().catch(()=>"");throw new Error(`File upload failed with ${i.status} ${i.statusText}${n?`: ${n}`:""}`)}}function xt(e){if(typeof e=="string")return new TextEncoder().encode(e).byteLength;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;let t=e;if(typeof t?.size=="number")return t.size;if(typeof t?.byteLength=="number")return t.byteLength;if(typeof t?.length=="number")return t.length}function Tt(e){if(!(!e||e==="scan_image"))return e==="import"?"import":e==="scan_template_example"?"scan_template_example":e}var qt=class extends f{constructor(e,t){super(e,t);}async createUploadSession(e){let t=this.resolveCreateUploadSessionInput(e),{query:r}=a.createScanUploadSession();return (await this.connection.execute(r,a.createScanUploadSessionVariables(t))).createScanUploadSession}async confirmUpload(e){let t=this.resolveConfirmUploadInput(e),{query:r}=a.confirmScanUpload();return (await this.connection.execute(r,a.confirmScanUploadVariables(t))).confirmScanUpload}async createJob(e){let t=this.resolveCreateJobInput(e),{query:r}=a.createScanJob();return (await this.connection.execute(r,a.createScanJobVariables(t))).createScanJob}async getJob(e,t={}){let r=this.cacheKey("scans","getJob",{id:e});return this.withCache(r,"scans",t,async()=>{let{query:s}=a.scanJob();return (await this.connection.execute(s,{id:e})).scanJob??null})}async pollJob(e,t={}){let r=t.timeoutMs??3e5,s=Math.max(t.backoffFactor??1.5,1),i=t.maxIntervalMs??1e4,n=Date.now(),c=Math.max(t.intervalMs??1e3,1);for(;;){Kt(t.signal);let o=await this.getJob(e,{cache:false});if(!o)throw new Error(`Scan job '${e}' was not found`);if(Rt(o.status))return o;let h=Date.now()-n,w=r-h;if(w<=0)throw new Error(`Timed out waiting for scan job '${e}'`);await Ct(Math.min(c,w)),c=Math.min(Math.ceil(c*s),i);}}async submitFeedback(e){let{query:t}=a.submitScanFeedback();return (await this.connection.execute(t,a.submitScanFeedbackVariables(e))).submitScanFeedback}async metrics(e){let t=this.resolveMetricsInput(e),{query:r}=a.scanMetrics();return (await this.connection.execute(r,a.scanMetricsVariables(t))).scanMetrics}async verifyWebhookSignature(e){let t=Ut(),r=await t.importKey("raw",ve(e.secret),{name:"HMAC",hash:"SHA-256"},false,["sign"]),s=await t.sign("HMAC",r,Ft(e.body)),i=`sha256=${Pt(new Uint8Array(s))}`;return Lt(e.signature.trim().toLowerCase(),i)}resolveCreateJobInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveCreateUploadSessionInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveConfirmUploadInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolveMetricsInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}};function Rt(e){let t=e.toLowerCase();return t==="completed"||t==="failed"||t==="cancelled"}async function Ct(e){return new Promise(t=>setTimeout(t,e))}function Kt(e){if(e&&(e.throwIfAborted&&e.throwIfAborted(),e.aborted))throw new Error("Scan job polling aborted")}function Ut(){let t=globalThis.crypto?.subtle;if(!t)throw new Error("Web Crypto HMAC support is not available in this runtime");return t}function Ft(e){return typeof e=="string"?ve(e):e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function ve(e){return new TextEncoder().encode(e)}function Pt(e){return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function Lt(e,t){let r=Math.max(e.length,t.length),s=e.length^t.length;for(let i=0;i<r;i++)s|=(e.charCodeAt(i)||0)^(t.charCodeAt(i)||0);return s===0}var Vt=class extends f{constructor(e,t){super(e,t);}async resolve(e){let t=this.resolveTemplateScope(e),r=this.cacheKey("scanTemplates","resolve",{...t});return this.withCache(r,"scanTemplates",e,async()=>{let{query:s}=a.resolveScanTemplate();return (await this.connection.execute(s,a.resolveScanTemplateVariables(t))).resolveScanTemplate})}async list(e){let t=this.resolveListScope(e),r=this.cacheKey("scanTemplates","list",{...t});return this.withCache(r,"scanTemplates",e,async()=>{let{query:s}=a.scanTemplates();return (await this.connection.execute(s,a.scanTemplatesVariables(t))).scanTemplates?.templates??[]})}async create(e){this.config.requireSecretCredential("scanTemplates.create");let t=this.resolveSaveInput(e),{query:r}=a.createScanTemplate();return (await this.connection.execute(r,a.createScanTemplateVariables(t))).createScanTemplate}async update(e,t){this.config.requireSecretCredential("scanTemplates.update");let r=typeof e=="string"?e:e.id,s=typeof e=="string"?t:_t(e);if(!s)throw new Error("scan template input is required");let i=this.resolveSaveInput(s),{query:n}=a.updateScanTemplate();return (await this.connection.execute(n,a.updateScanTemplateVariables(r,i))).updateScanTemplate}async preview(e){let t=this.resolvePreviewInput(e),{query:r}=a.previewScanTemplate();return (await this.connection.execute(r,a.previewScanTemplateVariables(t))).previewScanTemplate}resolveTemplateScope(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,templateId:e.templateId}}resolveListScope(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,includeArchived:e.includeArchived}}resolveSaveInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}resolvePreviewInput(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);return this.validateAccess(t,r),{...e,publisherSlug:t,gameKey:r}}};function _t(e){let t={...e};return delete t.id,t}var De=class we{config;connection;publishers;games;datasets;records;decks;rules;importFormats;imports;exports;files;scans;scanTemplates;constructor(t={}){this.config=new nt(t),this.connection=new dt(this.config),this.publishers=new pt(this.connection,this.config),this.games=new mt(this.connection,this.config),this.datasets=new gt(this.connection,this.config),this.records=new bt(this.connection,this.config),this.decks=new kt(this.connection,this.config),this.rules=new $t(this.connection,this.config),this.importFormats=new vt(this.connection,this.config),this.imports=new Dt(this.connection,this.config),this.exports=new St(this.connection,this.config),this.files=new At(this.connection,this.config),this.scans=new qt(this.connection,this.config),this.scanTemplates=new Vt(this.connection,this.config);}async me(){let{query:t}=a.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return lt()}withConfig(t){let r=this.config.merge(t);return new we({apiKey:r.configApiKey(),publishableKey:r.publishableKey,secretKey:r.secretKey,accessToken:r.accessToken,environment:r.environment,endpoint:r.endpoint,timeout:r.timeout,openTimeout:r.openTimeout,defaultPublisher:r.defaultPublisher,defaultGame:r.defaultGame,allowedPublishers:r.allowedPublishers,allowedGames:r.allowedGames,logger:r.logger,logLevel:r.logLevel,retryOnRateLimit:r.retryOnRateLimit,maxRetries:r.maxRetries,retryOnNetworkError:r.retryOnNetworkError,maxNetworkRetries:r.maxNetworkRetries,retryBaseDelay:r.retryBaseDelay,retryMaxDelay:r.retryMaxDelay,cache:r.cache,cacheTtl:r.cacheTtl,cacheTtls:r.cacheTtls})}};var W=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";this.storage=r==="sessionStorage"?globalThis.sessionStorage:globalThis.localStorage,this.prefix=t.prefix??"carddb:";}get(t){try{let r=this.storage.getItem(this.prefix+t);if(!r)return null;let s=JSON.parse(r);return s.expiresAt!==null&&Date.now()>s.expiresAt?(this.storage.removeItem(this.prefix+t),null):s.value}catch{return this.storage.removeItem(this.prefix+t),null}}set(t,r,s){try{let i={value:r,expiresAt:s!==void 0?Date.now()+s*1e3:null};this.storage.setItem(this.prefix+t,JSON.stringify(i));}catch(i){console.warn("[CardDB] Failed to write to cache:",i);}}delete(t){this.storage.removeItem(this.prefix+t);}clear(){let t=[];for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t.push(s);}for(let r of t)this.storage.removeItem(r);}has(t){return this.get(t)!==null}get size(){let t=0;for(let r=0;r<this.storage.length;r++){let s=this.storage.key(r);s&&s.startsWith(this.prefix)&&t++;}return t}cleanup(){let t=Date.now(),r=[];for(let s=0;s<this.storage.length;s++){let i=this.storage.key(s);if(i&&i.startsWith(this.prefix))try{let n=this.storage.getItem(i);if(n){let c=JSON.parse(n);c.expiresAt!==null&&t>c.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var Se=class extends De{constructor(t={}){if("apiKey"in t&&t.apiKey!==void 0)throw new $("apiKey is not accepted in browsers; use publishableKey or accessToken");if("secretKey"in t&&t.secretKey!==void 0)throw new $("secretKey is server-only; use publishableKey or accessToken in browsers");super(t);}};
1945
+ export{M as AuthenticationError,f as BaseResource,W as BrowserCache,Se as CardDBClient,y as CardDBError,l as Collection,nt as Configuration,dt as Connection,x as ConnectionError,tt as DEFAULT_CACHE_TTL,Qe as DEFAULT_ENDPOINT,st as DEFAULT_MAX_NETWORK_RETRIES,rt as DEFAULT_MAX_RETRIES,et as DEFAULT_OPEN_TIMEOUT,it as DEFAULT_RETRY_BASE_DELAY,at as DEFAULT_RETRY_MAX_DELAY,Ze as DEFAULT_TIMEOUT,gt as DatasetsResource,kt as DecksResource,St as ExportsResource,At as FilesResource,Ae as FilterBuilder,mt as GamesResource,ce as GraphQLError,vt as ImportFormatsResource,Dt as ImportsResource,Mt as LinkResolutionError,Bt as NotFoundError,pt as PublishersResource,a as QueryBuilder,K as RateLimitError,bt as RecordsResource,$ as RestrictedError,$t as RulesResource,Vt as ScanTemplatesResource,qt as ScansResource,O as ServerError,G as TimeoutError,J as ValidationError,ht as cacheKey,Wt as contains,Jt as eq,lt as getRateLimitInfo,fr as getSDKVersion,ut as getUserAgent,Ot as gt,Nt as gte,Qt as ilike,er as isNotNull,Zt as isNull,Xt as like,jt as lt,Ht as lte,Gt as neq,zt as notWithin,yt as readCache,U as resolveFilter,Yt as within,ft as writeCache};//# sourceMappingURL=index.js.map
1933
1946
  //# sourceMappingURL=index.js.map