Skip to content

Commit 46ee49b

Browse files
authored
Merge pull request #7 from hey-api/fix/semantic-release-6
fix: initial release
2 parents ef28564 + 146e191 commit 46ee49b

File tree

9 files changed

+52
-181
lines changed

9 files changed

+52
-181
lines changed

src/dotenv.ts

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,7 @@ export async function loadDotenv(options: DotenvOptions): Promise<Env> {
105105
}
106106

107107
// Based on https://github.com/motdotla/dotenv-expand
108-
function interpolate(
109-
target: Record<string, any>,
110-
source: Record<string, any> = {},
111-
parse = (v: any) => v,
112-
) {
108+
function interpolate(target: Record<string, any>, source: Record<string, any> = {}, parse = (v: any) => v) {
113109
function getValue(key: string) {
114110
// Source value 'wins' over target value
115111
return source[key] === undefined ? target[key] : source[key];
@@ -137,11 +133,7 @@ function interpolate(
137133

138134
// Avoid recursion
139135
if (parents.includes(key)) {
140-
console.warn(
141-
`Please avoid recursive environment variables ( loop: ${parents.join(
142-
" > ",
143-
)} > ${key} )`,
144-
);
136+
console.warn(`Please avoid recursive environment variables ( loop: ${parents.join(" > ")} > ${key} )`);
145137
return "";
146138
}
147139

@@ -151,9 +143,7 @@ function interpolate(
151143
value = interpolate(value, [...parents, key]);
152144
}
153145

154-
return value === undefined
155-
? newValue
156-
: newValue.replace(replacePart, value);
146+
return value === undefined ? newValue : newValue.replace(replacePart, value);
157147
}, value),
158148
);
159149
}

src/loader.ts

Lines changed: 22 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ export async function loadConfig<
5858
options.cwd = resolve(process.cwd(), options.cwd || ".");
5959
options.name = options.name || "config";
6060
options.envName = options.envName ?? process.env.NODE_ENV;
61-
options.configFile =
62-
options.configFile ??
63-
(options.name === "config" ? "config" : `${options.name}.config`);
61+
options.configFile = options.configFile ?? (options.name === "config" ? "config" : `${options.name}.config`);
6462
options.rcFile = options.rcFile ?? `.${options.name}rc`;
6563
if (options.extend !== false) {
6664
options.extend = {
@@ -173,11 +171,7 @@ export async function loadConfig<
173171
const keys = (
174172
Array.isArray(options.packageJson)
175173
? options.packageJson
176-
: [
177-
typeof options.packageJson === "string"
178-
? options.packageJson
179-
: options.name,
180-
]
174+
: [typeof options.packageJson === "string" ? options.packageJson : options.name]
181175
).filter((t) => t && typeof t === "string");
182176
const pkgJsonFile = await readPackageJSON(options.cwd).catch(() => {});
183177
const values = keys.map((key) => pkgJsonFile?.[key]);
@@ -189,19 +183,11 @@ export async function loadConfig<
189183
// TODO: #253 change order from defaults to overrides in next major version
190184
for (const key in rawConfigs) {
191185
const value = rawConfigs[key as ConfigSource];
192-
configs[key as ConfigSource] = await (typeof value === "function"
193-
? value({ configs, rawConfigs })
194-
: value);
186+
configs[key as ConfigSource] = await (typeof value === "function" ? value({ configs, rawConfigs }) : value);
195187
}
196188

197189
// Combine sources
198-
r.config = _merger(
199-
configs.overrides,
200-
configs.main,
201-
configs.rc,
202-
configs.packageJson,
203-
configs.defaultConfig,
204-
) as T;
190+
r.config = _merger(configs.overrides, configs.main, configs.rc, configs.packageJson, configs.defaultConfig) as T;
205191

206192
// Allow extending
207193
if (options.extend) {
@@ -252,10 +238,10 @@ export async function loadConfig<
252238
return r;
253239
}
254240

255-
async function extendConfig<
256-
T extends UserInputConfig = UserInputConfig,
257-
MT extends ConfigLayerMeta = ConfigLayerMeta,
258-
>(config: InputConfig<T, MT>, options: LoadConfigOptions<T, MT>) {
241+
async function extendConfig<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta>(
242+
config: InputConfig<T, MT>,
243+
options: LoadConfigOptions<T, MT>,
244+
) {
259245
(config as any)._layers = config._layers || [];
260246
if (!options.extend) {
261247
return;
@@ -265,9 +251,7 @@ async function extendConfig<
265251
keys = [keys];
266252
}
267253
const extendSources: Array<
268-
| string
269-
| [string, SourceOptions<T, MT>?]
270-
| { source: string; options?: SourceOptions<T, MT> }
254+
string | [string, SourceOptions<T, MT>?] | { source: string; options?: SourceOptions<T, MT> }
271255
> = [];
272256
for (const key of keys) {
273257
const value = config[key];
@@ -278,11 +262,7 @@ async function extendConfig<
278262
for (let extendSource of extendSources) {
279263
const originalExtendSource = extendSource;
280264
let sourceOptions: SourceOptions<T, MT> = {};
281-
if (
282-
typeof extendSource === "object" &&
283-
extendSource !== null &&
284-
"source" in extendSource
285-
) {
265+
if (typeof extendSource === "object" && extendSource !== null && "source" in extendSource) {
286266
sourceOptions = extendSource.options || {};
287267
extendSource = extendSource.source;
288268
}
@@ -293,20 +273,14 @@ async function extendConfig<
293273
if (typeof extendSource !== "string") {
294274
// TODO: Use error in next major versions
295275

296-
console.warn(
297-
`Cannot extend config from \`${JSON.stringify(
298-
originalExtendSource,
299-
)}\` in ${options.cwd}`,
300-
);
276+
console.warn(`Cannot extend config from \`${JSON.stringify(originalExtendSource)}\` in ${options.cwd}`);
301277
continue;
302278
}
303279
const _config = await resolveConfig(extendSource, options, sourceOptions);
304280
if (!_config.config) {
305281
// TODO: Use error in next major versions
306282

307-
console.warn(
308-
`Cannot extend config from \`${extendSource}\` in ${options.cwd}`,
309-
);
283+
console.warn(`Cannot extend config from \`${extendSource}\` in ${options.cwd}`);
310284
continue;
311285
}
312286
await extendConfig(_config.config, {
@@ -323,23 +297,12 @@ async function extendConfig<
323297
}
324298

325299
// TODO: Either expose from giget directly or redirect all non file:// protocols to giget
326-
const GIGET_PREFIXES = [
327-
"gh:",
328-
"github:",
329-
"gitlab:",
330-
"bitbucket:",
331-
"https://",
332-
"http://",
333-
];
300+
const GIGET_PREFIXES = ["gh:", "github:", "gitlab:", "bitbucket:", "https://", "http://"];
334301

335302
// https://github.com/dword-design/package-name-regex
336-
const NPM_PACKAGE_RE =
337-
/^(@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*($|\/.*)/;
303+
const NPM_PACKAGE_RE = /^(@[\da-z~-][\d._a-z~-]*\/)?[\da-z~-][\d._a-z~-]*($|\/.*)/;
338304

339-
async function resolveConfig<
340-
T extends UserInputConfig = UserInputConfig,
341-
MT extends ConfigLayerMeta = ConfigLayerMeta,
342-
>(
305+
async function resolveConfig<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta>(
343306
source: string,
344307
options: LoadConfigOptions<T, MT>,
345308
sourceOptions: SourceOptions<T, MT> = {},
@@ -356,18 +319,11 @@ async function resolveConfig<
356319
const _merger = options.merger || defu;
357320

358321
// Download giget URIs and resolve to local path
359-
const customProviderKeys = Object.keys(
360-
sourceOptions.giget?.providers || {},
361-
).map((key) => `${key}:`);
322+
const customProviderKeys = Object.keys(sourceOptions.giget?.providers || {}).map((key) => `${key}:`);
362323
const gigetPrefixes =
363-
customProviderKeys.length > 0
364-
? [...new Set([...customProviderKeys, ...GIGET_PREFIXES])]
365-
: GIGET_PREFIXES;
366-
367-
if (
368-
options.giget !== false &&
369-
gigetPrefixes.some((prefix) => source.startsWith(prefix))
370-
) {
324+
customProviderKeys.length > 0 ? [...new Set([...customProviderKeys, ...GIGET_PREFIXES])] : GIGET_PREFIXES;
325+
326+
if (options.giget !== false && gigetPrefixes.some((prefix) => source.startsWith(prefix))) {
371327
const { downloadTemplate } = await import("giget");
372328
const { digest } = await import("ohash");
373329

@@ -427,10 +383,7 @@ async function resolveConfig<
427383

428384
res.configFile =
429385
tryResolve(resolve(cwd, source), options) ||
430-
tryResolve(
431-
resolve(cwd, ".config", source.replace(/\.config$/, "")),
432-
options,
433-
) ||
386+
tryResolve(resolve(cwd, ".config", source.replace(/\.config$/, "")), options) ||
434387
tryResolve(resolve(cwd, ".config", source), options) ||
435388
source;
436389

@@ -442,8 +395,7 @@ async function resolveConfig<
442395

443396
const configFileExt = extname(res.configFile!) || "";
444397
if (configFileExt in ASYNC_LOADERS) {
445-
const asyncLoader =
446-
await ASYNC_LOADERS[configFileExt as keyof typeof ASYNC_LOADERS]();
398+
const asyncLoader = await ASYNC_LOADERS[configFileExt as keyof typeof ASYNC_LOADERS]();
447399
const contents = await readFile(res.configFile!, "utf8");
448400
res.config = asyncLoader(contents);
449401
} else {
@@ -452,9 +404,7 @@ async function resolveConfig<
452404
})) as T;
453405
}
454406
if (typeof res.config === "function") {
455-
res.config = await (
456-
res.config as (ctx?: ConfigFunctionContext) => Promise<any>
457-
)(options.context);
407+
res.config = await (res.config as (ctx?: ConfigFunctionContext) => Promise<any>)(options.context);
458408
}
459409

460410
// Extend env specific config

src/types.ts

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -81,20 +81,13 @@ export interface ResolvedConfig<
8181
_configFile?: string;
8282
}
8383

84-
export type ConfigSource =
85-
| "overrides"
86-
| "main"
87-
| "rc"
88-
| "packageJson"
89-
| "defaultConfig";
84+
export type ConfigSource = "overrides" | "main" | "rc" | "packageJson" | "defaultConfig";
9085

9186
export interface ConfigFunctionContext {
9287
[key: string]: any;
9388
}
9489

95-
export interface ResolvableConfigContext<
96-
T extends UserInputConfig = UserInputConfig,
97-
> {
90+
export interface ResolvableConfigContext<T extends UserInputConfig = UserInputConfig> {
9891
configs: Record<ConfigSource, T | null | undefined>;
9992
rawConfigs: Record<ConfigSource, ResolvableConfig<T> | null | undefined>;
10093
}
@@ -135,11 +128,7 @@ export interface LoadConfigOptions<
135128
resolve?: (
136129
id: string,
137130
options: LoadConfigOptions<T, MT>,
138-
) =>
139-
| null
140-
| undefined
141-
| ResolvedConfig<T, MT>
142-
| Promise<ResolvedConfig<T, MT> | undefined | null>;
131+
) => null | undefined | ResolvedConfig<T, MT> | Promise<ResolvedConfig<T, MT> | undefined | null>;
143132

144133
jiti?: Jiti;
145134
jitiOptions?: JitiOptions;
@@ -157,10 +146,9 @@ export interface LoadConfigOptions<
157146
configFileRequired?: boolean;
158147
}
159148

160-
export type DefineConfig<
161-
T extends UserInputConfig = UserInputConfig,
162-
MT extends ConfigLayerMeta = ConfigLayerMeta,
163-
> = (input: InputConfig<T, MT>) => InputConfig<T, MT>;
149+
export type DefineConfig<T extends UserInputConfig = UserInputConfig, MT extends ConfigLayerMeta = ConfigLayerMeta> = (
150+
input: InputConfig<T, MT>,
151+
) => InputConfig<T, MT>;
164152

165153
export function createDefineConfig<
166154
T extends UserInputConfig = UserInputConfig,

src/update.ts

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,39 +9,24 @@ const UPDATABLE_EXTS = [".js", ".ts", ".mjs", ".cjs", ".mts", ".cts"] as const;
99
/**
1010
* @experimental Update a config file or create a new one.
1111
*/
12-
export async function updateConfig(
13-
opts: UpdateConfigOptions,
14-
): Promise<UpdateConfigResult> {
12+
export async function updateConfig(opts: UpdateConfigOptions): Promise<UpdateConfigResult> {
1513
const { parseModule } = await import("magicast");
1614

1715
// Try to find an existing config file
1816
let configFile =
1917
tryResolve(`./${opts.configFile}`, opts.cwd, SUPPORTED_EXTENSIONS) ||
20-
tryResolve(
21-
`./.config/${opts.configFile}`,
22-
opts.cwd,
23-
SUPPORTED_EXTENSIONS,
24-
) ||
25-
tryResolve(
26-
`./.config/${opts.configFile.split(".")[0]}`,
27-
opts.cwd,
28-
SUPPORTED_EXTENSIONS,
29-
);
18+
tryResolve(`./.config/${opts.configFile}`, opts.cwd, SUPPORTED_EXTENSIONS) ||
19+
tryResolve(`./.config/${opts.configFile.split(".")[0]}`, opts.cwd, SUPPORTED_EXTENSIONS);
3020

3121
// If not found
3222
let created = false;
3323
if (!configFile) {
34-
configFile = join(
35-
opts.cwd,
36-
opts.configFile + (opts.createExtension || ".ts"),
37-
);
38-
const createResult =
39-
(await opts.onCreate?.({ configFile: configFile })) ?? true;
24+
configFile = join(opts.cwd, opts.configFile + (opts.createExtension || ".ts"));
25+
const createResult = (await opts.onCreate?.({ configFile: configFile })) ?? true;
4026
if (!createResult) {
4127
throw new Error("Config file creation aborted.");
4228
}
43-
const content =
44-
typeof createResult === "string" ? createResult : `export default {}\n`;
29+
const content = typeof createResult === "string" ? createResult : `export default {}\n`;
4530
await mkdir(dirname(configFile), { recursive: true });
4631
await writeFile(configFile, content, "utf8");
4732
created = true;
@@ -62,10 +47,7 @@ export async function updateConfig(
6247
if (!defaultExport) {
6348
throw new Error("Default export is missing in the config file!");
6449
}
65-
const configObj =
66-
defaultExport.$type === "function-call"
67-
? defaultExport.$args[0]
68-
: defaultExport;
50+
const configObj = defaultExport.$type === "function-call" ? defaultExport.$args[0] : defaultExport;
6951

7052
await opts.onUpdate?.(configObj);
7153

@@ -99,10 +81,7 @@ export interface UpdateConfigResult {
9981

10082
type MaybePromise<T> = T | Promise<T>;
10183

102-
type MagicAstOptions = Exclude<
103-
Parameters<(typeof import("magicast"))["parseModule"]>[1],
104-
undefined
105-
>;
84+
type MagicAstOptions = Exclude<Parameters<(typeof import("magicast"))["parseModule"]>[1], undefined>;
10685

10786
export interface UpdateConfigOptions {
10887
/**

0 commit comments

Comments
 (0)