@carddb/browser 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,10 +25,7 @@ const client = new CardDBClient({
25
25
  // Search for cards with filtering
26
26
  const cards = await client.records.search({
27
27
  datasetKey: 'cards',
28
- filter: (f) =>
29
- f
30
- .where('hp', gte(100))
31
- .where('name', ilike('%pikachu%')),
28
+ filter: (f) => f.where('hp', gte(100)).where('name', ilike('%pikachu%')),
32
29
  })
33
30
 
34
31
  // Iterate through all results (auto-paginates)
@@ -1,4 +1,4 @@
1
- var $=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 a=this.storage.getItem(i);if(a){let n=JSON.parse(a);n.expiresAt!==null&&t>n.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var u=class T extends Error{response;constructor(t,r){super(t),this.name="CardDBError",this.response=r,Error.captureStackTrace&&Error.captureStackTrace(this,T);}},R=class extends u{constructor(e="Invalid or missing API key",t){super(e,t),this.name="AuthenticationError";}},b=class extends u{retryAfter;limit;remaining;resetAt;constructor(e="Rate limit exceeded",t={}){super(e,t.response),this.name="RateLimitError",this.retryAfter=t.retryAfter??null,this.limit=t.limit??null,this.remaining=t.remaining??null,this.resetAt=t.resetAt??null;}},le=class extends u{constructor(e="Resource not found",t){super(e,t),this.name="NotFoundError";}},k=class extends u{errors;constructor(e="Validation error",t={}){super(e,t.response),this.name="ValidationError",this.errors=t.errors??[];}},x=class extends u{constructor(e,t){super(e,t),this.name="RestrictedError";}},B=class extends u{errors;constructor(e="GraphQL error",t={}){super(e,t.response),this.name="GraphQLError",this.errors=t.errors??[];}},w=class extends u{constructor(e="Connection error",t){super(e,t),this.name="ConnectionError";}},S=class extends w{constructor(e="Request timed out",t){super(e,t),this.name="TimeoutError";}},D=class extends u{status;constructor(e="Server error",t={}){super(e,t.response),this.name="ServerError",this.status=t.status??null;}},de=class extends u{failures;partialResults;constructor(e="Some links could not be resolved",t={}){super(e,t.response),this.name="LinkResolutionError",this.failures=t.failures??[],this.partialResults=t.partialResults;}getFailuresForField(e){return this.failures.filter(t=>t.field===e)}hasFailuresForField(e){return this.failures.some(t=>t.field===e)}};function fe(e){return {eq:e}}function ye(e){return {neq:e}}function ge(e){return {gt:e}}function me(e){return {gte:e}}function we(e){return {lt:e}}function pe(e){return {lte:e}}function ve(e){return {in:e}}function be(e){return {nin:e}}function $e(e){return {contains:e}}function Re(e){return {like:e}}function ke(e){return {ilike:e}}function xe(){return {is_null:true}}function Se(){return {is_null:false}}var F=class C{conditions=[];orGroups=[];where(t,r){if(typeof t=="string")this.conditions.push({[t]:r});else for(let[s,i]of Object.entries(t))this.conditions.push({[s]:i});return this}any(t){let r=new C;t(r);let s=r.getConditions();return s.length>0&&this.orGroups.push({$or:s}),this}whereLink(t,r){let s={};for(let[i,a]of Object.entries(r))s[i]=a;return this.conditions.push({[`${t}._link`]:s}),this}whereAny(t,r){let s={};for(let[i,a]of Object.entries(r))s[i]=a;return this.conditions.push({[`${t}._any`]:s}),this}getConditions(){return this.conditions}build(){let t=[...this.conditions,...this.orGroups];return t.length===0?{}:t.length===1?t[0]:{$and:t}}};function E(e){if(e!==void 0){if(typeof e=="function"){let t=new F;e(t);let r=t.build();return Object.keys(r).length>0?r:void 0}return Object.keys(e).length>0?e:void 0}}var p=`
1
+ var $=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 a=JSON.parse(n);a.expiresAt!==null&&t>a.expiresAt&&r.push(i);}}catch{r.push(i);}}for(let s of r)this.storage.removeItem(s);}};var l=class L extends Error{response;constructor(t,r){super(t),this.name="CardDBError",this.response=r,Error.captureStackTrace&&Error.captureStackTrace(this,L);}},D=class extends l{constructor(e="Invalid or missing API key",t){super(e,t),this.name="AuthenticationError";}},p=class extends l{retryAfter;limit;remaining;resetAt;constructor(e="Rate limit exceeded",t={}){super(e,t.response),this.name="RateLimitError",this.retryAfter=t.retryAfter??null,this.limit=t.limit??null,this.remaining=t.remaining??null,this.resetAt=t.resetAt??null;}},me=class extends l{constructor(e="Resource not found",t){super(e,t),this.name="NotFoundError";}},R=class extends l{errors;constructor(e="Validation error",t={}){super(e,t.response),this.name="ValidationError",this.errors=t.errors??[];}},S=class extends l{constructor(e,t){super(e,t),this.name="RestrictedError";}},B=class extends l{errors;constructor(e="GraphQL error",t={}){super(e,t.response),this.name="GraphQLError",this.errors=t.errors??[];}},k=class extends l{constructor(e="Connection error",t){super(e,t),this.name="ConnectionError";}},x=class extends k{constructor(e="Request timed out",t){super(e,t),this.name="TimeoutError";}},I=class extends l{status;constructor(e="Server error",t={}){super(e,t.response),this.name="ServerError",this.status=t.status??null;}},ke=class extends l{failures;partialResults;constructor(e="Some links could not be resolved",t={}){super(e,t.response),this.name="LinkResolutionError",this.failures=t.failures??[],this.partialResults=t.partialResults;}getFailuresForField(e){return this.failures.filter(t=>t.field===e)}hasFailuresForField(e){return this.failures.some(t=>t.field===e)}};function we(e){return {eq:e}}function ve(e){return {neq:e}}function be(e){return {gt:e}}function pe(e){return {gte:e}}function $e(e){return {lt:e}}function De(e){return {lte:e}}function Re(e){return {in:e}}function Se(e){return {nin:e}}function xe(e){return {contains:e}}function Ie(e){return {like:e}}function Ee(e){return {ilike:e}}function Ce(){return {is_null:true}}function Pe(){return {is_null:false}}var _=class A{conditions=[];orGroups=[];where(t,r){if(typeof t=="string")this.conditions.push({[t]:r});else for(let[s,i]of Object.entries(t))this.conditions.push({[s]:i});return this}any(t){let r=new A;t(r);let s=r.getConditions();return s.length>0&&this.orGroups.push({$or:s}),this}whereLink(t,r){let s={};for(let[i,n]of Object.entries(r))s[i]=n;return this.conditions.push({[`${t}._link`]:s}),this}whereAny(t,r){let s={};for(let[i,n]of Object.entries(r))s[i]=n;return this.conditions.push({[`${t}._any`]:s}),this}getConditions(){return this.conditions}build(){let t=[...this.conditions,...this.orGroups];return t.length===0?{}:t.length===1?t[0]:{$and:t}}};function E(e){if(e!==void 0){if(typeof e=="function"){let t=new _;e(t);let r=t.build();return Object.keys(r).length>0?r:void 0}return Object.keys(e).length>0?e:void 0}}var w=`
2
2
  id
3
3
  name
4
4
  slug
@@ -61,9 +61,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
61
61
  key
62
62
  name
63
63
  }
64
- `,L=`
65
- schema {
66
- fields {
64
+ `,V=4;function U(e){return `
67
65
  key
68
66
  label
69
67
  description
@@ -76,17 +74,14 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
76
74
  displayFormat
77
75
  semanticType
78
76
  allowedValues
77
+ ${e>0?`
79
78
  nestedFields {
80
- key
81
- label
82
- description
83
- type
84
- isRequired
85
- filterable
86
- searchable
87
- itemType
88
- semanticType
89
- }
79
+ ${U(e-1)}
80
+ }`:""}
81
+ `}var T=`
82
+ schema {
83
+ fields {
84
+ ${U(V)}
90
85
  }
91
86
  filterableFields
92
87
  searchableFields
@@ -98,7 +93,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
98
93
  targetDatasetId
99
94
  }
100
95
  }
101
- `,d=`
96
+ `,f=`
102
97
  id
103
98
  datasetId
104
99
  data
@@ -111,11 +106,61 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
111
106
  gameId
112
107
  publisherId
113
108
  }
114
- `,y=`
109
+ `,b=`
110
+ id
111
+ deckId
112
+ versionNumber
113
+ slug
114
+ identifier
115
+ title
116
+ description
117
+ formatKey
118
+ visibility
119
+ externalRef
120
+ sourceUrl
121
+ metadata
122
+ publishNote
123
+ computedDiff
124
+ publishedByAccountId
125
+ publishedByApiApplicationId
126
+ createdAt
127
+ entries {
128
+ id
129
+ datasetId
130
+ recordId
131
+ identifier
132
+ quantity
133
+ section
134
+ sortOrder
135
+ annotations
136
+ record {
137
+ ${f}
138
+ }
139
+ }
140
+ `,K=`
141
+ id
142
+ deckId
143
+ accountId
144
+ role
145
+ createdByAccountId
146
+ createdAt
147
+ updatedAt
148
+ `,q=`
149
+ id
150
+ deckId
151
+ label
152
+ expiresAt
153
+ revokedAt
154
+ lastUsedAt
155
+ createdAt
156
+ updatedAt
157
+ `,d=`
115
158
  id
116
159
  accountId
117
160
  apiApplicationId
118
161
  gameId
162
+ slug
163
+ identifier
119
164
  title
120
165
  description
121
166
  formatKey
@@ -123,6 +168,11 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
123
168
  externalRef
124
169
  sourceUrl
125
170
  metadata
171
+ latestPublishedVersion {
172
+ ${b}
173
+ }
174
+ publishedAt
175
+ hasUnpublishedChanges
126
176
  createdAt
127
177
  updatedAt
128
178
  game {
@@ -138,10 +188,10 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
138
188
  sortOrder
139
189
  annotations
140
190
  record {
141
- ${d}
191
+ ${f}
142
192
  }
143
193
  }
144
- `,N=`
194
+ `,O=`
145
195
  resolvedLinks {
146
196
  field
147
197
  linkFieldKey
@@ -152,7 +202,7 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
152
202
  data
153
203
  }
154
204
  }
155
- `;function g(e){return `
205
+ `;function y(e){return `
156
206
  totalCount
157
207
  pageInfo {
158
208
  hasNextPage
@@ -166,34 +216,34 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
166
216
  ${e}
167
217
  }
168
218
  }
169
- `}var o={searchPublishers(e={}){let t={},r=[],s=[];e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),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);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
219
+ `}var c={searchPublishers(e={}){let t={},r=[],s=[];e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),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);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
170
220
  query SearchPublishers${i} {
171
- searchPublishers${a} {
172
- ${g(p)}
221
+ searchPublishers${n} {
222
+ ${y(w)}
173
223
  }
174
224
  }
175
225
  `,variables:t}},fetchPublisherById(){return {query:`
176
226
  query FetchPublisher($id: UUID!) {
177
227
  fetchPublisher(id: $id) {
178
- ${p}
228
+ ${w}
179
229
  }
180
230
  }
181
231
  `}},fetchPublisherBySlug(){return {query:`
182
232
  query FetchPublisher($slug: String!) {
183
233
  fetchPublisher(slug: $slug) {
184
- ${p}
234
+ ${w}
185
235
  }
186
236
  }
187
237
  `}},fetchPublishers(){return {query:`
188
238
  query FetchPublishers($slugs: [String!]!) {
189
239
  fetchPublishers(slugs: $slugs) {
190
- ${p}
240
+ ${w}
191
241
  }
192
242
  }
193
- `}},searchGames(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),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);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
243
+ `}},searchGames(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),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);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
194
244
  query SearchGames${i} {
195
- searchGames${a} {
196
- ${g(m)}
245
+ searchGames${n} {
246
+ ${y(m)}
197
247
  }
198
248
  }
199
249
  `,variables:t}},fetchGameById(){return {query:`
@@ -214,24 +264,24 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
214
264
  ${m}
215
265
  }
216
266
  }
217
- `}},searchDatasets(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.gameKey!==void 0&&(s.push("$gameKey: String"),r.push("gameKey: $gameKey"),t.gameKey=e.gameKey),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.purpose!==void 0&&(s.push("$purpose: DatasetPurpose"),r.push("purpose: $purpose"),t.purpose=e.purpose),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);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
267
+ `}},searchDatasets(e={}){let t={},r=[],s=[];e.publisherSlug!==void 0&&(s.push("$publisherSlug: String"),r.push("publisherSlug: $publisherSlug"),t.publisherSlug=e.publisherSlug),e.gameKey!==void 0&&(s.push("$gameKey: String"),r.push("gameKey: $gameKey"),t.gameKey=e.gameKey),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.purpose!==void 0&&(s.push("$purpose: DatasetPurpose"),r.push("purpose: $purpose"),t.purpose=e.purpose),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);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
218
268
  query SearchDatasets${i} {
219
- searchDatasets${a} {
220
- ${g(v)}
269
+ searchDatasets${n} {
270
+ ${y(v)}
221
271
  }
222
272
  }
223
273
  `,variables:t}},fetchDatasetById(){return {query:`
224
274
  query FetchDataset($id: UUID!) {
225
275
  fetchDataset(id: $id) {
226
276
  ${v}
227
- ${L}
277
+ ${T}
228
278
  }
229
279
  }
230
280
  `}},fetchDatasetByKeys(){return {query:`
231
281
  query FetchDataset($publisherSlug: String!, $gameKey: String!, $datasetKey: String!) {
232
282
  fetchDataset(publisherSlug: $publisherSlug, gameKey: $gameKey, datasetKey: $datasetKey) {
233
283
  ${v}
234
- ${L}
284
+ ${T}
235
285
  }
236
286
  }
237
287
  `}},fetchDatasets(){return {query:`
@@ -240,72 +290,143 @@ var $=class{storage;prefix;constructor(t={}){let r=t.storage??"localStorage";thi
240
290
  ${v}
241
291
  }
242
292
  }
243
- `}},searchRecords(e){let t={publisherSlug:e.publisherSlug,gameKey:e.gameKey,datasetKey:e.datasetKey},r=["publisherSlug: $publisherSlug","gameKey: $gameKey","datasetKey: $datasetKey"],s=["$publisherSlug: String!","$gameKey: String!","$datasetKey: String!"];e.filter!==void 0&&(s.push("$filter: JSON"),r.push("filter: $filter"),t.filter=e.filter),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.orderBy!==void 0&&(s.push("$orderBy: String"),r.push("orderBy: $orderBy"),t.orderBy=e.orderBy),e.resolveLinks!==void 0&&(s.push("$resolveLinks: [String!]"),r.push("resolveLinks: $resolveLinks"),t.resolveLinks=e.resolveLinks),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),e.validateSchema!==void 0&&(s.push("$validateSchema: Boolean"),r.push("validateSchema: $validateSchema"),t.validateSchema=e.validateSchema);let a=e.resolveLinks&&e.resolveLinks.length>0?`${d}
244
- ${N}`:d;return {query:`
293
+ `}},searchRecords(e){let t={publisherSlug:e.publisherSlug,gameKey:e.gameKey,datasetKey:e.datasetKey},r=["publisherSlug: $publisherSlug","gameKey: $gameKey","datasetKey: $datasetKey"],s=["$publisherSlug: String!","$gameKey: String!","$datasetKey: String!"];e.filter!==void 0&&(s.push("$filter: JSON"),r.push("filter: $filter"),t.filter=e.filter),e.search!==void 0&&(s.push("$search: String"),r.push("search: $search"),t.search=e.search),e.orderBy!==void 0&&(s.push("$orderBy: String"),r.push("orderBy: $orderBy"),t.orderBy=e.orderBy),e.resolveLinks!==void 0&&(s.push("$resolveLinks: [String!]"),r.push("resolveLinks: $resolveLinks"),t.resolveLinks=e.resolveLinks),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),e.validateSchema!==void 0&&(s.push("$validateSchema: Boolean"),r.push("validateSchema: $validateSchema"),t.validateSchema=e.validateSchema);let n=e.resolveLinks&&e.resolveLinks.length>0?`${f}
294
+ ${O}`:f;return {query:`
245
295
  query SearchRecords(${s.join(", ")}) {
246
296
  searchRecords(${r.join(", ")}) {
247
- ${g(a)}
297
+ ${y(n)}
248
298
  }
249
299
  }
250
300
  `,variables:t}},fetchRecordById(){return {query:`
251
301
  query FetchRecord($id: UUID!) {
252
302
  fetchRecord(id: $id) {
253
- ${d}
303
+ ${f}
254
304
  }
255
305
  }
256
306
  `}},fetchRecordByIdentifier(){return {query:`
257
307
  query FetchRecordByIdentifier($publisherSlug: String!, $gameKey: String!, $datasetKey: String!, $identifier: String!) {
258
308
  fetchRecordByIdentifier(publisherSlug: $publisherSlug, gameKey: $gameKey, datasetKey: $datasetKey, identifier: $identifier) {
259
- ${d}
309
+ ${f}
260
310
  }
261
311
  }
262
312
  `}},fetchRecordsByIdentifier(){return {query:`
263
313
  query FetchRecordsByIdentifier($publisherSlug: String!, $gameKey: String!, $datasetKey: String!, $identifiers: [String!]!) {
264
314
  fetchRecordsByIdentifier(publisherSlug: $publisherSlug, gameKey: $gameKey, datasetKey: $datasetKey, identifiers: $identifiers) {
265
- ${d}
315
+ ${f}
266
316
  }
267
317
  }
268
318
  `}},fetchRecords(){return {query:`
269
319
  query FetchRecords($ids: [UUID!]!) {
270
320
  fetchRecords(ids: $ids) {
271
- ${d}
321
+ ${f}
272
322
  }
273
323
  }
274
- `}},listMyDecks(e={}){let t={},r=[],s=[];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);let i=s.length>0?`(${s.join(", ")})`:"",a=r.length>0?`(${r.join(", ")})`:"";return {query:`
324
+ `}},listMyDecks(e={}){let t={},r=[],s=[];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);let i=s.length>0?`(${s.join(", ")})`:"",n=r.length>0?`(${r.join(", ")})`:"";return {query:`
275
325
  query MyDecks${i} {
276
- myDecks${a} {
277
- ${g(y)}
326
+ myDecks${n} {
327
+ ${y(d)}
278
328
  }
279
329
  }
280
330
  `,variables:t}},fetchDeckById(){return {query:`
281
331
  query FetchDeck($id: UUID!) {
282
332
  fetchDeck(id: $id) {
283
- ${y}
333
+ ${d}
334
+ }
335
+ }
336
+ `}},myDeck(){return {query:`
337
+ query MyDeck($id: UUID!) {
338
+ myDeck(id: $id) {
339
+ ${d}
340
+ }
341
+ }
342
+ `}},fetchDeckBySlug(){return {query:`
343
+ query FetchDeckBySlug($publisherSlug: String!, $gameKey: String!, $slug: String!) {
344
+ fetchDeckBySlug(publisherSlug: $publisherSlug, gameKey: $gameKey, slug: $slug) {
345
+ ${d}
284
346
  }
285
347
  }
286
348
  `}},fetchDeckByExternalRef(){return {query:`
287
349
  query FetchDeckByExternalRef($externalRef: String!) {
288
350
  fetchDeckByExternalRef(externalRef: $externalRef) {
289
- ${y}
351
+ ${d}
352
+ }
353
+ }
354
+ `}},deckVersion(){return {query:`
355
+ query DeckVersion($id: UUID!) {
356
+ deckVersion(id: $id) {
357
+ ${b}
358
+ }
359
+ }
360
+ `}},deckVersions(e={}){let t={},r=["deckId: $deckId"],s=["$deckId: UUID!"];return 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:`
361
+ query DeckVersions(${s.join(", ")}) {
362
+ deckVersions(${r.join(", ")}) {
363
+ ${y(b)}
364
+ }
365
+ }
366
+ `,variables:t}},deckPreview(){return {query:`
367
+ query DeckPreview($token: String!) {
368
+ deckPreview(token: $token) {
369
+ ${d}
370
+ }
371
+ }
372
+ `}},deckCollaborators(){return {query:`
373
+ query DeckCollaborators($deckId: UUID!) {
374
+ deckCollaborators(deckId: $deckId) {
375
+ ${K}
376
+ }
377
+ }
378
+ `}},deckPreviewTokens(){return {query:`
379
+ query DeckPreviewTokens($deckId: UUID!) {
380
+ deckPreviewTokens(deckId: $deckId) {
381
+ ${q}
290
382
  }
291
383
  }
292
384
  `}},createDeck(){return {query:`
293
385
  mutation DeckCreate($input: DeckCreateInput!) {
294
386
  deckCreate(input: $input) {
295
- ${y}
387
+ ${d}
296
388
  }
297
389
  }
298
390
  `}},updateDeck(){return {query:`
299
391
  mutation DeckUpdate($id: UUID!, $input: DeckUpdateInput!) {
300
392
  deckUpdate(id: $id, input: $input) {
301
- ${y}
393
+ ${d}
302
394
  }
303
395
  }
304
396
  `}},deleteDeck(){return {query:`
305
397
  mutation DeckDelete($id: UUID!) {
306
398
  deckDelete(id: $id)
307
399
  }
308
- `}},deckCreateVariables(e){return {input:e}},deckUpdateVariables(e,t){return {id:e,input:t}},fetchMe(){return {query:`
400
+ `}},publishDeck(){return {query:`
401
+ mutation DeckPublish($id: UUID!, $input: DeckPublishInput!) {
402
+ deckPublish(id: $id, input: $input) {
403
+ ${b}
404
+ }
405
+ }
406
+ `}},upsertDeckCollaborator(){return {query:`
407
+ mutation DeckCollaboratorUpsert($deckId: UUID!, $accountId: UUID!, $role: DeckCollaboratorRole!) {
408
+ deckCollaboratorUpsert(deckId: $deckId, accountId: $accountId, role: $role) {
409
+ ${K}
410
+ }
411
+ }
412
+ `}},removeDeckCollaborator(){return {query:`
413
+ mutation DeckCollaboratorRemove($deckId: UUID!, $accountId: UUID!) {
414
+ deckCollaboratorRemove(deckId: $deckId, accountId: $accountId)
415
+ }
416
+ `}},createDeckPreviewToken(){return {query:`
417
+ mutation DeckPreviewTokenCreate($input: DeckPreviewTokenCreateInput!) {
418
+ deckPreviewTokenCreate(input: $input) {
419
+ token
420
+ previewToken {
421
+ ${q}
422
+ }
423
+ }
424
+ }
425
+ `}},revokeDeckPreviewToken(){return {query:`
426
+ mutation DeckPreviewTokenRevoke($id: UUID!) {
427
+ deckPreviewTokenRevoke(id: $id)
428
+ }
429
+ `}},deckCreateVariables(e){return {input:e}},deckUpdateVariables(e,t){return {id:e,input:t}},deckPublishVariables(e,t={}){return {id:e,input:t}},deckCollaboratorVariables(e,t,r){return r===void 0?{deckId:e,accountId:t}:{deckId:e,accountId:t,role:r}},deckPreviewTokenCreateVariables(e){return {input:e}},fetchMe(){return {query:`
309
430
  query FetchMe {
310
431
  fetchMe {
311
432
  application {
@@ -327,6 +448,6 @@ ${N}`:d;return {query:`
327
448
  }
328
449
  }
329
450
  }
330
- `}}},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 U="https://carddb.xtda.org/query",M=3e4,_=1e4,O=300,j=3,V=2,X=1e3,Q=3e4,J=class P{apiKey;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.apiKey=t.apiKey,this.endpoint=t.endpoint??U,this.timeout=t.timeout??M,this.openTimeout=t.openTimeout??_,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??j,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??V,this.retryBaseDelay=t.retryBaseDelay??X,this.retryMaxDelay=t.retryMaxDelay??Q,this.cache=t.cache,this.cacheTtl=t.cacheTtl??O,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 x(`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 x(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new P({apiKey:t.apiKey??this.apiKey,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})}},q="0.1.0";function W(){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?H(navigator.userAgent):{name:"unknown",version:"unknown"}}function H(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 Y(){let e=W();return `CardDB-SDK/js/${q} (${e.name}/${e.version})`}function Ne(){return q}var A=null;function z(){return A}var Z=class{config;constructor(e){this.config=e;}async execute(e,t={}){let r=this.extractOperationName(e),s=0,i=0;for(;;)try{let a=Date.now();this.logRequest(r,t);let n=await this.fetch(e,t),c=Date.now()-a,h=await this.handleResponse(n);return this.logResponse(r,c),h}catch(a){if(a instanceof b&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let n=a.retryAfter??60;this.logRateLimitRetry(r,s,n),await this.sleep(n*1e3);continue}if(this.isRetryableNetworkError(a)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let n=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,n,a),i++,await this.sleep(n);continue}if(a instanceof D&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let n=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,n,a),i++,await this.sleep(n);continue}throw a}}isRetryableNetworkError(e){return e instanceof w||e instanceof S}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":Y(),...this.config.apiKey?{"X-API-Key":this.config.apiKey}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(i){throw i instanceof Error?i.name==="AbortError"?(this.logError("Request timed out"),new S("Request timed out")):(this.logError(`Connection failed: ${i.message}`),new w(`Connection failed: ${i.message}`)):new w("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new R("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 D(`Server error (${e.status})`,{status:e.status,response:t})}throw new u(`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 R(s,t);case "RATE_LIMITED":throw new b(s,{response:t});case "NOT_FOUND":throw new u(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new k(s,{errors:e,response:t});default:throw new B(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,a=i?new Date(i*1e3):null,n=await this.parseBody(e);throw new b("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:a,response:n})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new k(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;A={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 ee(e,t,r){let s=Object.entries(r).filter(([,i])=>i!==void 0).sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>`${i}=${JSON.stringify(a)}`).join("&");return `carddb:${e}:${t}:${s}`}async function te(e,t){let r=e.get(t);return r}async function re(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,a=this.config.cache;if(!i||!a)return s();let n=await te(a,e);if(n!==null)return n;let c=await s();if(c!=null){let h=this.config.cacheTtlFor(t);await re(a,e,c,h);}return c}cacheKey(e,t,r){return ee(e,t,r)}},se=class extends f{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=o.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 a=>this.search({...e,after:a})})}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}=o.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=o.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}=o.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)}},ie=class extends f{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=o.searchGames({publisherSlug:t,search:e.search,first:e.first,after:e.after}),i=this.cacheKey("games","search",s),a=await this.withCache(i,"games",e,async()=>(await this.connection.execute(r,s)).searchGames);return new l(a,{nextPageLoader:async n=>this.search({...e,after:n})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,a=r??{};this.validateAccess(s,i);let n=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(n,"games",a,async()=>{let{query:c}=o.fetchGameByKeys();return (await this.connection.execute(c,{publisherSlug:s,gameKey:i})).fetchGame??null})}else {let s=e,i=t??{},a=this.cacheKey("games","get",{id:s});return this.withCache(a,"games",i,async()=>{let{query:n}=o.fetchGameById();return (await this.connection.execute(n,{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}=o.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},ae=class extends f{constructor(e,t){super(e,t);}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}=o.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),a=this.cacheKey("datasets","search",i),n=await this.withCache(a,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(n,{nextPageLoader:async c=>this.search({...e,after:c})})}async get(e,t,r,s){if(typeof t=="string"&&typeof r=="string"){let i=e,a=t,n=s??{};this.validateAccess(i,a);let c=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:a,datasetKey:r});return this.withCache(c,"datasets",n,async()=>{let{query:h}=o.fetchDatasetByKeys();return (await this.connection.execute(h,{publisherSlug:i,gameKey:a,datasetKey:r})).fetchDataset??null})}else {let i=e,a=t??{},n=this.cacheKey("datasets","get",{id:i});return this.withCache(n,"datasets",a,async()=>{let{query:c}=o.fetchDatasetById();return (await this.connection.execute(c,{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}=o.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},ne=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}=o.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=o.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=o.listMyDecks({first:e.first,after:e.after}),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 a=>this.listMine({...e,after:a})})}async create(e){let{query:t}=o.createDeck(),r=o.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=o.updateDeck(),s=o.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async delete(e){let{query:t}=o.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}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(c=>c.identifier),i=this.cacheKey("decks","hydrateEntries",{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s}),a=await this.withCache(i,"decks",e,async()=>{let{query:c}=o.fetchRecordsByIdentifier();return (await this.connection.execute(c,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),n=ce(a,s,e.identifierField);return e.entries.map(c=>({...c,record:n.get(c.identifier)??null}))}};function ce(e,t,r){let s=new Set(t),i=new Map;for(let a of e){let n=r?a.data[r]:Object.values(a.data).find(h=>s.has(String(h)));if(n==null)continue;let c=String(n);s.has(c)&&(i.set(c,a),s.delete(c));}return i}var oe=class extends f{constructor(e,t){super(e,t);}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=E(e.filter),{query:i,variables:a}=o.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}),n=this.cacheKey("records","search",a),c=await this.withCache(n,"records",e,async()=>(await this.connection.execute(i,a)).searchRecords);return new l(c,{nextPageLoader:async h=>this.search({...e,after:h})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e});return this.withCache(r,"records",t,async()=>{let{query:s}=o.fetchRecordById();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});return this.withCache(s,"records",e,async()=>{let{query:i}=o.fetchRecordByIdentifier();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});return this.withCache(s,"records",e,async()=>{let{query:i}=o.fetchRecordsByIdentifier();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});return this.withCache(r,"records",t,async()=>{let{query:s}=o.fetchRecords();return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},he=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}=o.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),a=this.cacheKey("rules","datasets",i),n=await this.withCache(a,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new l(n,{nextPageLoader:async c=>this.datasets({...e,after:c})})}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 a=E(t.filter),{query:n,variables:c}=o.searchRecords({publisherSlug:r,gameKey:s,datasetKey:i,filter:a,search:t.search,orderBy:t.orderBy,resolveLinks:t.resolveLinks,first:t.first,after:t.after,validateSchema:t.validateSchema}),h=this.cacheKey("rules","records",c),I=await this.withCache(h,"records",t,async()=>(await this.connection.execute(n,c)).searchRecords);return new l(I,{nextPageLoader:async K=>this.searchRuleRecords(e,{...t,after:K})})}},Ue=class G{config;connection;publishers;games;datasets;records;decks;rules;constructor(t={}){this.config=new J(t),this.connection=new Z(this.config),this.publishers=new se(this.connection,this.config),this.games=new ie(this.connection,this.config),this.datasets=new ae(this.connection,this.config),this.records=new oe(this.connection,this.config),this.decks=new ne(this.connection,this.config),this.rules=new he(this.connection,this.config);}async me(){let{query:t}=o.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return z()}withConfig(t){let r=this.config.merge(t);return new G({apiKey:r.apiKey,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})}};
331
- export{R as AuthenticationError,f as BaseResource,$ as BrowserCache,Ue as CardDBClient,u as CardDBError,l as Collection,J as Configuration,Z as Connection,w as ConnectionError,O as DEFAULT_CACHE_TTL,U as DEFAULT_ENDPOINT,V as DEFAULT_MAX_NETWORK_RETRIES,j as DEFAULT_MAX_RETRIES,_ as DEFAULT_OPEN_TIMEOUT,X as DEFAULT_RETRY_BASE_DELAY,Q as DEFAULT_RETRY_MAX_DELAY,M as DEFAULT_TIMEOUT,ae as DatasetsResource,ne as DecksResource,F as FilterBuilder,ie as GamesResource,B as GraphQLError,de as LinkResolutionError,le as NotFoundError,se as PublishersResource,o as QueryBuilder,b as RateLimitError,oe as RecordsResource,x as RestrictedError,he as RulesResource,D as ServerError,S as TimeoutError,k as ValidationError,ee as cacheKey,$e as contains,fe as eq,z as getRateLimitInfo,Ne as getSDKVersion,Y as getUserAgent,ge as gt,me as gte,ke as ilike,Se as isNotNull,xe as isNull,Re as like,we as lt,pe as lte,ye as neq,be as notWithin,te as readCache,E as resolveFilter,ve as within,re as writeCache};//# sourceMappingURL=index.js.map
451
+ `}}},h=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 j="https://carddb.xtda.org/query",X=3e4,Q=1e4,H=300,J=3,W=2,Y=1e3,z=3e4,Z=class F{apiKey;endpoint;timeout;openTimeout;defaultPublisher;defaultGame;allowedPublishers;allowedGames;logger;logLevel;retryOnRateLimit;maxRetries;retryOnNetworkError;maxNetworkRetries;retryBaseDelay;retryMaxDelay;cache;cacheTtl;cacheTtls;constructor(t={}){this.apiKey=t.apiKey,this.endpoint=t.endpoint??j,this.timeout=t.timeout??X,this.openTimeout=t.openTimeout??Q,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??J,this.retryOnNetworkError=t.retryOnNetworkError??true,this.maxNetworkRetries=t.maxNetworkRetries??W,this.retryBaseDelay=t.retryBaseDelay??Y,this.retryMaxDelay=t.retryMaxDelay??z,this.cache=t.cache,this.cacheTtl=t.cacheTtl??H,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 S(`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 S(`Game '${r}' is not allowed for publisher '${t}'`)}validateAccess(t,r){t&&(this.validatePublisher(t),r&&this.validateGame(t,r));}shouldLog(t){let r={debug:0,info:1,warn:2,error:3};return r[t]>=r[this.logLevel]}merge(t){return new F({apiKey:t.apiKey??this.apiKey,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})}},N="0.1.0";function ee(){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?te(navigator.userAgent):{name:"unknown",version:"unknown"}}function te(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 re(){let e=ee();return `CardDB-SDK/js/${N} (${e.name}/${e.version})`}function Oe(){return N}var G=null;function se(){return G}var ie=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 a=await this.fetch(e,t),o=Date.now()-n,u=await this.handleResponse(a);return this.logResponse(r,o),u}catch(n){if(n instanceof p&&this.config.retryOnRateLimit&&s<this.config.maxRetries){s++;let a=n.retryAfter??60;this.logRateLimitRetry(r,s,a),await this.sleep(a*1e3);continue}if(this.isRetryableNetworkError(n)&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let a=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,a,n),i++,await this.sleep(a);continue}if(n instanceof I&&this.config.retryOnNetworkError&&i<this.config.maxNetworkRetries){let a=this.config.calculateRetryDelay(i);this.logNetworkRetry(r,i+1,a,n),i++,await this.sleep(a);continue}throw n}}isRetryableNetworkError(e){return e instanceof k||e instanceof x}async fetch(e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),this.config.timeout);try{return await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":re(),...this.config.apiKey?{"X-API-Key":this.config.apiKey}:{}},body:JSON.stringify({query:e,variables:t}),signal:r.signal})}catch(i){throw i instanceof Error?i.name==="AbortError"?(this.logError("Request timed out"),new x("Request timed out")):(this.logError(`Connection failed: ${i.message}`),new k(`Connection failed: ${i.message}`)):new k("Connection failed")}finally{clearTimeout(s);}}async handleResponse(e){switch(this.extractRateLimitInfo(e),e.status){case 200:return this.handleSuccessResponse(e);case 401:throw new D("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 I(`Server error (${e.status})`,{status:e.status,response:t})}throw new l(`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 D(s,t);case "RATE_LIMITED":throw new p(s,{response:t});case "NOT_FOUND":throw new l(s,t);case "VALIDATION_ERROR":case "BAD_USER_INPUT":throw new R(s,{errors:e,response:t});default:throw new B(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,a=await this.parseBody(e);throw new p("Rate limit exceeded",{retryAfter:t,limit:r,remaining:s,resetAt:n,response:a})}async handleClientError(e){let t=await this.parseBody(e),r=t.errors?.[0]?.message??`Client error (${e.status})`;throw new R(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;G={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 ne(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 ae(e,t){let r=e.get(t);return r}async function ce(e,t,r,s){let i=e.set(t,r,s);i instanceof Promise&&await i;}var g=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 a=await ae(n,e);if(a!==null)return a;let o=await s();if(o!=null){let u=this.config.cacheTtlFor(t);await ce(n,e,o,u);}return o}cacheKey(e,t,r){return ne(e,t,r)}},oe=class extends g{constructor(e,t){super(e,t);}async search(e={}){let{query:t,variables:r}=c.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 h(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}=c.fetchPublisherById();return (await this.connection.execute(i,{id:e})).fetchPublisher??null}else {let{query:i}=c.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}=c.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)}},ue=class extends g{constructor(e,t){super(e,t);}async search(e={}){let t=this.config.resolvePublisher(e.publisherSlug);t&&this.validateAccess(t);let{query:r,variables:s}=c.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 h(n,{nextPageLoader:async a=>this.search({...e,after:a})})}async get(e,t,r){if(typeof t=="string"){let s=e,i=t,n=r??{};this.validateAccess(s,i);let a=this.cacheKey("games","getByKeys",{publisherSlug:s,gameKey:i});return this.withCache(a,"games",n,async()=>{let{query:o}=c.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:a}=c.fetchGameById();return (await this.connection.execute(a,{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}=c.fetchGames();return (await this.connection.execute(s,{ids:e})).fetchGames??[]})}},le=class extends g{constructor(e,t){super(e,t);}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}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:e.purpose,first:e.first,after:e.after}),n=this.cacheKey("datasets","search",i),a=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(a,{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,a=s??{};this.validateAccess(i,n);let o=this.cacheKey("datasets","getByKeys",{publisherSlug:i,gameKey:n,datasetKey:r});return this.withCache(o,"datasets",a,async()=>{let{query:u}=c.fetchDatasetByKeys();return (await this.connection.execute(u,{publisherSlug:i,gameKey:n,datasetKey:r})).fetchDataset??null})}else {let i=e,n=t??{},a=this.cacheKey("datasets","get",{id:i});return this.withCache(a,"datasets",n,async()=>{let{query:o}=c.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}=c.fetchDatasets();return (await this.connection.execute(s,{ids:e})).fetchDatasets??[]})}},he=class extends g{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}=c.fetchDeckById();return (await this.connection.execute(s,{id:e})).fetchDeck??null})}async fetchMine(e,t={}){let r=this.cacheKey("decks","fetchMine",{id:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.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}=c.fetchDeckBySlug();return (await this.connection.execute(n,{publisherSlug:e,gameKey:t,slug:r})).fetchDeckBySlug??null})}async fetchByExternalRef(e,t={}){let r=this.cacheKey("decks","fetchByExternalRef",{externalRef:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.fetchDeckByExternalRef();return (await this.connection.execute(s,{externalRef:e})).fetchDeckByExternalRef??null})}async listMine(e={}){let{query:t,variables:r}=c.listMyDecks({first:e.first,after:e.after}),s=this.cacheKey("decks","listMine",r),i=await this.withCache(s,"decks",e,async()=>(await this.connection.execute(t,r)).myDecks);return new h(i,{nextPageLoader:async n=>this.listMine({...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}=c.deckVersion();return (await this.connection.execute(s,{id:e})).deckVersion??null})}async listVersions(e,t={}){let{query:r,variables:s}=c.deckVersions({first:t.first,after:t.after}),i={deckId:e,...s},n=this.cacheKey("decks","listVersions",i),a=await this.withCache(n,"decks",t,async()=>(await this.connection.execute(r,i)).deckVersions);return new h(a,{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}=c.deckPreview();return (await this.connection.execute(s,{token:e})).deckPreview??null})}async listCollaborators(e,t={}){let r=this.cacheKey("decks","listCollaborators",{deckId:e});return this.withCache(r,"decks",t,async()=>{let{query:s}=c.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}=c.deckPreviewTokens();return (await this.connection.execute(s,{deckId:e})).deckPreviewTokens})}async create(e){let{query:t}=c.createDeck(),r=c.deckCreateVariables(e);return (await this.connection.execute(t,r)).deckCreate}async update(e,t){let{query:r}=c.updateDeck(),s=c.deckUpdateVariables(e,t);return (await this.connection.execute(r,s)).deckUpdate}async delete(e){let{query:t}=c.deleteDeck();return !!(await this.connection.execute(t,{id:e})).deckDelete}async publish(e,t={}){let{query:r}=c.publishDeck(),s=c.deckPublishVariables(e,t);return (await this.connection.execute(r,s)).deckPublish}async upsertCollaborator(e,t,r){let{query:s}=c.upsertDeckCollaborator(),i=c.deckCollaboratorVariables(e,t,r);return (await this.connection.execute(s,i)).deckCollaboratorUpsert}async removeCollaborator(e,t){let{query:r}=c.removeDeckCollaborator(),s=c.deckCollaboratorVariables(e,t);return !!(await this.connection.execute(r,s)).deckCollaboratorRemove}async createPreviewToken(e){let{query:t}=c.createDeckPreviewToken(),r=c.deckPreviewTokenCreateVariables(e);return (await this.connection.execute(t,r)).deckPreviewTokenCreate}async revokePreviewToken(e){let{query:t}=c.revokeDeckPreviewToken();return !!(await this.connection.execute(t,{id:e})).deckPreviewTokenRevoke}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}=c.fetchRecordsByIdentifier();return (await this.connection.execute(o,{publisherSlug:t,gameKey:r,datasetKey:e.datasetKey,identifiers:s})).fetchRecordsByIdentifier}),a=de(n,s,e.identifierField);return e.entries.map(o=>({...o,record:a.get(o.identifier)??null}))}};function de(e,t,r){let s=new Set(t),i=new Map;for(let n of e){let a=r?n.data[r]:Object.values(n.data).find(u=>s.has(String(u)));if(a==null)continue;let o=String(a);s.has(o)&&(i.set(o,n),s.delete(o));}return i}var fe=class extends g{constructor(e,t){super(e,t);}async search(e){let t=this.resolvePublisher(e.publisherSlug),r=this.resolveGame(e.gameKey);this.validateAccess(t,r);let s=E(e.filter),{query:i,variables:n}=c.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}),a=this.cacheKey("records","search",n),o=await this.withCache(a,"records",e,async()=>(await this.connection.execute(i,n)).searchRecords);return new h(o,{nextPageLoader:async u=>this.search({...e,after:u})})}async get(e,t={}){let r=this.cacheKey("records","get",{id:e});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecordById();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});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordByIdentifier();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});return this.withCache(s,"records",e,async()=>{let{query:i}=c.fetchRecordsByIdentifier();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});return this.withCache(r,"records",t,async()=>{let{query:s}=c.fetchRecords();return (await this.connection.execute(s,{ids:e})).fetchRecords??[]})}},ye=class extends g{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}=c.searchDatasets({publisherSlug:t,gameKey:r,search:e.search,purpose:"RULES",first:e.first,after:e.after}),n=this.cacheKey("rules","datasets",i),a=await this.withCache(n,"datasets",e,async()=>(await this.connection.execute(s,i)).searchDatasets);return new h(a,{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=E(t.filter),{query:a,variables:o}=c.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}),u=this.cacheKey("rules","records",o),C=await this.withCache(u,"records",t,async()=>(await this.connection.execute(a,o)).searchRecords);return new h(C,{nextPageLoader:async P=>this.searchRuleRecords(e,{...t,after:P})})}},je=class M{config;connection;publishers;games;datasets;records;decks;rules;constructor(t={}){this.config=new Z(t),this.connection=new ie(this.config),this.publishers=new oe(this.connection,this.config),this.games=new ue(this.connection,this.config),this.datasets=new le(this.connection,this.config),this.records=new fe(this.connection,this.config),this.decks=new he(this.connection,this.config),this.rules=new ye(this.connection,this.config);}async me(){let{query:t}=c.fetchMe();return (await this.connection.execute(t)).fetchMe??null}getRateLimitInfo(){return se()}withConfig(t){let r=this.config.merge(t);return new M({apiKey:r.apiKey,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})}};
452
+ export{D as AuthenticationError,g as BaseResource,$ as BrowserCache,je as CardDBClient,l as CardDBError,h as Collection,Z as Configuration,ie as Connection,k as ConnectionError,H as DEFAULT_CACHE_TTL,j as DEFAULT_ENDPOINT,W as DEFAULT_MAX_NETWORK_RETRIES,J as DEFAULT_MAX_RETRIES,Q as DEFAULT_OPEN_TIMEOUT,Y as DEFAULT_RETRY_BASE_DELAY,z as DEFAULT_RETRY_MAX_DELAY,X as DEFAULT_TIMEOUT,le as DatasetsResource,he as DecksResource,_ as FilterBuilder,ue as GamesResource,B as GraphQLError,ke as LinkResolutionError,me as NotFoundError,oe as PublishersResource,c as QueryBuilder,p as RateLimitError,fe as RecordsResource,S as RestrictedError,ye as RulesResource,I as ServerError,x as TimeoutError,R as ValidationError,ne as cacheKey,xe as contains,we as eq,se as getRateLimitInfo,Oe as getSDKVersion,re as getUserAgent,be as gt,pe as gte,Ee as ilike,Pe as isNotNull,Ce as isNull,Ie as like,$e as lt,De as lte,ve as neq,Se as notWithin,ae as readCache,E as resolveFilter,Re as within,ce as writeCache};//# sourceMappingURL=index.js.map
332
453
  //# sourceMappingURL=index.js.map