@stacks/network 6.17.0 → 7.0.0-beta.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.
package/src/network.ts CHANGED
@@ -1,215 +1,132 @@
1
- import { TransactionVersion, ChainID } from '@stacks/common';
2
- import { createFetchFn, FetchFn } from './fetch';
3
-
4
- export const HIRO_MAINNET_DEFAULT = 'https://api.mainnet.hiro.so';
5
- export const HIRO_TESTNET_DEFAULT = 'https://api.testnet.hiro.so';
6
- export const HIRO_MOCKNET_DEFAULT = 'http://localhost:3999';
1
+ import {
2
+ ClientOpts,
3
+ DEVNET_URL,
4
+ FetchFn,
5
+ HIRO_MAINNET_URL,
6
+ HIRO_TESTNET_URL,
7
+ createFetchFn,
8
+ } from '@stacks/common';
9
+ import { AddressVersion, ChainId, PeerNetworkId, TransactionVersion } from './constants';
10
+ import { ClientParam } from '@stacks/common';
11
+
12
+ export type StacksNetwork = {
13
+ chainId: number;
14
+ transactionVersion: number; // todo: txVersion better?
15
+ peerNetworkId: number;
16
+ magicBytes: string;
17
+ bootAddress: string;
18
+ addressVersion: {
19
+ singleSig: number;
20
+ multiSig: number;
21
+ };
22
+ // todo: add check32 character bytes string
23
+ client: {
24
+ baseUrl: string; // URL is always required
25
+ fetch?: FetchFn; // fetch is optional and will be created by default in fetch helpers
26
+ };
27
+ };
7
28
 
8
- /**
9
- * Used for constructing Network instances
10
- * @related {@link StacksNetwork}, {@link StacksMainnet}, {@link StacksTestnet}, {@link StacksDevnet}, {@link StacksMocknet}
11
- */
12
- export interface NetworkConfig {
13
- /** The base API/node URL for the network fetch calls */
14
- url: string;
15
- /** An optional custom fetch function to override default behaviors */
16
- fetchFn?: FetchFn;
29
+ export interface NetworkParam {
30
+ network?: StacksNetworkName | StacksNetwork;
17
31
  }
18
32
 
33
+ export type NetworkClientParam = NetworkParam & ClientParam;
34
+
35
+ export const STACKS_MAINNET: StacksNetwork = {
36
+ chainId: ChainId.Mainnet,
37
+ transactionVersion: TransactionVersion.Mainnet,
38
+ peerNetworkId: PeerNetworkId.Mainnet,
39
+ magicBytes: 'X2', // todo: comment bytes version of magic bytes
40
+ bootAddress: 'SP000000000000000000002Q6VF78',
41
+ addressVersion: {
42
+ singleSig: AddressVersion.MainnetSingleSig,
43
+ multiSig: AddressVersion.MainnetMultiSig,
44
+ },
45
+ client: { baseUrl: HIRO_MAINNET_URL },
46
+ };
47
+
48
+ export const STACKS_TESTNET: StacksNetwork = {
49
+ chainId: ChainId.Testnet,
50
+ transactionVersion: TransactionVersion.Testnet,
51
+ peerNetworkId: PeerNetworkId.Testnet,
52
+ magicBytes: 'T2', // todo: comment bytes version of magic bytes
53
+ bootAddress: 'ST000000000000000000002AMW42H',
54
+ addressVersion: {
55
+ singleSig: AddressVersion.TestnetSingleSig,
56
+ multiSig: AddressVersion.TestnetMultiSig,
57
+ },
58
+ client: { baseUrl: HIRO_TESTNET_URL },
59
+ };
60
+
61
+ export const STACKS_DEVNET: StacksNetwork = {
62
+ ...STACKS_TESTNET, // todo: ensure deep copy
63
+ addressVersion: { ...STACKS_TESTNET.addressVersion }, // deep copy
64
+ magicBytes: 'id', // todo: comment bytes version of magic bytes
65
+ client: { baseUrl: DEVNET_URL },
66
+ };
67
+
68
+ export const STACKS_MOCKNET: StacksNetwork = {
69
+ ...STACKS_DEVNET,
70
+ addressVersion: { ...STACKS_DEVNET.addressVersion }, // deep copy
71
+ client: { ...STACKS_DEVNET.client }, // deep copy
72
+ };
73
+
19
74
  /** @ignore internal */
20
75
  export const StacksNetworks = ['mainnet', 'testnet', 'devnet', 'mocknet'] as const;
21
76
  /** The enum-style names of different common Stacks networks */
22
77
  export type StacksNetworkName = (typeof StacksNetworks)[number];
23
78
 
24
79
  /**
25
- * The base class for Stacks networks. Typically used via its subclasses.
26
- * @related {@link StacksMainnet}, {@link StacksTestnet}, {@link StacksDevnet}, {@link StacksMocknet}
27
- */
28
- export class StacksNetwork {
29
- version: TransactionVersion = TransactionVersion.Mainnet;
30
- chainId: ChainID = ChainID.Mainnet;
31
- bnsLookupUrl = 'https://api.mainnet.hiro.so';
32
- broadcastEndpoint = '/v2/transactions';
33
- transferFeeEstimateEndpoint = '/v2/fees/transfer';
34
- transactionFeeEstimateEndpoint = '/v2/fees/transaction';
35
- accountEndpoint = '/v2/accounts';
36
- contractAbiEndpoint = '/v2/contracts/interface';
37
- readOnlyFunctionCallEndpoint = '/v2/contracts/call-read';
38
-
39
- readonly coreApiUrl: string;
40
-
41
- fetchFn: FetchFn;
42
-
43
- constructor(networkConfig: NetworkConfig) {
44
- this.coreApiUrl = networkConfig.url;
45
- this.fetchFn = networkConfig.fetchFn ?? createFetchFn();
46
- }
47
-
48
- /** A static network constructor from a network name */
49
- static fromName = (networkName: StacksNetworkName): StacksNetwork => {
50
- switch (networkName) {
51
- case 'mainnet':
52
- return new StacksMainnet();
53
- case 'testnet':
54
- return new StacksTestnet();
55
- case 'devnet':
56
- return new StacksDevnet();
57
- case 'mocknet':
58
- return new StacksMocknet();
59
- default:
60
- throw new Error(
61
- `Invalid network name provided. Must be one of the following: ${StacksNetworks.join(
62
- ', '
63
- )}`
64
- );
65
- }
66
- };
67
-
68
- /** @ignore internal */
69
- static fromNameOrNetwork = (network: StacksNetworkName | StacksNetwork) => {
70
- if (typeof network !== 'string' && 'version' in network) {
71
- return network;
72
- }
73
-
74
- return StacksNetwork.fromName(network);
75
- };
76
-
77
- /** Returns `true` if the network is configured to 'mainnet', based on the TransactionVersion */
78
- isMainnet = () => this.version === TransactionVersion.Mainnet;
79
- getBroadcastApiUrl = () => `${this.coreApiUrl}${this.broadcastEndpoint}`;
80
- getTransferFeeEstimateApiUrl = () => `${this.coreApiUrl}${this.transferFeeEstimateEndpoint}`;
81
- getTransactionFeeEstimateApiUrl = () =>
82
- `${this.coreApiUrl}${this.transactionFeeEstimateEndpoint}`;
83
- getAccountApiUrl = (address: string) =>
84
- `${this.coreApiUrl}${this.accountEndpoint}/${address}?proof=0`;
85
- getAccountExtendedBalancesApiUrl = (address: string) =>
86
- `${this.coreApiUrl}/extended/v1/address/${address}/balances`;
87
- getAbiApiUrl = (address: string, contract: string) =>
88
- `${this.coreApiUrl}${this.contractAbiEndpoint}/${address}/${contract}`;
89
- getReadOnlyFunctionCallApiUrl = (
90
- contractAddress: string,
91
- contractName: string,
92
- functionName: string
93
- ) =>
94
- `${this.coreApiUrl}${
95
- this.readOnlyFunctionCallEndpoint
96
- }/${contractAddress}/${contractName}/${encodeURIComponent(functionName)}`;
97
- getInfoUrl = () => `${this.coreApiUrl}/v2/info`;
98
- getBlockTimeInfoUrl = () => `${this.coreApiUrl}/extended/v1/info/network_block_times`;
99
- getPoxInfoUrl = () => `${this.coreApiUrl}/v2/pox`;
100
- getRewardsUrl = (address: string, options?: any) => {
101
- let url = `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}`;
102
- if (options) {
103
- url = `${url}?limit=${options.limit}&offset=${options.offset}`;
104
- }
105
- return url;
106
- };
107
- getRewardsTotalUrl = (address: string) =>
108
- `${this.coreApiUrl}/extended/v1/burnchain/rewards/${address}/total`;
109
- getRewardHoldersUrl = (address: string, options?: any) => {
110
- let url = `${this.coreApiUrl}/extended/v1/burnchain/reward_slot_holders/${address}`;
111
- if (options) {
112
- url = `${url}?limit=${options.limit}&offset=${options.offset}`;
113
- }
114
- return url;
115
- };
116
- getStackerInfoUrl = (contractAddress: string, contractName: string) =>
117
- `${this.coreApiUrl}${this.readOnlyFunctionCallEndpoint}
118
- ${contractAddress}/${contractName}/get-stacker-info`;
119
- getDataVarUrl = (contractAddress: string, contractName: string, dataVarName: string) =>
120
- `${this.coreApiUrl}/v2/data_var/${contractAddress}/${contractName}/${dataVarName}?proof=0`;
121
- getMapEntryUrl = (contractAddress: string, contractName: string, mapName: string) =>
122
- `${this.coreApiUrl}/v2/map_entry/${contractAddress}/${contractName}/${mapName}?proof=0`;
123
- getNameInfo(fullyQualifiedName: string) {
124
- /*
125
- TODO: Update to v2 API URL for name lookups
126
- */
127
- const nameLookupURL = `${this.bnsLookupUrl}/v1/names/${fullyQualifiedName}`;
128
- return this.fetchFn(nameLookupURL)
129
- .then(resp => {
130
- if (resp.status === 404) {
131
- throw new Error('Name not found');
132
- } else if (resp.status !== 200) {
133
- throw new Error(`Bad response status: ${resp.status}`);
134
- } else {
135
- return resp.json();
136
- }
137
- })
138
- .then(nameInfo => {
139
- // the returned address _should_ be in the correct network ---
140
- // stacks node gets into trouble because it tries to coerce back to mainnet
141
- // and the regtest transaction generation libraries want to use testnet addresses
142
- if (nameInfo.address) {
143
- return Object.assign({}, nameInfo, { address: nameInfo.address });
144
- } else {
145
- return nameInfo;
146
- }
147
- });
148
- }
149
- }
150
-
151
- /**
152
- * A {@link StacksNetwork} with the parameters for the Stacks mainnet.
153
- * Pass a `url` option to override the default Hiro hosted Stacks node API.
154
- * Pass a `fetchFn` option to customize the default networking functions.
80
+ * Returns the default network for a given name
155
81
  * @example
82
+ * ```ts
83
+ * networkFromName('mainnet') // same as STACKS_MAINNET
84
+ * networkFromName('testnet') // same as STACKS_TESTNET
85
+ * networkFromName('devnet') // same as STACKS_DEVNET
86
+ * networkFromName('mocknet') // same as STACKS_MOCKNET
156
87
  * ```
157
- * const network = new StacksMainnet();
158
- * const network = new StacksMainnet({ url: "https://api.mainnet.hiro.so" });
159
- * const network = new StacksMainnet({ fetch: createFetchFn() });
160
- * ```
161
- * @related {@link createFetchFn}, {@link createApiKeyMiddleware}
162
88
  */
163
- export class StacksMainnet extends StacksNetwork {
164
- version = TransactionVersion.Mainnet;
165
- chainId = ChainID.Mainnet;
166
-
167
- constructor(opts?: Partial<NetworkConfig>) {
168
- super({
169
- url: opts?.url ?? HIRO_MAINNET_DEFAULT,
170
- fetchFn: opts?.fetchFn,
171
- });
89
+ export function networkFromName(name: StacksNetworkName) {
90
+ switch (name) {
91
+ case 'mainnet':
92
+ return STACKS_MAINNET;
93
+ case 'testnet':
94
+ return STACKS_TESTNET;
95
+ case 'devnet':
96
+ return STACKS_DEVNET;
97
+ case 'mocknet':
98
+ return STACKS_MOCKNET;
99
+ default:
100
+ throw new Error(`Unknown network name: ${name}`);
172
101
  }
173
102
  }
174
103
 
175
- /**
176
- * A {@link StacksNetwork} with the parameters for the Stacks testnet.
177
- * Pass a `url` option to override the default Hiro hosted Stacks node API.
178
- * Pass a `fetchFn` option to customize the default networking functions.
179
- * @example
180
- * ```
181
- * const network = new StacksTestnet();
182
- * const network = new StacksTestnet({ url: "https://api.testnet.hiro.so" });
183
- * const network = new StacksTestnet({ fetch: createFetchFn() });
184
- * ```
185
- * @related {@link createFetchFn}, {@link createApiKeyMiddleware}
186
- */
187
- export class StacksTestnet extends StacksNetwork {
188
- version = TransactionVersion.Testnet;
189
- chainId = ChainID.Testnet;
104
+ /** @ignore */
105
+ export function networkFrom(network: StacksNetworkName | StacksNetwork) {
106
+ if (typeof network === 'string') return networkFromName(network);
107
+ return network;
108
+ }
190
109
 
191
- constructor(opts?: Partial<NetworkConfig>) {
192
- super({
193
- url: opts?.url ?? HIRO_TESTNET_DEFAULT,
194
- fetchFn: opts?.fetchFn,
195
- });
196
- }
110
+ /** @ignore */
111
+ export function defaultUrlFromNetwork(network?: StacksNetworkName | StacksNetwork) {
112
+ if (!network) return HIRO_MAINNET_URL; // default to mainnet if no network is given
113
+
114
+ network = networkFrom(network);
115
+
116
+ return !network || network.transactionVersion === TransactionVersion.Mainnet
117
+ ? HIRO_MAINNET_URL // default to mainnet if txVersion is mainnet
118
+ : network.magicBytes === 'id'
119
+ ? DEVNET_URL // default to devnet if magicBytes are devnet
120
+ : HIRO_TESTNET_URL;
197
121
  }
198
122
 
199
123
  /**
200
- * A {@link StacksNetwork} using the testnet parameters, but `localhost:3999` as the API URL.
124
+ * Returns the client of a network, creating a new fetch function if none is available
201
125
  */
202
- export class StacksMocknet extends StacksNetwork {
203
- version = TransactionVersion.Testnet;
204
- chainId = ChainID.Testnet;
205
-
206
- constructor(opts?: Partial<NetworkConfig>) {
207
- super({
208
- url: opts?.url ?? HIRO_MOCKNET_DEFAULT,
209
- fetchFn: opts?.fetchFn,
210
- });
211
- }
126
+ export function clientFromNetwork(network: StacksNetwork): Required<ClientOpts> {
127
+ if (network.client.fetch) return network.client as Required<ClientOpts>;
128
+ return {
129
+ ...network.client,
130
+ fetch: createFetchFn(),
131
+ };
212
132
  }
213
-
214
- /** Alias for {@link StacksMocknet} */
215
- export const StacksDevnet = StacksMocknet;
@@ -1,31 +0,0 @@
1
- import 'cross-fetch/polyfill';
2
- export declare const getFetchOptions: () => RequestInit;
3
- export declare const setFetchOptions: (ops: RequestInit) => RequestInit;
4
- export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>;
5
- export interface RequestContext {
6
- fetch: FetchFn;
7
- url: string;
8
- init: RequestInit;
9
- }
10
- export interface ResponseContext {
11
- fetch: FetchFn;
12
- url: string;
13
- init: RequestInit;
14
- response: Response;
15
- }
16
- export interface FetchParams {
17
- url: string;
18
- init: RequestInit;
19
- }
20
- export interface FetchMiddleware {
21
- pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void;
22
- post?: (context: ResponseContext) => Promise<Response | void> | Response | void;
23
- }
24
- export interface ApiKeyMiddlewareOpts {
25
- host?: RegExp | string;
26
- httpHeader?: string;
27
- apiKey: string;
28
- }
29
- export declare function createApiKeyMiddleware({ apiKey, host, httpHeader, }: ApiKeyMiddlewareOpts): FetchMiddleware;
30
- export declare function createFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn;
31
- export declare function createFetchFn(...middleware: FetchMiddleware[]): FetchFn;
package/dist/esm/fetch.js DELETED
@@ -1,78 +0,0 @@
1
- import 'cross-fetch/polyfill';
2
- const defaultFetchOpts = {
3
- referrerPolicy: 'origin',
4
- headers: {
5
- 'x-hiro-product': 'stacksjs',
6
- },
7
- };
8
- export const getFetchOptions = () => {
9
- return defaultFetchOpts;
10
- };
11
- export const setFetchOptions = (ops) => {
12
- return Object.assign(defaultFetchOpts, ops);
13
- };
14
- export async function fetchWrapper(input, init) {
15
- const fetchOpts = {};
16
- Object.assign(fetchOpts, defaultFetchOpts, init);
17
- const fetchResult = await fetch(input, fetchOpts);
18
- return fetchResult;
19
- }
20
- export function hostMatches(host, pattern) {
21
- if (typeof pattern === 'string')
22
- return pattern === host;
23
- return pattern.exec(host);
24
- }
25
- export function createApiKeyMiddleware({ apiKey, host = /(.*)api(.*)(\.stacks\.co|\.hiro\.so)$/i, httpHeader = 'x-api-key', }) {
26
- return {
27
- pre: context => {
28
- const reqUrl = new URL(context.url);
29
- if (!hostMatches(reqUrl.host, host))
30
- return;
31
- const headers = context.init.headers instanceof Headers
32
- ? context.init.headers
33
- : (context.init.headers = new Headers(context.init.headers));
34
- headers.set(httpHeader, apiKey);
35
- },
36
- };
37
- }
38
- function argsForCreateFetchFn(args) {
39
- let fetchLib = fetchWrapper;
40
- let middlewares = [];
41
- if (args.length > 0 && typeof args[0] === 'function') {
42
- fetchLib = args.shift();
43
- }
44
- if (args.length > 0) {
45
- middlewares = args;
46
- }
47
- return { fetchLib, middlewares };
48
- }
49
- export function createFetchFn(...args) {
50
- const { fetchLib, middlewares } = argsForCreateFetchFn(args);
51
- const fetchFn = async (url, init) => {
52
- let fetchParams = { url, init: init ?? {} };
53
- for (const middleware of middlewares) {
54
- if (typeof middleware.pre === 'function') {
55
- const result = await Promise.resolve(middleware.pre({
56
- fetch: fetchLib,
57
- ...fetchParams,
58
- }));
59
- fetchParams = result ?? fetchParams;
60
- }
61
- }
62
- let response = await fetchLib(fetchParams.url, fetchParams.init);
63
- for (const middleware of middlewares) {
64
- if (typeof middleware.post === 'function') {
65
- const result = await Promise.resolve(middleware.post({
66
- fetch: fetchLib,
67
- url: fetchParams.url,
68
- init: fetchParams.init,
69
- response: response?.clone() ?? response,
70
- }));
71
- response = result ?? response;
72
- }
73
- }
74
- return response;
75
- };
76
- return fetchFn;
77
- }
78
- //# sourceMappingURL=fetch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["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G,MAAM,IAAI,WAAW,CAAC;aACrC;SACF;QAED,IAAI,QAAQ,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,WAAW,CAAC,IAAI,CAAC,CAAC;QAEjE,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE;YACpC,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,UAAU,EAAE;gBACzC,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAClC,UAAU,CAAC,IAAI,CAAC;oBACd,KAAK,EAAE,QAAQ;oBACf,GAAG,EAAE,WAAW,CAAC,GAAG;oBACpB,IAAI,EAAE,WAAW,CAAC,IAAI;oBACtB,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,QAAQ;iBACxC,CAAC,CACH,CAAC;gBACF,QAAQ,GAAG,MAAM,IAAI,QAAQ,CAAC;aAC/B;SACF;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC"}
package/dist/fetch.d.ts DELETED
@@ -1,31 +0,0 @@
1
- import 'cross-fetch/polyfill';
2
- export declare const getFetchOptions: () => RequestInit;
3
- export declare const setFetchOptions: (ops: RequestInit) => RequestInit;
4
- export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>;
5
- export interface RequestContext {
6
- fetch: FetchFn;
7
- url: string;
8
- init: RequestInit;
9
- }
10
- export interface ResponseContext {
11
- fetch: FetchFn;
12
- url: string;
13
- init: RequestInit;
14
- response: Response;
15
- }
16
- export interface FetchParams {
17
- url: string;
18
- init: RequestInit;
19
- }
20
- export interface FetchMiddleware {
21
- pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void;
22
- post?: (context: ResponseContext) => Promise<Response | void> | Response | void;
23
- }
24
- export interface ApiKeyMiddlewareOpts {
25
- host?: RegExp | string;
26
- httpHeader?: string;
27
- apiKey: string;
28
- }
29
- export declare function createApiKeyMiddleware({ apiKey, host, httpHeader, }: ApiKeyMiddlewareOpts): FetchMiddleware;
30
- export declare function createFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn;
31
- export declare function createFetchFn(...middleware: FetchMiddleware[]): FetchFn;
package/dist/fetch.js DELETED
@@ -1,87 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createFetchFn = exports.createApiKeyMiddleware = exports.hostMatches = exports.fetchWrapper = exports.setFetchOptions = exports.getFetchOptions = void 0;
4
- require("cross-fetch/polyfill");
5
- const defaultFetchOpts = {
6
- referrerPolicy: 'origin',
7
- headers: {
8
- 'x-hiro-product': 'stacksjs',
9
- },
10
- };
11
- const getFetchOptions = () => {
12
- return defaultFetchOpts;
13
- };
14
- exports.getFetchOptions = getFetchOptions;
15
- const setFetchOptions = (ops) => {
16
- return Object.assign(defaultFetchOpts, ops);
17
- };
18
- exports.setFetchOptions = setFetchOptions;
19
- async function fetchWrapper(input, init) {
20
- const fetchOpts = {};
21
- Object.assign(fetchOpts, defaultFetchOpts, init);
22
- const fetchResult = await fetch(input, fetchOpts);
23
- return fetchResult;
24
- }
25
- exports.fetchWrapper = fetchWrapper;
26
- function hostMatches(host, pattern) {
27
- if (typeof pattern === 'string')
28
- return pattern === host;
29
- return pattern.exec(host);
30
- }
31
- exports.hostMatches = hostMatches;
32
- function createApiKeyMiddleware({ apiKey, host = /(.*)api(.*)(\.stacks\.co|\.hiro\.so)$/i, httpHeader = 'x-api-key', }) {
33
- return {
34
- pre: context => {
35
- const reqUrl = new URL(context.url);
36
- if (!hostMatches(reqUrl.host, host))
37
- return;
38
- const headers = context.init.headers instanceof Headers
39
- ? context.init.headers
40
- : (context.init.headers = new Headers(context.init.headers));
41
- headers.set(httpHeader, apiKey);
42
- },
43
- };
44
- }
45
- exports.createApiKeyMiddleware = createApiKeyMiddleware;
46
- function argsForCreateFetchFn(args) {
47
- let fetchLib = fetchWrapper;
48
- let middlewares = [];
49
- if (args.length > 0 && typeof args[0] === 'function') {
50
- fetchLib = args.shift();
51
- }
52
- if (args.length > 0) {
53
- middlewares = args;
54
- }
55
- return { fetchLib, middlewares };
56
- }
57
- function createFetchFn(...args) {
58
- const { fetchLib, middlewares } = argsForCreateFetchFn(args);
59
- const fetchFn = async (url, init) => {
60
- let fetchParams = { url, init: init ?? {} };
61
- for (const middleware of middlewares) {
62
- if (typeof middleware.pre === 'function') {
63
- const result = await Promise.resolve(middleware.pre({
64
- fetch: fetchLib,
65
- ...fetchParams,
66
- }));
67
- fetchParams = result ?? fetchParams;
68
- }
69
- }
70
- let response = await fetchLib(fetchParams.url, fetchParams.init);
71
- for (const middleware of middlewares) {
72
- if (typeof middleware.post === 'function') {
73
- const result = await Promise.resolve(middleware.post({
74
- fetch: fetchLib,
75
- url: fetchParams.url,
76
- init: fetchParams.init,
77
- response: response?.clone() ?? response,
78
- }));
79
- response = result ?? response;
80
- }
81
- }
82
- return response;
83
- };
84
- return fetchFn;
85
- }
86
- exports.createFetchFn = createFetchFn;
87
- //# sourceMappingURL=fetch.js.map
package/dist/fetch.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":";;;AAAA,gCAA8B;AAI9B,MAAM,gBAAgB,GAAgB;IAGpC,cAAc,EAAE,QAAQ;IACxB,OAAO,EAAE;QACP,gBAAgB,EAAE,UAAU;KAC7B;CACF,CAAC;AAMK,MAAM,eAAe,GAAG,GAAG,EAAE;IAClC,OAAO,gBAAgB,CAAC;AAC1B,CAAC,CAAC;AAFW,QAAA,eAAe,mBAE1B;AAiBK,MAAM,eAAe,GAAG,CAAC,GAAgB,EAAe,EAAE;IAC/D,OAAO,MAAM,CAAC,MAAM,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;AAC9C,CAAC,CAAC;AAFW,QAAA,eAAe,mBAE1B;AAGK,KAAK,UAAU,YAAY,CAAC,KAAkB,EAAE,IAAkB;IACvE,MAAM,SAAS,GAAG,EAAE,CAAC;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