@letsmoe/otter-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +184 -2
  2. package/package.json +40 -4
  3. package/src/aes-gcm.ts +189 -0
  4. package/src/client.ts +23 -0
  5. package/src/context.ts +74 -0
  6. package/src/definition.ts +81 -0
  7. package/src/errors.ts +61 -0
  8. package/src/extract.ts +134 -0
  9. package/src/generated/index.ts +79 -0
  10. package/src/generated/runtime/batcher.ts +275 -0
  11. package/src/generated/runtime/createClient.ts +68 -0
  12. package/src/generated/runtime/error.ts +29 -0
  13. package/src/generated/runtime/fetcher.ts +97 -0
  14. package/src/generated/runtime/generateGraphqlOperation.ts +225 -0
  15. package/src/generated/runtime/index.ts +13 -0
  16. package/src/generated/runtime/linkTypeMap.ts +156 -0
  17. package/src/generated/runtime/typeSelection.ts +95 -0
  18. package/src/generated/runtime/types.ts +69 -0
  19. package/src/generated/schema.graphql +657 -0
  20. package/src/generated/schema.ts +1338 -0
  21. package/src/generated/types.ts +1495 -0
  22. package/src/hosters/dead-link.ts +55 -0
  23. package/src/hosters/dood.ts +69 -0
  24. package/src/hosters/filemoon.ts +152 -0
  25. package/src/hosters/generic.ts +63 -0
  26. package/src/hosters/index.ts +14 -0
  27. package/src/hosters/recaptcha.ts +61 -0
  28. package/src/hosters/registry.ts +74 -0
  29. package/src/hosters/streamtape.ts +63 -0
  30. package/src/hosters/vidara.ts +48 -0
  31. package/src/hosters/vinovo.ts +55 -0
  32. package/src/hosters/voe-decoding.ts +131 -0
  33. package/src/hosters/voe-domains.ts +39 -0
  34. package/src/hosters/voe.ts +82 -0
  35. package/src/http-client.ts +295 -0
  36. package/src/http.ts +97 -0
  37. package/src/index.ts +9 -0
  38. package/src/languages.ts +73 -0
  39. package/src/match.ts +120 -0
  40. package/src/model.ts +110 -0
  41. package/src/packer.ts +106 -0
  42. package/src/plugin.ts +4 -0
  43. package/src/run.ts +74 -0
  44. package/src/runtime.ts +254 -0
  45. package/src/testing.ts +120 -0
  46. package/src/timing.ts +11 -0
  47. package/src/types.ts +122 -0
  48. package/src/url.ts +60 -0
package/src/extract.ts ADDED
@@ -0,0 +1,134 @@
1
+ import { parse } from "node-html-parser";
2
+ import type { MimeType } from "./model.ts";
3
+ import { unpack } from "./packer.ts";
4
+ import { resolveAgainst } from "./url.ts";
5
+
6
+ export interface ExtractedMedia {
7
+ url: string;
8
+ mime_type: MimeType;
9
+ }
10
+
11
+ const URL_TOKEN = /https?:\/\/[^\s"'<>\\)]+/gi;
12
+ const MEDIA_PATH = /\.(m3u8|mpd|mp4|webm)(?:[?#]|$)/i;
13
+
14
+ /** The media type a URL's extension says; `fallback` applies when it has no known one. */
15
+ export function mimeType(url: string, fallback: MimeType = "video/mp4"): MimeType {
16
+ if (/\.m3u8/i.test(url)) return "application/x-mpegURL";
17
+ if (/\.mpd/i.test(url)) return "application/dash+xml";
18
+ if (/\.webm/i.test(url)) return "video/webm";
19
+ if (/\.mp4/i.test(url)) return "video/mp4";
20
+ return fallback;
21
+ }
22
+
23
+ /** Makes URLs written inside JSON or HTML attributes plain: `https:\/\/a&b` -> `https://a&b`. */
24
+ function unescapeUrls(text: string): string {
25
+ return text
26
+ .replace(/\\\//g, "/")
27
+ .replace(/\\u0026/gi, "&")
28
+ .replace(/&amp;/g, "&");
29
+ }
30
+
31
+ function mediaUrlsIn(text: string): string[] {
32
+ const tokens = unescapeUrls(text).match(URL_TOKEN) || [];
33
+ const urls: string[] = [];
34
+ for (const token of tokens) {
35
+ const url = token.replace(/[,;]+$/, "");
36
+ if (MEDIA_PATH.test(url)) urls.push(url);
37
+ }
38
+ return urls;
39
+ }
40
+
41
+ /** Every m3u8/mpd/mp4/webm URL in a page, including those inside packed scripts, in page order. */
42
+ export function mediaUrls(html: string): ExtractedMedia[] {
43
+ const unpacked = unpack(html);
44
+ const found = mediaUrlsIn(html);
45
+ if (unpacked !== undefined) found.push(...mediaUrlsIn(unpacked));
46
+ const unique = [...new Set(found)];
47
+ return unique.map((url) => ({ url, mime_type: mimeType(url) }));
48
+ }
49
+
50
+ function usableFrameUrl(source: string, pageUrl: string): string | undefined {
51
+ if (!source || /^(javascript|about|data):/i.test(source)) return undefined;
52
+ try {
53
+ return resolveAgainst(pageUrl, source);
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+
59
+ /** Absolute URLs of the page's iframes. */
60
+ export function iframes(html: string, pageUrl: string): string[] {
61
+ const urls: string[] = [];
62
+ for (const frame of parse(html).querySelectorAll("iframe")) {
63
+ const source = frame.getAttribute("src") || frame.getAttribute("data-src") || "";
64
+ const url = usableFrameUrl(source, pageUrl);
65
+ if (url) urls.push(url);
66
+ }
67
+ return urls;
68
+ }
69
+
70
+ function escapeRegExp(text: string): string {
71
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
72
+ }
73
+
74
+ /** The balanced JSON object or array starting at `start`, or undefined if it never closes. */
75
+ function balancedJson(text: string, start: number): string | undefined {
76
+ const opening = text[start];
77
+ const closing = opening === "{" ? "}" : "]";
78
+ let depth = 0;
79
+ let insideString = false;
80
+ for (let position = start; position < text.length; position++) {
81
+ const character = text[position];
82
+ if (insideString) {
83
+ if (character === "\\") position += 1;
84
+ else if (character === '"') insideString = false;
85
+ continue;
86
+ }
87
+ if (character === '"') insideString = true;
88
+ else if (character === opening) depth += 1;
89
+ else if (character === closing) depth -= 1;
90
+ if (depth === 0) return text.slice(start, position + 1);
91
+ }
92
+ return undefined;
93
+ }
94
+
95
+ function tryParse(json: string | undefined): unknown {
96
+ if (json === undefined) return undefined;
97
+ try {
98
+ return JSON.parse(json);
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ }
103
+
104
+ function jsonScriptWithId(html: string, id: string): unknown {
105
+ const script = parse(html).querySelector(`script[id="${id}"]`);
106
+ if (!script) return undefined;
107
+ return tryParse(script.textContent);
108
+ }
109
+
110
+ /**
111
+ * The JSON value assigned to `variableName` in a page script
112
+ * (`var data = {...}`, `window.data = [...]`, `"data": {...}`), or the content
113
+ * of `<script id="variableName">`. Undefined when absent or not valid JSON.
114
+ */
115
+ export function scriptJson(html: string, variableName: string): unknown {
116
+ const fromScriptTag = jsonScriptWithId(html, variableName);
117
+ if (fromScriptTag !== undefined) return fromScriptTag;
118
+
119
+ const assignment = new RegExp(`${escapeRegExp(variableName)}["']?\\s*[:=]\\s*([\\[{])`);
120
+ const found = assignment.exec(html);
121
+ if (!found) return undefined;
122
+ const start = found.index + found[0].length - 1;
123
+ return tryParse(balancedJson(html, start));
124
+ }
125
+
126
+ /** Decodes base64, also the URL-safe alphabet and missing padding. */
127
+ export function base64(text: string): string {
128
+ const standard = text.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
129
+ const padding = (4 - (standard.length % 4)) % 4;
130
+ return Buffer.from(standard + "=".repeat(padding), "base64").toString("utf-8");
131
+ }
132
+
133
+ export const extract = { mediaUrls, unpack, iframes, scriptJson, base64, mimeType };
134
+ export type Extractor = typeof extract;
@@ -0,0 +1,79 @@
1
+ // @ts-nocheck
2
+ import type {
3
+ QueryGenqlSelection,
4
+ Query,
5
+ MutationGenqlSelection,
6
+ Mutation,
7
+ SubscriptionGenqlSelection,
8
+ Subscription,
9
+ } from './schema'
10
+ import {
11
+ linkTypeMap,
12
+ createClient as createClientOriginal,
13
+ generateGraphqlOperation,
14
+ type FieldsSelection,
15
+ type GraphqlOperation,
16
+ type ClientOptions,
17
+ GenqlError,
18
+ } from './runtime'
19
+ export type { FieldsSelection } from './runtime'
20
+ export { GenqlError }
21
+
22
+ import types from './types'
23
+ export * from './schema'
24
+ const typeMap = linkTypeMap(types as any)
25
+
26
+ export interface Client {
27
+ query<R extends QueryGenqlSelection>(
28
+ request: R & { __name?: string },
29
+ ): Promise<FieldsSelection<Query, R>>
30
+
31
+ mutation<R extends MutationGenqlSelection>(
32
+ request: R & { __name?: string },
33
+ ): Promise<FieldsSelection<Mutation, R>>
34
+ }
35
+
36
+ export const createClient = function (options?: ClientOptions): Client {
37
+ return createClientOriginal({
38
+ url: undefined,
39
+
40
+ ...options,
41
+ queryRoot: typeMap.Query!,
42
+ mutationRoot: typeMap.Mutation!,
43
+ subscriptionRoot: typeMap.Subscription!,
44
+ }) as any
45
+ }
46
+
47
+ export const everything = {
48
+ __scalar: true,
49
+ }
50
+
51
+ export type QueryResult<fields extends QueryGenqlSelection> = FieldsSelection<
52
+ Query,
53
+ fields
54
+ >
55
+ export const generateQueryOp: (
56
+ fields: QueryGenqlSelection & { __name?: string },
57
+ ) => GraphqlOperation = function (fields) {
58
+ return generateGraphqlOperation('query', typeMap.Query!, fields as any)
59
+ }
60
+
61
+ export type MutationResult<fields extends MutationGenqlSelection> =
62
+ FieldsSelection<Mutation, fields>
63
+ export const generateMutationOp: (
64
+ fields: MutationGenqlSelection & { __name?: string },
65
+ ) => GraphqlOperation = function (fields) {
66
+ return generateGraphqlOperation('mutation', typeMap.Mutation!, fields as any)
67
+ }
68
+
69
+ export type SubscriptionResult<fields extends SubscriptionGenqlSelection> =
70
+ FieldsSelection<Subscription, fields>
71
+ export const generateSubscriptionOp: (
72
+ fields: SubscriptionGenqlSelection & { __name?: string },
73
+ ) => GraphqlOperation = function (fields) {
74
+ return generateGraphqlOperation(
75
+ 'subscription',
76
+ typeMap.Subscription!,
77
+ fields as any,
78
+ )
79
+ }
@@ -0,0 +1,275 @@
1
+ // @ts-nocheck
2
+ import type { GraphqlOperation } from './generateGraphqlOperation'
3
+ import { GenqlError } from './error'
4
+
5
+ type Variables = Record<string, any>
6
+
7
+ type QueryError = Error & {
8
+ message: string
9
+
10
+ locations?: Array<{
11
+ line: number
12
+ column: number
13
+ }>
14
+ path?: any
15
+ rid: string
16
+ details?: Record<string, any>
17
+ }
18
+ type Result = {
19
+ data: Record<string, any>
20
+ errors: Array<QueryError>
21
+ }
22
+ type Fetcher = (
23
+ batchedQuery: GraphqlOperation | Array<GraphqlOperation>,
24
+ ) => Promise<Array<Result>>
25
+ type Options = {
26
+ batchInterval?: number
27
+ shouldBatch?: boolean
28
+ maxBatchSize?: number
29
+ }
30
+ type Queue = Array<{
31
+ request: GraphqlOperation
32
+ resolve: (...args: Array<any>) => any
33
+ reject: (...args: Array<any>) => any
34
+ }>
35
+
36
+ /**
37
+ * takes a list of requests (queue) and batches them into a single server request.
38
+ * It will then resolve each individual requests promise with the appropriate data.
39
+ * @private
40
+ * @param {QueryBatcher} client - the client to use
41
+ * @param {Queue} queue - the list of requests to batch
42
+ */
43
+ function dispatchQueueBatch(client: QueryBatcher, queue: Queue): void {
44
+ let batchedQuery: any = queue.map((item) => item.request)
45
+
46
+ if (batchedQuery.length === 1) {
47
+ batchedQuery = batchedQuery[0]
48
+ }
49
+ (() => {
50
+ try {
51
+ return client.fetcher(batchedQuery);
52
+ } catch(e) {
53
+ return Promise.reject(e);
54
+ }
55
+ })().then((responses: any) => {
56
+ if (queue.length === 1 && !Array.isArray(responses)) {
57
+ if (responses.errors && responses.errors.length) {
58
+ queue[0].reject(
59
+ new GenqlError(responses.errors, responses.data),
60
+ )
61
+ return
62
+ }
63
+
64
+ queue[0].resolve(responses)
65
+ return
66
+ } else if (responses.length !== queue.length) {
67
+ throw new Error('response length did not match query length')
68
+ }
69
+
70
+ for (let i = 0; i < queue.length; i++) {
71
+ if (responses[i].errors && responses[i].errors.length) {
72
+ queue[i].reject(
73
+ new GenqlError(responses[i].errors, responses[i].data),
74
+ )
75
+ } else {
76
+ queue[i].resolve(responses[i])
77
+ }
78
+ }
79
+ })
80
+ .catch((e) => {
81
+ for (let i = 0; i < queue.length; i++) {
82
+ queue[i].reject(e)
83
+ }
84
+ });
85
+ }
86
+
87
+ /**
88
+ * creates a list of requests to batch according to max batch size.
89
+ * @private
90
+ * @param {QueryBatcher} client - the client to create list of requests from from
91
+ * @param {Options} options - the options for the batch
92
+ */
93
+ function dispatchQueue(client: QueryBatcher, options: Options): void {
94
+ const queue = client._queue
95
+ const maxBatchSize = options.maxBatchSize || 0
96
+ client._queue = []
97
+
98
+ if (maxBatchSize > 0 && maxBatchSize < queue.length) {
99
+ for (let i = 0; i < queue.length / maxBatchSize; i++) {
100
+ dispatchQueueBatch(
101
+ client,
102
+ queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize),
103
+ )
104
+ }
105
+ } else {
106
+ dispatchQueueBatch(client, queue)
107
+ }
108
+ }
109
+ /**
110
+ * Create a batcher client.
111
+ * @param {Fetcher} fetcher - A function that can handle the network requests to graphql endpoint
112
+ * @param {Options} options - the options to be used by client
113
+ * @param {boolean} options.shouldBatch - should the client batch requests. (default true)
114
+ * @param {integer} options.batchInterval - duration (in MS) of each batch window. (default 6)
115
+ * @param {integer} options.maxBatchSize - max number of requests in a batch. (default 0)
116
+ * @param {boolean} options.defaultHeaders - default headers to include with every request
117
+ *
118
+ * @example
119
+ * const fetcher = batchedQuery => fetch('path/to/graphql', {
120
+ * method: 'post',
121
+ * headers: {
122
+ * Accept: 'application/json',
123
+ * 'Content-Type': 'application/json',
124
+ * },
125
+ * body: JSON.stringify(batchedQuery),
126
+ * credentials: 'include',
127
+ * })
128
+ * .then(response => response.json())
129
+ *
130
+ * const client = new QueryBatcher(fetcher, { maxBatchSize: 10 })
131
+ */
132
+
133
+ export class QueryBatcher {
134
+ fetcher: Fetcher
135
+ _options: Options
136
+ _queue: Queue
137
+
138
+ constructor(
139
+ fetcher: Fetcher,
140
+ {
141
+ batchInterval = 6,
142
+ shouldBatch = true,
143
+ maxBatchSize = 0,
144
+ }: Options = {},
145
+ ) {
146
+ this.fetcher = fetcher
147
+ this._options = {
148
+ batchInterval,
149
+ shouldBatch,
150
+ maxBatchSize,
151
+ }
152
+ this._queue = []
153
+ }
154
+
155
+ /**
156
+ * Fetch will send a graphql request and return the parsed json.
157
+ * @param {string} query - the graphql query.
158
+ * @param {Variables} variables - any variables you wish to inject as key/value pairs.
159
+ * @param {[string]} operationName - the graphql operationName.
160
+ * @param {Options} overrides - the client options overrides.
161
+ *
162
+ * @return {promise} resolves to parsed json of server response
163
+ *
164
+ * @example
165
+ * client.fetch(`
166
+ * query getHuman($id: ID!) {
167
+ * human(id: $id) {
168
+ * name
169
+ * height
170
+ * }
171
+ * }
172
+ * `, { id: "1001" }, 'getHuman')
173
+ * .then(human => {
174
+ * // do something with human
175
+ * console.log(human);
176
+ * });
177
+ */
178
+ fetch(
179
+ query: string,
180
+ variables?: Variables,
181
+ operationName?: string,
182
+ overrides: Options = {},
183
+ ): Promise<Result> {
184
+ const request: GraphqlOperation = {
185
+ query,
186
+ }
187
+ const options = Object.assign({}, this._options, overrides)
188
+
189
+ if (variables) {
190
+ request.variables = variables
191
+ }
192
+
193
+ if (operationName) {
194
+ request.operationName = operationName
195
+ }
196
+
197
+ const promise = new Promise<Result>((resolve, reject) => {
198
+ this._queue.push({
199
+ request,
200
+ resolve,
201
+ reject,
202
+ })
203
+
204
+ if (this._queue.length === 1) {
205
+ if (options.shouldBatch) {
206
+ setTimeout(
207
+ () => dispatchQueue(this, options),
208
+ options.batchInterval,
209
+ )
210
+ } else {
211
+ dispatchQueue(this, options)
212
+ }
213
+ }
214
+ })
215
+ return promise
216
+ }
217
+
218
+ /**
219
+ * Fetch will send a graphql request and return the parsed json.
220
+ * @param {string} query - the graphql query.
221
+ * @param {Variables} variables - any variables you wish to inject as key/value pairs.
222
+ * @param {[string]} operationName - the graphql operationName.
223
+ * @param {Options} overrides - the client options overrides.
224
+ *
225
+ * @return {Promise<Array<Result>>} resolves to parsed json of server response
226
+ *
227
+ * @example
228
+ * client.forceFetch(`
229
+ * query getHuman($id: ID!) {
230
+ * human(id: $id) {
231
+ * name
232
+ * height
233
+ * }
234
+ * }
235
+ * `, { id: "1001" }, 'getHuman')
236
+ * .then(human => {
237
+ * // do something with human
238
+ * console.log(human);
239
+ * });
240
+ */
241
+ forceFetch(
242
+ query: string,
243
+ variables?: Variables,
244
+ operationName?: string,
245
+ overrides: Options = {},
246
+ ): Promise<Result> {
247
+ const request: GraphqlOperation = {
248
+ query,
249
+ }
250
+ const options = Object.assign({}, this._options, overrides, {
251
+ shouldBatch: false,
252
+ })
253
+
254
+ if (variables) {
255
+ request.variables = variables
256
+ }
257
+
258
+ if (operationName) {
259
+ request.operationName = operationName
260
+ }
261
+
262
+ const promise = new Promise<Result>((resolve, reject) => {
263
+ const client = new QueryBatcher(this.fetcher, this._options)
264
+ client._queue = [
265
+ {
266
+ request,
267
+ resolve,
268
+ reject,
269
+ },
270
+ ]
271
+ dispatchQueue(client, options)
272
+ })
273
+ return promise
274
+ }
275
+ }
@@ -0,0 +1,68 @@
1
+ // @ts-nocheck
2
+
3
+ import { type BatchOptions, createFetcher } from './fetcher'
4
+ import type { ExecutionResult, LinkedType } from './types'
5
+ import {
6
+ generateGraphqlOperation,
7
+ type GraphqlOperation,
8
+ } from './generateGraphqlOperation'
9
+
10
+ export type Headers =
11
+ | HeadersInit
12
+ | (() => HeadersInit)
13
+ | (() => Promise<HeadersInit>)
14
+
15
+ export type BaseFetcher = (
16
+ operation: GraphqlOperation | GraphqlOperation[],
17
+ ) => Promise<ExecutionResult | ExecutionResult[]>
18
+
19
+ export type ClientOptions = Omit<RequestInit, 'body' | 'headers'> & {
20
+ url?: string
21
+ batch?: BatchOptions | boolean
22
+ fetcher?: BaseFetcher
23
+ fetch?: Function
24
+ headers?: Headers
25
+ }
26
+
27
+ export const createClient = ({
28
+ queryRoot,
29
+ mutationRoot,
30
+ subscriptionRoot,
31
+ ...options
32
+ }: ClientOptions & {
33
+ queryRoot?: LinkedType
34
+ mutationRoot?: LinkedType
35
+ subscriptionRoot?: LinkedType
36
+ }) => {
37
+ const fetcher = createFetcher(options)
38
+ const client: {
39
+ query?: Function
40
+ mutation?: Function
41
+ } = {}
42
+
43
+ if (queryRoot) {
44
+ client.query = (request: any) => {
45
+ if (!queryRoot) throw new Error('queryRoot argument is missing')
46
+
47
+ const resultPromise = fetcher(
48
+ generateGraphqlOperation('query', queryRoot, request),
49
+ )
50
+
51
+ return resultPromise
52
+ }
53
+ }
54
+ if (mutationRoot) {
55
+ client.mutation = (request: any) => {
56
+ if (!mutationRoot)
57
+ throw new Error('mutationRoot argument is missing')
58
+
59
+ const resultPromise = fetcher(
60
+ generateGraphqlOperation('mutation', mutationRoot, request),
61
+ )
62
+
63
+ return resultPromise
64
+ }
65
+ }
66
+
67
+ return client as any
68
+ }
@@ -0,0 +1,29 @@
1
+ // @ts-nocheck
2
+ export class GenqlError extends Error {
3
+ errors: Array<GraphqlError> = []
4
+ /**
5
+ * Partial data returned by the server
6
+ */
7
+ data?: any
8
+ constructor(errors: any[], data: any) {
9
+ let message = Array.isArray(errors)
10
+ ? errors.map((x) => x?.message || '').join('\n')
11
+ : ''
12
+ if (!message) {
13
+ message = 'GraphQL error'
14
+ }
15
+ super(message)
16
+ this.errors = errors
17
+ this.data = data
18
+ }
19
+ }
20
+
21
+ interface GraphqlError {
22
+ message: string
23
+ locations?: Array<{
24
+ line: number
25
+ column: number
26
+ }>
27
+ path?: string[]
28
+ extensions?: Record<string, any>
29
+ }
@@ -0,0 +1,97 @@
1
+ // @ts-nocheck
2
+ import { QueryBatcher } from './batcher'
3
+
4
+ import type { ClientOptions } from './createClient'
5
+ import type { GraphqlOperation } from './generateGraphqlOperation'
6
+ import { GenqlError } from './error'
7
+
8
+ export interface Fetcher {
9
+ (gql: GraphqlOperation): Promise<any>
10
+ }
11
+
12
+ export type BatchOptions = {
13
+ batchInterval?: number // ms
14
+ maxBatchSize?: number
15
+ }
16
+
17
+ const DEFAULT_BATCH_OPTIONS = {
18
+ maxBatchSize: 10,
19
+ batchInterval: 40,
20
+ }
21
+
22
+ export const createFetcher = ({
23
+ url,
24
+ headers = {},
25
+ fetcher,
26
+ fetch: _fetch,
27
+ batch = false,
28
+ ...rest
29
+ }: ClientOptions): Fetcher => {
30
+ if (!url && !fetcher) {
31
+ throw new Error('url or fetcher is required')
32
+ }
33
+
34
+ fetcher = fetcher || (async (body) => {
35
+ let headersObject =
36
+ typeof headers == 'function' ? await headers() : headers
37
+ headersObject = headersObject || {}
38
+ if (typeof fetch === 'undefined' && !_fetch) {
39
+ throw new Error(
40
+ 'Global `fetch` function is not available, pass a fetch polyfill to Genql `createClient`',
41
+ )
42
+ }
43
+ let fetchImpl = _fetch || fetch
44
+ const res = await fetchImpl(url!, {
45
+ headers: {
46
+ 'Content-Type': 'application/json',
47
+ ...headersObject,
48
+ },
49
+ method: 'POST',
50
+ body: JSON.stringify(body),
51
+ ...rest,
52
+ })
53
+ if (!res.ok) {
54
+ throw new Error(`${res.statusText}: ${await res.text()}`)
55
+ }
56
+ const json = await res.json()
57
+ return json
58
+ })
59
+
60
+ if (!batch) {
61
+ return async (body) => {
62
+ const json = await fetcher!(body)
63
+ if (Array.isArray(json)) {
64
+ return json.map((json) => {
65
+ if (json?.errors?.length) {
66
+ throw new GenqlError(json.errors || [], json.data)
67
+ }
68
+ return json.data
69
+ })
70
+ } else {
71
+ if (json?.errors?.length) {
72
+ throw new GenqlError(json.errors || [], json.data)
73
+ }
74
+ return json.data
75
+ }
76
+ }
77
+ }
78
+
79
+ const batcher = new QueryBatcher(
80
+ async (batchedQuery) => {
81
+ // console.log(batchedQuery) // [{ query: 'query{user{age}}', variables: {} }, ...]
82
+ const json = await fetcher!(batchedQuery)
83
+ return json as any
84
+ },
85
+ batch === true ? DEFAULT_BATCH_OPTIONS : batch,
86
+ )
87
+
88
+ return async ({ query, variables }) => {
89
+ const json = await batcher.fetch(query, variables)
90
+ if (json?.data) {
91
+ return json.data
92
+ }
93
+ throw new Error(
94
+ 'Genql batch fetcher returned unexpected result ' + JSON.stringify(json),
95
+ )
96
+ }
97
+ }