@mherod/get-cookie 2.0.0-rc.2 → 2.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mherod/get-cookie",
3
- "version": "2.0.0-rc.2",
3
+ "version": "2.0.0-rc.4",
4
4
  "description": "Node.js module for querying a local user's Chrome cookie",
5
5
  "source": "src/index.ts",
6
6
  "bin": "dist/cli.js",
@@ -66,7 +66,9 @@
66
66
  "lodash": "^4.17.21",
67
67
  "lru-cache": "^7.14.0",
68
68
  "minimist": "^1.2.6",
69
- "sqlite3": "^5.1.1"
69
+ "sqlite3": "^5.1.1",
70
+ "tough-cookie": "^4.1.2",
71
+ "tough-cookie-file-store": "^2.0.3"
70
72
  },
71
73
  "devDependencies": {
72
74
  "@parcel/packager-ts": "^2.7.0",
@@ -75,6 +77,7 @@
75
77
  "@types/lodash": "^4.14.186",
76
78
  "@types/minimist": "^1.2.2",
77
79
  "@types/node": "^18.8.2",
80
+ "@types/tough-cookie": "^4.0.2",
78
81
  "@types/user-agents": "^1.0.2",
79
82
  "jest": "^29.0.3",
80
83
  "parcel": "^2.7.0",
package/src/CookieRow.ts CHANGED
@@ -1,4 +1,4 @@
1
- export interface CookieRow {
1
+ export default interface CookieRow {
2
2
  domain: string;
3
3
  name: string;
4
4
  value: Buffer;
package/src/CookieSpec.ts CHANGED
@@ -1,4 +1,4 @@
1
- export interface CookieSpec {
2
- name: string;
1
+ export default interface CookieSpec {
3
2
  domain: string;
3
+ name: string;
4
4
  }
@@ -0,0 +1,10 @@
1
+ import { CookieJar } from "tough-cookie";
2
+ import { env } from "./global";
3
+ const { FileCookieStore } = require("tough-cookie-file-store");
4
+
5
+ export const cookieStore = new FileCookieStore(
6
+ `${env["HOME"]}/cookie-star.json`
7
+ );
8
+ // export const cookieStore = new MemoryCookieStore();
9
+
10
+ export const cookieJar = new CookieJar(cookieStore);
@@ -1,4 +1,4 @@
1
- export interface ExportedCookie {
1
+ export default interface ExportedCookie {
2
2
  domain: string;
3
3
  name: string;
4
4
  value: string;
@@ -1,3 +1,5 @@
1
+ // noinspection JSUnusedGlobalSymbols
2
+
1
3
  import { Response } from "cross-fetch";
2
4
 
3
5
  export default interface FetchResponse extends Response {
@@ -1,4 +1,4 @@
1
- import { CookieRow } from "./CookieRow";
1
+ import CookieRow from "./CookieRow";
2
2
 
3
3
  export function isCookieRow(obj: any): obj is CookieRow {
4
4
  return (
@@ -1,4 +1,4 @@
1
- import { ExportedCookie } from "./ExportedCookie";
1
+ import ExportedCookie from "./ExportedCookie";
2
2
 
3
3
  export function isExportedCookie(obj: any): obj is ExportedCookie {
4
4
  return (
@@ -1,4 +1,4 @@
1
- import { CookieSpec } from "./CookieSpec";
1
+ import CookieSpec from "./CookieSpec";
2
2
 
3
3
  export function specialCases({ name, domain }: CookieSpec): {
4
4
  specifiedName: boolean;
@@ -0,0 +1,6 @@
1
+ export function stringToRegex(s: string): RegExp {
2
+ const s1 = s.replaceAll(/\./gi, ".");
3
+ const s2 = s1.replace(/%/g, ".*");
4
+ const s3 = s2.replace(/\*/g, ".*");
5
+ return new RegExp(s3);
6
+ }
@@ -9,10 +9,13 @@ import { doSqliteQuery1 } from "../doSqliteQuery1";
9
9
  import { merge } from "lodash";
10
10
  import { isCookieRow } from "../IsCookieRow";
11
11
  import { isExportedCookie } from "../IsExportedCookie";
12
- import { CookieRow } from "../CookieRow";
13
- import { ExportedCookie } from "../ExportedCookie";
12
+ import CookieRow from "../CookieRow";
13
+ import ExportedCookie from "../ExportedCookie";
14
+ import { stringToRegex } from "../StringToRegex";
14
15
 
15
16
  export default class ChromeCookieQueryStrategy implements CookieQueryStrategy {
17
+ browserName = "Chrome";
18
+
16
19
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
17
20
  if (process.platform !== "darwin") {
18
21
  throw new Error("This only works on macOS");
@@ -56,7 +59,7 @@ async function getPromise(name: string, domain: string): Promise<CookieRow[]> {
56
59
  const promises: Promise<CookieRow[]>[] = files.map((file) =>
57
60
  getPromise1(name, domain, file)
58
61
  );
59
- const results1: Awaited<CookieRow[]>[] = await Promise.all(promises);
62
+ const results1: CookieRow[][] = await Promise.all(promises);
60
63
  return results1.flat().filter(isCookieRow);
61
64
  } catch (error) {
62
65
  if (env.VERBOSE) {
@@ -146,19 +149,22 @@ async function getEncryptedChromeCookie({
146
149
  const wildcardRegexp = /^([*%])$/i;
147
150
  const specifiedName = name.match(wildcardRegexp) == null;
148
151
  const specifiedDomain = domain.match(wildcardRegexp) == null;
149
- if (specifiedName || specifiedDomain) {
152
+ const wildcardDomain = domain.match(/[%*]/) != null;
153
+ const queryDomain = specifiedDomain && !wildcardDomain;
154
+ // if we have a wildcard domain, we need to use a regexp
155
+ if (specifiedName || queryDomain) {
150
156
  sql += ` WHERE `;
151
157
  if (specifiedName) {
152
158
  sql += `name = '${name}'`;
153
- if (specifiedDomain) {
159
+ if (queryDomain) {
154
160
  sql += ` AND `;
155
161
  }
156
162
  }
157
- if (specifiedDomain) {
163
+ if (queryDomain) {
158
164
  sql += `host_key LIKE '${domain}';`;
159
165
  }
160
166
  }
161
- return doSqliteQuery1({
167
+ const sqliteQuery1: CookieRow[] = await doSqliteQuery1({
162
168
  file: file,
163
169
  sql: sql,
164
170
  rowTransform: (row) => {
@@ -169,6 +175,9 @@ async function getEncryptedChromeCookie({
169
175
  };
170
176
  },
171
177
  });
178
+ return sqliteQuery1.filter((row) => {
179
+ return row.domain.match(stringToRegex(domain)) != null;
180
+ });
172
181
  }
173
182
 
174
183
  async function getChromePassword(): Promise<string> {
@@ -2,8 +2,10 @@ import ChromeCookieQueryStrategy from "./ChromeCookieQueryStrategy";
2
2
  import FirefoxCookieQueryStrategy from "./FirefoxCookieQueryStrategy";
3
3
  import SafariCookieQueryStrategy from "./SafariCookieQueryStrategy";
4
4
  import CookieQueryStrategy from "./CookieQueryStrategy";
5
- import { ExportedCookie } from "../ExportedCookie";
5
+ import ExportedCookie from "../ExportedCookie";
6
6
  import LRUCache from "lru-cache";
7
+ import CookieStoreQueryStrategy from "./CookieStoreQueryStrategy";
8
+ import { red } from "colorette";
7
9
 
8
10
  const cache = new LRUCache<string, ExportedCookie[]>({
9
11
  ttl: 1000 * 2,
@@ -13,10 +15,13 @@ const cache = new LRUCache<string, ExportedCookie[]>({
13
15
  export default class CompositeCookieQueryStrategy
14
16
  implements CookieQueryStrategy
15
17
  {
18
+ browserName = "all";
19
+
16
20
  #strategies;
17
21
 
18
22
  constructor() {
19
23
  this.#strategies = [
24
+ CookieStoreQueryStrategy,
20
25
  ChromeCookieQueryStrategy,
21
26
  FirefoxCookieQueryStrategy,
22
27
  SafariCookieQueryStrategy,
@@ -26,19 +31,24 @@ export default class CompositeCookieQueryStrategy
26
31
  }
27
32
 
28
33
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
34
+ // domain = domain.match(/(\w+.+\w+)/gi)?.pop() ?? domain;
29
35
  const key = `${name}:${domain}`;
30
36
  const cached = cache.get(key);
31
37
  if (cached) {
32
38
  return cached;
33
39
  }
34
- const results = await Promise.all(
35
- this.#strategies.map(async (strategy) => {
40
+ console.log("Querying cookies:", name, domain);
41
+ const results: ExportedCookie[][] = await Promise.all(
42
+ this.#strategies.map(async (strategy: CookieQueryStrategy) => {
36
43
  // @ts-ignore
37
44
  const cookies: Promise<ExportedCookie[]> = strategy.queryCookies(
38
45
  name,
39
46
  domain
40
47
  );
41
- return cookies.catch(() => []);
48
+ return cookies.catch((e) => {
49
+ console.log(red(`Error querying ${strategy.browserName} cookies`), e);
50
+ return [];
51
+ });
42
52
  })
43
53
  );
44
54
  const flat: ExportedCookie[] = results.flat();
@@ -1,5 +1,6 @@
1
- import { ExportedCookie } from "../ExportedCookie";
1
+ import ExportedCookie from "../ExportedCookie";
2
2
 
3
3
  export default interface CookieQueryStrategy {
4
+ browserName: string;
4
5
  queryCookies(name: string, domain: string): Promise<ExportedCookie[]>;
5
6
  }
@@ -0,0 +1,88 @@
1
+ import CookieQueryStrategy from "./CookieQueryStrategy";
2
+ import CookieSpec from "../CookieSpec";
3
+ import ExportedCookie from "../ExportedCookie";
4
+ import { Cookie } from "tough-cookie";
5
+ import { cookieStore, cookieJar } from "../CookieStore";
6
+ import { stringToRegex } from "../StringToRegex";
7
+
8
+ export default class CookieStoreQueryStrategy implements CookieQueryStrategy {
9
+ browserName = "internal";
10
+
11
+ async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
12
+ const exportedCookies: ExportedCookie[] = [];
13
+
14
+ if (name.match(/[%*]/) || domain.match(/[%*]/)) {
15
+ const cookies: Cookie[] = await this.#getAllCookies();
16
+ const allExportedCookies = cookies.map((cookie: Cookie) => {
17
+ return this.#extracted(cookie, { name, domain });
18
+ });
19
+ exportedCookies.push(...allExportedCookies);
20
+ }
21
+
22
+ if (name == "%" && domain == "%") {
23
+ return exportedCookies;
24
+ }
25
+
26
+ const path = "/";
27
+
28
+ if (domain != "%") {
29
+ const domain1 = domain.match(/(\w+.+\w+)/gi)?.pop() ?? domain;
30
+ const url = new URL("https://" + domain1);
31
+ url.pathname = path;
32
+ const cookies: Cookie[] = await cookieJar.getCookies(url.href);
33
+ const domainCookies = cookies.map((cookie: Cookie) => {
34
+ return this.#extracted(cookie, {
35
+ domain,
36
+ name,
37
+ });
38
+ });
39
+ exportedCookies.push(...domainCookies);
40
+ }
41
+
42
+ if (name == "%") {
43
+ return exportedCookies;
44
+ }
45
+
46
+ const cookie: Cookie | null = await cookieStore.findCookie(
47
+ domain,
48
+ path,
49
+ name
50
+ );
51
+
52
+ if (cookie) {
53
+ const singleCookie = this.#extracted(cookie, { name, domain });
54
+ return [singleCookie];
55
+ }
56
+
57
+ return exportedCookies.filter((cookie: ExportedCookie) => {
58
+ return (
59
+ cookie.name.match(stringToRegex(name)) &&
60
+ cookie.domain.match(stringToRegex(domain))
61
+ );
62
+ });
63
+ }
64
+
65
+ #extracted(cookie: Cookie, cookieSpec: CookieSpec): ExportedCookie {
66
+ return {
67
+ domain: cookie.domain ?? cookieSpec.domain,
68
+ name: cookie.key ?? cookieSpec.name,
69
+ value: cookie.value,
70
+ meta: {
71
+ file: "memory",
72
+ },
73
+ };
74
+ }
75
+
76
+ #getAllCookies(): Promise<Cookie[]> {
77
+ return new Promise((resolve, reject) => {
78
+ // @ts-ignore
79
+ return cookieStore.getAllCookies((err, cookies) => {
80
+ if (err) {
81
+ reject(err);
82
+ } else {
83
+ resolve(cookies ?? []);
84
+ }
85
+ });
86
+ });
87
+ }
88
+ }
@@ -4,12 +4,14 @@ import { env, HOME } from "../global";
4
4
  import { existsSync } from "fs";
5
5
  import { findAllFiles } from "../findAllFiles";
6
6
  import { doSqliteQuery1 } from "../doSqliteQuery1";
7
- import { ExportedCookie } from "../ExportedCookie";
8
- import { CookieRow } from "../CookieRow";
9
- import { CookieSpec } from "../CookieSpec";
7
+ import ExportedCookie from "../ExportedCookie";
8
+ import CookieRow from "../CookieRow";
9
+ import CookieSpec from "../CookieSpec";
10
10
  import { specialCases } from "../SpecialCases";
11
11
 
12
12
  export default class FirefoxCookieQueryStrategy implements CookieQueryStrategy {
13
+ browserName = "Firefox";
14
+
13
15
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
14
16
  if (process.platform !== "darwin") {
15
17
  throw new Error("This only works on macOS");
@@ -1,7 +1,9 @@
1
1
  import CookieQueryStrategy from "./CookieQueryStrategy";
2
- import { ExportedCookie } from "../ExportedCookie";
2
+ import ExportedCookie from "../ExportedCookie";
3
3
 
4
4
  export default class SafariCookieQueryStrategy implements CookieQueryStrategy {
5
+ browserName = "Safari";
6
+
5
7
  async queryCookies(name: string, domain: string): Promise<ExportedCookie[]> {
6
8
  return [];
7
9
  }
package/src/cli.ts CHANGED
@@ -2,42 +2,50 @@
2
2
 
3
3
  import minimist from "minimist";
4
4
  import { argv } from "./argv";
5
- import { env } from "./global";
6
5
  import { queryCookies } from "./queryCookies";
7
6
  import { groupBy } from "lodash";
8
- import { green, yellow } from "colorette";
7
+ import { green, red, yellow } from "colorette";
9
8
  import { resultsRendered } from "./resultsRendered";
10
9
  import { fetchWithCookies } from "./fetchWithCookies";
11
10
  import { unpackHeaders } from "./unpackHeaders";
11
+ import CookieSpec from "./CookieSpec";
12
12
 
13
- const parsedArgs: minimist.ParsedArgs = minimist(argv);
13
+ const parsedArgs: minimist.ParsedArgs = minimist(argv.slice(2));
14
14
 
15
- async function cliQueryCookies(name: string, domain: string) {
15
+ async function cliQueryCookies({ name, domain }: CookieSpec) {
16
16
  try {
17
17
  const results = await queryCookies({ name, domain });
18
- if (results.length > 0) {
19
- if (argv.includes("--combined-string")) {
20
- console.log(yellow(resultsRendered(results)));
21
- } else if (argv.includes("--render") || argv.includes("-r")) {
22
- console.log(yellow(resultsRendered(results)));
23
- } else if (argv.includes("--dump") || argv.includes("-d")) {
24
- console.log(results);
25
- } else if (argv.includes("--dump-grouped")) {
26
- const groupedByFile = groupBy(results, (r) => r.meta?.file);
27
- console.log(green(JSON.stringify(groupedByFile, null, 2)));
28
- } else if (argv.includes("--combined-string-grouped")) {
29
- const groupedByFile = groupBy(results, (r) => r.meta?.file);
30
- for (const file of Object.keys(groupedByFile)) {
31
- let results = groupedByFile[file];
32
- console.log(green(file) + ": ", yellow(resultsRendered(results)));
33
- }
34
- } else {
35
- for (const result of results) {
36
- console.log(result.value);
37
- }
18
+ if (results == null || results.length == 0) {
19
+ console.error(red("No results"));
20
+ return;
21
+ }
22
+ if (parsedArgs["dump"] || parsedArgs["d"]) {
23
+ console.log(results);
24
+ return;
25
+ }
26
+ if (parsedArgs["dump-grouped"] || parsedArgs["D"]) {
27
+ const groupedByFile = groupBy(results, (r) => r.meta?.file);
28
+ console.log(green(JSON.stringify(groupedByFile, null, 2)));
29
+ return;
30
+ }
31
+ if (
32
+ parsedArgs["render"] ||
33
+ parsedArgs["render-merged"] ||
34
+ parsedArgs["r"]
35
+ ) {
36
+ console.log(yellow(resultsRendered(results)));
37
+ return;
38
+ }
39
+ if (parsedArgs["render-grouped"] || parsedArgs["R"]) {
40
+ const groupedByFile = groupBy(results, (r) => r.meta?.file);
41
+ for (const file of Object.keys(groupedByFile)) {
42
+ let results = groupedByFile[file];
43
+ console.log(green(file) + ": ", yellow(resultsRendered(results)));
38
44
  }
39
- } else {
40
- console.error("No results");
45
+ return;
46
+ }
47
+ for (const result of results) {
48
+ console.log(result.value);
41
49
  }
42
50
  } catch (e) {
43
51
  console.error(e);
@@ -45,74 +53,62 @@ async function cliQueryCookies(name: string, domain: string) {
45
53
  }
46
54
 
47
55
  function main() {
48
- if (argv && argv.length > 2) {
49
- const arg2 = argv[2];
50
- const arg3 = argv[3];
51
- if (arg2 == "--fetch" || arg2 == "-f") {
52
- const f = parsedArgs["f"];
53
- let url: URL;
54
- try {
55
- url = new URL(f);
56
- } catch (e) {
57
- console.error("Invalid URL", arg3);
58
- return;
56
+ if (parsedArgs["help"] || parsedArgs["h"]) {
57
+ console.log(`Usage: ${argv[1]} [name] [domain] [options] `);
58
+ console.log(`Options:`);
59
+ console.log(` -h, --help: Show this help`);
60
+ console.log(` -v, --verbose: Show verbose output`);
61
+ console.log(` -d, --dump: Dump all results`);
62
+ console.log(` -D, --dump-grouped: Dump all results, grouped by profile`);
63
+ console.log(` -r, --render: Render all results`);
64
+ return;
65
+ }
66
+
67
+ const fetchUrl: string = parsedArgs["fetch"] || parsedArgs["F"];
68
+ if (fetchUrl) {
69
+ let url: URL;
70
+ try {
71
+ url = new URL(<string>fetchUrl);
72
+ } catch (e) {
73
+ console.error("Invalid URL", fetchUrl);
74
+ return;
75
+ }
76
+ const headerArgs: string[] | string = parsedArgs["H"];
77
+ const headers = unpackHeaders(headerArgs);
78
+ const onfulfilled = (res: Response) => {
79
+ if (parsedArgs["dump-response-headers"]) {
80
+ res.headers.forEach((value: string, key: string) => {
81
+ console.log(`${key}: ${value}`);
82
+ });
59
83
  }
60
- const headerArgs: string[] | string = parsedArgs["H"];
61
- const headers = unpackHeaders(headerArgs);
62
- const onfulfilled = (res: Response) => {
63
- return res.text().then((r) => {
84
+ if (parsedArgs["dump-response-body"]) {
85
+ res.text().then((r) => {
64
86
  console.log(r);
65
87
  });
66
- };
67
- fetchWithCookies(
68
- url,
69
- {
70
- //
71
- headers,
72
- }
73
- //
74
- ).then(
75
- onfulfilled,
76
- console.error
77
- //
78
- );
88
+ }
79
89
  return;
80
- }
81
- let domain;
82
- if (arg3 != null && arg3.indexOf(".") > -1) {
83
- domain = arg3;
84
- } else {
85
- domain = "%";
86
- }
87
-
88
- const tru = `${true}`;
89
-
90
- if (argv.includes("--require-jwt")) {
91
- env.REQUIRE_JWT = tru;
92
- }
93
- if (argv.includes("--verbose")) {
94
- env.VERBOSE = tru;
95
- }
96
- if (argv.includes("--chrome-only")) {
97
- env.CHROME_ONLY = tru;
98
- }
99
- if (argv.includes("--firefox-only")) {
100
- env.FIREFOX_ONLY = tru;
101
- }
102
- if (argv.includes("--ignore-expired")) {
103
- env.IGNORE_EXPIRED = tru;
104
- }
105
-
106
- if (argv.includes("--single")) {
107
- env.SINGLE = tru;
108
- }
90
+ };
91
+ fetchWithCookies(
92
+ url,
93
+ {
94
+ //
95
+ headers,
96
+ }
97
+ //
98
+ ).then(
99
+ onfulfilled,
100
+ console.error
101
+ //
102
+ );
103
+ return;
104
+ }
109
105
 
110
- if (env.VERBOSE) {
111
- console.log("Verbose mode", argv);
112
- }
106
+ const cookieSpec: CookieSpec = {
107
+ name: parsedArgs["name"] || parsedArgs["_"][0] || "%",
108
+ domain: parsedArgs["domain"] || parsedArgs["_"][1] || "%",
109
+ };
113
110
 
114
- cliQueryCookies(arg2, domain).catch(console.error);
115
- }
111
+ cliQueryCookies(cookieSpec).catch(console.error);
116
112
  }
117
113
 
118
114
  main();
@@ -1,6 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as sqlite3 from "sqlite3";
3
- import { CookieRow } from "./CookieRow";
3
+ import CookieRow from "./CookieRow";
4
4
  import { merge } from "lodash";
5
5
 
6
6
  interface DoSqliteQuery1Params {
@@ -1,16 +1,18 @@
1
1
  // noinspection JSUnusedGlobalSymbols
2
2
 
3
- import { fetch } from "cross-fetch";
3
+ import { fetch as fetchImpl } from "cross-fetch";
4
4
  import { merge } from "lodash";
5
5
  // noinspection SpellCheckingInspection
6
6
  import destr from "destr";
7
- import FetchResponse from "./FetchResponse";
7
+ import CookieSpec from "./CookieSpec";
8
8
  import { getGroupedRenderedCookies } from "./getGroupedRenderedCookies";
9
+ import { cookieJar } from "./CookieStore";
9
10
 
10
11
  export async function fetchWithCookies(
11
12
  url: RequestInfo | URL,
12
- options: RequestInit | undefined = {}
13
- ): Promise<FetchResponse> {
13
+ options: RequestInit | undefined = {},
14
+ fetch: Function = fetchImpl
15
+ ): Promise<Response> {
14
16
  const defaultOptions: RequestInit = {
15
17
  headers: {
16
18
  "User-Agent":
@@ -23,10 +25,13 @@ export async function fetchWithCookies(
23
25
  const domain = url1.hostname.replace(/^.*(\.\w+\.\w+)$/, (match, p1) => {
24
26
  return `%${p1}`;
25
27
  });
26
- const cookies: string[] = await getGroupedRenderedCookies({
28
+ const cookieSpec: CookieSpec = {
27
29
  name: "%",
28
30
  domain: domain,
29
- }).catch(() => []);
31
+ };
32
+ const cookies: string[] = await getGroupedRenderedCookies(cookieSpec).catch(
33
+ () => []
34
+ );
30
35
  const cookie = cookies.pop();
31
36
  const newOptions1: RequestInit = merge(defaultOptions, options, {
32
37
  headers: {
@@ -35,29 +40,64 @@ export async function fetchWithCookies(
35
40
  });
36
41
  try {
37
42
  const res: Response = await fetch(url2, newOptions1);
38
- const newUrl = res.headers.get("location") as string;
43
+ const headers: [string, string][] = [];
44
+ res.headers.forEach((value, key) => {
45
+ headers.push([key, value]);
46
+ });
47
+ for (const [key, value] of headers) {
48
+ if (key === "set-cookie") {
49
+ await cookieJar.setCookie(value, url2);
50
+ // const cookie = tough.parse(value);
51
+ // if (cookie instanceof Cookie) {
52
+ // await memoryCookieStore.putCookie(cookie);
53
+ // }
54
+ }
55
+ }
56
+
57
+ const newUrl: string = res.headers.get("location") as string;
39
58
  if (res.redirected || (newUrl && newUrl !== url2)) {
40
59
  return fetchWithCookies(newUrl, newOptions1);
41
60
  }
42
- const arrayBuffer1 = res.arrayBuffer();
43
- const arrayBuffer = async () => arrayBuffer1;
44
- const buffer = async () => arrayBuffer().then(Buffer.from);
45
- const text = async () => buffer().then((buffer) => buffer.toString("utf8"));
46
- const json = async () => text().then(destr);
47
- const formData = async () =>
48
- text().then((text) => new URLSearchParams(text));
61
+
62
+ const arrayBuffer1: Promise<ArrayBuffer> = res.arrayBuffer();
63
+
64
+ async function arrayBuffer(): Promise<ArrayBuffer> {
65
+ return arrayBuffer1;
66
+ }
67
+
68
+ async function buffer(): Promise<Buffer> {
69
+ return arrayBuffer().then(Buffer.from);
70
+ }
71
+
72
+ async function text(): Promise<string> {
73
+ return buffer().then((buffer) => buffer.toString("utf8"));
74
+ }
75
+
76
+ async function json(): Promise<any> {
77
+ return text().then((text) => destr(text));
78
+ }
79
+
80
+ async function formData(): Promise<FormData> {
81
+ const urlSearchParams: URLSearchParams = await text().then(
82
+ (text) => new URLSearchParams(text)
83
+ );
84
+ const formData = new FormData();
85
+ for (const [key, value] of urlSearchParams.entries()) {
86
+ formData.append(key, value);
87
+ }
88
+ return formData;
89
+ }
90
+
91
+ const res1: Response = res;
49
92
  const source2 = {
50
- status: res.status,
51
- statusText: res.statusText,
52
- headers: res.headers,
53
93
  arrayBuffer,
54
- buffer,
55
94
  text,
56
95
  json,
96
+ buffer,
57
97
  formData,
58
98
  //
59
99
  };
60
- return merge({}, res, source2);
100
+ return merge(res1, source2);
61
101
  } catch (e) {
62
102
  throw e;
63
103
  }