arangojs 7.3.0 → 7.6.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 (56) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +4 -2
  3. package/analyzer.d.ts +188 -1
  4. package/analyzer.d.ts.map +1 -1
  5. package/analyzer.js.map +1 -1
  6. package/aql.d.ts +2 -1
  7. package/aql.d.ts.map +1 -1
  8. package/aql.js +5 -1
  9. package/aql.js.map +1 -1
  10. package/collection.d.ts +72 -11
  11. package/collection.d.ts.map +1 -1
  12. package/collection.js +16 -3
  13. package/collection.js.map +1 -1
  14. package/connection.d.ts +3 -3
  15. package/connection.d.ts.map +1 -1
  16. package/connection.js +21 -9
  17. package/connection.js.map +1 -1
  18. package/cursor.js +4 -4
  19. package/cursor.js.map +1 -1
  20. package/database.d.ts +451 -4
  21. package/database.d.ts.map +1 -1
  22. package/database.js +357 -0
  23. package/database.js.map +1 -1
  24. package/documents.d.ts +6 -6
  25. package/documents.d.ts.map +1 -1
  26. package/documents.js +2 -2
  27. package/documents.js.map +1 -1
  28. package/error.d.ts +10 -0
  29. package/error.d.ts.map +1 -1
  30. package/error.js +14 -0
  31. package/error.js.map +1 -1
  32. package/graph.d.ts +16 -4
  33. package/graph.d.ts.map +1 -1
  34. package/graph.js +18 -1
  35. package/graph.js.map +1 -1
  36. package/indexes.d.ts +70 -0
  37. package/indexes.d.ts.map +1 -1
  38. package/indexes.js.map +1 -1
  39. package/lib/error.d.ts.map +1 -1
  40. package/lib/error.js +1 -0
  41. package/lib/error.js.map +1 -1
  42. package/lib/multipart.d.ts.map +1 -1
  43. package/lib/multipart.js +1 -0
  44. package/lib/multipart.js.map +1 -1
  45. package/lib/normalizeUrl.js +1 -1
  46. package/lib/normalizeUrl.js.map +1 -1
  47. package/lib/request.node.js.map +1 -1
  48. package/lib/xhr.d.ts.map +1 -1
  49. package/lib/xhr.js +1 -0
  50. package/lib/xhr.js.map +1 -1
  51. package/package.json +1 -1
  52. package/view.d.ts +1 -1
  53. package/view.d.ts.map +1 -1
  54. package/view.js.map +1 -1
  55. package/web.js +1 -1
  56. package/web.js.map +1 -1
package/connection.d.ts CHANGED
@@ -228,10 +228,10 @@ export declare type RequestOptions = {
228
228
  */
229
229
  declare type Task = {
230
230
  host?: number;
231
- stack?: string;
231
+ stack?: () => string;
232
232
  allowDirtyRead: boolean;
233
- resolve: Function;
234
- reject: Function;
233
+ resolve: (res: ArangojsResponse) => void;
234
+ reject: (error: Error) => void;
235
235
  retries: number;
236
236
  options: {
237
237
  method: string;
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,YAAY,IAAI,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAEzD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAUtC,OAAO,EACL,aAAa,EACb,gBAAgB,EAGhB,eAAe,EAChB,MAAM,eAAe,CAAC;AAKvB;;;;GAIG;AACH,oBAAY,IAAI,CAAC,CAAC,IAAI;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,CAAA;CAAE,CAAC;AAE3C;;;;;;;;;;;GAWG;AACH,oBAAY,qBAAqB,GAAG,MAAM,GAAG,aAAa,GAAG,YAAY,CAAC;AAE1E;;;;;GAKG;AACH,oBAAY,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;AAEnC;;;GAGG;AACH,oBAAY,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AAE/B;;GAEG;AACH,oBAAY,sBAAsB,GAAG;IACnC;;OAEG;IACH,KAAK,EAAE,KAAK,CAAC;IACb;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAY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IACH,KAAK;IAML;;;;;;;;;OASG;IACG,kBAAkB,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,SAAW;IA2BpE;;;;OAIG;IACH,OAAO,CAAC,CAAC,GAAG,gBAAgB,EAC1B,EACE,IAAI,EACJ,MAAc,EACd,IAAI,EACJ,YAAoB,EACpB,QAAgB,EAChB,cAAsB,EACtB,OAAW,EACX,OAAO,EACP,GAAG,OAAO,EACX,EAAE,cAAc,EACjB,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,CAAC,GACvC,OAAO,CAAC,CAAC,CAAC;CAsGd"}
package/connection.js CHANGED
@@ -36,7 +36,7 @@ function generateStackTrace() {
36
36
  err = e;
37
37
  }
38
38
  }
39
- return err.stack;
39
+ return err;
40
40
  }
41
41
  /**
42
42
  * Indicates whether the given value represents a {@link Connection}.
@@ -170,7 +170,7 @@ class Connection {
170
170
  }
171
171
  else {
172
172
  if (task.stack) {
173
- err.stack += task.stack;
173
+ err.stack += task.stack();
174
174
  }
175
175
  task.reject(err);
176
176
  }
@@ -391,6 +391,9 @@ class Connection {
391
391
  parsedBody = res.body.toString("utf-8");
392
392
  }
393
393
  e.response = res;
394
+ if (task.stack) {
395
+ e.stack += task.stack();
396
+ }
394
397
  reject(e);
395
398
  return;
396
399
  }
@@ -404,11 +407,19 @@ class Connection {
404
407
  }
405
408
  if (error_1.isArangoErrorResponse(parsedBody)) {
406
409
  res.body = parsedBody;
407
- reject(new error_1.ArangoError(res));
410
+ const err = new error_1.ArangoError(res);
411
+ if (task.stack) {
412
+ err.stack += task.stack();
413
+ }
414
+ reject(err);
408
415
  }
409
416
  else if (res.statusCode && res.statusCode >= 400) {
410
417
  res.body = parsedBody;
411
- reject(new error_1.HttpError(res));
418
+ const err = new error_1.HttpError(res);
419
+ if (task.stack) {
420
+ err.stack += task.stack();
421
+ }
422
+ reject(err);
412
423
  }
413
424
  else {
414
425
  if (!expectBinary)
@@ -419,13 +430,14 @@ class Connection {
419
430
  };
420
431
  if (this._precaptureStackTraces) {
421
432
  if (typeof Error.captureStackTrace === "function") {
422
- Error.captureStackTrace(task);
423
- task.stack = `\n${task.stack.split("\n").slice(3).join("\n")}`;
433
+ const capture = {};
434
+ Error.captureStackTrace(capture);
435
+ task.stack = () => `\n${capture.stack.split("\n").slice(3).join("\n")}`;
424
436
  }
425
437
  else {
426
- const stack = generateStackTrace();
427
- if (stack) {
428
- task.stack = `\n${stack.split("\n").slice(4).join("\n")}`;
438
+ const capture = generateStackTrace();
439
+ if (Object.prototype.hasOwnProperty.call(capture, "stack")) {
440
+ task.stack = () => `\n${capture.stack.split("\n").slice(4).join("\n")}`;
429
441
  }
430
442
  }
431
443
  }
package/connection.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"connection.js","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":";;;AAYA,6CAA0D;AAC1D,iDAA2C;AAE3C,mCAKiB;AACjB,qCAAkC;AAElC,qDAAkD;AAClD,2CAMuB;AAEvB,MAAM,SAAS,GAAG,2BAA2B,CAAC;AAC9C,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AAmDnD,SAAS,KAAK,CAAI,GAAM;IACtB,MAAM,MAAM,GAAG,EAAgB,CAAC;IAChC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAClC,MAAM,KAAK,GAAI,GAAW,CAAC,GAAG,CAAC,CAAC;QAChC,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QACjC,MAAc,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;KAC9B;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AA0BD,SAAS,YAAY,CAAC,IAAS;IAC7B,OAAO,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;AAED;;;GAGG;AACH,SAAS,kBAAkB;IACzB,IAAI,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC;IACtB,IAAI,CAAC,GAAG,CA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;CACF;AA/bD,gCA+bC","sourcesContent":["/**\n * ```ts\n * import type { Config } from \"arangojs/connection\";\n * ```\n *\n * The \"connection\" module provides connection and configuration related types\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ClientRequest } from \"http\";\nimport { AgentOptions as NodeAgentOptions } from \"https\";\nimport { stringify as querystringify } from \"querystring\";\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\nimport {\n ArangoError,\n HttpError,\n isArangoErrorResponse,\n isSystemError,\n} from \"./error\";\nimport { btoa } from \"./lib/btoa\";\nimport { Errback } from \"./lib/errback\";\nimport { normalizeUrl } from \"./lib/normalizeUrl\";\nimport {\n ArangojsError,\n ArangojsResponse,\n createRequest,\n isBrowser,\n RequestFunction,\n} from \"./lib/request\";\n\nconst MIME_JSON = /\\/(json|javascript)(\\W|$)/;\nconst LEADER_ENDPOINT_HEADER = \"x-arango-endpoint\";\n\n/**\n * Generic type representing an object with values of a given value type.\n *\n * @param T - Type of the object's property values.\n */\nexport type Dict<T> = { [key: string]: T };\n\n/**\n * Determines the behavior when multiple URLs are used:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n */\nexport type LoadBalancingStrategy = \"NONE\" | \"ROUND_ROBIN\" | \"ONE_RANDOM\";\n\n/**\n * An arbitrary object with string values representing HTTP headers and their\n * values.\n *\n * Header names should always be lowercase.\n */\nexport type Headers = Dict<string>;\n\n/**\n * An arbitrary object with scalar values representing query string parameters\n * and their values.\n */\nexport type Params = Dict<any>;\n\n/**\n * Generic properties shared by all ArangoDB HTTP API responses.\n */\nexport type ArangoResponseMetadata = {\n /**\n * Indicates that the request was successful.\n */\n error: false;\n /**\n * Response status code, typically `200`.\n */\n code: number;\n};\n\nfunction clean<T>(obj: T) {\n const result = {} as typeof obj;\n for (const key of Object.keys(obj)) {\n const value = (obj as any)[key];\n if (value === undefined) continue;\n (result as any)[key] = value;\n }\n return result;\n}\n\n/**\n * Credentials for HTTP Basic authentication.\n */\nexport type BasicAuthCredentials = {\n /**\n * Username to use for authentication, e.g. `\"root\"`.\n */\n username: string;\n /**\n * Password to use for authentication. Defaults to an empty string.\n */\n password?: string;\n};\n\n/**\n * Credentials for HTTP Bearer token authentication.\n */\nexport type BearerAuthCredentials = {\n /**\n * Bearer token to use for authentication.\n */\n token: string;\n};\n\nfunction isBearerAuth(auth: any): auth is BearerAuthCredentials {\n return auth.hasOwnProperty(\"token\");\n}\n\n/**\n * @internal\n * @hidden\n */\nfunction generateStackTrace() {\n let err = new Error();\n if (!err.stack) {\n try {\n throw err;\n } catch (e) {\n err = e;\n }\n }\n return err.stack;\n}\n\n/**\n * @internal\n * @hidden\n */\ntype UrlInfo = {\n absolutePath?: boolean;\n basePath?: string;\n path?: string;\n qs?: string | Params;\n};\n\n/**\n * Options of the `xhr` module that can be set using `agentOptions` when using\n * arangojs in the browser. Additionally `maxSockets` can be used to control\n * the maximum number of parallel requests.\n *\n * See also: {@link https://www.npmjs.com/package/xhr | `xhr` on npm }.\n */\nexport type XhrOptions = {\n /**\n * Maximum number of parallel requests arangojs will perform. If any\n * additional requests are attempted, they will be enqueued until one of the\n * active requests has completed.\n */\n maxSockets?: number;\n /**\n * Number of milliseconds to wait for a response.\n *\n * Default: `0` (disabled)\n */\n timeout?: number;\n /**\n * Callback that will be invoked immediately before the `send` method of the\n * request is called.\n *\n * See also {@link RequestInterceptors}.\n */\n beforeSend?: (xhrObject: any) => void;\n /**\n * `XMLHttpRequest` object to use instead of the native implementation.\n */\n xhr?: any;\n /**\n * (Internet Explorer 10 and lower only.) Whether `XDomainRequest` should be\n * used instead of `XMLHttpRequest`. Only required for performing\n * cross-domain requests in older versions of Internet Explorer.\n */\n useXdr?: boolean;\n /**\n * Specifies whether browser credentials (e.g. cookies) should be sent if\n * performing a cross-domain request.\n *\n * See {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials | `XMLHttpRequest.withCredentials`}.\n */\n withCredentials?: boolean;\n};\n\n/**\n * Additional options for intercepting the request/response. These methods\n * are primarily intended for tracking network related metrics.\n */\nexport type RequestInterceptors = {\n /**\n * Callback that will be invoked with the finished request object before it\n * is finalized. In the browser the request may already have been sent.\n *\n * @param req - Request object or XHR instance used for this request.\n */\n before?: (req: ClientRequest) => void;\n /**\n * Callback that will be invoked when the server response has been received\n * and processed or when the request has been failed without a response.\n *\n * The originating request will be available as the `request` property\n * on either the error or response object.\n *\n * @param err - Error encountered when handling this request or `null`.\n * @param res - Response object for this request, if no error occurred.\n */\n after?: (err: ArangojsError | null, res?: ArangojsResponse) => void;\n};\n\n/**\n * Options for performing a request with arangojs.\n */\nexport type RequestOptions = {\n /**\n * @internal\n *\n * Identifier of a specific ArangoDB host to use when more than one is known.\n */\n host?: number;\n /**\n * HTTP method to use in order to perform the request.\n *\n * Default: `\"GET\"`\n */\n method?: string;\n /**\n * Request body data.\n */\n body?: any;\n /**\n * If set to `true`, the response body will not be interpreted as JSON and\n * instead passed as-is.\n */\n expectBinary?: boolean;\n /**\n * If set to `true`, the request body will not be converted to JSON and\n * instead passed as-is.\n */\n isBinary?: boolean;\n /**\n * Whether ArangoDB is allowed to perform a dirty read to respond to this\n * request. If set to `true`, the response may reflect a dirty state from\n * a non-authoritative server.\n */\n allowDirtyRead?: boolean;\n /**\n * HTTP headers to pass along with this request in addition to the default\n * headers generated by arangojs.\n */\n headers?: Headers;\n /**\n * Time in milliseconds after which arangojs will abort the request if the\n * socket has not already timed out.\n *\n * See also `agentOptions.timeout` in {@link Config}.\n */\n timeout?: number;\n /**\n * Optional prefix path to prepend to the `path`.\n */\n basePath?: string;\n /**\n * URL path, relative to the `basePath` and server domain.\n */\n path?: string;\n /**\n * URL parameters to pass as part of the query string.\n */\n qs?: string | Params;\n};\n\n/**\n * @internal\n * @hidden\n */\ntype Task = {\n host?: number;\n stack?: string;\n allowDirtyRead: boolean;\n resolve: Function;\n reject: Function;\n retries: number;\n options: {\n method: string;\n expectBinary: boolean;\n timeout?: number;\n url: { pathname: string; search?: string };\n headers: Headers;\n body: any;\n };\n};\n\n/**\n * Options for creating the Node.js `http.Agent` or `https.Agent`.\n *\n * In browser environments this option can be used to pass additional options\n * to the underlying calls of the\n * {@link https://www.npmjs.com/package/xhr | xhr module}.\n *\n * See also {@link https://nodejs.org/api/http.html#http_new_agent_options | `http.Agent`}\n * and {@link https://nodejs.org/api/https.html#https_new_agent_options | `https.Agent`}\n * (when using TLS).\n */\nexport type AgentOptions = NodeAgentOptions | XhrOptions;\n\n/**\n * Options for configuring arangojs.\n */\nexport type Config = {\n /**\n * Name of the database to use.\n *\n * Default: `\"_system\"`\n */\n databaseName?: string;\n /**\n * Base URL of the ArangoDB server or list of server URLs.\n *\n * When working with a cluster or a single server with leader/follower\n * failover, the method {@link Database.acquireHostList} can be used to\n * automatically pick up additional coordinators/followers at any point.\n *\n * When running ArangoDB on a unix socket, e.g. `/tmp/arangodb.sock`, the\n * following URL formats are supported for unix sockets:\n *\n * - `unix:///tmp/arangodb.sock` (no SSL)\n * - `http+unix:///tmp/arangodb.sock` (or `https+unix://` for SSL)\n * - `http://unix:/tmp/arangodb.sock` (or `https://unix:` for SSL)\n *\n * Additionally `ssl` and `tls` are treated as synonymous with `https` and\n * `tcp` is treated as synonymous with `http`, so the following URLs are\n * considered identical:\n *\n * - `tcp://localhost:8529` and `http://localhost:8529`\n * - `ssl://localhost:8529` and `https://localhost:8529`\n * - `tcp+unix:///tmp/arangodb.sock` and `http+unix:///tmp/arangodb.sock`\n * - `ssl+unix:///tmp/arangodb.sock` and `https+unix:///tmp/arangodb.sock`\n * - `tcp://unix:/tmp/arangodb.sock` and `http://unix:/tmp/arangodb.sock`\n * - `ssl://unix:/tmp/arangodb.sock` and `https://unix:/tmp/arangodb.sock`\n *\n * See also `auth` for passing authentication credentials.\n *\n * Default: `\"http://localhost:8529\"`\n */\n url?: string | string[];\n /**\n * Credentials to use for authentication.\n *\n * See also {@link Database.useBasicAuth} and {@link Database.useBearerAuth}.\n *\n * Default: `{ username: \"root\", password: \"\" }`\n */\n auth?: BasicAuthCredentials | BearerAuthCredentials;\n /**\n * Numeric representation of the ArangoDB version the driver should expect.\n * The format is defined as `XYYZZ` where `X` is the major version, `Y` is\n * the zero-filled two-digit minor version and `Z` is the zero-filled two-digit\n * bugfix version, e.g. `30102` for 3.1.2, `20811` for 2.8.11.\n *\n * Depending on this value certain methods may become unavailable or change\n * their behavior to remain compatible with different versions of ArangoDB.\n *\n * Default: `30400`\n */\n arangoVersion?: number;\n /**\n * Determines the behavior when multiple URLs are provided:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n *\n * Default: `\"NONE\"`\n */\n loadBalancingStrategy?: LoadBalancingStrategy;\n /**\n * Determines the behavior when a request fails because the underlying\n * connection to the server could not be opened\n * (i.e. {@link https://nodejs.org/api/errors.html#errors_common_system_errors | `ECONNREFUSED` in Node.js}):\n *\n * - `false`: the request fails immediately.\n *\n * - `0`: the request is retried until a server can be reached but only a\n * total number of times matching the number of known servers (including\n * the initial failed request).\n *\n * - any other number: the request is retried until a server can be reached\n * the request has been retried a total of `maxRetries` number of times\n * (not including the initial failed request).\n *\n * When working with a single server without leader/follower failover, the\n * retries (if any) will be made to the same server.\n *\n * This setting currently has no effect when using arangojs in a browser.\n *\n * **Note**: Requests bound to a specific server (e.g. fetching query results)\n * will never be retried automatically and ignore this setting.\n *\n * Default: `0`\n */\n maxRetries?: false | number;\n /**\n * An http `Agent` instance to use for connections.\n *\n * By default a new `Agent` instance will be created using the `agentOptions`.\n *\n * This option has no effect when using the browser version of arangojs.\n *\n * See also: {@link https://nodejs.org/api/http.html#http_new_agent_options | `http.Agent`}\n * and {@link https://nodejs.org/api/https.html#https_new_agent_options | `https.Agent`}\n * (when using TLS).\n */\n agent?: any;\n /**\n * Options used to create that underlying HTTP/HTTPS `Agent` (or the `xhr`\n * module when using arangojs in the browser). This will be ignored if\n * `agent` is also provided.\n *\n * The option `maxSockets` is also used to limit how many requests\n * arangojs will perform concurrently. The maximum number of requests is\n * equal to `maxSockets`.\n *\n * **Note:** arangojs will limit the number of concurrent requests based on\n * this value even if an `agent` is provided.\n *\n * **Note:** when using `ROUND_ROBIN` load balancing and passing an array of\n * URLs in the `url` option, the default value of `maxSockets` will be set\n * to `3 * url.length` instead of `3`.\n *\n * Default (Node.js): `{ maxSockets: 3, keepAlive: true, keepAliveMsecs: 1000 }`\n *\n * Default (browser): `{ maxSockets: 3, useXDR: true, withCredentials: true }`\n */\n agentOptions?: AgentOptions & RequestInterceptors;\n /**\n * An object with additional headers to send with every request.\n *\n * If an `\"authorization\"` header is provided, it will be overridden when\n * using {@link Database.useBasicAuth}, {@link Database.useBearerAuth} or\n * the `auth` configuration option.\n */\n headers?: Headers;\n /**\n * If set to `true`, arangojs will generate stack traces every time a request\n * is initiated and augment the stack traces of any errors it generates.\n *\n * **Warning**: This will cause arangojs to generate stack traces in advance\n * even if the request does not result in an error. Generating stack traces\n * may negatively impact performance.\n */\n precaptureStackTraces?: boolean;\n};\n\n/**\n * Indicates whether the given value represents a {@link Connection}.\n *\n * @param connection - A value that might be a connection.\n *\n * @internal\n * @hidden\n */\nexport function isArangoConnection(connection: any): connection is Connection {\n return Boolean(connection && connection.isArangoConnection);\n}\n\n/**\n * Represents a connection pool shared by one or more databases.\n *\n * @internal\n * @hidden\n */\nexport class Connection {\n protected _activeTasks: number = 0;\n protected _agent?: any;\n protected _agentOptions: { [key: string]: any };\n protected _arangoVersion: number = 30400;\n protected _headers: Headers;\n protected _loadBalancingStrategy: LoadBalancingStrategy;\n protected _useFailOver: boolean;\n protected _shouldRetry: boolean;\n protected _maxRetries: number;\n protected _maxTasks: number;\n protected _queue = new LinkedList<Task>();\n protected _databases = new Map<string, Database>();\n protected _hosts: RequestFunction[] = [];\n protected _urls: string[] = [];\n protected _activeHost: number;\n protected _activeDirtyHost: number;\n protected _transactionId: string | null = null;\n protected _precaptureStackTraces: boolean;\n\n /**\n * @internal\n *\n * Creates a new `Connection` instance.\n *\n * @param config - An object with configuration options.\n *\n * @hidden\n */\n constructor(config: Omit<Config, \"databaseName\"> = {}) {\n const URLS = config.url\n ? Array.isArray(config.url)\n ? config.url\n : [config.url]\n : [\"http://localhost:8529\"];\n const MAX_SOCKETS =\n 3 * (config.loadBalancingStrategy === \"ROUND_ROBIN\" ? URLS.length : 1);\n\n if (config.arangoVersion !== undefined) {\n this._arangoVersion = config.arangoVersion;\n }\n this._agent = config.agent;\n this._agentOptions = isBrowser\n ? { maxSockets: MAX_SOCKETS, ...config.agentOptions }\n : {\n maxSockets: MAX_SOCKETS,\n keepAlive: true,\n keepAliveMsecs: 1000,\n scheduling: \"lifo\",\n ...config.agentOptions,\n };\n this._maxTasks = this._agentOptions.maxSockets;\n this._headers = { ...config.headers };\n this._loadBalancingStrategy = config.loadBalancingStrategy ?? \"NONE\";\n this._useFailOver = this._loadBalancingStrategy !== \"ROUND_ROBIN\";\n this._precaptureStackTraces = Boolean(config.precaptureStackTraces);\n if (config.maxRetries === false) {\n this._shouldRetry = false;\n this._maxRetries = 0;\n } else {\n this._shouldRetry = true;\n this._maxRetries = config.maxRetries ?? 0;\n }\n\n this.addToHostList(URLS);\n\n if (config.auth) {\n if (isBearerAuth(config.auth)) {\n this.setBearerAuth(config.auth);\n } else {\n this.setBasicAuth(config.auth);\n }\n }\n\n if (this._loadBalancingStrategy === \"ONE_RANDOM\") {\n this._activeHost = Math.floor(Math.random() * this._hosts.length);\n this._activeDirtyHost = Math.floor(Math.random() * this._hosts.length);\n } else {\n this._activeHost = 0;\n this._activeDirtyHost = 0;\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB connection.\n */\n get isArangoConnection(): true {\n return true;\n }\n\n protected _runQueue() {\n if (!this._queue.length || this._activeTasks >= this._maxTasks) return;\n const task = this._queue.shift()!;\n let host = this._activeHost;\n if (task.host !== undefined) {\n host = task.host;\n } else if (task.allowDirtyRead) {\n host = this._activeDirtyHost;\n this._activeDirtyHost = (this._activeDirtyHost + 1) % this._hosts.length;\n task.options.headers[\"x-arango-allow-dirty-read\"] = \"true\";\n } else if (this._loadBalancingStrategy === \"ROUND_ROBIN\") {\n this._activeHost = (this._activeHost + 1) % this._hosts.length;\n }\n this._activeTasks += 1;\n const callback: Errback<ArangojsResponse> = (err, res) => {\n this._activeTasks -= 1;\n if (err) {\n if (\n !task.allowDirtyRead &&\n this._hosts.length > 1 &&\n this._activeHost === host &&\n this._useFailOver\n ) {\n this._activeHost = (this._activeHost + 1) % this._hosts.length;\n }\n if (\n !task.host &&\n this._shouldRetry &&\n task.retries < (this._maxRetries || this._hosts.length - 1) &&\n isSystemError(err) &&\n err.syscall === \"connect\" &&\n err.code === \"ECONNREFUSED\"\n ) {\n task.retries += 1;\n this._queue.push(task);\n } else {\n if (task.stack) {\n err.stack += task.stack;\n }\n task.reject(err);\n }\n } else {\n const response = res!;\n if (\n response.statusCode === 503 &&\n response.headers[LEADER_ENDPOINT_HEADER]\n ) {\n const url = response.headers[LEADER_ENDPOINT_HEADER]!;\n const [index] = this.addToHostList(url);\n task.host = index;\n if (this._activeHost === host) {\n this._activeHost = index;\n }\n this._queue.push(task);\n } else {\n response.arangojsHostId = host;\n task.resolve(response);\n }\n }\n this._runQueue();\n };\n try {\n this._hosts[host](task.options, callback);\n } catch (e) {\n callback(e);\n }\n }\n\n protected _buildUrl({ basePath, path, qs }: UrlInfo) {\n const pathname = `${basePath || \"\"}${path || \"\"}`;\n let search;\n if (qs) {\n if (typeof qs === \"string\") search = `?${qs}`;\n else search = `?${querystringify(clean(qs))}`;\n }\n return search ? { pathname, search } : { pathname };\n }\n\n setBearerAuth(auth: BearerAuthCredentials) {\n this.setHeader(\"authorization\", `Bearer ${auth.token}`);\n }\n\n setBasicAuth(auth: BasicAuthCredentials) {\n this.setHeader(\n \"authorization\",\n `Basic ${btoa(`${auth.username}:${auth.password}`)}`\n );\n }\n\n /**\n * @internal\n *\n * Fetches a {@link Database} instance for the given database name from the\n * internal cache, if available.\n *\n * @param databaseName - Name of the database.\n */\n database(databaseName: string): Database | undefined;\n /**\n * @internal\n *\n * Adds a {@link Database} instance for the given database name to the\n * internal cache.\n *\n * @param databaseName - Name of the database.\n * @param database - Database instance to add to the cache.\n */\n database(databaseName: string, database: Database): Database;\n /**\n * @internal\n *\n * Clears any {@link Database} instance stored for the given database name\n * from the internal cache, if present.\n *\n * @param databaseName - Name of the database.\n * @param database - Must be `null`.\n */\n database(databaseName: string, database: null): undefined;\n database(\n databaseName: string,\n database?: Database | null\n ): Database | undefined {\n if (database === null) {\n this._databases.delete(databaseName);\n return undefined;\n }\n if (!database) {\n return this._databases.get(databaseName);\n }\n this._databases.set(databaseName, database);\n return database;\n }\n\n /**\n * @internal\n *\n * Adds the given URL or URLs to the host list.\n *\n * See {@link Connection.acquireHostList}.\n *\n * @param urls - URL or URLs to add.\n */\n addToHostList(urls: string | string[]): number[] {\n const cleanUrls = (Array.isArray(urls) ? urls : [urls]).map((url) =>\n normalizeUrl(url)\n );\n const newUrls = cleanUrls.filter((url) => this._urls.indexOf(url) === -1);\n this._urls.push(...newUrls);\n this._hosts.push(\n ...newUrls.map((url: string) =>\n createRequest(url, this._agentOptions, this._agent)\n )\n );\n return cleanUrls.map((url) => this._urls.indexOf(url));\n }\n\n /**\n * @internal\n *\n * Sets the connection's active `transactionId`.\n *\n * While set, all requests will use this ID, ensuring the requests are executed\n * within the transaction if possible. Setting the ID manually may cause\n * unexpected behavior.\n *\n * See also {@link Connection.clearTransactionId}.\n *\n * @param transactionId - ID of the active transaction.\n */\n setTransactionId(transactionId: string) {\n this._transactionId = transactionId;\n }\n\n /**\n * @internal\n *\n * Clears the connection's active `transactionId`.\n */\n clearTransactionId() {\n this._transactionId = null;\n }\n\n /**\n * @internal\n *\n * Sets the header `headerName` with the given `value` or clears the header if\n * `value` is `null`.\n *\n * @param headerName - Name of the header to set.\n * @param value - Value of the header.\n */\n setHeader(headerName: string, value: string | null) {\n if (value === null) {\n delete this._headers[headerName];\n } else {\n this._headers[headerName] = value;\n }\n }\n\n /**\n * @internal\n *\n * Closes all open connections.\n *\n * See {@link Database.close}.\n */\n close() {\n for (const host of this._hosts) {\n if (host.close) host.close();\n }\n }\n\n /**\n * @internal\n *\n * Waits for propagation.\n *\n * See {@link Database.waitForPropagation}.\n *\n * @param request - Request to perform against each coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(request: RequestOptions, timeout = Infinity) {\n const numHosts = this._hosts.length;\n const propagated = [] as number[];\n const started = Date.now();\n let host = 0;\n while (true) {\n if (propagated.length === numHosts) {\n return;\n }\n while (propagated.includes(host)) {\n host = (host + 1) % numHosts;\n }\n try {\n await this.request({ ...request, host });\n } catch (e) {\n if (started + timeout < Date.now()) {\n throw e;\n }\n await new Promise((resolve) => setTimeout(resolve, 1000));\n continue;\n }\n if (!propagated.includes(host)) {\n propagated.push(host);\n }\n }\n }\n\n /**\n * @internal\n *\n * Performs a request using the arangojs connection pool.\n */\n request<T = ArangojsResponse>(\n {\n host,\n method = \"GET\",\n body,\n expectBinary = false,\n isBinary = false,\n allowDirtyRead = false,\n timeout = 0,\n headers,\n ...urlInfo\n }: RequestOptions,\n transform?: (res: ArangojsResponse) => T\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let contentType = \"text/plain\";\n if (isBinary) {\n contentType = \"application/octet-stream\";\n } else if (body) {\n if (typeof body === \"object\") {\n body = JSON.stringify(body);\n contentType = \"application/json\";\n } else {\n body = String(body);\n }\n }\n\n const extraHeaders: Headers = {\n ...this._headers,\n \"content-type\": contentType,\n \"x-arango-version\": String(this._arangoVersion),\n };\n\n if (this._transactionId) {\n extraHeaders[\"x-arango-trx-id\"] = this._transactionId;\n }\n\n const task: Task = {\n retries: 0,\n host,\n allowDirtyRead,\n options: {\n url: this._buildUrl(urlInfo),\n headers: { ...extraHeaders, ...headers },\n timeout,\n method,\n expectBinary,\n body,\n },\n reject,\n resolve: (res: ArangojsResponse) => {\n const contentType = res.headers[\"content-type\"];\n let parsedBody: any = undefined;\n if (res.body.length && contentType && contentType.match(MIME_JSON)) {\n try {\n parsedBody = res.body;\n parsedBody = JSON.parse(parsedBody);\n } catch (e) {\n if (!expectBinary) {\n if (typeof parsedBody !== \"string\") {\n parsedBody = res.body.toString(\"utf-8\");\n }\n e.response = res;\n reject(e);\n return;\n }\n }\n } else if (res.body && !expectBinary) {\n parsedBody = res.body.toString(\"utf-8\");\n } else {\n parsedBody = res.body;\n }\n if (isArangoErrorResponse(parsedBody)) {\n res.body = parsedBody;\n reject(new ArangoError(res));\n } else if (res.statusCode && res.statusCode >= 400) {\n res.body = parsedBody;\n reject(new HttpError(res));\n } else {\n if (!expectBinary) res.body = parsedBody;\n resolve(transform ? transform(res) : (res as any));\n }\n },\n };\n\n if (this._precaptureStackTraces) {\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(task);\n task.stack = `\\n${task.stack!.split(\"\\n\").slice(3).join(\"\\n\")}`;\n } else {\n const stack = generateStackTrace();\n if (stack) {\n task.stack = `\\n${stack.split(\"\\n\").slice(4).join(\"\\n\")}`;\n }\n }\n }\n\n this._queue.push(task);\n this._runQueue();\n });\n }\n}\n"]}
1
+ {"version":3,"file":"connection.js","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":";;;AAYA,6CAA0D;AAC1D,iDAA2C;AAE3C,mCAKiB;AACjB,qCAAkC;AAElC,qDAAkD;AAClD,2CAMuB;AAEvB,MAAM,SAAS,GAAG,2BAA2B,CAAC;AAC9C,MAAM,sBAAsB,GAAG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AAM,CAAC,GAAG,CAAC,CAAC;qBACb;yBAAM;wBACL,IAAI,CAAC,YAAY;4BAAE,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC;wBACzC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,GAAW,CAAC,CAAC;qBACpD;gBACH,CAAC;aACF,CAAC;YAEF,IAAI,IAAI,CAAC,sBAAsB,EAAE;gBAC/B,IAAI,OAAO,KAAK,CAAC,iBAAiB,KAAK,UAAU,EAAE;oBACjD,MAAM,OAAO,GAAG,EAAgC,CAAC;oBACjD,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;oBACjC,IAAI,CAAC,KAAK,GAAG,GAAG,EAAE,CAChB,KAAK,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;iBACxD;qBAAM;oBACL,MAAM,OAAO,GAAG,kBAAkB,EAAgC,CAAC;oBACnE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE;wBAC1D,IAAI,CAAC,KAAK,GAAG,GAAG,EAAE,CAChB,KAAK,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;qBACxD;iBACF;aACF;YAED,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACvB,IAAI,CAAC,SAAS,EAAE,CAAC;QACnB,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7cD,gCA6cC","sourcesContent":["/**\n * ```ts\n * import type { Config } from \"arangojs/connection\";\n * ```\n *\n * The \"connection\" module provides connection and configuration related types\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ClientRequest } from \"http\";\nimport { AgentOptions as NodeAgentOptions } from \"https\";\nimport { stringify as querystringify } from \"querystring\";\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\nimport {\n ArangoError,\n HttpError,\n isArangoErrorResponse,\n isSystemError,\n} from \"./error\";\nimport { btoa } from \"./lib/btoa\";\nimport { Errback } from \"./lib/errback\";\nimport { normalizeUrl } from \"./lib/normalizeUrl\";\nimport {\n ArangojsError,\n ArangojsResponse,\n createRequest,\n isBrowser,\n RequestFunction,\n} from \"./lib/request\";\n\nconst MIME_JSON = /\\/(json|javascript)(\\W|$)/;\nconst LEADER_ENDPOINT_HEADER = \"x-arango-endpoint\";\n\n/**\n * Generic type representing an object with values of a given value type.\n *\n * @param T - Type of the object's property values.\n */\nexport type Dict<T> = { [key: string]: T };\n\n/**\n * Determines the behavior when multiple URLs are used:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n */\nexport type LoadBalancingStrategy = \"NONE\" | \"ROUND_ROBIN\" | \"ONE_RANDOM\";\n\n/**\n * An arbitrary object with string values representing HTTP headers and their\n * values.\n *\n * Header names should always be lowercase.\n */\nexport type Headers = Dict<string>;\n\n/**\n * An arbitrary object with scalar values representing query string parameters\n * and their values.\n */\nexport type Params = Dict<any>;\n\n/**\n * Generic properties shared by all ArangoDB HTTP API responses.\n */\nexport type ArangoResponseMetadata = {\n /**\n * Indicates that the request was successful.\n */\n error: false;\n /**\n * Response status code, typically `200`.\n */\n code: number;\n};\n\nfunction clean<T>(obj: T) {\n const result = {} as typeof obj;\n for (const key of Object.keys(obj)) {\n const value = (obj as any)[key];\n if (value === undefined) continue;\n (result as any)[key] = value;\n }\n return result;\n}\n\n/**\n * Credentials for HTTP Basic authentication.\n */\nexport type BasicAuthCredentials = {\n /**\n * Username to use for authentication, e.g. `\"root\"`.\n */\n username: string;\n /**\n * Password to use for authentication. Defaults to an empty string.\n */\n password?: string;\n};\n\n/**\n * Credentials for HTTP Bearer token authentication.\n */\nexport type BearerAuthCredentials = {\n /**\n * Bearer token to use for authentication.\n */\n token: string;\n};\n\nfunction isBearerAuth(auth: any): auth is BearerAuthCredentials {\n return auth.hasOwnProperty(\"token\");\n}\n\n/**\n * @internal\n * @hidden\n */\nfunction generateStackTrace() {\n let err = new Error();\n if (!err.stack) {\n try {\n throw err;\n } catch (e) {\n err = e;\n }\n }\n return err;\n}\n\n/**\n * @internal\n * @hidden\n */\ntype UrlInfo = {\n absolutePath?: boolean;\n basePath?: string;\n path?: string;\n qs?: string | Params;\n};\n\n/**\n * Options of the `xhr` module that can be set using `agentOptions` when using\n * arangojs in the browser. Additionally `maxSockets` can be used to control\n * the maximum number of parallel requests.\n *\n * See also: {@link https://www.npmjs.com/package/xhr | `xhr` on npm }.\n */\nexport type XhrOptions = {\n /**\n * Maximum number of parallel requests arangojs will perform. If any\n * additional requests are attempted, they will be enqueued until one of the\n * active requests has completed.\n */\n maxSockets?: number;\n /**\n * Number of milliseconds to wait for a response.\n *\n * Default: `0` (disabled)\n */\n timeout?: number;\n /**\n * Callback that will be invoked immediately before the `send` method of the\n * request is called.\n *\n * See also {@link RequestInterceptors}.\n */\n beforeSend?: (xhrObject: any) => void;\n /**\n * `XMLHttpRequest` object to use instead of the native implementation.\n */\n xhr?: any;\n /**\n * (Internet Explorer 10 and lower only.) Whether `XDomainRequest` should be\n * used instead of `XMLHttpRequest`. Only required for performing\n * cross-domain requests in older versions of Internet Explorer.\n */\n useXdr?: boolean;\n /**\n * Specifies whether browser credentials (e.g. cookies) should be sent if\n * performing a cross-domain request.\n *\n * See {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials | `XMLHttpRequest.withCredentials`}.\n */\n withCredentials?: boolean;\n};\n\n/**\n * Additional options for intercepting the request/response. These methods\n * are primarily intended for tracking network related metrics.\n */\nexport type RequestInterceptors = {\n /**\n * Callback that will be invoked with the finished request object before it\n * is finalized. In the browser the request may already have been sent.\n *\n * @param req - Request object or XHR instance used for this request.\n */\n before?: (req: ClientRequest) => void;\n /**\n * Callback that will be invoked when the server response has been received\n * and processed or when the request has been failed without a response.\n *\n * The originating request will be available as the `request` property\n * on either the error or response object.\n *\n * @param err - Error encountered when handling this request or `null`.\n * @param res - Response object for this request, if no error occurred.\n */\n after?: (err: ArangojsError | null, res?: ArangojsResponse) => void;\n};\n\n/**\n * Options for performing a request with arangojs.\n */\nexport type RequestOptions = {\n /**\n * @internal\n *\n * Identifier of a specific ArangoDB host to use when more than one is known.\n */\n host?: number;\n /**\n * HTTP method to use in order to perform the request.\n *\n * Default: `\"GET\"`\n */\n method?: string;\n /**\n * Request body data.\n */\n body?: any;\n /**\n * If set to `true`, the response body will not be interpreted as JSON and\n * instead passed as-is.\n */\n expectBinary?: boolean;\n /**\n * If set to `true`, the request body will not be converted to JSON and\n * instead passed as-is.\n */\n isBinary?: boolean;\n /**\n * Whether ArangoDB is allowed to perform a dirty read to respond to this\n * request. If set to `true`, the response may reflect a dirty state from\n * a non-authoritative server.\n */\n allowDirtyRead?: boolean;\n /**\n * HTTP headers to pass along with this request in addition to the default\n * headers generated by arangojs.\n */\n headers?: Headers;\n /**\n * Time in milliseconds after which arangojs will abort the request if the\n * socket has not already timed out.\n *\n * See also `agentOptions.timeout` in {@link Config}.\n */\n timeout?: number;\n /**\n * Optional prefix path to prepend to the `path`.\n */\n basePath?: string;\n /**\n * URL path, relative to the `basePath` and server domain.\n */\n path?: string;\n /**\n * URL parameters to pass as part of the query string.\n */\n qs?: string | Params;\n};\n\n/**\n * @internal\n * @hidden\n */\ntype Task = {\n host?: number;\n stack?: () => string;\n allowDirtyRead: boolean;\n resolve: (res: ArangojsResponse) => void;\n reject: (error: Error) => void;\n retries: number;\n options: {\n method: string;\n expectBinary: boolean;\n timeout?: number;\n url: { pathname: string; search?: string };\n headers: Headers;\n body: any;\n };\n};\n\n/**\n * Options for creating the Node.js `http.Agent` or `https.Agent`.\n *\n * In browser environments this option can be used to pass additional options\n * to the underlying calls of the\n * {@link https://www.npmjs.com/package/xhr | xhr module}.\n *\n * See also {@link https://nodejs.org/api/http.html#http_new_agent_options | `http.Agent`}\n * and {@link https://nodejs.org/api/https.html#https_new_agent_options | `https.Agent`}\n * (when using TLS).\n */\nexport type AgentOptions = NodeAgentOptions | XhrOptions;\n\n/**\n * Options for configuring arangojs.\n */\nexport type Config = {\n /**\n * Name of the database to use.\n *\n * Default: `\"_system\"`\n */\n databaseName?: string;\n /**\n * Base URL of the ArangoDB server or list of server URLs.\n *\n * When working with a cluster or a single server with leader/follower\n * failover, the method {@link Database.acquireHostList} can be used to\n * automatically pick up additional coordinators/followers at any point.\n *\n * When running ArangoDB on a unix socket, e.g. `/tmp/arangodb.sock`, the\n * following URL formats are supported for unix sockets:\n *\n * - `unix:///tmp/arangodb.sock` (no SSL)\n * - `http+unix:///tmp/arangodb.sock` (or `https+unix://` for SSL)\n * - `http://unix:/tmp/arangodb.sock` (or `https://unix:` for SSL)\n *\n * Additionally `ssl` and `tls` are treated as synonymous with `https` and\n * `tcp` is treated as synonymous with `http`, so the following URLs are\n * considered identical:\n *\n * - `tcp://localhost:8529` and `http://localhost:8529`\n * - `ssl://localhost:8529` and `https://localhost:8529`\n * - `tcp+unix:///tmp/arangodb.sock` and `http+unix:///tmp/arangodb.sock`\n * - `ssl+unix:///tmp/arangodb.sock` and `https+unix:///tmp/arangodb.sock`\n * - `tcp://unix:/tmp/arangodb.sock` and `http://unix:/tmp/arangodb.sock`\n * - `ssl://unix:/tmp/arangodb.sock` and `https://unix:/tmp/arangodb.sock`\n *\n * See also `auth` for passing authentication credentials.\n *\n * Default: `\"http://localhost:8529\"`\n */\n url?: string | string[];\n /**\n * Credentials to use for authentication.\n *\n * See also {@link Database.useBasicAuth} and {@link Database.useBearerAuth}.\n *\n * Default: `{ username: \"root\", password: \"\" }`\n */\n auth?: BasicAuthCredentials | BearerAuthCredentials;\n /**\n * Numeric representation of the ArangoDB version the driver should expect.\n * The format is defined as `XYYZZ` where `X` is the major version, `Y` is\n * the zero-filled two-digit minor version and `Z` is the zero-filled two-digit\n * bugfix version, e.g. `30102` for 3.1.2, `20811` for 2.8.11.\n *\n * Depending on this value certain methods may become unavailable or change\n * their behavior to remain compatible with different versions of ArangoDB.\n *\n * Default: `30400`\n */\n arangoVersion?: number;\n /**\n * Determines the behavior when multiple URLs are provided:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n *\n * Default: `\"NONE\"`\n */\n loadBalancingStrategy?: LoadBalancingStrategy;\n /**\n * Determines the behavior when a request fails because the underlying\n * connection to the server could not be opened\n * (i.e. {@link https://nodejs.org/api/errors.html#errors_common_system_errors | `ECONNREFUSED` in Node.js}):\n *\n * - `false`: the request fails immediately.\n *\n * - `0`: the request is retried until a server can be reached but only a\n * total number of times matching the number of known servers (including\n * the initial failed request).\n *\n * - any other number: the request is retried until a server can be reached\n * the request has been retried a total of `maxRetries` number of times\n * (not including the initial failed request).\n *\n * When working with a single server without leader/follower failover, the\n * retries (if any) will be made to the same server.\n *\n * This setting currently has no effect when using arangojs in a browser.\n *\n * **Note**: Requests bound to a specific server (e.g. fetching query results)\n * will never be retried automatically and ignore this setting.\n *\n * Default: `0`\n */\n maxRetries?: false | number;\n /**\n * An http `Agent` instance to use for connections.\n *\n * By default a new `Agent` instance will be created using the `agentOptions`.\n *\n * This option has no effect when using the browser version of arangojs.\n *\n * See also: {@link https://nodejs.org/api/http.html#http_new_agent_options | `http.Agent`}\n * and {@link https://nodejs.org/api/https.html#https_new_agent_options | `https.Agent`}\n * (when using TLS).\n */\n agent?: any;\n /**\n * Options used to create that underlying HTTP/HTTPS `Agent` (or the `xhr`\n * module when using arangojs in the browser). This will be ignored if\n * `agent` is also provided.\n *\n * The option `maxSockets` is also used to limit how many requests\n * arangojs will perform concurrently. The maximum number of requests is\n * equal to `maxSockets`.\n *\n * **Note:** arangojs will limit the number of concurrent requests based on\n * this value even if an `agent` is provided.\n *\n * **Note:** when using `ROUND_ROBIN` load balancing and passing an array of\n * URLs in the `url` option, the default value of `maxSockets` will be set\n * to `3 * url.length` instead of `3`.\n *\n * Default (Node.js): `{ maxSockets: 3, keepAlive: true, keepAliveMsecs: 1000 }`\n *\n * Default (browser): `{ maxSockets: 3, useXDR: true, withCredentials: true }`\n */\n agentOptions?: AgentOptions & RequestInterceptors;\n /**\n * An object with additional headers to send with every request.\n *\n * If an `\"authorization\"` header is provided, it will be overridden when\n * using {@link Database.useBasicAuth}, {@link Database.useBearerAuth} or\n * the `auth` configuration option.\n */\n headers?: Headers;\n /**\n * If set to `true`, arangojs will generate stack traces every time a request\n * is initiated and augment the stack traces of any errors it generates.\n *\n * **Warning**: This will cause arangojs to generate stack traces in advance\n * even if the request does not result in an error. Generating stack traces\n * may negatively impact performance.\n */\n precaptureStackTraces?: boolean;\n};\n\n/**\n * Indicates whether the given value represents a {@link Connection}.\n *\n * @param connection - A value that might be a connection.\n *\n * @internal\n * @hidden\n */\nexport function isArangoConnection(connection: any): connection is Connection {\n return Boolean(connection && connection.isArangoConnection);\n}\n\n/**\n * Represents a connection pool shared by one or more databases.\n *\n * @internal\n * @hidden\n */\nexport class Connection {\n protected _activeTasks: number = 0;\n protected _agent?: any;\n protected _agentOptions: { [key: string]: any };\n protected _arangoVersion: number = 30400;\n protected _headers: Headers;\n protected _loadBalancingStrategy: LoadBalancingStrategy;\n protected _useFailOver: boolean;\n protected _shouldRetry: boolean;\n protected _maxRetries: number;\n protected _maxTasks: number;\n protected _queue = new LinkedList<Task>();\n protected _databases = new Map<string, Database>();\n protected _hosts: RequestFunction[] = [];\n protected _urls: string[] = [];\n protected _activeHost: number;\n protected _activeDirtyHost: number;\n protected _transactionId: string | null = null;\n protected _precaptureStackTraces: boolean;\n\n /**\n * @internal\n *\n * Creates a new `Connection` instance.\n *\n * @param config - An object with configuration options.\n *\n * @hidden\n */\n constructor(config: Omit<Config, \"databaseName\"> = {}) {\n const URLS = config.url\n ? Array.isArray(config.url)\n ? config.url\n : [config.url]\n : [\"http://localhost:8529\"];\n const MAX_SOCKETS =\n 3 * (config.loadBalancingStrategy === \"ROUND_ROBIN\" ? URLS.length : 1);\n\n if (config.arangoVersion !== undefined) {\n this._arangoVersion = config.arangoVersion;\n }\n this._agent = config.agent;\n this._agentOptions = isBrowser\n ? { maxSockets: MAX_SOCKETS, ...config.agentOptions }\n : {\n maxSockets: MAX_SOCKETS,\n keepAlive: true,\n keepAliveMsecs: 1000,\n scheduling: \"lifo\",\n ...config.agentOptions,\n };\n this._maxTasks = this._agentOptions.maxSockets;\n this._headers = { ...config.headers };\n this._loadBalancingStrategy = config.loadBalancingStrategy ?? \"NONE\";\n this._useFailOver = this._loadBalancingStrategy !== \"ROUND_ROBIN\";\n this._precaptureStackTraces = Boolean(config.precaptureStackTraces);\n if (config.maxRetries === false) {\n this._shouldRetry = false;\n this._maxRetries = 0;\n } else {\n this._shouldRetry = true;\n this._maxRetries = config.maxRetries ?? 0;\n }\n\n this.addToHostList(URLS);\n\n if (config.auth) {\n if (isBearerAuth(config.auth)) {\n this.setBearerAuth(config.auth);\n } else {\n this.setBasicAuth(config.auth);\n }\n }\n\n if (this._loadBalancingStrategy === \"ONE_RANDOM\") {\n this._activeHost = Math.floor(Math.random() * this._hosts.length);\n this._activeDirtyHost = Math.floor(Math.random() * this._hosts.length);\n } else {\n this._activeHost = 0;\n this._activeDirtyHost = 0;\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB connection.\n */\n get isArangoConnection(): true {\n return true;\n }\n\n protected _runQueue() {\n if (!this._queue.length || this._activeTasks >= this._maxTasks) return;\n const task = this._queue.shift()!;\n let host = this._activeHost;\n if (task.host !== undefined) {\n host = task.host;\n } else if (task.allowDirtyRead) {\n host = this._activeDirtyHost;\n this._activeDirtyHost = (this._activeDirtyHost + 1) % this._hosts.length;\n task.options.headers[\"x-arango-allow-dirty-read\"] = \"true\";\n } else if (this._loadBalancingStrategy === \"ROUND_ROBIN\") {\n this._activeHost = (this._activeHost + 1) % this._hosts.length;\n }\n this._activeTasks += 1;\n const callback: Errback<ArangojsResponse> = (err, res) => {\n this._activeTasks -= 1;\n if (err) {\n if (\n !task.allowDirtyRead &&\n this._hosts.length > 1 &&\n this._activeHost === host &&\n this._useFailOver\n ) {\n this._activeHost = (this._activeHost + 1) % this._hosts.length;\n }\n if (\n !task.host &&\n this._shouldRetry &&\n task.retries < (this._maxRetries || this._hosts.length - 1) &&\n isSystemError(err) &&\n err.syscall === \"connect\" &&\n err.code === \"ECONNREFUSED\"\n ) {\n task.retries += 1;\n this._queue.push(task);\n } else {\n if (task.stack) {\n err.stack += task.stack();\n }\n task.reject(err);\n }\n } else {\n const response = res!;\n if (\n response.statusCode === 503 &&\n response.headers[LEADER_ENDPOINT_HEADER]\n ) {\n const url = response.headers[LEADER_ENDPOINT_HEADER]!;\n const [index] = this.addToHostList(url);\n task.host = index;\n if (this._activeHost === host) {\n this._activeHost = index;\n }\n this._queue.push(task);\n } else {\n response.arangojsHostId = host;\n task.resolve(response);\n }\n }\n this._runQueue();\n };\n try {\n this._hosts[host](task.options, callback);\n } catch (e) {\n callback(e);\n }\n }\n\n protected _buildUrl({ basePath, path, qs }: UrlInfo) {\n const pathname = `${basePath || \"\"}${path || \"\"}`;\n let search;\n if (qs) {\n if (typeof qs === \"string\") search = `?${qs}`;\n else search = `?${querystringify(clean(qs))}`;\n }\n return search ? { pathname, search } : { pathname };\n }\n\n setBearerAuth(auth: BearerAuthCredentials) {\n this.setHeader(\"authorization\", `Bearer ${auth.token}`);\n }\n\n setBasicAuth(auth: BasicAuthCredentials) {\n this.setHeader(\n \"authorization\",\n `Basic ${btoa(`${auth.username}:${auth.password}`)}`\n );\n }\n\n /**\n * @internal\n *\n * Fetches a {@link Database} instance for the given database name from the\n * internal cache, if available.\n *\n * @param databaseName - Name of the database.\n */\n database(databaseName: string): Database | undefined;\n /**\n * @internal\n *\n * Adds a {@link Database} instance for the given database name to the\n * internal cache.\n *\n * @param databaseName - Name of the database.\n * @param database - Database instance to add to the cache.\n */\n database(databaseName: string, database: Database): Database;\n /**\n * @internal\n *\n * Clears any {@link Database} instance stored for the given database name\n * from the internal cache, if present.\n *\n * @param databaseName - Name of the database.\n * @param database - Must be `null`.\n */\n database(databaseName: string, database: null): undefined;\n database(\n databaseName: string,\n database?: Database | null\n ): Database | undefined {\n if (database === null) {\n this._databases.delete(databaseName);\n return undefined;\n }\n if (!database) {\n return this._databases.get(databaseName);\n }\n this._databases.set(databaseName, database);\n return database;\n }\n\n /**\n * @internal\n *\n * Adds the given URL or URLs to the host list.\n *\n * See {@link Connection.acquireHostList}.\n *\n * @param urls - URL or URLs to add.\n */\n addToHostList(urls: string | string[]): number[] {\n const cleanUrls = (Array.isArray(urls) ? urls : [urls]).map((url) =>\n normalizeUrl(url)\n );\n const newUrls = cleanUrls.filter((url) => this._urls.indexOf(url) === -1);\n this._urls.push(...newUrls);\n this._hosts.push(\n ...newUrls.map((url: string) =>\n createRequest(url, this._agentOptions, this._agent)\n )\n );\n return cleanUrls.map((url) => this._urls.indexOf(url));\n }\n\n /**\n * @internal\n *\n * Sets the connection's active `transactionId`.\n *\n * While set, all requests will use this ID, ensuring the requests are executed\n * within the transaction if possible. Setting the ID manually may cause\n * unexpected behavior.\n *\n * See also {@link Connection.clearTransactionId}.\n *\n * @param transactionId - ID of the active transaction.\n */\n setTransactionId(transactionId: string) {\n this._transactionId = transactionId;\n }\n\n /**\n * @internal\n *\n * Clears the connection's active `transactionId`.\n */\n clearTransactionId() {\n this._transactionId = null;\n }\n\n /**\n * @internal\n *\n * Sets the header `headerName` with the given `value` or clears the header if\n * `value` is `null`.\n *\n * @param headerName - Name of the header to set.\n * @param value - Value of the header.\n */\n setHeader(headerName: string, value: string | null) {\n if (value === null) {\n delete this._headers[headerName];\n } else {\n this._headers[headerName] = value;\n }\n }\n\n /**\n * @internal\n *\n * Closes all open connections.\n *\n * See {@link Database.close}.\n */\n close() {\n for (const host of this._hosts) {\n if (host.close) host.close();\n }\n }\n\n /**\n * @internal\n *\n * Waits for propagation.\n *\n * See {@link Database.waitForPropagation}.\n *\n * @param request - Request to perform against each coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(request: RequestOptions, timeout = Infinity) {\n const numHosts = this._hosts.length;\n const propagated = [] as number[];\n const started = Date.now();\n let host = 0;\n while (true) {\n if (propagated.length === numHosts) {\n return;\n }\n while (propagated.includes(host)) {\n host = (host + 1) % numHosts;\n }\n try {\n await this.request({ ...request, host });\n } catch (e) {\n if (started + timeout < Date.now()) {\n throw e;\n }\n await new Promise((resolve) => setTimeout(resolve, 1000));\n continue;\n }\n if (!propagated.includes(host)) {\n propagated.push(host);\n }\n }\n }\n\n /**\n * @internal\n *\n * Performs a request using the arangojs connection pool.\n */\n request<T = ArangojsResponse>(\n {\n host,\n method = \"GET\",\n body,\n expectBinary = false,\n isBinary = false,\n allowDirtyRead = false,\n timeout = 0,\n headers,\n ...urlInfo\n }: RequestOptions,\n transform?: (res: ArangojsResponse) => T\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let contentType = \"text/plain\";\n if (isBinary) {\n contentType = \"application/octet-stream\";\n } else if (body) {\n if (typeof body === \"object\") {\n body = JSON.stringify(body);\n contentType = \"application/json\";\n } else {\n body = String(body);\n }\n }\n\n const extraHeaders: Headers = {\n ...this._headers,\n \"content-type\": contentType,\n \"x-arango-version\": String(this._arangoVersion),\n };\n\n if (this._transactionId) {\n extraHeaders[\"x-arango-trx-id\"] = this._transactionId;\n }\n\n const task: Task = {\n retries: 0,\n host,\n allowDirtyRead,\n options: {\n url: this._buildUrl(urlInfo),\n headers: { ...extraHeaders, ...headers },\n timeout,\n method,\n expectBinary,\n body,\n },\n reject,\n resolve: (res: ArangojsResponse) => {\n const contentType = res.headers[\"content-type\"];\n let parsedBody: any = undefined;\n if (res.body.length && contentType && contentType.match(MIME_JSON)) {\n try {\n parsedBody = res.body;\n parsedBody = JSON.parse(parsedBody);\n } catch (e) {\n if (!expectBinary) {\n if (typeof parsedBody !== \"string\") {\n parsedBody = res.body.toString(\"utf-8\");\n }\n e.response = res;\n if (task.stack) {\n e.stack += task.stack();\n }\n reject(e);\n return;\n }\n }\n } else if (res.body && !expectBinary) {\n parsedBody = res.body.toString(\"utf-8\");\n } else {\n parsedBody = res.body;\n }\n if (isArangoErrorResponse(parsedBody)) {\n res.body = parsedBody;\n const err = new ArangoError(res);\n if (task.stack) {\n err.stack += task.stack();\n }\n reject(err);\n } else if (res.statusCode && res.statusCode >= 400) {\n res.body = parsedBody;\n const err = new HttpError(res);\n if (task.stack) {\n err.stack += task.stack();\n }\n reject(err);\n } else {\n if (!expectBinary) res.body = parsedBody;\n resolve(transform ? transform(res) : (res as any));\n }\n },\n };\n\n if (this._precaptureStackTraces) {\n if (typeof Error.captureStackTrace === \"function\") {\n const capture = {} as { readonly stack: string };\n Error.captureStackTrace(capture);\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(3).join(\"\\n\")}`;\n } else {\n const capture = generateStackTrace() as { readonly stack: string };\n if (Object.prototype.hasOwnProperty.call(capture, \"stack\")) {\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(4).join(\"\\n\")}`;\n }\n }\n }\n\n this._queue.push(task);\n this._runQueue();\n });\n }\n}\n"]}
package/cursor.js CHANGED
@@ -326,7 +326,7 @@ class BatchedArrayCursor {
326
326
  */
327
327
  async map(callback) {
328
328
  let index = 0;
329
- let result = [];
329
+ const result = [];
330
330
  while (this.hasNext) {
331
331
  const currentBatch = await this.next();
332
332
  result.push(callback(currentBatch, index, this));
@@ -380,7 +380,7 @@ class BatchedArrayCursor {
380
380
  */
381
381
  async flatMap(callback) {
382
382
  let index = 0;
383
- let result = [];
383
+ const result = [];
384
384
  while (this.hasNext) {
385
385
  const currentBatch = await this.next();
386
386
  const value = callback(currentBatch, index, this);
@@ -655,7 +655,7 @@ class ArrayCursor {
655
655
  */
656
656
  async map(callback) {
657
657
  let index = 0;
658
- let result = [];
658
+ const result = [];
659
659
  while (this.hasNext) {
660
660
  const value = await this.next();
661
661
  result.push(callback(value, index, this));
@@ -703,7 +703,7 @@ class ArrayCursor {
703
703
  */
704
704
  async flatMap(callback) {
705
705
  let index = 0;
706
- let result = [];
706
+ const result = [];
707
707
  while (this.hasNext) {
708
708
  const value = await this.next();
709
709
  const item = callback(value, index, this);
package/cursor.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../src/cursor.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;GAQG;AACH,iDAA2C;AAmC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,kBAAkB;IAW7B;;;OAGG;IACH,YACE,EAAY,EACZ,IAMC,EACD,IAAa,EACb,cAAwB;QAExB,MAAM,OAAO,GAAG,IAAI,0BAAU,CAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,0BAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CACxD,CAAC;QACF,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;QACjD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CA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AAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC3C,KAAK,EAAE,CAAC;SACT;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;;;;;;;;;;;OAkBG;IACH,KAAK,CAAC,IAAI;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IAC7B,CAAC;CACF;AA/YD,kCA+YC","sourcesContent":["/**\n * ```ts\n * import type { ArrayCursor, BatchedArrayCursor } from \"arangojs/cursor\";\n * ```\n *\n * The \"cursor\" module provides cursor-related interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Dict } from \"./connection\";\nimport { Database } from \"./database\";\n\n/**\n * Additional information about the cursor.\n */\nexport interface CursorExtras {\n /**\n * Warnings encountered while executing the query.\n */\n warnings: {\n code: number;\n message: string;\n }[];\n /**\n * Query execution plan for the executed query.\n */\n plan?: any;\n /**\n * Additional profiling information for the executed query.\n */\n profile?: any;\n /**\n * Additional statistics about the query execution.\n */\n stats?: Dict<any>;\n}\n\ninterface BatchView<T = any> {\n isEmpty: boolean;\n more(): Promise<void>;\n shift(): T | undefined;\n}\n\n/**\n * The `BatchedArrayCursor` provides a batch-wise API to an {@link ArrayCursor}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const cursor = await db.query(query) as ArrayCursor<number>;\n * const batches = cursor.batches;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10000 RETURN x`;\n * const cursor = await db.query(query, { batchSize: 10 });\n * for await (const batch of cursor.batches) {\n * // Process all values in a batch in parallel\n * await Promise.all(batch.map(\n * value => asyncProcessValue(value)\n * ));\n * }\n * ```\n */\nexport class BatchedArrayCursor<T = any> {\n protected _db: Database;\n protected _batches: LinkedList<LinkedList<any>>;\n protected _count?: number;\n protected _extra: CursorExtras;\n protected _hasMore: boolean;\n protected _id: string | undefined;\n protected _host?: number;\n protected _allowDirtyRead?: boolean;\n protected _itemsCursor: ArrayCursor<T>;\n\n /**\n * @internal\n * @hidden\n */\n constructor(\n db: Database,\n body: {\n extra: any;\n result: T[];\n hasMore: boolean;\n id: string;\n count: number;\n },\n host?: number,\n allowDirtyRead?: boolean\n ) {\n const batches = new LinkedList(\n body.result.length ? [new LinkedList(body.result)] : []\n );\n this._db = db;\n this._batches = batches;\n this._id = body.id;\n this._hasMore = Boolean(body.id && body.hasMore);\n this._host = host;\n this._count = body.count;\n this._extra = body.extra;\n this._allowDirtyRead = allowDirtyRead;\n this._itemsCursor = new ArrayCursor(this, {\n get isEmpty() {\n return !batches.length;\n },\n more: () => this._more(),\n shift: () => {\n let batch = batches.first?.value;\n while (batch && !batch.length) {\n batches.shift();\n batch = batches.first?.value;\n }\n if (!batch) return undefined;\n const value = batch.shift();\n if (!batch.length) batches.shift();\n return value;\n },\n });\n }\n\n protected async _more(): Promise<void> {\n if (!this.hasMore) return;\n const res = await this._db.request({\n method: \"PUT\",\n path: `/_api/cursor/${this._id}`,\n host: this._host,\n allowDirtyRead: this._allowDirtyRead,\n });\n this._batches.push(new LinkedList(res.body.result));\n this._hasMore = res.body.hasMore;\n }\n\n /**\n * An {@link ArrayCursor} providing item-wise access to the cursor result set.\n *\n * See also {@link ArrayCursor.batches}.\n */\n get items() {\n return this._itemsCursor;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): Readonly<CursorExtras> {\n return this._extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this._count;\n }\n\n /**\n * Whether the cursor has any remaining batches that haven't yet been\n * fetched. If set to `false`, all batches have been fetched and no\n * additional requests to the server will be made when consuming any\n * remaining batches from this cursor.\n */\n get hasMore(): boolean {\n return this._hasMore;\n }\n\n /**\n * Whether the cursor has more batches. If set to `false`, the cursor has\n * already been depleted and contains no more batches.\n */\n get hasNext(): boolean {\n return this.hasMore || Boolean(this._batches.length);\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every batch in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const users of cursor.batches) {\n * for (const user of users) {\n * console.log(user.email, user.isAdmin);\n * }\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T[], undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T[]>;\n }\n return undefined;\n }\n\n /**\n * Loads all remaining batches from the server.\n *\n * **Warning**: This may impact memory use when working with very large\n * query result sets.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * console.log(cursor.hasMore); // true\n * await cursor.batches.loadAll();\n * console.log(cursor.hasMore); // false\n * console.log(cursor.hasNext); // true\n * for await (const item of cursor) {\n * console.log(item);\n * // No server roundtrips necessary any more\n * }\n * ```\n */\n async loadAll(): Promise<void> {\n while (this._hasMore) {\n await this._more();\n }\n }\n\n /**\n * Depletes the cursor, then returns an array containing all batches in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.all(); // [[1, 2], [3, 4], [5]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[][]> {\n return this.map((batch) => batch);\n }\n\n /**\n * Advances the cursor and returns all remaining values in the cursor's\n * current batch. If the current batch has already been exhausted, fetches\n * the next batch from the server and returns it, or `undefined` if the\n * cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR i IN 1..10 RETURN i`,\n * { batchSize: 5 }\n * );\n * const firstBatch = await cursor.batches.next(); // [1, 2, 3, 4, 5]\n * await cursor.next(); // 6\n * const lastBatch = await cursor.batches.next(); // [7, 8, 9, 10]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async next(): Promise<T[] | undefined> {\n while (!this._batches.length && this.hasNext) {\n await this._more();\n }\n if (!this._batches.length) {\n return undefined;\n }\n const batch = this._batches.shift();\n if (!batch) return undefined;\n const values = [...batch.values()];\n batch.clear(true);\n return values;\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | `Array.prototype.forEach`}.\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * return false; // stop after the first batch\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentBatch: T[], index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const currentBatch = await this.next();\n const result = callback(currentBatch!, index, this);\n index++;\n if (result === false) return result;\n if (this.hasNext) await this._more();\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link BatchedArrayCursor.forEach}, {@link BatchedArrayCursor.reduce} or\n * {@link BatchedArrayCursor.flatMap} instead.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | `Array.prototype.map`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.map((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [[1, 4], [9, 16], [25]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentBatch: T[], index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n let result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n result.push(callback(currentBatch!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | `Array.prototype.flatMap`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.flatMap((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const odds = await cursor.batches.flatMap((currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentBatch;\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentBatch: T[], index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n let result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n const value = callback(currentBatch!, index, this);\n if (Array.isArray(value)) {\n result.push(...value);\n } else {\n result.push(value);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link BatchedArrayCursor.forEach} or the `for await`\n * syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestValue(baseline, values) {\n * return Math.max(baseline, ...values);\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.batches.reduce(largestValue, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const result = await cursor.reduce((accumulator, currentBatch) => {\n * accumulator[\n * currentBatch[0] % 2 === 0 ? \"even\" : \"odd\"\n * ].push(...currentBatch);\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const item of cursor) {\n * if (currentBatch[0] % 2 === 0) {\n * even.push(...currentBatch);\n * } else {\n * odd.push(...currentBatch);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue: R\n ): Promise<R>;\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestValue(values1, values2) {\n * return [Math.max(...values1, ...values2)];\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue);\n * console.log(result); // [5]\n * console.log(cursor.hasNext); // false\n * ```\n *\n */\n async reduce<R>(\n reducer: (\n accumulator: T[] | R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n initialValue = (await this.next()) as any;\n index += 1;\n }\n let value = initialValue as R;\n while (this.hasNext) {\n const currentBatch = await this.next();\n value = reducer(value, currentBatch!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Drains the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been consumed.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n if (this._batches.length) {\n for (const batch of this._batches.values()) {\n batch.clear();\n }\n this._batches.clear();\n }\n if (!this.hasNext) return undefined;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/cursor/${this._id}`,\n },\n () => {\n this._hasMore = false;\n return undefined;\n }\n );\n }\n}\n\n/**\n * The `ArrayCursor` type represents a cursor returned from a\n * {@link Database.query}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * See also {@link BatchedArrayCursor}.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const result = await db.query(query) as ArrayCursor<number>;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10 RETURN x`;\n * const cursor = await db.query(query);\n * for await (const value of cursor) {\n * // Process each value asynchronously\n * await processValue(value);\n * }\n * ```\n */\nexport class ArrayCursor<T = any> {\n protected _batches: BatchedArrayCursor<T>;\n protected _view: BatchView<T>;\n\n constructor(batchedCursor: BatchedArrayCursor, view: BatchView<T>) {\n this._batches = batchedCursor;\n this._view = view;\n }\n\n /**\n * A {@link BatchedArrayCursor} providing batch-wise access to the cursor\n * result set.\n *\n * See also {@link BatchedArrayCursor.items}.\n */\n get batches() {\n return this._batches;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): CursorExtras {\n return this.batches.extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this.batches.count;\n }\n\n /**\n * Whether the cursor has more values. If set to `false`, the cursor has\n * already been depleted and contains no more items.\n */\n get hasNext(): boolean {\n return this.batches.hasNext;\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every value in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const user of cursor) {\n * console.log(user.email, user.isAdmin);\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T, undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T>;\n }\n return undefined;\n }\n\n /**\n * Depletes the cursor, then returns an array containing all values in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.all(); // [1, 2, 3, 4, 5]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[]> {\n return this.batches.flatMap((v) => v);\n }\n\n /**\n * Advances the cursor and returns the next value in the cursor's remaining\n * result list, or `undefined` if the cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..3 RETURN x`);\n * const one = await cursor.next(); // 1\n * const two = await cursor.next(); // 2\n * const three = await cursor.next(); // 3\n * const empty = await cursor.next(); // undefined\n * ```\n */\n async next(): Promise<T | undefined> {\n while (this._view.isEmpty && this.batches.hasMore) {\n await this._view.more();\n }\n if (this._view.isEmpty) {\n return undefined;\n }\n return this._view.shift();\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | `Array.prototype.forEach`}.\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * return false; // stop after the first item\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentValue: T, index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const value = await this.next();\n const result = callback(value!, index, this);\n index++;\n if (result === false) return result;\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link ArrayCursor.forEach}, {@link ArrayCursor.reduce} or\n * {@link ArrayCursor.flatMap} instead.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | `Array.prototype.map`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.map((currentValue) => {\n * return currentValue ** 2;\n * });\n * console.log(squares); // [1, 4, 9, 16, 25]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentValue: T, index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n let result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n result.push(callback(value!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | `Array.prototype.flatMap`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.flatMap((currentValue) => {\n * return [currentValue, currentValue ** 2];\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odds = await cursor.flatMap((currentValue) => {\n * if (currentValue % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentValue; // or [currentValue]\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentValue: T, index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n let result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n const item = callback(value!, index, this);\n if (Array.isArray(item)) {\n result.push(...item);\n } else {\n result.push(item);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link ArrayCursor.forEach} or the `for await` syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce((accumulator, currentValue) => {\n * accumulator[currentValue % 2 === 0 ? \"even\" : \"odd\"].push(currentValue);\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const item of cursor) {\n * if (currentValue % 2 === 0) {\n * even.push(currentValue);\n * } else {\n * odd.push(currentValue);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue: R\n ): Promise<R>;\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo);\n * console.log(emptyResult); // undefined\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: T | R,\n currentValue: T,\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n const value = (await this.next()) as any;\n initialValue = value as R;\n index += 1;\n }\n let value = initialValue;\n while (this.hasNext) {\n const item = await this.next();\n value = reducer(value, item!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Kills the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been fetched.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n return this.batches.kill();\n }\n}\n"]}
1
+ {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../src/cursor.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;GAQG;AACH,iDAA2C;AAmC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,kBAAkB;IAW7B;;;OAGG;IACH,YACE,EAAY,EACZ,IAMC,EACD,IAAa,EACb,cAAwB;QAExB,MAAM,OAAO,GAAG,IAAI,0BAAU,CAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,0BAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CACxD,CAAC;QACF,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC;QACnB,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,CAAC;QACjD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;QACtC,IAAI,CAAC,YAAY,GAAG,IAAI,WAAW,CAAC,IAAI,EAAE;YACxC,IAAI,OAAO;gBACT,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC;YACzB,CAAC;YACD,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE;YACxB,KAAK,EAAE,GAAG,EAAE;;gBACV,IAAI,KAAK,SAAG,OAAO,CAAC,KAAK,0CAAE,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C,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAM,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC3C,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;gBACvB,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;aACtB;iBAAM;gBACL,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACnB;YACD,KAAK,EAAE,CAAC;SACT;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAqGD,KAAK,CAAC,MAAM,CACV,OAA0E,EAC1E,YAAgB;QAEhB,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO,YAAY,CAAC;QACvC,IAAI,YAAY,KAAK,SAAS,EAAE;YAC9B,MAAM,KAAK,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAQ,CAAC;YACzC,YAAY,GAAG,KAAU,CAAC;YAC1B,KAAK,IAAI,CAAC,CAAC;SACZ;QACD,IAAI,KAAK,GAAG,YAAY,CAAC;QACzB,OAAO,IAAI,CAAC,OAAO,EAAE;YACnB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC;YAC/B,KAAK,GAAG,OAAO,CAAC,KAAK,EAAE,IAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;YAC3C,KAAK,EAAE,CAAC;SACT;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;;;;;;;;;;;OAkBG;IACH,KAAK,CAAC,IAAI;QACR,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IAC7B,CAAC;CACF;AA/YD,kCA+YC","sourcesContent":["/**\n * ```ts\n * import type { ArrayCursor, BatchedArrayCursor } from \"arangojs/cursor\";\n * ```\n *\n * The \"cursor\" module provides cursor-related interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Dict } from \"./connection\";\nimport { Database } from \"./database\";\n\n/**\n * Additional information about the cursor.\n */\nexport interface CursorExtras {\n /**\n * Warnings encountered while executing the query.\n */\n warnings: {\n code: number;\n message: string;\n }[];\n /**\n * Query execution plan for the executed query.\n */\n plan?: any;\n /**\n * Additional profiling information for the executed query.\n */\n profile?: any;\n /**\n * Additional statistics about the query execution.\n */\n stats?: Dict<any>;\n}\n\ninterface BatchView<T = any> {\n isEmpty: boolean;\n more(): Promise<void>;\n shift(): T | undefined;\n}\n\n/**\n * The `BatchedArrayCursor` provides a batch-wise API to an {@link ArrayCursor}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const cursor = await db.query(query) as ArrayCursor<number>;\n * const batches = cursor.batches;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10000 RETURN x`;\n * const cursor = await db.query(query, { batchSize: 10 });\n * for await (const batch of cursor.batches) {\n * // Process all values in a batch in parallel\n * await Promise.all(batch.map(\n * value => asyncProcessValue(value)\n * ));\n * }\n * ```\n */\nexport class BatchedArrayCursor<T = any> {\n protected _db: Database;\n protected _batches: LinkedList<LinkedList<any>>;\n protected _count?: number;\n protected _extra: CursorExtras;\n protected _hasMore: boolean;\n protected _id: string | undefined;\n protected _host?: number;\n protected _allowDirtyRead?: boolean;\n protected _itemsCursor: ArrayCursor<T>;\n\n /**\n * @internal\n * @hidden\n */\n constructor(\n db: Database,\n body: {\n extra: any;\n result: T[];\n hasMore: boolean;\n id: string;\n count: number;\n },\n host?: number,\n allowDirtyRead?: boolean\n ) {\n const batches = new LinkedList(\n body.result.length ? [new LinkedList(body.result)] : []\n );\n this._db = db;\n this._batches = batches;\n this._id = body.id;\n this._hasMore = Boolean(body.id && body.hasMore);\n this._host = host;\n this._count = body.count;\n this._extra = body.extra;\n this._allowDirtyRead = allowDirtyRead;\n this._itemsCursor = new ArrayCursor(this, {\n get isEmpty() {\n return !batches.length;\n },\n more: () => this._more(),\n shift: () => {\n let batch = batches.first?.value;\n while (batch && !batch.length) {\n batches.shift();\n batch = batches.first?.value;\n }\n if (!batch) return undefined;\n const value = batch.shift();\n if (!batch.length) batches.shift();\n return value;\n },\n });\n }\n\n protected async _more(): Promise<void> {\n if (!this.hasMore) return;\n const res = await this._db.request({\n method: \"PUT\",\n path: `/_api/cursor/${this._id}`,\n host: this._host,\n allowDirtyRead: this._allowDirtyRead,\n });\n this._batches.push(new LinkedList(res.body.result));\n this._hasMore = res.body.hasMore;\n }\n\n /**\n * An {@link ArrayCursor} providing item-wise access to the cursor result set.\n *\n * See also {@link ArrayCursor.batches}.\n */\n get items() {\n return this._itemsCursor;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): Readonly<CursorExtras> {\n return this._extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this._count;\n }\n\n /**\n * Whether the cursor has any remaining batches that haven't yet been\n * fetched. If set to `false`, all batches have been fetched and no\n * additional requests to the server will be made when consuming any\n * remaining batches from this cursor.\n */\n get hasMore(): boolean {\n return this._hasMore;\n }\n\n /**\n * Whether the cursor has more batches. If set to `false`, the cursor has\n * already been depleted and contains no more batches.\n */\n get hasNext(): boolean {\n return this.hasMore || Boolean(this._batches.length);\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every batch in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const users of cursor.batches) {\n * for (const user of users) {\n * console.log(user.email, user.isAdmin);\n * }\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T[], undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T[]>;\n }\n return undefined;\n }\n\n /**\n * Loads all remaining batches from the server.\n *\n * **Warning**: This may impact memory use when working with very large\n * query result sets.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * console.log(cursor.hasMore); // true\n * await cursor.batches.loadAll();\n * console.log(cursor.hasMore); // false\n * console.log(cursor.hasNext); // true\n * for await (const item of cursor) {\n * console.log(item);\n * // No server roundtrips necessary any more\n * }\n * ```\n */\n async loadAll(): Promise<void> {\n while (this._hasMore) {\n await this._more();\n }\n }\n\n /**\n * Depletes the cursor, then returns an array containing all batches in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.all(); // [[1, 2], [3, 4], [5]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[][]> {\n return this.map((batch) => batch);\n }\n\n /**\n * Advances the cursor and returns all remaining values in the cursor's\n * current batch. If the current batch has already been exhausted, fetches\n * the next batch from the server and returns it, or `undefined` if the\n * cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR i IN 1..10 RETURN i`,\n * { batchSize: 5 }\n * );\n * const firstBatch = await cursor.batches.next(); // [1, 2, 3, 4, 5]\n * await cursor.next(); // 6\n * const lastBatch = await cursor.batches.next(); // [7, 8, 9, 10]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async next(): Promise<T[] | undefined> {\n while (!this._batches.length && this.hasNext) {\n await this._more();\n }\n if (!this._batches.length) {\n return undefined;\n }\n const batch = this._batches.shift();\n if (!batch) return undefined;\n const values = [...batch.values()];\n batch.clear(true);\n return values;\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | `Array.prototype.forEach`}.\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * return false; // stop after the first batch\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentBatch: T[], index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const currentBatch = await this.next();\n const result = callback(currentBatch!, index, this);\n index++;\n if (result === false) return result;\n if (this.hasNext) await this._more();\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link BatchedArrayCursor.forEach}, {@link BatchedArrayCursor.reduce} or\n * {@link BatchedArrayCursor.flatMap} instead.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | `Array.prototype.map`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.map((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [[1, 4], [9, 16], [25]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentBatch: T[], index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n result.push(callback(currentBatch!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | `Array.prototype.flatMap`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.flatMap((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const odds = await cursor.batches.flatMap((currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentBatch;\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentBatch: T[], index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n const value = callback(currentBatch!, index, this);\n if (Array.isArray(value)) {\n result.push(...value);\n } else {\n result.push(value);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link BatchedArrayCursor.forEach} or the `for await`\n * syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestValue(baseline, values) {\n * return Math.max(baseline, ...values);\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.batches.reduce(largestValue, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const result = await cursor.reduce((accumulator, currentBatch) => {\n * accumulator[\n * currentBatch[0] % 2 === 0 ? \"even\" : \"odd\"\n * ].push(...currentBatch);\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const item of cursor) {\n * if (currentBatch[0] % 2 === 0) {\n * even.push(...currentBatch);\n * } else {\n * odd.push(...currentBatch);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue: R\n ): Promise<R>;\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestValue(values1, values2) {\n * return [Math.max(...values1, ...values2)];\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue);\n * console.log(result); // [5]\n * console.log(cursor.hasNext); // false\n * ```\n *\n */\n async reduce<R>(\n reducer: (\n accumulator: T[] | R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n initialValue = (await this.next()) as any;\n index += 1;\n }\n let value = initialValue as R;\n while (this.hasNext) {\n const currentBatch = await this.next();\n value = reducer(value, currentBatch!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Drains the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been consumed.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n if (this._batches.length) {\n for (const batch of this._batches.values()) {\n batch.clear();\n }\n this._batches.clear();\n }\n if (!this.hasNext) return undefined;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/cursor/${this._id}`,\n },\n () => {\n this._hasMore = false;\n return undefined;\n }\n );\n }\n}\n\n/**\n * The `ArrayCursor` type represents a cursor returned from a\n * {@link Database.query}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * See also {@link BatchedArrayCursor}.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const result = await db.query(query) as ArrayCursor<number>;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10 RETURN x`;\n * const cursor = await db.query(query);\n * for await (const value of cursor) {\n * // Process each value asynchronously\n * await processValue(value);\n * }\n * ```\n */\nexport class ArrayCursor<T = any> {\n protected _batches: BatchedArrayCursor<T>;\n protected _view: BatchView<T>;\n\n constructor(batchedCursor: BatchedArrayCursor, view: BatchView<T>) {\n this._batches = batchedCursor;\n this._view = view;\n }\n\n /**\n * A {@link BatchedArrayCursor} providing batch-wise access to the cursor\n * result set.\n *\n * See also {@link BatchedArrayCursor.items}.\n */\n get batches() {\n return this._batches;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): CursorExtras {\n return this.batches.extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this.batches.count;\n }\n\n /**\n * Whether the cursor has more values. If set to `false`, the cursor has\n * already been depleted and contains no more items.\n */\n get hasNext(): boolean {\n return this.batches.hasNext;\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every value in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const user of cursor) {\n * console.log(user.email, user.isAdmin);\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T, undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T>;\n }\n return undefined;\n }\n\n /**\n * Depletes the cursor, then returns an array containing all values in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.all(); // [1, 2, 3, 4, 5]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[]> {\n return this.batches.flatMap((v) => v);\n }\n\n /**\n * Advances the cursor and returns the next value in the cursor's remaining\n * result list, or `undefined` if the cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..3 RETURN x`);\n * const one = await cursor.next(); // 1\n * const two = await cursor.next(); // 2\n * const three = await cursor.next(); // 3\n * const empty = await cursor.next(); // undefined\n * ```\n */\n async next(): Promise<T | undefined> {\n while (this._view.isEmpty && this.batches.hasMore) {\n await this._view.more();\n }\n if (this._view.isEmpty) {\n return undefined;\n }\n return this._view.shift();\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | `Array.prototype.forEach`}.\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * return false; // stop after the first item\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentValue: T, index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const value = await this.next();\n const result = callback(value!, index, this);\n index++;\n if (result === false) return result;\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link ArrayCursor.forEach}, {@link ArrayCursor.reduce} or\n * {@link ArrayCursor.flatMap} instead.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | `Array.prototype.map`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.map((currentValue) => {\n * return currentValue ** 2;\n * });\n * console.log(squares); // [1, 4, 9, 16, 25]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentValue: T, index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n result.push(callback(value!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | `Array.prototype.flatMap`}.\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.flatMap((currentValue) => {\n * return [currentValue, currentValue ** 2];\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odds = await cursor.flatMap((currentValue) => {\n * if (currentValue % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentValue; // or [currentValue]\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentValue: T, index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n const item = callback(value!, index, this);\n if (Array.isArray(item)) {\n result.push(...item);\n } else {\n result.push(item);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link ArrayCursor.forEach} or the `for await` syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce((accumulator, currentValue) => {\n * accumulator[currentValue % 2 === 0 ? \"even\" : \"odd\"].push(currentValue);\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const item of cursor) {\n * if (currentValue % 2 === 0) {\n * even.push(currentValue);\n * } else {\n * odd.push(currentValue);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue: R\n ): Promise<R>;\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | `Array.prototype.reduce`}.\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo);\n * console.log(emptyResult); // undefined\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: T | R,\n currentValue: T,\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n const value = (await this.next()) as any;\n initialValue = value as R;\n index += 1;\n }\n let value = initialValue;\n while (this.hasNext) {\n const item = await this.next();\n value = reducer(value, item!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Kills the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been fetched.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n return this.batches.kill();\n }\n}\n"]}