Skip to content

Commit

Permalink
fix: prevent loadConfig from failing in browser env and do not sent a…
Browse files Browse the repository at this point in the history
…uth requests (#1552)
  • Loading branch information
tatomyr committed May 9, 2024
1 parent e2b59a0 commit a96ce09
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 16 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-apes-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@redocly/openapi-core": patch
---

Improved loading of configuration files in environments different from Node.js.
14 changes: 6 additions & 8 deletions packages/core/src/config/__tests__/load.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ const path = require('path');
describe('loadConfig', () => {
it('should resolve config http header by US region', async () => {
jest
.spyOn(RedoclyClient.prototype, 'getTokens')
.mockImplementation(() =>
Promise.resolve([{ region: 'us', token: 'accessToken', valid: true }])
);
.spyOn(RedoclyClient.prototype, 'getAllTokens')
.mockImplementation(() => [{ region: 'us', token: 'accessToken' }]);
jest.spyOn(RedoclyClient.prototype, 'hasTokens').mockImplementation(() => true);
const config = await loadConfig();
expect(config.resolve.http.headers).toStrictEqual([
{
Expand All @@ -36,10 +35,9 @@ describe('loadConfig', () => {

it('should resolve config http header by EU region', async () => {
jest
.spyOn(RedoclyClient.prototype, 'getTokens')
.mockImplementation(() =>
Promise.resolve([{ region: 'eu', token: 'accessToken', valid: true }])
);
.spyOn(RedoclyClient.prototype, 'getAllTokens')
.mockImplementation(() => [{ region: 'eu', token: 'accessToken' }]);
jest.spyOn(RedoclyClient.prototype, 'hasTokens').mockImplementation(() => true);
const config = await loadConfig();
expect(config.resolve.http.headers).toStrictEqual([
{
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/config/load.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import * as fs from 'fs';
import * as path from 'path';
import { RedoclyClient } from '../redocly';
import { isEmptyObject, doesYamlFileExist } from '../utils';
import { isEmptyObject } from '../utils';
import { parseYaml } from '../js-yaml';
import { Config, DOMAINS } from './config';
import { ConfigValidationError, transformConfig } from './utils';
import { resolveConfig, resolveConfigFileAndRefs } from './config-resolvers';
import { bundleConfig } from '../bundle';

import type { Document } from '../resolve';
import type { RegionalTokenWithValidity } from '../redocly/redocly-client-types';
import type { RegionalToken, RegionalTokenWithValidity } from '../redocly/redocly-client-types';
import type { RawConfig, RawUniversalConfig, Region } from './types';
import type { BaseResolver, ResolvedRefMap } from '../resolve';

Expand All @@ -25,7 +25,7 @@ async function addConfigMetadata({
rawConfig: RawConfig;
customExtends?: string[];
configPath?: string;
tokens?: RegionalTokenWithValidity[];
tokens?: RegionalToken[];
files?: string[];
region?: Region;
externalRefResolver?: BaseResolver;
Expand Down Expand Up @@ -102,8 +102,8 @@ export async function loadConfig(
} = options;
const rawConfig = await getConfig({ configPath, processRawConfig, externalRefResolver });

const redoclyClient = new RedoclyClient();
const tokens = await redoclyClient.getTokens();
const redoclyClient = isEmptyObject(fs) ? undefined : new RedoclyClient();
const tokens = redoclyClient && redoclyClient.hasTokens() ? redoclyClient.getAllTokens() : [];

return addConfigMetadata({
rawConfig,
Expand All @@ -119,7 +119,7 @@ export async function loadConfig(
export const CONFIG_FILE_NAMES = ['redocly.yaml', 'redocly.yml', '.redocly.yaml', '.redocly.yml'];

export function findConfig(dir?: string): string | undefined {
if (!fs.hasOwnProperty('existsSync')) return;
if (!fs?.hasOwnProperty?.('existsSync')) return;
const existingConfigFiles = CONFIG_FILE_NAMES.map((name) =>
dir ? path.resolve(dir, name) : name
).filter(fs.existsSync);
Expand All @@ -141,7 +141,9 @@ export async function getConfig(
} = {}
): Promise<RawConfig> {
const { configPath = findConfig(), processRawConfig, externalRefResolver } = options;
if (!configPath || !doesYamlFileExist(configPath)) return {};
if (!configPath || !['.yaml', '.yml'].includes(path.extname(configPath))) {
return {};
}
try {
const { document, resolvedRefMap } = await resolveConfigFileAndRefs({
configPath,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ export function isCustomRuleId(id: string) {
export function doesYamlFileExist(filePath: string): boolean {
return (
(extname(filePath) === '.yaml' || extname(filePath) === '.yml') &&
fs.hasOwnProperty('existsSync') &&
fs?.hasOwnProperty?.('existsSync') &&
fs.existsSync(filePath)
);
}
Expand Down

1 comment on commit a96ce09

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage report

St.
Category Percentage Covered / Total
🟡 Statements 77.03% 4450/5777
🟡 Branches 67.52% 2463/3648
🟡 Functions 70.64% 741/1049
🟡 Lines 77.23% 4185/5419

Test suite run success

734 tests passing in 102 suites.

Report generated by 🧪jest coverage report action from a96ce09

Please sign in to comment.