Skip to content

Commit f214a00

Browse files
authored
feat: allow dynamic configurations (#905)
1 parent 6bdfe2f commit f214a00

7 files changed

Lines changed: 70 additions & 41 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@node-core/doc-kit': patch
3+
---
4+
5+
Allow for the specification of dynamically generated configuration values

‎src/generators/web/index.mjs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,20 @@ export default createLazyGenerator({
3030

3131
dependsOn: 'jsx-ast',
3232

33-
defaultConfiguration: {
33+
/**
34+
* @param {import('../../utils/configuration/types').Configuration} config
35+
*/
36+
defaultConfiguration: config => ({
3437
templatePath: join(import.meta.dirname, 'template.html'),
3538
project: 'Node.js',
3639
title: '{project} {version} Documentation',
3740
useAbsoluteURLs: false,
3841
editURL: `${GITHUB_EDIT_URL}/doc/api{path}.md`,
3942
pageURL: '{baseURL}/latest-{version}/api{path}.html',
4043
remoteConfigUrl: 'https://nodejs.org/site.json',
44+
// By default, the search box is only shown when we are _also_ building search data
45+
showSearchBox:
46+
Array.isArray(config.target) && config.target.includes('orama-db'),
4147

4248
// Project-specific document `<head>` contents. `meta` and `links` are
4349
// arrays of attribute bags (boolean `true` renders a valueless attribute,
@@ -97,5 +103,5 @@ export default createLazyGenerator({
97103
// Options merged into the Rolldown build (client and server), e.g. extra
98104
// `plugins`. See the README for the merge semantics.
99105
rolldown: {},
100-
},
106+
}),
101107
});

‎src/generators/web/ui/components/NavBar.jsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import GitHubIcon from '@node-core/ui-components/Icons/Social/GitHub';
66
import SearchBox from './SearchBox';
77
import { useTheme } from '../hooks/useTheme.mjs';
88

9-
import { repository } from '#theme/config';
9+
import { repository, showSearchBox } from '#theme/config';
1010
import Logo from '#theme/Logo';
1111

1212
/**
@@ -21,7 +21,7 @@ export default ({ metadata }) => {
2121
sidebarItemTogglerAriaLabel="Toggle navigation menu"
2222
navItems={[]}
2323
>
24-
<SearchBox pathname={metadata.path} />
24+
{showSearchBox && <SearchBox pathname={metadata.path} />}
2525
<ThemeToggle
2626
onChange={setThemePreference}
2727
currentTheme={themePreference}

‎src/utils/__tests__/misc.test.mjs‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,18 +114,13 @@ describe('omitKeys', () => {
114114
});
115115

116116
describe('deepMerge', () => {
117-
it('should merge flat objects with source taking precedence over base', () => {
117+
it('should merge flat objects with latter-arguments taking precedence', () => {
118118
const result = deepMerge({ a: 1, b: 2 }, { b: 10, c: 3 });
119-
assert.deepStrictEqual(result, { a: 1, b: 2, c: 3 });
119+
assert.deepStrictEqual(result, { a: 1, b: 10, c: 3 });
120120
});
121121

122122
it('should merge nested objects recursively', () => {
123123
const result = deepMerge({ nested: { a: 1 } }, { nested: { b: 2 } });
124124
assert.deepStrictEqual(result, { nested: { a: 1, b: 2 } });
125125
});
126-
127-
it('should use base values when source values are undefined', () => {
128-
const result = deepMerge({ a: undefined }, { a: 'base' });
129-
assert.deepStrictEqual(result, { a: 'base' });
130-
});
131126
});

‎src/utils/configuration/__tests__/index.test.mjs‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ mock.module('../../../generators/index.mjs', {
1818
json: { defaultConfiguration: { format: 'json' } },
1919
html: { defaultConfiguration: { format: 'html' } },
2020
markdown: {},
21+
web: {
22+
defaultConfiguration: config => ({
23+
showSearchBox:
24+
Array.isArray(config.target) && config.target.includes('orama-db'),
25+
}),
26+
},
2127
},
2228
},
2329
});
@@ -149,20 +155,33 @@ describe('config.mjs', () => {
149155
});
150156

151157
describe('createRunConfiguration', () => {
152-
it('should merge config sources in correct order', async () => {
158+
it('should let defined CLI options override the config file', async () => {
153159
mockImportFromURL.mock.mockImplementationOnce(async () =>
154-
createMockConfig({ global: { input: 'custom-src/' } })
160+
createMockConfig({
161+
global: {
162+
input: 'custom-src/',
163+
output: 'config-dist/',
164+
version: '18.0.0',
165+
},
166+
target: ['html'],
167+
threads: 1,
168+
})
155169
);
156170

157171
const config = await createRunConfiguration({
158172
configFile: 'config.mjs',
159173
output: 'custom-dist/',
174+
version: '20.0.0',
175+
target: ['html', 'orama-db'],
160176
threads: 2,
161177
});
162178

163179
assert.strictEqual(config.global.input, 'custom-src/');
164180
assert.strictEqual(config.global.output, 'custom-dist/');
181+
assert.strictEqual(config.global.version.version, '20.0.0');
182+
assert.deepStrictEqual(config.target, ['html', 'orama-db']);
165183
assert.strictEqual(config.threads, 2);
184+
assert.strictEqual(config.web.showSearchBox, true);
166185
});
167186

168187
it('should transform string values only once', async () => {

‎src/utils/configuration/index.mjs‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,16 @@ import { deepMerge, lazy } from '../misc.mjs';
1515
/**
1616
* Get's the default configuration
1717
*/
18-
export const getDefaultConfig = lazy(() =>
18+
export const getDefaultConfig = lazy(config =>
1919
Object.keys(allGenerators).reduce(
2020
(acc, k) => {
21-
acc[k] = allGenerators[k].defaultConfiguration ?? {};
21+
acc[k] =
22+
'defaultConfiguration' in allGenerators[k]
23+
? typeof allGenerators[k].defaultConfiguration === 'function'
24+
? allGenerators[k].defaultConfiguration(config)
25+
: allGenerators[k].defaultConfiguration
26+
: {};
27+
2228
return acc;
2329
},
2430
/** @type {import('./types').Configuration} */ ({
@@ -134,12 +140,10 @@ export const createRunConfiguration = async options => {
134140
const config = await loadConfigFile(options.configFile);
135141
config.target &&= enforceArray(config.target);
136142

137-
// Merge with defaults
138-
const merged = deepMerge(
139-
config,
140-
createConfigFromCLIOptions(options),
141-
getDefaultConfig()
142-
);
143+
// Resolve user configuration first so dynamic defaults can use it
144+
const cliConfig = createConfigFromCLIOptions(options);
145+
const intermediate = deepMerge(config, cliConfig);
146+
const merged = deepMerge(getDefaultConfig(intermediate), intermediate);
143147

144148
// These need to be coerced
145149
merged.threads = Math.max(merged.threads, 1);

‎src/utils/misc.mjs‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,14 @@ export const lazy = fn =>
1616
* @param {*} value - The value to check
1717
* @returns {boolean} True if the value is a plain object, false otherwise
1818
*/
19-
export const isPlainObject = value =>
20-
value !== null && typeof value === 'object' && !Array.isArray(value);
19+
export const isPlainObject = value => {
20+
if (value === null || typeof value !== 'object') {
21+
return false;
22+
}
23+
24+
const prototype = Object.getPrototypeOf(value);
25+
return prototype === Object.prototype || prototype === null;
26+
};
2127

2228
/**
2329
* Checks if a value is an async generator/iterable.
@@ -41,32 +47,26 @@ export const omitKeys = (obj, keys = []) =>
4147
);
4248

4349
/**
44-
* Recursively merges multiple objects deeply.
50+
* Recursively merges plain objects from left to right.
4551
* @template T
4652
* @param {...T} objects - Any number of objects to merge
4753
* @returns {T} A new object containing the deep merge of all provided objects
4854
*/
4955
export const deepMerge = (...objects) => {
50-
const base = objects.pop();
51-
5256
return objects.reduce((result, source) => {
53-
for (const key in source) {
54-
if (Object.prototype.hasOwnProperty.call(source, key)) {
55-
const sourceValue = source[key];
56-
const isSourcePlainObject = isPlainObject(sourceValue);
57-
58-
const targetValue = result[key];
59-
const baseValue = base[key];
60-
61-
result[key] =
62-
isSourcePlainObject && isPlainObject(targetValue)
63-
? deepMerge(targetValue, sourceValue, baseValue ?? {})
64-
: isSourcePlainObject && isPlainObject(baseValue)
65-
? deepMerge(sourceValue, baseValue)
66-
: (sourceValue ?? baseValue);
57+
for (const [key, sourceValue] of Object.entries(source)) {
58+
if (sourceValue === undefined) {
59+
continue;
6760
}
61+
62+
const targetValue = result[key];
63+
result[key] = isPlainObject(sourceValue)
64+
? deepMerge(isPlainObject(targetValue) ? targetValue : {}, sourceValue)
65+
: Array.isArray(sourceValue)
66+
? sourceValue.slice()
67+
: sourceValue;
6868
}
6969

7070
return result;
71-
}, base);
71+
}, {});
7272
};

0 commit comments

Comments
 (0)