Skip to content

Commit 707007d

Browse files
authored
chore: upgrade flowtype to 0.131.0 (#1603)
* chore: upgrade flowtype to 0.131.0 and yarn to 1.22.4 * refactor: build headers as single string value * test: fix assertion * chore: remove unnecessary eslint-disable * chore: update lockfile
1 parent 9999af1 commit 707007d

File tree

12 files changed

+142
-132
lines changed

12 files changed

+142
-132
lines changed

.flowconfig

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[version]
2-
^0.126.1
2+
^0.131.0
33

44
[ignore]
55
<PROJECT_ROOT>/_book/.*
@@ -55,8 +55,24 @@ packages/*/src
5555

5656
[libs]
5757

58+
[lints]
59+
# https://dev.to/wgao19/making-flow-happy-after-0-98-32bb
60+
# NOTE: express flow-typed currently contain some `$Subtype` types.
61+
deprecated-utility=off
62+
5863
[options]
59-
module.name_mapper='^types/\(.*\)$' -> '<PROJECT_ROOT>/types/\1.js'
60-
include_warnings=true
6164
emoji=true
65+
include_warnings=true
6266
esproposal.optional_chaining=enable
67+
esproposal.nullish_coalescing=enable
68+
69+
server.max_workers=2
70+
71+
module.name_mapper='^types/\(.*\)$' -> '<PROJECT_ROOT>/types/\1.js'
72+
73+
suppress_type=$FlowIssue
74+
suppress_type=$FlowFixMe
75+
76+
# https://medium.com/flow-type/types-first-a-scalable-new-architecture-for-flow-3d8c7ba1d4eb
77+
well_formed_exports=true
78+
types_first=true

integration-tests/sdk/auth-middleware.it.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ describe('Auth Middleware Flows', () => {
218218
body: { results: carts },
219219
request: {
220220
headers: {
221-
Authorization: [token],
221+
Authorization: token,
222222
},
223223
},
224224
}) => {

packages/product-json-to-csv/src/main.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ export default class ProductJsonToCsv {
197197
)
198198
}
199199

200-
async _resolveVariantReferences(variant: Variant) {
200+
async _resolveVariantReferences(variant: Variant): Promise<Variant> {
201201
if (!variant) return variant
202202

203203
return {

packages/product-json-to-csv/src/map-product-data.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ export default class ProductMapping {
305305
* @returns Object
306306
* @private
307307
*/
308-
_joinMappedSetValues(setValues: Array<Object>) {
308+
_joinMappedSetValues(setValues: Array<Object>): Object {
309309
// when there is an object property missing in first N objects, we should
310310
// prepend value from N+1 object with delimiters:
311311
// [{attrName.en: 'AA'}, {attrName.en: 'BB'},{attrName.de: '12'}]

packages/product-json-to-xlsx/src/writer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export function finishWorksheetsAndArchive(
4343
dir: string,
4444
output: stream$Writable,
4545
logger: Object
46-
) {
46+
): void {
4747
if (exports.length === 0) return archiveDir(dir, output, logger)
4848

4949
const writeStreams: Array<stream$Writable> = exports.map(

packages/resource-deleter/src/main.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import type {
2121
ClientRequest,
2222
ClientResult,
2323
MethodType,
24+
ServiceBuilderInstance,
2425
} from 'types/sdk'
2526
import silentLogger from './utils/silent-logger'
2627
import pkg from '../package.json'
@@ -153,7 +154,7 @@ export default class ResourceDeleter {
153154
})
154155
}
155156

156-
createService() {
157+
createService(): ServiceBuilderInstance {
157158
return createRequestBuilder({
158159
projectKey: this.apiConfig.projectKey,
159160
})[this.resource]

packages/sdk-auth/src/auth.js

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import type {
44
AuthOptions,
55
CustomAuthOptions,
66
ClientAuthOptions,
7-
ConfigFetch,
87
HttpErrorType,
98
AuthRequest,
109
UserAuthOptions,
@@ -17,7 +16,7 @@ import * as constants from './constants'
1716
export default class SdkAuth {
1817
// Set flowtype annotations
1918
config: AuthOptions
20-
fetcher: ConfigFetch
19+
fetcher: typeof fetch
2120
ANONYMOUS_FLOW_URI: string
2221
BASE_AUTH_FLOW_URI: string
2322
CUSTOMER_PASSWORD_FLOW_URI: string
@@ -53,12 +52,21 @@ export default class SdkAuth {
5352
this.INTROSPECT_URI = '/oauth/introspect'
5453
}
5554

56-
static _getFetcher(configFetch: ?ConfigFetch): ConfigFetch {
57-
if (!configFetch && typeof fetch === 'undefined')
55+
static _getFetcher(fetcher: ?typeof fetch): typeof fetch {
56+
if (!fetcher && typeof fetch === 'undefined')
5857
throw new Error(
5958
'`fetch` is not available. Please pass in `fetch` as an option or have it globally available.'
6059
)
61-
return configFetch || fetch
60+
let fetchFunction: typeof fetch
61+
if (fetcher) {
62+
fetchFunction = fetcher
63+
} else {
64+
// `fetcher` is set here rather than the destructuring to ensure fetch is
65+
// declared before referencing it otherwise it would cause a `ReferenceError`.
66+
// For reference of this pattern: https://github.com/apollographql/apollo-link/blob/498b413a5b5199b0758ce898b3bb55451f57a2fa/packages/apollo-link-http/src/httpLink.ts#L49
67+
fetchFunction = fetch
68+
}
69+
return fetchFunction
6270
}
6371

6472
static _checkRequiredConfiguration(config: AuthOptions) {
@@ -78,11 +86,11 @@ export default class SdkAuth {
7886
static _encodeClientCredentials({
7987
clientId,
8088
clientSecret,
81-
}: ClientAuthOptions) {
89+
}: ClientAuthOptions): string {
8290
return Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
8391
}
8492

85-
static _getScopes(scopes: ?Array<string>, projectKey: ?string) {
93+
static _getScopes(scopes: ?Array<string>, projectKey: ?string): string {
8694
return scopes
8795
? scopes.join(' ')
8896
: [constants.MANAGE_PROJECT, projectKey].filter(Boolean).join(':') // generate a default scope manage_project:projectKey
@@ -108,11 +116,20 @@ export default class SdkAuth {
108116
const authType = config.authType || constants.DEFAULT_AUTH_TYPE
109117

110118
const isNotRefreshTokenGrantType = grantType !== 'refresh_token'
111-
const initialBody = encode({
119+
const queryParams: {
120+
grant_type: string,
121+
refresh_token?: boolean,
122+
scope?: string,
123+
} = {
112124
grant_type: grantType,
113-
...(disableRefreshToken && { refresh_token: false }),
114-
...(isNotRefreshTokenGrantType && { scope }),
115-
})
125+
}
126+
if (disableRefreshToken) {
127+
queryParams.refresh_token = false
128+
}
129+
if (isNotRefreshTokenGrantType) {
130+
queryParams.scope = scope
131+
}
132+
const initialBody = encode(queryParams)
116133

117134
return { basicAuth, authType, uri, body: initialBody, headers }
118135
}
@@ -131,7 +148,7 @@ export default class SdkAuth {
131148
return request
132149
}
133150

134-
_process(request: AuthRequest) {
151+
_process(request: AuthRequest): Promise<Object> {
135152
return this._performRequest(request).then((response) =>
136153
SdkAuth._handleResponse(request.uri, response)
137154
)
@@ -173,7 +190,7 @@ export default class SdkAuth {
173190
return response
174191
}
175192

176-
static _handleResponse(uri: string, response: Object) {
193+
static _handleResponse(uri: string, response: Response): Promise<Object> {
177194
return SdkAuth._parseResponseJson(response).then((jsonResponse) => {
178195
if (SdkAuth._isErrorResponse(response))
179196
throw SdkAuth._createResponseError(jsonResponse, uri, response.status)
@@ -199,7 +216,7 @@ export default class SdkAuth {
199216
return uri.replace('--projectKey--', projectKey)
200217
}
201218

202-
_performRequest(request: AuthRequest) {
219+
_performRequest(request: AuthRequest): Promise<Response> {
203220
const { uri, body, basicAuth, authType, headers } = request
204221
const fetchHeaders = headers || {
205222
Authorization: `${authType || constants.DEFAULT_AUTH_TYPE} ${basicAuth}`,
@@ -228,7 +245,10 @@ export default class SdkAuth {
228245
return mergedConfig
229246
}
230247

231-
anonymousFlow(anonymousId: string = '', config: CustomAuthOptions = {}) {
248+
anonymousFlow(
249+
anonymousId: string = '',
250+
config: CustomAuthOptions = {}
251+
): Promise<Object> {
232252
const _config = this._getRequestConfig(config)
233253
let request = SdkAuth._buildRequest(
234254
_config,
@@ -246,7 +266,7 @@ export default class SdkAuth {
246266
return this._process(request)
247267
}
248268

249-
clientCredentialsFlow(config: CustomAuthOptions = {}) {
269+
clientCredentialsFlow(config: CustomAuthOptions = {}): Promise<Object> {
250270
const _config = this._getRequestConfig(config)
251271
const request = SdkAuth._buildRequest(_config, this.BASE_AUTH_FLOW_URI)
252272

@@ -257,7 +277,7 @@ export default class SdkAuth {
257277
credentials: UserAuthOptions,
258278
config: AuthOptions,
259279
url: string
260-
) {
280+
): Promise<Object> {
261281
const { username, password } = credentials || {}
262282
let request = SdkAuth._buildRequest(config, url, 'password')
263283

@@ -269,7 +289,7 @@ export default class SdkAuth {
269289
customerPasswordFlow(
270290
credentials: UserAuthOptions,
271291
config: CustomAuthOptions = {}
272-
) {
292+
): Promise<Object> {
273293
const _config = this._getRequestConfig(config)
274294
const url = SdkAuth._enrichUriWithProjectKey(
275295
this.CUSTOMER_PASSWORD_FLOW_URI,
@@ -282,13 +302,16 @@ export default class SdkAuth {
282302
clientPasswordFlow(
283303
credentials: UserAuthOptions,
284304
config: CustomAuthOptions = {}
285-
) {
305+
): Promise<Object> {
286306
const _config = this._getRequestConfig(config)
287307

288308
return this._passwordFlow(credentials, _config, this.BASE_AUTH_FLOW_URI)
289309
}
290310

291-
refreshTokenFlow(token: string, config: CustomAuthOptions = {}) {
311+
refreshTokenFlow(
312+
token: string,
313+
config: CustomAuthOptions = {}
314+
): Promise<Object> {
292315
if (!token) throw new Error('Missing required token value')
293316

294317
const _config = this._getRequestConfig(config)
@@ -300,7 +323,10 @@ export default class SdkAuth {
300323
return this._process(request)
301324
}
302325

303-
introspectToken(token: string, config: CustomAuthOptions = {}) {
326+
introspectToken(
327+
token: string,
328+
config: CustomAuthOptions = {}
329+
): Promise<Object> {
304330
if (!token) throw new Error('Missing required token value')
305331

306332
const _config = this._getRequestConfig(config)
@@ -312,7 +338,7 @@ export default class SdkAuth {
312338
return this._process(request)
313339
}
314340

315-
customFlow(requestConfig: Object) {
341+
customFlow(requestConfig: Object): Promise<Object> {
316342
const {
317343
credentials,
318344
host,

packages/sdk-middleware-http/src/http.js

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* @flow */
22

33
import type {
4+
HttpHeaders,
45
HttpErrorType,
56
HttpMiddlewareOptions,
67
Middleware,
@@ -44,9 +45,9 @@ function calcDelayDuration(
4445
function maskAuthData(request: Object, maskSensitiveHeaderData: ?boolean) {
4546
if (maskSensitiveHeaderData) {
4647
if (request.headers.authorization)
47-
request.headers.authorization = ['Bearer ********']
48+
request.headers.authorization = 'Bearer ********'
4849
if (request.headers.Authorization)
49-
request.headers.Authorization = ['Bearer ********']
50+
request.headers.Authorization = 'Bearer ********'
5051
}
5152
}
5253

@@ -76,14 +77,15 @@ export default function createHttpMiddleware({
7677
throw new Error(
7778
'`AbortController` is not available. Please pass in `AbortController` as an option or have it globally available when using timeout.'
7879
)
79-
80-
if (!fetcher)
80+
let fetchFunction: typeof fetch
81+
if (fetcher) {
82+
fetchFunction = fetcher
83+
} else {
8184
// `fetcher` is set here rather than the destructuring to ensure fetch is
8285
// declared before referencing it otherwise it would cause a `ReferenceError`.
8386
// For reference of this pattern: https://github.com/apollographql/apollo-link/blob/498b413a5b5199b0758ce898b3bb55451f57a2fa/packages/apollo-link-http/src/httpLink.ts#L49
84-
85-
// eslint-disable-next-line
86-
fetcher = fetch
87+
fetchFunction = fetch
88+
}
8789

8890
let abortController
8991
if (timeout || _abortController)
@@ -100,21 +102,28 @@ export default function createHttpMiddleware({
100102
? request.body
101103
: // NOTE: `stringify` of `null` gives the String('null')
102104
JSON.stringify(request.body || undefined)
103-
// $FlowFixMe
104-
const requestHeader = {
105-
'Content-Type': ['application/json'],
106-
...request.headers,
107-
...(body
108-
? { 'Content-Length': Buffer.byteLength(body).toString() }
109-
: null),
105+
106+
const requestHeader: HttpHeaders = { ...request.headers }
107+
if (
108+
!Object.prototype.hasOwnProperty.call(request.headers, 'Content-Type')
109+
) {
110+
requestHeader['Content-Type'] = 'application/json'
110111
}
111-
// $FlowFixMe
112-
const fetchOptions: Object = {
112+
if (body) {
113+
requestHeader['Content-Length'] = Buffer.byteLength(body).toString()
114+
}
115+
const fetchOptions: RequestOptions = {
113116
method: request.method,
114117
headers: requestHeader,
115-
...(credentialsMode ? { credentials: credentialsMode } : {}),
116-
...(timeout || abortController ? { signal: abortController.signal } : {}),
117-
...(body ? { body } : null),
118+
}
119+
if (credentialsMode) {
120+
fetchOptions.credentials = credentialsMode
121+
}
122+
if (timeout || abortController) {
123+
fetchOptions.signal = abortController.signal
124+
}
125+
if (body) {
126+
fetchOptions.body = body
118127
}
119128
let retryCount = 0
120129
// wrap in a fn so we can retry if error occur
@@ -125,8 +134,7 @@ export default function createHttpMiddleware({
125134
timer = setTimeout(() => {
126135
abortController.abort()
127136
}, timeout)
128-
// $FlowFixMe
129-
fetcher(url, fetchOptions)
137+
fetchFunction(url, fetchOptions)
130138
.then(
131139
(res: Response) => {
132140
if (res.ok) {

0 commit comments

Comments
 (0)