Skip to content

Commit c2746bc

Browse files
committed
feat: add fetch middleware for api keys and request init
chore: remove file wip wip docs: optimize ts docs wip
1 parent 2add622 commit c2746bc

39 files changed

+3443
-9076
lines changed

package-lock.json

Lines changed: 2448 additions & 8503 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,14 @@
6767
"rollup-plugin-node-globals": "^1.4.0",
6868
"rollup-plugin-terser": "^7.0.2",
6969
"stream-http": "^3.2.0",
70-
"typedoc": "^0.22.13",
70+
"typedoc": "^0.22.15",
7171
"typescript": "^4.2.4",
7272
"vite-compatible-readable-stream": "^3.6.0"
7373
},
7474
"scripts": {
7575
"bootstrap": "lerna bootstrap",
7676
"build": "lerna run build",
77-
"build:docs": "rimraf docs && typedoc --tsconfig tsconfig.typedoc.json packages/**/src/index.ts --release-version $(node -p \"require('./lerna.json').version\")",
77+
"build:docs": "rimraf docs && RELEASE_VERSION=$(node -p \"require('./lerna.json').version\") && typedoc --tsconfig tsconfig.typedoc.json packages/**/src/index.ts --release-version $RELEASE_VERSION",
7878
"clean": "lerna clean",
7979
"lerna": "lerna",
8080
"lint": "npm run lint:eslint && npm run lint:prettier",

packages/auth/src/profile.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { resolveZoneFileToProfile } from '@stacks/profile';
2-
import { fetchPrivate } from '@stacks/common';
32
import { StacksMainnet, StacksNetwork, StacksNetworkName } from '@stacks/network';
43

54
export interface ProfileLookupOptions {
@@ -31,13 +30,13 @@ export function lookupProfile(lookupOptions: ProfileLookupOptions): Promise<Reco
3130
let lookupPromise;
3231
if (options.zoneFileLookupURL) {
3332
const url = `${options.zoneFileLookupURL.replace(/\/$/, '')}/${options.username}`;
34-
lookupPromise = fetchPrivate(url).then(response => response.json());
33+
lookupPromise = network.fetchFn(url).then(response => response.json());
3534
} else {
3635
lookupPromise = network.getNameInfo(options.username);
3736
}
3837
return lookupPromise.then((responseJSON: any) => {
3938
if (responseJSON.hasOwnProperty('zonefile') && responseJSON.hasOwnProperty('address')) {
40-
return resolveZoneFileToProfile(responseJSON.zonefile, responseJSON.address);
39+
return resolveZoneFileToProfile(responseJSON.zonefile, responseJSON.address, network.fetchFn);
4140
} else {
4241
throw new Error(
4342
'Invalid zonefile lookup response: did not contain `address`' + ' or `zonefile` field'

packages/auth/src/provider.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as queryString from 'query-string';
22
import { decodeToken } from 'jsontokens';
3-
import { BLOCKSTACK_HANDLER, getGlobalObject, fetchPrivate } from '@stacks/common';
3+
import { BLOCKSTACK_HANDLER, getGlobalObject } from '@stacks/common';
4+
import { createFetchFn, FetchFn } from '@stacks/network';
45

56
/**
67
* Retrieves the authentication request from the query string
@@ -36,7 +37,10 @@ export function getAuthRequestFromURL() {
3637
* @private
3738
* @ignore
3839
*/
39-
export async function fetchAppManifest(authRequest: string): Promise<any> {
40+
export async function fetchAppManifest(
41+
authRequest: string,
42+
fetchFn: FetchFn = createFetchFn()
43+
): Promise<any> {
4044
if (!authRequest) {
4145
throw new Error('Invalid auth request');
4246
}
@@ -47,7 +51,7 @@ export async function fetchAppManifest(authRequest: string): Promise<any> {
4751
const manifestURI = payload.manifest_uri as string;
4852
try {
4953
// Logger.debug(`Fetching manifest from ${manifestURI}`)
50-
const response = await fetchPrivate(manifestURI);
54+
const response = await fetchFn(manifestURI);
5155
const responseText = await response.text();
5256
const responseJSON = JSON.parse(responseText);
5357
return { ...responseJSON, manifestURI };

packages/auth/src/userSession.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import {
1515
import { getAddressFromDID } from './dids';
1616
import {
1717
BLOCKSTACK_DEFAULT_GAIA_HUB_URL,
18-
fetchPrivate,
1918
getGlobalObject,
2019
InvalidStateError,
2120
isLaterVersion,
@@ -28,7 +27,7 @@ import { extractProfile } from '@stacks/profile';
2827
import { AuthScope, DEFAULT_PROFILE } from './constants';
2928
import * as queryString from 'query-string';
3029
import { UserData } from './userData';
31-
import { StacksMainnet } from '@stacks/network';
30+
import { createFetchFn, FetchFn, StacksMainnet } from '@stacks/network';
3231
import { protocolEchoReplyDetection } from './protocolEchoDetection';
3332

3433
/**
@@ -214,7 +213,8 @@ export class UserSession {
214213
* if handling the sign in request fails or there was no pending sign in request.
215214
*/
216215
async handlePendingSignIn(
217-
authResponseToken: string = this.getAuthResponseToken()
216+
authResponseToken: string = this.getAuthResponseToken(),
217+
fetchFn: FetchFn = createFetchFn()
218218
): Promise<UserData> {
219219
const sessionData = this.store.getSessionData();
220220

@@ -312,7 +312,7 @@ export class UserSession {
312312
};
313313
const profileURL = tokenPayload.profile_url as string;
314314
if (!userData.profile && profileURL) {
315-
const response = await fetchPrivate(profileURL);
315+
const response = await fetchFn(profileURL);
316316
if (!response.ok) {
317317
// return blank profile if we fail to fetch
318318
userData.profile = Object.assign({}, DEFAULT_PROFILE);

packages/cli/src/network.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import blockstack from 'blockstack';
22
import * as bitcoin from 'bitcoinjs-lib';
33
import BN from 'bn.js';
4-
import fetch from 'node-fetch';
54

65
import { CLI_CONFIG_TYPE } from './argparse';
76

87
import { BlockstackNetwork } from 'blockstack/lib/network';
8+
import { createFetchFn, FetchFn } from '@stacks/network';
99

1010
export interface CLI_NETWORK_OPTS {
1111
consensusHash: string | null;
@@ -187,15 +187,16 @@ export class CLINetworkAdapter {
187187
getNamespaceBurnAddress(
188188
namespace: string,
189189
useCLI: boolean = true,
190-
receiveFeesPeriod: number = -1
190+
receiveFeesPeriod: number = -1,
191+
fetchFn: FetchFn = createFetchFn()
191192
): Promise<string> {
192193
// override with CLI option
193194
if (this.namespaceBurnAddress && useCLI) {
194195
return new Promise((resolve: any) => resolve(this.namespaceBurnAddress));
195196
}
196197

197198
return Promise.all([
198-
fetch(`${this.legacyNetwork.blockstackAPIUrl}/v1/namespaces/${namespace}`),
199+
fetchFn(`${this.legacyNetwork.blockstackAPIUrl}/v1/namespaces/${namespace}`),
199200
this.legacyNetwork.getBlockHeight(),
200201
])
201202
.then(([resp, blockHeight]: [any, number]) => {
@@ -245,10 +246,10 @@ export class CLINetworkAdapter {
245246
});
246247
}
247248

248-
getBlockchainNameRecord(name: string): Promise<any> {
249+
getBlockchainNameRecord(name: string, fetchFn: FetchFn = createFetchFn()): Promise<any> {
249250
// TODO: send to blockstack.js
250251
const url = `${this.legacyNetwork.blockstackAPIUrl}/v1/blockchains/bitcoin/names/${name}`;
251-
return fetch(url)
252+
return fetchFn(url)
252253
.then(resp => {
253254
if (resp.status !== 200) {
254255
throw new Error(`Bad response status: ${resp.status}`);
@@ -268,10 +269,14 @@ export class CLINetworkAdapter {
268269
});
269270
}
270271

271-
getNameHistory(name: string, page: number): Promise<Record<string, any[]>> {
272+
getNameHistory(
273+
name: string,
274+
page: number,
275+
fetchFn: FetchFn = createFetchFn()
276+
): Promise<Record<string, any[]>> {
272277
// TODO: send to blockstack.js
273278
const url = `${this.legacyNetwork.blockstackAPIUrl}/v1/names/${name}/history?page=${page}`;
274-
return fetch(url)
279+
return fetchFn(url)
275280
.then(resp => {
276281
if (resp.status !== 200) {
277282
throw new Error(`Bad response status: ${resp.status}`);

packages/common/src/fetchUtil.ts

Lines changed: 0 additions & 38 deletions
This file was deleted.

packages/common/src/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
export * from './config';
22
export * from './errors';
3-
export * from './fetchUtil';
43
export * from './logger';
54
export * from './utils';
65
export * from './constants';

packages/keychain/src/identity.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { makeAuthResponse } from '@stacks/auth';
22
import { getPublicKeyFromPrivate, publicKeyToAddress } from '@stacks/encryption';
3+
import { createFetchFn, FetchFn } from '@stacks/network';
34
import { bip32 } from 'bitcoinjs-lib';
45
import { Identity as IdentifyInterface, Profile } from './common';
56
import IdentityAddressOwnerNode from './nodes/identity-address-owner-node';
67
import { DEFAULT_PROFILE, fetchProfile, signAndUploadProfile } from './profiles';
78
import { getProfileURLFromZoneFile, IdentityKeyPair } from './utils';
8-
import { fetchPrivate } from '@stacks/common';
99
import {
1010
connectToGaiaHubWithConfig,
1111
DEFAULT_GAIA_HUB,
@@ -130,9 +130,9 @@ export class Identity implements IdentifyInterface {
130130
return `${gaiaUrl}${this.address}/profile.json`;
131131
}
132132

133-
async fetchNames() {
133+
async fetchNames(fetchFn: FetchFn = createFetchFn()) {
134134
const getNamesUrl = `https://stacks-node-api.stacks.co/v1/addresses/bitcoin/${this.address}`;
135-
const res = await fetchPrivate(getNamesUrl);
135+
const res = await fetchFn(getNamesUrl);
136136
const data = await res.json();
137137
const { names }: { names: string[] } = data;
138138
return names;

packages/keychain/src/profiles.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
import { connectToGaiaHub } from '@stacks/storage';
2-
import { signProfileToken, wrapProfileToken, makeProfileZoneFile } from '@stacks/profile';
1+
import { createFetchFn, FetchFn } from '@stacks/network';
2+
import { makeProfileZoneFile, signProfileToken, wrapProfileToken } from '@stacks/profile';
3+
import { connectToGaiaHub, GaiaHubConfig } from '@stacks/storage';
34
import { Identity, Profile } from './common';
45
import { IdentityKeyPair } from './utils';
56
import { uploadToGaiaHub } from './utils/gaia';
6-
import { GaiaHubConfig } from '@stacks/storage';
7-
import { fetchPrivate } from '@stacks/common';
87

98
export const DEFAULT_PROFILE: Profile = {
109
'@type': 'Person',
@@ -61,13 +60,15 @@ interface SendToRegistrarParams {
6160
subdomain: Subdomains;
6261
zoneFile: string;
6362
identity: Identity;
63+
fetchFn?: FetchFn;
6464
}
6565

6666
const sendUsernameToRegistrar = async ({
6767
username,
6868
subdomain,
6969
zoneFile,
7070
identity,
71+
fetchFn = createFetchFn(),
7172
}: SendToRegistrarParams) => {
7273
const { registerUrl } = registrars[subdomain];
7374

@@ -82,7 +83,7 @@ const sendUsernameToRegistrar = async ({
8283
'Content-Type': 'application/json',
8384
};
8485

85-
const response = await fetchPrivate(registerUrl, {
86+
const response = await fetchFn(registerUrl, {
8687
method: 'POST',
8788
headers: requestHeaders,
8889
body: registrationRequestBody,
@@ -151,13 +152,15 @@ export const signAndUploadProfile = async ({
151152
export const fetchProfile = async ({
152153
identity,
153154
gaiaUrl,
155+
fetchFn = createFetchFn(),
154156
}: {
155157
identity: Identity;
156158
gaiaUrl: string;
159+
fetchFn?: FetchFn;
157160
}) => {
158161
try {
159162
const url = await identity.profileUrl(gaiaUrl);
160-
const res = await fetchPrivate(url);
163+
const res = await fetchFn(url);
161164
if (res.ok) {
162165
const json = await res.json();
163166
const { decodedToken } = json[0];

0 commit comments

Comments
 (0)